tools.spec.ts 55 KB

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