1
0

tool-workflow.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import Loader from '@deepseek-ai/cordis-plugin-loader'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools'
  6. import type { ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools'
  7. import type { Agent } from '@deepseek-ai/dsh-agent'
  8. import { WorkflowRunId, WorkflowEngine } from '@deepseek-ai/dsh-workflow'
  9. import type {
  10. WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowResult, WorkflowRun,
  11. WorkflowRunId as WorkflowRunIdType, WorkflowStartRequest,
  12. } from '@deepseek-ai/dsh-workflow'
  13. import { CallId } from '@deepseek-ai/dsh-llm'
  14. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  15. import WorkerThreadWorkflowEngine from '@deepseek-ai/dsh-workflow-worker-thread'
  16. import * as toolWorkflow from '../src/index.ts'
  17. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  18. const testToolSignal = new AbortController().signal
  19. /** A controllable engine standing in behind ctx.workflowEngine (the tool's only seam). */
  20. class StubEngine extends WorkflowEngine {
  21. requests: WorkflowStartRequest[] = []
  22. cancels: string[] = []
  23. disposed = 0
  24. disposeBarrier: Promise<void> | undefined
  25. settle!: (result: WorkflowResult) => void
  26. readonly settlements = new Map<WorkflowRunIdType, (result: WorkflowResult) => void>()
  27. startError: Error | undefined
  28. start(request: WorkflowStartRequest): WorkflowRun {
  29. if (this.startError) throw this.startError
  30. this.requests.push(request)
  31. const id = WorkflowRunId(`run-${this.requests.length}`)
  32. const result = new Promise<WorkflowResult>((resolve) => { this.settle = resolve })
  33. this.settlements.set(id, this.settle)
  34. request.signal?.addEventListener('abort', () => {
  35. this.settle({ value: null, stopReason: 'cancelled', error: 'signal', agentsStarted: 0 })
  36. }, { once: true })
  37. return {
  38. id,
  39. meta: request.meta,
  40. result,
  41. cancel: (reason?: string) => {
  42. this.cancels.push(reason ?? 'cancelled')
  43. this.settle({ value: null, stopReason: 'cancelled', ...reason !== undefined ? { error: reason } : {}, agentsStarted: 0 })
  44. },
  45. dispose: async () => {
  46. this.disposed += 1
  47. await this.disposeBarrier
  48. this.settlements.delete(id)
  49. },
  50. }
  51. }
  52. settleRun(id: WorkflowRunIdType, result: WorkflowResult): void {
  53. const settle = this.settlements.get(id)
  54. if (settle === undefined) throw new Error(`unknown stub workflow ${id}`)
  55. settle(result)
  56. }
  57. agentStart(id: WorkflowRunIdType, agent: WorkflowAgentInfo): void {
  58. this.emitWorkflowEvent('workflow/agent-start', {
  59. id,
  60. meta: this.requests[Number(String(id).slice(4)) - 1]!.meta,
  61. }, agent)
  62. }
  63. agentEnd(id: WorkflowRunIdType, agent: WorkflowAgentEndInfo): void {
  64. this.emitWorkflowEvent('workflow/agent-end', {
  65. id,
  66. meta: this.requests[Number(String(id).slice(4)) - 1]!.meta,
  67. }, agent)
  68. }
  69. }
  70. async function setup(config?: { toolName?: string; maxResultChars?: number }) {
  71. const ctx = new Context()
  72. await ctx.plugin(SystemPrompt)
  73. await ctx.plugin(ToolRuntime)
  74. await ctx.plugin(StubEngine)
  75. await ctx.plugin(toolWorkflow, config ?? {})
  76. const engine = ctx.workflowEngine as StubEngine
  77. const session = Session.create(SessionId('caller'))
  78. const parent = { id: session.id, options: {}, session } as unknown as Agent
  79. return { ctx, engine, parent, session }
  80. }
  81. const SCRIPT = 'return 1'
  82. const META = { name: 'audit', description: 'd' }
  83. function execute(ctx: Context, args: unknown, extra?: {
  84. agent?: Agent
  85. signal?: AbortSignal
  86. parent?: ToolExecutionToken
  87. }): Promise<ToolExecutionResult> {
  88. return ctx.tools.execute({
  89. signal: testToolSignal,
  90. callId: CallId('call-1'),
  91. name: 'workflow',
  92. arguments: args,
  93. ...extra?.agent ? { agent: extra.agent } : {},
  94. ...extra?.signal ? { signal: extra.signal } : {},
  95. ...extra?.parent ? { parent: extra.parent } : {},
  96. })
  97. }
  98. describe('dsh-tool-workflow', () => {
  99. it('starts a run with the script/args/parent/signal and renders the completed value', async () => {
  100. const { ctx, engine, parent } = await setup()
  101. const controller = new AbortController()
  102. const pending = execute(ctx, { script: SCRIPT, meta: META, args: { files: ['a.ts'] } }, { agent: parent, signal: controller.signal })
  103. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  104. expect(engine.requests[0]).toMatchObject({ script: SCRIPT, meta: META, args: { files: ['a.ts'] }, parent })
  105. expect(engine.requests[0]!.signal).toBe(controller.signal)
  106. engine.settle({ value: { findings: [1, 2] }, stopReason: 'completed', agentsStarted: 7 })
  107. const result = await pending
  108. expect(result.isError).toBe(false)
  109. if (result.isError) throw new Error('expected workflow success')
  110. expect(result.value).toEqual({ runId: 'run-1', agentsStarted: 7, result: { findings: [1, 2] } })
  111. const rendered = (result.content[0] as { text: string }).text
  112. expect(rendered).toContain('workflow "audit" completed (7 agents)')
  113. expect(rendered).toContain('"findings"')
  114. expect(engine.disposed).toBe(1)
  115. })
  116. it('records one top-level run and its members in the calling Session after cleanup', async () => {
  117. const { ctx, engine, parent, session } = await setup()
  118. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  119. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  120. const runId = WorkflowRunId('run-1')
  121. engine.agentStart(runId, {
  122. seq: 1,
  123. label: '',
  124. phase: '',
  125. childId: SessionId('child-1'),
  126. })
  127. engine.agentEnd(runId, {
  128. seq: 1,
  129. label: '',
  130. phase: '',
  131. childId: SessionId('child-1'),
  132. outcome: 'completed',
  133. })
  134. engine.settleRun(runId, { value: 1, stopReason: 'completed', agentsStarted: 1 })
  135. expect((await pending).isError).toBe(false)
  136. expect(engine.disposed).toBe(1)
  137. expect(session.events.map(event => [event.type, event.data])).toEqual([
  138. ['tool-workflow/run-start', { runId: 'run-1', name: 'audit' }],
  139. ['tool-workflow/agent-start', {
  140. runId: 'run-1', seq: 1, label: '', phase: '', childId: 'child-1',
  141. }],
  142. ['tool-workflow/agent-end', { runId: 'run-1', seq: 1, outcome: 'completed' }],
  143. ['tool-workflow/run-end', { runId: 'run-1', stopReason: 'completed' }],
  144. ])
  145. })
  146. it('writes run-end only after run disposal reaches quiescence', async () => {
  147. const { ctx, engine, parent, session } = await setup()
  148. const barrier = Promise.withResolvers<undefined>()
  149. engine.disposeBarrier = barrier.promise
  150. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  151. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  152. engine.settleRun(WorkflowRunId('run-1'), {
  153. value: null, stopReason: 'completed', agentsStarted: 0,
  154. })
  155. await vi.waitFor(() => { expect(engine.disposed).toBe(1) })
  156. expect(session.events.map(event => event.type)).toEqual(['tool-workflow/run-start'])
  157. barrier.resolve(undefined)
  158. expect((await pending).isError).toBe(false)
  159. expect(session.events.map(event => event.type)).toEqual([
  160. 'tool-workflow/run-start', 'tool-workflow/run-end',
  161. ])
  162. })
  163. it('records zero-member and concurrent runs independently', async () => {
  164. const { ctx, engine, parent, session } = await setup()
  165. const first = execute(ctx, { script: SCRIPT, meta: { ...META, name: 'first' } }, { agent: parent })
  166. const second = execute(ctx, { script: SCRIPT, meta: { ...META, name: 'second' } }, { agent: parent })
  167. await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) })
  168. const secondId = WorkflowRunId('run-2')
  169. engine.agentStart(secondId, {
  170. seq: 1, label: 'member', childId: SessionId('child-2'),
  171. })
  172. engine.agentEnd(secondId, {
  173. seq: 1, label: 'member', childId: SessionId('child-2'), outcome: 'failed',
  174. })
  175. engine.settleRun(WorkflowRunId('run-1'), { value: null, stopReason: 'completed', agentsStarted: 0 })
  176. engine.settleRun(secondId, { value: null, stopReason: 'error', error: 'child failed', agentsStarted: 1 })
  177. expect((await first).isError).toBe(false)
  178. expect((await second).isError).toBe(true)
  179. expect(session.events.filter(event => event.type === 'tool-workflow/agent-start'))
  180. .toHaveLength(1)
  181. expect(session.events.filter(event => event.type === 'tool-workflow/run-end').map(event => event.data))
  182. .toEqual([
  183. { runId: 'run-1', stopReason: 'completed' },
  184. { runId: 'run-2', stopReason: 'error' },
  185. ])
  186. })
  187. it('does not record nested transport executions', async () => {
  188. const { ctx, engine, parent, session } = await setup()
  189. const pending = execute(ctx, { script: SCRIPT, meta: META }, {
  190. agent: parent,
  191. parent: Symbol('outer') as ToolExecutionToken,
  192. })
  193. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  194. engine.settleRun(WorkflowRunId('run-1'), { value: null, stopReason: 'completed', agentsStarted: 0 })
  195. expect((await pending).isError).toBe(false)
  196. expect(session.events).toEqual([])
  197. })
  198. it.each([
  199. 'tool-workflow/run-start',
  200. 'tool-workflow/agent-start',
  201. 'tool-workflow/agent-end',
  202. 'tool-workflow/run-end',
  203. ] as const)('isolates a first append failure at %s and preserves a valid prefix', async (failedType) => {
  204. const { ctx, engine, parent, session } = await setup()
  205. const warnings: string[] = []
  206. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  207. const append = session.append.bind(session)
  208. session.append = ((type: Parameters<Session['append']>[0], data: never) => {
  209. if (type === failedType) throw new Error(`injected ${failedType} failure`)
  210. return append(type, data)
  211. }) as Session['append']
  212. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  213. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  214. const runId = WorkflowRunId('run-1')
  215. engine.agentStart(runId, {
  216. seq: 1, label: 'member', childId: SessionId('child-1'),
  217. })
  218. engine.agentEnd(runId, {
  219. seq: 1, label: 'member', childId: SessionId('child-1'), outcome: 'completed',
  220. })
  221. engine.settleRun(runId, { value: null, stopReason: 'completed', agentsStarted: 1 })
  222. expect((await pending).isError).toBe(false)
  223. expect(engine.disposed).toBe(1)
  224. expect(warnings).toHaveLength(1)
  225. expect(warnings[0]).toContain(failedType)
  226. const types = session.events.map(event => event.type)
  227. const expectedPrefixes = {
  228. 'tool-workflow/run-start': [],
  229. 'tool-workflow/agent-start': ['tool-workflow/run-start'],
  230. 'tool-workflow/agent-end': ['tool-workflow/run-start', 'tool-workflow/agent-start'],
  231. 'tool-workflow/run-end': [
  232. 'tool-workflow/run-start', 'tool-workflow/agent-start', 'tool-workflow/agent-end',
  233. ],
  234. } as const
  235. expect(types).toEqual(expectedPrefixes[failedType])
  236. })
  237. it('contains an append failure whose thrown value cannot be rendered', async () => {
  238. const { ctx, engine, parent, session } = await setup()
  239. const warnings: string[] = []
  240. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  241. session.append = () => {
  242. throw { toString: () => { throw new Error('coercion trap') } }
  243. }
  244. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  245. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  246. engine.settleRun(WorkflowRunId('run-1'), {
  247. value: null, stopReason: 'completed', agentsStarted: 0,
  248. })
  249. expect((await pending).isError).toBe(false)
  250. expect(warnings).toHaveLength(1)
  251. expect(warnings[0]).toContain('[unrenderable thrown value]')
  252. })
  253. it('maps a non-completed stop reason to an isError result (and still disposes)', async () => {
  254. const { ctx, engine, parent } = await setup()
  255. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  256. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  257. engine.settle({ value: null, stopReason: 'error', error: 'script threw: boom', agentsStarted: 2 })
  258. const result = await pending
  259. expect(result.isError).toBe(true)
  260. expect((result.content[0] as { text: string }).text).toContain('workflow run failed: script threw: boom')
  261. expect(engine.disposed).toBe(1)
  262. })
  263. it('reports a cancelled run distinctly (with and without a reason)', async () => {
  264. const { ctx, engine, parent } = await setup()
  265. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  266. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  267. engine.settle({ value: null, stopReason: 'cancelled', error: 'user', agentsStarted: 0 })
  268. const result = await pending
  269. expect(result.isError).toBe(true)
  270. expect((result.content[0] as { text: string }).text).toContain('workflow run was cancelled (user)')
  271. const bare = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  272. await vi.waitFor(() => { expect(engine.requests.length).toBe(2) })
  273. engine.settle({ value: null, stopReason: 'cancelled', agentsStarted: 0 })
  274. expect(((await bare).content[0] as { text: string }).text.trim().endsWith('cancelled')).toBe(true)
  275. })
  276. it('an error result without a message renders the unknown-error fallback', async () => {
  277. const { ctx, engine, parent } = await setup()
  278. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  279. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  280. engine.settle({ value: null, stopReason: 'error', agentsStarted: 0 })
  281. expect(((await pending).content[0] as { text: string }).text).toContain('unknown error')
  282. })
  283. it('cancels the run when exec.signal aborts MID-FLIGHT (the abort bridge)', async () => {
  284. const { ctx, engine, parent } = await setup()
  285. const controller = new AbortController()
  286. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  287. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  288. controller.abort()
  289. const result = await pending
  290. expect(result.isError).toBe(true)
  291. expect(engine.cancels).toContain('parent step aborted')
  292. expect(engine.disposed).toBe(1)
  293. })
  294. it('a synchronous engine start throw (meta/parse failure) becomes an isError result', async () => {
  295. const { ctx, engine, parent } = await setup()
  296. engine.startError = new Error('invalid meta: meta.name must be a non-empty string')
  297. const result = await execute(ctx, { script: 'nope', meta: { name: '', description: 'd' } }, { agent: parent })
  298. expect(result.isError).toBe(true)
  299. expect((result.content[0] as { text: string }).text).toContain('meta.name must be a non-empty string')
  300. })
  301. it('requires a calling agent (fails loud without exec.agent)', async () => {
  302. const { ctx, engine } = await setup()
  303. const result = await execute(ctx, { script: SCRIPT, meta: META })
  304. expect(result.isError).toBe(true)
  305. expect((result.content[0] as { text: string }).text).toContain('requires a calling agent')
  306. expect(engine.requests.length).toBe(0)
  307. })
  308. it('validates its own arguments via the schema DSL (missing script)', async () => {
  309. const { ctx, parent } = await setup()
  310. const result = await execute(ctx, {}, { agent: parent })
  311. expect(result.isError).toBe(true)
  312. expect(result.error?.info?.code).toBe('INVALID_ARGS')
  313. })
  314. it('skips workflow startup when exec.signal is already aborted', async () => {
  315. const { ctx, engine, parent } = await setup()
  316. const controller = new AbortController()
  317. controller.abort()
  318. const result = await execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  319. expect(result.isError).toBe(true)
  320. expect(result.error).toEqual({
  321. message: 'tool call aborted before dispatch',
  322. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  323. })
  324. expect(engine.requests).toHaveLength(0)
  325. expect(engine.cancels).toHaveLength(0)
  326. expect(engine.disposed).toBe(0)
  327. })
  328. it('truncates an oversized rendered value with a notice (maxResultChars)', async () => {
  329. const { ctx, engine, parent } = await setup({ maxResultChars: 40 })
  330. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  331. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  332. engine.settle({ value: { blob: 'x'.repeat(500) }, stopReason: 'completed', agentsStarted: 1 })
  333. const result = await pending
  334. if (result.isError) throw new Error('expected workflow success')
  335. expect(result.value).toEqual({ runId: 'run-1', agentsStarted: 1, result: { blob: 'x'.repeat(500) } })
  336. const rendered = (result.content[0] as { text: string }).text
  337. expect(rendered).toContain('[truncated:')
  338. expect(rendered.length).toBeLessThan(400)
  339. })
  340. it('registers under a configured toolName and unregisters on fiber dispose (HMR safety)', async () => {
  341. const ctx = new Context()
  342. await ctx.plugin(SystemPrompt)
  343. await ctx.plugin(ToolRuntime)
  344. await ctx.plugin(StubEngine)
  345. const fiber = await ctx.plugin(toolWorkflow, { toolName: 'orchestrate' })
  346. expect(ctx.tools.get('orchestrate')).toBeDefined()
  347. expect(ctx.tools.get('workflow')).toBeUndefined()
  348. // The usage-policy prompt section rides the same registration: present
  349. // under the CONFIGURED name (its guidance names the tool it describes)…
  350. const sections = (await ctx.systemPrompt.assemble()).sections
  351. const section = sections.find(s => s.name === 'tool:orchestrate')
  352. expect(section?.text).toContain('orchestrate')
  353. expect(sections.some(s => s.name === 'tool:workflow')).toBe(false)
  354. await fiber.dispose()
  355. expect(ctx.tools.get('orchestrate')).toBeUndefined()
  356. // …and gone with the fiber — a reload must not leak a stale section.
  357. expect((await ctx.systemPrompt.assemble()).sections.some(s => s.name === 'tool:orchestrate')).toBe(false)
  358. })
  359. it('presents a generic pending card titled by the meta name, with the script as rawInput', async () => {
  360. const { ctx } = await setup()
  361. const tool = ctx.tools.get('workflow')!
  362. const view = tool.presentCall!({ script: SCRIPT, meta: META })
  363. expect(view).toMatchObject({ card: 'generic', title: 'workflow: audit', rawInput: SCRIPT })
  364. })
  365. it('presentResult keeps the generic card; presentation is pure and replay-safe on malformed args', async () => {
  366. const { ctx } = await setup()
  367. const tool = ctx.tools.get('workflow')!
  368. expect(tool.presentResult!({ script: SCRIPT, meta: META }, { content: [], isError: false })).toEqual({ card: 'generic' })
  369. // defineTool soft-validates presentation args: a malformed logged shape
  370. // (wrong fields entirely, or a call missing its meta) falls back to
  371. // undefined instead of throwing mid-replay.
  372. expect(tool.presentCall!({ not: 'the schema' })).toBeUndefined()
  373. expect(tool.presentCall!({ script: SCRIPT })).toBeUndefined()
  374. })
  375. it('has the namespace-plugin export shape (no stray default)', () => {
  376. expect('default' in toolWorkflow).toBe(false)
  377. expect(toolWorkflow.name).toBe('tool-workflow')
  378. expect(toolWorkflow.inject).toEqual(['tools', 'workflowEngine', 'systemPrompt'])
  379. const loader = Object.create(Loader.prototype) as Loader
  380. const unwrapped = loader.unwrapExports(toolWorkflow) as Record<string, unknown>
  381. expect(unwrapped).toBe(toolWorkflow)
  382. expect(typeof unwrapped.apply).toBe('function')
  383. })
  384. describe('composition with the REAL worker-thread engine (the mock above must stay honest)', () => {
  385. it('an abort releases the tool even when the script parks on a promise no hook owns', async () => {
  386. // The tool and loop await run.result before cleanup, so cancellation must settle a script
  387. // parked on an unowned promise. Exercise that guarantee through the real registry and worker.
  388. const ctx = new Context()
  389. await ctx.plugin(SystemPrompt)
  390. await ctx.plugin(ToolRuntime)
  391. await ctx.plugin(SubagentRuntime)
  392. ctx.subagents.registerProvider({
  393. name: 'spawn',
  394. capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  395. inheritsParentContext: false,
  396. start: () => Promise.reject(new Error('the parked-script fixture must not start a child')),
  397. })
  398. await ctx.plugin(WorkerThreadWorkflowEngine, { disposeGraceMs: 30 })
  399. await ctx.plugin(toolWorkflow, {})
  400. const session = Session.create(SessionId('caller'))
  401. const parent = { id: session.id, options: {}, session } as unknown as Agent
  402. const controller = new AbortController()
  403. const pending = execute(ctx, {
  404. script: 'await new Promise(() => {})\nreturn 1',
  405. meta: { name: 'stuck', description: 'parks forever' },
  406. }, { agent: parent, signal: controller.signal })
  407. // Give the run a beat to start (past its synchronous slice), then abort.
  408. await new Promise(resolve => setTimeout(resolve, 20))
  409. controller.abort('user abort')
  410. const result = await pending
  411. expect(result.isError).toBe(true)
  412. expect((result.content[0] as { text: string }).text).toContain('cancelled')
  413. })
  414. })
  415. })