tool-workflow.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. const rendered = (result.content[0] as { text: string }).text
  77. expect(rendered).toContain('workflow "stub-flow" completed (7 agents)')
  78. expect(rendered).toContain('"findings"')
  79. expect(engine.disposed).toBe(1)
  80. })
  81. it('maps a non-completed stop reason to an isError result (and still disposes)', async () => {
  82. const { ctx, engine, parent } = await setup()
  83. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  84. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  85. engine.settle({ value: null, stopReason: 'error', error: 'script threw: boom', agentsStarted: 2 })
  86. const result = await pending
  87. expect(result.isError).toBe(true)
  88. expect((result.content[0] as { text: string }).text).toContain('workflow run failed: script threw: boom')
  89. expect(engine.disposed).toBe(1)
  90. })
  91. it('reports a cancelled run distinctly (with and without a reason)', async () => {
  92. const { ctx, engine, parent } = await setup()
  93. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  94. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  95. engine.settle({ value: null, stopReason: 'cancelled', error: 'user', agentsStarted: 0 })
  96. const result = await pending
  97. expect(result.isError).toBe(true)
  98. expect((result.content[0] as { text: string }).text).toContain('workflow run was cancelled (user)')
  99. const bare = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  100. await vi.waitFor(() => { expect(engine.requests.length).toBe(2) })
  101. engine.settle({ value: null, stopReason: 'cancelled', agentsStarted: 0 })
  102. expect(((await bare).content[0] as { text: string }).text.trim().endsWith('cancelled')).toBe(true)
  103. })
  104. it('an error result without a message renders the unknown-error fallback', async () => {
  105. const { ctx, engine, parent } = await setup()
  106. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  107. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  108. engine.settle({ value: null, stopReason: 'error', agentsStarted: 0 })
  109. expect(((await pending).content[0] as { text: string }).text).toContain('unknown error')
  110. })
  111. it('cancels the run when exec.signal aborts MID-FLIGHT (the abort bridge)', async () => {
  112. const { ctx, engine, parent } = await setup()
  113. const controller = new AbortController()
  114. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  115. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  116. controller.abort()
  117. const result = await pending
  118. expect(result.isError).toBe(true)
  119. expect(engine.cancels).toContain('parent step aborted')
  120. expect(engine.disposed).toBe(1)
  121. })
  122. it('a synchronous engine start throw (meta/parse failure) becomes an isError result', async () => {
  123. const { ctx, engine, parent } = await setup()
  124. engine.startError = new Error('invalid meta: meta.name must be a non-empty string')
  125. const result = await execute(ctx, { script: 'nope', meta: { name: '', description: 'd' } }, { agent: parent })
  126. expect(result.isError).toBe(true)
  127. expect((result.content[0] as { text: string }).text).toContain('meta.name must be a non-empty string')
  128. })
  129. it('requires a calling agent (fails loud without exec.agent)', async () => {
  130. const { ctx, engine } = await setup()
  131. const result = await execute(ctx, { script: SCRIPT, meta: META })
  132. expect(result.isError).toBe(true)
  133. expect((result.content[0] as { text: string }).text).toContain('requires a calling agent')
  134. expect(engine.requests.length).toBe(0)
  135. })
  136. it('validates its own arguments via the schema DSL (missing script)', async () => {
  137. const { ctx, parent } = await setup()
  138. const result = await execute(ctx, {}, { agent: parent })
  139. expect(result.isError).toBe(true)
  140. expect(result.error?.code).toBe('INVALID_ARGS')
  141. })
  142. it('cancels the run when exec.signal is ALREADY aborted at call time', async () => {
  143. const { ctx, engine, parent } = await setup()
  144. const controller = new AbortController()
  145. controller.abort()
  146. const result = await execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  147. expect(result.isError).toBe(true)
  148. expect(engine.cancels).toContain('parent step aborted')
  149. expect(engine.disposed).toBe(1)
  150. })
  151. it('truncates an oversized rendered value with a notice (maxResultChars)', async () => {
  152. const { ctx, engine, parent } = await setup({ maxResultChars: 40 })
  153. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  154. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  155. engine.settle({ value: { blob: 'x'.repeat(500) }, stopReason: 'completed', agentsStarted: 1 })
  156. const rendered = ((await pending).content[0] as { text: string }).text
  157. expect(rendered).toContain('[truncated:')
  158. expect(rendered.length).toBeLessThan(400)
  159. })
  160. it('registers under a configured toolName and unregisters on fiber dispose (HMR safety)', async () => {
  161. const ctx = new Context()
  162. await ctx.plugin(SystemPrompt)
  163. await ctx.plugin(ToolRegistry)
  164. await ctx.plugin(StubEngine)
  165. const fiber = await ctx.plugin(toolWorkflow, { toolName: 'orchestrate' })
  166. expect(ctx.tools.get('orchestrate')).toBeDefined()
  167. expect(ctx.tools.get('workflow')).toBeUndefined()
  168. // The usage-policy prompt section rides the same registration: present
  169. // under the CONFIGURED name (its guidance names the tool it describes)…
  170. const sections = (await ctx.systemPrompt.assemble()).sections
  171. const section = sections.find(s => s.name === 'tool:orchestrate')
  172. expect(section?.text).toContain('orchestrate')
  173. expect(sections.some(s => s.name === 'tool:workflow')).toBe(false)
  174. await fiber.dispose()
  175. expect(ctx.tools.get('orchestrate')).toBeUndefined()
  176. // …and gone with the fiber — a reload must not leak a stale section.
  177. expect((await ctx.systemPrompt.assemble()).sections.some(s => s.name === 'tool:orchestrate')).toBe(false)
  178. })
  179. it('presents a generic pending card titled by the meta name, with the script as rawInput', async () => {
  180. const { ctx } = await setup()
  181. const tool = ctx.tools.get('workflow')!
  182. const view = tool.presentCall!({ script: SCRIPT, meta: META })
  183. expect(view).toMatchObject({ card: 'generic', title: 'workflow: audit', rawInput: SCRIPT })
  184. })
  185. it('presentResult keeps the generic card; presentation is pure and replay-safe on malformed args', async () => {
  186. const { ctx } = await setup()
  187. const tool = ctx.tools.get('workflow')!
  188. expect(tool.presentResult!({ script: SCRIPT, meta: META }, { content: [], isError: false })).toEqual({ card: 'generic' })
  189. // defineTool soft-validates presentation args: a malformed logged shape
  190. // (wrong fields entirely, or a call missing its meta) falls back to
  191. // undefined instead of throwing mid-replay.
  192. expect(tool.presentCall!({ not: 'the schema' })).toBeUndefined()
  193. expect(tool.presentCall!({ script: SCRIPT })).toBeUndefined()
  194. })
  195. it('has the namespace-plugin export shape (no stray default)', () => {
  196. expect('default' in toolWorkflow).toBe(false)
  197. expect(toolWorkflow.name).toBe('tool-workflow')
  198. expect(toolWorkflow.inject).toEqual(['tools', 'workflows', 'systemPrompt'])
  199. const loader = Object.create(Loader.prototype) as Loader
  200. const unwrapped = loader.unwrapExports(toolWorkflow) as Record<string, unknown>
  201. expect(unwrapped).toBe(toolWorkflow)
  202. expect(typeof unwrapped.apply).toBe('function')
  203. })
  204. describe('composition with the REAL worker-thread engine (the mock above must stay honest)', () => {
  205. it('an abort releases the tool even when the script parks on a promise no hook owns', async () => {
  206. // The tool and loop await run.result before cleanup, so cancellation must settle a script
  207. // parked on an unowned promise. Exercise that guarantee through the real registry and worker.
  208. const ctx = new Context()
  209. await ctx.plugin(SystemPrompt)
  210. await ctx.plugin(ToolRegistry)
  211. await ctx.plugin(SubagentService)
  212. await ctx.plugin(WorkerWorkflowEngine, { disposeGraceMs: 30 })
  213. await ctx.plugin(toolWorkflow, {})
  214. const parent = { id: SessionId('caller'), options: {} } as unknown as Agent
  215. const controller = new AbortController()
  216. const pending = execute(ctx, {
  217. script: 'await new Promise(() => {})\nreturn 1',
  218. meta: { name: 'stuck', description: 'parks forever' },
  219. }, { agent: parent, signal: controller.signal })
  220. // Give the run a beat to start (past its synchronous slice), then abort.
  221. await new Promise(resolve => setTimeout(resolve, 20))
  222. controller.abort('user abort')
  223. const result = await pending
  224. expect(result.isError).toBe(true)
  225. expect((result.content[0] as { text: string }).text).toContain('cancelled')
  226. })
  227. })
  228. })