index.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /**
  2. * Worker-thread workflow engine. Each run executes its model-written script in
  3. * an escapable vm context on a fresh worker and bridges `agent()` calls to host
  4. * subagents. The thread prevents synchronous script work from blocking the host
  5. * and permits forced termination, but it is containment rather than a security boundary.
  6. * @module @deepseek-ai/dsh-workflow-worker-thread
  7. */
  8. import { randomUUID } from 'node:crypto'
  9. import { availableParallelism } from 'node:os'
  10. import * as vm from 'node:vm'
  11. import type { Context } from '@deepseek-ai/cordis'
  12. import z from '@deepseek-ai/schemastery'
  13. import WorkflowEngine, { WorkflowError, WorkflowRunId } from '@deepseek-ai/dsh-workflow'
  14. import type { WorkflowRun, WorkflowRunInfo, WorkflowStartRequest } from '@deepseek-ai/dsh-workflow'
  15. import { WorkerRun } from './host.ts'
  16. import { validateMeta } from './meta.ts'
  17. import type { WorkerInit, WorkerLimits } from './types.ts'
  18. export { validateMeta } from './meta.ts'
  19. export { materializeFromRealm, MaterializeError } from './realm.ts'
  20. export type {
  21. ChildHandle,
  22. ChildPort,
  23. ChildResult,
  24. ChildStartRequest,
  25. WorkerInit,
  26. WorkerLimits,
  27. } from './types.ts'
  28. /** Plugin config (all optional — `static Config` supplies the defaults). */
  29. export interface Config {
  30. /** The `ctx.subagents` provider children run on (default `spawn`). */
  31. provider?: string
  32. /** Concurrent `agent()` ceiling; `0` (the default) auto-resolves to `min(16, max(1, cores - 2))`. */
  33. maxConcurrentAgents?: number
  34. /** Total `agent()` calls one run may start — the runaway-loop backstop (default 1000). */
  35. maxTotalAgents?: number
  36. /** Items accepted by a single `parallel()`/`pipeline()` call (default 4096). */
  37. maxItemsPerCall?: number
  38. /** vm timeout for the script's initial synchronous slice, inside the worker (default 5000 ms). */
  39. syncTimeoutMs?: number
  40. /**
  41. * How long after a cancellation an unsettled script may keep running before
  42. * the run force-settles `cancelled` and its worker is TERMINATED (default
  43. * 5000 ms); also bounds `dispose()`.
  44. */
  45. disposeGraceMs?: number
  46. }
  47. type ResolvedConfig = Required<Config>
  48. /** A body that still carries the Claude Code-style meta header (meta rides the seam as data here). */
  49. const META_STATEMENT = /^\s*export\s+const\s+meta\b/
  50. /**
  51. * Parse-check the body with the SAME wrapper the worker-side runtime
  52. * compiles, so `start()` keeps the seam's synchronous `SCRIPT_PARSE` throw
  53. * (the worker's own compile happens a thread away, after `start()` returned).
  54. * One redundant parse per run, bought deliberately for the contract. A body
  55. * opening with `export const meta` gets a pointed message instead of the
  56. * wrapper's bare SyntaxError — the model's likeliest authoring slip.
  57. */
  58. function assertBodyParses(body: string, name: string): void {
  59. if (META_STATEMENT.test(body)) {
  60. throw new WorkflowError('workflow meta rides the `meta` request field, not the script: remove the `export const meta = {...}` statement from the body', 'SCRIPT_PARSE')
  61. }
  62. try {
  63. // Parse only — the script object is discarded, nothing executes.
  64. void new vm.Script(`(async () => {\n${body}\n})()`, { filename: `workflow:${name}`, lineOffset: -1 })
  65. } catch (error: unknown) {
  66. throw new WorkflowError(`workflow script does not parse: ${String(error)}`, 'SCRIPT_PARSE', { cause: error })
  67. }
  68. }
  69. /** Resolve one run's provider route before publishing work. */
  70. function resolveSubagentProvider(ctx: Context, configured: string, override: string | undefined): string {
  71. const provider = override ?? configured
  72. if (provider.length === 0 || provider !== provider.trim()) {
  73. throw new WorkflowError(
  74. 'workflow subagentProvider must be a non-empty normalized string',
  75. 'INVALID_ARGUMENT',
  76. )
  77. }
  78. if (ctx.subagents.getProvider(provider) === undefined) {
  79. throw new WorkflowError(`no subagent provider registered for "${provider}"`, 'AGENT_START')
  80. }
  81. return provider
  82. }
  83. /** Resolve one run's total-child cap against the engine deployment ceiling. */
  84. function resolveMaxTotalAgents(requested: number | undefined, ceiling: number): number {
  85. if (requested === undefined) return ceiling
  86. if (!Number.isSafeInteger(requested) || requested < 1) {
  87. throw new WorkflowError('workflow maxTotalAgents must be a positive safe integer', 'INVALID_ARGUMENT')
  88. }
  89. if (requested > ceiling) {
  90. throw new WorkflowError(
  91. `workflow maxTotalAgents ${requested} exceeds the engine ceiling ${ceiling}`,
  92. 'INVALID_ARGUMENT',
  93. )
  94. }
  95. return requested
  96. }
  97. /**
  98. * The worker-thread engine service. `start()` validates the script up front
  99. * (meta + a host-side body parse) and returns a {@link WorkflowRun} whose
  100. * `result` never rejects; the `workflow/*` events fire around the run per
  101. * the seam contract.
  102. */
  103. class WorkerThreadWorkflowEngine extends WorkflowEngine {
  104. static inject = ['subagents']
  105. static Config: z<Config> = z.object({
  106. provider: z.string().default('spawn'),
  107. maxConcurrentAgents: z.natural().default(0),
  108. maxTotalAgents: z.natural().min(1).default(1000),
  109. maxItemsPerCall: z.natural().min(1).default(4096),
  110. syncTimeoutMs: z.natural().min(1).default(5000),
  111. disposeGraceMs: z.natural().default(5000),
  112. })
  113. private readonly config: ResolvedConfig
  114. constructor(ctx: Context, config: Config) {
  115. super(ctx)
  116. // schemastery (static Config) has already filled the defaulted fields;
  117. // the assertion records that resolution, not a hidden fallback.
  118. this.config = config as ResolvedConfig
  119. }
  120. /**
  121. * Validate and execute a workflow script in a fresh worker thread. Throws
  122. * {@link WorkflowError} synchronously (`META_INVALID` for a malformed meta
  123. * block, `SCRIPT_PARSE` for a body that does not compile) for a request
  124. * that cannot begin; once a run is returned, every failure resolves through
  125. * `result.stopReason` instead.
  126. * @param request - the script body, its meta data and `args`, the parent
  127. * agent, and an optional cancel signal.
  128. * @returns the live run (its `result` resolves when the script settles).
  129. */
  130. start(request: WorkflowStartRequest): WorkflowRun {
  131. const meta = validateMeta(request.meta)
  132. assertBodyParses(request.script, meta.name)
  133. const subagentProvider = resolveSubagentProvider(this.ctx, this.config.provider, request.subagentProvider)
  134. const maxTotalAgents = resolveMaxTotalAgents(request.maxTotalAgents, this.config.maxTotalAgents)
  135. const id = WorkflowRunId(randomUUID())
  136. const info: WorkflowRunInfo = { id, meta }
  137. const limits: WorkerLimits = {
  138. maxConcurrentAgents: this.config.maxConcurrentAgents === 0
  139. ? Math.min(16, Math.max(1, availableParallelism() - 2))
  140. : this.config.maxConcurrentAgents,
  141. maxTotalAgents,
  142. maxItemsPerCall: this.config.maxItemsPerCall,
  143. syncTimeoutMs: this.config.syncTimeoutMs,
  144. }
  145. const init: WorkerInit = {
  146. meta,
  147. body: request.script,
  148. ...request.args !== undefined ? { args: request.args } : {},
  149. limits,
  150. }
  151. // Capture the dependency while this service call is still traced through
  152. // the start() holder. Cordis strips the engine-provider shadow when it
  153. // returns the SubagentRuntime handle, so an already-returned run can keep
  154. // starting children after an engine HMR unload removes ctx.workflowEngine.
  155. // Re-resolving `this.ctx.subagents` later from WorkerRun would instead walk
  156. // the now-inactive engine fiber and break the seam's holder-owned lifetime.
  157. const runCtx = this.ctx
  158. const subagents = runCtx.subagents
  159. const workerRun = new WorkerRun(
  160. runCtx,
  161. subagents,
  162. id,
  163. meta,
  164. request.parent,
  165. init,
  166. subagentProvider,
  167. this.config.disposeGraceMs,
  168. {
  169. phase: (title) => { this.emitWorkflowEvent('workflow/phase', info, title) },
  170. log: (message) => { this.emitWorkflowEvent('workflow/log', info, message) },
  171. agentStart: (agent) => { this.emitWorkflowEvent('workflow/agent-start', info, agent) },
  172. agentEnd: (agent) => { this.emitWorkflowEvent('workflow/agent-end', info, agent) },
  173. },
  174. request.signal,
  175. )
  176. this.emitWorkflowEvent('workflow/start', info)
  177. // `workflow/end` fires as the (never-rejecting) result settles, with the
  178. // outcome DATA only — the value stays with the run's holder.
  179. void workerRun.result.then((settled) => {
  180. this.emitWorkflowEvent('workflow/end', info, {
  181. stopReason: settled.stopReason,
  182. ...settled.error !== undefined ? { error: settled.error } : {},
  183. agentsStarted: settled.agentsStarted,
  184. })
  185. })
  186. return workerRun
  187. }
  188. }
  189. export default WorkerThreadWorkflowEngine