tools.spec.ts 55 KB

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