tools.spec.ts 51 KB

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