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