tools.spec.ts 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. import { 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 } from '@deepseek-ai/dsh-bash'
  8. import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult } from '@deepseek-ai/dsh-bash'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry from '@deepseek-ai/dsh-agent'
  12. import type { Agent } from '@deepseek-ai/dsh-agent'
  13. import SessionStore from '@deepseek-ai/dsh-session'
  14. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  15. import TaskService from '@deepseek-ai/dsh-tasks'
  16. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  17. import ApprovalService from '@deepseek-ai/dsh-user-approval'
  18. import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
  19. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  20. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  21. import { processOutcome } from '../src/background.ts'
  22. import { renderProcessRead, renderResult } from '../src/render.ts'
  23. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-tool-bash-spec-'))
  24. /** Foreground-only harness: no task runtime (backgrounding fails loud here). */
  25. async function setup() {
  26. const ctx = new Context()
  27. await ctx.plugin(SystemPrompt)
  28. await ctx.plugin(ToolRegistry)
  29. await ctx.plugin(AgentRegistry)
  30. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  31. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  32. await ctx.plugin(ToolBash)
  33. return ctx
  34. }
  35. /** Full harness: the generic task runtime + its control surface, then the bash tool. */
  36. async function setupWithTasks() {
  37. const ctx = new Context()
  38. await ctx.plugin(SystemPrompt)
  39. await ctx.plugin(ToolRegistry)
  40. await ctx.plugin(AgentRegistry)
  41. await ctx.plugin(TaskService)
  42. await ctx.plugin(ToolTasks)
  43. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 })
  44. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  45. await ctx.plugin(ToolBash)
  46. return ctx
  47. }
  48. /**
  49. * Build a fake {@link Agent} whose session token is `sessionId`, give it a
  50. * dedicated lifecycle fiber for `Agent.ctx`, and register it in `ctx.agents`.
  51. * The agent id is deliberately different from the session token so a
  52. * wrong-field ownership match fails the test.
  53. */
  54. function registerFakeAgent(ctx: Context, sessionId: string, inject: (...args: unknown[]) => void = () => {}): Agent {
  55. const scopeFiber = ctx.plugin(() => {})
  56. const agent = {
  57. id: `agent-${sessionId}`,
  58. ctx: scopeFiber.ctx,
  59. inject,
  60. session: { header: { version: 0, id: sessionId, createdAt: 0 } },
  61. } as unknown as Agent
  62. ctx.agents.register(agent)
  63. return agent
  64. }
  65. let callCounter = 0
  66. function call(ctx: Context, name: string, args: unknown, agent?: Agent) {
  67. return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args, ...agent ? { agent } : {} })
  68. }
  69. function text(result: { content: { type: string; text?: string }[] }): string {
  70. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  71. }
  72. async function callUntilText(
  73. ctx: Context,
  74. name: string,
  75. args: unknown,
  76. expected: string,
  77. timeoutMs = 5_000,
  78. ): Promise<Awaited<ReturnType<typeof call>>> {
  79. const deadline = Date.now() + timeoutMs
  80. let last: Awaited<ReturnType<typeof call>> | undefined
  81. while (Date.now() < deadline) {
  82. last = await call(ctx, name, args)
  83. if (text(last).includes(expected)) return last
  84. await new Promise(resolve => setTimeout(resolve, 20))
  85. }
  86. throw new Error(`${name} output did not include ${JSON.stringify(expected)}; last text was ${JSON.stringify(last !== undefined ? text(last) : '')}`)
  87. }
  88. class RecordingSandboxExecutor extends BashExecutor {
  89. readonly modes: Array<string | undefined> = []
  90. override get sandboxMode() {
  91. return 'read-only' as const
  92. }
  93. resolve(request: BashExecRequest): BashExecSpec {
  94. return {
  95. command: request.command,
  96. workdir: request.workdir ?? process.cwd(),
  97. stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000,
  98. timeoutMs: request.timeoutMs ?? 1000,
  99. ...request.signal ? { signal: request.signal } : {},
  100. sandboxMode: request.sandboxMode ?? 'read-only',
  101. }
  102. }
  103. run(spec: BashExecSpec): Promise<BashRunResult> {
  104. this.modes.push(spec.sandboxMode)
  105. return Promise.resolve({
  106. exitCode: 0,
  107. signal: null,
  108. timedOut: false,
  109. aborted: false,
  110. timeoutMs: spec.timeoutMs,
  111. stdout: { text: 'ok', truncated: false },
  112. stderr: { text: '', truncated: false },
  113. sandbox: { mode: spec.sandboxMode ?? 'read-only', denied: false },
  114. })
  115. }
  116. start(spec: BashExecSpec): BashProcess {
  117. this.modes.push(spec.sandboxMode)
  118. return {
  119. status: 'completed',
  120. exitCode: 0,
  121. signal: null,
  122. done: Promise.resolve(),
  123. sandbox: { mode: spec.sandboxMode ?? 'read-only', denied: false },
  124. readOutput: () => ({ delta: '', lossy: false }),
  125. kill: () => false,
  126. }
  127. }
  128. }
  129. /** Test executor that records whether the background start boundary was crossed. */
  130. class CountingStartExecutor extends BashExecutor {
  131. starts = 0
  132. resolve(request: BashExecRequest): BashExecSpec {
  133. return {
  134. command: request.command,
  135. workdir: request.workdir ?? '/x',
  136. timeoutMs: request.timeoutMs ?? 0,
  137. stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000,
  138. sandboxMode: request.sandboxMode,
  139. }
  140. }
  141. run(): Promise<BashRunResult> { return Promise.reject(new Error('unused')) }
  142. start(): BashProcess {
  143. this.starts += 1
  144. return {
  145. status: 'completed',
  146. exitCode: 0,
  147. signal: null,
  148. done: Promise.resolve(),
  149. readOutput: () => ({ delta: '', lossy: false }),
  150. kill: () => false,
  151. }
  152. }
  153. }
  154. async function setupSandboxed(withApproval = false) {
  155. const ctx = new Context()
  156. await ctx.plugin(SystemPrompt)
  157. await ctx.plugin(ToolRegistry)
  158. await ctx.plugin(AgentRegistry)
  159. await ctx.plugin(TaskService)
  160. await ctx.plugin(ToolTasks)
  161. await ctx.plugin(RecordingSandboxExecutor)
  162. if (withApproval) await ctx.plugin(ApprovalService)
  163. await ctx.plugin(ToolBash)
  164. return { ctx, bash: ctx.bash as RecordingSandboxExecutor }
  165. }
  166. function sandboxAgent(mode?: 'read-only' | 'workspace-write' | 'danger-full-access', ctx?: Context): Agent {
  167. const events: Array<{ type: string; data?: Record<string, unknown> }> = [{ type: 'turn/start' }]
  168. if (mode !== undefined) events.push({ type: 'bash/sandbox-mode', data: { mode } })
  169. return {
  170. id: 'sandbox-agent',
  171. ...ctx === undefined ? {} : { ctx: ctx.plugin(() => {}).ctx },
  172. session: {
  173. header: { version: 0, id: 'sandbox-session', createdAt: 0 },
  174. events,
  175. append: (type: string, data: Record<string, unknown>) => {
  176. const event = { type, data }
  177. events.push(event)
  178. return event
  179. },
  180. },
  181. } as unknown as Agent
  182. }
  183. describe('bash tool', () => {
  184. it('returns stdout for a successful command', async () => {
  185. const ctx = await setup()
  186. const result = await call(ctx, 'bash', { command: 'echo hello', description: 'test command' })
  187. expect(result.isError).toBe(false)
  188. expect(text(result)).toBe('hello\n')
  189. })
  190. it('reports (no output) for silent commands', async () => {
  191. const ctx = await setup()
  192. const result = await call(ctx, 'bash', { command: 'true', description: 'test command' })
  193. expect(text(result)).toBe('(no output)')
  194. })
  195. it('marks stderr sections', async () => {
  196. const ctx = await setup()
  197. const result = await call(ctx, 'bash', { command: 'echo out; echo err >&2', description: 'test command' })
  198. expect(text(result)).toBe('out\n[stderr]\nerr\n')
  199. expect(result.isError).toBe(false)
  200. })
  201. it('reports non-zero exits without isError', async () => {
  202. const ctx = await setup()
  203. const result = await call(ctx, 'bash', { command: 'echo failing; exit 3', description: 'test command' })
  204. expect(result.isError).toBe(false)
  205. expect(text(result)).toBe('failing\n[exit code: 3]')
  206. })
  207. it('reports timeout kills with both markers (timeout first)', async () => {
  208. const ctx = await setup()
  209. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', timeoutMs: 100 })
  210. expect(result.isError).toBe(false)
  211. expect(text(result)).toBe('(no output)\n[timed out after 100ms]\n[killed by signal: SIGTERM]')
  212. })
  213. it('reports a timeout even when the command traps the signal and exits 0', async () => {
  214. // The signal-independent timeout marker: a trapped SIGTERM that exits 0
  215. // after our timer fired must NOT look like a clean success. (bash may
  216. // print "Terminated" to stderr for the killed sleep — environment
  217. // dependent — so assert the marker, not the exact body.)
  218. const ctx = await setup()
  219. const result = await call(ctx, 'bash', { command: 'trap "exit 0" TERM; sleep 60', description: 'test command', timeoutMs: 100 })
  220. expect(result.isError).toBe(false)
  221. expect(text(result)).toContain('[timed out after 100ms]')
  222. expect(text(result)).not.toContain('[exit code:')
  223. })
  224. it('reports truncation with the spill path', async () => {
  225. const ctx = new Context()
  226. await ctx.plugin(SystemPrompt)
  227. await ctx.plugin(ToolRegistry)
  228. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 })
  229. ;(ctx.bash as LocalBashExecutor).internals = { spillDir }
  230. await ctx.plugin(ToolBash)
  231. const result = await call(ctx, 'bash', { command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done', description: 'test command' })
  232. expect(text(result)).toContain('[output truncated; full output: ')
  233. expect(text(result)).toContain('line-0100')
  234. })
  235. it('honors workdir', async () => {
  236. const ctx = await setup()
  237. const result = await call(ctx, 'bash', { command: 'pwd', description: 'test command', workdir: '/tmp' })
  238. expect(text(result).trim()).toMatch(/\/tmp$/)
  239. })
  240. it('surfaces spawn failures as isError', async () => {
  241. const ctx = await setup()
  242. const result = await call(ctx, 'bash', { command: 'true', description: 'test command', workdir: '/nonexistent-dsh' })
  243. expect(result.isError).toBe(true)
  244. expect(text(result)).toMatch(/ENOENT/)
  245. })
  246. it('surfaces foreground aborts as isError', async () => {
  247. const ctx = await setup()
  248. const controller = new AbortController()
  249. const pending = ctx.tools.execute({
  250. callId: CallId('call-abort'),
  251. name: 'bash',
  252. arguments: { command: 'sleep 60', description: 'test command' },
  253. signal: controller.signal,
  254. })
  255. setTimeout(() => { controller.abort() }, 50)
  256. const result = await pending
  257. expect(result.isError).toBe(true)
  258. expect(text(result)).toMatch(/aborted/)
  259. })
  260. // Type and required-key violations are rejected by the harness
  261. // (defineTool validates against the SchemaSpec — the arg-validation RFC) before execute.
  262. it.each([
  263. [{}, /missing required property "command"/],
  264. [{ command: 42, description: 'd' }, /"command" must be a string/],
  265. [{ command: 'x' }, /missing required property "description"/],
  266. [{ command: 'x', description: 7 }, /"description" must be a string/],
  267. [{ command: 'x', description: 'd', timeoutMs: 'soon' }, /"timeoutMs" must be a number/],
  268. [{ command: 'x', description: 'd', workdir: 7 }, /"workdir" must be a string/],
  269. [{ command: 'x', description: 'd', run_in_background: 'yes' }, /"run_in_background" must be a boolean/],
  270. ])('rejects schema-invalid args %j', async (args, pattern) => {
  271. const ctx = await setup()
  272. const result = await call(ctx, 'bash', args)
  273. expect(result.isError).toBe(true)
  274. expect(text(result)).toMatch(pattern)
  275. })
  276. // Value constraints the SchemaSpec can't express stay in the tool body.
  277. it.each([
  278. [{ command: ' ', description: 'd' }, /invalid command/],
  279. [{ command: 'x', description: ' ' }, /invalid description/],
  280. [{ command: 'x', description: 'd', timeoutMs: -1 }, /invalid timeoutMs/],
  281. ])('rejects value-invalid args %j', async (args, pattern) => {
  282. const ctx = await setup()
  283. const result = await call(ctx, 'bash', args)
  284. expect(result.isError).toBe(true)
  285. expect(text(result)).toMatch(pattern)
  286. })
  287. it('rejects a non-JSON numeric argument before tool-specific validation', async () => {
  288. const ctx = await setup()
  289. const result = await call(ctx, 'bash', {
  290. command: 'x', description: 'd', timeoutMs: Number.NaN,
  291. })
  292. expect(result.isError).toBe(true)
  293. expect(text(result)).toContain('tool execution arguments must be losslessly JSON-serializable')
  294. })
  295. it('registers the bash schema with run_in_background exposed by default', async () => {
  296. const ctx = await setup()
  297. const schemas = ctx.tools.schemas()
  298. expect(schemas.map(schema => schema.name)).toEqual(['bash'])
  299. const bashSchema = schemas[0]!
  300. expect(bashSchema.parameters).toMatchObject({
  301. type: 'object',
  302. required: ['command', 'description'],
  303. })
  304. expect(Object.keys(bashSchema.parameters.properties as Record<string, unknown>))
  305. .toContain('run_in_background')
  306. expect(bashSchema.description).toContain('task_output')
  307. })
  308. it('contributes the exit-code habit as its prompt section (guidance the descriptions cannot carry)', async () => {
  309. const ctx = await setup()
  310. ctx.systemPrompt.section({ name: 'test:before-bash', order: 104, text: 'before' })
  311. ctx.systemPrompt.section({ name: 'test:after-bash', order: 106, text: 'after' })
  312. const assembly = await ctx.systemPrompt.assemble()
  313. const section = assembly.sections.find(s => s.name === 'tool:bash')
  314. expect(assembly.sections.map(s => s.name)).toEqual([
  315. 'harness:identity',
  316. 'deployment:persona',
  317. 'test:before-bash',
  318. 'tool:bash',
  319. 'test:after-bash',
  320. ])
  321. expect(section?.text).toContain('[exit code: N]')
  322. })
  323. it('unregisters everything when the plugin fiber is disposed (HMR safety)', async () => {
  324. const ctx = new Context()
  325. await ctx.plugin(SystemPrompt)
  326. await ctx.plugin(ToolRegistry)
  327. await ctx.plugin(LocalBashExecutor, {})
  328. const fiber = await ctx.plugin(ToolBash)
  329. expect(ctx.tools.schemas()).toHaveLength(1)
  330. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona', 'tool:bash'])
  331. await fiber.dispose()
  332. expect(ctx.tools.schemas()).toHaveLength(0)
  333. // Only the system-prompt plugin's own built-in sections remain.
  334. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona'])
  335. })
  336. it('tools depend on the executor: no registration without ctx.bash', async () => {
  337. const ctx = new Context()
  338. await ctx.plugin(SystemPrompt)
  339. await ctx.plugin(ToolRegistry)
  340. // inject: ['tools', 'bash'] keeps the plugin pending until bash exists.
  341. await ctx.plugin(ToolBash)
  342. expect(ctx.tools.schemas()).toHaveLength(0)
  343. await ctx.plugin(LocalBashExecutor, {})
  344. await new Promise(resolve => setTimeout(resolve, 0))
  345. expect(ctx.tools.schemas()).toHaveLength(1)
  346. })
  347. it('applies the built-in background default when apply() receives a bare config', async () => {
  348. // Bypasses the schemastery defaults on purpose: apply() must stand on its
  349. // own `?? true` fallback when embedded programmatically without the schema.
  350. const ctx = new Context()
  351. await ctx.plugin(SystemPrompt)
  352. await ctx.plugin(ToolRegistry)
  353. await ctx.plugin(LocalBashExecutor, {})
  354. ToolBash.apply(ctx, {})
  355. const schema = ctx.tools.schemas()[0]!
  356. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  357. .toContain('run_in_background')
  358. })
  359. })
  360. describe('background execution through the task runtime', () => {
  361. it('run_in_background acks with the task id, readable through the REAL task_output tool', async () => {
  362. const ctx = await setupWithTasks()
  363. const started = await call(ctx, 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true })
  364. expect(started.isError).toBe(false)
  365. expect(text(started)).toBe('started background task bash-1')
  366. const read = await callUntilText(ctx, 'task_output', { task_id: 'bash-1' }, 'bg-ok')
  367. expect(text(read)).toContain('bg-ok')
  368. // A later read reports the terminal outcome in the generic status line.
  369. const final = await callUntilText(ctx, 'task_output', { task_id: 'bash-1' }, '[status: completed, exit code: 0]')
  370. expect(final.isError).toBe(false)
  371. })
  372. it('a running background task is killable through the REAL task_kill tool', async () => {
  373. const ctx = await setupWithTasks()
  374. await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  375. const killed = await call(ctx, 'task_kill', { task_id: 'bash-1' })
  376. expect(text(killed)).toBe('requested cancellation of task bash-1')
  377. // The cancel reached the process handle; the task settles as killed with
  378. // the signal detail mapped by processOutcome.
  379. const final = await call(ctx, 'task_output', { task_id: 'bash-1', wait: true })
  380. expect(text(final)).toContain('[status: killed, signal: SIGTERM]')
  381. })
  382. it('a self-signal background exit is reported as killed through the REAL task_output tool', async () => {
  383. const ctx = await setupWithTasks()
  384. await call(ctx, 'bash', { command: 'kill -TERM $$', description: 'test command', run_in_background: true })
  385. const final = await call(ctx, 'task_output', { task_id: 'bash-1', wait: true })
  386. expect(text(final)).toContain('[status: killed, signal: SIGTERM]')
  387. })
  388. it('a background task started by an agent is registered with that agent as owner', async () => {
  389. // The producer must forward exec.agent as the task owner.
  390. const ctx = await setupWithTasks()
  391. const agent = registerFakeAgent(ctx, 'sess-owner')
  392. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true }, agent)
  393. expect(text(started)).toBe('started background task bash-1')
  394. const anon = await call(ctx, 'task_output', { task_id: 'bash-1' })
  395. expect(anon.isError).toBe(true)
  396. expect(text(anon)).toMatch(/belongs to another session/)
  397. const killed = await call(ctx, 'task_kill', { task_id: 'bash-1' }, agent)
  398. expect(killed.isError).toBe(false)
  399. await call(ctx, 'task_output', { task_id: 'bash-1', wait: true }, agent) // await settlement — no orphan
  400. })
  401. it('fails loud when the task runtime is not loaded', async () => {
  402. const ctx = await setup() // no TaskService / ToolTasks
  403. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  404. expect(result.isError).toBe(true)
  405. expect(text(result)).toContain('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
  406. })
  407. it('a pre-aborted call refuses to start: isError, no process spawned', async () => {
  408. const ctx = new Context()
  409. await ctx.plugin(SystemPrompt)
  410. await ctx.plugin(ToolRegistry)
  411. await ctx.plugin(AgentRegistry)
  412. await ctx.plugin(TaskService)
  413. await ctx.plugin(ToolTasks)
  414. await ctx.plugin(CountingStartExecutor)
  415. await ctx.plugin(ToolBash)
  416. const controller = new AbortController()
  417. controller.abort()
  418. const result = await ctx.tools.execute({
  419. callId: CallId('call-pre-aborted'),
  420. name: 'bash',
  421. arguments: { command: 'sleep 60', description: 'test command', run_in_background: true },
  422. signal: controller.signal,
  423. })
  424. expect(result.isError).toBe(true)
  425. expect(text(result)).toContain('command aborted')
  426. expect((ctx.bash as CountingStartExecutor).starts).toBe(0)
  427. })
  428. it('never spawns the process when tasks.start preflight throws (no orphan, by construction)', async () => {
  429. // With no control surface, task preflight fails before the executor can spawn.
  430. const ctx = new Context()
  431. await ctx.plugin(SystemPrompt)
  432. await ctx.plugin(ToolRegistry)
  433. await ctx.plugin(AgentRegistry)
  434. await ctx.plugin(TaskService)
  435. await ctx.plugin(CountingStartExecutor)
  436. await ctx.plugin(ToolBash)
  437. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  438. expect(result.isError).toBe(true)
  439. expect(text(result)).toContain('no control surface is attached')
  440. // Declare-then-execute: the failed preflight means no process ever ran.
  441. expect((ctx.bash as CountingStartExecutor).starts).toBe(0)
  442. })
  443. it('enableRunInBackground: false removes the parameter and flips the description', async () => {
  444. const ctx = new Context()
  445. await ctx.plugin(SystemPrompt)
  446. await ctx.plugin(ToolRegistry)
  447. await ctx.plugin(LocalBashExecutor, {})
  448. await ctx.plugin(ToolBash, { enableRunInBackground: false })
  449. const schema = ctx.tools.schemas().find(s => s.name === 'bash')!
  450. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  451. .toEqual(['command', 'description', 'timeoutMs', 'workdir'])
  452. expect(schema.description).toContain('Background execution is not available')
  453. expect(schema.description).not.toContain('run_in_background')
  454. // The registry-held definition agrees (schema and capability never disagree).
  455. const parameters = ctx.tools.get('bash')!.parameters as { properties: Record<string, unknown> }
  456. expect('run_in_background' in parameters.properties).toBe(false)
  457. // Schema omission is advertising; execution must also enforce the opt-out.
  458. const forced = await call(ctx, 'bash', { command: 'echo hi', description: 'test command', run_in_background: true })
  459. expect(forced.isError).toBe(true)
  460. expect(text(forced)).toContain('run_in_background is disabled for this deployment')
  461. const foreground = await call(ctx, 'bash', { command: 'echo hi', description: 'test command' })
  462. expect(foreground.isError).toBe(false)
  463. })
  464. })
  465. describe('sandbox escalation through the generic task producer', () => {
  466. const escalate = {
  467. command: 'true',
  468. description: 'test escalation',
  469. sandbox_permissions: 'workspace-write',
  470. justification: 'the command needs workspace writes',
  471. }
  472. it('advertises the sandbox fields and validates their pairing', async () => {
  473. const { ctx } = await setupSandboxed()
  474. const schema = ctx.tools.schemas().find(item => item.name === 'bash')!
  475. const properties = schema.parameters.properties as Record<string, { enum?: string[] }>
  476. expect(properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
  477. expect(schema.description).toContain('approval prompt')
  478. for (const args of [
  479. { command: 'true', description: 'd', sandbox_permissions: 'workspace-write' },
  480. { command: 'true', description: 'd', justification: 'why' },
  481. { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: ' ' },
  482. ]) {
  483. expect((await call(ctx, 'bash', args)).isError).toBe(true)
  484. }
  485. })
  486. it('rejects injected escalation without a sandbox and non-widening escalation without prompting', async () => {
  487. const plain = await setup()
  488. expect(text(await call(plain, 'bash', escalate))).toContain('not available in this composition')
  489. const { ctx } = await setupSandboxed(true)
  490. const prompted = vi.fn()
  491. ctx.on('approval/request', () => { prompted(); return Promise.resolve<ApprovalOutcome>('allowed-once') })
  492. const result = await call(ctx, 'bash', { ...escalate, sandbox_permissions: 'workspace-write' }, sandboxAgent('workspace-write'))
  493. expect(text(result)).toContain('not strictly wider')
  494. expect(prompted).not.toHaveBeenCalled()
  495. const malformed = sandboxAgent()
  496. ;(malformed.session.events as unknown as Array<{ type: string; data: { mode: string } }>).push({
  497. type: 'bash/sandbox-mode',
  498. data: { mode: 'unknown-mode' },
  499. })
  500. expect(text(await call(ctx, 'bash', escalate, malformed))).toContain('not strictly wider')
  501. })
  502. it('fails closed when approval cannot be routed', async () => {
  503. const withoutService = await setupSandboxed()
  504. expect(text(await call(withoutService.ctx, 'bash', escalate, sandboxAgent()))).toContain('no approval service')
  505. const withService = await setupSandboxed(true)
  506. expect(text(await call(withService.ctx, 'bash', escalate))).toContain('no agent to route')
  507. expect(text(await call(withService.ctx, 'bash', escalate, sandboxAgent()))).toContain('no approval channel')
  508. })
  509. it.each([
  510. ['rejected', 'user rejected'],
  511. ['cancelled', 'was cancelled'],
  512. ] as const)('maps an approval %s to its distinct failure', async (outcome, message) => {
  513. const { ctx, bash } = await setupSandboxed(true)
  514. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>(outcome))
  515. const result = await call(ctx, 'bash', escalate, sandboxAgent())
  516. expect(text(result)).toContain(message)
  517. expect(bash.modes).toEqual([])
  518. })
  519. it('runs a granted foreground or background call under the approved mode', async () => {
  520. const { ctx, bash } = await setupSandboxed(true)
  521. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  522. const agent = sandboxAgent(undefined, ctx)
  523. ctx.agents.register(agent)
  524. const foreground = await ctx.tools.execute({
  525. callId: CallId('sandbox-signal'),
  526. name: 'bash',
  527. arguments: escalate,
  528. agent,
  529. signal: new AbortController().signal,
  530. })
  531. expect(foreground.isError).toBe(false)
  532. const background = await call(ctx, 'bash', { ...escalate, run_in_background: true }, agent)
  533. expect(text(background)).toBe('started background task bash-1')
  534. expect(bash.modes).toEqual(['workspace-write', 'workspace-write'])
  535. })
  536. it('uses the session override for ordinary calls and evaluates widening against it', async () => {
  537. const { ctx, bash } = await setupSandboxed(true)
  538. const agent = sandboxAgent('workspace-write')
  539. await call(ctx, 'bash', { command: 'true', description: 'ordinary' }, agent)
  540. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  541. await call(ctx, 'bash', { ...escalate, sandbox_permissions: 'danger-full-access' }, agent)
  542. expect(bash.modes).toEqual(['workspace-write', 'danger-full-access'])
  543. })
  544. it('keeps the exhaustiveness backstop for a rogue approval implementation', async () => {
  545. const { ctx } = await setupSandboxed(true)
  546. ctx.approval.request = () => Promise.resolve('rogue' as ApprovalOutcome)
  547. const result = await call(ctx, 'bash', escalate, sandboxAgent())
  548. expect(text(result)).toContain('unreachable variant in ApprovalOutcome')
  549. })
  550. })
  551. describe('renderProcessRead', () => {
  552. const base: BashProcessRead = { delta: 'out\n', lossy: false }
  553. it('returns the delta verbatim for a lossless read', () => {
  554. expect(renderProcessRead(base)).toBe('out\n')
  555. expect(renderProcessRead({ delta: '', lossy: false })).toBe('')
  556. })
  557. it('appends the loss notice with the available spill paths', () => {
  558. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log' }))
  559. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log]')
  560. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log', stderrSpillPath: '/spill/err.log' }))
  561. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log, /spill/err.log]')
  562. })
  563. it('reports (unavailable) when a lossy read has no safe spill path', () => {
  564. expect(renderProcessRead({ ...base, lossy: true }))
  565. .toBe('out\n[some output was dropped from memory; full output: (unavailable)]')
  566. })
  567. it('an empty lossy delta is the notice alone', () => {
  568. expect(renderProcessRead({ delta: '', lossy: true, stderrSpillPath: '/spill/err.log' }))
  569. .toBe('[some output was dropped from memory; full output: /spill/err.log]')
  570. })
  571. it('inserts the separating newline only when the delta lacks one', () => {
  572. expect(renderProcessRead({ delta: 'tail', lossy: true }))
  573. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  574. expect(renderProcessRead({ delta: 'tail\n', lossy: true }))
  575. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  576. })
  577. it('appends settled sandbox denial and runner-failure facts', () => {
  578. expect(renderProcessRead(base, { mode: 'read-only', denied: true }, ['workspace-write']))
  579. .toContain('[sandbox: escalation available')
  580. expect(renderProcessRead({ delta: 'tail', lossy: false }, { mode: 'read-only', denied: true }))
  581. .toBe('tail\n[sandbox: file access denied under read-only mode]')
  582. const runner = renderProcessRead(
  583. { delta: '', lossy: false },
  584. { mode: 'workspace-write', denied: true, runnerFailed: true },
  585. ['danger-full-access'],
  586. )
  587. expect(runner).toContain('sandbox runner itself failed under workspace-write mode')
  588. expect(runner).not.toContain('file access denied')
  589. })
  590. })
  591. describe('processOutcome', () => {
  592. function settled(over: Partial<BashProcess>): BashProcess {
  593. return {
  594. status: 'completed',
  595. exitCode: 0,
  596. signal: null,
  597. done: Promise.resolve(),
  598. readOutput: () => ({ delta: '', lossy: false }),
  599. kill: () => false,
  600. ...over,
  601. }
  602. }
  603. it('maps a signal-killed process to killed with the signal detail', () => {
  604. expect(processOutcome(settled({ status: 'killed', signal: 'SIGTERM' })))
  605. .toEqual({ status: 'killed', detail: 'signal: SIGTERM' })
  606. })
  607. it('maps a killed process without a recorded signal (kill raced exit / spawn failure)', () => {
  608. expect(processOutcome(settled({ status: 'killed', exitCode: null })))
  609. .toEqual({ status: 'killed', detail: 'killed before exit' })
  610. })
  611. it('maps a completed process to its exit code', () => {
  612. expect(processOutcome(settled({ exitCode: 3 })))
  613. .toEqual({ status: 'completed', detail: 'exit code: 3' })
  614. })
  615. it('defensively reads a null exit code as 0 (handle shapes from other executors)', () => {
  616. expect(processOutcome(settled({ exitCode: null })))
  617. .toEqual({ status: 'completed', detail: 'exit code: 0' })
  618. })
  619. })
  620. describe('session-cwd routing (per-session workdir)', () => {
  621. // An agent whose session header carries a cwd (what session/new records).
  622. const agentInCwd = (cwd: string) =>
  623. ({ inject: () => undefined, session: { header: { version: 0, id: 'c', createdAt: 0, cwd } } }) as unknown as Agent
  624. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  625. const ctx = await setup()
  626. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  627. expect(text(result).trim()).toMatch(/\/tmp$/)
  628. })
  629. it('an explicit absolute workdir overrides the session cwd', async () => {
  630. const ctx = await setup()
  631. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: '/tmp' }, agentInCwd('/'))
  632. expect(text(result).trim()).toMatch(/\/tmp$/)
  633. })
  634. it('a relative workdir is resolved against the session cwd', async () => {
  635. const ctx = await setup()
  636. // session cwd /usr + relative 'bin' → /usr/bin
  637. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: 'bin' }, agentInCwd('/usr'))
  638. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  639. })
  640. it('two sessions with different cwds each run bash in their own dir', async () => {
  641. const ctx = await setup()
  642. const inUsr = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/usr'))
  643. const inTmp = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  644. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  645. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  646. })
  647. it('falls back to the executor default when the agent has no session cwd', async () => {
  648. const ctx = await setup()
  649. // No exec.agent at all → executor uses its config/process.cwd() default.
  650. const result = await ctx.tools.execute({ callId: CallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  651. expect(result.isError).toBe(false)
  652. expect(text(result).trim().length).toBeGreaterThan(0)
  653. })
  654. })
  655. describe('renderResult', () => {
  656. const base = {
  657. exitCode: 0 as number | null,
  658. signal: null as NodeJS.Signals | null,
  659. timedOut: false,
  660. aborted: false,
  661. timeoutMs: 1000,
  662. stdout: { text: '', truncated: false },
  663. stderr: { text: '', truncated: false },
  664. }
  665. it('renders stderr-only output without a stdout prefix', () => {
  666. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  667. .toBe('[stderr]\nerr\n')
  668. })
  669. it('adds a separator when stdout does not end with a newline', () => {
  670. expect(renderResult({
  671. ...base,
  672. stdout: { text: 'out', truncated: false },
  673. stderr: { text: 'err', truncated: false },
  674. })).toBe('out\n[stderr]\nerr')
  675. })
  676. it('appends exit-code markers after a newline for unterminated output', () => {
  677. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  678. .toBe('x\n[exit code: 7]')
  679. })
  680. it('renders signal kills without the timeout marker when not timed out', () => {
  681. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  682. .toBe('(no output)\n[killed by signal: SIGKILL]')
  683. })
  684. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  685. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  686. .toBe('(no output)\n[timed out after 1000ms]')
  687. })
  688. it('orders the timeout marker before a kill marker', () => {
  689. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  690. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  691. })
  692. it('notes truncation with a fallback when the spill path is missing', () => {
  693. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  694. .toBe('tail\n[output truncated; full output: (unavailable)]')
  695. })
  696. it('reports sandbox denials before exit status and hints only when escalation is advertised', () => {
  697. const result: BashRunResult = {
  698. exitCode: 1,
  699. signal: null,
  700. timedOut: false,
  701. aborted: false,
  702. timeoutMs: 1000,
  703. stdout: { text: '', truncated: false },
  704. stderr: { text: 'denied', truncated: false },
  705. sandbox: { mode: 'read-only', denied: true },
  706. }
  707. expect(renderResult(result)).toMatch(/denied under read-only mode\]\n\[exit code: 1\]$/)
  708. expect(renderResult(result, ['workspace-write'])).toContain('[sandbox: escalation available')
  709. expect(renderResult({ ...result, sandbox: { mode: 'read-only', denied: false } }, ['workspace-write']))
  710. .not.toContain('[sandbox:')
  711. })
  712. })
  713. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  714. it('bash presentCall: a foreground run is a terminal card (command title, description, workdir → cwd absolute or relative)', async () => {
  715. const ctx = await setup()
  716. // No explicit workdir → a terminal card with no cwd (the UI bridge fills the
  717. // session cwd it owns; the pure presenter can't see it).
  718. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  719. .toEqual({ card: 'terminal', title: 'ls -la src', description: 'List files in src' })
  720. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  721. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  722. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: '/tmp/x' })
  723. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  724. // the session cwd, matching where execution runs) — not dropped.
  725. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  726. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: 'sub' })
  727. })
  728. it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => {
  729. const ctx = await setup()
  730. const present = ctx.tools.get('bash')!.presentResult!(
  731. { command: 'echo hi', description: 'echo' },
  732. { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false },
  733. )
  734. // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer
  735. // needs; the bridge derives the fenced fallback. exitCode is parsed back from
  736. // the [exit code: N] marker.
  737. expect(present).toEqual({ card: 'terminal', output: 'hi\n[exit code: 0]\n\n', exitCode: 0 })
  738. })
  739. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  740. const ctx = await setup()
  741. const args = { command: 'x', description: 'x' }
  742. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  743. expect(nonzero).toEqual({ card: 'terminal', output: 'oops\n[exit code: 3]', exitCode: 3 })
  744. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  745. expect(killed).toEqual({ card: 'terminal', output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' })
  746. })
  747. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  748. const ctx = await setup()
  749. const present = ctx.tools.get('bash')!
  750. // For each renderResult outcome, the rendered text fed back through
  751. // presentResult recovers the matching structured exit — the parse and the
  752. // marker emission co-evolve in one file, so this pins the pair.
  753. const base = {
  754. aborted: false,
  755. timeoutMs: 1000,
  756. stdout: { text: 'out', truncated: false },
  757. stderr: { text: '', truncated: false },
  758. }
  759. const cases = [
  760. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  761. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  762. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  763. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  764. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  765. ]
  766. for (const c of cases) {
  767. const rendered = renderResult(c.result)
  768. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  769. // Drop card + output; the remaining fields are the parsed exit.
  770. const { card: _c, output: _o, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string }
  771. expect(exit).toEqual(c.expect)
  772. }
  773. })
  774. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  775. const ctx = await setup()
  776. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  777. // A successful command may print marker-like text. A clean result appends no marker or
  778. // newline; parsing requires the leading newline emitted for real markers, so this stays exit 0.
  779. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  780. expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 })
  781. // Same for a fake signal marker with no leading newline.
  782. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  783. expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 })
  784. })
  785. it('bash presentCall/presentResult: a run_in_background call is a generic card and its ack carries no exit pill', async () => {
  786. const ctx = await setup()
  787. // The background start returns a task-id ack, not a streamed run — a generic
  788. // execute card with the command as rawInput and the description as content.
  789. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  790. expect(call).toEqual({ card: 'generic', title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  791. // The ack result is a generic fenced-text card — no terminal output / exit pill.
  792. const result = ctx.tools.get('bash')!.presentResult!(
  793. { command: 'sleep 100', description: 'wait', run_in_background: true },
  794. { content: [{ type: 'text', text: 'started background task bash-1' }], isError: false },
  795. )
  796. expect(result).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\nstarted background task bash-1\n```' }] })
  797. })
  798. it('bash presentResult: an isError result is a generic card (no real process exit to report)', async () => {
  799. const ctx = await setup()
  800. // A spawn failure / abort has no process exit — the body is an error message,
  801. // not renderResult output, so a generic fenced card, no terminal output/exit.
  802. const out = ctx.tools.get('bash')!.presentResult!(
  803. { command: 'x', description: 'x' },
  804. { content: [{ type: 'text', text: 'command aborted' }], isError: true },
  805. )
  806. expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ncommand aborted\n```' }] })
  807. })
  808. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  809. const ctx = await setup()
  810. const present = ctx.tools.get('bash')!.presentResult!(
  811. { command: 'x', description: 'x' },
  812. { content: [{ type: 'reasoning', text: 'unexpected' }], isError: false },
  813. )
  814. expect(present).toBeUndefined()
  815. })
  816. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  817. const ctx = await setup()
  818. const args = { command: 'x', description: 'x' }
  819. // Empty content (no block) and multi-block content both fall through.
  820. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  821. expect(ctx.tools.get('bash')!.presentResult!(args, {
  822. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  823. isError: false,
  824. })).toBeUndefined()
  825. })
  826. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  827. const ctx = await setup()
  828. // `defineTool` soft-validates replayed logged args before presentation. Invalid shapes return
  829. // undefined for generic UI rendering rather than throwing; `presentCall` accepts `unknown`.
  830. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  831. })
  832. })
  833. describe('the model-facing bash tool builds its request from named args only (no {...args} forward)', () => {
  834. const recordingDshHome = join(spillDir, 'dsh-home')
  835. /**
  836. * Records every {@link BashExecRequest} the consumer hands to `resolve()`, so a
  837. * test can assert what the model-facing tool DID and DID NOT forward. The `bash`
  838. * tool does not expose trusted-plugin fields (`stdoutMaxBytes`, `stdin`, or
  839. * `env`) as parameters, so it must build its request from named args only and
  840. * never spread unknown tool-call keys into it. This guard's job is to catch a
  841. * future refactor that blindly forwards `...args` — which would silently thread
  842. * model input into the post-scrub `env` merge or per-run capture budget — NOT
  843. * to defend a trust boundary
  844. * (the credential scrub in dsh-bash-local is the security control; see the
  845. * bash-stdin-env RFC). Foreground `run()` returns a canned result; `start()`
  846. * hands back an already-settled fake handle so the task registration completes.
  847. */
  848. class RecordingBashExecutor extends BashExecutor {
  849. readonly requests: BashExecRequest[] = []
  850. resolve(request: BashExecRequest): BashExecSpec {
  851. this.requests.push(request)
  852. return {
  853. command: request.command,
  854. workdir: request.workdir ?? process.cwd(),
  855. timeoutMs: request.timeoutMs ?? 0,
  856. stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000,
  857. ...request.signal ? { signal: request.signal } : {},
  858. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  859. ...request.env !== undefined ? { env: request.env } : {},
  860. ...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {},
  861. sandboxMode: request.sandboxMode,
  862. }
  863. }
  864. run(): Promise<BashRunResult> {
  865. return Promise.resolve({
  866. exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 0,
  867. stdout: { text: 'ok', truncated: false }, stderr: { text: '', truncated: false },
  868. })
  869. }
  870. start(): BashProcess {
  871. return {
  872. status: 'completed',
  873. exitCode: 0,
  874. signal: null,
  875. done: Promise.resolve(),
  876. readOutput: () => ({ delta: '', lossy: false }),
  877. kill: () => false,
  878. }
  879. }
  880. }
  881. async function setupRecording(withJsonl = false) {
  882. const ctx = new Context()
  883. await ctx.plugin(SystemPrompt)
  884. await ctx.plugin(ToolRegistry)
  885. await ctx.plugin(AgentRegistry)
  886. if (withJsonl) {
  887. await ctx.plugin(SessionStore)
  888. await ctx.plugin(SessionPersistenceJsonl, { root: join(spillDir, 'jsonl') })
  889. }
  890. await ctx.plugin(TaskService)
  891. await ctx.plugin(ToolTasks)
  892. await ctx.plugin(RecordingBashExecutor)
  893. await ctx.plugin(ToolBash, { dshHome: recordingDshHome })
  894. return { ctx, bash: ctx.bash as RecordingBashExecutor }
  895. }
  896. it('describes the managed harness environment namespace to the model', async () => {
  897. const { ctx } = await setupRecording()
  898. const description = ctx.tools.get('bash')?.description ?? ''
  899. expect(description).toContain('$DSH_*')
  900. expect(description).not.toContain('DSH_SESSION_JSONL')
  901. })
  902. it('injects the session id and JSONL target path into a foreground request', async () => {
  903. const { ctx, bash } = await setupRecording(true)
  904. const agent = registerFakeAgent(ctx, 'request-fg', () => undefined)
  905. const path = ctx.sessionPersistence.locate(agent.session.header)?.path
  906. await ctx.tools.execute({
  907. callId: CallId('session-env-fg'),
  908. name: 'bash',
  909. arguments: { command: 'true', description: 'run command' },
  910. agent,
  911. })
  912. expect(bash.requests[0]?.dshEnv).toEqual({
  913. DSH_HOME: recordingDshHome,
  914. DSH_SESSION_ID: 'request-fg',
  915. DSH_SESSION_JSONL: path,
  916. DSH_SHELL: '1',
  917. })
  918. })
  919. it('injects the same trusted variables into a background request without forwarding model env', async () => {
  920. const { ctx, bash } = await setupRecording(true)
  921. const agent = registerFakeAgent(ctx, 'request-bg', () => undefined)
  922. const path = ctx.sessionPersistence.locate(agent.session.header)?.path
  923. await ctx.tools.execute({
  924. callId: CallId('session-env-bg'),
  925. name: 'bash',
  926. arguments: {
  927. command: 'sleep 1',
  928. description: 'run command',
  929. run_in_background: true,
  930. env: { DSH_SESSION_ID: 'spoofed', DSH_SESSION_JSONL: '/tmp/spoofed' },
  931. },
  932. agent,
  933. })
  934. expect(bash.requests[0]?.env).toBeUndefined()
  935. expect(bash.requests[0]?.dshEnv).toEqual({
  936. DSH_HOME: recordingDshHome,
  937. DSH_SESSION_ID: 'request-bg',
  938. DSH_SESSION_JSONL: path,
  939. DSH_SHELL: '1',
  940. })
  941. })
  942. it('injects built-ins and the stable session id when no JSONL locator is available', async () => {
  943. const { ctx, bash } = await setupRecording()
  944. const agent = registerFakeAgent(ctx, 'request-id-only', () => undefined)
  945. const ambient = process.env.DSH_SESSION_ID
  946. await ctx.tools.execute({
  947. callId: CallId('session-env-id-only'),
  948. name: 'bash',
  949. arguments: { command: 'true', description: 'run command' },
  950. agent,
  951. })
  952. expect(bash.requests[0]?.dshEnv).toEqual({
  953. DSH_HOME: recordingDshHome,
  954. DSH_SESSION_ID: 'request-id-only',
  955. DSH_SHELL: '1',
  956. })
  957. expect(process.env.DSH_SESSION_ID).toBe(ambient)
  958. })
  959. it('keeps parent and child agent session environments isolated', async () => {
  960. const { ctx, bash } = await setupRecording(true)
  961. const parent = registerFakeAgent(ctx, 'request-parent', () => undefined)
  962. const child = registerFakeAgent(ctx, 'request-child', () => undefined)
  963. for (const [callId, agent] of [['parent', parent], ['child', child]] as const) {
  964. await ctx.tools.execute({
  965. callId: CallId(`session-env-${callId}`),
  966. name: 'bash',
  967. arguments: { command: 'true', description: 'run command' },
  968. agent,
  969. })
  970. }
  971. expect(bash.requests.map(request => request.dshEnv)).toEqual([
  972. {
  973. DSH_HOME: recordingDshHome,
  974. DSH_SESSION_ID: 'request-parent',
  975. DSH_SESSION_JSONL: ctx.sessionPersistence.locate(parent.session.header)?.path,
  976. DSH_SHELL: '1',
  977. },
  978. {
  979. DSH_HOME: recordingDshHome,
  980. DSH_SESSION_ID: 'request-child',
  981. DSH_SESSION_JSONL: ctx.sessionPersistence.locate(child.session.header)?.path,
  982. DSH_SHELL: '1',
  983. },
  984. ])
  985. expect(bash.requests[0]?.dshEnv?.DSH_SESSION_JSONL).not.toBe(bash.requests[1]?.dshEnv?.DSH_SESSION_JSONL)
  986. })
  987. it('does not forward trusted-only fields even when the model includes them as extra arguments', async () => {
  988. const { ctx, bash } = await setupRecording()
  989. // Unknown `env` and `stdin` keys are ignored by the schema and named request construction.
  990. // This preserves the request shape; it is not a security boundary because shell syntax can
  991. // already set environment variables or feed stdin.
  992. await ctx.tools.execute({
  993. callId: CallId('no-forward-1'),
  994. name: 'bash',
  995. arguments: {
  996. command: 'echo hi',
  997. description: 'echo',
  998. env: { SNEAKY_API_KEY: 'leak' },
  999. stdin: 'malicious payload',
  1000. stdoutMaxBytes: 999_999,
  1001. },
  1002. })
  1003. expect(bash.requests).toHaveLength(1)
  1004. const request = bash.requests[0]!
  1005. expect(request.command).toBe('echo hi')
  1006. expect('env' in request).toBe(false)
  1007. expect('stdin' in request).toBe(false)
  1008. expect('stdoutMaxBytes' in request).toBe(false)
  1009. })
  1010. it('a background bash call likewise carries no trusted-only fields', async () => {
  1011. const { ctx, bash } = await setupRecording()
  1012. const result = await ctx.tools.execute({
  1013. callId: CallId('no-forward-2'),
  1014. name: 'bash',
  1015. arguments: {
  1016. command: 'sleep 1',
  1017. description: 'sleep',
  1018. run_in_background: true,
  1019. env: { TOKEN: 'leak' },
  1020. stdin: 'x',
  1021. stdoutMaxBytes: 999_999,
  1022. },
  1023. })
  1024. // The call really went down the background path (the recorder sees the real
  1025. // request the consumer built, so the absent env/stdin below is a real
  1026. // negative, not a recorder that drops everything).
  1027. expect(text(result)).toBe('started background task bash-1')
  1028. expect(bash.requests).toHaveLength(1)
  1029. const request = bash.requests[0]!
  1030. expect(request.command).toBe('sleep 1')
  1031. expect('env' in request).toBe(false)
  1032. expect('stdin' in request).toBe(false)
  1033. expect('stdoutMaxBytes' in request).toBe(false)
  1034. })
  1035. })