tools.spec.ts 55 KB

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