tools.spec.ts 51 KB

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