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