tools.spec.ts 71 KB

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