tools.spec.ts 77 KB

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