tools.spec.ts 40 KB

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