tools.spec.ts 47 KB

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