tools.spec.ts 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { Context } from '@deepseek-ai/cordis'
  6. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  7. import { ShellExecutor } from '@deepseek-ai/dsh-shell'
  8. import type { ShellExecRequest, ShellExecSpec, ShellProcess, ShellProcessRead, ShellRunResult } from '@deepseek-ai/dsh-shell'
  9. import SystemPrompt, { FIRST_PARTY_SECTION_ORDER } 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: ToolCallId(`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: ToolCallId('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({
  348. name: 'test:before-bash',
  349. order: FIRST_PARTY_SECTION_ORDER.TOOL_BASH - 10,
  350. text: 'before',
  351. })
  352. ctx.systemPrompt.section({
  353. name: 'test:after-bash',
  354. order: FIRST_PARTY_SECTION_ORDER.TOOL_BASH + 10,
  355. text: 'after',
  356. })
  357. const assembly = await ctx.systemPrompt.assemble()
  358. const section = assembly.sections.find(s => s.name === 'tool:bash')
  359. expect(assembly.sections.map(s => s.name)).toEqual([
  360. 'harness:identity',
  361. 'deployment:persona',
  362. 'test:before-bash',
  363. 'tool:bash',
  364. 'test:after-bash',
  365. ])
  366. expect(section?.text).toContain('[exit code: N]')
  367. })
  368. it('unregisters everything when the plugin fiber is disposed (HMR safety)', async () => {
  369. const ctx = new Context()
  370. await ctx.plugin(SystemPrompt)
  371. await ctx.plugin(ToolRuntime)
  372. await ctx.plugin(LocalSubprocessRuntime)
  373. await ctx.plugin(LocalBashExecutor, {})
  374. await ctx.plugin(BashEnvPlugin)
  375. const fiber = await ctx.plugin(ToolBash)
  376. expect(ctx.tools.schemas()).toHaveLength(1)
  377. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona', 'tool:bash'])
  378. await fiber.dispose()
  379. expect(ctx.tools.schemas()).toHaveLength(0)
  380. // Only the system-prompt plugin's own built-in sections remain.
  381. expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona'])
  382. })
  383. it('tools depend on the executor: no registration without ctx.shell', async () => {
  384. const ctx = new Context()
  385. await ctx.plugin(SystemPrompt)
  386. await ctx.plugin(ToolRuntime)
  387. // inject: ['tools', 'bash'] keeps the plugin pending until bash exists.
  388. await ctx.plugin(BashEnvPlugin)
  389. await ctx.plugin(ToolBash)
  390. expect(ctx.tools.schemas()).toHaveLength(0)
  391. await ctx.plugin(LocalSubprocessRuntime)
  392. await ctx.plugin(LocalBashExecutor, {})
  393. await new Promise(resolve => setTimeout(resolve, 0))
  394. expect(ctx.tools.schemas()).toHaveLength(1)
  395. })
  396. it('applies the built-in background default when apply() receives a bare config', async () => {
  397. // Bypasses the schemastery defaults on purpose: apply() must stand on its
  398. // own `?? true` fallback when embedded programmatically without the schema.
  399. const ctx = new Context()
  400. await ctx.plugin(SystemPrompt)
  401. await ctx.plugin(ToolRuntime)
  402. await ctx.plugin(LocalSubprocessRuntime)
  403. await ctx.plugin(LocalBashExecutor, {})
  404. ToolBash.apply(ctx, {})
  405. const schema = ctx.tools.schemas()[0]!
  406. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  407. .toContain('run_in_background')
  408. })
  409. })
  410. describe('background execution through the job runtime', () => {
  411. it('run_in_background acks with the job id, readable through the REAL job_output tool', async () => {
  412. const ctx = await setupWithTasks()
  413. const started = await call(ctx, 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true })
  414. expect(started.isError).toBe(false)
  415. if (started.isError) throw new Error('expected background bash success')
  416. expect(started.value).toEqual({ kind: 'background', jobId: 'bash-1' })
  417. expect(text(started)).toBe('started background job bash-1')
  418. const read = await callUntilText(ctx, 'job_output', { job_id: 'bash-1' }, 'bg-ok')
  419. expect(text(read)).toContain('bg-ok')
  420. // A later read reports the terminal outcome in the generic status line.
  421. const final = await callUntilText(ctx, 'job_output', { job_id: 'bash-1' }, '[status: completed, exit code: 0]')
  422. expect(final.isError).toBe(false)
  423. })
  424. it('a running background job is killable through the REAL job_kill tool', async () => {
  425. const ctx = await setupWithTasks()
  426. await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  427. const killed = await call(ctx, 'job_kill', { job_id: 'bash-1' })
  428. expect(text(killed)).toBe('requested cancellation of job bash-1')
  429. // The cancel reached the process handle; the task settles as killed with
  430. // the signal detail mapped by processOutcome.
  431. const final = await call(ctx, 'job_output', { job_id: 'bash-1', wait: true })
  432. expect(text(final)).toContain('[status: killed, signal: SIGTERM]')
  433. })
  434. it('a self-signal background exit is reported as killed through the REAL job_output tool', async () => {
  435. const ctx = await setupWithTasks()
  436. await call(ctx, 'bash', { command: 'kill -TERM $$', description: 'test command', run_in_background: true })
  437. const final = await call(ctx, 'job_output', { job_id: 'bash-1', wait: true })
  438. expect(text(final)).toContain('[status: killed, signal: SIGTERM]')
  439. })
  440. it('a background job started by an agent is registered with that agent as owner', async () => {
  441. // The producer must forward exec.agent as the job owner.
  442. const ctx = await setupWithTasks()
  443. const agent = registerFakeAgent(ctx, 'sess-owner')
  444. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true }, agent)
  445. expect(text(started)).toBe('started background job bash-1')
  446. const anon = await call(ctx, 'job_output', { job_id: 'bash-1' })
  447. expect(anon.isError).toBe(true)
  448. expect(text(anon)).toMatch(/belongs to another session/)
  449. const killed = await call(ctx, 'job_kill', { job_id: 'bash-1' }, agent)
  450. expect(killed.isError).toBe(false)
  451. await call(ctx, 'job_output', { job_id: 'bash-1', wait: true }, agent) // await settlement — no orphan
  452. })
  453. it('fails loud when the job runtime is not loaded', async () => {
  454. const ctx = await setup() // no LocalJobRegistry / ToolTasks
  455. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  456. expect(result.isError).toBe(true)
  457. expect(text(result)).toContain('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs')
  458. })
  459. it('a pre-aborted call is skipped before the process starts', async () => {
  460. const ctx = new Context()
  461. await ctx.plugin(SystemPrompt)
  462. await ctx.plugin(ToolRuntime)
  463. await ctx.plugin(AgentRegistry)
  464. await ctx.plugin(LocalJobRegistry)
  465. await ctx.plugin(ToolTasks)
  466. await ctx.plugin(CountingStartExecutor)
  467. await ctx.plugin(BashEnvPlugin)
  468. await ctx.plugin(ToolBash)
  469. const controller = new AbortController()
  470. controller.abort()
  471. const result = await ctx.tools.execute({
  472. callId: ToolCallId('call-pre-aborted'),
  473. name: 'bash',
  474. arguments: { command: 'sleep 60', description: 'test command', run_in_background: true },
  475. signal: controller.signal,
  476. })
  477. expect(result.isError).toBe(true)
  478. expect(result.error).toEqual({
  479. message: 'tool call aborted before dispatch',
  480. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  481. })
  482. expect(text(result)).toBe('Error: tool call aborted before dispatch')
  483. expect((ctx.shell as CountingStartExecutor).starts).toBe(0)
  484. })
  485. it('never spawns the process when tasks.start preflight throws (no orphan, by construction)', async () => {
  486. // With no job controller, preflight fails before the executor can spawn.
  487. const ctx = new Context()
  488. await ctx.plugin(SystemPrompt)
  489. await ctx.plugin(ToolRuntime)
  490. await ctx.plugin(AgentRegistry)
  491. await ctx.plugin(LocalJobRegistry)
  492. await ctx.plugin(CountingStartExecutor)
  493. await ctx.plugin(BashEnvPlugin)
  494. await ctx.plugin(ToolBash)
  495. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  496. expect(result.isError).toBe(true)
  497. expect(text(result)).toContain('no job controller serves this agent')
  498. // Declare-then-execute: the failed preflight means no process ever ran.
  499. expect((ctx.shell as CountingStartExecutor).starts).toBe(0)
  500. })
  501. it('enableRunInBackground: false removes the parameter and flips the description', async () => {
  502. const ctx = new Context()
  503. await ctx.plugin(SystemPrompt)
  504. await ctx.plugin(ToolRuntime)
  505. await ctx.plugin(LocalSubprocessRuntime)
  506. await ctx.plugin(BashEnvPlugin)
  507. await ctx.plugin(LocalBashExecutor, {})
  508. await ctx.plugin(ToolBash, { enableRunInBackground: false })
  509. const schema = ctx.tools.schemas().find(s => s.name === 'bash')!
  510. expect(Object.keys(schema.parameters.properties as Record<string, unknown>))
  511. .toEqual(['command', 'description', 'timeoutMs', 'workdir'])
  512. expect(schema.description).toContain('Background execution is not available')
  513. expect(schema.description).not.toContain('run_in_background')
  514. // The registry-held definition agrees (schema and capability never disagree).
  515. const parameters = ctx.tools.get('bash')!.parameters as { properties: Record<string, unknown> }
  516. expect('run_in_background' in parameters.properties).toBe(false)
  517. // Schema omission is advertising; execution must also enforce the opt-out.
  518. const forced = await call(ctx, 'bash', { command: 'echo hi', description: 'test command', run_in_background: true })
  519. expect(forced.isError).toBe(true)
  520. expect(text(forced)).toContain('run_in_background is disabled for this deployment')
  521. const foreground = await call(ctx, 'bash', { command: 'echo hi', description: 'test command' })
  522. expect(foreground.isError).toBe(false)
  523. })
  524. })
  525. describe('sandbox escalation through the generic task producer', () => {
  526. const escalate = {
  527. command: 'true',
  528. description: 'test escalation',
  529. sandbox_permissions: 'workspace-write',
  530. justification: 'the command needs workspace writes',
  531. }
  532. it('fails load when a confining executor has no shared sandbox-policy resolver', async () => {
  533. const ctx = new Context()
  534. await ctx.plugin(SystemPrompt)
  535. await ctx.plugin(ToolRuntime)
  536. await ctx.plugin(RecordingSandboxExecutor)
  537. await ctx.plugin(BashEnvPlugin)
  538. await expect(ctx.plugin(ToolBash)).rejects.toThrow('tool-bash: the mounted bash executor confines but ctx.sandboxPolicy is missing')
  539. })
  540. it('advertises the sandbox fields and validates their pairing', async () => {
  541. const { ctx } = await setupSandboxed()
  542. const schema = ctx.tools.schemas().find(item => item.name === 'bash')!
  543. const properties = schema.parameters.properties as Record<string, { enum?: string[] }>
  544. expect(properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
  545. expect(schema.description).toContain('approval prompt')
  546. for (const args of [
  547. { command: 'true', description: 'd', sandbox_permissions: 'workspace-write' },
  548. { command: 'true', description: 'd', justification: 'why' },
  549. { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: ' ' },
  550. ]) {
  551. expect((await call(ctx, 'bash', args)).isError).toBe(true)
  552. }
  553. })
  554. it('rejects injected escalation without a sandbox and non-widening escalation without prompting', async () => {
  555. const plain = await setup()
  556. expect(text(await call(plain, 'bash', escalate))).toContain('not available in this composition')
  557. const { ctx } = await setupSandboxed(true)
  558. const prompted = vi.fn()
  559. ctx.on('approval/request', () => { prompted(); return Promise.resolve<ApprovalOutcome>('allowed-once') })
  560. const result = await call(ctx, 'bash', { ...escalate, sandbox_permissions: 'workspace-write' }, sandboxAgent('workspace-write'))
  561. expect(text(result)).toContain('not strictly wider')
  562. expect(prompted).not.toHaveBeenCalled()
  563. const malformed = sandboxAgent()
  564. ;(malformed.session.events as unknown as Array<{ type: string; data: { mode: string } }>).push({
  565. type: 'sandbox/mode',
  566. data: { mode: 'unknown-mode' },
  567. })
  568. expect(text(await call(ctx, 'bash', escalate, malformed))).toContain('not strictly wider')
  569. })
  570. it('fails closed when approval cannot be routed', async () => {
  571. const withoutService = await setupSandboxed()
  572. expect(text(await call(withoutService.ctx, 'bash', escalate, sandboxAgent()))).toContain('no approval service')
  573. const withService = await setupSandboxed(true)
  574. expect(text(await call(withService.ctx, 'bash', escalate))).toContain('no agent to route')
  575. expect(text(await call(withService.ctx, 'bash', escalate, sandboxAgent()))).toContain('no approval channel')
  576. })
  577. it.each([
  578. ['rejected', 'user rejected'],
  579. ['cancelled', 'was cancelled'],
  580. ] as const)('maps an approval %s to its distinct failure', async (outcome, message) => {
  581. const { ctx, bash } = await setupSandboxed(true)
  582. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>(outcome))
  583. const result = await call(ctx, 'bash', escalate, sandboxAgent())
  584. expect(text(result)).toContain(message)
  585. expect(bash.modes).toEqual([])
  586. })
  587. it('runs a granted foreground or background call under the approved mode', async () => {
  588. const { ctx, bash } = await setupSandboxed(true)
  589. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  590. const agent = sandboxAgent(undefined, ctx)
  591. ctx.agents.register(agent)
  592. const foreground = await ctx.tools.execute({
  593. callId: ToolCallId('sandbox-signal'),
  594. name: 'bash',
  595. arguments: escalate,
  596. agent,
  597. signal: new AbortController().signal,
  598. })
  599. expect(foreground.isError).toBe(false)
  600. const background = await call(ctx, 'bash', { ...escalate, run_in_background: true }, agent)
  601. expect(text(background)).toBe('started background job bash-1')
  602. expect(bash.modes).toEqual(['workspace-write', 'workspace-write'])
  603. })
  604. it('does not publish detached work when cancellation follows the escalation grant', async () => {
  605. const { ctx, bash } = await setupSandboxed(true)
  606. const controller = new AbortController()
  607. const agent = sandboxAgent(undefined, ctx, (type) => {
  608. if (type === 'approval/decided') controller.abort()
  609. })
  610. ctx.agents.register(agent)
  611. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  612. const start = vi.spyOn(bash, 'start')
  613. const result = await ctx.tools.execute({
  614. callId: ToolCallId('cancelled-escalation-background'),
  615. name: 'bash',
  616. arguments: { ...escalate, run_in_background: true },
  617. agent,
  618. signal: controller.signal,
  619. })
  620. expect(result.error).toEqual({
  621. message: 'tool call aborted',
  622. info: { name: 'AbortError', code: TOOL_ABORTED },
  623. })
  624. expect(text(result)).toBe('Error: tool call aborted')
  625. expect(start).not.toHaveBeenCalled()
  626. })
  627. it('uses the session override for ordinary calls and evaluates widening against it', async () => {
  628. const { ctx, bash } = await setupSandboxed(true)
  629. const agent = sandboxAgent('workspace-write')
  630. await call(ctx, 'bash', { command: 'true', description: 'ordinary' }, agent)
  631. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  632. await call(ctx, 'bash', { ...escalate, sandbox_permissions: 'danger-full-access' }, agent)
  633. expect(bash.modes).toEqual(['workspace-write', 'danger-full-access'])
  634. })
  635. it('omits sandbox facts the executor did not acquire from the canonical result', async () => {
  636. const { ctx } = await setupSandboxed()
  637. const result = await call(ctx, 'bash', {
  638. command: 'without optional sandbox facts',
  639. description: 'exercise optional sandbox facts',
  640. })
  641. if (result.isError) throw new Error('expected foreground bash success')
  642. expect(result.value).toMatchObject({
  643. kind: 'foreground',
  644. sandbox: { mode: 'read-only', denied: false },
  645. })
  646. expect((result.value as { sandbox: object }).sandbox).not.toHaveProperty('enforcement')
  647. expect((result.value as { sandbox: object }).sandbox).not.toHaveProperty('runnerFailed')
  648. })
  649. it('keeps the exhaustiveness backstop for a rogue approval implementation', async () => {
  650. const { ctx } = await setupSandboxed(true)
  651. ctx.approval.request = () => Promise.resolve('rogue' as ApprovalOutcome)
  652. const result = await call(ctx, 'bash', escalate, sandboxAgent())
  653. expect(text(result)).toContain('unreachable variant in EscalationOutcome')
  654. })
  655. })
  656. describe('renderProcessRead', () => {
  657. const base: ShellProcessRead = { delta: 'out\n', lossy: false }
  658. it('returns the delta verbatim for a lossless read', () => {
  659. expect(renderProcessRead(base)).toBe('out\n')
  660. expect(renderProcessRead({ delta: '', lossy: false })).toBe('')
  661. })
  662. it('appends the loss notice with the available spill paths', () => {
  663. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log' }))
  664. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log]')
  665. expect(renderProcessRead({ ...base, lossy: true, stdoutSpillPath: '/spill/out.log', stderrSpillPath: '/spill/err.log' }))
  666. .toBe('out\n[some output was dropped from memory; full output: /spill/out.log, /spill/err.log]')
  667. })
  668. it('reports (unavailable) when a lossy read has no safe spill path', () => {
  669. expect(renderProcessRead({ ...base, lossy: true }))
  670. .toBe('out\n[some output was dropped from memory; full output: (unavailable)]')
  671. })
  672. it('an empty lossy delta is the notice alone', () => {
  673. expect(renderProcessRead({ delta: '', lossy: true, stderrSpillPath: '/spill/err.log' }))
  674. .toBe('[some output was dropped from memory; full output: /spill/err.log]')
  675. })
  676. it('inserts the separating newline only when the delta lacks one', () => {
  677. expect(renderProcessRead({ delta: 'tail', lossy: true }))
  678. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  679. expect(renderProcessRead({ delta: 'tail\n', lossy: true }))
  680. .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
  681. })
  682. it('appends settled sandbox denial and runner-failure facts', () => {
  683. expect(renderProcessRead(base, { mode: 'read-only', denied: true }, ['workspace-write']))
  684. .toContain('[sandbox: escalation available')
  685. expect(renderProcessRead({ delta: 'tail', lossy: false }, { mode: 'read-only', denied: true }))
  686. .toBe('tail\n[sandbox: file access denied under read-only mode]')
  687. const runner = renderProcessRead(
  688. { delta: '', lossy: false },
  689. { mode: 'workspace-write', denied: true, runnerFailed: true },
  690. ['danger-full-access'],
  691. )
  692. expect(runner).toContain('sandbox runner itself failed under workspace-write mode')
  693. expect(runner).not.toContain('file access denied')
  694. })
  695. })
  696. describe('processOutcome', () => {
  697. function settled(over: Partial<ShellProcess>): ShellProcess {
  698. return {
  699. status: 'completed',
  700. exitCode: 0,
  701. signal: null,
  702. done: Promise.resolve(),
  703. readOutput: () => ({ delta: '', lossy: false }),
  704. kill: () => false,
  705. ...over,
  706. }
  707. }
  708. it('maps a signal-killed process to killed with the signal detail', () => {
  709. expect(processOutcome(settled({ status: 'killed', signal: 'SIGTERM' })))
  710. .toEqual({ status: 'killed', detail: 'signal: SIGTERM' })
  711. })
  712. it('maps a killed process without a recorded signal (kill raced exit / spawn failure)', () => {
  713. expect(processOutcome(settled({ status: 'killed', exitCode: null })))
  714. .toEqual({ status: 'killed', detail: 'killed before exit' })
  715. })
  716. it('maps a completed process to its exit code', () => {
  717. expect(processOutcome(settled({ exitCode: 3 })))
  718. .toEqual({ status: 'completed', detail: 'exit code: 3' })
  719. })
  720. it('defensively reads a null exit code as 0 (handle shapes from other executors)', () => {
  721. expect(processOutcome(settled({ exitCode: null })))
  722. .toEqual({ status: 'completed', detail: 'exit code: 0' })
  723. })
  724. })
  725. describe('session-cwd routing (per-session workdir)', () => {
  726. // An agent whose session header carries a cwd (what session/new records).
  727. const agentInCwd = (cwd: string) =>
  728. ({ inject: () => undefined, session: { header: { version: 0, id: 'c', createdAt: 0, cwd } } }) as unknown as Agent
  729. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  730. const ctx = await setup()
  731. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  732. expect(text(result).trim()).toMatch(/\/tmp$/)
  733. })
  734. it('an explicit absolute workdir overrides the session cwd', async () => {
  735. const ctx = await setup()
  736. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: '/tmp' }, agentInCwd('/'))
  737. expect(text(result).trim()).toMatch(/\/tmp$/)
  738. })
  739. it('a relative workdir is resolved against the session cwd', async () => {
  740. const ctx = await setup()
  741. // session cwd /usr + relative 'bin' → /usr/bin
  742. const result = await call(ctx, 'bash', { command: 'pwd', description: 'pwd', workdir: 'bin' }, agentInCwd('/usr'))
  743. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  744. })
  745. it('two sessions with different cwds each run bash in their own dir', async () => {
  746. const ctx = await setup()
  747. const inUsr = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/usr'))
  748. const inTmp = await call(ctx, 'bash', { command: 'pwd', description: 'pwd' }, agentInCwd('/tmp'))
  749. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  750. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  751. })
  752. it('falls back to the executor default when the agent has no session cwd', async () => {
  753. const ctx = await setup()
  754. // No exec.agent at all → executor uses its config/process.cwd() default.
  755. const result = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  756. expect(result.isError).toBe(false)
  757. expect(text(result).trim().length).toBeGreaterThan(0)
  758. })
  759. })
  760. describe('renderResult', () => {
  761. const base = {
  762. exitCode: 0 as number | null,
  763. signal: null as NodeJS.Signals | null,
  764. timedOut: false,
  765. aborted: false,
  766. timeoutMs: 1000,
  767. stdout: { text: '', truncated: false },
  768. stderr: { text: '', truncated: false },
  769. }
  770. it('renders stderr-only output without a stdout prefix', () => {
  771. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  772. .toBe('[stderr]\nerr\n')
  773. })
  774. it('adds a separator when stdout does not end with a newline', () => {
  775. expect(renderResult({
  776. ...base,
  777. stdout: { text: 'out', truncated: false },
  778. stderr: { text: 'err', truncated: false },
  779. })).toBe('out\n[stderr]\nerr')
  780. })
  781. it('appends exit-code markers after a newline for unterminated output', () => {
  782. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  783. .toBe('x\n[exit code: 7]')
  784. })
  785. it('renders signal kills without the timeout marker when not timed out', () => {
  786. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  787. .toBe('(no output)\n[killed by signal: SIGKILL]')
  788. })
  789. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  790. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  791. .toBe('(no output)\n[timed out after 1000ms]')
  792. })
  793. it('orders the timeout marker before a kill marker', () => {
  794. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  795. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  796. })
  797. it('notes truncation with a fallback when the spill path is missing', () => {
  798. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  799. .toBe('tail\n[output truncated; full output: (unavailable)]')
  800. })
  801. it('reports sandbox denials before exit status and hints only when escalation is advertised', () => {
  802. const result: ShellRunResult = {
  803. exitCode: 1,
  804. signal: null,
  805. timedOut: false,
  806. aborted: false,
  807. timeoutMs: 1000,
  808. stdout: { text: '', truncated: false },
  809. stderr: { text: 'denied', truncated: false },
  810. sandbox: { mode: 'read-only', denied: true },
  811. }
  812. expect(renderResult(result)).toMatch(/denied under read-only mode\]\n\[exit code: 1\]$/)
  813. expect(renderResult(result, ['workspace-write'])).toContain('[sandbox: escalation available')
  814. expect(renderResult({ ...result, sandbox: { mode: 'read-only', denied: false } }, ['workspace-write']))
  815. .not.toContain('[sandbox:')
  816. })
  817. })
  818. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  819. it('bash presentCall: a foreground run is a terminal card (command title, description, workdir → cwd absolute or relative)', async () => {
  820. const ctx = await setup()
  821. // No explicit workdir → a terminal card with no cwd (the UI bridge fills the
  822. // session cwd it owns; the pure presenter can't see it).
  823. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  824. .toEqual({ card: 'terminal', title: 'ls -la src', description: 'List files in src' })
  825. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  826. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  827. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: '/tmp/x' })
  828. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  829. // the session cwd, matching where execution runs) — not dropped.
  830. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  831. .toEqual({ card: 'terminal', title: 'pwd', description: 'Print dir', cwd: 'sub' })
  832. })
  833. it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => {
  834. const ctx = await setup()
  835. const present = ctx.tools.get('bash')!.presentResult!(
  836. { command: 'printf "hi\\n\\n"', description: 'echo' },
  837. // A clean run renders no exit marker at all, so the body is the raw bytes.
  838. { content: [{ type: 'text', text: 'hi\n\n' }], isError: false },
  839. )
  840. // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer
  841. // needs; the bridge derives the fenced fallback.
  842. expect(present).toEqual({ card: 'terminal', output: 'hi\n\n', exitCode: 0 })
  843. })
  844. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  845. const ctx = await setup()
  846. const args = { command: 'x', description: 'x' }
  847. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  848. expect(nonzero).toEqual({ card: 'terminal', output: 'oops', exitCode: 3 })
  849. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  850. expect(killed).toEqual({ card: 'terminal', output: 'gone', signal: 'SIGKILL' })
  851. })
  852. it('bash presentResult: markers a pill CANNOT show (timeout, sandbox denial) stay in the terminal output', async () => {
  853. const ctx = await setup()
  854. const args = { command: 'x', description: 'x' }
  855. const timedOut = ctx.tools.get('bash')!.presentResult!(
  856. args,
  857. { content: [{ type: 'text', text: 'slow\n[timed out after 100ms]\n[exit code: 143]' }], isError: false },
  858. )
  859. expect(timedOut).toEqual({ card: 'terminal', output: 'slow\n[timed out after 100ms]', exitCode: 143 })
  860. })
  861. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  862. const ctx = await setup()
  863. const present = ctx.tools.get('bash')!
  864. // For each renderResult outcome, the rendered text fed back through
  865. // presentResult recovers the matching structured exit — the parse and the
  866. // marker emission co-evolve in one file, so this pins the pair.
  867. const base = {
  868. aborted: false,
  869. timeoutMs: 1000,
  870. stdout: { text: 'out', truncated: false },
  871. stderr: { text: '', truncated: false },
  872. }
  873. const cases = [
  874. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  875. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  876. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  877. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  878. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  879. ]
  880. for (const c of cases) {
  881. const rendered = renderResult(c.result)
  882. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  883. // Drop card + output; the remaining fields are the parsed exit.
  884. const { card: _c, output, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string }
  885. expect(exit).toEqual(c.expect)
  886. // Whatever the parse consumed is gone from the body, so a card with an exit
  887. // pill never shows the same status twice.
  888. expect(output).not.toMatch(/\[exit code: \d+\]|\[killed by signal: /)
  889. }
  890. })
  891. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  892. const ctx = await setup()
  893. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  894. // A successful command may print marker-like text. A clean result appends no marker or
  895. // newline; parsing requires the leading newline emitted for real markers, so this stays exit 0.
  896. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  897. expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 })
  898. // Unparsed marker-like text is real output, so it is NOT stripped from the body.
  899. // Same for a fake signal marker with no leading newline.
  900. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  901. expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 })
  902. })
  903. it('bash presentCall/presentResult: a run_in_background call is a generic card and its ack carries no exit pill', async () => {
  904. const ctx = await setup()
  905. // The background start returns a task-id ack, not a streamed run — a generic
  906. // execute card with the command as rawInput and the description as content.
  907. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  908. expect(call).toEqual({ card: 'generic', title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  909. // The ack result is a generic fenced-text card — no terminal output / exit pill.
  910. const result = ctx.tools.get('bash')!.presentResult!(
  911. { command: 'sleep 100', description: 'wait', run_in_background: true },
  912. { content: [{ type: 'text', text: 'started background job bash-1' }], isError: false },
  913. )
  914. expect(result).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\nstarted background job bash-1\n```' }] })
  915. })
  916. it('bash presentResult: an isError result is a generic card (no real process exit to report)', async () => {
  917. const ctx = await setup()
  918. // A spawn failure / abort has no process exit — the body is an error message,
  919. // not renderResult output, so a generic fenced card, no terminal output/exit.
  920. const out = ctx.tools.get('bash')!.presentResult!(
  921. { command: 'x', description: 'x' },
  922. { content: [{ type: 'text', text: 'tool call aborted' }], isError: true },
  923. )
  924. expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ntool call aborted\n```' }] })
  925. })
  926. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  927. const ctx = await setup()
  928. const present = ctx.tools.get('bash')!.presentResult!(
  929. { command: 'x', description: 'x' },
  930. { content: [{ type: 'reasoning', text: 'unexpected' }], isError: false },
  931. )
  932. expect(present).toBeUndefined()
  933. })
  934. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  935. const ctx = await setup()
  936. const args = { command: 'x', description: 'x' }
  937. // Empty content (no block) and multi-block content both fall through.
  938. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  939. expect(ctx.tools.get('bash')!.presentResult!(args, {
  940. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  941. isError: false,
  942. })).toBeUndefined()
  943. })
  944. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  945. const ctx = await setup()
  946. // `defineTool` soft-validates replayed logged args before presentation. Invalid shapes return
  947. // undefined for generic UI rendering rather than throwing; `presentCall` accepts `unknown`.
  948. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  949. })
  950. })
  951. describe('the model-facing bash tool builds its request from named args only (no {...args} forward)', () => {
  952. const recordingDshHome = join(spillDir, 'dsh-home')
  953. /**
  954. * Records every {@link ShellExecRequest} the consumer hands to `resolve()`, so a
  955. * test can assert what the model-facing tool DID and DID NOT forward. The `bash`
  956. * tool does not expose trusted-plugin fields (`stdoutMaxBytes`, `stdin`, or
  957. * `env`) as parameters, so it must build its request from named args only and
  958. * never spread unknown tool-call keys into it. This guard's job is to catch a
  959. * future refactor that blindly forwards `...args` — which would silently thread
  960. * model input into the post-scrub `env` merge or per-run capture budget — NOT
  961. * to defend a trust boundary
  962. * (the credential scrub in dsh-bash-local is the security control; see the
  963. * bash-stdin-env Agent Note). Foreground `run()` returns a canned result; `start()`
  964. * hands back an already-settled fake handle so the task registration completes.
  965. */
  966. class RecordingBashExecutor extends ShellExecutor {
  967. readonly requests: ShellExecRequest[] = []
  968. resolve(request: ShellExecRequest): ShellExecSpec {
  969. this.requests.push(request)
  970. return {
  971. command: request.command,
  972. workdir: request.workdir ?? process.cwd(),
  973. timeoutMs: request.timeoutMs ?? 0,
  974. stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000,
  975. ...request.signal ? { signal: request.signal } : {},
  976. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  977. ...request.env !== undefined ? { env: request.env } : {},
  978. ...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {},
  979. sandboxPolicy: request.sandboxPolicy,
  980. }
  981. }
  982. run(): Promise<ShellRunResult> {
  983. return Promise.resolve({
  984. exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 0,
  985. stdout: { text: 'ok', truncated: false }, stderr: { text: '', truncated: false },
  986. })
  987. }
  988. start(): ShellProcess {
  989. return {
  990. status: 'completed',
  991. exitCode: 0,
  992. signal: null,
  993. done: Promise.resolve(),
  994. readOutput: () => ({ delta: '', lossy: false }),
  995. kill: () => false,
  996. }
  997. }
  998. }
  999. async function setupRecording(withJsonl = false) {
  1000. const ctx = new Context()
  1001. await ctx.plugin(SystemPrompt)
  1002. await ctx.plugin(ToolRuntime)
  1003. await ctx.plugin(AgentRegistry)
  1004. if (withJsonl) {
  1005. await ctx.plugin(SessionStore)
  1006. await ctx.plugin(JsonlSessionPersistence, { root: join(spillDir, 'jsonl') })
  1007. }
  1008. await ctx.plugin(LocalJobRegistry)
  1009. await ctx.plugin(ToolTasks)
  1010. await ctx.plugin(BashEnvPlugin, { dshHome: recordingDshHome })
  1011. await ctx.plugin(RecordingBashExecutor)
  1012. await ctx.plugin(ToolBash)
  1013. return { ctx, bash: ctx.shell as RecordingBashExecutor }
  1014. }
  1015. it('describes the managed harness environment namespace to the model', async () => {
  1016. const { ctx } = await setupRecording()
  1017. const description = ctx.tools.get('bash')?.description ?? ''
  1018. expect(description).toContain('$DSH_*')
  1019. expect(description).not.toContain('DSH_SESSION_JSONL')
  1020. })
  1021. it('injects the session id and JSONL target path into a foreground request', async () => {
  1022. const { ctx, bash } = await setupRecording(true)
  1023. const agent = registerFakeAgent(ctx, 'request-fg', () => undefined)
  1024. const path = ctx.sessionPersistence.locate(agent.session.header)?.path
  1025. await ctx.tools.execute({
  1026. signal: testToolSignal,
  1027. callId: ToolCallId('session-env-fg'),
  1028. name: 'bash',
  1029. arguments: { command: 'true', description: 'run command' },
  1030. agent,
  1031. })
  1032. expect(bash.requests[0]?.dshEnv).toEqual({
  1033. DSH_HOME: recordingDshHome,
  1034. DSH_SESSION_ID: 'request-fg',
  1035. DSH_SESSION_JSONL: path,
  1036. DSH_SHELL: '1',
  1037. })
  1038. })
  1039. it('injects the same trusted variables into a background request without forwarding model env', async () => {
  1040. const { ctx, bash } = await setupRecording(true)
  1041. const agent = registerFakeAgent(ctx, 'request-bg', () => undefined)
  1042. const path = ctx.sessionPersistence.locate(agent.session.header)?.path
  1043. await ctx.tools.execute({
  1044. signal: testToolSignal,
  1045. callId: ToolCallId('session-env-bg'),
  1046. name: 'bash',
  1047. arguments: {
  1048. command: 'sleep 1',
  1049. description: 'run command',
  1050. run_in_background: true,
  1051. env: { DSH_SESSION_ID: 'spoofed', DSH_SESSION_JSONL: '/tmp/spoofed' },
  1052. },
  1053. agent,
  1054. })
  1055. expect(bash.requests[0]?.env).toBeUndefined()
  1056. expect(bash.requests[0]?.dshEnv).toEqual({
  1057. DSH_HOME: recordingDshHome,
  1058. DSH_SESSION_ID: 'request-bg',
  1059. DSH_SESSION_JSONL: path,
  1060. DSH_SHELL: '1',
  1061. })
  1062. })
  1063. it('injects built-ins and the stable session id when no JSONL locator is available', async () => {
  1064. const { ctx, bash } = await setupRecording()
  1065. const agent = registerFakeAgent(ctx, 'request-id-only', () => undefined)
  1066. const ambient = process.env.DSH_SESSION_ID
  1067. await ctx.tools.execute({
  1068. signal: testToolSignal,
  1069. callId: ToolCallId('session-env-id-only'),
  1070. name: 'bash',
  1071. arguments: { command: 'true', description: 'run command' },
  1072. agent,
  1073. })
  1074. expect(bash.requests[0]?.dshEnv).toEqual({
  1075. DSH_HOME: recordingDshHome,
  1076. DSH_SESSION_ID: 'request-id-only',
  1077. DSH_SHELL: '1',
  1078. })
  1079. expect(process.env.DSH_SESSION_ID).toBe(ambient)
  1080. })
  1081. it('keeps parent and child agent session environments isolated', async () => {
  1082. const { ctx, bash } = await setupRecording(true)
  1083. const parent = registerFakeAgent(ctx, 'request-parent', () => undefined)
  1084. const child = registerFakeAgent(ctx, 'request-child', () => undefined)
  1085. for (const [callId, agent] of [['parent', parent], ['child', child]] as const) {
  1086. await ctx.tools.execute({
  1087. signal: testToolSignal,
  1088. callId: ToolCallId(`session-env-${callId}`),
  1089. name: 'bash',
  1090. arguments: { command: 'true', description: 'run command' },
  1091. agent,
  1092. })
  1093. }
  1094. expect(bash.requests.map(request => request.dshEnv)).toEqual([
  1095. {
  1096. DSH_HOME: recordingDshHome,
  1097. DSH_SESSION_ID: 'request-parent',
  1098. DSH_SESSION_JSONL: ctx.sessionPersistence.locate(parent.session.header)?.path,
  1099. DSH_SHELL: '1',
  1100. },
  1101. {
  1102. DSH_HOME: recordingDshHome,
  1103. DSH_SESSION_ID: 'request-child',
  1104. DSH_SESSION_JSONL: ctx.sessionPersistence.locate(child.session.header)?.path,
  1105. DSH_SHELL: '1',
  1106. },
  1107. ])
  1108. expect(bash.requests[0]?.dshEnv?.DSH_SESSION_JSONL).not.toBe(bash.requests[1]?.dshEnv?.DSH_SESSION_JSONL)
  1109. })
  1110. it('does not forward trusted-only fields even when the model includes them as extra arguments', async () => {
  1111. const { ctx, bash } = await setupRecording()
  1112. // Unknown `env` and `stdin` keys are ignored by the schema and named request construction.
  1113. // This preserves the request shape; it is not a security boundary because shell syntax can
  1114. // already set environment variables or feed stdin.
  1115. await ctx.tools.execute({
  1116. signal: testToolSignal,
  1117. callId: ToolCallId('no-forward-1'),
  1118. name: 'bash',
  1119. arguments: {
  1120. command: 'echo hi',
  1121. description: 'echo',
  1122. env: { SNEAKY_API_KEY: 'leak' },
  1123. stdin: 'malicious payload',
  1124. stdoutMaxBytes: 999_999,
  1125. },
  1126. })
  1127. expect(bash.requests).toHaveLength(1)
  1128. const request = bash.requests[0]!
  1129. expect(request.command).toBe('echo hi')
  1130. expect('env' in request).toBe(false)
  1131. expect('stdin' in request).toBe(false)
  1132. expect('stdoutMaxBytes' in request).toBe(false)
  1133. })
  1134. it('a background bash call likewise carries no trusted-only fields', async () => {
  1135. const { ctx, bash } = await setupRecording()
  1136. const result = await ctx.tools.execute({
  1137. signal: testToolSignal,
  1138. callId: ToolCallId('no-forward-2'),
  1139. name: 'bash',
  1140. arguments: {
  1141. command: 'sleep 1',
  1142. description: 'sleep',
  1143. run_in_background: true,
  1144. env: { TOKEN: 'leak' },
  1145. stdin: 'x',
  1146. stdoutMaxBytes: 999_999,
  1147. },
  1148. })
  1149. // The call really went down the background path (the recorder sees the real
  1150. // request the consumer built, so the absent env/stdin below is a real
  1151. // negative, not a recorder that drops everything).
  1152. expect(text(result)).toBe('started background job bash-1')
  1153. expect(bash.requests).toHaveLength(1)
  1154. const request = bash.requests[0]!
  1155. expect(request.command).toBe('sleep 1')
  1156. expect('env' in request).toBe(false)
  1157. expect('stdin' in request).toBe(false)
  1158. expect('stdoutMaxBytes' in request).toBe(false)
  1159. })
  1160. })