host.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /**
  2. * The host half of one worker-engine run: spawn the Worker, bridge its child
  3. * RPC onto `ctx.subagents`, fan its observer messages into the engine's
  4. * events, and own cancellation, the settle-within-grace guarantee, and child
  5. * cleanup. The worker's lifetime IS the run's lifetime: `dispose()` always
  6. * ends with `worker.terminate()`, so no thread outlives its run.
  7. *
  8. * The run's `result` promise settles exactly once, from whichever of these
  9. * lands first: the worker's `result` message (a host-side cancellation in
  10. * flight overrides a non-cancelled report — the seam-visible result had not
  11. * settled when cancellation was requested), an unexpected worker death
  12. * (`error`/`messageerror`/premature `exit` → `stopReason: 'error'`, or
  13. * `'cancelled'` when a cancel was in flight), or the post-cancel grace timer
  14. * (a script that never settles is force-settled `cancelled` and its worker
  15. * terminated — the real kill an in-process engine could not perform).
  16. *
  17. * Children live in a host-side registry (callId → run): the worker drives
  18. * their disposal by RPC on the graceful path, `dispose()` host-drives every
  19. * registered child's disposal immediately (a wedged worker can relay no
  20. * dispose RPC, and child teardown must overlap the grace, not start after
  21. * it), and the registry is what lets the host abort and dispose every
  22. * survivor when the worker dies or is terminated mid-flight. The three
  23. * paths share ONE disposal per child (memoized by callId; the seam's
  24. * dispose() is idempotent anyway, the memo keeps the bookkeeping and the
  25. * containment warn single). Lifecycle pairing is host-guaranteed the same
  26. * way: every forwarded `agent-start` lives in a ledger, and a start the
  27. * dead or terminated worker never paired is closed by a synthesized
  28. * `agent-end` (outcome `'cancelled'`) before the run settles. On a
  29. * termination path `agentsStarted` reports the
  30. * HOST-observed count (accepted `child-start` messages) — `agent()` calls
  31. * still queued worker-side for a concurrency slot are unknowable then; the
  32. * worker's own count rides the result message on every graceful path.
  33. *
  34. * @module @deepseek-ai/dsh-workflow-workerthread/host
  35. */
  36. import { fileURLToPath } from 'node:url'
  37. import { Worker } from 'node:worker_threads'
  38. import type { WorkerOptions } from 'node:worker_threads'
  39. import type { Context } from 'cordis'
  40. import type { Agent } from '@deepseek-ai/dsh-agent'
  41. import { assertNever } from '@deepseek-ai/dsh-llm'
  42. import type { SubagentRun } from '@deepseek-ai/dsh-subagent'
  43. import type { WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowMeta, WorkflowResult, WorkflowRun, WorkflowRunId } from '@deepseek-ai/dsh-workflow'
  44. import { renderThrown } from './realm.ts'
  45. import type { ExecutionObserver } from './runtime.ts'
  46. import { HostToWorkerType, WorkerToHostType } from './protocol.ts'
  47. import type { HostToWorkerPayloads, WorkerToHostMessage } from './protocol.ts'
  48. import type { ChildStartRequest, WorkerInit } from './types.ts'
  49. /**
  50. * Resolve the worker entry and spawn options for the current runtime shape.
  51. * Unbuilt (tsx demos, vitest — `import.meta.url` points into `src/`), the
  52. * entry is the TypeScript sibling and the worker needs the tsx loader
  53. * registered explicitly: a worker thread inherits no transform pipeline from
  54. * vitest (vite transforms in-process, not via a node loader), and passing
  55. * execArgv explicitly also shields the worker from any loader flags the
  56. * parent was started with. Built (`lib/index.js`), the entry is the sibling
  57. * bundle the package tsdown config emits and no loader is needed.
  58. * @param init - the run payload, passed as `workerData`.
  59. * @returns the entry URL and the Worker options to spawn it with.
  60. */
  61. function resolveWorkerSpawn(init: WorkerInit): { entry: URL; options: WorkerOptions } {
  62. /* v8 ignore next 3 -- the built-output arm: tests always run unbuilt (src/); the built-worker e2e exercises this shape for real */
  63. if (!import.meta.url.endsWith('.ts')) {
  64. return { entry: new URL('./worker.js', import.meta.url), options: { workerData: init } }
  65. }
  66. // Lazy tsx resolution: only the unbuilt shape needs it, so the built
  67. // bundle never requires tsx to be installed.
  68. return {
  69. entry: new URL('./worker.ts', import.meta.url),
  70. options: { workerData: init, execArgv: ['--import', fileURLToPath(import.meta.resolve('tsx'))] },
  71. }
  72. }
  73. /**
  74. * One live worker-engine run — the seam's {@link WorkflowRun}, returned by
  75. * `start()` directly. Owns the Worker, the child registry, and the result
  76. * settlement; `result` never rejects. `meta` is this handle's OWN clone
  77. * (event payloads carry separate clones), so a consumer mutating it corrupts
  78. * nothing.
  79. */
  80. export class WorkerRun implements WorkflowRun {
  81. /** Settles exactly once with the run's outcome; never rejects. */
  82. readonly result: Promise<WorkflowResult>
  83. private settleResolve!: (result: WorkflowResult) => void
  84. private settled = false
  85. private cancelReason: string | undefined
  86. private graceTimer: NodeJS.Timeout | undefined
  87. private readonly worker: Worker
  88. /** Set on `exit`: the thread is gone, so posting has nowhere to go. */
  89. private workerGone = false
  90. /** Accepted `child-start` messages — the terminate-path `agentsStarted` (see module doc). */
  91. private hostStarted = 0
  92. /** Live children by callId; an entry leaves ONLY after its dispose settles (quiescence = empty). */
  93. private readonly children = new Map<number, SubagentRun>()
  94. /** In-flight child disposals by callId — the memo that gives every path (worker RPC, dispose(), reap) ONE shared disposal per child. */
  95. private readonly childDisposals = new Map<number, Promise<void>>()
  96. /** Started-but-not-ended agents by seq — the pairing ledger the HOST guarantees (see {@link endAgent}). */
  97. private readonly liveAgents = new Map<number, WorkflowAgentInfo>()
  98. private readonly quiescenceWaiters: (() => void)[] = []
  99. /** The per-run abort fanout every child start request carries. */
  100. private readonly controller = new AbortController()
  101. private disposed: Promise<void> | undefined
  102. constructor(
  103. private readonly ctx: Context,
  104. readonly id: WorkflowRunId,
  105. readonly meta: WorkflowMeta,
  106. private readonly parent: Agent,
  107. init: WorkerInit,
  108. private readonly provider: string,
  109. private readonly disposeGraceMs: number,
  110. private readonly observer: ExecutionObserver,
  111. signal: AbortSignal | undefined,
  112. ) {
  113. this.result = new Promise<WorkflowResult>((resolve) => { this.settleResolve = resolve })
  114. // workerData rides the structured clone: args are plain JSON by the seam
  115. // contract, so the clone is total and doubles as the caller-isolation
  116. // copy (a clone failure throws loud out of start()).
  117. const { entry, options } = resolveWorkerSpawn(init)
  118. this.worker = new Worker(entry, options)
  119. this.worker.on('message', (message: WorkerToHostMessage) => { this.onMessage(message) })
  120. this.worker.on('error', (error) => { this.onWorkerDeath(`workflow worker failed: ${renderThrown(error)}`) })
  121. /* v8 ignore next -- messageerror: not constructible from the engine's own protocol (every payload is JSON data) */
  122. this.worker.on('messageerror', (error) => { this.onWorkerDeath(`workflow worker message failed to deserialize: ${renderThrown(error)}`) })
  123. this.worker.on('exit', (code) => {
  124. this.workerGone = true
  125. this.onWorkerDeath(`workflow worker exited before the run settled (exit code ${code})`)
  126. })
  127. if (signal?.aborted) {
  128. this.cancel('workflow start signal already aborted')
  129. } else {
  130. signal?.addEventListener('abort', () => { this.cancel('workflow signal aborted') }, { once: true })
  131. }
  132. }
  133. /**
  134. * Cancel the run: the worker is told (its hooks start throwing and the
  135. * script dies at its next await), every host-side child is cancelled NOW on
  136. * BOTH seam channels — the shared request signal aborts and each registered
  137. * child's explicit `cancel()` is called (the seam leaves a provider free to
  138. * honor either, and a worker wedged in a synchronous spin could not relay
  139. * its own per-child cancel RPCs until far too late) — and the grace timer
  140. * arms: a run still unsettled `disposeGraceMs` later force-settles
  141. * `cancelled` and its worker is TERMINATED. Idempotent; the first reason
  142. * wins.
  143. * @param reason - human-readable cause (default `'workflow cancelled'`).
  144. */
  145. cancel(reason?: string): void {
  146. // A settled run has nothing left to cancel: without this guard the
  147. // ordinary consumer path (await result, then dispose -> cancel) would arm
  148. // a grace timer nothing ever clears, pinning the run and its Worker
  149. // closure until the grace expires - a bounded leak per completed run.
  150. if (this.settled || this.cancelReason !== undefined) return
  151. this.cancelReason = reason ?? 'workflow cancelled'
  152. this.post(HostToWorkerType.Cancel, { reason: this.cancelReason })
  153. this.controller.abort(this.cancelReason)
  154. // The explicit channel is driven host-side, not left to the worker: a
  155. // provider honoring only run.cancel() must not wait on a wedged worker's
  156. // ChildCancel relay (those later RPCs land as idempotent no-ops).
  157. for (const run of this.children.values()) run.cancel(this.cancelReason)
  158. this.graceTimer = setTimeout(() => {
  159. // The worker may no longer speak (it is about to be terminated): pair
  160. // every stranded start before the run settles, so ends precede
  161. // workflow/end.
  162. this.endStrandedAgents()
  163. this.settleResult(this.cancelledResult(this.hostStarted))
  164. void this.worker.terminate()
  165. }, this.disposeGraceMs)
  166. // unref'd: an armed grace timer must never hold the process open.
  167. this.graceTimer.unref()
  168. }
  169. /**
  170. * Cancel + bounded settle + termination. Host-drives every registered
  171. * child's disposal IMMEDIATELY — a wedged worker can relay no dispose RPC,
  172. * and deferring child teardown to the post-terminate reap would spend the
  173. * whole grace waiting for a quiescence that cannot start, then return with
  174. * the disposals still in flight — so child disposal overlaps the same
  175. * grace the worker gets to settle (the worker's own dispose RPCs join the
  176. * shared per-child disposal). Waits (at most the grace) for the result and
  177. * child quiescence, then terminates the worker unconditionally — the
  178. * thread never outlives its run — and reaps whatever children remain
  179. * (their disposal is contained, not awaited past the grace, the same
  180. * abandonment the seam documents for a slow-disposing child). Idempotent;
  181. * safe on every path.
  182. * @returns resolves when the run's resources are released or abandoned.
  183. */
  184. dispose(): Promise<void> {
  185. this.disposed ??= (async () => {
  186. this.cancel('workflow disposed')
  187. for (const [callId, run] of [...this.children]) void this.disposeChild(callId, run)
  188. await Promise.race([
  189. (async () => {
  190. await this.result
  191. await this.childQuiescence()
  192. })(),
  193. sleep(this.disposeGraceMs),
  194. ])
  195. await this.worker.terminate()
  196. this.reapChildren('workflow disposed')
  197. })()
  198. return this.disposed
  199. }
  200. /** Post one message to the worker (payload looked up from the tag's map entry), tolerating a thread that is already gone. */
  201. private post<T extends HostToWorkerType>(type: T, payload: HostToWorkerPayloads[T]): void {
  202. if (this.workerGone) return
  203. try {
  204. this.worker.postMessage({ type, ...payload })
  205. } catch (error: unknown) {
  206. // Only a teardown race can land here (every engine message is JSON
  207. // data, so serialization cannot fail); there is nothing left to
  208. // deliver to — log and move on.
  209. /* v8 ignore next -- postMessage teardown race (a throw between exit and its event): not constructible in-process */
  210. this.ctx.logger.warn(`workflow-workerthread: postMessage failed: ${renderThrown(error)}`)
  211. }
  212. }
  213. private onMessage(message: WorkerToHostMessage): void {
  214. switch (message.type) {
  215. case WorkerToHostType.Ready:
  216. this.post(HostToWorkerType.Go, {})
  217. break
  218. case WorkerToHostType.Phase:
  219. // Post-cancel narration is suppressed host-side: worker-side the
  220. // hooks throw once the cancel message is PROCESSED, but narration
  221. // already in flight (or emitted while the cancel crossed the
  222. // boundary) must not reach observers — nothing is emitted after
  223. // cancel() returns.
  224. if (this.cancelReason === undefined) this.observer.phase(message.title)
  225. break
  226. case WorkerToHostType.Log:
  227. if (this.cancelReason === undefined) this.observer.log(message.message)
  228. break
  229. case WorkerToHostType.AgentStart:
  230. this.liveAgents.set(message.info.seq, message.info)
  231. this.observer.agentStart(message.info)
  232. break
  233. case WorkerToHostType.AgentEnd:
  234. // NOT suppressed on cancel: cancelled children report their paired
  235. // agent-end with outcome 'cancelled'. The gate (with the termination
  236. // paths' synthesis) is what makes the one-pair-per-started-child
  237. // contract hold on every stop path.
  238. this.endAgent(message.info)
  239. break
  240. case WorkerToHostType.ChildStart:
  241. this.onChildStart(message.callId, message.request)
  242. break
  243. case WorkerToHostType.ChildCancel:
  244. this.children.get(message.callId)?.cancel(message.reason)
  245. break
  246. case WorkerToHostType.ChildDispose:
  247. this.onChildDispose(message.callId)
  248. break
  249. case WorkerToHostType.Result:
  250. this.onResult(message.result)
  251. break
  252. /* v8 ignore next 2 -- closed engine-owned union; the arm only makes adding a message type a compile error */
  253. default:
  254. assertNever(message, 'worker-to-host message')
  255. }
  256. }
  257. private onChildStart(callId: number, request: ChildStartRequest): void {
  258. if (this.cancelReason !== undefined) {
  259. // The worker's start raced our cancel: refuse — a child must never
  260. // start on an already-aborted signal (a provider subscribing only to
  261. // future abort events would never observe it).
  262. this.post(HostToWorkerType.ChildStartError, { callId, rendered: `workflow run cancelled: ${this.cancelReason}` })
  263. return
  264. }
  265. this.hostStarted += 1
  266. let run: SubagentRun
  267. try {
  268. run = this.ctx.subagents.start(this.provider, {
  269. prompt: [{ type: 'text', text: request.prompt }],
  270. parent: this.parent,
  271. signal: this.controller.signal,
  272. ...request.schema !== undefined ? { outputSchema: request.schema } : {},
  273. ...request.model !== undefined ? { agentOptions: { model: request.model } } : {},
  274. })
  275. } catch (error: unknown) {
  276. this.post(HostToWorkerType.ChildStartError, { callId, rendered: renderThrown(error) })
  277. return
  278. }
  279. this.children.set(callId, run)
  280. this.post(HostToWorkerType.ChildStarted, { callId, childId: run.id })
  281. run.result.then(
  282. (result) => {
  283. this.post(HostToWorkerType.ChildSettled, {
  284. callId,
  285. result: {
  286. output: result.output,
  287. ...result.structured !== undefined ? { structured: result.structured } : {},
  288. stopReason: result.stopReason,
  289. },
  290. })
  291. },
  292. (error: unknown) => { this.post(HostToWorkerType.ChildFailed, { callId, rendered: renderThrown(error) }) },
  293. )
  294. }
  295. private onChildDispose(callId: number): void {
  296. const run = this.children.get(callId)
  297. if (run === undefined) {
  298. // Already disposed host-side (a dispose() drive or a death reap beat
  299. // the RPC) — the ack is still owed (the worker-side wrapper awaits it).
  300. this.post(HostToWorkerType.ChildDisposed, { callId })
  301. return
  302. }
  303. // disposeChild never rejects (containment is inside), so the ack always follows.
  304. void this.disposeChild(callId, run).then(() => { this.post(HostToWorkerType.ChildDisposed, { callId }) })
  305. }
  306. /**
  307. * Start (or join) one registered child's disposal; the registry entry
  308. * leaves when it settles. Memoized per callId: the worker's dispose RPC,
  309. * the dispose() host drive, and the reap can all land on the same child —
  310. * the child's `dispose()` runs once and every caller awaits that one
  311. * settlement. A rejection is contained (the subagent seam's dispose() is
  312. * not supposed to reject, but a backend that does anyway must not break
  313. * quiescence): logged, and the child still leaves the registry.
  314. * @param callId - the child's registry key.
  315. * @param run - the registered child (the caller looked it up).
  316. * @returns resolves when the disposal settled either way; never rejects.
  317. */
  318. private disposeChild(callId: number, run: SubagentRun): Promise<void> {
  319. let disposal = this.childDisposals.get(callId)
  320. if (disposal === undefined) {
  321. disposal = run.dispose().then(
  322. () => { this.finishChild(callId) },
  323. (error: unknown) => {
  324. this.ctx.logger.warn(`workflow-workerthread: child dispose failed: ${renderThrown(error)}`)
  325. this.finishChild(callId)
  326. },
  327. )
  328. this.childDisposals.set(callId, disposal)
  329. }
  330. return disposal
  331. }
  332. /** Drop a child from the registry (and its disposal memo), releasing quiescence waiters at zero. */
  333. private finishChild(callId: number): void {
  334. this.children.delete(callId)
  335. this.childDisposals.delete(callId)
  336. if (this.children.size === 0) {
  337. for (const waiter of this.quiescenceWaiters.splice(0)) waiter()
  338. }
  339. }
  340. /** Resolves once the child registry is empty (every disposal settled). */
  341. private childQuiescence(): Promise<void> {
  342. if (this.children.size === 0) return Promise.resolve()
  343. return new Promise((resolve) => { this.quiescenceWaiters.push(resolve) })
  344. }
  345. /** Abort + dispose every registered child (worker death / final teardown); disposal is contained, not awaited. */
  346. private reapChildren(reason: string): void {
  347. this.controller.abort(this.cancelReason ?? reason)
  348. for (const [callId, run] of [...this.children]) {
  349. run.cancel(this.cancelReason ?? reason)
  350. void this.disposeChild(callId, run)
  351. }
  352. }
  353. private onResult(result: WorkflowResult): void {
  354. // The worker's settle-reap already child-cancel()s every stray; this
  355. // abort fires the seam signal too, for providers that only honor the
  356. // request signal (both channels, on every path).
  357. if (this.cancelReason === undefined) this.controller.abort('workflow settled')
  358. if (this.cancelReason !== undefined && result.stopReason !== 'cancelled') {
  359. // The script settled while our cancel was crossing the thread boundary
  360. // — the seam-visible result had NOT settled when cancellation was
  361. // requested, so report cancelled (the vm drive()'s post-settle check,
  362. // relocated to the receiving side of the race).
  363. this.settleResult(this.cancelledResult(result.agentsStarted))
  364. return
  365. }
  366. this.settleResult(result)
  367. }
  368. /** An unexpected worker death (or the expected exit after termination). */
  369. private onWorkerDeath(message: string): void {
  370. // Whatever the worker left behind must not leak — abort + dispose it all.
  371. if (this.children.size > 0) this.reapChildren('workflow worker gone')
  372. // The thread is gone: no more worker-authored agent-ends can arrive —
  373. // pair every stranded start (a start that crossed between the grace
  374. // force-settle and this exit included) before the run settles.
  375. this.endStrandedAgents()
  376. // settleResult no-ops on an already-settled run (the expected exit after
  377. // a dispose's terminate lands here too).
  378. if (this.cancelReason !== undefined) {
  379. this.settleResult(this.cancelledResult(this.hostStarted))
  380. return
  381. }
  382. this.settleResult({ value: null, stopReason: 'error', error: message, agentsStarted: this.hostStarted })
  383. }
  384. /**
  385. * The single agent-end emission gate: forwards `end` iff its start is still
  386. * unpaired in the ledger, so every forwarded `workflow/agent-start` gets
  387. * EXACTLY one `workflow/agent-end` — the worker's own report where it can
  388. * speak, a host-synthesized one where it cannot ({@link endStrandedAgents}).
  389. * @param end - the settlement to emit (worker-reported or synthesized).
  390. */
  391. private endAgent(end: WorkflowAgentEndInfo): void {
  392. /* v8 ignore next -- a real end still in flight across the grace force-settle: not orderable in-process */
  393. if (!this.liveAgents.delete(end.seq)) return
  394. this.observer.agentEnd(end)
  395. }
  396. /**
  397. * Synthesize the missing `agent-end` for every started-but-unpaired agent,
  398. * outcome `'cancelled'`: the reap cancels every child, and a real
  399. * settlement racing the force-settle loses to the cancellation — the same
  400. * first-wins override {@link onResult} applies to the run's own result.
  401. * Called where the worker can no longer speak (the grace force-settle,
  402. * worker death), BEFORE settleResult, so the paired ends reach observers
  403. * before `workflow/end`.
  404. */
  405. private endStrandedAgents(): void {
  406. for (const info of [...this.liveAgents.values()]) {
  407. this.endAgent({ ...info, outcome: 'cancelled' })
  408. }
  409. }
  410. private cancelledResult(agentsStarted: number): WorkflowResult {
  411. // cancel() is the only writer of cancelReason and every caller checks it
  412. // first; the fallback guards the type, not a reachable path.
  413. /* v8 ignore next */
  414. const reason = this.cancelReason ?? 'workflow cancelled'
  415. return { value: null, stopReason: 'cancelled', error: `workflow run cancelled: ${reason}`, agentsStarted }
  416. }
  417. /** First settle wins; disarms the grace timer. */
  418. private settleResult(result: WorkflowResult): void {
  419. if (this.settled) return
  420. this.settled = true
  421. clearTimeout(this.graceTimer)
  422. this.settleResolve(result)
  423. }
  424. }
  425. /** A plain timer sleep (the dispose grace); unref'd so it never holds the process open. */
  426. function sleep(ms: number): Promise<void> {
  427. return new Promise((resolve) => {
  428. const timer = setTimeout(resolve, ms)
  429. timer.unref()
  430. })
  431. }