tool-workflow.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import ToolRegistry from '@deepseek-ai/dsh-tools'
  6. import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  7. import type { Agent } from '@deepseek-ai/dsh-agent'
  8. import { WorkflowRunId, WorkflowService } from '@deepseek-ai/dsh-workflow'
  9. import type { WorkflowResult, WorkflowRun, WorkflowStartRequest } from '@deepseek-ai/dsh-workflow'
  10. import { CallId } from '@deepseek-ai/dsh-llm'
  11. import SubagentService from '@deepseek-ai/dsh-subagent'
  12. import WorkerWorkflowEngine from '@deepseek-ai/dsh-workflow-workerthread'
  13. import * as toolWorkflow from '../src/index.ts'
  14. import { SessionId } from '@deepseek-ai/dsh-session'
  15. /** A controllable engine standing in behind ctx.workflows (the tool's only seam). */
  16. class StubEngine extends WorkflowService {
  17. requests: WorkflowStartRequest[] = []
  18. cancels: string[] = []
  19. disposed = 0
  20. settle!: (result: WorkflowResult) => void
  21. startError: Error | undefined
  22. start(request: WorkflowStartRequest): WorkflowRun {
  23. if (this.startError) throw this.startError
  24. this.requests.push(request)
  25. const result = new Promise<WorkflowResult>((resolve) => { this.settle = resolve })
  26. request.signal?.addEventListener('abort', () => {
  27. this.settle({ value: null, stopReason: 'cancelled', error: 'signal', agentsStarted: 0 })
  28. }, { once: true })
  29. return {
  30. id: WorkflowRunId('run-1'),
  31. meta: { name: 'stub-flow', description: 'd' },
  32. result,
  33. cancel: (reason?: string) => {
  34. this.cancels.push(reason ?? 'cancelled')
  35. this.settle({ value: null, stopReason: 'cancelled', ...reason !== undefined ? { error: reason } : {}, agentsStarted: 0 })
  36. },
  37. dispose: () => {
  38. this.disposed += 1
  39. return Promise.resolve()
  40. },
  41. }
  42. }
  43. }
  44. async function setup(config?: { toolName?: string; maxResultChars?: number }) {
  45. const ctx = new Context()
  46. await ctx.plugin(SystemPrompt)
  47. await ctx.plugin(ToolRegistry)
  48. await ctx.plugin(StubEngine)
  49. await ctx.plugin(toolWorkflow, config ?? {})
  50. const engine = ctx.workflows as StubEngine
  51. const parent = { id: SessionId('caller'), options: {} } as unknown as Agent
  52. return { ctx, engine, parent }
  53. }
  54. const SCRIPT = 'return 1'
  55. const META = { name: 'audit', description: 'd' }
  56. function execute(ctx: Context, args: unknown, extra?: { agent?: Agent; signal?: AbortSignal }): Promise<ToolExecutionResult> {
  57. return ctx.tools.execute({
  58. callId: CallId('call-1'),
  59. name: 'workflow',
  60. arguments: args,
  61. ...extra?.agent ? { agent: extra.agent } : {},
  62. ...extra?.signal ? { signal: extra.signal } : {},
  63. })
  64. }
  65. describe('dsh-tool-workflow', () => {
  66. it('starts a run with the script/args/parent/signal and renders the completed value', async () => {
  67. const { ctx, engine, parent } = await setup()
  68. const controller = new AbortController()
  69. const pending = execute(ctx, { script: SCRIPT, meta: META, args: { files: ['a.ts'] } }, { agent: parent, signal: controller.signal })
  70. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  71. expect(engine.requests[0]).toMatchObject({ script: SCRIPT, meta: META, args: { files: ['a.ts'] }, parent })
  72. expect(engine.requests[0]!.signal).toBe(controller.signal)
  73. engine.settle({ value: { findings: [1, 2] }, stopReason: 'completed', agentsStarted: 7 })
  74. const result = await pending
  75. expect(result.isError).toBe(false)
  76. if (result.isError) throw new Error('expected workflow success')
  77. expect(result.value).toEqual({ runId: 'run-1', agentsStarted: 7, result: { findings: [1, 2] } })
  78. const rendered = (result.content[0] as { text: string }).text
  79. expect(rendered).toContain('workflow "audit" completed (7 agents)')
  80. expect(rendered).toContain('"findings"')
  81. expect(engine.disposed).toBe(1)
  82. })
  83. it('maps a non-completed stop reason to an isError result (and still disposes)', async () => {
  84. const { ctx, engine, parent } = await setup()
  85. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  86. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  87. engine.settle({ value: null, stopReason: 'error', error: 'script threw: boom', agentsStarted: 2 })
  88. const result = await pending
  89. expect(result.isError).toBe(true)
  90. expect((result.content[0] as { text: string }).text).toContain('workflow run failed: script threw: boom')
  91. expect(engine.disposed).toBe(1)
  92. })
  93. it('reports a cancelled run distinctly (with and without a reason)', async () => {
  94. const { ctx, engine, parent } = await setup()
  95. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  96. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  97. engine.settle({ value: null, stopReason: 'cancelled', error: 'user', agentsStarted: 0 })
  98. const result = await pending
  99. expect(result.isError).toBe(true)
  100. expect((result.content[0] as { text: string }).text).toContain('workflow run was cancelled (user)')
  101. const bare = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  102. await vi.waitFor(() => { expect(engine.requests.length).toBe(2) })
  103. engine.settle({ value: null, stopReason: 'cancelled', agentsStarted: 0 })
  104. expect(((await bare).content[0] as { text: string }).text.trim().endsWith('cancelled')).toBe(true)
  105. })
  106. it('an error result without a message renders the unknown-error fallback', async () => {
  107. const { ctx, engine, parent } = await setup()
  108. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  109. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  110. engine.settle({ value: null, stopReason: 'error', agentsStarted: 0 })
  111. expect(((await pending).content[0] as { text: string }).text).toContain('unknown error')
  112. })
  113. it('cancels the run when exec.signal aborts MID-FLIGHT (the abort bridge)', async () => {
  114. const { ctx, engine, parent } = await setup()
  115. const controller = new AbortController()
  116. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  117. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  118. controller.abort()
  119. const result = await pending
  120. expect(result.isError).toBe(true)
  121. expect(engine.cancels).toContain('parent step aborted')
  122. expect(engine.disposed).toBe(1)
  123. })
  124. it('a synchronous engine start throw (meta/parse failure) becomes an isError result', async () => {
  125. const { ctx, engine, parent } = await setup()
  126. engine.startError = new Error('invalid meta: meta.name must be a non-empty string')
  127. const result = await execute(ctx, { script: 'nope', meta: { name: '', description: 'd' } }, { agent: parent })
  128. expect(result.isError).toBe(true)
  129. expect((result.content[0] as { text: string }).text).toContain('meta.name must be a non-empty string')
  130. })
  131. it('requires a calling agent (fails loud without exec.agent)', async () => {
  132. const { ctx, engine } = await setup()
  133. const result = await execute(ctx, { script: SCRIPT, meta: META })
  134. expect(result.isError).toBe(true)
  135. expect((result.content[0] as { text: string }).text).toContain('requires a calling agent')
  136. expect(engine.requests.length).toBe(0)
  137. })
  138. it('validates its own arguments via the schema DSL (missing script)', async () => {
  139. const { ctx, parent } = await setup()
  140. const result = await execute(ctx, {}, { agent: parent })
  141. expect(result.isError).toBe(true)
  142. expect(result.error?.info?.code).toBe('INVALID_ARGS')
  143. })
  144. it('cancels the run when exec.signal is ALREADY aborted at call time', async () => {
  145. const { ctx, engine, parent } = await setup()
  146. const controller = new AbortController()
  147. controller.abort()
  148. const result = await execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  149. expect(result.isError).toBe(true)
  150. expect(engine.cancels).toContain('parent step aborted')
  151. expect(engine.disposed).toBe(1)
  152. })
  153. it('truncates an oversized rendered value with a notice (maxResultChars)', async () => {
  154. const { ctx, engine, parent } = await setup({ maxResultChars: 40 })
  155. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  156. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  157. engine.settle({ value: { blob: 'x'.repeat(500) }, stopReason: 'completed', agentsStarted: 1 })
  158. const result = await pending
  159. if (result.isError) throw new Error('expected workflow success')
  160. expect(result.value).toEqual({ runId: 'run-1', agentsStarted: 1, result: { blob: 'x'.repeat(500) } })
  161. const rendered = (result.content[0] as { text: string }).text
  162. expect(rendered).toContain('[truncated:')
  163. expect(rendered.length).toBeLessThan(400)
  164. })
  165. it('registers under a configured toolName and unregisters on fiber dispose (HMR safety)', async () => {
  166. const ctx = new Context()
  167. await ctx.plugin(SystemPrompt)
  168. await ctx.plugin(ToolRegistry)
  169. await ctx.plugin(StubEngine)
  170. const fiber = await ctx.plugin(toolWorkflow, { toolName: 'orchestrate' })
  171. expect(ctx.tools.get('orchestrate')).toBeDefined()
  172. expect(ctx.tools.get('workflow')).toBeUndefined()
  173. // The usage-policy prompt section rides the same registration: present
  174. // under the CONFIGURED name (its guidance names the tool it describes)…
  175. const sections = (await ctx.systemPrompt.assemble()).sections
  176. const section = sections.find(s => s.name === 'tool:orchestrate')
  177. expect(section?.text).toContain('orchestrate')
  178. expect(sections.some(s => s.name === 'tool:workflow')).toBe(false)
  179. await fiber.dispose()
  180. expect(ctx.tools.get('orchestrate')).toBeUndefined()
  181. // …and gone with the fiber — a reload must not leak a stale section.
  182. expect((await ctx.systemPrompt.assemble()).sections.some(s => s.name === 'tool:orchestrate')).toBe(false)
  183. })
  184. it('presents a generic pending card titled by the meta name, with the script as rawInput', async () => {
  185. const { ctx } = await setup()
  186. const tool = ctx.tools.get('workflow')!
  187. const view = tool.presentCall!({ script: SCRIPT, meta: META })
  188. expect(view).toMatchObject({ card: 'generic', title: 'workflow: audit', rawInput: SCRIPT })
  189. })
  190. it('presentResult keeps the generic card; presentation is pure and replay-safe on malformed args', async () => {
  191. const { ctx } = await setup()
  192. const tool = ctx.tools.get('workflow')!
  193. expect(tool.presentResult!({ script: SCRIPT, meta: META }, { content: [], isError: false })).toEqual({ card: 'generic' })
  194. // defineTool soft-validates presentation args: a malformed logged shape
  195. // (wrong fields entirely, or a call missing its meta) falls back to
  196. // undefined instead of throwing mid-replay.
  197. expect(tool.presentCall!({ not: 'the schema' })).toBeUndefined()
  198. expect(tool.presentCall!({ script: SCRIPT })).toBeUndefined()
  199. })
  200. it('has the namespace-plugin export shape (no stray default)', () => {
  201. expect('default' in toolWorkflow).toBe(false)
  202. expect(toolWorkflow.name).toBe('tool-workflow')
  203. expect(toolWorkflow.inject).toEqual(['tools', 'workflows', 'systemPrompt'])
  204. const loader = Object.create(Loader.prototype) as Loader
  205. const unwrapped = loader.unwrapExports(toolWorkflow) as Record<string, unknown>
  206. expect(unwrapped).toBe(toolWorkflow)
  207. expect(typeof unwrapped.apply).toBe('function')
  208. })
  209. describe('composition with the REAL worker-thread engine (the mock above must stay honest)', () => {
  210. it('an abort releases the tool even when the script parks on a promise no hook owns', async () => {
  211. // The tool and loop await run.result before cleanup, so cancellation must settle a script
  212. // parked on an unowned promise. Exercise that guarantee through the real registry and worker.
  213. const ctx = new Context()
  214. await ctx.plugin(SystemPrompt)
  215. await ctx.plugin(ToolRegistry)
  216. await ctx.plugin(SubagentService)
  217. ctx.subagents.registerProvider({
  218. name: 'spawn',
  219. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  220. inheritsParentContext: false,
  221. start: () => Promise.reject(new Error('the parked-script fixture must not start a child')),
  222. })
  223. await ctx.plugin(WorkerWorkflowEngine, { disposeGraceMs: 30 })
  224. await ctx.plugin(toolWorkflow, {})
  225. const parent = { id: SessionId('caller'), options: {} } as unknown as Agent
  226. const controller = new AbortController()
  227. const pending = execute(ctx, {
  228. script: 'await new Promise(() => {})\nreturn 1',
  229. meta: { name: 'stuck', description: 'parks forever' },
  230. }, { agent: parent, signal: controller.signal })
  231. // Give the run a beat to start (past its synchronous slice), then abort.
  232. await new Promise(resolve => setTimeout(resolve, 20))
  233. controller.abort('user abort')
  234. const result = await pending
  235. expect(result.isError).toBe(true)
  236. expect((result.content[0] as { text: string }).text).toContain('cancelled')
  237. })
  238. })
  239. })