tools.spec.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { Context } from 'cordis'
  6. import { CallId } from '@deepseek-ai/dsh-llm'
  7. import { BashExecutor } from '@deepseek-ai/dsh-bash'
  8. import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead } from '@deepseek-ai/dsh-bash'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry from '@deepseek-ai/dsh-tools'
  11. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  12. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  13. import { renderResult } from '@deepseek-ai/dsh-tool-bash'
  14. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-tool-bash-spec-'))
  15. async function setup() {
  16. const ctx = new Context()
  17. await ctx.plugin(SystemPrompt)
  18. await ctx.plugin(ToolRegistry)
  19. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  20. ;(ctx.bash as LocalBashExecutor).internals = { spillDir, graceMs: 200 }
  21. await ctx.plugin(ToolBash)
  22. return ctx
  23. }
  24. let callCounter = 0
  25. function call(ctx: Context, name: string, args: unknown) {
  26. return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args })
  27. }
  28. function text(result: { content: { type: string; text?: string }[] }): string {
  29. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  30. }
  31. class LossyReadBashExecutor extends BashExecutor {
  32. private readonly task: BashTask = {
  33. id: 'bash-lossy',
  34. command: 'fake',
  35. status: 'running',
  36. exitCode: null,
  37. signal: null,
  38. done: Promise.resolve(),
  39. }
  40. resolve(request: BashExecRequest): BashExecSpec {
  41. return {
  42. command: request.command,
  43. workdir: request.workdir ?? process.cwd(),
  44. timeoutMs: request.timeoutMs ?? 0,
  45. ...request.signal ? { signal: request.signal } : {},
  46. }
  47. }
  48. run(): Promise<BashRunResult> {
  49. return Promise.reject(new Error('not used'))
  50. }
  51. start(): BashTask {
  52. return this.task
  53. }
  54. get(id: string): BashTask | undefined {
  55. return id === this.task.id ? this.task : undefined
  56. }
  57. list(): BashTask[] {
  58. return [this.task]
  59. }
  60. readOutput(id: string): BashTaskRead {
  61. if (id !== this.task.id) throw new Error(`unknown bash task "${id}"`)
  62. return { task: this.task, delta: 'tail', lossy: true }
  63. }
  64. kill(): boolean {
  65. return false
  66. }
  67. }
  68. describe('bash tool', () => {
  69. it('returns stdout for a successful command', async () => {
  70. const ctx = await setup()
  71. const result = await call(ctx, 'bash', { command: 'echo hello', description: 'test command' })
  72. expect(result.isError).toBe(false)
  73. expect(text(result)).toBe('hello\n')
  74. })
  75. it('reports (no output) for silent commands', async () => {
  76. const ctx = await setup()
  77. const result = await call(ctx, 'bash', { command: 'true', description: 'test command' })
  78. expect(text(result)).toBe('(no output)')
  79. })
  80. it('marks stderr sections', async () => {
  81. const ctx = await setup()
  82. const result = await call(ctx, 'bash', { command: 'echo out; echo err >&2', description: 'test command' })
  83. expect(text(result)).toBe('out\n[stderr]\nerr\n')
  84. expect(result.isError).toBe(false)
  85. })
  86. it('reports non-zero exits without isError', async () => {
  87. const ctx = await setup()
  88. const result = await call(ctx, 'bash', { command: 'echo failing; exit 3', description: 'test command' })
  89. expect(result.isError).toBe(false)
  90. expect(text(result)).toBe('failing\n[exit code: 3]')
  91. })
  92. it('reports timeout kills with both markers (timeout first)', async () => {
  93. const ctx = await setup()
  94. const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', timeoutMs: 100 })
  95. expect(result.isError).toBe(false)
  96. expect(text(result)).toBe('(no output)\n[timed out after 100ms]\n[killed by signal: SIGTERM]')
  97. })
  98. it('reports a timeout even when the command traps the signal and exits 0', async () => {
  99. // The signal-independent timeout marker: a trapped SIGTERM that exits 0
  100. // after our timer fired must NOT look like a clean success. (bash may
  101. // print "Terminated" to stderr for the killed sleep — environment
  102. // dependent — so assert the marker, not the exact body.)
  103. const ctx = await setup()
  104. const result = await call(ctx, 'bash', { command: 'trap "exit 0" TERM; sleep 60', description: 'test command', timeoutMs: 100 })
  105. expect(result.isError).toBe(false)
  106. expect(text(result)).toContain('[timed out after 100ms]')
  107. expect(text(result)).not.toContain('[exit code:')
  108. })
  109. it('reports truncation with the spill path', async () => {
  110. const ctx = new Context()
  111. await ctx.plugin(SystemPrompt)
  112. await ctx.plugin(ToolRegistry)
  113. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100 })
  114. ;(ctx.bash as LocalBashExecutor).internals = { spillDir, graceMs: 200 }
  115. await ctx.plugin(ToolBash)
  116. const result = await call(ctx, 'bash', { command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done', description: 'test command' })
  117. expect(text(result)).toContain('[output truncated; full output: ')
  118. expect(text(result)).toContain('line-0100')
  119. })
  120. it('honors workdir', async () => {
  121. const ctx = await setup()
  122. const result = await call(ctx, 'bash', { command: 'pwd', description: 'test command', workdir: '/tmp' })
  123. expect(text(result).trim()).toMatch(/\/tmp$/)
  124. })
  125. it('surfaces spawn failures as isError', async () => {
  126. const ctx = await setup()
  127. const result = await call(ctx, 'bash', { command: 'true', description: 'test command', workdir: '/nonexistent-dsh' })
  128. expect(result.isError).toBe(true)
  129. expect(text(result)).toMatch(/ENOENT/)
  130. })
  131. it('surfaces aborts as isError', async () => {
  132. const ctx = await setup()
  133. const controller = new AbortController()
  134. const pending = ctx.tools.execute({
  135. callId: CallId('call-abort'),
  136. name: 'bash',
  137. arguments: { command: 'sleep 60', description: 'test command' },
  138. signal: controller.signal,
  139. })
  140. setTimeout(() => { controller.abort() }, 50)
  141. const result = await pending
  142. expect(result.isError).toBe(true)
  143. expect(text(result)).toMatch(/aborted/)
  144. })
  145. // Type and required-key violations are now rejected by the harness
  146. // (defineTool validates against the SchemaSpec — the arg-validation RFC) before execute.
  147. it.each([
  148. [{}, /missing required property "command"/],
  149. [{ command: 42, description: 'd' }, /"command" must be a string/],
  150. [{ command: 'x' }, /missing required property "description"/],
  151. [{ command: 'x', description: 7 }, /"description" must be a string/],
  152. [{ command: 'x', description: 'd', timeoutMs: 'soon' }, /"timeoutMs" must be a number/],
  153. [{ command: 'x', description: 'd', workdir: 7 }, /"workdir" must be a string/],
  154. [{ command: 'x', description: 'd', run_in_background: 'yes' }, /"run_in_background" must be a boolean/],
  155. ])('rejects schema-invalid args %j', async (args, pattern) => {
  156. const ctx = await setup()
  157. const result = await call(ctx, 'bash', args)
  158. expect(result.isError).toBe(true)
  159. expect(text(result)).toMatch(pattern)
  160. })
  161. // Value constraints the SchemaSpec can't express stay in the tool body.
  162. it.each([
  163. [{ command: ' ', description: 'd' }, /invalid command/],
  164. [{ command: 'x', description: ' ' }, /invalid description/],
  165. [{ command: 'x', description: 'd', timeoutMs: -1 }, /invalid timeoutMs/],
  166. [{ command: 'x', description: 'd', timeoutMs: Number.NaN }, /invalid timeoutMs/],
  167. ])('rejects value-invalid args %j', async (args, pattern) => {
  168. const ctx = await setup()
  169. const result = await call(ctx, 'bash', args)
  170. expect(result.isError).toBe(true)
  171. expect(text(result)).toMatch(pattern)
  172. })
  173. it('registers all three schemas in the system prompt assembly', async () => {
  174. const ctx = await setup()
  175. const names = ctx.tools.schemas().map(schema => schema.name)
  176. expect(names).toEqual(['bash', 'bash_output', 'bash_kill'])
  177. const bashSchema = ctx.tools.schemas()[0]!
  178. expect(bashSchema.parameters).toMatchObject({
  179. type: 'object',
  180. required: ['command', 'description'],
  181. })
  182. })
  183. it('unregisters everything when the plugin fiber is disposed (HMR safety)', async () => {
  184. const ctx = new Context()
  185. await ctx.plugin(SystemPrompt)
  186. await ctx.plugin(ToolRegistry)
  187. await ctx.plugin(LocalBashExecutor, {})
  188. const fiber = await ctx.plugin(ToolBash)
  189. expect(ctx.tools.schemas()).toHaveLength(3)
  190. await fiber.dispose()
  191. expect(ctx.tools.schemas()).toHaveLength(0)
  192. })
  193. it('tools depend on the executor: no registration without ctx.bash', async () => {
  194. const ctx = new Context()
  195. await ctx.plugin(SystemPrompt)
  196. await ctx.plugin(ToolRegistry)
  197. // inject: ['tools', 'bash'] keeps the plugin pending until bash exists.
  198. await ctx.plugin(ToolBash)
  199. expect(ctx.tools.schemas()).toHaveLength(0)
  200. await ctx.plugin(LocalBashExecutor, {})
  201. await new Promise(resolve => setTimeout(resolve, 0))
  202. expect(ctx.tools.schemas()).toHaveLength(3)
  203. })
  204. })
  205. describe('background tools', () => {
  206. it('bash with run_in_background returns a task id immediately', async () => {
  207. const ctx = await setup()
  208. const result = await call(ctx, 'bash', { command: 'sleep 0.2; echo bg-done', description: 'test command', run_in_background: true })
  209. expect(result.isError).toBe(false)
  210. expect(text(result)).toMatch(/^started background task bash-\d+$/)
  211. })
  212. it('bash_output polls incrementally and reports status', async () => {
  213. const ctx = await setup()
  214. const started = await call(ctx, 'bash', { command: 'echo first; sleep 0.3; echo second', description: 'test command', run_in_background: true })
  215. const id = /task (bash-\d+)/.exec(text(started))![1]!
  216. await new Promise(resolve => setTimeout(resolve, 150))
  217. const first = await call(ctx, 'bash_output', { task_id: id })
  218. expect(text(first)).toContain('first')
  219. expect(text(first)).toContain('[status: running]')
  220. await ctx.bash.get(id)!.done
  221. const second = await call(ctx, 'bash_output', { task_id: id })
  222. expect(text(second)).toContain('second')
  223. expect(text(second)).not.toContain('first')
  224. expect(text(second)).toContain('[status: completed, exit code: 0]')
  225. const third = await call(ctx, 'bash_output', { task_id: id })
  226. expect(text(third)).toContain('(no new output)')
  227. })
  228. it('bash_output flags lossy reads with spill paths', async () => {
  229. const ctx = new Context()
  230. await ctx.plugin(SystemPrompt)
  231. await ctx.plugin(ToolRegistry)
  232. await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100 })
  233. ;(ctx.bash as LocalBashExecutor).internals = { spillDir, graceMs: 200 }
  234. await ctx.plugin(ToolBash)
  235. const started = await call(ctx, 'bash', { command: 'for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', description: 'test command', run_in_background: true })
  236. const id = /task (bash-\d+)/.exec(text(started))![1]!
  237. await ctx.bash.get(id)!.done
  238. const read = await call(ctx, 'bash_output', { task_id: id })
  239. expect(text(read)).toContain('[some output was dropped from memory; full output: ')
  240. })
  241. it('bash_output reports unavailable when a lossy read has no safe spill path', async () => {
  242. const ctx = new Context()
  243. await ctx.plugin(SystemPrompt)
  244. await ctx.plugin(ToolRegistry)
  245. await ctx.plugin(LossyReadBashExecutor)
  246. await ctx.plugin(ToolBash)
  247. const read = await call(ctx, 'bash_output', { task_id: 'bash-lossy' })
  248. expect(text(read)).toBe('tail\n[some output was dropped from memory; full output: (unavailable)]\n[status: running]')
  249. })
  250. it('bash_kill stops a running task; repeat reports already-finished', async () => {
  251. const ctx = await setup()
  252. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  253. const id = /task (bash-\d+)/.exec(text(started))![1]!
  254. const killed = await call(ctx, 'bash_kill', { task_id: id })
  255. expect(text(killed)).toBe(`killed background task ${id}`)
  256. await ctx.bash.get(id)!.done
  257. const again = await call(ctx, 'bash_kill', { task_id: id })
  258. expect(text(again)).toBe(`task ${id} had already finished`)
  259. const status = await call(ctx, 'bash_output', { task_id: id })
  260. expect(text(status)).toContain('[status: killed by SIGTERM]')
  261. })
  262. it('unknown task ids are isError for both tools', async () => {
  263. const ctx = await setup()
  264. const read = await call(ctx, 'bash_output', { task_id: 'bash-999' })
  265. expect(read.isError).toBe(true)
  266. expect(text(read)).toMatch(/unknown bash task/)
  267. const kill = await call(ctx, 'bash_kill', { task_id: 'bash-999' })
  268. expect(kill.isError).toBe(true)
  269. })
  270. it.each([
  271. ['bash_output', {}, /missing required property "task_id"/],
  272. ['bash_output', { task_id: 9 }, /"task_id" must be a string/],
  273. ['bash_kill', { task_id: '' }, /invalid task_id/],
  274. ])('%s rejects invalid task_id %j', async (tool, args, pattern) => {
  275. const ctx = await setup()
  276. const result = await call(ctx, tool, args)
  277. expect(result.isError).toBe(true)
  278. expect(text(result)).toMatch(pattern)
  279. })
  280. it('injects a completion notice into the owning agent', async () => {
  281. const ctx = await setup()
  282. const inject = vi.fn()
  283. const agent = { inject, session: { header: { version: 1, id: 'bg', createdAt: 0 } } } as unknown as import('@deepseek-ai/dsh-agent').Agent
  284. const started = await ctx.tools.execute({
  285. callId: CallId('call-bg'),
  286. name: 'bash',
  287. arguments: { command: 'true', description: 'test command', run_in_background: true },
  288. agent,
  289. })
  290. const id = /task (bash-\d+)/.exec(text(started))![1]!
  291. await ctx.bash.get(id)!.done
  292. expect(inject).toHaveBeenCalledTimes(1)
  293. const [content, options] = inject.mock.calls[0] as [
  294. { type: string; text: string }[],
  295. { source: { kind: string; plugin: string } },
  296. ]
  297. expect(content[0]!.text).toContain(`background bash task ${id} finished`)
  298. expect(content[0]!.text).toContain('bash_output')
  299. expect(options.source).toEqual({ kind: 'plugin', plugin: 'tool-bash' })
  300. })
  301. it('swallows ONLY the disposed-agent inject error', async () => {
  302. const ctx = await setup()
  303. const agent = {
  304. inject: () => { throw new Error('agent "x" is disposed') },
  305. session: { header: { version: 1, id: 'bg', createdAt: 0 } },
  306. } as unknown as import('@deepseek-ai/dsh-agent').Agent
  307. const started = await ctx.tools.execute({
  308. callId: CallId('call-bg2'),
  309. name: 'bash',
  310. arguments: { command: 'true', description: 'test command', run_in_background: true },
  311. agent,
  312. })
  313. const id = /task (bash-\d+)/.exec(text(started))![1]!
  314. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  315. })
  316. it('rethrows a non-disposed inject failure (not blindly swallowed)', async () => {
  317. const ctx = await setup()
  318. // A real bug in inject (not the benign disposed race) must surface — the
  319. // base-class notifier contains it (logs, does not reject task.done), but
  320. // the listener itself must have thrown rather than silently eaten it.
  321. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  322. try {
  323. const agent = {
  324. inject: () => { throw new Error('unexpected inject bug') },
  325. session: { header: { version: 1, id: 'bg', createdAt: 0 } },
  326. } as unknown as import('@deepseek-ai/dsh-agent').Agent
  327. const started = await ctx.tools.execute({
  328. callId: CallId('call-bg3'),
  329. name: 'bash',
  330. arguments: { command: 'true', description: 'test command', run_in_background: true },
  331. agent,
  332. })
  333. const id = /task (bash-\d+)/.exec(text(started))![1]!
  334. await ctx.bash.get(id)!.done
  335. // notifyTaskDone caught and logged the rethrown error.
  336. expect(errorSpy).toHaveBeenCalled()
  337. const logged = errorSpy.mock.calls.flat().some(arg => arg instanceof Error && arg.message === 'unexpected inject bug')
  338. expect(logged).toBe(true)
  339. } finally {
  340. errorSpy.mockRestore()
  341. }
  342. })
  343. it('does not notify when no agent owned the task', async () => {
  344. const ctx = await setup()
  345. const started = await call(ctx, 'bash', { command: 'true', description: 'test command', run_in_background: true })
  346. const id = /task (bash-\d+)/.exec(text(started))![1]!
  347. await expect(ctx.bash.get(id)!.done).resolves.toBeUndefined()
  348. })
  349. })
  350. describe('background task ownership (cross-session isolation)', () => {
  351. /** Run a tool on behalf of a specific agent (sets exec.agent). */
  352. function callAs(ctx: Context, agent: import('@deepseek-ai/dsh-agent').Agent | undefined, name: string, args: unknown) {
  353. return ctx.tools.execute({ callId: CallId(`own-${++callCounter}`), name, arguments: args, ...agent ? { agent } : {} })
  354. }
  355. // Distinct identities — ownership is by agent object identity, not id.
  356. const fakeAgent = () => ({ inject: () => undefined, session: { header: { version: 1, id: 'bg', createdAt: 0 } } }) as unknown as import('@deepseek-ai/dsh-agent').Agent
  357. it('rejects bash_output/bash_kill for a task owned by a DIFFERENT agent', async () => {
  358. const ctx = await setup()
  359. const a = fakeAgent()
  360. const b = fakeAgent()
  361. // Agent A starts a long-running background task.
  362. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  363. const id = /task (bash-\d+)/.exec(text(started))![1]!
  364. // Agent B cannot read or kill A's task.
  365. const readByB = await callAs(ctx, b, 'bash_output', { task_id: id })
  366. expect(readByB.isError).toBe(true)
  367. expect(text(readByB)).toMatch(/belongs to another session/)
  368. const killByB = await callAs(ctx, b, 'bash_kill', { task_id: id })
  369. expect(killByB.isError).toBe(true)
  370. expect(text(killByB)).toMatch(/belongs to another session/)
  371. // The task is still running (B's kill did nothing) — A can still kill it.
  372. const killByA = await callAs(ctx, a, 'bash_kill', { task_id: id })
  373. expect(killByA.isError).toBe(false)
  374. expect(text(killByA)).toBe(`killed background task ${id}`)
  375. })
  376. it('the no-agent (non-loop) caller cannot access an owned task', async () => {
  377. const ctx = await setup()
  378. const a = fakeAgent()
  379. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  380. const id = /task (bash-\d+)/.exec(text(started))![1]!
  381. // A call with no exec.agent cannot prove ownership of an owned task.
  382. const read = await callAs(ctx, undefined, 'bash_output', { task_id: id })
  383. expect(read.isError).toBe(true)
  384. expect(text(read)).toMatch(/belongs to another session/)
  385. await callAs(ctx, a, 'bash_kill', { task_id: id }) // cleanup
  386. })
  387. it('an UNOWNED task (started with no agent) is accessible to anyone', async () => {
  388. const ctx = await setup()
  389. // Started by a non-loop caller (no exec.agent) → no recorded owner.
  390. const started = await callAs(ctx, undefined, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  391. const id = /task (bash-\d+)/.exec(text(started))![1]!
  392. // Any agent (and the no-agent caller) may read/kill it.
  393. const read = await callAs(ctx, fakeAgent(), 'bash_output', { task_id: id })
  394. expect(read.isError).toBe(false)
  395. const killed = await callAs(ctx, undefined, 'bash_kill', { task_id: id })
  396. expect(killed.isError).toBe(false)
  397. })
  398. it('the owner can still access its task AFTER it completes (owner record persists)', async () => {
  399. const ctx = await setup()
  400. const a = fakeAgent()
  401. const b = fakeAgent()
  402. const started = await callAs(ctx, a, 'bash', { command: 'echo done', description: 'bg', run_in_background: true })
  403. const id = /task (bash-\d+)/.exec(text(started))![1]!
  404. await ctx.bash.get(id)!.done
  405. // Completion does NOT clear ownership: B is still rejected, A still allowed.
  406. const readByB = await callAs(ctx, b, 'bash_output', { task_id: id })
  407. expect(readByB.isError).toBe(true)
  408. expect(text(readByB)).toMatch(/belongs to another session/)
  409. const readByA = await callAs(ctx, a, 'bash_output', { task_id: id })
  410. expect(readByA.isError).toBe(false)
  411. })
  412. it('documents the HMR caveat: an independent tool-bash reload resets ownership', async () => {
  413. // The ownership map is per-plugin-instance (XXX(tool-bash-owner-hmr)). When
  414. // ONLY tool-bash is reloaded (bash/executor + task survive), the new instance
  415. // has an empty map, so the previously-owned task becomes unowned (open). This
  416. // test pins that documented behavior — a regression here (e.g. an accidental
  417. // global map) would change it.
  418. const ctx = new Context()
  419. await ctx.plugin(SystemPrompt)
  420. await ctx.plugin(ToolRegistry)
  421. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  422. ;(ctx.bash as LocalBashExecutor).internals = { spillDir, graceMs: 200 }
  423. const fiber = await ctx.plugin(ToolBash)
  424. const a = fakeAgent()
  425. const b = fakeAgent()
  426. const started = await callAs(ctx, a, 'bash', { command: 'sleep 60', description: 'bg', run_in_background: true })
  427. const id = /task (bash-\d+)/.exec(text(started))![1]!
  428. // Before reload: B is rejected (A owns it).
  429. expect((await callAs(ctx, b, 'bash_output', { task_id: id })).isError).toBe(true)
  430. // Reload ONLY tool-bash; the executor and its running task survive.
  431. await fiber.dispose()
  432. await ctx.plugin(ToolBash)
  433. expect(ctx.bash.get(id)?.status).toBe('running')
  434. // After reload the fresh map has no owner → B can now access it (the caveat).
  435. expect((await callAs(ctx, b, 'bash_output', { task_id: id })).isError).toBe(false)
  436. await callAs(ctx, b, 'bash_kill', { task_id: id }) // cleanup
  437. })
  438. })
  439. describe('session-cwd routing (per-session workdir)', () => {
  440. function callAs(ctx: Context, agent: import('@deepseek-ai/dsh-agent').Agent | undefined, args: unknown) {
  441. return ctx.tools.execute({ callId: CallId(`cwd-${++callCounter}`), name: 'bash', arguments: args, ...agent ? { agent } : {} })
  442. }
  443. // An agent whose session header carries a cwd (what session/new records).
  444. const agentInCwd = (cwd: string) =>
  445. ({ inject: () => undefined, session: { header: { version: 1, id: 'c', createdAt: 0, cwd } } }) as unknown as import('@deepseek-ai/dsh-agent').Agent
  446. it('defaults bash to the agent\'s session cwd (not the server launch dir)', async () => {
  447. const ctx = await setup()
  448. const result = await callAs(ctx, agentInCwd('/tmp'), { command: 'pwd', description: 'pwd' })
  449. expect(text(result).trim()).toMatch(/\/tmp$/)
  450. })
  451. it('an explicit absolute workdir overrides the session cwd', async () => {
  452. const ctx = await setup()
  453. const result = await callAs(ctx, agentInCwd('/'), { command: 'pwd', description: 'pwd', workdir: '/tmp' })
  454. expect(text(result).trim()).toMatch(/\/tmp$/)
  455. })
  456. it('a relative workdir is resolved against the session cwd', async () => {
  457. const ctx = await setup()
  458. // session cwd /usr + relative 'bin' → /usr/bin
  459. const result = await callAs(ctx, agentInCwd('/usr'), { command: 'pwd', description: 'pwd', workdir: 'bin' })
  460. expect(text(result).trim()).toMatch(/\/usr\/bin$/)
  461. })
  462. it('two sessions with different cwds each run bash in their own dir', async () => {
  463. const ctx = await setup()
  464. const inUsr = await callAs(ctx, agentInCwd('/usr'), { command: 'pwd', description: 'pwd' })
  465. const inTmp = await callAs(ctx, agentInCwd('/tmp'), { command: 'pwd', description: 'pwd' })
  466. expect(text(inUsr).trim()).toMatch(/\/usr$/)
  467. expect(text(inTmp).trim()).toMatch(/\/tmp$/)
  468. })
  469. it('falls back to the executor default when the agent has no session cwd', async () => {
  470. const ctx = await setup()
  471. // No exec.agent at all → executor uses its config/process.cwd() default.
  472. const result = await ctx.tools.execute({ callId: CallId('cwd-noagent'), name: 'bash', arguments: { command: 'pwd', description: 'pwd' } })
  473. expect(result.isError).toBe(false)
  474. expect(text(result).trim().length).toBeGreaterThan(0)
  475. })
  476. })
  477. describe('renderResult', () => {
  478. const base = {
  479. exitCode: 0 as number | null,
  480. signal: null as NodeJS.Signals | null,
  481. timedOut: false,
  482. aborted: false,
  483. timeoutMs: 1000,
  484. stdout: { text: '', truncated: false },
  485. stderr: { text: '', truncated: false },
  486. }
  487. it('renders stderr-only output without a stdout prefix', () => {
  488. expect(renderResult({ ...base, stderr: { text: 'err\n', truncated: false } }))
  489. .toBe('[stderr]\nerr\n')
  490. })
  491. it('adds a separator when stdout does not end with a newline', () => {
  492. expect(renderResult({
  493. ...base,
  494. stdout: { text: 'out', truncated: false },
  495. stderr: { text: 'err', truncated: false },
  496. })).toBe('out\n[stderr]\nerr')
  497. })
  498. it('appends exit-code markers after a newline for unterminated output', () => {
  499. expect(renderResult({ ...base, exitCode: 7, stdout: { text: 'x', truncated: false } }))
  500. .toBe('x\n[exit code: 7]')
  501. })
  502. it('renders signal kills without the timeout marker when not timed out', () => {
  503. expect(renderResult({ ...base, exitCode: null, signal: 'SIGKILL' }))
  504. .toBe('(no output)\n[killed by signal: SIGKILL]')
  505. })
  506. it('reports a timeout that exited 0 (trapped signal) without a kill marker', () => {
  507. expect(renderResult({ ...base, exitCode: 0, signal: null, timedOut: true }))
  508. .toBe('(no output)\n[timed out after 1000ms]')
  509. })
  510. it('orders the timeout marker before a kill marker', () => {
  511. expect(renderResult({ ...base, exitCode: null, signal: 'SIGTERM', timedOut: true }))
  512. .toBe('(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]')
  513. })
  514. it('notes truncation with a fallback when the spill path is missing', () => {
  515. expect(renderResult({ ...base, stdout: { text: 'tail', truncated: true } }))
  516. .toBe('tail\n[output truncated; full output: (unavailable)]')
  517. })
  518. })
  519. describe('status lines', () => {
  520. it('reports kills without a recorded signal (executor raced process exit)', async () => {
  521. const ctx = await setup()
  522. const started = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true })
  523. const id = /task (bash-\d+)/.exec(text(started))![1]!
  524. const task = ctx.bash.get(id)!
  525. await call(ctx, 'bash_kill', { task_id: id })
  526. await task.done
  527. // Simulate the variant where the close event carried no signal.
  528. task.signal = null
  529. const read = await call(ctx, 'bash_output', { task_id: id })
  530. expect(text(read)).toContain('[status: killed]')
  531. })
  532. it('reports completed tasks with a null exit code as exit 0', async () => {
  533. const ctx = await setup()
  534. const started = await call(ctx, 'bash', { command: 'true', description: 'test command', run_in_background: true })
  535. const id = /task (bash-\d+)/.exec(text(started))![1]!
  536. const task = ctx.bash.get(id)!
  537. await task.done
  538. // Defensive: completed tasks always carry an exit code in practice; the
  539. // ?? 0 fallback covers task shapes from other executor implementations.
  540. task.exitCode = null
  541. const read = await call(ctx, 'bash_output', { task_id: id })
  542. expect(text(read)).toContain('[status: completed, exit code: 0]')
  543. })
  544. })
  545. describe('tool-owned UI presentation (presentCall / presentResult)', () => {
  546. it('bash presentCall: title is the command, description as a content block, marks a terminal; workdir → cwd (absolute or relative, bridge resolves)', async () => {
  547. const ctx = await setup()
  548. // No explicit workdir → the call still flags a terminal, but with no cwd (the
  549. // UI bridge fills the session cwd it owns; the pure presenter can't see it).
  550. // The command is the title (an execute card hides rawInput); the description
  551. // rides as a content text block (shown above the terminal card).
  552. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls -la src', description: 'List files in src' }))
  553. .toEqual({ title: 'ls -la src', kind: 'execute', rawInput: 'ls -la src', content: [{ type: 'text', text: 'List files in src' }], terminal: {} })
  554. // An ABSOLUTE workdir is surfaced verbatim as the terminal cwd header.
  555. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: '/tmp/x' }))
  556. .toEqual({ title: 'pwd', kind: 'execute', rawInput: 'pwd', content: [{ type: 'text', text: 'Print dir' }], terminal: { cwd: '/tmp/x' } })
  557. // A RELATIVE workdir is passed through AS-IS (the bridge resolves it against
  558. // the session cwd, matching where execution runs) — not dropped.
  559. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd', description: 'Print dir', workdir: 'sub' }))
  560. .toEqual({ title: 'pwd', kind: 'execute', rawInput: 'pwd', content: [{ type: 'text', text: 'Print dir' }], terminal: { cwd: 'sub' } })
  561. })
  562. it('bash presentResult: console-block content AND terminal.output (RAW newlines) + parsed exit code', async () => {
  563. const ctx = await setup()
  564. const present = ctx.tools.get('bash')!.presentResult!(
  565. { command: 'echo hi', description: 'echo' },
  566. { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false },
  567. )
  568. // The fenced ```console content trims trailing blank lines for a tidy block;
  569. // terminal.output keeps the RAW bytes (newlines intact) a terminal renderer
  570. // needs; exitCode is parsed back from the [exit code: N] marker.
  571. expect(present).toEqual({
  572. content: [{ type: 'text', text: '```console\nhi\n[exit code: 0]\n```' }],
  573. terminal: { output: 'hi\n[exit code: 0]\n\n', exitCode: 0 },
  574. })
  575. })
  576. it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => {
  577. const ctx = await setup()
  578. const args = { command: 'x', description: 'x' }
  579. const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false })
  580. expect(nonzero?.terminal).toEqual({ output: 'oops\n[exit code: 3]', exitCode: 3 })
  581. const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false })
  582. expect(killed?.terminal).toEqual({ output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' })
  583. })
  584. it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => {
  585. const ctx = await setup()
  586. const present = ctx.tools.get('bash')!
  587. // For each renderResult outcome, the rendered text fed back through
  588. // presentResult recovers the matching structured exit — the parse and the
  589. // marker emission co-evolve in one file, so this pins the pair.
  590. const base = {
  591. aborted: false,
  592. timeoutMs: 1000,
  593. stdout: { text: 'out', truncated: false },
  594. stderr: { text: '', truncated: false },
  595. }
  596. const cases = [
  597. { result: { ...base, exitCode: 0, signal: null, timedOut: false }, expect: { exitCode: 0 } },
  598. { result: { ...base, exitCode: 7, signal: null, timedOut: false }, expect: { exitCode: 7 } },
  599. { result: { ...base, exitCode: null, signal: 'SIGTERM' as const, timedOut: false }, expect: { signal: 'SIGTERM' } },
  600. // A trapped-timeout run that exits 0 has no signal/exit marker → reads as exit 0 (it did exit 0).
  601. { result: { ...base, exitCode: 0, signal: null, timedOut: true }, expect: { exitCode: 0 } },
  602. ]
  603. for (const c of cases) {
  604. const rendered = renderResult(c.result)
  605. const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false })
  606. const { output: _o, ...exit } = out?.terminal ?? {}
  607. expect(exit).toEqual(c.expect)
  608. }
  609. })
  610. it('bash presentResult: a clean exit-0 whose output ENDS in marker-like text is NOT read as a failure', async () => {
  611. const ctx = await setup()
  612. const args = { command: 'printf "[exit code: 5]"', description: 'print' }
  613. // A successful command can print text that looks like a marker. renderResult
  614. // for a clean exit 0 appends NOTHING (and no trailing newline), so the body's
  615. // own tail is `[exit code: 5]`. The parse requires a LEADING newline before
  616. // the marker (renderResult always inserts one before a REAL marker), so this
  617. // no-trailing-newline body is NOT mistaken for a failure → exitCode 0.
  618. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false })
  619. expect(out?.terminal).toEqual({ output: '[exit code: 5]', exitCode: 0 })
  620. // Same for a fake signal marker with no leading newline.
  621. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false })
  622. expect(sig?.terminal).toEqual({ output: '[killed by signal: SIGKILL]', exitCode: 0 })
  623. })
  624. it('bash presentCall/presentResult: a run_in_background call is NOT a terminal and its ack carries no exit pill', async () => {
  625. const ctx = await setup()
  626. // The background start returns a task-id ack, not a streamed run — no terminal.
  627. const call = ctx.tools.get('bash')!.presentCall!({ command: 'sleep 100', description: 'wait', run_in_background: true })
  628. expect(call).toEqual({ title: 'sleep 100', kind: 'execute', rawInput: 'sleep 100', content: [{ type: 'text', text: 'wait' }] })
  629. expect((call as { terminal?: unknown }).terminal).toBeUndefined()
  630. // The ack result is fenced text only — no terminal output / exit pill.
  631. const result = ctx.tools.get('bash')!.presentResult!(
  632. { command: 'sleep 100', description: 'wait', run_in_background: true },
  633. { content: [{ type: 'text', text: 'started background task bash-1' }], isError: false },
  634. )
  635. expect(result?.terminal).toBeUndefined()
  636. expect(result?.content).toEqual([{ type: 'text', text: '```console\nstarted background task bash-1\n```' }])
  637. })
  638. it('bash presentResult: an isError result carries no exit pill (no real process exit to report)', async () => {
  639. const ctx = await setup()
  640. // A spawn failure / abort has no process exit — the body is an error message,
  641. // not renderResult output, so no terminal output/exit is emitted.
  642. const out = ctx.tools.get('bash')!.presentResult!(
  643. { command: 'x', description: 'x' },
  644. { content: [{ type: 'text', text: 'command aborted' }], isError: true },
  645. )
  646. expect(out?.terminal).toBeUndefined()
  647. expect(out?.content).toEqual([{ type: 'text', text: '```console\ncommand aborted\n```' }])
  648. })
  649. it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => {
  650. const ctx = await setup()
  651. const present = ctx.tools.get('bash')!.presentResult!(
  652. { command: 'x', description: 'x' },
  653. { content: [{ type: 'image', url: 'https://x/y.png' }], isError: false },
  654. )
  655. expect(present).toBeUndefined()
  656. })
  657. it('bash presentResult: a result that is not exactly one block → undefined (no single text to fence)', async () => {
  658. const ctx = await setup()
  659. const args = { command: 'x', description: 'x' }
  660. // Empty content (no block) and multi-block content both fall through.
  661. expect(ctx.tools.get('bash')!.presentResult!(args, { content: [], isError: false })).toBeUndefined()
  662. expect(ctx.tools.get('bash')!.presentResult!(args, {
  663. content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }],
  664. isError: false,
  665. })).toBeUndefined()
  666. })
  667. it('bash_output / bash_kill presentCall: a readable task-scoped title, task id as rawInput', async () => {
  668. const ctx = await setup()
  669. expect(ctx.tools.get('bash_output')!.presentCall!({ task_id: 'bash-3' }))
  670. .toEqual({ title: 'Read output from background task bash-3', kind: 'execute', rawInput: 'bash-3' })
  671. expect(ctx.tools.get('bash_kill')!.presentCall!({ task_id: 'bash-3' }))
  672. .toEqual({ title: 'Kill background task bash-3', kind: 'execute', rawInput: 'bash-3' })
  673. })
  674. it('presentCall validates softly: malformed args (missing required description) return undefined, never throw', async () => {
  675. const ctx = await setup()
  676. // defineTool wraps presentCall to soft-validate against the schema and fall
  677. // back to undefined (a generic UI presentation) rather than throwing on the
  678. // display path — it may run on replay of arbitrary logged args. The
  679. // ToolDefinition.presentCall takes `unknown`, so a malformed shape needs no cast.
  680. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'ls' })).toBeUndefined()
  681. })
  682. })