index.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /**
  2. * The model-facing `workflow` tool: run a JavaScript orchestration script that fans out
  3. * subagents, and return the script's final value. Pure schema + lifecycle shaping — script
  4. * parsing, execution, caps, and cancellation live behind `ctx.workflows`
  5. * (`@deepseek-ai/dsh-workflow`), so a hardened engine swaps in without touching what the model
  6. * sees. Execution awaits `run.result` and always disposes the run; non-completed reasons become tool
  7. * errors, and background collection remains deferred. Presentation is an args-only generic card
  8. * titled from `meta.name`. Explicit-ask usage guidance is registered as the tool's own prompt
  9. * section rather than deployment persona prose.
  10. * @module @deepseek-ai/dsh-tool-workflow
  11. */
  12. import type { Context } from 'cordis'
  13. import z from 'schemastery'
  14. import { defineTool } from '@deepseek-ai/dsh-tools'
  15. import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools'
  16. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  17. import type { JsonValue } from '@deepseek-ai/dsh-session'
  18. import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow'
  19. // Declaration merge only: makes ctx.systemPrompt visible for the section registration.
  20. import type {} from '@deepseek-ai/dsh-system-prompt'
  21. export const name = 'tool-workflow'
  22. export const inject = ['tools', 'workflows', 'systemPrompt']
  23. /** Config: the model-facing tool name plus result rendering caps. */
  24. export interface Config {
  25. /** The model-facing tool name to register (default `workflow`). */
  26. toolName?: string
  27. /** Rendered-result ceiling, in characters: a longer JSON value is truncated with a notice (default 50000). */
  28. maxResultChars?: number
  29. }
  30. export const Config: z<Config> = z.object({
  31. toolName: z.string().default('workflow'),
  32. maxResultChars: z.natural().min(1).default(50_000),
  33. })
  34. type ResolvedConfig = Required<Config>
  35. /**
  36. * The script-authoring contract, embedded in the tool description. This IS the
  37. * model-facing spec: the meta block, the hooks and their exact semantics, and
  38. * the supported schema subset.
  39. */
  40. 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.
  41. 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?, provider?, 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.
  42. Script-body hooks:
  43. - \`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/oneOf — no 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), and independent \`provider\`/\`model\` LLM target overrides (either may be provided alone). Anything else (\`effort\`/\`isolation\`/\`agentType\`) is rejected loudly.
  44. - \`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.
  45. - \`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\`.
  46. - \`phase(title)\` — start a progress phase; \`log(message)\` — narrate progress; \`args\` — the tool call's \`args\` input, verbatim.
  47. 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\`.
  48. 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.`
  49. type WorkflowCallArgs = {
  50. script: string
  51. meta: {
  52. name: string
  53. description: string
  54. whenToUse?: string
  55. phases?: { title: string; detail?: string; provider?: string; model?: string }[]
  56. }
  57. args?: Record<string, unknown>
  58. }
  59. /** The pending-state card: a generic card titled by the workflow's meta name. */
  60. function presentWorkflowCall(args: WorkflowCallArgs): ToolCallView {
  61. return {
  62. card: 'generic',
  63. title: `workflow: ${args.meta.name}`,
  64. rawInput: args.script,
  65. }
  66. }
  67. /** The completed-state card: keep the pending title; render the result content as-is. */
  68. function presentWorkflowResult(args: WorkflowCallArgs, result: { content: ContentBlock[]; isError: boolean }): ToolResultView {
  69. void args
  70. void result
  71. return { card: 'generic' }
  72. }
  73. /** A non-`completed` stop reason means the script did not finish cleanly. */
  74. function stopReasonError(result: WorkflowResult): string | undefined {
  75. switch (result.stopReason) {
  76. case 'completed':
  77. return undefined
  78. case 'cancelled':
  79. return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`
  80. case 'error':
  81. return `workflow run failed: ${result.error ?? 'unknown error'}`
  82. /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
  83. default:
  84. return `workflow run ended abnormally (${String(result.stopReason satisfies never)})`
  85. /* v8 ignore stop */
  86. }
  87. }
  88. /** Render the run's outcome text: the meta name, agent count, and the JSON value (capped). */
  89. function renderResult(name: string, agentsStarted: number, value: JsonValue, maxChars: number): string {
  90. // The engine returns JSON data (null for a valueless script), so stringify never yields undefined.
  91. const rendered = JSON.stringify(value, null, 2)
  92. const clipped = rendered.length > maxChars
  93. ? `${rendered.slice(0, maxChars)}\n… [truncated: ${rendered.length - maxChars} more characters]`
  94. : rendered
  95. return `workflow "${name}" completed (${agentsStarted} agent${agentsStarted === 1 ? '' : 's'}).\nReturn value:\n${clipped}`
  96. }
  97. export function apply(ctx: Context, config: Config): void {
  98. // schemastery (the exported Config schema) has already filled the defaulted
  99. // fields; the assertion records that resolution, not a hidden fallback.
  100. const { toolName, maxResultChars } = config as ResolvedConfig
  101. // Usage policy ships with the tool (the master convention: tool guidance
  102. // lives in tool plugins as prompt sections, not in the deployment persona).
  103. ctx.systemPrompt.section({
  104. name: `tool:${toolName}`,
  105. order: 115,
  106. 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.`,
  107. })
  108. ctx.tools.register(defineTool({
  109. name: toolName,
  110. description: DESCRIPTION,
  111. parameters: {
  112. script: {
  113. type: 'string',
  114. required: true,
  115. description: 'The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`).',
  116. },
  117. meta: {
  118. type: 'object',
  119. additionalProperties: true,
  120. required: true,
  121. description: 'The workflow identity block (plain JSON — never code).',
  122. properties: {
  123. name: { type: 'string', required: true, description: 'Short kebab-case workflow name.' },
  124. description: { type: 'string', required: true, description: 'One-line description of what the workflow does.' },
  125. whenToUse: { type: 'string', description: 'Optional guidance on when this workflow applies.' },
  126. phases: {
  127. type: 'array',
  128. description: 'Optional phase declarations matched by phase() calls.',
  129. items: {
  130. type: 'object',
  131. additionalProperties: true,
  132. properties: {
  133. title: { type: 'string', required: true, description: 'The phase title phase() calls match by exact string.' },
  134. detail: { type: 'string', description: 'Optional one-line description of the phase.' },
  135. provider: { type: 'string', description: 'Optional provider override this phase is expected to use.' },
  136. model: { type: 'string', description: 'Optional model override this phase is expected to use.' },
  137. },
  138. },
  139. },
  140. },
  141. },
  142. args: {
  143. type: 'object',
  144. additionalProperties: true,
  145. description: 'Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {"files": [...]}).',
  146. },
  147. },
  148. output: {
  149. schema: {
  150. type: 'object',
  151. additionalProperties: false,
  152. properties: {
  153. runId: { type: 'string', required: true },
  154. agentsStarted: { type: 'integer', required: true },
  155. result: { type: 'json', required: true },
  156. },
  157. },
  158. render: (args, value) => [{
  159. type: 'text',
  160. text: renderResult(args.meta.name, value.agentsStarted, value.result, maxResultChars),
  161. }],
  162. },
  163. async execute(args, exec) {
  164. const parent = exec.agent
  165. if (!parent) {
  166. // The loop sets `exec.agent` for every model-driven call; its absence
  167. // means a non-agent caller invoked the tool directly, which has no
  168. // parent to attribute the children to. Fail loud rather than guess.
  169. throw new Error('workflow tool requires a calling agent (exec.agent was undefined)')
  170. }
  171. // Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
  172. // synchronously here and become isError results via the registry — the
  173. // model sees the violation list and can correct the call.
  174. const run: WorkflowRun = ctx.workflows.start({
  175. script: args.script,
  176. meta: args.meta,
  177. ...args.args !== undefined ? { args: args.args } : {},
  178. parent,
  179. signal: exec.signal,
  180. })
  181. // Bridge the tool's abort signal to the run: if the parent step is aborted while the
  182. // script is in flight, cancel the whole run. The signal also enters the engine directly, but
  183. // this local bridge preserves the tool contract even if an implementation ignores it.
  184. const onAbort = (): void => { run.cancel('parent step aborted') }
  185. exec.signal.addEventListener('abort', onAbort, { once: true })
  186. try {
  187. const result = await run.result
  188. const error = stopReasonError(result)
  189. if (error !== undefined) {
  190. // Map a non-clean finish to an isError result (the registry turns a
  191. // throw into an isError). Report the reason, not partial output.
  192. throw new Error(error)
  193. }
  194. return {
  195. runId: run.id,
  196. agentsStarted: result.agentsStarted,
  197. result: result.value as JsonValue,
  198. }
  199. } finally {
  200. exec.signal.removeEventListener('abort', onAbort)
  201. // Always reach run quiescence — never leak a live script or children.
  202. await run.dispose()
  203. }
  204. },
  205. presentCall: args => presentWorkflowCall(args),
  206. presentResult: (args, result) => presentWorkflowResult(args, result),
  207. }))
  208. }