tools.spec.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it } from 'vitest'
  5. import { Context } from 'cordis'
  6. import { CallId } from '@deepseek-ai/dsh-llm'
  7. import { BashExecutor } from '@deepseek-ai/dsh-bash'
  8. import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult } from '@deepseek-ai/dsh-bash'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry from '@deepseek-ai/dsh-agent'
  12. import type { Agent } from '@deepseek-ai/dsh-agent'
  13. import TaskService from '@deepseek-ai/dsh-tasks'
  14. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  15. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  16. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  17. import { processOutcome, renderProcessRead, renderResult } from '@deepseek-ai/dsh-tool-bash'
  18. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-tool-bash-spec-'))
  19. /** Foreground-only harness: no task runtime (backgrounding fails loud here). */
  20. async function setup() {
  21. const ctx = new Context()
  22. await ctx.plugin(SystemPrompt)
  23. await ctx.plugin(ToolRegistry)
  24. await ctx.plugin(AgentRegistry)
  25. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  26. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  27. await ctx.plugin(ToolBash)
  28. return ctx
  29. }
  30. /** Full harness: the generic task runtime + its control surface, then the bash tool. */
  31. async function setupWithTasks() {
  32. const ctx = new Context()
  33. await ctx.plugin(SystemPrompt)
  34. await ctx.plugin(ToolRegistry)
  35. await ctx.plugin(AgentRegistry)
  36. await ctx.plugin(TaskService)
  37. await ctx.plugin(ToolTasks)
  38. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  39. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  40. await ctx.plugin(ToolBash)
  41. return ctx
  42. }
  43. /**
  44. * Build a fake {@link Agent} whose session token is `sessionId` and REGISTER it
  45. * in `ctx.agents` (an owned task registration attaches the awaited owner
  46. * cleanup via `ctx.agents.onCleanup`, which requires a live registered agent).
  47. * The agent id is deliberately DIFFERENT from the session token so a
  48. * wrong-field match fails the test.
  49. */
  50. function registerFakeAgent(ctx: Context, sessionId: string): Agent {
  51. const agent = { id: `agent-${sessionId}`, inject: () => {}, session: { header: { version: 0, id: sessionId, createdAt: 0 } } } as unknown as Agent
  52. ctx.agents.register(agent)
  53. return agent
  54. }
  55. let callCounter = 0
  56. function call(ctx: Context, name: string, args: unknown, agent?: Agent) {
  57. return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args, ...agent ? { agent } : {} })
  58. }
  59. function text(result: { content: { type: string; text?: string }[] }): string {
  60. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  61. }
  62. async function callUntilText(
  63. ctx: Context,
  64. name: string,
  65. args: unknown,
  66. expected: string,
  67. timeoutMs = 5_000,
  68. ): Promise<Awaited<ReturnType<typeof call>>> {
  69. const deadline = Date.now() + timeoutMs
  70. let last: Awaited<ReturnType<typeof call>> | undefined
  71. while (Date.now() < deadline) {
  72. last = await call(ctx, name, args)
  73. if (text(last).includes(expected)) return last
  74. await new Promise(resolve => setTimeout(resolve, 20))
  75. }
  76. throw new Error(`${name} output did not include ${JSON.stringify(expected)}; last text was ${JSON.stringify(last !== undefined ? text(last) : '')}`)
  77. }
  78. describe('bash tool', () => {
  79. it('returns stdout for a successful command', async () => {
  80. const ctx = await setup()
  81. const result = await call(ctx, 'bash', { command: 'echo hello', description: 'test command' })
  82. expect(result.isError).toBe(false)
  83. expect(text(result)).toBe('hello\n')
  84. })
  85. it('reports (no output) for silent commands', async () => {
  86. const ctx = await setup()
  87. const result = await call(ctx, 'bash', { command: 'true', description: 'test command' })
  88. expect(text(result)).toBe('(no output)')
  89. })
  90. it('marks stderr sections', async () => {
  91. const ctx = await setup()
  92. const result = await call(ctx, 'bash', { command: 'echo out; echo err >&2', description: 'test command' })
  93. expect(text(result)).toBe('out\n[stderr]\nerr\n')
  94. expect(result.isError).toBe(false)
  95. })
  96. it('reports non-zero exits without isError', async () => {
  97. const ctx = await setup()
  98. const result = await call(ctx, 'bash', { command: 'echo failing; exit 3', description: 'test command' })
  99. expect(result.isError).toBe(false)
  100. expect(text(result)).toBe('failing\n[exit code: 3]')
  101. })
  102. it('reports timeout kills with both markers (timeout first)', async () => {
  103. const ctx = await setup()
  104. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', timeoutMs: 100 })
  105. expect(result.isError).toBe(false)
  106. expect(text(result)).toBe('(no output)\n[timed out after 100ms]\n[killed by signal: SIGTERM]')
  107. })
  108. it('reports a timeout even when the command traps the signal and exits 0', async () => {
  109. // The signal-independent timeout marker: a trapped SIGTERM that exits 0
  110. // after our timer fired must NOT look like a clean success. (bash may
  111. // print "Terminated" to stderr for the killed sleep — environment
  112. // dependent — so assert the marker, not the exact body.)
  113. const ctx = await setup()
  114. const result = await call(ctx, 'bash', { command: 'trap "exit 0" TERM; sleep 60', description: 'test command', timeoutMs: 100 })
  115. expect(result.isError).toBe(false)
  116. expect(text(result)).toContain('[timed out after 100ms]')
  117. expect(text(result)).not.toContain('[exit code:')
  118. })
  119. it('reports truncation with the spill path', async () => {
  120. const ctx = new Context()
  121. await ctx.plugin(SystemPrompt)
  122. await ctx.plugin(ToolRegistry)
  123. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 })
  124. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  125. await ctx.plugin(ToolBash)
  126. const result = await call(ctx, 'bash', { command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done', description: 'test command' })
  127. expect(text(result)).toContain('[output truncated; full output: ')
  128. expect(text(result)).toContain('line-0100')
  129. })
  130. it('honors workdir', async () => {
  131. const ctx = await setup()
  132. const result = await call(ctx, 'bash', { command: 'pwd', description: 'test command', workdir: '/tmp' })
  133. expect(text(result).trim()).toMatch(/\/tmp$/)
  134. })
  135. it('surfaces spawn failures as isError', async () => {
  136. const ctx = await setup()
  137. const result = await call(ctx, 'bash', { command: 'true', description: 'test command', workdir: '/nonexistent-dsh' })
  138. expect(result.isError).toBe(true)
  139. expect(text(result)).toMatch(/ENOENT/)
  140. })
  141. it('surfaces foreground aborts as isError', async () => {
  142. const ctx = await setup()
  143. const controller = new AbortController()
  144. const pending = ctx.tools.execute({
  145. callId: CallId('call-abort'),
  146. name: 'bash',
  147. arguments: { command: 'sleep 60', description: 'test command' },
  148. signal: controller.signal,
  149. })
  150. setTimeout(() => { controller.abort() }, 50)
  151. const result = await pending
  152. expect(result.isError).toBe(true)
  153. expect(text(result)).toMatch(/aborted/)
  154. })
  155. // Type and required-key violations are rejected by the harness
  156. // (defineTool validates against the SchemaSpec — the arg-validation RFC) before execute.
  157. it.each([
  158. [{}, /missing required property "command"/],
  159. [{ command: 42, description: 'd' }, /"command" must be a string/],
  160. [{ command: 'x' }, /missing required property "description"/],
  161. [{ command: 'x', description: 7 }, /"description" must be a string/],
  162. [{ command: 'x', description: 'd', timeoutMs: 'soon' }, /"timeoutMs" must be a number/],
  163. [{ command: 'x', description: 'd', workdir: 7 }, /"workdir" must be a string/],
  164. [{ command: 'x', description: 'd', run_in_background: 'yes' }, /"run_in_background" must be a boolean/],
  165. ])('rejects schema-invalid args %j', async (args, pattern) => {
  166. const ctx = await setup()
  167. const result = await call(ctx, 'bash', args)
  168. expect(result.isError).toBe(true)
  169. expect(text(result)).toMatch(pattern)
  170. })
  171. // Value constraints the SchemaSpec can't express stay in the tool body.
  172. it.each([
  173. [{ command: ' ', description: 'd' }, /invalid command/],
  174. [{ command: 'x', description: ' ' }, /invalid description/],
  175. [{ command: 'x', description: 'd', timeoutMs: -1 }, /invalid timeoutMs/],
  176. [{ command: 'x', description: 'd', timeoutMs: Number.NaN }, /invalid timeoutMs/],
  177. ])('rejects value-invalid args %j', async (args, pattern) => {
  178. const ctx = await setup()
  179. const result = await call(ctx, 'bash', args)
  180. expect(result.isError).toBe(true)
  181. expect(text(result)).toMatch(pattern)
  182. })
  183. it('registers the bash schema with run_in_background exposed by default', async () => {
  184. const ctx = await setup()
  185. const schemas = ctx.tools.schemas()
  186. expect(schemas.map(schema => schema.name)).toEqual(['bash'])
  187. const bashSchema = schemas[0]!
  188. expect(bashSchema.parameters).toMatchObject({
  189. type: 'object',
  190. required: ['command', 'description'],
  191. })
  192. expect(Object.keys(bashSchema.parameters.properties as Record<string, unknown>))
  193. .toContain('run_in_background')
  194. expect(bashSchema.description).toContain('task_output')
  195. })
  196. it('contributes the exit-code habit as its prompt section (guidance the descriptions cannot carry)', async () => {
  197. const ctx = await setup()
  198. const assembly = await ctx.systemPrompt.assemble()
  199. const section = assembly.sections.find(s => s.name === 'tool:bash')
  200. expect(section?.order).toBe(105)
  201. expect(section?.text).toContain('[exit code: N]')
  202. })
  203. it('unregisters everything when the plugin fiber is disposed (HMR safety)', async () => {
  204. const ctx = new Context()
  205. await ctx.plugin(SystemPrompt)
  206. await ctx.plugin(ToolRegistry)
  207. await ctx.plugin(LocalBashExecutor, {})
  208. const fiber = await ctx.plugin(ToolBash)
  209. expect(ctx.tools.schemas()).toHaveLength(1)
  210. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona', 'tool:bash'])
  211. await fiber.dispose()
  212. expect(ctx.tools.schemas()).toHaveLength(0)
  213. // Only the system-prompt plugin's own built-in sections remain.
  214. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona'])
  215. })
  216. it('tools depend on the executor: no registration without ctx.bash', async () => {
  217. const ctx = new Context()
  218. await ctx.plugin(SystemPrompt)
  219. await ctx.plugin(ToolRegistry)
  220. // inject: ['tools', 'bash'] keeps the plugin pending until bash exists.
  221. await ctx.plugin(ToolBash)
  222. expect(ctx.tools.schemas()).toHaveLength(0)
  223. await ctx.plugin(LocalBashExecutor, {})
  224. await new Promise(resolve => setTimeout(resolve, 0))
  225. expect(ctx.tools.schemas()).toHaveLength(1)
  226. })
  227. it('applies the built-in background default when apply() receives a bare config', async () => {
  228. // Bypasses the schemastery defaults on purpose: apply() must stand on its
  229. // own `?? true` fallback when embedded programmatically without the schema.
  230. const ctx = new Context()
  231. await ctx.plugin(SystemPrompt)
  232. await ctx.plugin(ToolRegistry)
  233. await ctx.plugin(LocalBashExecutor, {})
  234. ToolBash.apply(ctx, {})
  235. const schema = ctx.tools.schemas()[0]!
  236. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  237. .toContain('run_in_background')
  238. })
  239. })
  240. describe('background execution through the task runtime', () => {
  241. it('run_in_background acks with the task id, readable through the REAL task_output tool', async () => {
  242. const ctx = await setupWithTasks()
  243. const started = await call(ctx, 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true })
  244. expect(started.isError).toBe(false)
  245. expect(text(started)).toBe('started background task bash-1')
  246. const read = await callUntilText(ctx, 'task_output', { task_id: 'bash-1' }, 'bg-ok')
  247. expect(text(read)).toContain('bg-ok')
  248. // A later read reports the terminal outcome in the generic status line.
  249. const final = await callUntilText(ctx, 'task_output', { task_id: 'bash-1' }, '[status: completed, exit code: 0]')
  250. expect(final.isError).toBe(false)
  251. })
  252. it('a running background task is killable through the REAL task_kill tool', async () => {
  253. const ctx = await setupWithTasks()
  254. await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  255. const killed = await call(ctx, 'task_kill', { task_id: 'bash-1' })
  256. expect(text(killed)).toBe('requested cancellation of task bash-1')
  257. // The cancel reached the process handle; the task settles as killed with
  258. // the signal detail mapped by processOutcome.
  259. const final = await call(ctx, 'task_output', { task_id: 'bash-1', wait: true })
  260. expect(text(final)).toContain('[status: killed, signal: SIGTERM]')
  261. })
  262. it('a background task started by an agent is registered with that agent as owner', async () => {
  263. // The fence SEMANTICS are pinned in dsh-tasks; this only pins that
  264. // tool-bash forwards exec.agent as the registration's owner.
  265. const ctx = await setupWithTasks()
  266. const agent = registerFakeAgent(ctx, 'sess-owner')
  267. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true }, agent)
  268. expect(text(started)).toBe('started background task bash-1')
  269. const anon = await call(ctx, 'task_output', { task_id: 'bash-1' })
  270. expect(anon.isError).toBe(true)
  271. expect(text(anon)).toMatch(/belongs to another session/)
  272. const killed = await call(ctx, 'task_kill', { task_id: 'bash-1' }, agent)
  273. expect(killed.isError).toBe(false)
  274. await call(ctx, 'task_output', { task_id: 'bash-1', wait: true }, agent) // await settlement — no orphan
  275. })
  276. it('fails loud when the task runtime is not loaded', async () => {
  277. const ctx = await setup() // no TaskService / ToolTasks
  278. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  279. expect(result.isError).toBe(true)
  280. expect(text(result)).toContain('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
  281. })
  282. it('a pre-aborted call refuses to start: isError, no process spawned', async () => {
  283. class CountingStartExecutor extends BashExecutor {
  284. starts = 0
  285. resolve(request: BashExecRequest): BashExecSpec {
  286. return { command: request.command, workdir: request.workdir ?? '/x', timeoutMs: request.timeoutMs ?? 0 }
  287. }
  288. run(): Promise<BashRunResult> { return Promise.reject(new Error('unused')) }
  289. start(spec: BashExecSpec): BashProcess {
  290. this.starts += 1
  291. return {
  292. command: spec.command,
  293. status: 'completed',
  294. exitCode: 0,
  295. signal: null,
  296. done: Promise.resolve(),
  297. readOutput: () => ({ delta: '', lossy: false }),
  298. kill: () => false,
  299. }
  300. }
  301. }
  302. const ctx = new Context()
  303. await ctx.plugin(SystemPrompt)
  304. await ctx.plugin(ToolRegistry)
  305. await ctx.plugin(AgentRegistry)
  306. await ctx.plugin(TaskService)
  307. await ctx.plugin(ToolTasks)
  308. await ctx.plugin(CountingStartExecutor)
  309. await ctx.plugin(ToolBash)
  310. const controller = new AbortController()
  311. controller.abort()
  312. const result = await ctx.tools.execute({
  313. callId: CallId('call-pre-aborted'),
  314. name: 'bash',
  315. arguments: { command: 'sleep 60', description: 'test command', run_in_background: true },
  316. signal: controller.signal,
  317. })
  318. expect(result.isError).toBe(true)
  319. expect(text(result)).toContain('command aborted')
  320. expect((ctx.bash as CountingStartExecutor).starts).toBe(0)
  321. })
  322. it('a failed registration kills the just-started process (no orphan without an id)', async () => {
  323. class LeakProbeExecutor extends BashExecutor {
  324. kills = 0
  325. resolve(request: BashExecRequest): BashExecSpec {
  326. return { command: request.command, workdir: request.workdir ?? '/x', timeoutMs: request.timeoutMs ?? 0 }
  327. }
  328. run(): Promise<BashRunResult> { return Promise.reject(new Error('unused')) }
  329. start(spec: BashExecSpec): BashProcess {
  330. let close!: () => void
  331. const done = new Promise<void>((res) => { close = res })
  332. const proc: BashProcess = {
  333. command: spec.command,
  334. status: 'running',
  335. exitCode: null,
  336. signal: null,
  337. done,
  338. readOutput: () => ({ delta: '', lossy: false }),
  339. kill: () => {
  340. this.kills += 1
  341. proc.status = 'killed'
  342. close()
  343. return true
  344. },
  345. }
  346. return proc
  347. }
  348. }
  349. // TaskService WITHOUT any control surface: register() throws AFTER the
  350. // process already started — the producer must kill and await it.
  351. const ctx = new Context()
  352. await ctx.plugin(SystemPrompt)
  353. await ctx.plugin(ToolRegistry)
  354. await ctx.plugin(AgentRegistry)
  355. await ctx.plugin(TaskService)
  356. await ctx.plugin(LeakProbeExecutor)
  357. await ctx.plugin(ToolBash)
  358. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  359. expect(result.isError).toBe(true)
  360. expect(text(result)).toContain('no control surface is attached')
  361. // The call resolved only after the kill landed (the catch awaits done).
  362. expect((ctx.bash as LeakProbeExecutor).kills).toBe(1)
  363. })
  364. it('enableRunInBackground: false removes the parameter and flips the description', async () => {
  365. const ctx = new Context()
  366. await ctx.plugin(SystemPrompt)
  367. await ctx.plugin(ToolRegistry)
  368. await ctx.plugin(LocalBashExecutor, {})
  369. await ctx.plugin(ToolBash, { enableRunInBackground: false })
  370. const schema = ctx.tools.schemas().find(s => s.name === 'bash')!
  371. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  372. .toEqual(['command', 'description', 'timeoutMs', 'workdir'])
  373. expect(schema.description).toContain('Background execution is not available')
  374. expect(schema.description).not.toContain('run_in_background')
  375. // The registry-held definition agrees (schema and capability never disagree).
  376. const parameters = ctx.tools.get('bash')!.parameters as { properties: Record<string, unknown> }
  377. expect('run_in_background' in parameters.properties).toBe(false)
  378. })
  379. })
  380. describe('renderProcessRead', () => {
  381. const base: BashProcessRead = { delta: 'out\n', lossy: false }
  382. it('returns the delta verbatim for a lossless read', () => {
  383. expect(renderProcessRead(base)).toBe('out\n')
  384. expect(renderProcessRead({ delta: '', lossy: false })).toBe('')
  385. })
  386. it('appends the loss notice with the available spill paths', () => {
  387. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log' }))
  388. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log]')
  389. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log', stderrSpillPath: '/spill/err.log' }))
  390. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log, /spill/err.log]')
  391. })
  392. it('reports (unavailable) when a lossy read has no safe spill path', () => {
  393. expect(renderProcessRead({ ...base, lossy: true }))
  394. .toBe('out\n[some output was dropped from memory; full output: (unavailable)]')
  395. })
  396. it('an empty lossy delta is the notice alone', () => {
  397. expect(renderProcessRead({ delta: '', lossy: true, stderrSpillPath: '/spill/err.log' }))
  398. .toBe('[some output was dropped from memory; full output: /spill/err.log]')
  399. })
  400. it('inserts the separating newline only when the delta lacks one', () => {
  401. expect(renderProcessRead({ delta: 'tail', lossy: true }))
  402. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  403. expect(renderProcessRead({ delta: 'tail\n', lossy: true }))
  404. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  405. })
  406. })
  407. describe('processOutcome', () => {
  408. function settled(over: Partial<BashProcess>): BashProcess {
  409. return {
  410. command: 'x',
  411. status: 'completed',
  412. exitCode: 0,
  413. signal: null,
  414. done: Promise.resolve(),
  415. readOutput: () => ({ delta: '', lossy: false }),
  416. kill: () => false,
  417. ...over,
  418. }
  419. }
  420. it('maps a signal-killed process to killed with the signal detail', () => {
  421. expect(processOutcome(settled({ status: 'killed', signal: 'SIGTERM' })))
  422. .toEqual({ status: 'killed', detail: 'signal: SIGTERM' })
  423. })
  424. it('maps a killed process without a recorded signal (kill raced exit / spawn failure)', () => {
  425. expect(processOutcome(settled({ status: 'killed', exitCode: null })))
  426. .toEqual({ status: 'killed', detail: 'killed before exit' })
  427. })
  428. it('maps a completed process to its exit code', () => {
  429. expect(processOutcome(settled({ exitCode: 3 })))
  430. .toEqual({ status: 'completed', detail: 'exit code: 3' })
  431. })
  432. it('defensively reads a null exit code as 0 (handle shapes from other executors)', () => {
  433. expect(processOutcome(settled({ exitCode: null })))
  434. .toEqual({ status: 'completed', detail: 'exit code: 0' })
  435. })
  436. })
  437. describe('session-cwd routing (per-session workdir)', () => {
  438. // An agent whose session header carries a cwd (what session/new records).
  439. const agentInCwd = (cwd: string) =>
  440. ({ inject: () => undefined, session: { header: { version: 0, id: 'c', createdAt: 0, cwd } } }) as unknown as Agent
  441. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  442. const ctx = await setup()
  443. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  444. expect(text(result).trim()).toMatch(/\/tmp$/)
  445. })
  446. it('an explicit absolute workdir overrides the session cwd', async () => {
  447. const ctx = await setup()
  448. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: '/tmp' }, agentInCwd('/'))
  449. expect(text(result).trim()).toMatch(/\/tmp$/)
  450. })
  451. it('a relative workdir is resolved against the session cwd', async () => {
  452. const ctx = await setup()
  453. // session cwd /usr + relative 'bin' → /usr/bin
  454. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: 'bin' }, agentInCwd('/usr'))
  455. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  456. })
  457. it('two sessions with different cwds each run bash in their own dir', async () => {
  458. const ctx = await setup()
  459. const inUsr = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/usr'))
  460. const inTmp = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  461. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  462. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  463. })
  464. it('falls back to the executor default when the agent has no session cwd', async () => {
  465. const ctx = await setup()
  466. // No exec.agent at all → executor uses its config/process.cwd() default.
  467. const result = await ctx.tools.execute({ callId: CallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  468. expect(result.isError).toBe(false)
  469. expect(text(result).trim().length).toBeGreaterThan(0)
  470. })
  471. })
  472. describe('renderResult', () => {
  473. const base = {
  474. exitCode: 0 as number | null,
  475. signal: null as NodeJS.Signals | null,
  476. timedOut: false,
  477. aborted: false,
  478. timeoutMs: 1000,
  479. stdout: { text: '', truncated: false },
  480. stderr: { text: '', truncated: false },
  481. }
  482. it('renders stderr-only output without a stdout prefix', () => {
  483. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  484. .toBe('[stderr]\nerr\n')
  485. })
  486. it('adds a separator when stdout does not end with a newline', () => {
  487. expect(renderResult({
  488. ...base,
  489. stdout: { text: 'out', truncated: false },
  490. stderr: { text: 'err', truncated: false },
  491. })).toBe('out\n[stderr]\nerr')
  492. })
  493. it('appends exit-code markers after a newline for unterminated output', () => {
  494. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  495. .toBe('x\n[exit code: 7]')
  496. })
  497. it('renders signal kills without the timeout marker when not timed out', () => {
  498. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  499. .toBe('(no output)\n[killed by signal: SIGKILL]')
  500. })
  501. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  502. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  503. .toBe('(no output)\n[timed out after 1000ms]')
  504. })
  505. it('orders the timeout marker before a kill marker', () => {
  506. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  507. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  508. })
  509. it('notes truncation with a fallback when the spill path is missing', () => {
  510. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  511. .toBe('tail\n[output truncated; full output: (unavailable)]')
  512. })
  513. })
  514. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  515. it('bash presentCall: a foreground run is a terminal card (command title, description, workdir → cwd absolute or relative)', async () => {
  516. const ctx = await setup()
  517. // No explicit workdir → a terminal card with no cwd (the UI bridge fills the
  518. // session cwd it owns; the pure presenter can't see it).
  519. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  520. .toEqual({ card: 'terminal', title: 'ls -la src', description: 'List files in src' })
  521. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  522. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  523. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: '/tmp/x' })
  524. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  525. // the session cwd, matching where execution runs) — not dropped.
  526. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  527. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: 'sub' })
  528. })
  529. it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => {
  530. const ctx = await setup()
  531. const present = ctx.tools.get('bash')!.presentResult!(
  532. { command: 'echo hi', description: 'echo' },
  533. { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false },
  534. )
  535. // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer
  536. // needs; the bridge derives the fenced fallback. exitCode is parsed back from
  537. // the [exit code: N] marker.
  538. expect(present).toEqual({ card: 'terminal', output: 'hi\n[exit code: 0]\n\n', exitCode: 0 })
  539. })
  540. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  541. const ctx = await setup()
  542. const args = { command: 'x', description: 'x' }
  543. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  544. expect(nonzero).toEqual({ card: 'terminal', output: 'oops\n[exit code: 3]', exitCode: 3 })
  545. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  546. expect(killed).toEqual({ card: 'terminal', output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' })
  547. })
  548. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  549. const ctx = await setup()
  550. const present = ctx.tools.get('bash')!
  551. // For each renderResult outcome, the rendered text fed back through
  552. // presentResult recovers the matching structured exit — the parse and the
  553. // marker emission co-evolve in one file, so this pins the pair.
  554. const base = {
  555. aborted: false,
  556. timeoutMs: 1000,
  557. stdout: { text: 'out', truncated: false },
  558. stderr: { text: '', truncated: false },
  559. }
  560. const cases = [
  561. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  562. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  563. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  564. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  565. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  566. ]
  567. for (const c of cases) {
  568. const rendered = renderResult(c.result)
  569. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  570. // Drop card + output; the remaining fields are the parsed exit.
  571. const { card: _c, output: _o, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string }
  572. expect(exit).toEqual(c.expect)
  573. }
  574. })
  575. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  576. const ctx = await setup()
  577. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  578. // A successful command can print text that looks like a marker. renderResult
  579. // for a clean exit 0 appends NOTHING (and no trailing newline), so the body's
  580. // own tail is `[exit code: 5]`. The parse requires a LEADING newline before
  581. // the marker (renderResult always inserts one before a REAL marker), so this
  582. // no-trailing-newline body is NOT mistaken for a failure → exitCode 0.
  583. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  584. expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 })
  585. // Same for a fake signal marker with no leading newline.
  586. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  587. expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 })
  588. })
  589. it('bash presentCall/presentResult: a run_in_background call is a generic card and its ack carries no exit pill', async () => {
  590. const ctx = await setup()
  591. // The background start returns a task-id ack, not a streamed run — a generic
  592. // execute card with the command as rawInput and the description as content.
  593. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  594. expect(call).toEqual({ card: 'generic', title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  595. // The ack result is a generic fenced-text card — no terminal output / exit pill.
  596. const result = ctx.tools.get('bash')!.presentResult!(
  597. { command: 'sleep 100', description: 'wait', run_in_background: true },
  598. { content: [{ type: 'text', text: 'started background task bash-1' }], isError: false },
  599. )
  600. expect(result).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\nstarted background task bash-1\n```' }] })
  601. })
  602. it('bash presentResult: an isError result is a generic card (no real process exit to report)', async () => {
  603. const ctx = await setup()
  604. // A spawn failure / abort has no process exit — the body is an error message,
  605. // not renderResult output, so a generic fenced card, no terminal output/exit.
  606. const out = ctx.tools.get('bash')!.presentResult!(
  607. { command: 'x', description: 'x' },
  608. { content: [{ type: 'text', text: 'command aborted' }], isError: true },
  609. )
  610. expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ncommand aborted\n```' }] })
  611. })
  612. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  613. const ctx = await setup()
  614. const present = ctx.tools.get('bash')!.presentResult!(
  615. { command: 'x', description: 'x' },
  616. { content: [{ type: 'reasoning', text: 'unexpected' }], isError: false },
  617. )
  618. expect(present).toBeUndefined()
  619. })
  620. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  621. const ctx = await setup()
  622. const args = { command: 'x', description: 'x' }
  623. // Empty content (no block) and multi-block content both fall through.
  624. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  625. expect(ctx.tools.get('bash')!.presentResult!(args, {
  626. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  627. isError: false,
  628. })).toBeUndefined()
  629. })
  630. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  631. const ctx = await setup()
  632. // defineTool wraps presentCall to soft-validate against the schema and fall
  633. // back to undefined (a generic UI presentation) rather than throwing on the
  634. // display path — it may run on replay of arbitrary logged args. The
  635. // ToolDefinition.presentCall takes `unknown`, so a malformed shape needs no cast.
  636. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  637. })
  638. })
  639. describe('the model-facing bash tool builds its request from named args only (no {...args} forward)', () => {
  640. /**
  641. * Records every {@link BashExecRequest} the consumer hands to `resolve()`, so a
  642. * test can assert what the model-facing tool DID and DID NOT forward. The `bash`
  643. * tool does not expose `stdin`/`env` as parameters (bash syntax already gives a
  644. * model that power), so it must build its request from named args only and
  645. * never spread unknown tool-call keys into it. This guard's job is to catch a
  646. * future refactor that blindly forwards `...args` — which would silently thread
  647. * model input into the post-scrub `env` merge — NOT to defend a trust boundary
  648. * (the credential scrub in dsh-bash-local is the security control; see the
  649. * bash-stdin-env RFC). Foreground `run()` returns a canned result; `start()`
  650. * hands back an already-settled fake handle so the task registration completes.
  651. */
  652. class RecordingBashExecutor extends BashExecutor {
  653. readonly requests: BashExecRequest[] = []
  654. resolve(request: BashExecRequest): BashExecSpec {
  655. this.requests.push(request)
  656. return {
  657. command: request.command,
  658. workdir: request.workdir ?? process.cwd(),
  659. timeoutMs: request.timeoutMs ?? 0,
  660. ...request.signal ? { signal: request.signal } : {},
  661. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  662. ...request.env !== undefined ? { env: request.env } : {},
  663. }
  664. }
  665. run(): Promise<BashRunResult> {
  666. return Promise.resolve({
  667. exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 0,
  668. stdout: { text: 'ok', truncated: false }, stderr: { text: '', truncated: false },
  669. })
  670. }
  671. start(spec: BashExecSpec): BashProcess {
  672. return {
  673. command: spec.command,
  674. status: 'completed',
  675. exitCode: 0,
  676. signal: null,
  677. done: Promise.resolve(),
  678. readOutput: () => ({ delta: '', lossy: false }),
  679. kill: () => false,
  680. }
  681. }
  682. }
  683. async function setupRecording() {
  684. const ctx = new Context()
  685. await ctx.plugin(SystemPrompt)
  686. await ctx.plugin(ToolRegistry)
  687. await ctx.plugin(AgentRegistry)
  688. await ctx.plugin(TaskService)
  689. await ctx.plugin(ToolTasks)
  690. await ctx.plugin(RecordingBashExecutor)
  691. await ctx.plugin(ToolBash)
  692. return { ctx, bash: ctx.bash as RecordingBashExecutor }
  693. }
  694. it('does not forward env/stdin even when the model includes them as extra arguments', async () => {
  695. const { ctx, bash } = await setupRecording()
  696. // Extra args: the model includes `env` and `stdin` keys hoping they reach the
  697. // executor. The bash tool's schema ignores unknown keys, and execute() builds
  698. // the request from only command/workdir/timeoutMs/signal — so the recorded
  699. // request carries NEITHER. (Not a security wall — the model could set an env
  700. // var or feed stdin via shell syntax anyway; this just keeps the request
  701. // shape honest so a future `...args` spread can't silently forward input.)
  702. await ctx.tools.execute({
  703. callId: CallId('no-forward-1'),
  704. name: 'bash',
  705. arguments: {
  706. command: 'echo hi',
  707. description: 'echo',
  708. env: { SNEAKY_API_KEY: 'leak' },
  709. stdin: 'malicious payload',
  710. },
  711. })
  712. expect(bash.requests).toHaveLength(1)
  713. const request = bash.requests[0]!
  714. expect(request.command).toBe('echo hi')
  715. expect('env' in request).toBe(false)
  716. expect('stdin' in request).toBe(false)
  717. })
  718. it('a background bash call likewise carries no env/stdin', async () => {
  719. const { ctx, bash } = await setupRecording()
  720. const result = await ctx.tools.execute({
  721. callId: CallId('no-forward-2'),
  722. name: 'bash',
  723. arguments: {
  724. command: 'sleep 1',
  725. description: 'sleep',
  726. run_in_background: true,
  727. env: { TOKEN: 'leak' },
  728. stdin: 'x',
  729. },
  730. })
  731. // The call really went down the background path (the recorder sees the real
  732. // request the consumer built, so the absent env/stdin below is a real
  733. // negative, not a recorder that drops everything).
  734. expect(text(result)).toBe('started background task bash-1')
  735. expect(bash.requests).toHaveLength(1)
  736. const request = bash.requests[0]!
  737. expect(request.command).toBe('sleep 1')
  738. expect('env' in request).toBe(false)
  739. expect('stdin' in request).toBe(false)
  740. })
  741. })