tools.spec.ts 56 KB

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