tools.spec.ts 76 KB

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