tools.spec.ts 50 KB

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