tools.spec.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { Context } from 'cordis'
  6. import { CallId } from '@deepseek-ai/dsh-llm'
  7. import { BashExecutor, BashTaskId } from '@deepseek-ai/dsh-bash'
  8. import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead, OwnerToken } 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 { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  14. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  15. import { renderResult } from '@deepseek-ai/dsh-tool-bash'
  16. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-tool-bash-spec-'))
  17. async function setup() {
  18. const ctx = new Context()
  19. await ctx.plugin(SystemPrompt)
  20. await ctx.plugin(ToolRegistry)
  21. await ctx.plugin(AgentRegistry)
  22. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  23. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  24. await ctx.plugin(ToolBash)
  25. return ctx
  26. }
  27. /**
  28. * Build a fake {@link Agent} whose session token is `sessionId`, REGISTER it in
  29. * `ctx.agents` (the completion-notice path finds the owning agent by scanning
  30. * the registry for a matching `session.header.id`), and return it. The returned
  31. * agent is also passed to `execute` as `exec.agent` so it owns the spawned task.
  32. * The registration disposer is tracked so {@link unregisterFakeAgents} can drop
  33. * it (simulating the owning session disconnecting before a task completes).
  34. */
  35. const fakeAgentDisposers = new Map<Context, (() => Promise<void> | void)[]>()
  36. function registerFakeAgent(ctx: Context, sessionId: string, inject: (...args: unknown[]) => void): Agent {
  37. // The registry KEY (agent.id) is deliberately DIFFERENT from the session
  38. // token (session.header.id) — a config agent has `agentId !== sessionId`. The
  39. // owner token IS the session id, so the notice path must find the agent by
  40. // `session.header.id`, NOT the registry key. Using distinct values here makes
  41. // the test fail if a regression matched on the wrong field (a same-value fake
  42. // would pass either way — the "hits the line but not the scenario" trap).
  43. const agent = { id: `agent-${sessionId}`, inject, session: { header: { version: 0, id: sessionId, createdAt: 0 } } } as unknown as Agent
  44. const dispose = ctx.agents.register(agent)
  45. const list = fakeAgentDisposers.get(ctx) ?? []
  46. list.push(dispose)
  47. fakeAgentDisposers.set(ctx, list)
  48. return agent
  49. }
  50. /** Unregister every fake agent in this ctx (simulate the owning session disconnecting). */
  51. function unregisterFakeAgents(ctx: Context): void {
  52. for (const dispose of fakeAgentDisposers.get(ctx) ?? []) void dispose()
  53. fakeAgentDisposers.delete(ctx)
  54. }
  55. let callCounter = 0
  56. function call(ctx: Context, name: string, args: unknown) {
  57. return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args })
  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. class LossyReadBashExecutor extends BashExecutor {
  79. private readonly task: BashTask = {
  80. id: BashTaskId('bash-lossy'),
  81. command: 'fake',
  82. status: 'running',
  83. exitCode: null,
  84. signal: null,
  85. done: Promise.resolve(),
  86. }
  87. resolve(request: BashExecRequest): BashExecSpec {
  88. return {
  89. command: request.command,
  90. workdir: request.workdir ?? process.cwd(),
  91. timeoutMs: request.timeoutMs ?? 0,
  92. ...request.signal ? { signal: request.signal } : {},
  93. owner: request.owner,
  94. }
  95. }
  96. run(): Promise<BashRunResult> {
  97. return Promise.reject(new Error('not used'))
  98. }
  99. start(): BashTask {
  100. return this.task
  101. }
  102. get(id: BashTaskId): BashTask | undefined {
  103. return id === this.task.id ? this.task : undefined
  104. }
  105. ownerOf(): OwnerToken | undefined {
  106. return undefined
  107. }
  108. list(): BashTask[] {
  109. return [this.task]
  110. }
  111. readOutput(id: BashTaskId): BashTaskRead {
  112. if (id !== this.task.id) throw new Error(`unknown bash task "${id}"`)
  113. return { task: this.task, delta: 'tail', lossy: true }
  114. }
  115. kill(): boolean {
  116. return false
  117. }
  118. }
  119. describe('bash tool', () => {
  120. it('returns stdout for a successful command', async () => {
  121. const ctx = await setup()
  122. const result = await call(ctx, 'bash', { command: 'echo hello', description: 'test command' })
  123. expect(result.isError).toBe(false)
  124. expect(text(result)).toBe('hello\n')
  125. })
  126. it('reports (no output) for silent commands', async () => {
  127. const ctx = await setup()
  128. const result = await call(ctx, 'bash', { command: 'true', description: 'test command' })
  129. expect(text(result)).toBe('(no output)')
  130. })
  131. it('marks stderr sections', async () => {
  132. const ctx = await setup()
  133. const result = await call(ctx, 'bash', { command: 'echo out; echo err >&2', description: 'test command' })
  134. expect(text(result)).toBe('out\n[stderr]\nerr\n')
  135. expect(result.isError).toBe(false)
  136. })
  137. it('reports non-zero exits without isError', async () => {
  138. const ctx = await setup()
  139. const result = await call(ctx, 'bash', { command: 'echo failing; exit 3', description: 'test command' })
  140. expect(result.isError).toBe(false)
  141. expect(text(result)).toBe('failing\n[exit code: 3]')
  142. })
  143. it('reports timeout kills with both markers (timeout first)', async () => {
  144. const ctx = await setup()
  145. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', timeoutMs: 100 })
  146. expect(result.isError).toBe(false)
  147. expect(text(result)).toBe('(no output)\n[timed out after 100ms]\n[killed by signal: SIGTERM]')
  148. })
  149. it('reports a timeout even when the command traps the signal and exits 0', async () => {
  150. // The signal-independent timeout marker: a trapped SIGTERM that exits 0
  151. // after our timer fired must NOT look like a clean success. (bash may
  152. // print "Terminated" to stderr for the killed sleep — environment
  153. // dependent — so assert the marker, not the exact body.)
  154. const ctx = await setup()
  155. const result = await call(ctx, 'bash', { command: 'trap "exit 0" TERM; sleep 60', description: 'test command', timeoutMs: 100 })
  156. expect(result.isError).toBe(false)
  157. expect(text(result)).toContain('[timed out after 100ms]')
  158. expect(text(result)).not.toContain('[exit code:')
  159. })
  160. it('reports truncation with the spill path', async () => {
  161. const ctx = new Context()
  162. await ctx.plugin(SystemPrompt)
  163. await ctx.plugin(ToolRegistry)
  164. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 })
  165. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  166. await ctx.plugin(ToolBash)
  167. const result = await call(ctx, 'bash', { command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done', description: 'test command' })
  168. expect(text(result)).toContain('[output truncated; full output: ')
  169. expect(text(result)).toContain('line-0100')
  170. })
  171. it('honors workdir', async () => {
  172. const ctx = await setup()
  173. const result = await call(ctx, 'bash', { command: 'pwd', description: 'test command', workdir: '/tmp' })
  174. expect(text(result).trim()).toMatch(/\/tmp$/)
  175. })
  176. it('surfaces spawn failures as isError', async () => {
  177. const ctx = await setup()
  178. const result = await call(ctx, 'bash', { command: 'true', description: 'test command', workdir: '/nonexistent-dsh' })
  179. expect(result.isError).toBe(true)
  180. expect(text(result)).toMatch(/ENOENT/)
  181. })
  182. it('surfaces aborts as isError', async () => {
  183. const ctx = await setup()
  184. const controller = new AbortController()
  185. const pending = ctx.tools.execute({
  186. callId: CallId('call-abort'),
  187. name: 'bash',
  188. arguments: { command: 'sleep 60', description: 'test command' },
  189. signal: controller.signal,
  190. })
  191. setTimeout(() => { controller.abort() }, 50)
  192. const result = await pending
  193. expect(result.isError).toBe(true)
  194. expect(text(result)).toMatch(/aborted/)
  195. })
  196. // Type and required-key violations are now rejected by the harness
  197. // (defineTool validates against the SchemaSpec — the arg-validation RFC) before execute.
  198. it.each([
  199. [{}, /missing required property "command"/],
  200. [{ command: 42, description: 'd' }, /"command" must be a string/],
  201. [{ command: 'x' }, /missing required property "description"/],
  202. [{ command: 'x', description: 7 }, /"description" must be a string/],
  203. [{ command: 'x', description: 'd', timeoutMs: 'soon' }, /"timeoutMs" must be a number/],
  204. [{ command: 'x', description: 'd', workdir: 7 }, /"workdir" must be a string/],
  205. [{ command: 'x', description: 'd', run_in_background: 'yes' }, /"run_in_background" must be a boolean/],
  206. ])('rejects schema-invalid args %j', async (args, pattern) => {
  207. const ctx = await setup()
  208. const result = await call(ctx, 'bash', args)
  209. expect(result.isError).toBe(true)
  210. expect(text(result)).toMatch(pattern)
  211. })
  212. // Value constraints the SchemaSpec can't express stay in the tool body.
  213. it.each([
  214. [{ command: ' ', description: 'd' }, /invalid command/],
  215. [{ command: 'x', description: ' ' }, /invalid description/],
  216. [{ command: 'x', description: 'd', timeoutMs: -1 }, /invalid timeoutMs/],
  217. ])('rejects value-invalid args %j', async (args, pattern) => {
  218. const ctx = await setup()
  219. const result = await call(ctx, 'bash', args)
  220. expect(result.isError).toBe(true)
  221. expect(text(result)).toMatch(pattern)
  222. })
  223. it('rejects a non-JSON numeric argument before tool-specific validation', async () => {
  224. const ctx = await setup()
  225. const result = await call(ctx, 'bash', {
  226. command: 'x', description: 'd', timeoutMs: Number.NaN,
  227. })
  228. expect(result.isError).toBe(true)
  229. expect(text(result)).toContain('tool execution arguments must be losslessly JSON-serializable')
  230. })
  231. it('registers all three schemas in the system prompt assembly', async () => {
  232. const ctx = await setup()
  233. const names = ctx.tools.schemas().map(schema => schema.name)
  234. expect(names).toEqual(['bash', 'bash_output', 'bash_kill'])
  235. const bashSchema = ctx.tools.schemas()[0]!
  236. expect(bashSchema.parameters).toMatchObject({
  237. type: 'object',
  238. required: ['command', 'description'],
  239. })
  240. })
  241. it('contributes the exit-code habit as its prompt section (guidance the descriptions cannot carry)', async () => {
  242. const ctx = await setup()
  243. const assembly = await ctx.systemPrompt.assemble()
  244. const section = assembly.sections.find(s => s.name === 'tool:bash')
  245. expect(section?.order).toBe(105)
  246. expect(section?.text).toContain('[exit code: N]')
  247. })
  248. it('unregisters everything when the plugin fiber is disposed (HMR safety)', async () => {
  249. const ctx = new Context()
  250. await ctx.plugin(SystemPrompt)
  251. await ctx.plugin(ToolRegistry)
  252. await ctx.plugin(LocalBashExecutor, {})
  253. const fiber = await ctx.plugin(ToolBash)
  254. expect(ctx.tools.schemas()).toHaveLength(3)
  255. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona', 'tool:bash'])
  256. await fiber.dispose()
  257. expect(ctx.tools.schemas()).toHaveLength(0)
  258. // Only the system-prompt plugin's own built-in sections remain.
  259. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona'])
  260. })
  261. it('tools depend on the executor: no registration without ctx.bash', async () => {
  262. const ctx = new Context()
  263. await ctx.plugin(SystemPrompt)
  264. await ctx.plugin(ToolRegistry)
  265. // inject: ['tools', 'bash'] keeps the plugin pending until bash exists.
  266. await ctx.plugin(ToolBash)
  267. expect(ctx.tools.schemas()).toHaveLength(0)
  268. await ctx.plugin(LocalBashExecutor, {})
  269. await new Promise(resolve => setTimeout(resolve, 0))
  270. expect(ctx.tools.schemas()).toHaveLength(3)
  271. })
  272. })
  273. describe('background tools', () => {
  274. it('bash with run_in_background returns a task id immediately', async () => {
  275. const ctx = await setup()
  276. const result = await call(ctx, 'bash', { command: 'sleep 0.2; echo bg-done', description: 'test command', run_in_background: true })
  277. expect(result.isError).toBe(false)
  278. expect(text(result)).toMatch(/^started background task bash-\d+$/)
  279. })
  280. it('bash_output polls incrementally and reports status', async () => {
  281. const ctx = await setup()
  282. const started = await call(ctx, 'bash', { command: 'echo first; sleep 1; echo second', description: 'test command', run_in_background: true })
  283. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  284. const first = await callUntilText(ctx, 'bash_output', { task_id: id }, 'first')
  285. expect(text(first)).toContain('first')
  286. expect(text(first)).toContain('[status: running]')
  287. await ctx.bash.get(id)!.done
  288. const second = await call(ctx, 'bash_output', { task_id: id })
  289. expect(text(second)).toContain('second')
  290. expect(text(second)).not.toContain('first')
  291. expect(text(second)).toContain('[status: completed, exit code: 0]')
  292. const third = await call(ctx, 'bash_output', { task_id: id })
  293. expect(text(third)).toContain('(no new output)')
  294. })
  295. it('bash_output flags lossy reads with spill paths', async () => {
  296. const ctx = new Context()
  297. await ctx.plugin(SystemPrompt)
  298. await ctx.plugin(ToolRegistry)
  299. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 })
  300. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  301. await ctx.plugin(ToolBash)
  302. const started = await call(ctx, 'bash', { command: 'for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', description: 'test command', run_in_background: true })
  303. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  304. await ctx.bash.get(id)!.done
  305. const read = await call(ctx, 'bash_output', { task_id: id })
  306. expect(text(read)).toContain('[some output was dropped from memory; full output: ')
  307. })
  308. it('bash_output reports unavailable when a lossy read has no safe spill path', async () => {
  309. const ctx = new Context()
  310. await ctx.plugin(SystemPrompt)
  311. await ctx.plugin(ToolRegistry)
  312. await ctx.plugin(LossyReadBashExecutor)
  313. await ctx.plugin(ToolBash)
  314. const read = await call(ctx, 'bash_output', { task_id: 'bash-lossy' })
  315. expect(text(read)).toBe('tail\n[some output was dropped from memory; full output: (unavailable)]\n[status: running]')
  316. })
  317. it('bash_kill stops a running task; repeat reports already-finished', async () => {
  318. const ctx = await setup()
  319. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  320. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  321. const killed = await call(ctx, 'bash_kill', { task_id: id })
  322. expect(text(killed)).toBe(`killed background task ${id}`)
  323. await ctx.bash.get(id)!.done
  324. const again = await call(ctx, 'bash_kill', { task_id: id })
  325. expect(text(again)).toBe(`task ${id} had already finished`)
  326. const status = await call(ctx, 'bash_output', { task_id: id })
  327. expect(text(status)).toContain('[status: killed by SIGTERM]')
  328. })
  329. it('unknown task ids are isError for both tools', async () => {
  330. const ctx = await setup()
  331. const read = await call(ctx, 'bash_output', { task_id: 'bash-999' })
  332. expect(read.isError).toBe(true)
  333. expect(text(read)).toMatch(/unknown bash task/)
  334. const kill = await call(ctx, 'bash_kill', { task_id: 'bash-999' })
  335. expect(kill.isError).toBe(true)
  336. })
  337. it.each([
  338. ['bash_output', {}, /missing required property "task_id"/],
  339. ['bash_output', { task_id: 9 }, /"task_id" must be a string/],
  340. ['bash_kill', { task_id: '' }, /invalid task_id/],
  341. ])('%s rejects invalid task_id %j', async (tool, args, pattern) => {
  342. const ctx = await setup()
  343. const result = await call(ctx, tool, args)
  344. expect(result.isError).toBe(true)
  345. expect(text(result)).toMatch(pattern)
  346. })
  347. it('injects a completion notice into the owning agent (found via the registry by session token)', async () => {
  348. const ctx = await setup()
  349. const inject = vi.fn()
  350. // The notice path looks the agent up in ctx.agents by its session token, so
  351. // the agent must be REGISTERED (not merely passed to execute). Mount a
  352. // registry and register a fake whose session.header.id IS the owner token.
  353. const agent = registerFakeAgent(ctx, 'bg', inject)
  354. const started = await ctx.tools.execute({
  355. callId: CallId('call-bg'),
  356. name: 'bash',
  357. arguments: { command: 'true', description: 'test command', run_in_background: true },
  358. agent,
  359. })
  360. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  361. await ctx.bash.get(id)!.done
  362. expect(inject).toHaveBeenCalledTimes(1)
  363. const [content, options] = inject.mock.calls[0] as [
  364. { type: string; text: string }[],
  365. { source: { kind: string; plugin: string } },
  366. ]
  367. expect(content[0]!.text).toContain(`background bash task ${id} finished`)
  368. expect(content[0]!.text).toContain('bash_output')
  369. expect(options.source).toEqual({ kind: 'plugin', plugin: 'tool-bash' })
  370. })
  371. it('swallows ONLY the disposed-agent inject error', async () => {
  372. const ctx = await setup()
  373. const agent = registerFakeAgent(ctx, 'bg', () => { throw new Error('agent "x" is disposed') })
  374. const started = await ctx.tools.execute({
  375. callId: CallId('call-bg2'),
  376. name: 'bash',
  377. arguments: { command: 'true', description: 'test command', run_in_background: true },
  378. agent,
  379. })
  380. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  381. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  382. })
  383. it('rethrows a non-disposed inject failure (not blindly swallowed)', async () => {
  384. const ctx = await setup()
  385. // A real bug in inject (not the benign disposed race) must surface — the
  386. // base-class notifier contains it (logs, does not reject task.done), but
  387. // the listener itself must have thrown rather than silently eaten it.
  388. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  389. try {
  390. const agent = registerFakeAgent(ctx, 'bg', () => { throw new Error('unexpected inject bug') })
  391. const started = await ctx.tools.execute({
  392. callId: CallId('call-bg3'),
  393. name: 'bash',
  394. arguments: { command: 'true', description: 'test command', run_in_background: true },
  395. agent,
  396. })
  397. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  398. await ctx.bash.get(id)!.done
  399. // notifyTaskDone caught and logged the rethrown error.
  400. expect(errorSpy).toHaveBeenCalled()
  401. const logged = errorSpy.mock.calls.flat().some(arg => arg instanceof Error && arg.message === 'unexpected inject bug')
  402. expect(logged).toBe(true)
  403. } finally {
  404. errorSpy.mockRestore()
  405. }
  406. })
  407. it('drops the notice cleanly when the owning agent is gone from the registry by completion', async () => {
  408. // A bash task (owned by the host-scoped bash-local fiber) can OUTLIVE its
  409. // per-session agent — e.g. the ACP session disconnects and its AgentHandle
  410. // disposes while the background task is still running. The owner token is
  411. // still on the task, but no live agent carries it anymore, so the registry
  412. // lookup finds nothing and the notice is dropped (no throw).
  413. const ctx = await setup()
  414. const inject = vi.fn()
  415. const agent = registerFakeAgent(ctx, 'bg', inject)
  416. const started = await ctx.tools.execute({
  417. callId: CallId('call-bg4'),
  418. name: 'bash',
  419. arguments: { command: 'true', description: 'test command', run_in_background: true },
  420. agent,
  421. })
  422. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  423. // Unregister the agent BEFORE the task completes (simulate disconnect).
  424. unregisterFakeAgents(ctx)
  425. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  426. expect(inject).not.toHaveBeenCalled()
  427. })
  428. it('does not notify when no agent owned the task', async () => {
  429. const ctx = await setup()
  430. const started = await call(ctx, 'bash', { command: 'true', description: 'test command', run_in_background: true })
  431. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  432. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  433. })
  434. })
  435. describe('background task ownership (cross-session isolation)', () => {
  436. /** Run a tool on behalf of a specific agent (sets exec.agent). */
  437. function callAs(ctx: Context, agent: import('@deepseek-ai/dsh-agent').Agent | undefined, name: string, args: unknown) {
  438. return ctx.tools.execute({ callId: CallId(`own-${++callCounter}`), name, arguments: args, ...agent ? { agent } : {} })
  439. }
  440. // Ownership is by TOKEN (session.header.id), NOT agent object identity — so
  441. // each agent needs a DISTINCT session id, else every fake yields the same
  442. // token and the isolation tests pass for the wrong reason (all tasks owned by
  443. // the same token). The impl reads `session.header.id`, so the fakes MUST carry
  444. // it.
  445. const fakeAgent = (sessionId: string) =>
  446. ({ inject: () => undefined, session: { header: { version: 0, id: sessionId, createdAt: 0 } } }) as unknown as import('@deepseek-ai/dsh-agent').Agent
  447. it('rejects bash_output/bash_kill for a task owned by a DIFFERENT session token', async () => {
  448. const ctx = await setup()
  449. const a = fakeAgent('sess-a')
  450. const b = fakeAgent('sess-b')
  451. // Agent A starts a long-running background task.
  452. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  453. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  454. // Agent B (a different session token) cannot read or kill A's task.
  455. const readByB = await callAs(ctx, b, 'bash_output', { task_id: id })
  456. expect(readByB.isError).toBe(true)
  457. expect(text(readByB)).toMatch(/belongs to another session/)
  458. const killByB = await callAs(ctx, b, 'bash_kill', { task_id: id })
  459. expect(killByB.isError).toBe(true)
  460. expect(text(killByB)).toMatch(/belongs to another session/)
  461. // The task is still running (B's kill did nothing) — A can still kill it.
  462. const killByA = await callAs(ctx, a, 'bash_kill', { task_id: id })
  463. expect(killByA.isError).toBe(false)
  464. expect(text(killByA)).toBe(`killed background task ${id}`)
  465. })
  466. it('a DIFFERENT Agent object with the SAME session token may access the task (ownership is by token, not object identity)', async () => {
  467. // Ownership fences by session.header.id, NOT Agent object identity. Two
  468. // distinct Agent objects sharing one session token (e.g. an agent re-created
  469. // on the same session) are the SAME owner.
  470. const ctx = await setup()
  471. const a1 = fakeAgent('sess-shared')
  472. const a2 = fakeAgent('sess-shared') // distinct object, same token
  473. const started = await callAs(ctx, a1, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  474. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  475. const readByA2 = await callAs(ctx, a2, 'bash_output', { task_id: id })
  476. expect(readByA2.isError).toBe(false)
  477. await callAs(ctx, a1, 'bash_kill', { task_id: id }) // cleanup
  478. })
  479. it('the no-agent (non-loop) caller cannot access an owned task', async () => {
  480. const ctx = await setup()
  481. const a = fakeAgent('sess-a')
  482. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  483. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  484. // A call with no exec.agent has no token → cannot prove ownership of an owned task.
  485. const read = await callAs(ctx, undefined, 'bash_output', { task_id: id })
  486. expect(read.isError).toBe(true)
  487. expect(text(read)).toMatch(/belongs to another session/)
  488. await callAs(ctx, a, 'bash_kill', { task_id: id }) // cleanup
  489. })
  490. it('an UNOWNED task (started with no agent) is accessible to anyone', async () => {
  491. const ctx = await setup()
  492. // Started by a non-loop caller (no exec.agent) → no owner token recorded.
  493. const started = await callAs(ctx, undefined, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  494. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  495. // Any agent (and the no-agent caller) may read/kill it.
  496. const read = await callAs(ctx, fakeAgent('sess-x'), 'bash_output', { task_id: id })
  497. expect(read.isError).toBe(false)
  498. const killed = await callAs(ctx, undefined, 'bash_kill', { task_id: id })
  499. expect(killed.isError).toBe(false)
  500. })
  501. it('the owner can still access its task AFTER it completes (owner token persists on the task)', async () => {
  502. const ctx = await setup()
  503. const a = fakeAgent('sess-a')
  504. const b = fakeAgent('sess-b')
  505. const started = await callAs(ctx, a, 'bash', { command: 'echo done', description: 'bg', run_in_background: true })
  506. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  507. await ctx.bash.get(id)!.done
  508. // Completion does NOT clear ownership: B is still rejected, A still allowed.
  509. const readByB = await callAs(ctx, b, 'bash_output', { task_id: id })
  510. expect(readByB.isError).toBe(true)
  511. expect(text(readByB)).toMatch(/belongs to another session/)
  512. const readByA = await callAs(ctx, a, 'bash_output', { task_id: id })
  513. expect(readByA.isError).toBe(false)
  514. })
  515. it('ownership SURVIVES an independent tool-bash HMR reload (token lives on the executor)', async () => {
  516. // The owner token lives on the TASK inside the executor (dsh-bash fiber), NOT
  517. // in a tool-bash plugin-local map. So reloading ONLY tool-bash (executor +
  518. // task survive) preserves ownership. This is the regression guard: a
  519. // plugin-local map would make B accessible after reload, and this test would
  520. // catch it.
  521. const ctx = new Context()
  522. await ctx.plugin(SystemPrompt)
  523. await ctx.plugin(ToolRegistry)
  524. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  525. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  526. const fiber = await ctx.plugin(ToolBash)
  527. const a = fakeAgent('sess-a')
  528. const b = fakeAgent('sess-b')
  529. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  530. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  531. // Before reload: B is rejected (A owns it).
  532. expect((await callAs(ctx, b, 'bash_output', { task_id: id })).isError).toBe(true)
  533. // Reload ONLY tool-bash; the executor and its running task (with its owner
  534. // token) survive.
  535. await fiber.dispose()
  536. await ctx.plugin(ToolBash)
  537. expect(ctx.bash.get(id)?.status).toBe('running')
  538. expect(ctx.bash.ownerOf(id)).toBe('sess-a')
  539. // After reload, ownership is INTACT → B is STILL rejected.
  540. expect((await callAs(ctx, b, 'bash_output', { task_id: id })).isError).toBe(true)
  541. await callAs(ctx, a, 'bash_kill', { task_id: id }) // cleanup
  542. })
  543. })
  544. describe('session-cwd routing (per-session workdir)', () => {
  545. function callAs(ctx: Context, agent: import('@deepseek-ai/dsh-agent').Agent | undefined, args: unknown) {
  546. return ctx.tools.execute({ callId: CallId(`cwd-${++callCounter}`), name: 'bash', arguments: args, ...agent ? { agent } : {} })
  547. }
  548. // An agent whose session header carries a cwd (what session/new records).
  549. const agentInCwd = (cwd: string) =>
  550. ({ inject: () => undefined, session: { header: { version: 0, id: 'c', createdAt: 0, cwd } } }) as unknown as import('@deepseek-ai/dsh-agent').Agent
  551. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  552. const ctx = await setup()
  553. const result = await callAs(ctx, agentInCwd('/tmp'), { command: 'pwd', description: 'pwd' })
  554. expect(text(result).trim()).toMatch(/\/tmp$/)
  555. })
  556. it('an explicit absolute workdir overrides the session cwd', async () => {
  557. const ctx = await setup()
  558. const result = await callAs(ctx, agentInCwd('/'), { command: 'pwd', description: 'pwd', workdir: '/tmp' })
  559. expect(text(result).trim()).toMatch(/\/tmp$/)
  560. })
  561. it('a relative workdir is resolved against the session cwd', async () => {
  562. const ctx = await setup()
  563. // session cwd /usr + relative 'bin' → /usr/bin
  564. const result = await callAs(ctx, agentInCwd('/usr'), { command: 'pwd', description: 'pwd', workdir: 'bin' })
  565. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  566. })
  567. it('two sessions with different cwds each run bash in their own dir', async () => {
  568. const ctx = await setup()
  569. const inUsr = await callAs(ctx, agentInCwd('/usr'), { command: 'pwd', description: 'pwd' })
  570. const inTmp = await callAs(ctx, agentInCwd('/tmp'), { command: 'pwd', description: 'pwd' })
  571. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  572. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  573. })
  574. it('falls back to the executor default when the agent has no session cwd', async () => {
  575. const ctx = await setup()
  576. // No exec.agent at all → executor uses its config/process.cwd() default.
  577. const result = await ctx.tools.execute({ callId: CallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  578. expect(result.isError).toBe(false)
  579. expect(text(result).trim().length).toBeGreaterThan(0)
  580. })
  581. })
  582. describe('renderResult', () => {
  583. const base = {
  584. exitCode: 0 as number | null,
  585. signal: null as NodeJS.Signals | null,
  586. timedOut: false,
  587. aborted: false,
  588. timeoutMs: 1000,
  589. stdout: { text: '', truncated: false },
  590. stderr: { text: '', truncated: false },
  591. }
  592. it('renders stderr-only output without a stdout prefix', () => {
  593. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  594. .toBe('[stderr]\nerr\n')
  595. })
  596. it('adds a separator when stdout does not end with a newline', () => {
  597. expect(renderResult({
  598. ...base,
  599. stdout: { text: 'out', truncated: false },
  600. stderr: { text: 'err', truncated: false },
  601. })).toBe('out\n[stderr]\nerr')
  602. })
  603. it('appends exit-code markers after a newline for unterminated output', () => {
  604. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  605. .toBe('x\n[exit code: 7]')
  606. })
  607. it('renders signal kills without the timeout marker when not timed out', () => {
  608. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  609. .toBe('(no output)\n[killed by signal: SIGKILL]')
  610. })
  611. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  612. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  613. .toBe('(no output)\n[timed out after 1000ms]')
  614. })
  615. it('orders the timeout marker before a kill marker', () => {
  616. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  617. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  618. })
  619. it('notes truncation with a fallback when the spill path is missing', () => {
  620. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  621. .toBe('tail\n[output truncated; full output: (unavailable)]')
  622. })
  623. })
  624. describe('status lines', () => {
  625. it('reports kills without a recorded signal (executor raced process exit)', async () => {
  626. const ctx = await setup()
  627. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  628. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  629. const task = ctx.bash.get(id)!
  630. await call(ctx, 'bash_kill', { task_id: id })
  631. await task.done
  632. // Simulate the variant where the close event carried no signal.
  633. task.signal = null
  634. const read = await call(ctx, 'bash_output', { task_id: id })
  635. expect(text(read)).toContain('[status: killed]')
  636. })
  637. it('reports completed tasks with a null exit code as exit 0', async () => {
  638. const ctx = await setup()
  639. const started = await call(ctx, 'bash', { command: 'true', description: 'test command', run_in_background: true })
  640. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  641. const task = ctx.bash.get(id)!
  642. await task.done
  643. // Defensive: completed tasks always carry an exit code in practice; the
  644. // ?? 0 fallback covers task shapes from other executor implementations.
  645. task.exitCode = null
  646. const read = await call(ctx, 'bash_output', { task_id: id })
  647. expect(text(read)).toContain('[status: completed, exit code: 0]')
  648. })
  649. })
  650. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  651. it('bash presentCall: a foreground run is a terminal card (command title, description, workdir → cwd absolute or relative)', async () => {
  652. const ctx = await setup()
  653. // No explicit workdir → a terminal card with no cwd (the UI bridge fills the
  654. // session cwd it owns; the pure presenter can't see it).
  655. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  656. .toEqual({ card: 'terminal', title: 'ls -la src', description: 'List files in src' })
  657. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  658. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  659. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: '/tmp/x' })
  660. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  661. // the session cwd, matching where execution runs) — not dropped.
  662. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  663. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: 'sub' })
  664. })
  665. it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => {
  666. const ctx = await setup()
  667. const present = ctx.tools.get('bash')!.presentResult!(
  668. { command: 'echo hi', description: 'echo' },
  669. { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false },
  670. )
  671. // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer
  672. // needs; the bridge derives the fenced fallback. exitCode is parsed back from
  673. // the [exit code: N] marker.
  674. expect(present).toEqual({ card: 'terminal', output: 'hi\n[exit code: 0]\n\n', exitCode: 0 })
  675. })
  676. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  677. const ctx = await setup()
  678. const args = { command: 'x', description: 'x' }
  679. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  680. expect(nonzero).toEqual({ card: 'terminal', output: 'oops\n[exit code: 3]', exitCode: 3 })
  681. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  682. expect(killed).toEqual({ card: 'terminal', output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' })
  683. })
  684. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  685. const ctx = await setup()
  686. const present = ctx.tools.get('bash')!
  687. // For each renderResult outcome, the rendered text fed back through
  688. // presentResult recovers the matching structured exit — the parse and the
  689. // marker emission co-evolve in one file, so this pins the pair.
  690. const base = {
  691. aborted: false,
  692. timeoutMs: 1000,
  693. stdout: { text: 'out', truncated: false },
  694. stderr: { text: '', truncated: false },
  695. }
  696. const cases = [
  697. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  698. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  699. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  700. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  701. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  702. ]
  703. for (const c of cases) {
  704. const rendered = renderResult(c.result)
  705. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  706. // Drop card + output; the remaining fields are the parsed exit.
  707. const { card: _c, output: _o, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string }
  708. expect(exit).toEqual(c.expect)
  709. }
  710. })
  711. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  712. const ctx = await setup()
  713. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  714. // A successful command can print text that looks like a marker. renderResult
  715. // for a clean exit 0 appends NOTHING (and no trailing newline), so the body's
  716. // own tail is `[exit code: 5]`. The parse requires a LEADING newline before
  717. // the marker (renderResult always inserts one before a REAL marker), so this
  718. // no-trailing-newline body is NOT mistaken for a failure → exitCode 0.
  719. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  720. expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 })
  721. // Same for a fake signal marker with no leading newline.
  722. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  723. expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 })
  724. })
  725. it('bash presentCall/presentResult: a run_in_background call is a generic card and its ack carries no exit pill', async () => {
  726. const ctx = await setup()
  727. // The background start returns a task-id ack, not a streamed run — a generic
  728. // execute card with the command as rawInput and the description as content.
  729. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  730. expect(call).toEqual({ card: 'generic', title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  731. // The ack result is a generic fenced-text card — no terminal output / exit pill.
  732. const result = ctx.tools.get('bash')!.presentResult!(
  733. { command: 'sleep 100', description: 'wait', run_in_background: true },
  734. { content: [{ type: 'text', text: 'started background task bash-1' }], isError: false },
  735. )
  736. expect(result).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\nstarted background task bash-1\n```' }] })
  737. })
  738. it('bash presentResult: an isError result is a generic card (no real process exit to report)', async () => {
  739. const ctx = await setup()
  740. // A spawn failure / abort has no process exit — the body is an error message,
  741. // not renderResult output, so a generic fenced card, no terminal output/exit.
  742. const out = ctx.tools.get('bash')!.presentResult!(
  743. { command: 'x', description: 'x' },
  744. { content: [{ type: 'text', text: 'command aborted' }], isError: true },
  745. )
  746. expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ncommand aborted\n```' }] })
  747. })
  748. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  749. const ctx = await setup()
  750. const present = ctx.tools.get('bash')!.presentResult!(
  751. { command: 'x', description: 'x' },
  752. { content: [{ type: 'reasoning', text: 'unexpected' }], isError: false },
  753. )
  754. expect(present).toBeUndefined()
  755. })
  756. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  757. const ctx = await setup()
  758. const args = { command: 'x', description: 'x' }
  759. // Empty content (no block) and multi-block content both fall through.
  760. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  761. expect(ctx.tools.get('bash')!.presentResult!(args, {
  762. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  763. isError: false,
  764. })).toBeUndefined()
  765. })
  766. it('bash_output / bash_kill presentCall: a readable task-scoped title, task id as rawInput', async () => {
  767. const ctx = await setup()
  768. expect(ctx.tools.get('bash_output')!.presentCall!({ task_id: 'bash-3' }))
  769. .toEqual({ card: 'generic', title: 'Read output from background task bash-3', kind: 'execute', rawInput: 'bash-3' })
  770. expect(ctx.tools.get('bash_kill')!.presentCall!({ task_id: 'bash-3' }))
  771. .toEqual({ card: 'generic', title: 'Kill background task bash-3', kind: 'execute', rawInput: 'bash-3' })
  772. })
  773. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  774. const ctx = await setup()
  775. // defineTool wraps presentCall to soft-validate against the schema and fall
  776. // back to undefined (a generic UI presentation) rather than throwing on the
  777. // display path — it may run on replay of arbitrary logged args. The
  778. // ToolDefinition.presentCall takes `unknown`, so a malformed shape needs no cast.
  779. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  780. })
  781. })
  782. describe('the model-facing bash tool builds its request from named args only (no {...args} forward)', () => {
  783. /**
  784. * Records every {@link BashExecRequest} the consumer hands to `resolve()`, so a
  785. * test can assert what the model-facing tool DID and DID NOT forward. The `bash`
  786. * tool does not expose `stdin`/`env` as parameters (bash syntax already gives a
  787. * model that power), so it must build its request from named args only and
  788. * never spread unknown tool-call keys into it. This guard's job is to catch a
  789. * future refactor that blindly forwards `...args` — which would silently thread
  790. * model input into the post-scrub `env` merge — NOT to defend a trust boundary
  791. * (the credential scrub in dsh-bash-local is the security control; see the
  792. * bash-stdin-env RFC). Foreground `run()` returns a canned result; `start()` is
  793. * unused here.
  794. */
  795. class RecordingBashExecutor extends BashExecutor {
  796. readonly requests: BashExecRequest[] = []
  797. resolve(request: BashExecRequest): BashExecSpec {
  798. this.requests.push(request)
  799. return {
  800. command: request.command,
  801. workdir: request.workdir ?? process.cwd(),
  802. timeoutMs: request.timeoutMs ?? 0,
  803. ...request.signal ? { signal: request.signal } : {},
  804. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  805. ...request.env !== undefined ? { env: request.env } : {},
  806. owner: request.owner,
  807. }
  808. }
  809. run(): Promise<BashRunResult> {
  810. return Promise.resolve({
  811. exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 0,
  812. stdout: { text: 'ok', truncated: false }, stderr: { text: '', truncated: false },
  813. })
  814. }
  815. start(): BashTask { throw new Error('unused') }
  816. get(): BashTask | undefined { return undefined }
  817. ownerOf(): OwnerToken | undefined { return undefined }
  818. list(): BashTask[] { return [] }
  819. readOutput(): BashTaskRead { throw new Error('unused') }
  820. kill(): boolean { return false }
  821. }
  822. async function setupRecording() {
  823. const ctx = new Context()
  824. await ctx.plugin(SystemPrompt)
  825. await ctx.plugin(ToolRegistry)
  826. await ctx.plugin(AgentRegistry)
  827. await ctx.plugin(RecordingBashExecutor)
  828. await ctx.plugin(ToolBash)
  829. return { ctx, bash: ctx.bash as RecordingBashExecutor }
  830. }
  831. it('does not forward env/stdin even when the model includes them as extra arguments', async () => {
  832. const { ctx, bash } = await setupRecording()
  833. // Extra args: the model includes `env` and `stdin` keys hoping they reach the
  834. // executor. The bash tool's schema ignores unknown keys, and execute() builds
  835. // the request from only command/workdir/timeoutMs/signal — so the recorded
  836. // request carries NEITHER. (Not a security wall — the model could set an env
  837. // var or feed stdin via shell syntax anyway; this just keeps the request
  838. // shape honest so a future `...args` spread can't silently forward input.)
  839. await ctx.tools.execute({
  840. callId: CallId('no-forward-1'),
  841. name: 'bash',
  842. arguments: {
  843. command: 'echo hi',
  844. description: 'echo',
  845. env: { SNEAKY_API_KEY: 'leak' },
  846. stdin: 'malicious payload',
  847. },
  848. })
  849. expect(bash.requests).toHaveLength(1)
  850. const request = bash.requests[0]!
  851. expect(request.command).toBe('echo hi')
  852. expect('env' in request).toBe(false)
  853. expect('stdin' in request).toBe(false)
  854. })
  855. it('a background bash call likewise carries no env/stdin', async () => {
  856. const { ctx, bash } = await setupRecording()
  857. // start() throws in this recorder, but resolve() runs first and records the
  858. // request — which is all this no-forward assertion needs.
  859. await ctx.tools.execute({
  860. callId: CallId('no-forward-2'),
  861. name: 'bash',
  862. arguments: {
  863. command: 'sleep 1',
  864. description: 'sleep',
  865. run_in_background: true,
  866. env: { TOKEN: 'leak' },
  867. stdin: 'x',
  868. },
  869. })
  870. expect(bash.requests).toHaveLength(1)
  871. const request = bash.requests[0]!
  872. expect('env' in request).toBe(false)
  873. expect('stdin' in request).toBe(false)
  874. // The owner token IS set on a background call (the isolation fence) — proving
  875. // the recorder sees the real request the consumer built, so the absent
  876. // env/stdin above is a real negative, not a recorder that drops everything.
  877. expect('owner' in request).toBe(true)
  878. })
  879. })