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, { TOOL_ABORTED_BEFORE_DISPATCH } 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. const testToolSignal = new AbortController().signal
  16. /** A controllable engine standing in behind ctx.workflows (the tool's only seam). */
  17. class StubEngine extends WorkflowService {
  18. requests: WorkflowStartRequest[] = []
  19. cancels: string[] = []
  20. disposed = 0
  21. settle!: (result: WorkflowResult) => void
  22. startError: Error | undefined
  23. start(request: WorkflowStartRequest): WorkflowRun {
  24. if (this.startError) throw this.startError
  25. this.requests.push(request)
  26. const result = new Promise<WorkflowResult>((resolve) => { this.settle = resolve })
  27. request.signal?.addEventListener('abort', () => {
  28. this.settle({ value: null, stopReason: 'cancelled', error: 'signal', agentsStarted: 0 })
  29. }, { once: true })
  30. return {
  31. id: WorkflowRunId('run-1'),
  32. meta: { name: 'stub-flow', description: 'd' },
  33. result,
  34. cancel: (reason?: string) => {
  35. this.cancels.push(reason ?? 'cancelled')
  36. this.settle({ value: null, stopReason: 'cancelled', ...reason !== undefined ? { error: reason } : {}, agentsStarted: 0 })
  37. },
  38. dispose: () => {
  39. this.disposed += 1
  40. return Promise.resolve()
  41. },
  42. }
  43. }
  44. }
  45. async function setup(config?: { toolName?: string; maxResultChars?: number }) {
  46. const ctx = new Context()
  47. await ctx.plugin(SystemPrompt)
  48. await ctx.plugin(ToolRegistry)
  49. await ctx.plugin(StubEngine)
  50. await ctx.plugin(toolWorkflow, config ?? {})
  51. const engine = ctx.workflows as StubEngine
  52. const parent = { id: SessionId('caller'), options: {} } as unknown as Agent
  53. return { ctx, engine, parent }
  54. }
  55. const SCRIPT = 'return 1'
  56. const META = { name: 'audit', description: 'd' }
  57. function execute(ctx: Context, args: unknown, extra?: { agent?: Agent; signal?: AbortSignal }): Promise<ToolExecutionResult> {
  58. return ctx.tools.execute({
  59. signal: testToolSignal,
  60. callId: CallId('call-1'),
  61. name: 'workflow',
  62. arguments: args,
  63. ...extra?.agent ? { agent: extra.agent } : {},
  64. ...extra?.signal ? { signal: extra.signal } : {},
  65. })
  66. }
  67. describe('dsh-tool-workflow', () => {
  68. it('starts a run with the script/args/parent/signal and renders the completed value', async () => {
  69. const { ctx, engine, parent } = await setup()
  70. const controller = new AbortController()
  71. const pending = execute(ctx, { script: SCRIPT, meta: META, args: { files: ['a.ts'] } }, { agent: parent, signal: controller.signal })
  72. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  73. expect(engine.requests[0]).toMatchObject({ script: SCRIPT, meta: META, args: { files: ['a.ts'] }, parent })
  74. expect(engine.requests[0]!.signal).toBe(controller.signal)
  75. engine.settle({ value: { findings: [1, 2] }, stopReason: 'completed', agentsStarted: 7 })
  76. const result = await pending
  77. expect(result.isError).toBe(false)
  78. const rendered = (result.content[0] as { text: string }).text
  79. expect(rendered).toContain('workflow "stub-flow" 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?.code).toBe('INVALID_ARGS')
  143. })
  144. it('skips workflow startup when exec.signal is already aborted', 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(result.error).toEqual({ name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH })
  151. expect(engine.requests).toHaveLength(0)
  152. expect(engine.cancels).toHaveLength(0)
  153. expect(engine.disposed).toBe(0)
  154. })
  155. it('truncates an oversized rendered value with a notice (maxResultChars)', async () => {
  156. const { ctx, engine, parent } = await setup({ maxResultChars: 40 })
  157. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  158. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  159. engine.settle({ value: { blob: 'x'.repeat(500) }, stopReason: 'completed', agentsStarted: 1 })
  160. const rendered = ((await pending).content[0] as { text: string }).text
  161. expect(rendered).toContain('[truncated:')
  162. expect(rendered.length).toBeLessThan(400)
  163. })
  164. it('registers under a configured toolName and unregisters on fiber dispose (HMR safety)', async () => {
  165. const ctx = new Context()
  166. await ctx.plugin(SystemPrompt)
  167. await ctx.plugin(ToolRegistry)
  168. await ctx.plugin(StubEngine)
  169. const fiber = await ctx.plugin(toolWorkflow, { toolName: 'orchestrate' })
  170. expect(ctx.tools.get('orchestrate')).toBeDefined()
  171. expect(ctx.tools.get('workflow')).toBeUndefined()
  172. // The usage-policy prompt section rides the same registration: present
  173. // under the CONFIGURED name (its guidance names the tool it describes)…
  174. const sections = (await ctx.systemPrompt.assemble()).sections
  175. const section = sections.find(s => s.name === 'tool:orchestrate')
  176. expect(section?.text).toContain('orchestrate')
  177. expect(sections.some(s => s.name === 'tool:workflow')).toBe(false)
  178. await fiber.dispose()
  179. expect(ctx.tools.get('orchestrate')).toBeUndefined()
  180. // …and gone with the fiber — a reload must not leak a stale section.
  181. expect((await ctx.systemPrompt.assemble()).sections.some(s => s.name === 'tool:orchestrate')).toBe(false)
  182. })
  183. it('presents a generic pending card titled by the meta name, with the script as rawInput', async () => {
  184. const { ctx } = await setup()
  185. const tool = ctx.tools.get('workflow')!
  186. const view = tool.presentCall!({ script: SCRIPT, meta: META })
  187. expect(view).toMatchObject({ card: 'generic', title: 'workflow: audit', rawInput: SCRIPT })
  188. })
  189. it('presentResult keeps the generic card; presentation is pure and replay-safe on malformed args', async () => {
  190. const { ctx } = await setup()
  191. const tool = ctx.tools.get('workflow')!
  192. expect(tool.presentResult!({ script: SCRIPT, meta: META }, { content: [], isError: false })).toEqual({ card: 'generic' })
  193. // defineTool soft-validates presentation args: a malformed logged shape
  194. // (wrong fields entirely, or a call missing its meta) falls back to
  195. // undefined instead of throwing mid-replay.
  196. expect(tool.presentCall!({ not: 'the schema' })).toBeUndefined()
  197. expect(tool.presentCall!({ script: SCRIPT })).toBeUndefined()
  198. })
  199. it('has the namespace-plugin export shape (no stray default)', () => {
  200. expect('default' in toolWorkflow).toBe(false)
  201. expect(toolWorkflow.name).toBe('tool-workflow')
  202. expect(toolWorkflow.inject).toEqual(['tools', 'workflows', 'systemPrompt'])
  203. const loader = Object.create(Loader.prototype) as Loader
  204. const unwrapped = loader.unwrapExports(toolWorkflow) as Record<string, unknown>
  205. expect(unwrapped).toBe(toolWorkflow)
  206. expect(typeof unwrapped.apply).toBe('function')
  207. })
  208. describe('composition with the REAL worker-thread engine (the mock above must stay honest)', () => {
  209. it('an abort releases the tool even when the script parks on a promise no hook owns', async () => {
  210. // The tool and loop await run.result before cleanup, so cancellation must settle a script
  211. // parked on an unowned promise. Exercise that guarantee through the real registry and worker.
  212. const ctx = new Context()
  213. await ctx.plugin(SystemPrompt)
  214. await ctx.plugin(ToolRegistry)
  215. await ctx.plugin(SubagentService)
  216. ctx.subagents.registerProvider({
  217. name: 'spawn',
  218. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  219. inheritsParentContext: false,
  220. start: () => Promise.reject(new Error('the parked-script fixture must not start a child')),
  221. })
  222. await ctx.plugin(WorkerWorkflowEngine, { disposeGraceMs: 30 })
  223. await ctx.plugin(toolWorkflow, {})
  224. const parent = { id: SessionId('caller'), options: {} } as unknown as Agent
  225. const controller = new AbortController()
  226. const pending = execute(ctx, {
  227. script: 'await new Promise(() => {})\nreturn 1',
  228. meta: { name: 'stuck', description: 'parks forever' },
  229. }, { agent: parent, signal: controller.signal })
  230. // Give the run a beat to start (past its synchronous slice), then abort.
  231. await new Promise(resolve => setTimeout(resolve, 20))
  232. controller.abort('user abort')
  233. const result = await pending
  234. expect(result.isError).toBe(true)
  235. expect((result.content[0] as { text: string }).text).toContain('cancelled')
  236. })
  237. })
  238. })