tools.spec.ts 54 KB

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