tools.spec.ts 53 KB

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