tools.spec.ts 55 KB

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