tools.spec.ts 73 KB

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