1
0

tools.spec.ts 73 KB

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