tools.spec.ts 51 KB

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