tools.spec.ts 73 KB

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