{"version":3,"file":"execution.mjs","names":[],"sources":["../../../../../../../ai/src/orchestrator/execution.ts"],"sourcesContent":["import type { Message } from \"../contracts/conversation-message.type\";\nimport type { OrchestratorCommands } from \"../contracts/orchestrator/orchestrator-commands.type\";\nimport type { OrchestratorConfig } from \"../contracts/orchestrator/orchestrator-config.type\";\nimport type {\n  OrchestratorEvent,\n  OrchestratorEventHandlers,\n  OrchestratorEventMap,\n  OrchestratorEventName,\n} from \"../contracts/orchestrator/orchestrator-event.type\";\nimport type {\n  OrchestratorExecuteOptions,\n  OrchestratorResumeOptions,\n} from \"../contracts/orchestrator/orchestrator-execute-options.type\";\nimport type {\n  CompactionResult,\n  OrchestratorReport,\n  OrchestratorReportStatus,\n  OrchestratorResult,\n  TurnSnapshot,\n} from \"../contracts/result/orchestrator-result.type\";\nimport { REPORT_SCHEMA_VERSION } from \"../contracts/result/base-report.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type { EventIdentity } from \"../contracts/events/event-identity.type\";\nimport {\n  resolveDefaultCheckpointStore,\n  resolveDefaultSnapshotStore,\n} from \"../config\";\nimport type { AIError } from \"../errors/ai-error\";\nimport { OrchestratorConfigError, OrchestratorDriftError } from \"../errors\";\nimport { notifyObservers } from \"../observe/resolve-observers\";\nimport type { ResolvedIntentEntry } from \"../supervisor/entries\";\nimport { generateRunId } from \"../utils/generate-run-id\";\nimport { persistCheckpoint, summarizeRoute } from \"./checkpoint\";\nimport { runCompaction, runManualCompaction, shouldCompact } from \"./compaction\";\nimport { deriveRunId, dispatchTurn } from \"./dispatch\";\nimport type { OrchestratorEmitter } from \"./emitter\";\nimport type { OrchestratorEmitterLike } from \"./emitter-port.type\";\nimport type { OrchestratorEngineContext } from \"./engine-context.type\";\nimport { acquireLock } from \"./lock\";\nimport { loadSession } from \"./load\";\nimport {\n  injectMemories,\n  outcomeTextFromTurn,\n  recallForTurn,\n  rememberTurnOutcome,\n  resolveOrchestratorMemory,\n} from \"./memory\";\nimport type { OrchestratorStreamController } from \"./orchestrator-stream\";\nimport { resolveResume } from \"./resume\";\nimport { windowHistory } from \"./window\";\n\n/** Empty rolled-up usage for turns that never dispatched (drift/seed). */\nconst ZERO_USAGE: Usage = { input: 0, output: 0, total: 0 };\n\n/**\n * Constructor params the C1 factory passes when building an\n * {@link OrchestratorExecution} per call. The factory owns author-time\n * validation, intent-entry resolution, and signature computation; it\n * hands the engine the validated `config`, the resolved `entries`, the\n * computed `signature`, and the shared three-tier `emitter`. The\n * per-call inputs vary by entry point:\n *\n * - `execute` / `stream` — `input` + `options` (and `streamController`\n *   for `stream`).\n * - `resume` — `resumeSessionId` + `resumeOptions`.\n * - `command(\"compact\")` — neither; `compact(args)` carries its own.\n */\nexport type OrchestratorExecutionParams<TOutput, TState> = {\n  config: OrchestratorConfig<TOutput, TState>;\n  /** Resolved intent entries (validated by C1; the engine delegates dispatch to the supervisor). */\n  entries?: Map<string, ResolvedIntentEntry>;\n  signature: string;\n  emitter: OrchestratorEmitter;\n  input?: SupervisorInput;\n  options?: OrchestratorExecuteOptions<TState>;\n  streamController?: OrchestratorStreamController<OrchestratorResult<TOutput>>;\n  resumeSessionId?: string;\n  resumeOptions?: OrchestratorResumeOptions;\n};\n\n/**\n * Per-call lifecycle engine — the single object the C1 factory\n * constructs and drives. Owns the 7-phase lifecycle (orchestrator.md §3:\n * load → drift → lock → window → dispatch → persist → compaction),\n * resolving the durable stores (own config field → `ai.config` default)\n * and adapting C1's three-tier {@link OrchestratorEmitter} to the\n * {@link OrchestratorEmitterLike} port the phase modules call.\n *\n * The factory creates a fresh instance per `execute` / `stream` /\n * `resume` / `command` call (single-call lifecycle invariant — §18.8);\n * the heavy lifting lives in the standalone phase functions\n * ({@link runTurn} / {@link runResume}) which this class delegates to.\n *\n * @example\n * const execution = new OrchestratorExecution({\n *   config, entries, signature, emitter, input, options,\n * });\n * const result = await execution.run();\n */\nexport class OrchestratorExecution<TOutput, TState> {\n  private readonly params: OrchestratorExecutionParams<TOutput, TState>;\n  private readonly ctx: OrchestratorEngineContext<TOutput, TState>;\n  private readonly streamController?: OrchestratorStreamController<\n    OrchestratorResult<TOutput>\n  >;\n\n  public constructor(params: OrchestratorExecutionParams<TOutput, TState>) {\n    this.params = params;\n    this.streamController = params.streamController;\n    this.ctx = {\n      config: params.config,\n      signature: params.signature,\n      checkpointStore: resolveCheckpointStore(params.config),\n      snapshotStore: resolveSnapshotStore(params.config),\n      emitter: adaptEmitter(\n        params.emitter,\n        generateRunId(\"orchestrator\"),\n        this.streamController as\n          | OrchestratorStreamController<unknown>\n          | undefined,\n      ),\n      memory: resolveOrchestratorMemory(params.config.memory),\n    };\n  }\n\n  /**\n   * `execute()` / `stream()` entry — run one turn through the 7-phase\n   * lifecycle. When a `streamController` was supplied, the adapter mirrors\n   * every emitted event into the stream and the controller is settled\n   * (`end` / `fail`) once the result resolves.\n   */\n  public async run(): Promise<OrchestratorResult<TOutput>> {\n    if (this.params.input === undefined || !this.params.options) {\n      throw new OrchestratorConfigError(\n        `ai.orchestrator(\"${this.params.config.name}\"): internal — run() invoked without input/options`,\n      );\n    }\n\n    try {\n      const result = await runTurn(\n        this.ctx,\n        this.params.input,\n        this.params.options,\n      );\n\n      // Route the orchestrator's report to observers (per-flow `observe` +\n      // the global observe-all gate) — parity with agent/workflow/supervisor,\n      // so a durable session root no longer needs a manual observe.collect().\n      await notifyObservers(this.ctx.config.observe, result.report);\n\n      this.streamController?.end(result);\n\n      return result;\n    } catch (error) {\n      this.streamController?.fail(error as Error);\n\n      throw error;\n    }\n  }\n\n  /**\n   * `resume()` entry — drain an interrupted `iterate: true` turn (§9).\n   * Returns `null` when nothing is in flight.\n   */\n  public async resume(): Promise<OrchestratorResult<TOutput> | null> {\n    if (!this.params.resumeSessionId) {\n      throw new OrchestratorConfigError(\n        `ai.orchestrator(\"${this.params.config.name}\"): internal — resume() invoked without a sessionId`,\n      );\n    }\n\n    return runResume(this.ctx, this.params.resumeSessionId, this.params.resumeOptions);\n  }\n\n  /**\n   * `command(\"compact\")` entry — run a manual compaction on demand (§11 /\n   * §12.1). Reuses the post-turn compaction code path against the\n   * caller-supplied history and returns the raw {@link CompactionResult}.\n   */\n  public async compact(\n    args: OrchestratorCommands[\"compact\"][\"args\"],\n  ): Promise<OrchestratorCommands[\"compact\"][\"result\"]> {\n    return runManualCompaction(\n      this.ctx as OrchestratorEngineContext<unknown, TState>,\n      args.history,\n    );\n  }\n}\n\n/**\n * Resolve the durable checkpoint store: the config's own field, falling\n * back to `ai.config({ defaultCheckpointStore })`. Throws\n * {@link OrchestratorConfigError} when neither resolves — persistence is\n * always on (§8.1), so a turn can never run without a checkpoint store.\n */\nfunction resolveCheckpointStore<TOutput, TState>(\n  config: OrchestratorConfig<TOutput, TState>,\n) {\n  const store = config.checkpointStore ?? resolveDefaultCheckpointStore();\n\n  if (!store) {\n    throw new OrchestratorConfigError(\n      `ai.orchestrator(\"${config.name}\"): a \\`checkpointStore\\` is required ` +\n        `(set one on the config or via \\`ai.config({ defaultCheckpointStore })\\`)`,\n    );\n  }\n\n  return store;\n}\n\n/**\n * Resolve the internal-supervisor snapshot store for `iterate: true`\n * turns: the config's own field, falling back to\n * `ai.config({ defaultSnapshotStore })`. Returns `undefined` for\n * `iterate: false` orchestrators (no mid-turn resume — nothing to\n * snapshot). The factory already guarantees presence when\n * `iterate: true`, so the engine never asserts here.\n */\nfunction resolveSnapshotStore<TOutput, TState>(\n  config: OrchestratorConfig<TOutput, TState>,\n) {\n  if (config.iterate !== true) {\n    return undefined;\n  }\n\n  return config.snapshotStore ?? resolveDefaultSnapshotStore();\n}\n\n/**\n * Adapt C1's three-tier {@link OrchestratorEmitter} (whose `emit` takes\n * `event, payload, identity, perCallHandlers?`) to the\n * {@link OrchestratorEmitterLike} port the phase modules call (a 2-arg\n * `emit(event, payload)` plus `bindPerCall`).\n *\n * The adapter injects the run identity centrally and, when a stream\n * controller is present, mirrors every fully-stamped event into the\n * stream pipe (§14.1 — the orchestrator's own events surface on the\n * stream alongside the bubbled child events). `bindPerCall` registers\n * the per-call `options.on` bag for the turn's duration and returns a\n * disposer that clears it.\n */\nfunction adaptEmitter(\n  emitter: OrchestratorEmitter,\n  runId: string,\n  streamController: OrchestratorStreamController<unknown> | undefined,\n): OrchestratorEmitterLike {\n  // `rootRunId === runId` for a standalone run; nested propagation lands\n  // in a follow-up (see `EventIdentity`).\n  const fullIdentity: EventIdentity = { runId, rootRunId: runId };\n\n  let perCall: OrchestratorEventHandlers | undefined;\n\n  return {\n    emit<K extends OrchestratorEventName>(\n      event: K,\n      payload: OrchestratorEventMap[K],\n    ): void {\n      const fullPayload = emitter.emit(event, payload, fullIdentity, perCall);\n\n      // The discriminated-union correlation between `type` and the\n      // matching payload variant can't be expressed structurally — the\n      // cast mirrors the supervisor stream's established pattern.\n      streamController?.push({ type: event, ...fullPayload } as OrchestratorEvent);\n    },\n    bindPerCall(handlers: OrchestratorEventHandlers | undefined): () => void {\n      perCall = handlers;\n\n      return () => {\n        perCall = undefined;\n      };\n    },\n  };\n}\n\n/**\n * Phase 2 — drift check (orchestrator.md §3 / §4 Phase 2). Compares the\n * loaded checkpoint's `signature` against the current definition's.\n * Mismatch throws `OrchestratorDriftError` synchronously unless\n * `force` is set. Emits `orchestrator.drift.checked` either way. A new\n * session (no loaded signature) never drifts.\n */\nfunction assertNoDrift(\n  ctx: OrchestratorEngineContext,\n  sessionId: string,\n  loadedSignature: string | undefined,\n  force: boolean | undefined,\n): void {\n  const drifted =\n    loadedSignature !== undefined && loadedSignature !== ctx.signature;\n\n  ctx.emitter.emit(\"orchestrator.drift.checked\", {\n    sessionId,\n    signature: ctx.signature,\n    drifted,\n  });\n\n  if (drifted && !force) {\n    throw new OrchestratorDriftError(\n      `orchestrator \"${ctx.config.name}\": signature drift on session \"${sessionId}\" — ` +\n        `the definition changed since this session was last persisted. ` +\n        `Pass { force: true } only after reviewing the change, or discard / migrate the session.`,\n      {\n        savedSignature: loadedSignature as string,\n        currentSignature: ctx.signature,\n        sessionId,\n      },\n    );\n  }\n}\n\n/**\n * Shallow-merge the per-call `state` patch (§5 — partial state\n * override) over the loaded session-state seed. The merged value\n * becomes the supervisor's seed for this turn.\n */\nfunction applyStatePatch<TState>(\n  seed: TState,\n  patch: Partial<TState> | undefined,\n): TState {\n  if (!patch) {\n    return seed;\n  }\n\n  return { ...seed, ...patch } as TState;\n}\n\n/**\n * Assemble the orchestrator-scope {@link OrchestratorReport} from the\n * dispatched turn's child report and the turn snapshot. Wraps the\n * child supervisor/agent report tree as `children[0]` (§15.6 —\n * `children[]` carries only the CURRENT turn's dispatched primitive\n * reports) while the per-turn forensic record lives on `turns[]`.\n */\nfunction buildReport(\n  ctx: OrchestratorEngineContext,\n  sessionId: string,\n  turnIndex: number,\n  status: OrchestratorReportStatus,\n  turnSnapshot: TurnSnapshot | undefined,\n  childReport: BaseReport | undefined,\n  error?: AIError,\n): OrchestratorReport {\n  const now = new Date().toISOString();\n  const usage = turnSnapshot?.usage ?? childReport?.usage ?? ZERO_USAGE;\n\n  return {\n    runId: deriveRunId(sessionId, ctx.config.version, turnIndex),\n    rootRunId: deriveRunId(sessionId, ctx.config.version, turnIndex),\n    name: ctx.config.name,\n    version: ctx.config.version,\n    sessionId,\n    type: \"orchestrator\",\n    status,\n    // Stamp the terminal error so the observe path surfaces it on the\n    // orchestrator span (an observer never sees the result envelope).\n    // Absent on a clean turn.\n    ...(error ? { error } : {}),\n    startedAt: turnSnapshot?.startedAt ?? now,\n    endedAt: turnSnapshot?.endedAt ?? now,\n    duration: turnSnapshot?.duration ?? 0,\n    usage,\n    children: childReport ? [childReport] : [],\n    reportSchemaVersion: REPORT_SCHEMA_VERSION,\n    turnIndex,\n    signature: ctx.signature,\n    turns: turnSnapshot ? [turnSnapshot] : [],\n  };\n}\n\n/**\n * Map the dispatched supervisor result's report status onto the\n * orchestrator's status surface (§15.6). A clean completion that is\n * still mid-conversation reports `\"awaiting-input\"` (the session\n * continues) rather than `\"completed\"`; failures and cancellations\n * pass through.\n */\nfunction deriveStatus(childStatus: BaseReport[\"status\"]): OrchestratorReportStatus {\n  if (childStatus === \"completed\") {\n    return \"awaiting-input\";\n  }\n\n  return childStatus;\n}\n\n/**\n * Emit the terminal turn event matching the report status (§14.1).\n */\nfunction emitTerminal(\n  ctx: OrchestratorEngineContext,\n  sessionId: string,\n  turnIndex: number,\n  status: OrchestratorReportStatus,\n): void {\n  if (status === \"cancelled\") {\n    ctx.emitter.emit(\"orchestrator.turn.cancelled\", { sessionId, turnIndex });\n\n    return;\n  }\n\n  if (status === \"failed\" || status === \"max-iterations\") {\n    ctx.emitter.emit(\"orchestrator.turn.failed\", { sessionId, turnIndex });\n\n    return;\n  }\n\n  if (status === \"awaiting-input\") {\n    ctx.emitter.emit(\"orchestrator.turn.awaiting-input\", {\n      sessionId,\n      turnIndex,\n    });\n\n    return;\n  }\n\n  ctx.emitter.emit(\"orchestrator.turn.completed\", { sessionId, turnIndex });\n}\n\n/**\n * Run one turn end-to-end through the 7-phase lifecycle (orchestrator\n * .md §3). The single entry the C1 factory's `execute()` delegates to.\n *\n * Phase order is the diagram's contract: load → drift → lock → window\n * → dispatch → persist → compaction. Drift / config misuse throw;\n * every other failure surfaces on `result.error` (the contract: the\n * orchestrator never throws on runtime failure). Cancellation and\n * failure do NOT persist a fresh checkpoint (§17 — state reverts to the\n * pre-turn checkpoint).\n */\nexport async function runTurn<TOutput, TState>(\n  ctx: OrchestratorEngineContext<TOutput, TState>,\n  input: SupervisorInput,\n  options: OrchestratorExecuteOptions<TState>,\n): Promise<OrchestratorResult<TOutput>> {\n  const sessionId = options.sessionId;\n  const disposePerCall = ctx.emitter.bindPerCall(options.on);\n\n  try {\n    // Phase 1 — load session.\n    const loaded = await loadSession(ctx, sessionId);\n\n    ctx.emitter.emit(\"orchestrator.turn.starting\", {\n      sessionId,\n      turnIndex: loaded.turnIndex,\n    });\n\n    ctx.emitter.emit(\"orchestrator.session.loaded\", {\n      sessionId,\n      turnIndex: loaded.turnIndex,\n      found: loaded.found,\n    });\n\n    // Phase 2 — drift check.\n    assertNoDrift(\n      ctx as OrchestratorEngineContext,\n      sessionId,\n      loaded.record?.signature,\n      options.force,\n    );\n\n    // Phase 3 — lock check (cooperative, fail-open).\n    await acquireLock(ctx, sessionId, loaded.record);\n\n    // Phase 4 — window history.\n    const windowed = windowHistory(\n      ctx as OrchestratorEngineContext,\n      sessionId,\n      options.history,\n    );\n\n    // Phase 5 — dispatch. When memory is configured, recall the\n    // turn-relevant memories and inject them into the request-scoped\n    // context bag so every route / router / evaluate / dispatch callback\n    // surfaces them at `ctx.context[injectKey]` before routing runs.\n    const seedState = applyStatePatch(loaded.state, options.state);\n\n    let turnContext = options.context;\n\n    // Recall is scoped to THIS session (`memory.scope`, default\n    // `\"session\"`): the store is shared by every session of this\n    // orchestrator instance, so the scope — not the store — is what keeps\n    // another session's remembered turns out of this turn's context.\n    if (ctx.memory) {\n      const recalled = await recallForTurn(ctx.memory, input, sessionId);\n      turnContext = injectMemories(turnContext, ctx.memory, recalled);\n    }\n\n    const { result, state, turnSnapshot } = await dispatchTurn<TOutput, TState>({\n      ctx,\n      sessionId,\n      input,\n      seedState,\n      turnIndex: loaded.turnIndex,\n      history: windowed.agents,\n      context: turnContext,\n      signal: options.signal,\n    });\n\n    ctx.emitter.emit(\"orchestrator.turn.routed\", {\n      sessionId,\n      turnIndex: loaded.turnIndex,\n      source: turnSnapshot.decision.source,\n      raw: turnSnapshot.decision.raw,\n    });\n\n    const status = result.error\n      ? deriveStatus(result.report.status)\n      : \"awaiting-input\";\n\n    // Cancelled / failed turns revert: no fresh checkpoint, no compaction.\n    if (result.error) {\n      const report = buildReport(\n        ctx as OrchestratorEngineContext,\n        sessionId,\n        loaded.turnIndex,\n        status,\n        turnSnapshot,\n        result.report,\n        result.error,\n      );\n\n      emitTerminal(ctx as OrchestratorEngineContext, sessionId, loaded.turnIndex, status);\n\n      return {\n        data: result.data,\n        error: result.error,\n        usage: result.usage,\n        report,\n        sessionId,\n        turnIndex: loaded.turnIndex,\n      };\n    }\n\n    // Phase 6 — persist checkpoint.\n    await persistCheckpoint({\n      ctx,\n      sessionId,\n      turnIndex: loaded.turnIndex,\n      state,\n      lastRoute: summarizeRoute(turnSnapshot.decision.raw as never),\n      summarizedThrough: loaded.record?.summarized_through ?? null,\n    });\n\n    // Memory write-back (memory core M2). The turn settled cleanly (the\n    // `result.error` branch above already returned for cancelled /\n    // failed turns, which revert and never remember — §17), so remember\n    // the input + its outcome for later recall.\n    if (ctx.memory) {\n      await rememberTurnOutcome(\n        ctx.memory,\n        input,\n        outcomeTextFromTurn(result.data, turnSnapshot),\n        sessionId,\n      );\n    }\n\n    // Phase 7 — post-turn compaction (only when triggered).\n    let compaction: CompactionResult | undefined;\n\n    if (shouldCompact(ctx as OrchestratorEngineContext, loaded.turnIndex)) {\n      const outcome = await runCompaction(\n        ctx as OrchestratorEngineContext<unknown, TState>,\n        sessionId,\n        options.history,\n      );\n\n      if (outcome) {\n        compaction = outcome.compaction;\n\n        if (outcome.applied) {\n          await advanceSummarizedThrough(\n            ctx as OrchestratorEngineContext<unknown, TState>,\n            sessionId,\n            outcome.compaction.replacesToIndex,\n          );\n        }\n      }\n    }\n\n    const report = buildReport(\n      ctx as OrchestratorEngineContext,\n      sessionId,\n      loaded.turnIndex,\n      \"awaiting-input\",\n      turnSnapshot,\n      result.report,\n    );\n\n    emitTerminal(ctx as OrchestratorEngineContext, sessionId, loaded.turnIndex, \"awaiting-input\");\n\n    return {\n      data: result.data,\n      error: undefined,\n      usage: result.usage,\n      report,\n      sessionId,\n      turnIndex: loaded.turnIndex,\n      compaction,\n    };\n  } finally {\n    disposePerCall();\n  }\n}\n\n/**\n * After a framework-applied compaction (`onCompact` succeeded), advance\n * the persisted `summarized_through` to the compaction's\n * `replacesToIndex` (§12.2 step 4). Re-saves the latest row with the\n * updated marker (append-only stores keep the prior row).\n */\nasync function advanceSummarizedThrough<TState>(\n  ctx: OrchestratorEngineContext<unknown, TState>,\n  sessionId: string,\n  replacesToIndex: number,\n): Promise<void> {\n  const latest = await ctx.checkpointStore.load(ctx.config.name, sessionId);\n\n  if (!latest) {\n    return;\n  }\n\n  await ctx.checkpointStore.save({\n    ...latest,\n    summarized_through: replacesToIndex,\n    saved_at: new Date().toISOString(),\n  });\n}\n\n/**\n * §9 resume protocol entry the C1 factory's `resume()` delegates to.\n * Returns `null` when no in-flight `iterate: true` turn is detected;\n * otherwise drains the interrupted supervisor run, persists a fresh\n * checkpoint for the resumed turn, and returns the completed result.\n *\n * Runs the same Phase 2 drift check as `runTurn` (§9.4). The heavy\n * lifting lives in `resume.ts`; this wrapper threads the engine\n * context.\n */\nexport async function runResume<TOutput, TState>(\n  ctx: OrchestratorEngineContext<TOutput, TState>,\n  sessionId: string,\n  options?: OrchestratorResumeOptions,\n): Promise<OrchestratorResult<TOutput> | null> {\n  const disposePerCall = ctx.emitter.bindPerCall(options?.on);\n\n  try {\n    return await resolveResume(ctx, sessionId, options, {\n      assertNoDrift: (loadedSignature) =>\n        assertNoDrift(\n          ctx as OrchestratorEngineContext,\n          sessionId,\n          loadedSignature,\n          options?.force,\n        ),\n      buildReport: (turnIndex, status, turnSnapshot, childReport) =>\n        buildReport(\n          ctx as OrchestratorEngineContext,\n          sessionId,\n          turnIndex,\n          status,\n          turnSnapshot,\n          childReport,\n        ),\n      deriveStatus,\n      emitTerminal: (turnIndex, status) =>\n        emitTerminal(ctx as OrchestratorEngineContext, sessionId, turnIndex, status),\n      persist: (turnIndex, state, lastRoute, summarizedThrough) =>\n        persistCheckpoint({\n          ctx,\n          sessionId,\n          turnIndex,\n          state,\n          lastRoute,\n          summarizedThrough,\n        }),\n    });\n  } finally {\n    disposePerCall();\n  }\n}\n\n/**\n * The `stream()` entry. The orchestrator's streaming surface bubbles\n * child agent/supervisor events under their own namespace (§14.2); the\n * C1 stream controller owns the `StreamContract` wiring. This engine\n * entry runs the same lifecycle as `runTurn` — the C1 factory passes a\n * per-call `on` bag wired to the stream controller, so the engine needs\n * no streaming-specific branch. Exposed as a distinct name for the\n * factory to call, returning the same `OrchestratorResult` the stream's\n * `.result` resolves to.\n */\nexport async function streamTurn<TOutput, TState>(\n  ctx: OrchestratorEngineContext<TOutput, TState>,\n  input: SupervisorInput,\n  options: OrchestratorExecuteOptions<TState>,\n): Promise<OrchestratorResult<TOutput>> {\n  return runTurn(ctx, input, options);\n}\n\nexport type { OrchestratorEngineContext } from \"./engine-context.type\";\nexport type { Message };\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,MAAM,aAAoB;CAAE,OAAO;CAAG,QAAQ;CAAG,OAAO;AAAE;;;;;;;;;;;;;;;;;;;;AA+C1D,IAAa,wBAAb,MAAoD;CAOlD,AAAO,YAAY,QAAsD;EACvE,KAAK,SAAS;EACd,KAAK,mBAAmB,OAAO;EAC/B,KAAK,MAAM;GACT,QAAQ,OAAO;GACf,WAAW,OAAO;GAClB,iBAAiB,uBAAuB,OAAO,MAAM;GACrD,eAAe,qBAAqB,OAAO,MAAM;GACjD,SAAS,aACP,OAAO,SACP,cAAc,cAAc,GAC5B,KAAK,gBAGP;GACA,QAAQ,0BAA0B,OAAO,OAAO,MAAM;EACxD;CACF;;;;;;;CAQA,MAAa,MAA4C;EACvD,IAAI,KAAK,OAAO,UAAU,UAAa,CAAC,KAAK,OAAO,SAClD,MAAM,IAAI,wBACR,oBAAoB,KAAK,OAAO,OAAO,KAAK,mDAC9C;EAGF,IAAI;GACF,MAAM,SAAS,MAAM,QACnB,KAAK,KACL,KAAK,OAAO,OACZ,KAAK,OAAO,OACd;GAKA,MAAM,gBAAgB,KAAK,IAAI,OAAO,SAAS,OAAO,MAAM;GAE5D,KAAK,kBAAkB,IAAI,MAAM;GAEjC,OAAO;EACT,SAAS,OAAO;GACd,KAAK,kBAAkB,KAAK,KAAc;GAE1C,MAAM;EACR;CACF;;;;;CAMA,MAAa,SAAsD;EACjE,IAAI,CAAC,KAAK,OAAO,i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