tools.spec.ts 52 KB

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