tools.spec.ts 75 KB

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