tools.spec.ts 72 KB

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