index.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /**
  2. * The model-facing `workflow` tool: run a JavaScript orchestration script that
  3. * fans out subagents, and return the script's final value. Pure schema +
  4. * lifecycle shaping — script parsing, execution, caps, and cancellation live
  5. * behind `ctx.workflows` (`@deepseek-ai/dsh-workflow`), so a hardened engine
  6. * swaps in without touching what the model sees.
  7. *
  8. * Collection is SYNCHRONOUS this cut (like `dsh-tool-subagent`): `execute`
  9. * starts a run and awaits `run.result` inside a `try/finally` that always
  10. * disposes the run, so the script and its children are torn down on every
  11. * path. A non-`completed` stop reason maps to an `isError` tool result (by
  12. * throwing) rather than returning partial output as success. Background
  13. * collection is deferred to the cross-tool background redesign.
  14. *
  15. * Render intent (decided up front, per the render-intent RFC): a `generic`
  16. * card whose title carries the workflow's `meta.name`, read directly from the
  17. * call's `meta` parameter — presentation is a pure function of `args`.
  18. *
  19. * Usage policy ships with the tool as a `tool:<toolName>` system-prompt
  20. * section (explicit-ask-only guidance) — tool guidance lives in tool plugins,
  21. * never in the deployment persona.
  22. *
  23. * @module @deepseek-ai/dsh-tool-workflow
  24. */
  25. import type { Context } from 'cordis'
  26. import z from 'schemastery'
  27. import { defineTool } from '@deepseek-ai/dsh-tools'
  28. import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools'
  29. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  30. import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow'
  31. // Declaration merge only: makes ctx.systemPrompt visible for the section registration.
  32. import type {} from '@deepseek-ai/dsh-system-prompt'
  33. export const name = 'tool-workflow'
  34. export const inject = ['tools', 'workflows', 'systemPrompt']
  35. /** Config: the model-facing tool name plus result rendering caps. */
  36. export interface Config {
  37. /** The model-facing tool name to register (default `workflow`). */
  38. toolName?: string
  39. /** Rendered-result ceiling, in characters: a longer JSON value is truncated with a notice (default 50000). */
  40. maxResultChars?: number
  41. }
  42. export const Config: z<Config> = z.object({
  43. toolName: z.string().default('workflow'),
  44. maxResultChars: z.natural().min(1).default(50_000),
  45. })
  46. type ResolvedConfig = Required<Config>
  47. /**
  48. * The script-authoring contract, embedded in the tool description. This IS the
  49. * model-facing spec: the meta block, the hooks and their exact semantics, and
  50. * the supported schema subset.
  51. */
  52. const DESCRIPTION = `Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.
  53. The workflow's identity rides the \`meta\` parameter as JSON: required \`name\` (short kebab-case) and \`description\` strings, optional \`whenToUse\` string and \`phases\` array (\`{title, detail?, model?}\`). The \`script\` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO \`export const meta\` statement — meta is a parameter, not code), running with top-level await; end with \`return <value>\` — the value must be JSON-serializable and is this tool's result.
  54. Script-body hooks:
  55. - \`agent(prompt, opts?): Promise<any>\` — run one subagent to completion. Without \`opts.schema\` it resolves to the child's final text; with \`opts.schema\` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const — no oneOf/pattern/format/numeric bounds) it resolves to the validated object. Resolves \`null\` when the child fails (filter with \`.filter(Boolean)\`). Other opts: \`label\` (display), \`phase\` (progress group), \`model\` (override). Anything else (\`effort\`/\`isolation\`/\`agentType\`) is rejected loudly.
  56. - \`pipeline(items, ...stages): Promise<any[]>\` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives \`(prev, item, index)\`. An ordinary stage throw drops that ITEM to \`null\` and skips its remaining stages.
  57. - \`parallel(thunks): Promise<any[]>\` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to \`null\`.
  58. - \`phase(title)\` — start a progress phase; \`log(message)\` — narrate progress; \`args\` — the tool call's \`args\` input, verbatim.
  59. Misused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item \`null\`.
  60. Constraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.`
  61. type WorkflowCallArgs = {
  62. script: string
  63. meta: { name: string; description: string; whenToUse?: string; phases?: { title: string; detail?: string; model?: string }[] }
  64. args?: Record<string, unknown>
  65. }
  66. /** The pending-state card: a generic card titled by the workflow's meta name. */
  67. function presentWorkflowCall(args: WorkflowCallArgs): ToolCallView {
  68. return {
  69. card: 'generic',
  70. title: `workflow: ${args.meta.name}`,
  71. rawInput: args.script,
  72. }
  73. }
  74. /** The completed-state card: keep the pending title; render the result content as-is. */
  75. function presentWorkflowResult(args: WorkflowCallArgs, result: { content: ContentBlock[]; isError: boolean }): ToolResultView {
  76. void args
  77. void result
  78. return { card: 'generic' }
  79. }
  80. /** A non-`completed` stop reason means the script did not finish cleanly. */
  81. function stopReasonError(result: WorkflowResult): string | undefined {
  82. switch (result.stopReason) {
  83. case 'completed':
  84. return undefined
  85. case 'cancelled':
  86. return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`
  87. case 'error':
  88. return `workflow run failed: ${result.error ?? 'unknown error'}`
  89. /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
  90. default:
  91. return `workflow run ended abnormally (${String(result.stopReason satisfies never)})`
  92. /* v8 ignore stop */
  93. }
  94. }
  95. /** Render the run's outcome text: the meta name, agent count, and the JSON value (capped). */
  96. function renderResult(run: WorkflowRun, result: WorkflowResult, maxChars: number): string {
  97. // The engine returns JSON data (null for a valueless script), so stringify never yields undefined.
  98. const rendered = JSON.stringify(result.value, null, 2)
  99. const clipped = rendered.length > maxChars
  100. ? `${rendered.slice(0, maxChars)}\n… [truncated: ${rendered.length - maxChars} more characters]`
  101. : rendered
  102. return `workflow "${run.meta.name}" completed (${result.agentsStarted} agent${result.agentsStarted === 1 ? '' : 's'}).\nReturn value:\n${clipped}`
  103. }
  104. export function apply(ctx: Context, config: Config): void {
  105. // schemastery (the exported Config schema) has already filled the defaulted
  106. // fields; the assertion records that resolution, not a hidden fallback.
  107. const { toolName, maxResultChars } = config as ResolvedConfig
  108. // Usage policy ships with the tool (the master convention: tool guidance
  109. // lives in tool plugins as prompt sections, not in the deployment persona).
  110. ctx.systemPrompt.section({
  111. name: `tool:${toolName}`,
  112. order: 115,
  113. text: `Use the ${toolName} tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.`,
  114. })
  115. ctx.tools.register(defineTool({
  116. name: toolName,
  117. description: DESCRIPTION,
  118. parameters: {
  119. script: {
  120. type: 'string',
  121. required: true,
  122. description: 'The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`).',
  123. },
  124. meta: {
  125. type: 'object',
  126. required: true,
  127. description: 'The workflow identity block (plain JSON — never code).',
  128. properties: {
  129. name: { type: 'string', required: true, description: 'Short kebab-case workflow name.' },
  130. description: { type: 'string', required: true, description: 'One-line description of what the workflow does.' },
  131. whenToUse: { type: 'string', description: 'Optional guidance on when this workflow applies.' },
  132. phases: {
  133. type: 'array',
  134. description: 'Optional phase declarations matched by phase() calls.',
  135. items: {
  136. type: 'object',
  137. properties: {
  138. title: { type: 'string', required: true, description: 'The phase title phase() calls match by exact string.' },
  139. detail: { type: 'string', description: 'Optional one-line description of the phase.' },
  140. model: { type: 'string', description: 'Optional model override this phase is expected to use.' },
  141. },
  142. },
  143. },
  144. },
  145. },
  146. args: {
  147. type: 'object',
  148. description: 'Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {"files": [...]}).',
  149. },
  150. },
  151. async execute(args, exec): Promise<ContentBlock[]> {
  152. const parent = exec.agent
  153. if (!parent) {
  154. // The loop sets `exec.agent` for every model-driven call; its absence
  155. // means a non-agent caller invoked the tool directly, which has no
  156. // parent to attribute the children to. Fail loud rather than guess.
  157. throw new Error('workflow tool requires a calling agent (exec.agent was undefined)')
  158. }
  159. // Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
  160. // synchronously here and become isError results via the registry — the
  161. // model sees the violation list and can correct the call.
  162. const run: WorkflowRun = ctx.workflows.start({
  163. script: args.script,
  164. meta: args.meta,
  165. ...args.args !== undefined ? { args: args.args } : {},
  166. parent,
  167. ...exec.signal ? { signal: exec.signal } : {},
  168. })
  169. // Bridge the tool's abort signal to the run: if the parent step is
  170. // aborted while the script is in flight, cancel the whole run. The
  171. // engine also receives `signal` directly, but an explicit bridge keeps
  172. // the tool's contract local (and covers an engine that ignores it).
  173. const onAbort = (): void => { run.cancel('parent step aborted') }
  174. exec.signal?.addEventListener('abort', onAbort, { once: true })
  175. // `addEventListener` does NOT fire for a signal already aborted before
  176. // this line — cancel explicitly in that case.
  177. if (exec.signal?.aborted) run.cancel('parent step aborted')
  178. try {
  179. const result = await run.result
  180. const error = stopReasonError(result)
  181. if (error !== undefined) {
  182. // Map a non-clean finish to an isError result (the registry turns a
  183. // throw into an isError). Report the reason, not partial output.
  184. throw new Error(error)
  185. }
  186. return [{ type: 'text', text: renderResult(run, result, maxResultChars) }]
  187. } finally {
  188. exec.signal?.removeEventListener('abort', onAbort)
  189. // Always reach run quiescence — never leak a live script or children.
  190. await run.dispose()
  191. }
  192. },
  193. presentCall: args => presentWorkflowCall(args),
  194. presentResult: (args, result) => presentWorkflowResult(args, result),
  195. }))
  196. }