tools.spec.ts 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  1. import { chmodSync, mkdirSync, 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, BashTaskId, setSandboxMode } from '@deepseek-ai/dsh-bash'
  8. import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead, OwnerToken } from '@deepseek-ai/dsh-bash'
  9. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import ToolRegistry from '@deepseek-ai/dsh-tools'
  12. import AgentRegistry from '@deepseek-ai/dsh-agent'
  13. import type { Agent } from '@deepseek-ai/dsh-agent'
  14. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  15. import { SandboxBashExecutor } from '@deepseek-ai/dsh-bash-sandbox'
  16. import { SandboxProvider } from '@deepseek-ai/dsh-sandbox'
  17. import type { ConfinedArgv } from '@deepseek-ai/dsh-sandbox'
  18. import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
  19. import ApprovalService from '@deepseek-ai/dsh-user-approval'
  20. import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
  21. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  22. import { renderResult } from '@deepseek-ai/dsh-tool-bash'
  23. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-tool-bash-spec-'))
  24. // Pure-config passthrough runner (same knob the snapshot tier uses): skips the
  25. // profile args up to `--` and execs the command unconfined — deterministic
  26. // without a host bwrap.
  27. const PASSTHROUGH_RUNNER = ['bash', '-c', 'while [ "$1" != "--" ]; do shift; done; shift; exec "$@"', 'passthrough-runner']
  28. const PASSTHROUGH_RUNNER_CONFIG = {
  29. runnerCommand: PASSTHROUGH_RUNNER,
  30. // The script has no pre-exec failure path; the provider still requires an
  31. // explicit dialect so a future script change cannot silently turn runner
  32. // failure into an ordinary command result.
  33. runnerFailureSignatures: ['passthrough-runner: profile rejected'],
  34. }
  35. async function setup() {
  36. const ctx = new Context()
  37. await ctx.plugin(SystemPrompt)
  38. await ctx.plugin(ToolRegistry)
  39. await ctx.plugin(AgentRegistry)
  40. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  41. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  42. await ctx.plugin(ToolBash)
  43. return ctx
  44. }
  45. /**
  46. * Build a fake {@link Agent} whose session token is `sessionId`, REGISTER it in
  47. * `ctx.agents` (the completion-notice path finds the owning agent by scanning
  48. * the registry for a matching `session.header.id`), and return it. The returned
  49. * agent is also passed to `execute` as `exec.agent` so it owns the spawned task.
  50. * The registration disposer is tracked so {@link unregisterFakeAgents} can drop
  51. * it (simulating the owning session disconnecting before a task completes).
  52. */
  53. const fakeAgentDisposers = new Map<Context, (() => Promise<void> | void)[]>()
  54. function registerFakeAgent(ctx: Context, sessionId: string, inject: (...args: unknown[]) => void): Agent {
  55. // The registry KEY (agent.id) is deliberately DIFFERENT from the session
  56. // token (session.header.id) — a config agent has `agentId !== sessionId`. The
  57. // owner token IS the session id, so the notice path must find the agent by
  58. // `session.header.id`, NOT the registry key. Using distinct values here makes
  59. // the test fail if a regression matched on the wrong field (a same-value fake
  60. // would pass either way — the "hits the line but not the scenario" trap).
  61. const agent = { id: `agent-${sessionId}`, inject, session: { header: { version: 0, id: sessionId, createdAt: 0 } } } as unknown as Agent
  62. const dispose = ctx.agents.register(agent)
  63. const list = fakeAgentDisposers.get(ctx) ?? []
  64. list.push(dispose)
  65. fakeAgentDisposers.set(ctx, list)
  66. return agent
  67. }
  68. /** Unregister every fake agent in this ctx (simulate the owning session disconnecting). */
  69. function unregisterFakeAgents(ctx: Context): void {
  70. for (const dispose of fakeAgentDisposers.get(ctx) ?? []) void dispose()
  71. fakeAgentDisposers.delete(ctx)
  72. }
  73. let callCounter = 0
  74. function call(ctx: Context, name: string, args: unknown) {
  75. return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args })
  76. }
  77. function text(result: { content: { type: string; text?: string }[] }): string {
  78. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  79. }
  80. async function callUntilText(
  81. ctx: Context,
  82. name: string,
  83. args: unknown,
  84. expected: string,
  85. timeoutMs = 5_000,
  86. ): Promise<Awaited<ReturnType<typeof call>>> {
  87. const deadline = Date.now() + timeoutMs
  88. let last: Awaited<ReturnType<typeof call>> | undefined
  89. while (Date.now() < deadline) {
  90. last = await call(ctx, name, args)
  91. if (text(last).includes(expected)) return last
  92. await new Promise(resolve => setTimeout(resolve, 20))
  93. }
  94. throw new Error(`${name} output did not include ${JSON.stringify(expected)}; last text was ${JSON.stringify(last !== undefined ? text(last) : '')}`)
  95. }
  96. class LossyReadBashExecutor extends BashExecutor {
  97. private readonly task: BashTask = {
  98. id: BashTaskId('bash-lossy'),
  99. command: 'fake',
  100. status: 'running',
  101. exitCode: null,
  102. signal: null,
  103. done: Promise.resolve(),
  104. }
  105. resolve(request: BashExecRequest): BashExecSpec {
  106. return {
  107. command: request.command,
  108. workdir: request.workdir ?? process.cwd(),
  109. timeoutMs: request.timeoutMs ?? 0,
  110. ...request.signal ? { signal: request.signal } : {},
  111. owner: request.owner,
  112. sandboxMode: request.sandboxMode,
  113. }
  114. }
  115. run(): Promise<BashRunResult> {
  116. return Promise.reject(new Error('not used'))
  117. }
  118. start(): BashTask {
  119. return this.task
  120. }
  121. get(id: BashTaskId): BashTask | undefined {
  122. return id === this.task.id ? this.task : undefined
  123. }
  124. ownerOf(): OwnerToken | undefined {
  125. return undefined
  126. }
  127. list(): BashTask[] {
  128. return [this.task]
  129. }
  130. readOutput(id: BashTaskId): BashTaskRead {
  131. if (id !== this.task.id) throw new Error(`unknown bash task "${id}"`)
  132. return { task: this.task, delta: 'tail', lossy: true }
  133. }
  134. kill(): boolean {
  135. return false
  136. }
  137. }
  138. describe('bash tool', () => {
  139. it('returns stdout for a successful command', async () => {
  140. const ctx = await setup()
  141. const result = await call(ctx, 'bash', { command: 'echo hello', description: 'test command' })
  142. expect(result.isError).toBe(false)
  143. expect(text(result)).toBe('hello\n')
  144. })
  145. it('reports (no output) for silent commands', async () => {
  146. const ctx = await setup()
  147. const result = await call(ctx, 'bash', { command: 'true', description: 'test command' })
  148. expect(text(result)).toBe('(no output)')
  149. })
  150. it('marks stderr sections', async () => {
  151. const ctx = await setup()
  152. const result = await call(ctx, 'bash', { command: 'echo out; echo err >&2', description: 'test command' })
  153. expect(text(result)).toBe('out\n[stderr]\nerr\n')
  154. expect(result.isError).toBe(false)
  155. })
  156. it('reports non-zero exits without isError', async () => {
  157. const ctx = await setup()
  158. const result = await call(ctx, 'bash', { command: 'echo failing; exit 3', description: 'test command' })
  159. expect(result.isError).toBe(false)
  160. expect(text(result)).toBe('failing\n[exit code: 3]')
  161. })
  162. it('reports timeout kills with both markers (timeout first)', async () => {
  163. const ctx = await setup()
  164. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', timeoutMs: 100 })
  165. expect(result.isError).toBe(false)
  166. expect(text(result)).toBe('(no output)\n[timed out after 100ms]\n[killed by signal: SIGTERM]')
  167. })
  168. it('reports a timeout even when the command traps the signal and exits 0', async () => {
  169. // The signal-independent timeout marker: a trapped SIGTERM that exits 0
  170. // after our timer fired must NOT look like a clean success. (bash may
  171. // print "Terminated" to stderr for the killed sleep — environment
  172. // dependent — so assert the marker, not the exact body.)
  173. const ctx = await setup()
  174. const result = await call(ctx, 'bash', { command: 'trap "exit 0" TERM; sleep 60', description: 'test command', timeoutMs: 100 })
  175. expect(result.isError).toBe(false)
  176. expect(text(result)).toContain('[timed out after 100ms]')
  177. expect(text(result)).not.toContain('[exit code:')
  178. })
  179. it('reports truncation with the spill path', async () => {
  180. const ctx = new Context()
  181. await ctx.plugin(SystemPrompt)
  182. await ctx.plugin(ToolRegistry)
  183. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 })
  184. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  185. await ctx.plugin(ToolBash)
  186. const result = await call(ctx, 'bash', { command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done', description: 'test command' })
  187. expect(text(result)).toContain('[output truncated; full output: ')
  188. expect(text(result)).toContain('line-0100')
  189. })
  190. it('honors workdir', async () => {
  191. const ctx = await setup()
  192. const result = await call(ctx, 'bash', { command: 'pwd', description: 'test command', workdir: '/tmp' })
  193. expect(text(result).trim()).toMatch(/\/tmp$/)
  194. })
  195. it('surfaces spawn failures as isError', async () => {
  196. const ctx = await setup()
  197. const result = await call(ctx, 'bash', { command: 'true', description: 'test command', workdir: '/nonexistent-dsh' })
  198. expect(result.isError).toBe(true)
  199. expect(text(result)).toMatch(/ENOENT/)
  200. })
  201. it('surfaces aborts as isError', async () => {
  202. const ctx = await setup()
  203. const controller = new AbortController()
  204. const pending = ctx.tools.execute({
  205. callId: CallId('call-abort'),
  206. name: 'bash',
  207. arguments: { command: 'sleep 60', description: 'test command' },
  208. signal: controller.signal,
  209. })
  210. setTimeout(() => { controller.abort() }, 50)
  211. const result = await pending
  212. expect(result.isError).toBe(true)
  213. expect(text(result)).toMatch(/aborted/)
  214. })
  215. // Type and required-key violations are now rejected by the harness
  216. // (defineTool validates against the SchemaSpec — the arg-validation RFC) before execute.
  217. it.each([
  218. [{}, /missing required property "command"/],
  219. [{ command: 42, description: 'd' }, /"command" must be a string/],
  220. [{ command: 'x' }, /missing required property "description"/],
  221. [{ command: 'x', description: 7 }, /"description" must be a string/],
  222. [{ command: 'x', description: 'd', timeoutMs: 'soon' }, /"timeoutMs" must be a number/],
  223. [{ command: 'x', description: 'd', workdir: 7 }, /"workdir" must be a string/],
  224. [{ command: 'x', description: 'd', run_in_background: 'yes' }, /"run_in_background" must be a boolean/],
  225. ])('rejects schema-invalid args %j', async (args, pattern) => {
  226. const ctx = await setup()
  227. const result = await call(ctx, 'bash', args)
  228. expect(result.isError).toBe(true)
  229. expect(text(result)).toMatch(pattern)
  230. })
  231. // Value constraints the SchemaSpec can't express stay in the tool body.
  232. it.each([
  233. [{ command: ' ', description: 'd' }, /invalid command/],
  234. [{ command: 'x', description: ' ' }, /invalid description/],
  235. [{ command: 'x', description: 'd', timeoutMs: -1 }, /invalid timeoutMs/],
  236. ])('rejects value-invalid args %j', async (args, pattern) => {
  237. const ctx = await setup()
  238. const result = await call(ctx, 'bash', args)
  239. expect(result.isError).toBe(true)
  240. expect(text(result)).toMatch(pattern)
  241. })
  242. it('rejects a non-JSON numeric argument before tool-specific validation', async () => {
  243. const ctx = await setup()
  244. const result = await call(ctx, 'bash', {
  245. command: 'x', description: 'd', timeoutMs: Number.NaN,
  246. })
  247. expect(result.isError).toBe(true)
  248. expect(text(result)).toContain('tool execution arguments must be losslessly JSON-serializable')
  249. })
  250. it('registers all three schemas in the system prompt assembly', async () => {
  251. const ctx = await setup()
  252. const names = ctx.tools.schemas().map(schema => schema.name)
  253. expect(names).toEqual(['bash', 'bash_output', 'bash_kill'])
  254. const bashSchema = ctx.tools.schemas()[0]!
  255. expect(bashSchema.parameters).toMatchObject({
  256. type: 'object',
  257. required: ['command', 'description'],
  258. })
  259. })
  260. it('contributes the exit-code habit as its prompt section (guidance the descriptions cannot carry)', async () => {
  261. const ctx = await setup()
  262. const assembly = await ctx.systemPrompt.assemble()
  263. const section = assembly.sections.find(s => s.name === 'tool:bash')
  264. expect(section?.order).toBe(105)
  265. expect(section?.text).toContain('[exit code: N]')
  266. })
  267. it('unregisters everything when the plugin fiber is disposed (HMR safety)', async () => {
  268. const ctx = new Context()
  269. await ctx.plugin(SystemPrompt)
  270. await ctx.plugin(ToolRegistry)
  271. await ctx.plugin(LocalBashExecutor, {})
  272. const fiber = await ctx.plugin(ToolBash)
  273. expect(ctx.tools.schemas()).toHaveLength(3)
  274. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona', 'tool:bash'])
  275. await fiber.dispose()
  276. expect(ctx.tools.schemas()).toHaveLength(0)
  277. // Only the system-prompt plugin's own built-in sections remain.
  278. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona'])
  279. })
  280. it('tools depend on the executor: no registration without ctx.bash', async () => {
  281. const ctx = new Context()
  282. await ctx.plugin(SystemPrompt)
  283. await ctx.plugin(ToolRegistry)
  284. // inject: ['tools', 'bash'] keeps the plugin pending until bash exists.
  285. await ctx.plugin(ToolBash)
  286. expect(ctx.tools.schemas()).toHaveLength(0)
  287. await ctx.plugin(LocalBashExecutor, {})
  288. await new Promise(resolve => setTimeout(resolve, 0))
  289. expect(ctx.tools.schemas()).toHaveLength(3)
  290. })
  291. })
  292. describe('background tools', () => {
  293. it('bash with run_in_background returns a task id immediately', async () => {
  294. const ctx = await setup()
  295. const result = await call(ctx, 'bash', { command: 'sleep 0.2; echo bg-done', description: 'test command', run_in_background: true })
  296. expect(result.isError).toBe(false)
  297. expect(text(result)).toMatch(/^started background task bash-\d+$/)
  298. })
  299. it('bash_output polls incrementally and reports status', async () => {
  300. const ctx = await setup()
  301. const started = await call(ctx, 'bash', { command: 'echo first; sleep 1; echo second', description: 'test command', run_in_background: true })
  302. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  303. const first = await callUntilText(ctx, 'bash_output', { task_id: id }, 'first')
  304. expect(text(first)).toContain('first')
  305. expect(text(first)).toContain('[status: running]')
  306. await ctx.bash.get(id)!.done
  307. const second = await call(ctx, 'bash_output', { task_id: id })
  308. expect(text(second)).toContain('second')
  309. expect(text(second)).not.toContain('first')
  310. expect(text(second)).toContain('[status: completed, exit code: 0]')
  311. const third = await call(ctx, 'bash_output', { task_id: id })
  312. expect(text(third)).toContain('(no new output)')
  313. })
  314. it('bash_output flags lossy reads with spill paths', async () => {
  315. const ctx = new Context()
  316. await ctx.plugin(SystemPrompt)
  317. await ctx.plugin(ToolRegistry)
  318. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 })
  319. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  320. await ctx.plugin(ToolBash)
  321. const started = await call(ctx, 'bash', { command: 'for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', description: 'test command', run_in_background: true })
  322. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  323. await ctx.bash.get(id)!.done
  324. const read = await call(ctx, 'bash_output', { task_id: id })
  325. expect(text(read)).toContain('[some output was dropped from memory; full output: ')
  326. })
  327. it('bash_output reports unavailable when a lossy read has no safe spill path', async () => {
  328. const ctx = new Context()
  329. await ctx.plugin(SystemPrompt)
  330. await ctx.plugin(ToolRegistry)
  331. await ctx.plugin(LossyReadBashExecutor)
  332. await ctx.plugin(ToolBash)
  333. const read = await call(ctx, 'bash_output', { task_id: 'bash-lossy' })
  334. expect(text(read)).toBe('tail\n[some output was dropped from memory; full output: (unavailable)]\n[status: running]')
  335. })
  336. it('bash_kill stops a running task; repeat reports already-finished', async () => {
  337. const ctx = await setup()
  338. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  339. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  340. const killed = await call(ctx, 'bash_kill', { task_id: id })
  341. expect(text(killed)).toBe(`killed background task ${id}`)
  342. await ctx.bash.get(id)!.done
  343. const again = await call(ctx, 'bash_kill', { task_id: id })
  344. expect(text(again)).toBe(`task ${id} had already finished`)
  345. const status = await call(ctx, 'bash_output', { task_id: id })
  346. expect(text(status)).toContain('[status: killed by SIGTERM]')
  347. })
  348. it('unknown task ids are isError for both tools', async () => {
  349. const ctx = await setup()
  350. const read = await call(ctx, 'bash_output', { task_id: 'bash-999' })
  351. expect(read.isError).toBe(true)
  352. expect(text(read)).toMatch(/unknown bash task/)
  353. const kill = await call(ctx, 'bash_kill', { task_id: 'bash-999' })
  354. expect(kill.isError).toBe(true)
  355. })
  356. it.each([
  357. ['bash_output', {}, /missing required property "task_id"/],
  358. ['bash_output', { task_id: 9 }, /"task_id" must be a string/],
  359. ['bash_kill', { task_id: '' }, /invalid task_id/],
  360. ])('%s rejects invalid task_id %j', async (tool, args, pattern) => {
  361. const ctx = await setup()
  362. const result = await call(ctx, tool, args)
  363. expect(result.isError).toBe(true)
  364. expect(text(result)).toMatch(pattern)
  365. })
  366. it('injects a completion notice into the owning agent (found via the registry by session token)', async () => {
  367. const ctx = await setup()
  368. const inject = vi.fn()
  369. // The notice path looks the agent up in ctx.agents by its session token, so
  370. // the agent must be REGISTERED (not merely passed to execute). Mount a
  371. // registry and register a fake whose session.header.id IS the owner token.
  372. const agent = registerFakeAgent(ctx, 'bg', inject)
  373. const started = await ctx.tools.execute({
  374. callId: CallId('call-bg'),
  375. name: 'bash',
  376. arguments: { command: 'true', description: 'test command', run_in_background: true },
  377. agent,
  378. })
  379. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  380. await ctx.bash.get(id)!.done
  381. expect(inject).toHaveBeenCalledTimes(1)
  382. const [content, options] = inject.mock.calls[0] as [
  383. { type: string; text: string }[],
  384. { source: { kind: string; plugin: string } },
  385. ]
  386. expect(content[0]!.text).toContain(`background bash task ${id} finished`)
  387. expect(content[0]!.text).toContain('bash_output')
  388. expect(options.source).toEqual({ kind: 'plugin', plugin: 'tool-bash' })
  389. })
  390. it('swallows ONLY the disposed-agent inject error', async () => {
  391. const ctx = await setup()
  392. const agent = registerFakeAgent(ctx, 'bg', () => { throw new Error('agent "x" is disposed') })
  393. const started = await ctx.tools.execute({
  394. callId: CallId('call-bg2'),
  395. name: 'bash',
  396. arguments: { command: 'true', description: 'test command', run_in_background: true },
  397. agent,
  398. })
  399. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  400. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  401. })
  402. it('rethrows a non-disposed inject failure (not blindly swallowed)', async () => {
  403. const ctx = await setup()
  404. // A real bug in inject (not the benign disposed race) must surface — the
  405. // base-class notifier contains it (logs, does not reject task.done), but
  406. // the listener itself must have thrown rather than silently eaten it.
  407. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  408. try {
  409. const agent = registerFakeAgent(ctx, 'bg', () => { throw new Error('unexpected inject bug') })
  410. const started = await ctx.tools.execute({
  411. callId: CallId('call-bg3'),
  412. name: 'bash',
  413. arguments: { command: 'true', description: 'test command', run_in_background: true },
  414. agent,
  415. })
  416. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  417. await ctx.bash.get(id)!.done
  418. // notifyTaskDone caught and logged the rethrown error.
  419. expect(errorSpy).toHaveBeenCalled()
  420. const logged = errorSpy.mock.calls.flat().some(arg => arg instanceof Error && arg.message === 'unexpected inject bug')
  421. expect(logged).toBe(true)
  422. } finally {
  423. errorSpy.mockRestore()
  424. }
  425. })
  426. it('drops the notice cleanly when the owning agent is gone from the registry by completion', async () => {
  427. // A bash task (owned by the host-scoped bash-local fiber) can OUTLIVE its
  428. // per-session agent — e.g. the ACP session disconnects and its AgentHandle
  429. // disposes while the background task is still running. The owner token is
  430. // still on the task, but no live agent carries it anymore, so the registry
  431. // lookup finds nothing and the notice is dropped (no throw).
  432. const ctx = await setup()
  433. const inject = vi.fn()
  434. const agent = registerFakeAgent(ctx, 'bg', inject)
  435. const started = await ctx.tools.execute({
  436. callId: CallId('call-bg4'),
  437. name: 'bash',
  438. arguments: { command: 'true', description: 'test command', run_in_background: true },
  439. agent,
  440. })
  441. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  442. // Unregister the agent BEFORE the task completes (simulate disconnect).
  443. unregisterFakeAgents(ctx)
  444. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  445. expect(inject).not.toHaveBeenCalled()
  446. })
  447. it('does not notify when no agent owned the task', async () => {
  448. const ctx = await setup()
  449. const started = await call(ctx, 'bash', { command: 'true', description: 'test command', run_in_background: true })
  450. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  451. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  452. })
  453. })
  454. describe('background task ownership (cross-session isolation)', () => {
  455. /** Run a tool on behalf of a specific agent (sets exec.agent). */
  456. function callAs(ctx: Context, agent: import('@deepseek-ai/dsh-agent').Agent | undefined, name: string, args: unknown) {
  457. return ctx.tools.execute({ callId: CallId(`own-${++callCounter}`), name, arguments: args, ...agent ? { agent } : {} })
  458. }
  459. // Ownership is by TOKEN (session.header.id), NOT agent object identity — so
  460. // each agent needs a DISTINCT session id, else every fake yields the same
  461. // token and the isolation tests pass for the wrong reason (all tasks owned by
  462. // the same token). The impl reads `session.header.id`, so the fakes MUST carry
  463. // it.
  464. const fakeAgent = (sessionId: string) =>
  465. ({ inject: () => undefined, session: { header: { version: 0, id: sessionId, createdAt: 0 } } }) as unknown as import('@deepseek-ai/dsh-agent').Agent
  466. it('rejects bash_output/bash_kill for a task owned by a DIFFERENT session token', async () => {
  467. const ctx = await setup()
  468. const a = fakeAgent('sess-a')
  469. const b = fakeAgent('sess-b')
  470. // Agent A starts a long-running background task.
  471. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  472. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  473. // Agent B (a different session token) cannot read or kill A's task.
  474. const readByB = await callAs(ctx, b, 'bash_output', { task_id: id })
  475. expect(readByB.isError).toBe(true)
  476. expect(text(readByB)).toMatch(/belongs to another session/)
  477. const killByB = await callAs(ctx, b, 'bash_kill', { task_id: id })
  478. expect(killByB.isError).toBe(true)
  479. expect(text(killByB)).toMatch(/belongs to another session/)
  480. // The task is still running (B's kill did nothing) — A can still kill it.
  481. const killByA = await callAs(ctx, a, 'bash_kill', { task_id: id })
  482. expect(killByA.isError).toBe(false)
  483. expect(text(killByA)).toBe(`killed background task ${id}`)
  484. })
  485. it('a DIFFERENT Agent object with the SAME session token may access the task (ownership is by token, not object identity)', async () => {
  486. // Ownership fences by session.header.id, NOT Agent object identity. Two
  487. // distinct Agent objects sharing one session token (e.g. an agent re-created
  488. // on the same session) are the SAME owner.
  489. const ctx = await setup()
  490. const a1 = fakeAgent('sess-shared')
  491. const a2 = fakeAgent('sess-shared') // distinct object, same token
  492. const started = await callAs(ctx, a1, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  493. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  494. const readByA2 = await callAs(ctx, a2, 'bash_output', { task_id: id })
  495. expect(readByA2.isError).toBe(false)
  496. await callAs(ctx, a1, 'bash_kill', { task_id: id }) // cleanup
  497. })
  498. it('the no-agent (non-loop) caller cannot access an owned task', async () => {
  499. const ctx = await setup()
  500. const a = fakeAgent('sess-a')
  501. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  502. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  503. // A call with no exec.agent has no token → cannot prove ownership of an owned task.
  504. const read = await callAs(ctx, undefined, 'bash_output', { task_id: id })
  505. expect(read.isError).toBe(true)
  506. expect(text(read)).toMatch(/belongs to another session/)
  507. await callAs(ctx, a, 'bash_kill', { task_id: id }) // cleanup
  508. })
  509. it('an UNOWNED task (started with no agent) is accessible to anyone', async () => {
  510. const ctx = await setup()
  511. // Started by a non-loop caller (no exec.agent) → no owner token recorded.
  512. const started = await callAs(ctx, undefined, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  513. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  514. // Any agent (and the no-agent caller) may read/kill it.
  515. const read = await callAs(ctx, fakeAgent('sess-x'), 'bash_output', { task_id: id })
  516. expect(read.isError).toBe(false)
  517. const killed = await callAs(ctx, undefined, 'bash_kill', { task_id: id })
  518. expect(killed.isError).toBe(false)
  519. })
  520. it('the owner can still access its task AFTER it completes (owner token persists on the task)', async () => {
  521. const ctx = await setup()
  522. const a = fakeAgent('sess-a')
  523. const b = fakeAgent('sess-b')
  524. const started = await callAs(ctx, a, 'bash', { command: 'echo done', description: 'bg', run_in_background: true })
  525. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  526. await ctx.bash.get(id)!.done
  527. // Completion does NOT clear ownership: B is still rejected, A still allowed.
  528. const readByB = await callAs(ctx, b, 'bash_output', { task_id: id })
  529. expect(readByB.isError).toBe(true)
  530. expect(text(readByB)).toMatch(/belongs to another session/)
  531. const readByA = await callAs(ctx, a, 'bash_output', { task_id: id })
  532. expect(readByA.isError).toBe(false)
  533. })
  534. it('ownership SURVIVES an independent tool-bash HMR reload (token lives on the executor)', async () => {
  535. // The owner token lives on the TASK inside the executor (dsh-bash fiber), NOT
  536. // in a tool-bash plugin-local map. So reloading ONLY tool-bash (executor +
  537. // task survive) preserves ownership. This is the regression guard: a
  538. // plugin-local map would make B accessible after reload, and this test would
  539. // catch it.
  540. const ctx = new Context()
  541. await ctx.plugin(SystemPrompt)
  542. await ctx.plugin(ToolRegistry)
  543. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  544. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  545. const fiber = await ctx.plugin(ToolBash)
  546. const a = fakeAgent('sess-a')
  547. const b = fakeAgent('sess-b')
  548. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  549. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  550. // Before reload: B is rejected (A owns it).
  551. expect((await callAs(ctx, b, 'bash_output', { task_id: id })).isError).toBe(true)
  552. // Reload ONLY tool-bash; the executor and its running task (with its owner
  553. // token) survive.
  554. await fiber.dispose()
  555. await ctx.plugin(ToolBash)
  556. expect(ctx.bash.get(id)?.status).toBe('running')
  557. expect(ctx.bash.ownerOf(id)).toBe('sess-a')
  558. // After reload, ownership is INTACT → B is STILL rejected.
  559. expect((await callAs(ctx, b, 'bash_output', { task_id: id })).isError).toBe(true)
  560. await callAs(ctx, a, 'bash_kill', { task_id: id }) // cleanup
  561. })
  562. })
  563. describe('session-cwd routing (per-session workdir)', () => {
  564. function callAs(ctx: Context, agent: import('@deepseek-ai/dsh-agent').Agent | undefined, args: unknown) {
  565. return ctx.tools.execute({ callId: CallId(`cwd-${++callCounter}`), name: 'bash', arguments: args, ...agent ? { agent } : {} })
  566. }
  567. // An agent whose session header carries a cwd (what session/new records).
  568. const agentInCwd = (cwd: string) =>
  569. ({ inject: () => undefined, session: { header: { version: 0, id: 'c', createdAt: 0, cwd } } }) as unknown as import('@deepseek-ai/dsh-agent').Agent
  570. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  571. const ctx = await setup()
  572. const result = await callAs(ctx, agentInCwd('/tmp'), { command: 'pwd', description: 'pwd' })
  573. expect(text(result).trim()).toMatch(/\/tmp$/)
  574. })
  575. it('an explicit absolute workdir overrides the session cwd', async () => {
  576. const ctx = await setup()
  577. const result = await callAs(ctx, agentInCwd('/'), { command: 'pwd', description: 'pwd', workdir: '/tmp' })
  578. expect(text(result).trim()).toMatch(/\/tmp$/)
  579. })
  580. it('a relative workdir is resolved against the session cwd', async () => {
  581. const ctx = await setup()
  582. // session cwd /usr + relative 'bin' → /usr/bin
  583. const result = await callAs(ctx, agentInCwd('/usr'), { command: 'pwd', description: 'pwd', workdir: 'bin' })
  584. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  585. })
  586. it('two sessions with different cwds each run bash in their own dir', async () => {
  587. const ctx = await setup()
  588. const inUsr = await callAs(ctx, agentInCwd('/usr'), { command: 'pwd', description: 'pwd' })
  589. const inTmp = await callAs(ctx, agentInCwd('/tmp'), { command: 'pwd', description: 'pwd' })
  590. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  591. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  592. })
  593. it('falls back to the executor default when the agent has no session cwd', async () => {
  594. const ctx = await setup()
  595. // No exec.agent at all → executor uses its config/process.cwd() default.
  596. const result = await ctx.tools.execute({ callId: CallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  597. expect(result.isError).toBe(false)
  598. expect(text(result).trim().length).toBeGreaterThan(0)
  599. })
  600. })
  601. describe('renderResult', () => {
  602. const base = {
  603. exitCode: 0 as number | null,
  604. signal: null as NodeJS.Signals | null,
  605. timedOut: false,
  606. aborted: false,
  607. timeoutMs: 1000,
  608. stdout: { text: '', truncated: false },
  609. stderr: { text: '', truncated: false },
  610. }
  611. it('renders stderr-only output without a stdout prefix', () => {
  612. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  613. .toBe('[stderr]\nerr\n')
  614. })
  615. it('adds a separator when stdout does not end with a newline', () => {
  616. expect(renderResult({
  617. ...base,
  618. stdout: { text: 'out', truncated: false },
  619. stderr: { text: 'err', truncated: false },
  620. })).toBe('out\n[stderr]\nerr')
  621. })
  622. it('appends exit-code markers after a newline for unterminated output', () => {
  623. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  624. .toBe('x\n[exit code: 7]')
  625. })
  626. it('renders signal kills without the timeout marker when not timed out', () => {
  627. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  628. .toBe('(no output)\n[killed by signal: SIGKILL]')
  629. })
  630. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  631. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  632. .toBe('(no output)\n[timed out after 1000ms]')
  633. })
  634. it('orders the timeout marker before a kill marker', () => {
  635. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  636. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  637. })
  638. it('notes truncation with a fallback when the spill path is missing', () => {
  639. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  640. .toBe('tail\n[output truncated; full output: (unavailable)]')
  641. })
  642. })
  643. describe('status lines', () => {
  644. it('reports kills without a recorded signal (executor raced process exit)', async () => {
  645. const ctx = await setup()
  646. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  647. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  648. const task = ctx.bash.get(id)!
  649. await call(ctx, 'bash_kill', { task_id: id })
  650. await task.done
  651. // Simulate the variant where the close event carried no signal.
  652. task.signal = null
  653. const read = await call(ctx, 'bash_output', { task_id: id })
  654. expect(text(read)).toContain('[status: killed]')
  655. })
  656. it('reports completed tasks with a null exit code as exit 0', async () => {
  657. const ctx = await setup()
  658. const started = await call(ctx, 'bash', { command: 'true', description: 'test command', run_in_background: true })
  659. const id = BashTaskId(/task (bash-\d+)/.exec(text(started))![1]!)
  660. const task = ctx.bash.get(id)!
  661. await task.done
  662. // Defensive: completed tasks always carry an exit code in practice; the
  663. // ?? 0 fallback covers task shapes from other executor implementations.
  664. task.exitCode = null
  665. const read = await call(ctx, 'bash_output', { task_id: id })
  666. expect(text(read)).toContain('[status: completed, exit code: 0]')
  667. })
  668. })
  669. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  670. it('bash presentCall: a foreground run is a terminal card (command title, description, workdir → cwd absolute or relative)', async () => {
  671. const ctx = await setup()
  672. // No explicit workdir → a terminal card with no cwd (the UI bridge fills the
  673. // session cwd it owns; the pure presenter can't see it).
  674. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  675. .toEqual({ card: 'terminal', title: 'ls -la src', description: 'List files in src' })
  676. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  677. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  678. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: '/tmp/x' })
  679. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  680. // the session cwd, matching where execution runs) — not dropped.
  681. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  682. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: 'sub' })
  683. })
  684. it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => {
  685. const ctx = await setup()
  686. const present = ctx.tools.get('bash')!.presentResult!(
  687. { command: 'echo hi', description: 'echo' },
  688. { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false },
  689. )
  690. // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer
  691. // needs; the bridge derives the fenced fallback. exitCode is parsed back from
  692. // the [exit code: N] marker.
  693. expect(present).toEqual({ card: 'terminal', output: 'hi\n[exit code: 0]\n\n', exitCode: 0 })
  694. })
  695. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  696. const ctx = await setup()
  697. const args = { command: 'x', description: 'x' }
  698. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  699. expect(nonzero).toEqual({ card: 'terminal', output: 'oops\n[exit code: 3]', exitCode: 3 })
  700. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  701. expect(killed).toEqual({ card: 'terminal', output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' })
  702. })
  703. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  704. const ctx = await setup()
  705. const present = ctx.tools.get('bash')!
  706. // For each renderResult outcome, the rendered text fed back through
  707. // presentResult recovers the matching structured exit — the parse and the
  708. // marker emission co-evolve in one file, so this pins the pair.
  709. const base = {
  710. aborted: false,
  711. timeoutMs: 1000,
  712. stdout: { text: 'out', truncated: false },
  713. stderr: { text: '', truncated: false },
  714. }
  715. const cases = [
  716. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  717. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  718. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  719. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  720. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  721. ]
  722. for (const c of cases) {
  723. const rendered = renderResult(c.result)
  724. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  725. // Drop card + output; the remaining fields are the parsed exit.
  726. const { card: _c, output: _o, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string }
  727. expect(exit).toEqual(c.expect)
  728. }
  729. })
  730. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  731. const ctx = await setup()
  732. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  733. // A successful command can print text that looks like a marker. renderResult
  734. // for a clean exit 0 appends NOTHING (and no trailing newline), so the body's
  735. // own tail is `[exit code: 5]`. The parse requires a LEADING newline before
  736. // the marker (renderResult always inserts one before a REAL marker), so this
  737. // no-trailing-newline body is NOT mistaken for a failure → exitCode 0.
  738. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  739. expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 })
  740. // Same for a fake signal marker with no leading newline.
  741. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  742. expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 })
  743. })
  744. it('bash presentCall/presentResult: a run_in_background call is a generic card and its ack carries no exit pill', async () => {
  745. const ctx = await setup()
  746. // The background start returns a task-id ack, not a streamed run — a generic
  747. // execute card with the command as rawInput and the description as content.
  748. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  749. expect(call).toEqual({ card: 'generic', title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  750. // The ack result is a generic fenced-text card — no terminal output / exit pill.
  751. const result = ctx.tools.get('bash')!.presentResult!(
  752. { command: 'sleep 100', description: 'wait', run_in_background: true },
  753. { content: [{ type: 'text', text: 'started background task bash-1' }], isError: false },
  754. )
  755. expect(result).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\nstarted background task bash-1\n```' }] })
  756. })
  757. it('bash presentResult: an isError result is a generic card (no real process exit to report)', async () => {
  758. const ctx = await setup()
  759. // A spawn failure / abort has no process exit — the body is an error message,
  760. // not renderResult output, so a generic fenced card, no terminal output/exit.
  761. const out = ctx.tools.get('bash')!.presentResult!(
  762. { command: 'x', description: 'x' },
  763. { content: [{ type: 'text', text: 'command aborted' }], isError: true },
  764. )
  765. expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ncommand aborted\n```' }] })
  766. })
  767. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  768. const ctx = await setup()
  769. const present = ctx.tools.get('bash')!.presentResult!(
  770. { command: 'x', description: 'x' },
  771. { content: [{ type: 'reasoning', text: 'unexpected' }], isError: false },
  772. )
  773. expect(present).toBeUndefined()
  774. })
  775. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  776. const ctx = await setup()
  777. const args = { command: 'x', description: 'x' }
  778. // Empty content (no block) and multi-block content both fall through.
  779. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  780. expect(ctx.tools.get('bash')!.presentResult!(args, {
  781. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  782. isError: false,
  783. })).toBeUndefined()
  784. })
  785. it('bash_output / bash_kill presentCall: a readable task-scoped title, task id as rawInput', async () => {
  786. const ctx = await setup()
  787. expect(ctx.tools.get('bash_output')!.presentCall!({ task_id: 'bash-3' }))
  788. .toEqual({ card: 'generic', title: 'Read output from background task bash-3', kind: 'execute', rawInput: 'bash-3' })
  789. expect(ctx.tools.get('bash_kill')!.presentCall!({ task_id: 'bash-3' }))
  790. .toEqual({ card: 'generic', title: 'Kill background task bash-3', kind: 'execute', rawInput: 'bash-3' })
  791. })
  792. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  793. const ctx = await setup()
  794. // defineTool wraps presentCall to soft-validate against the schema and fall
  795. // back to undefined (a generic UI presentation) rather than throwing on the
  796. // display path — it may run on replay of arbitrary logged args. The
  797. // ToolDefinition.presentCall takes `unknown`, so a malformed shape needs no cast.
  798. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  799. })
  800. })
  801. describe('the model-facing bash tool builds its request from named args only (no {...args} forward)', () => {
  802. /**
  803. * Records every {@link BashExecRequest} the consumer hands to `resolve()`, so a
  804. * test can assert what the model-facing tool DID and DID NOT forward. The `bash`
  805. * tool does not expose `stdin`/`env` as parameters (bash syntax already gives a
  806. * model that power), so it must build its request from named args only and
  807. * never spread unknown tool-call keys into it. This guard's job is to catch a
  808. * future refactor that blindly forwards `...args` — which would silently thread
  809. * model input into the post-scrub `env` merge — NOT to defend a trust boundary
  810. * (the credential scrub in dsh-bash-local is the security control; see the
  811. * bash-stdin-env RFC). Foreground `run()` returns a canned result; `start()` is
  812. * unused here.
  813. */
  814. class RecordingBashExecutor extends BashExecutor {
  815. readonly requests: BashExecRequest[] = []
  816. resolve(request: BashExecRequest): BashExecSpec {
  817. this.requests.push(request)
  818. return {
  819. command: request.command,
  820. workdir: request.workdir ?? process.cwd(),
  821. timeoutMs: request.timeoutMs ?? 0,
  822. ...request.signal ? { signal: request.signal } : {},
  823. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  824. ...request.env !== undefined ? { env: request.env } : {},
  825. owner: request.owner,
  826. sandboxMode: request.sandboxMode,
  827. }
  828. }
  829. run(): Promise<BashRunResult> {
  830. return Promise.resolve({
  831. exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 0,
  832. stdout: { text: 'ok', truncated: false }, stderr: { text: '', truncated: false },
  833. })
  834. }
  835. start(): BashTask { throw new Error('unused') }
  836. get(): BashTask | undefined { return undefined }
  837. ownerOf(): OwnerToken | undefined { return undefined }
  838. list(): BashTask[] { return [] }
  839. readOutput(): BashTaskRead { throw new Error('unused') }
  840. kill(): boolean { return false }
  841. }
  842. async function setupRecording() {
  843. const ctx = new Context()
  844. await ctx.plugin(SystemPrompt)
  845. await ctx.plugin(ToolRegistry)
  846. await ctx.plugin(AgentRegistry)
  847. await ctx.plugin(RecordingBashExecutor)
  848. await ctx.plugin(ToolBash)
  849. return { ctx, bash: ctx.bash as RecordingBashExecutor }
  850. }
  851. it('does not forward env/stdin even when the model includes them as extra arguments', async () => {
  852. const { ctx, bash } = await setupRecording()
  853. // Extra args: the model includes `env` and `stdin` keys hoping they reach the
  854. // executor. The bash tool's schema ignores unknown keys, and execute() builds
  855. // the request from only command/workdir/timeoutMs/signal — so the recorded
  856. // request carries NEITHER. (Not a security wall — the model could set an env
  857. // var or feed stdin via shell syntax anyway; this just keeps the request
  858. // shape honest so a future `...args` spread can't silently forward input.)
  859. await ctx.tools.execute({
  860. callId: CallId('no-forward-1'),
  861. name: 'bash',
  862. arguments: {
  863. command: 'echo hi',
  864. description: 'echo',
  865. env: { SNEAKY_API_KEY: 'leak' },
  866. stdin: 'malicious payload',
  867. },
  868. })
  869. expect(bash.requests).toHaveLength(1)
  870. const request = bash.requests[0]!
  871. expect(request.command).toBe('echo hi')
  872. expect('env' in request).toBe(false)
  873. expect('stdin' in request).toBe(false)
  874. })
  875. it('a background bash call likewise carries no env/stdin', async () => {
  876. const { ctx, bash } = await setupRecording()
  877. // start() throws in this recorder, but resolve() runs first and records the
  878. // request — which is all this no-forward assertion needs.
  879. await ctx.tools.execute({
  880. callId: CallId('no-forward-2'),
  881. name: 'bash',
  882. arguments: {
  883. command: 'sleep 1',
  884. description: 'sleep',
  885. run_in_background: true,
  886. env: { TOKEN: 'leak' },
  887. stdin: 'x',
  888. },
  889. })
  890. expect(bash.requests).toHaveLength(1)
  891. const request = bash.requests[0]!
  892. expect('env' in request).toBe(false)
  893. expect('stdin' in request).toBe(false)
  894. // The owner token IS set on a background call (the isolation fence) — proving
  895. // the recorder sees the real request the consumer built, so the absent
  896. // env/stdin above is a real negative, not a recorder that drops everything.
  897. expect('owner' in request).toBe(true)
  898. })
  899. })
  900. describe('sandbox rendering', () => {
  901. const sandboxResult = (denied: boolean, exitCode: number): BashRunResult => ({
  902. exitCode,
  903. signal: null,
  904. timedOut: false,
  905. aborted: false,
  906. timeoutMs: 1000,
  907. stdout: { text: '', truncated: false },
  908. stderr: { text: denied ? 'bash: /x: Read-only file system' : 'boom', truncated: false },
  909. sandbox: { mode: 'read-only', denied },
  910. })
  911. it('renders a denial marker BEFORE the exit-code marker (the $-anchored parse survives)', () => {
  912. const text = renderResult(sandboxResult(true, 1))
  913. expect(text).toMatch(/\[sandbox: file access denied under read-only mode\]\n\[exit code: 1\]$/)
  914. })
  915. it('appends the same-turn escalation hint to a denial exactly when the fields are advertised', () => {
  916. const hinted = renderResult(sandboxResult(true, 1), ['workspace-write', 'danger-full-access'])
  917. expect(hinted).toMatch(
  918. /denied under read-only mode\]\n\[sandbox: escalation available — retry this exact command once with sandbox_permissions [^\n]+\]\n\[exit code: 1\]$/, // eslint-disable-line @stylistic/max-len -- the hint sentence is pinned verbatim
  919. )
  920. // Default (no advertisement): no hint — a lever the schema does not offer is never suggested.
  921. expect(renderResult(sandboxResult(true, 1))).not.toContain('escalation available')
  922. // A non-denied result never hints, advertised or not.
  923. expect(renderResult(sandboxResult(false, 2), ['danger-full-access'])).not.toContain('escalation available')
  924. })
  925. it('renders no sandbox marker for a plain failure under a sandboxed mode', () => {
  926. expect(renderResult(sandboxResult(false, 2))).not.toContain('[sandbox:')
  927. })
  928. it('bash_output reports a settled background denial with the same marker', async () => {
  929. const ctx = new Context()
  930. await ctx.plugin(SystemPrompt)
  931. await ctx.plugin(ToolRegistry)
  932. await ctx.plugin(AgentRegistry)
  933. await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
  934. await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
  935. const bash = ctx.bash as SandboxBashExecutor
  936. bash.internals = { spillDir }
  937. await ctx.plugin(ToolBash)
  938. const started = await call(ctx, 'bash', { command: 'echo "x: Permission denied" >&2; exit 1', description: 'test command', run_in_background: true })
  939. const id = text(started).match(/started background task (bash-\d+)/)![1]
  940. await bash.list().find(task => task.id === id)!.done
  941. const read = await call(ctx, 'bash_output', { task_id: id })
  942. expect(text(read)).toMatch(
  943. /\[status: completed, exit code: 1\]\n\[sandbox: file access denied under read-only mode\]\n\[sandbox: escalation available[^\n]+\]$/,
  944. )
  945. })
  946. it('a settled background denial renders no escalation hint without a confining executor (defensive arm)', async () => {
  947. // Structurally near-unreachable through the real stack — every confining
  948. // default advertises the static target set — but the read path guards
  949. // it anyway: an executor that reports no sandboxMode (fields never
  950. // advertised) whose task nonetheless carries denial facts must render
  951. // the marker without suggesting a lever the schema does not offer.
  952. class FactsOnlyExecutor extends BashExecutor {
  953. private readonly task: BashTask = {
  954. id: BashTaskId('bash-facts'),
  955. command: 'fake',
  956. status: 'completed',
  957. exitCode: 1,
  958. signal: null,
  959. done: Promise.resolve(),
  960. sandbox: { mode: 'read-only', denied: true },
  961. }
  962. resolve(request: BashExecRequest): BashExecSpec {
  963. return {
  964. command: request.command,
  965. workdir: request.workdir ?? process.cwd(),
  966. timeoutMs: request.timeoutMs ?? 0,
  967. ...request.signal ? { signal: request.signal } : {},
  968. owner: request.owner,
  969. sandboxMode: request.sandboxMode,
  970. }
  971. }
  972. run(): Promise<BashRunResult> { return Promise.reject(new Error('not used')) }
  973. start(): BashTask { return this.task }
  974. get(id: string): BashTask | undefined { return id === this.task.id ? this.task : undefined }
  975. list(): BashTask[] { return [this.task] }
  976. kill(): boolean { return false }
  977. ownerOf(): OwnerToken | undefined { return undefined }
  978. readOutput(): BashTaskRead {
  979. return { task: this.task, delta: '', lossy: false }
  980. }
  981. }
  982. const ctx = new Context()
  983. await ctx.plugin(SystemPrompt)
  984. await ctx.plugin(ToolRegistry)
  985. await ctx.plugin(AgentRegistry)
  986. await ctx.plugin(FactsOnlyExecutor)
  987. await ctx.plugin(ToolBash)
  988. const read = await call(ctx, 'bash_output', { task_id: 'bash-facts' })
  989. expect(text(read)).toMatch(/\[sandbox: file access denied under read-only mode\]$/)
  990. expect(text(read)).not.toContain('escalation available')
  991. })
  992. it('bash_output reports a settled background RUNNER failure as a sandbox problem, outranking the denial marker', async () => {
  993. // A provider whose wrap carries a runner-failure signature: the settled
  994. // task's stderr matching it means the sandbox itself broke and the
  995. // command never ran — even though the same stderr also carries denial
  996. // words (a runner's error text may contain them).
  997. class FakeProvider extends SandboxProvider {
  998. confine(argv: readonly string[]): ConfinedArgv {
  999. return { argv: [...argv], enforcement: 'full', denialSignatures: ['permission denied'], runnerFailureSignatures: ['fake-runner: '] }
  1000. }
  1001. }
  1002. const ctx = new Context()
  1003. await ctx.plugin(SystemPrompt)
  1004. await ctx.plugin(ToolRegistry)
  1005. await ctx.plugin(AgentRegistry)
  1006. await ctx.plugin(FakeProvider)
  1007. await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
  1008. const bash = ctx.bash as SandboxBashExecutor
  1009. bash.internals = { spillDir }
  1010. await ctx.plugin(ToolBash)
  1011. const started = await call(ctx, 'bash', { command: 'echo "fake-runner: cannot open rule path: /x: Permission denied" >&2; exit 125', description: 'test command', run_in_background: true })
  1012. const id = text(started).match(/started background task (bash-\d+)/)![1]
  1013. await bash.list().find(task => task.id === id)!.done
  1014. const read = await call(ctx, 'bash_output', { task_id: id })
  1015. expect(text(read)).toMatch(/\[sandbox: the sandbox runner itself failed under read-only mode — the command did not run; /)
  1016. expect(text(read)).toMatch(/this is a sandbox problem, not a command failure\]$/)
  1017. expect(text(read)).not.toContain('file access denied')
  1018. })
  1019. it('classifies an executable configured runner that refuses its profile before the command runs', async () => {
  1020. const signature = 'custom-runner-rejected'
  1021. const ctx = new Context()
  1022. await ctx.plugin(LocalSandboxProvider, {
  1023. runnerCommand: ['bash', '-c', `printf '${signature}\\n' >&2; exit 125`, 'custom-runner'],
  1024. runnerFailureSignatures: [signature],
  1025. })
  1026. await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
  1027. const bash = ctx.bash as SandboxBashExecutor
  1028. bash.internals = { spillDir }
  1029. await expect(bash.run(bash.resolve({ command: 'echo command-must-not-run' })))
  1030. .rejects.toMatchObject({ code: 'SANDBOX_UNAVAILABLE' })
  1031. const task = bash.start(bash.resolve({ command: 'echo command-must-not-run' }))
  1032. await task.done
  1033. expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full', runnerFailed: true })
  1034. })
  1035. it('reports a real denial end-to-end through the shipping sandbox executor', async () => {
  1036. const ctx = new Context()
  1037. await ctx.plugin(SystemPrompt)
  1038. await ctx.plugin(ToolRegistry)
  1039. await ctx.plugin(AgentRegistry)
  1040. await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
  1041. await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
  1042. const bash = ctx.bash as SandboxBashExecutor
  1043. bash.internals = { spillDir }
  1044. await ctx.plugin(ToolBash)
  1045. const lockedDir = join(mkdtempSync(join(tmpdir(), 'dsh-tool-bash-denied-')), 'locked')
  1046. mkdirSync(lockedDir)
  1047. chmodSync(lockedDir, 0o555)
  1048. const result = await call(ctx, 'bash', { command: `echo x > ${lockedDir}/f`, description: 'Write into a locked directory' })
  1049. expect(result.isError).toBe(false)
  1050. expect(text(result)).toMatch(
  1051. /denied under read-only mode\]\n\[sandbox: escalation available[^\n]+\]\n\[exit code: \d+\]$/,
  1052. )
  1053. })
  1054. })
  1055. describe('sandbox escalation (sandbox_permissions / justification)', () => {
  1056. /** Compose the real sandbox stack (passthrough runner) at a given default mode. */
  1057. async function setupSandboxed(mode?: 'read-only' | 'workspace-write' | 'danger-full-access', opts: { approval?: boolean; policy?: 'ask' | 'never' } = {}) {
  1058. const ctx = new Context()
  1059. await ctx.plugin(SystemPrompt)
  1060. await ctx.plugin(ToolRegistry)
  1061. await ctx.plugin(AgentRegistry)
  1062. await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
  1063. await ctx.plugin(SandboxBashExecutor, { graceMs: 200, ...mode !== undefined ? { mode } : {} })
  1064. const bash = ctx.bash as SandboxBashExecutor
  1065. bash.internals = { spillDir }
  1066. if (opts.approval === true) await ctx.plugin(ApprovalService, opts.policy !== undefined ? { policy: opts.policy } : {})
  1067. await ctx.plugin(ToolBash)
  1068. return { ctx, bash }
  1069. }
  1070. /** The registered bash tool's wire schema (what the model actually sees). */
  1071. function bashSchema(ctx: Context) {
  1072. const schema = ctx.tools.schemas().find(s => s.name === 'bash')
  1073. if (!schema) throw new Error('bash tool not registered')
  1074. return schema as unknown as { description: string; parameters: { properties: Record<string, { enum?: string[] }> } }
  1075. }
  1076. /**
  1077. * A fake agent whose session records appends — the approval audit surface.
  1078. * Seeded mid-turn: an escalating call always runs inside one, and request()
  1079. * enforces the enclosure.
  1080. */
  1081. function escalationAgent(events: Array<{ type: string; data: Record<string, unknown> }>): Agent {
  1082. return {
  1083. id: 'agent-esc',
  1084. session: {
  1085. header: { version: 0, id: 'sess-esc', createdAt: 0 },
  1086. events: [{ type: 'turn/start' }],
  1087. append: (type: string, data: Record<string, unknown>) => { events.push({ type, data }) },
  1088. },
  1089. } as unknown as Agent
  1090. }
  1091. let escCall = 0
  1092. function callAs(ctx: Context, agent: Agent | undefined, args: unknown) {
  1093. return ctx.tools.execute({ callId: CallId(`call-esc-${++escCall}`), name: 'bash', arguments: args, ...agent ? { agent } : {} })
  1094. }
  1095. const ESCALATE = { command: 'true', description: 'test escalation', sandbox_permissions: 'workspace-write', justification: 'the test needs it' }
  1096. it('advertises no escalation surface under a non-sandboxing executor', async () => {
  1097. const ctx = await setup()
  1098. expect(ctx.bash.sandboxMode).toBeUndefined()
  1099. const schema = bashSchema(ctx)
  1100. expect(schema.parameters.properties['sandbox_permissions']).toBeUndefined()
  1101. expect(schema.parameters.properties['justification']).toBeUndefined()
  1102. expect(schema.description).not.toContain('sanctioned exception')
  1103. })
  1104. it('advertises the full closed target vocabulary under any confining default', async () => {
  1105. // The enum is deliberately NOT default-relative: a session's effective
  1106. // mode is per-session and switchable, so every confining composition
  1107. // advertises every possible target — strict widening is checked at
  1108. // execution against the call's effective mode instead.
  1109. for (const mode of [undefined, 'workspace-write', 'danger-full-access'] as const) {
  1110. const { ctx } = await setupSandboxed(mode)
  1111. const schema = bashSchema(ctx)
  1112. expect(schema.parameters.properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
  1113. expect(schema.parameters.properties['justification']).toBeDefined()
  1114. expect(schema.description).toContain('sanctioned exception')
  1115. }
  1116. })
  1117. it('a non-widening request fails at execution with its own text and prompts no one', async () => {
  1118. const { ctx } = await setupSandboxed('danger-full-access', { approval: true })
  1119. const consulted = vi.fn()
  1120. ctx.on('approval/request', (_req, next) => { consulted(); return next() })
  1121. const result = await callAs(ctx, escalationAgent([]), { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'already wider' })
  1122. expect(result.isError).toBe(true)
  1123. expect(text(result)).toContain('not strictly wider than this call\'s current "danger-full-access" mode')
  1124. expect(consulted).not.toHaveBeenCalled()
  1125. })
  1126. it('rejects sandbox_permissions without a justification, and vice versa, and a blank justification', async () => {
  1127. const { ctx } = await setupSandboxed()
  1128. const missing = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write' })
  1129. expect(missing.isError).toBe(true)
  1130. expect(text(missing)).toContain('sandbox_permissions requires a justification')
  1131. const orphan = await callAs(ctx, undefined, { command: 'true', description: 'd', justification: 'why not' })
  1132. expect(orphan.isError).toBe(true)
  1133. expect(text(orphan)).toContain('only valid together with sandbox_permissions')
  1134. const blank = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: ' ' })
  1135. expect(blank.isError).toBe(true)
  1136. expect(text(blank)).toContain('expected a non-empty sentence')
  1137. })
  1138. it('the schema enum rejects a mode outside the target vocabulary before execute (registry-level, any caller)', async () => {
  1139. const { ctx } = await setupSandboxed()
  1140. const result = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'read-only', justification: 'narrow' })
  1141. expect(result.isError).toBe(true)
  1142. expect(text(result)).toContain('must be one of')
  1143. })
  1144. it('rejects an unadvertised sandbox_permissions injection under a non-sandboxing executor', async () => {
  1145. const ctx = await setup()
  1146. const result = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'sneaky' })
  1147. expect(result.isError).toBe(true)
  1148. expect(text(result)).toContain('not available in this composition')
  1149. })
  1150. it('fails closed with its own text when no approval service is composed', async () => {
  1151. const { ctx } = await setupSandboxed()
  1152. const result = await callAs(ctx, escalationAgent([]), ESCALATE)
  1153. expect(result.isError).toBe(true)
  1154. expect(text(result)).toContain('no approval service is composed')
  1155. })
  1156. it('fails closed with its own text for an agent-less escalating call', async () => {
  1157. const { ctx } = await setupSandboxed('read-only', { approval: true })
  1158. const result = await callAs(ctx, undefined, ESCALATE)
  1159. expect(result.isError).toBe(true)
  1160. expect(text(result)).toContain('no agent to route it through')
  1161. })
  1162. it('fails closed with its own text when the service has no answerer', async () => {
  1163. const { ctx } = await setupSandboxed('read-only', { approval: true })
  1164. const result = await callAs(ctx, escalationAgent([]), ESCALATE)
  1165. expect(result.isError).toBe(true)
  1166. expect(text(result)).toContain('no approval channel is available')
  1167. })
  1168. it('a grant runs THAT call under the wider mode — the denial marker names it — and lands the audit pair', async () => {
  1169. const { ctx } = await setupSandboxed('read-only', { approval: true })
  1170. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  1171. const events: Array<{ type: string; data: Record<string, unknown> }> = []
  1172. // A real unix denial under the passthrough runner: the marker's mode can
  1173. // only say workspace-write if the override actually rode the spec.
  1174. const lockedDir = join(mkdtempSync(join(tmpdir(), 'dsh-esc-denied-')), 'locked')
  1175. mkdirSync(lockedDir)
  1176. chmodSync(lockedDir, 0o555)
  1177. const result = await callAs(ctx, escalationAgent(events), {
  1178. command: `echo x > ${lockedDir}/f`,
  1179. description: 'write into a locked directory',
  1180. sandbox_permissions: 'workspace-write',
  1181. justification: 'must write outside the workspace',
  1182. })
  1183. expect(result.isError).toBe(false)
  1184. expect(text(result)).toMatch(/\[sandbox: file access denied under workspace-write mode\]/)
  1185. expect(events.map(e => e.type)).toEqual(['approval/asked', 'approval/decided'])
  1186. expect(events[0]?.data['toolName']).toBe('bash')
  1187. expect(events[0]?.data['reason']).toBe('escalate sandbox to workspace-write: must write outside the workspace')
  1188. expect(events[1]?.data['outcome']).toBe('allowed-once')
  1189. })
  1190. it('a granted background start settles with the wider mode\'s facts', async () => {
  1191. const { ctx, bash } = await setupSandboxed('read-only', { approval: true })
  1192. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  1193. const started = await callAs(ctx, escalationAgent([]), { ...ESCALATE, run_in_background: true })
  1194. expect(started.isError).toBe(false)
  1195. const id = text(started).match(/started background task (bash-\d+)/)?.[1]
  1196. const task = bash.list().find(t => t.id === id)
  1197. if (!task) throw new Error('escalated task not tracked')
  1198. await task.done
  1199. expect(task.sandbox).toMatchObject({ mode: 'workspace-write', denied: false })
  1200. })
  1201. it('a rejection denies with the user-said-no text and runs nothing', async () => {
  1202. const { ctx } = await setupSandboxed('read-only', { approval: true })
  1203. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('rejected'))
  1204. // A live (non-aborted) signal rides the execution: the gate threads it
  1205. // into the approval request so a turn cancellation can withdraw the ask.
  1206. const result = await ctx.tools.execute({
  1207. callId: CallId(`call-esc-${++escCall}`),
  1208. name: 'bash',
  1209. arguments: ESCALATE,
  1210. agent: escalationAgent([]),
  1211. signal: new AbortController().signal,
  1212. })
  1213. expect(result.isError).toBe(true)
  1214. expect(text(result)).toContain('the user rejected escalating this command to "workspace-write"')
  1215. })
  1216. it('a cancellation denies with the cancelled text', async () => {
  1217. const { ctx } = await setupSandboxed('read-only', { approval: true })
  1218. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('cancelled'))
  1219. const result = await callAs(ctx, escalationAgent([]), ESCALATE)
  1220. expect(result.isError).toBe(true)
  1221. expect(text(result)).toContain('approval for escalating to "workspace-write" was cancelled')
  1222. })
  1223. it('a rogue approval stand-in returning a non-vocabulary outcome hits the exhaustiveness backstop', async () => {
  1224. const { ctx } = await setupSandboxed()
  1225. ctx.provide('approval', { request: () => Promise.resolve('yolo') } as unknown as InstanceType<typeof ApprovalService>)
  1226. const result = await callAs(ctx, escalationAgent([]), ESCALATE)
  1227. expect(result.isError).toBe(true)
  1228. expect(text(result)).toContain('unreachable')
  1229. })
  1230. it('a never policy rejects an escalation deterministically without consulting any answerer', async () => {
  1231. // The live-session e.md case: the model requests escalation against a
  1232. // 'never' session — the prepend gate answers rejected before any
  1233. // interactive answerer, the fail-closed text is the ordinary rejection
  1234. // wording, and the audit pair still lands.
  1235. const { ctx } = await setupSandboxed('read-only', { approval: true, policy: 'never' })
  1236. const consulted = vi.fn()
  1237. ctx.on('approval/request', (_req, next) => { consulted(); return next() })
  1238. const events: Array<{ type: string; data: Record<string, unknown> }> = []
  1239. const result = await callAs(ctx, escalationAgent(events), ESCALATE)
  1240. expect(result.isError).toBe(true)
  1241. expect(text(result)).toContain('the user rejected escalating this command to "workspace-write"')
  1242. expect(consulted).not.toHaveBeenCalled()
  1243. expect(events.map(e => e.type)).toEqual(['approval/asked', 'approval/decided'])
  1244. expect(events[1]?.data).toMatchObject({ outcome: 'rejected' })
  1245. })
  1246. it('a plain call under a sandboxing executor never consults approval', async () => {
  1247. const { ctx } = await setupSandboxed('read-only', { approval: true })
  1248. const asked = vi.fn()
  1249. ctx.on('approval/request', (_req, next) => { asked(); return next() })
  1250. const result = await callAs(ctx, escalationAgent([]), { command: 'echo plain', description: 'plain run' })
  1251. expect(result.isError).toBe(false)
  1252. expect(text(result)).toContain('plain')
  1253. expect(asked).not.toHaveBeenCalled()
  1254. })
  1255. })
  1256. describe('per-session sandbox mode (the bash/sandbox-mode fold)', () => {
  1257. /** Compose the real sandbox stack (passthrough runner) at a given default mode. */
  1258. async function setupModal(mode: 'read-only' | 'workspace-write' | 'danger-full-access' = 'read-only', opts: { approval?: boolean } = {}) {
  1259. const ctx = new Context()
  1260. await ctx.plugin(SystemPrompt)
  1261. await ctx.plugin(ToolRegistry)
  1262. await ctx.plugin(AgentRegistry)
  1263. await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
  1264. await ctx.plugin(SandboxBashExecutor, { graceMs: 200, mode })
  1265. ;(ctx.bash as SandboxBashExecutor).internals = { spillDir }
  1266. if (opts.approval === true) await ctx.plugin(ApprovalService)
  1267. await ctx.plugin(ToolBash)
  1268. return ctx
  1269. }
  1270. /**
  1271. * An agent stand-in over a REAL Session — the stamping folds real events;
  1272. * the opened turn satisfies approval's enclosure precondition on escalating
  1273. * calls.
  1274. */
  1275. function sessionAgent(id: string): { agent: Agent; session: Session; injected: string[] } {
  1276. const session = new Session(SessionId(id))
  1277. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1278. const injected: string[] = []
  1279. const agent = {
  1280. id,
  1281. session,
  1282. inject: (content: { type: string; text: string }[]) => { injected.push(content[0]?.text ?? '') },
  1283. } as unknown as Agent
  1284. return { agent, session, injected }
  1285. }
  1286. let modeCall = 0
  1287. const callAs = (ctx: Context, agent: Agent | undefined, args: unknown) =>
  1288. ctx.tools.execute({ callId: CallId(`call-mode-${++modeCall}`), name: 'bash', arguments: args, ...agent ? { agent } : {} })
  1289. it('stamps calls with grant > session override > nothing (executor default)', async () => {
  1290. const ctx = await setupModal('read-only', { approval: true })
  1291. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  1292. const seen: (string | undefined)[] = []
  1293. const original = ctx.bash.resolve.bind(ctx.bash)
  1294. vi.spyOn(ctx.bash, 'resolve').mockImplementation((req) => {
  1295. seen.push(req.sandboxMode)
  1296. return original(req)
  1297. })
  1298. const { agent, session } = sessionAgent('sess-stamp-1')
  1299. const run = { command: 'true', description: 'stamp probe' }
  1300. await callAs(ctx, agent, run) // no override yet
  1301. setSandboxMode(session, 'workspace-write')
  1302. await callAs(ctx, agent, run) // standing override
  1303. await callAs(ctx, undefined, run) // agent-less caller: no session to fold
  1304. await callAs(ctx, agent, { ...run, sandbox_permissions: 'danger-full-access', justification: 'grant outranks override' })
  1305. expect(seen).toEqual([undefined, 'workspace-write', undefined, 'danger-full-access'])
  1306. })
  1307. it('escalates relative to the session effective mode, not the executor default (narrower override)', async () => {
  1308. // The blocker scenario: a workspace-write default with a read-only
  1309. // override — the sensible escalation is workspace-write, which a
  1310. // default-relative ladder could not even express. The static target
  1311. // vocabulary advertises it and the execution check accepts it as
  1312. // strictly wider than the CALL's effective (overridden) mode.
  1313. const ctx = await setupModal('workspace-write', { approval: true })
  1314. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  1315. const seen: (string | undefined)[] = []
  1316. const original = ctx.bash.resolve.bind(ctx.bash)
  1317. vi.spyOn(ctx.bash, 'resolve').mockImplementation((req) => {
  1318. seen.push(req.sandboxMode)
  1319. return original(req)
  1320. })
  1321. const { agent, session } = sessionAgent('sess-esc-narrow')
  1322. setSandboxMode(session, 'read-only')
  1323. const result = await callAs(ctx, agent, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'the override is narrower than the default' })
  1324. expect(result.isError).toBe(false)
  1325. expect(seen).toEqual(['workspace-write'])
  1326. })
  1327. it('a danger-full-access default still offers the lever to a narrower-switched session', async () => {
  1328. // Under the default-relative ladder these fields VANISHED (nothing is
  1329. // wider than the default), stranding a read-only-overridden session
  1330. // with no escalation path at all.
  1331. const ctx = await setupModal('danger-full-access', { approval: true })
  1332. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  1333. const schema = ctx.tools.schemas().find(t => t.name === 'bash') as unknown as { parameters: { properties: Record<string, { enum?: string[] }> } }
  1334. expect(schema.parameters.properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
  1335. const { agent, session } = sessionAgent('sess-esc-dfa')
  1336. setSandboxMode(session, 'read-only')
  1337. const result = await callAs(ctx, agent, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'confined by override under a wide default' })
  1338. expect(result.isError).toBe(false)
  1339. })
  1340. it('rejects a non-widening request against the OVERRIDDEN effective mode without prompting', async () => {
  1341. const ctx = await setupModal('read-only', { approval: true })
  1342. const consulted = vi.fn()
  1343. ctx.on('approval/request', (_req, next) => { consulted(); return next() })
  1344. const { agent, session } = sessionAgent('sess-esc-nonwide')
  1345. setSandboxMode(session, 'danger-full-access')
  1346. const result = await callAs(ctx, agent, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'already wider via override' })
  1347. expect(result.isError).toBe(true)
  1348. expect(text(result)).toContain('not strictly wider than this call\'s current "danger-full-access" mode')
  1349. expect(consulted).not.toHaveBeenCalled()
  1350. })
  1351. it('never stamps an override under a non-sandboxing executor (nothing honors it)', async () => {
  1352. const ctx = await setup()
  1353. const seen: (string | undefined)[] = []
  1354. const original = ctx.bash.resolve.bind(ctx.bash)
  1355. vi.spyOn(ctx.bash, 'resolve').mockImplementation((req) => {
  1356. seen.push(req.sandboxMode)
  1357. return original(req)
  1358. })
  1359. const { agent, session } = sessionAgent('sess-stamp-2')
  1360. setSandboxMode(session, 'danger-full-access')
  1361. await callAs(ctx, agent, { command: 'true', description: 'plain probe' })
  1362. expect(seen).toEqual([undefined])
  1363. })
  1364. })