tools.spec.ts 41 KB

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