tools.spec.ts 77 KB

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