tools.spec.ts 46 KB

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