tools.spec.ts 56 KB

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