tools.spec.ts 54 KB

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