tools.spec.ts 52 KB

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