tools.spec.ts 57 KB

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