tools.spec.ts 71 KB

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