tools.spec.ts 55 KB

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