tools.spec.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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('never spawns the process when tasks.start preflight throws (no orphan, by construction)', async () => {
  323. class LeakProbeExecutor extends BashExecutor {
  324. starts = 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. this.starts += 1
  331. return {
  332. command: spec.command,
  333. status: 'completed',
  334. exitCode: 0,
  335. signal: null,
  336. done: Promise.resolve(),
  337. readOutput: () => ({ delta: '', lossy: false }),
  338. kill: () => false,
  339. }
  340. }
  341. }
  342. // TaskService WITHOUT any control surface: tasks.start preflights that
  343. // fence BEFORE invoking the producer's run(), so the executor is never
  344. // asked to spawn — there is no orphan to roll back.
  345. const ctx = new Context()
  346. await ctx.plugin(SystemPrompt)
  347. await ctx.plugin(ToolRegistry)
  348. await ctx.plugin(AgentRegistry)
  349. await ctx.plugin(TaskService)
  350. await ctx.plugin(LeakProbeExecutor)
  351. await ctx.plugin(ToolBash)
  352. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  353. expect(result.isError).toBe(true)
  354. expect(text(result)).toContain('no control surface is attached')
  355. // Declare-then-execute: the failed preflight means no process ever ran.
  356. expect((ctx.bash as LeakProbeExecutor).starts).toBe(0)
  357. })
  358. it('enableRunInBackground: false removes the parameter and flips the description', async () => {
  359. const ctx = new Context()
  360. await ctx.plugin(SystemPrompt)
  361. await ctx.plugin(ToolRegistry)
  362. await ctx.plugin(LocalBashExecutor, {})
  363. await ctx.plugin(ToolBash, { enableRunInBackground: false })
  364. const schema = ctx.tools.schemas().find(s => s.name === 'bash')!
  365. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  366. .toEqual(['command', 'description', 'timeoutMs', 'workdir'])
  367. expect(schema.description).toContain('Background execution is not available')
  368. expect(schema.description).not.toContain('run_in_background')
  369. // The registry-held definition agrees (schema and capability never disagree).
  370. const parameters = ctx.tools.get('bash')!.parameters as { properties: Record<string, unknown> }
  371. expect('run_in_background' in parameters.properties).toBe(false)
  372. })
  373. })
  374. describe('renderProcessRead', () => {
  375. const base: BashProcessRead = { delta: 'out\n', lossy: false }
  376. it('returns the delta verbatim for a lossless read', () => {
  377. expect(renderProcessRead(base)).toBe('out\n')
  378. expect(renderProcessRead({ delta: '', lossy: false })).toBe('')
  379. })
  380. it('appends the loss notice with the available spill paths', () => {
  381. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log' }))
  382. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log]')
  383. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log', stderrSpillPath: '/spill/err.log' }))
  384. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log, /spill/err.log]')
  385. })
  386. it('reports (unavailable) when a lossy read has no safe spill path', () => {
  387. expect(renderProcessRead({ ...base, lossy: true }))
  388. .toBe('out\n[some output was dropped from memory; full output: (unavailable)]')
  389. })
  390. it('an empty lossy delta is the notice alone', () => {
  391. expect(renderProcessRead({ delta: '', lossy: true, stderrSpillPath: '/spill/err.log' }))
  392. .toBe('[some output was dropped from memory; full output: /spill/err.log]')
  393. })
  394. it('inserts the separating newline only when the delta lacks one', () => {
  395. expect(renderProcessRead({ delta: 'tail', lossy: true }))
  396. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  397. expect(renderProcessRead({ delta: 'tail\n', lossy: true }))
  398. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  399. })
  400. })
  401. describe('processOutcome', () => {
  402. function settled(over: Partial<BashProcess>): BashProcess {
  403. return {
  404. command: 'x',
  405. status: 'completed',
  406. exitCode: 0,
  407. signal: null,
  408. done: Promise.resolve(),
  409. readOutput: () => ({ delta: '', lossy: false }),
  410. kill: () => false,
  411. ...over,
  412. }
  413. }
  414. it('maps a signal-killed process to killed with the signal detail', () => {
  415. expect(processOutcome(settled({ status: 'killed', signal: 'SIGTERM' })))
  416. .toEqual({ status: 'killed', detail: 'signal: SIGTERM' })
  417. })
  418. it('maps a killed process without a recorded signal (kill raced exit / spawn failure)', () => {
  419. expect(processOutcome(settled({ status: 'killed', exitCode: null })))
  420. .toEqual({ status: 'killed', detail: 'killed before exit' })
  421. })
  422. it('maps a completed process to its exit code', () => {
  423. expect(processOutcome(settled({ exitCode: 3 })))
  424. .toEqual({ status: 'completed', detail: 'exit code: 3' })
  425. })
  426. it('defensively reads a null exit code as 0 (handle shapes from other executors)', () => {
  427. expect(processOutcome(settled({ exitCode: null })))
  428. .toEqual({ status: 'completed', detail: 'exit code: 0' })
  429. })
  430. })
  431. describe('session-cwd routing (per-session workdir)', () => {
  432. // An agent whose session header carries a cwd (what session/new records).
  433. const agentInCwd = (cwd: string) =>
  434. ({ inject: () => undefined, session: { header: { version: 0, id: 'c', createdAt: 0, cwd } } }) as unknown as Agent
  435. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  436. const ctx = await setup()
  437. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  438. expect(text(result).trim()).toMatch(/\/tmp$/)
  439. })
  440. it('an explicit absolute workdir overrides the session cwd', async () => {
  441. const ctx = await setup()
  442. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: '/tmp' }, agentInCwd('/'))
  443. expect(text(result).trim()).toMatch(/\/tmp$/)
  444. })
  445. it('a relative workdir is resolved against the session cwd', async () => {
  446. const ctx = await setup()
  447. // session cwd /usr + relative 'bin' → /usr/bin
  448. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: 'bin' }, agentInCwd('/usr'))
  449. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  450. })
  451. it('two sessions with different cwds each run bash in their own dir', async () => {
  452. const ctx = await setup()
  453. const inUsr = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/usr'))
  454. const inTmp = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  455. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  456. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  457. })
  458. it('falls back to the executor default when the agent has no session cwd', async () => {
  459. const ctx = await setup()
  460. // No exec.agent at all → executor uses its config/process.cwd() default.
  461. const result = await ctx.tools.execute({ callId: CallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  462. expect(result.isError).toBe(false)
  463. expect(text(result).trim().length).toBeGreaterThan(0)
  464. })
  465. })
  466. describe('renderResult', () => {
  467. const base = {
  468. exitCode: 0 as number | null,
  469. signal: null as NodeJS.Signals | null,
  470. timedOut: false,
  471. aborted: false,
  472. timeoutMs: 1000,
  473. stdout: { text: '', truncated: false },
  474. stderr: { text: '', truncated: false },
  475. }
  476. it('renders stderr-only output without a stdout prefix', () => {
  477. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  478. .toBe('[stderr]\nerr\n')
  479. })
  480. it('adds a separator when stdout does not end with a newline', () => {
  481. expect(renderResult({
  482. ...base,
  483. stdout: { text: 'out', truncated: false },
  484. stderr: { text: 'err', truncated: false },
  485. })).toBe('out\n[stderr]\nerr')
  486. })
  487. it('appends exit-code markers after a newline for unterminated output', () => {
  488. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  489. .toBe('x\n[exit code: 7]')
  490. })
  491. it('renders signal kills without the timeout marker when not timed out', () => {
  492. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  493. .toBe('(no output)\n[killed by signal: SIGKILL]')
  494. })
  495. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  496. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  497. .toBe('(no output)\n[timed out after 1000ms]')
  498. })
  499. it('orders the timeout marker before a kill marker', () => {
  500. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  501. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  502. })
  503. it('notes truncation with a fallback when the spill path is missing', () => {
  504. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  505. .toBe('tail\n[output truncated; full output: (unavailable)]')
  506. })
  507. })
  508. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  509. it('bash presentCall: a foreground run is a terminal card (command title, description, workdir → cwd absolute or relative)', async () => {
  510. const ctx = await setup()
  511. // No explicit workdir → a terminal card with no cwd (the UI bridge fills the
  512. // session cwd it owns; the pure presenter can't see it).
  513. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  514. .toEqual({ card: 'terminal', title: 'ls -la src', description: 'List files in src' })
  515. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  516. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  517. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: '/tmp/x' })
  518. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  519. // the session cwd, matching where execution runs) — not dropped.
  520. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  521. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: 'sub' })
  522. })
  523. it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => {
  524. const ctx = await setup()
  525. const present = ctx.tools.get('bash')!.presentResult!(
  526. { command: 'echo hi', description: 'echo' },
  527. { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false },
  528. )
  529. // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer
  530. // needs; the bridge derives the fenced fallback. exitCode is parsed back from
  531. // the [exit code: N] marker.
  532. expect(present).toEqual({ card: 'terminal', output: 'hi\n[exit code: 0]\n\n', exitCode: 0 })
  533. })
  534. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  535. const ctx = await setup()
  536. const args = { command: 'x', description: 'x' }
  537. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  538. expect(nonzero).toEqual({ card: 'terminal', output: 'oops\n[exit code: 3]', exitCode: 3 })
  539. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  540. expect(killed).toEqual({ card: 'terminal', output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' })
  541. })
  542. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  543. const ctx = await setup()
  544. const present = ctx.tools.get('bash')!
  545. // For each renderResult outcome, the rendered text fed back through
  546. // presentResult recovers the matching structured exit — the parse and the
  547. // marker emission co-evolve in one file, so this pins the pair.
  548. const base = {
  549. aborted: false,
  550. timeoutMs: 1000,
  551. stdout: { text: 'out', truncated: false },
  552. stderr: { text: '', truncated: false },
  553. }
  554. const cases = [
  555. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  556. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  557. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  558. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  559. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  560. ]
  561. for (const c of cases) {
  562. const rendered = renderResult(c.result)
  563. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  564. // Drop card + output; the remaining fields are the parsed exit.
  565. const { card: _c, output: _o, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string }
  566. expect(exit).toEqual(c.expect)
  567. }
  568. })
  569. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  570. const ctx = await setup()
  571. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  572. // A successful command can print text that looks like a marker. renderResult
  573. // for a clean exit 0 appends NOTHING (and no trailing newline), so the body's
  574. // own tail is `[exit code: 5]`. The parse requires a LEADING newline before
  575. // the marker (renderResult always inserts one before a REAL marker), so this
  576. // no-trailing-newline body is NOT mistaken for a failure → exitCode 0.
  577. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  578. expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 })
  579. // Same for a fake signal marker with no leading newline.
  580. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  581. expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 })
  582. })
  583. it('bash presentCall/presentResult: a run_in_background call is a generic card and its ack carries no exit pill', async () => {
  584. const ctx = await setup()
  585. // The background start returns a task-id ack, not a streamed run — a generic
  586. // execute card with the command as rawInput and the description as content.
  587. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  588. expect(call).toEqual({ card: 'generic', title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  589. // The ack result is a generic fenced-text card — no terminal output / exit pill.
  590. const result = ctx.tools.get('bash')!.presentResult!(
  591. { command: 'sleep 100', description: 'wait', run_in_background: true },
  592. { content: [{ type: 'text', text: 'started background task bash-1' }], isError: false },
  593. )
  594. expect(result).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\nstarted background task bash-1\n```' }] })
  595. })
  596. it('bash presentResult: an isError result is a generic card (no real process exit to report)', async () => {
  597. const ctx = await setup()
  598. // A spawn failure / abort has no process exit — the body is an error message,
  599. // not renderResult output, so a generic fenced card, no terminal output/exit.
  600. const out = ctx.tools.get('bash')!.presentResult!(
  601. { command: 'x', description: 'x' },
  602. { content: [{ type: 'text', text: 'command aborted' }], isError: true },
  603. )
  604. expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ncommand aborted\n```' }] })
  605. })
  606. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  607. const ctx = await setup()
  608. const present = ctx.tools.get('bash')!.presentResult!(
  609. { command: 'x', description: 'x' },
  610. { content: [{ type: 'reasoning', text: 'unexpected' }], isError: false },
  611. )
  612. expect(present).toBeUndefined()
  613. })
  614. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  615. const ctx = await setup()
  616. const args = { command: 'x', description: 'x' }
  617. // Empty content (no block) and multi-block content both fall through.
  618. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  619. expect(ctx.tools.get('bash')!.presentResult!(args, {
  620. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  621. isError: false,
  622. })).toBeUndefined()
  623. })
  624. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  625. const ctx = await setup()
  626. // defineTool wraps presentCall to soft-validate against the schema and fall
  627. // back to undefined (a generic UI presentation) rather than throwing on the
  628. // display path — it may run on replay of arbitrary logged args. The
  629. // ToolDefinition.presentCall takes `unknown`, so a malformed shape needs no cast.
  630. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  631. })
  632. })
  633. describe('the model-facing bash tool builds its request from named args only (no {...args} forward)', () => {
  634. /**
  635. * Records every {@link BashExecRequest} the consumer hands to `resolve()`, so a
  636. * test can assert what the model-facing tool DID and DID NOT forward. The `bash`
  637. * tool does not expose `stdin`/`env` as parameters (bash syntax already gives a
  638. * model that power), so it must build its request from named args only and
  639. * never spread unknown tool-call keys into it. This guard's job is to catch a
  640. * future refactor that blindly forwards `...args` — which would silently thread
  641. * model input into the post-scrub `env` merge — NOT to defend a trust boundary
  642. * (the credential scrub in dsh-bash-local is the security control; see the
  643. * bash-stdin-env RFC). Foreground `run()` returns a canned result; `start()`
  644. * hands back an already-settled fake handle so the task registration completes.
  645. */
  646. class RecordingBashExecutor extends BashExecutor {
  647. readonly requests: BashExecRequest[] = []
  648. resolve(request: BashExecRequest): BashExecSpec {
  649. this.requests.push(request)
  650. return {
  651. command: request.command,
  652. workdir: request.workdir ?? process.cwd(),
  653. timeoutMs: request.timeoutMs ?? 0,
  654. ...request.signal ? { signal: request.signal } : {},
  655. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  656. ...request.env !== undefined ? { env: request.env } : {},
  657. }
  658. }
  659. run(): Promise<BashRunResult> {
  660. return Promise.resolve({
  661. exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 0,
  662. stdout: { text: 'ok', truncated: false }, stderr: { text: '', truncated: false },
  663. })
  664. }
  665. start(spec: BashExecSpec): BashProcess {
  666. return {
  667. command: spec.command,
  668. status: 'completed',
  669. exitCode: 0,
  670. signal: null,
  671. done: Promise.resolve(),
  672. readOutput: () => ({ delta: '', lossy: false }),
  673. kill: () => false,
  674. }
  675. }
  676. }
  677. async function setupRecording() {
  678. const ctx = new Context()
  679. await ctx.plugin(SystemPrompt)
  680. await ctx.plugin(ToolRegistry)
  681. await ctx.plugin(AgentRegistry)
  682. await ctx.plugin(TaskService)
  683. await ctx.plugin(ToolTasks)
  684. await ctx.plugin(RecordingBashExecutor)
  685. await ctx.plugin(ToolBash)
  686. return { ctx, bash: ctx.bash as RecordingBashExecutor }
  687. }
  688. it('does not forward env/stdin even when the model includes them as extra arguments', async () => {
  689. const { ctx, bash } = await setupRecording()
  690. // Extra args: the model includes `env` and `stdin` keys hoping they reach the
  691. // executor. The bash tool's schema ignores unknown keys, and execute() builds
  692. // the request from only command/workdir/timeoutMs/signal — so the recorded
  693. // request carries NEITHER. (Not a security wall — the model could set an env
  694. // var or feed stdin via shell syntax anyway; this just keeps the request
  695. // shape honest so a future `...args` spread can't silently forward input.)
  696. await ctx.tools.execute({
  697. callId: CallId('no-forward-1'),
  698. name: 'bash',
  699. arguments: {
  700. command: 'echo hi',
  701. description: 'echo',
  702. env: { SNEAKY_API_KEY: 'leak' },
  703. stdin: 'malicious payload',
  704. },
  705. })
  706. expect(bash.requests).toHaveLength(1)
  707. const request = bash.requests[0]!
  708. expect(request.command).toBe('echo hi')
  709. expect('env' in request).toBe(false)
  710. expect('stdin' in request).toBe(false)
  711. })
  712. it('a background bash call likewise carries no env/stdin', async () => {
  713. const { ctx, bash } = await setupRecording()
  714. const result = await ctx.tools.execute({
  715. callId: CallId('no-forward-2'),
  716. name: 'bash',
  717. arguments: {
  718. command: 'sleep 1',
  719. description: 'sleep',
  720. run_in_background: true,
  721. env: { TOKEN: 'leak' },
  722. stdin: 'x',
  723. },
  724. })
  725. // The call really went down the background path (the recorder sees the real
  726. // request the consumer built, so the absent env/stdin below is a real
  727. // negative, not a recorder that drops everything).
  728. expect(text(result)).toBe('started background task bash-1')
  729. expect(bash.requests).toHaveLength(1)
  730. const request = bash.requests[0]!
  731. expect(request.command).toBe('sleep 1')
  732. expect('env' in request).toBe(false)
  733. expect('stdin' in request).toBe(false)
  734. })
  735. })