tools.spec.ts 46 KB

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