index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /**
  2. * The model-facing `workflow` tool: run a JavaScript orchestration script that fans out
  3. * subagents, and return the script's final value. It owns the model-facing schema and run lifecycle; script
  4. * parsing, execution, caps, and cancellation live behind `ctx.workflowEngine`
  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 '@deepseek-ai/cordis'
  13. import z from '@deepseek-ai/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 { Session, SessionEventMap } from '@deepseek-ai/dsh-session'
  18. import type { JsonValue } from '@deepseek-ai/dsh-util-values'
  19. import type {
  20. WorkflowResult, WorkflowRun, WorkflowRunId, WorkflowStopReason,
  21. } from '@deepseek-ai/dsh-workflow'
  22. import type {
  23. ToolWorkflowAgentEndData, ToolWorkflowAgentStartData,
  24. ToolWorkflowRunEndData, ToolWorkflowRunStartData,
  25. } from './types.ts'
  26. export const name = 'tool-workflow'
  27. export const inject = ['tools', 'workflowEngine', 'systemPrompt']
  28. /** Config: the model-facing tool name plus result rendering caps. */
  29. export interface Config {
  30. /** The model-facing tool name to register (default `workflow`). */
  31. toolName?: string
  32. /** Rendered-result ceiling, in characters: a longer JSON value is truncated with a notice (default 50000). */
  33. maxResultChars?: number
  34. }
  35. export const Config: z<Config> = z.object({
  36. toolName: z.string().default('workflow'),
  37. maxResultChars: z.natural().min(1).default(50_000),
  38. })
  39. type ResolvedConfig = Required<Config>
  40. interface WorkflowRecorder {
  41. start(session: Session, run: WorkflowRun): void
  42. finish(runId: WorkflowRunId, stopReason: WorkflowStopReason): void
  43. abandon(runId: WorkflowRunId): void
  44. }
  45. interface ToolWorkflowRecordEventMap {
  46. 'tool-workflow/run-start': ToolWorkflowRunStartData
  47. 'tool-workflow/agent-start': ToolWorkflowAgentStartData
  48. 'tool-workflow/agent-end': ToolWorkflowAgentEndData
  49. 'tool-workflow/run-end': ToolWorkflowRunEndData
  50. }
  51. /** Render a contained recording failure without trusting the thrown value. */
  52. function renderRecordingError(error: unknown): string {
  53. try {
  54. return String(error)
  55. } catch {
  56. return '[unrenderable thrown value]'
  57. }
  58. }
  59. /**
  60. * Project active top-level workflow runs into their parent Sessions without
  61. * letting recording failure affect tool execution.
  62. */
  63. function createWorkflowRecorder(ctx: Context): WorkflowRecorder {
  64. const active = new Map<WorkflowRunId, Session>()
  65. const append = <Type extends keyof ToolWorkflowRecordEventMap>(
  66. session: Session,
  67. type: Type,
  68. data: SessionEventMap[Type],
  69. ): boolean => {
  70. // These four package-owned events are all log-only. Narrowing the generic
  71. // append face here discharges Session.append's conditional options tuple.
  72. const appendRecord = session.append.bind(session) as <Event extends keyof ToolWorkflowRecordEventMap>(
  73. event: Event,
  74. value: SessionEventMap[Event],
  75. ) => void
  76. try {
  77. appendRecord(type, data)
  78. return true
  79. } catch (error: unknown) {
  80. ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`)
  81. return false
  82. }
  83. }
  84. ctx.on('workflow/agent-start', (info, agent) => {
  85. const session = active.get(info.id)
  86. if (session === undefined) return
  87. const data: ToolWorkflowAgentStartData = {
  88. runId: info.id,
  89. seq: agent.seq,
  90. label: agent.label,
  91. ...agent.phase === undefined ? {} : { phase: agent.phase },
  92. childId: agent.childId,
  93. }
  94. if (!append(session, 'tool-workflow/agent-start', data)) active.delete(info.id)
  95. })
  96. ctx.on('workflow/agent-end', (info, agent) => {
  97. const session = active.get(info.id)
  98. if (session === undefined) return
  99. const data: ToolWorkflowAgentEndData = {
  100. runId: info.id,
  101. seq: agent.seq,
  102. outcome: agent.outcome,
  103. }
  104. if (!append(session, 'tool-workflow/agent-end', data)) active.delete(info.id)
  105. })
  106. return {
  107. start(session, run) {
  108. if (append(session, 'tool-workflow/run-start', { runId: run.id, name: run.meta.name })) {
  109. active.set(run.id, session)
  110. }
  111. },
  112. finish(runId, stopReason) {
  113. const session = active.get(runId)
  114. if (session !== undefined) append(session, 'tool-workflow/run-end', { runId, stopReason })
  115. active.delete(runId)
  116. },
  117. abandon: (runId) => { active.delete(runId) },
  118. }
  119. }
  120. /**
  121. * The script-authoring contract, embedded in the tool description. This IS the
  122. * model-facing spec: the meta block, the hooks and their exact semantics, and
  123. * the supported schema subset.
  124. */
  125. 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.
  126. 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.
  127. Script-body hooks:
  128. - \`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.
  129. - \`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.
  130. - \`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\`.
  131. - \`phase(title)\` — start a progress phase; \`log(message)\` — narrate progress; \`args\` — the tool call's \`args\` input, verbatim.
  132. 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\`.
  133. 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.`
  134. type WorkflowCallArgs = {
  135. script: string
  136. meta: {
  137. name: string
  138. description: string
  139. whenToUse?: string
  140. phases?: { title: string; detail?: string; provider?: string; model?: string }[]
  141. }
  142. args?: Record<string, unknown>
  143. }
  144. /** The pending-state card: a generic card titled by the workflow's meta name. */
  145. function presentWorkflowCall(args: WorkflowCallArgs): ToolCallView {
  146. return {
  147. card: 'generic',
  148. title: `workflow: ${args.meta.name}`,
  149. rawInput: args.script,
  150. }
  151. }
  152. /** The completed-state card: keep the pending title; render the result content as-is. */
  153. function presentWorkflowResult(args: WorkflowCallArgs, result: { content: ContentBlock[]; isError: boolean }): ToolResultView {
  154. void args
  155. void result
  156. return { card: 'generic' }
  157. }
  158. /** A non-`completed` stop reason means the script did not finish cleanly. */
  159. function stopReasonError(result: WorkflowResult): string | undefined {
  160. switch (result.stopReason) {
  161. case 'completed':
  162. return undefined
  163. case 'cancelled':
  164. return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`
  165. case 'error':
  166. return `workflow run failed: ${result.error ?? 'unknown error'}`
  167. /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
  168. default:
  169. return `workflow run ended abnormally (${String(result.stopReason satisfies never)})`
  170. /* v8 ignore stop */
  171. }
  172. }
  173. /** Render the run's outcome text: the meta name, agent count, and the JSON value (capped). */
  174. function renderResult(name: string, agentsStarted: number, value: JsonValue, maxChars: number): string {
  175. // The engine returns JSON data (null for a valueless script), so stringify never yields undefined.
  176. const rendered = JSON.stringify(value, null, 2)
  177. const clipped = rendered.length > maxChars
  178. ? `${rendered.slice(0, maxChars)}\n… [truncated: ${rendered.length - maxChars} more characters]`
  179. : rendered
  180. return `workflow "${name}" completed (${agentsStarted} agent${agentsStarted === 1 ? '' : 's'}).\nReturn value:\n${clipped}`
  181. }
  182. export function apply(ctx: Context, config: Config): void {
  183. // schemastery (the exported Config schema) has already filled the defaulted
  184. // fields; the assertion records that resolution, not a hidden fallback.
  185. const { toolName, maxResultChars } = config as ResolvedConfig
  186. const recorder = createWorkflowRecorder(ctx)
  187. // Usage policy ships with the tool (the master convention: tool guidance
  188. // lives in tool plugins as prompt sections, not in the deployment persona).
  189. ctx.systemPrompt.section({
  190. name: `tool:${toolName}`,
  191. order: ctx.systemPrompt.getSectionOrder('TOOL_WORKFLOW'),
  192. 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.`,
  193. })
  194. ctx.tools.register(defineTool({
  195. name: toolName,
  196. description: DESCRIPTION,
  197. parameters: {
  198. script: {
  199. type: 'string',
  200. required: true,
  201. description: 'The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`).',
  202. },
  203. meta: {
  204. type: 'object',
  205. additionalProperties: true,
  206. required: true,
  207. description: 'The workflow identity block (plain JSON — never code).',
  208. properties: {
  209. name: { type: 'string', required: true, description: 'Short kebab-case workflow name.' },
  210. description: { type: 'string', required: true, description: 'One-line description of what the workflow does.' },
  211. whenToUse: { type: 'string', description: 'Optional guidance on when this workflow applies.' },
  212. phases: {
  213. type: 'array',
  214. description: 'Optional phase declarations matched by phase() calls.',
  215. items: {
  216. type: 'object',
  217. additionalProperties: true,
  218. properties: {
  219. title: { type: 'string', required: true, description: 'The phase title phase() calls match by exact string.' },
  220. detail: { type: 'string', description: 'Optional one-line description of the phase.' },
  221. provider: { type: 'string', description: 'Optional provider override this phase is expected to use.' },
  222. model: { type: 'string', description: 'Optional model override this phase is expected to use.' },
  223. },
  224. },
  225. },
  226. },
  227. },
  228. args: {
  229. type: 'object',
  230. additionalProperties: true,
  231. description: 'Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {"files": [...]}).',
  232. },
  233. },
  234. output: {
  235. schema: {
  236. type: 'object',
  237. additionalProperties: false,
  238. properties: {
  239. runId: { type: 'string', required: true },
  240. agentsStarted: { type: 'integer', required: true },
  241. result: { type: 'json', required: true },
  242. },
  243. },
  244. render: (args, value) => [{
  245. type: 'text',
  246. text: renderResult(args.meta.name, value.agentsStarted, value.result, maxResultChars),
  247. }],
  248. },
  249. async execute(args, exec) {
  250. const parent = exec.agent
  251. if (!parent) {
  252. // The loop sets `exec.agent` for every model-driven call; its absence
  253. // means a non-agent caller invoked the tool directly, which has no
  254. // parent to attribute the children to. Fail loud rather than guess.
  255. throw new Error('workflow tool requires a calling agent (exec.agent was undefined)')
  256. }
  257. // Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
  258. // synchronously here and become isError results via the registry — the
  259. // model sees the violation list and can correct the call.
  260. const run = ctx.workflowEngine.start({
  261. script: args.script,
  262. meta: args.meta,
  263. ...args.args !== undefined ? { args: args.args } : {},
  264. parent,
  265. signal: exec.signal,
  266. })
  267. const recordsRun = exec.parent === undefined
  268. // The shipped worker-thread engine publishes member events from later
  269. // worker messages, after start() returns and this run record is active.
  270. if (recordsRun) recorder.start(parent.session, run)
  271. // Bridge the tool's abort signal to the run: if the parent step is aborted while the
  272. // script is in flight, cancel the whole run. The signal also enters the engine directly, but
  273. // this local bridge preserves the tool contract even if an implementation ignores it.
  274. const onAbort = (): void => { run.cancel('parent step aborted') }
  275. exec.signal.addEventListener('abort', onAbort, { once: true })
  276. let result: WorkflowResult | undefined
  277. try {
  278. result = await run.result
  279. const error = stopReasonError(result)
  280. if (error !== undefined) {
  281. // Map a non-clean finish to an isError result (the registry turns a
  282. // throw into an isError). Report the reason, not partial output.
  283. throw new Error(error)
  284. }
  285. return {
  286. runId: run.id,
  287. agentsStarted: result.agentsStarted,
  288. result: result.value as JsonValue,
  289. }
  290. } finally {
  291. exec.signal.removeEventListener('abort', onAbort)
  292. try {
  293. // Keep member listeners alive through disposal: an engine may
  294. // synthesize cancelled member endings while reaching quiescence.
  295. await run.dispose()
  296. if (recordsRun) {
  297. /* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
  298. if (result === undefined) throw new Error('workflow run settled without a result')
  299. recorder.finish(run.id, result.stopReason)
  300. }
  301. } finally {
  302. if (recordsRun) recorder.abandon(run.id)
  303. }
  304. }
  305. },
  306. presentCall: args => presentWorkflowCall(args),
  307. presentResult: (args, result) => presentWorkflowResult(args, result),
  308. }))
  309. }