tools.spec.ts 52 KB

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