tools.spec.ts 73 KB

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