tools.spec.ts 57 KB

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