tools.spec.ts 71 KB

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