tools.spec.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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 } from '@deepseek-ai/dsh-bash'
  8. import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult } from '@deepseek-ai/dsh-bash'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry from '@deepseek-ai/dsh-agent'
  12. import type { Agent } from '@deepseek-ai/dsh-agent'
  13. import { SessionId } from '@deepseek-ai/dsh-session'
  14. import TaskService from '@deepseek-ai/dsh-tasks'
  15. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  16. import ApprovalService from '@deepseek-ai/dsh-user-approval'
  17. import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
  18. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  19. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  20. import { processOutcome } from '../src/background.ts'
  21. import { renderProcessRead, renderResult } from '../src/render.ts'
  22. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-tool-bash-spec-'))
  23. /** Foreground-only harness: no task runtime (backgrounding fails loud here). */
  24. async function setup() {
  25. const ctx = new Context()
  26. await ctx.plugin(SystemPrompt)
  27. await ctx.plugin(ToolRegistry)
  28. await ctx.plugin(AgentRegistry)
  29. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  30. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  31. await ctx.plugin(ToolBash)
  32. return ctx
  33. }
  34. /** Full harness: the generic task runtime + its control surface, then the bash tool. */
  35. async function setupWithTasks() {
  36. const ctx = new Context()
  37. await ctx.plugin(SystemPrompt)
  38. await ctx.plugin(ToolRegistry)
  39. await ctx.plugin(AgentRegistry)
  40. await ctx.plugin(TaskService)
  41. await ctx.plugin(ToolTasks)
  42. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  43. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  44. await ctx.plugin(ToolBash)
  45. return ctx
  46. }
  47. /**
  48. * Build a fake {@link Agent} with the shared agent/session identity, give it a
  49. * dedicated lifecycle fiber for `Agent.ctx`, and register it in `ctx.agents`.
  50. */
  51. function registerFakeAgent(ctx: Context, sessionId: string, inject: (...args: unknown[]) => void = () => {}): Agent {
  52. const scopeFiber = ctx.plugin(() => {})
  53. const id = SessionId(sessionId)
  54. const agent = {
  55. id,
  56. ctx: scopeFiber.ctx,
  57. inject,
  58. session: { id, header: { version: 0, id, createdAt: 0 } },
  59. } as unknown as Agent
  60. ctx.agents.register(agent)
  61. return agent
  62. }
  63. let callCounter = 0
  64. function call(ctx: Context, name: string, args: unknown, agent?: Agent) {
  65. return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args, ...agent ? { agent } : {} })
  66. }
  67. function text(result: { content: { type: string; text?: string }[] }): string {
  68. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  69. }
  70. async function callUntilText(
  71. ctx: Context,
  72. name: string,
  73. args: unknown,
  74. expected: string,
  75. timeoutMs = 5_000,
  76. ): Promise<Awaited<ReturnType<typeof call>>> {
  77. const deadline = Date.now() + timeoutMs
  78. let last: Awaited<ReturnType<typeof call>> | undefined
  79. while (Date.now() < deadline) {
  80. last = await call(ctx, name, args)
  81. if (text(last).includes(expected)) return last
  82. await new Promise(resolve => setTimeout(resolve, 20))
  83. }
  84. throw new Error(`${name} output did not include ${JSON.stringify(expected)}; last text was ${JSON.stringify(last !== undefined ? text(last) : '')}`)
  85. }
  86. class RecordingSandboxExecutor extends BashExecutor {
  87. readonly modes: Array<string | undefined> = []
  88. override get sandboxMode() {
  89. return 'read-only' as const
  90. }
  91. resolve(request: BashExecRequest): BashExecSpec {
  92. return {
  93. command: request.command,
  94. workdir: request.workdir ?? process.cwd(),
  95. timeoutMs: request.timeoutMs ?? 1000,
  96. ...request.signal ? { signal: request.signal } : {},
  97. sandboxMode: request.sandboxMode ?? 'read-only',
  98. }
  99. }
  100. run(spec: BashExecSpec): Promise<BashRunResult> {
  101. this.modes.push(spec.sandboxMode)
  102. return Promise.resolve({
  103. exitCode: 0,
  104. signal: null,
  105. timedOut: false,
  106. aborted: false,
  107. timeoutMs: spec.timeoutMs,
  108. stdout: { text: 'ok', truncated: false },
  109. stderr: { text: '', truncated: false },
  110. sandbox: { mode: spec.sandboxMode ?? 'read-only', denied: false },
  111. })
  112. }
  113. start(spec: BashExecSpec): BashProcess {
  114. this.modes.push(spec.sandboxMode)
  115. return {
  116. status: 'completed',
  117. exitCode: 0,
  118. signal: null,
  119. done: Promise.resolve(),
  120. sandbox: { mode: spec.sandboxMode ?? 'read-only', denied: false },
  121. readOutput: () => ({ delta: '', lossy: false }),
  122. kill: () => false,
  123. }
  124. }
  125. }
  126. /** Test executor that records whether the background start boundary was crossed. */
  127. class CountingStartExecutor extends BashExecutor {
  128. starts = 0
  129. resolve(request: BashExecRequest): BashExecSpec {
  130. return { command: request.command, workdir: request.workdir ?? '/x', timeoutMs: request.timeoutMs ?? 0, sandboxMode: request.sandboxMode }
  131. }
  132. run(): Promise<BashRunResult> { return Promise.reject(new Error('unused')) }
  133. start(): BashProcess {
  134. this.starts += 1
  135. return {
  136. status: 'completed',
  137. exitCode: 0,
  138. signal: null,
  139. done: Promise.resolve(),
  140. readOutput: () => ({ delta: '', lossy: false }),
  141. kill: () => false,
  142. }
  143. }
  144. }
  145. async function setupSandboxed(withApproval = false) {
  146. const ctx = new Context()
  147. await ctx.plugin(SystemPrompt)
  148. await ctx.plugin(ToolRegistry)
  149. await ctx.plugin(AgentRegistry)
  150. await ctx.plugin(TaskService)
  151. await ctx.plugin(ToolTasks)
  152. await ctx.plugin(RecordingSandboxExecutor)
  153. if (withApproval) await ctx.plugin(ApprovalService)
  154. await ctx.plugin(ToolBash)
  155. return { ctx, bash: ctx.bash as RecordingSandboxExecutor }
  156. }
  157. function sandboxAgent(mode?: 'read-only' | 'workspace-write' | 'danger-full-access', ctx?: Context): Agent {
  158. const events: Array<{ type: string; data?: Record<string, unknown> }> = [{ type: 'turn/start' }]
  159. if (mode !== undefined) events.push({ type: 'bash/sandbox-mode', data: { mode } })
  160. const id = SessionId('sandbox-session')
  161. return {
  162. id,
  163. ...ctx === undefined ? {} : { ctx: ctx.plugin(() => {}).ctx },
  164. session: {
  165. id,
  166. header: { version: 0, id, createdAt: 0 },
  167. events,
  168. append: (type: string, data: Record<string, unknown>) => {
  169. const event = { type, data }
  170. events.push(event)
  171. return event
  172. },
  173. },
  174. } as unknown as Agent
  175. }
  176. describe('bash tool', () => {
  177. it('returns stdout for a successful command', async () => {
  178. const ctx = await setup()
  179. const result = await call(ctx, 'bash', { command: 'echo hello', description: 'test command' })
  180. expect(result.isError).toBe(false)
  181. expect(text(result)).toBe('hello\n')
  182. })
  183. it('reports (no output) for silent commands', async () => {
  184. const ctx = await setup()
  185. const result = await call(ctx, 'bash', { command: 'true', description: 'test command' })
  186. expect(text(result)).toBe('(no output)')
  187. })
  188. it('marks stderr sections', async () => {
  189. const ctx = await setup()
  190. const result = await call(ctx, 'bash', { command: 'echo out; echo err >&2', description: 'test command' })
  191. expect(text(result)).toBe('out\n[stderr]\nerr\n')
  192. expect(result.isError).toBe(false)
  193. })
  194. it('reports non-zero exits without isError', async () => {
  195. const ctx = await setup()
  196. const result = await call(ctx, 'bash', { command: 'echo failing; exit 3', description: 'test command' })
  197. expect(result.isError).toBe(false)
  198. expect(text(result)).toBe('failing\n[exit code: 3]')
  199. })
  200. it('reports timeout kills with both markers (timeout first)', async () => {
  201. const ctx = await setup()
  202. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', timeoutMs: 100 })
  203. expect(result.isError).toBe(false)
  204. expect(text(result)).toBe('(no output)\n[timed out after 100ms]\n[killed by signal: SIGTERM]')
  205. })
  206. it('reports a timeout even when the command traps the signal and exits 0', async () => {
  207. // The signal-independent timeout marker: a trapped SIGTERM that exits 0
  208. // after our timer fired must NOT look like a clean success. (bash may
  209. // print "Terminated" to stderr for the killed sleep — environment
  210. // dependent — so assert the marker, not the exact body.)
  211. const ctx = await setup()
  212. const result = await call(ctx, 'bash', { command: 'trap "exit 0" TERM; sleep 60', description: 'test command', timeoutMs: 100 })
  213. expect(result.isError).toBe(false)
  214. expect(text(result)).toContain('[timed out after 100ms]')
  215. expect(text(result)).not.toContain('[exit code:')
  216. })
  217. it('reports truncation with the spill path', async () => {
  218. const ctx = new Context()
  219. await ctx.plugin(SystemPrompt)
  220. await ctx.plugin(ToolRegistry)
  221. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 })
  222. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  223. await ctx.plugin(ToolBash)
  224. const result = await call(ctx, 'bash', { command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done', description: 'test command' })
  225. expect(text(result)).toContain('[output truncated; full output: ')
  226. expect(text(result)).toContain('line-0100')
  227. })
  228. it('honors workdir', async () => {
  229. const ctx = await setup()
  230. const result = await call(ctx, 'bash', { command: 'pwd', description: 'test command', workdir: '/tmp' })
  231. expect(text(result).trim()).toMatch(/\/tmp$/)
  232. })
  233. it('surfaces spawn failures as isError', async () => {
  234. const ctx = await setup()
  235. const result = await call(ctx, 'bash', { command: 'true', description: 'test command', workdir: '/nonexistent-dsh' })
  236. expect(result.isError).toBe(true)
  237. expect(text(result)).toMatch(/ENOENT/)
  238. })
  239. it('surfaces foreground aborts as isError', async () => {
  240. const ctx = await setup()
  241. const controller = new AbortController()
  242. const pending = ctx.tools.execute({
  243. callId: CallId('call-abort'),
  244. name: 'bash',
  245. arguments: { command: 'sleep 60', description: 'test command' },
  246. signal: controller.signal,
  247. })
  248. setTimeout(() => { controller.abort() }, 50)
  249. const result = await pending
  250. expect(result.isError).toBe(true)
  251. expect(text(result)).toMatch(/aborted/)
  252. })
  253. // Type and required-key violations are rejected by the harness
  254. // (defineTool validates against the SchemaSpec — the arg-validation RFC) before execute.
  255. it.each([
  256. [{}, /missing required property "command"/],
  257. [{ command: 42, description: 'd' }, /"command" must be a string/],
  258. [{ command: 'x' }, /missing required property "description"/],
  259. [{ command: 'x', description: 7 }, /"description" must be a string/],
  260. [{ command: 'x', description: 'd', timeoutMs: 'soon' }, /"timeoutMs" must be a number/],
  261. [{ command: 'x', description: 'd', workdir: 7 }, /"workdir" must be a string/],
  262. [{ command: 'x', description: 'd', run_in_background: 'yes' }, /"run_in_background" must be a boolean/],
  263. ])('rejects schema-invalid args %j', async (args, pattern) => {
  264. const ctx = await setup()
  265. const result = await call(ctx, 'bash', args)
  266. expect(result.isError).toBe(true)
  267. expect(text(result)).toMatch(pattern)
  268. })
  269. // Value constraints the SchemaSpec can't express stay in the tool body.
  270. it.each([
  271. [{ command: ' ', description: 'd' }, /invalid command/],
  272. [{ command: 'x', description: ' ' }, /invalid description/],
  273. [{ command: 'x', description: 'd', timeoutMs: -1 }, /invalid timeoutMs/],
  274. ])('rejects value-invalid args %j', async (args, pattern) => {
  275. const ctx = await setup()
  276. const result = await call(ctx, 'bash', args)
  277. expect(result.isError).toBe(true)
  278. expect(text(result)).toMatch(pattern)
  279. })
  280. it('rejects a non-JSON numeric argument before tool-specific validation', async () => {
  281. const ctx = await setup()
  282. const result = await call(ctx, 'bash', {
  283. command: 'x', description: 'd', timeoutMs: Number.NaN,
  284. })
  285. expect(result.isError).toBe(true)
  286. expect(text(result)).toContain('tool execution arguments must be losslessly JSON-serializable')
  287. })
  288. it('registers the bash schema with run_in_background exposed by default', async () => {
  289. const ctx = await setup()
  290. const schemas = ctx.tools.schemas()
  291. expect(schemas.map(schema => schema.name)).toEqual(['bash'])
  292. const bashSchema = schemas[0]!
  293. expect(bashSchema.parameters).toMatchObject({
  294. type: 'object',
  295. required: ['command', 'description'],
  296. })
  297. expect(Object.keys(bashSchema.parameters.properties as Record<string, unknown>))
  298. .toContain('run_in_background')
  299. expect(bashSchema.description).toContain('task_output')
  300. })
  301. it('contributes the exit-code habit as its prompt section (guidance the descriptions cannot carry)', async () => {
  302. const ctx = await setup()
  303. ctx.systemPrompt.section({ name: 'test:before-bash', order: 104, text: 'before' })
  304. ctx.systemPrompt.section({ name: 'test:after-bash', order: 106, text: 'after' })
  305. const assembly = await ctx.systemPrompt.assemble()
  306. const section = assembly.sections.find(s => s.name === 'tool:bash')
  307. expect(assembly.sections.map(s => s.name)).toEqual([
  308. 'harness:identity',
  309. 'deployment:persona',
  310. 'test:before-bash',
  311. 'tool:bash',
  312. 'test:after-bash',
  313. ])
  314. expect(section?.text).toContain('[exit code: N]')
  315. })
  316. it('unregisters everything when the plugin fiber is disposed (HMR safety)', async () => {
  317. const ctx = new Context()
  318. await ctx.plugin(SystemPrompt)
  319. await ctx.plugin(ToolRegistry)
  320. await ctx.plugin(LocalBashExecutor, {})
  321. const fiber = await ctx.plugin(ToolBash)
  322. expect(ctx.tools.schemas()).toHaveLength(1)
  323. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona', 'tool:bash'])
  324. await fiber.dispose()
  325. expect(ctx.tools.schemas()).toHaveLength(0)
  326. // Only the system-prompt plugin's own built-in sections remain.
  327. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona'])
  328. })
  329. it('tools depend on the executor: no registration without ctx.bash', async () => {
  330. const ctx = new Context()
  331. await ctx.plugin(SystemPrompt)
  332. await ctx.plugin(ToolRegistry)
  333. // inject: ['tools', 'bash'] keeps the plugin pending until bash exists.
  334. await ctx.plugin(ToolBash)
  335. expect(ctx.tools.schemas()).toHaveLength(0)
  336. await ctx.plugin(LocalBashExecutor, {})
  337. await new Promise(resolve => setTimeout(resolve, 0))
  338. expect(ctx.tools.schemas()).toHaveLength(1)
  339. })
  340. it('applies the built-in background default when apply() receives a bare config', async () => {
  341. // Bypasses the schemastery defaults on purpose: apply() must stand on its
  342. // own `?? true` fallback when embedded programmatically without the schema.
  343. const ctx = new Context()
  344. await ctx.plugin(SystemPrompt)
  345. await ctx.plugin(ToolRegistry)
  346. await ctx.plugin(LocalBashExecutor, {})
  347. ToolBash.apply(ctx, {})
  348. const schema = ctx.tools.schemas()[0]!
  349. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  350. .toContain('run_in_background')
  351. })
  352. })
  353. describe('background execution through the task runtime', () => {
  354. it('run_in_background acks with the task id, readable through the REAL task_output tool', async () => {
  355. const ctx = await setupWithTasks()
  356. const started = await call(ctx, 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true })
  357. expect(started.isError).toBe(false)
  358. expect(text(started)).toBe('started background task bash-1')
  359. const read = await callUntilText(ctx, 'task_output', { task_id: 'bash-1' }, 'bg-ok')
  360. expect(text(read)).toContain('bg-ok')
  361. // A later read reports the terminal outcome in the generic status line.
  362. const final = await callUntilText(ctx, 'task_output', { task_id: 'bash-1' }, '[status: completed, exit code: 0]')
  363. expect(final.isError).toBe(false)
  364. })
  365. it('a running background task is killable through the REAL task_kill tool', async () => {
  366. const ctx = await setupWithTasks()
  367. await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  368. const killed = await call(ctx, 'task_kill', { task_id: 'bash-1' })
  369. expect(text(killed)).toBe('requested cancellation of task bash-1')
  370. // The cancel reached the process handle; the task settles as killed with
  371. // the signal detail mapped by processOutcome.
  372. const final = await call(ctx, 'task_output', { task_id: 'bash-1', wait: true })
  373. expect(text(final)).toContain('[status: killed, signal: SIGTERM]')
  374. })
  375. it('a self-signal background exit is reported as killed through the REAL task_output tool', async () => {
  376. const ctx = await setupWithTasks()
  377. await call(ctx, 'bash', { command: 'kill -TERM $$', description: 'test command', run_in_background: true })
  378. const final = await call(ctx, 'task_output', { task_id: 'bash-1', wait: true })
  379. expect(text(final)).toContain('[status: killed, signal: SIGTERM]')
  380. })
  381. it('a background task started by an agent is registered with that agent as owner', async () => {
  382. // The producer must forward exec.agent as the task owner.
  383. const ctx = await setupWithTasks()
  384. const agent = registerFakeAgent(ctx, 'sess-owner')
  385. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true }, agent)
  386. expect(text(started)).toBe('started background task bash-1')
  387. const anon = await call(ctx, 'task_output', { task_id: 'bash-1' })
  388. expect(anon.isError).toBe(true)
  389. expect(text(anon)).toMatch(/belongs to another session/)
  390. const killed = await call(ctx, 'task_kill', { task_id: 'bash-1' }, agent)
  391. expect(killed.isError).toBe(false)
  392. await call(ctx, 'task_output', { task_id: 'bash-1', wait: true }, agent) // await settlement — no orphan
  393. })
  394. it('fails loud when the task runtime is not loaded', async () => {
  395. const ctx = await setup() // no TaskService / ToolTasks
  396. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  397. expect(result.isError).toBe(true)
  398. expect(text(result)).toContain('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
  399. })
  400. it('a pre-aborted call refuses to start: isError, no process spawned', async () => {
  401. const ctx = new Context()
  402. await ctx.plugin(SystemPrompt)
  403. await ctx.plugin(ToolRegistry)
  404. await ctx.plugin(AgentRegistry)
  405. await ctx.plugin(TaskService)
  406. await ctx.plugin(ToolTasks)
  407. await ctx.plugin(CountingStartExecutor)
  408. await ctx.plugin(ToolBash)
  409. const controller = new AbortController()
  410. controller.abort()
  411. const result = await ctx.tools.execute({
  412. callId: CallId('call-pre-aborted'),
  413. name: 'bash',
  414. arguments: { command: 'sleep 60', description: 'test command', run_in_background: true },
  415. signal: controller.signal,
  416. })
  417. expect(result.isError).toBe(true)
  418. expect(text(result)).toContain('command aborted')
  419. expect((ctx.bash as CountingStartExecutor).starts).toBe(0)
  420. })
  421. it('never spawns the process when tasks.start preflight throws (no orphan, by construction)', async () => {
  422. // With no control surface, task preflight fails before the executor can spawn.
  423. const ctx = new Context()
  424. await ctx.plugin(SystemPrompt)
  425. await ctx.plugin(ToolRegistry)
  426. await ctx.plugin(AgentRegistry)
  427. await ctx.plugin(TaskService)
  428. await ctx.plugin(CountingStartExecutor)
  429. await ctx.plugin(ToolBash)
  430. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  431. expect(result.isError).toBe(true)
  432. expect(text(result)).toContain('no control surface is attached')
  433. // Declare-then-execute: the failed preflight means no process ever ran.
  434. expect((ctx.bash as CountingStartExecutor).starts).toBe(0)
  435. })
  436. it('enableRunInBackground: false removes the parameter and flips the description', async () => {
  437. const ctx = new Context()
  438. await ctx.plugin(SystemPrompt)
  439. await ctx.plugin(ToolRegistry)
  440. await ctx.plugin(LocalBashExecutor, {})
  441. await ctx.plugin(ToolBash, { enableRunInBackground: false })
  442. const schema = ctx.tools.schemas().find(s => s.name === 'bash')!
  443. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  444. .toEqual(['command', 'description', 'timeoutMs', 'workdir'])
  445. expect(schema.description).toContain('Background execution is not available')
  446. expect(schema.description).not.toContain('run_in_background')
  447. // The registry-held definition agrees (schema and capability never disagree).
  448. const parameters = ctx.tools.get('bash')!.parameters as { properties: Record<string, unknown> }
  449. expect('run_in_background' in parameters.properties).toBe(false)
  450. // Schema omission is advertising; execution must also enforce the opt-out.
  451. const forced = await call(ctx, 'bash', { command: 'echo hi', description: 'test command', run_in_background: true })
  452. expect(forced.isError).toBe(true)
  453. expect(text(forced)).toContain('run_in_background is disabled for this deployment')
  454. const foreground = await call(ctx, 'bash', { command: 'echo hi', description: 'test command' })
  455. expect(foreground.isError).toBe(false)
  456. })
  457. })
  458. describe('sandbox escalation through the generic task producer', () => {
  459. const escalate = {
  460. command: 'true',
  461. description: 'test escalation',
  462. sandbox_permissions: 'workspace-write',
  463. justification: 'the command needs workspace writes',
  464. }
  465. it('advertises the sandbox fields and validates their pairing', async () => {
  466. const { ctx } = await setupSandboxed()
  467. const schema = ctx.tools.schemas().find(item => item.name === 'bash')!
  468. const properties = schema.parameters.properties as Record<string, { enum?: string[] }>
  469. expect(properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
  470. expect(schema.description).toContain('approval prompt')
  471. for (const args of [
  472. { command: 'true', description: 'd', sandbox_permissions: 'workspace-write' },
  473. { command: 'true', description: 'd', justification: 'why' },
  474. { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: ' ' },
  475. ]) {
  476. expect((await call(ctx, 'bash', args)).isError).toBe(true)
  477. }
  478. })
  479. it('rejects injected escalation without a sandbox and non-widening escalation without prompting', async () => {
  480. const plain = await setup()
  481. expect(text(await call(plain, 'bash', escalate))).toContain('not available in this composition')
  482. const { ctx } = await setupSandboxed(true)
  483. const prompted = vi.fn()
  484. ctx.on('approval/request', () => { prompted(); return Promise.resolve<ApprovalOutcome>('allowed-once') })
  485. const result = await call(ctx, 'bash', { ...escalate, sandbox_permissions: 'workspace-write' }, sandboxAgent('workspace-write'))
  486. expect(text(result)).toContain('not strictly wider')
  487. expect(prompted).not.toHaveBeenCalled()
  488. const malformed = sandboxAgent()
  489. ;(malformed.session.events as unknown as Array<{ type: string; data: { mode: string } }>).push({
  490. type: 'bash/sandbox-mode',
  491. data: { mode: 'unknown-mode' },
  492. })
  493. expect(text(await call(ctx, 'bash', escalate, malformed))).toContain('not strictly wider')
  494. })
  495. it('fails closed when approval cannot be routed', async () => {
  496. const withoutService = await setupSandboxed()
  497. expect(text(await call(withoutService.ctx, 'bash', escalate, sandboxAgent()))).toContain('no approval service')
  498. const withService = await setupSandboxed(true)
  499. expect(text(await call(withService.ctx, 'bash', escalate))).toContain('no agent to route')
  500. expect(text(await call(withService.ctx, 'bash', escalate, sandboxAgent()))).toContain('no approval channel')
  501. })
  502. it.each([
  503. ['rejected', 'user rejected'],
  504. ['cancelled', 'was cancelled'],
  505. ] as const)('maps an approval %s to its distinct failure', async (outcome, message) => {
  506. const { ctx, bash } = await setupSandboxed(true)
  507. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>(outcome))
  508. const result = await call(ctx, 'bash', escalate, sandboxAgent())
  509. expect(text(result)).toContain(message)
  510. expect(bash.modes).toEqual([])
  511. })
  512. it('runs a granted foreground or background call under the approved mode', async () => {
  513. const { ctx, bash } = await setupSandboxed(true)
  514. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  515. const agent = sandboxAgent(undefined, ctx)
  516. ctx.agents.register(agent)
  517. const foreground = await ctx.tools.execute({
  518. callId: CallId('sandbox-signal'),
  519. name: 'bash',
  520. arguments: escalate,
  521. agent,
  522. signal: new AbortController().signal,
  523. })
  524. expect(foreground.isError).toBe(false)
  525. const background = await call(ctx, 'bash', { ...escalate, run_in_background: true }, agent)
  526. expect(text(background)).toBe('started background task bash-1')
  527. expect(bash.modes).toEqual(['workspace-write', 'workspace-write'])
  528. })
  529. it('uses the session override for ordinary calls and evaluates widening against it', async () => {
  530. const { ctx, bash } = await setupSandboxed(true)
  531. const agent = sandboxAgent('workspace-write')
  532. await call(ctx, 'bash', { command: 'true', description: 'ordinary' }, agent)
  533. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  534. await call(ctx, 'bash', { ...escalate, sandbox_permissions: 'danger-full-access' }, agent)
  535. expect(bash.modes).toEqual(['workspace-write', 'danger-full-access'])
  536. })
  537. it('keeps the exhaustiveness backstop for a rogue approval implementation', async () => {
  538. const { ctx } = await setupSandboxed(true)
  539. ctx.approval.request = () => Promise.resolve('rogue' as ApprovalOutcome)
  540. const result = await call(ctx, 'bash', escalate, sandboxAgent())
  541. expect(text(result)).toContain('unreachable variant in ApprovalOutcome')
  542. })
  543. })
  544. describe('renderProcessRead', () => {
  545. const base: BashProcessRead = { delta: 'out\n', lossy: false }
  546. it('returns the delta verbatim for a lossless read', () => {
  547. expect(renderProcessRead(base)).toBe('out\n')
  548. expect(renderProcessRead({ delta: '', lossy: false })).toBe('')
  549. })
  550. it('appends the loss notice with the available spill paths', () => {
  551. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log' }))
  552. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log]')
  553. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log', stderrSpillPath: '/spill/err.log' }))
  554. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log, /spill/err.log]')
  555. })
  556. it('reports (unavailable) when a lossy read has no safe spill path', () => {
  557. expect(renderProcessRead({ ...base, lossy: true }))
  558. .toBe('out\n[some output was dropped from memory; full output: (unavailable)]')
  559. })
  560. it('an empty lossy delta is the notice alone', () => {
  561. expect(renderProcessRead({ delta: '', lossy: true, stderrSpillPath: '/spill/err.log' }))
  562. .toBe('[some output was dropped from memory; full output: /spill/err.log]')
  563. })
  564. it('inserts the separating newline only when the delta lacks one', () => {
  565. expect(renderProcessRead({ delta: 'tail', lossy: true }))
  566. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  567. expect(renderProcessRead({ delta: 'tail\n', lossy: true }))
  568. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  569. })
  570. it('appends settled sandbox denial and runner-failure facts', () => {
  571. expect(renderProcessRead(base, { mode: 'read-only', denied: true }, ['workspace-write']))
  572. .toContain('[sandbox: escalation available')
  573. expect(renderProcessRead({ delta: 'tail', lossy: false }, { mode: 'read-only', denied: true }))
  574. .toBe('tail\n[sandbox: file access denied under read-only mode]')
  575. const runner = renderProcessRead(
  576. { delta: '', lossy: false },
  577. { mode: 'workspace-write', denied: true, runnerFailed: true },
  578. ['danger-full-access'],
  579. )
  580. expect(runner).toContain('sandbox runner itself failed under workspace-write mode')
  581. expect(runner).not.toContain('file access denied')
  582. })
  583. })
  584. describe('processOutcome', () => {
  585. function settled(over: Partial<BashProcess>): BashProcess {
  586. return {
  587. status: 'completed',
  588. exitCode: 0,
  589. signal: null,
  590. done: Promise.resolve(),
  591. readOutput: () => ({ delta: '', lossy: false }),
  592. kill: () => false,
  593. ...over,
  594. }
  595. }
  596. it('maps a signal-killed process to killed with the signal detail', () => {
  597. expect(processOutcome(settled({ status: 'killed', signal: 'SIGTERM' })))
  598. .toEqual({ status: 'killed', detail: 'signal: SIGTERM' })
  599. })
  600. it('maps a killed process without a recorded signal (kill raced exit / spawn failure)', () => {
  601. expect(processOutcome(settled({ status: 'killed', exitCode: null })))
  602. .toEqual({ status: 'killed', detail: 'killed before exit' })
  603. })
  604. it('maps a completed process to its exit code', () => {
  605. expect(processOutcome(settled({ exitCode: 3 })))
  606. .toEqual({ status: 'completed', detail: 'exit code: 3' })
  607. })
  608. it('defensively reads a null exit code as 0 (handle shapes from other executors)', () => {
  609. expect(processOutcome(settled({ exitCode: null })))
  610. .toEqual({ status: 'completed', detail: 'exit code: 0' })
  611. })
  612. })
  613. describe('session-cwd routing (per-session workdir)', () => {
  614. // An agent whose session header carries a cwd (what session/new records).
  615. const agentInCwd = (cwd: string) =>
  616. ({ inject: () => undefined, session: { header: { version: 0, id: 'c', createdAt: 0, cwd } } }) as unknown as Agent
  617. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  618. const ctx = await setup()
  619. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  620. expect(text(result).trim()).toMatch(/\/tmp$/)
  621. })
  622. it('an explicit absolute workdir overrides the session cwd', async () => {
  623. const ctx = await setup()
  624. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: '/tmp' }, agentInCwd('/'))
  625. expect(text(result).trim()).toMatch(/\/tmp$/)
  626. })
  627. it('a relative workdir is resolved against the session cwd', async () => {
  628. const ctx = await setup()
  629. // session cwd /usr + relative 'bin' → /usr/bin
  630. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: 'bin' }, agentInCwd('/usr'))
  631. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  632. })
  633. it('two sessions with different cwds each run bash in their own dir', async () => {
  634. const ctx = await setup()
  635. const inUsr = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/usr'))
  636. const inTmp = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  637. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  638. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  639. })
  640. it('falls back to the executor default when the agent has no session cwd', async () => {
  641. const ctx = await setup()
  642. // No exec.agent at all → executor uses its config/process.cwd() default.
  643. const result = await ctx.tools.execute({ callId: CallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  644. expect(result.isError).toBe(false)
  645. expect(text(result).trim().length).toBeGreaterThan(0)
  646. })
  647. })
  648. describe('renderResult', () => {
  649. const base = {
  650. exitCode: 0 as number | null,
  651. signal: null as NodeJS.Signals | null,
  652. timedOut: false,
  653. aborted: false,
  654. timeoutMs: 1000,
  655. stdout: { text: '', truncated: false },
  656. stderr: { text: '', truncated: false },
  657. }
  658. it('renders stderr-only output without a stdout prefix', () => {
  659. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  660. .toBe('[stderr]\nerr\n')
  661. })
  662. it('adds a separator when stdout does not end with a newline', () => {
  663. expect(renderResult({
  664. ...base,
  665. stdout: { text: 'out', truncated: false },
  666. stderr: { text: 'err', truncated: false },
  667. })).toBe('out\n[stderr]\nerr')
  668. })
  669. it('appends exit-code markers after a newline for unterminated output', () => {
  670. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  671. .toBe('x\n[exit code: 7]')
  672. })
  673. it('renders signal kills without the timeout marker when not timed out', () => {
  674. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  675. .toBe('(no output)\n[killed by signal: SIGKILL]')
  676. })
  677. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  678. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  679. .toBe('(no output)\n[timed out after 1000ms]')
  680. })
  681. it('orders the timeout marker before a kill marker', () => {
  682. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  683. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  684. })
  685. it('notes truncation with a fallback when the spill path is missing', () => {
  686. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  687. .toBe('tail\n[output truncated; full output: (unavailable)]')
  688. })
  689. it('reports sandbox denials before exit status and hints only when escalation is advertised', () => {
  690. const result: BashRunResult = {
  691. exitCode: 1,
  692. signal: null,
  693. timedOut: false,
  694. aborted: false,
  695. timeoutMs: 1000,
  696. stdout: { text: '', truncated: false },
  697. stderr: { text: 'denied', truncated: false },
  698. sandbox: { mode: 'read-only', denied: true },
  699. }
  700. expect(renderResult(result)).toMatch(/denied under read-only mode\]\n\[exit code: 1\]$/)
  701. expect(renderResult(result, ['workspace-write'])).toContain('[sandbox: escalation available')
  702. expect(renderResult({ ...result, sandbox: { mode: 'read-only', denied: false } }, ['workspace-write']))
  703. .not.toContain('[sandbox:')
  704. })
  705. })
  706. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  707. it('bash presentCall: a foreground run is a terminal card (command title, description, workdir → cwd absolute or relative)', async () => {
  708. const ctx = await setup()
  709. // No explicit workdir → a terminal card with no cwd (the UI bridge fills the
  710. // session cwd it owns; the pure presenter can't see it).
  711. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  712. .toEqual({ card: 'terminal', title: 'ls -la src', description: 'List files in src' })
  713. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  714. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  715. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: '/tmp/x' })
  716. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  717. // the session cwd, matching where execution runs) — not dropped.
  718. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  719. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: 'sub' })
  720. })
  721. it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => {
  722. const ctx = await setup()
  723. const present = ctx.tools.get('bash')!.presentResult!(
  724. { command: 'echo hi', description: 'echo' },
  725. { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false },
  726. )
  727. // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer
  728. // needs; the bridge derives the fenced fallback. exitCode is parsed back from
  729. // the [exit code: N] marker.
  730. expect(present).toEqual({ card: 'terminal', output: 'hi\n[exit code: 0]\n\n', exitCode: 0 })
  731. })
  732. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  733. const ctx = await setup()
  734. const args = { command: 'x', description: 'x' }
  735. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  736. expect(nonzero).toEqual({ card: 'terminal', output: 'oops\n[exit code: 3]', exitCode: 3 })
  737. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  738. expect(killed).toEqual({ card: 'terminal', output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' })
  739. })
  740. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  741. const ctx = await setup()
  742. const present = ctx.tools.get('bash')!
  743. // For each renderResult outcome, the rendered text fed back through
  744. // presentResult recovers the matching structured exit — the parse and the
  745. // marker emission co-evolve in one file, so this pins the pair.
  746. const base = {
  747. aborted: false,
  748. timeoutMs: 1000,
  749. stdout: { text: 'out', truncated: false },
  750. stderr: { text: '', truncated: false },
  751. }
  752. const cases = [
  753. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  754. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  755. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  756. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  757. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  758. ]
  759. for (const c of cases) {
  760. const rendered = renderResult(c.result)
  761. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  762. // Drop card + output; the remaining fields are the parsed exit.
  763. const { card: _c, output: _o, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string }
  764. expect(exit).toEqual(c.expect)
  765. }
  766. })
  767. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  768. const ctx = await setup()
  769. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  770. // A successful command may print marker-like text. A clean result appends no marker or
  771. // newline; parsing requires the leading newline emitted for real markers, so this stays exit 0.
  772. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  773. expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 })
  774. // Same for a fake signal marker with no leading newline.
  775. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  776. expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 })
  777. })
  778. it('bash presentCall/presentResult: a run_in_background call is a generic card and its ack carries no exit pill', async () => {
  779. const ctx = await setup()
  780. // The background start returns a task-id ack, not a streamed run — a generic
  781. // execute card with the command as rawInput and the description as content.
  782. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  783. expect(call).toEqual({ card: 'generic', title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  784. // The ack result is a generic fenced-text card — no terminal output / exit pill.
  785. const result = ctx.tools.get('bash')!.presentResult!(
  786. { command: 'sleep 100', description: 'wait', run_in_background: true },
  787. { content: [{ type: 'text', text: 'started background task bash-1' }], isError: false },
  788. )
  789. expect(result).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\nstarted background task bash-1\n```' }] })
  790. })
  791. it('bash presentResult: an isError result is a generic card (no real process exit to report)', async () => {
  792. const ctx = await setup()
  793. // A spawn failure / abort has no process exit — the body is an error message,
  794. // not renderResult output, so a generic fenced card, no terminal output/exit.
  795. const out = ctx.tools.get('bash')!.presentResult!(
  796. { command: 'x', description: 'x' },
  797. { content: [{ type: 'text', text: 'command aborted' }], isError: true },
  798. )
  799. expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ncommand aborted\n```' }] })
  800. })
  801. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  802. const ctx = await setup()
  803. const present = ctx.tools.get('bash')!.presentResult!(
  804. { command: 'x', description: 'x' },
  805. { content: [{ type: 'reasoning', text: 'unexpected' }], isError: false },
  806. )
  807. expect(present).toBeUndefined()
  808. })
  809. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  810. const ctx = await setup()
  811. const args = { command: 'x', description: 'x' }
  812. // Empty content (no block) and multi-block content both fall through.
  813. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  814. expect(ctx.tools.get('bash')!.presentResult!(args, {
  815. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  816. isError: false,
  817. })).toBeUndefined()
  818. })
  819. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  820. const ctx = await setup()
  821. // `defineTool` soft-validates replayed logged args before presentation. Invalid shapes return
  822. // undefined for generic UI rendering rather than throwing; `presentCall` accepts `unknown`.
  823. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  824. })
  825. })
  826. describe('the model-facing bash tool builds its request from named args only (no {...args} forward)', () => {
  827. /**
  828. * Records every {@link BashExecRequest} the consumer hands to `resolve()`, so a
  829. * test can assert what the model-facing tool DID and DID NOT forward. The `bash`
  830. * tool does not expose `stdin`/`env` as parameters (bash syntax already gives a
  831. * model that power), so it must build its request from named args only and
  832. * never spread unknown tool-call keys into it. This guard's job is to catch a
  833. * future refactor that blindly forwards `...args` — which would silently thread
  834. * model input into the post-scrub `env` merge — NOT to defend a trust boundary
  835. * (the credential scrub in dsh-bash-local is the security control; see the
  836. * bash-stdin-env RFC). Foreground `run()` returns a canned result; `start()`
  837. * hands back an already-settled fake handle so the task registration completes.
  838. */
  839. class RecordingBashExecutor extends BashExecutor {
  840. readonly requests: BashExecRequest[] = []
  841. resolve(request: BashExecRequest): BashExecSpec {
  842. this.requests.push(request)
  843. return {
  844. command: request.command,
  845. workdir: request.workdir ?? process.cwd(),
  846. timeoutMs: request.timeoutMs ?? 0,
  847. ...request.signal ? { signal: request.signal } : {},
  848. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  849. ...request.env !== undefined ? { env: request.env } : {},
  850. sandboxMode: request.sandboxMode,
  851. }
  852. }
  853. run(): Promise<BashRunResult> {
  854. return Promise.resolve({
  855. exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 0,
  856. stdout: { text: 'ok', truncated: false }, stderr: { text: '', truncated: false },
  857. })
  858. }
  859. start(): BashProcess {
  860. return {
  861. status: 'completed',
  862. exitCode: 0,
  863. signal: null,
  864. done: Promise.resolve(),
  865. readOutput: () => ({ delta: '', lossy: false }),
  866. kill: () => false,
  867. }
  868. }
  869. }
  870. async function setupRecording() {
  871. const ctx = new Context()
  872. await ctx.plugin(SystemPrompt)
  873. await ctx.plugin(ToolRegistry)
  874. await ctx.plugin(AgentRegistry)
  875. await ctx.plugin(TaskService)
  876. await ctx.plugin(ToolTasks)
  877. await ctx.plugin(RecordingBashExecutor)
  878. await ctx.plugin(ToolBash)
  879. return { ctx, bash: ctx.bash as RecordingBashExecutor }
  880. }
  881. it('does not forward env/stdin even when the model includes them as extra arguments', async () => {
  882. const { ctx, bash } = await setupRecording()
  883. // Unknown `env` and `stdin` keys are ignored by the schema and named request construction.
  884. // This preserves the request shape; it is not a security boundary because shell syntax can
  885. // already set environment variables or feed stdin.
  886. await ctx.tools.execute({
  887. callId: CallId('no-forward-1'),
  888. name: 'bash',
  889. arguments: {
  890. command: 'echo hi',
  891. description: 'echo',
  892. env: { SNEAKY_API_KEY: 'leak' },
  893. stdin: 'malicious payload',
  894. },
  895. })
  896. expect(bash.requests).toHaveLength(1)
  897. const request = bash.requests[0]!
  898. expect(request.command).toBe('echo hi')
  899. expect('env' in request).toBe(false)
  900. expect('stdin' in request).toBe(false)
  901. })
  902. it('a background bash call likewise carries no env/stdin', async () => {
  903. const { ctx, bash } = await setupRecording()
  904. const result = await ctx.tools.execute({
  905. callId: CallId('no-forward-2'),
  906. name: 'bash',
  907. arguments: {
  908. command: 'sleep 1',
  909. description: 'sleep',
  910. run_in_background: true,
  911. env: { TOKEN: 'leak' },
  912. stdin: 'x',
  913. },
  914. })
  915. // The call really went down the background path (the recorder sees the real
  916. // request the consumer built, so the absent env/stdin below is a real
  917. // negative, not a recorder that drops everything).
  918. expect(text(result)).toBe('started background task bash-1')
  919. expect(bash.requests).toHaveLength(1)
  920. const request = bash.requests[0]!
  921. expect(request.command).toBe('sleep 1')
  922. expect('env' in request).toBe(false)
  923. expect('stdin' in request).toBe(false)
  924. })
  925. })