@leitwerk-dev/process-sdk 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +12 -0
  2. package/dist/{chunk-I7U6HCLN.js → chunk-GVBLXKSR.js} +1 -1
  3. package/dist/chunk-GVBLXKSR.js.map +1 -0
  4. package/dist/core-capabilities.d.ts +2 -0
  5. package/dist/core-capabilities.d.ts.map +1 -1
  6. package/dist/define-process.d.ts +3 -0
  7. package/dist/define-process.d.ts.map +1 -1
  8. package/dist/{extension-api-B4gG5w1K.d.ts → extension-api-DM-AvWOW.d.ts} +211 -14
  9. package/dist/extension-api.d.ts +19 -5
  10. package/dist/extension-api.d.ts.map +1 -1
  11. package/dist/external-source-poll.d.ts +18 -12
  12. package/dist/external-source-poll.d.ts.map +1 -1
  13. package/dist/flow.d.ts +118 -13
  14. package/dist/flow.d.ts.map +1 -1
  15. package/dist/index.d.ts +6 -4
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +647 -82
  18. package/dist/index.js.map +1 -1
  19. package/dist/integration-http.d.ts +4 -4
  20. package/dist/integration-http.d.ts.map +1 -1
  21. package/dist/json-data.d.ts +1 -1
  22. package/dist/json-data.d.ts.map +1 -1
  23. package/dist/mapped-turn.d.ts +185 -0
  24. package/dist/mapped-turn.d.ts.map +1 -0
  25. package/dist/pi-config-public.js +1 -1
  26. package/dist/pi-config.js +1 -1
  27. package/dist/repository-feedback.d.ts +32 -26
  28. package/dist/repository-feedback.d.ts.map +1 -1
  29. package/dist/repository-https.d.ts +1 -1
  30. package/dist/repository-https.d.ts.map +1 -1
  31. package/dist/repository-issue-watcher.d.ts +30 -25
  32. package/dist/repository-issue-watcher.d.ts.map +1 -1
  33. package/dist/repository-source-config.d.ts +29 -44
  34. package/dist/repository-source-config.d.ts.map +1 -1
  35. package/dist/subprocess-env.d.ts +1 -1
  36. package/dist/subprocess-env.d.ts.map +1 -1
  37. package/dist/tool-arguments.d.ts +3 -3
  38. package/dist/tool-arguments.d.ts.map +1 -1
  39. package/dist/turn-semantics.d.ts.map +1 -1
  40. package/dist/types.d.ts +15 -7
  41. package/dist/types.d.ts.map +1 -1
  42. package/package.json +6 -6
  43. package/src/core-capabilities.ts +2 -0
  44. package/src/define-process.ts +83 -0
  45. package/src/extension-api.ts +23 -5
  46. package/src/external-source-poll.ts +65 -11
  47. package/src/flow.ts +448 -31
  48. package/src/index.ts +38 -2
  49. package/src/integration-http.ts +3 -3
  50. package/src/json-data.ts +1 -1
  51. package/src/mapped-turn.ts +386 -0
  52. package/src/repository-feedback.ts +48 -20
  53. package/src/repository-https.ts +1 -1
  54. package/src/repository-issue-watcher.ts +48 -21
  55. package/src/repository-source-config.ts +66 -23
  56. package/src/subprocess-env.ts +1 -1
  57. package/src/tool-arguments.ts +3 -3
  58. package/src/turn-semantics.ts +76 -1
  59. package/src/types.ts +15 -7
  60. package/dist/chunk-I7U6HCLN.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/capabilities.ts","../src/codecs.ts","../src/commit-message.ts","../src/core-capabilities.ts","../src/define-process.ts","../src/event-bus.ts","../src/extension-api.ts","../src/external-action-source.ts","../src/external-source-poll.ts","../src/flow.ts","../src/fs-utils.ts","../src/process-graph.ts","../src/graph-fragments.ts","../src/host-capabilities.ts","../src/integration-http.ts","../src/json-data.ts","../src/leaf-outcomes.ts","../src/model-provider.ts","../src/process-flow-view.ts","../src/process-launcher-builder.ts","../src/process-watcher-builder.ts","../src/tool-arguments.ts","../src/process-watcher-source.ts","../src/project-binding.ts","../src/repository-feedback.ts","../src/subprocess-env.ts","../src/repository-git-env.ts","../src/repository-http.ts","../src/repository-https.ts","../src/repository-issue-watcher.ts","../src/repository-reconciliation.ts","../src/repository-source-config.ts","../src/turn-semantics.ts","../src/tool-renderers.ts","../src/server-process-builder.ts","../src/state-helpers.ts","../src/ui-process-builder.ts","../src/worker-process-builder.ts"],"sourcesContent":["/** @internal */\nexport type CapabilityCardinality = \"single\" | \"multi\";\n\n/** @public */\nexport interface CapabilityToken<_TValue> {\n\t/** @internal */\n\treadonly id: string;\n\t/** @internal */\n\treadonly cardinality: CapabilityCardinality;\n}\n\n/** @public */\nexport function createCapabilityToken<TValue>(\n\tid: string,\n\toptions: {\n\t\t/** @internal */\n\t\tcardinality?: CapabilityCardinality;\n\t} = {},\n): CapabilityToken<TValue> {\n\treturn {\n\t\tid,\n\t\tcardinality: options.cardinality ?? \"single\",\n\t};\n}\n","import type { Codec } from \"./extension-api.js\";\n\n/** @internal */\nexport const emptyParamsCodec: Codec<Record<string, never>> = {\n\tparse() {\n\t\treturn {};\n\t},\n\tserialize(value) {\n\t\treturn value;\n\t},\n};\n","/** @internal */\nexport const COMMIT_MESSAGE_PROJECT_METADATA_KEY = \"leitwerk.commitMessage\";\n\n/** @internal */\nexport const BUILT_IN_COMMIT_MESSAGE_RULES =\n\t\"Write a concise imperative subject that summarizes the accepted plan. Add a body only when it provides useful context.\";\n\n/** @internal */\nexport interface CommitMessageProjectMetadata {\n\t/** @internal */\n\ttemplateId: string | null;\n\t/** @internal */\n\trules: string;\n}\n","import type {\n\tActor,\n\tInputKind,\n\tInputSource,\n\tLaunchModelConfigInput,\n\tProcessEvent,\n\tProcessInputTarget,\n\tProcessInstance,\n\tProcessLifecycleStatus,\n\tProcessProject,\n\tTurnId,\n\tWorkerErrorClass,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tKnownDurableWsFrameType,\n\tKnownEphemeralWsFrameType,\n\tLauncherModelConfigPreview,\n\tLauncherModelConfigSchema,\n\tProcessActionModelPreview,\n\tWsPayloadByType,\n} from \"@leitwerk-dev/protocol\";\nimport { createCapabilityToken } from \"./capabilities.js\";\nimport type {\n\tExternalActionSource,\n\tFormDefinition,\n\tLauncherContext,\n\tLaunchPreparationCheck,\n\tProcessLaunchConfig,\n\tProcessLauncherService,\n\tProcessLaunchPlan,\n\tProcessWatcherPresentation,\n\tProcessWatcherSource,\n\tRepositoryCredentialRegistrar,\n} from \"./extension-api.js\";\n\n/** @internal */\nexport interface ProcessCreateInputLike {\n\t/** @internal */\n\tprocessId?: ProcessInstance[\"processId\"];\n\t/** @internal */\n\tselectedTurnId?: ProcessInstance[\"selectedTurnId\"];\n\t/** @internal */\n\tlifecycleStatus?: ProcessInstance[\"lifecycleStatus\"];\n\t/** @internal */\n\ttitle?: string | null;\n\t/** @internal */\n\texternalId?: string | null;\n\t/** @internal */\n\texternalUrl?: string | null;\n\t/** @internal */\n\tmetadata?: Record<string, unknown> | null;\n\t/** @internal */\n\tdefaultModelProfileId?: string | null;\n\t/** @internal */\n\tturnConfigsJson?: string | null;\n\t/** @internal */\n\tselectedTurnModelProfileId?: string | null;\n\t/** @internal */\n\tparamsJson?: string | null;\n\t/** @internal */\n\tstateJson?: string | null;\n}\n\n/** @public */\nexport interface ProcessRepoLike {\n\t/** @internal */\n\tcreate(input: ProcessCreateInputLike): ProcessInstance;\n\t/** @internal */\n\tgetById(id: string): ProcessInstance | null;\n\t/** @public */\n\tlistAll(): ProcessInstance[];\n\t/** Startup-only compatibility migrations may rewrite persisted process position and state. @public */\n\tupdate(\n\t\tid: string,\n\t\tinput: {\n\t\t\t/** @public */\n\t\t\tselectedTurnId?: TurnId | null;\n\t\t\t/** @public */\n\t\t\tcurrentExecution?: ProcessInstance[\"currentExecution\"];\n\t\t\t/** @public */\n\t\t\tstateJson?: string | null;\n\t\t},\n\t): ProcessInstance | null;\n}\n\n/** @public */\nexport interface ProcessProjectRepoLike {\n\t/** Server-provided project mutation service. Implementations should emit project.updated after committed writes. @internal */\n\tcreate(input: {\n\t\t/** @internal */\n\t\tinstanceId: string;\n\t\t/** @internal */\n\t\tkey: string;\n\t\t/** @internal */\n\t\trepoLocator: string;\n\t\t/** @internal */\n\t\tbaseBranch: string;\n\t\t/** @internal */\n\t\tworkBranch?: string | null;\n\t\t/** @internal */\n\t\texternalId?: string | null;\n\t\t/** @internal */\n\t\texternalUrl?: string | null;\n\t\t/** @internal */\n\t\tmetadata?: Record<string, unknown> | null;\n\t\t/** @internal */\n\t\tpipelineStatus?: string | null;\n\t}): ProcessProject;\n\t/** @internal */\n\tgetByInstanceAndKey(instanceId: string, key: string): ProcessProject | null;\n\t/** @public */\n\tupdate(\n\t\tid: string,\n\t\tinput: {\n\t\t\t/** @internal */\n\t\t\tbaseBranch?: string;\n\t\t\t/** @internal */\n\t\t\tworkBranch?: string | null;\n\t\t\t/** @internal */\n\t\t\texternalId?: string | null;\n\t\t\t/** @internal */\n\t\t\texternalUrl?: string | null;\n\t\t\t/** @public */\n\t\t\tmetadata?: Record<string, unknown> | null;\n\t\t\t/** @internal */\n\t\t\tpipelineStatus?: string | null;\n\t\t},\n\t): ProcessProject | null;\n\t/** @internal */\n\tlistByInstance(instanceId: string): ProcessProject[];\n}\n\n/** @public */\nexport interface ProcessEventRepoLike {\n\t/** @public */\n\tcreate(input: {\n\t\t/** @public */\n\t\tinstanceId: string;\n\t\t/** @public */\n\t\teventType: string;\n\t\t/** @public */\n\t\tdata?: Record<string, unknown>;\n\t}): unknown;\n\t/** @internal */\n\tlistByInstance(instanceId: string, limit?: number): ProcessEvent[];\n}\n\n/** @internal */\nexport interface BroadcasterLike {\n\t/** @internal */\n\tsendDurable<T extends KnownDurableWsFrameType>(\n\t\ttype: T,\n\t\tpayload: WsPayloadByType[T],\n\t\tinstanceId?: string,\n\t): void;\n\t/** @internal */\n\tsendEphemeral?<T extends KnownEphemeralWsFrameType>(\n\t\ttype: T,\n\t\tpayload: WsPayloadByType[T],\n\t\tinstanceId?: string,\n\t): void;\n}\n\n/** @internal */\nexport type LaunchModelConfigInputLike = LaunchModelConfigInput;\n/** @internal */\nexport type LauncherModelConfigSchemaLike = LauncherModelConfigSchema;\n/** @internal */\nexport type LauncherModelConfigPreviewLike = LauncherModelConfigPreview;\n\n/** @internal */\nexport interface LauncherModelConfigServiceLike {\n\t/** @internal */\n\tgetSchema(launcherId: string): Promise<LauncherModelConfigSchemaLike | null>;\n\t/** @internal */\n\tpreview(\n\t\tlauncherId: string,\n\t\tlauncherInput: Record<string, unknown>,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tmodelConfig?: LaunchModelConfigInputLike;\n\t\t},\n\t): Promise<LauncherModelConfigPreviewLike | null>;\n}\n\n/** Stable, machine-readable codes returned while preparing a launch. @internal */\nexport type LaunchPlanPreparationIssueCode =\n\t| \"process_id_mismatch\"\n\t| \"invalid_turn_configs_json\"\n\t| \"unknown_model_profile\"\n\t| \"model_profile_not_allowed\"\n\t| \"unknown_llm_turn\"\n\t| \"selected_turn_model_requires_selected_turn\"\n\t| \"selected_turn_model_requires_llm_turn\"\n\t| \"model_required\";\n\n/** Complete, presentation-safe diagnostic returned while preparing a launch. @internal */\nexport interface LaunchPlanPreparationIssue {\n\t/** @internal */\n\treadonly code: LaunchPlanPreparationIssueCode;\n\t/** @internal */\n\treadonly message: string;\n}\n\n/** @internal */\nexport type LaunchPlanPreparationResultLike =\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: true;\n\t\t\t/** @internal */\n\t\t\tlaunchPlan: ProcessLaunchPlan;\n\t\t\t/** @internal */\n\t\t\tmodelConfig: LaunchModelConfigInputLike;\n\t\t\t/** @internal */\n\t\t\twarnings: readonly LaunchPlanPreparationIssue[];\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: false;\n\t\t\t/** Normalized durable plan retained when a scheduled launch is blocked. @internal */\n\t\t\tlaunchPlan: ProcessLaunchPlan;\n\t\t\t/** @internal */\n\t\t\tmodelConfig: LaunchModelConfigInputLike;\n\t\t\t/** @internal */\n\t\t\terrors: readonly LaunchPlanPreparationIssue[];\n\t };\n\n/** @internal */\nexport interface ProcessLaunchPlanServiceLike {\n\t/** @internal */\n\tprepare(\n\t\tlaunchPlan: ProcessLaunchPlan,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tmodelConfig?: LaunchModelConfigInputLike;\n\t\t\t/** @internal */\n\t\t\treplaceModelConfig?: boolean;\n\t\t\t/** @internal */\n\t\t\tinvalidModelConfig?: \"reject\" | \"omit\";\n\t\t},\n\t): Promise<LaunchPlanPreparationResultLike>;\n}\n\n/** @internal */\nexport interface HandoffDedupKeyRecordLike {\n\t/** @internal */\n\tkey: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\tmetadata: Record<string, unknown>;\n}\n\n/** @internal */\nexport interface HandoffDedupKeyServiceLike {\n\t/** @internal */\n\tgetByKey(key: string): HandoffDedupKeyRecordLike | null;\n}\n\n/** @internal */\nexport interface WorkerSupervisorLike {\n\t/** @internal */\n\tspawnWorker(instanceId: string): Promise<unknown>;\n\t/** @internal */\n\tgetWorker(instanceId: string): unknown | undefined;\n}\n\n/** @public */\nexport interface ProcessEngineResultLike {\n\t/** @public */\n\tok: boolean;\n\t/** @internal */\n\tcode?: string;\n\t/** @internal */\n\tmessage?: string;\n\t/** @internal */\n\tprocess?: ProcessInstance | null;\n\t/** @internal */\n\tstage?: \"pre_commit\" | \"post_commit\";\n\t/** @internal */\n\tdata?: unknown;\n}\n\n/** @internal */\nexport interface DeferredProcessActivationExpected {\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tlifecycleStatus: ProcessLifecycleStatus;\n\t/** @internal */\n\tselectedTurnId: TurnId | null;\n\t/** @internal */\n\ttitle: string | null;\n\t/** @internal */\n\tparamsJson: string | null;\n\t/** @internal */\n\tprojectId: string;\n\t/** @internal */\n\tprojectKey: string;\n\t/** @internal */\n\trepoLocator: string;\n\t/** @internal */\n\tbaseBranch: string;\n\t/** @internal */\n\tworkBranch: string | null;\n}\n\n/** @internal */\nexport interface DeferredProcessActivationSnapshot extends DeferredProcessActivationExpected {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tprocessMetadata: Record<string, unknown> | null;\n\t/** @internal */\n\tprojectMetadata: Record<string, unknown> | null;\n}\n\n/** @internal */\nexport interface DeferredProcessActivationSnapshotQuery {\n\t/** @internal */\n\tprojectKey: string;\n\t/** @internal */\n\tinstanceId?: string;\n\t/** @internal */\n\tprocessId?: string;\n}\n\n/** @internal */\nexport type DeferredProcessActivationSnapshotResult =\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"ready\";\n\t\t\t/** @internal */\n\t\t\tsnapshots: DeferredProcessActivationSnapshot[];\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"process_not_found\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"project_not_found\";\n\t };\n\n/** @internal */\nexport interface DeferredProcessActivationEvent {\n\t/** @internal */\n\teventType: string;\n\t/** @internal */\n\tdata?: Record<string, unknown>;\n\t/** @internal */\n\tlevel: \"info\" | \"warn\" | \"error\";\n\t/** @internal */\n\tmessage: string;\n}\n\n/** @internal */\nexport interface PreparedDeferredProcessActivation {\n\t/** @internal */\n\texpected: DeferredProcessActivationExpected;\n\t/** @internal */\n\tworkBranch: string;\n\t/** @internal */\n\tparamsJson: string;\n\t/** @internal */\n\tprojectMetadata: Record<string, unknown> | null;\n\t/** @internal */\n\tselectedTurnId: TurnId;\n\t/** @internal */\n\tevent: DeferredProcessActivationEvent;\n\t/** @internal */\n\tactor?: Actor;\n}\n\n/** @internal */\nexport type DeferredProcessActivationOutcome =\n\t| \"activated\"\n\t| \"already_activated\"\n\t| \"stale\"\n\t| \"not_applicable\"\n\t| \"project_not_found\"\n\t| \"invalid_selected_turn\";\n\n/** @internal */\nexport interface DeferredProcessActivationFailure {\n\t/** @internal */\n\texpected: DeferredProcessActivationExpected;\n\t/** @internal */\n\terrorClass: WorkerErrorClass;\n\t/** @internal */\n\tevent: DeferredProcessActivationEvent;\n}\n\n/** @internal */\nexport type ProcessActionExecutionSource = \"ui\" | \"external\" | \"scheduled\";\n/** @internal */\nexport type ProcessActionExecutionOrigin = \"web_ui\" | \"external_interface\" | \"scheduled\";\n\n/** @internal */\nexport interface ProcessActionSummaryLike {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription?: string | null;\n\t/** @internal */\n\tform?: FormDefinition;\n}\n\n/** @internal */\nexport type ActionExecutionFailureStageLike = \"pre_commit\" | \"post_commit\";\n\n/** @public */\nexport type ActionExecutionResultLike =\n\t| {\n\t\t\t/** @public */\n\t\t\tok: true;\n\t\t\t/** @internal */\n\t\t\tprocess: ProcessInstance | null;\n\t\t\t/** @internal */\n\t\t\tdata?: Record<string, unknown>;\n\t\t\t/** @internal */\n\t\t\terror?: undefined;\n\t\t\t/** @internal */\n\t\t\tcode?: undefined;\n\t\t\t/** @internal */\n\t\t\tstage?: undefined;\n\t }\n\t| {\n\t\t\t/** @public */\n\t\t\tok: false;\n\t\t\t/** @internal */\n\t\t\tstage: \"pre_commit\";\n\t\t\t/** @internal */\n\t\t\terror: string;\n\t\t\t/** @internal */\n\t\t\tcode?: string;\n\t\t\t/** @internal */\n\t\t\tprocess?: undefined;\n\t\t\t/** @internal */\n\t\t\tdata?: undefined;\n\t }\n\t| {\n\t\t\t/** @public */\n\t\t\tok: false;\n\t\t\t/** @internal */\n\t\t\tstage: \"post_commit\";\n\t\t\t/** @internal */\n\t\t\tprocess: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\terror: string;\n\t\t\t/** @internal */\n\t\t\tcode?: string;\n\t\t\t/** @internal */\n\t\t\tdata?: Record<string, unknown>;\n\t };\n\n/** @internal */\nexport interface ProcessActionServiceLike {\n\t/** @internal */\n\tlistVisibleActions(instanceId: string): readonly ProcessActionSummaryLike[];\n\t/** @internal */\n\texecuteAction(\n\t\tinstanceId: string,\n\t\tactionId: string,\n\t\tinput: Record<string, unknown>,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tsource?: ProcessActionExecutionSource;\n\t\t\t/** @internal */\n\t\t\torigin?: ProcessActionExecutionOrigin;\n\t\t\t/** @internal */\n\t\t\tnextTurnModelProfileId?: string | null;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ActionExecutionResultLike>;\n}\n\n/** @public */\nexport interface ExternalObservationInput {\n\t/** @public */\n\tinstanceId: string;\n\t/** @public */\n\tarmingId: string;\n\t/** @public */\n\tgeneration: string;\n\t/** @public */\n\tobservation?: {\n\t\t/** @public */\n\t\tsummary: string;\n\t\t/** @internal */\n\t\tlinks?: import(\"@leitwerk-dev/domain\").TurnProgressLink[];\n\t\t/** @public */\n\t\tobservedAt: string;\n\t\t/** @public */\n\t\tsubject: string;\n\t\t/** @public */\n\t\trevision: string;\n\t};\n\t/** @public */\n\trefreshError?: string;\n}\n\n/** @public */\nexport interface ExternalSourceArmingLike {\n\t/** Process-local arming id. Durable arming identity is { instanceId, id }. @public */\n\tid: string;\n\t/** @public */\n\tinstanceId: string;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\texternalActionId: string;\n\t/** @internal */\n\tsource: ExternalActionSource;\n\t/** @public */\n\tresolved: unknown;\n\t/** Opaque identity of this resolved subscription. @public */\n\tgeneration?: string;\n}\n\n/** @public */\nexport interface ExternalSourceFireInput {\n\t/** @public */\n\tinstanceId: string;\n\t/** @public */\n\tarmingId: string;\n\t/** Reject a superseded subscription instead of queuing its event for a later turn. @internal */\n\tgeneration?: string;\n\t/** @internal */\n\tinput?: Record<string, unknown>;\n\t/** @public */\n\tevent?: Record<string, unknown>;\n\t/** @public */\n\tmergeKey?: string | null;\n}\n\n/** @public */\nexport interface ExternalSourceServiceLike {\n\t/** @public */\n\tlistArmed(kind: string): readonly ExternalSourceArmingLike[];\n\t/** @public */\n\tfire(input: ExternalSourceFireInput): Promise<ActionExecutionResultLike>;\n\t/** Records facts without firing an action or changing lifecycle state. @public */\n\tobserve?(input: ExternalObservationInput): Promise<ActionExecutionResultLike>;\n}\n\n/** @internal */\nexport interface LauncherRecentValuesServiceLike {\n\t/** @internal */\n\tlist(launcherId: string): Record<string, readonly string[]>;\n\t/** @internal */\n\trecord(launcherId: string, launcherInput: Record<string, unknown>): void;\n}\n\n/** @internal */\nexport interface QueuedProcessInputLike {\n\t/** @internal */\n\tsource: InputSource;\n\t/** @internal */\n\tkind: InputKind;\n\t/** @internal */\n\tbodyMarkdown: string;\n\t/** @internal */\n\ttarget?: ProcessInputTarget | null;\n\t/** Stable principal that queued this input. Defaults to SYSTEM_ACTOR at persist time. @internal */\n\tactor?: Actor;\n}\n\n/** @public */\nexport interface ProcessEngineLike {\n\t/** @internal */\n\tgetDeferredProcessActivationSnapshots(\n\t\tquery: DeferredProcessActivationSnapshotQuery,\n\t): DeferredProcessActivationSnapshotResult;\n\t/** @internal */\n\tactivateDeferredProcess(\n\t\tinstanceId: string,\n\t\tprepared: PreparedDeferredProcessActivation,\n\t): Promise<\n\t\tProcessEngineResultLike & {\n\t\t\t/** @internal */\n\t\t\tdata?: {\n\t\t\t\t/** @internal */\n\t\t\t\toutcome: DeferredProcessActivationOutcome;\n\t\t\t};\n\t\t}\n\t>;\n\t/** @internal */\n\tparkDeferredProcessActivationFailure(\n\t\tinstanceId: string,\n\t\tfailure: DeferredProcessActivationFailure,\n\t): Promise<\n\t\tProcessEngineResultLike & {\n\t\t\t/** @internal */\n\t\t\tdata?: {\n\t\t\t\t/** @internal */\n\t\t\t\toutcome: \"parked\" | \"stale\" | \"not_applicable\" | \"project_not_found\";\n\t\t\t};\n\t\t}\n\t>;\n\t/** @internal */\n\tstartProcess(instanceId: string, startTurnId: TurnId): Promise<ProcessEngineResultLike>;\n\t/** @public */\n\tabortProcess(\n\t\tinstanceId: string,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n\t/** Retries the current failed startup or accepted turn; startup retries consume no attempt. @public */\n\tretryProcess(\n\t\tinstanceId: string,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tnextTurnModelProfileId?: string | null;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n\t/** @internal */\n\tcontinueFailedTurn(\n\t\tinstanceId: string,\n\t\tturnRecordId: string,\n\t\toptions?: {\n\t\t\t/** @internal */\n\t\t\tprompt?: string | null;\n\t\t\t/** @internal */\n\t\t\tnextTurnModelProfileId?: string | null;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n\t/** @internal */\n\tqueueInputs(\n\t\tinstanceId: string,\n\t\tinputs: readonly QueuedProcessInputLike[],\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tdispatchErrorMessage?: string;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n}\n\n/** @internal */\nexport interface ComponentConfigLike {\n\t/** @internal */\n\trepo: string;\n\t/** @internal */\n\tdefault_branch: string;\n}\n\n/** @public */\nexport interface RegisteredProcessWatcherLike<TConfig = unknown, TEvent = unknown> {\n\t/** @public */\n\treadonly processId: string;\n\t/** @internal */\n\treadonly processDisplayName: string;\n\t/** @public */\n\treadonly watcherId: string;\n\t/** @internal */\n\treadonly watcherLabel: string;\n\t/** @internal */\n\treadonly watcherDescription: string;\n\t/** @internal */\n\treadonly sourceId: string;\n\t/** @internal */\n\treadonly sourceLabel: string;\n\t/** @public */\n\treadonly enabled: boolean;\n\t/** @internal */\n\treadonly configPath: string;\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly presentation: ProcessWatcherPresentation;\n\t/** @internal */\n\treadonly launchModelConfig: LaunchModelConfigInputLike;\n\t/** @internal */\n\tresolveLaunch(event: TEvent, ctx?: LauncherContext): Promise<ProcessLaunchPlan | null>;\n\t/** @internal */\n\tresolveLaunchAttempt(\n\t\tevent: TEvent,\n\t\tctx?: LauncherContext,\n\t): Promise<{\n\t\t/** @internal */\n\t\tlaunchConfig: ProcessLaunchConfig;\n\t\t/** @internal */\n\t\tlaunchPlan: ProcessLaunchPlan;\n\t\t/** @internal */\n\t\tpreparationChecks: readonly LaunchPreparationCheck[];\n\t} | null>;\n}\n\n/** @public */\nexport interface WatcherLaunchResultLike extends ProgrammaticLaunchResultLike {}\n\n/** @internal */\nexport interface ProgrammaticLaunchRequestLike {\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tlauncherInput: Record<string, unknown>;\n\t/** @internal */\n\ttitle?: string | null;\n\t/** @internal */\n\tmodelConfig?: LaunchModelConfigInputLike;\n\t/** @internal */\n\tskillIds?: readonly string[];\n\t/** Trusted, non-secret process metadata merged after launcher resolution. @internal */\n\tprocessMetadata?: Record<string, unknown>;\n}\n\n/** @public */\nexport interface ProgrammaticLaunchResultLike {\n\t/** @public */\n\tlaunchRunId: string;\n\t/** @public */\n\tprocess: ProcessInstance | null;\n\t/** @public */\n\terror: string | null;\n}\n\n/** @public */\nexport interface LaunchRunServiceLike {\n\t/** @internal */\n\tstartProgrammatic(\n\t\trequest: ProgrammaticLaunchRequestLike,\n\t\topts: {\n\t\t\t/** @internal */\n\t\t\tidempotencyKey: string;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProgrammaticLaunchResultLike>;\n\t/** @public */\n\tstartWatcher<TConfig, TEvent>(\n\t\twatcher: RegisteredProcessWatcherLike<TConfig, TEvent>,\n\t\tevent: TEvent,\n\t\topts: {\n\t\t\t/** @public */\n\t\t\tidempotencyKey: string;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<WatcherLaunchResultLike>;\n}\n\n/** @public */\nexport interface ProcessWatcherServiceLike {\n\t/** @internal */\n\tlistAll(): readonly RegisteredProcessWatcherLike[];\n\t/** @public */\n\tlistBySource<TConfig, TEvent>(\n\t\tsource: ProcessWatcherSource<TConfig, TEvent>,\n\t): readonly RegisteredProcessWatcherLike<TConfig, TEvent>[];\n}\n\n/** @public */\nexport interface PollResultLike {\n\t/** @internal */\n\treadonly errors: readonly string[];\n}\n\n/** @public */\nexport interface PollingServiceLike {\n\t/** @public */\n\tcreate<T extends PollResultLike>(options: {\n\t\t/** @public */\n\t\tid: string;\n\t\t/** @public */\n\t\tpollOnce(): Promise<T>;\n\t\t/** @public */\n\t\tisEnabled(): boolean;\n\t\t/** @public */\n\t\tpollInterval(): string;\n\t\t/** @public */\n\t\tdefaultIntervalMs?: number;\n\t}): {\n\t\t/** @public */\n\t\tpoll(): Promise<T>;\n\t};\n}\n\n/** @internal */\nexport interface ProcessQuestionServiceLike {\n\t/** @internal */\n\tlistOpen(instanceId?: string): readonly import(\"@leitwerk-dev/domain\").ProcessQuestionRequest[];\n\t/** @internal */\n\tsubmitAnswers(\n\t\tinstanceId: string,\n\t\trequestId: string,\n\t\tdraft: readonly import(\"@leitwerk-dev/domain\").QuestionAnswerDraft[],\n\t\tactor: Actor,\n\t): Promise<\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tok: true;\n\t\t\t\t/** @internal */\n\t\t\t\trequest: import(\"@leitwerk-dev/domain\").ProcessQuestionRequest;\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tok: false;\n\t\t\t\t/** @internal */\n\t\t\t\tcode: \"not_found\" | \"not_current\" | \"invalid\";\n\t\t\t\t/** @internal */\n\t\t\t\tmessage: string;\n\t\t\t\t/** @internal */\n\t\t\t\trequest?: import(\"@leitwerk-dev/domain\").ProcessQuestionRequest;\n\t\t }\n\t>;\n}\n\n/** @public */\nexport interface CoreServerSetupDeps {\n\t/** @internal */\n\tserverBaseUrl: string;\n\t/** @internal */\n\tprocessWorkspacesDir?: string;\n\t/** @internal */\n\tcomponents: Record<string, ComponentConfigLike>;\n\t/** Typed by consuming extensions via watcher-utils ExternalWriteLogRepoLike. @public */\n\texternalWrites: unknown;\n\t/** @public */\n\tprocesses: ProcessRepoLike;\n\t/** @public */\n\tprojects: ProcessProjectRepoLike;\n\t/** @public */\n\tevents: ProcessEventRepoLike;\n\t/** @internal */\n\tbroadcaster: BroadcasterLike;\n\t/** @public */\n\tcommands: ProcessEngineLike;\n\t/** @internal */\n\tprocessActions: ProcessActionServiceLike;\n\t/** @public */\n\texternalSources: ExternalSourceServiceLike;\n\t/** @internal */\n\tgetSupervisor: () => WorkerSupervisorLike | undefined;\n\t/** @internal */\n\tlauncherService: ProcessLauncherService;\n\t/** @internal */\n\tlauncherRecentValues: LauncherRecentValuesServiceLike;\n\t/** @internal */\n\tlauncherModelConfigs: LauncherModelConfigServiceLike;\n\t/** @internal */\n\tlaunchPlans: ProcessLaunchPlanServiceLike;\n\t/** @internal */\n\thandoffDedupKeys?: HandoffDedupKeyServiceLike;\n\t/** @public */\n\tprocessWatchers?: ProcessWatcherServiceLike;\n\t/** @public */\n\tlaunchRuns: LaunchRunServiceLike;\n\t/** @public */\n\tpolling: PollingServiceLike;\n\t/** @internal */\n\tprocessModelSelection?: ProcessModelSelectionServiceLike;\n\t/** Durable active-turn questions for trusted operator-channel extensions. @internal */\n\tprocessQuestions?: ProcessQuestionServiceLike;\n\t/** Registration boundary for secret-backed repository credential extensions. @internal */\n\trepositoryCredentials: RepositoryCredentialRegistrar;\n\t/** Server-owned managed result images, available to trusted delivery extensions. @internal */\n\tresultImages?: {\n\t\t/** @internal */\n\t\tget(instanceId: string, turnRecordId: string, imageId: string): Promise<Uint8Array | null>;\n\t};\n}\n\n/** @internal */\nexport type ProcessActionModelPreviewLike = ProcessActionModelPreview;\n\n/** @internal */\nexport type ProcessModelSelectionPreviewFailureCode =\n\t| \"process_not_found\"\n\t| \"instance_tree_unavailable\";\n\n/** @internal */\nexport type ProcessModelSelectionPreviewResultLike =\n\t| ProcessActionModelPreviewLike\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"operational_failure\";\n\t\t\t/** @internal */\n\t\t\tcode: ProcessModelSelectionPreviewFailureCode;\n\t };\n\n/** @internal */\nexport interface ModelProfileOptionSummaryLike {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\tavailability: \"available\" | \"unavailable\" | \"stale\";\n}\n\n/** @internal */\nexport interface ProcessModelSelectionServiceLike {\n\t/** @internal */\n\tlistAvailableProfiles(instanceId: string): readonly ModelProfileOptionSummaryLike[] | null;\n\t/** @internal */\n\tpreview(\n\t\tinstanceId: string,\n\t\tactionId: string,\n\t\tinput: Record<string, unknown>,\n\t): Promise<ProcessModelSelectionPreviewResultLike>;\n}\n\n/** @public */\nexport const coreHostCapabilities = {\n\t/** @public */\n\tserverSetup: createCapabilityToken<CoreServerSetupDeps>(\"core:serverSetup\"),\n\t/** @internal */\n\tprocessModelSelection: createCapabilityToken<ProcessModelSelectionServiceLike>(\n\t\t\"core:processModelSelection\",\n\t),\n} as const;\n","import {\n\tassertValidProcessProductName,\n\ttrimString as normalizeEffectString,\n\tnormalizeStringArray as normalizeEffectStringArray,\n\ttype ProcessInstance,\n\ttype ProcessSemanticEntryRefKey,\n\ttype ProcessTurnStartSelection,\n\ttype ProcessTurnTerminalLifecycleStatus,\n\ttype ProcessTurnTransition,\n\ttype TurnId,\n\ttype TurnProgressReport,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tExtensionProcessDefinition,\n\tExternalActionSource,\n\tExternalSourceEffect,\n\tExternalSourceResolveContext,\n\tFormDefinition,\n\tProcessTurnBinding,\n\tProcessTurnOutcomeEvent,\n\tServerProcessContext,\n\tServerTransitionRequest,\n\tWorkerCompleteInput,\n\tWorkerProcessContext,\n} from \"./extension-api.js\";\nimport {\n\tgetProcessTurnTransitions,\n\tmarkDefinedProcess,\n\tsetProcessTurnTransitions,\n} from \"./process-definition-internals.js\";\nimport type { ServerExtensionEventMap } from \"./server-events.js\";\nimport type {\n\tHumanTurnActionView,\n\tHumanTurnExternalActionView,\n\tHumanTurnExternalTrigger,\n\tHumanTurnNotesField,\n\tOutcomeToolParameterSpec,\n\tPiBuiltInToolName,\n\tProcessActionPreviewDefinition,\n\tProcessActionSchedulingDefinition,\n\tTurnAcceptanceState,\n\tTurnBranchType,\n\tTurnCompletionMode,\n\tTurnContextMode,\n\tTurnResultMarkdownBehavior,\n} from \"./types.js\";\n\n/** @internal */\ntype ProcessEventName = keyof ServerExtensionEventMap & string;\n\n/** @internal */\ntype ProcessEmittedEvent = {\n\t/** @internal */\n\ttype: ProcessEventName;\n\t/** @internal */\n\tdata: unknown;\n};\n\n/** @public */\ntype ProcessQueuedInput = Parameters<ServerProcessContext[\"queueInput\"]>[0];\n\n/** @public */\ntype MaybePromise<T> = T | Promise<T>;\n\n/** @public */\ntype StaticRouteTarget = {\n\t/** @public */\n\tto?: TurnId;\n\t/** @internal */\n\tcomplete?: boolean;\n\t/** @public */\n\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n};\n\ntype NormalizedRouteTarget = {\n\tnextTurnId?: TurnId;\n\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n};\n\ntype NormalizedActionRoute = NormalizedRouteTarget & {\n\ttrigger: string;\n};\n\n/** @public */\nexport interface ProcessRuntimeTurnContext<TParams = unknown, TState = unknown>\n\textends WorkerProcessContext<TParams, TState> {}\n\n/** @internal */\nexport interface LlmTurnPreparationContext<TParams = unknown, TState = unknown>\n\textends ProcessRuntimeTurnContext<TParams, TState> {\n\t/** @internal */\n\tcallIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;\n\t/** @internal */\n\treportProgress(report: TurnProgressReport): void;\n}\n\n/** @public */\nexport interface ProcessServerRuntimeContext<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly process: ServerProcessContext<TParams, TState>[\"process\"];\n\t/** @internal */\n\treadonly projects: ServerProcessContext<TParams, TState>[\"projects\"];\n\t/** @internal */\n\treadonly params: TParams;\n\t/** @public */\n\treadonly state: TState;\n\t/** @internal */\n\treadSemanticTurnResultMarkdown(ref: ProcessSemanticEntryRefKey): string | null;\n\t/** @internal */\n\treadProductTurnResultMarkdown(productName: string): string | null;\n\t/** @internal */\n\treportProgress?(report: TurnProgressReport): void;\n}\n\n/** @internal */\nexport interface ProcessBroadcastEffect {\n\t/** @internal */\n\ttype: string;\n\t/** @internal */\n\tpayload: Record<string, unknown>;\n}\n\n/** @public */\nexport type ProcessPatchEffect = Partial<\n\tPick<\n\t\tProcessInstance,\n\t\t| \"lifecycleStatus\"\n\t\t| \"planRevision\"\n\t\t| \"title\"\n\t\t| \"externalId\"\n\t\t| \"externalUrl\"\n\t\t| \"metadata\"\n\t\t| \"defaultModelProfileId\"\n\t\t| \"turnConfigsJson\"\n\t>\n>;\n\n/** @public */\nexport interface ProcessLifecycleEffects {\n\t/** @public */\n\tprocessPatch?: ProcessPatchEffect;\n\t/** @internal */\n\tbroadcasts?: readonly ProcessBroadcastEffect[];\n}\n\n/** @public */\nexport interface ProcessEffectPlan<TState = unknown> extends ProcessLifecycleEffects {\n\t/** @public */\n\tstate?: TState;\n\t/** @internal */\n\temit?: readonly ProcessEmittedEvent[];\n\t/** @public */\n\tqueueInput?: readonly ProcessQueuedInput[];\n}\n\n/** @internal */\nexport interface SavePlanResultLifecycleIntent<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tkind: \"save_plan_result\";\n\t/** @internal */\n\tsummaryParam: string;\n\t/** @internal */\n\tacceptanceCriteriaParam: string;\n\t/** @internal */\n\tplanMarkdownParam: string;\n\t/** @internal */\n\temitEventType: ProcessEventName;\n\t/** @internal */\n\tbroadcastType: string;\n\t/** @internal */\n\tstate?: ProcessOutcomeEffect<TParams, TState>;\n}\n\n/** @internal */\nexport type ProcessOutcomeLifecycleIntent<\n\tTParams = unknown,\n\tTState = unknown,\n> = SavePlanResultLifecycleIntent<TParams, TState>;\n\n/** @public */\nexport interface ProcessActionExecution<TParams = unknown, TState = unknown> {\n\t/** @public */\n\treadonly ctx: ProcessServerRuntimeContext<TParams, TState>;\n\t/** @public */\n\treadonly input: Record<string, unknown>;\n\t/** @internal */\n\treadonly turnId: TurnId;\n\t/** @internal */\n\treadonly actionId: string;\n\t/** @internal */\n\treadonly selectedBranchId?: string;\n}\n\n/** @public */\nexport interface ProcessOutcomeExecution<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly ctx: ProcessServerRuntimeContext<TParams, TState>;\n\t/** @internal */\n\treadonly event: ProcessTurnOutcomeEvent;\n\t/** @internal */\n\treadonly turnId: TurnId;\n\t/** @internal */\n\treadonly outcome: string;\n}\n\n/** @public */\nexport type ProcessActionEffect<TParams = unknown, TState = unknown> = (\n\tinput: ProcessActionExecution<TParams, TState>,\n) => MaybePromise<ProcessEffectPlan<TState> | undefined>;\n\n/** @public */\nexport type ProcessActionBranchSelector<TParams = unknown, TState = unknown> = (\n\tinput: Omit<ProcessActionExecution<TParams, TState>, \"selectedBranchId\">,\n) => MaybePromise<string>;\n\n/** @public */\nexport type ProcessOutcomeEffect<TParams = unknown, TState = unknown> = (\n\tinput: ProcessOutcomeExecution<TParams, TState>,\n) => MaybePromise<ProcessEffectPlan<TState> | undefined>;\n\n/** @internal */\nexport type ProcessOutcomeBranchSelector<TParams = unknown, TState = unknown> = (\n\tinput: ProcessOutcomeExecution<TParams, TState>,\n) => MaybePromise<string>;\n\n/** @internal */\nexport interface ProcessOutcomeBranchSpec extends StaticRouteTarget {\n\t/** @internal */\n\ttrigger?: string;\n}\n\n/** @internal */\nexport interface ProcessActionExternalTrigger {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription: string;\n}\n\n/** @internal */\nexport interface ExternalActionInputPublication {\n\t/** @internal */\n\tproductName: string;\n\t/** @internal */\n\tinputField: string;\n}\n\n/** @public */\nexport interface ProcessHumanTurnExternalActionSpec<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends StaticRouteTarget {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>;\n\t/** Arms and exposes this action only when the current process snapshot matches. @public */\n\twhen?: (ctx: ExternalSourceResolveContext<TParams, TState>) => boolean;\n\t/** @internal */\n\tlabel?: string;\n\t/** @internal */\n\tdescription?: string;\n\t/** @internal */\n\tpublishInput?: ExternalActionInputPublication;\n\t/** @public */\n\teffect?: ExternalSourceEffect<TParams, TState, TEvent, TInput>;\n}\n\n/** @public */\nexport interface ProcessActionBranchSpec extends StaticRouteTarget {\n\t/** @internal */\n\ttrigger?: string;\n}\n\n/** @public */\ntype StaticActionRouting = StaticRouteTarget & {\n\t/** @internal */\n\ttrigger?: string;\n};\n\n/** @public */\ntype BranchingActionRouting<TParams, TState> = {\n\t/** @public */\n\tbranches: Record<string, ProcessActionBranchSpec>;\n\t/** @public */\n\tchoose: ProcessActionBranchSelector<TParams, TState>;\n};\n\n/** @public */\ninterface BaseActionSpec<TParams, TState> {\n\t/** @public */\n\tlabel: string;\n\t/** @public */\n\tdescription?: string;\n\t/** @internal */\n\tform?: FormDefinition;\n\t/** @public */\n\tpreview?: ProcessActionPreviewDefinition;\n\t/** @public */\n\tschedulable?: boolean;\n\t/** @public */\n\teffect?: ProcessActionEffect<TParams, TState>;\n}\n\n/** @public */\nexport type ProcessHumanTurnActionSpec<TParams = unknown, TState = unknown> = BaseActionSpec<\n\tTParams,\n\tTState\n> & {\n\t/** @public */\n\tacceptanceState: TurnAcceptanceState;\n\t/** @internal */\n\texternalTriggers?: readonly ProcessActionExternalTrigger[];\n} & (StaticActionRouting | BranchingActionRouting<TParams, TState>);\n\n/** @public */\ninterface ProcessToolOutcomeBaseSpec<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\tparameters: Record<string, OutcomeToolParameterSpec>;\n\t/** Product published from this outcome's turn-result markdown, when this outcome is selected. @internal */\n\tpublishedProduct?: string;\n\t/** Outcome parameter whose markdown value is captured as the turn result. @internal */\n\tturnResultMarkdownParameter?: string;\n\t/** Outcome parameter containing a concise operator-facing summary. @internal */\n\tresultSummaryParameter?: string;\n\t/** @internal */\n\teffect?: ProcessOutcomeEffect<TParams, TState>;\n\t/** @internal */\n\tlifecycleIntent?: ProcessOutcomeLifecycleIntent<TParams, TState>;\n}\n\n/** @public */\nexport type ProcessToolOutcomeSpec<\n\tTParams = unknown,\n\tTState = unknown,\n> = ProcessToolOutcomeBaseSpec<TParams, TState> &\n\t(\n\t\t| StaticRouteTarget\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tbranches: Record<string, ProcessOutcomeBranchSpec>;\n\t\t\t\t/** @internal */\n\t\t\t\tchoose: ProcessOutcomeBranchSelector<TParams, TState>;\n\t\t }\n\t);\n/** @public */\nexport type HumanTurnOperatorAttention = \"required\" | \"passive\";\n\n/** @public */\nexport interface HumanTurnDefinition<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tkind: \"human\";\n\t/** @public */\n\tdescription: string;\n\t/** Named product rendered as the subject of this human review turn. @internal */\n\treviewProduct?: string;\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** Controls whether entering this turn should raise an action-required toast. @public */\n\toperatorAttention?: HumanTurnOperatorAttention;\n\t/** @internal */\n\tnotesFields?: readonly HumanTurnNotesField[];\n\t/** @internal */\n\tcommentary?: string;\n\t/** @public */\n\tactions: Record<string, ProcessHumanTurnActionSpec<TParams, TState>>;\n\t/** @internal */\n\texternalActions?: Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>;\n}\n\n/** @public */\nexport interface ProcessTurnEndSpec<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n> extends StaticRouteTarget {\n\t/** @public */\n\toutcome: TOutcome;\n\t/** @public */\n\tparams?: Record<string, unknown>;\n\t/** @public */\n\teffect?: ProcessOutcomeEffect<TParams, TState>;\n}\n\n/** @internal */\nexport type OutcomeRouteSpec<TParams = unknown, TState = unknown> = StaticRouteTarget &\n\tPartial<Pick<ProcessToolOutcomeSpec<TParams, TState>, \"description\" | \"parameters\" | \"effect\">>;\n\n/** @internal */\nexport interface OutcomeRouteOptions {\n\t/** @internal */\n\tstrict?: boolean;\n}\n\n/** @internal */\nexport type LlmModelPurpose = \"process_title_generation\";\n\n/** @public */\nexport interface LlmTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n> {\n\t/** @public */\n\tkind: \"llm\";\n\t/** @public */\n\tdescription: string;\n\t/** Code-defined model policy purpose. Purpose selections cannot be overridden per launch/action. @internal */\n\tmodelPurpose?: LlmModelPurpose;\n\t/** Built-in Pi tools active while this turn runs. @public */\n\tavailableTools: readonly PiBuiltInToolName[];\n\t/** Server-owned integration tools proxied over authenticated worker IPC. @internal */\n\tintegrationTools?: readonly string[];\n\t/** Resolve a constrained tool set from validated durable process data at turn start. @public */\n\tresolveIntegrationTools?: (params: TParams, state: TState) => readonly string[];\n\t/** Opt in to the durable, operator-facing ask_questions custom tool. @internal */\n\taskQuestions?: boolean;\n\t/** Deterministic worker preparation that must complete before Pi is prompted. @internal */\n\tprepare?(ctx: LlmTurnPreparationContext<TParams, TState>): MaybePromise<unknown>;\n\t/** @public */\n\tcompletionMode?: TurnCompletionMode;\n\t/** @public */\n\tbranchType: TurnBranchType;\n\t/** @public */\n\tcontext: TurnContextMode;\n\t/** @internal */\n\tstartFrom?: ProcessTurnStartSelection;\n\t/** @internal */\n\trestorePrimaryLeafAfterTurn?: boolean;\n\t/** @public */\n\tprompt(ctx: ProcessRuntimeTurnContext<TParams, TState>): string | Promise<string>;\n\t/** @public */\n\toutcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;\n\t/** @public */\n\tturnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;\n\t/** @public */\n\tturnResultMarkdown?: TurnResultMarkdownBehavior;\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @internal */\n\tresultSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @internal */\n\tpublishedProduct?: string;\n\t/** @internal */\n\tconsumedProducts?: readonly string[];\n\t/** @internal */\n\toptionalConsumedProducts?: readonly string[];\n\t/** @internal */\n\trequiredSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n\t/** @internal */\n\toptionalSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n}\n\n/** @public */\nexport interface AutomaticTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n> {\n\t/** @public */\n\tkind: \"automatic\";\n\t/** @public */\n\tdescription: string;\n\t/** Server-owned integration tools callable by this deterministic worker turn. @internal */\n\tintegrationTools?: readonly string[];\n\t/** External events armed while this automatic turn is selected and waiting. @public */\n\texternalActions?: Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>;\n\t/** @internal */\n\toutcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;\n\t/** @internal */\n\tturnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @public */\n\trun(\n\t\tctx: ProcessRuntimeTurnContext<TParams, TState>,\n\t): Promise<WorkerCompleteInput<TOutcome>> | WorkerCompleteInput<TOutcome>;\n}\n\n/** @internal */\nexport interface ExternalSourceTransition<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends StaticRouteTarget {\n\t/** @internal */\n\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>;\n\t/** @internal */\n\teffect?: ExternalSourceEffect<TParams, TState, TEvent, TInput>;\n}\n\n/** @public */\nexport interface ExternalTurnDefinition<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tkind: \"external\";\n\t/** @public */\n\tdescription: string;\n\t/** @internal */\n\ttransitions: readonly ExternalSourceTransition<TParams, TState>[];\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n}\n\n/** @public */\nexport type TurnDefinition<TParams = unknown, TState = unknown> =\n\t| LlmTurnDefinition<string, TParams, TState>\n\t| AutomaticTurnDefinition<string, TParams, TState>\n\t| HumanTurnDefinition<TParams, TState>\n\t| ExternalTurnDefinition<TParams, TState>;\n\n/** @public */\nexport type TurnDefinitionRecord<TParams = unknown, TState = unknown> = Record<\n\tTurnId,\n\tTurnDefinition<TParams, TState>\n>;\n\n/** @public */\nexport interface DefinedProcessInput<TParams = unknown, TState = unknown>\n\textends Omit<\n\t\tExtensionProcessDefinition<TParams, TState>,\n\t\t\"entryTurnId\" | \"alternateEntryTurnIds\" | \"turns\"\n\t> {\n\t/** Primary entry used when a launch does not select a start turn explicitly. @public */\n\tentry: TurnId;\n\t/** Additional entry turns that launchers may select explicitly. @public */\n\talternateEntries?: readonly TurnId[];\n\t/** @public */\n\tturns: TurnDefinitionRecord<TParams, TState>;\n}\n\ntype CompiledActionRouting<TParams, TState> =\n\t| {\n\t\t\tkind: \"static\";\n\t\t\troute: NormalizedActionRoute;\n\t }\n\t| {\n\t\t\tkind: \"branches\";\n\t\t\troutes: Record<string, NormalizedActionRoute>;\n\t\t\tchoose: ProcessActionBranchSelector<TParams, TState>;\n\t };\n\ntype CompiledActionUse<TParams, TState> = {\n\tturnId: TurnId;\n\tlabel?: string;\n\tform?: FormDefinition;\n\teffect?: ProcessActionEffect<TParams, TState>;\n\trouting: CompiledActionRouting<TParams, TState>;\n};\n\ninterface CompiledOutcomeHandlers<TParams, TState> {\n\teffects: ReadonlyMap<string, ProcessOutcomeEffect<TParams, TState> | undefined>;\n\troutings: ReadonlyMap<string, CompiledOutcomeRouting<TParams, TState>>;\n}\n\nfunction createProcessTurnBinding<TTurn>(\n\tdefinition: TTurn,\n\ttransitions?: readonly ProcessTurnTransition[],\n): ProcessTurnBinding<TTurn> {\n\tconst binding: ProcessTurnBinding<TTurn> = { definition };\n\tif (transitions && transitions.length > 0) {\n\t\tsetProcessTurnTransitions(binding, transitions);\n\t}\n\treturn binding;\n}\n\nfunction normalizeStaticRouteTarget(\n\tcontext: string,\n\ttarget: StaticRouteTarget,\n\tknownTurnIds?: ReadonlySet<TurnId>,\n): NormalizedRouteTarget {\n\tconst declaredTargetCount =\n\t\t(target.to !== undefined ? 1 : 0) +\n\t\t(target.complete === true ? 1 : 0) +\n\t\t(target.lifecycleStatus !== undefined ? 1 : 0);\n\tif (declaredTargetCount !== 1) {\n\t\tthrow new Error(\n\t\t\t`${context} must declare exactly one target via 'to', 'complete', or 'lifecycleStatus'`,\n\t\t);\n\t}\n\tif (target.to !== undefined) {\n\t\tif (knownTurnIds && !knownTurnIds.has(target.to)) {\n\t\t\tthrow new Error(`${context} references unknown turn '${target.to}'`);\n\t\t}\n\t\treturn { nextTurnId: target.to };\n\t}\n\tif (target.complete === true) {\n\t\treturn { lifecycleStatus: \"completed\" };\n\t}\n\treturn { lifecycleStatus: target.lifecycleStatus };\n}\n\nfunction buildOutcomeTransition<TParams, TState>(\n\tturnId: TurnId,\n\toutcome: string,\n\ttarget: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState>,\n\tknownTurnIds?: ReadonlySet<TurnId>,\n): NormalizedRouteTarget {\n\tif (\"branches\" in target) {\n\t\tthrow new Error(\n\t\t\t`Turn '${turnId}' outcome '${outcome}' must compile state routing before a static transition`,\n\t\t);\n\t}\n\tif (!hasDeclaredStaticRouteTarget(target)) {\n\t\treturn { nextTurnId: turnId };\n\t}\n\treturn normalizeStaticRouteTarget(`Turn '${turnId}' outcome '${outcome}'`, target, knownTurnIds);\n}\n\ntype CompiledOutcomeRouting<TParams, TState> = {\n\troutes: Readonly<Record<string, NormalizedActionRoute>>;\n\tchoose: ProcessOutcomeBranchSelector<TParams, TState>;\n};\n\ntype BranchRouteSpec = StaticRouteTarget & { trigger?: string };\n\nfunction compileBranchRoutes(input: {\n\tbranches: Record<string, BranchRouteSpec>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n\ttargetContext(branchId: string): string;\n\temptyBranchError: string;\n\tduplicateTriggerError(trigger: string): string;\n}): {\n\troutes: Record<string, NormalizedActionRoute>;\n\ttransitions: NormalizedActionRoute[];\n} {\n\tconst routes: Record<string, NormalizedActionRoute> = {};\n\tconst transitions: NormalizedActionRoute[] = [];\n\tconst usedTriggers = new Set<string>();\n\tfor (const [branchId, branchSpec] of Object.entries(input.branches)) {\n\t\tif (branchId.trim() === \"\") throw new Error(input.emptyBranchError);\n\t\tconst target = normalizeStaticRouteTarget(\n\t\t\tinput.targetContext(branchId),\n\t\t\tbranchSpec,\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\tconst trigger = branchSpec.trigger ?? branchId;\n\t\tif (usedTriggers.has(trigger)) throw new Error(input.duplicateTriggerError(trigger));\n\t\tusedTriggers.add(trigger);\n\t\tconst route = { ...target, trigger };\n\t\troutes[branchId] = route;\n\t\ttransitions.push(route);\n\t}\n\treturn { routes, transitions };\n}\n\nfunction resolveOutcomeRouting<TParams, TState>(input: {\n\tturnId: TurnId;\n\toutcome: string;\n\tspec: ProcessToolOutcomeSpec<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): CompiledOutcomeRouting<TParams, TState> | null {\n\tif (!(\"branches\" in input.spec)) {\n\t\treturn null;\n\t}\n\tconst entries = Object.entries(input.spec.branches);\n\tif (entries.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.turnId}' outcome '${input.outcome}' must declare at least one branch`,\n\t\t);\n\t}\n\tconst { routes } = compileBranchRoutes({\n\t\tbranches: input.spec.branches,\n\t\tknownTurnIds: input.knownTurnIds,\n\t\ttargetContext: (branchId) =>\n\t\t\t`Turn '${input.turnId}' outcome '${input.outcome}' branch '${branchId}'`,\n\t\temptyBranchError: `Turn '${input.turnId}' outcome '${input.outcome}' contains an empty branch id`,\n\t\tduplicateTriggerError: (trigger) =>\n\t\t\t`Turn '${input.turnId}' outcome '${input.outcome}' contains duplicate branch trigger '${trigger}'`,\n\t});\n\treturn { routes, choose: input.spec.choose };\n}\n\nfunction resolveActionRouting<TParams, TState>(input: {\n\tturnId: TurnId;\n\tactionId: string;\n\tspec: ProcessHumanTurnActionSpec<TParams, TState>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n}): {\n\trouting: CompiledActionRouting<TParams, TState>;\n\ttransitions: readonly NormalizedActionRoute[];\n} {\n\tif (\"branches\" in input.spec) {\n\t\tconst entries = Object.entries(input.spec.branches) as Array<[string, ProcessActionBranchSpec]>;\n\t\tif (entries.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Action '${input.actionId}' on turn '${input.turnId}' must declare at least one branch`,\n\t\t\t);\n\t\t}\n\t\tconst { routes, transitions } = compileBranchRoutes({\n\t\t\tbranches: input.spec.branches,\n\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t\ttargetContext: (branchId) =>\n\t\t\t\t`Action '${input.actionId}' branch '${branchId}' on turn '${input.turnId}'`,\n\t\t\temptyBranchError: `Action '${input.actionId}' on turn '${input.turnId}' contains an empty branch id`,\n\t\t\tduplicateTriggerError: (trigger) =>\n\t\t\t\t`Action '${input.actionId}' on turn '${input.turnId}' contains duplicate branch trigger '${trigger}'`,\n\t\t});\n\t\treturn {\n\t\t\trouting: {\n\t\t\t\tkind: \"branches\",\n\t\t\t\troutes,\n\t\t\t\tchoose: input.spec.choose,\n\t\t\t},\n\t\t\ttransitions,\n\t\t};\n\t}\n\tconst target = normalizeStaticRouteTarget(\n\t\t`Action '${input.actionId}' on turn '${input.turnId}'`,\n\t\tinput.spec,\n\t\tinput.knownTurnIds,\n\t);\n\tconst route = {\n\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\ttrigger: input.spec.trigger ?? input.actionId,\n\t};\n\treturn {\n\t\trouting: {\n\t\t\tkind: \"static\",\n\t\t\troute,\n\t\t},\n\t\ttransitions: [route],\n\t};\n}\n\n/** @internal */\nexport function getExternalSourceTransitionId(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tsource: ExternalActionSource;\n\t/** @internal */\n\tindex: number;\n}): string {\n\treturn `${input.turnId}:${input.source.kind}:${input.index}`;\n}\n\n/** @internal */\nexport function getExternalActionArmingId(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\texternalActionId: string;\n}): string {\n\treturn `${input.turnId}:${input.externalActionId}`;\n}\n\n/** @internal */\nexport function getExternalActionTransitionTrigger(input: {\n\t/** @internal */\n\texternalActionId: string;\n}): string {\n\treturn `external:${input.externalActionId}`;\n}\n\nfunction compileExternalSourceTransitions<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: ExternalTurnDefinition<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): readonly ProcessTurnTransition[] {\n\tif (input.spec.transitions.length === 0) {\n\t\tthrow new Error(`External turn '${input.turnId}' must declare at least one source transition`);\n\t}\n\treturn input.spec.transitions.map((transition, index) => {\n\t\tif (transition.source.kind.trim() === \"\") {\n\t\t\tthrow new Error(\n\t\t\t\t`External turn '${input.turnId}' source transition ${index} has an empty kind`,\n\t\t\t);\n\t\t}\n\t\tconst target = normalizeStaticRouteTarget(\n\t\t\t`External turn '${input.turnId}' source '${transition.source.kind}'`,\n\t\t\ttransition,\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\treturn {\n\t\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\t\ttrigger: getExternalSourceTransitionId({\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tsource: transition.source,\n\t\t\t\tindex,\n\t\t\t}),\n\t\t};\n\t});\n}\n\nfunction previewMatchesTransition(\n\tpreview: ProcessActionPreviewDefinition,\n\ttransition: NormalizedActionRoute,\n): boolean {\n\tif (preview.kind === \"trigger\") {\n\t\treturn transition.trigger === preview.trigger;\n\t}\n\tif (preview.kind === \"terminal\") {\n\t\treturn transition.lifecycleStatus === preview.lifecycleStatus;\n\t}\n\treturn transition.nextTurnId === preview.turnId;\n}\n\nfunction validateActionPreviewMatchesTransitions(input: {\n\tturnId: TurnId;\n\tactionId: string;\n\tpreview: ProcessActionPreviewDefinition;\n\ttransitions: readonly NormalizedActionRoute[];\n\tcontext: \"preview\" | \"scheduling\";\n}): void {\n\tconst matches = input.transitions.filter((transition) =>\n\t\tpreviewMatchesTransition(input.preview, transition),\n\t);\n\tif (matches.length === 1) {\n\t\treturn;\n\t}\n\tconst previewLabel =\n\t\tinput.preview.kind === \"trigger\"\n\t\t\t? `trigger '${input.preview.trigger}'`\n\t\t\t: input.preview.kind === \"terminal\"\n\t\t\t\t? `terminal '${input.preview.lifecycleStatus}'`\n\t\t\t\t: `fixed turn '${String(input.preview.turnId)}'`;\n\tthrow new Error(\n\t\t`Action '${input.actionId}' on turn '${input.turnId}' ${input.context} does not match a compiled transition for ${previewLabel}`,\n\t);\n}\n\nfunction buildActionPreviewAndScheduling(\n\tturnId: TurnId,\n\tactionId: string,\n\tspec: Pick<BaseActionSpec<unknown, unknown>, \"preview\" | \"schedulable\">,\n\ttransitions: readonly NormalizedActionRoute[],\n): {\n\tpreview?: ProcessActionPreviewDefinition;\n\tscheduling?: ProcessActionSchedulingDefinition;\n} {\n\tconst preview = (() => {\n\t\tif (spec.preview) {\n\t\t\treturn spec.preview;\n\t\t}\n\t\tif (transitions.length !== 1) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst [transition] = transitions;\n\t\tif (!transition) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (transition.lifecycleStatus !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: \"terminal\",\n\t\t\t\tlifecycleStatus: transition.lifecycleStatus,\n\t\t\t} satisfies ProcessActionPreviewDefinition;\n\t\t}\n\t\treturn {\n\t\t\tkind: \"trigger\",\n\t\t\ttrigger: transition.trigger,\n\t\t} satisfies ProcessActionPreviewDefinition;\n\t})();\n\tif (spec.preview && preview) {\n\t\tvalidateActionPreviewMatchesTransitions({\n\t\t\tturnId,\n\t\t\tactionId,\n\t\t\tpreview,\n\t\t\ttransitions,\n\t\t\tcontext: \"preview\",\n\t\t});\n\t}\n\tif (spec.schedulable && preview) {\n\t\tvalidateActionPreviewMatchesTransitions({\n\t\t\tturnId,\n\t\t\tactionId,\n\t\t\tpreview,\n\t\t\ttransitions,\n\t\t\tcontext: \"scheduling\",\n\t\t});\n\t}\n\tif (spec.schedulable && !preview) {\n\t\tthrow new Error(\n\t\t\t`Action '${actionId}' is schedulable but does not resolve to a unique preview transition`,\n\t\t);\n\t}\n\treturn {\n\t\t...(preview ? { preview } : {}),\n\t\t...(spec.schedulable && preview ? { scheduling: { preview } } : {}),\n\t};\n}\n\nfunction mergeProcessEffectPlans<TState>(\n\tleft: ProcessEffectPlan<TState> | undefined,\n\tright: ProcessEffectPlan<TState> | undefined,\n): ProcessEffectPlan<TState> | undefined {\n\tif (!left) {\n\t\treturn right;\n\t}\n\tif (!right) {\n\t\treturn left;\n\t}\n\treturn {\n\t\t...left,\n\t\t...right,\n\t\t...(left.processPatch || right.processPatch\n\t\t\t? { processPatch: { ...(left.processPatch ?? {}), ...(right.processPatch ?? {}) } }\n\t\t\t: {}),\n\t\t...(left.broadcasts || right.broadcasts\n\t\t\t? { broadcasts: [...(left.broadcasts ?? []), ...(right.broadcasts ?? [])] }\n\t\t\t: {}),\n\t\t...(left.emit || right.emit ? { emit: [...(left.emit ?? []), ...(right.emit ?? [])] } : {}),\n\t\t...(left.queueInput || right.queueInput\n\t\t\t? { queueInput: [...(left.queueInput ?? []), ...(right.queueInput ?? [])] }\n\t\t\t: {}),\n\t};\n}\n\nasync function buildSavePlanResultEffect<TParams, TState>(input: {\n\tintent: SavePlanResultLifecycleIntent<TParams, TState>;\n\texecution: ProcessOutcomeExecution<TParams, TState>;\n}): Promise<ProcessEffectPlan<TState>> {\n\tconst statePlan = input.intent.state ? await input.intent.state(input.execution) : undefined;\n\tconst planRevision = input.execution.ctx.process.planRevision + 1;\n\tconst summary = normalizeEffectString(input.execution.event.params[input.intent.summaryParam]);\n\tconst acceptanceCriteria = normalizeEffectStringArray(\n\t\tinput.execution.event.params[input.intent.acceptanceCriteriaParam],\n\t);\n\tconst planMarkdown =\n\t\ttypeof input.execution.event.turnResultMarkdown === \"string\"\n\t\t\t? input.execution.event.turnResultMarkdown\n\t\t\t: normalizeEffectString(input.execution.event.params[input.intent.planMarkdownParam]);\n\n\treturn mergeProcessEffectPlans(statePlan, {\n\t\tprocessPatch: { planRevision },\n\t\tbroadcasts: [\n\t\t\t{\n\t\t\t\ttype: input.intent.broadcastType,\n\t\t\t\tpayload: {\n\t\t\t\t\tplanRevision,\n\t\t\t\t\treviewState: \"awaiting_approval\",\n\t\t\t\t\tapproved: false,\n\t\t\t\t\tsummary,\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\temit: [\n\t\t\t{\n\t\t\t\ttype: input.intent.emitEventType,\n\t\t\t\tdata: {\n\t\t\t\t\tplanRevision,\n\t\t\t\t\tsummary,\n\t\t\t\t\tplanMarkdown,\n\t\t\t\t\tacceptanceCriteria,\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t}) as ProcessEffectPlan<TState>;\n}\n\nfunction resolveOutcomeEffect<TParams, TState>(input: {\n\tspec: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState, string>;\n}): ProcessOutcomeEffect<TParams, TState> | undefined {\n\tconst lifecycleIntent = \"lifecycleIntent\" in input.spec ? input.spec.lifecycleIntent : undefined;\n\tif (!lifecycleIntent) {\n\t\treturn input.spec.effect;\n\t}\n\treturn async (execution) => {\n\t\tconst explicitPlan = input.spec.effect ? await input.spec.effect(execution) : undefined;\n\t\tlet lifecyclePlan: ProcessEffectPlan<TState> | undefined;\n\t\tswitch (lifecycleIntent.kind) {\n\t\t\tcase \"save_plan_result\":\n\t\t\t\tlifecyclePlan = await buildSavePlanResultEffect({\n\t\t\t\t\tintent: lifecycleIntent,\n\t\t\t\t\texecution,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t}\n\t\treturn mergeProcessEffectPlans(explicitPlan, lifecyclePlan);\n\t};\n}\n\nfunction areFormsEquivalent(\n\tleft: FormDefinition | undefined,\n\tright: FormDefinition | undefined,\n): boolean {\n\tif (left === right) {\n\t\treturn true;\n\t}\n\treturn JSON.stringify(left ?? null) === JSON.stringify(right ?? null);\n}\n\nfunction cloneStateForFormPatch<TState>(state: TState): TState {\n\tif (typeof state !== \"object\" || state === null) {\n\t\tthrow new Error(\"Declarative form state fields require object process state\");\n\t}\n\treturn structuredClone(state);\n}\n\nfunction normalizeFormStateValue(field: FormDefinition[\"fields\"][number], value: unknown): unknown {\n\tif (field.kind === \"number\") {\n\t\tconst parsed = typeof value === \"number\" ? value : Number(String(value).trim());\n\t\tif (!Number.isFinite(parsed)) {\n\t\t\tthrow new Error(`Field '${field.id}' must be a number`);\n\t\t}\n\t\treturn parsed;\n\t}\n\treturn value;\n}\n\nfunction applyFormStateFields<TState>(input: {\n\tform?: FormDefinition;\n\tinputValue: Record<string, unknown>;\n\tstate: TState;\n}): TState | undefined {\n\tconst stateFields = (input.form?.fields ?? []).filter((field) => field.state);\n\tif (stateFields.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst nextState = cloneStateForFormPatch(input.state) as Record<string, unknown>;\n\tfor (const field of stateFields) {\n\t\tconst rawValue = input.inputValue[field.id];\n\t\tif (rawValue === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst path = field.state?.path.trim();\n\t\tif (!path) {\n\t\t\tthrow new Error(`Form field '${field.id}' declares an empty state path`);\n\t\t}\n\t\tconst segments = path.split(\".\").map((segment) => segment.trim());\n\t\tif (segments.some((segment) => segment === \"\")) {\n\t\t\tthrow new Error(`Form field '${field.id}' declares invalid state path '${path}'`);\n\t\t}\n\t\tlet target: Record<string, unknown> = nextState;\n\t\tfor (const segment of segments.slice(0, -1)) {\n\t\t\tconst existing = target[segment];\n\t\t\tif (typeof existing !== \"object\" || existing === null || Array.isArray(existing)) {\n\t\t\t\ttarget[segment] = {};\n\t\t\t}\n\t\t\ttarget = target[segment] as Record<string, unknown>;\n\t\t}\n\t\ttarget[segments[segments.length - 1] as string] = normalizeFormStateValue(field, rawValue);\n\t}\n\treturn nextState as TState;\n}\n\nfunction makeProcessServerRuntimeContext<TParams, TState>(\n\tctx: ServerProcessContext<TParams, TState>,\n): ProcessServerRuntimeContext<TParams, TState> {\n\treturn {\n\t\tprocess: ctx.process,\n\t\tprojects: ctx.projects,\n\t\tparams: ctx.params,\n\t\tstate: ctx.state,\n\t\treadSemanticTurnResultMarkdown: (ref) => ctx.readSemanticTurnResultMarkdown(ref),\n\t\treadProductTurnResultMarkdown: (productName) => ctx.readProductTurnResultMarkdown(productName),\n\t};\n}\n\nfunction mergeTransitionWithState<TState>(input: {\n\tresult: ProcessEffectPlan<TState> | undefined;\n\ttransition?: Omit<ServerTransitionRequest<TState>, \"state\">;\n}): ServerTransitionRequest<TState> | null {\n\tconst next = {\n\t\t...(input.transition ?? {}),\n\t\t...(input.result?.state !== undefined ? { state: input.result.state } : {}),\n\t};\n\tconst hasFields =\n\t\tnext.turnId !== undefined ||\n\t\tnext.lifecycleStatus !== undefined ||\n\t\tnext.trigger !== undefined ||\n\t\tnext.effect !== undefined ||\n\t\tnext.state !== undefined;\n\treturn hasFields ? next : null;\n}\n\nfunction hasLifecycleEffects(result: ProcessEffectPlan | undefined): result is ProcessEffectPlan {\n\treturn Boolean(\n\t\tresult?.processPatch !== undefined ||\n\t\t\t(result?.broadcasts !== undefined && result.broadcasts.length > 0),\n\t);\n}\n\nasync function applyProcessEffectPlan<TParams, TState>(input: {\n\tctx: ServerProcessContext<TParams, TState>;\n\tresult: ProcessEffectPlan<TState> | undefined;\n\ttransition?: Omit<ServerTransitionRequest<TState>, \"state\">;\n}): Promise<void> {\n\tconst transition = mergeTransitionWithState({\n\t\tresult: input.result,\n\t\ttransition: input.transition,\n\t});\n\tif (transition) {\n\t\tawait input.ctx.transition(transition);\n\t}\n\tif (hasLifecycleEffects(input.result)) {\n\t\tif (!input.ctx.applyLifecycleEffects) {\n\t\t\tthrow new Error(\"Process lifecycle effects are not supported by this server context\");\n\t\t}\n\t\tinput.ctx.applyLifecycleEffects({\n\t\t\t...(input.result.processPatch ? { processPatch: input.result.processPatch } : {}),\n\t\t\t...(input.result.broadcasts ? { broadcasts: input.result.broadcasts } : {}),\n\t\t});\n\t}\n\tfor (const emitted of input.result?.emit ?? []) {\n\t\tinput.ctx.emitEvent(emitted.type, emitted.data as never);\n\t}\n\tfor (const queuedInput of input.result?.queueInput ?? []) {\n\t\tinput.ctx.queueInput(queuedInput);\n\t}\n}\n\nfunction compileTurnOutcomeDefinitions<TParams, TState>(input: {\n\tturnId: TurnId;\n\toutcomes?: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>>;\n\tturnEnd?: ProcessTurnEndSpec<TParams, TState, string>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): CompiledOutcomeHandlers<TParams, TState> & {\n\ttransitions: readonly ProcessTurnTransition[];\n} {\n\tconst outcomeEntries = Object.entries(input.outcomes ?? {}) as Array<\n\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t>;\n\tif (outcomeEntries.length > 0 && input.turnEnd) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.turnId}' cannot declare both tool outcomes and a turnEnd result`,\n\t\t);\n\t}\n\tif (outcomeEntries.length === 0 && !input.turnEnd) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.turnId}' must declare at least one tool outcome or a turnEnd result`,\n\t\t);\n\t}\n\n\tconst transitions: ProcessTurnTransition[] = [];\n\tconst effects = new Map<string, ProcessOutcomeEffect<TParams, TState> | undefined>();\n\tconst routings = new Map<string, CompiledOutcomeRouting<TParams, TState>>();\n\tfor (const [outcome, spec] of outcomeEntries) {\n\t\tif (outcome.trim() === \"\") {\n\t\t\tthrow new Error(`Turn '${input.turnId}' declares an empty outcome id`);\n\t\t}\n\t\tconst routing = resolveOutcomeRouting({\n\t\t\tturnId: input.turnId,\n\t\t\toutcome,\n\t\t\tspec,\n\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t});\n\t\tconst target = routing\n\t\t\t? null\n\t\t\t: buildOutcomeTransition(input.turnId, outcome, spec, input.knownTurnIds);\n\t\tif (routing) {\n\t\t\troutings.set(outcome, routing);\n\t\t\tfor (const route of Object.values(routing.routes)) {\n\t\t\t\ttransitions.push({\n\t\t\t\t\t...(route.nextTurnId ? { nextTurnId: route.nextTurnId } : {}),\n\t\t\t\t\t...(route.lifecycleStatus ? { lifecycleStatus: route.lifecycleStatus } : {}),\n\t\t\t\t\ttrigger: route.trigger,\n\t\t\t\t\toutcome,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (target) {\n\t\t\ttransitions.push({\n\t\t\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\t\t\toutcome,\n\t\t\t});\n\t\t}\n\t\teffects.set(outcome, resolveOutcomeEffect({ spec }));\n\t}\n\n\tif (input.turnEnd) {\n\t\tif (input.turnEnd.outcome.trim() === \"\") {\n\t\t\tthrow new Error(`Turn '${input.turnId}' declares an empty turnEnd outcome id`);\n\t\t}\n\t\tconst target = buildOutcomeTransition(\n\t\t\tinput.turnId,\n\t\t\tinput.turnEnd.outcome,\n\t\t\tinput.turnEnd,\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\ttransitions.push({\n\t\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\t\toutcome: input.turnEnd.outcome,\n\t\t});\n\t\teffects.set(input.turnEnd.outcome, resolveOutcomeEffect({ spec: input.turnEnd }));\n\t}\n\n\treturn {\n\t\ttransitions,\n\t\teffects,\n\t\troutings,\n\t};\n}\n\nfunction addActionUse<TParams, TState>(input: {\n\tactionUses: Map<string, CompiledActionUse<TParams, TState>[]>;\n\tactionId: string;\n\tuse: CompiledActionUse<TParams, TState>;\n}) {\n\tconst existing = input.actionUses.get(input.actionId) ?? [];\n\tif (existing.some((candidate) => candidate.turnId === input.use.turnId)) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.use.turnId}' declares action '${input.actionId}' more than once`,\n\t\t);\n\t}\n\texisting.push(input.use);\n\tinput.actionUses.set(input.actionId, existing);\n}\n\ntype DerivedHumanTurnAction<TParams, TState> = {\n\tactionId: string;\n\tactionSpec: ProcessHumanTurnActionSpec<TParams, TState>;\n\trouting: CompiledActionRouting<TParams, TState>;\n\ttransitions: readonly NormalizedActionRoute[];\n\tactionView: HumanTurnActionView;\n\texternalTriggers: readonly HumanTurnExternalTrigger[];\n};\n\ntype DerivedHumanTurnExternalAction<TParams, TState> = {\n\texternalActionId: string;\n\tactionSpec: ProcessHumanTurnExternalActionSpec<TParams, TState>;\n\ttransition: NormalizedActionRoute;\n\tview: HumanTurnExternalActionView;\n};\n\nfunction hasDeclaredStaticRouteTarget(target: StaticRouteTarget): boolean {\n\treturn (\n\t\ttarget.to !== undefined || target.complete === true || target.lifecycleStatus !== undefined\n\t);\n}\n\nfunction resolveExternalActionRoute<TParams, TState>(input: {\n\tturnId: TurnId;\n\texternalActionId: string;\n\tspec: ProcessHumanTurnExternalActionSpec<TParams, TState>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n}): NormalizedActionRoute {\n\tif (input.externalActionId.trim() === \"\") {\n\t\tthrow new Error(`Human turn '${input.turnId}' declares an empty external action id`);\n\t}\n\tif (input.spec.id !== input.externalActionId) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' has mismatched spec id '${input.spec.id}'`,\n\t\t);\n\t}\n\tif (input.spec.source.kind.trim() === \"\") {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' must declare a non-empty source kind`,\n\t\t);\n\t}\n\tconst target = normalizeStaticRouteTarget(\n\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}'`,\n\t\tinput.spec,\n\t\tinput.knownTurnIds,\n\t);\n\treturn {\n\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\ttrigger: getExternalActionTransitionTrigger({ externalActionId: input.externalActionId }),\n\t};\n}\n\nfunction validateExternalActionPublishedInputTarget<TParams, TState>(input: {\n\tturnId: TurnId;\n\texternalActionId: string;\n\tspec: ProcessHumanTurnExternalActionSpec<TParams, TState>;\n\tturnDefinitionsById?: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n}): void {\n\tconst publication = input.spec.publishInput;\n\tif (!publication || !input.turnDefinitionsById) {\n\t\treturn;\n\t}\n\tif (input.spec.to === undefined) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but does not route to a consuming turn`,\n\t\t);\n\t}\n\tconst targetTurn = input.turnDefinitionsById.get(input.spec.to);\n\tif (!targetTurn || targetTurn.kind !== \"llm\") {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' is not an LLM turn`,\n\t\t);\n\t}\n\tconst consumed = new Set([\n\t\t...(targetTurn.consumedProducts ?? []),\n\t\t...(targetTurn.optionalConsumedProducts ?? []),\n\t]);\n\tif (!consumed.has(publication.productName)) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' does not consume it`,\n\t\t);\n\t}\n}\n\nfunction validateActionPrimaryPrompt(\n\tturnId: TurnId,\n\tactionId: string,\n\taction: { form?: FormDefinition },\n): void {\n\tconst fields = action.form?.fields ?? [];\n\tconst textualFields = fields.filter(\n\t\t(field) => field.kind === \"text\" || field.kind === \"textarea\",\n\t);\n\tconst primaryPrompts = fields.filter((field) => field.primaryPrompt);\n\tif (primaryPrompts.some((field) => field.kind !== \"text\" && field.kind !== \"textarea\")) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${turnId}' action '${actionId}' primary prompt must be a text or textarea field`,\n\t\t);\n\t}\n\tif (primaryPrompts.length > 1) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${turnId}' action '${actionId}' must declare at most one primary prompt`,\n\t\t);\n\t}\n\tif (textualFields.length > 0 && primaryPrompts.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${turnId}' action '${actionId}' with textual fields must declare a primary prompt`,\n\t\t);\n\t}\n}\n\nfunction deriveHumanTurnActions<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: HumanTurnDefinition<TParams, TState>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n\tturnDefinitionsById?: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n\trequireHumanActions?: boolean;\n}): {\n\tactions: readonly DerivedHumanTurnAction<TParams, TState>[];\n\texternalActions: readonly DerivedHumanTurnExternalAction<TParams, TState>[];\n\ttransitions: readonly ProcessTurnTransition[];\n} {\n\tconst actionEntries = Object.entries(input.spec.actions) as Array<\n\t\t[string, ProcessHumanTurnActionSpec<TParams, TState>]\n\t>;\n\tif (actionEntries.length === 0 && input.knownTurnIds && input.requireHumanActions !== false) {\n\t\tthrow new Error(`Human turn '${input.turnId}' must declare at least one action`);\n\t}\n\n\tconst derivedActions: DerivedHumanTurnAction<TParams, TState>[] = [];\n\tconst transitions: ProcessTurnTransition[] = [];\n\tconst actionIdByTrigger = new Map<string, string>();\n\tfor (const [actionId, actionSpec] of actionEntries) {\n\t\tif (actionId.trim() === \"\") {\n\t\t\tthrow new Error(`Human turn '${input.turnId}' declares an empty action id`);\n\t\t}\n\t\tvalidateActionPrimaryPrompt(input.turnId, actionId, actionSpec);\n\t\tconst resolved =\n\t\t\t!input.knownTurnIds &&\n\t\t\t!(\"branches\" in actionSpec) &&\n\t\t\t!hasDeclaredStaticRouteTarget(actionSpec)\n\t\t\t\t? {\n\t\t\t\t\t\trouting: {\n\t\t\t\t\t\t\tkind: \"static\",\n\t\t\t\t\t\t\troute: { trigger: actionSpec.trigger ?? actionId },\n\t\t\t\t\t\t} satisfies CompiledActionRouting<TParams, TState>,\n\t\t\t\t\t\ttransitions: [] as readonly NormalizedActionRoute[],\n\t\t\t\t\t}\n\t\t\t\t: resolveActionRouting({\n\t\t\t\t\t\tturnId: input.turnId,\n\t\t\t\t\t\tactionId,\n\t\t\t\t\t\tspec: actionSpec,\n\t\t\t\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t\t\t\t});\n\t\tfor (const transition of resolved.transitions) {\n\t\t\tconst existingActionId = actionIdByTrigger.get(transition.trigger);\n\t\t\tif (existingActionId && existingActionId !== actionId) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Human turn '${input.turnId}' contains duplicate action trigger '${transition.trigger}' across actions '${existingActionId}' and '${actionId}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tactionIdByTrigger.set(transition.trigger, actionId);\n\t\t\ttransitions.push({\n\t\t\t\t...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),\n\t\t\t\t...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),\n\t\t\t\ttrigger: transition.trigger,\n\t\t\t});\n\t\t}\n\t\tconst previewAndScheduling =\n\t\t\t!input.knownTurnIds && resolved.transitions.length === 0\n\t\t\t\t? {\n\t\t\t\t\t\t...(actionSpec.preview ? { preview: actionSpec.preview } : {}),\n\t\t\t\t\t\t...(actionSpec.schedulable && actionSpec.preview\n\t\t\t\t\t\t\t? { scheduling: { preview: actionSpec.preview } }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t}\n\t\t\t\t: buildActionPreviewAndScheduling(input.turnId, actionId, actionSpec, resolved.transitions);\n\t\tderivedActions.push({\n\t\t\tactionId,\n\t\t\tactionSpec,\n\t\t\trouting: resolved.routing,\n\t\t\ttransitions: resolved.transitions,\n\t\t\tactionView: {\n\t\t\t\tactionId,\n\t\t\t\tlabel: actionSpec.label,\n\t\t\t\tdescription: actionSpec.description,\n\t\t\t\tacceptanceState: actionSpec.acceptanceState,\n\t\t\t\t...previewAndScheduling,\n\t\t\t},\n\t\t\texternalTriggers:\n\t\t\t\tactionSpec.externalTriggers?.map((trigger) => ({\n\t\t\t\t\tid: trigger.id,\n\t\t\t\t\tactionId,\n\t\t\t\t\tlabel: trigger.label,\n\t\t\t\t\tdescription: trigger.description,\n\t\t\t\t})) ?? [],\n\t\t});\n\t}\n\n\tconst externalActionEntries = Object.entries(input.spec.externalActions ?? {}) as Array<\n\t\t[string, ProcessHumanTurnExternalActionSpec<TParams, TState>]\n\t>;\n\tconst derivedExternalActions: DerivedHumanTurnExternalAction<TParams, TState>[] = [];\n\tconst externalActionIds = new Set<string>();\n\tfor (const [externalActionId, actionSpec] of externalActionEntries) {\n\t\tif (externalActionIds.has(externalActionId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Human turn '${input.turnId}' declares duplicate external action '${externalActionId}'`,\n\t\t\t);\n\t\t}\n\t\texternalActionIds.add(externalActionId);\n\t\tif (actionSpec.publishInput) {\n\t\t\tassertValidProcessProductName(actionSpec.publishInput.productName);\n\t\t\tif (actionSpec.publishInput.inputField.trim() === \"\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Human turn '${input.turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tvalidateExternalActionPublishedInputTarget({\n\t\t\tturnId: input.turnId,\n\t\t\texternalActionId,\n\t\t\tspec: actionSpec,\n\t\t\tturnDefinitionsById: input.turnDefinitionsById,\n\t\t});\n\t\tconst transition = resolveExternalActionRoute({\n\t\t\tturnId: input.turnId,\n\t\t\texternalActionId,\n\t\t\tspec: actionSpec,\n\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t});\n\t\tconst existingActionId = actionIdByTrigger.get(transition.trigger);\n\t\tif (existingActionId) {\n\t\t\tthrow new Error(\n\t\t\t\t`Human turn '${input.turnId}' contains duplicate trigger '${transition.trigger}' across action '${existingActionId}' and external action '${externalActionId}'`,\n\t\t\t);\n\t\t}\n\t\tactionIdByTrigger.set(transition.trigger, externalActionId);\n\t\ttransitions.push({\n\t\t\t...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),\n\t\t\t...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),\n\t\t\ttrigger: transition.trigger,\n\t\t});\n\t\tderivedExternalActions.push({\n\t\t\texternalActionId,\n\t\t\tactionSpec,\n\t\t\ttransition,\n\t\t\tview: {\n\t\t\t\tid: getExternalActionArmingId({ turnId: input.turnId, externalActionId }),\n\t\t\t\texternalActionId,\n\t\t\t\tsourceKind: actionSpec.source.kind,\n\t\t\t\tlabel: actionSpec.label ?? actionSpec.source.label ?? null,\n\t\t\t\tdescription: actionSpec.description ?? actionSpec.source.description ?? null,\n\t\t\t},\n\t\t});\n\t}\n\n\treturn {\n\t\tactions: derivedActions,\n\t\texternalActions: derivedExternalActions,\n\t\ttransitions,\n\t};\n}\n\n/** @internal */\nexport function resolveHumanTurnView<TParams, TState>(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tturn: HumanTurnDefinition<TParams, TState>;\n}): {\n\t/** @internal */\n\tactions: readonly HumanTurnActionView[];\n\t/** @internal */\n\texternalTriggers: readonly HumanTurnExternalTrigger[];\n\t/** @internal */\n\texternalActions: readonly HumanTurnExternalActionView[];\n} {\n\tconst derived = deriveHumanTurnActions({\n\t\tturnId: input.turnId,\n\t\tspec: input.turn,\n\t});\n\treturn {\n\t\tactions: derived.actions.map((action) => action.actionView),\n\t\texternalTriggers: derived.actions.flatMap((action) => action.externalTriggers),\n\t\texternalActions: derived.externalActions.map((action) => action.view),\n\t};\n}\n\nfunction compileHumanTurn<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: HumanTurnDefinition<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n\tturnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n\tactionUses: Map<string, CompiledActionUse<TParams, TState>[]>;\n}): {\n\tbinding: ProcessTurnBinding<HumanTurnDefinition<TParams, TState>>;\n} {\n\tconst derived = deriveHumanTurnActions({\n\t\tturnId: input.turnId,\n\t\tspec: input.spec,\n\t\tknownTurnIds: input.knownTurnIds,\n\t\tturnDefinitionsById: input.turnDefinitionsById,\n\t});\n\tfor (const action of derived.actions) {\n\t\taddActionUse({\n\t\t\tactionUses: input.actionUses,\n\t\t\tactionId: action.actionId,\n\t\t\tuse: {\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tlabel: action.actionSpec.label,\n\t\t\t\t...(action.actionSpec.form ? { form: action.actionSpec.form } : {}),\n\t\t\t\t...(action.actionSpec.effect ? { effect: action.actionSpec.effect } : {}),\n\t\t\t\trouting: action.routing,\n\t\t\t},\n\t\t});\n\t}\n\n\treturn {\n\t\tbinding: createProcessTurnBinding(input.spec, derived.transitions),\n\t};\n}\n\nfunction compileExternalTurn<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: ExternalTurnDefinition<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): {\n\tbinding: ProcessTurnBinding<ExternalTurnDefinition<TParams, TState>>;\n} {\n\tconst transitions = compileExternalSourceTransitions({\n\t\tturnId: input.turnId,\n\t\tspec: input.spec,\n\t\tknownTurnIds: input.knownTurnIds,\n\t});\n\treturn {\n\t\tbinding: createProcessTurnBinding(input.spec, transitions),\n\t};\n}\n\nfunction resolveActionRouteForExecution<TParams, TState>(input: {\n\tuse: CompiledActionUse<TParams, TState>;\n\tactionId: string;\n\tctx: ServerProcessContext<TParams, TState>;\n\tinputValue: Record<string, unknown>;\n}): MaybePromise<{\n\troute: NormalizedActionRoute;\n\tselectedBranchId?: string;\n}> {\n\tif (input.use.routing.kind === \"static\") {\n\t\treturn { route: input.use.routing.route };\n\t}\n\tconst actionExecution: Omit<ProcessActionExecution<TParams, TState>, \"selectedBranchId\"> = {\n\t\tctx: makeProcessServerRuntimeContext(input.ctx),\n\t\tinput: input.inputValue,\n\t\tturnId: input.use.turnId,\n\t\tactionId: input.actionId,\n\t};\n\tconst routes = input.use.routing.routes;\n\treturn Promise.resolve(input.use.routing.choose(actionExecution)).then((selectedBranchId) => {\n\t\tif (!Object.hasOwn(routes, selectedBranchId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`,\n\t\t\t);\n\t\t}\n\t\tconst route = routes[selectedBranchId];\n\t\tif (!route) {\n\t\t\tthrow new Error(\n\t\t\t\t`Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`,\n\t\t\t);\n\t\t}\n\t\treturn { route, selectedBranchId };\n\t});\n}\n\nfunction buildActionTransitionRequest<TState>(route: NormalizedActionRoute) {\n\tif (route.nextTurnId !== undefined) {\n\t\treturn {\n\t\t\tturnId: route.nextTurnId,\n\t\t\ttrigger: route.trigger,\n\t\t} satisfies Omit<ServerTransitionRequest<TState>, \"state\">;\n\t}\n\treturn {\n\t\tturnId: null,\n\t\tlifecycleStatus: route.lifecycleStatus,\n\t\ttrigger: route.trigger,\n\t} satisfies Omit<ServerTransitionRequest<TState>, \"state\">;\n}\n\nfunction validateHappyPathConnectivity<TParams, TState>(input: {\n\tprocessId: string;\n\thappyPath: readonly TurnId[] | undefined;\n\tturns: ReadonlyMap<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>;\n\tturnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n}): void {\n\tconst happyPath = input.happyPath;\n\tif (!happyPath || happyPath.length < 2) {\n\t\treturn;\n\t}\n\tconst happyPathTurns = new Set<TurnId>(happyPath);\n\tfor (let index = 0; index < happyPath.length - 1; index += 1) {\n\t\tconst source = happyPath[index];\n\t\tconst target = happyPath[index + 1];\n\t\tlet connected = false;\n\t\tconst visited = new Set<TurnId>([source]);\n\t\tconst queue: TurnId[] = [source];\n\t\twhile (queue.length > 0 && !connected) {\n\t\t\tconst current = queue.shift() as TurnId;\n\t\t\tfor (const transition of getProcessTurnTransitions(input.turns.get(current))) {\n\t\t\t\tconst next = transition.nextTurnId;\n\t\t\t\tif (next === undefined || !input.turnDefinitionsById.has(next)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (next === target) {\n\t\t\t\t\tconnected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (visited.has(next) || happyPathTurns.has(next)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst definition = input.turnDefinitionsById.get(next);\n\t\t\t\tif (definition?.kind !== \"human\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvisited.add(next);\n\t\t\t\tqueue.push(next);\n\t\t\t}\n\t\t}\n\t\tif (!connected) {\n\t\t\tthrow new Error(\n\t\t\t\t`Process '${input.processId}' happy path segment '${source}' -> '${target}' is not connected by declared transitions`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction buildDefinedProcess<TParams, TState>(\n\tinput: DefinedProcessInput<TParams, TState>,\n): Pick<ExtensionProcessDefinition<TParams, TState>, \"turns\" | \"worker\" | \"server\"> {\n\tconst turnEntries = Object.entries(input.turns);\n\tif (turnEntries.length === 0) {\n\t\tthrow new Error(`Process '${input.id}' must declare at least one turn`);\n\t}\n\tconst knownTurnIds = new Set(turnEntries.map(([turnId]) => turnId));\n\tconst turnDefinitionsById = new Map<TurnId, TurnDefinition<unknown, unknown>>(\n\t\tturnEntries.map(([turnId, turnSpec]) => [turnId, turnSpec as TurnDefinition<unknown, unknown>]),\n\t);\n\tif (!knownTurnIds.has(input.entry)) {\n\t\tthrow new Error(`Process '${input.id}' entry turn '${input.entry}' is not declared`);\n\t}\n\tconst seenEntries = new Set<TurnId>();\n\tfor (const turnId of [input.entry, ...(input.alternateEntries ?? [])]) {\n\t\tif (seenEntries.has(turnId)) {\n\t\t\tthrow new Error(`Process '${input.id}' declares duplicate entry turn '${turnId}'`);\n\t\t}\n\t\tif (!knownTurnIds.has(turnId)) {\n\t\t\tthrow new Error(`Process '${input.id}' entry turn '${turnId}' is not declared`);\n\t\t}\n\t\tseenEntries.add(turnId);\n\t}\n\n\tif (input.happyPath) {\n\t\tif (input.happyPath.length === 0) {\n\t\t\tthrow new Error(`Process '${input.id}' declares an empty happy path`);\n\t\t}\n\t\tconst seen = new Set<TurnId>();\n\t\tfor (const turnId of input.happyPath) {\n\t\t\tif (!knownTurnIds.has(turnId)) {\n\t\t\t\tthrow new Error(`Process '${input.id}' happy path references undeclared turn '${turnId}'`);\n\t\t\t}\n\t\t\tif (seen.has(turnId)) {\n\t\t\t\tthrow new Error(`Process '${input.id}' happy path repeats turn '${turnId}'`);\n\t\t\t}\n\t\t\tseen.add(turnId);\n\t\t}\n\t\tif (input.happyPath[0] !== input.entry) {\n\t\t\tthrow new Error(\n\t\t\t\t`Process '${input.id}' happy path must start at the entry turn '${input.entry}'`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst turns = new Map<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>();\n\tconst actionUses = new Map<string, CompiledActionUse<TParams, TState>[]>();\n\tconst executableTurns = new Map<\n\t\tTurnId,\n\t\tCompiledOutcomeHandlers<TParams, TState> & {\n\t\t\tspec: RoutableTurnDefinition<string, TParams, TState>;\n\t\t}\n\t>();\n\n\tfor (const [turnId, turnSpec] of turnEntries) {\n\t\tif (turnSpec.kind === \"llm\" || turnSpec.kind === \"automatic\") {\n\t\t\tconst { transitions, effects, routings } = compileTurnOutcomeDefinitions({\n\t\t\t\tturnId,\n\t\t\t\toutcomes: turnSpec.outcomes,\n\t\t\t\tturnEnd: turnSpec.turnEnd,\n\t\t\t\tknownTurnIds,\n\t\t\t});\n\t\t\tconst externalTransitions =\n\t\t\t\tturnSpec.kind === \"automatic\" && turnSpec.externalActions\n\t\t\t\t\t? deriveHumanTurnActions({\n\t\t\t\t\t\t\tturnId,\n\t\t\t\t\t\t\tspec: {\n\t\t\t\t\t\t\t\tkind: \"human\",\n\t\t\t\t\t\t\t\tdescription: turnSpec.description,\n\t\t\t\t\t\t\t\tactions: {},\n\t\t\t\t\t\t\t\texternalActions: turnSpec.externalActions,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tknownTurnIds,\n\t\t\t\t\t\t\tturnDefinitionsById,\n\t\t\t\t\t\t\trequireHumanActions: false,\n\t\t\t\t\t\t}).transitions\n\t\t\t\t\t: [];\n\t\t\tturns.set(\n\t\t\t\tturnId,\n\t\t\t\tcreateProcessTurnBinding(turnSpec, [...transitions, ...externalTransitions]),\n\t\t\t);\n\t\t\texecutableTurns.set(turnId, { spec: turnSpec, effects, routings });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (turnSpec.kind === \"human\") {\n\t\t\tconst compiled = compileHumanTurn({\n\t\t\t\tturnId,\n\t\t\t\tspec: turnSpec,\n\t\t\t\tknownTurnIds,\n\t\t\t\tturnDefinitionsById,\n\t\t\t\tactionUses,\n\t\t\t});\n\t\t\tturns.set(turnId, compiled.binding);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst compiled = compileExternalTurn({\n\t\t\tturnId,\n\t\t\tspec: turnSpec,\n\t\t\tknownTurnIds,\n\t\t});\n\t\tturns.set(turnId, compiled.binding);\n\t}\n\n\tvalidateHappyPathConnectivity({\n\t\tprocessId: input.id,\n\t\thappyPath: input.happyPath,\n\t\tturns,\n\t\tturnDefinitionsById,\n\t});\n\n\tconst worker: ExtensionProcessDefinition<TParams, TState>[\"worker\"] = (api) => {\n\t\tapi.start(input.entry);\n\t\tconst manuallyRegisteredTurns = new Set<TurnId>();\n\t\tinput.worker?.({\n\t\t\tstart(turnId) {\n\t\t\t\tapi.start(turnId);\n\t\t\t},\n\t\t\tturn(turnId, handler) {\n\t\t\t\tmanuallyRegisteredTurns.add(turnId);\n\t\t\t\tapi.turn(turnId, handler);\n\t\t\t},\n\t\t});\n\t\tfor (const [turnId, { spec }] of executableTurns) {\n\t\t\tif (manuallyRegisteredTurns.has(turnId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (spec.kind === \"llm\") {\n\t\t\t\tapi.turn(turnId, async (run) => {\n\t\t\t\t\tawait run.turn(spec);\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tapi.turn(turnId, async (run) => {\n\t\t\t\tawait run.complete(await spec.run(run.ctx));\n\t\t\t});\n\t\t}\n\t};\n\n\tconst server: ExtensionProcessDefinition<TParams, TState>[\"server\"] = (api) => {\n\t\tfor (const [actionId, uses] of actionUses) {\n\t\t\tconst [firstUse] = uses;\n\t\t\tconst form = firstUse?.form;\n\t\t\tfor (const use of uses) {\n\t\t\t\tif (!areFormsEquivalent(form, use.form)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Action '${actionId}' must use the same form on every turn that references it`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tapi.action({\n\t\t\t\tid: actionId,\n\t\t\t\tlabel: firstUse?.label ?? actionId,\n\t\t\t\t...(form ? { form } : {}),\n\t\t\t\tasync plan(inputValue, ctx) {\n\t\t\t\t\tconst turnId = ctx.process.selectedTurnId;\n\t\t\t\t\tconst use = uses.find((candidate) => candidate.turnId === turnId);\n\t\t\t\t\tif (!use || !turnId) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Action '${actionId}' is not available for selected turn '${String(turnId)}'`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst resolvedRoute = await resolveActionRouteForExecution({\n\t\t\t\t\t\tuse,\n\t\t\t\t\t\tactionId,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tinputValue,\n\t\t\t\t\t});\n\t\t\t\t\tconst effectResult = use.effect\n\t\t\t\t\t\t? await use.effect({\n\t\t\t\t\t\t\t\tctx: makeProcessServerRuntimeContext(ctx),\n\t\t\t\t\t\t\t\tinput: inputValue,\n\t\t\t\t\t\t\t\tturnId,\n\t\t\t\t\t\t\t\tactionId,\n\t\t\t\t\t\t\t\t...(resolvedRoute.selectedBranchId\n\t\t\t\t\t\t\t\t\t? { selectedBranchId: resolvedRoute.selectedBranchId }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst formState = applyFormStateFields({\n\t\t\t\t\t\tform: use.form,\n\t\t\t\t\t\tinputValue,\n\t\t\t\t\t\tstate: effectResult?.state ?? ctx.state,\n\t\t\t\t\t});\n\t\t\t\t\tconst result = formState\n\t\t\t\t\t\t? mergeProcessEffectPlans(effectResult, { state: formState })\n\t\t\t\t\t\t: effectResult;\n\t\t\t\t\tawait applyProcessEffectPlan({\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\ttransition: buildActionTransitionRequest(resolvedRoute.route),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tfor (const [turnId, { effects, routings }] of executableTurns) {\n\t\t\tapi.onTurnOutcome(turnId, async (event, ctx) => {\n\t\t\t\tconst effect = effects.get(event.outcome);\n\t\t\t\tconst routing = routings.get(event.outcome);\n\t\t\t\tif (!effect && !routing) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst execution = {\n\t\t\t\t\tctx: makeProcessServerRuntimeContext(ctx),\n\t\t\t\t\tevent,\n\t\t\t\t\tturnId,\n\t\t\t\t\toutcome: event.outcome,\n\t\t\t\t};\n\t\t\t\tconst result = effect ? await effect(execution) : undefined;\n\t\t\t\tlet transition: Omit<ServerTransitionRequest<TState>, \"state\"> | undefined;\n\t\t\t\tif (routing) {\n\t\t\t\t\tconst branchId = await routing.choose(execution);\n\t\t\t\t\tconst route = routing.routes[branchId];\n\t\t\t\t\tif (!route) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Turn '${turnId}' outcome '${event.outcome}' selected unknown branch '${branchId}'`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\ttransition = buildActionTransitionRequest(route);\n\t\t\t\t}\n\t\t\t\tawait applyProcessEffectPlan({ ctx, result, transition });\n\t\t\t});\n\t\t}\n\n\t\tinput.server?.(api);\n\t};\n\n\treturn {\n\t\tturns,\n\t\tworker,\n\t\tserver,\n\t};\n}\n\n/** @public */\nexport function defineProcess<TParams = unknown, TState = unknown>(\n\tinput: DefinedProcessInput<TParams, TState>,\n): ExtensionProcessDefinition<TParams, TState> {\n\tconst compiled = buildDefinedProcess(input);\n\tconst process = {\n\t\tid: input.id,\n\t\tdisplayName: input.displayName,\n\t\tentryTurnId: input.entry,\n\t\talternateEntryTurnIds: [...(input.alternateEntries ?? [])],\n\t\t...(input.happyPath ? { happyPath: [...input.happyPath] } : {}),\n\t\tturns: compiled.turns,\n\t\tparamsCodec: input.paramsCodec,\n\t\tstateCodec: input.stateCodec,\n\t\tinitialState: input.initialState,\n\t\t...(input.runtime ? { runtime: { ...input.runtime } } : {}),\n\t\t...(input.resolveStorageSize ? { resolveStorageSize: input.resolveStorageSize } : {}),\n\t\t...(input.repositoryCredentials ? { repositoryCredentials: input.repositoryCredentials } : {}),\n\t\t...(input.piConfig ? { piConfig: input.piConfig } : {}),\n\t\tserver: compiled.server,\n\t\tworker: compiled.worker,\n\t\tui: input.ui,\n\t\tlaunchers: input.launchers,\n\t\twatchers: input.watchers,\n\t};\n\tmarkDefinedProcess(process);\n\treturn process;\n}\n\n/** @internal */\ntype RoutableTurnDefinition<TOutcome extends string, TParams, TState> =\n\t| LlmTurnDefinition<TOutcome, TParams, TState>\n\t| AutomaticTurnDefinition<TOutcome, TParams, TState>;\n\n// biome-ignore-start lint/suspicious/noExplicitAny: conditional helper types must match and preserve any routable turn instantiation\n/** @internal */\ntype RoutableOutcome<TTurn> =\n\tTTurn extends RoutableTurnDefinition<infer TOutcome, any, any> ? TOutcome : never;\n/** @internal */\ntype RoutableParams<TTurn> =\n\tTTurn extends RoutableTurnDefinition<any, infer TParams, any> ? TParams : never;\n/** @internal */\ntype RoutableState<TTurn> =\n\tTTurn extends RoutableTurnDefinition<any, any, infer TState> ? TState : never;\n\n/** @internal */\nexport function routeTurnOutcomes<TTurn extends RoutableTurnDefinition<string, any, any>>(\n\tbaseTurn: TTurn,\n\troutes: Partial<\n\t\tRecord<RoutableOutcome<TTurn>, OutcomeRouteSpec<RoutableParams<TTurn>, RoutableState<TTurn>>>\n\t>,\n\toptions: OutcomeRouteOptions = {},\n): TTurn {\n\ttype TOutcome = RoutableOutcome<TTurn>;\n\ttype TParams = RoutableParams<TTurn>;\n\ttype TState = RoutableState<TTurn>;\n\tconst baseOutcomes = (baseTurn.outcomes ?? {}) as Partial<\n\t\tRecord<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>\n\t>;\n\tfor (const outcomeId of Object.keys(routes) as TOutcome[]) {\n\t\tif (!baseOutcomes[outcomeId]) {\n\t\t\tthrow new Error(`Cannot route unknown outcome '${outcomeId}' on reusable turn`);\n\t\t}\n\t}\n\tif (options.strict) {\n\t\tfor (const outcomeId of Object.keys(baseOutcomes) as TOutcome[]) {\n\t\t\tif (!routes[outcomeId]) {\n\t\t\t\tthrow new Error(`Strict routing omitted outcome '${outcomeId}' on reusable turn`);\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\t...baseTurn,\n\t\toutcomes: Object.fromEntries(\n\t\t\t(\n\t\t\t\tObject.entries(baseOutcomes) as Array<[TOutcome, ProcessToolOutcomeSpec<TParams, TState>]>\n\t\t\t).map(([outcomeId, baseOutcome]) => [\n\t\t\t\toutcomeId,\n\t\t\t\t{ ...baseOutcome, ...(routes[outcomeId] ?? {}) },\n\t\t\t]),\n\t\t) as Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>,\n\t};\n}\n// biome-ignore-end lint/suspicious/noExplicitAny: end routable turn instantiation helper suppression\n\n/** @public */\nexport function llmTurn<TParams = unknown, TState = unknown, TOutcome extends string = string>(\n\tinput: Omit<LlmTurnDefinition<TOutcome, TParams, TState>, \"kind\">,\n): LlmTurnDefinition<TOutcome, TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"llm\",\n\t};\n}\n\n/** @internal */\nexport function automaticTurn<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n>(\n\tinput: Omit<AutomaticTurnDefinition<TOutcome, TParams, TState>, \"kind\">,\n): AutomaticTurnDefinition<TOutcome, TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"automatic\",\n\t};\n}\n\n/** @public */\nexport function humanTurn<TParams = unknown, TState = unknown>(\n\tinput: Omit<HumanTurnDefinition<TParams, TState>, \"kind\">,\n): HumanTurnDefinition<TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"human\",\n\t};\n}\n\n/** @internal */\nexport function externalTurn<TParams = unknown, TState = unknown>(\n\tinput: Omit<ExternalTurnDefinition<TParams, TState>, \"kind\">,\n): ExternalTurnDefinition<TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"external\",\n\t};\n}\n","import type { EventBus } from \"./types.js\";\n\n/** @internal */\nexport function createEventBus<\n\tTEventMap extends object = Record<string, unknown>,\n>(): EventBus<TEventMap> {\n\tconst listeners = new Map<string, Set<(data: unknown) => void | Promise<void>>>();\n\n\treturn {\n\t\temit(event, data) {\n\t\t\tconst handlers = listeners.get(event);\n\t\t\tif (!handlers) return;\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tvoid handler(data);\n\t\t\t\t} catch {\n\t\t\t\t\t// swallow handler errors to avoid breaking the emit loop\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\ton(event, handler) {\n\t\t\tconst typedHandler = handler as unknown as (data: unknown) => void | Promise<void>;\n\t\t\tlet set = listeners.get(event);\n\t\t\tif (!set) {\n\t\t\t\tset = new Set();\n\t\t\t\tlisteners.set(event, set);\n\t\t\t}\n\t\t\tset.add(typedHandler);\n\t\t},\n\n\t\toff(event, handler) {\n\t\t\tlisteners.get(event)?.delete(handler as unknown as (data: unknown) => void | Promise<void>);\n\t\t},\n\t};\n}\n","import type {\n\tActor,\n\tInputKind,\n\tInputSource,\n\tLaunchModelConfigInput,\n\tProcessCustomizableFields,\n\tProcessInputTarget,\n\tProcessInstance,\n\tProcessLifecycleStatus,\n\tProcessProject,\n\tProcessSemanticEntryRefKey,\n\tProcessTurnRecord,\n\tTurnId,\n\tTurnProgressReport,\n} from \"@leitwerk-dev/domain\";\nimport type { ExternalWrites } from \"@leitwerk-dev/external-writes\";\nimport type { WatcherPresentationField } from \"@leitwerk-dev/protocol\";\nimport type { CapabilityToken } from \"./capabilities.js\";\nimport type { FormDefinition } from \"./form-contract.js\";\n\nexport type { FormDefinition, FormFieldDefinition } from \"./form-contract.js\";\n\nimport type {\n\tLlmTurnDefinition,\n\tProcessEffectPlan,\n\tProcessLifecycleEffects,\n\tTurnDefinition,\n} from \"./define-process.js\";\nimport type {\n\tLauncherCardMetadata,\n\tLauncherFieldOptionDefinition,\n\tLauncherSchemaDefinition,\n\tLauncherValidationError,\n\tUiLauncherSummaryBase,\n} from \"./launcher-contract.js\";\nimport type { ModelProviderSet } from \"./model-provider.js\";\nimport type {\n\tServerExtensionEventMap,\n\tServerExtensionEventPayloadInputMap,\n} from \"./server-events.js\";\nimport type { ToolCallRendererDefinition } from \"./tool-renderers.js\";\nimport type {\n\tEventBus,\n\tPiTreeEntry,\n\tProcessActionPreviewDefinition,\n\tProcessActionSchedulingDefinition,\n\tProcessPiConfig,\n\tTurnOptions,\n} from \"./types.js\";\n\n/** @public */\nexport interface Codec<T> {\n\t/** @public */\n\tparse(value: unknown): T;\n\t/** @public */\n\tserialize(value: T): unknown;\n}\n\n/** @internal */\nexport interface LauncherModelProfileSummary {\n\t/** @internal */\n\treadonly id: string;\n\t/** @internal */\n\treadonly provider: string;\n\t/** @internal */\n\treadonly modelId: string;\n\t/** @internal */\n\treadonly thinkingLevel: string;\n}\n\n/** @public */\nexport interface LauncherContext {\n\t/** @internal */\n\treadonly process?: ProcessInstance;\n\t/** @internal */\n\treadonly projects?: readonly ProcessProject[];\n\t/**\n\t * Effective model profiles available to this launch path.\n\t * The server may filter this list per process (for example via process allowlists)\n\t * before invoking UI launcher or process watcher code.\n\t */\n\t/** @internal */\n\treadonly modelProfiles?: readonly LauncherModelProfileSummary[];\n}\n\n/** @public */\nexport type LauncherVisibility = \"ui\";\n\n/** @public */\nexport interface ProcessLaunchProjectConfig {\n\t/** @public */\n\tkey: string;\n\t/** @public */\n\trepoLocator: string;\n\t/** @public */\n\tbaseBranch: string;\n\t/** @public */\n\tworkBranch?: string | null;\n\t/** @public */\n\texternalId?: string | null;\n\t/** @public */\n\texternalUrl?: string | null;\n\t/** @public */\n\tmetadata?: Record<string, unknown> | null;\n}\n\n/** @public */\nexport interface ProcessTitleSourceField {\n\t/** Short label shown to the title-generation model, e.g. \"Prompt\" or \"Summary\". @public */\n\tlabel: string;\n\t/** Launcher-selected descriptive text to summarize into a short operator-facing title. @public */\n\tvalue: string;\n}\n\n/** @public */\nexport interface ProcessLaunchConfig<TParams = unknown> {\n\t/** @public */\n\tprocessId: string;\n\t/** @public */\n\tparams: TParams;\n\t/** @public */\n\tstartTurnId?: TurnId | null;\n\t/** Explicit operator-facing title. UI launches may override this with the built-in title input before persistence. @public */\n\ttitle?: string | null;\n\t/** Explicit launcher-selected fields for optional server-side title generation when title is blank. @public */\n\ttitleSourceFields?: readonly ProcessTitleSourceField[];\n\t/** @public */\n\texternalId?: string | null;\n\t/** @public */\n\texternalUrl?: string | null;\n\t/** @public */\n\tmetadata?: Record<string, unknown> | null;\n\t/** @internal */\n\tdefaultModelProfileId?: string | null;\n\t/** @internal */\n\tturnConfigs?: Record<\n\t\tstring,\n\t\t{\n\t\t\t/** @internal */\n\t\t\tmodelProfileId?: string | null;\n\t\t}\n\t>;\n\t/** Skill ids resolved to active immutable revisions before process creation. @internal */\n\tskillIds?: readonly string[];\n\t/** @public */\n\tprojects?: readonly ProcessLaunchProjectConfig[];\n}\n\n/** @public */\nexport type UiLauncherConfigResolution<TParams = unknown> =\n\t| {\n\t\t\t/** @public */\n\t\t\tok: true;\n\t\t\t/** @public */\n\t\t\tlaunchConfig: ProcessLaunchConfig<TParams>;\n\t }\n\t| {\n\t\t\t/** @public */\n\t\t\tok: false;\n\t\t\t/** @public */\n\t\t\terrors: readonly LauncherValidationError[];\n\t };\n\n/** @public */\nexport interface LaunchPreparationContext<TParams = unknown> {\n\t/** @public */\n\treadonly signal: AbortSignal;\n\t/** @public */\n\treadonly launchConfig: ProcessLaunchConfig<TParams>;\n\t/** @public */\n\treadonly logger: {\n\t\t/** @internal */\n\t\tinfo(message: string): void;\n\t\t/** @public */\n\t\twarn(message: string): void;\n\t};\n}\n\n/** @public */\nexport interface LaunchPreparationCheck<TParams = unknown> {\n\t/** @public */\n\treadonly id: string;\n\t/** @public */\n\treadonly label: string;\n\t/** @public */\n\trun(ctx: LaunchPreparationContext<TParams>): Promise<void>;\n}\n\n/** A launcher check may throw this error to expose bounded operator-safe remediation. @public */\nexport class SafeLaunchPreparationError extends Error {\n\t/** @public */\n\tconstructor(\n\t\tmessage: string,\n\t\t/** @internal */\n\t\treadonly safeSummary: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"SafeLaunchPreparationError\";\n\t}\n}\n\n/** @public */\nexport interface UiLauncherDefinition<TParams = unknown> {\n\t/** @public */\n\tcard: LauncherCardMetadata;\n\t/** @public */\n\tlaunchConfigSchema: LauncherSchemaDefinition;\n\t/** @public */\n\tresolveDefaults?(\n\t\tctx: LauncherContext,\n\t): Record<string, unknown> | Promise<Record<string, unknown>>;\n\t/** @public */\n\tresolveOptions?(\n\t\tinput: Record<string, unknown>,\n\t\tctx: LauncherContext,\n\t):\n\t\t| Record<string, readonly LauncherFieldOptionDefinition[]>\n\t\t| Promise<Record<string, readonly LauncherFieldOptionDefinition[]>>;\n\t/**\n\t * Convert persisted operator input into a new-launch draft. The default preserves\n\t * the complete input. Launchers override this only for values that must be rebuilt.\n\t */\n\t/** @public */\n\tresolveRelaunchInput?(\n\t\tpreviousInput: Record<string, unknown>,\n\t\tctx: LauncherContext,\n\t): Record<string, unknown> | Promise<Record<string, unknown>>;\n\t/** @public */\n\tpreparationChecks?(\n\t\tinput: Record<string, unknown>,\n\t\tlaunchConfig: ProcessLaunchConfig<TParams>,\n\t): readonly LaunchPreparationCheck<TParams>[];\n\t/** @public */\n\tresolveLaunchConfig(\n\t\tinput: Record<string, unknown>,\n\t\tctx: LauncherContext,\n\t): UiLauncherConfigResolution<TParams> | Promise<UiLauncherConfigResolution<TParams>>;\n}\n\n/** @public */\nexport interface ProcessWatcherPresentation {\n\t/** @public */\n\treadonly targetSummary: string;\n\t/** @public */\n\treadonly details?: readonly WatcherPresentationField[];\n}\n\n/** @public */\nexport interface ParsedProcessWatcherConfig<TConfig = unknown> {\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly enabled: boolean;\n\t/** @public */\n\treadonly launchModelConfig?: LaunchModelConfigInput;\n}\n\n/** A watcher source is defined and owned by the extension that implements it. @public */\nexport interface ProcessWatcherSource<TConfig = unknown, TEvent = unknown> {\n\t/** @public */\n\treadonly id: string;\n\t/** @public */\n\treadonly label: string;\n\t/** Type-only marker used to carry the provider event type across the source seam. @internal */\n\treadonly eventType?: TEvent;\n\t/** @public */\n\tparseConfig(raw: unknown): ParsedProcessWatcherConfig<TConfig>;\n\t/** @public */\n\tpresentConfig(config: TConfig): ProcessWatcherPresentation;\n}\n\n/** @public */\nexport interface ProcessWatcherDefinition<TParams = unknown, TEvent = unknown, TConfig = unknown> {\n\t/** @public */\n\tid: string;\n\t/** @public */\n\tlabel: string;\n\t/** @public */\n\tdescription: string;\n\t/** @public */\n\tsource: ProcessWatcherSource<TConfig, TEvent>;\n\t/** @internal */\n\tmatches?(event: TEvent, ctx: LauncherContext): boolean | Promise<boolean>;\n\t/** @public */\n\tpreparationChecks?(\n\t\tevent: TEvent,\n\t\tlaunchConfig: ProcessLaunchConfig<TParams>,\n\t): readonly LaunchPreparationCheck<TParams>[];\n\t/** @public */\n\tresolveLaunchConfig(\n\t\tevent: TEvent,\n\t\tctx: LauncherContext,\n\t): ProcessLaunchConfig<TParams> | Promise<ProcessLaunchConfig<TParams>>;\n}\n\n/** @public */\nexport interface ProcessLauncherDefinition<TParams = unknown> {\n\t/** @public */\n\tid: string;\n\t/** @public */\n\tlabel: string;\n\t/** @public */\n\tdescription: string;\n\t/** @public */\n\tvisibility: LauncherVisibility;\n\t/** @public */\n\tui: UiLauncherDefinition<TParams>;\n}\n\n/** @internal */\nexport interface ProcessLaunchPlanProcessInput extends ProcessCustomizableFields {\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tselectedTurnId: string | null;\n\t/** @internal */\n\tlifecycleStatus: ProcessLifecycleStatus;\n\t/** @internal */\n\tparamsJson: string | null;\n\t/** @internal */\n\tstateJson: string | null;\n}\n\n/** @internal */\nexport interface ProcessLaunchPlan {\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tprocessInput: ProcessLaunchPlanProcessInput;\n\t/** Optional server-owned idempotency key for cross-process handoffs. @internal */\n\thandoffDedupKey?: string | null;\n\t/** Carry-forward launcher-selected fields for optional server-side title generation. @internal */\n\ttitleSourceFields?: readonly ProcessTitleSourceField[];\n\t/** @internal */\n\tprojectInputs: readonly ProcessLaunchProjectConfig[];\n\t/** @internal */\n\tstartTurnId: TurnId | null;\n\t/** @internal */\n\tskillIds?: readonly string[];\n}\n\n/** @internal */\nexport interface ResolvedProcessLauncher<TParams = unknown> {\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tdisplayName: string;\n\t/** @internal */\n\tlaunchConfig: ProcessLaunchConfig<TParams>;\n\t/** @internal */\n\tlaunchPlan: ProcessLaunchPlan;\n}\n\n/** @internal */\nexport type UiLauncherResolutionResult<TParams = unknown> =\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: true;\n\t\t\t/** @internal */\n\t\t\tlauncher: ResolvedProcessLauncher<TParams>;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: false;\n\t\t\t/** @internal */\n\t\t\terrors: readonly LauncherValidationError[];\n\t };\n\n/** @internal */\nexport interface UiLauncherSummary extends UiLauncherSummaryBase {}\n\n/** @internal */\nexport interface ProcessLauncherService {\n\t/** @internal */\n\tlistUiLaunchers(): readonly UiLauncherSummary[];\n\t/** @internal */\n\tresolveUiDefaults(launcherId: string, ctx?: LauncherContext): Promise<Record<string, unknown>>;\n\t/** @internal */\n\tresolveUiOptions(\n\t\tlauncherId: string,\n\t\tinput: Record<string, unknown>,\n\t\tctx?: LauncherContext,\n\t): Promise<Record<string, readonly LauncherFieldOptionDefinition[]>>;\n\t/** @internal */\n\tresolveUiRelaunchInput(\n\t\tlauncherId: string,\n\t\tpreviousInput: Record<string, unknown>,\n\t\tctx?: LauncherContext,\n\t): Promise<Record<string, unknown>>;\n\t/** @internal */\n\tresolvePreparationChecks?(\n\t\tlauncherId: string,\n\t\tinput: Record<string, unknown>,\n\t\tlaunchConfig: ProcessLaunchConfig,\n\t): readonly LaunchPreparationCheck[];\n\t/** @internal */\n\tresolveUiLauncher(\n\t\tlauncherId: string,\n\t\tinput: Record<string, unknown>,\n\t\tctx?: LauncherContext,\n\t): Promise<UiLauncherResolutionResult>;\n}\n\n/** Resolve a UI launcher summary by id, returning `null` when it is unknown. @internal */\nexport function findUiLauncherById(\n\tlauncherService: Pick<ProcessLauncherService, \"listUiLaunchers\">,\n\tlauncherId: string,\n): UiLauncherSummary | null {\n\treturn launcherService.listUiLaunchers().find((launcher) => launcher.id === launcherId) ?? null;\n}\n\n/** @public */\nexport interface ProcessTurnOutcomeEvent {\n\t/** @internal */\n\tturnRecordId: string;\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\toutcome: string;\n\t/** @public */\n\tparams: Record<string, unknown>;\n\t/** @internal */\n\tturnResultMarkdown?: string | null;\n}\n\n/** @internal */\nexport type ProcessCleanupReason = \"abort\";\n\n/** @internal */\nexport interface ProcessCleanupResult<TState = unknown> extends ProcessLifecycleEffects {\n\t/** @internal */\n\tstate?: TState;\n}\n\n/** @internal */\nexport interface ProcessCleanupContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\treadonly reason: ProcessCleanupReason;\n}\n\n/** @internal */\nexport type ProcessCleanupHandler<TParams = unknown, TState = unknown> = (\n\tctx: ProcessCleanupContext<TParams, TState>,\n) => undefined | ProcessCleanupResult<TState> | Promise<ProcessCleanupResult<TState> | undefined>;\n\n/** @internal */\nexport interface LeafOutcomeCaptureContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\treadonly leaf: {\n\t\t/** @internal */\n\t\tentryId: string;\n\t\t/** @internal */\n\t\tturnRecordId: string | null;\n\t};\n\t/** @internal */\n\treadonly turnRecord: ProcessTurnRecord | null;\n\t/** @internal */\n\treadTreeEntry(entryId: string): PiTreeEntry | null;\n\t/** @internal */\n\treadLeafEntry(): PiTreeEntry | null;\n\t/** @internal */\n\treadTurnRecord(turnRecordId: string): ProcessTurnRecord | null;\n}\n\n/** @internal */\nexport interface LeafOutcomeCaptureResult {\n\t/** @internal */\n\trendererId: string;\n\t/** @internal */\n\tschemaVersion?: number;\n\t/** @internal */\n\tprops: Record<string, unknown>;\n\t/** @internal */\n\tfallbackMarkdown?: string | null;\n}\n\n/** @internal */\nexport interface ProcessLeafOutcomeDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\trendererId: string;\n\t/** @internal */\n\tcapture(\n\t\tctx: LeafOutcomeCaptureContext<TParams, TState>,\n\t): Promise<LeafOutcomeCaptureResult | null> | LeafOutcomeCaptureResult | null;\n}\n\n/** @internal */\nexport interface ProcessActionDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tform?: FormDefinition;\n\t/** @internal */\n\tpreview?: ProcessActionPreviewDefinition;\n\t/** @internal */\n\tscheduling?: ProcessActionSchedulingDefinition;\n\t/**\n\t * Explicitly marks an action as an immediate-only side-effect command. Such\n\t * actions must declare execute(...), cannot participate in pure preview or\n\t * scheduling flows, and are run only by immediate action execution.\n\t */\n\t/** @internal */\n\texecutionMode?: \"side_effect\";\n\t/**\n\t * Optional pure planner used for side-effect-free previews, scheduling validation,\n\t * and immediate execution. The shared server runtime collects the declared\n\t * transition/input/event plan from this hook without committing side effects\n\t * while the hook runs.\n\t */\n\t/** @internal */\n\tplan?(input: Record<string, unknown>, ctx: ServerProcessContext<TParams, TState>): Promise<void>;\n\t/**\n\t * Imperative hook for actions with executionMode: \"side_effect\". Use only for\n\t * immediate side effects that cannot be represented as a pure plan(...).\n\t */\n\t/** @internal */\n\texecute?(\n\t\tinput: Record<string, unknown>,\n\t\tctx: ServerProcessContext<TParams, TState>,\n\t): Promise<void>;\n}\n\n/** @internal */\nexport type ServerTransitionRuntime = \"reconcile\" | \"restart_worker\";\n\n/** @internal */\nexport interface ServerTransitionEffect {\n\t/**\n\t * Declares how the server runtime should handle the worker context after the\n\t * durable transition is committed.\n\t */\n\t/** @internal */\n\truntime?: ServerTransitionRuntime;\n}\n\n/** @internal */\nexport interface ServerTransitionRequest<TState = unknown> {\n\t/** @internal */\n\tlifecycleStatus?: ProcessLifecycleStatus;\n\t/** @internal */\n\tturnId?: TurnId | null;\n\t/** @internal */\n\tstate?: TState;\n\t/** State machine trigger for the selected-turn graph. @internal */\n\ttrigger?: string;\n\t/** @internal */\n\teffect?: ServerTransitionEffect;\n}\n\n/** @public */\nexport interface ProcessSnapshotContext<TParams = unknown, TState = unknown> {\n\t/** @public */\n\treadonly process: ProcessInstance;\n\t/** @public */\n\treadonly projects: readonly ProcessProject[];\n\t/** @public */\n\treadonly params: TParams;\n\t/** @public */\n\treadonly state: TState;\n}\n\n/** @public */\nexport type ExternalSourceInputMode = \"none\" | \"input\" | \"instruction\";\n\n/** @public */\nexport interface ExternalSourceResolveContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {}\n\n/** @public */\nexport interface ExternalSourceEffectContext<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends ProcessSnapshotContext<TParams, TState> {\n\t/** @public */\n\treadonly event: TEvent;\n\t/** @internal */\n\treadonly input: TInput;\n}\n\n/** @public */\nexport type ExternalSourceEffect<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> = (\n\tctx: ExternalSourceEffectContext<TParams, TState, TEvent, TInput>,\n) => ProcessEffectPlan<TState> | Promise<ProcessEffectPlan<TState> | undefined> | undefined;\n\n/** @public */\nexport interface ExternalEventDescription {\n\t/** @public */\n\tsummary: string;\n\t/** @internal */\n\tmarkdown?: string;\n\t/** @public */\n\tlinks?: import(\"@leitwerk-dev/domain\").TurnProgressLink[];\n}\n\n/** @public */\nexport interface ExternalActionSource<\n\tTParams = unknown,\n\tTState = unknown,\n\t_TEvent = unknown,\n\t_TInput extends Record<string, unknown> = Record<string, unknown>,\n> {\n\t/** @public */\n\tkind: string;\n\t/** @public */\n\tlabel?: string;\n\t/** @public */\n\tdescription?: string;\n\t/** Pure description captured when the event is consumed. @public */\n\tdescribeEvent?(event: _TEvent): ExternalEventDescription;\n\t/**\n\t * Extension-owned opaque config. Core may persist, hash, and display it, but must not\n\t * interpret provider-specific fields.\n\t */\n\t/** @public */\n\tconfig: unknown;\n\t/** Source-provided input behavior. Provider input is only published when the external action declares publishInput. @public */\n\tinputMode?: ExternalSourceInputMode;\n\t/** Optional extension-owned resolver for process-instance-specific matching. @public */\n\tresolve?(ctx: ExternalSourceResolveContext<TParams, TState>): unknown;\n}\n\n/** @public */\nexport interface ServerProcessContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\ttransition(next: ServerTransitionRequest<TState>): Promise<void>;\n\t/** @internal */\n\temitEvent<K extends keyof ServerExtensionEventMap & string>(\n\t\teventType: K,\n\t\tdata: ServerExtensionEventPayloadInputMap[K],\n\t): void;\n\t/**\n\t * Resolves non-empty turn-result markdown for the current semantic ref.\n\t * Returns `null` when the ref is unset or the referenced turn result does not\n\t * carry operator-facing markdown. Throws when persisted semantic-ref state is\n\t * malformed.\n\t */\n\t/** @internal */\n\treadSemanticTurnResultMarkdown(ref: ProcessSemanticEntryRefKey): string | null;\n\t/**\n\t * Resolves non-empty turn-result markdown for a process-defined published product.\n\t * Returns `null` when the product ref is unset or the referenced turn result does\n\t * not carry operator-facing markdown. Throws when persisted product-ref state is\n\t * malformed.\n\t */\n\t/** @internal */\n\treadProductTurnResultMarkdown(productName: string): string | null;\n\t/**\n\t * Queue durable process input for worker delivery.\n\t * Use `source: \"action_prompt\"` for action-originated follow-up prompts.\n\t * When `target` is set, the worker appends the input on the referenced\n\t * semantic or product branch before the next selected LLM turn continues from\n\t * that same branch. For `action_prompt` targeted follow-up reruns, that queued\n\t * input is the only new instruction: the worker does not replay the original\n\t * kickoff prompt.\n\t */\n\t/** @public */\n\tqueueInput(input: {\n\t\t/** @public */\n\t\tsource: InputSource;\n\t\t/** @public */\n\t\tkind: InputKind;\n\t\t/** @public */\n\t\tbodyMarkdown: string;\n\t\t/** @public */\n\t\ttarget?: ProcessInputTarget;\n\t}): void;\n\t/**\n\t * Internal SDK lifecycle-effect collector used by high-level process authoring\n\t * helpers. Raw process definitions should prefer intent helpers instead of\n\t * constructing these effects directly.\n\t */\n\t/** @internal */\n\tapplyLifecycleEffects?(effects: ProcessLifecycleEffects): void;\n}\n\n/** @public */\nexport interface WorkerProcessContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\treadonly turnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;\n\t/** @internal */\n\treadonly turnResultMarkdownByProduct?: Readonly<Record<string, string>>;\n\t/** Absolute workspace root for the current process instance, when available. @internal */\n\treadonly workspaceRoot?: string;\n\t/** Durable output produced by this LLM turn's preparation phase, when declared. @internal */\n\treadonly prepared?: unknown;\n\t/** Invoke a server-owned integration tool authorized for this automatic turn or LLM preparation. @internal */\n\tcallIntegrationTool?(name: string, args: Record<string, unknown>): Promise<unknown>;\n\t/** Replace the durable operator-facing progress report for this turn attempt. @internal */\n\treportProgress?(report: TurnProgressReport): void;\n}\n\n/** @public */\nexport interface WorkerCompleteInput<TOutcome extends string = string> {\n\t/** @internal */\n\toutcome: TOutcome;\n\t/** @internal */\n\tparams?: Record<string, unknown>;\n\t/** @internal */\n\tmarkdown?: string | null;\n\t/** @internal */\n\tresultSummary?: string;\n}\n\n/** @internal */\nexport interface WorkerRunHandle<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly ctx: WorkerProcessContext<TParams, TState>;\n\t/** @internal */\n\tturn<TOutcome extends string>(\n\t\tdef: LlmTurnDefinition<TOutcome, TParams, TState>,\n\t\toptions?: TurnOptions,\n\t): Promise<{\n\t\t/** @internal */\n\t\toutcome: TOutcome;\n\t\t/** @internal */\n\t\tparams: Record<string, unknown>;\n\t}>;\n\t/** @internal */\n\tcomplete<TOutcome extends string>(input: WorkerCompleteInput<TOutcome>): Promise<void>;\n\t/** @internal */\n\tpark(reason?: string): void;\n}\n\n/** @internal */\nexport type WorkerTurnHandler<TParams = unknown, TState = unknown> = (\n\trun: WorkerRunHandle<TParams, TState>,\n) => Promise<void>;\n\n/** @internal */\nexport interface ServerProcessAPI<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\taction(def: ProcessActionDefinition<TParams, TState>): void;\n\t/** @internal */\n\tonTurnOutcome(\n\t\tturnId: string,\n\t\thandler: (\n\t\t\tevent: ProcessTurnOutcomeEvent,\n\t\t\tctx: ServerProcessContext<TParams, TState>,\n\t\t) => void | Promise<void>,\n\t): void;\n\t/** @internal */\n\tonCleanup(handler: ProcessCleanupHandler<TParams, TState>): void;\n}\n\n/** @internal */\nexport interface WorkerProcessAPI<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tstart(turnId: TurnId): void;\n\t/** @internal */\n\tturn(turnId: TurnId, handler: WorkerTurnHandler<TParams, TState>): void;\n}\n\n/** @public */\nexport interface UiProcessAPI<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tleafOutcome(def: ProcessLeafOutcomeDefinition<TParams, TState>): void;\n}\n\n/** @public */\nexport interface ProcessLauncherAPI<TParams = unknown> {\n\t/** @public */\n\tlauncher(def: ProcessLauncherDefinition<TParams>): void;\n}\n\n/** @public */\nexport interface ProcessWatcherAPI<TParams = unknown> {\n\t/** @public */\n\twatcher<TEvent = unknown, TConfig = unknown>(\n\t\tdef: ProcessWatcherDefinition<TParams, TEvent, TConfig>,\n\t): void;\n}\n\n/** @public */\nexport interface ProcessTurnBinding<TTurn = TurnDefinition> {\n\t/** @public */\n\tdefinition: TTurn;\n}\n\n/** @public */\nexport type RepositoryCredentialKind = \"git_ssh\" | \"git_https\";\n\n/** Non-secret, code-defined repository authentication request. @public */\nexport interface RepositoryCredentialRequirement {\n\t/** @public */\n\treadonly projectKey: string;\n\t/** @public */\n\treadonly kind: RepositoryCredentialKind;\n\t/** @public */\n\treadonly credentialRef: string;\n}\n\n/** Project fields available while deriving repository credential requirements. @public */\nexport interface RepositoryCredentialProject {\n\t/** @internal */\n\treadonly key: string;\n\t/** @internal */\n\treadonly repoLocator: string;\n\t/** @internal */\n\treadonly baseBranch: string;\n\t/** @internal */\n\treadonly workBranch: string | null;\n}\n\n/** Secret material is intentionally restricted to server registration and worker.start. @internal */\nexport interface GitSshCredentialMaterial {\n\t/** @internal */\n\treadonly privateKey: string;\n\t/** @internal */\n\treadonly knownHosts: string;\n}\n\n/** @internal */\nexport interface GitHttpsCredentialMaterial {\n\t/** HTTPS origin authorized by the credential-owning extension. @internal */\n\treadonly origin: string;\n\t/** @internal */\n\treadonly username: string;\n\t/** @internal */\n\treadonly password: string;\n}\n\n/** @internal */\nexport type RepositoryCredentialProvider =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"git_ssh\";\n\t\t\t/** @internal */\n\t\t\tresolve(credentialRef: string): GitSshCredentialMaterial | null;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"git_https\";\n\t\t\t/** @internal */\n\t\t\tresolve(credentialRef: string): GitHttpsCredentialMaterial | null;\n\t };\n\n/** @internal */\nexport interface RepositoryCredentialRegistrar {\n\t/** @internal */\n\tregister(provider: RepositoryCredentialProvider): void;\n}\n\n/** @public */\nexport interface ProcessRuntimeCapabilities {\n\t/** Install repository-declared development tools with mise before accepting work. @internal */\n\treadonly developmentTools?: boolean;\n\t/** Require a Docker CLI connected to a private or explicitly acknowledged daemon. @public */\n\treadonly docker?: boolean;\n}\n\n/** @public */\nexport interface ExtensionProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tid: string;\n\t/** @public */\n\tdisplayName: string;\n\t/** Primary entry used when a launch does not select a start turn explicitly. @public */\n\tentryTurnId: TurnId;\n\t/** Additional entry turns that launchers may select explicitly. @public */\n\talternateEntryTurnIds?: readonly TurnId[];\n\t/**\n\t * Optional author-declared happy path: the ordered spine of turns a successful\n\t * run walks through. Flow diagrams render this as the main line and hang every\n\t * other turn off it as a branch. When omitted, consumers fall back to a derived\n\t * best-effort spine.\n\t */\n\t/** @public */\n\thappyPath?: readonly TurnId[];\n\t/** @public */\n\tturns: ReadonlyMap<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>;\n\t/** @public */\n\tparamsCodec: Codec<TParams>;\n\t/** @public */\n\tstateCodec: Codec<TState>;\n\t/** @public */\n\tinitialState(params: TParams): TState;\n\t/** Process-owned runtime capabilities. All capabilities default to disabled. @public */\n\truntime?: ProcessRuntimeCapabilities;\n\t/**\n\t * Server-only Kubernetes process-volume size, derived from extension configuration.\n\t * Explicit process storage_size wins; undefined uses the runner default.\n\t * Called before provisioning on worker starts. Must be synchronous and side-effect free;\n\t * repeated calls never resize or replace an existing volume.\n\t */\n\t/** @internal */\n\tresolveStorageSize?(input: {\n\t\t/** @internal */\n\t\tparams: TParams;\n\t\t/** @internal */\n\t\tprojects: readonly ProcessProject[];\n\t}): string | undefined;\n\t/** Runtime-only requirements; references are non-secret and remain in opaque params JSON. @public */\n\trepositoryCredentials?(input: {\n\t\t/** @public */\n\t\tparams: TParams;\n\t\t/** @public */\n\t\tprojects: readonly RepositoryCredentialProject[];\n\t}): readonly RepositoryCredentialRequirement[];\n\t/** @public */\n\tpiConfig?: ProcessPiConfig;\n\t/** @internal */\n\tserver?: (api: ServerProcessAPI<TParams, TState>) => void;\n\t/** @internal */\n\tworker?: (api: WorkerProcessAPI<TParams, TState>) => void;\n\t/** @public */\n\tui?: (api: UiProcessAPI<TParams, TState>) => void;\n\t/** @public */\n\tlaunchers?: (api: ProcessLauncherAPI<TParams>) => void;\n\t/** @public */\n\twatchers?: (api: ProcessWatcherAPI<TParams>) => void;\n}\n\n/** @public */\nexport interface CatalogExtensionAPI {\n\t/** @internal */\n\treadonly events: EventBus;\n\t/** @public */\n\tregisterProcess<TParams = unknown, TState = unknown>(\n\t\tdef: ExtensionProcessDefinition<TParams, TState>,\n\t): void;\n\t/** @internal */\n\tregisterToolRenderer(def: ToolCallRendererDefinition): void;\n\t/** @internal */\n\tprovide<T>(token: CapabilityToken<T>, value: T): void;\n\t/** @internal */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @internal */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n}\n\n/** @public */\nexport type ExtensionLifecycleHook = () => void | Promise<void>;\n\n/** @internal */\nexport interface ServerExtensionLogger {\n\t/** @internal */\n\tinfo?(payload: Record<string, unknown>, message?: string): void;\n\t/** @internal */\n\twarn?(payload: Record<string, unknown>, message?: string): void;\n\t/** @internal */\n\terror?(payload: Record<string, unknown>, message?: string): void;\n}\n\n/** @public */\nexport interface TicketCreationDestinationSummary {\n\t/** Adapter-owned opaque identifier. Browsers must not construct or interpret it. @public */\n\treadonly id: string;\n\t/** @public */\n\treadonly displayName: string;\n\t/** @public */\n\treadonly group?: string;\n\t/** @public */\n\treadonly description?: string;\n}\n\n/** @public */\nexport interface TicketCreationDestinationList {\n\t/** @public */\n\treadonly destinations: readonly TicketCreationDestinationSummary[];\n\t/** @public */\n\treadonly warnings?: readonly string[];\n}\n\n/** @public */\nexport interface TicketCreationDestinationSnapshot {\n\t/** @public */\n\treadonly summary: TicketCreationDestinationSummary;\n\t/** Adapter-owned, JSON-serializable immutable destination state. @public */\n\treadonly data: unknown;\n\t/** Untrusted destination context included in the ticket agent prompt. @public */\n\treadonly agentContext?: string;\n}\n\n/** @public */\nexport interface TicketCreationDestinationContext {\n\t/** @public */\n\treadonly actor: Actor;\n}\n\n/** @public */\nexport interface TicketCreationDestinationProvider {\n\t/** @public */\n\tlist(ctx: TicketCreationDestinationContext): Promise<TicketCreationDestinationList>;\n\t/** @public */\n\tresolve(\n\t\tctx: TicketCreationDestinationContext & {\n\t\t\t/** @public */\n\t\t\tdestinationId: string;\n\t\t},\n\t): Promise<TicketCreationDestinationSnapshot>;\n\t/** Rejects stale, renamed, transferred, or otherwise invalid snapshots. @public */\n\tvalidate(snapshot: TicketCreationDestinationSnapshot): Promise<void>;\n}\n\n/** @public */\nexport interface TicketCreationCapability {\n\t/** @public */\n\treadonly kind: \"ticket_creation\";\n\t/** @public */\n\treadonly displayName: string;\n\t/** Extension-owned process launched by the generic derived-ticket route. @public */\n\treadonly processId: string;\n\t/** Entry turn selected when the derived process starts. @public */\n\treadonly startTurnId: TurnId;\n\t/** RFC 6901 JSON Pointer into the tool arguments. @public */\n\treadonly titlePath?: string;\n\t/** RFC 6901 JSON Pointer into the tool arguments. @public */\n\treadonly descriptionPath?: string;\n\t/** @public */\n\treadonly destinations?: TicketCreationDestinationProvider;\n}\n\n/** @internal */\nexport interface TicketCreationReceipt {\n\t/** @internal */\n\treadonly externalId: string;\n\t/** @internal */\n\treadonly url: string;\n\t/** @internal */\n\treadonly result?: unknown;\n}\n\n/** @public */\nexport interface IntegrationToolExecutionContext {\n\t/** Process-bound coordination; storage remains server-owned. */\n\t/** @public */\n\treadonly externalWrites: ExternalWrites;\n\t/** @public */\n\treadonly process: ProcessInstance;\n\t/** @public */\n\treadonly projects: readonly ProcessProject[];\n\t/** @public */\n\treadonly turn: ProcessTurnRecord;\n\t/** @public */\n\treadonly project: ProcessProject | null;\n\t/** @public */\n\treadonly ticketDestination?: TicketCreationDestinationSnapshot;\n\t/** Stable for a single Pi tool call, including reconnect/replay. @public */\n\treadonly idempotencyKey: string;\n\t/** Aborted when the worker stops waiting for this tool call. @public */\n\treadonly signal: AbortSignal;\n}\n\n/** @public */\nexport interface IntegrationToolDefinition<TArgs = Record<string, unknown>> {\n\t/** @public */\n\treadonly name: string;\n\t/** @public */\n\treadonly description: string;\n\t/** @public */\n\treadonly parameters: Record<string, unknown>;\n\t/** Sanitized discovery metadata; credentials and adapter configuration never belong here. @public */\n\treadonly capability?: TicketCreationCapability;\n\t/** @internal */\n\tparse?(value: unknown): TArgs;\n\t/** @public */\n\texecute(ctx: IntegrationToolExecutionContext, args: TArgs): Promise<unknown>;\n}\n\n/** @public */\nexport interface ServerExtensionAPI {\n\t/** @internal */\n\treadonly events: EventBus<ServerExtensionEventMap>;\n\t/** @internal */\n\treadonly logger?: ServerExtensionLogger;\n\t/** @public */\n\tprovide<T>(token: CapabilityToken<T>, value: T): void;\n\t/** @public */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @public */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n\t/** @public */\n\ttool<TArgs>(definition: IntegrationToolDefinition<TArgs>): void;\n\t/** @internal */\n\tonStart(handler: ExtensionLifecycleHook): void;\n\t/** @public */\n\tonStop(handler: ExtensionLifecycleHook): void;\n}\n\n/** @internal */\nexport interface WorkerExtensionAPI {\n\t/** @internal */\n\treadonly events: EventBus;\n\t/** @internal */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @internal */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n}\n\n/** @public */\nexport interface LeitwerkExtensionModule {\n\t/** @public */\n\tmanifest: {\n\t\t/** @public */\n\t\tid: string;\n\t\t/** @public */\n\t\tversion: string;\n\t\t/** @public */\n\t\trequires?: readonly string[];\n\t\t/** @internal */\n\t\toptional?: readonly string[];\n\t};\n\t/** Resolves every provider owned by this extension before setupServer. @public */\n\tmodelProviders?: ModelProviderSet;\n\t/** @public */\n\tsetupCatalog?(api: CatalogExtensionAPI): void | Promise<void>;\n\t/** @public */\n\tsetupServer?(api: ServerExtensionAPI, config: unknown): void | Promise<void>;\n\t/** @internal */\n\tsetupWorker?(api: WorkerExtensionAPI, config: unknown): void | Promise<void>;\n}\n","import type { ExternalActionSource } from \"./extension-api.js\";\n\n/** Define a resolver-based source with no provider input. @public */\nexport function defineExternalActionSource<TConfig>(\n\tmetadata: Pick<ExternalActionSource, \"kind\" | \"label\" | \"description\" | \"describeEvent\">,\n) {\n\treturn function source<TParams, TState>(\n\t\tresolve: (ctx: {\n\t\t\t/** @public */\n\t\t\tparams: TParams;\n\t\t\t/** @public */\n\t\t\tstate: TState;\n\t\t}) => TConfig,\n\t): ExternalActionSource<TParams, TState> {\n\t\treturn { ...metadata, config: {}, inputMode: \"none\", resolve };\n\t};\n}\n","import type {\n\tExternalObservationInput,\n\tExternalSourceArmingLike,\n\tExternalSourceServiceLike,\n} from \"./core-capabilities.js\";\n\n/** @internal */\ntype Arming = Pick<ExternalSourceArmingLike, \"id\" | \"instanceId\" | \"generation\">;\n\n/** Report one poll's effects without choosing events, scheduling, or subscription policy. @internal */\nexport function createExternalSourcePollReporter(\n\tsources: ExternalSourceServiceLike,\n\tresult: {\n\t\t/** @internal */\n\t\tcreated: string[];\n\t\t/** @internal */\n\t\terrors: string[];\n\t},\n\toptions: {\n\t\t/** @internal */\n\t\tforwardGeneration?: boolean;\n\t} = {},\n) {\n\treturn {\n\t\t/** @internal */\n\t\tasync poll(kind: string, read: (armed: ExternalSourceArmingLike) => Promise<void>) {\n\t\t\tfor (const armed of sources.listArmed(kind)) {\n\t\t\t\ttry {\n\t\t\t\t\tawait read(armed);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tresult.errors.push(\n\t\t\t\t\t\t`${armed.id}:${error instanceof Error ? error.message : \"poll_failed\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** @internal */\n\t\tasync fire(armed: Arming, event: Record<string, unknown>, mergeKey: string): Promise<boolean> {\n\t\t\tconst fired = await sources.fire({\n\t\t\t\tinstanceId: armed.instanceId,\n\t\t\t\tarmingId: armed.id,\n\t\t\t\t...(options.forwardGeneration && armed.generation ? { generation: armed.generation } : {}),\n\t\t\t\tevent,\n\t\t\t\tmergeKey,\n\t\t\t});\n\t\t\tif (fired.ok) result.created.push(armed.id);\n\t\t\telse result.errors.push(`${armed.id}:fire_failed`);\n\t\t\treturn fired.ok;\n\t\t},\n\t\t/** @internal */\n\t\tobserve(armed: Arming, input: Pick<ExternalObservationInput, \"observation\" | \"refreshError\">) {\n\t\t\tif (sources.observe && armed.generation)\n\t\t\t\treturn sources.observe({\n\t\t\t\t\tinstanceId: armed.instanceId,\n\t\t\t\t\tarmingId: armed.id,\n\t\t\t\t\tgeneration: armed.generation,\n\t\t\t\t\t...input,\n\t\t\t\t});\n\t\t},\n\t};\n}\n","import path from \"node:path\";\nimport {\n\tassertValidProcessProductName,\n\thumanizeProcessLabel,\n\ttype ProcessInstance,\n\ttype ProcessProject,\n\ttype ProcessSemanticEntryRefKey,\n\ttype ProcessTurnStartSelection,\n\ttype ProcessTurnTerminalLifecycleStatus,\n\ttype TurnId,\n\ttype TurnProgressReport,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tAutomaticTurnDefinition,\n\tDefinedProcessInput,\n\tExternalTurnDefinition,\n\tHumanTurnDefinition,\n\tHumanTurnOperatorAttention,\n\tLlmModelPurpose,\n\tLlmTurnDefinition,\n\tProcessEffectPlan,\n\tProcessHumanTurnActionSpec,\n\tProcessHumanTurnExternalActionSpec,\n\tProcessOutcomeEffect,\n\tProcessOutcomeExecution,\n\tProcessRuntimeTurnContext,\n\tProcessToolOutcomeSpec,\n\tProcessTurnEndSpec,\n\tTurnDefinition,\n\tTurnDefinitionRecord,\n} from \"./define-process.js\";\nimport { defineProcess } from \"./define-process.js\";\nimport type {\n\tCodec,\n\tExtensionProcessDefinition,\n\tExternalActionSource,\n\tExternalSourceEffect,\n\tExternalSourceEffectContext,\n\tFormDefinition,\n\tProcessActionDefinition,\n\tProcessLauncherAPI,\n\tProcessLauncherDefinition,\n\tProcessWatcherAPI,\n\tProcessWatcherDefinition,\n\tServerProcessAPI,\n\tUiProcessAPI,\n\tWorkerCompleteInput,\n} from \"./extension-api.js\";\nimport { isPathInside } from \"./fs-utils.js\";\nimport {\n\ttype ProcessGraphSource,\n\ttoProcessGraphView,\n\tvalidateProcessGraphProducts,\n} from \"./process-graph.js\";\nimport type { OutcomeToolParameterSpec, PiBuiltInToolName, ProcessPiConfig } from \"./types.js\";\n\n/** @public */\ntype MaybePromise<T> = T | Promise<T>;\n\n/** @internal */\nexport const DEFAULT_PLAN_RESULT_OUTCOME_ID = \"plan_saved\" as const;\n/** @internal */\nexport const DEFAULT_FLOW_PRODUCT_NAME = \"default\" as const;\nconst ASSISTANT_OUTPUT_TURN_RESULT = { mode: \"assistant_output\", required: true } as const;\nconst OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME = \"markdown\" as const;\nconst OUTCOME_TOOL_ARGUMENT_TURN_RESULT = {\n\tmode: \"outcome_tool_argument\",\n\tparameterName: OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME,\n\trequired: true,\n} as const;\n\n/** @public */\nexport interface FlowLlmTurn<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: LlmTurnDefinition<TOutcome, TParams, TState>;\n}\n\n/** @public */\nexport interface FlowAutomaticTurn<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: AutomaticTurnDefinition<TOutcome, TParams, TState>;\n}\n\n/** @public */\nexport interface FlowHumanTurn<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: HumanTurnDefinition<TParams, TState>;\n}\n\n/** @public */\nexport interface FlowExternalTurn<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: ExternalTurnDefinition<TParams, TState>;\n}\n\n/** @public */\nexport type FlowTurn<TParams = unknown, TState = unknown> =\n\t| FlowLlmTurn<TParams, TState, string>\n\t| FlowAutomaticTurn<TParams, TState, string>\n\t| FlowHumanTurn<TParams, TState>\n\t| FlowExternalTurn<TParams, TState>\n\t| {\n\t\t\t/** @public */\n\t\t\tid: TurnId;\n\t\t\t/** @public */\n\t\t\tdefinition: TurnDefinition<TParams, TState>;\n\t };\n\n/** @internal */\nexport interface PlanFieldOptions {\n\t/** @internal */\n\tdescription?: string;\n\t/** @internal */\n\trequiredErrorCode?: string;\n}\n\n/** @internal */\nexport interface PlanAcceptanceCriteriaOptions extends PlanFieldOptions {\n\t/** @internal */\n\tminItems?: number;\n\t/** @internal */\n\tminItemsErrorCode?: string;\n}\n\nexport interface PlanSavedStateInput<TParams = unknown, TState = unknown> {\n\teffect: ProcessOutcomeEffect<TParams, TState>;\n}\n\n/** @public */\nexport interface FlowRepoContext {\n\t/** @internal */\n\tkey: string;\n\t/** @public */\n\tfsPath: string;\n\t/** @internal */\n\tworkspaceClonePath: string;\n\t/** @public */\n\tbaseBranch: string;\n\t/** @public */\n\tworkBranch: string;\n\t/** @internal */\n\tlocator: string;\n}\n\n/** @public */\nexport interface FlowRepoLookup {\n\t/** @public */\n\tget(key: string): FlowRepoContext;\n\t/** @internal */\n\toptional(key: string): FlowRepoContext | undefined;\n\t/** @internal */\n\tall(): FlowRepoContext[];\n}\n\n/** @public */\nexport type FlowPromptContext<\n\tTParams = unknown,\n\tTState = unknown,\n\tTConsumedProducts extends string = string,\n\tTPrepared = undefined,\n> = {\n\t/** @internal */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tprojects: readonly ProcessProject[];\n\t/** @public */\n\tparams: TParams;\n\t/** @public */\n\tstate: TState;\n\t/** @internal */\n\tworkspaceRoot?: string;\n\t/** @internal */\n\tprompts: {\n\t\t/** @internal */\n\t\tinitial: string;\n\t};\n\t/** @public */\n\tinput: Readonly<Partial<Record<TConsumedProducts, string>>>;\n\t/** @internal */\n\trepo: FlowRepoLookup;\n} & ([TPrepared] extends [undefined]\n\t? {\n\t\t\t/** @internal */\n\t\t\tprepared?: undefined;\n\t\t}\n\t: {\n\t\t\t/** @internal */\n\t\t\tprepared: TPrepared;\n\t\t});\n\n/** @public */\nexport interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tprocess: ProcessInstance;\n\t/** @public */\n\tprojects: readonly ProcessProject[];\n\t/** @public */\n\tparams: TParams;\n\t/** @public */\n\tstate: TState;\n\t/** @public */\n\tworkspaceRoot?: string;\n\t/** @public */\n\trepo: FlowRepoLookup;\n\t/** @public */\n\tcallIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;\n\t/** @public */\n\treportProgress(report: TurnProgressReport): void;\n}\n\n/** @public */\nexport type FlowLlmPreparationContext<\n\tTParams = unknown,\n\tTState = unknown,\n> = FlowAutomaticRunContext<TParams, TState>;\n\n/** @public */\ninterface FlowOutcomeEffectContext<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tprojects: readonly ProcessProject[];\n\t/** @internal */\n\tparams: TParams;\n\t/** @public */\n\tstate: TState;\n\t/** @internal */\n\toutput: {\n\t\t/** @internal */\n\t\tcontent: string | null;\n\t} | null;\n}\n\n/** @public */\nexport interface FlowLlmOutcomeEffectContext<TParams = unknown, TState = unknown>\n\textends FlowOutcomeEffectContext<TParams, TState> {}\n\n/** @public */\nexport interface FlowAutomaticOutcomeEffectContext<TParams = unknown, TState = unknown>\n\textends FlowOutcomeEffectContext<TParams, TState> {}\n\n/** @internal */\nexport interface FlowExternalSourceContext<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends ExternalSourceEffectContext<TParams, TState, TEvent, TInput> {}\n\n/** @public */\ntype FlowOutcomeEffectInput<TParams, TState, TContext> = {\n\t/** @public */\n\tctx: TContext;\n\t/** @public */\n\tevent: ProcessOutcomeExecution<TParams, TState>[\"event\"];\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\toutcome: string;\n};\n\n/** @public */\ntype FlowOutcomeEffect<TParams, TState, TContext> = (\n\tinput: FlowOutcomeEffectInput<TParams, TState, TContext>,\n) => MaybePromise<ProcessEffectPlan<TState> | undefined>;\n\n/** @public */\ntype FlowOutcomeStateEffect<TParams, TState, TContext> = (\n\tinput: FlowOutcomeEffectInput<TParams, TState, TContext>,\n) => MaybePromise<TState>;\n\nfunction textField(input: {\n\tdescription: string;\n\trequiredErrorCode: string;\n}): OutcomeToolParameterSpec {\n\treturn {\n\t\ttype: \"string\",\n\t\tdescription: input.description,\n\t\trequired: true,\n\t\trequiredErrorCode: input.requiredErrorCode,\n\t};\n}\n\nfunction stringArrayField(input: {\n\tdescription: string;\n\trequiredErrorCode: string;\n\tminItems: number;\n\tminItemsErrorCode: string;\n}): OutcomeToolParameterSpec {\n\treturn {\n\t\ttype: \"array\",\n\t\tdescription: input.description,\n\t\titems: { type: \"string\" },\n\t\trequired: true,\n\t\trequiredErrorCode: input.requiredErrorCode,\n\t\tminItems: input.minItems,\n\t\tminItemsErrorCode: input.minItemsErrorCode,\n\t};\n}\n\nfunction normalizeProductName(productName: string): string {\n\tassertValidProcessProductName(productName);\n\treturn productName;\n}\n\nfunction toRequiredErrorCode(name: string): string {\n\tconst snake = name\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n\t\t.replace(/[^a-zA-Z0-9]+/g, \"_\")\n\t\t.replace(/^_+|_+$/g, \"\")\n\t\t.toLowerCase();\n\treturn `${snake || \"value\"}_required`;\n}\n\nfunction readInitialPrompt<TParams>(params: TParams): string {\n\tif (typeof params === \"object\" && params !== null && \"prompt\" in params) {\n\t\tconst value = (params as { prompt?: unknown }).prompt;\n\t\tif (typeof value === \"string\") {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn \"\";\n}\n\nfunction safeJoinInside(parent: string, childPath: string, context: string): string {\n\tconst parentPath = path.resolve(parent);\n\tconst targetPath = path.resolve(parentPath, childPath);\n\tif (!isPathInside(parentPath, targetPath)) {\n\t\tthrow new Error(`${context} resolves outside '${parentPath}'`);\n\t}\n\treturn targetPath;\n}\n\nfunction toWorkspaceClonePath(relativePath: string): string {\n\treturn `./${relativePath.split(path.sep).join(\"/\")}`;\n}\n\nfunction resolveSafeProjectWorkspacePath(key: string): {\n\trelativePath: string;\n\tworkspaceClonePath: string;\n} {\n\tif (path.isAbsolute(key)) {\n\t\tthrow new Error(`Flow context project key '${key}' must be a relative workspace path`);\n\t}\n\tconst virtualWorkspaceRoot = path.resolve(path.sep, \"__leitwerk_process_workspace__\");\n\tconst virtualTarget = safeJoinInside(\n\t\tvirtualWorkspaceRoot,\n\t\tkey,\n\t\t`Flow context project key '${key}'`,\n\t);\n\tconst relativePath = path.relative(virtualWorkspaceRoot, virtualTarget);\n\treturn {\n\t\trelativePath,\n\t\tworkspaceClonePath: toWorkspaceClonePath(relativePath),\n\t};\n}\n\nfunction resolveRepoByKey(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n\tkey: string;\n\trequired: true;\n}): FlowRepoContext;\nfunction resolveRepoByKey(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n\tkey: string;\n\trequired: false;\n}): FlowRepoContext | undefined;\nfunction resolveRepoByKey(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n\tkey: string;\n\trequired: boolean;\n}): FlowRepoContext | undefined {\n\tconst requestedKey = input.key.trim();\n\tif (!requestedKey) {\n\t\tthrow new Error(\"Flow repo lookup requires a non-empty project key\");\n\t}\n\tconst matches = input.projects.filter((project) => project.key.trim() === requestedKey);\n\tif (matches.length === 0) {\n\t\tif (!input.required) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst availableKeys = input.projects\n\t\t\t.map((project) => project.key.trim())\n\t\t\t.filter((key) => key !== \"\")\n\t\t\t.join(\", \");\n\t\tthrow new Error(\n\t\t\t`Flow context requires project '${requestedKey}', but this process has no project with that key${\n\t\t\t\tavailableKeys ? ` (available: ${availableKeys})` : \"\"\n\t\t\t}`,\n\t\t);\n\t}\n\tif (matches.length > 1) {\n\t\tthrow new Error(`Flow context found duplicate project key '${requestedKey}'`);\n\t}\n\tconst project = matches[0];\n\tconst key = project.key.trim();\n\tif (!key) {\n\t\tthrow new Error(\"Flow context requires projects to have non-empty keys\");\n\t}\n\tconst baseBranch = project.baseBranch.trim();\n\tif (!baseBranch) {\n\t\tthrow new Error(`Flow context project '${key}' has no base branch`);\n\t}\n\tconst workBranch = (project.workBranch ?? project.baseBranch).trim();\n\tif (!workBranch) {\n\t\tthrow new Error(`Flow context project '${key}' has no work branch`);\n\t}\n\tconst workspacePath = resolveSafeProjectWorkspacePath(key);\n\treturn {\n\t\tkey,\n\t\tworkspaceClonePath: workspacePath.workspaceClonePath,\n\t\tfsPath:\n\t\t\ttypeof input.workspaceRoot === \"string\" && input.workspaceRoot.trim() !== \"\"\n\t\t\t\t? safeJoinInside(\n\t\t\t\t\t\tinput.workspaceRoot,\n\t\t\t\t\t\tworkspacePath.relativePath,\n\t\t\t\t\t\t`Flow context project '${key}' workspace path`,\n\t\t\t\t\t)\n\t\t\t\t: workspacePath.workspaceClonePath,\n\t\tbaseBranch,\n\t\tworkBranch,\n\t\tlocator: project.repoLocator,\n\t};\n}\n\nfunction createFlowRepoLookup(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n}): FlowRepoLookup {\n\treturn {\n\t\tget: (key) => resolveRepoByKey({ ...input, key, required: true }),\n\t\toptional: (key) => resolveRepoByKey({ ...input, key, required: false }),\n\t\tall: () =>\n\t\t\tinput.projects.map((project) =>\n\t\t\t\tresolveRepoByKey({ ...input, key: project.key, required: true }),\n\t\t\t),\n\t};\n}\n\nfunction createFlowContextBase<TParams, TState>(ctx: ProcessRuntimeTurnContext<TParams, TState>) {\n\tconst { process, projects, params, state, workspaceRoot } = ctx;\n\treturn {\n\t\tprocess,\n\t\tprojects,\n\t\tparams,\n\t\tstate,\n\t\t...(workspaceRoot ? { workspaceRoot } : {}),\n\t\trepo: createFlowRepoLookup({ projects, workspaceRoot }),\n\t};\n}\n\n/** @internal */\nexport function createFlowPromptContext<\n\tTParams,\n\tTState,\n\tTConsumedProducts extends string = string,\n\tTPrepared = undefined,\n>(\n\tctx: ProcessRuntimeTurnContext<TParams, TState>,\n\tconsumedProducts: readonly TConsumedProducts[],\n\toptionalConsumedProducts: readonly string[] = [],\n): FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> {\n\tconst productInput: Record<string, string> = {};\n\tfor (const productName of consumedProducts) {\n\t\tconst markdown = ctx.turnResultMarkdownByProduct?.[productName];\n\t\tif (typeof markdown !== \"string\" || markdown.trim() === \"\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Flow prompt context requires product '${productName}' markdown, but the worker payload did not provide it`,\n\t\t\t);\n\t\t}\n\t\tproductInput[productName] = markdown;\n\t}\n\tfor (const productName of optionalConsumedProducts) {\n\t\tif (productName in productInput) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst markdown = ctx.turnResultMarkdownByProduct?.[productName];\n\t\tif (typeof markdown === \"string\" && markdown.trim() !== \"\") {\n\t\t\tproductInput[productName] = markdown;\n\t\t}\n\t}\n\treturn {\n\t\t...createFlowContextBase(ctx),\n\t\tprompts: {\n\t\t\tinitial: readInitialPrompt(ctx.params),\n\t\t},\n\t\tinput: productInput as Partial<Record<TConsumedProducts, string>>,\n\t\tprepared: ctx.prepared as TPrepared,\n\t} as FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>;\n}\n\n/** @internal */\nexport function createFlowAutomaticRunContext<TParams, TState>(\n\tctx: ProcessRuntimeTurnContext<TParams, TState>,\n): FlowAutomaticRunContext<TParams, TState> {\n\treturn {\n\t\t...createFlowContextBase(ctx),\n\t\tcallIntegrationTool(name, args) {\n\t\t\tif (!ctx.callIntegrationTool) {\n\t\t\t\tthrow new Error(`Automatic integration tool '${name}' is unavailable`);\n\t\t\t}\n\t\t\treturn ctx.callIntegrationTool(name, args);\n\t\t},\n\t\treportProgress(report) {\n\t\t\tctx.reportProgress?.(report);\n\t\t},\n\t};\n}\n\nfunction wrapOutcomeCallback<TParams, TState, TResult>(\n\tcallback: (\n\t\tinput: FlowOutcomeEffectInput<TParams, TState, FlowOutcomeEffectContext<TParams, TState>>,\n\t) => TResult,\n): (execution: ProcessOutcomeExecution<TParams, TState>) => TResult {\n\treturn (execution) =>\n\t\tcallback({\n\t\t\tctx: {\n\t\t\t\tprocess: execution.ctx.process,\n\t\t\t\tprojects: execution.ctx.projects,\n\t\t\t\tparams: execution.ctx.params,\n\t\t\t\tstate: execution.ctx.state,\n\t\t\t\toutput:\n\t\t\t\t\ttypeof execution.event.turnResultMarkdown === \"string\"\n\t\t\t\t\t\t? { content: execution.event.turnResultMarkdown }\n\t\t\t\t\t\t: null,\n\t\t\t},\n\t\t\tevent: execution.event,\n\t\t\tturnId: execution.turnId,\n\t\t\toutcome: execution.outcome,\n\t\t});\n}\n\n/** @public */\nclass RouteAndEffectBuilder<TParams, TState, TContext> {\n\t/** @internal */\n\tprotected target: FlowTargetSpec = null;\n\t/** @internal */\n\tprotected flowEffect: FlowOutcomeEffect<TParams, TState, TContext> | undefined;\n\n\t/** @internal */\n\tprotected setTarget(next: FlowTargetSpec): this {\n\t\tif (this.target && next) {\n\t\t\tthrow new Error(\"Flow route already declares a target\");\n\t\t}\n\t\tthis.target = next;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\treturn this.setTarget({ kind: \"to\", turnId });\n\t}\n\n\t/** @public */\n\tcomplete(): this {\n\t\treturn this.setTarget({ kind: \"complete\" });\n\t}\n\n\t/** @public */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\treturn this.setTarget({ kind: \"lifecycleStatus\", status });\n\t}\n\n\t/** @internal */\n\tstay(): this {\n\t\tthis.target = null;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tstate(fn: FlowOutcomeStateEffect<TParams, TState, TContext>): this {\n\t\tthis.flowEffect = async (input) => ({ state: await fn(input) });\n\t\treturn this;\n\t}\n\n\t/** @public */\n\teffect(fn: FlowOutcomeEffect<TParams, TState, TContext>): this {\n\t\tthis.flowEffect = fn;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\thasRoute(): boolean {\n\t\treturn this.target !== null;\n\t}\n\n\t/** @internal */\n\tprotected buildRouteTarget(): {\n\t\t/** @internal */\n\t\tto?: TurnId;\n\t\t/** @internal */\n\t\tcomplete?: boolean;\n\t\t/** @internal */\n\t\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n\t} {\n\t\treturn buildRouteTargetSpec(this.target);\n\t}\n}\n\n/** @internal */\nexport type FlowTargetSpec =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"to\";\n\t\t\t/** @internal */\n\t\t\tturnId: TurnId;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"complete\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"lifecycleStatus\";\n\t\t\t/** @internal */\n\t\t\tstatus: ProcessTurnTerminalLifecycleStatus;\n\t }\n\t| null;\n\nexport function buildRouteTargetSpec(target: FlowTargetSpec): {\n\t/** @internal */\n\tto?: TurnId;\n\t/** @internal */\n\tcomplete?: boolean;\n\t/** @internal */\n\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n} {\n\tif (!target) {\n\t\treturn {};\n\t}\n\tif (target.kind === \"to\") {\n\t\treturn { to: target.turnId };\n\t}\n\tif (target.kind === \"complete\") {\n\t\treturn { complete: true };\n\t}\n\treturn { lifecycleStatus: target.status };\n}\n\n/** @public */\ninterface ParameterOptions extends Partial<Omit<OutcomeToolParameterSpec, \"type\" | \"description\">> {\n\t/** @public */\n\tdescription?: string;\n\t/** @internal */\n\trequiredErrorCode?: string;\n}\n\n/** @internal */\ninterface ArrayParameterOptions extends ParameterOptions {\n\t/** @internal */\n\titems?: OutcomeToolParameterSpec[\"items\"];\n}\n\n/** @internal */\ninterface EnumParameterOptions extends ParameterOptions {\n\t/** @internal */\n\tvalues?: readonly string[];\n}\n\n/** @public */\ninterface MarkdownParameterOptions extends ParameterOptions {\n\t/** @public */\n\tpublish?: true;\n}\n\nfunction isStringArray(value: unknown): value is readonly string[] {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/** @public */\nclass ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEffectBuilder<\n\tTParams,\n\tTState,\n\tTContext\n> {\n\t/** @internal */\n\tprotected outcomeDescription: string | null = null;\n\t/** @internal */\n\tprotected parameters: Record<string, OutcomeToolParameterSpec> = {};\n\t/** @internal */\n\tprotected publishedMarkdownParameter: string | null = null;\n\t/** @internal */\n\tprotected summaryParameter: string | null = null;\n\n\t/** Optional concise result publication, separate from the full Markdown. @public */\n\tresultSummary(name = \"resultSummary\"): this {\n\t\tthis.summaryParameter = name;\n\t\treturn this.parameter(name, {\n\t\t\ttype: \"string\",\n\t\t\tdescription: \"Concise summary of this attempt’s outcome.\",\n\t\t});\n\t}\n\n\t/** @internal */\n\tprotected publishedMarkdownFields() {\n\t\treturn this.publishedMarkdownParameter\n\t\t\t? {\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tpublishedProduct: this.publishedMarkdownParameter,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tturnResultMarkdownParameter: this.publishedMarkdownParameter,\n\t\t\t\t}\n\t\t\t: {};\n\t}\n\n\t/** @public */\n\tdescription(text: string): this {\n\t\tthis.outcomeDescription = text;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tparameter(name: string, spec: OutcomeToolParameterSpec): this {\n\t\tif (name.trim() === \"\") {\n\t\t\tthrow new Error(\"Outcome parameter name must be non-empty\");\n\t\t}\n\t\tthis.parameters[name] = {\n\t\t\t...spec,\n\t\t\tdescription: spec.description ?? \"\",\n\t\t};\n\t\treturn this;\n\t}\n\n\tprivate withRequired(\n\t\tname: string,\n\t\toptions: string | ParameterOptions,\n\t): ParameterOptions & { description?: string } {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\treturn {\n\t\t\t...resolved,\n\t\t\trequired: true,\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? toRequiredErrorCode(name),\n\t\t};\n\t}\n\n\tprivate typedParameter(\n\t\tname: string,\n\t\ttype: OutcomeToolParameterSpec[\"type\"],\n\t\toptions: string | ArrayParameterOptions = {},\n\t): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\treturn this.parameter(name, {\n\t\t\t...resolved,\n\t\t\ttype,\n\t\t\tdescription: resolved.description ?? \"\",\n\t\t\t...(type === \"array\" ? { items: resolved.items ?? { type: \"string\" } } : {}),\n\t\t});\n\t}\n\n\t/** @internal */\n\tstring(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"string\", options);\n\t}\n\n\t/** @public */\n\tmarkdown(name: string, options: string | MarkdownParameterOptions = {}): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\tconst { publish, ...parameterOptions } = resolved;\n\t\tif (publish) {\n\t\t\tif (this.publishedMarkdownParameter && this.publishedMarkdownParameter !== name) {\n\t\t\t\tthrow new Error(\"Outcome can publish only one markdown parameter\");\n\t\t\t}\n\t\t\tnormalizeProductName(name);\n\t\t\tthis.publishedMarkdownParameter = name;\n\t\t}\n\t\treturn this.typedParameter(name, \"string\", {\n\t\t\t...parameterOptions,\n\t\t\trequired: publish ? true : resolved.required,\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : undefined),\n\t\t});\n\t}\n\n\t/** @public */\n\trequiredString(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"string\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tnumber(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"number\", options);\n\t}\n\n\t/** @internal */\n\trequiredNumber(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"number\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tboolean(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"boolean\", options);\n\t}\n\n\t/** @internal */\n\trequiredBoolean(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"boolean\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tstringArray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"array\", options);\n\t}\n\n\t/** @internal */\n\trequiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"array\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tenum(name: string, valuesOrOptions: readonly string[] | EnumParameterOptions): this {\n\t\tconst resolved: EnumParameterOptions = isStringArray(valuesOrOptions)\n\t\t\t? { values: [...valuesOrOptions] }\n\t\t\t: valuesOrOptions;\n\t\tconst { values = [], ...options } = resolved;\n\t\treturn this.parameter(name, {\n\t\t\t...options,\n\t\t\ttype: \"string\",\n\t\t\tdescription: options.description ?? \"\",\n\t\t\tenum: [...values],\n\t\t});\n\t}\n\n\t/** @public */\n\tobject(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"object\", options);\n\t}\n\n\t/** @internal */\n\tarray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"array\", options);\n\t}\n}\n\n/** @public */\nexport class OutcomeToolBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n> extends ParameterizedOutcomeBuilder<\n\tTParams,\n\tTState,\n\tFlowLlmOutcomeEffectContext<TParams, TState>\n> {\n\tprivate stateRouting:\n\t\t| {\n\t\t\t\tbranches: Record<string, TurnId>;\n\t\t\t\tchoose: (\n\t\t\t\t\tinput: FlowOutcomeEffectInput<\n\t\t\t\t\t\tTParams,\n\t\t\t\t\t\tTState,\n\t\t\t\t\t\tFlowLlmOutcomeEffectContext<TParams, TState>\n\t\t\t\t\t>,\n\t\t\t\t) => MaybePromise<string>;\n\t\t }\n\t\t| undefined;\n\n\t/** @public */\n\trouteByState(\n\t\tbranches: Record<string, TurnId>,\n\t\tchoose: (\n\t\t\tinput: FlowOutcomeEffectInput<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>,\n\t\t) => MaybePromise<string>,\n\t): this {\n\t\tif (this.hasRoute() || this.stateRouting) {\n\t\t\tthrow new Error(\"State-routed outcome cannot declare another route\");\n\t\t}\n\t\tif (Object.keys(branches).length === 0) {\n\t\t\tthrow new Error(\"State-routed outcome must declare at least one branch\");\n\t\t}\n\t\tthis.stateRouting = { branches, choose };\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessToolOutcomeSpec<TParams, TState> {\n\t\tif (!this.outcomeDescription) {\n\t\t\tthrow new Error(\"LLM outcome tool must declare .description(...)\");\n\t\t}\n\t\tif (this.stateRouting && this.hasRoute()) {\n\t\t\tthrow new Error(\"State-routed outcome cannot declare another route\");\n\t\t}\n\t\tconst stateRouting = this.stateRouting;\n\t\treturn {\n\t\t\tdescription: this.outcomeDescription,\n\t\t\tparameters: this.parameters,\n\t\t\t...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),\n\t\t\t...this.publishedMarkdownFields(),\n\t\t\t...(stateRouting\n\t\t\t\t? {\n\t\t\t\t\t\tbranches: Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(stateRouting.branches).map(([branchId, turnId]) => [\n\t\t\t\t\t\t\t\tbranchId,\n\t\t\t\t\t\t\t\t{ to: turnId },\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tchoose: wrapOutcomeCallback((input) => stateRouting.choose(input)),\n\t\t\t\t\t}\n\t\t\t\t: this.buildRouteTarget()),\n\t\t\t...(this.flowEffect ? { effect: wrapOutcomeCallback(this.flowEffect) } : {}),\n\t\t};\n\t}\n}\n\n/** @public */\nexport class AutomaticOutcomeBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n> extends ParameterizedOutcomeBuilder<\n\tTParams,\n\tTState,\n\tFlowAutomaticOutcomeEffectContext<TParams, TState>\n> {\n\tprivate waits = false;\n\n\t/** @public */\n\twait(): this {\n\t\tif (this.hasRoute()) throw new Error(\"Waiting outcome cannot declare another route\");\n\t\tthis.waits = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessToolOutcomeSpec<TParams, TState> {\n\t\tif (!this.outcomeDescription) {\n\t\t\tthrow new Error(\"Automatic outcome must declare .description(...)\");\n\t\t}\n\t\tconst configuredEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;\n\t\tconst effect = this.waits\n\t\t\t? async (\n\t\t\t\t\texecution: Parameters<NonNullable<ProcessToolOutcomeSpec<TParams, TState>[\"effect\"]>>[0],\n\t\t\t\t) => {\n\t\t\t\t\tconst result = configuredEffect ? await configuredEffect(execution) : undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...result,\n\t\t\t\t\t\tprocessPatch: { ...(result?.processPatch ?? {}), lifecycleStatus: \"waiting\" as const },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t: configuredEffect;\n\t\treturn {\n\t\t\tdescription: this.outcomeDescription,\n\t\t\tparameters: this.parameters,\n\t\t\t...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),\n\t\t\t...this.publishedMarkdownFields(),\n\t\t\t...this.buildRouteTarget(),\n\t\t\t...(effect ? { effect } : {}),\n\t\t};\n\t}\n}\n\n/** @internal */\nexport class PlanResultBuilder<TParams = unknown, TState = unknown> extends RouteAndEffectBuilder<\n\tTParams,\n\tTState,\n\tFlowLlmOutcomeEffectContext<TParams, TState>\n> {\n\tprivate resultDescription = \"The candidate plan is ready for operator review\";\n\tprivate summarySpec: OutcomeToolParameterSpec | null = null;\n\tprivate acceptanceCriteriaSpec: OutcomeToolParameterSpec | null = null;\n\tprivate reviewTurnId: TurnId | null = null;\n\n\t/** @internal */\n\tdescription(text: string): this {\n\t\tthis.resultDescription = text;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tsummary(options: string | PlanFieldOptions = {}): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\tthis.summarySpec = textField({\n\t\t\tdescription: resolved.description ?? \"Short summary of the proposed plan\",\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? \"summary_required\",\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tacceptanceCriteria(options: string | PlanAcceptanceCriteriaOptions = {}): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\tthis.acceptanceCriteriaSpec = stringArrayField({\n\t\t\tdescription: resolved.description ?? \"Acceptance criteria for the requested change\",\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? \"acceptance_criteria_required\",\n\t\t\tminItems: resolved.minItems ?? 1,\n\t\t\tminItemsErrorCode: resolved.minItemsErrorCode ?? \"acceptance_criteria_required\",\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\treview(turnId: TurnId): this {\n\t\tthis.reviewTurnId = turnId;\n\t\treturn this.setTarget({ kind: \"to\", turnId });\n\t}\n\n\t/** @internal */\n\tbuildOutcome(): ProcessToolOutcomeSpec<TParams, TState> {\n\t\tif (!this.summarySpec) {\n\t\t\tthrow new Error(\"plan result must declare .summary(...)\");\n\t\t}\n\t\tif (!this.acceptanceCriteriaSpec) {\n\t\t\tthrow new Error(\"plan result must declare .acceptanceCriteria(...)\");\n\t\t}\n\t\tif (!this.reviewTurnId) {\n\t\t\tthrow new Error(\"plan result must declare .review(turnId)\");\n\t\t}\n\t\tconst stateEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;\n\t\treturn {\n\t\t\tdescription: this.resultDescription,\n\t\t\tparameters: {\n\t\t\t\tsummary: this.summarySpec,\n\t\t\t\tacceptanceCriteria: this.acceptanceCriteriaSpec,\n\t\t\t},\n\t\t\tto: this.reviewTurnId,\n\t\t\tlifecycleIntent: {\n\t\t\t\tkind: \"save_plan_result\",\n\t\t\t\tsummaryParam: \"summary\",\n\t\t\t\tacceptanceCriteriaParam: \"acceptanceCriteria\",\n\t\t\t\tplanMarkdownParam: \"planMarkdown\",\n\t\t\t\temitEventType: DEFAULT_PLAN_RESULT_OUTCOME_ID,\n\t\t\t\tbroadcastType: \"plan.updated\",\n\t\t\t\t...(stateEffect ? { state: stateEffect } : {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** @public */\nabstract class TurnEndBuilder<TParams, TState>\n\textends RouteAndEffectBuilder<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>\n\timplements FlowLlmTurn<TParams, TState, string>\n{\n\t/** @internal */\n\tprotected abstract readonly builderName: string;\n\n\t/** @internal */\n\tconstructor(\n\t\tprivate readonly outcomeId: string,\n\t\tprivate readonly parent?: FlowLlmTurn<TParams, TState, string>,\n\t) {\n\t\tsuper();\n\t}\n\n\tprivate get turn(): FlowLlmTurn<TParams, TState, string> {\n\t\tif (!this.parent) throw new Error(`${this.builderName} builder is not attached to a turn`);\n\t\treturn this.parent;\n\t}\n\n\t/** @internal */\n\tget id(): TurnId {\n\t\treturn this.turn.id;\n\t}\n\n\t/** @internal */\n\tget definition(): LlmTurnDefinition<string, TParams, TState> {\n\t\treturn this.turn.definition;\n\t}\n\n\t/** @internal */\n\tprotected buildResult(): ProcessTurnEndSpec<TParams, TState, string> {\n\t\tconst effect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;\n\t\treturn {\n\t\t\toutcome: this.outcomeId,\n\t\t\t...this.buildRouteTarget(),\n\t\t\t...(effect ? { effect } : {}),\n\t\t};\n\t}\n}\n\n/** @public */\nexport class PublishedResultBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<\n\tTParams,\n\tTState\n> {\n\t/** @internal */\n\tprotected readonly builderName = \"Published result\";\n\n\t/** @internal */\n\tbuildTurnEnd(): ProcessTurnEndSpec<TParams, TState, string> {\n\t\treturn this.buildResult();\n\t}\n}\n\n/** @public */\nexport class LlmTurnEndBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<\n\tTParams,\n\tTState\n> {\n\t/** @internal */\n\tprotected readonly builderName = \"LLM turn end\";\n\n\t/** @internal */\n\tconstructor(outcomeId: string, parent?: FlowLlmTurn<TParams, TState, string>) {\n\t\tsuper(outcomeId, parent);\n\t\tif (outcomeId.trim() === \"\") throw new Error(\"LLM turn end outcome must be non-empty\");\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessTurnEndSpec<TParams, TState, string> {\n\t\treturn this.buildResult();\n\t}\n}\n\n/** @public */\ntype LlmPromptBuilder<TParams, TState, TConsumedProducts extends string, TPrepared> = (\n\tctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>,\n) => MaybePromise<string>;\n\n/** @public */\nabstract class DescribedTurnBuilder {\n\t/** @internal */\n\tprotected turnDescription: string | null = null;\n\n\t/** @internal */\n\tconstructor(\n\t\t/** @internal */\n\t\tprotected readonly turnId: TurnId,\n\t) {}\n\n\t/** @internal */\n\tget id(): TurnId {\n\t\treturn this.turnId;\n\t}\n\n\t/** @public */\n\tdescription(description: string): this {\n\t\tthis.turnDescription = description;\n\t\treturn this;\n\t}\n}\n\n/** @public */\nexport class LlmFlowBuilder<\n\t\tTParams = unknown,\n\t\tTState = unknown,\n\t\tTConsumedProducts extends string = never,\n\t\tTPrepared = undefined,\n\t>\n\textends DescribedTurnBuilder\n\timplements FlowLlmTurn<TParams, TState, string>\n{\n\tprivate modelPurposeValue: LlmModelPurpose | undefined;\n\tprivate availableTools: readonly PiBuiltInToolName[] = [];\n\tprivate availableIntegrationTools: readonly string[] = [];\n\tprivate integrationToolResolver:\n\t\t| ((params: TParams, state: TState) => readonly string[])\n\t\t| undefined;\n\tprivate preparation:\n\t\t| ((ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<unknown>)\n\t\t| null = null;\n\tprivate promptBuilder:\n\t\t| ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>)\n\t\t| null = null;\n\tprivate branchType: LlmTurnDefinition<string, TParams, TState>[\"branchType\"] = \"primary\";\n\tprivate context: LlmTurnDefinition<string, TParams, TState>[\"context\"] = \"fresh\";\n\tprivate questionsEnabled = false;\n\tprivate startFrom: LlmTurnDefinition<string, TParams, TState>[\"startFrom\"] | undefined;\n\tprivate restorePrimaryLeafAfterTurn: boolean | undefined;\n\tprivate readonly consumedProductNames = new Set<string>();\n\tprivate readonly optionalConsumedProductNames = new Set<string>();\n\tprivate publishedResult: {\n\t\tproductName: string;\n\t\tbuilder: PublishedResultBuilder<TParams, TState>;\n\t} | null = null;\n\tprivate endResult: LlmTurnEndBuilder<TParams, TState> | null = null;\n\tprivate outcomeToolBuilders = new Map<string, OutcomeToolBuilder<TParams, TState>>();\n\n\t/** @internal */\n\tget definition(): LlmTurnDefinition<string, TParams, TState> {\n\t\treturn this.buildDefinition();\n\t}\n\n\t/** @internal */\n\tmodelPurpose(purpose: LlmModelPurpose): this {\n\t\tthis.modelPurposeValue = purpose;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\ttools(...tools: readonly PiBuiltInToolName[]): this {\n\t\tthis.availableTools = tools;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tintegrationTools(...tools: readonly string[]): this {\n\t\tthis.availableIntegrationTools = tools.map((tool) => tool.trim());\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tresolveIntegrationTools(resolver: (params: TParams, state: TState) => readonly string[]): this {\n\t\tthis.integrationToolResolver = resolver;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tprepare<TNextPrepared>(\n\t\tfn: (ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<TNextPrepared>,\n\t): LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared> {\n\t\tthis.preparation = fn;\n\t\treturn this as unknown as LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared>;\n\t}\n\n\t/** Enable durable operator questions for this LLM turn. @public */\n\taskQuestions(): this {\n\t\tthis.questionsEnabled = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tfreshPrimary(): this {\n\t\tthis.branchType = \"primary\";\n\t\tthis.context = \"fresh\";\n\t\tthis.startFrom = undefined;\n\t\tthis.restorePrimaryLeafAfterTurn = undefined;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tfreshSeededPrimary(): this {\n\t\tthis.branchType = \"primary\";\n\t\tthis.context = \"fresh_seeded\";\n\t\tthis.startFrom = undefined;\n\t\tthis.restorePrimaryLeafAfterTurn = undefined;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tfullPrimary(): this {\n\t\tthis.branchType = \"primary\";\n\t\tthis.context = \"full\";\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\trootBranchReview(): this {\n\t\tthis.branchType = \"root_branch\";\n\t\tthis.context = \"full\";\n\t\tthis.restorePrimaryLeafAfterTurn = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tcontinueFromPrimaryLeaf(): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"semantic_ref\",\n\t\t\tref: \"currentPrimaryPathLeaf\",\n\t\t\tfallback: { kind: \"current_leaf\" },\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcontinueFromReviewBranch(): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"semantic_ref\",\n\t\t\tref: \"review\",\n\t\t\tfallback: { kind: \"current_leaf\" },\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcontinueFromProductBranch(\n\t\tproductName: string,\n\t\tfallback: ProcessTurnStartSelection = { kind: \"current_leaf\" },\n\t): this {\n\t\treturn this.startFromProductBranch(productName, fallback);\n\t}\n\n\t/** @internal */\n\tstartFromReviewBranch(): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"semantic_ref\",\n\t\t\tref: \"review\",\n\t\t\tfallback: { kind: \"session_root\" },\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tstartFromProductBranch(\n\t\tproductName: string,\n\t\tfallback: ProcessTurnStartSelection = { kind: \"session_root\" },\n\t): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"product_ref\",\n\t\t\tproductName: normalizeProductName(productName),\n\t\t\tfallback,\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tstartFromRoot(): this {\n\t\tthis.startFrom = { kind: \"session_root\" };\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tconsume<TProductName extends string>(\n\t\tproductName: TProductName,\n\t): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {\n\t\tthis.consumedProductNames.add(normalizeProductName(productName));\n\t\treturn this as unknown as LlmFlowBuilder<\n\t\t\tTParams,\n\t\t\tTState,\n\t\t\tTConsumedProducts | TProductName,\n\t\t\tTPrepared\n\t\t>;\n\t}\n\n\t/** @public */\n\toptionalConsume<TProductName extends string>(\n\t\tproductName: TProductName,\n\t): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {\n\t\tthis.optionalConsumedProductNames.add(normalizeProductName(productName));\n\t\treturn this as unknown as LlmFlowBuilder<\n\t\t\tTParams,\n\t\t\tTState,\n\t\t\tTConsumedProducts | TProductName,\n\t\t\tTPrepared\n\t\t>;\n\t}\n\n\t/** @public */\n\tpublish(productName: string): PublishedResultBuilder<TParams, TState> {\n\t\tconst normalized = normalizeProductName(productName);\n\t\tif (this.publishedResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' can publish only one product in flow v1`);\n\t\t}\n\t\tif (this.endResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .publish(...) and .end(...)`);\n\t\t}\n\t\tconst builder = new PublishedResultBuilder<TParams, TState>(normalized, this);\n\t\tthis.publishedResult = { productName: normalized, builder };\n\t\treturn builder;\n\t}\n\n\t/** @public */\n\tend(outcomeId: string): LlmTurnEndBuilder<TParams, TState> {\n\t\tif (this.endResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares duplicate .end(...) completion`);\n\t\t}\n\t\tif (this.publishedResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .publish(...) and .end(...)`);\n\t\t}\n\t\tif (this.outcomeToolBuilders.size > 0) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .end(...) and outcome tools`);\n\t\t}\n\t\tthis.endResult = new LlmTurnEndBuilder<TParams, TState>(outcomeId, this);\n\t\treturn this.endResult;\n\t}\n\n\t/** @public */\n\tbuildPrompt(fn: LlmPromptBuilder<TParams, TState, TConsumedProducts, TPrepared>): this {\n\t\tthis.promptBuilder = (ctx) =>\n\t\t\tfn(\n\t\t\t\tcreateFlowPromptContext(ctx, [...this.consumedProductNames] as TConsumedProducts[], [\n\t\t\t\t\t...this.optionalConsumedProductNames,\n\t\t\t\t]),\n\t\t\t);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tprompt(prompt: (ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>): this {\n\t\tthis.promptBuilder = prompt;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\toutcomeTool(\n\t\tid: string,\n\t\tconfigure: (\n\t\t\ttool: OutcomeToolBuilder<TParams, TState>,\n\t\t) => OutcomeToolBuilder<TParams, TState> | undefined,\n\t): this {\n\t\tif (id.trim() === \"\") {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);\n\t\t}\n\t\tif (this.endResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .end(...) and outcome tools`);\n\t\t}\n\t\tif (this.publishedResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare outcome tools after .publish(...)`);\n\t\t}\n\t\tif (this.outcomeToolBuilders.has(id)) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);\n\t\t}\n\t\tconst builder = new OutcomeToolBuilder<TParams, TState>();\n\t\tconfigure(builder);\n\t\tthis.outcomeToolBuilders.set(id, builder);\n\t\treturn this;\n\t}\n\n\tprivate buildBaseDefinition() {\n\t\tif (!this.turnDescription) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' must declare .description(...)`);\n\t\t}\n\t\tconst prompt = this.promptBuilder;\n\t\tif (!prompt) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);\n\t\t}\n\t\tconst preparation = this.preparation;\n\t\treturn {\n\t\t\tkind: \"llm\" as const,\n\t\t\tdescription: this.turnDescription,\n\t\t\t...(this.modelPurposeValue ? { modelPurpose: this.modelPurposeValue } : {}),\n\t\t\tavailableTools: this.availableTools,\n\t\t\t...(this.availableIntegrationTools.length > 0\n\t\t\t\t? { integrationTools: this.availableIntegrationTools }\n\t\t\t\t: {}),\n\t\t\t...(this.integrationToolResolver\n\t\t\t\t? { resolveIntegrationTools: this.integrationToolResolver }\n\t\t\t\t: {}),\n\t\t\t...(this.questionsEnabled ? { askQuestions: true as const } : {}),\n\t\t\t...(preparation\n\t\t\t\t? {\n\t\t\t\t\t\tprepare: (ctx: ProcessRuntimeTurnContext<TParams, TState>) =>\n\t\t\t\t\t\t\tpreparation(createFlowAutomaticRunContext(ctx)),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tcompletionMode: \"turn_end\" as const,\n\t\t\tbranchType: this.branchType,\n\t\t\tcontext: this.context,\n\t\t\t...(this.startFrom ? { startFrom: this.startFrom } : {}),\n\t\t\t...(this.restorePrimaryLeafAfterTurn !== undefined\n\t\t\t\t? { restorePrimaryLeafAfterTurn: this.restorePrimaryLeafAfterTurn }\n\t\t\t\t: {}),\n\t\t\tprompt,\n\t\t};\n\t}\n\n\t/** @internal */\n\tproducesPlan(\n\t\tconfigure: (plan: PlanResultBuilder<TParams, TState>) => PlanResultBuilder<TParams, TState>,\n\t): FlowLlmTurn<TParams, TState, typeof DEFAULT_PLAN_RESULT_OUTCOME_ID> {\n\t\tconst definition = this.buildBaseDefinition();\n\t\tconst plan = configure(new PlanResultBuilder<TParams, TState>());\n\t\tconst outcome = plan.buildOutcome();\n\t\treturn {\n\t\t\tid: this.turnId,\n\t\t\tdefinition: {\n\t\t\t\t...definition,\n\t\t\t\toutcomes: {\n\t\t\t\t\t[DEFAULT_PLAN_RESULT_OUTCOME_ID]: outcome,\n\t\t\t\t},\n\t\t\t\tturnResultMarkdown: OUTCOME_TOOL_ARGUMENT_TURN_RESULT,\n\t\t\t\tresultSemanticRef: \"plan\",\n\t\t\t\tpublishedProduct: \"plan\",\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate buildDefinition(): LlmTurnDefinition<string, TParams, TState> {\n\t\tconst definition = this.buildBaseDefinition();\n\t\tconst hasOutcomeTools = this.outcomeToolBuilders.size > 0;\n\t\tconst explicitTurnEnd = this.endResult;\n\t\tconst published = this.publishedResult;\n\t\tconst outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};\n\t\tfor (const [outcomeId, builder] of this.outcomeToolBuilders) {\n\t\t\toutcomes[outcomeId] = builder.build();\n\t\t}\n\t\tconst outcomePublishedProducts = new Set(\n\t\t\tObject.values(outcomes)\n\t\t\t\t.map((outcome) => outcome.publishedProduct)\n\t\t\t\t.filter((productName): productName is string => typeof productName === \"string\"),\n\t\t);\n\t\tconst hasOutcomePublishedProduct = outcomePublishedProducts.size > 0;\n\t\tlet turnEnd: ProcessTurnEndSpec<TParams, TState, string> | undefined;\n\t\tlet resultSemanticRef: \"plan\" | \"review\" | undefined = outcomePublishedProducts.has(\"review\")\n\t\t\t? \"review\"\n\t\t\t: outcomePublishedProducts.has(\"plan\")\n\t\t\t\t? \"plan\"\n\t\t\t\t: undefined;\n\t\tlet turnResultMarkdown: LlmTurnDefinition<string, TParams, TState>[\"turnResultMarkdown\"];\n\t\tlet publishedProduct: string | undefined;\n\n\t\tif (published) {\n\t\t\tpublishedProduct = published.productName;\n\t\t\tif (published.productName === \"plan\") {\n\t\t\t\tresultSemanticRef = \"plan\";\n\t\t\t}\n\t\t\tif (published.productName === \"review\") {\n\t\t\t\tresultSemanticRef = \"review\";\n\t\t\t}\n\t\t\tconst publishHasRoute = published.builder.hasRoute();\n\t\t\tif (publishHasRoute && hasOutcomeTools) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`LLM turn '${this.turnId}' cannot route published product '${published.productName}' and declare outcome tools in flow v1`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (publishHasRoute && !hasOutcomeTools) {\n\t\t\t\tturnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;\n\t\t\t\tturnEnd = published.builder.buildTurnEnd();\n\t\t\t}\n\t\t\tif (!publishHasRoute && hasOutcomeTools) {\n\t\t\t\tturnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;\n\t\t\t}\n\t\t\tif (!publishHasRoute && !hasOutcomeTools) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`LLM turn '${this.turnId}' publishes product '${published.productName}' but declares no route or outcome tool completion path`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (hasOutcomeTools && !hasOutcomePublishedProduct) {\n\t\t\tturnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;\n\t\t} else if (explicitTurnEnd) {\n\t\t\tturnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;\n\t\t}\n\n\t\tif (hasOutcomeTools) {\n\t\t\tfor (const [outcomeId, outcome] of Object.entries(outcomes)) {\n\t\t\t\tif (OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME in outcome.parameters) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`LLM turn '${this.turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME}'`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (explicitTurnEnd) {\n\t\t\tif (turnEnd || Object.keys(outcomes).length > 0) {\n\t\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);\n\t\t\t}\n\t\t\tturnEnd = explicitTurnEnd.build();\n\t\t}\n\t\tif (Object.keys(outcomes).length === 0 && !turnEnd) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' must declare a completion path`);\n\t\t}\n\n\t\treturn {\n\t\t\t...definition,\n\t\t\t...(Object.keys(outcomes).length > 0 ? { outcomes } : {}),\n\t\t\t...(turnEnd ? { turnEnd } : {}),\n\t\t\t...(turnResultMarkdown ? { turnResultMarkdown } : {}),\n\t\t\t...(resultSemanticRef ? { resultSemanticRef } : {}),\n\t\t\t...(publishedProduct ? { publishedProduct } : {}),\n\t\t\t...(this.consumedProductNames.size > 0\n\t\t\t\t? { consumedProducts: [...this.consumedProductNames] }\n\t\t\t\t: {}),\n\t\t\t...(this.optionalConsumedProductNames.size > 0\n\t\t\t\t? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }\n\t\t\t\t: {}),\n\t\t};\n\t}\n}\n\ntype StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<\n\tTParams,\n\tTState,\n\tunknown,\n\tRecord<string, unknown>\n>;\n\n/** @public */\nabstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {\n\t/** @internal */\n\tprotected abstract readonly turnKind: \"Automatic\" | \"Human\";\n\tprivate externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();\n\n\t/** @public */\n\texternalAction<\n\t\tTEvent = unknown,\n\t\tTInput extends Record<string, unknown> = Record<string, unknown>,\n\t>(\n\t\texternalActionId: string,\n\t\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>,\n\t\tconfigure: (\n\t\t\texternal: ExternalActionBuilder<TParams, TState, TEvent, TInput>,\n\t\t) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,\n\t): this {\n\t\tif (this.externalActionBuilders.has(externalActionId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,\n\t\t\t);\n\t\t}\n\t\tconst builder = new ExternalActionBuilder(externalActionId, source);\n\t\tconfigure(builder);\n\t\tthis.externalActionBuilders.set(\n\t\t\texternalActionId,\n\t\t\tbuilder as unknown as StoredExternalActionBuilder<TParams, TState>,\n\t\t);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tprotected buildExternalActions():\n\t\t| Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>\n\t\t| undefined {\n\t\treturn this.externalActionBuilders.size > 0\n\t\t\t? Object.fromEntries(\n\t\t\t\t\t[...this.externalActionBuilders].map(([id, builder]) => [id, builder.build()]),\n\t\t\t\t)\n\t\t\t: undefined;\n\t}\n}\n\n/** @public */\nexport class AutomaticFlowBuilder<TParams = unknown, TState = unknown>\n\textends ExternalActionTurnBuilder<TParams, TState>\n\timplements FlowAutomaticTurn<TParams, TState, string>\n{\n\t/** @internal */\n\tprotected readonly turnKind = \"Automatic\";\n\tprivate runFn:\n\t\t| ((ctx: FlowAutomaticRunContext<TParams, TState>) => MaybePromise<WorkerCompleteInput<string>>)\n\t\t| null = null;\n\tprivate outcomeBuilders = new Map<string, AutomaticOutcomeBuilder<TParams, TState>>();\n\tprivate availableIntegrationTools: readonly string[] = [];\n\n\t/** @internal */\n\tget definition(): AutomaticTurnDefinition<string, TParams, TState> {\n\t\treturn this.buildDefinition();\n\t}\n\n\t/** @public */\n\trun(\n\t\tfn: (\n\t\t\tctx: FlowAutomaticRunContext<TParams, TState>,\n\t\t) => MaybePromise<WorkerCompleteInput<string>>,\n\t): this {\n\t\tthis.runFn = fn;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tintegrationTools(...tools: readonly string[]): this {\n\t\tthis.availableIntegrationTools = tools.map((tool) => tool.trim());\n\t\treturn this;\n\t}\n\n\t/** @public */\n\toutcome(\n\t\tid: string,\n\t\tconfigure: (\n\t\t\toutcome: AutomaticOutcomeBuilder<TParams, TState>,\n\t\t) => AutomaticOutcomeBuilder<TParams, TState> | undefined,\n\t): this {\n\t\tif (id.trim() === \"\") {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' declares an empty outcome id`);\n\t\t}\n\t\tif (this.outcomeBuilders.has(id)) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' declares duplicate outcome '${id}'`);\n\t\t}\n\t\tconst builder = new AutomaticOutcomeBuilder<TParams, TState>();\n\t\tconfigure(builder);\n\t\tthis.outcomeBuilders.set(id, builder);\n\t\treturn this;\n\t}\n\n\tprivate buildDefinition(): AutomaticTurnDefinition<string, TParams, TState> {\n\t\tif (!this.turnDescription) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);\n\t\t}\n\t\tif (!this.runFn) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' must declare .run(...)`);\n\t\t}\n\t\tif (this.outcomeBuilders.size === 0) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);\n\t\t}\n\t\tconst outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};\n\t\tfor (const [outcomeId, builder] of this.outcomeBuilders) {\n\t\t\toutcomes[outcomeId] = builder.build();\n\t\t}\n\t\tconst runFn = this.runFn;\n\t\tconst externalActions = this.buildExternalActions();\n\t\treturn {\n\t\t\tkind: \"automatic\",\n\t\t\tdescription: this.turnDescription,\n\t\t\t...(this.availableIntegrationTools.length > 0\n\t\t\t\t? { integrationTools: this.availableIntegrationTools }\n\t\t\t\t: {}),\n\t\t\t...(externalActions ? { externalActions } : {}),\n\t\t\toutcomes,\n\t\t\trun: (ctx) => runFn(createFlowAutomaticRunContext(ctx)),\n\t\t};\n\t}\n}\n\nfunction inferAcceptanceState(actionId: string): ProcessHumanTurnActionSpec[\"acceptanceState\"] {\n\tconst normalized = actionId.toLowerCase();\n\tif (/approve|accept|complete|merged/.test(normalized)) {\n\t\treturn \"accepted\";\n\t}\n\tif (/request|revision|feedback|change|reject/.test(normalized)) {\n\t\treturn \"requires_changes\";\n\t}\n\treturn \"neutral\";\n}\n\n/** @public */\nexport class HumanActionBuilder<TParams = unknown, TState = unknown> {\n\tprivate spec: Record<string, unknown> = {};\n\n\t/** @internal */\n\tconstructor(private readonly actionId: string) {}\n\n\t/** @public */\n\tlabel(label: string): this {\n\t\tthis.spec.label = label;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tdescription(description: string): this {\n\t\tthis.spec.description = description;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tacceptanceState(state: ProcessHumanTurnActionSpec<TParams, TState>[\"acceptanceState\"]): this {\n\t\tthis.spec.acceptanceState = state;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tform(form: FormDefinition): this {\n\t\tthis.spec.form = form;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\tthis.spec.to = turnId;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcomplete(): this {\n\t\tthis.spec.complete = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\tthis.spec.lifecycleStatus = status;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\ttrigger(trigger: string): this {\n\t\tthis.spec.trigger = trigger;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tschedulable(value = true): this {\n\t\tthis.spec.schedulable = value;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\teffect(effect: ProcessHumanTurnActionSpec<TParams, TState>[\"effect\"]): this {\n\t\tthis.spec.effect = effect;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessHumanTurnActionSpec<TParams, TState> {\n\t\treturn {\n\t\t\tlabel:\n\t\t\t\ttypeof this.spec.label === \"string\" ? this.spec.label : humanizeProcessLabel(this.actionId),\n\t\t\tacceptanceState:\n\t\t\t\t(this.spec.acceptanceState as\n\t\t\t\t\t| ProcessHumanTurnActionSpec<TParams, TState>[\"acceptanceState\"]\n\t\t\t\t\t| undefined) ?? inferAcceptanceState(this.actionId),\n\t\t\t...this.spec,\n\t\t} as ProcessHumanTurnActionSpec<TParams, TState>;\n\t}\n}\n\n/** @public */\nexport class ExternalActionBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> {\n\tprivate spec: Partial<ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput>>;\n\n\t/** @internal */\n\tconstructor(actionId: string, source: ExternalActionSource<TParams, TState, TEvent, TInput>) {\n\t\tthis.spec = { id: actionId, source };\n\t}\n\n\t/** @public */\n\tlabel(label: string): this {\n\t\tthis.spec.label = label;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tdescription(description: string): this {\n\t\tthis.spec.description = description;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\twhen(condition: NonNullable<ProcessHumanTurnExternalActionSpec<TParams, TState>[\"when\"]>): this {\n\t\tthis.spec.when = condition;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\tthis.spec.to = turnId;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcomplete(): this {\n\t\tthis.spec.complete = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\tthis.spec.lifecycleStatus = status;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tpublishInput(\n\t\tproductName: string,\n\t\toptions: {\n\t\t\t/** @internal */\n\t\t\tinputField: string;\n\t\t},\n\t): this {\n\t\tthis.spec.publishInput = {\n\t\t\tproductName: normalizeProductName(productName),\n\t\t\tinputField: options.inputField,\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @public */\n\teffect(effect: ExternalSourceEffect<TParams, TState, TEvent, TInput>): this {\n\t\tthis.spec.effect = effect;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput> {\n\t\treturn this.spec as ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput>;\n\t}\n}\n\n/** @public */\nexport class HumanFlowBuilder<TParams = unknown, TState = unknown>\n\textends ExternalActionTurnBuilder<TParams, TState>\n\timplements FlowHumanTurn<TParams, TState>\n{\n\t/** @internal */\n\tprotected readonly turnKind = \"Human\";\n\tprivate reviewProductName: string | undefined;\n\tprivate reviewSemanticRef: ProcessSemanticEntryRefKey | undefined;\n\tprivate operatorAttentionValue: HumanTurnOperatorAttention | undefined;\n\tprivate turnCommentary: string | undefined;\n\tprivate notes: HumanTurnDefinition<TParams, TState>[\"notesFields\"] | undefined;\n\tprivate actions = new Map<string, HumanActionBuilder<TParams, TState>>();\n\n\t/** @public */\n\tget definition(): HumanTurnDefinition<TParams, TState> {\n\t\tif (!this.turnDescription) {\n\t\t\tthrow new Error(`Human turn '${this.turnId}' must declare .description(...)`);\n\t\t}\n\t\tconst externalActions = this.buildExternalActions();\n\t\treturn {\n\t\t\tkind: \"human\",\n\t\t\tdescription: this.turnDescription,\n\t\t\t...(this.reviewProductName ? { reviewProduct: this.reviewProductName } : {}),\n\t\t\t...(this.reviewSemanticRef ? { reviewSemanticRef: this.reviewSemanticRef } : {}),\n\t\t\t...(this.operatorAttentionValue ? { operatorAttention: this.operatorAttentionValue } : {}),\n\t\t\t...(this.notes ? { notesFields: this.notes } : {}),\n\t\t\t...(this.turnCommentary ? { commentary: this.turnCommentary } : {}),\n\t\t\tactions: Object.fromEntries(\n\t\t\t\t[...this.actions.entries()].map(([actionId, builder]) => [actionId, builder.build()]),\n\t\t\t),\n\t\t\t...(externalActions ? { externalActions } : {}),\n\t\t};\n\t}\n\n\t/** @public */\n\treviewProduct(productName: string): this {\n\t\tconst normalized = normalizeProductName(productName);\n\t\tthis.reviewProductName = normalized;\n\t\tthis.reviewSemanticRef =\n\t\t\tnormalized === \"plan\" ? \"plan\" : normalized === \"review\" ? \"review\" : undefined;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\toperatorAttention(attention: HumanTurnOperatorAttention): this {\n\t\tthis.operatorAttentionValue = attention;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcommentary(commentary: string): this {\n\t\tthis.turnCommentary = commentary;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tnotesFields(notes: HumanTurnDefinition<TParams, TState>[\"notesFields\"]): this {\n\t\tthis.notes = notes;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\taction(\n\t\tactionId: string,\n\t\tconfigure: (\n\t\t\taction: HumanActionBuilder<TParams, TState>,\n\t\t) => HumanActionBuilder<TParams, TState> | undefined,\n\t): this {\n\t\tif (this.actions.has(actionId)) {\n\t\t\tthrow new Error(`Human turn '${this.turnId}' declares duplicate action '${actionId}'`);\n\t\t}\n\t\tconst builder = new HumanActionBuilder<TParams, TState>(actionId);\n\t\tconfigure(builder);\n\t\tthis.actions.set(actionId, builder);\n\t\treturn this;\n\t}\n}\n\n/** @public */\nexport class ExternalRouteBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> implements FlowExternalTurn<TParams, TState>\n{\n\tprivate externalEffect: ExternalSourceEffect<TParams, TState, TEvent, TInput> | undefined;\n\tprivate target: FlowTargetSpec = null;\n\t/** @internal */\n\tconstructor(\n\t\tprivate readonly parent: ExternalFlowBuilder<TParams, TState>,\n\t\tprivate readonly source: ExternalActionSource<TParams, TState, TEvent, TInput>,\n\t) {}\n\n\t/** @internal */\n\tget id(): TurnId {\n\t\treturn this.parent.id;\n\t}\n\n\t/** @internal */\n\tget definition(): ExternalTurnDefinition<TParams, TState> {\n\t\treturn this.parent.definition;\n\t}\n\n\tprivate setTarget(next: Exclude<FlowTargetSpec, null>): this {\n\t\tif (this.target) {\n\t\t\tthrow new Error(\"External source route already declares a target\");\n\t\t}\n\t\tthis.target = next;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\treturn this.setTarget({ kind: \"to\", turnId });\n\t}\n\n\t/** @internal */\n\tcomplete(): this {\n\t\treturn this.setTarget({ kind: \"complete\" });\n\t}\n\n\t/** @internal */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\treturn this.setTarget({ kind: \"lifecycleStatus\", status });\n\t}\n\n\t/** @internal */\n\tstate(\n\t\tfn: (input: {\n\t\t\t/** @internal */\n\t\t\tctx: FlowExternalSourceContext<TParams, TState, TEvent, TInput>;\n\t\t\t/** @internal */\n\t\t\tevent: TEvent;\n\t\t\t/** @internal */\n\t\t\tinput: TInput;\n\t\t}) => MaybePromise<TState>,\n\t): this {\n\t\tthis.externalEffect = async (ctx) => ({\n\t\t\tstate: await fn({ ctx, event: ctx.event, input: ctx.input }),\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\teffect(\n\t\tfn: (input: {\n\t\t\t/** @internal */\n\t\t\tctx: FlowExternalSourceContext<TParams, TState, TEvent, TInput>;\n\t\t\t/** @internal */\n\t\t\tevent: TEvent;\n\t\t\t/** @internal */\n\t\t\tinput: TInput;\n\t\t}) => MaybePromise<ProcessEffectPlan<TState> | undefined>,\n\t): this {\n\t\tthis.externalEffect = (ctx) => fn({ ctx, event: ctx.event, input: ctx.input });\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild() {\n\t\treturn {\n\t\t\t/** @internal */\n\t\t\tsource: this.source,\n\t\t\t...buildRouteTargetSpec(this.target),\n\t\t\t...(this.externalEffect\n\t\t\t\t? {\n\t\t\t\t\t\t/** @internal */\n\t\t\t\t\t\teffect: this.externalEffect,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n}\n\n/** @public */\nexport class ExternalFlowBuilder<TParams = unknown, TState = unknown>\n\textends DescribedTurnBuilder\n\timplements FlowExternalTurn<TParams, TState>\n{\n\tprivate routeBuilders: ExternalRouteBuilder<TParams, TState, unknown, Record<string, unknown>>[] =\n\t\t[];\n\n\t/** @internal */\n\tget definition(): ExternalTurnDefinition<TParams, TState> {\n\t\tif (!this.turnDescription) {\n\t\t\tthis.turnDescription =\n\t\t\t\tthis.routeBuilders[0]?.build().source.description ?? \"Wait for an external source\";\n\t\t}\n\t\tif (this.routeBuilders.length === 0) {\n\t\t\tthrow new Error(`External turn '${this.turnId}' must declare at least one .from(...) source`);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"external\",\n\t\t\tdescription: this.turnDescription,\n\t\t\ttransitions: this.routeBuilders.map((builder) => builder.build()),\n\t\t};\n\t}\n\n\t/** @public */\n\tfrom<TEvent = unknown, TInput extends Record<string, unknown> = Record<string, unknown>>(\n\t\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>,\n\t): ExternalRouteBuilder<TParams, TState, TEvent, TInput> {\n\t\tconst builder = new ExternalRouteBuilder<TParams, TState, TEvent, TInput>(this, source);\n\t\tthis.routeBuilders.push(\n\t\t\tbuilder as unknown as ExternalRouteBuilder<TParams, TState, unknown, Record<string, unknown>>,\n\t\t);\n\t\treturn builder;\n\t}\n}\n\n/** @public */\ntype Hook<TApi> = (api: TApi) => void;\n\nfunction chainHooks<TApi>(hooks: readonly Hook<TApi>[]): Hook<TApi> {\n\treturn (api) => {\n\t\tfor (const hook of hooks) hook(api);\n\t};\n}\n\n/** @public */\nexport abstract class FlowComponentBuilder<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly turns: FlowTurn<TParams, TState>[] = [];\n\t/** @internal */\n\treadonly serverHooks: Hook<ServerProcessAPI<TParams, TState>>[] = [];\n\t/** @internal */\n\treadonly uiHooks: Hook<UiProcessAPI<TParams, TState>>[] = [];\n\t/** @internal */\n\treadonly launcherHooks: Hook<ProcessLauncherAPI<TParams>>[] = [];\n\t/** @internal */\n\treadonly watcherHooks: Hook<ProcessWatcherAPI<TParams>>[] = [];\n\n\t/** @public */\n\tturn(turn: FlowTurn<TParams, TState>): this {\n\t\tthis.turns.push(turn);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tserver(hook: Hook<ServerProcessAPI<TParams, TState>>): this {\n\t\tthis.serverHooks.push(hook);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\taction(definition: ProcessActionDefinition<TParams, TState>): this {\n\t\tthis.serverHooks.push((api) => api.action(definition));\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tui(hook: Hook<UiProcessAPI<TParams, TState>>): this {\n\t\tthis.uiHooks.push(hook);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tlauncher(\n\t\tdefinitionOrHook: ProcessLauncherDefinition<TParams> | Hook<ProcessLauncherAPI<TParams>>,\n\t): this {\n\t\tif (typeof definitionOrHook === \"function\") {\n\t\t\tthis.launcherHooks.push(definitionOrHook);\n\t\t} else {\n\t\t\tthis.launcherHooks.push((api) => api.launcher(definitionOrHook));\n\t\t}\n\t\treturn this;\n\t}\n\n\t/** @public */\n\twatcher<TEvent = unknown, TConfig = unknown>(\n\t\tdefinitionOrHook:\n\t\t\t| ProcessWatcherDefinition<TParams, TEvent, TConfig>\n\t\t\t| Hook<ProcessWatcherAPI<TParams>>,\n\t): this {\n\t\tif (typeof definitionOrHook === \"function\") {\n\t\t\tthis.watcherHooks.push(definitionOrHook);\n\t\t} else {\n\t\t\tthis.watcherHooks.push((api) => api.watcher(definitionOrHook));\n\t\t}\n\t\treturn this;\n\t}\n}\n\n/** @public */\nexport class FlowFragmentBuilder<TParams = unknown, TState = unknown> extends FlowComponentBuilder<\n\tTParams,\n\tTState\n> {\n\t/** @internal */\n\treadonly name: string;\n\n\t/** @internal */\n\tconstructor(name: string) {\n\t\tsuper();\n\t\tif (name.trim() === \"\") {\n\t\t\tthrow new Error(\"Flow fragment name must be non-empty\");\n\t\t}\n\t\tthis.name = name;\n\t}\n}\n\n/** @public */\nexport class FlowProcessBuilder<TParams = unknown, TState = unknown> extends FlowComponentBuilder<\n\tTParams,\n\tTState\n> {\n\tprivate readonly processId: string;\n\tprivate processDisplayName: string | null = null;\n\tprivate entryTurnId: TurnId | null = null;\n\tprivate readonly alternateEntryTurnIds: TurnId[] = [];\n\tprivate happyPathTurnIds: readonly TurnId[] | null = null;\n\tprivate paramsCodec: Codec<TParams> | null = null;\n\tprivate stateCodec: Codec<TState> | null = null;\n\tprivate initialStateFn: ((params: TParams) => TState) | null = null;\n\tprivate repositoryCredentialsFn: ExtensionProcessDefinition<\n\t\tTParams,\n\t\tTState\n\t>[\"repositoryCredentials\"];\n\tprivate storageSizeResolver: ExtensionProcessDefinition<TParams, TState>[\"resolveStorageSize\"];\n\tprivate processPiConfig: ProcessPiConfig | undefined;\n\tprivate developmentTools = false;\n\tprivate docker = false;\n\n\t/** @internal */\n\tconstructor(processId: string) {\n\t\tsuper();\n\t\tif (processId.trim() === \"\") {\n\t\t\tthrow new Error(\"Flow process id must be non-empty\");\n\t\t}\n\t\tthis.processId = processId;\n\t}\n\n\t/** @public */\n\tdisplayName(displayName: string): this {\n\t\tthis.processDisplayName = displayName;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tentry(turnId: TurnId): this {\n\t\tthis.entryTurnId = turnId;\n\t\treturn this;\n\t}\n\n\t/** Declare an additional turn that launchers may select as the first turn. @internal */\n\talternateEntry(turnId: TurnId): this {\n\t\tthis.alternateEntryTurnIds.push(turnId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Declare the happy path: the ordered spine of turns a successful run walks\n\t * through. Flow diagrams render this as the main line. Must start at the entry\n\t * turn and reference only declared turns without repeats.\n\t */\n\t/** @public */\n\thappyPath(...turnIds: readonly TurnId[]): this {\n\t\tthis.happyPathTurnIds = turnIds;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tcodecs(input: {\n\t\t/** @public */\n\t\tparams: Codec<TParams>;\n\t\t/** @public */\n\t\tstate: Codec<TState>;\n\t}): this {\n\t\tthis.paramsCodec = input.params;\n\t\tthis.stateCodec = input.state;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tinitialState(fn: (params: TParams) => TState): this {\n\t\tthis.initialStateFn = fn;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\trepositoryCredentials(\n\t\tfn: NonNullable<ExtensionProcessDefinition<TParams, TState>[\"repositoryCredentials\"]>,\n\t): this {\n\t\tthis.repositoryCredentialsFn = fn;\n\t\treturn this;\n\t}\n\n\t/** Resolve new process-volume capacity on the server; operator configuration wins. @internal */\n\tresolveStorageSize(\n\t\tfn: NonNullable<ExtensionProcessDefinition<TParams, TState>[\"resolveStorageSize\"]>,\n\t): this {\n\t\tthis.storageSizeResolver = fn;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tpiConfig(config: ProcessPiConfig): this {\n\t\tthis.processPiConfig = config;\n\t\treturn this;\n\t}\n\n\t/** Declare runner-provided process runtime capabilities. @public */\n\truntime(capabilities: {\n\t\t/** @internal */\n\t\tdevelopmentTools?: boolean;\n\t\t/** @public */\n\t\tdocker?: boolean;\n\t}): this {\n\t\tthis.developmentTools = capabilities.developmentTools === true;\n\t\tthis.docker = capabilities.docker === true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tuse(fragment: FlowFragmentBuilder<TParams, TState>): this {\n\t\tthis.turns.push(...fragment.turns);\n\t\tthis.serverHooks.push(...fragment.serverHooks);\n\t\tthis.uiHooks.push(...fragment.uiHooks);\n\t\tthis.launcherHooks.push(...fragment.launcherHooks);\n\t\tthis.watcherHooks.push(...fragment.watcherHooks);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tdefine(): ExtensionProcessDefinition<TParams, TState> {\n\t\tif (!this.processDisplayName) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .displayName(...)`);\n\t\t}\n\t\tif (!this.entryTurnId) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .entry(turnId)`);\n\t\t}\n\t\tif (!this.paramsCodec || !this.stateCodec) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .codecs(...)`);\n\t\t}\n\t\tif (!this.initialStateFn) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .initialState(...)`);\n\t\t}\n\n\t\tconst turns: TurnDefinitionRecord<TParams, TState> = {};\n\t\tfor (const turn of this.turns) {\n\t\t\tif (Object.hasOwn(turns, turn.id)) {\n\t\t\t\tthrow new Error(`Flow process '${this.processId}' declares duplicate turn '${turn.id}'`);\n\t\t\t}\n\t\t\tturns[turn.id] = turn.definition;\n\t\t}\n\n\t\tconst input: DefinedProcessInput<TParams, TState> = {\n\t\t\tid: this.processId,\n\t\t\tdisplayName: this.processDisplayName,\n\t\t\tentry: this.entryTurnId,\n\t\t\t...(this.alternateEntryTurnIds.length > 0\n\t\t\t\t? { alternateEntries: [...this.alternateEntryTurnIds] }\n\t\t\t\t: {}),\n\t\t\t...(this.happyPathTurnIds ? { happyPath: [...this.happyPathTurnIds] } : {}),\n\t\t\tparamsCodec: this.paramsCodec,\n\t\t\tstateCodec: this.stateCodec,\n\t\t\tinitialState: this.initialStateFn,\n\t\t\t...(this.developmentTools || this.docker\n\t\t\t\t? {\n\t\t\t\t\t\truntime: {\n\t\t\t\t\t\t\t...(this.developmentTools ? { developmentTools: true } : {}),\n\t\t\t\t\t\t\t...(this.docker ? { docker: true } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(this.repositoryCredentialsFn\n\t\t\t\t? { repositoryCredentials: this.repositoryCredentialsFn }\n\t\t\t\t: {}),\n\t\t\t...(this.storageSizeResolver ? { resolveStorageSize: this.storageSizeResolver } : {}),\n\t\t\t...(this.processPiConfig ? { piConfig: this.processPiConfig } : {}),\n\t\t\tturns,\n\t\t\t...(this.serverHooks.length > 0 ? { server: chainHooks(this.serverHooks) } : {}),\n\t\t\t...(this.uiHooks.length > 0 ? { ui: chainHooks(this.uiHooks) } : {}),\n\t\t\t...(this.launcherHooks.length > 0 ? { launchers: chainHooks(this.launcherHooks) } : {}),\n\t\t\t...(this.watcherHooks.length > 0 ? { watchers: chainHooks(this.watcherHooks) } : {}),\n\t\t};\n\t\tconst process = defineProcess(input);\n\t\tconst errors = validateProcessGraphProducts(\n\t\t\ttoProcessGraphView(process as unknown as ProcessGraphSource),\n\t\t);\n\t\tif (errors.length > 0)\n\t\t\tthrow new Error(`Flow process '${this.processId}': ${errors.join(\"; \")}`);\n\t\treturn process;\n\t}\n}\n\n/** @public */\nexport const flow = {\n\t/** @public */\n\tllm<TParams = unknown, TState = unknown>(turnId: TurnId): LlmFlowBuilder<TParams, TState> {\n\t\treturn new LlmFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\tautomatic<TParams = unknown, TState = unknown>(\n\t\tturnId: TurnId,\n\t): AutomaticFlowBuilder<TParams, TState> {\n\t\treturn new AutomaticFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\thuman<TParams = unknown, TState = unknown>(turnId: TurnId): HumanFlowBuilder<TParams, TState> {\n\t\treturn new HumanFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\texternal<TParams = unknown, TState = unknown>(\n\t\tturnId: TurnId,\n\t): ExternalFlowBuilder<TParams, TState> {\n\t\treturn new ExternalFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\tfragment<TParams = unknown, TState = unknown>(\n\t\tname: string,\n\t): FlowFragmentBuilder<TParams, TState> {\n\t\treturn new FlowFragmentBuilder<TParams, TState>(name);\n\t},\n\t/** @public */\n\tprocess<TParams = unknown, TState = unknown>(\n\t\tprocessId: string,\n\t): FlowProcessBuilder<TParams, TState> {\n\t\treturn new FlowProcessBuilder<TParams, TState>(processId);\n\t},\n};\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** @internal */\nexport async function atomicWriteUtf8(filePath: string, content: string): Promise<void> {\n\tconst dir = path.dirname(filePath);\n\tawait mkdir(dir, { recursive: true });\n\tconst tempPath = path.join(\n\t\tdir,\n\t\t`.${path.basename(filePath)}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tawait writeFile(tempPath, content, \"utf8\");\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\tawait unlink(tempPath).catch(() => {});\n\t\tthrow error;\n\t}\n}\n\n// The parent itself is not inside: callers require a strict descendant.\n/** @internal */\nexport function isPathInside(parent: string, child: string): boolean {\n\tconst relative = path.relative(parent, child);\n\treturn (\n\t\trelative !== \"\" &&\n\t\trelative !== \"..\" &&\n\t\t!relative.startsWith(`..${path.sep}`) &&\n\t\t!path.isAbsolute(relative)\n\t);\n}\n\n/** @internal */\nexport function hasErrorCode(error: unknown, code: string): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\t(error as { code?: unknown }).code === code\n\t);\n}\n\n/** @internal */\nexport function isEnoent(error: unknown): boolean {\n\treturn hasErrorCode(error, \"ENOENT\");\n}\n","import type {\n\tProcessSemanticEntryRefKey,\n\tProcessTurnTransition,\n\tProcessTurnType,\n\tSerializedProcessGraph,\n\tTurnId,\n} from \"@leitwerk-dev/domain\";\nimport { isValidProcessProductName } from \"@leitwerk-dev/domain\";\nimport type { TurnDefinition } from \"./define-process.js\";\nimport type { ExtensionProcessDefinition, ProcessTurnBinding } from \"./extension-api.js\";\nimport { getProcessTurnTransitions } from \"./process-definition-internals.js\";\n\n/** @internal */\nexport type ProcessGraphSource = ExtensionProcessDefinition<unknown, unknown>;\n/** @internal */\nexport type ProcessGraphRegistry = ReadonlyMap<string, ProcessGraphSource>;\n\n/** @internal */\nexport interface ProcessGraphTurnView {\n\t/** @internal */\n\tturnType: ProcessTurnType;\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\ttransitions: readonly ProcessTurnTransition[];\n\t/** @internal */\n\treviewProduct?: string;\n\t/** @internal */\n\tresultSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @internal */\n\tpublishedProduct?: string;\n\t/** @internal */\n\tpublishedProducts?: readonly string[];\n\t/** @internal */\n\tconsumedProducts?: readonly string[];\n\t/** @internal */\n\toptionalConsumedProducts?: readonly string[];\n\t/** @internal */\n\trequiredSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n\t/** @internal */\n\toptionalSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n\t/** @internal */\n\tturnResultMarkdownRequired?: boolean;\n}\n\n/** @internal */\nexport interface ProcessGraphView {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tprimaryEntryTurnId: TurnId;\n\t/** @internal */\n\tentryTurnIds: ReadonlySet<TurnId>;\n\t/** @internal */\n\thappyPath: readonly TurnId[] | null;\n\t/** @internal */\n\tturns: ReadonlyMap<TurnId, ProcessGraphTurnView>;\n}\n\nfunction turnPublishedProducts(definition: TurnDefinition<unknown, unknown>): string[] {\n\tconst products = new Set<string>();\n\tif (definition.kind === \"human\") {\n\t\tfor (const action of Object.values(definition.actions)) {\n\t\t\tfor (const field of action.form?.fields ?? []) {\n\t\t\t\tif (field.publish) {\n\t\t\t\t\tproducts.add(\n\t\t\t\t\t\ttypeof field.publish === \"object\" && field.publish.product\n\t\t\t\t\t\t\t? field.publish.product\n\t\t\t\t\t\t\t: field.id,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const action of Object.values(definition.externalActions ?? {})) {\n\t\t\tif (action.publishInput) {\n\t\t\t\tproducts.add(action.publishInput.productName);\n\t\t\t}\n\t\t}\n\t} else if (definition.kind === \"llm\" || definition.kind === \"automatic\") {\n\t\tfor (const outcome of Object.values(definition.outcomes ?? {})) {\n\t\t\tif (typeof outcome?.publishedProduct === \"string\") {\n\t\t\t\tproducts.add(outcome.publishedProduct);\n\t\t\t}\n\t\t}\n\t}\n\treturn [...products];\n}\n\nfunction toTurnView(\n\tbinding: ProcessTurnBinding<TurnDefinition<unknown, unknown>>,\n): ProcessGraphTurnView {\n\tconst definition = binding.definition;\n\tconst publishedProducts = turnPublishedProducts(definition);\n\treturn {\n\t\tturnType: definition.kind,\n\t\tdescription: definition.description,\n\t\ttransitions: getProcessTurnTransitions(binding),\n\t\t...(definition.kind === \"human\" && definition.reviewProduct\n\t\t\t? { reviewProduct: definition.reviewProduct }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.resultSemanticRef\n\t\t\t? { resultSemanticRef: definition.resultSemanticRef }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.publishedProduct\n\t\t\t? { publishedProduct: definition.publishedProduct }\n\t\t\t: {}),\n\t\t...(publishedProducts.length > 0 ? { publishedProducts } : {}),\n\t\t...(definition.kind === \"llm\" && definition.consumedProducts?.length\n\t\t\t? { consumedProducts: [...definition.consumedProducts] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.optionalConsumedProducts?.length\n\t\t\t? { optionalConsumedProducts: [...definition.optionalConsumedProducts] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.requiredSemanticMarkdownRefs?.length\n\t\t\t? { requiredSemanticMarkdownRefs: [...definition.requiredSemanticMarkdownRefs] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.optionalSemanticMarkdownRefs?.length\n\t\t\t? { optionalSemanticMarkdownRefs: [...definition.optionalSemanticMarkdownRefs] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" &&\n\t\tdefinition.turnResultMarkdown &&\n\t\t\"required\" in definition.turnResultMarkdown &&\n\t\tdefinition.turnResultMarkdown.required === true\n\t\t\t? { turnResultMarkdownRequired: true }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Runtime adapter from an extension process definition to the internal graph view.\n * All server lifecycle, validation, model-selection and serialization code should use this view\n * instead of maintaining a second graph representation.\n */\n/** @internal */\nexport function toProcessGraphView(definition: ProcessGraphSource): ProcessGraphView {\n\tconst turns = new Map<TurnId, ProcessGraphTurnView>();\n\tfor (const [turnId, binding] of definition.turns) {\n\t\tturns.set(turnId, toTurnView(binding));\n\t}\n\treturn {\n\t\tid: definition.id,\n\t\tprimaryEntryTurnId: definition.entryTurnId,\n\t\tentryTurnIds: new Set([definition.entryTurnId, ...(definition.alternateEntryTurnIds ?? [])]),\n\t\thappyPath: definition.happyPath ? [...definition.happyPath] : null,\n\t\tturns,\n\t};\n}\n\n/** @internal */\nexport function hasProcessGraph(registry: ProcessGraphRegistry, processId: string): boolean {\n\treturn registry.has(processId);\n}\n\n/** @internal */\nexport function getProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): ProcessGraphView {\n\tconst definition = registry.get(processId);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown process definition: ${processId}`);\n\t}\n\treturn toProcessGraphView(definition);\n}\n\n/** @internal */\nexport function getAllProcessGraphs(registry: ProcessGraphRegistry): readonly ProcessGraphView[] {\n\treturn [...registry.values()].map((definition) => toProcessGraphView(definition));\n}\n\n/** @internal */\nexport function getProcessTurnGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n\tturnId: TurnId,\n): ProcessGraphTurnView | undefined {\n\treturn getProcessGraph(registry, processId).turns.get(turnId);\n}\n\n/** @internal */\nexport function getTurnTransitionsForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n\tturnId: TurnId,\n): readonly ProcessTurnTransition[] {\n\treturn getProcessTurnGraph(registry, processId, turnId)?.transitions ?? [];\n}\n\n/** @internal */\nexport function getReachableTurnIdsForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): readonly TurnId[] {\n\treturn [...getProcessGraph(registry, processId).turns.keys()];\n}\n\n/** @internal */\nexport function isTurnAvailableForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n\tturnId: TurnId,\n): boolean {\n\treturn getProcessGraph(registry, processId).turns.has(turnId);\n}\n\n/** @internal */\nexport function serializeProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): SerializedProcessGraph {\n\tconst definition = getProcessGraph(registry, processId);\n\tconst turnTransitions: Record<TurnId, ProcessTurnTransition[]> = {};\n\tfor (const [turnId, turn] of definition.turns) {\n\t\tturnTransitions[turnId] = turn.transitions.map((transition) => ({ ...transition }));\n\t}\n\treturn {\n\t\tid: definition.id,\n\t\tentryTurnIds: [...definition.entryTurnIds],\n\t\treachableTurnIds: [...definition.turns.keys()],\n\t\tturnTransitions,\n\t};\n}\n\n/** @internal */\nexport function listLlmTurnIdsForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): readonly TurnId[] {\n\treturn [...getProcessGraph(registry, processId).turns.entries()]\n\t\t.filter(([, turn]) => turn.turnType === \"llm\")\n\t\t.map(([turnId]) => turnId);\n}\n\nfunction isTerminalLifecycleStatus(value: string | undefined): value is \"completed\" | \"aborted\" {\n\treturn value === \"completed\" || value === \"aborted\";\n}\n\n/** @internal */\nexport function validateProcessGraphEntryTurns(graph: ProcessGraphView): readonly string[] {\n\tconst errors: string[] = [];\n\tfor (const turnId of graph.entryTurnIds) {\n\t\tif (!graph.turns.has(turnId)) {\n\t\t\terrors.push(`Entry turn '${turnId}' is not declared in turns`);\n\t\t}\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateProcessGraphProducts(graph: ProcessGraphView): readonly string[] {\n\tconst errors: string[] = [];\n\tconst publishedProducts = new Set<string>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tconst productNames = [\n\t\t\t...(turn.publishedProduct ? [turn.publishedProduct] : []),\n\t\t\t...(turn.publishedProducts ?? []),\n\t\t];\n\t\tfor (const productName of productNames) {\n\t\t\tif (!isValidProcessProductName(productName)) {\n\t\t\t\terrors.push(`Turn '${turnId}' publishes invalid product '${productName}'`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpublishedProducts.add(productName);\n\t\t}\n\t}\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const productName of [\n\t\t\t...(turn.consumedProducts ?? []),\n\t\t\t...(turn.optionalConsumedProducts ?? []),\n\t\t]) {\n\t\t\tif (!isValidProcessProductName(productName)) {\n\t\t\t\terrors.push(`Turn '${turnId}' consumes invalid product '${productName}'`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!publishedProducts.has(productName)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn '${turnId}' consumes product '${productName}' that is never published by this process`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateProcessGraphTurnTransitions(graph: ProcessGraphView): readonly string[] {\n\tconst errors: string[] = [];\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst hasNextTurn = transition.nextTurnId !== undefined;\n\t\t\tconst hasLifecycleStatus = transition.lifecycleStatus !== undefined;\n\t\t\tif (hasNextTurn === hasLifecycleStatus) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn transition from '${turnId}' must declare exactly one target: nextTurnId or lifecycleStatus`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (transition.nextTurnId !== undefined && !graph.turns.has(transition.nextTurnId)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn transition from '${turnId}' references undeclared nextTurnId '${transition.nextTurnId}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttransition.lifecycleStatus !== undefined &&\n\t\t\t\t!isTerminalLifecycleStatus(transition.lifecycleStatus)\n\t\t\t) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn transition from '${turnId}' references invalid lifecycleStatus '${transition.lifecycleStatus}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n","import type { InputKind, InputSource, ProcessInputTarget } from \"@leitwerk-dev/domain\";\nimport type {\n\tProcessActionEffect,\n\tProcessActionExecution,\n\tProcessEffectPlan,\n\tProcessHumanTurnActionSpec,\n} from \"./define-process.js\";\n\n/** @internal */\ntype MaybePromise<T> = T | Promise<T>;\n/** @internal */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\nfunction appendQueuedInstruction<TState>(input: {\n\tplan: ProcessEffectPlan<TState> | undefined;\n\tbodyMarkdown: string | null | undefined;\n\tqueueTarget?: ProcessInputTarget;\n\tqueueSource?: InputSource;\n\tqueueKind?: InputKind;\n}) {\n\tif (input.bodyMarkdown == null) {\n\t\treturn input.plan;\n\t}\n\tif (input.bodyMarkdown.trim() === \"\") {\n\t\tthrow new Error(\"Queued instruction bodyMarkdown must not be empty\");\n\t}\n\treturn {\n\t\t...(input.plan ?? {}),\n\t\tqueueInput: [\n\t\t\t...(input.plan?.queueInput ?? []),\n\t\t\t{\n\t\t\t\tsource: input.queueSource ?? \"action_prompt\",\n\t\t\t\tkind: input.queueKind ?? \"instruction\",\n\t\t\t\t...(input.queueTarget ? { target: input.queueTarget } : {}),\n\t\t\t\tbodyMarkdown: input.bodyMarkdown,\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** @internal */\nexport type QueuedInstructionActionSpec<TParams = unknown, TState = unknown> = DistributiveOmit<\n\tProcessHumanTurnActionSpec<TParams, TState>,\n\t\"effect\"\n> & {\n\t/** @internal */\n\tqueueTarget?: ProcessInputTarget;\n\t/** @internal */\n\tqueueSource?: InputSource;\n\t/** @internal */\n\tqueueKind?: InputKind;\n\t/** @internal */\n\tresolveBodyMarkdown(\n\t\tinput: ProcessActionExecution<TParams, TState>,\n\t): MaybePromise<string | null | undefined>;\n\t/** @internal */\n\teffect?: ProcessActionEffect<TParams, TState>;\n};\n\n/** @internal */\nexport function queuedInstructionAction<TParams = unknown, TState = unknown>(\n\tspec: QueuedInstructionActionSpec<TParams, TState>,\n): ProcessHumanTurnActionSpec<TParams, TState> {\n\tconst { queueTarget, queueSource, queueKind, resolveBodyMarkdown, effect, ...rest } = spec;\n\treturn {\n\t\t...rest,\n\t\tasync effect(input) {\n\t\t\tconst bodyMarkdown = await resolveBodyMarkdown(input);\n\t\t\tconst plan = effect ? await effect(input) : undefined;\n\t\t\treturn appendQueuedInstruction({\n\t\t\t\tplan,\n\t\t\t\tbodyMarkdown,\n\t\t\t\tqueueTarget,\n\t\t\t\tqueueSource,\n\t\t\t\tqueueKind,\n\t\t\t});\n\t\t},\n\t} as ProcessHumanTurnActionSpec<TParams, TState>;\n}\n\n/** @internal */\nexport type RevisionActionSpec<TParams = unknown, TState = unknown> = DistributiveOmit<\n\tQueuedInstructionActionSpec<TParams, TState>,\n\t\"resolveBodyMarkdown\"\n> & {\n\t/** @internal */\n\tmessageFieldId?: string;\n\t/** @internal */\n\tmissingMessageError?: string;\n};\n\n/** @internal */\nexport function revisionAction<TParams = unknown, TState = unknown>(\n\tspec: RevisionActionSpec<TParams, TState>,\n): ProcessHumanTurnActionSpec<TParams, TState> {\n\tconst { messageFieldId = \"message\", missingMessageError, ...rest } = spec;\n\treturn queuedInstructionAction({\n\t\t...rest,\n\t\tresolveBodyMarkdown({ input }) {\n\t\t\tconst message = typeof input[messageFieldId] === \"string\" ? input[messageFieldId].trim() : \"\";\n\t\t\tif (!message) {\n\t\t\t\tthrow new Error(missingMessageError ?? `${messageFieldId} is required`);\n\t\t\t}\n\t\t\treturn message;\n\t\t},\n\t});\n}\n\n/** @internal */\nexport type AcceptedReviewHandoffActionSpec<TParams = unknown, TState = unknown> = DistributiveOmit<\n\tQueuedInstructionActionSpec<TParams, TState>,\n\t\"queueTarget\"\n> & {\n\t/** @internal */\n\tqueueTarget?: ProcessInputTarget;\n};\n\n/** @internal */\nexport function acceptedReviewHandoffAction<TParams = unknown, TState = unknown>(\n\tspec: AcceptedReviewHandoffActionSpec<TParams, TState>,\n): ProcessHumanTurnActionSpec<TParams, TState> {\n\treturn queuedInstructionAction({\n\t\t...spec,\n\t\tqueueTarget: spec.queueTarget ?? { semanticRef: \"currentPrimaryPathLeaf\" },\n\t});\n}\n","import type { CapabilityToken } from \"./capabilities.js\";\n\n/** @internal */\nexport interface ProvidedCapability<T = unknown> {\n\t/** @internal */\n\ttoken: CapabilityToken<T>;\n\t/** @internal */\n\tvalue: T;\n}\n\n/** @internal */\nexport function createCapabilityAccessor(provided: readonly ProvidedCapability[] = []): {\n\t/** @internal */\n\tprovide<T>(token: CapabilityToken<T>, value: T): void;\n\t/** @internal */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @internal */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n} {\n\tconst singleCapabilities = new Map<string, unknown>();\n\tconst multiCapabilities = new Map<string, unknown[]>();\n\n\tfor (const entry of provided) {\n\t\tif (entry.token.cardinality === \"multi\") {\n\t\t\tconst list = multiCapabilities.get(entry.token.id) ?? [];\n\t\t\tlist.push(entry.value);\n\t\t\tmultiCapabilities.set(entry.token.id, list);\n\t\t\tcontinue;\n\t\t}\n\t\tsingleCapabilities.set(entry.token.id, entry.value);\n\t}\n\n\treturn {\n\t\tprovide(token, value) {\n\t\t\tif (token.cardinality === \"multi\") {\n\t\t\t\tconst list = multiCapabilities.get(token.id) ?? [];\n\t\t\t\tlist.push(value);\n\t\t\t\tmultiCapabilities.set(token.id, list);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (singleCapabilities.has(token.id)) {\n\t\t\t\tthrow new Error(`Capability '${token.id}' is already provided`);\n\t\t\t}\n\t\t\tsingleCapabilities.set(token.id, value);\n\t\t},\n\t\tget<T>(token: CapabilityToken<T>): T | T[] | undefined {\n\t\t\tif (token.cardinality === \"multi\") {\n\t\t\t\treturn [...(multiCapabilities.get(token.id) ?? [])] as T[];\n\t\t\t}\n\t\t\treturn singleCapabilities.get(token.id) as T | undefined;\n\t\t},\n\t\trequire<T>(token: CapabilityToken<T>): T | T[] {\n\t\t\tconst value = this.get(token);\n\t\t\tif (\n\t\t\t\tvalue === undefined ||\n\t\t\t\t(Array.isArray(value) && token.cardinality === \"multi\" && value.length === 0)\n\t\t\t) {\n\t\t\t\tthrow new Error(`Required capability '${token.id}' is not available`);\n\t\t\t}\n\t\t\treturn value;\n\t\t},\n\t};\n}\n","/** An HTTP failure without provider response bodies or credentials. @internal */\nexport class IntegrationHttpError extends Error {\n\t/** @internal */\n\tconstructor(\n\t\t/** @internal */\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/** Shared transport; extensions own endpoint paths, credentials, and response types. @public */\nexport class IntegrationHttpClient {\n\t/** @internal */\n\tconstructor(\n\t\tprivate readonly provider: string,\n\t\tprivate readonly baseUrl: string,\n\t\tprivate readonly headers: Record<string, string>,\n\t\tprivate readonly pagination = {\n\t\t\t/** @internal */\n\t\t\tkey: \"per_page\",\n\t\t\t/** @internal */\n\t\t\tsize: 100,\n\t\t},\n\t) {}\n\n\t/** @internal */\n\tprotected async response(path: string, init: RequestInit = {}): Promise<Response> {\n\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...this.headers,\n\t\t\t\t...(init.body ? { \"Content-Type\": \"application/json\" } : {}),\n\t\t\t\t...init.headers,\n\t\t\t},\n\t\t});\n\t\tif (!response.ok)\n\t\t\tthrow new IntegrationHttpError(\n\t\t\t\tresponse.status,\n\t\t\t\t`${this.provider} ${init.method ?? \"GET\"} ${path} failed with ${response.status}`,\n\t\t\t);\n\t\treturn response;\n\t}\n\n\t/** @internal */\n\tprotected async request<T>(path: string, init: RequestInit = {}): Promise<T> {\n\t\tconst response = await this.response(path, init);\n\t\treturn response.status === 204 ? (undefined as T) : response.json();\n\t}\n\n\t/** @internal */\n\tprotected writeJson<T>(path: string, method: string, body: unknown, signal?: AbortSignal) {\n\t\treturn this.request<T>(path, { method, body: JSON.stringify(body), signal });\n\t}\n\n\t/** @internal */\n\tprotected async pages<T>(path: string, signal?: AbortSignal): Promise<T[]> {\n\t\tconst items: T[] = [];\n\t\tconst { key, size } = this.pagination;\n\t\tfor (let page = 1; ; page++) {\n\t\t\tconst separator = path.includes(\"?\") ? \"&\" : \"?\";\n\t\t\tconst batch = await this.request<T[]>(`${path}${separator}${key}=${size}&page=${page}`, {\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\titems.push(...batch);\n\t\t\tif (batch.length < size) return items;\n\t\t}\n\t}\n}\n","/** Validate and detach JSON data without silently dropping unsupported values. @internal */\nexport function parseJsonData(\n\tvalue: unknown,\n\tmessage = \"Value must be JSON-serializable\",\n): unknown {\n\tconst ancestors = new Set<object>();\n\tfunction parse(value: unknown): unknown {\n\t\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\t\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\t\tif (!value || typeof value !== \"object\" || ancestors.has(value)) throw new Error(message);\n\t\tancestors.add(value);\n\t\ttry {\n\t\t\tif (Array.isArray(value)) return Array.from(value, parse);\n\t\t\tif (\n\t\t\t\t![Object.prototype, null].includes(Object.getPrototypeOf(value)) ||\n\t\t\t\tObject.getOwnPropertySymbols(value).length\n\t\t\t)\n\t\t\t\tthrow new Error(message);\n\t\t\treturn Object.fromEntries(Object.entries(value).map(([key, item]) => [key, parse(item)]));\n\t\t} finally {\n\t\t\tancestors.delete(value);\n\t\t}\n\t}\n\treturn parse(value);\n}\n","import { copiedUnknownRecordSchema as unknownRecordSchema } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\nimport type { LeafOutcomeCaptureResult, ProcessLeafOutcomeDefinition } from \"./extension-api.js\";\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.trim() !== \"\";\n}\n\n/** @internal */\nexport function validateProcessLeafOutcomeDefinition(def: ProcessLeafOutcomeDefinition): string[] {\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(def.rendererId)) {\n\t\terrors.push(\"Leaf outcome definition must declare a non-empty rendererId\");\n\t}\n\tif (typeof def.capture !== \"function\") {\n\t\terrors.push(`Leaf outcome '${String(def.rendererId)}' must declare a capture() function`);\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateLeafOutcomeCaptureResult(\n\tresult: unknown,\n\texpectedRendererId?: string,\n): string[] {\n\tconst errors: string[] = [];\n\tconst parsedResult = v.safeParse(unknownRecordSchema, result);\n\tif (!parsedResult.success) {\n\t\treturn [\"Leaf outcome capture result must be an object\"];\n\t}\n\tconst captureResult = parsedResult.output;\n\tif (!isNonEmptyString(captureResult.rendererId)) {\n\t\terrors.push(\"Leaf outcome capture result must include a non-empty rendererId\");\n\t} else if (expectedRendererId && captureResult.rendererId.trim() !== expectedRendererId.trim()) {\n\t\terrors.push(\n\t\t\t`Leaf outcome capture result rendererId '${captureResult.rendererId}' must match '${expectedRendererId}'`,\n\t\t);\n\t}\n\tif (!v.safeParse(unknownRecordSchema, captureResult.props).success) {\n\t\terrors.push(\"Leaf outcome capture result props must be an object\");\n\t}\n\tif (\n\t\tcaptureResult.schemaVersion !== undefined &&\n\t\t(typeof captureResult.schemaVersion !== \"number\" ||\n\t\t\t!Number.isInteger(captureResult.schemaVersion))\n\t) {\n\t\terrors.push(\"Leaf outcome capture result schemaVersion must be an integer when provided\");\n\t}\n\tif (\n\t\tcaptureResult.fallbackMarkdown !== undefined &&\n\t\tcaptureResult.fallbackMarkdown !== null &&\n\t\ttypeof captureResult.fallbackMarkdown !== \"string\"\n\t) {\n\t\terrors.push(\"Leaf outcome capture result fallbackMarkdown must be a string or null\");\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function normalizeLeafOutcomeCaptureResult(\n\tresult: LeafOutcomeCaptureResult,\n): LeafOutcomeCaptureResult {\n\treturn {\n\t\trendererId: result.rendererId.trim(),\n\t\t...(result.schemaVersion !== undefined ? { schemaVersion: result.schemaVersion } : {}),\n\t\tprops: { ...result.props },\n\t\t...(result.fallbackMarkdown !== undefined ? { fallbackMarkdown: result.fallbackMarkdown } : {}),\n\t};\n}\n","/** JSON values that may cross the server/worker bootstrap boundary. @public */\nexport type ProviderJsonPrimitive = string | number | boolean | null;\n/** @public */\nexport type ProviderJsonValue =\n\t| ProviderJsonPrimitive\n\t| ProviderJsonValue[]\n\t| {\n\t\t\t/** @internal */\n\t\t\t[key: string]: ProviderJsonValue;\n\t };\n/** @public */\nexport type ProviderJsonObject = {\n\t/** @internal */\n\t[key: string]: ProviderJsonValue;\n};\n\n/** @public */\nexport interface ConfiguredProviderModel {\n\t/** @public */\n\treadonly profileId: string;\n\t/** @public */\n\treadonly modelId: string;\n}\n\n/** @public */\nexport type ProviderAvailability = \"available\" | \"unavailable\" | \"stale\";\n\n/** @public */\nexport interface ProviderModelStatus {\n\t/** @public */\n\treadonly modelId: string;\n\t/** @public */\n\treadonly availability: ProviderAvailability;\n\t/** Safe operator-facing reason. It must not contain credential material. @internal */\n\treadonly safeReason?: string;\n}\n\n/** @public */\nexport interface ProviderCredentialStatus {\n\t/** @public */\n\treadonly available: boolean;\n\t/** @public */\n\treadonly revision: number | null;\n}\n\n/** @public */\nexport interface ModelProviderModelsContext<TConfig = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly configuredModels: readonly ConfiguredProviderModel[];\n\t/** @public */\n\treadonly credentialStatus: ProviderCredentialStatus;\n}\n\n/** @public */\nexport interface ProviderOptionChoice {\n\t/** @internal */\n\treadonly value: string;\n\t/** @internal */\n\treadonly label: string;\n}\n\n/** @public */\nexport interface ProviderOptionChoicesContext<TConfig = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly credentialStatus: ProviderCredentialStatus;\n}\n\n/** @internal */\nexport interface ProviderOptionDefaultContext<TConfig = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n}\n\n/** @public */\nexport interface ProviderOptionField<TConfig = unknown> {\n\t/** @public */\n\treadonly label: string;\n\t/** @public */\n\treadonly required?: boolean;\n\t/** @internal */\n\treadonly minLength?: number;\n\t/** @public */\n\treadonly maxLength?: number;\n\t/**\n\t * Explicit provider default. Dynamic choices are advisory and are never used\n\t * as an implicit default.\n\t */\n\t/** @internal */\n\treadonly defaultValue?:\n\t\t| string\n\t\t| null\n\t\t| ((ctx: ProviderOptionDefaultContext<TConfig>) => string | null | undefined);\n}\n\n/** @public */\nexport interface ProviderOptionsDefinition<TConfig = unknown> {\n\t/** @public */\n\treadonly fields: Readonly<Record<string, ProviderOptionField<TConfig>>>;\n\t/** @public */\n\tchoices?(\n\t\tctx: ProviderOptionChoicesContext<TConfig>,\n\t):\n\t\t| Readonly<Record<string, readonly ProviderOptionChoice[]>>\n\t\t| Promise<Readonly<Record<string, readonly ProviderOptionChoice[]>>>;\n}\n\n/** @public */\nexport function defineProviderOptions<TConfig = unknown>(\n\tdefinition: ProviderOptionsDefinition<TConfig>,\n): ProviderOptionsDefinition<TConfig> {\n\tfor (const [fieldId, field] of Object.entries(definition.fields)) {\n\t\tif (fieldId.trim() === \"\") {\n\t\t\tthrow new Error(\"Provider option field ids must not be empty\");\n\t\t}\n\t\tfor (const bound of [\"minLength\", \"maxLength\"] as const) {\n\t\t\tconst value = field[bound];\n\t\t\tif (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n\t\t\t\tthrow new Error(`Provider option '${fieldId}' ${bound} must be a non-negative integer`);\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tfield.minLength !== undefined &&\n\t\t\tfield.maxLength !== undefined &&\n\t\t\tfield.minLength > field.maxLength\n\t\t) {\n\t\t\tthrow new Error(`Provider option '${fieldId}' minLength must not exceed maxLength`);\n\t\t}\n\t}\n\treturn { ...definition, fields: { ...definition.fields } };\n}\n\n/** @internal */\nexport interface ProviderOptionsResolutionInput<TConfig = unknown> {\n\t/** @internal */\n\treadonly definition: ProviderOptionsDefinition<TConfig> | null | undefined;\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly explicit?: Readonly<Record<string, unknown>> | null;\n\t/** @internal */\n\treadonly profileDefaults?: Readonly<Record<string, unknown>> | null;\n}\n\n/** @internal */\nexport interface ProviderOptionValidationIssue {\n\t/** @internal */\n\treadonly fieldId: string;\n\t/** @internal */\n\treadonly code: \"unknown\" | \"not_string\" | \"too_short\" | \"too_long\" | \"required\";\n\t/** @internal */\n\treadonly message: string;\n}\n\n/** @internal */\nexport type ProviderOptionsResolution =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly ok: true;\n\t\t\t/** @internal */\n\t\t\treadonly value: Readonly<Record<string, string>>;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly ok: false;\n\t\t\t/** @internal */\n\t\t\treadonly issues: readonly ProviderOptionValidationIssue[];\n\t };\n\nfunction validateOptionValue<TConfig>(\n\tfieldId: string,\n\tfield: ProviderOptionField<TConfig>,\n\tvalue: unknown,\n): ProviderOptionValidationIssue | null {\n\tif (typeof value !== \"string\") {\n\t\treturn {\n\t\t\tfieldId,\n\t\t\tcode: \"not_string\",\n\t\t\tmessage: `Provider option '${fieldId}' must be a string`,\n\t\t};\n\t}\n\tif (field.minLength !== undefined && value.length < field.minLength) {\n\t\treturn {\n\t\t\tfieldId,\n\t\t\tcode: \"too_short\",\n\t\t\tmessage: `Provider option '${fieldId}' must contain at least ${field.minLength} characters`,\n\t\t};\n\t}\n\tif (field.maxLength !== undefined && value.length > field.maxLength) {\n\t\treturn {\n\t\t\tfieldId,\n\t\t\tcode: \"too_long\",\n\t\t\tmessage: `Provider option '${fieldId}' must contain at most ${field.maxLength} characters`,\n\t\t};\n\t}\n\treturn null;\n}\n\n/**\n * Resolve explicit values, profile defaults, then declared provider defaults.\n * Dynamic choices deliberately do not participate in validation or fallback.\n */\n/** @internal */\nexport function resolveProviderOptions<TConfig = unknown>(\n\tinput: ProviderOptionsResolutionInput<TConfig>,\n): ProviderOptionsResolution {\n\tconst fields = input.definition?.fields ?? {};\n\tconst issues: ProviderOptionValidationIssue[] = [];\n\tfor (const source of [input.explicit, input.profileDefaults]) {\n\t\tfor (const fieldId of Object.keys(source ?? {})) {\n\t\t\tif (!(fieldId in fields)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfieldId,\n\t\t\t\t\tcode: \"unknown\",\n\t\t\t\t\tmessage: `Unknown provider option '${fieldId}'`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tif (issues.length > 0) {\n\t\treturn { ok: false, issues };\n\t}\n\n\tconst resolved: Record<string, string> = {};\n\tfor (const [fieldId, field] of Object.entries(fields)) {\n\t\tconst explicit = input.explicit?.[fieldId];\n\t\tconst profileDefault = input.profileDefaults?.[fieldId];\n\t\tconst declaredDefault =\n\t\t\ttypeof field.defaultValue === \"function\"\n\t\t\t\t? field.defaultValue({ config: input.config })\n\t\t\t\t: field.defaultValue;\n\t\tconst value = explicit ?? profileDefault ?? declaredDefault;\n\t\tif (value === undefined || value === null) {\n\t\t\tif (field.required) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfieldId,\n\t\t\t\t\tcode: \"required\",\n\t\t\t\t\tmessage: `Provider option '${fieldId}' is required`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst issue = validateOptionValue(fieldId, field, value);\n\t\tif (issue) {\n\t\t\tissues.push(issue);\n\t\t\tcontinue;\n\t\t}\n\t\tresolved[fieldId] = value as string;\n\t}\n\treturn issues.length > 0 ? { ok: false, issues } : { ok: true, value: resolved };\n}\n\n/** Keep only fields declared by a newly selected provider. @internal */\nexport function filterProviderOptionsForDefinition<TConfig = unknown>(\n\tdefinition: ProviderOptionsDefinition<TConfig> | null | undefined,\n\tvalues: Readonly<Record<string, string>>,\n): Readonly<Record<string, string>> {\n\tconst fields = definition?.fields ?? {};\n\treturn Object.fromEntries(Object.entries(values).filter(([fieldId]) => fieldId in fields));\n}\n\n/**\n * Runtime-independent schema boundary for non-secret provider worker config.\n * Adapters may wrap Valibot, TypeBox, Zod, or another validator behind parse.\n */\n/** @public */\nexport interface ProviderWorkerConfigSchema<TValue extends ProviderJsonObject> {\n\t/** @public */\n\tparse(value: unknown): TValue;\n}\n\n/** @public */\nexport interface ProviderWorkerConfigContext<TConfig = unknown> {\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly options: Readonly<Record<string, string>>;\n}\n\n/** @public */\nexport interface ProviderWorkerConfigDefinition<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n> {\n\t/** @public */\n\treadonly version: number;\n\t/** @public */\n\treadonly schema: ProviderWorkerConfigSchema<TValue>;\n\t/** @public */\n\tresolve(ctx: ProviderWorkerConfigContext<TConfig>): TValue;\n}\n\n/** @public */\nexport function defineWorkerConfig<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n>(\n\tdefinition: ProviderWorkerConfigDefinition<TConfig, TValue>,\n): ProviderWorkerConfigDefinition<TConfig, TValue> {\n\tif (!Number.isInteger(definition.version) || definition.version < 1) {\n\t\tthrow new Error(\"Provider worker config version must be a positive integer\");\n\t}\n\treturn definition;\n}\n\n/** @public */\nexport interface PiWorkerReference<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n> {\n\t/** @public */\n\treadonly kind: \"extension_pi_worker\";\n\t/** @internal */\n\treadonly config?: ProviderWorkerConfigDefinition<TConfig, TValue>;\n\t/** Mutable, flat JSON credential files required by this provider's Pi extension. @internal */\n\treadonly credentialFiles?: readonly string[];\n}\n\n/** @public */\nexport interface PiServerReference {\n\t/** @internal */\n\treadonly kind: \"extension_pi_server\";\n}\n\n/** @public */\nexport interface PiServerGenerateTextInput<TConfig = unknown> {\n\t/** @public */\n\treadonly providerId: string;\n\t/** @public */\n\treadonly modelId: string;\n\t/** @public */\n\treadonly thinkingLevel: string;\n\t/** @public */\n\treadonly prompt: string;\n\t/** @public */\n\treadonly systemPrompt: string;\n\t/** @public */\n\treadonly maxTokens: number;\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly options: Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly secrets: Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly request: {\n\t\t/** @public */\n\t\treadonly timeoutMs?: number;\n\t\t/** @internal */\n\t\treadonly maxRetries?: number;\n\t\t/** @public */\n\t\treadonly maxRetryDelayMs: number;\n\t};\n}\n\n/** Server-only provider boundary for title generation and future cheap LLM consumers. @public */\nexport interface PiServerAdapter<TConfig = unknown> {\n\t/** @public */\n\tgenerateText(input: PiServerGenerateTextInput<TConfig>): Promise<string>;\n}\n\n/** @public */\nexport function definePiServerAdapter<TConfig = unknown>(\n\tadapter: PiServerAdapter<TConfig>,\n): PiServerAdapter<TConfig> {\n\tif (!adapter || typeof adapter.generateText !== \"function\") {\n\t\tthrow new Error(\"Pi server adapter must define generateText()\");\n\t}\n\treturn adapter;\n}\n\n/** @public */\nexport interface BuiltinPiProviderReference {\n\t/** @public */\n\treadonly kind: \"builtin_pi_provider\";\n\t/** @internal */\n\treadonly providerId: string;\n}\n\n/** @public */\nexport interface ConfiguredPiProviderReference<TConfig = unknown> {\n\t/** @public */\n\treadonly kind: \"configured_pi_provider\";\n\t/** @internal */\n\treadonly providerId: string;\n\t/** Resolve the credential-blind models.json document pinned into each worker snapshot. @internal */\n\tresolveModels(ctx: {\n\t\t/** @internal */\n\t\treadonly config: TConfig;\n\t}): ProviderJsonObject;\n}\n\n/** @public */\nexport function piWorker<TConfig = unknown, TValue extends ProviderJsonObject = ProviderJsonObject>(\n\tinput: {\n\t\t/** @public */\n\t\tconfig?: ProviderWorkerConfigDefinition<TConfig, TValue>;\n\t\t/** @public */\n\t\tcredentialFiles?: readonly string[];\n\t} = {},\n): PiWorkerReference<TConfig, TValue> {\n\tconst credentialFiles = input.credentialFiles?.map((file) => {\n\t\tif (!file || file.startsWith(\"/\") || file.includes(\"..\") || file.includes(\"\\\\\\\\\")) {\n\t\t\tthrow new Error(\"Pi worker credential file must be a relative path\");\n\t\t}\n\t\treturn file;\n\t});\n\treturn {\n\t\tkind: \"extension_pi_worker\",\n\t\t...input,\n\t\t...(credentialFiles ? { credentialFiles } : {}),\n\t};\n}\n\n/** @public */\nexport function piServer(): PiServerReference {\n\treturn { kind: \"extension_pi_server\" };\n}\n\n/** @public */\nexport function builtinPiProvider(providerId: string): BuiltinPiProviderReference {\n\tif (providerId.trim() === \"\") {\n\t\tthrow new Error(\"Built-in Pi provider id must not be empty\");\n\t}\n\treturn { kind: \"builtin_pi_provider\", providerId };\n}\n\n/** @internal */\nexport function configuredPiProvider<TConfig>(\n\tproviderId: string,\n\tresolveModels: ConfiguredPiProviderReference<TConfig>[\"resolveModels\"],\n): ConfiguredPiProviderReference<TConfig> {\n\tif (providerId.trim() === \"\") {\n\t\tthrow new Error(\"Configured Pi provider id must not be empty\");\n\t}\n\treturn { kind: \"configured_pi_provider\", providerId, resolveModels };\n}\n\n/** @public */\nexport type ModelProviderWorker<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n> =\n\t| PiWorkerReference<TConfig, TValue>\n\t| BuiltinPiProviderReference\n\t| ConfiguredPiProviderReference<TConfig>;\n\n/** @public */\nexport type ModelProviderServer = PiServerReference | BuiltinPiProviderReference;\n\n/** @public */\nexport interface ModelProviderSecretsContext<TConfig = unknown, TCredential = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly credential: TCredential | null;\n\t/** @internal */\n\treadonly options: Readonly<Record<string, string>>;\n}\n\n/** @public */\nexport interface ParsedModelProviderConfig<TConfig = unknown, TCredential = unknown> {\n\t/** Restart-scoped, non-secret provider configuration. @public */\n\treadonly config: TConfig;\n\t/** Optional credential used only to initialize an empty durable credential store. @internal */\n\treadonly credential?: TCredential;\n}\n\n/** @public */\nexport interface ModelProviderCredentialDefinition<TCredential = unknown> {\n\t/** Validates configured, durable, and worker-refreshed credential data. @public */\n\tparse?(value: unknown): TCredential;\n}\n\n/** @public */\nexport interface ModelProviderDefinition<\n\tTConfig = unknown,\n\tTCredential = unknown,\n\tTWorkerConfig extends ProviderJsonObject = ProviderJsonObject,\n> {\n\t/** @public */\n\treadonly id: string;\n\t/** @public */\n\tparseConfig(raw: unknown): ParsedModelProviderConfig<TConfig, TCredential>;\n\t/** @public */\n\treadonly worker: ModelProviderWorker<TConfig, TWorkerConfig>;\n\t/** @public */\n\treadonly server?: ModelProviderServer;\n\t/** @public */\n\tmodels(\n\t\tctx: ModelProviderModelsContext<TConfig>,\n\t): readonly ProviderModelStatus[] | Promise<readonly ProviderModelStatus[]>;\n\t/** @public */\n\treadonly options?: ProviderOptionsDefinition<TConfig>;\n\t/** @public */\n\tsecrets(ctx: ModelProviderSecretsContext<TConfig, TCredential>): Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly credential?: ModelProviderCredentialDefinition<TCredential>;\n}\n\n/** @public */\nexport function defineModelProvider<\n\tTConfig = unknown,\n\tTCredential = unknown,\n\tTWorkerConfig extends ProviderJsonObject = ProviderJsonObject,\n>(\n\tdefinition: ModelProviderDefinition<TConfig, TCredential, TWorkerConfig>,\n): ModelProviderDefinition<TConfig, TCredential, TWorkerConfig> {\n\tif (definition.id.trim() === \"\") {\n\t\tthrow new Error(\"Model provider id must not be empty\");\n\t}\n\treturn definition;\n}\n\n/** Type-erased provider definition used after its typed boundary has been established. @public */\n// biome-ignore lint/suspicious/noExplicitAny: provider sets intentionally erase provider-owned generic types\nexport type ErasedModelProviderDefinition = ModelProviderDefinition<any, any, any>;\n\n/** @public */\nexport interface ModelProviderSetEntry {\n\t/** @public */\n\treadonly definition: ErasedModelProviderDefinition;\n\t/** Owner-scoped fragment passed to this provider's parseConfig(). @public */\n\treadonly rawConfig: unknown;\n}\n\n/** Resolves every provider owned by one extension from its owner-scoped configuration. @public */\nexport type ModelProviderSet = (ownerConfig: unknown) => readonly ModelProviderSetEntry[];\n\n/** @public */\nexport function defineModelProviders(resolve: ModelProviderSet): ModelProviderSet {\n\treturn resolve;\n}\n\n/** @public */\nexport interface PiWorkerSecretBag {\n\t/** @public */\n\tget(key: string): string | undefined;\n\t/** @public */\n\trequire(key: string): string;\n\t/** @public */\n\tkeys(): readonly string[];\n}\n\n/** @public */\nexport interface PiWorkerContributionContext {\n\t/** @public */\n\treadonly model: {\n\t\t/** @public */\n\t\treadonly providerId: string;\n\t\t/** @public */\n\t\treadonly modelId: string;\n\t};\n\t/** @public */\n\treadonly options: Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly workerConfig: ProviderJsonObject | null;\n\t/** @public */\n\treadonly secrets: PiWorkerSecretBag;\n\t/** @public */\n\treport(event: Readonly<Record<string, ProviderJsonValue>>): void;\n}\n\n/** @public */\nexport type PiWorkerContribution = (\n\tpi: {\n\t\t/** @public */\n\t\tregisterProvider(name: string, config: object): void;\n\t},\n\tctx: PiWorkerContributionContext,\n) => void | Promise<void>;\n\n/** @public */\nexport function definePiWorker(contribution: PiWorkerContribution): PiWorkerContribution {\n\treturn contribution;\n}\n\n/**\n * Report each distinct configured model as available or unavailable based solely\n * on credential status. Providers that do not perform runtime model probing can\n * delegate their `models()` callback to this helper.\n */\n/** @public */\nexport function credentialBasedModelStatuses(\n\tconfiguredModels: readonly ConfiguredProviderModel[],\n\tcredentialStatus: ProviderCredentialStatus,\n\tunavailableReason: string,\n): readonly ProviderModelStatus[] {\n\treturn [...new Set(configuredModels.map((configured) => configured.modelId))].map((modelId) => ({\n\t\tmodelId,\n\t\tavailability: credentialStatus.available ? \"available\" : \"unavailable\",\n\t\t...(credentialStatus.available ? {} : { safeReason: unavailableReason }),\n\t}));\n}\n","import {\n\thumanizeProcessLabel,\n\ttype ProcessFlowEdge,\n\ttype ProcessFlowEndState,\n\ttype ProcessFlowNode,\n\ttype ProcessFlowView,\n\ttype ProcessTurnTerminalLifecycleStatus,\n\ttype ProcessTurnTransition,\n\ttype TurnId,\n\ttrimToNull,\n} from \"@leitwerk-dev/domain\";\nimport type { ProcessGraphTurnView, ProcessGraphView } from \"./process-graph.js\";\n\n/**\n * Human/operator turns are routing decisions: they pick which path the process\n * takes but perform no work themselves. They are collapsed out of the flow graph\n * so the chart shows only work nodes (LLM/automatic/server) and end states, with\n * the operator's decision surfaced as the edge label between the real nodes.\n */\nfunction isRoutingTurn(turn: ProcessGraphTurnView): boolean {\n\treturn turn.turnType === \"human\";\n}\n\n/**\n * Picks the work turn an operator decision is *about* — its anchor. A decision is\n * both a join (many work turns lead into it) and a split (the operator picks one\n * of several actions). Folding the split onto every join predecessor would invent\n * an N×M mesh of work→work edges that no single step actually connects (e.g. a\n * \"review implementation → simplify\" edge that does not exist in the process).\n *\n * Instead, every operator decision collapses into exactly one anchor work node:\n * - edges that lead *into* the decision are redirected to the anchor, and\n * - the decision's action edges are emitted *from* the anchor.\n *\n * That yields N+M edges around one real node instead of N×M fabricated ones, and\n * every surviving edge still maps to a single declared transition with one human\n * hop folded into the work node that owns the decision.\n *\n * The anchor is the work predecessor the decision belongs to, preferring a\n * predecessor on the declared happy path (earliest position), then the earliest\n * declared work predecessor. Decisions reached only from other decisions inherit\n * their predecessor decision's anchor.\n */\nfunction computeRoutingAnchors(\n\tgraph: ProcessGraphView,\n\troutingIds: ReadonlySet<TurnId>,\n): Map<TurnId, TurnId> {\n\t// Happy-path turns come first, then the remaining turns in declaration order.\n\tconst preferenceIndex = new Map(\n\t\t[...new Set([...(graph.happyPath ?? []), ...graph.turns.keys()])].map((turnId, index) => [\n\t\t\tturnId,\n\t\t\tindex,\n\t\t]),\n\t);\n\n\tconst workPredecessors = new Map<TurnId, TurnId[]>();\n\tconst routingPredecessors = new Map<TurnId, TurnId[]>();\n\tfor (const routingId of routingIds) {\n\t\tworkPredecessors.set(routingId, []);\n\t\troutingPredecessors.set(routingId, []);\n\t}\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst next = transition.nextTurnId;\n\t\t\tif (next === undefined || !routingIds.has(next) || next === turnId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (routingIds.has(turnId)) {\n\t\t\t\troutingPredecessors.get(next)?.push(turnId);\n\t\t\t} else {\n\t\t\t\tworkPredecessors.get(next)?.push(turnId);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst pickPreferred = (candidates: readonly TurnId[]): TurnId | undefined => {\n\t\tlet best: TurnId | undefined;\n\t\tlet bestIndex = Number.POSITIVE_INFINITY;\n\t\tfor (const candidate of candidates) {\n\t\t\tconst index = preferenceIndex.get(candidate) ?? Number.POSITIVE_INFINITY;\n\t\t\tif (best === undefined || index < bestIndex) {\n\t\t\t\tbest = candidate;\n\t\t\t\tbestIndex = index;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t};\n\n\tconst anchors = new Map<TurnId, TurnId>();\n\tfor (const routingId of routingIds) {\n\t\tconst preferred = pickPreferred(workPredecessors.get(routingId) ?? []);\n\t\tif (preferred !== undefined) {\n\t\t\tanchors.set(routingId, preferred);\n\t\t}\n\t}\n\n\t// Decisions reached only from other decisions resolve transitively to the\n\t// anchor of a predecessor decision. Iterate to a fixpoint.\n\tlet changed = true;\n\twhile (changed) {\n\t\tchanged = false;\n\t\tfor (const routingId of routingIds) {\n\t\t\tif (anchors.has(routingId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const predecessor of routingPredecessors.get(routingId) ?? []) {\n\t\t\t\tconst predecessorAnchor = anchors.get(predecessor);\n\t\t\t\tif (predecessorAnchor !== undefined) {\n\t\t\t\t\tanchors.set(routingId, predecessorAnchor);\n\t\t\t\t\tchanged = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Any decision still unresolved (an isolated decision-only cluster) falls back\n\t// to the first declared work turn so the graph stays connected and deterministic.\n\tconst fallbackWork = [...graph.turns.keys()].find((turnId) => !routingIds.has(turnId));\n\tif (fallbackWork !== undefined) {\n\t\tfor (const routingId of routingIds) {\n\t\t\tif (!anchors.has(routingId)) {\n\t\t\t\tanchors.set(routingId, fallbackWork);\n\t\t\t}\n\t\t}\n\t}\n\treturn anchors;\n}\n\nfunction redirectTransition(\n\ttransition: ProcessTurnTransition,\n\tresolveWork: (turnId: TurnId) => TurnId,\n): ProcessTurnTransition {\n\tconst label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);\n\tif (transition.lifecycleStatus !== undefined) {\n\t\treturn {\n\t\t\tlifecycleStatus: transition.lifecycleStatus,\n\t\t\t...(label ? { outcome: label } : {}),\n\t\t};\n\t}\n\tconst next = transition.nextTurnId;\n\tif (next === undefined) {\n\t\treturn { ...(label ? { outcome: label } : {}) };\n\t}\n\treturn {\n\t\tnextTurnId: resolveWork(next),\n\t\t...(label ? { outcome: label } : {}),\n\t};\n}\n\nfunction dedupeTransitions(transitions: readonly ProcessTurnTransition[]): ProcessTurnTransition[] {\n\tconst result = new Map<string, ProcessTurnTransition>();\n\tfor (const transition of transitions) {\n\t\tconst label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);\n\t\tconst key = `${transition.nextTurnId ?? \"\"}|${transition.lifecycleStatus ?? \"\"}|${label ?? \"\"}`;\n\t\tif (result.has(key)) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.set(key, transition);\n\t}\n\treturn [...result.values()];\n}\n\n/**\n * Removes routing (human) turns from a process graph by merging each one into a\n * single anchor work node (see {@link computeRoutingAnchors}). Edges into a\n * decision are redirected to its anchor, and the decision's action edges are\n * re-emitted from that anchor. Self-loops produced by the merge are left in place\n * here and dropped later during edge construction. Entry turns and the declared\n * happy path are remapped/filtered to stay consistent.\n */\n/** @internal */\nexport function collapseRoutingTurns(graph: ProcessGraphView): ProcessGraphView {\n\tconst routingIds = new Set<TurnId>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tif (isRoutingTurn(turn)) {\n\t\t\troutingIds.add(turnId);\n\t\t}\n\t}\n\tif (routingIds.size === 0 || routingIds.size === graph.turns.size) {\n\t\treturn graph;\n\t}\n\n\tconst anchors = computeRoutingAnchors(graph, routingIds);\n\tconst resolveWork = (turnId: TurnId): TurnId =>\n\t\troutingIds.has(turnId) ? (anchors.get(turnId) ?? turnId) : turnId;\n\n\t// Group each decision's action transitions onto its anchor work turn.\n\tconst inheritedByAnchor = new Map<TurnId, ProcessTurnTransition[]>();\n\tfor (const routingId of routingIds) {\n\t\tconst anchor = anchors.get(routingId);\n\t\tif (anchor === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst routingTurn = graph.turns.get(routingId);\n\t\tif (!routingTurn) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst bucket = inheritedByAnchor.get(anchor) ?? [];\n\t\tfor (const transition of routingTurn.transitions) {\n\t\t\tbucket.push(redirectTransition(transition, resolveWork));\n\t\t}\n\t\tinheritedByAnchor.set(anchor, bucket);\n\t}\n\n\tconst turns = new Map<TurnId, ProcessGraphTurnView>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tif (routingIds.has(turnId)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst transitions = [\n\t\t\t...turn.transitions.map((transition) => redirectTransition(transition, resolveWork)),\n\t\t\t...(inheritedByAnchor.get(turnId) ?? []),\n\t\t];\n\t\tturns.set(turnId, { ...turn, transitions: dedupeTransitions(transitions) });\n\t}\n\n\tconst entryTurnIds = new Set<TurnId>();\n\tfor (const entry of graph.entryTurnIds) {\n\t\tif (graph.turns.has(entry)) {\n\t\t\tentryTurnIds.add(resolveWork(entry));\n\t\t}\n\t}\n\n\tconst filteredHappyPath = graph.happyPath?.filter((turnId) => !routingIds.has(turnId)) ?? null;\n\n\treturn {\n\t\tid: graph.id,\n\t\tprimaryEntryTurnId: resolveWork(graph.primaryEntryTurnId),\n\t\tentryTurnIds,\n\t\thappyPath: filteredHappyPath && filteredHappyPath.length > 0 ? filteredHappyPath : null,\n\t\tturns,\n\t};\n}\n\n/**\n * Best-effort spine when a process does not declare an explicit happy path.\n * Walks `nextTurnId` edges breadth-first from the entry turn to the nearest turn\n * that can reach a `completed` terminal, preferring the shortest forward path and\n * breaking ties by transition declaration order. Returns `[entry]` when no\n * completing path exists.\n */\nfunction deriveSpine(graph: ProcessGraphView, entry: TurnId): TurnId[] {\n\tconst predecessor = new Map<TurnId, TurnId | null>([[entry, null]]);\n\tconst queue: TurnId[] = [entry];\n\tlet goal: TurnId | null = null;\n\tfor (const current of queue) {\n\t\tconst turn = graph.turns.get(current);\n\t\tif (!turn) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (turn.transitions.some((transition) => transition.lifecycleStatus === \"completed\")) {\n\t\t\tgoal = current;\n\t\t\tbreak;\n\t\t}\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst next = transition.nextTurnId;\n\t\t\tif (next === undefined || predecessor.has(next) || !graph.turns.has(next)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpredecessor.set(next, current);\n\t\t\tqueue.push(next);\n\t\t}\n\t}\n\n\tif (goal === null) {\n\t\treturn [entry];\n\t}\n\tconst reversed: TurnId[] = [];\n\tlet cursor: TurnId | null = goal;\n\twhile (cursor !== null) {\n\t\treversed.push(cursor);\n\t\tcursor = predecessor.get(cursor) ?? null;\n\t}\n\treturn reversed.reverse();\n}\n\n/**\n * Assigns each non-spine turn to the spine node it hangs off. A branch is anchored\n * to the lowest-index spine node that can reach it without passing through another\n * spine node, so offshoots attach to the earliest spine step that launches them.\n */\nfunction deriveBranchAnchors(\n\tgraph: ProcessGraphView,\n\tspineIndexByTurn: ReadonlyMap<TurnId, number>,\n): Map<TurnId, TurnId> {\n\tconst anchorByTurn = new Map<TurnId, TurnId>();\n\tconst orderedSpine = [...spineIndexByTurn.entries()]\n\t\t.sort((left, right) => left[1] - right[1])\n\t\t.map(([turnId]) => turnId);\n\n\tfor (const spineTurnId of orderedSpine) {\n\t\tconst stack: TurnId[] = [spineTurnId];\n\t\tconst visited = new Set<TurnId>([spineTurnId]);\n\t\twhile (stack.length > 0) {\n\t\t\tconst current = stack.pop() as TurnId;\n\t\t\tconst turn = graph.turns.get(current);\n\t\t\tif (!turn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const transition of turn.transitions) {\n\t\t\t\tconst next = transition.nextTurnId;\n\t\t\t\tif (next === undefined || !graph.turns.has(next) || visited.has(next)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvisited.add(next);\n\t\t\t\tif (spineIndexByTurn.has(next)) {\n\t\t\t\t\t// Stop at spine nodes; do not traverse through them.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!anchorByTurn.has(next)) {\n\t\t\t\t\tanchorByTurn.set(next, spineTurnId);\n\t\t\t\t}\n\t\t\t\tstack.push(next);\n\t\t\t}\n\t\t}\n\t}\n\treturn anchorByTurn;\n}\n\nfunction transitionLabel(transition: { outcome?: string; trigger?: string }): string | null {\n\t// Route every operator-facing edge label through the shared humanizer so the\n\t// diagram shows nice Title Case names (e.g. `approve_plan` -> `Approve Plan`),\n\t// consistent with action forms and ready for future localization.\n\tconst raw = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);\n\treturn raw === null ? null : humanizeProcessLabel(raw);\n}\n\n/**\n * Projects a process graph into a spine-first flow view for operator-facing\n * diagrams. The spine is the declared happy path (or a derived best-effort path\n * when none is declared); every other turn hangs off the spine as a branch.\n * The `aborted` end state is always present because abort is reachable from any\n * active turn, even when no explicit transition targets it.\n */\n/** @internal */\nexport function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowView {\n\tconst graph = collapseRoutingTurns(rawGraph);\n\tconst entryTurnIds = [...graph.entryTurnIds].filter((turnId) => graph.turns.has(turnId));\n\tconst primaryEntry = graph.turns.has(graph.primaryEntryTurnId)\n\t\t? graph.primaryEntryTurnId\n\t\t: [...graph.turns.keys()][0];\n\n\tconst declaredSpine = graph.happyPath?.filter((turnId) => graph.turns.has(turnId)) ?? null;\n\tconst spine =\n\t\tdeclaredSpine && declaredSpine.length > 0\n\t\t\t? [...declaredSpine]\n\t\t\t: primaryEntry !== undefined\n\t\t\t\t? deriveSpine(graph, primaryEntry)\n\t\t\t\t: [];\n\n\tconst spineIndexByTurn = new Map<TurnId, number>();\n\tspine.forEach((turnId, index) => {\n\t\tspineIndexByTurn.set(turnId, index);\n\t});\n\n\tconst anchorByTurn = deriveBranchAnchors(graph, spineIndexByTurn);\n\tconst entrySet = new Set(entryTurnIds);\n\n\tconst nodes: ProcessFlowNode[] = [];\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tconst spineIndex = spineIndexByTurn.get(turnId) ?? null;\n\t\tnodes.push({\n\t\t\tturnId,\n\t\t\tdescription: trimToNull(turn.description) ?? turnId,\n\t\t\tturnType: turn.turnType,\n\t\t\trole: spineIndex === null ? \"branch\" : \"spine\",\n\t\t\tspineIndex,\n\t\t\tanchorTurnId: spineIndex === null ? (anchorByTurn.get(turnId) ?? null) : null,\n\t\t\tisEntry: entrySet.has(turnId),\n\t\t});\n\t}\n\n\tconst edges: ProcessFlowEdge[] = [];\n\tconst terminalStatuses = new Set<ProcessTurnTerminalLifecycleStatus>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst label = transitionLabel(transition);\n\t\t\tif (transition.lifecycleStatus !== undefined) {\n\t\t\t\tterminalStatuses.add(transition.lifecycleStatus);\n\t\t\t\tedges.push({\n\t\t\t\t\tfrom: turnId,\n\t\t\t\t\tto: null,\n\t\t\t\t\tlifecycleStatus: transition.lifecycleStatus,\n\t\t\t\t\tkind: \"terminal\",\n\t\t\t\t\tlabel,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst next = transition.nextTurnId;\n\t\t\t// Skip self-loops: an edge that leaves and re-enters the same box adds\n\t\t\t// clutter without conveying additional flow.\n\t\t\tif (next === undefined || next === turnId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst fromIndex = spineIndexByTurn.get(turnId);\n\t\t\tconst toIndex = spineIndexByTurn.get(next);\n\t\t\tlet kind: ProcessFlowEdge[\"kind\"];\n\t\t\tif (fromIndex !== undefined && toIndex !== undefined) {\n\t\t\t\tkind = toIndex === fromIndex + 1 ? \"forward\" : \"loopback\";\n\t\t\t} else {\n\t\t\t\tkind = \"branch\";\n\t\t\t}\n\t\t\tedges.push({ from: turnId, to: next, lifecycleStatus: null, kind, label });\n\t\t}\n\t}\n\n\tconst endStates: ProcessFlowEndState[] = [];\n\tfor (const status of terminalStatuses) {\n\t\tendStates.push({ lifecycleStatus: status, synthetic: false });\n\t}\n\tif (!terminalStatuses.has(\"aborted\")) {\n\t\tendStates.push({ lifecycleStatus: \"aborted\", synthetic: true });\n\t}\n\tendStates.sort((left, right) => left.lifecycleStatus.localeCompare(right.lifecycleStatus));\n\n\treturn {\n\t\tprocessId: graph.id,\n\t\tentryTurnIds,\n\t\tspine,\n\t\tnodes,\n\t\tedges,\n\t\tendStates,\n\t};\n}\n","import type {\n\tExtensionProcessDefinition,\n\tProcessLauncherAPI,\n\tProcessLauncherDefinition,\n} from \"./extension-api.js\";\nimport { cloneMap, registerUnique } from \"./registry-utils.js\";\n\n/** @public */\nexport interface BuiltProcessLauncherDefinition<TParams = unknown> {\n\t/** @public */\n\tlaunchers: ReadonlyMap<string, ProcessLauncherDefinition<TParams>>;\n}\n\nfunction validateLauncherDefinition<TParams>(def: ProcessLauncherDefinition<TParams>): void {\n\tif (!def.id.trim()) {\n\t\tthrow new Error(\"Launcher id is required\");\n\t}\n\tif (!def.label.trim()) {\n\t\tthrow new Error(`Launcher '${def.id}' must define a non-empty label`);\n\t}\n\tif (!def.description.trim()) {\n\t\tthrow new Error(`Launcher '${def.id}' must define a non-empty description`);\n\t}\n\tif (def.visibility !== \"ui\") {\n\t\tthrow new Error(`Launcher '${def.id}' has unsupported visibility`);\n\t}\n\tif (!def.ui) {\n\t\tthrow new Error(`UI launcher '${def.id}' must define a ui block`);\n\t}\n}\n\n/** @internal */\nexport function createProcessLauncherBuilder<TParams = unknown>(): ProcessLauncherAPI<TParams> & {\n\t/** @internal */\n\tgetDefinition(): BuiltProcessLauncherDefinition<TParams>;\n} {\n\tconst launchers = new Map<string, ProcessLauncherDefinition<TParams>>();\n\n\treturn {\n\t\tlauncher(def: ProcessLauncherDefinition<TParams>) {\n\t\t\tregisterUnique(launchers, def.id, def, {\n\t\t\t\tduplicateMessage: `Launcher '${def.id}' is already registered`,\n\t\t\t\tvalidate: validateLauncherDefinition,\n\t\t\t});\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\tlaunchers: cloneMap(launchers),\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** @public */\nexport function buildProcessLaunchers<TParams = unknown, TState = unknown>(\n\tprocess: ExtensionProcessDefinition<TParams, TState>,\n): BuiltProcessLauncherDefinition<TParams> | undefined {\n\tif (!process.launchers) {\n\t\treturn undefined;\n\t}\n\tconst builder = createProcessLauncherBuilder<TParams>();\n\tprocess.launchers(builder);\n\treturn builder.getDefinition();\n}\n","import type {\n\tExtensionProcessDefinition,\n\tProcessWatcherAPI,\n\tProcessWatcherDefinition,\n} from \"./extension-api.js\";\nimport { cloneMap, registerUnique } from \"./registry-utils.js\";\n\n/** @public */\nexport interface BuiltProcessWatcherDefinition<TParams = unknown> {\n\t/** @public */\n\twatchers: ReadonlyMap<string, ProcessWatcherDefinition<TParams, unknown, unknown>>;\n}\n\nfunction validateWatcherDefinition<TParams>(\n\tdef: ProcessWatcherDefinition<TParams, unknown, unknown>,\n): void {\n\tif (!def.id.trim()) {\n\t\tthrow new Error(\"Process watcher id is required\");\n\t}\n\tif (!def.label.trim()) {\n\t\tthrow new Error(`Process watcher '${def.id}' must define a non-empty label`);\n\t}\n\tif (!def.description.trim()) {\n\t\tthrow new Error(`Process watcher '${def.id}' must define a non-empty description`);\n\t}\n\tif (!def.source || def.source.id.trim() === \"\") {\n\t\tthrow new Error(`Process watcher '${def.id}' must define a watcher source`);\n\t}\n}\n\n/** @internal */\nexport function createProcessWatcherBuilder<TParams = unknown>(): ProcessWatcherAPI<TParams> & {\n\t/** @internal */\n\tgetDefinition(): BuiltProcessWatcherDefinition<TParams>;\n} {\n\tconst watchers = new Map<string, ProcessWatcherDefinition<TParams, unknown, unknown>>();\n\n\treturn {\n\t\twatcher<TEvent = unknown, TConfig = unknown>(\n\t\t\tdef: ProcessWatcherDefinition<TParams, TEvent, TConfig>,\n\t\t) {\n\t\t\tregisterUnique(\n\t\t\t\twatchers,\n\t\t\t\tdef.id,\n\t\t\t\tdef as unknown as ProcessWatcherDefinition<TParams, unknown, unknown>,\n\t\t\t\t{\n\t\t\t\t\tduplicateMessage: `Process watcher '${def.id}' is already registered`,\n\t\t\t\t\tvalidate: validateWatcherDefinition,\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\twatchers: cloneMap(watchers),\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** @public */\nexport function buildProcessWatchers<TParams = unknown, TState = unknown>(\n\tprocess: ExtensionProcessDefinition<TParams, TState>,\n): BuiltProcessWatcherDefinition<TParams> | undefined {\n\tif (!process.watchers) {\n\t\treturn undefined;\n\t}\n\tconst builder = createProcessWatcherBuilder<TParams>();\n\tprocess.watchers(builder);\n\treturn builder.getDefinition();\n}\n","/** Object parameters for a tool bound to a current process project. @public */\nexport function projectParameters(\n\tproperties: Record<string, unknown> = {},\n\trequired: readonly string[] = Object.keys(properties),\n): Record<string, unknown> {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {\n\t\t\tprojectKey: { type: \"string\", description: \"Current process project key\" },\n\t\t\t...properties,\n\t\t},\n\t\trequired: [\"projectKey\", ...required],\n\t};\n}\n\n/** @internal */\nexport function objectArg(\n\tvalue: unknown,\n\tmessage = \"Tool arguments must be an object\",\n): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(message);\n\treturn value as Record<string, unknown>;\n}\n\n/** Read required integration-tool arguments at the runtime boundary. @internal */\nexport function stringArg(args: Record<string, unknown>, name: string): string {\n\tconst value = args[name];\n\tif (typeof value !== \"string\" || !value.trim())\n\t\tthrow new Error(`'${name}' must be a non-empty string`);\n\treturn value.trim();\n}\n\n/** @internal */\nexport function numberArg(args: Record<string, unknown>, name: string): number {\n\tconst value = args[name];\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0)\n\t\tthrow new Error(`'${name}' must be a positive integer`);\n\treturn value;\n}\n","import type { LaunchModelConfigInput } from \"@leitwerk-dev/domain\";\nimport type { ProcessWatcherSource } from \"./extension-api.js\";\nimport { objectArg } from \"./tool-arguments.js\";\n\nconst record = (value: unknown, subject: string) =>\n\tobjectArg(value, `${subject} must be an object`);\n\nfunction nonEmptyString(value: unknown, path: string): string {\n\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\tthrow new Error(`${path} must be a non-empty string`);\n\t}\n\treturn value;\n}\n\n/** Parse the shared launch-model fragment nested inside extension-owned watcher config. @public */\nexport function parseProcessWatcherLaunchModelConfig(value: unknown): LaunchModelConfigInput & {\n\t/** @internal */\n\tskillIds: string[];\n} {\n\tif (value === undefined) return { defaultModelProfileId: null, turnConfigs: {}, skillIds: [] };\n\tconst launch = record(value, \"launch\");\n\tconst rawSkills = launch.skills === undefined ? [] : launch.skills;\n\tif (!Array.isArray(rawSkills)) throw new Error(\"launch.skills must be an array\");\n\tconst skillIds = rawSkills.map((skill, index) => nonEmptyString(skill, `launch.skills.${index}`));\n\tif (new Set(skillIds).size !== skillIds.length)\n\t\tthrow new Error(\"launch.skills contains duplicates\");\n\tconst rawTurns =\n\t\tlaunch.turn_configs === undefined ? {} : record(launch.turn_configs, \"launch.turn_configs\");\n\treturn {\n\t\tdefaultModelProfileId:\n\t\t\tlaunch.default_model_profile === undefined\n\t\t\t\t? null\n\t\t\t\t: nonEmptyString(launch.default_model_profile, \"launch.default_model_profile\"),\n\t\tturnConfigs: Object.fromEntries(\n\t\t\tObject.entries(rawTurns).map(([turnId, value]) => {\n\t\t\t\tconst turn = record(value, `launch.turn_configs.${turnId}`);\n\t\t\t\treturn [\n\t\t\t\t\tturnId,\n\t\t\t\t\t{\n\t\t\t\t\t\tmodelProfileId:\n\t\t\t\t\t\t\tturn.model_profile === undefined\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: nonEmptyString(turn.model_profile, `launch.turn_configs.${turnId}.model_profile`),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}),\n\t\t),\n\t\tskillIds,\n\t};\n}\n\n/** @public */\nexport function defineProcessWatcherSource<TConfig, TEvent = unknown>(\n\tsource: ProcessWatcherSource<TConfig, TEvent>,\n): ProcessWatcherSource<TConfig, TEvent> {\n\tif (source.id.trim() === \"\") {\n\t\tthrow new Error(\"Process watcher source id must not be empty\");\n\t}\n\tif (source.label.trim() === \"\") {\n\t\tthrow new Error(`Process watcher source '${source.id}' must define a non-empty label`);\n\t}\n\treturn source;\n}\n","import type { IntegrationToolExecutionContext } from \"./extension-api.js\";\nimport { objectArg } from \"./tool-arguments.js\";\n\n/** @public */\nexport interface RepositoryProjectBinding {\n\t/** @public */\n\towner: string;\n\t/** @public */\n\trepo: string;\n\t/** @public */\n\tprofile: string;\n}\n\n/** Validate an authorized project's binding, retaining extension-selected legacy metadata. @public */\nexport function resolveRepositoryProjectBinding(\n\tctx: Pick<IntegrationToolExecutionContext, \"project\" | \"process\">,\n\tprovider: string,\n\tlegacyMetadataKey?: string,\n): RepositoryProjectBinding {\n\tconst object = (value: unknown) => objectArg(value, `Invalid ${provider} project binding`);\n\tfunction text(value: unknown, key: string): string {\n\t\tif (typeof value !== \"string\" || !value.trim())\n\t\t\tthrow new Error(`${provider} binding ${key} must be a non-empty string`);\n\t\treturn value.trim();\n\t}\n\tif (!ctx.project || ctx.project.instanceId !== ctx.process.id)\n\t\tthrow new Error(\"An authorized process project is required\");\n\tconst metadata = object(ctx.project.metadata ?? {});\n\tconst useLegacy = legacyMetadataKey !== undefined && metadata[provider] === undefined;\n\tconst binding = object(metadata[useLegacy ? legacyMetadataKey : provider]);\n\tconst profile =\n\t\tuseLegacy || (legacyMetadataKey === undefined && binding.profile === undefined)\n\t\t\t? object(JSON.parse(ctx.process.paramsJson ?? \"{}\"))[`${provider}Profile`]\n\t\t\t: binding.profile;\n\treturn {\n\t\towner: text(binding.owner, \"owner\"),\n\t\trepo: text(binding.repo, \"repo\"),\n\t\tprofile: text(profile, \"profile\"),\n\t};\n}\n","import { asUnknownRecord } from \"@leitwerk-dev/domain\";\n\n/** @public */\nexport interface RepositoryFeedbackItem {\n\t/** @public */\n\tkind: \"conversation\" | \"review\" | \"inline\";\n\t/** @internal */\n\tid: number;\n\t/** @public */\n\tbody: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @public */\n\tauthor: string;\n\t/** @internal */\n\tpath?: string;\n\t/** @internal */\n\tline?: number | null;\n}\n\n/** Batch already-authorized, unseen feedback after its quiet period. @internal */\nexport function repositoryFeedbackBatch(\n\tunseen: readonly RepositoryFeedbackItem[],\n\tconfig: Record<`${RepositoryFeedbackItem[\"kind\"]}Cursor`, number> & {\n\t\t/** @internal */\n\t\tquietPeriodMs: number;\n\t},\n\tnow: number,\n) {\n\tif (!unseen.length) return null;\n\tconst latest = Math.max(...unseen.map((item) => Date.parse(item.createdAt) || 0));\n\tif (now - latest < config.quietPeriodMs) return null;\n\tconst cursors = {\n\t\t/** @internal */\n\t\tconversationCursor: config.conversationCursor,\n\t\t/** @internal */\n\t\treviewCursor: config.reviewCursor,\n\t\t/** @internal */\n\t\tinlineCursor: config.inlineCursor,\n\t};\n\tfor (const item of unseen) {\n\t\tconst key = `${item.kind}Cursor` as const;\n\t\tcursors[key] = Math.max(cursors[key], item.id);\n\t}\n\treturn {\n\t\t/** @internal */\n\t\tevent: {\n\t\t\t/** @internal */\n\t\t\tfeedbackIds: unseen.map(({ kind, id }) => ({\n\t\t\t\t/** @internal */\n\t\t\t\tkind,\n\t\t\t\t/** @internal */\n\t\t\t\tid,\n\t\t\t})),\n\t\t\t/** @internal */\n\t\t\tcursors,\n\t\t},\n\t\t/** @internal */\n\t\tmergeKey: `${cursors.conversationCursor}:${cursors.reviewCursor}:${cursors.inlineCursor}`,\n\t};\n}\n\n/** Normalize common forge feedback fields; reject empty bodies and missing identities. @internal */\nexport function normalizeRepositoryFeedback(\n\tkind: RepositoryFeedbackItem[\"kind\"],\n\titem: Record<string, unknown>,\n): RepositoryFeedbackItem | null {\n\tconst body = typeof item.body === \"string\" ? item.body.trim() : \"\";\n\tconst user = asUnknownRecord(item.user) ?? {};\n\tif (!body || typeof item.id !== \"number\" || typeof user.login !== \"string\") return null;\n\treturn {\n\t\tkind,\n\t\tid: item.id,\n\t\tbody,\n\t\tcreatedAt:\n\t\t\ttypeof item.submitted_at === \"string\"\n\t\t\t\t? item.submitted_at\n\t\t\t\t: typeof item.created_at === \"string\"\n\t\t\t\t\t? item.created_at\n\t\t\t\t\t: new Date(0).toISOString(),\n\t\tauthor: user.login,\n\t\t...(typeof item.path === \"string\" ? { path: item.path } : {}),\n\t\t...(typeof item.line === \"number\" ? { line: item.line } : {}),\n\t};\n}\n","import {\n\tWORKER_IPC_CONNECT_TOKEN_ENV,\n\tWORKER_IPC_RECONNECT_ENV,\n\tWORKER_SNAPSHOT_TOKEN_ENV,\n} from \"@leitwerk-dev/worker-protocol\";\n\n/** @public */\nexport type SubprocessEnvInput = Record<string, string | undefined>;\n\nexport const INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX = \"LEITWERK_INTERNAL_REPOSITORY_GIT_SSH_\";\nexport const INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX = \"LEITWERK_INTERNAL_REPOSITORY_GIT_HTTPS_\";\n\n/** @internal */\nexport const WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS = [\n\tWORKER_IPC_CONNECT_TOKEN_ENV,\n\tWORKER_IPC_RECONNECT_ENV,\n\tWORKER_SNAPSHOT_TOKEN_ENV,\n] as const;\n\nconst SENSITIVE_ENV_KEYS = new Set<string>([\n\t...WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS,\n\t\"SSH_AUTH_SOCK\",\n\t\"SSH_AGENT_PID\",\n\t\"GIT_SSH\",\n\t\"GIT_SSH_COMMAND\",\n\t\"GIT_ASKPASS\",\n\t\"SSH_ASKPASS\",\n]);\n\n/**\n * Builds an environment for worker-executed repository shell/tool commands.\n *\n * Worker IPC and session-snapshot credentials are valid only for the worker\n * process itself. Repository scripts, git hooks, package managers, and other\n * tool subprocesses must not receive them.\n */\n/** @internal */\nexport function sanitizeWorkerSubprocessEnv(\n\tbaseEnv: SubprocessEnvInput = process.env,\n\toverrides: SubprocessEnvInput = {},\n): NodeJS.ProcessEnv {\n\tconst sanitized: NodeJS.ProcessEnv = {};\n\tfor (const [key, value] of Object.entries({ ...baseEnv, ...overrides })) {\n\t\tif (\n\t\t\tSENSITIVE_ENV_KEYS.has(key) ||\n\t\t\tkey.startsWith(INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX) ||\n\t\t\tkey.startsWith(INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX) ||\n\t\t\tkey.startsWith(\"GIT_CONFIG_\") ||\n\t\t\t/(?:^|_)(?:TOKEN|API_KEY|PASSWORD|SECRET)$/.test(key) ||\n\t\t\tvalue === undefined\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tsanitized[key] = value;\n\t}\n\treturn sanitized;\n}\n","import {\n\tINTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX,\n\tINTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX,\n\ttype SubprocessEnvInput,\n\tsanitizeWorkerSubprocessEnv,\n} from \"./subprocess-env.js\";\n\nfunction wrapperKey(projectKey: string): string {\n\treturn `${INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX}${encodeURIComponent(projectKey).replace(/%/g, \"_\")}`;\n}\n\n/** Worker-internal registration; the wrapper path is never copied to ordinary subprocesses. @internal */\nexport function setRepositoryGitSshWrapper(projectKey: string, wrapperPath: string): void {\n\tprocess.env[wrapperKey(projectKey)] = wrapperPath;\n}\n\n/** @internal */\nexport function clearRepositoryGitSshWrappers(): void {\n\tfor (const key of Object.keys(process.env)) {\n\t\tif (key.startsWith(INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX)) delete process.env[key];\n\t}\n}\n\n/** @internal */\nexport function setRepositoryGitHttpsHelper(projectKey: string, helperPath: string): void {\n\tprocess.env[`${INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX}${encodeURIComponent(projectKey)}`] =\n\t\thelperPath;\n}\n\n/** @internal */\nexport function clearRepositoryGitHttpsHelpers(): void {\n\tfor (const key of Object.keys(process.env)) {\n\t\tif (key.startsWith(INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX)) delete process.env[key];\n\t}\n}\n\n/** Safe environment for a trusted Git invocation for one process project. @public */\nexport function repositoryGitSubprocessEnv(\n\tprojectKey: string,\n\toverrides: SubprocessEnvInput = {},\n): NodeJS.ProcessEnv {\n\tconst env = sanitizeWorkerSubprocessEnv(process.env, overrides);\n\tconst wrapper = process.env[wrapperKey(projectKey)];\n\tif (wrapper) env.GIT_SSH = wrapper;\n\tconst helper =\n\t\tprocess.env[`${INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX}${encodeURIComponent(projectKey)}`];\n\tif (helper) {\n\t\tconst config = [\n\t\t\t[\"credential.helper\", \"\"],\n\t\t\t[\"credential.helper\", `!${shellQuote(process.execPath)} ${shellQuote(helper)}`],\n\t\t\t[\"credential.useHttpPath\", \"true\"],\n\t\t\t[\"http.followRedirects\", \"false\"],\n\t\t\t[\"protocol.allow\", \"never\"],\n\t\t\t[\"protocol.https.allow\", \"always\"],\n\t\t];\n\t\tenv.GIT_CONFIG_COUNT = String(config.length);\n\t\tconfig.forEach(([key, value], index) => {\n\t\t\tenv[`GIT_CONFIG_KEY_${index}`] = key;\n\t\t\tenv[`GIT_CONFIG_VALUE_${index}`] = value;\n\t\t});\n\t\tenv.GIT_TERMINAL_PROMPT = \"0\";\n\t}\n\treturn env;\n}\n\n/** @public */\nexport function repositoryGitArgs(args: readonly string[]): string[] {\n\treturn [\"-c\", \"core.hooksPath=/dev/null\", ...args];\n}\n\nfunction shellQuote(value: string): string {\n\treturn \"'\" + value.replaceAll(\"'\", \"'\\\"'\\\"'\") + \"'\";\n}\n","import { IntegrationHttpClient } from \"./integration-http.js\";\nimport type { RepositoryIssue, RepositoryPullRequest } from \"./repository-types.js\";\n\n/** Common forge endpoints; extensions retain authentication and specialized operations. @public */\nexport class RepositoryHttpClient<Comment = Record<string, unknown>> extends IntegrationHttpClient {\n\t/** @internal */\n\tprotected repositoryPath(owner: string, repo: string): string {\n\t\treturn `/repos/${owner}/${repo}`;\n\t}\n\n\t/** @internal */\n\tgetIssue(owner: string, repo: string, number: number, signal?: AbortSignal) {\n\t\treturn this.request<RepositoryIssue>(`${this.repositoryPath(owner, repo)}/issues/${number}`, {\n\t\t\tsignal,\n\t\t});\n\t}\n\n\t/** @public */\n\tlistIssueComments(owner: string, repo: string, number: number, signal?: AbortSignal) {\n\t\treturn this.pages<Comment>(\n\t\t\t`${this.repositoryPath(owner, repo)}/issues/${number}/comments`,\n\t\t\tsignal,\n\t\t);\n\t}\n\n\t/** @public */\n\taddIssueComment(owner: string, repo: string, number: number, body: string, signal?: AbortSignal) {\n\t\treturn this.writeJson(\n\t\t\t`${this.repositoryPath(owner, repo)}/issues/${number}/comments`,\n\t\t\t\"POST\",\n\t\t\t{ body },\n\t\t\tsignal,\n\t\t);\n\t}\n\n\t/** @public */\n\tcreatePullRequest(\n\t\towner: string,\n\t\trepo: string,\n\t\tinput: {\n\t\t\t/** @public */\n\t\t\ttitle: string;\n\t\t\t/** @public */\n\t\t\tbody: string;\n\t\t\t/** @public */\n\t\t\thead: string;\n\t\t\t/** @public */\n\t\t\tbase: string;\n\t\t},\n\t) {\n\t\treturn this.writeJson<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls`,\n\t\t\t\"POST\",\n\t\t\tinput,\n\t\t);\n\t}\n\n\t/** @public */\n\tgetPullRequest(owner: string, repo: string, number: number, signal?: AbortSignal) {\n\t\treturn this.request<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls/${number}`,\n\t\t\t{ signal },\n\t\t);\n\t}\n\n\t/** @internal */\n\tlistPullRequests(owner: string, repo: string, state = \"open\") {\n\t\treturn this.pages<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls?state=${encodeURIComponent(state)}`,\n\t\t);\n\t}\n\n\t/** @public */\n\tupdatePullRequest(\n\t\towner: string,\n\t\trepo: string,\n\t\tnumber: number,\n\t\tpatch: Record<string, unknown>,\n\t\tsignal?: AbortSignal,\n\t) {\n\t\treturn this.writeJson<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls/${number}`,\n\t\t\t\"PATCH\",\n\t\t\tpatch,\n\t\t\tsignal,\n\t\t);\n\t}\n}\n","/** Canonical, credential-free HTTPS repository URL. Reject ambiguous Git credential paths. @internal */\nexport function repositoryHttpsUrl(value: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow new Error(\"Repository authentication requires a valid HTTPS URL\");\n\t}\n\tif (\n\t\turl.protocol !== \"https:\" ||\n\t\turl.username ||\n\t\turl.password ||\n\t\turl.search ||\n\t\turl.hash ||\n\t\t!url.pathname.slice(1) ||\n\t\t/[%\\\\\\s]/.test(url.pathname) ||\n\t\turl.pathname.split(\"/\").some((part) => part === \".\" || part === \"..\") ||\n\t\turl.href !== value\n\t)\n\t\tthrow new Error(\"Repository authentication requires a canonical credential-free HTTPS URL\");\n\treturn url;\n}\n","import { parseDurationMs } from \"@leitwerk-dev/watcher-utils\";\nimport { parseProcessWatcherLaunchModelConfig } from \"./process-watcher-source.js\";\nimport { objectArg } from \"./tool-arguments.js\";\n\n/** @public */\nexport interface RepositoryIssueWatcherConfig {\n\t/** @internal */\n\tprofile: string;\n\t/** @internal */\n\tpollInterval: string;\n\t/** @internal */\n\trepositories: {\n\t\t/** @internal */\n\t\tinclude: readonly string[];\n\t\t/** @internal */\n\t\texclude: readonly string[];\n\t};\n\t/** @internal */\n\tlabels: {\n\t\t/** @internal */\n\t\ttrigger: string;\n\t\t/** @internal */\n\t\tdone: string;\n\t};\n}\n\n/** @internal */\nexport function matchesRepository(\n\tconfig: Pick<RepositoryIssueWatcherConfig, \"repositories\">,\n\trepository: {\n\t\t/** @internal */\n\t\tfull_name: string;\n\t},\n): boolean {\n\tconst { include = [], exclude = [] } = config.repositories ?? {};\n\treturn (\n\t\t!exclude.includes(repository.full_name) &&\n\t\t(include.length === 0 || include.includes(repository.full_name))\n\t);\n}\n\nconst record = (value: unknown, subject: string) =>\n\tobjectArg(value, `${subject} must be an object`);\n\nfunction nonEmptyString(value: unknown, path: string): string {\n\tif (typeof value !== \"string\" || value.trim() === \"\")\n\t\tthrow new Error(`${path} must be a non-empty string`);\n\treturn value.trim();\n}\n\nfunction repositoryNames(value: unknown, path: string): readonly string[] {\n\tif (value === undefined) return [];\n\tif (!Array.isArray(value)) throw new Error(`${path} must be an array`);\n\treturn value.map((candidate, index) => {\n\t\tconst name = nonEmptyString(candidate, `${path}[${index}]`);\n\t\tif (!/^[^/\\s]+\\/[^/\\s]+$/.test(name))\n\t\t\tthrow new Error(`${path}[${index}] must use owner/name format`);\n\t\treturn name;\n\t});\n}\n\n/** Parse shared issue watcher fields; extensions choose the legacy type and label policy. @internal */\nexport function parseRepositoryIssueWatcherConfig(\n\traw: unknown,\n\tlegacyType: string,\n\tdistinctLabels = false,\n) {\n\tconst config = record(raw, \"watcher config\");\n\tif (config.type !== undefined && config.type !== legacyType)\n\t\tthrow new Error(`type must be '${legacyType}' when specified`);\n\tif (typeof config.enabled !== \"boolean\") throw new Error(\"enabled must be a boolean\");\n\tconst pollInterval = nonEmptyString(config.poll_interval, \"poll_interval\");\n\tif (parseDurationMs(pollInterval, -1, { allowHours: true }) <= 0)\n\t\tthrow new Error(\"poll_interval must be a positive duration\");\n\tconst labels = record(config.labels, \"labels\");\n\tconst repositories =\n\t\tconfig.repositories === undefined ? {} : record(config.repositories, \"repositories\");\n\tconst parsed: RepositoryIssueWatcherConfig = {\n\t\tprofile: nonEmptyString(config.profile, \"profile\"),\n\t\tpollInterval,\n\t\trepositories: {\n\t\t\tinclude: repositoryNames(repositories.include, \"repositories.include\"),\n\t\t\texclude: repositoryNames(repositories.exclude, \"repositories.exclude\"),\n\t\t},\n\t\tlabels: {\n\t\t\ttrigger: nonEmptyString(labels.trigger, \"labels.trigger\"),\n\t\t\tdone: nonEmptyString(labels.done, \"labels.done\"),\n\t\t},\n\t};\n\tif (distinctLabels && parsed.labels.trigger === parsed.labels.done)\n\t\tthrow new Error(\"Trigger and done labels must differ\");\n\treturn {\n\t\t/** @internal */\n\t\tconfig: parsed,\n\t\t/** @internal */\n\t\tenabled: config.enabled,\n\t\t/** @internal */\n\t\tlaunchModelConfig: parseProcessWatcherLaunchModelConfig(config.launch),\n\t};\n}\n\n/** @internal */\nexport function presentRepositoryIssueWatcherConfig(config: RepositoryIssueWatcherConfig) {\n\treturn {\n\t\t/** @internal */\n\t\ttargetSummary: `Profile ${config.profile} · trigger ${config.labels.trigger}`,\n\t\t/** @internal */\n\t\tdetails: [\n\t\t\t{\n\t\t\t\t/** @internal */\n\t\t\t\tlabel: \"Profile\",\n\t\t\t\t/** @internal */\n\t\t\t\tvalue: config.profile,\n\t\t\t},\n\t\t\t{ label: \"Included repositories\", value: config.repositories.include.join(\", \") || \"all\" },\n\t\t\t{ label: \"Excluded repositories\", value: config.repositories.exclude.join(\", \") || \"none\" },\n\t\t\t{ label: \"Trigger label\", value: config.labels.trigger },\n\t\t\t{ label: \"Done label\", value: config.labels.done },\n\t\t\t{ label: \"Poll interval\", value: config.pollInterval },\n\t\t],\n\t};\n}\n","import { IntegrationHttpError } from \"./integration-http.js\";\n\n/** @internal */\nexport async function existingObject<T>(read: () => Promise<T>): Promise<T | null> {\n\ttry {\n\t\treturn await read();\n\t} catch (error) {\n\t\tif (error instanceof IntegrationHttpError && error.status === 404) return null;\n\t\tthrow error;\n\t}\n}\n\n/** @internal */\nexport function matchesPatch(current: object, patch: Record<string, unknown>): boolean {\n\tconst fields = current as Record<string, unknown>;\n\treturn Object.entries(patch).every(([key, expected]) => {\n\t\tconst labelKey = Array.isArray(expected) && typeof expected[0] === \"number\" ? \"id\" : \"name\";\n\t\tconst normalize = (value: unknown) =>\n\t\t\tkey === \"labels\" && Array.isArray(value)\n\t\t\t\t? [\n\t\t\t\t\t\t...new Set(\n\t\t\t\t\t\t\tvalue.map((label) =>\n\t\t\t\t\t\t\t\ttypeof label === \"object\" && label !== null ? label[labelKey] : label,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t].sort()\n\t\t\t\t: value;\n\t\treturn JSON.stringify(normalize(fields[key])) === JSON.stringify(normalize(expected));\n\t});\n}\n","import { asUnknownRecord } from \"@leitwerk-dev/domain\";\n\n/** Parse common forge source fields, preserving polling defaults and permissive string handling. @internal */\nexport function parseRepositoryPullRequestConfig(value: unknown) {\n\tconst config = asUnknownRecord(value) ?? {};\n\tif (\n\t\ttypeof config.profile !== \"string\" ||\n\t\ttypeof config.owner !== \"string\" ||\n\t\ttypeof config.repo !== \"string\" ||\n\t\ttypeof config.prNumber !== \"number\"\n\t)\n\t\treturn null;\n\tconst terminalOutcome: \"merged\" | \"closed\" | undefined =\n\t\tconfig.terminalOutcome === \"merged\" || config.terminalOutcome === \"closed\"\n\t\t\t? config.terminalOutcome\n\t\t\t: undefined;\n\treturn {\n\t\t/** @internal */\n\t\tprofile: config.profile,\n\t\t/** @internal */\n\t\towner: config.owner,\n\t\t/** @internal */\n\t\trepo: config.repo,\n\t\t/** @internal */\n\t\tprNumber: config.prNumber,\n\t\t/** @internal */\n\t\tpollInterval: typeof config.pollInterval === \"string\" ? config.pollInterval : \"30s\",\n\t\t/** @internal */\n\t\tterminalOutcome,\n\t\t/** @internal */\n\t\tdisabled: config.disabled === true,\n\t};\n}\n\n/** @internal */\nexport function parseRepositoryFeedbackConfig(value: unknown) {\n\tconst base = parseRepositoryPullRequestConfig(value);\n\tconst config = asUnknownRecord(value) ?? {};\n\tif (!base) return null;\n\treturn {\n\t\t...base,\n\t\t/** @internal */\n\t\tconversationCursor:\n\t\t\ttypeof config.conversationCursor === \"number\" ? config.conversationCursor : 0,\n\t\t/** @internal */\n\t\treviewCursor: typeof config.reviewCursor === \"number\" ? config.reviewCursor : 0,\n\t\t/** @internal */\n\t\tinlineCursor: typeof config.inlineCursor === \"number\" ? config.inlineCursor : 0,\n\t\t/** @internal */\n\t\tquietPeriodMs: typeof config.quietPeriodMs === \"number\" ? config.quietPeriodMs : 120_000,\n\t};\n}\n\n/** @internal */\nexport function parseRepositoryIssueCancelledConfig(value: unknown) {\n\tconst config = asUnknownRecord(value) ?? {};\n\tif (\n\t\ttypeof config.profile !== \"string\" ||\n\t\ttypeof config.owner !== \"string\" ||\n\t\ttypeof config.repo !== \"string\" ||\n\t\ttypeof config.issueNumber !== \"number\" ||\n\t\ttypeof config.triggerLabel !== \"string\"\n\t)\n\t\treturn null;\n\treturn {\n\t\t/** @internal */\n\t\tprofile: config.profile,\n\t\t/** @internal */\n\t\towner: config.owner,\n\t\t/** @internal */\n\t\trepo: config.repo,\n\t\t/** @internal */\n\t\tissueNumber: config.issueNumber,\n\t\t/** @internal */\n\t\ttriggerLabel: config.triggerLabel,\n\t\t/** @internal */\n\t\tpollInterval: typeof config.pollInterval === \"string\" ? config.pollInterval : \"30s\",\n\t};\n}\n","import {\n\tassertValidProcessProductName,\n\ttype ProcessTurnStartSelection,\n\tresolveProcessTurnStartSelection,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tAutomaticTurnDefinition,\n\tExternalTurnDefinition,\n\tHumanTurnDefinition,\n\tLlmTurnDefinition,\n\tProcessToolOutcomeSpec,\n\tTurnDefinition,\n} from \"./define-process.js\";\nimport { llmTurn, resolveHumanTurnView } from \"./define-process.js\";\nimport { validatePiBuiltInToolArray } from \"./pi-config.js\";\nimport { REQUIRED_MARKDOWN_RESULT_TURN_RESULT } from \"./tool-renderers.js\";\nimport {\n\ttype OutcomeToolParameterSpec,\n\ttype ProcessActionPreviewDefinition,\n\ttype ProcessActionSchedulingDefinition,\n\tRESERVED_INTEGRATION_TOOL_NAMES,\n} from \"./types.js\";\n\n/** @internal */\nexport function isLlmTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is LlmTurnDefinition<string, TParams, TState> {\n\treturn turnDef.kind === \"llm\";\n}\n\n/** @internal */\nexport function isAutomaticTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is AutomaticTurnDefinition<string, TParams, TState> {\n\treturn turnDef.kind === \"automatic\";\n}\n\n/** @internal */\nexport function isHumanTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is HumanTurnDefinition<TParams, TState> {\n\treturn turnDef.kind === \"human\";\n}\n\n/** @internal */\nexport function isExternalTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is ExternalTurnDefinition<TParams, TState> {\n\treturn turnDef.kind === \"external\";\n}\n\n/** @internal */\nexport function resolveLlmTurnStartSelection<TOutcome extends string = string>(\n\tturnDef: Pick<LlmTurnDefinition<TOutcome>, \"branchType\" | \"startFrom\">,\n): ProcessTurnStartSelection {\n\treturn resolveProcessTurnStartSelection(turnDef);\n}\n\n/** @internal */\nexport function resolveLlmTurnRestorePrimaryLeafAfterTurn<TOutcome extends string = string>(\n\tturnDef: Pick<LlmTurnDefinition<TOutcome>, \"branchType\" | \"restorePrimaryLeafAfterTurn\">,\n): boolean {\n\treturn turnDef.restorePrimaryLeafAfterTurn ?? turnDef.branchType !== \"primary\";\n}\n\nexport function validateProcessActionPreviewDefinition(\n\tpreview: ProcessActionPreviewDefinition | undefined,\n\tcontext: string,\n): string[] {\n\tif (!preview) {\n\t\treturn [];\n\t}\n\tif (preview.kind === \"trigger\") {\n\t\treturn preview.trigger.trim() ? [] : [`${context} must declare a non-empty trigger preview`];\n\t}\n\tif (preview.kind === \"terminal\" || preview.turnId === null || preview.turnId.trim()) {\n\t\treturn [];\n\t}\n\treturn [`${context} must declare a non-empty fixed turn id when turnId is not null`];\n}\n\nexport function validateProcessActionSchedulingDefinition(\n\tscheduling: ProcessActionSchedulingDefinition | undefined,\n\tcontext: string,\n): string[] {\n\treturn validateProcessActionPreviewDefinition(scheduling?.preview, context);\n}\n\nfunction findDuplicateBy<TItem>(\n\titems: readonly TItem[],\n\tselectKey: (item: TItem) => string,\n): TItem | undefined {\n\tconst ids = new Set<string>();\n\tfor (const item of items) {\n\t\tconst key = selectKey(item);\n\t\tif (ids.has(key)) {\n\t\t\treturn item;\n\t\t}\n\t\tids.add(key);\n\t}\n\treturn undefined;\n}\n\nfunction validateProcessProductName(name: string): string[] {\n\ttry {\n\t\tassertValidProcessProductName(name);\n\t\treturn [];\n\t} catch (error) {\n\t\treturn [error instanceof Error ? error.message : String(error)];\n\t}\n}\n\nfunction validateOutcomeTurnResultContract<TParams = unknown, TState = unknown>(\n\tturnKindLabel: string,\n\tturnId: string,\n\toutcomes: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>> | undefined,\n\tturnEnd: unknown,\n): string[] {\n\tconst errors: string[] = [];\n\tconst hasOutcomeTools = Object.keys(outcomes ?? {}).length > 0;\n\tconst hasTurnEndResult = turnEnd !== undefined;\n\tif (!hasOutcomeTools && !hasTurnEndResult) {\n\t\terrors.push(\n\t\t\t`${turnKindLabel} turn '${turnId}' must declare at least one outcome tool or a turnEnd result`,\n\t\t);\n\t}\n\tif (hasOutcomeTools && hasTurnEndResult) {\n\t\terrors.push(`${turnKindLabel} turn '${turnId}' cannot declare both outcomes and turnEnd`);\n\t}\n\treturn errors;\n}\n\nfunction isValidOutcomeToolArrayItemType(type: unknown): boolean {\n\treturn type === \"string\" || type === \"number\" || type === \"boolean\" || type === \"object\";\n}\n\nfunction validateOutcomeToolParameters<TParams = unknown, TState = unknown>(\n\tturnKindLabel: string,\n\tturnId: string,\n\toutcomes: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>> | undefined,\n): string[] {\n\tconst errors: string[] = [];\n\tfor (const [outcome, outcomeSpec] of Object.entries(outcomes ?? {}) as Array<\n\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t>) {\n\t\tif (outcomeSpec.publishedProduct) {\n\t\t\terrors.push(...validateProcessProductName(outcomeSpec.publishedProduct));\n\t\t\tconst parameterName = outcomeSpec.turnResultMarkdownParameter?.trim() ?? \"\";\n\t\t\tif (!parameterName) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' but does not declare a turn-result markdown parameter`,\n\t\t\t\t);\n\t\t\t} else if (!Object.hasOwn(outcomeSpec.parameters, parameterName)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' from missing parameter '${parameterName}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const [paramName, paramSpec] of Object.entries(outcomeSpec.parameters) as Array<\n\t\t\t[string, OutcomeToolParameterSpec]\n\t\t>) {\n\t\t\tif (paramSpec.minItems !== undefined && paramSpec.type !== \"array\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minItems but is not an array`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (paramSpec.minimum !== undefined && paramSpec.type !== \"number\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minimum but is not a number`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (paramSpec.items !== undefined && paramSpec.type !== \"array\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares array items but is not an array`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (paramSpec.type === \"array\") {\n\t\t\t\tif (!paramSpec.items) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' is an array and must declare items`,\n\t\t\t\t\t);\n\t\t\t\t} else if (!isValidOutcomeToolArrayItemType(paramSpec.items.type)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares unsupported array item type '${String(paramSpec.items.type)}'`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n\nfunction assertNoValidationErrors(errors: readonly string[]): void {\n\tif (errors.length > 0) {\n\t\tthrow new Error(errors.join(\"; \"));\n\t}\n}\n\nfunction validateTurnStartSelection(\n\tturnId: string,\n\tstartFrom: ProcessTurnStartSelection,\n\tcontext = \"startFrom\",\n): string[] {\n\tconst errors: string[] = [];\n\tif (startFrom.kind === \"entry\" && startFrom.entryId.trim() === \"\") {\n\t\terrors.push(`LLM turn '${turnId}' ${context} entry id must be non-empty`);\n\t}\n\tif (startFrom.kind === \"product_ref\") {\n\t\terrors.push(...validateProcessProductName(startFrom.productName));\n\t}\n\tif (\"fallback\" in startFrom && startFrom.fallback) {\n\t\terrors.push(...validateTurnStartSelection(turnId, startFrom.fallback, `${context} fallback`));\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateLlmTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n>(turnId: string, turnDef: LlmTurnDefinition<TOutcome, TParams, TState>): string[] {\n\tconst errors: string[] = [];\n\tconst declaredOutcomes = turnDef.outcomes;\n\tconst startFrom = resolveLlmTurnStartSelection(turnDef);\n\n\tif ((turnDef.completionMode ?? \"turn_end\") !== \"turn_end\") {\n\t\terrors.push(`LLM turn '${turnId}' must use completionMode 'turn_end'`);\n\t}\n\n\tconst declaredTurnEnd = turnDef.turnEnd;\n\terrors.push(\n\t\t...validateOutcomeTurnResultContract(\"LLM\", turnId, declaredOutcomes, declaredTurnEnd),\n\t);\n\n\tif (turnDef.branchType === \"root_branch\" && startFrom.kind === \"current_leaf\") {\n\t\terrors.push(\n\t\t\t`LLM turn '${turnId}' uses branchType 'root_branch' but starts from the current leaf`,\n\t\t);\n\t}\n\n\tif (turnDef.branchType === \"leaf_branch\" && startFrom.kind === \"session_root\") {\n\t\terrors.push(\n\t\t\t`LLM turn '${turnId}' uses branchType 'leaf_branch' but starts from the session root`,\n\t\t);\n\t}\n\n\terrors.push(...validateTurnStartSelection(turnId, startFrom));\n\n\tif (turnDef.askQuestions !== undefined && turnDef.askQuestions !== true) {\n\t\terrors.push(`LLM turn '${turnId}' askQuestions must be true when declared`);\n\t}\n\n\tif (!Array.isArray(turnDef.availableTools)) {\n\t\terrors.push(`LLM turn '${turnId}' must declare availableTools as an array`);\n\t} else {\n\t\terrors.push(\n\t\t\t...validatePiBuiltInToolArray(turnDef.availableTools, `LLM turn '${turnId}' availableTools`),\n\t\t);\n\t}\n\n\tif (turnDef.integrationTools !== undefined) {\n\t\tif (!Array.isArray(turnDef.integrationTools)) {\n\t\t\terrors.push(`LLM turn '${turnId}' integrationTools must be an array`);\n\t\t} else {\n\t\t\tconst seen = new Set<string>();\n\t\t\tconst conflictingNames = new Set<string>([\n\t\t\t\t...RESERVED_INTEGRATION_TOOL_NAMES,\n\t\t\t\t...Object.keys(declaredOutcomes ?? {}),\n\t\t\t]);\n\t\t\tfor (const name of turnDef.integrationTools) {\n\t\t\t\tif (typeof name !== \"string\" || name.trim() === \"\") {\n\t\t\t\t\terrors.push(`LLM turn '${turnId}' integration tool names must be non-empty strings`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (seen.has(name)) {\n\t\t\t\t\terrors.push(`LLM turn '${turnId}' declares duplicate integration tool '${name}'`);\n\t\t\t\t}\n\t\t\t\tif (conflictingNames.has(name)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`LLM turn '${turnId}' integration tool '${name}' conflicts with a built-in, framework, or outcome tool`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tseen.add(name);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (turnDef.turnResultMarkdown?.mode === \"tool_call\") {\n\t\tif (turnDef.turnResultMarkdown.toolName.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`LLM turn '${turnId}' tool-call turnResultMarkdown must use a non-empty toolName`,\n\t\t\t);\n\t\t}\n\t\tif (turnDef.turnResultMarkdown.path.trim() === \"\") {\n\t\t\terrors.push(`LLM turn '${turnId}' tool-call turnResultMarkdown must use a non-empty path`);\n\t\t}\n\t}\n\tif (turnDef.turnResultMarkdown?.mode === \"outcome_tool_argument\") {\n\t\tconst parameterName = turnDef.turnResultMarkdown.parameterName.trim();\n\t\tconst outcomeEntries = Object.entries(declaredOutcomes ?? {}) as Array<\n\t\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t\t>;\n\t\tif (parameterName === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`LLM turn '${turnId}' outcome-tool turnResultMarkdown must use a non-empty parameterName`,\n\t\t\t);\n\t\t}\n\t\tif (outcomeEntries.length === 0) {\n\t\t\terrors.push(\n\t\t\t\t`LLM turn '${turnId}' outcome-tool turnResultMarkdown requires at least one outcome tool`,\n\t\t\t);\n\t\t}\n\t\tfor (const [outcomeId, spec] of outcomeEntries) {\n\t\t\tif (parameterName in spec.parameters) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`LLM turn '${turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${parameterName}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\terrors.push(...validateOutcomeToolParameters(\"LLM\", turnId, declaredOutcomes));\n\n\treturn errors;\n}\n\n/** @internal */\nexport function validateAutomaticTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n>(turnId: string, turnDef: AutomaticTurnDefinition<TOutcome, TParams, TState>): string[] {\n\treturn [\n\t\t...validateOutcomeTurnResultContract(\"Automatic\", turnId, turnDef.outcomes, turnDef.turnEnd),\n\t\t...validateOutcomeToolParameters(\"Automatic\", turnId, turnDef.outcomes),\n\t];\n}\n\n/** @internal */\nexport function validateHumanTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnId: string,\n\tturnDef: HumanTurnDefinition<TParams, TState>,\n): string[] {\n\tconst errors: string[] = [];\n\n\ttry {\n\t\tresolveHumanTurnView({ turnId, turn: turnDef });\n\t} catch (error: unknown) {\n\t\terrors.push(error instanceof Error ? error.message : String(error));\n\t}\n\tif (turnDef.reviewProduct) {\n\t\terrors.push(...validateProcessProductName(turnDef.reviewProduct));\n\t}\n\n\tconst actionEntries = Object.entries(turnDef.actions) as Array<\n\t\t[string, HumanTurnDefinition<TParams, TState>[\"actions\"][string]]\n\t>;\n\tif (actionEntries.length === 0) {\n\t\terrors.push(`Human turn '${turnId}' must declare at least one action`);\n\t}\n\tfor (const [actionId, action] of actionEntries) {\n\t\tif (!action.acceptanceState) {\n\t\t\terrors.push(`Human turn '${turnId}' is missing an acceptance state for action '${actionId}'`);\n\t\t}\n\t\terrors.push(\n\t\t\t...validateProcessActionPreviewDefinition(\n\t\t\t\taction.preview,\n\t\t\t\t`Human turn '${turnId}' action '${actionId}' preview`,\n\t\t\t),\n\t\t);\n\t}\n\n\tconst externalTriggers = actionEntries.flatMap(([actionId, action]) =>\n\t\t(action.externalTriggers ?? []).map((trigger) => ({ actionId, trigger })),\n\t);\n\tif (findDuplicateBy(externalTriggers, ({ trigger }) => trigger.id) !== undefined) {\n\t\terrors.push(`Human turn '${turnId}' contains duplicate external trigger ids`);\n\t}\n\tif (findDuplicateBy(externalTriggers, ({ actionId }) => actionId) !== undefined) {\n\t\terrors.push(`Human turn '${turnId}' contains duplicate external trigger action ids`);\n\t}\n\tfor (const { actionId, trigger } of externalTriggers) {\n\t\tif (trigger.id.trim() === \"\") {\n\t\t\terrors.push(`Human turn '${turnId}' contains an external trigger with an empty id`);\n\t\t}\n\t\tif (actionId.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty actionId`,\n\t\t\t);\n\t\t}\n\t\tif (trigger.label.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty label`,\n\t\t\t);\n\t\t}\n\t\tif (trigger.description.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty description`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfor (const [externalActionId, externalAction] of Object.entries(turnDef.externalActions ?? {})) {\n\t\tif (externalActionId.trim() === \"\") {\n\t\t\terrors.push(`Human turn '${turnId}' contains an external action with an empty id`);\n\t\t}\n\t\tif (externalAction.id !== externalActionId) {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' has mismatched id '${externalAction.id}'`,\n\t\t\t);\n\t\t}\n\t\tif (externalAction.source.kind.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' must declare a non-empty source kind`,\n\t\t\t);\n\t\t}\n\t\tconst targetCount =\n\t\t\t(externalAction.to !== undefined ? 1 : 0) +\n\t\t\t(externalAction.complete === true ? 1 : 0) +\n\t\t\t(externalAction.lifecycleStatus !== undefined ? 1 : 0);\n\t\tif (targetCount !== 1) {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' must declare exactly one target`,\n\t\t\t);\n\t\t}\n\t\tif (externalAction.publishInput) {\n\t\t\terrors.push(...validateProcessProductName(externalAction.publishInput.productName));\n\t\t\tif (externalAction.publishInput.inputField.trim() === \"\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (externalAction.complete === true || externalAction.lifecycleStatus !== undefined) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' cannot publish input on a terminal route`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst duplicateNote = findDuplicateBy(turnDef.notesFields ?? [], (field) => field.id);\n\tif (duplicateNote !== undefined) {\n\t\terrors.push(`Human turn '${turnId}' contains duplicate notes field id '${duplicateNote.id}'`);\n\t}\n\n\treturn errors;\n}\n\n/** @internal */\nexport function validateExternalTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnId: string,\n\tturnDef: ExternalTurnDefinition<TParams, TState>,\n): string[] {\n\tconst errors: string[] = [];\n\tif (turnDef.transitions.length === 0) {\n\t\terrors.push(`External turn '${turnId}' must declare at least one source transition`);\n\t}\n\tfor (const [index, transition] of turnDef.transitions.entries()) {\n\t\tif (transition.source.kind.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`External turn '${turnId}' source transition ${index} must declare a non-empty kind`,\n\t\t\t);\n\t\t}\n\t\tconst targetCount =\n\t\t\t(transition.to !== undefined ? 1 : 0) +\n\t\t\t(transition.complete === true ? 1 : 0) +\n\t\t\t(transition.lifecycleStatus !== undefined ? 1 : 0);\n\t\tif (targetCount !== 1) {\n\t\t\terrors.push(\n\t\t\t\t`External turn '${turnId}' source transition ${index} must declare exactly one target`,\n\t\t\t);\n\t\t}\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnId: string,\n\tturnDef: TurnDefinition<TParams, TState>,\n): string[];\n/** @internal */\nexport function validateTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): string[];\n/** @internal */\nexport function validateTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnIdOrDef: string | TurnDefinition<TParams, TState>,\n\tturnDef?: TurnDefinition<TParams, TState>,\n): string[] {\n\tconst effectiveTurnDef = typeof turnIdOrDef === \"string\" ? turnDef : turnIdOrDef;\n\tconst effectiveTurnId =\n\t\ttypeof turnIdOrDef === \"string\"\n\t\t\t? turnIdOrDef\n\t\t\t: ((turnIdOrDef as { id?: string }).id ?? \"unknown_turn\");\n\tif (!effectiveTurnDef) {\n\t\treturn [\"Turn definition is required\"];\n\t}\n\treturn isLlmTurnDefinition(effectiveTurnDef)\n\t\t? validateLlmTurnDefinition(effectiveTurnId, effectiveTurnDef)\n\t\t: isAutomaticTurnDefinition(effectiveTurnDef)\n\t\t\t? validateAutomaticTurnDefinition(effectiveTurnId, effectiveTurnDef)\n\t\t\t: isHumanTurnDefinition(effectiveTurnDef)\n\t\t\t\t? validateHumanTurnDefinition(effectiveTurnId, effectiveTurnDef)\n\t\t\t\t: validateExternalTurnDefinition(effectiveTurnId, effectiveTurnDef);\n}\n\n/** @internal */\nexport function assertValidLlmTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n>(turnId: string, turnDef: LlmTurnDefinition<TOutcome, TParams, TState>): void {\n\tassertNoValidationErrors(validateLlmTurnDefinition(turnId, turnDef));\n}\n\n/** @internal */\nexport function createRootBranchReviewTurn<\n\tTOutcome extends string,\n\tTParams = unknown,\n\tTState = unknown,\n>(\n\tdef: Omit<\n\t\tLlmTurnDefinition<TOutcome, TParams, TState>,\n\t\t\"kind\" | \"branchType\" | \"completionMode\" | \"startFrom\" | \"restorePrimaryLeafAfterTurn\"\n\t> &\n\t\tPartial<\n\t\t\tPick<\n\t\t\t\tLlmTurnDefinition<TOutcome, TParams, TState>,\n\t\t\t\t\"completionMode\" | \"startFrom\" | \"restorePrimaryLeafAfterTurn\"\n\t\t\t>\n\t\t>,\n): LlmTurnDefinition<TOutcome, TParams, TState> {\n\tconst {\n\t\tcompletionMode = \"turn_end\",\n\t\tstartFrom = { kind: \"session_root\" },\n\t\trestorePrimaryLeafAfterTurn = true,\n\t\tturnResultMarkdown = REQUIRED_MARKDOWN_RESULT_TURN_RESULT,\n\t\t...rest\n\t} = def;\n\n\treturn llmTurn({\n\t\tcompletionMode,\n\t\tbranchType: \"root_branch\",\n\t\tstartFrom,\n\t\trestorePrimaryLeafAfterTurn,\n\t\tturnResultMarkdown,\n\t\t...rest,\n\t});\n}\n","import {\n\tTOOL_CALL_RENDERER_VALUE_KINDS,\n\tTOOL_CALL_RENDERER_VALUE_SOURCES,\n\ttype ToolCallRendererDefinition,\n\ttype ToolCallRendererFieldDefinition,\n\ttype ToolCallRendererValueKind,\n\ttype ToolCallRendererValueSource,\n} from \"@leitwerk-dev/protocol/tool-renderer-contract\";\nimport type { TurnResultMarkdownBehavior } from \"./types.js\";\n\nexport {\n\tTOOL_CALL_RENDERER_VALUE_KINDS,\n\tTOOL_CALL_RENDERER_VALUE_SOURCES,\n\ttype ToolCallRendererDefinition,\n\ttype ToolCallRendererFieldDefinition,\n\ttype ToolCallRendererValueKind,\n\ttype ToolCallRendererValueSource,\n};\n\n/** @internal */\nexport const MARKDOWN_RESULT_TOOL_NAME = \"markdown_result\";\n/** @internal */\nexport const MARKDOWN_RESULT_TOOL_MARKDOWN_PATH = \"markdown\";\n\n/** @internal */\nexport const MARKDOWN_RESULT_TOOL_RENDERER: ToolCallRendererDefinition = {\n\ttoolName: MARKDOWN_RESULT_TOOL_NAME,\n\ttitle: \"Markdown result\",\n\tfields: [\n\t\t{\n\t\t\tid: \"markdown\",\n\t\t\tlabel: \"Rendered markdown\",\n\t\t\tkind: \"markdown\",\n\t\t\tsource: \"arguments\",\n\t\t\tpath: MARKDOWN_RESULT_TOOL_MARKDOWN_PATH,\n\t\t},\n\t],\n};\n\n/** @internal */\nexport const CORE_TOOL_CALL_RENDERERS: readonly ToolCallRendererDefinition[] = [\n\tMARKDOWN_RESULT_TOOL_RENDERER,\n];\n\n/** @public */\nexport const REQUIRED_MARKDOWN_RESULT_TURN_RESULT: TurnResultMarkdownBehavior = {\n\tmode: \"tool_call\",\n\ttoolName: MARKDOWN_RESULT_TOOL_NAME,\n\tpath: MARKDOWN_RESULT_TOOL_MARKDOWN_PATH,\n\trequired: true,\n};\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.trim() !== \"\";\n}\n\n/** @internal */\nexport function validateToolCallRendererDefinition(def: ToolCallRendererDefinition): string[] {\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(def.toolName)) {\n\t\terrors.push(\"Tool renderer must declare a non-empty toolName\");\n\t}\n\tif (!Array.isArray(def.fields) || def.fields.length === 0) {\n\t\terrors.push(`Tool renderer '${def.toolName}' must declare at least one field`);\n\t\treturn errors;\n\t}\n\tconst fieldIds = new Set<string>();\n\tfor (const field of def.fields) {\n\t\tif (!isNonEmptyString(field.id)) {\n\t\t\terrors.push(`Tool renderer '${def.toolName}' contains a field with an empty id`);\n\t\t}\n\t\tif (fieldIds.has(field.id)) {\n\t\t\terrors.push(`Tool renderer '${def.toolName}' contains duplicate field id '${field.id}'`);\n\t\t}\n\t\tfieldIds.add(field.id);\n\t\tif (!isNonEmptyString(field.label)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' must declare a non-empty label`,\n\t\t\t);\n\t\t}\n\t\tif (!TOOL_CALL_RENDERER_VALUE_KINDS.includes(field.kind)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' uses unknown kind '${String(field.kind)}'`,\n\t\t\t);\n\t\t}\n\t\tif (!TOOL_CALL_RENDERER_VALUE_SOURCES.includes(field.source)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' uses unknown source '${String(field.source)}'`,\n\t\t\t);\n\t\t}\n\t\tif (field.path !== undefined && !isNonEmptyString(field.path)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' path must be non-empty when provided`,\n\t\t\t);\n\t\t}\n\t}\n\treturn errors;\n}\n","import type {\n\tProcessActionDefinition,\n\tProcessCleanupHandler,\n\tProcessTurnOutcomeEvent,\n\tServerProcessAPI,\n\tServerProcessContext,\n} from \"./extension-api.js\";\nimport { cloneArrayValueMap, cloneMap, registerUnique } from \"./registry-utils.js\";\nimport {\n\tvalidateProcessActionPreviewDefinition,\n\tvalidateProcessActionSchedulingDefinition,\n} from \"./turn-semantics.js\";\n\n/** @internal */\nexport type ServerTurnOutcomeHandler<TParams = unknown, TState = unknown> = (\n\tevent: ProcessTurnOutcomeEvent,\n\tctx: ServerProcessContext<TParams, TState>,\n) => void | Promise<void>;\n\n/** @internal */\nexport interface BuiltServerProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tactions: ReadonlyMap<string, ProcessActionDefinition<TParams, TState>>;\n\t/** @internal */\n\tturnOutcomeHandlers: ReadonlyMap<string, readonly ServerTurnOutcomeHandler<TParams, TState>[]>;\n\t/** @internal */\n\tcleanupHandlers: readonly ProcessCleanupHandler<TParams, TState>[];\n}\n\n/** @internal */\nexport function createServerProcessBuilder<TParams = unknown, TState = unknown>(): ServerProcessAPI<\n\tTParams,\n\tTState\n> & {\n\t/** @internal */\n\tgetDefinition(): BuiltServerProcessDefinition<TParams, TState>;\n} {\n\tconst actions = new Map<string, ProcessActionDefinition<TParams, TState>>();\n\tconst turnOutcomeHandlers = new Map<string, ServerTurnOutcomeHandler<TParams, TState>[]>();\n\tconst cleanupHandlers: ProcessCleanupHandler<TParams, TState>[] = [];\n\treturn {\n\t\taction(def) {\n\t\t\tregisterUnique(actions, def.id, def, {\n\t\t\t\tduplicateMessage: `Process action '${def.id}' is already registered`,\n\t\t\t\tvalidate: (value) => {\n\t\t\t\t\tif (!value.plan && !value.execute) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' must declare plan(...) or side-effect execute(...)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (value.execute && !value.plan && value.executionMode !== \"side_effect\") {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' with execute(...) must set executionMode: \"side_effect\"`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (value.executionMode === \"side_effect\" && !value.execute) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' with executionMode: \"side_effect\" must declare execute(...)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (value.executionMode === \"side_effect\" && value.scheduling) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' with executionMode: \"side_effect\" cannot declare scheduling metadata`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst previewErrors = validateProcessActionPreviewDefinition(\n\t\t\t\t\t\tvalue.preview,\n\t\t\t\t\t\t`Process action '${value.id}' preview`,\n\t\t\t\t\t);\n\t\t\t\t\tif (previewErrors.length > 0) {\n\t\t\t\t\t\tthrow new Error(previewErrors.join(\"; \"));\n\t\t\t\t\t}\n\t\t\t\t\tconst schedulingErrors = validateProcessActionSchedulingDefinition(\n\t\t\t\t\t\tvalue.scheduling,\n\t\t\t\t\t\t`Process action '${value.id}' scheduling`,\n\t\t\t\t\t);\n\t\t\t\t\tif (schedulingErrors.length > 0) {\n\t\t\t\t\t\tthrow new Error(schedulingErrors.join(\"; \"));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tonTurnOutcome(turnId, handler) {\n\t\t\tconst handlers = turnOutcomeHandlers.get(turnId) ?? [];\n\t\t\thandlers.push(handler);\n\t\t\tturnOutcomeHandlers.set(turnId, handlers);\n\t\t},\n\t\tonCleanup(handler) {\n\t\t\tcleanupHandlers.push(handler);\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\tactions: cloneMap(actions),\n\t\t\t\tturnOutcomeHandlers: cloneArrayValueMap(turnOutcomeHandlers),\n\t\t\t\tcleanupHandlers: [...cleanupHandlers],\n\t\t\t};\n\t\t},\n\t};\n}\n","import {\n\tasUnknownRecord,\n\tcreateEmptyProcessProductRefs,\n\tcreateEmptyProcessSemanticEntryRefs,\n\ttype ProcessProductRefs,\n\ttype ProcessSemanticEntryRefs,\n\tparseProcessProductRefs,\n\tparseProcessSemanticEntryRefs,\n} from \"@leitwerk-dev/domain\";\nimport type { Codec } from \"./extension-api.js\";\n\n/** @public */\nexport interface StructuralProcessState {\n\t/** @internal */\n\tsemanticEntryRefs: ProcessSemanticEntryRefs;\n\t/** @internal */\n\tproductRefs: ProcessProductRefs;\n}\n\n/** @internal */\nexport const structuralStateCodec: Codec<StructuralProcessState> = {\n\tparse: parseStructuralProcessState,\n\tserialize: (value) => value,\n};\n\n/** @public */\nexport function createEmptyStructuralProcessState(): StructuralProcessState {\n\treturn {\n\t\tsemanticEntryRefs: createEmptyProcessSemanticEntryRefs(),\n\t\tproductRefs: createEmptyProcessProductRefs(),\n\t};\n}\n\n/** @public */\nexport function parseStructuralProcessState(value: unknown): StructuralProcessState {\n\tconst record = asUnknownRecord(value) ?? {};\n\treturn {\n\t\tsemanticEntryRefs: parseProcessSemanticEntryRefs(record.semanticEntryRefs),\n\t\tproductRefs: parseProcessProductRefs(record.productRefs),\n\t};\n}\n","import type {\n\tExtensionProcessDefinition,\n\tProcessLeafOutcomeDefinition,\n\tUiProcessAPI,\n} from \"./extension-api.js\";\nimport { validateProcessLeafOutcomeDefinition } from \"./leaf-outcomes.js\";\n\n/** @internal */\nexport interface BuiltUiProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tleafOutcome: ProcessLeafOutcomeDefinition<TParams, TState> | null;\n}\n\n/** @internal */\nexport function createUiProcessBuilder<TParams = unknown, TState = unknown>(): UiProcessAPI<\n\tTParams,\n\tTState\n> & {\n\t/** @internal */\n\tgetDefinition(): BuiltUiProcessDefinition<TParams, TState>;\n} {\n\tlet leafOutcome: ProcessLeafOutcomeDefinition<TParams, TState> | null = null;\n\n\treturn {\n\t\tleafOutcome(def) {\n\t\t\tif (leafOutcome) {\n\t\t\t\tthrow new Error(\"Leaf outcome is already registered\");\n\t\t\t}\n\t\t\tconst validationErrors = validateProcessLeafOutcomeDefinition(def);\n\t\t\tif (validationErrors.length > 0) {\n\t\t\t\tthrow new Error(validationErrors.join(\"; \"));\n\t\t\t}\n\t\t\tleafOutcome = def;\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\tleafOutcome,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** @internal */\nexport function buildUiProcessDefinition<TParams = unknown, TState = unknown>(\n\tprocess: ExtensionProcessDefinition<TParams, TState>,\n): BuiltUiProcessDefinition<TParams, TState> | undefined {\n\tif (!process.ui) {\n\t\treturn undefined;\n\t}\n\tconst builder = createUiProcessBuilder<TParams, TState>();\n\tprocess.ui(builder);\n\treturn builder.getDefinition();\n}\n","import type { TurnId } from \"@leitwerk-dev/domain\";\nimport type { WorkerProcessAPI, WorkerTurnHandler } from \"./extension-api.js\";\nimport { cloneMap, registerUnique } from \"./registry-utils.js\";\n\n/** @internal */\nexport interface BuiltWorkerProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tstartTurnId: TurnId | null;\n\t/** @internal */\n\tturns: ReadonlyMap<TurnId, WorkerTurnHandler<TParams, TState>>;\n}\n\n/** @internal */\nexport function createWorkerProcessBuilder<TParams = unknown, TState = unknown>(): WorkerProcessAPI<\n\tTParams,\n\tTState\n> & {\n\t/** @internal */\n\tgetDefinition(): BuiltWorkerProcessDefinition<TParams, TState>;\n} {\n\tconst turns = new Map<TurnId, WorkerTurnHandler<TParams, TState>>();\n\tlet startTurnId: TurnId | null = null;\n\n\treturn {\n\t\tstart(turnId: TurnId): void {\n\t\t\tstartTurnId = turnId;\n\t\t},\n\t\tturn(turnId: TurnId, handler: WorkerTurnHandler<TParams, TState>): void {\n\t\t\tregisterUnique(turns, turnId, handler, {\n\t\t\t\tduplicateMessage: `Worker turn '${turnId}' is already registered`,\n\t\t\t});\n\t\t},\n\t\tgetDefinition(): BuiltWorkerProcessDefinition<TParams, TState> {\n\t\t\treturn {\n\t\t\t\tstartTurnId,\n\t\t\t\tturns: cloneMap(turns),\n\t\t\t};\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;AAYO,SAAS,sBACf,IACA,UAGI,CAAC,GACqB;AAC1B,SAAO;AAAA,IACN;AAAA,IACA,aAAa,QAAQ,eAAe;AAAA,EACrC;AACD;;;ACpBO,IAAM,mBAAiD;AAAA,EAC7D,QAAQ;AACP,WAAO,CAAC;AAAA,EACT;AAAA,EACA,UAAU,OAAO;AAChB,WAAO;AAAA,EACR;AACD;;;ACTO,IAAM,sCAAsC;AAG5C,IAAM,gCACZ;;;ACo5BM,IAAM,uBAAuB;AAAA;AAAA,EAEnC,aAAa,sBAA2C,kBAAkB;AAAA;AAAA,EAE1E,uBAAuB;AAAA,IACtB;AAAA,EACD;AACD;;;ACh6BA;AAAA,EACC;AAAA,EACA,cAAc;AAAA,EACd,wBAAwB;AAAA,OAQlB;AAsiBP,SAAS,yBACR,YACA,aAC4B;AAC5B,QAAM,UAAqC,EAAE,WAAW;AACxD,MAAI,eAAe,YAAY,SAAS,GA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AACvE,qBAAe,OAAO,QAAQ,SAAS;AAAA,QACtC,kBAAkB,gBAAgB,MAAM;AAAA,MACzC,CAAC;AAAA,IACF;AAAA,IACA,gBAA+D;AAC9D,aAAO;AAAA,QACN;AAAA,QACA,OAAO,SAAS,KAAK;AAAA,MACtB;AAAA,IACD;AAAA,EACD;AACD;","names":["path","compiled","process","path","assertValidProcessProductName","assertValidProcessProductName","path","project","key","process","path","value","humanizeProcessLabel","process","process","path","value","record","nonEmptyString","path","asUnknownRecord","assertValidProcessProductName","isNonEmptyString","assertValidProcessProductName","asUnknownRecord","record","process"]}
1
+ {"version":3,"sources":["../src/capabilities.ts","../src/codecs.ts","../src/commit-message.ts","../src/core-capabilities.ts","../src/define-process.ts","../src/extension-api.ts","../src/mapped-turn.ts","../src/event-bus.ts","../src/external-action-source.ts","../src/external-source-poll.ts","../src/flow.ts","../src/fs-utils.ts","../src/process-graph.ts","../src/graph-fragments.ts","../src/host-capabilities.ts","../src/integration-http.ts","../src/json-data.ts","../src/leaf-outcomes.ts","../src/model-provider.ts","../src/process-flow-view.ts","../src/process-launcher-builder.ts","../src/process-watcher-builder.ts","../src/tool-arguments.ts","../src/process-watcher-source.ts","../src/project-binding.ts","../src/repository-feedback.ts","../src/subprocess-env.ts","../src/repository-git-env.ts","../src/repository-http.ts","../src/repository-https.ts","../src/repository-issue-watcher.ts","../src/repository-reconciliation.ts","../src/repository-source-config.ts","../src/turn-semantics.ts","../src/tool-renderers.ts","../src/server-process-builder.ts","../src/state-helpers.ts","../src/ui-process-builder.ts","../src/worker-process-builder.ts"],"sourcesContent":["/** @internal */\nexport type CapabilityCardinality = \"single\" | \"multi\";\n\n/** @public */\nexport interface CapabilityToken<_TValue> {\n\t/** @internal */\n\treadonly id: string;\n\t/** @internal */\n\treadonly cardinality: CapabilityCardinality;\n}\n\n/** @public */\nexport function createCapabilityToken<TValue>(\n\tid: string,\n\toptions: {\n\t\t/** @internal */\n\t\tcardinality?: CapabilityCardinality;\n\t} = {},\n): CapabilityToken<TValue> {\n\treturn {\n\t\tid,\n\t\tcardinality: options.cardinality ?? \"single\",\n\t};\n}\n","import type { Codec } from \"./extension-api.js\";\n\n/** @internal */\nexport const emptyParamsCodec: Codec<Record<string, never>> = {\n\tparse() {\n\t\treturn {};\n\t},\n\tserialize(value) {\n\t\treturn value;\n\t},\n};\n","/** @internal */\nexport const COMMIT_MESSAGE_PROJECT_METADATA_KEY = \"leitwerk.commitMessage\";\n\n/** @internal */\nexport const BUILT_IN_COMMIT_MESSAGE_RULES =\n\t\"Write a concise imperative subject that summarizes the accepted plan. Add a body only when it provides useful context.\";\n\n/** @internal */\nexport interface CommitMessageProjectMetadata {\n\t/** @internal */\n\ttemplateId: string | null;\n\t/** @internal */\n\trules: string;\n}\n","import type {\n\tActor,\n\tInputKind,\n\tInputSource,\n\tLaunchModelConfigInput,\n\tProcessEvent,\n\tProcessInputTarget,\n\tProcessInstance,\n\tProcessLifecycleStatus,\n\tProcessProject,\n\tTurnId,\n\tWorkerErrorClass,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tKnownDurableWsFrameType,\n\tKnownEphemeralWsFrameType,\n\tLauncherModelConfigPreview,\n\tLauncherModelConfigSchema,\n\tProcessActionModelPreview,\n\tWsPayloadByType,\n} from \"@leitwerk-dev/protocol\";\nimport { createCapabilityToken } from \"./capabilities.js\";\nimport type {\n\tExternalActionSource,\n\tFormDefinition,\n\tLauncherContext,\n\tLaunchPreparationCheck,\n\tProcessLaunchConfig,\n\tProcessLauncherService,\n\tProcessLaunchPlan,\n\tProcessWatcherPresentation,\n\tProcessWatcherSource,\n\tRepositoryCredentialRegistrar,\n} from \"./extension-api.js\";\n\n/** @internal */\nexport interface ProcessCreateInputLike {\n\t/** @internal */\n\tprocessId?: ProcessInstance[\"processId\"];\n\t/** @internal */\n\tselectedTurnId?: ProcessInstance[\"selectedTurnId\"];\n\t/** @internal */\n\tlifecycleStatus?: ProcessInstance[\"lifecycleStatus\"];\n\t/** @internal */\n\ttitle?: string | null;\n\t/** @internal */\n\texternalId?: string | null;\n\t/** @internal */\n\texternalUrl?: string | null;\n\t/** @internal */\n\tmetadata?: Record<string, unknown> | null;\n\t/** @internal */\n\tdefaultModelProfileId?: string | null;\n\t/** @internal */\n\tturnConfigsJson?: string | null;\n\t/** @internal */\n\tselectedTurnModelProfileId?: string | null;\n\t/** @internal */\n\tparamsJson?: string | null;\n\t/** @internal */\n\tstateJson?: string | null;\n}\n\n/** @public */\nexport interface ProcessRepoLike {\n\t/** @internal */\n\tcreate(input: ProcessCreateInputLike): ProcessInstance;\n\t/** @internal */\n\tgetById(id: string): ProcessInstance | null;\n\t/** @public */\n\tlistAll(): ProcessInstance[];\n\t/** Startup-only compatibility migrations may rewrite persisted process position and state. @public */\n\tupdate(\n\t\tid: string,\n\t\tinput: {\n\t\t\t/** @public */\n\t\t\tselectedTurnId?: TurnId | null;\n\t\t\t/** Encoded params rewritten by a startup compatibility migration. @public */\n\t\t\tparamsJson?: string | null;\n\t\t\t/** @public */\n\t\t\tcurrentExecution?: ProcessInstance[\"currentExecution\"];\n\t\t\t/** @public */\n\t\t\tstateJson?: string | null;\n\t\t},\n\t): ProcessInstance | null;\n}\n\n/** @public */\nexport interface ProcessProjectRepoLike {\n\t/** Server-provided project mutation service. Implementations should emit project.updated after committed writes. @internal */\n\tcreate(input: {\n\t\t/** @internal */\n\t\tinstanceId: string;\n\t\t/** @internal */\n\t\tkey: string;\n\t\t/** @internal */\n\t\trepoLocator: string;\n\t\t/** @internal */\n\t\tbaseBranch: string;\n\t\t/** @internal */\n\t\tworkBranch?: string | null;\n\t\t/** @internal */\n\t\texternalId?: string | null;\n\t\t/** @internal */\n\t\texternalUrl?: string | null;\n\t\t/** @internal */\n\t\tmetadata?: Record<string, unknown> | null;\n\t\t/** @internal */\n\t\tpipelineStatus?: string | null;\n\t}): ProcessProject;\n\t/** @internal */\n\tgetByInstanceAndKey(instanceId: string, key: string): ProcessProject | null;\n\t/** @public */\n\tupdate(\n\t\tid: string,\n\t\tinput: {\n\t\t\t/** @internal */\n\t\t\tbaseBranch?: string;\n\t\t\t/** @internal */\n\t\t\tworkBranch?: string | null;\n\t\t\t/** @internal */\n\t\t\texternalId?: string | null;\n\t\t\t/** @internal */\n\t\t\texternalUrl?: string | null;\n\t\t\t/** @public */\n\t\t\tmetadata?: Record<string, unknown> | null;\n\t\t\t/** @internal */\n\t\t\tpipelineStatus?: string | null;\n\t\t},\n\t): ProcessProject | null;\n\t/** @internal */\n\tlistByInstance(instanceId: string): ProcessProject[];\n}\n\n/** @public */\nexport interface ProcessEventRepoLike {\n\t/** @public */\n\tcreate(input: {\n\t\t/** @public */\n\t\tinstanceId: string;\n\t\t/** @public */\n\t\teventType: string;\n\t\t/** @public */\n\t\tdata?: Record<string, unknown>;\n\t}): unknown;\n\t/** @internal */\n\tlistByInstance(instanceId: string, limit?: number): ProcessEvent[];\n}\n\n/** @internal */\nexport interface BroadcasterLike {\n\t/** @internal */\n\tsendDurable<T extends KnownDurableWsFrameType>(\n\t\ttype: T,\n\t\tpayload: WsPayloadByType[T],\n\t\tinstanceId?: string,\n\t): void;\n\t/** @internal */\n\tsendEphemeral?<T extends KnownEphemeralWsFrameType>(\n\t\ttype: T,\n\t\tpayload: WsPayloadByType[T],\n\t\tinstanceId?: string,\n\t): void;\n}\n\n/** @internal */\nexport type LaunchModelConfigInputLike = LaunchModelConfigInput;\n/** @internal */\nexport type LauncherModelConfigSchemaLike = LauncherModelConfigSchema;\n/** @internal */\nexport type LauncherModelConfigPreviewLike = LauncherModelConfigPreview;\n\n/** @internal */\nexport interface LauncherModelConfigServiceLike {\n\t/** @internal */\n\tgetSchema(launcherId: string): Promise<LauncherModelConfigSchemaLike | null>;\n\t/** @internal */\n\tpreview(\n\t\tlauncherId: string,\n\t\tlauncherInput: Record<string, unknown>,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tmodelConfig?: LaunchModelConfigInputLike;\n\t\t},\n\t): Promise<LauncherModelConfigPreviewLike | null>;\n}\n\n/** Stable, machine-readable codes returned while preparing a launch. @internal */\nexport type LaunchPlanPreparationIssueCode =\n\t| \"process_id_mismatch\"\n\t| \"invalid_turn_configs_json\"\n\t| \"unknown_model_profile\"\n\t| \"model_profile_not_allowed\"\n\t| \"unknown_llm_turn\"\n\t| \"selected_turn_model_requires_selected_turn\"\n\t| \"selected_turn_model_requires_llm_turn\"\n\t| \"model_required\";\n\n/** Complete, presentation-safe diagnostic returned while preparing a launch. @internal */\nexport interface LaunchPlanPreparationIssue {\n\t/** @internal */\n\treadonly code: LaunchPlanPreparationIssueCode;\n\t/** @internal */\n\treadonly message: string;\n}\n\n/** @internal */\nexport type LaunchPlanPreparationResultLike =\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: true;\n\t\t\t/** @internal */\n\t\t\tlaunchPlan: ProcessLaunchPlan;\n\t\t\t/** @internal */\n\t\t\tmodelConfig: LaunchModelConfigInputLike;\n\t\t\t/** @internal */\n\t\t\twarnings: readonly LaunchPlanPreparationIssue[];\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: false;\n\t\t\t/** Normalized durable plan retained when a scheduled launch is blocked. @internal */\n\t\t\tlaunchPlan: ProcessLaunchPlan;\n\t\t\t/** @internal */\n\t\t\tmodelConfig: LaunchModelConfigInputLike;\n\t\t\t/** @internal */\n\t\t\terrors: readonly LaunchPlanPreparationIssue[];\n\t };\n\n/** @internal */\nexport interface ProcessLaunchPlanServiceLike {\n\t/** @internal */\n\tprepare(\n\t\tlaunchPlan: ProcessLaunchPlan,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tmodelConfig?: LaunchModelConfigInputLike;\n\t\t\t/** @internal */\n\t\t\treplaceModelConfig?: boolean;\n\t\t\t/** @internal */\n\t\t\tinvalidModelConfig?: \"reject\" | \"omit\";\n\t\t},\n\t): Promise<LaunchPlanPreparationResultLike>;\n}\n\n/** @internal */\nexport interface HandoffDedupKeyRecordLike {\n\t/** @internal */\n\tkey: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\tmetadata: Record<string, unknown>;\n}\n\n/** @internal */\nexport interface HandoffDedupKeyServiceLike {\n\t/** @internal */\n\tgetByKey(key: string): HandoffDedupKeyRecordLike | null;\n}\n\n/** @internal */\nexport interface WorkerSupervisorLike {\n\t/** @internal */\n\tspawnWorker(instanceId: string): Promise<unknown>;\n\t/** @internal */\n\tgetWorker(instanceId: string): unknown | undefined;\n}\n\n/** @public */\nexport interface ProcessEngineResultLike {\n\t/** @public */\n\tok: boolean;\n\t/** @internal */\n\tcode?: string;\n\t/** @internal */\n\tmessage?: string;\n\t/** @internal */\n\tprocess?: ProcessInstance | null;\n\t/** @internal */\n\tstage?: \"pre_commit\" | \"post_commit\";\n\t/** @internal */\n\tdata?: unknown;\n}\n\n/** @internal */\nexport interface DeferredProcessActivationExpected {\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tlifecycleStatus: ProcessLifecycleStatus;\n\t/** @internal */\n\tselectedTurnId: TurnId | null;\n\t/** @internal */\n\ttitle: string | null;\n\t/** @internal */\n\tparamsJson: string | null;\n\t/** @internal */\n\tprojectId: string;\n\t/** @internal */\n\tprojectKey: string;\n\t/** @internal */\n\trepoLocator: string;\n\t/** @internal */\n\tbaseBranch: string;\n\t/** @internal */\n\tworkBranch: string | null;\n}\n\n/** @internal */\nexport interface DeferredProcessActivationSnapshot extends DeferredProcessActivationExpected {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tprocessMetadata: Record<string, unknown> | null;\n\t/** @internal */\n\tprojectMetadata: Record<string, unknown> | null;\n}\n\n/** @internal */\nexport interface DeferredProcessActivationSnapshotQuery {\n\t/** @internal */\n\tprojectKey: string;\n\t/** @internal */\n\tinstanceId?: string;\n\t/** @internal */\n\tprocessId?: string;\n}\n\n/** @internal */\nexport type DeferredProcessActivationSnapshotResult =\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"ready\";\n\t\t\t/** @internal */\n\t\t\tsnapshots: DeferredProcessActivationSnapshot[];\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"process_not_found\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"project_not_found\";\n\t };\n\n/** @internal */\nexport interface DeferredProcessActivationEvent {\n\t/** @internal */\n\teventType: string;\n\t/** @internal */\n\tdata?: Record<string, unknown>;\n\t/** @internal */\n\tlevel: \"info\" | \"warn\" | \"error\";\n\t/** @internal */\n\tmessage: string;\n}\n\n/** @internal */\nexport interface PreparedDeferredProcessActivation {\n\t/** @internal */\n\texpected: DeferredProcessActivationExpected;\n\t/** @internal */\n\tworkBranch: string;\n\t/** @internal */\n\tparamsJson: string;\n\t/** @internal */\n\tprojectMetadata: Record<string, unknown> | null;\n\t/** @internal */\n\tselectedTurnId: TurnId;\n\t/** @internal */\n\tevent: DeferredProcessActivationEvent;\n\t/** @internal */\n\tactor?: Actor;\n}\n\n/** @internal */\nexport type DeferredProcessActivationOutcome =\n\t| \"activated\"\n\t| \"already_activated\"\n\t| \"stale\"\n\t| \"not_applicable\"\n\t| \"project_not_found\"\n\t| \"invalid_selected_turn\";\n\n/** @internal */\nexport interface DeferredProcessActivationFailure {\n\t/** @internal */\n\texpected: DeferredProcessActivationExpected;\n\t/** @internal */\n\terrorClass: WorkerErrorClass;\n\t/** @internal */\n\tevent: DeferredProcessActivationEvent;\n}\n\n/** @internal */\nexport type ProcessActionExecutionSource = \"ui\" | \"external\" | \"scheduled\";\n/** @internal */\nexport type ProcessActionExecutionOrigin = \"web_ui\" | \"external_interface\" | \"scheduled\";\n\n/** @internal */\nexport interface ProcessActionSummaryLike {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription?: string | null;\n\t/** @internal */\n\tform?: FormDefinition;\n}\n\n/** @internal */\nexport type ActionExecutionFailureStageLike = \"pre_commit\" | \"post_commit\";\n\n/** @public */\nexport type ActionExecutionResultLike =\n\t| {\n\t\t\t/** @public */\n\t\t\tok: true;\n\t\t\t/** @internal */\n\t\t\tprocess: ProcessInstance | null;\n\t\t\t/** @internal */\n\t\t\tdata?: Record<string, unknown>;\n\t\t\t/** @internal */\n\t\t\terror?: undefined;\n\t\t\t/** @internal */\n\t\t\tcode?: undefined;\n\t\t\t/** @internal */\n\t\t\tstage?: undefined;\n\t }\n\t| {\n\t\t\t/** @public */\n\t\t\tok: false;\n\t\t\t/** @internal */\n\t\t\tstage: \"pre_commit\";\n\t\t\t/** @internal */\n\t\t\terror: string;\n\t\t\t/** @internal */\n\t\t\tcode?: string;\n\t\t\t/** @internal */\n\t\t\tprocess?: undefined;\n\t\t\t/** @internal */\n\t\t\tdata?: undefined;\n\t }\n\t| {\n\t\t\t/** @public */\n\t\t\tok: false;\n\t\t\t/** @internal */\n\t\t\tstage: \"post_commit\";\n\t\t\t/** @internal */\n\t\t\tprocess: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\terror: string;\n\t\t\t/** @internal */\n\t\t\tcode?: string;\n\t\t\t/** @internal */\n\t\t\tdata?: Record<string, unknown>;\n\t };\n\n/** @internal */\nexport interface ProcessActionServiceLike {\n\t/** @internal */\n\tlistVisibleActions(instanceId: string): readonly ProcessActionSummaryLike[];\n\t/** @internal */\n\texecuteAction(\n\t\tinstanceId: string,\n\t\tactionId: string,\n\t\tinput: Record<string, unknown>,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tsource?: ProcessActionExecutionSource;\n\t\t\t/** @internal */\n\t\t\torigin?: ProcessActionExecutionOrigin;\n\t\t\t/** @internal */\n\t\t\tnextTurnModelProfileId?: string | null;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ActionExecutionResultLike>;\n}\n\n/** @public */\nexport interface ExternalObservationInput {\n\t/** @public */\n\tinstanceId: string;\n\t/** @public */\n\tarmingId: string;\n\t/** @public */\n\tgeneration: string;\n\t/** @public */\n\tobservation?: {\n\t\t/** @public */\n\t\tsummary: string;\n\t\t/** @internal */\n\t\tlinks?: import(\"@leitwerk-dev/domain\").TurnProgressLink[];\n\t\t/** @public */\n\t\tobservedAt: string;\n\t\t/** @public */\n\t\tsubject: string;\n\t\t/** @public */\n\t\trevision: string;\n\t};\n\t/** @public */\n\trefreshError?: string;\n}\n\n/** @public */\nexport interface ExternalSourceArmingLike {\n\t/** Process-local arming id. Durable arming identity is { instanceId, id }. @public */\n\tid: string;\n\t/** @public */\n\tinstanceId: string;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\texternalActionId: string;\n\t/** @internal */\n\tsource: ExternalActionSource;\n\t/** @public */\n\tresolved: unknown;\n\t/** Opaque identity of this resolved subscription. @public */\n\tgeneration?: string;\n}\n\n/** @public */\nexport interface ExternalSourceFireInput {\n\t/** @public */\n\tinstanceId: string;\n\t/** @public */\n\tarmingId: string;\n\t/** Reject a superseded subscription instead of queuing its event for a later turn. @internal */\n\tgeneration?: string;\n\t/** @internal */\n\tinput?: Record<string, unknown>;\n\t/** @public */\n\tevent?: Record<string, unknown>;\n\t/** @public */\n\tmergeKey?: string | null;\n}\n\n/** @public */\nexport interface ExternalSourceServiceLike {\n\t/** @public */\n\tlistArmed(kind: string): readonly ExternalSourceArmingLike[];\n\t/** @public */\n\tfire(input: ExternalSourceFireInput): Promise<ActionExecutionResultLike>;\n\t/** Records facts without firing an action or changing lifecycle state. @public */\n\tobserve?(input: ExternalObservationInput): Promise<ActionExecutionResultLike>;\n}\n\n/** @internal */\nexport interface LauncherRecentValuesServiceLike {\n\t/** @internal */\n\tlist(launcherId: string): Record<string, readonly string[]>;\n\t/** @internal */\n\trecord(launcherId: string, launcherInput: Record<string, unknown>): void;\n}\n\n/** @internal */\nexport interface QueuedProcessInputLike {\n\t/** @internal */\n\tsource: InputSource;\n\t/** @internal */\n\tkind: InputKind;\n\t/** @internal */\n\tbodyMarkdown: string;\n\t/** @internal */\n\ttarget?: ProcessInputTarget | null;\n\t/** Stable principal that queued this input. Defaults to SYSTEM_ACTOR at persist time. @internal */\n\tactor?: Actor;\n}\n\n/** @public */\nexport interface ProcessEngineLike {\n\t/** @internal */\n\tgetDeferredProcessActivationSnapshots(\n\t\tquery: DeferredProcessActivationSnapshotQuery,\n\t): DeferredProcessActivationSnapshotResult;\n\t/** @internal */\n\tactivateDeferredProcess(\n\t\tinstanceId: string,\n\t\tprepared: PreparedDeferredProcessActivation,\n\t): Promise<\n\t\tProcessEngineResultLike & {\n\t\t\t/** @internal */\n\t\t\tdata?: {\n\t\t\t\t/** @internal */\n\t\t\t\toutcome: DeferredProcessActivationOutcome;\n\t\t\t};\n\t\t}\n\t>;\n\t/** @internal */\n\tparkDeferredProcessActivationFailure(\n\t\tinstanceId: string,\n\t\tfailure: DeferredProcessActivationFailure,\n\t): Promise<\n\t\tProcessEngineResultLike & {\n\t\t\t/** @internal */\n\t\t\tdata?: {\n\t\t\t\t/** @internal */\n\t\t\t\toutcome: \"parked\" | \"stale\" | \"not_applicable\" | \"project_not_found\";\n\t\t\t};\n\t\t}\n\t>;\n\t/** @internal */\n\tstartProcess(instanceId: string, startTurnId: TurnId): Promise<ProcessEngineResultLike>;\n\t/** @public */\n\tabortProcess(\n\t\tinstanceId: string,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n\t/** Retries the current failed startup or accepted turn; startup retries consume no attempt. @public */\n\tretryProcess(\n\t\tinstanceId: string,\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tnextTurnModelProfileId?: string | null;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n\t/** @internal */\n\tcontinueFailedTurn(\n\t\tinstanceId: string,\n\t\tturnRecordId: string,\n\t\toptions?: {\n\t\t\t/** @internal */\n\t\t\tprompt?: string | null;\n\t\t\t/** @internal */\n\t\t\tnextTurnModelProfileId?: string | null;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n\t/** @internal */\n\tqueueInputs(\n\t\tinstanceId: string,\n\t\tinputs: readonly QueuedProcessInputLike[],\n\t\topts?: {\n\t\t\t/** @internal */\n\t\t\tdispatchErrorMessage?: string;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProcessEngineResultLike>;\n}\n\n/** @internal */\nexport interface ComponentConfigLike {\n\t/** @internal */\n\trepo: string;\n\t/** @internal */\n\tdefault_branch: string;\n}\n\n/** @public */\nexport interface RegisteredProcessWatcherLike<TConfig = unknown, TEvent = unknown> {\n\t/** @public */\n\treadonly processId: string;\n\t/** @internal */\n\treadonly processDisplayName: string;\n\t/** @public */\n\treadonly watcherId: string;\n\t/** @internal */\n\treadonly watcherLabel: string;\n\t/** @internal */\n\treadonly watcherDescription: string;\n\t/** @internal */\n\treadonly sourceId: string;\n\t/** @internal */\n\treadonly sourceLabel: string;\n\t/** @public */\n\treadonly enabled: boolean;\n\t/** @internal */\n\treadonly configPath: string;\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly presentation: ProcessWatcherPresentation;\n\t/** @internal */\n\treadonly launchModelConfig: LaunchModelConfigInputLike;\n\t/** @internal */\n\tresolveLaunch(event: TEvent, ctx?: LauncherContext): Promise<ProcessLaunchPlan | null>;\n\t/** @internal */\n\tresolveLaunchAttempt(\n\t\tevent: TEvent,\n\t\tctx?: LauncherContext,\n\t): Promise<{\n\t\t/** @internal */\n\t\tlaunchConfig: ProcessLaunchConfig;\n\t\t/** @internal */\n\t\tlaunchPlan: ProcessLaunchPlan;\n\t\t/** @internal */\n\t\tpreparationChecks: readonly LaunchPreparationCheck[];\n\t} | null>;\n}\n\n/** @public */\nexport interface WatcherLaunchResultLike extends ProgrammaticLaunchResultLike {}\n\n/** @internal */\nexport interface ProgrammaticLaunchRequestLike {\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tlauncherInput: Record<string, unknown>;\n\t/** @internal */\n\ttitle?: string | null;\n\t/** @internal */\n\tmodelConfig?: LaunchModelConfigInputLike;\n\t/** @internal */\n\tskillIds?: readonly string[];\n\t/** Trusted, non-secret process metadata merged after launcher resolution. @internal */\n\tprocessMetadata?: Record<string, unknown>;\n}\n\n/** @public */\nexport interface ProgrammaticLaunchResultLike {\n\t/** @public */\n\tlaunchRunId: string;\n\t/** @public */\n\tprocess: ProcessInstance | null;\n\t/** @public */\n\terror: string | null;\n}\n\n/** @public */\nexport interface LaunchRunServiceLike {\n\t/** @internal */\n\tstartProgrammatic(\n\t\trequest: ProgrammaticLaunchRequestLike,\n\t\topts: {\n\t\t\t/** @internal */\n\t\t\tidempotencyKey: string;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<ProgrammaticLaunchResultLike>;\n\t/** @public */\n\tstartWatcher<TConfig, TEvent>(\n\t\twatcher: RegisteredProcessWatcherLike<TConfig, TEvent>,\n\t\tevent: TEvent,\n\t\topts: {\n\t\t\t/** @public */\n\t\t\tidempotencyKey: string;\n\t\t\t/** @internal */\n\t\t\tactor?: Actor;\n\t\t},\n\t): Promise<WatcherLaunchResultLike>;\n}\n\n/** @public */\nexport interface ProcessWatcherServiceLike {\n\t/** @internal */\n\tlistAll(): readonly RegisteredProcessWatcherLike[];\n\t/** @public */\n\tlistBySource<TConfig, TEvent>(\n\t\tsource: ProcessWatcherSource<TConfig, TEvent>,\n\t): readonly RegisteredProcessWatcherLike<TConfig, TEvent>[];\n}\n\n/** @public */\nexport interface PollResultLike {\n\t/** @internal */\n\treadonly errors: readonly string[];\n}\n\n/** @public */\nexport interface PollingServiceLike {\n\t/** @public */\n\tcreate<T extends PollResultLike>(options: {\n\t\t/** @public */\n\t\tid: string;\n\t\t/** @public */\n\t\tpollOnce(): Promise<T>;\n\t\t/** @public */\n\t\tisEnabled(): boolean;\n\t\t/** @public */\n\t\tpollInterval(): string;\n\t\t/** @public */\n\t\tdefaultIntervalMs?: number;\n\t}): {\n\t\t/** @public */\n\t\tpoll(): Promise<T>;\n\t};\n}\n\n/** @internal */\nexport interface ProcessQuestionServiceLike {\n\t/** @internal */\n\tlistOpen(instanceId?: string): readonly import(\"@leitwerk-dev/domain\").ProcessQuestionRequest[];\n\t/** @internal */\n\tsubmitAnswers(\n\t\tinstanceId: string,\n\t\trequestId: string,\n\t\tdraft: readonly import(\"@leitwerk-dev/domain\").QuestionAnswerDraft[],\n\t\tactor: Actor,\n\t): Promise<\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tok: true;\n\t\t\t\t/** @internal */\n\t\t\t\trequest: import(\"@leitwerk-dev/domain\").ProcessQuestionRequest;\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tok: false;\n\t\t\t\t/** @internal */\n\t\t\t\tcode: \"not_found\" | \"not_current\" | \"invalid\";\n\t\t\t\t/** @internal */\n\t\t\t\tmessage: string;\n\t\t\t\t/** @internal */\n\t\t\t\trequest?: import(\"@leitwerk-dev/domain\").ProcessQuestionRequest;\n\t\t }\n\t>;\n}\n\n/** @public */\nexport interface CoreServerSetupDeps {\n\t/** @internal */\n\tserverBaseUrl: string;\n\t/** @internal */\n\tprocessWorkspacesDir?: string;\n\t/** @internal */\n\tcomponents: Record<string, ComponentConfigLike>;\n\t/** Typed by consuming extensions via watcher-utils ExternalWriteLogRepoLike. @public */\n\texternalWrites: unknown;\n\t/** @public */\n\tprocesses: ProcessRepoLike;\n\t/** @public */\n\tprojects: ProcessProjectRepoLike;\n\t/** @public */\n\tevents: ProcessEventRepoLike;\n\t/** @internal */\n\tbroadcaster: BroadcasterLike;\n\t/** @public */\n\tcommands: ProcessEngineLike;\n\t/** @internal */\n\tprocessActions: ProcessActionServiceLike;\n\t/** @public */\n\texternalSources: ExternalSourceServiceLike;\n\t/** @internal */\n\tgetSupervisor: () => WorkerSupervisorLike | undefined;\n\t/** @internal */\n\tlauncherService: ProcessLauncherService;\n\t/** @internal */\n\tlauncherRecentValues: LauncherRecentValuesServiceLike;\n\t/** @internal */\n\tlauncherModelConfigs: LauncherModelConfigServiceLike;\n\t/** @internal */\n\tlaunchPlans: ProcessLaunchPlanServiceLike;\n\t/** @internal */\n\thandoffDedupKeys?: HandoffDedupKeyServiceLike;\n\t/** @public */\n\tprocessWatchers?: ProcessWatcherServiceLike;\n\t/** @public */\n\tlaunchRuns: LaunchRunServiceLike;\n\t/** @public */\n\tpolling: PollingServiceLike;\n\t/** @internal */\n\tprocessModelSelection?: ProcessModelSelectionServiceLike;\n\t/** Durable active-turn questions for trusted operator-channel extensions. @internal */\n\tprocessQuestions?: ProcessQuestionServiceLike;\n\t/** Registration boundary for secret-backed repository credential extensions. @internal */\n\trepositoryCredentials: RepositoryCredentialRegistrar;\n\t/** Server-owned managed result images, available to trusted delivery extensions. @internal */\n\tresultImages?: {\n\t\t/** @internal */\n\t\tget(instanceId: string, turnRecordId: string, imageId: string): Promise<Uint8Array | null>;\n\t};\n}\n\n/** @internal */\nexport type ProcessActionModelPreviewLike = ProcessActionModelPreview;\n\n/** @internal */\nexport type ProcessModelSelectionPreviewFailureCode =\n\t| \"process_not_found\"\n\t| \"instance_tree_unavailable\";\n\n/** @internal */\nexport type ProcessModelSelectionPreviewResultLike =\n\t| ProcessActionModelPreviewLike\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"operational_failure\";\n\t\t\t/** @internal */\n\t\t\tcode: ProcessModelSelectionPreviewFailureCode;\n\t };\n\n/** @internal */\nexport interface ModelProfileOptionSummaryLike {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\tavailability: \"available\" | \"unavailable\" | \"stale\";\n}\n\n/** @internal */\nexport interface ProcessModelSelectionServiceLike {\n\t/** @internal */\n\tlistAvailableProfiles(instanceId: string): readonly ModelProfileOptionSummaryLike[] | null;\n\t/** @internal */\n\tpreview(\n\t\tinstanceId: string,\n\t\tactionId: string,\n\t\tinput: Record<string, unknown>,\n\t): Promise<ProcessModelSelectionPreviewResultLike>;\n}\n\n/** @public */\nexport const coreHostCapabilities = {\n\t/** @public */\n\tserverSetup: createCapabilityToken<CoreServerSetupDeps>(\"core:serverSetup\"),\n\t/** @internal */\n\tprocessModelSelection: createCapabilityToken<ProcessModelSelectionServiceLike>(\n\t\t\"core:processModelSelection\",\n\t),\n} as const;\n","import {\n\tassertValidProcessProductName,\n\ttrimString as normalizeEffectString,\n\tnormalizeStringArray as normalizeEffectStringArray,\n\ttype ProcessInstance,\n\ttype ProcessSemanticEntryRefKey,\n\ttype ProcessTurnStartSelection,\n\ttype ProcessTurnTerminalLifecycleStatus,\n\ttype ProcessTurnTransition,\n\ttype TurnId,\n\ttype TurnProgressReport,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tExtensionProcessDefinition,\n\tExternalActionSource,\n\tExternalSourceEffect,\n\tExternalSourceResolveContext,\n\tFormDefinition,\n\tProcessTurnBinding,\n\tProcessTurnOutcomeEvent,\n\tServerProcessContext,\n\tServerTransitionRequest,\n\tWorkerCompleteInput,\n\tWorkerProcessContext,\n} from \"./extension-api.js\";\nimport { type MappedLlmTurnSpec, mappedCollectTrigger } from \"./mapped-turn.js\";\nimport {\n\tgetProcessTurnTransitions,\n\tmarkDefinedProcess,\n\tsetProcessTurnTransitions,\n} from \"./process-definition-internals.js\";\nimport type { ServerExtensionEventMap } from \"./server-events.js\";\nimport type {\n\tHumanTurnActionView,\n\tHumanTurnExternalActionView,\n\tHumanTurnExternalTrigger,\n\tHumanTurnNotesField,\n\tOutcomeToolParameterSpec,\n\tPiBuiltInToolName,\n\tProcessActionPreviewDefinition,\n\tProcessActionSchedulingDefinition,\n\tTurnAcceptanceState,\n\tTurnBranchType,\n\tTurnCompletionMode,\n\tTurnContextMode,\n\tTurnResultMarkdownBehavior,\n} from \"./types.js\";\n\n/** @internal */\ntype ProcessEventName = keyof ServerExtensionEventMap & string;\n\n/** @internal */\ntype ProcessEmittedEvent = {\n\t/** @internal */\n\ttype: ProcessEventName;\n\t/** @internal */\n\tdata: unknown;\n};\n\n/** @public */\ntype ProcessQueuedInput = Parameters<ServerProcessContext[\"queueInput\"]>[0];\n\n/** @public */\ntype MaybePromise<T> = T | Promise<T>;\n\n/** @public */\ntype StaticRouteTarget = {\n\t/** @public */\n\tto?: TurnId;\n\t/** @internal */\n\tcomplete?: boolean;\n\t/** @public */\n\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n};\n\ntype NormalizedRouteTarget = {\n\tnextTurnId?: TurnId;\n\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n};\n\ntype NormalizedActionRoute = NormalizedRouteTarget & {\n\ttrigger: string;\n};\n\n/** @public */\nexport interface ProcessRuntimeTurnContext<TParams = unknown, TState = unknown>\n\textends WorkerProcessContext<TParams, TState> {}\n\n/** @internal */\nexport interface LlmTurnPreparationContext<TParams = unknown, TState = unknown>\n\textends ProcessRuntimeTurnContext<TParams, TState> {\n\t/** @internal */\n\tcallIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;\n\t/** @internal */\n\treportProgress(report: TurnProgressReport): void;\n}\n\n/** @public */\nexport interface ProcessServerRuntimeContext<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly process: ServerProcessContext<TParams, TState>[\"process\"];\n\t/** @internal */\n\treadonly projects: ServerProcessContext<TParams, TState>[\"projects\"];\n\t/** @internal */\n\treadonly params: TParams;\n\t/** @public */\n\treadonly state: TState;\n\t/** @internal */\n\treadSemanticTurnResultMarkdown(ref: ProcessSemanticEntryRefKey): string | null;\n\t/** @internal */\n\treadProductTurnResultMarkdown(productName: string): string | null;\n\t/** @internal */\n\treportProgress?(report: TurnProgressReport): void;\n}\n\n/** @internal */\nexport interface ProcessBroadcastEffect {\n\t/** @internal */\n\ttype: string;\n\t/** @internal */\n\tpayload: Record<string, unknown>;\n}\n\n/** @public */\nexport type ProcessPatchEffect = Partial<\n\tPick<\n\t\tProcessInstance,\n\t\t| \"lifecycleStatus\"\n\t\t| \"planRevision\"\n\t\t| \"title\"\n\t\t| \"externalId\"\n\t\t| \"externalUrl\"\n\t\t| \"metadata\"\n\t\t| \"defaultModelProfileId\"\n\t\t| \"turnConfigsJson\"\n\t>\n>;\n\n/** @public */\nexport interface ProcessLifecycleEffects {\n\t/** @public */\n\tprocessPatch?: ProcessPatchEffect;\n\t/** @internal */\n\tbroadcasts?: readonly ProcessBroadcastEffect[];\n}\n\n/** @public */\nexport interface ProcessEffectPlan<TState = unknown> extends ProcessLifecycleEffects {\n\t/** @public */\n\tstate?: TState;\n\t/** @internal */\n\temit?: readonly ProcessEmittedEvent[];\n\t/** @public */\n\tqueueInput?: readonly ProcessQueuedInput[];\n}\n\n/** @internal */\nexport interface SavePlanResultLifecycleIntent<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tkind: \"save_plan_result\";\n\t/** @internal */\n\tsummaryParam: string;\n\t/** @internal */\n\tacceptanceCriteriaParam: string;\n\t/** @internal */\n\tplanMarkdownParam: string;\n\t/** @internal */\n\temitEventType: ProcessEventName;\n\t/** @internal */\n\tbroadcastType: string;\n\t/** @internal */\n\tstate?: ProcessOutcomeEffect<TParams, TState>;\n}\n\n/** @internal */\nexport type ProcessOutcomeLifecycleIntent<\n\tTParams = unknown,\n\tTState = unknown,\n> = SavePlanResultLifecycleIntent<TParams, TState>;\n\n/** @public */\nexport interface ProcessActionExecution<TParams = unknown, TState = unknown> {\n\t/** @public */\n\treadonly ctx: ProcessServerRuntimeContext<TParams, TState>;\n\t/** @public */\n\treadonly input: Record<string, unknown>;\n\t/** @internal */\n\treadonly turnId: TurnId;\n\t/** @internal */\n\treadonly actionId: string;\n\t/** @internal */\n\treadonly selectedBranchId?: string;\n}\n\n/** @public */\nexport interface ProcessOutcomeExecution<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly ctx: ProcessServerRuntimeContext<TParams, TState>;\n\t/** @internal */\n\treadonly event: ProcessTurnOutcomeEvent;\n\t/** @internal */\n\treadonly turnId: TurnId;\n\t/** @internal */\n\treadonly outcome: string;\n}\n\n/** @public */\nexport type ProcessActionEffect<TParams = unknown, TState = unknown> = (\n\tinput: ProcessActionExecution<TParams, TState>,\n) => MaybePromise<ProcessEffectPlan<TState> | undefined>;\n\n/** @public */\nexport type ProcessActionBranchSelector<TParams = unknown, TState = unknown> = (\n\tinput: Omit<ProcessActionExecution<TParams, TState>, \"selectedBranchId\">,\n) => MaybePromise<string>;\n\n/** @public */\nexport type ProcessOutcomeEffect<TParams = unknown, TState = unknown> = (\n\tinput: ProcessOutcomeExecution<TParams, TState>,\n) => MaybePromise<ProcessEffectPlan<TState> | undefined>;\n\n/** @internal */\nexport type ProcessOutcomeBranchSelector<TParams = unknown, TState = unknown> = (\n\tinput: ProcessOutcomeExecution<TParams, TState>,\n) => MaybePromise<string>;\n\n/** @internal */\nexport interface ProcessOutcomeBranchSpec extends StaticRouteTarget {\n\t/** @internal */\n\ttrigger?: string;\n}\n\n/** @internal */\nexport interface ProcessActionExternalTrigger {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription: string;\n}\n\n/** @internal */\nexport interface ExternalActionInputPublication {\n\t/** @internal */\n\tproductName: string;\n\t/** @internal */\n\tinputField: string;\n}\n\n/** @public */\nexport interface ProcessHumanTurnExternalActionSpec<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends StaticRouteTarget {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>;\n\t/** Arms and exposes this action only when the current process snapshot matches. @public */\n\twhen?: (ctx: ExternalSourceResolveContext<TParams, TState>) => boolean;\n\t/** @internal */\n\tlabel?: string;\n\t/** @internal */\n\tdescription?: string;\n\t/** @internal */\n\tpublishInput?: ExternalActionInputPublication;\n\t/** @public */\n\teffect?: ExternalSourceEffect<TParams, TState, TEvent, TInput>;\n}\n\n/** @public */\nexport interface ProcessActionBranchSpec extends StaticRouteTarget {\n\t/** @internal */\n\ttrigger?: string;\n}\n\n/** @public */\ntype StaticActionRouting = StaticRouteTarget & {\n\t/** @internal */\n\ttrigger?: string;\n};\n\n/** @public */\ntype BranchingActionRouting<TParams, TState> = {\n\t/** @public */\n\tbranches: Record<string, ProcessActionBranchSpec>;\n\t/** @public */\n\tchoose: ProcessActionBranchSelector<TParams, TState>;\n};\n\n/** @public */\ninterface BaseActionSpec<TParams, TState> {\n\t/** @public */\n\tlabel: string;\n\t/** @public */\n\tdescription?: string;\n\t/** @internal */\n\tform?: FormDefinition;\n\t/** @public */\n\tpreview?: ProcessActionPreviewDefinition;\n\t/** @public */\n\tschedulable?: boolean;\n\t/** @public */\n\teffect?: ProcessActionEffect<TParams, TState>;\n}\n\n/** @public */\nexport type ProcessHumanTurnActionSpec<TParams = unknown, TState = unknown> = BaseActionSpec<\n\tTParams,\n\tTState\n> & {\n\t/** @public */\n\tacceptanceState: TurnAcceptanceState;\n\t/** @internal */\n\texternalTriggers?: readonly ProcessActionExternalTrigger[];\n} & (StaticActionRouting | BranchingActionRouting<TParams, TState>);\n\n/** @public */\ninterface ProcessToolOutcomeBaseSpec<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\tparameters: Record<string, OutcomeToolParameterSpec>;\n\t/** Product published from this outcome's turn-result markdown, when this outcome is selected. @internal */\n\tpublishedProduct?: string;\n\t/** Outcome parameter whose markdown value is captured as the turn result. @internal */\n\tturnResultMarkdownParameter?: string;\n\t/** Outcome parameter containing a concise operator-facing summary. @internal */\n\tresultSummaryParameter?: string;\n\t/** @internal */\n\teffect?: ProcessOutcomeEffect<TParams, TState>;\n\t/** @internal */\n\tlifecycleIntent?: ProcessOutcomeLifecycleIntent<TParams, TState>;\n}\n\n/** @public */\nexport type ProcessToolOutcomeSpec<\n\tTParams = unknown,\n\tTState = unknown,\n> = ProcessToolOutcomeBaseSpec<TParams, TState> &\n\t(\n\t\t| StaticRouteTarget\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tbranches: Record<string, ProcessOutcomeBranchSpec>;\n\t\t\t\t/** @internal */\n\t\t\t\tchoose: ProcessOutcomeBranchSelector<TParams, TState>;\n\t\t }\n\t);\n/** @public */\nexport type HumanTurnOperatorAttention = \"required\" | \"passive\";\n\n/** @public */\nexport interface HumanTurnDefinition<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tkind: \"human\";\n\t/** @public */\n\tdescription: string;\n\t/** Named product rendered as the subject of this human review turn. @internal */\n\treviewProduct?: string;\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** Controls whether entering this turn should raise an action-required toast. @public */\n\toperatorAttention?: HumanTurnOperatorAttention;\n\t/** @internal */\n\tnotesFields?: readonly HumanTurnNotesField[];\n\t/** @internal */\n\tcommentary?: string;\n\t/** @public */\n\tactions: Record<string, ProcessHumanTurnActionSpec<TParams, TState>>;\n\t/** @internal */\n\texternalActions?: Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>;\n}\n\n/** @public */\nexport interface ProcessTurnEndSpec<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n> extends StaticRouteTarget {\n\t/** @public */\n\toutcome: TOutcome;\n\t/** @public */\n\tparams?: Record<string, unknown>;\n\t/** @public */\n\teffect?: ProcessOutcomeEffect<TParams, TState>;\n}\n\n/** @internal */\nexport type OutcomeRouteSpec<TParams = unknown, TState = unknown> = StaticRouteTarget &\n\tPartial<Pick<ProcessToolOutcomeSpec<TParams, TState>, \"description\" | \"parameters\" | \"effect\">>;\n\n/** @internal */\nexport interface OutcomeRouteOptions {\n\t/** @internal */\n\tstrict?: boolean;\n}\n\n/** @internal */\nexport type LlmModelPurpose = \"process_title_generation\";\n\n/** @public */\nexport interface LlmTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n> {\n\t/** @public */\n\tkind: \"llm\";\n\t/** @public */\n\tdescription: string;\n\t/** Code-defined model policy purpose. Purpose selections cannot be overridden per launch/action. @internal */\n\tmodelPurpose?: LlmModelPurpose;\n\t/** Built-in Pi tools active while this turn runs. @public */\n\tavailableTools: readonly PiBuiltInToolName[];\n\t/** Server-owned integration tools proxied over authenticated worker IPC. @internal */\n\tintegrationTools?: readonly string[];\n\t/** Resolve a constrained tool set from validated durable process data at turn start. @public */\n\tresolveIntegrationTools?: (params: TParams, state: TState) => readonly string[];\n\t/** Opt in to the durable, operator-facing ask_questions custom tool. @internal */\n\taskQuestions?: boolean;\n\t/** Deterministic worker preparation that must complete before Pi is prompted. @internal */\n\tprepare?(ctx: LlmTurnPreparationContext<TParams, TState>): MaybePromise<unknown>;\n\t/** @public */\n\tcompletionMode?: TurnCompletionMode;\n\t/** @public */\n\tbranchType: TurnBranchType;\n\t/** @public */\n\tcontext: TurnContextMode;\n\t/** @internal */\n\tstartFrom?: ProcessTurnStartSelection;\n\t/** @internal */\n\trestorePrimaryLeafAfterTurn?: boolean;\n\t/** @public */\n\tprompt(ctx: ProcessRuntimeTurnContext<TParams, TState>): string | Promise<string>;\n\t/** @public */\n\toutcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;\n\t/** @public */\n\tturnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;\n\t/** @public */\n\tturnResultMarkdown?: TurnResultMarkdownBehavior;\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @internal */\n\tresultSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @internal */\n\tpublishedProduct?: string;\n\t/** @internal */\n\tconsumedProducts?: readonly string[];\n\t/** @internal */\n\toptionalConsumedProducts?: readonly string[];\n\t/** @internal */\n\trequiredSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n\t/** @internal */\n\toptionalSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n\t/** Runs this turn once per frozen item, then collects and routes once. @public */\n\tforEach?: MappedLlmTurnSpec<TParams, TState>;\n}\n\n/** @public */\nexport interface AutomaticTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n> {\n\t/** @public */\n\tkind: \"automatic\";\n\t/** @public */\n\tdescription: string;\n\t/** Server-owned integration tools callable by this deterministic worker turn. @internal */\n\tintegrationTools?: readonly string[];\n\t/** External events armed while this automatic turn is selected and waiting. @public */\n\texternalActions?: Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>;\n\t/** @internal */\n\toutcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;\n\t/** @internal */\n\tturnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @public */\n\trun(\n\t\tctx: ProcessRuntimeTurnContext<TParams, TState>,\n\t): Promise<WorkerCompleteInput<TOutcome>> | WorkerCompleteInput<TOutcome>;\n}\n\n/** @internal */\nexport interface ExternalSourceTransition<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends StaticRouteTarget {\n\t/** @internal */\n\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>;\n\t/** @internal */\n\teffect?: ExternalSourceEffect<TParams, TState, TEvent, TInput>;\n}\n\n/** @public */\nexport interface ExternalTurnDefinition<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tkind: \"external\";\n\t/** @public */\n\tdescription: string;\n\t/** @internal */\n\ttransitions: readonly ExternalSourceTransition<TParams, TState>[];\n\t/** @internal */\n\treviewSemanticRef?: ProcessSemanticEntryRefKey;\n}\n\n/** @public */\nexport type TurnDefinition<TParams = unknown, TState = unknown> =\n\t| LlmTurnDefinition<string, TParams, TState>\n\t| AutomaticTurnDefinition<string, TParams, TState>\n\t| HumanTurnDefinition<TParams, TState>\n\t| ExternalTurnDefinition<TParams, TState>;\n\n/** @public */\nexport type TurnDefinitionRecord<TParams = unknown, TState = unknown> = Record<\n\tTurnId,\n\tTurnDefinition<TParams, TState>\n>;\n\n/** @public */\nexport interface DefinedProcessInput<TParams = unknown, TState = unknown>\n\textends Omit<\n\t\tExtensionProcessDefinition<TParams, TState>,\n\t\t\"entryTurnId\" | \"alternateEntryTurnIds\" | \"turns\"\n\t> {\n\t/** Primary entry used when a launch does not select a start turn explicitly. @public */\n\tentry: TurnId;\n\t/** Additional entry turns that launchers may select explicitly. @public */\n\talternateEntries?: readonly TurnId[];\n\t/** @public */\n\tturns: TurnDefinitionRecord<TParams, TState>;\n}\n\ntype CompiledActionRouting<TParams, TState> =\n\t| {\n\t\t\tkind: \"static\";\n\t\t\troute: NormalizedActionRoute;\n\t }\n\t| {\n\t\t\tkind: \"branches\";\n\t\t\troutes: Record<string, NormalizedActionRoute>;\n\t\t\tchoose: ProcessActionBranchSelector<TParams, TState>;\n\t };\n\ntype CompiledActionUse<TParams, TState> = {\n\tturnId: TurnId;\n\tlabel?: string;\n\tform?: FormDefinition;\n\teffect?: ProcessActionEffect<TParams, TState>;\n\trouting: CompiledActionRouting<TParams, TState>;\n};\n\ninterface CompiledOutcomeHandlers<TParams, TState> {\n\teffects: ReadonlyMap<string, ProcessOutcomeEffect<TParams, TState> | undefined>;\n\troutings: ReadonlyMap<string, CompiledOutcomeRouting<TParams, TState>>;\n}\n\nfunction createProcessTurnBinding<TTurn>(\n\tdefinition: TTurn,\n\ttransitions?: readonly ProcessTurnTransition[],\n): ProcessTurnBinding<TTurn> {\n\tconst binding: ProcessTurnBinding<TTurn> = { definition };\n\tif (transitions && transitions.length > 0) {\n\t\tsetProcessTurnTransitions(binding, transitions);\n\t}\n\treturn binding;\n}\n\nfunction normalizeStaticRouteTarget(\n\tcontext: string,\n\ttarget: StaticRouteTarget,\n\tknownTurnIds?: ReadonlySet<TurnId>,\n): NormalizedRouteTarget {\n\tconst declaredTargetCount =\n\t\t(target.to !== undefined ? 1 : 0) +\n\t\t(target.complete === true ? 1 : 0) +\n\t\t(target.lifecycleStatus !== undefined ? 1 : 0);\n\tif (declaredTargetCount !== 1) {\n\t\tthrow new Error(\n\t\t\t`${context} must declare exactly one target via 'to', 'complete', or 'lifecycleStatus'`,\n\t\t);\n\t}\n\tif (target.to !== undefined) {\n\t\tif (knownTurnIds && !knownTurnIds.has(target.to)) {\n\t\t\tthrow new Error(`${context} references unknown turn '${target.to}'`);\n\t\t}\n\t\treturn { nextTurnId: target.to };\n\t}\n\tif (target.complete === true) {\n\t\treturn { lifecycleStatus: \"completed\" };\n\t}\n\treturn { lifecycleStatus: target.lifecycleStatus };\n}\n\nfunction buildOutcomeTransition<TParams, TState>(\n\tturnId: TurnId,\n\toutcome: string,\n\ttarget: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState>,\n\tknownTurnIds?: ReadonlySet<TurnId>,\n): NormalizedRouteTarget {\n\tif (\"branches\" in target) {\n\t\tthrow new Error(\n\t\t\t`Turn '${turnId}' outcome '${outcome}' must compile state routing before a static transition`,\n\t\t);\n\t}\n\tif (!hasDeclaredStaticRouteTarget(target)) {\n\t\treturn { nextTurnId: turnId };\n\t}\n\treturn normalizeStaticRouteTarget(`Turn '${turnId}' outcome '${outcome}'`, target, knownTurnIds);\n}\n\ntype CompiledOutcomeRouting<TParams, TState> = {\n\troutes: Readonly<Record<string, NormalizedActionRoute>>;\n\tchoose: ProcessOutcomeBranchSelector<TParams, TState>;\n};\n\ntype BranchRouteSpec = StaticRouteTarget & { trigger?: string };\n\nfunction compileBranchRoutes(input: {\n\tbranches: Record<string, BranchRouteSpec>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n\ttargetContext(branchId: string): string;\n\temptyBranchError: string;\n\tduplicateTriggerError(trigger: string): string;\n}): {\n\troutes: Record<string, NormalizedActionRoute>;\n\ttransitions: NormalizedActionRoute[];\n} {\n\tconst routes: Record<string, NormalizedActionRoute> = {};\n\tconst transitions: NormalizedActionRoute[] = [];\n\tconst usedTriggers = new Set<string>();\n\tfor (const [branchId, branchSpec] of Object.entries(input.branches)) {\n\t\tif (branchId.trim() === \"\") throw new Error(input.emptyBranchError);\n\t\tconst target = normalizeStaticRouteTarget(\n\t\t\tinput.targetContext(branchId),\n\t\t\tbranchSpec,\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\tconst trigger = branchSpec.trigger ?? branchId;\n\t\tif (usedTriggers.has(trigger)) throw new Error(input.duplicateTriggerError(trigger));\n\t\tusedTriggers.add(trigger);\n\t\tconst route = { ...target, trigger };\n\t\troutes[branchId] = route;\n\t\ttransitions.push(route);\n\t}\n\treturn { routes, transitions };\n}\n\nfunction resolveOutcomeRouting<TParams, TState>(input: {\n\tturnId: TurnId;\n\toutcome: string;\n\tspec: ProcessToolOutcomeSpec<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): CompiledOutcomeRouting<TParams, TState> | null {\n\tif (!(\"branches\" in input.spec)) {\n\t\treturn null;\n\t}\n\tconst entries = Object.entries(input.spec.branches);\n\tif (entries.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.turnId}' outcome '${input.outcome}' must declare at least one branch`,\n\t\t);\n\t}\n\tconst { routes } = compileBranchRoutes({\n\t\tbranches: input.spec.branches,\n\t\tknownTurnIds: input.knownTurnIds,\n\t\ttargetContext: (branchId) =>\n\t\t\t`Turn '${input.turnId}' outcome '${input.outcome}' branch '${branchId}'`,\n\t\temptyBranchError: `Turn '${input.turnId}' outcome '${input.outcome}' contains an empty branch id`,\n\t\tduplicateTriggerError: (trigger) =>\n\t\t\t`Turn '${input.turnId}' outcome '${input.outcome}' contains duplicate branch trigger '${trigger}'`,\n\t});\n\treturn { routes, choose: input.spec.choose };\n}\n\nfunction resolveActionRouting<TParams, TState>(input: {\n\tturnId: TurnId;\n\tactionId: string;\n\tspec: ProcessHumanTurnActionSpec<TParams, TState>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n}): {\n\trouting: CompiledActionRouting<TParams, TState>;\n\ttransitions: readonly NormalizedActionRoute[];\n} {\n\tif (\"branches\" in input.spec) {\n\t\tconst entries = Object.entries(input.spec.branches) as Array<[string, ProcessActionBranchSpec]>;\n\t\tif (entries.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Action '${input.actionId}' on turn '${input.turnId}' must declare at least one branch`,\n\t\t\t);\n\t\t}\n\t\tconst { routes, transitions } = compileBranchRoutes({\n\t\t\tbranches: input.spec.branches,\n\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t\ttargetContext: (branchId) =>\n\t\t\t\t`Action '${input.actionId}' branch '${branchId}' on turn '${input.turnId}'`,\n\t\t\temptyBranchError: `Action '${input.actionId}' on turn '${input.turnId}' contains an empty branch id`,\n\t\t\tduplicateTriggerError: (trigger) =>\n\t\t\t\t`Action '${input.actionId}' on turn '${input.turnId}' contains duplicate branch trigger '${trigger}'`,\n\t\t});\n\t\treturn {\n\t\t\trouting: {\n\t\t\t\tkind: \"branches\",\n\t\t\t\troutes,\n\t\t\t\tchoose: input.spec.choose,\n\t\t\t},\n\t\t\ttransitions,\n\t\t};\n\t}\n\tconst target = normalizeStaticRouteTarget(\n\t\t`Action '${input.actionId}' on turn '${input.turnId}'`,\n\t\tinput.spec,\n\t\tinput.knownTurnIds,\n\t);\n\tconst route = {\n\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\ttrigger: input.spec.trigger ?? input.actionId,\n\t};\n\treturn {\n\t\trouting: {\n\t\t\tkind: \"static\",\n\t\t\troute,\n\t\t},\n\t\ttransitions: [route],\n\t};\n}\n\n/** @internal */\nexport function getExternalSourceTransitionId(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tsource: ExternalActionSource;\n\t/** @internal */\n\tindex: number;\n}): string {\n\treturn `${input.turnId}:${input.source.kind}:${input.index}`;\n}\n\n/** @internal */\nexport function getExternalActionArmingId(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\texternalActionId: string;\n}): string {\n\treturn `${input.turnId}:${input.externalActionId}`;\n}\n\n/** @internal */\nexport function getExternalActionTransitionTrigger(input: {\n\t/** @internal */\n\texternalActionId: string;\n}): string {\n\treturn `external:${input.externalActionId}`;\n}\n\nfunction compileExternalSourceTransitions<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: ExternalTurnDefinition<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): readonly ProcessTurnTransition[] {\n\tif (input.spec.transitions.length === 0) {\n\t\tthrow new Error(`External turn '${input.turnId}' must declare at least one source transition`);\n\t}\n\treturn input.spec.transitions.map((transition, index) => {\n\t\tif (transition.source.kind.trim() === \"\") {\n\t\t\tthrow new Error(\n\t\t\t\t`External turn '${input.turnId}' source transition ${index} has an empty kind`,\n\t\t\t);\n\t\t}\n\t\tconst target = normalizeStaticRouteTarget(\n\t\t\t`External turn '${input.turnId}' source '${transition.source.kind}'`,\n\t\t\ttransition,\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\treturn {\n\t\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\t\ttrigger: getExternalSourceTransitionId({\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tsource: transition.source,\n\t\t\t\tindex,\n\t\t\t}),\n\t\t};\n\t});\n}\n\nfunction previewMatchesTransition(\n\tpreview: ProcessActionPreviewDefinition,\n\ttransition: NormalizedActionRoute,\n): boolean {\n\tif (preview.kind === \"trigger\") {\n\t\treturn transition.trigger === preview.trigger;\n\t}\n\tif (preview.kind === \"terminal\") {\n\t\treturn transition.lifecycleStatus === preview.lifecycleStatus;\n\t}\n\treturn transition.nextTurnId === preview.turnId;\n}\n\nfunction validateActionPreviewMatchesTransitions(input: {\n\tturnId: TurnId;\n\tactionId: string;\n\tpreview: ProcessActionPreviewDefinition;\n\ttransitions: readonly NormalizedActionRoute[];\n\tcontext: \"preview\" | \"scheduling\";\n}): void {\n\tconst matches = input.transitions.filter((transition) =>\n\t\tpreviewMatchesTransition(input.preview, transition),\n\t);\n\tif (matches.length === 1) {\n\t\treturn;\n\t}\n\tconst previewLabel =\n\t\tinput.preview.kind === \"trigger\"\n\t\t\t? `trigger '${input.preview.trigger}'`\n\t\t\t: input.preview.kind === \"terminal\"\n\t\t\t\t? `terminal '${input.preview.lifecycleStatus}'`\n\t\t\t\t: `fixed turn '${String(input.preview.turnId)}'`;\n\tthrow new Error(\n\t\t`Action '${input.actionId}' on turn '${input.turnId}' ${input.context} does not match a compiled transition for ${previewLabel}`,\n\t);\n}\n\nfunction buildActionPreviewAndScheduling(\n\tturnId: TurnId,\n\tactionId: string,\n\tspec: Pick<BaseActionSpec<unknown, unknown>, \"preview\" | \"schedulable\">,\n\ttransitions: readonly NormalizedActionRoute[],\n): {\n\tpreview?: ProcessActionPreviewDefinition;\n\tscheduling?: ProcessActionSchedulingDefinition;\n} {\n\tconst preview = (() => {\n\t\tif (spec.preview) {\n\t\t\treturn spec.preview;\n\t\t}\n\t\tif (transitions.length !== 1) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst [transition] = transitions;\n\t\tif (!transition) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (transition.lifecycleStatus !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: \"terminal\",\n\t\t\t\tlifecycleStatus: transition.lifecycleStatus,\n\t\t\t} satisfies ProcessActionPreviewDefinition;\n\t\t}\n\t\treturn {\n\t\t\tkind: \"trigger\",\n\t\t\ttrigger: transition.trigger,\n\t\t} satisfies ProcessActionPreviewDefinition;\n\t})();\n\tif (spec.preview && preview) {\n\t\tvalidateActionPreviewMatchesTransitions({\n\t\t\tturnId,\n\t\t\tactionId,\n\t\t\tpreview,\n\t\t\ttransitions,\n\t\t\tcontext: \"preview\",\n\t\t});\n\t}\n\tif (spec.schedulable && preview) {\n\t\tvalidateActionPreviewMatchesTransitions({\n\t\t\tturnId,\n\t\t\tactionId,\n\t\t\tpreview,\n\t\t\ttransitions,\n\t\t\tcontext: \"scheduling\",\n\t\t});\n\t}\n\tif (spec.schedulable && !preview) {\n\t\tthrow new Error(\n\t\t\t`Action '${actionId}' is schedulable but does not resolve to a unique preview transition`,\n\t\t);\n\t}\n\treturn {\n\t\t...(preview ? { preview } : {}),\n\t\t...(spec.schedulable && preview ? { scheduling: { preview } } : {}),\n\t};\n}\n\nfunction mergeProcessEffectPlans<TState>(\n\tleft: ProcessEffectPlan<TState> | undefined,\n\tright: ProcessEffectPlan<TState> | undefined,\n): ProcessEffectPlan<TState> | undefined {\n\tif (!left) {\n\t\treturn right;\n\t}\n\tif (!right) {\n\t\treturn left;\n\t}\n\treturn {\n\t\t...left,\n\t\t...right,\n\t\t...(left.processPatch || right.processPatch\n\t\t\t? { processPatch: { ...(left.processPatch ?? {}), ...(right.processPatch ?? {}) } }\n\t\t\t: {}),\n\t\t...(left.broadcasts || right.broadcasts\n\t\t\t? { broadcasts: [...(left.broadcasts ?? []), ...(right.broadcasts ?? [])] }\n\t\t\t: {}),\n\t\t...(left.emit || right.emit ? { emit: [...(left.emit ?? []), ...(right.emit ?? [])] } : {}),\n\t\t...(left.queueInput || right.queueInput\n\t\t\t? { queueInput: [...(left.queueInput ?? []), ...(right.queueInput ?? [])] }\n\t\t\t: {}),\n\t};\n}\n\nasync function buildSavePlanResultEffect<TParams, TState>(input: {\n\tintent: SavePlanResultLifecycleIntent<TParams, TState>;\n\texecution: ProcessOutcomeExecution<TParams, TState>;\n}): Promise<ProcessEffectPlan<TState>> {\n\tconst statePlan = input.intent.state ? await input.intent.state(input.execution) : undefined;\n\tconst planRevision = input.execution.ctx.process.planRevision + 1;\n\tconst summary = normalizeEffectString(input.execution.event.params[input.intent.summaryParam]);\n\tconst acceptanceCriteria = normalizeEffectStringArray(\n\t\tinput.execution.event.params[input.intent.acceptanceCriteriaParam],\n\t);\n\tconst planMarkdown =\n\t\ttypeof input.execution.event.turnResultMarkdown === \"string\"\n\t\t\t? input.execution.event.turnResultMarkdown\n\t\t\t: normalizeEffectString(input.execution.event.params[input.intent.planMarkdownParam]);\n\n\treturn mergeProcessEffectPlans(statePlan, {\n\t\tprocessPatch: { planRevision },\n\t\tbroadcasts: [\n\t\t\t{\n\t\t\t\ttype: input.intent.broadcastType,\n\t\t\t\tpayload: {\n\t\t\t\t\tplanRevision,\n\t\t\t\t\treviewState: \"awaiting_approval\",\n\t\t\t\t\tapproved: false,\n\t\t\t\t\tsummary,\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\temit: [\n\t\t\t{\n\t\t\t\ttype: input.intent.emitEventType,\n\t\t\t\tdata: {\n\t\t\t\t\tplanRevision,\n\t\t\t\t\tsummary,\n\t\t\t\t\tplanMarkdown,\n\t\t\t\t\tacceptanceCriteria,\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t}) as ProcessEffectPlan<TState>;\n}\n\nfunction resolveOutcomeEffect<TParams, TState>(input: {\n\tspec: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState, string>;\n}): ProcessOutcomeEffect<TParams, TState> | undefined {\n\tconst lifecycleIntent = \"lifecycleIntent\" in input.spec ? input.spec.lifecycleIntent : undefined;\n\tif (!lifecycleIntent) {\n\t\treturn input.spec.effect;\n\t}\n\treturn async (execution) => {\n\t\tconst explicitPlan = input.spec.effect ? await input.spec.effect(execution) : undefined;\n\t\tlet lifecyclePlan: ProcessEffectPlan<TState> | undefined;\n\t\tswitch (lifecycleIntent.kind) {\n\t\t\tcase \"save_plan_result\":\n\t\t\t\tlifecyclePlan = await buildSavePlanResultEffect({\n\t\t\t\t\tintent: lifecycleIntent,\n\t\t\t\t\texecution,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t}\n\t\treturn mergeProcessEffectPlans(explicitPlan, lifecyclePlan);\n\t};\n}\n\nfunction areFormsEquivalent(\n\tleft: FormDefinition | undefined,\n\tright: FormDefinition | undefined,\n): boolean {\n\tif (left === right) {\n\t\treturn true;\n\t}\n\treturn JSON.stringify(left ?? null) === JSON.stringify(right ?? null);\n}\n\nfunction cloneStateForFormPatch<TState>(state: TState): TState {\n\tif (typeof state !== \"object\" || state === null) {\n\t\tthrow new Error(\"Declarative form state fields require object process state\");\n\t}\n\treturn structuredClone(state);\n}\n\nfunction normalizeFormStateValue(field: FormDefinition[\"fields\"][number], value: unknown): unknown {\n\tif (field.kind === \"number\") {\n\t\tconst parsed = typeof value === \"number\" ? value : Number(String(value).trim());\n\t\tif (!Number.isFinite(parsed)) {\n\t\t\tthrow new Error(`Field '${field.id}' must be a number`);\n\t\t}\n\t\treturn parsed;\n\t}\n\treturn value;\n}\n\nfunction applyFormStateFields<TState>(input: {\n\tform?: FormDefinition;\n\tinputValue: Record<string, unknown>;\n\tstate: TState;\n}): TState | undefined {\n\tconst stateFields = (input.form?.fields ?? []).filter((field) => field.state);\n\tif (stateFields.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst nextState = cloneStateForFormPatch(input.state) as Record<string, unknown>;\n\tfor (const field of stateFields) {\n\t\tconst rawValue = input.inputValue[field.id];\n\t\tif (rawValue === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst path = field.state?.path.trim();\n\t\tif (!path) {\n\t\t\tthrow new Error(`Form field '${field.id}' declares an empty state path`);\n\t\t}\n\t\tconst segments = path.split(\".\").map((segment) => segment.trim());\n\t\tif (segments.some((segment) => segment === \"\")) {\n\t\t\tthrow new Error(`Form field '${field.id}' declares invalid state path '${path}'`);\n\t\t}\n\t\tlet target: Record<string, unknown> = nextState;\n\t\tfor (const segment of segments.slice(0, -1)) {\n\t\t\tconst existing = target[segment];\n\t\t\tif (typeof existing !== \"object\" || existing === null || Array.isArray(existing)) {\n\t\t\t\ttarget[segment] = {};\n\t\t\t}\n\t\t\ttarget = target[segment] as Record<string, unknown>;\n\t\t}\n\t\ttarget[segments[segments.length - 1] as string] = normalizeFormStateValue(field, rawValue);\n\t}\n\treturn nextState as TState;\n}\n\nfunction makeProcessServerRuntimeContext<TParams, TState>(\n\tctx: ServerProcessContext<TParams, TState>,\n): ProcessServerRuntimeContext<TParams, TState> {\n\treturn {\n\t\tprocess: ctx.process,\n\t\tprojects: ctx.projects,\n\t\tparams: ctx.params,\n\t\tstate: ctx.state,\n\t\treadSemanticTurnResultMarkdown: (ref) => ctx.readSemanticTurnResultMarkdown(ref),\n\t\treadProductTurnResultMarkdown: (productName) => ctx.readProductTurnResultMarkdown(productName),\n\t};\n}\n\nfunction mergeTransitionWithState<TState>(input: {\n\tresult: ProcessEffectPlan<TState> | undefined;\n\ttransition?: Omit<ServerTransitionRequest<TState>, \"state\">;\n}): ServerTransitionRequest<TState> | null {\n\tconst next = {\n\t\t...(input.transition ?? {}),\n\t\t...(input.result?.state !== undefined ? { state: input.result.state } : {}),\n\t};\n\tconst hasFields =\n\t\tnext.turnId !== undefined ||\n\t\tnext.lifecycleStatus !== undefined ||\n\t\tnext.trigger !== undefined ||\n\t\tnext.effect !== undefined ||\n\t\tnext.state !== undefined;\n\treturn hasFields ? next : null;\n}\n\nfunction hasLifecycleEffects(result: ProcessEffectPlan | undefined): result is ProcessEffectPlan {\n\treturn Boolean(\n\t\tresult?.processPatch !== undefined ||\n\t\t\t(result?.broadcasts !== undefined && result.broadcasts.length > 0),\n\t);\n}\n\nasync function applyProcessEffectPlan<TParams, TState>(input: {\n\tctx: ServerProcessContext<TParams, TState>;\n\tresult: ProcessEffectPlan<TState> | undefined;\n\ttransition?: Omit<ServerTransitionRequest<TState>, \"state\">;\n}): Promise<void> {\n\tconst transition = mergeTransitionWithState({\n\t\tresult: input.result,\n\t\ttransition: input.transition,\n\t});\n\tif (transition) {\n\t\tawait input.ctx.transition(transition);\n\t}\n\tif (hasLifecycleEffects(input.result)) {\n\t\tif (!input.ctx.applyLifecycleEffects) {\n\t\t\tthrow new Error(\"Process lifecycle effects are not supported by this server context\");\n\t\t}\n\t\tinput.ctx.applyLifecycleEffects({\n\t\t\t...(input.result.processPatch ? { processPatch: input.result.processPatch } : {}),\n\t\t\t...(input.result.broadcasts ? { broadcasts: input.result.broadcasts } : {}),\n\t\t});\n\t}\n\tfor (const emitted of input.result?.emit ?? []) {\n\t\tinput.ctx.emitEvent(emitted.type, emitted.data as never);\n\t}\n\tfor (const queuedInput of input.result?.queueInput ?? []) {\n\t\tinput.ctx.queueInput(queuedInput);\n\t}\n}\n\nfunction compileTurnOutcomeDefinitions<TParams, TState>(input: {\n\tturnId: TurnId;\n\toutcomes?: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>>;\n\tturnEnd?: ProcessTurnEndSpec<TParams, TState, string>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): CompiledOutcomeHandlers<TParams, TState> & {\n\ttransitions: readonly ProcessTurnTransition[];\n} {\n\tconst outcomeEntries = Object.entries(input.outcomes ?? {}) as Array<\n\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t>;\n\tif (outcomeEntries.length > 0 && input.turnEnd) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.turnId}' cannot declare both tool outcomes and a turnEnd result`,\n\t\t);\n\t}\n\tif (outcomeEntries.length === 0 && !input.turnEnd) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.turnId}' must declare at least one tool outcome or a turnEnd result`,\n\t\t);\n\t}\n\n\tconst transitions: ProcessTurnTransition[] = [];\n\tconst effects = new Map<string, ProcessOutcomeEffect<TParams, TState> | undefined>();\n\tconst routings = new Map<string, CompiledOutcomeRouting<TParams, TState>>();\n\tfor (const [outcome, spec] of outcomeEntries) {\n\t\tif (outcome.trim() === \"\") {\n\t\t\tthrow new Error(`Turn '${input.turnId}' declares an empty outcome id`);\n\t\t}\n\t\tconst routing = resolveOutcomeRouting({\n\t\t\tturnId: input.turnId,\n\t\t\toutcome,\n\t\t\tspec,\n\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t});\n\t\tconst target = routing\n\t\t\t? null\n\t\t\t: buildOutcomeTransition(input.turnId, outcome, spec, input.knownTurnIds);\n\t\tif (routing) {\n\t\t\troutings.set(outcome, routing);\n\t\t\tfor (const route of Object.values(routing.routes)) {\n\t\t\t\ttransitions.push({\n\t\t\t\t\t...(route.nextTurnId ? { nextTurnId: route.nextTurnId } : {}),\n\t\t\t\t\t...(route.lifecycleStatus ? { lifecycleStatus: route.lifecycleStatus } : {}),\n\t\t\t\t\ttrigger: route.trigger,\n\t\t\t\t\toutcome,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (target) {\n\t\t\ttransitions.push({\n\t\t\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\t\t\toutcome,\n\t\t\t});\n\t\t}\n\t\teffects.set(outcome, resolveOutcomeEffect({ spec }));\n\t}\n\n\tif (input.turnEnd) {\n\t\tif (input.turnEnd.outcome.trim() === \"\") {\n\t\t\tthrow new Error(`Turn '${input.turnId}' declares an empty turnEnd outcome id`);\n\t\t}\n\t\tconst target = buildOutcomeTransition(\n\t\t\tinput.turnId,\n\t\t\tinput.turnEnd.outcome,\n\t\t\tinput.turnEnd,\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\ttransitions.push({\n\t\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\t\toutcome: input.turnEnd.outcome,\n\t\t});\n\t\teffects.set(input.turnEnd.outcome, resolveOutcomeEffect({ spec: input.turnEnd }));\n\t}\n\n\treturn {\n\t\ttransitions,\n\t\teffects,\n\t\troutings,\n\t};\n}\n\nfunction compileMappedTurnTransitions<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: LlmTurnDefinition<string, TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): readonly ProcessTurnTransition[] {\n\tconst mapped = input.spec.forEach;\n\tif (!mapped) return [];\n\tconst outcomes = Object.entries(input.spec.outcomes ?? {}) as Array<\n\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t>;\n\tif (outcomes.length === 0) {\n\t\tthrow new Error(`Mapped turn '${input.turnId}' must declare at least one outcome tool`);\n\t}\n\tif (input.spec.turnEnd) {\n\t\tthrow new Error(`Mapped turn '${input.turnId}' cannot declare a turnEnd result`);\n\t}\n\tfor (const [outcome, spec] of outcomes) {\n\t\tif (\n\t\t\t\"branches\" in spec ||\n\t\t\thasDeclaredStaticRouteTarget(spec) ||\n\t\t\tspec.effect ||\n\t\t\tspec.lifecycleIntent ||\n\t\t\tspec.publishedProduct\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Mapped turn '${input.turnId}' outcome '${outcome}' cannot route, change state, or publish; collect results instead`,\n\t\t\t);\n\t\t}\n\t\tif (!Object.hasOwn(mapped.yields, outcome)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Mapped turn '${input.turnId}' outcome '${outcome}' must declare .yield(...)`,\n\t\t\t);\n\t\t}\n\t}\n\tconst routing = mapped.routing;\n\tif (routing.kind === \"static\") {\n\t\tconst target = normalizeStaticRouteTarget(\n\t\t\t`Mapped turn '${input.turnId}' collection`,\n\t\t\t{\n\t\t\t\t...(routing.to !== undefined ? { to: routing.to } : {}),\n\t\t\t\t...(routing.lifecycleStatus !== undefined\n\t\t\t\t\t? { lifecycleStatus: routing.lifecycleStatus }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\treturn [{ ...target, trigger: mappedCollectTrigger() }];\n\t}\n\tconst branches = Object.entries(routing.branches);\n\tif (branches.length === 0) {\n\t\tthrow new Error(`Mapped turn '${input.turnId}' collection must declare at least one branch`);\n\t}\n\treturn branches.map(([branchId, to]) => {\n\t\tif (branchId.trim() === \"\") {\n\t\t\tthrow new Error(`Mapped turn '${input.turnId}' collection contains an empty branch id`);\n\t\t}\n\t\tconst target = normalizeStaticRouteTarget(\n\t\t\t`Mapped turn '${input.turnId}' collection branch '${branchId}'`,\n\t\t\t{ to },\n\t\t\tinput.knownTurnIds,\n\t\t);\n\t\treturn { ...target, trigger: mappedCollectTrigger(branchId) };\n\t});\n}\n\nfunction addActionUse<TParams, TState>(input: {\n\tactionUses: Map<string, CompiledActionUse<TParams, TState>[]>;\n\tactionId: string;\n\tuse: CompiledActionUse<TParams, TState>;\n}) {\n\tconst existing = input.actionUses.get(input.actionId) ?? [];\n\tif (existing.some((candidate) => candidate.turnId === input.use.turnId)) {\n\t\tthrow new Error(\n\t\t\t`Turn '${input.use.turnId}' declares action '${input.actionId}' more than once`,\n\t\t);\n\t}\n\texisting.push(input.use);\n\tinput.actionUses.set(input.actionId, existing);\n}\n\ntype DerivedHumanTurnAction<TParams, TState> = {\n\tactionId: string;\n\tactionSpec: ProcessHumanTurnActionSpec<TParams, TState>;\n\trouting: CompiledActionRouting<TParams, TState>;\n\ttransitions: readonly NormalizedActionRoute[];\n\tactionView: HumanTurnActionView;\n\texternalTriggers: readonly HumanTurnExternalTrigger[];\n};\n\ntype DerivedHumanTurnExternalAction<TParams, TState> = {\n\texternalActionId: string;\n\tactionSpec: ProcessHumanTurnExternalActionSpec<TParams, TState>;\n\ttransition: NormalizedActionRoute;\n\tview: HumanTurnExternalActionView;\n};\n\nfunction hasDeclaredStaticRouteTarget(target: StaticRouteTarget): boolean {\n\treturn (\n\t\ttarget.to !== undefined || target.complete === true || target.lifecycleStatus !== undefined\n\t);\n}\n\nfunction resolveExternalActionRoute<TParams, TState>(input: {\n\tturnId: TurnId;\n\texternalActionId: string;\n\tspec: ProcessHumanTurnExternalActionSpec<TParams, TState>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n}): NormalizedActionRoute {\n\tif (input.externalActionId.trim() === \"\") {\n\t\tthrow new Error(`Human turn '${input.turnId}' declares an empty external action id`);\n\t}\n\tif (input.spec.id !== input.externalActionId) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' has mismatched spec id '${input.spec.id}'`,\n\t\t);\n\t}\n\tif (input.spec.source.kind.trim() === \"\") {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' must declare a non-empty source kind`,\n\t\t);\n\t}\n\tconst target = normalizeStaticRouteTarget(\n\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}'`,\n\t\tinput.spec,\n\t\tinput.knownTurnIds,\n\t);\n\treturn {\n\t\t...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),\n\t\t...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),\n\t\ttrigger: getExternalActionTransitionTrigger({ externalActionId: input.externalActionId }),\n\t};\n}\n\nfunction validateExternalActionPublishedInputTarget<TParams, TState>(input: {\n\tturnId: TurnId;\n\texternalActionId: string;\n\tspec: ProcessHumanTurnExternalActionSpec<TParams, TState>;\n\tturnDefinitionsById?: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n}): void {\n\tconst publication = input.spec.publishInput;\n\tif (!publication || !input.turnDefinitionsById) {\n\t\treturn;\n\t}\n\tif (input.spec.to === undefined) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but does not route to a consuming turn`,\n\t\t);\n\t}\n\tconst targetTurn = input.turnDefinitionsById.get(input.spec.to);\n\tif (!targetTurn || targetTurn.kind !== \"llm\") {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' is not an LLM turn`,\n\t\t);\n\t}\n\tconst consumed = new Set([\n\t\t...(targetTurn.consumedProducts ?? []),\n\t\t...(targetTurn.optionalConsumedProducts ?? []),\n\t]);\n\tif (!consumed.has(publication.productName)) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' does not consume it`,\n\t\t);\n\t}\n}\n\nfunction validateActionPrimaryPrompt(\n\tturnId: TurnId,\n\tactionId: string,\n\taction: { form?: FormDefinition },\n): void {\n\tconst fields = action.form?.fields ?? [];\n\tconst textualFields = fields.filter(\n\t\t(field) => field.kind === \"text\" || field.kind === \"textarea\",\n\t);\n\tconst primaryPrompts = fields.filter((field) => field.primaryPrompt);\n\tif (primaryPrompts.some((field) => field.kind !== \"text\" && field.kind !== \"textarea\")) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${turnId}' action '${actionId}' primary prompt must be a text or textarea field`,\n\t\t);\n\t}\n\tif (primaryPrompts.length > 1) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${turnId}' action '${actionId}' must declare at most one primary prompt`,\n\t\t);\n\t}\n\tif (textualFields.length > 0 && primaryPrompts.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Human turn '${turnId}' action '${actionId}' with textual fields must declare a primary prompt`,\n\t\t);\n\t}\n}\n\nfunction deriveHumanTurnActions<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: HumanTurnDefinition<TParams, TState>;\n\tknownTurnIds?: ReadonlySet<TurnId>;\n\tturnDefinitionsById?: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n\trequireHumanActions?: boolean;\n}): {\n\tactions: readonly DerivedHumanTurnAction<TParams, TState>[];\n\texternalActions: readonly DerivedHumanTurnExternalAction<TParams, TState>[];\n\ttransitions: readonly ProcessTurnTransition[];\n} {\n\tconst actionEntries = Object.entries(input.spec.actions) as Array<\n\t\t[string, ProcessHumanTurnActionSpec<TParams, TState>]\n\t>;\n\tif (actionEntries.length === 0 && input.knownTurnIds && input.requireHumanActions !== false) {\n\t\tthrow new Error(`Human turn '${input.turnId}' must declare at least one action`);\n\t}\n\n\tconst derivedActions: DerivedHumanTurnAction<TParams, TState>[] = [];\n\tconst transitions: ProcessTurnTransition[] = [];\n\tconst actionIdByTrigger = new Map<string, string>();\n\tfor (const [actionId, actionSpec] of actionEntries) {\n\t\tif (actionId.trim() === \"\") {\n\t\t\tthrow new Error(`Human turn '${input.turnId}' declares an empty action id`);\n\t\t}\n\t\tvalidateActionPrimaryPrompt(input.turnId, actionId, actionSpec);\n\t\tconst resolved =\n\t\t\t!input.knownTurnIds &&\n\t\t\t!(\"branches\" in actionSpec) &&\n\t\t\t!hasDeclaredStaticRouteTarget(actionSpec)\n\t\t\t\t? {\n\t\t\t\t\t\trouting: {\n\t\t\t\t\t\t\tkind: \"static\",\n\t\t\t\t\t\t\troute: { trigger: actionSpec.trigger ?? actionId },\n\t\t\t\t\t\t} satisfies CompiledActionRouting<TParams, TState>,\n\t\t\t\t\t\ttransitions: [] as readonly NormalizedActionRoute[],\n\t\t\t\t\t}\n\t\t\t\t: resolveActionRouting({\n\t\t\t\t\t\tturnId: input.turnId,\n\t\t\t\t\t\tactionId,\n\t\t\t\t\t\tspec: actionSpec,\n\t\t\t\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t\t\t\t});\n\t\tfor (const transition of resolved.transitions) {\n\t\t\tconst existingActionId = actionIdByTrigger.get(transition.trigger);\n\t\t\tif (existingActionId && existingActionId !== actionId) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Human turn '${input.turnId}' contains duplicate action trigger '${transition.trigger}' across actions '${existingActionId}' and '${actionId}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tactionIdByTrigger.set(transition.trigger, actionId);\n\t\t\ttransitions.push({\n\t\t\t\t...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),\n\t\t\t\t...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),\n\t\t\t\ttrigger: transition.trigger,\n\t\t\t});\n\t\t}\n\t\tconst previewAndScheduling =\n\t\t\t!input.knownTurnIds && resolved.transitions.length === 0\n\t\t\t\t? {\n\t\t\t\t\t\t...(actionSpec.preview ? { preview: actionSpec.preview } : {}),\n\t\t\t\t\t\t...(actionSpec.schedulable && actionSpec.preview\n\t\t\t\t\t\t\t? { scheduling: { preview: actionSpec.preview } }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t}\n\t\t\t\t: buildActionPreviewAndScheduling(input.turnId, actionId, actionSpec, resolved.transitions);\n\t\tderivedActions.push({\n\t\t\tactionId,\n\t\t\tactionSpec,\n\t\t\trouting: resolved.routing,\n\t\t\ttransitions: resolved.transitions,\n\t\t\tactionView: {\n\t\t\t\tactionId,\n\t\t\t\tlabel: actionSpec.label,\n\t\t\t\tdescription: actionSpec.description,\n\t\t\t\tacceptanceState: actionSpec.acceptanceState,\n\t\t\t\t...previewAndScheduling,\n\t\t\t},\n\t\t\texternalTriggers:\n\t\t\t\tactionSpec.externalTriggers?.map((trigger) => ({\n\t\t\t\t\tid: trigger.id,\n\t\t\t\t\tactionId,\n\t\t\t\t\tlabel: trigger.label,\n\t\t\t\t\tdescription: trigger.description,\n\t\t\t\t})) ?? [],\n\t\t});\n\t}\n\n\tconst externalActionEntries = Object.entries(input.spec.externalActions ?? {}) as Array<\n\t\t[string, ProcessHumanTurnExternalActionSpec<TParams, TState>]\n\t>;\n\tconst derivedExternalActions: DerivedHumanTurnExternalAction<TParams, TState>[] = [];\n\tconst externalActionIds = new Set<string>();\n\tfor (const [externalActionId, actionSpec] of externalActionEntries) {\n\t\tif (externalActionIds.has(externalActionId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Human turn '${input.turnId}' declares duplicate external action '${externalActionId}'`,\n\t\t\t);\n\t\t}\n\t\texternalActionIds.add(externalActionId);\n\t\tif (actionSpec.publishInput) {\n\t\t\tassertValidProcessProductName(actionSpec.publishInput.productName);\n\t\t\tif (actionSpec.publishInput.inputField.trim() === \"\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Human turn '${input.turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tvalidateExternalActionPublishedInputTarget({\n\t\t\tturnId: input.turnId,\n\t\t\texternalActionId,\n\t\t\tspec: actionSpec,\n\t\t\tturnDefinitionsById: input.turnDefinitionsById,\n\t\t});\n\t\tconst transition = resolveExternalActionRoute({\n\t\t\tturnId: input.turnId,\n\t\t\texternalActionId,\n\t\t\tspec: actionSpec,\n\t\t\tknownTurnIds: input.knownTurnIds,\n\t\t});\n\t\tconst existingActionId = actionIdByTrigger.get(transition.trigger);\n\t\tif (existingActionId) {\n\t\t\tthrow new Error(\n\t\t\t\t`Human turn '${input.turnId}' contains duplicate trigger '${transition.trigger}' across action '${existingActionId}' and external action '${externalActionId}'`,\n\t\t\t);\n\t\t}\n\t\tactionIdByTrigger.set(transition.trigger, externalActionId);\n\t\ttransitions.push({\n\t\t\t...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),\n\t\t\t...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),\n\t\t\ttrigger: transition.trigger,\n\t\t});\n\t\tderivedExternalActions.push({\n\t\t\texternalActionId,\n\t\t\tactionSpec,\n\t\t\ttransition,\n\t\t\tview: {\n\t\t\t\tid: getExternalActionArmingId({ turnId: input.turnId, externalActionId }),\n\t\t\t\texternalActionId,\n\t\t\t\tsourceKind: actionSpec.source.kind,\n\t\t\t\tlabel: actionSpec.label ?? actionSpec.source.label ?? null,\n\t\t\t\tdescription: actionSpec.description ?? actionSpec.source.description ?? null,\n\t\t\t},\n\t\t});\n\t}\n\n\treturn {\n\t\tactions: derivedActions,\n\t\texternalActions: derivedExternalActions,\n\t\ttransitions,\n\t};\n}\n\n/** @internal */\nexport function resolveHumanTurnView<TParams, TState>(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tturn: HumanTurnDefinition<TParams, TState>;\n}): {\n\t/** @internal */\n\tactions: readonly HumanTurnActionView[];\n\t/** @internal */\n\texternalTriggers: readonly HumanTurnExternalTrigger[];\n\t/** @internal */\n\texternalActions: readonly HumanTurnExternalActionView[];\n} {\n\tconst derived = deriveHumanTurnActions({\n\t\tturnId: input.turnId,\n\t\tspec: input.turn,\n\t});\n\treturn {\n\t\tactions: derived.actions.map((action) => action.actionView),\n\t\texternalTriggers: derived.actions.flatMap((action) => action.externalTriggers),\n\t\texternalActions: derived.externalActions.map((action) => action.view),\n\t};\n}\n\nfunction compileHumanTurn<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: HumanTurnDefinition<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n\tturnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n\tactionUses: Map<string, CompiledActionUse<TParams, TState>[]>;\n}): {\n\tbinding: ProcessTurnBinding<HumanTurnDefinition<TParams, TState>>;\n} {\n\tconst derived = deriveHumanTurnActions({\n\t\tturnId: input.turnId,\n\t\tspec: input.spec,\n\t\tknownTurnIds: input.knownTurnIds,\n\t\tturnDefinitionsById: input.turnDefinitionsById,\n\t});\n\tfor (const action of derived.actions) {\n\t\taddActionUse({\n\t\t\tactionUses: input.actionUses,\n\t\t\tactionId: action.actionId,\n\t\t\tuse: {\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tlabel: action.actionSpec.label,\n\t\t\t\t...(action.actionSpec.form ? { form: action.actionSpec.form } : {}),\n\t\t\t\t...(action.actionSpec.effect ? { effect: action.actionSpec.effect } : {}),\n\t\t\t\trouting: action.routing,\n\t\t\t},\n\t\t});\n\t}\n\n\treturn {\n\t\tbinding: createProcessTurnBinding(input.spec, derived.transitions),\n\t};\n}\n\nfunction compileExternalTurn<TParams, TState>(input: {\n\tturnId: TurnId;\n\tspec: ExternalTurnDefinition<TParams, TState>;\n\tknownTurnIds: ReadonlySet<TurnId>;\n}): {\n\tbinding: ProcessTurnBinding<ExternalTurnDefinition<TParams, TState>>;\n} {\n\tconst transitions = compileExternalSourceTransitions({\n\t\tturnId: input.turnId,\n\t\tspec: input.spec,\n\t\tknownTurnIds: input.knownTurnIds,\n\t});\n\treturn {\n\t\tbinding: createProcessTurnBinding(input.spec, transitions),\n\t};\n}\n\nfunction resolveActionRouteForExecution<TParams, TState>(input: {\n\tuse: CompiledActionUse<TParams, TState>;\n\tactionId: string;\n\tctx: ServerProcessContext<TParams, TState>;\n\tinputValue: Record<string, unknown>;\n}): MaybePromise<{\n\troute: NormalizedActionRoute;\n\tselectedBranchId?: string;\n}> {\n\tif (input.use.routing.kind === \"static\") {\n\t\treturn { route: input.use.routing.route };\n\t}\n\tconst actionExecution: Omit<ProcessActionExecution<TParams, TState>, \"selectedBranchId\"> = {\n\t\tctx: makeProcessServerRuntimeContext(input.ctx),\n\t\tinput: input.inputValue,\n\t\tturnId: input.use.turnId,\n\t\tactionId: input.actionId,\n\t};\n\tconst routes = input.use.routing.routes;\n\treturn Promise.resolve(input.use.routing.choose(actionExecution)).then((selectedBranchId) => {\n\t\tif (!Object.hasOwn(routes, selectedBranchId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`,\n\t\t\t);\n\t\t}\n\t\tconst route = routes[selectedBranchId];\n\t\tif (!route) {\n\t\t\tthrow new Error(\n\t\t\t\t`Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`,\n\t\t\t);\n\t\t}\n\t\treturn { route, selectedBranchId };\n\t});\n}\n\nfunction buildActionTransitionRequest<TState>(route: NormalizedActionRoute) {\n\tif (route.nextTurnId !== undefined) {\n\t\treturn {\n\t\t\tturnId: route.nextTurnId,\n\t\t\ttrigger: route.trigger,\n\t\t} satisfies Omit<ServerTransitionRequest<TState>, \"state\">;\n\t}\n\treturn {\n\t\tturnId: null,\n\t\tlifecycleStatus: route.lifecycleStatus,\n\t\ttrigger: route.trigger,\n\t} satisfies Omit<ServerTransitionRequest<TState>, \"state\">;\n}\n\nfunction validateHappyPathConnectivity<TParams, TState>(input: {\n\tprocessId: string;\n\thappyPath: readonly TurnId[] | undefined;\n\tturns: ReadonlyMap<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>;\n\tturnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;\n}): void {\n\tconst happyPath = input.happyPath;\n\tif (!happyPath || happyPath.length < 2) {\n\t\treturn;\n\t}\n\tconst happyPathTurns = new Set<TurnId>(happyPath);\n\tfor (let index = 0; index < happyPath.length - 1; index += 1) {\n\t\tconst source = happyPath[index];\n\t\tconst target = happyPath[index + 1];\n\t\tlet connected = false;\n\t\tconst visited = new Set<TurnId>([source]);\n\t\tconst queue: TurnId[] = [source];\n\t\twhile (queue.length > 0 && !connected) {\n\t\t\tconst current = queue.shift() as TurnId;\n\t\t\tfor (const transition of getProcessTurnTransitions(input.turns.get(current))) {\n\t\t\t\tconst next = transition.nextTurnId;\n\t\t\t\tif (next === undefined || !input.turnDefinitionsById.has(next)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (next === target) {\n\t\t\t\t\tconnected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (visited.has(next) || happyPathTurns.has(next)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst definition = input.turnDefinitionsById.get(next);\n\t\t\t\tif (definition?.kind !== \"human\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvisited.add(next);\n\t\t\t\tqueue.push(next);\n\t\t\t}\n\t\t}\n\t\tif (!connected) {\n\t\t\tthrow new Error(\n\t\t\t\t`Process '${input.processId}' happy path segment '${source}' -> '${target}' is not connected by declared transitions`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction buildDefinedProcess<TParams, TState>(\n\tinput: DefinedProcessInput<TParams, TState>,\n): Pick<ExtensionProcessDefinition<TParams, TState>, \"turns\" | \"worker\" | \"server\"> {\n\tconst turnEntries = Object.entries(input.turns);\n\tif (turnEntries.length === 0) {\n\t\tthrow new Error(`Process '${input.id}' must declare at least one turn`);\n\t}\n\tconst knownTurnIds = new Set(turnEntries.map(([turnId]) => turnId));\n\tconst turnDefinitionsById = new Map<TurnId, TurnDefinition<unknown, unknown>>(\n\t\tturnEntries.map(([turnId, turnSpec]) => [turnId, turnSpec as TurnDefinition<unknown, unknown>]),\n\t);\n\tif (!knownTurnIds.has(input.entry)) {\n\t\tthrow new Error(`Process '${input.id}' entry turn '${input.entry}' is not declared`);\n\t}\n\tconst seenEntries = new Set<TurnId>();\n\tfor (const turnId of [input.entry, ...(input.alternateEntries ?? [])]) {\n\t\tif (seenEntries.has(turnId)) {\n\t\t\tthrow new Error(`Process '${input.id}' declares duplicate entry turn '${turnId}'`);\n\t\t}\n\t\tif (!knownTurnIds.has(turnId)) {\n\t\t\tthrow new Error(`Process '${input.id}' entry turn '${turnId}' is not declared`);\n\t\t}\n\t\tseenEntries.add(turnId);\n\t}\n\n\tif (input.happyPath) {\n\t\tif (input.happyPath.length === 0) {\n\t\t\tthrow new Error(`Process '${input.id}' declares an empty happy path`);\n\t\t}\n\t\tconst seen = new Set<TurnId>();\n\t\tfor (const turnId of input.happyPath) {\n\t\t\tif (!knownTurnIds.has(turnId)) {\n\t\t\t\tthrow new Error(`Process '${input.id}' happy path references undeclared turn '${turnId}'`);\n\t\t\t}\n\t\t\tif (seen.has(turnId)) {\n\t\t\t\tthrow new Error(`Process '${input.id}' happy path repeats turn '${turnId}'`);\n\t\t\t}\n\t\t\tseen.add(turnId);\n\t\t}\n\t\tif (input.happyPath[0] !== input.entry) {\n\t\t\tthrow new Error(\n\t\t\t\t`Process '${input.id}' happy path must start at the entry turn '${input.entry}'`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst turns = new Map<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>();\n\tconst actionUses = new Map<string, CompiledActionUse<TParams, TState>[]>();\n\tconst executableTurns = new Map<\n\t\tTurnId,\n\t\tCompiledOutcomeHandlers<TParams, TState> & {\n\t\t\tspec: RoutableTurnDefinition<string, TParams, TState>;\n\t\t}\n\t>();\n\n\tfor (const [turnId, turnSpec] of turnEntries) {\n\t\tif (turnSpec.kind === \"llm\" && turnSpec.forEach) {\n\t\t\tturns.set(\n\t\t\t\tturnId,\n\t\t\t\tcreateProcessTurnBinding(\n\t\t\t\t\tturnSpec,\n\t\t\t\t\tcompileMappedTurnTransitions({ turnId, spec: turnSpec, knownTurnIds }),\n\t\t\t\t),\n\t\t\t);\n\t\t\texecutableTurns.set(turnId, {\n\t\t\t\tspec: turnSpec,\n\t\t\t\teffects: new Map(),\n\t\t\t\troutings: new Map(),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (turnSpec.kind === \"llm\" || turnSpec.kind === \"automatic\") {\n\t\t\tconst { transitions, effects, routings } = compileTurnOutcomeDefinitions({\n\t\t\t\tturnId,\n\t\t\t\toutcomes: turnSpec.outcomes,\n\t\t\t\tturnEnd: turnSpec.turnEnd,\n\t\t\t\tknownTurnIds,\n\t\t\t});\n\t\t\tconst externalTransitions =\n\t\t\t\tturnSpec.kind === \"automatic\" && turnSpec.externalActions\n\t\t\t\t\t? deriveHumanTurnActions({\n\t\t\t\t\t\t\tturnId,\n\t\t\t\t\t\t\tspec: {\n\t\t\t\t\t\t\t\tkind: \"human\",\n\t\t\t\t\t\t\t\tdescription: turnSpec.description,\n\t\t\t\t\t\t\t\tactions: {},\n\t\t\t\t\t\t\t\texternalActions: turnSpec.externalActions,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tknownTurnIds,\n\t\t\t\t\t\t\tturnDefinitionsById,\n\t\t\t\t\t\t\trequireHumanActions: false,\n\t\t\t\t\t\t}).transitions\n\t\t\t\t\t: [];\n\t\t\tturns.set(\n\t\t\t\tturnId,\n\t\t\t\tcreateProcessTurnBinding(turnSpec, [...transitions, ...externalTransitions]),\n\t\t\t);\n\t\t\texecutableTurns.set(turnId, { spec: turnSpec, effects, routings });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (turnSpec.kind === \"human\") {\n\t\t\tconst compiled = compileHumanTurn({\n\t\t\t\tturnId,\n\t\t\t\tspec: turnSpec,\n\t\t\t\tknownTurnIds,\n\t\t\t\tturnDefinitionsById,\n\t\t\t\tactionUses,\n\t\t\t});\n\t\t\tturns.set(turnId, compiled.binding);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst compiled = compileExternalTurn({\n\t\t\tturnId,\n\t\t\tspec: turnSpec,\n\t\t\tknownTurnIds,\n\t\t});\n\t\tturns.set(turnId, compiled.binding);\n\t}\n\n\tvalidateHappyPathConnectivity({\n\t\tprocessId: input.id,\n\t\thappyPath: input.happyPath,\n\t\tturns,\n\t\tturnDefinitionsById,\n\t});\n\n\tconst worker: ExtensionProcessDefinition<TParams, TState>[\"worker\"] = (api) => {\n\t\tapi.start(input.entry);\n\t\tconst manuallyRegisteredTurns = new Set<TurnId>();\n\t\tinput.worker?.({\n\t\t\tstart(turnId) {\n\t\t\t\tapi.start(turnId);\n\t\t\t},\n\t\t\tturn(turnId, handler) {\n\t\t\t\tmanuallyRegisteredTurns.add(turnId);\n\t\t\t\tapi.turn(turnId, handler);\n\t\t\t},\n\t\t});\n\t\tfor (const [turnId, { spec }] of executableTurns) {\n\t\t\tif (manuallyRegisteredTurns.has(turnId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (spec.kind === \"llm\") {\n\t\t\t\tapi.turn(turnId, async (run) => {\n\t\t\t\t\tawait run.turn(spec);\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tapi.turn(turnId, async (run) => {\n\t\t\t\tawait run.complete(await spec.run(run.ctx));\n\t\t\t});\n\t\t}\n\t};\n\n\tconst server: ExtensionProcessDefinition<TParams, TState>[\"server\"] = (api) => {\n\t\tfor (const [actionId, uses] of actionUses) {\n\t\t\tconst [firstUse] = uses;\n\t\t\tconst form = firstUse?.form;\n\t\t\tfor (const use of uses) {\n\t\t\t\tif (!areFormsEquivalent(form, use.form)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Action '${actionId}' must use the same form on every turn that references it`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tapi.action({\n\t\t\t\tid: actionId,\n\t\t\t\tlabel: firstUse?.label ?? actionId,\n\t\t\t\t...(form ? { form } : {}),\n\t\t\t\tasync plan(inputValue, ctx) {\n\t\t\t\t\tconst turnId = ctx.process.selectedTurnId;\n\t\t\t\t\tconst use = uses.find((candidate) => candidate.turnId === turnId);\n\t\t\t\t\tif (!use || !turnId) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Action '${actionId}' is not available for selected turn '${String(turnId)}'`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst resolvedRoute = await resolveActionRouteForExecution({\n\t\t\t\t\t\tuse,\n\t\t\t\t\t\tactionId,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tinputValue,\n\t\t\t\t\t});\n\t\t\t\t\tconst effectResult = use.effect\n\t\t\t\t\t\t? await use.effect({\n\t\t\t\t\t\t\t\tctx: makeProcessServerRuntimeContext(ctx),\n\t\t\t\t\t\t\t\tinput: inputValue,\n\t\t\t\t\t\t\t\tturnId,\n\t\t\t\t\t\t\t\tactionId,\n\t\t\t\t\t\t\t\t...(resolvedRoute.selectedBranchId\n\t\t\t\t\t\t\t\t\t? { selectedBranchId: resolvedRoute.selectedBranchId }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst formState = applyFormStateFields({\n\t\t\t\t\t\tform: use.form,\n\t\t\t\t\t\tinputValue,\n\t\t\t\t\t\tstate: effectResult?.state ?? ctx.state,\n\t\t\t\t\t});\n\t\t\t\t\tconst result = formState\n\t\t\t\t\t\t? mergeProcessEffectPlans(effectResult, { state: formState })\n\t\t\t\t\t\t: effectResult;\n\t\t\t\t\tawait applyProcessEffectPlan({\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\ttransition: buildActionTransitionRequest(resolvedRoute.route),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tfor (const [turnId, { effects, routings }] of executableTurns) {\n\t\t\tapi.onTurnOutcome(turnId, async (event, ctx) => {\n\t\t\t\tconst effect = effects.get(event.outcome);\n\t\t\t\tconst routing = routings.get(event.outcome);\n\t\t\t\tif (!effect && !routing) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst execution = {\n\t\t\t\t\tctx: makeProcessServerRuntimeContext(ctx),\n\t\t\t\t\tevent,\n\t\t\t\t\tturnId,\n\t\t\t\t\toutcome: event.outcome,\n\t\t\t\t};\n\t\t\t\tconst result = effect ? await effect(execution) : undefined;\n\t\t\t\tlet transition: Omit<ServerTransitionRequest<TState>, \"state\"> | undefined;\n\t\t\t\tif (routing) {\n\t\t\t\t\tconst branchId = await routing.choose(execution);\n\t\t\t\t\tconst route = routing.routes[branchId];\n\t\t\t\t\tif (!route) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Turn '${turnId}' outcome '${event.outcome}' selected unknown branch '${branchId}'`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\ttransition = buildActionTransitionRequest(route);\n\t\t\t\t}\n\t\t\t\tawait applyProcessEffectPlan({ ctx, result, transition });\n\t\t\t});\n\t\t}\n\n\t\tinput.server?.(api);\n\t};\n\n\treturn {\n\t\tturns,\n\t\tworker,\n\t\tserver,\n\t};\n}\n\n/** @public */\nexport function defineProcess<TParams = unknown, TState = unknown>(\n\tinput: DefinedProcessInput<TParams, TState>,\n): ExtensionProcessDefinition<TParams, TState> {\n\tconst compiled = buildDefinedProcess(input);\n\tconst process = {\n\t\tid: input.id,\n\t\tdisplayName: input.displayName,\n\t\tentryTurnId: input.entry,\n\t\talternateEntryTurnIds: [...(input.alternateEntries ?? [])],\n\t\t...(input.happyPath ? { happyPath: [...input.happyPath] } : {}),\n\t\tturns: compiled.turns,\n\t\tparamsCodec: input.paramsCodec,\n\t\tstateCodec: input.stateCodec,\n\t\tinitialState: input.initialState,\n\t\t...(input.runtime ? { runtime: { ...input.runtime } } : {}),\n\t\t...(input.resolveStorageSize ? { resolveStorageSize: input.resolveStorageSize } : {}),\n\t\t...(input.repositoryCredentials ? { repositoryCredentials: input.repositoryCredentials } : {}),\n\t\t...(input.piConfig ? { piConfig: input.piConfig } : {}),\n\t\tserver: compiled.server,\n\t\tworker: compiled.worker,\n\t\tui: input.ui,\n\t\tlaunchers: input.launchers,\n\t\twatchers: input.watchers,\n\t};\n\tmarkDefinedProcess(process);\n\treturn process;\n}\n\n/** @internal */\ntype RoutableTurnDefinition<TOutcome extends string, TParams, TState> =\n\t| LlmTurnDefinition<TOutcome, TParams, TState>\n\t| AutomaticTurnDefinition<TOutcome, TParams, TState>;\n\n// biome-ignore-start lint/suspicious/noExplicitAny: conditional helper types must match and preserve any routable turn instantiation\n/** @internal */\ntype RoutableOutcome<TTurn> =\n\tTTurn extends RoutableTurnDefinition<infer TOutcome, any, any> ? TOutcome : never;\n/** @internal */\ntype RoutableParams<TTurn> =\n\tTTurn extends RoutableTurnDefinition<any, infer TParams, any> ? TParams : never;\n/** @internal */\ntype RoutableState<TTurn> =\n\tTTurn extends RoutableTurnDefinition<any, any, infer TState> ? TState : never;\n\n/** @internal */\nexport function routeTurnOutcomes<TTurn extends RoutableTurnDefinition<string, any, any>>(\n\tbaseTurn: TTurn,\n\troutes: Partial<\n\t\tRecord<RoutableOutcome<TTurn>, OutcomeRouteSpec<RoutableParams<TTurn>, RoutableState<TTurn>>>\n\t>,\n\toptions: OutcomeRouteOptions = {},\n): TTurn {\n\ttype TOutcome = RoutableOutcome<TTurn>;\n\ttype TParams = RoutableParams<TTurn>;\n\ttype TState = RoutableState<TTurn>;\n\tconst baseOutcomes = (baseTurn.outcomes ?? {}) as Partial<\n\t\tRecord<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>\n\t>;\n\tfor (const outcomeId of Object.keys(routes) as TOutcome[]) {\n\t\tif (!baseOutcomes[outcomeId]) {\n\t\t\tthrow new Error(`Cannot route unknown outcome '${outcomeId}' on reusable turn`);\n\t\t}\n\t}\n\tif (options.strict) {\n\t\tfor (const outcomeId of Object.keys(baseOutcomes) as TOutcome[]) {\n\t\t\tif (!routes[outcomeId]) {\n\t\t\t\tthrow new Error(`Strict routing omitted outcome '${outcomeId}' on reusable turn`);\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\t...baseTurn,\n\t\toutcomes: Object.fromEntries(\n\t\t\t(\n\t\t\t\tObject.entries(baseOutcomes) as Array<[TOutcome, ProcessToolOutcomeSpec<TParams, TState>]>\n\t\t\t).map(([outcomeId, baseOutcome]) => [\n\t\t\t\toutcomeId,\n\t\t\t\t{ ...baseOutcome, ...(routes[outcomeId] ?? {}) },\n\t\t\t]),\n\t\t) as Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>,\n\t};\n}\n// biome-ignore-end lint/suspicious/noExplicitAny: end routable turn instantiation helper suppression\n\n/** @public */\nexport function llmTurn<TParams = unknown, TState = unknown, TOutcome extends string = string>(\n\tinput: Omit<LlmTurnDefinition<TOutcome, TParams, TState>, \"kind\">,\n): LlmTurnDefinition<TOutcome, TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"llm\",\n\t};\n}\n\n/** @internal */\nexport function automaticTurn<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n>(\n\tinput: Omit<AutomaticTurnDefinition<TOutcome, TParams, TState>, \"kind\">,\n): AutomaticTurnDefinition<TOutcome, TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"automatic\",\n\t};\n}\n\n/** @public */\nexport function humanTurn<TParams = unknown, TState = unknown>(\n\tinput: Omit<HumanTurnDefinition<TParams, TState>, \"kind\">,\n): HumanTurnDefinition<TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"human\",\n\t};\n}\n\n/** @internal */\nexport function externalTurn<TParams = unknown, TState = unknown>(\n\tinput: Omit<ExternalTurnDefinition<TParams, TState>, \"kind\">,\n): ExternalTurnDefinition<TParams, TState> {\n\treturn {\n\t\t...input,\n\t\tkind: \"external\",\n\t};\n}\n","import type {\n\tActor,\n\tInputKind,\n\tInputSource,\n\tLaunchModelConfigInput,\n\tProcessCustomizableFields,\n\tProcessInputTarget,\n\tProcessInstance,\n\tProcessLifecycleStatus,\n\tProcessProject,\n\tProcessSemanticEntryRefKey,\n\tProcessTurnRecord,\n\tTurnId,\n\tTurnProgressReport,\n} from \"@leitwerk-dev/domain\";\nimport type { ExternalWrites } from \"@leitwerk-dev/external-writes\";\nimport type { WatcherPresentationField } from \"@leitwerk-dev/protocol\";\nimport type { CapabilityToken } from \"./capabilities.js\";\nimport type { FormDefinition } from \"./form-contract.js\";\n\nexport type { FormDefinition, FormFieldDefinition } from \"./form-contract.js\";\n\nimport type {\n\tLlmTurnDefinition,\n\tProcessEffectPlan,\n\tProcessLifecycleEffects,\n\tTurnDefinition,\n} from \"./define-process.js\";\nimport type {\n\tLauncherCardMetadata,\n\tLauncherFieldOptionDefinition,\n\tLauncherSchemaDefinition,\n\tLauncherValidationError,\n\tUiLauncherSummaryBase,\n} from \"./launcher-contract.js\";\nimport type { MappedTurnIteration } from \"./mapped-turn.js\";\nimport type { ModelProviderSet } from \"./model-provider.js\";\nimport type {\n\tServerExtensionEventMap,\n\tServerExtensionEventPayloadInputMap,\n} from \"./server-events.js\";\nimport type { ToolCallRendererDefinition } from \"./tool-renderers.js\";\nimport type {\n\tEventBus,\n\tPiTreeEntry,\n\tProcessActionPreviewDefinition,\n\tProcessActionSchedulingDefinition,\n\tProcessPiConfig,\n\tTurnOptions,\n} from \"./types.js\";\n\n/** @public */\nexport interface Codec<T> {\n\t/** @public */\n\tparse(value: unknown): T;\n\t/** @public */\n\tserialize(value: T): unknown;\n}\n\n/** @internal */\nexport interface LauncherModelProfileSummary {\n\t/** @internal */\n\treadonly id: string;\n\t/** @internal */\n\treadonly provider: string;\n\t/** @internal */\n\treadonly modelId: string;\n\t/** @internal */\n\treadonly thinkingLevel: string;\n}\n\n/** @public */\nexport interface LauncherContext {\n\t/** @internal */\n\treadonly process?: ProcessInstance;\n\t/** @internal */\n\treadonly projects?: readonly ProcessProject[];\n\t/**\n\t * Effective model profiles available to this launch path.\n\t * The server may filter this list per process (for example via process allowlists)\n\t * before invoking UI launcher or process watcher code.\n\t */\n\t/** @internal */\n\treadonly modelProfiles?: readonly LauncherModelProfileSummary[];\n}\n\n/** @public */\nexport type LauncherVisibility = \"ui\";\n\n/** @public */\nexport interface ProcessLaunchProjectConfig {\n\t/** @public */\n\tkey: string;\n\t/** @public */\n\trepoLocator: string;\n\t/** @public */\n\tbaseBranch: string;\n\t/** @public */\n\tworkBranch?: string | null;\n\t/** @public */\n\texternalId?: string | null;\n\t/** @public */\n\texternalUrl?: string | null;\n\t/** @public */\n\tmetadata?: Record<string, unknown> | null;\n}\n\n/** @public */\nexport interface ProcessTitleSourceField {\n\t/** Short label shown to the title-generation model, e.g. \"Prompt\" or \"Summary\". @public */\n\tlabel: string;\n\t/** Launcher-selected descriptive text to summarize into a short operator-facing title. @public */\n\tvalue: string;\n}\n\n/** @public */\nexport interface ProcessLaunchConfig<TParams = unknown> {\n\t/** @public */\n\tprocessId: string;\n\t/** @public */\n\tparams: TParams;\n\t/** @public */\n\tstartTurnId?: TurnId | null;\n\t/** Explicit operator-facing title. UI launches may override this with the built-in title input before persistence. @public */\n\ttitle?: string | null;\n\t/** Explicit launcher-selected fields for optional server-side title generation when title is blank. @public */\n\ttitleSourceFields?: readonly ProcessTitleSourceField[];\n\t/** @public */\n\texternalId?: string | null;\n\t/** @public */\n\texternalUrl?: string | null;\n\t/** @public */\n\tmetadata?: Record<string, unknown> | null;\n\t/** @internal */\n\tdefaultModelProfileId?: string | null;\n\t/** @internal */\n\tturnConfigs?: Record<\n\t\tstring,\n\t\t{\n\t\t\t/** @internal */\n\t\t\tmodelProfileId?: string | null;\n\t\t}\n\t>;\n\t/** Skill ids resolved to active immutable revisions before process creation. @internal */\n\tskillIds?: readonly string[];\n\t/** @public */\n\tprojects?: readonly ProcessLaunchProjectConfig[];\n}\n\n/** @public */\nexport type UiLauncherConfigResolution<TParams = unknown> =\n\t| {\n\t\t\t/** @public */\n\t\t\tok: true;\n\t\t\t/** @public */\n\t\t\tlaunchConfig: ProcessLaunchConfig<TParams>;\n\t }\n\t| {\n\t\t\t/** @public */\n\t\t\tok: false;\n\t\t\t/** @public */\n\t\t\terrors: readonly LauncherValidationError[];\n\t };\n\n/** @public */\nexport interface LaunchPreparationContext<TParams = unknown> {\n\t/** @public */\n\treadonly signal: AbortSignal;\n\t/** @public */\n\treadonly launchConfig: ProcessLaunchConfig<TParams>;\n\t/** @public */\n\treadonly logger: {\n\t\t/** @internal */\n\t\tinfo(message: string): void;\n\t\t/** @public */\n\t\twarn(message: string): void;\n\t};\n}\n\n/** @public */\nexport interface LaunchPreparationCheck<TParams = unknown> {\n\t/** @public */\n\treadonly id: string;\n\t/** @public */\n\treadonly label: string;\n\t/** @public */\n\trun(ctx: LaunchPreparationContext<TParams>): Promise<void>;\n}\n\n/** A launcher check may throw this error to expose bounded operator-safe remediation. @public */\nexport class SafeLaunchPreparationError extends Error {\n\t/** @public */\n\tconstructor(\n\t\tmessage: string,\n\t\t/** @internal */\n\t\treadonly safeSummary: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"SafeLaunchPreparationError\";\n\t}\n}\n\n/** @public */\nexport interface UiLauncherDefinition<TParams = unknown> {\n\t/** @public */\n\tcard: LauncherCardMetadata;\n\t/** @public */\n\tlaunchConfigSchema: LauncherSchemaDefinition;\n\t/** @public */\n\tresolveDefaults?(\n\t\tctx: LauncherContext,\n\t): Record<string, unknown> | Promise<Record<string, unknown>>;\n\t/** @public */\n\tresolveOptions?(\n\t\tinput: Record<string, unknown>,\n\t\tctx: LauncherContext,\n\t):\n\t\t| Record<string, readonly LauncherFieldOptionDefinition[]>\n\t\t| Promise<Record<string, readonly LauncherFieldOptionDefinition[]>>;\n\t/**\n\t * Convert persisted operator input into a new-launch draft. The default preserves\n\t * the complete input. Launchers override this only for values that must be rebuilt.\n\t */\n\t/** @public */\n\tresolveRelaunchInput?(\n\t\tpreviousInput: Record<string, unknown>,\n\t\tctx: LauncherContext,\n\t): Record<string, unknown> | Promise<Record<string, unknown>>;\n\t/** @public */\n\tpreparationChecks?(\n\t\tinput: Record<string, unknown>,\n\t\tlaunchConfig: ProcessLaunchConfig<TParams>,\n\t): readonly LaunchPreparationCheck<TParams>[];\n\t/** @public */\n\tresolveLaunchConfig(\n\t\tinput: Record<string, unknown>,\n\t\tctx: LauncherContext,\n\t): UiLauncherConfigResolution<TParams> | Promise<UiLauncherConfigResolution<TParams>>;\n}\n\n/** @public */\nexport interface ProcessWatcherPresentation {\n\t/** @public */\n\treadonly targetSummary: string;\n\t/** @public */\n\treadonly details?: readonly WatcherPresentationField[];\n}\n\n/** @public */\nexport interface ParsedProcessWatcherConfig<TConfig = unknown> {\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly enabled: boolean;\n\t/** @public */\n\treadonly launchModelConfig?: LaunchModelConfigInput;\n}\n\n/** A watcher source is defined and owned by the extension that implements it. @public */\nexport interface ProcessWatcherSource<TConfig = unknown, TEvent = unknown> {\n\t/** @public */\n\treadonly id: string;\n\t/** @public */\n\treadonly label: string;\n\t/** Type-only marker used to carry the provider event type across the source seam. @internal */\n\treadonly eventType?: TEvent;\n\t/** @public */\n\tparseConfig(raw: unknown): ParsedProcessWatcherConfig<TConfig>;\n\t/** @public */\n\tpresentConfig(config: TConfig): ProcessWatcherPresentation;\n}\n\n/** @public */\nexport interface ProcessWatcherDefinition<TParams = unknown, TEvent = unknown, TConfig = unknown> {\n\t/** @public */\n\tid: string;\n\t/** @public */\n\tlabel: string;\n\t/** @public */\n\tdescription: string;\n\t/** @public */\n\tsource: ProcessWatcherSource<TConfig, TEvent>;\n\t/** @internal */\n\tmatches?(event: TEvent, ctx: LauncherContext): boolean | Promise<boolean>;\n\t/** @public */\n\tpreparationChecks?(\n\t\tevent: TEvent,\n\t\tlaunchConfig: ProcessLaunchConfig<TParams>,\n\t): readonly LaunchPreparationCheck<TParams>[];\n\t/** @public */\n\tresolveLaunchConfig(\n\t\tevent: TEvent,\n\t\tctx: LauncherContext,\n\t): ProcessLaunchConfig<TParams> | Promise<ProcessLaunchConfig<TParams>>;\n}\n\n/** @public */\nexport interface ProcessLauncherDefinition<TParams = unknown> {\n\t/** @public */\n\tid: string;\n\t/** @public */\n\tlabel: string;\n\t/** @public */\n\tdescription: string;\n\t/** @public */\n\tvisibility: LauncherVisibility;\n\t/** @public */\n\tui: UiLauncherDefinition<TParams>;\n}\n\n/** @internal */\nexport interface ProcessLaunchPlanProcessInput extends ProcessCustomizableFields {\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tselectedTurnId: string | null;\n\t/** @internal */\n\tlifecycleStatus: ProcessLifecycleStatus;\n\t/** @internal */\n\tparamsJson: string | null;\n\t/** @internal */\n\tstateJson: string | null;\n}\n\n/** @internal */\nexport interface ProcessLaunchPlan {\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tprocessInput: ProcessLaunchPlanProcessInput;\n\t/** Optional server-owned idempotency key for cross-process handoffs. @internal */\n\thandoffDedupKey?: string | null;\n\t/** Carry-forward launcher-selected fields for optional server-side title generation. @internal */\n\ttitleSourceFields?: readonly ProcessTitleSourceField[];\n\t/** @internal */\n\tprojectInputs: readonly ProcessLaunchProjectConfig[];\n\t/** @internal */\n\tstartTurnId: TurnId | null;\n\t/** @internal */\n\tskillIds?: readonly string[];\n}\n\n/** @internal */\nexport interface ResolvedProcessLauncher<TParams = unknown> {\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tdisplayName: string;\n\t/** @internal */\n\tlaunchConfig: ProcessLaunchConfig<TParams>;\n\t/** @internal */\n\tlaunchPlan: ProcessLaunchPlan;\n}\n\n/** @internal */\nexport type UiLauncherResolutionResult<TParams = unknown> =\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: true;\n\t\t\t/** @internal */\n\t\t\tlauncher: ResolvedProcessLauncher<TParams>;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: false;\n\t\t\t/** @internal */\n\t\t\terrors: readonly LauncherValidationError[];\n\t };\n\n/** @internal */\nexport interface UiLauncherSummary extends UiLauncherSummaryBase {}\n\n/** @internal */\nexport interface ProcessLauncherService {\n\t/** @internal */\n\tlistUiLaunchers(): readonly UiLauncherSummary[];\n\t/** @internal */\n\tresolveUiDefaults(launcherId: string, ctx?: LauncherContext): Promise<Record<string, unknown>>;\n\t/** @internal */\n\tresolveUiOptions(\n\t\tlauncherId: string,\n\t\tinput: Record<string, unknown>,\n\t\tctx?: LauncherContext,\n\t): Promise<Record<string, readonly LauncherFieldOptionDefinition[]>>;\n\t/** @internal */\n\tresolveUiRelaunchInput(\n\t\tlauncherId: string,\n\t\tpreviousInput: Record<string, unknown>,\n\t\tctx?: LauncherContext,\n\t): Promise<Record<string, unknown>>;\n\t/** @internal */\n\tresolvePreparationChecks?(\n\t\tlauncherId: string,\n\t\tinput: Record<string, unknown>,\n\t\tlaunchConfig: ProcessLaunchConfig,\n\t): readonly LaunchPreparationCheck[];\n\t/** @internal */\n\tresolveUiLauncher(\n\t\tlauncherId: string,\n\t\tinput: Record<string, unknown>,\n\t\tctx?: LauncherContext,\n\t): Promise<UiLauncherResolutionResult>;\n}\n\n/** Resolve a UI launcher summary by id, returning `null` when it is unknown. @internal */\nexport function findUiLauncherById(\n\tlauncherService: Pick<ProcessLauncherService, \"listUiLaunchers\">,\n\tlauncherId: string,\n): UiLauncherSummary | null {\n\treturn launcherService.listUiLaunchers().find((launcher) => launcher.id === launcherId) ?? null;\n}\n\n/** @public */\nexport interface ProcessTurnOutcomeEvent {\n\t/** @internal */\n\tturnRecordId: string;\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\toutcome: string;\n\t/** @public */\n\tparams: Record<string, unknown>;\n\t/** @internal */\n\tturnResultMarkdown?: string | null;\n\t/** Durable output produced by this turn's preparation phase. @public */\n\tprepared?: unknown;\n}\n\n/** Expected outcome-planning rejection safe to persist and show to operators. @public */\nexport class SafeOutcomePlanningError extends Error {\n\t/** @public */\n\tconstructor(\n\t\t/** Stable machine-readable failure code. @public */\n\t\treadonly code: string,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"SafeOutcomePlanningError\";\n\t}\n}\n\n/** @internal */\nexport type ProcessCleanupReason = \"abort\";\n\n/** @internal */\nexport interface ProcessCleanupResult<TState = unknown> extends ProcessLifecycleEffects {\n\t/** @internal */\n\tstate?: TState;\n}\n\n/** @internal */\nexport interface ProcessCleanupContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\treadonly reason: ProcessCleanupReason;\n}\n\n/** @internal */\nexport type ProcessCleanupHandler<TParams = unknown, TState = unknown> = (\n\tctx: ProcessCleanupContext<TParams, TState>,\n) => undefined | ProcessCleanupResult<TState> | Promise<ProcessCleanupResult<TState> | undefined>;\n\n/** @internal */\nexport interface LeafOutcomeCaptureContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\treadonly leaf: {\n\t\t/** @internal */\n\t\tentryId: string;\n\t\t/** @internal */\n\t\tturnRecordId: string | null;\n\t};\n\t/** @internal */\n\treadonly turnRecord: ProcessTurnRecord | null;\n\t/** @internal */\n\treadTreeEntry(entryId: string): PiTreeEntry | null;\n\t/** @internal */\n\treadLeafEntry(): PiTreeEntry | null;\n\t/** @internal */\n\treadTurnRecord(turnRecordId: string): ProcessTurnRecord | null;\n}\n\n/** @internal */\nexport interface LeafOutcomeCaptureResult {\n\t/** @internal */\n\trendererId: string;\n\t/** @internal */\n\tschemaVersion?: number;\n\t/** @internal */\n\tprops: Record<string, unknown>;\n\t/** @internal */\n\tfallbackMarkdown?: string | null;\n}\n\n/** @internal */\nexport interface ProcessLeafOutcomeDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\trendererId: string;\n\t/** @internal */\n\tcapture(\n\t\tctx: LeafOutcomeCaptureContext<TParams, TState>,\n\t): Promise<LeafOutcomeCaptureResult | null> | LeafOutcomeCaptureResult | null;\n}\n\n/** @internal */\nexport interface ProcessActionDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tform?: FormDefinition;\n\t/** @internal */\n\tpreview?: ProcessActionPreviewDefinition;\n\t/** @internal */\n\tscheduling?: ProcessActionSchedulingDefinition;\n\t/**\n\t * Explicitly marks an action as an immediate-only side-effect command. Such\n\t * actions must declare execute(...), cannot participate in pure preview or\n\t * scheduling flows, and are run only by immediate action execution.\n\t */\n\t/** @internal */\n\texecutionMode?: \"side_effect\";\n\t/**\n\t * Optional pure planner used for side-effect-free previews, scheduling validation,\n\t * and immediate execution. The shared server runtime collects the declared\n\t * transition/input/event plan from this hook without committing side effects\n\t * while the hook runs.\n\t */\n\t/** @internal */\n\tplan?(input: Record<string, unknown>, ctx: ServerProcessContext<TParams, TState>): Promise<void>;\n\t/**\n\t * Imperative hook for actions with executionMode: \"side_effect\". Use only for\n\t * immediate side effects that cannot be represented as a pure plan(...).\n\t */\n\t/** @internal */\n\texecute?(\n\t\tinput: Record<string, unknown>,\n\t\tctx: ServerProcessContext<TParams, TState>,\n\t): Promise<void>;\n}\n\n/** @internal */\nexport type ServerTransitionRuntime = \"reconcile\" | \"restart_worker\";\n\n/** @internal */\nexport interface ServerTransitionEffect {\n\t/**\n\t * Declares how the server runtime should handle the worker context after the\n\t * durable transition is committed.\n\t */\n\t/** @internal */\n\truntime?: ServerTransitionRuntime;\n}\n\n/** @internal */\nexport interface ServerTransitionRequest<TState = unknown> {\n\t/** @internal */\n\tlifecycleStatus?: ProcessLifecycleStatus;\n\t/** @internal */\n\tturnId?: TurnId | null;\n\t/** @internal */\n\tstate?: TState;\n\t/** State machine trigger for the selected-turn graph. @internal */\n\ttrigger?: string;\n\t/** @internal */\n\teffect?: ServerTransitionEffect;\n}\n\n/** @public */\nexport interface ProcessSnapshotContext<TParams = unknown, TState = unknown> {\n\t/** @public */\n\treadonly process: ProcessInstance;\n\t/** @public */\n\treadonly projects: readonly ProcessProject[];\n\t/** @public */\n\treadonly params: TParams;\n\t/** @public */\n\treadonly state: TState;\n}\n\n/** @public */\nexport type ExternalSourceInputMode = \"none\" | \"input\" | \"instruction\";\n\n/** @public */\nexport interface ExternalSourceResolveContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {}\n\n/** @public */\nexport interface ExternalSourceEffectContext<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends ProcessSnapshotContext<TParams, TState> {\n\t/** @public */\n\treadonly event: TEvent;\n\t/** @internal */\n\treadonly input: TInput;\n}\n\n/** @public */\nexport type ExternalSourceEffect<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> = (\n\tctx: ExternalSourceEffectContext<TParams, TState, TEvent, TInput>,\n) => ProcessEffectPlan<TState> | Promise<ProcessEffectPlan<TState> | undefined> | undefined;\n\n/** @public */\nexport interface ExternalEventDescription {\n\t/** @public */\n\tsummary: string;\n\t/** @internal */\n\tmarkdown?: string;\n\t/** @public */\n\tlinks?: import(\"@leitwerk-dev/domain\").TurnProgressLink[];\n}\n\n/** @public */\nexport interface ExternalActionSource<\n\tTParams = unknown,\n\tTState = unknown,\n\t_TEvent = unknown,\n\t_TInput extends Record<string, unknown> = Record<string, unknown>,\n> {\n\t/** @public */\n\tkind: string;\n\t/** @public */\n\tlabel?: string;\n\t/** @public */\n\tdescription?: string;\n\t/** Pure description captured when the event is consumed. @public */\n\tdescribeEvent?(event: _TEvent): ExternalEventDescription;\n\t/**\n\t * Extension-owned opaque config. Core may persist, hash, and display it, but must not\n\t * interpret provider-specific fields.\n\t */\n\t/** @public */\n\tconfig: unknown;\n\t/** Source-provided input behavior. Provider input is only published when the external action declares publishInput. @public */\n\tinputMode?: ExternalSourceInputMode;\n\t/** Optional extension-owned resolver for process-instance-specific matching. @public */\n\tresolve?(ctx: ExternalSourceResolveContext<TParams, TState>): unknown;\n}\n\n/** @public */\nexport interface ServerProcessContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\ttransition(next: ServerTransitionRequest<TState>): Promise<void>;\n\t/** @internal */\n\temitEvent<K extends keyof ServerExtensionEventMap & string>(\n\t\teventType: K,\n\t\tdata: ServerExtensionEventPayloadInputMap[K],\n\t): void;\n\t/**\n\t * Resolves non-empty turn-result markdown for the current semantic ref.\n\t * Returns `null` when the ref is unset or the referenced turn result does not\n\t * carry operator-facing markdown. Throws when persisted semantic-ref state is\n\t * malformed.\n\t */\n\t/** @internal */\n\treadSemanticTurnResultMarkdown(ref: ProcessSemanticEntryRefKey): string | null;\n\t/**\n\t * Resolves non-empty turn-result markdown for a process-defined published product.\n\t * Returns `null` when the product ref is unset or the referenced turn result does\n\t * not carry operator-facing markdown. Throws when persisted product-ref state is\n\t * malformed.\n\t */\n\t/** @internal */\n\treadProductTurnResultMarkdown(productName: string): string | null;\n\t/**\n\t * Queue durable process input for worker delivery.\n\t * Use `source: \"action_prompt\"` for action-originated follow-up prompts.\n\t * When `target` is set, the worker appends the input on the referenced\n\t * semantic or product branch before the next selected LLM turn continues from\n\t * that same branch. For `action_prompt` targeted follow-up reruns, that queued\n\t * input is the only new instruction: the worker does not replay the original\n\t * kickoff prompt.\n\t */\n\t/** @public */\n\tqueueInput(input: {\n\t\t/** @public */\n\t\tsource: InputSource;\n\t\t/** @public */\n\t\tkind: InputKind;\n\t\t/** @public */\n\t\tbodyMarkdown: string;\n\t\t/** @public */\n\t\ttarget?: ProcessInputTarget;\n\t}): void;\n\t/**\n\t * Internal SDK lifecycle-effect collector used by high-level process authoring\n\t * helpers. Raw process definitions should prefer intent helpers instead of\n\t * constructing these effects directly.\n\t */\n\t/** @internal */\n\tapplyLifecycleEffects?(effects: ProcessLifecycleEffects): void;\n}\n\n/** @public */\nexport interface WorkerProcessContext<TParams = unknown, TState = unknown>\n\textends ProcessSnapshotContext<TParams, TState> {\n\t/** @internal */\n\treadonly turnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;\n\t/** @internal */\n\treadonly turnResultMarkdownByProduct?: Readonly<Record<string, string>>;\n\t/** Absolute workspace root for the current process instance, when available. @internal */\n\treadonly workspaceRoot?: string;\n\t/** Durable output produced by this LLM turn's preparation phase, when declared. @internal */\n\treadonly prepared?: unknown;\n\t/** Active frozen item of a mapped LLM turn. @internal */\n\treadonly iteration?: MappedTurnIteration;\n\t/** Invoke a server-owned integration tool authorized for this automatic turn or LLM preparation. @internal */\n\tcallIntegrationTool?(name: string, args: Record<string, unknown>): Promise<unknown>;\n\t/** Replace the durable operator-facing progress report for this turn attempt. @internal */\n\treportProgress?(report: TurnProgressReport): void;\n}\n\n/** @public */\nexport interface WorkerCompleteInput<TOutcome extends string = string> {\n\t/** @internal */\n\toutcome: TOutcome;\n\t/** @internal */\n\tparams?: Record<string, unknown>;\n\t/** @internal */\n\tmarkdown?: string | null;\n\t/** @internal */\n\tresultSummary?: string;\n}\n\n/** @internal */\nexport interface WorkerRunHandle<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly ctx: WorkerProcessContext<TParams, TState>;\n\t/** @internal */\n\tturn<TOutcome extends string>(\n\t\tdef: LlmTurnDefinition<TOutcome, TParams, TState>,\n\t\toptions?: TurnOptions,\n\t): Promise<{\n\t\t/** @internal */\n\t\toutcome: TOutcome;\n\t\t/** @internal */\n\t\tparams: Record<string, unknown>;\n\t}>;\n\t/** @internal */\n\tcomplete<TOutcome extends string>(input: WorkerCompleteInput<TOutcome>): Promise<void>;\n\t/** @internal */\n\tpark(reason?: string): void;\n}\n\n/** @internal */\nexport type WorkerTurnHandler<TParams = unknown, TState = unknown> = (\n\trun: WorkerRunHandle<TParams, TState>,\n) => Promise<void>;\n\n/** @internal */\nexport interface ServerProcessAPI<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\taction(def: ProcessActionDefinition<TParams, TState>): void;\n\t/** @internal */\n\tonTurnOutcome(\n\t\tturnId: string,\n\t\thandler: (\n\t\t\tevent: ProcessTurnOutcomeEvent,\n\t\t\tctx: ServerProcessContext<TParams, TState>,\n\t\t) => void | Promise<void>,\n\t): void;\n\t/** @internal */\n\tonCleanup(handler: ProcessCleanupHandler<TParams, TState>): void;\n}\n\n/** @internal */\nexport interface WorkerProcessAPI<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tstart(turnId: TurnId): void;\n\t/** @internal */\n\tturn(turnId: TurnId, handler: WorkerTurnHandler<TParams, TState>): void;\n}\n\n/** @public */\nexport interface UiProcessAPI<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tleafOutcome(def: ProcessLeafOutcomeDefinition<TParams, TState>): void;\n}\n\n/** @public */\nexport interface ProcessLauncherAPI<TParams = unknown> {\n\t/** @public */\n\tlauncher(def: ProcessLauncherDefinition<TParams>): void;\n}\n\n/** @public */\nexport interface ProcessWatcherAPI<TParams = unknown> {\n\t/** @public */\n\twatcher<TEvent = unknown, TConfig = unknown>(\n\t\tdef: ProcessWatcherDefinition<TParams, TEvent, TConfig>,\n\t): void;\n}\n\n/** @public */\nexport interface ProcessTurnBinding<TTurn = TurnDefinition> {\n\t/** @public */\n\tdefinition: TTurn;\n}\n\n/** @public */\nexport type RepositoryCredentialKind = \"git_ssh\" | \"git_https\";\n\n/** Non-secret, code-defined repository authentication request. @public */\nexport interface RepositoryCredentialRequirement {\n\t/** @public */\n\treadonly projectKey: string;\n\t/** @public */\n\treadonly kind: RepositoryCredentialKind;\n\t/** @public */\n\treadonly credentialRef: string;\n}\n\n/** Project fields available while deriving repository credential requirements. @public */\nexport interface RepositoryCredentialProject {\n\t/** @internal */\n\treadonly key: string;\n\t/** @internal */\n\treadonly repoLocator: string;\n\t/** @internal */\n\treadonly baseBranch: string;\n\t/** @internal */\n\treadonly workBranch: string | null;\n}\n\n/** Secret material is intentionally restricted to server registration and worker.start. @internal */\nexport interface GitSshCredentialMaterial {\n\t/** @internal */\n\treadonly privateKey: string;\n\t/** @internal */\n\treadonly knownHosts: string;\n}\n\n/** @internal */\nexport interface GitHttpsCredentialMaterial {\n\t/** HTTPS origin authorized by the credential-owning extension. @internal */\n\treadonly origin: string;\n\t/** @internal */\n\treadonly username: string;\n\t/** @internal */\n\treadonly password: string;\n}\n\n/** @internal */\nexport type RepositoryCredentialProvider =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"git_ssh\";\n\t\t\t/** @internal */\n\t\t\tresolve(credentialRef: string): GitSshCredentialMaterial | null;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"git_https\";\n\t\t\t/** @internal */\n\t\t\tresolve(credentialRef: string): GitHttpsCredentialMaterial | null;\n\t };\n\n/** @internal */\nexport interface RepositoryCredentialRegistrar {\n\t/** @internal */\n\tregister(provider: RepositoryCredentialProvider): void;\n}\n\n/** @public */\nexport interface ProcessRuntimeCapabilities {\n\t/** Install repository-declared development tools with mise before accepting work. @internal */\n\treadonly developmentTools?: boolean;\n\t/** Require a Docker CLI connected to a private or explicitly acknowledged daemon. @public */\n\treadonly docker?: boolean;\n}\n\n/** @public */\nexport interface ExtensionProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tid: string;\n\t/** @public */\n\tdisplayName: string;\n\t/** Primary entry used when a launch does not select a start turn explicitly. @public */\n\tentryTurnId: TurnId;\n\t/** Additional entry turns that launchers may select explicitly. @public */\n\talternateEntryTurnIds?: readonly TurnId[];\n\t/**\n\t * Optional author-declared happy path: the ordered spine of turns a successful\n\t * run walks through. Flow diagrams render this as the main line and hang every\n\t * other turn off it as a branch. When omitted, consumers fall back to a derived\n\t * best-effort spine.\n\t */\n\t/** @public */\n\thappyPath?: readonly TurnId[];\n\t/** @public */\n\tturns: ReadonlyMap<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>;\n\t/** @public */\n\tparamsCodec: Codec<TParams>;\n\t/** @public */\n\tstateCodec: Codec<TState>;\n\t/** @public */\n\tinitialState(params: TParams): TState;\n\t/** Process-owned runtime capabilities. All capabilities default to disabled. @public */\n\truntime?: ProcessRuntimeCapabilities;\n\t/**\n\t * Server-only Kubernetes process-volume size, derived from extension configuration.\n\t * Explicit process storage_size wins; undefined uses the runner default.\n\t * Called before provisioning on worker starts. Must be synchronous and side-effect free;\n\t * repeated calls never resize or replace an existing volume.\n\t */\n\t/** @internal */\n\tresolveStorageSize?(input: {\n\t\t/** @internal */\n\t\tparams: TParams;\n\t\t/** @internal */\n\t\tprojects: readonly ProcessProject[];\n\t}): string | undefined;\n\t/** Runtime-only requirements; references are non-secret and remain in opaque params JSON. @public */\n\trepositoryCredentials?(input: {\n\t\t/** @public */\n\t\tparams: TParams;\n\t\t/** @public */\n\t\tprojects: readonly RepositoryCredentialProject[];\n\t}): readonly RepositoryCredentialRequirement[];\n\t/** @public */\n\tpiConfig?: ProcessPiConfig;\n\t/** @internal */\n\tserver?: (api: ServerProcessAPI<TParams, TState>) => void;\n\t/** @internal */\n\tworker?: (api: WorkerProcessAPI<TParams, TState>) => void;\n\t/** @public */\n\tui?: (api: UiProcessAPI<TParams, TState>) => void;\n\t/** @public */\n\tlaunchers?: (api: ProcessLauncherAPI<TParams>) => void;\n\t/** @public */\n\twatchers?: (api: ProcessWatcherAPI<TParams>) => void;\n}\n\n/** @public */\nexport interface CatalogExtensionAPI {\n\t/** @internal */\n\treadonly events: EventBus;\n\t/** @public */\n\tregisterProcess<TParams = unknown, TState = unknown>(\n\t\tdef: ExtensionProcessDefinition<TParams, TState>,\n\t): void;\n\t/** @internal */\n\tregisterToolRenderer(def: ToolCallRendererDefinition): void;\n\t/** @internal */\n\tprovide<T>(token: CapabilityToken<T>, value: T): void;\n\t/** @internal */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @internal */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n}\n\n/** @public */\nexport type ExtensionLifecycleHook = () => void | Promise<void>;\n\n/** @public */\nexport interface ServerExtensionLogger {\n\t/** @public */\n\tinfo?(payload: Record<string, unknown>, message?: string): void;\n\t/** @public */\n\twarn?(payload: Record<string, unknown>, message?: string): void;\n\t/** @public */\n\terror?(payload: Record<string, unknown>, message?: string): void;\n}\n\n/** @public */\nexport interface TicketCreationDestinationSummary {\n\t/** Adapter-owned opaque identifier. Browsers must not construct or interpret it. @public */\n\treadonly id: string;\n\t/** @public */\n\treadonly displayName: string;\n\t/** @public */\n\treadonly group?: string;\n\t/** @public */\n\treadonly description?: string;\n}\n\n/** @public */\nexport interface TicketCreationDestinationList {\n\t/** @public */\n\treadonly destinations: readonly TicketCreationDestinationSummary[];\n\t/** @public */\n\treadonly warnings?: readonly string[];\n}\n\n/** @public */\nexport interface TicketCreationDestinationSnapshot {\n\t/** @public */\n\treadonly summary: TicketCreationDestinationSummary;\n\t/** Adapter-owned, JSON-serializable immutable destination state. @public */\n\treadonly data: unknown;\n\t/** Untrusted destination context included in the ticket agent prompt. @public */\n\treadonly agentContext?: string;\n}\n\n/** @public */\nexport interface TicketCreationDestinationContext {\n\t/** @public */\n\treadonly actor: Actor;\n}\n\n/** @public */\nexport interface TicketCreationDestinationProvider {\n\t/** @public */\n\tlist(ctx: TicketCreationDestinationContext): Promise<TicketCreationDestinationList>;\n\t/** @public */\n\tresolve(\n\t\tctx: TicketCreationDestinationContext & {\n\t\t\t/** @public */\n\t\t\tdestinationId: string;\n\t\t},\n\t): Promise<TicketCreationDestinationSnapshot>;\n\t/** Rejects stale, renamed, transferred, or otherwise invalid snapshots. @public */\n\tvalidate(snapshot: TicketCreationDestinationSnapshot): Promise<void>;\n}\n\n/** @public */\nexport interface TicketCreationCapability {\n\t/** @public */\n\treadonly kind: \"ticket_creation\";\n\t/** @public */\n\treadonly displayName: string;\n\t/** Extension-owned process launched by the generic derived-ticket route. @public */\n\treadonly processId: string;\n\t/** Entry turn selected when the derived process starts. @public */\n\treadonly startTurnId: TurnId;\n\t/** RFC 6901 JSON Pointer into the tool arguments. @public */\n\treadonly titlePath?: string;\n\t/** RFC 6901 JSON Pointer into the tool arguments. @public */\n\treadonly descriptionPath?: string;\n\t/** @public */\n\treadonly destinations?: TicketCreationDestinationProvider;\n}\n\n/** @internal */\nexport interface TicketCreationReceipt {\n\t/** @internal */\n\treadonly externalId: string;\n\t/** @internal */\n\treadonly url: string;\n\t/** @internal */\n\treadonly result?: unknown;\n}\n\n/** @public */\nexport interface IntegrationToolExecutionContext {\n\t/** Process-bound coordination; storage remains server-owned. */\n\t/** @public */\n\treadonly externalWrites: ExternalWrites;\n\t/** @public */\n\treadonly process: ProcessInstance;\n\t/** @public */\n\treadonly projects: readonly ProcessProject[];\n\t/** @public */\n\treadonly turn: ProcessTurnRecord;\n\t/** @public */\n\treadonly project: ProcessProject | null;\n\t/** @public */\n\treadonly ticketDestination?: TicketCreationDestinationSnapshot;\n\t/** Stable for a single Pi tool call, including reconnect/replay. @public */\n\treadonly idempotencyKey: string;\n\t/** Aborted when the worker stops waiting for this tool call. @public */\n\treadonly signal: AbortSignal;\n}\n\n/** @public */\nexport interface IntegrationToolDefinition<TArgs = Record<string, unknown>> {\n\t/** @public */\n\treadonly name: string;\n\t/** @public */\n\treadonly description: string;\n\t/** @public */\n\treadonly parameters: Record<string, unknown>;\n\t/** Sanitized discovery metadata; credentials and adapter configuration never belong here. @public */\n\treadonly capability?: TicketCreationCapability;\n\t/** @internal */\n\tparse?(value: unknown): TArgs;\n\t/** @public */\n\texecute(ctx: IntegrationToolExecutionContext, args: TArgs): Promise<unknown>;\n}\n\n/** @public */\nexport interface ServerExtensionAPI {\n\t/** @internal */\n\treadonly events: EventBus<ServerExtensionEventMap>;\n\t/** @public */\n\treadonly logger?: ServerExtensionLogger;\n\t/** @public */\n\tprovide<T>(token: CapabilityToken<T>, value: T): void;\n\t/** @public */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @public */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n\t/** @public */\n\ttool<TArgs>(definition: IntegrationToolDefinition<TArgs>): void;\n\t/** @internal */\n\tonStart(handler: ExtensionLifecycleHook): void;\n\t/** @public */\n\tonStop(handler: ExtensionLifecycleHook): void;\n}\n\n/** @internal */\nexport interface WorkerExtensionAPI {\n\t/** @internal */\n\treadonly events: EventBus;\n\t/** @internal */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @internal */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n}\n\n/** @public */\nexport interface LeitwerkExtensionModule {\n\t/** @public */\n\tmanifest: {\n\t\t/** @public */\n\t\tid: string;\n\t\t/** @public */\n\t\tversion: string;\n\t\t/** @public */\n\t\trequires?: readonly string[];\n\t\t/** @internal */\n\t\toptional?: readonly string[];\n\t};\n\t/** Resolves every provider owned by this extension before setupServer. @public */\n\tmodelProviders?: ModelProviderSet;\n\t/** @public */\n\tsetupCatalog?(api: CatalogExtensionAPI): void | Promise<void>;\n\t/** @public */\n\tsetupServer?(api: ServerExtensionAPI, config: unknown): void | Promise<void>;\n\t/** @internal */\n\tsetupWorker?(api: WorkerExtensionAPI, config: unknown): void | Promise<void>;\n}\n","import type {\n\tProcessInstance,\n\tProcessProject,\n\tProcessTurnTerminalLifecycleStatus,\n\tTurnId,\n} from \"@leitwerk-dev/domain\";\nimport type { Codec, ProcessTurnOutcomeEvent } from \"./extension-api.js\";\nimport { SafeOutcomePlanningError } from \"./extension-api.js\";\n\n/** @public */\ntype MaybePromise<T> = T | Promise<T>;\n\n/** Maximum length of a mapped item key. @internal */\nexport const MAPPED_ITEM_KEY_MAX_LENGTH = 200;\n/** Maximum length of a mapped item label. @internal */\nexport const MAPPED_ITEM_LABEL_MAX_LENGTH = 200;\n/** Maximum number of items frozen by one mapped run. @internal */\nexport const MAPPED_ITEM_MAX_COUNT = 500;\n/** Graph trigger used by a mapped turn's collection route. @internal */\nexport const MAPPED_COLLECT_TRIGGER = \"collect\" as const;\n\n/** @internal */\nexport function mappedCollectTrigger(branchId?: string): string {\n\treturn branchId === undefined ? MAPPED_COLLECT_TRIGGER : `${MAPPED_COLLECT_TRIGGER}:${branchId}`;\n}\n\n/** Durable snapshot of process data available to mapped-turn server callbacks. @public */\nexport interface MappedTurnServerContext<TParams = unknown, TState = unknown> {\n\t/** @public */\n\treadonly process: ProcessInstance;\n\t/** @internal */\n\treadonly projects: readonly ProcessProject[];\n\t/** @public */\n\treadonly params: TParams;\n\t/** @public */\n\treadonly state: TState;\n}\n\n/** Active item of a mapped LLM turn, as delivered to one worker turn. @public */\nexport interface MappedTurnItemContext<TItem = unknown> {\n\t/** Frozen, codec-validated item value. @public */\n\treadonly item: TItem;\n\t/** Stable key unique within the run. @public */\n\treadonly itemKey: string;\n\t/** Short plain-text label shown to operators. @public */\n\treadonly itemLabel: string;\n\t/** Zero-based position in the frozen order. @public */\n\treadonly itemIndex: number;\n\t/** Number of frozen items in the run. @public */\n\treadonly itemCount: number;\n}\n\n/** Serialized active item carried by worker payloads and turn records. @internal */\nexport interface MappedTurnIteration {\n\t/** @internal */\n\treadonly runId: string;\n\t/** @internal */\n\treadonly itemKey: string;\n\t/** @internal */\n\treadonly itemLabel: string;\n\t/** @internal */\n\treadonly itemIndex: number;\n\t/** @internal */\n\treadonly itemCount: number;\n\t/** JSON value produced by the item codec. @internal */\n\treadonly item: unknown;\n}\n\n/** @public */\nexport interface MappedItemInput<TItem = unknown> {\n\t/** @public */\n\treadonly item: TItem;\n\t/** @public */\n\treadonly index: number;\n}\n\n/** @public */\nexport interface MappedSnapshotInput<TParams = unknown, TState = unknown, TItem = unknown> {\n\t/** @public */\n\treadonly params: TParams;\n\t/** @public */\n\treadonly state: TState;\n\t/** @public */\n\treadonly items: readonly TItem[];\n}\n\n/** Context passed to a mapped outcome's `yield` callback. @public */\nexport interface MappedOutcomeContext<TParams = unknown, TState = unknown, TItem = unknown>\n\textends MappedTurnServerContext<TParams, TState>,\n\t\tMappedTurnItemContext<TItem> {}\n\n/** @public */\nexport interface MappedYieldInput<TParams = unknown, TState = unknown, TItem = unknown> {\n\t/** @public */\n\treadonly ctx: MappedOutcomeContext<TParams, TState, TItem>;\n\t/** @public */\n\treadonly event: ProcessTurnOutcomeEvent;\n}\n\n/** @public */\nexport type MappedItemYield<\n\tTParams = unknown,\n\tTState = unknown,\n\tTItem = unknown,\n\tTResult = unknown,\n> = (input: MappedYieldInput<TParams, TState, TItem>) => MaybePromise<TResult>;\n\n/** @public */\nexport type MappedCollect<TParams = unknown, TState = unknown, TResult = unknown> = (\n\tctx: MappedTurnServerContext<TParams, TState>,\n\torderedResults: readonly TResult[],\n) => MaybePromise<TState>;\n\n/** Route applied once, after collection. @internal */\nexport type MappedCollectRouting<TParams = unknown, TState = unknown> =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"static\";\n\t\t\t/** @internal */\n\t\t\tto?: TurnId;\n\t\t\t/** @internal */\n\t\t\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"branches\";\n\t\t\t/** @internal */\n\t\t\tbranches: Readonly<Record<string, TurnId>>;\n\t\t\t/** @internal */\n\t\t\tchoose(ctx: MappedTurnServerContext<TParams, TState>): MaybePromise<string>;\n\t };\n\n/**\n * Durable sequential iteration of one LLM turn over frozen items. Items run one\n * at a time; each item yields a typed result, and business state and routing\n * change once, when all results are collected.\n * @public\n */\nexport interface MappedLlmTurnSpec<\n\tTParams = unknown,\n\tTState = unknown,\n\tTItem = unknown,\n\tTResult = unknown,\n> {\n\t/** Evaluated once when the turn is entered. @public */\n\titems(ctx: MappedTurnServerContext<TParams, TState>): readonly unknown[] | null | undefined;\n\t/** @public */\n\titemCodec: Codec<TItem>;\n\t/** @public */\n\tresultCodec: Codec<TResult>;\n\t/** @public */\n\tkey(input: MappedItemInput<TItem>): string;\n\t/** Defaults to the item key. @public */\n\tlabel?(input: MappedItemInput<TItem>): string;\n\t/** Applied in the freezing transaction, before any item starts. @public */\n\tstateAfterSnapshot?(input: MappedSnapshotInput<TParams, TState, TItem>): TState;\n\t/** @internal */\n\tyields: Readonly<Record<string, MappedItemYield<TParams, TState, TItem, TResult>>>;\n\t/** @internal */\n\tcollect: MappedCollect<TParams, TState, TResult>;\n\t/** @internal */\n\trouting: MappedCollectRouting<TParams, TState>;\n}\n\n/** @internal */\nexport interface FrozenMappedItem {\n\t/** @internal */\n\tindex: number;\n\t/** @internal */\n\tkey: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\titemJson: string;\n}\n\n/** @internal */\nexport interface MappedFreezeResult<TState = unknown> {\n\t/** @internal */\n\titems: FrozenMappedItem[];\n\t/** State to persist in the freezing transaction, when `stateAfterSnapshot` is declared. @internal */\n\tstate?: TState;\n}\n\n/** @internal */\nexport interface MappedCollectResult<TState = unknown> {\n\t/** @internal */\n\tstate: TState;\n\t/** @internal */\n\troute: {\n\t\t/** @internal */\n\t\ttrigger: string;\n\t\t/** @internal */\n\t\tnextTurnId?: TurnId;\n\t\t/** @internal */\n\t\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n\t};\n}\n\nfunction toJsonValue(value: unknown, context: string): string {\n\tlet json: string | undefined;\n\ttry {\n\t\tjson = JSON.stringify(value);\n\t} catch {\n\t\tjson = undefined;\n\t}\n\tif (json === undefined) {\n\t\tthrow new SafeOutcomePlanningError(\"invalid_mapped_value\", `${context} is not JSON`);\n\t}\n\treturn json;\n}\n\nfunction plainText(value: string): string {\n\treturn value.replace(/\\s+/g, \" \").trim();\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Evaluates, validates, and serializes the items of a mapped turn. @internal */\nexport function freezeMappedItems<TParams, TState>(\n\tturnId: TurnId,\n\tspec: MappedLlmTurnSpec<TParams, TState>,\n\tctx: MappedTurnServerContext<TParams, TState>,\n): MappedFreezeResult<TState> {\n\tconst raw = spec.items(ctx) ?? [];\n\tif (!Array.isArray(raw)) {\n\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\"invalid_mapped_items\",\n\t\t\t`Mapped turn '${turnId}' items must be an array`,\n\t\t);\n\t}\n\tif (raw.length > MAPPED_ITEM_MAX_COUNT) {\n\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\"invalid_mapped_items\",\n\t\t\t`Mapped turn '${turnId}' may freeze at most ${MAPPED_ITEM_MAX_COUNT} items`,\n\t\t);\n\t}\n\tconst parsed: unknown[] = [];\n\tconst items: FrozenMappedItem[] = [];\n\tconst keys = new Set<string>();\n\tfor (const [index, value] of raw.entries()) {\n\t\tlet item: unknown;\n\t\ttry {\n\t\t\titem = spec.itemCodec.parse(value);\n\t\t} catch (error) {\n\t\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\t\"invalid_mapped_item\",\n\t\t\t\t`Mapped turn '${turnId}' item ${index} is invalid: ${errorMessage(error)}`,\n\t\t\t);\n\t\t}\n\t\tconst key = spec.key({ item, index });\n\t\tif (typeof key !== \"string\" || key.trim() === \"\" || key.length > MAPPED_ITEM_KEY_MAX_LENGTH) {\n\t\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\t\"invalid_mapped_item_key\",\n\t\t\t\t`Mapped turn '${turnId}' item ${index} needs a non-empty key of at most ${MAPPED_ITEM_KEY_MAX_LENGTH} characters`,\n\t\t\t);\n\t\t}\n\t\tif (keys.has(key)) {\n\t\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\t\"duplicate_mapped_item_key\",\n\t\t\t\t`Mapped turn '${turnId}' repeats item key '${key}'`,\n\t\t\t);\n\t\t}\n\t\tkeys.add(key);\n\t\tconst rawLabel = spec.label ? spec.label({ item, index }) : key;\n\t\tconst label = plainText(typeof rawLabel === \"string\" ? rawLabel : \"\") || key;\n\t\tparsed.push(item);\n\t\titems.push({\n\t\t\tindex,\n\t\t\tkey,\n\t\t\tlabel: label.slice(0, MAPPED_ITEM_LABEL_MAX_LENGTH),\n\t\t\titemJson: toJsonValue(\n\t\t\t\tspec.itemCodec.serialize(item),\n\t\t\t\t`Mapped turn '${turnId}' item '${key}'`,\n\t\t\t),\n\t\t});\n\t}\n\treturn {\n\t\titems,\n\t\t...(spec.stateAfterSnapshot\n\t\t\t? {\n\t\t\t\t\tstate: spec.stateAfterSnapshot({\n\t\t\t\t\t\tparams: ctx.params,\n\t\t\t\t\t\tstate: ctx.state,\n\t\t\t\t\t\titems: parsed,\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/** Maps one item outcome to its serialized, codec-validated result. @internal */\nexport async function yieldMappedItemResult<TParams, TState>(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tspec: MappedLlmTurnSpec<TParams, TState>;\n\t/** @internal */\n\tctx: MappedTurnServerContext<TParams, TState>;\n\t/** @internal */\n\titeration: MappedTurnIteration;\n\t/** @internal */\n\tevent: ProcessTurnOutcomeEvent;\n}): Promise<string> {\n\tconst yieldResult = input.spec.yields[input.event.outcome];\n\tif (!yieldResult) {\n\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\"unknown_mapped_outcome\",\n\t\t\t`Mapped turn '${input.turnId}' has no result for outcome '${input.event.outcome}'`,\n\t\t);\n\t}\n\tconst item = input.spec.itemCodec.parse(input.iteration.item);\n\tconst value = await yieldResult({\n\t\tctx: {\n\t\t\t...input.ctx,\n\t\t\titem,\n\t\t\titemKey: input.iteration.itemKey,\n\t\t\titemLabel: input.iteration.itemLabel,\n\t\t\titemIndex: input.iteration.itemIndex,\n\t\t\titemCount: input.iteration.itemCount,\n\t\t},\n\t\tevent: input.event,\n\t});\n\tlet result: unknown;\n\ttry {\n\t\tresult = input.spec.resultCodec.parse(value);\n\t} catch (error) {\n\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\"invalid_mapped_result\",\n\t\t\t`Mapped turn '${input.turnId}' produced an invalid result for item '${input.iteration.itemKey}': ${errorMessage(error)}`,\n\t\t);\n\t}\n\treturn toJsonValue(\n\t\tinput.spec.resultCodec.serialize(result),\n\t\t`Mapped turn '${input.turnId}' result for item '${input.iteration.itemKey}'`,\n\t);\n}\n\n/** Collects ordered results once and resolves the turn's single business route. @internal */\nexport async function collectMappedResults<TParams, TState>(input: {\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tspec: MappedLlmTurnSpec<TParams, TState>;\n\t/** @internal */\n\tctx: MappedTurnServerContext<TParams, TState>;\n\t/** Serialized results in frozen item order. @internal */\n\tresultJsons: readonly string[];\n}): Promise<MappedCollectResult<TState>> {\n\tconst results = input.resultJsons.map((json, index) => {\n\t\ttry {\n\t\t\treturn input.spec.resultCodec.parse(JSON.parse(json));\n\t\t} catch (error) {\n\t\t\tthrow new SafeOutcomePlanningError(\n\t\t\t\t\"invalid_mapped_result\",\n\t\t\t\t`Mapped turn '${input.turnId}' stored an invalid result at item ${index}: ${errorMessage(error)}`,\n\t\t\t);\n\t\t}\n\t});\n\tconst state = await input.spec.collect(input.ctx, results);\n\tconst routing = input.spec.routing;\n\tif (routing.kind === \"static\") {\n\t\treturn {\n\t\t\tstate,\n\t\t\troute: {\n\t\t\t\ttrigger: mappedCollectTrigger(),\n\t\t\t\t...(routing.to !== undefined ? { nextTurnId: routing.to } : {}),\n\t\t\t\t...(routing.lifecycleStatus !== undefined\n\t\t\t\t\t? { lifecycleStatus: routing.lifecycleStatus }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t};\n\t}\n\tconst branchId = await routing.choose({ ...input.ctx, state });\n\tif (!Object.hasOwn(routing.branches, branchId)) {\n\t\tthrow new Error(\n\t\t\t`Mapped turn '${input.turnId}' collection selected unknown branch '${branchId}'`,\n\t\t);\n\t}\n\treturn {\n\t\tstate,\n\t\troute: { trigger: mappedCollectTrigger(branchId), nextTurnId: routing.branches[branchId] },\n\t};\n}\n","import type { EventBus } from \"./types.js\";\n\n/** @internal */\nexport function createEventBus<\n\tTEventMap extends object = Record<string, unknown>,\n>(): EventBus<TEventMap> {\n\tconst listeners = new Map<string, Set<(data: unknown) => void | Promise<void>>>();\n\n\treturn {\n\t\temit(event, data) {\n\t\t\tconst handlers = listeners.get(event);\n\t\t\tif (!handlers) return;\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tvoid handler(data);\n\t\t\t\t} catch {\n\t\t\t\t\t// swallow handler errors to avoid breaking the emit loop\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\ton(event, handler) {\n\t\t\tconst typedHandler = handler as unknown as (data: unknown) => void | Promise<void>;\n\t\t\tlet set = listeners.get(event);\n\t\t\tif (!set) {\n\t\t\t\tset = new Set();\n\t\t\t\tlisteners.set(event, set);\n\t\t\t}\n\t\t\tset.add(typedHandler);\n\t\t},\n\n\t\toff(event, handler) {\n\t\t\tlisteners.get(event)?.delete(handler as unknown as (data: unknown) => void | Promise<void>);\n\t\t},\n\t};\n}\n","import type { ExternalActionSource } from \"./extension-api.js\";\n\n/** Define a resolver-based source with no provider input. @public */\nexport function defineExternalActionSource<TConfig>(\n\tmetadata: Pick<ExternalActionSource, \"kind\" | \"label\" | \"description\" | \"describeEvent\">,\n) {\n\treturn function source<TParams, TState>(\n\t\tresolve: (ctx: {\n\t\t\t/** @public */\n\t\t\tparams: TParams;\n\t\t\t/** @public */\n\t\t\tstate: TState;\n\t\t}) => TConfig,\n\t): ExternalActionSource<TParams, TState> {\n\t\treturn { ...metadata, config: {}, inputMode: \"none\", resolve };\n\t};\n}\n","import type {\n\tExternalObservationInput,\n\tExternalSourceArmingLike,\n\tExternalSourceServiceLike,\n} from \"./core-capabilities.js\";\n\n/** @public */\ntype Arming = Pick<ExternalSourceArmingLike, \"id\" | \"instanceId\" | \"generation\" | \"resolved\">;\n\n/** Report one poll's effects without choosing events, scheduling, or subscription policy. @public */\nexport function createExternalSourcePollReporter(\n\tsources: ExternalSourceServiceLike,\n\tresult: {\n\t\t/** @public */\n\t\tcreated: string[];\n\t\t/** @public */\n\t\terrors: string[];\n\t},\n\toptions: {\n\t\t/** @public */\n\t\tforwardGeneration?: boolean;\n\t\t/** Live source kinds checked before fire and observe. @public */\n\t\tcurrentKinds?: readonly string[];\n\t} = {},\n): ExternalSourcePollReporter {\n\tconst isCurrent = (kind: string, armed: Arming) =>\n\t\tsources.listArmed(kind).some((current) => sameSubscription(armed, current));\n\tconst current = (armed: Arming) =>\n\t\toptions.currentKinds === undefined ||\n\t\toptions.currentKinds.some((kind) => isCurrent(kind, armed));\n\treturn {\n\t\tisCurrent,\n\t\t/** @public */\n\t\tasync poll(kind: string, read: (armed: ExternalSourceArmingLike) => Promise<void>) {\n\t\t\tfor (const armed of sources.listArmed(kind)) {\n\t\t\t\ttry {\n\t\t\t\t\tawait read(armed);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tresult.errors.push(\n\t\t\t\t\t\t`${armed.id}:${error instanceof Error ? error.message : \"poll_failed\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** @public */\n\t\tasync fire(armed: Arming, event: Record<string, unknown>, mergeKey: string): Promise<boolean> {\n\t\t\tif (!current(armed)) return false;\n\t\t\tconst fired = await sources.fire({\n\t\t\t\tinstanceId: armed.instanceId,\n\t\t\t\tarmingId: armed.id,\n\t\t\t\t...(options.forwardGeneration && armed.generation ? { generation: armed.generation } : {}),\n\t\t\t\tevent,\n\t\t\t\tmergeKey,\n\t\t\t});\n\t\t\tif (fired.ok) result.created.push(armed.id);\n\t\t\telse result.errors.push(`${armed.id}:fire_failed`);\n\t\t\treturn fired.ok;\n\t\t},\n\t\t/** @public */\n\t\tobserve(armed: Arming, input: Pick<ExternalObservationInput, \"observation\" | \"refreshError\">) {\n\t\t\tif (current(armed) && sources.observe && armed.generation)\n\t\t\t\treturn sources.observe({\n\t\t\t\t\tinstanceId: armed.instanceId,\n\t\t\t\t\tarmingId: armed.id,\n\t\t\t\t\tgeneration: armed.generation,\n\t\t\t\t\t...input,\n\t\t\t\t});\n\t\t},\n\t};\n}\n\n/** Effects of one poll, with caller-selected scheduling and event policy. @public */\nexport interface ExternalSourcePollReporter {\n\t/** @public */\n\tpoll(kind: string, read: (armed: ExternalSourceArmingLike) => Promise<void>): Promise<void>;\n\t/** @public */\n\tfire(armed: Arming, event: Record<string, unknown>, mergeKey: string): Promise<boolean>;\n\t/** @public */\n\tobserve(\n\t\tarmed: Arming,\n\t\tinput: Pick<ExternalObservationInput, \"observation\" | \"refreshError\">,\n\t): ReturnType<NonNullable<ExternalSourceServiceLike[\"observe\"]>> | undefined;\n\t/** Compare the captured identity, generation and resolved value with a live subscription. @public */\n\tisCurrent(kind: string, armed: Arming): boolean;\n}\n/** A captured generation and resolved identity must still be armed after provider I/O. @internal */\nfunction sameSubscription(\n\tcaptured: {\n\t\t/** @internal */\n\t\tid: string;\n\t\t/** @internal */\n\t\tinstanceId: string;\n\t\t/** @internal */\n\t\tgeneration?: string;\n\t\t/** @internal */\n\t\tresolved: unknown;\n\t},\n\tcurrent: {\n\t\t/** @internal */\n\t\tid: string;\n\t\t/** @internal */\n\t\tinstanceId: string;\n\t\t/** @internal */\n\t\tgeneration?: string;\n\t\t/** @internal */\n\t\tresolved: unknown;\n\t},\n): boolean {\n\treturn (\n\t\tcurrent.id === captured.id &&\n\t\tcurrent.instanceId === captured.instanceId &&\n\t\tcurrent.generation === captured.generation &&\n\t\tJSON.stringify(current.resolved) === JSON.stringify(captured.resolved)\n\t);\n}\n","import path from \"node:path\";\nimport {\n\tassertValidProcessProductName,\n\thumanizeProcessLabel,\n\ttype ProcessInstance,\n\ttype ProcessProject,\n\ttype ProcessSemanticEntryRefKey,\n\ttype ProcessTurnStartSelection,\n\ttype ProcessTurnTerminalLifecycleStatus,\n\ttype TurnId,\n\ttype TurnProgressReport,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tAutomaticTurnDefinition,\n\tDefinedProcessInput,\n\tExternalTurnDefinition,\n\tHumanTurnDefinition,\n\tHumanTurnOperatorAttention,\n\tLlmModelPurpose,\n\tLlmTurnDefinition,\n\tProcessEffectPlan,\n\tProcessHumanTurnActionSpec,\n\tProcessHumanTurnExternalActionSpec,\n\tProcessOutcomeEffect,\n\tProcessOutcomeExecution,\n\tProcessRuntimeTurnContext,\n\tProcessToolOutcomeSpec,\n\tProcessTurnEndSpec,\n\tTurnDefinition,\n\tTurnDefinitionRecord,\n} from \"./define-process.js\";\nimport { defineProcess } from \"./define-process.js\";\nimport type {\n\tCodec,\n\tExtensionProcessDefinition,\n\tExternalActionSource,\n\tExternalSourceEffect,\n\tExternalSourceEffectContext,\n\tFormDefinition,\n\tProcessActionDefinition,\n\tProcessLauncherAPI,\n\tProcessLauncherDefinition,\n\tProcessWatcherAPI,\n\tProcessWatcherDefinition,\n\tServerProcessAPI,\n\tUiProcessAPI,\n\tWorkerCompleteInput,\n} from \"./extension-api.js\";\nimport { isPathInside } from \"./fs-utils.js\";\nimport type {\n\tMappedCollect,\n\tMappedCollectRouting,\n\tMappedItemYield,\n\tMappedLlmTurnSpec,\n\tMappedTurnItemContext,\n\tMappedTurnServerContext,\n} from \"./mapped-turn.js\";\nimport {\n\ttype ProcessGraphSource,\n\ttoProcessGraphView,\n\tvalidateProcessGraphProducts,\n} from \"./process-graph.js\";\nimport type { OutcomeToolParameterSpec, PiBuiltInToolName, ProcessPiConfig } from \"./types.js\";\n\n/** @public */\ntype MaybePromise<T> = T | Promise<T>;\n\n/** @internal */\nexport const DEFAULT_PLAN_RESULT_OUTCOME_ID = \"plan_saved\" as const;\n/** @internal */\nexport const DEFAULT_FLOW_PRODUCT_NAME = \"default\" as const;\nconst ASSISTANT_OUTPUT_TURN_RESULT = { mode: \"assistant_output\", required: true } as const;\nconst OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME = \"markdown\" as const;\nconst OUTCOME_TOOL_ARGUMENT_TURN_RESULT = {\n\tmode: \"outcome_tool_argument\",\n\tparameterName: OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME,\n\trequired: true,\n} as const;\n\n/** @public */\nexport interface FlowLlmTurn<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: LlmTurnDefinition<TOutcome, TParams, TState>;\n}\n\n/** @public */\nexport interface FlowAutomaticTurn<\n\tTParams = unknown,\n\tTState = unknown,\n\tTOutcome extends string = string,\n> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: AutomaticTurnDefinition<TOutcome, TParams, TState>;\n}\n\n/** @public */\nexport interface FlowHumanTurn<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: HumanTurnDefinition<TParams, TState>;\n}\n\n/** @public */\nexport interface FlowExternalTurn<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tid: TurnId;\n\t/** @public */\n\tdefinition: ExternalTurnDefinition<TParams, TState>;\n}\n\n/** @public */\nexport type FlowTurn<TParams = unknown, TState = unknown> =\n\t| FlowLlmTurn<TParams, TState, string>\n\t| FlowAutomaticTurn<TParams, TState, string>\n\t| FlowHumanTurn<TParams, TState>\n\t| FlowExternalTurn<TParams, TState>\n\t| {\n\t\t\t/** @public */\n\t\t\tid: TurnId;\n\t\t\t/** @public */\n\t\t\tdefinition: TurnDefinition<TParams, TState>;\n\t };\n\n/** @internal */\nexport interface PlanFieldOptions {\n\t/** @internal */\n\tdescription?: string;\n\t/** @internal */\n\trequiredErrorCode?: string;\n}\n\n/** @internal */\nexport interface PlanAcceptanceCriteriaOptions extends PlanFieldOptions {\n\t/** @internal */\n\tminItems?: number;\n\t/** @internal */\n\tminItemsErrorCode?: string;\n}\n\nexport interface PlanSavedStateInput<TParams = unknown, TState = unknown> {\n\teffect: ProcessOutcomeEffect<TParams, TState>;\n}\n\n/** @public */\nexport interface FlowRepoContext {\n\t/** @internal */\n\tkey: string;\n\t/** @public */\n\tfsPath: string;\n\t/** @internal */\n\tworkspaceClonePath: string;\n\t/** @public */\n\tbaseBranch: string;\n\t/** @public */\n\tworkBranch: string;\n\t/** @internal */\n\tlocator: string;\n}\n\n/** @public */\nexport interface FlowRepoLookup {\n\t/** @public */\n\tget(key: string): FlowRepoContext;\n\t/** @internal */\n\toptional(key: string): FlowRepoContext | undefined;\n\t/** @internal */\n\tall(): FlowRepoContext[];\n}\n\n/** @public */\nexport type FlowPromptContext<\n\tTParams = unknown,\n\tTState = unknown,\n\tTConsumedProducts extends string = string,\n\tTPrepared = undefined,\n> = {\n\t/** @internal */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tprojects: readonly ProcessProject[];\n\t/** @public */\n\tparams: TParams;\n\t/** @public */\n\tstate: TState;\n\t/** @internal */\n\tworkspaceRoot?: string;\n\t/** @internal */\n\tprompts: {\n\t\t/** @internal */\n\t\tinitial: string;\n\t};\n\t/** @public */\n\tinput: Readonly<Partial<Record<TConsumedProducts, string>>>;\n\t/** @internal */\n\trepo: FlowRepoLookup;\n} & ([TPrepared] extends [undefined]\n\t? {\n\t\t\t/** @internal */\n\t\t\tprepared?: undefined;\n\t\t}\n\t: {\n\t\t\t/** @internal */\n\t\t\tprepared: TPrepared;\n\t\t});\n\n/** @public */\nexport interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tprocess: ProcessInstance;\n\t/** @public */\n\tprojects: readonly ProcessProject[];\n\t/** @public */\n\tparams: TParams;\n\t/** @public */\n\tstate: TState;\n\t/** @public */\n\tworkspaceRoot?: string;\n\t/** @public */\n\trepo: FlowRepoLookup;\n\t/** @public */\n\tcallIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;\n\t/** @public */\n\treportProgress(report: TurnProgressReport): void;\n}\n\n/** @public */\nexport type FlowLlmPreparationContext<\n\tTParams = unknown,\n\tTState = unknown,\n> = FlowAutomaticRunContext<TParams, TState>;\n\n/** @public */\ninterface FlowOutcomeEffectContext<TParams = unknown, TState = unknown> {\n\t/** @public */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tprojects: readonly ProcessProject[];\n\t/** @internal */\n\tparams: TParams;\n\t/** @public */\n\tstate: TState;\n\t/** @internal */\n\toutput: {\n\t\t/** @internal */\n\t\tcontent: string | null;\n\t} | null;\n}\n\n/** @public */\nexport interface FlowLlmOutcomeEffectContext<TParams = unknown, TState = unknown>\n\textends FlowOutcomeEffectContext<TParams, TState> {}\n\n/** @public */\nexport interface FlowAutomaticOutcomeEffectContext<TParams = unknown, TState = unknown>\n\textends FlowOutcomeEffectContext<TParams, TState> {}\n\n/** @internal */\nexport interface FlowExternalSourceContext<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> extends ExternalSourceEffectContext<TParams, TState, TEvent, TInput> {}\n\n/** @public */\ntype FlowOutcomeEffectInput<TParams, TState, TContext> = {\n\t/** @public */\n\tctx: TContext;\n\t/** @public */\n\tevent: ProcessOutcomeExecution<TParams, TState>[\"event\"];\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\toutcome: string;\n};\n\n/** @public */\ntype FlowOutcomeEffect<TParams, TState, TContext> = (\n\tinput: FlowOutcomeEffectInput<TParams, TState, TContext>,\n) => MaybePromise<ProcessEffectPlan<TState> | undefined>;\n\n/** @public */\ntype FlowOutcomeStateEffect<TParams, TState, TContext> = (\n\tinput: FlowOutcomeEffectInput<TParams, TState, TContext>,\n) => MaybePromise<TState>;\n\nfunction textField(input: {\n\tdescription: string;\n\trequiredErrorCode: string;\n}): OutcomeToolParameterSpec {\n\treturn {\n\t\ttype: \"string\",\n\t\tdescription: input.description,\n\t\trequired: true,\n\t\trequiredErrorCode: input.requiredErrorCode,\n\t};\n}\n\nfunction stringArrayField(input: {\n\tdescription: string;\n\trequiredErrorCode: string;\n\tminItems: number;\n\tminItemsErrorCode: string;\n}): OutcomeToolParameterSpec {\n\treturn {\n\t\ttype: \"array\",\n\t\tdescription: input.description,\n\t\titems: { type: \"string\" },\n\t\trequired: true,\n\t\trequiredErrorCode: input.requiredErrorCode,\n\t\tminItems: input.minItems,\n\t\tminItemsErrorCode: input.minItemsErrorCode,\n\t};\n}\n\nfunction normalizeProductName(productName: string): string {\n\tassertValidProcessProductName(productName);\n\treturn productName;\n}\n\nfunction toRequiredErrorCode(name: string): string {\n\tconst snake = name\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n\t\t.replace(/[^a-zA-Z0-9]+/g, \"_\")\n\t\t.replace(/^_+|_+$/g, \"\")\n\t\t.toLowerCase();\n\treturn `${snake || \"value\"}_required`;\n}\n\nfunction readInitialPrompt<TParams>(params: TParams): string {\n\tif (typeof params === \"object\" && params !== null && \"prompt\" in params) {\n\t\tconst value = (params as { prompt?: unknown }).prompt;\n\t\tif (typeof value === \"string\") {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn \"\";\n}\n\nfunction safeJoinInside(parent: string, childPath: string, context: string): string {\n\tconst parentPath = path.resolve(parent);\n\tconst targetPath = path.resolve(parentPath, childPath);\n\tif (!isPathInside(parentPath, targetPath)) {\n\t\tthrow new Error(`${context} resolves outside '${parentPath}'`);\n\t}\n\treturn targetPath;\n}\n\nfunction toWorkspaceClonePath(relativePath: string): string {\n\treturn `./${relativePath.split(path.sep).join(\"/\")}`;\n}\n\nfunction resolveSafeProjectWorkspacePath(key: string): {\n\trelativePath: string;\n\tworkspaceClonePath: string;\n} {\n\tif (path.isAbsolute(key)) {\n\t\tthrow new Error(`Flow context project key '${key}' must be a relative workspace path`);\n\t}\n\tconst virtualWorkspaceRoot = path.resolve(path.sep, \"__leitwerk_process_workspace__\");\n\tconst virtualTarget = safeJoinInside(\n\t\tvirtualWorkspaceRoot,\n\t\tkey,\n\t\t`Flow context project key '${key}'`,\n\t);\n\tconst relativePath = path.relative(virtualWorkspaceRoot, virtualTarget);\n\treturn {\n\t\trelativePath,\n\t\tworkspaceClonePath: toWorkspaceClonePath(relativePath),\n\t};\n}\n\nfunction resolveRepoByKey(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n\tkey: string;\n\trequired: true;\n}): FlowRepoContext;\nfunction resolveRepoByKey(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n\tkey: string;\n\trequired: false;\n}): FlowRepoContext | undefined;\nfunction resolveRepoByKey(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n\tkey: string;\n\trequired: boolean;\n}): FlowRepoContext | undefined {\n\tconst requestedKey = input.key.trim();\n\tif (!requestedKey) {\n\t\tthrow new Error(\"Flow repo lookup requires a non-empty project key\");\n\t}\n\tconst matches = input.projects.filter((project) => project.key.trim() === requestedKey);\n\tif (matches.length === 0) {\n\t\tif (!input.required) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst availableKeys = input.projects\n\t\t\t.map((project) => project.key.trim())\n\t\t\t.filter((key) => key !== \"\")\n\t\t\t.join(\", \");\n\t\tthrow new Error(\n\t\t\t`Flow context requires project '${requestedKey}', but this process has no project with that key${\n\t\t\t\tavailableKeys ? ` (available: ${availableKeys})` : \"\"\n\t\t\t}`,\n\t\t);\n\t}\n\tif (matches.length > 1) {\n\t\tthrow new Error(`Flow context found duplicate project key '${requestedKey}'`);\n\t}\n\tconst project = matches[0];\n\tconst key = project.key.trim();\n\tif (!key) {\n\t\tthrow new Error(\"Flow context requires projects to have non-empty keys\");\n\t}\n\tconst baseBranch = project.baseBranch.trim();\n\tif (!baseBranch) {\n\t\tthrow new Error(`Flow context project '${key}' has no base branch`);\n\t}\n\tconst workBranch = (project.workBranch ?? project.baseBranch).trim();\n\tif (!workBranch) {\n\t\tthrow new Error(`Flow context project '${key}' has no work branch`);\n\t}\n\tconst workspacePath = resolveSafeProjectWorkspacePath(key);\n\treturn {\n\t\tkey,\n\t\tworkspaceClonePath: workspacePath.workspaceClonePath,\n\t\tfsPath:\n\t\t\ttypeof input.workspaceRoot === \"string\" && input.workspaceRoot.trim() !== \"\"\n\t\t\t\t? safeJoinInside(\n\t\t\t\t\t\tinput.workspaceRoot,\n\t\t\t\t\t\tworkspacePath.relativePath,\n\t\t\t\t\t\t`Flow context project '${key}' workspace path`,\n\t\t\t\t\t)\n\t\t\t\t: workspacePath.workspaceClonePath,\n\t\tbaseBranch,\n\t\tworkBranch,\n\t\tlocator: project.repoLocator,\n\t};\n}\n\nfunction createFlowRepoLookup(input: {\n\tprojects: readonly ProcessProject[];\n\tworkspaceRoot?: string;\n}): FlowRepoLookup {\n\treturn {\n\t\tget: (key) => resolveRepoByKey({ ...input, key, required: true }),\n\t\toptional: (key) => resolveRepoByKey({ ...input, key, required: false }),\n\t\tall: () =>\n\t\t\tinput.projects.map((project) =>\n\t\t\t\tresolveRepoByKey({ ...input, key: project.key, required: true }),\n\t\t\t),\n\t};\n}\n\nfunction createFlowContextBase<TParams, TState>(ctx: ProcessRuntimeTurnContext<TParams, TState>) {\n\tconst { process, projects, params, state, workspaceRoot } = ctx;\n\treturn {\n\t\tprocess,\n\t\tprojects,\n\t\tparams,\n\t\tstate,\n\t\t...(workspaceRoot ? { workspaceRoot } : {}),\n\t\trepo: createFlowRepoLookup({ projects, workspaceRoot }),\n\t};\n}\n\n/** @internal */\nexport function createFlowPromptContext<\n\tTParams,\n\tTState,\n\tTConsumedProducts extends string = string,\n\tTPrepared = undefined,\n>(\n\tctx: ProcessRuntimeTurnContext<TParams, TState>,\n\tconsumedProducts: readonly TConsumedProducts[],\n\toptionalConsumedProducts: readonly string[] = [],\n): FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> {\n\tconst productInput: Record<string, string> = {};\n\tfor (const productName of consumedProducts) {\n\t\tconst markdown = ctx.turnResultMarkdownByProduct?.[productName];\n\t\tif (typeof markdown !== \"string\" || markdown.trim() === \"\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Flow prompt context requires product '${productName}' markdown, but the worker payload did not provide it`,\n\t\t\t);\n\t\t}\n\t\tproductInput[productName] = markdown;\n\t}\n\tfor (const productName of optionalConsumedProducts) {\n\t\tif (productName in productInput) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst markdown = ctx.turnResultMarkdownByProduct?.[productName];\n\t\tif (typeof markdown === \"string\" && markdown.trim() !== \"\") {\n\t\t\tproductInput[productName] = markdown;\n\t\t}\n\t}\n\treturn {\n\t\t...createFlowContextBase(ctx),\n\t\tprompts: {\n\t\t\tinitial: readInitialPrompt(ctx.params),\n\t\t},\n\t\tinput: productInput as Partial<Record<TConsumedProducts, string>>,\n\t\tprepared: ctx.prepared as TPrepared,\n\t} as FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>;\n}\n\n/** @internal */\nexport function createFlowAutomaticRunContext<TParams, TState>(\n\tctx: ProcessRuntimeTurnContext<TParams, TState>,\n): FlowAutomaticRunContext<TParams, TState> {\n\treturn {\n\t\t...createFlowContextBase(ctx),\n\t\tcallIntegrationTool(name, args) {\n\t\t\tif (!ctx.callIntegrationTool) {\n\t\t\t\tthrow new Error(`Automatic integration tool '${name}' is unavailable`);\n\t\t\t}\n\t\t\treturn ctx.callIntegrationTool(name, args);\n\t\t},\n\t\treportProgress(report) {\n\t\t\tctx.reportProgress?.(report);\n\t\t},\n\t};\n}\n\nfunction wrapOutcomeCallback<TParams, TState, TResult>(\n\tcallback: (\n\t\tinput: FlowOutcomeEffectInput<TParams, TState, FlowOutcomeEffectContext<TParams, TState>>,\n\t) => TResult,\n): (execution: ProcessOutcomeExecution<TParams, TState>) => TResult {\n\treturn (execution) =>\n\t\tcallback({\n\t\t\tctx: {\n\t\t\t\tprocess: execution.ctx.process,\n\t\t\t\tprojects: execution.ctx.projects,\n\t\t\t\tparams: execution.ctx.params,\n\t\t\t\tstate: execution.ctx.state,\n\t\t\t\toutput:\n\t\t\t\t\ttypeof execution.event.turnResultMarkdown === \"string\"\n\t\t\t\t\t\t? { content: execution.event.turnResultMarkdown }\n\t\t\t\t\t\t: null,\n\t\t\t},\n\t\t\tevent: execution.event,\n\t\t\tturnId: execution.turnId,\n\t\t\toutcome: execution.outcome,\n\t\t});\n}\n\n/** @public */\nclass RouteAndEffectBuilder<TParams, TState, TContext> {\n\t/** @internal */\n\tprotected target: FlowTargetSpec = null;\n\t/** @internal */\n\tprotected flowEffect: FlowOutcomeEffect<TParams, TState, TContext> | undefined;\n\n\t/** @internal */\n\tprotected setTarget(next: FlowTargetSpec): this {\n\t\tif (this.target && next) {\n\t\t\tthrow new Error(\"Flow route already declares a target\");\n\t\t}\n\t\tthis.target = next;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\treturn this.setTarget({ kind: \"to\", turnId });\n\t}\n\n\t/** @public */\n\tcomplete(): this {\n\t\treturn this.setTarget({ kind: \"complete\" });\n\t}\n\n\t/** @public */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\treturn this.setTarget({ kind: \"lifecycleStatus\", status });\n\t}\n\n\t/** @internal */\n\tstay(): this {\n\t\tthis.target = null;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tstate(fn: FlowOutcomeStateEffect<TParams, TState, TContext>): this {\n\t\tthis.flowEffect = async (input) => ({ state: await fn(input) });\n\t\treturn this;\n\t}\n\n\t/** @public */\n\teffect(fn: FlowOutcomeEffect<TParams, TState, TContext>): this {\n\t\tthis.flowEffect = fn;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\thasRoute(): boolean {\n\t\treturn this.target !== null;\n\t}\n\n\t/** @internal */\n\tprotected buildRouteTarget(): {\n\t\t/** @internal */\n\t\tto?: TurnId;\n\t\t/** @internal */\n\t\tcomplete?: boolean;\n\t\t/** @internal */\n\t\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n\t} {\n\t\treturn buildRouteTargetSpec(this.target);\n\t}\n}\n\n/** @internal */\nexport type FlowTargetSpec =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"to\";\n\t\t\t/** @internal */\n\t\t\tturnId: TurnId;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"complete\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"lifecycleStatus\";\n\t\t\t/** @internal */\n\t\t\tstatus: ProcessTurnTerminalLifecycleStatus;\n\t }\n\t| null;\n\nexport function buildRouteTargetSpec(target: FlowTargetSpec): {\n\t/** @internal */\n\tto?: TurnId;\n\t/** @internal */\n\tcomplete?: boolean;\n\t/** @internal */\n\tlifecycleStatus?: ProcessTurnTerminalLifecycleStatus;\n} {\n\tif (!target) {\n\t\treturn {};\n\t}\n\tif (target.kind === \"to\") {\n\t\treturn { to: target.turnId };\n\t}\n\tif (target.kind === \"complete\") {\n\t\treturn { complete: true };\n\t}\n\treturn { lifecycleStatus: target.status };\n}\n\n/** @public */\ninterface ParameterOptions extends Partial<Omit<OutcomeToolParameterSpec, \"type\" | \"description\">> {\n\t/** @public */\n\tdescription?: string;\n\t/** @internal */\n\trequiredErrorCode?: string;\n}\n\n/** @public */\ninterface ArrayParameterOptions extends ParameterOptions {\n\t/** @public */\n\titems?: OutcomeToolParameterSpec[\"items\"];\n}\n\n/** @internal */\ninterface EnumParameterOptions extends ParameterOptions {\n\t/** @internal */\n\tvalues?: readonly string[];\n}\n\n/** @public */\ninterface MarkdownParameterOptions extends ParameterOptions {\n\t/** @public */\n\tpublish?: true;\n}\n\nfunction isStringArray(value: unknown): value is readonly string[] {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/** @public */\nclass ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEffectBuilder<\n\tTParams,\n\tTState,\n\tTContext\n> {\n\t/** @internal */\n\tprotected outcomeDescription: string | null = null;\n\t/** @internal */\n\tprotected parameters: Record<string, OutcomeToolParameterSpec> = {};\n\t/** @internal */\n\tprotected publishedMarkdownParameter: string | null = null;\n\t/** @internal */\n\tprotected summaryParameter: string | null = null;\n\n\t/** Optional concise result publication, separate from the full Markdown. @public */\n\tresultSummary(name = \"resultSummary\"): this {\n\t\tthis.summaryParameter = name;\n\t\treturn this.parameter(name, {\n\t\t\ttype: \"string\",\n\t\t\tdescription: \"Concise summary of this attempt’s outcome.\",\n\t\t});\n\t}\n\n\t/** @internal */\n\tprotected buildParameterSpec(kind: string): ProcessToolOutcomeSpec<TParams, TState> {\n\t\tif (!this.outcomeDescription) throw new Error(`${kind} must declare .description(...)`);\n\t\treturn {\n\t\t\tdescription: this.outcomeDescription,\n\t\t\tparameters: this.parameters,\n\t\t\t...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),\n\t\t\t...(this.publishedMarkdownParameter\n\t\t\t\t? {\n\t\t\t\t\t\tpublishedProduct: this.publishedMarkdownParameter,\n\t\t\t\t\t\tturnResultMarkdownParameter: this.publishedMarkdownParameter,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\t/** @public */\n\tdescription(text: string): this {\n\t\tthis.outcomeDescription = text;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tparameter(name: string, spec: OutcomeToolParameterSpec): this {\n\t\tif (name.trim() === \"\") {\n\t\t\tthrow new Error(\"Outcome parameter name must be non-empty\");\n\t\t}\n\t\tthis.parameters[name] = {\n\t\t\t...spec,\n\t\t\tdescription: spec.description ?? \"\",\n\t\t};\n\t\treturn this;\n\t}\n\n\tprivate withRequired(\n\t\tname: string,\n\t\toptions: string | ParameterOptions,\n\t): ParameterOptions & { description?: string } {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\treturn {\n\t\t\t...resolved,\n\t\t\trequired: true,\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? toRequiredErrorCode(name),\n\t\t};\n\t}\n\n\tprivate typedParameter(\n\t\tname: string,\n\t\ttype: OutcomeToolParameterSpec[\"type\"],\n\t\toptions: string | ArrayParameterOptions = {},\n\t): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\treturn this.parameter(name, {\n\t\t\t...resolved,\n\t\t\ttype,\n\t\t\tdescription: resolved.description ?? \"\",\n\t\t\t...(type === \"array\" ? { items: resolved.items ?? { type: \"string\" } } : {}),\n\t\t});\n\t}\n\n\t/** @internal */\n\tstring(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"string\", options);\n\t}\n\n\t/** @public */\n\tmarkdown(name: string, options: string | MarkdownParameterOptions = {}): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\tconst { publish, ...parameterOptions } = resolved;\n\t\tif (publish) {\n\t\t\tif (this.publishedMarkdownParameter && this.publishedMarkdownParameter !== name) {\n\t\t\t\tthrow new Error(\"Outcome can publish only one markdown parameter\");\n\t\t\t}\n\t\t\tnormalizeProductName(name);\n\t\t\tthis.publishedMarkdownParameter = name;\n\t\t}\n\t\treturn this.typedParameter(name, \"string\", {\n\t\t\t...parameterOptions,\n\t\t\trequired: publish ? true : resolved.required,\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : undefined),\n\t\t});\n\t}\n\n\t/** @public */\n\trequiredString(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"string\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tnumber(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"number\", options);\n\t}\n\n\t/** @internal */\n\trequiredNumber(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"number\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tboolean(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"boolean\", options);\n\t}\n\n\t/** @internal */\n\trequiredBoolean(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"boolean\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tstringArray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"array\", options);\n\t}\n\n\t/** @internal */\n\trequiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"array\", this.withRequired(name, options));\n\t}\n\n\t/** @internal */\n\tenum(name: string, valuesOrOptions: readonly string[] | EnumParameterOptions): this {\n\t\tconst resolved: EnumParameterOptions = isStringArray(valuesOrOptions)\n\t\t\t? { values: [...valuesOrOptions] }\n\t\t\t: valuesOrOptions;\n\t\tconst { values = [], ...options } = resolved;\n\t\treturn this.parameter(name, {\n\t\t\t...options,\n\t\t\ttype: \"string\",\n\t\t\tdescription: options.description ?? \"\",\n\t\t\tenum: [...values],\n\t\t});\n\t}\n\n\t/** @public */\n\tobject(name: string, options: string | ParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"object\", options);\n\t}\n\n\t/** @internal */\n\tarray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"array\", options);\n\t}\n\n\t/** @public */\n\trequiredArray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\treturn this.typedParameter(name, \"array\", this.withRequired(name, options));\n\t}\n}\n\n/** @public */\nexport class OutcomeToolBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n> extends ParameterizedOutcomeBuilder<\n\tTParams,\n\tTState,\n\tFlowLlmOutcomeEffectContext<TParams, TState>\n> {\n\tprivate stateRouting:\n\t\t| {\n\t\t\t\tbranches: Record<string, TurnId>;\n\t\t\t\tchoose: (\n\t\t\t\t\tinput: FlowOutcomeEffectInput<\n\t\t\t\t\t\tTParams,\n\t\t\t\t\t\tTState,\n\t\t\t\t\t\tFlowLlmOutcomeEffectContext<TParams, TState>\n\t\t\t\t\t>,\n\t\t\t\t) => MaybePromise<string>;\n\t\t }\n\t\t| undefined;\n\n\t/** @public */\n\trouteByState(\n\t\tbranches: Record<string, TurnId>,\n\t\tchoose: (\n\t\t\tinput: FlowOutcomeEffectInput<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>,\n\t\t) => MaybePromise<string>,\n\t): this {\n\t\tif (this.hasRoute() || this.stateRouting) {\n\t\t\tthrow new Error(\"State-routed outcome cannot declare another route\");\n\t\t}\n\t\tif (Object.keys(branches).length === 0) {\n\t\t\tthrow new Error(\"State-routed outcome must declare at least one branch\");\n\t\t}\n\t\tthis.stateRouting = { branches, choose };\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessToolOutcomeSpec<TParams, TState> {\n\t\tconst parameters = this.buildParameterSpec(\"LLM outcome tool\");\n\t\tif (this.stateRouting && this.hasRoute()) {\n\t\t\tthrow new Error(\"State-routed outcome cannot declare another route\");\n\t\t}\n\t\tconst stateRouting = this.stateRouting;\n\t\treturn {\n\t\t\t...parameters,\n\t\t\t...(stateRouting\n\t\t\t\t? {\n\t\t\t\t\t\tbranches: Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(stateRouting.branches).map(([branchId, turnId]) => [\n\t\t\t\t\t\t\t\tbranchId,\n\t\t\t\t\t\t\t\t{ to: turnId },\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tchoose: wrapOutcomeCallback((input) => stateRouting.choose(input)),\n\t\t\t\t\t}\n\t\t\t\t: this.buildRouteTarget()),\n\t\t\t...(this.flowEffect ? { effect: wrapOutcomeCallback(this.flowEffect) } : {}),\n\t\t};\n\t}\n}\n\n/** @public */\nexport class AutomaticOutcomeBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n> extends ParameterizedOutcomeBuilder<\n\tTParams,\n\tTState,\n\tFlowAutomaticOutcomeEffectContext<TParams, TState>\n> {\n\tprivate waits = false;\n\n\t/** @public */\n\twait(): this {\n\t\tif (this.hasRoute()) throw new Error(\"Waiting outcome cannot declare another route\");\n\t\tthis.waits = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessToolOutcomeSpec<TParams, TState> {\n\t\tconst parameters = this.buildParameterSpec(\"Automatic outcome\");\n\t\tconst configuredEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;\n\t\tconst effect = this.waits\n\t\t\t? async (\n\t\t\t\t\texecution: Parameters<NonNullable<ProcessToolOutcomeSpec<TParams, TState>[\"effect\"]>>[0],\n\t\t\t\t) => {\n\t\t\t\t\tconst result = configuredEffect ? await configuredEffect(execution) : undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...result,\n\t\t\t\t\t\tprocessPatch: { ...(result?.processPatch ?? {}), lifecycleStatus: \"waiting\" as const },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t: configuredEffect;\n\t\treturn {\n\t\t\t...parameters,\n\t\t\t...this.buildRouteTarget(),\n\t\t\t...(effect ? { effect } : {}),\n\t\t};\n\t}\n}\n\n/** @internal */\nexport class PlanResultBuilder<TParams = unknown, TState = unknown> extends RouteAndEffectBuilder<\n\tTParams,\n\tTState,\n\tFlowLlmOutcomeEffectContext<TParams, TState>\n> {\n\tprivate resultDescription = \"The candidate plan is ready for operator review\";\n\tprivate summarySpec: OutcomeToolParameterSpec | null = null;\n\tprivate acceptanceCriteriaSpec: OutcomeToolParameterSpec | null = null;\n\tprivate reviewTurnId: TurnId | null = null;\n\n\t/** @internal */\n\tdescription(text: string): this {\n\t\tthis.resultDescription = text;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tsummary(options: string | PlanFieldOptions = {}): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\tthis.summarySpec = textField({\n\t\t\tdescription: resolved.description ?? \"Short summary of the proposed plan\",\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? \"summary_required\",\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tacceptanceCriteria(options: string | PlanAcceptanceCriteriaOptions = {}): this {\n\t\tconst resolved = typeof options === \"string\" ? { description: options } : options;\n\t\tthis.acceptanceCriteriaSpec = stringArrayField({\n\t\t\tdescription: resolved.description ?? \"Acceptance criteria for the requested change\",\n\t\t\trequiredErrorCode: resolved.requiredErrorCode ?? \"acceptance_criteria_required\",\n\t\t\tminItems: resolved.minItems ?? 1,\n\t\t\tminItemsErrorCode: resolved.minItemsErrorCode ?? \"acceptance_criteria_required\",\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\treview(turnId: TurnId): this {\n\t\tthis.reviewTurnId = turnId;\n\t\treturn this.setTarget({ kind: \"to\", turnId });\n\t}\n\n\t/** @internal */\n\tbuildOutcome(): ProcessToolOutcomeSpec<TParams, TState> {\n\t\tif (!this.summarySpec) {\n\t\t\tthrow new Error(\"plan result must declare .summary(...)\");\n\t\t}\n\t\tif (!this.acceptanceCriteriaSpec) {\n\t\t\tthrow new Error(\"plan result must declare .acceptanceCriteria(...)\");\n\t\t}\n\t\tif (!this.reviewTurnId) {\n\t\t\tthrow new Error(\"plan result must declare .review(turnId)\");\n\t\t}\n\t\tconst stateEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;\n\t\treturn {\n\t\t\tdescription: this.resultDescription,\n\t\t\tparameters: {\n\t\t\t\tsummary: this.summarySpec,\n\t\t\t\tacceptanceCriteria: this.acceptanceCriteriaSpec,\n\t\t\t},\n\t\t\tto: this.reviewTurnId,\n\t\t\tlifecycleIntent: {\n\t\t\t\tkind: \"save_plan_result\",\n\t\t\t\tsummaryParam: \"summary\",\n\t\t\t\tacceptanceCriteriaParam: \"acceptanceCriteria\",\n\t\t\t\tplanMarkdownParam: \"planMarkdown\",\n\t\t\t\temitEventType: DEFAULT_PLAN_RESULT_OUTCOME_ID,\n\t\t\t\tbroadcastType: \"plan.updated\",\n\t\t\t\t...(stateEffect ? { state: stateEffect } : {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** @public */\nabstract class TurnEndBuilder<TParams, TState>\n\textends RouteAndEffectBuilder<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>\n\timplements FlowLlmTurn<TParams, TState, string>\n{\n\t/** @internal */\n\tprotected abstract readonly builderName: string;\n\n\t/** @internal */\n\tconstructor(\n\t\tprivate readonly outcomeId: string,\n\t\tprivate readonly parent?: FlowLlmTurn<TParams, TState, string>,\n\t) {\n\t\tsuper();\n\t}\n\n\tprivate get turn(): FlowLlmTurn<TParams, TState, string> {\n\t\tif (!this.parent) throw new Error(`${this.builderName} builder is not attached to a turn`);\n\t\treturn this.parent;\n\t}\n\n\t/** @internal */\n\tget id(): TurnId {\n\t\treturn this.turn.id;\n\t}\n\n\t/** @internal */\n\tget definition(): LlmTurnDefinition<string, TParams, TState> {\n\t\treturn this.turn.definition;\n\t}\n\n\t/** @internal */\n\tprotected buildResult(): ProcessTurnEndSpec<TParams, TState, string> {\n\t\tconst effect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;\n\t\treturn {\n\t\t\toutcome: this.outcomeId,\n\t\t\t...this.buildRouteTarget(),\n\t\t\t...(effect ? { effect } : {}),\n\t\t};\n\t}\n}\n\n/** @public */\nexport class PublishedResultBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<\n\tTParams,\n\tTState\n> {\n\t/** @internal */\n\tprotected readonly builderName = \"Published result\";\n\n\t/** @internal */\n\tbuildTurnEnd(): ProcessTurnEndSpec<TParams, TState, string> {\n\t\treturn this.buildResult();\n\t}\n}\n\n/** @public */\nexport class LlmTurnEndBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<\n\tTParams,\n\tTState\n> {\n\t/** @internal */\n\tprotected readonly builderName = \"LLM turn end\";\n\n\t/** @internal */\n\tconstructor(outcomeId: string, parent?: FlowLlmTurn<TParams, TState, string>) {\n\t\tsuper(outcomeId, parent);\n\t\tif (outcomeId.trim() === \"\") throw new Error(\"LLM turn end outcome must be non-empty\");\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessTurnEndSpec<TParams, TState, string> {\n\t\treturn this.buildResult();\n\t}\n}\n\n/** @public */\ntype LlmPromptBuilder<TParams, TState, TConsumedProducts extends string, TPrepared> = (\n\tctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>,\n) => MaybePromise<string>;\n\n/** @public */\nabstract class DescribedTurnBuilder {\n\t/** @internal */\n\tprotected turnDescription: string | null = null;\n\n\t/** @internal */\n\tconstructor(\n\t\t/** @internal */\n\t\tprotected readonly turnId: TurnId,\n\t) {}\n\n\t/** @internal */\n\tget id(): TurnId {\n\t\treturn this.turnId;\n\t}\n\n\t/** @public */\n\tdescription(description: string): this {\n\t\tthis.turnDescription = description;\n\t\treturn this;\n\t}\n}\n\n/** @public */\nexport class LlmFlowBuilder<\n\t\tTParams = unknown,\n\t\tTState = unknown,\n\t\tTConsumedProducts extends string = never,\n\t\tTPrepared = undefined,\n\t>\n\textends DescribedTurnBuilder\n\timplements FlowLlmTurn<TParams, TState, string>\n{\n\tprivate modelPurposeValue: LlmModelPurpose | undefined;\n\tprivate availableTools: readonly PiBuiltInToolName[] = [];\n\tprivate availableIntegrationTools: readonly string[] = [];\n\tprivate integrationToolResolver:\n\t\t| ((params: TParams, state: TState) => readonly string[])\n\t\t| undefined;\n\tprivate preparation:\n\t\t| ((ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<unknown>)\n\t\t| null = null;\n\tprivate promptBuilder:\n\t\t| ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>)\n\t\t| null = null;\n\tprivate branchType: LlmTurnDefinition<string, TParams, TState>[\"branchType\"] = \"primary\";\n\tprivate context: LlmTurnDefinition<string, TParams, TState>[\"context\"] = \"fresh\";\n\tprivate questionsEnabled = false;\n\tprivate startFrom: LlmTurnDefinition<string, TParams, TState>[\"startFrom\"] | undefined;\n\tprivate restorePrimaryLeafAfterTurn: boolean | undefined;\n\tprivate readonly consumedProductNames = new Set<string>();\n\tprivate readonly optionalConsumedProductNames = new Set<string>();\n\tprivate publishedResult: {\n\t\tproductName: string;\n\t\tbuilder: PublishedResultBuilder<TParams, TState>;\n\t} | null = null;\n\tprivate endResult: LlmTurnEndBuilder<TParams, TState> | null = null;\n\tprivate outcomeToolBuilders = new Map<string, OutcomeToolBuilder<TParams, TState>>();\n\tprivate mapped: {\n\t\toptions: FlowForEachOptions<TParams, TState, unknown, unknown>;\n\t\tyields: Map<string, MappedItemYield<TParams, TState, unknown, unknown>>;\n\t\tcollect?: MappedCollect<TParams, TState, unknown>;\n\t\trouting?: MappedCollectRouting<TParams, TState>;\n\t} | null = null;\n\n\t/** @internal */\n\tget definition(): LlmTurnDefinition<string, TParams, TState> {\n\t\treturn this.buildDefinition();\n\t}\n\n\t/**\n\t * Run this turn once per frozen item. Items run sequentially; each item's\n\t * outcome yields a typed result, and `collect` updates state and routes once.\n\t * @public\n\t */\n\tforEach<TItem, TResult>(\n\t\toptions: FlowForEachOptions<TParams, TState, TItem, TResult>,\n\t): MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TPrepared> {\n\t\tif (this.mapped) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares .forEach(...) more than once`);\n\t\t}\n\t\tif (this.outcomeToolBuilders.size > 0 || this.publishedResult || this.endResult) {\n\t\t\tthrow new Error(\n\t\t\t\t`LLM turn '${this.turnId}' must declare .forEach(...) before its completion path`,\n\t\t\t);\n\t\t}\n\t\tthis.mapped = {\n\t\t\toptions: options as FlowForEachOptions<TParams, TState, unknown, unknown>,\n\t\t\tyields: new Map(),\n\t\t};\n\t\treturn new MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TPrepared>(\n\t\t\tthis,\n\t\t);\n\t}\n\n\t/** @internal */\n\taddMappedOutcome(\n\t\tid: string,\n\t\tbuilder: OutcomeToolBuilder<TParams, TState>,\n\t\tyieldResult: MappedItemYield<TParams, TState, unknown, unknown>,\n\t): void {\n\t\tif (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);\n\t\tif (id.trim() === \"\") {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);\n\t\t}\n\t\tif (this.outcomeToolBuilders.has(id)) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);\n\t\t}\n\t\tthis.outcomeToolBuilders.set(id, builder);\n\t\tthis.mapped.yields.set(id, yieldResult);\n\t}\n\n\t/** @internal */\n\tsetMappedCollect(collect: MappedCollect<TParams, TState, unknown>): void {\n\t\tif (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);\n\t\tif (this.mapped.collect) {\n\t\t\tthrow new Error(`Mapped turn '${this.turnId}' declares .collect(...) more than once`);\n\t\t}\n\t\tthis.mapped.collect = collect;\n\t}\n\n\t/** @internal */\n\tsetMappedRouting(routing: MappedCollectRouting<TParams, TState>): void {\n\t\tif (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);\n\t\tif (this.mapped.routing) {\n\t\t\tthrow new Error(`Mapped turn '${this.turnId}' collection already declares a route`);\n\t\t}\n\t\tthis.mapped.routing = routing;\n\t}\n\n\tprivate mappedItemContext(\n\t\tctx: ProcessRuntimeTurnContext<TParams, TState>,\n\t): Partial<MappedTurnItemContext<unknown>> {\n\t\tif (!this.mapped) return {};\n\t\tconst iteration = ctx.iteration;\n\t\tif (!iteration) {\n\t\t\tthrow new Error(`Mapped turn '${this.turnId}' requires an active item`);\n\t\t}\n\t\treturn {\n\t\t\titem: this.mapped.options.itemCodec.parse(iteration.item),\n\t\t\titemKey: iteration.itemKey,\n\t\t\titemLabel: iteration.itemLabel,\n\t\t\titemIndex: iteration.itemIndex,\n\t\t\titemCount: iteration.itemCount,\n\t\t};\n\t}\n\n\tprivate buildMappedSpec(): MappedLlmTurnSpec<TParams, TState> | undefined {\n\t\tif (!this.mapped) return undefined;\n\t\tif (!this.mapped.collect) {\n\t\t\tthrow new Error(`Mapped turn '${this.turnId}' must declare .collect(...)`);\n\t\t}\n\t\tif (!this.mapped.routing) {\n\t\t\tthrow new Error(`Mapped turn '${this.turnId}' must declare a collection route`);\n\t\t}\n\t\treturn {\n\t\t\t...this.mapped.options,\n\t\t\tyields: Object.fromEntries(this.mapped.yields),\n\t\t\tcollect: this.mapped.collect,\n\t\t\trouting: this.mapped.routing,\n\t\t};\n\t}\n\n\t/** @internal */\n\tmodelPurpose(purpose: LlmModelPurpose): this {\n\t\tthis.modelPurposeValue = purpose;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\ttools(...tools: readonly PiBuiltInToolName[]): this {\n\t\tthis.availableTools = tools;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tintegrationTools(...tools: readonly string[]): this {\n\t\tthis.availableIntegrationTools = tools.map((tool) => tool.trim());\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tresolveIntegrationTools(resolver: (params: TParams, state: TState) => readonly string[]): this {\n\t\tthis.integrationToolResolver = resolver;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tprepare<TNextPrepared>(\n\t\tfn: (ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<TNextPrepared>,\n\t): LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared> {\n\t\tthis.preparation = fn;\n\t\treturn this as unknown as LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared>;\n\t}\n\n\t/** Enable durable operator questions for this LLM turn. @public */\n\taskQuestions(): this {\n\t\tthis.questionsEnabled = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tfreshPrimary(): this {\n\t\tthis.branchType = \"primary\";\n\t\tthis.context = \"fresh\";\n\t\tthis.startFrom = undefined;\n\t\tthis.restorePrimaryLeafAfterTurn = undefined;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tfreshSeededPrimary(): this {\n\t\tthis.branchType = \"primary\";\n\t\tthis.context = \"fresh_seeded\";\n\t\tthis.startFrom = undefined;\n\t\tthis.restorePrimaryLeafAfterTurn = undefined;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tfullPrimary(): this {\n\t\tthis.branchType = \"primary\";\n\t\tthis.context = \"full\";\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\trootBranchReview(): this {\n\t\tthis.branchType = \"root_branch\";\n\t\tthis.context = \"full\";\n\t\tthis.restorePrimaryLeafAfterTurn = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tcontinueFromPrimaryLeaf(): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"semantic_ref\",\n\t\t\tref: \"currentPrimaryPathLeaf\",\n\t\t\tfallback: { kind: \"current_leaf\" },\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcontinueFromReviewBranch(): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"semantic_ref\",\n\t\t\tref: \"review\",\n\t\t\tfallback: { kind: \"current_leaf\" },\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcontinueFromProductBranch(\n\t\tproductName: string,\n\t\tfallback: ProcessTurnStartSelection = { kind: \"current_leaf\" },\n\t): this {\n\t\treturn this.startFromProductBranch(productName, fallback);\n\t}\n\n\t/** @internal */\n\tstartFromReviewBranch(): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"semantic_ref\",\n\t\t\tref: \"review\",\n\t\t\tfallback: { kind: \"session_root\" },\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tstartFromProductBranch(\n\t\tproductName: string,\n\t\tfallback: ProcessTurnStartSelection = { kind: \"session_root\" },\n\t): this {\n\t\tthis.startFrom = {\n\t\t\tkind: \"product_ref\",\n\t\t\tproductName: normalizeProductName(productName),\n\t\t\tfallback,\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tstartFromRoot(): this {\n\t\tthis.startFrom = { kind: \"session_root\" };\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tconsume<TProductName extends string>(\n\t\tproductName: TProductName,\n\t): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {\n\t\tthis.consumedProductNames.add(normalizeProductName(productName));\n\t\treturn this as unknown as LlmFlowBuilder<\n\t\t\tTParams,\n\t\t\tTState,\n\t\t\tTConsumedProducts | TProductName,\n\t\t\tTPrepared\n\t\t>;\n\t}\n\n\t/** @public */\n\toptionalConsume<TProductName extends string>(\n\t\tproductName: TProductName,\n\t): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {\n\t\tthis.optionalConsumedProductNames.add(normalizeProductName(productName));\n\t\treturn this as unknown as LlmFlowBuilder<\n\t\t\tTParams,\n\t\t\tTState,\n\t\t\tTConsumedProducts | TProductName,\n\t\t\tTPrepared\n\t\t>;\n\t}\n\n\t/** @public */\n\tpublish(productName: string): PublishedResultBuilder<TParams, TState> {\n\t\tthis.assertNotMapped(\".publish(...)\");\n\t\tconst normalized = normalizeProductName(productName);\n\t\tif (this.publishedResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' can publish only one product in flow v1`);\n\t\t}\n\t\tif (this.endResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .publish(...) and .end(...)`);\n\t\t}\n\t\tconst builder = new PublishedResultBuilder<TParams, TState>(normalized, this);\n\t\tthis.publishedResult = { productName: normalized, builder };\n\t\treturn builder;\n\t}\n\n\t/** @public */\n\tend(outcomeId: string): LlmTurnEndBuilder<TParams, TState> {\n\t\tthis.assertNotMapped(\".end(...)\");\n\t\tif (this.endResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares duplicate .end(...) completion`);\n\t\t}\n\t\tif (this.publishedResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .publish(...) and .end(...)`);\n\t\t}\n\t\tif (this.outcomeToolBuilders.size > 0) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .end(...) and outcome tools`);\n\t\t}\n\t\tthis.endResult = new LlmTurnEndBuilder<TParams, TState>(outcomeId, this);\n\t\treturn this.endResult;\n\t}\n\n\t/** @public */\n\tbuildPrompt(fn: LlmPromptBuilder<TParams, TState, TConsumedProducts, TPrepared>): this {\n\t\tthis.promptBuilder = (ctx) =>\n\t\t\tfn({\n\t\t\t\t...createFlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>(\n\t\t\t\t\tctx,\n\t\t\t\t\t[...this.consumedProductNames] as TConsumedProducts[],\n\t\t\t\t\t[...this.optionalConsumedProductNames],\n\t\t\t\t),\n\t\t\t\t...this.mappedItemContext(ctx),\n\t\t\t});\n\t\treturn this;\n\t}\n\n\tprivate assertNotMapped(feature: string): void {\n\t\tif (this.mapped) {\n\t\t\tthrow new Error(\n\t\t\t\t`Mapped turn '${this.turnId}' cannot declare ${feature}; items yield results and .collect(...) routes`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/** @public */\n\tprompt(prompt: (ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>): this {\n\t\tthis.promptBuilder = prompt;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\toutcomeTool(\n\t\tid: string,\n\t\tconfigure: (\n\t\t\ttool: OutcomeToolBuilder<TParams, TState>,\n\t\t) => OutcomeToolBuilder<TParams, TState> | undefined,\n\t): this {\n\t\tthis.assertNotMapped(\"routed outcome tools\");\n\t\tif (id.trim() === \"\") {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);\n\t\t}\n\t\tif (this.endResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare both .end(...) and outcome tools`);\n\t\t}\n\t\tif (this.publishedResult) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare outcome tools after .publish(...)`);\n\t\t}\n\t\tif (this.outcomeToolBuilders.has(id)) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);\n\t\t}\n\t\tconst builder = new OutcomeToolBuilder<TParams, TState>();\n\t\tconfigure(builder);\n\t\tthis.outcomeToolBuilders.set(id, builder);\n\t\treturn this;\n\t}\n\n\tprivate buildBaseDefinition() {\n\t\tif (!this.turnDescription) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' must declare .description(...)`);\n\t\t}\n\t\tconst prompt = this.promptBuilder;\n\t\tif (!prompt) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);\n\t\t}\n\t\tconst preparation = this.preparation;\n\t\treturn {\n\t\t\tkind: \"llm\" as const,\n\t\t\tdescription: this.turnDescription,\n\t\t\t...(this.modelPurposeValue ? { modelPurpose: this.modelPurposeValue } : {}),\n\t\t\tavailableTools: this.availableTools,\n\t\t\t...(this.availableIntegrationTools.length > 0\n\t\t\t\t? { integrationTools: this.availableIntegrationTools }\n\t\t\t\t: {}),\n\t\t\t...(this.integrationToolResolver\n\t\t\t\t? { resolveIntegrationTools: this.integrationToolResolver }\n\t\t\t\t: {}),\n\t\t\t...(this.questionsEnabled ? { askQuestions: true as const } : {}),\n\t\t\t...(preparation\n\t\t\t\t? {\n\t\t\t\t\t\tprepare: (ctx: ProcessRuntimeTurnContext<TParams, TState>) =>\n\t\t\t\t\t\t\tpreparation({\n\t\t\t\t\t\t\t\t...createFlowAutomaticRunContext(ctx),\n\t\t\t\t\t\t\t\t...this.mappedItemContext(ctx),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tcompletionMode: \"turn_end\" as const,\n\t\t\tbranchType: this.branchType,\n\t\t\tcontext: this.context,\n\t\t\t...(this.startFrom ? { startFrom: this.startFrom } : {}),\n\t\t\t...(this.restorePrimaryLeafAfterTurn !== undefined\n\t\t\t\t? { restorePrimaryLeafAfterTurn: this.restorePrimaryLeafAfterTurn }\n\t\t\t\t: {}),\n\t\t\tprompt,\n\t\t};\n\t}\n\n\t/** @internal */\n\tproducesPlan(\n\t\tconfigure: (plan: PlanResultBuilder<TParams, TState>) => PlanResultBuilder<TParams, TState>,\n\t): FlowLlmTurn<TParams, TState, typeof DEFAULT_PLAN_RESULT_OUTCOME_ID> {\n\t\tconst definition = this.buildBaseDefinition();\n\t\tconst plan = configure(new PlanResultBuilder<TParams, TState>());\n\t\tconst outcome = plan.buildOutcome();\n\t\treturn {\n\t\t\tid: this.turnId,\n\t\t\tdefinition: {\n\t\t\t\t...definition,\n\t\t\t\toutcomes: {\n\t\t\t\t\t[DEFAULT_PLAN_RESULT_OUTCOME_ID]: outcome,\n\t\t\t\t},\n\t\t\t\tturnResultMarkdown: OUTCOME_TOOL_ARGUMENT_TURN_RESULT,\n\t\t\t\tresultSemanticRef: \"plan\",\n\t\t\t\tpublishedProduct: \"plan\",\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate buildDefinition(): LlmTurnDefinition<string, TParams, TState> {\n\t\tconst definition = this.buildBaseDefinition();\n\t\tconst hasOutcomeTools = this.outcomeToolBuilders.size > 0;\n\t\tconst explicitTurnEnd = this.endResult;\n\t\tconst published = this.publishedResult;\n\t\tconst outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};\n\t\tfor (const [outcomeId, builder] of this.outcomeToolBuilders) {\n\t\t\toutcomes[outcomeId] = builder.build();\n\t\t}\n\t\tconst outcomePublishedProducts = new Set(\n\t\t\tObject.values(outcomes)\n\t\t\t\t.map((outcome) => outcome.publishedProduct)\n\t\t\t\t.filter((productName): productName is string => typeof productName === \"string\"),\n\t\t);\n\t\tconst hasOutcomePublishedProduct = outcomePublishedProducts.size > 0;\n\t\tlet turnEnd: ProcessTurnEndSpec<TParams, TState, string> | undefined;\n\t\tlet resultSemanticRef: \"plan\" | \"review\" | undefined = outcomePublishedProducts.has(\"review\")\n\t\t\t? \"review\"\n\t\t\t: outcomePublishedProducts.has(\"plan\")\n\t\t\t\t? \"plan\"\n\t\t\t\t: undefined;\n\t\tlet turnResultMarkdown: LlmTurnDefinition<string, TParams, TState>[\"turnResultMarkdown\"];\n\t\tlet publishedProduct: string | undefined;\n\n\t\tif (published) {\n\t\t\tpublishedProduct = published.productName;\n\t\t\tif (published.productName === \"plan\") {\n\t\t\t\tresultSemanticRef = \"plan\";\n\t\t\t}\n\t\t\tif (published.productName === \"review\") {\n\t\t\t\tresultSemanticRef = \"review\";\n\t\t\t}\n\t\t\tconst publishHasRoute = published.builder.hasRoute();\n\t\t\tif (publishHasRoute && hasOutcomeTools) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`LLM turn '${this.turnId}' cannot route published product '${published.productName}' and declare outcome tools in flow v1`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (publishHasRoute && !hasOutcomeTools) {\n\t\t\t\tturnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;\n\t\t\t\tturnEnd = published.builder.buildTurnEnd();\n\t\t\t}\n\t\t\tif (!publishHasRoute && hasOutcomeTools) {\n\t\t\t\tturnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;\n\t\t\t}\n\t\t\tif (!publishHasRoute && !hasOutcomeTools) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`LLM turn '${this.turnId}' publishes product '${published.productName}' but declares no route or outcome tool completion path`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (hasOutcomeTools && !hasOutcomePublishedProduct) {\n\t\t\tturnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;\n\t\t} else if (explicitTurnEnd) {\n\t\t\tturnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;\n\t\t}\n\n\t\tif (hasOutcomeTools) {\n\t\t\tfor (const [outcomeId, outcome] of Object.entries(outcomes)) {\n\t\t\t\tif (OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME in outcome.parameters) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`LLM turn '${this.turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME}'`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (explicitTurnEnd) {\n\t\t\tif (turnEnd || Object.keys(outcomes).length > 0) {\n\t\t\t\tthrow new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);\n\t\t\t}\n\t\t\tturnEnd = explicitTurnEnd.build();\n\t\t}\n\t\tif (Object.keys(outcomes).length === 0 && !turnEnd) {\n\t\t\tthrow new Error(`LLM turn '${this.turnId}' must declare a completion path`);\n\t\t}\n\t\tconst forEach = this.buildMappedSpec();\n\n\t\treturn {\n\t\t\t...definition,\n\t\t\t...(forEach ? { forEach } : {}),\n\t\t\t...(Object.keys(outcomes).length > 0 ? { outcomes } : {}),\n\t\t\t...(turnEnd ? { turnEnd } : {}),\n\t\t\t...(turnResultMarkdown ? { turnResultMarkdown } : {}),\n\t\t\t...(resultSemanticRef ? { resultSemanticRef } : {}),\n\t\t\t...(publishedProduct ? { publishedProduct } : {}),\n\t\t\t...(this.consumedProductNames.size > 0\n\t\t\t\t? { consumedProducts: [...this.consumedProductNames] }\n\t\t\t\t: {}),\n\t\t\t...(this.optionalConsumedProductNames.size > 0\n\t\t\t\t? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }\n\t\t\t\t: {}),\n\t\t};\n\t}\n}\n\n/** Item selection for `flow.llm(...).forEach(...)`. @public */\nexport type FlowForEachOptions<TParams, TState, TItem, TResult> = Pick<\n\tMappedLlmTurnSpec<TParams, TState, TItem, TResult>,\n\t\"items\" | \"itemCodec\" | \"resultCodec\" | \"key\" | \"label\" | \"stateAfterSnapshot\"\n>;\n\n/** @public */\nexport type FlowMappedPromptContext<\n\tTParams,\n\tTState,\n\tTItem,\n\tTConsumedProducts extends string,\n\tTPrepared,\n> = FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> & MappedTurnItemContext<TItem>;\n\n/** @public */\nexport type FlowMappedPreparationContext<TParams, TState, TItem> = FlowLlmPreparationContext<\n\tTParams,\n\tTState\n> &\n\tMappedTurnItemContext<TItem>;\n\n/**\n * Outcome of one mapped item. It declares parameters and yields the item's\n * result; it cannot route, change process state, or publish products.\n * @public\n */\nexport class MappedOutcomeBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n\tTItem = unknown,\n\tTResult = unknown,\n> {\n\tprivate readonly tool = new OutcomeToolBuilder<TParams, TState>();\n\tprivate yieldResult: MappedItemYield<TParams, TState, TItem, TResult> | null = null;\n\n\t/** @public */\n\tdescription(text: string): this {\n\t\tthis.tool.description(text);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tresultSummary(name?: string): this {\n\t\tthis.tool.resultSummary(name);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\trequiredString(name: string, options: string | ParameterOptions = {}): this {\n\t\tthis.tool.requiredString(name, options);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tstring(name: string, options: string | ParameterOptions = {}): this {\n\t\tthis.tool.string(name, options);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\trequiredNumber(name: string, options: string | ParameterOptions = {}): this {\n\t\tthis.tool.requiredNumber(name, options);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\trequiredBoolean(name: string, options: string | ParameterOptions = {}): this {\n\t\tthis.tool.requiredBoolean(name, options);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\trequiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\tthis.tool.requiredStringArray(name, options);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tobject(name: string, options: string | ParameterOptions = {}): this {\n\t\tthis.tool.object(name, options);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\trequiredArray(name: string, options: string | ArrayParameterOptions = {}): this {\n\t\tthis.tool.requiredArray(name, options);\n\t\treturn this;\n\t}\n\n\t/** Map this outcome to the item's typed result. @public */\n\tyield(fn: MappedItemYield<TParams, TState, TItem, TResult>): this {\n\t\tthis.yieldResult = fn;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): {\n\t\t/** @internal */\n\t\ttool: OutcomeToolBuilder<TParams, TState>;\n\t\t/** @internal */\n\t\tyieldResult: MappedItemYield<TParams, TState, TItem, TResult>;\n\t} {\n\t\tif (!this.yieldResult) {\n\t\t\tthrow new Error(\"Mapped outcome must declare .yield(...)\");\n\t\t}\n\t\treturn { tool: this.tool, yieldResult: this.yieldResult };\n\t}\n}\n\n/** @public */\nabstract class MappedTurnFacade<TParams, TState> implements FlowLlmTurn<TParams, TState, string> {\n\t/** @internal */\n\tconstructor(\n\t\t/** @internal */\n\t\tprotected readonly base: LlmFlowBuilder<TParams, TState, string, unknown>,\n\t) {}\n\n\t/** @internal */\n\tget id(): TurnId {\n\t\treturn this.base.id;\n\t}\n\n\t/** @internal */\n\tget definition(): LlmTurnDefinition<string, TParams, TState> {\n\t\treturn this.base.definition;\n\t}\n}\n\n/**\n * Routes a mapped turn once, after all item results are collected.\n * @public\n */\nexport class MappedCollectBuilder<TParams = unknown, TState = unknown> extends MappedTurnFacade<\n\tTParams,\n\tTState\n> {\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\tthis.base.setMappedRouting({ kind: \"static\", to: turnId });\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tcomplete(): this {\n\t\tthis.base.setMappedRouting({ kind: \"static\", lifecycleStatus: \"completed\" });\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\tthis.base.setMappedRouting({ kind: \"static\", lifecycleStatus: status });\n\t\treturn this;\n\t}\n\n\t/** Choose the next turn from the collected state. @public */\n\trouteByState(\n\t\tbranches: Record<string, TurnId>,\n\t\tchoose: (ctx: MappedTurnServerContext<TParams, TState>) => MaybePromise<string>,\n\t): this {\n\t\tif (Object.keys(branches).length === 0) {\n\t\t\tthrow new Error(\"Mapped collection routing must declare at least one branch\");\n\t\t}\n\t\tthis.base.setMappedRouting({ kind: \"branches\", branches: { ...branches }, choose });\n\t\treturn this;\n\t}\n}\n\n/**\n * LLM turn that runs once per frozen item. Business state and routing belong\n * to `.collect(...)`.\n * @public\n */\nexport class MappedLlmFlowBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n\tTItem = unknown,\n\tTResult = unknown,\n\tTConsumedProducts extends string = never,\n\tTPrepared = undefined,\n> extends MappedTurnFacade<TParams, TState> {\n\t/** @internal */\n\tconstructor(base: LlmFlowBuilder<TParams, TState, TConsumedProducts, TPrepared>) {\n\t\tsuper(base as unknown as LlmFlowBuilder<TParams, TState, string, unknown>);\n\t}\n\n\t/** @public */\n\tdescription(description: string): this {\n\t\tthis.base.description(description);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\ttools(...tools: readonly PiBuiltInToolName[]): this {\n\t\tthis.base.tools(...tools);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tintegrationTools(...tools: readonly string[]): this {\n\t\tthis.base.integrationTools(...tools);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tfreshPrimary(): this {\n\t\tthis.base.freshPrimary();\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tconsume<TProductName extends string>(\n\t\tproductName: TProductName,\n\t): MappedLlmFlowBuilder<\n\t\tTParams,\n\t\tTState,\n\t\tTItem,\n\t\tTResult,\n\t\tTConsumedProducts | TProductName,\n\t\tTPrepared\n\t> {\n\t\tthis.base.consume(productName);\n\t\treturn this as unknown as MappedLlmFlowBuilder<\n\t\t\tTParams,\n\t\t\tTState,\n\t\t\tTItem,\n\t\t\tTResult,\n\t\t\tTConsumedProducts | TProductName,\n\t\t\tTPrepared\n\t\t>;\n\t}\n\n\t/** Deterministic worker preparation for the active item. @public */\n\tprepare<TNextPrepared>(\n\t\tfn: (ctx: FlowMappedPreparationContext<TParams, TState, TItem>) => MaybePromise<TNextPrepared>,\n\t): MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TNextPrepared> {\n\t\tthis.base.prepare((ctx) => fn(ctx as FlowMappedPreparationContext<TParams, TState, TItem>));\n\t\treturn this as unknown as MappedLlmFlowBuilder<\n\t\t\tTParams,\n\t\t\tTState,\n\t\t\tTItem,\n\t\t\tTResult,\n\t\t\tTConsumedProducts,\n\t\t\tTNextPrepared\n\t\t>;\n\t}\n\n\t/** Build the prompt for the active item. @public */\n\tbuildPrompt(\n\t\tfn: (\n\t\t\tctx: FlowMappedPromptContext<TParams, TState, TItem, TConsumedProducts, TPrepared>,\n\t\t) => MaybePromise<string>,\n\t): this {\n\t\tthis.base.buildPrompt((ctx) =>\n\t\t\tfn(\n\t\t\t\tctx as unknown as FlowMappedPromptContext<\n\t\t\t\t\tTParams,\n\t\t\t\t\tTState,\n\t\t\t\t\tTItem,\n\t\t\t\t\tTConsumedProducts,\n\t\t\t\t\tTPrepared\n\t\t\t\t>,\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\toutcomeTool(\n\t\tid: string,\n\t\tconfigure: (\n\t\t\toutcome: MappedOutcomeBuilder<TParams, TState, TItem, TResult>,\n\t\t) => MappedOutcomeBuilder<TParams, TState, TItem, TResult> | undefined,\n\t): this {\n\t\tconst outcome = new MappedOutcomeBuilder<TParams, TState, TItem, TResult>();\n\t\tconfigure(outcome);\n\t\tconst built = outcome.build();\n\t\tthis.base.addMappedOutcome(\n\t\t\tid,\n\t\t\tbuilt.tool,\n\t\t\tbuilt.yieldResult as MappedItemYield<TParams, TState, unknown, unknown>,\n\t\t);\n\t\treturn this;\n\t}\n\n\t/** Combine ordered item results into process state, once. @public */\n\tcollect(fn: MappedCollect<TParams, TState, TResult>): MappedCollectBuilder<TParams, TState> {\n\t\tthis.base.setMappedCollect(fn as MappedCollect<TParams, TState, unknown>);\n\t\treturn new MappedCollectBuilder<TParams, TState>(this.base);\n\t}\n}\n\ntype StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<\n\tTParams,\n\tTState,\n\tunknown,\n\tRecord<string, unknown>\n>;\n\n/** @public */\nabstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {\n\t/** @internal */\n\tprotected abstract readonly turnKind: \"Automatic\" | \"Human\";\n\tprivate externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();\n\n\t/** @public */\n\texternalAction<\n\t\tTEvent = unknown,\n\t\tTInput extends Record<string, unknown> = Record<string, unknown>,\n\t>(\n\t\texternalActionId: string,\n\t\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>,\n\t\tconfigure: (\n\t\t\texternal: ExternalActionBuilder<TParams, TState, TEvent, TInput>,\n\t\t) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,\n\t): this {\n\t\tif (this.externalActionBuilders.has(externalActionId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,\n\t\t\t);\n\t\t}\n\t\tconst builder = new ExternalActionBuilder(externalActionId, source);\n\t\tconfigure(builder);\n\t\tthis.externalActionBuilders.set(\n\t\t\texternalActionId,\n\t\t\tbuilder as unknown as StoredExternalActionBuilder<TParams, TState>,\n\t\t);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tprotected buildExternalActions():\n\t\t| Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>\n\t\t| undefined {\n\t\treturn this.externalActionBuilders.size > 0\n\t\t\t? Object.fromEntries(\n\t\t\t\t\t[...this.externalActionBuilders].map(([id, builder]) => [id, builder.build()]),\n\t\t\t\t)\n\t\t\t: undefined;\n\t}\n}\n\n/** @public */\nexport class AutomaticFlowBuilder<TParams = unknown, TState = unknown>\n\textends ExternalActionTurnBuilder<TParams, TState>\n\timplements FlowAutomaticTurn<TParams, TState, string>\n{\n\t/** @internal */\n\tprotected readonly turnKind = \"Automatic\";\n\tprivate runFn:\n\t\t| ((ctx: FlowAutomaticRunContext<TParams, TState>) => MaybePromise<WorkerCompleteInput<string>>)\n\t\t| null = null;\n\tprivate outcomeBuilders = new Map<string, AutomaticOutcomeBuilder<TParams, TState>>();\n\tprivate availableIntegrationTools: readonly string[] = [];\n\n\t/** @internal */\n\tget definition(): AutomaticTurnDefinition<string, TParams, TState> {\n\t\treturn this.buildDefinition();\n\t}\n\n\t/** @public */\n\trun(\n\t\tfn: (\n\t\t\tctx: FlowAutomaticRunContext<TParams, TState>,\n\t\t) => MaybePromise<WorkerCompleteInput<string>>,\n\t): this {\n\t\tthis.runFn = fn;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tintegrationTools(...tools: readonly string[]): this {\n\t\tthis.availableIntegrationTools = tools.map((tool) => tool.trim());\n\t\treturn this;\n\t}\n\n\t/** @public */\n\toutcome(\n\t\tid: string,\n\t\tconfigure: (\n\t\t\toutcome: AutomaticOutcomeBuilder<TParams, TState>,\n\t\t) => AutomaticOutcomeBuilder<TParams, TState> | undefined,\n\t): this {\n\t\tif (id.trim() === \"\") {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' declares an empty outcome id`);\n\t\t}\n\t\tif (this.outcomeBuilders.has(id)) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' declares duplicate outcome '${id}'`);\n\t\t}\n\t\tconst builder = new AutomaticOutcomeBuilder<TParams, TState>();\n\t\tconfigure(builder);\n\t\tthis.outcomeBuilders.set(id, builder);\n\t\treturn this;\n\t}\n\n\tprivate buildDefinition(): AutomaticTurnDefinition<string, TParams, TState> {\n\t\tif (!this.turnDescription) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);\n\t\t}\n\t\tif (!this.runFn) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' must declare .run(...)`);\n\t\t}\n\t\tif (this.outcomeBuilders.size === 0) {\n\t\t\tthrow new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);\n\t\t}\n\t\tconst outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};\n\t\tfor (const [outcomeId, builder] of this.outcomeBuilders) {\n\t\t\toutcomes[outcomeId] = builder.build();\n\t\t}\n\t\tconst runFn = this.runFn;\n\t\tconst externalActions = this.buildExternalActions();\n\t\treturn {\n\t\t\tkind: \"automatic\",\n\t\t\tdescription: this.turnDescription,\n\t\t\t...(this.availableIntegrationTools.length > 0\n\t\t\t\t? { integrationTools: this.availableIntegrationTools }\n\t\t\t\t: {}),\n\t\t\t...(externalActions ? { externalActions } : {}),\n\t\t\toutcomes,\n\t\t\trun: (ctx) => runFn(createFlowAutomaticRunContext(ctx)),\n\t\t};\n\t}\n}\n\nfunction inferAcceptanceState(actionId: string): ProcessHumanTurnActionSpec[\"acceptanceState\"] {\n\tconst normalized = actionId.toLowerCase();\n\tif (/approve|accept|complete|merged/.test(normalized)) {\n\t\treturn \"accepted\";\n\t}\n\tif (/request|revision|feedback|change|reject/.test(normalized)) {\n\t\treturn \"requires_changes\";\n\t}\n\treturn \"neutral\";\n}\n\n/** @public */\nexport class HumanActionBuilder<TParams = unknown, TState = unknown> {\n\tprivate spec: Record<string, unknown> = {};\n\n\t/** @internal */\n\tconstructor(private readonly actionId: string) {}\n\n\t/** @public */\n\tlabel(label: string): this {\n\t\tthis.spec.label = label;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tdescription(description: string): this {\n\t\tthis.spec.description = description;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tacceptanceState(state: ProcessHumanTurnActionSpec<TParams, TState>[\"acceptanceState\"]): this {\n\t\tthis.spec.acceptanceState = state;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tform(form: FormDefinition): this {\n\t\tthis.spec.form = form;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\tthis.spec.to = turnId;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcomplete(): this {\n\t\tthis.spec.complete = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\tthis.spec.lifecycleStatus = status;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\ttrigger(trigger: string): this {\n\t\tthis.spec.trigger = trigger;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tschedulable(value = true): this {\n\t\tthis.spec.schedulable = value;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\teffect(effect: ProcessHumanTurnActionSpec<TParams, TState>[\"effect\"]): this {\n\t\tthis.spec.effect = effect;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessHumanTurnActionSpec<TParams, TState> {\n\t\treturn {\n\t\t\tlabel:\n\t\t\t\ttypeof this.spec.label === \"string\" ? this.spec.label : humanizeProcessLabel(this.actionId),\n\t\t\tacceptanceState:\n\t\t\t\t(this.spec.acceptanceState as\n\t\t\t\t\t| ProcessHumanTurnActionSpec<TParams, TState>[\"acceptanceState\"]\n\t\t\t\t\t| undefined) ?? inferAcceptanceState(this.actionId),\n\t\t\t...this.spec,\n\t\t} as ProcessHumanTurnActionSpec<TParams, TState>;\n\t}\n}\n\n/** @public */\nexport class ExternalActionBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> {\n\tprivate spec: Partial<ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput>>;\n\n\t/** @internal */\n\tconstructor(actionId: string, source: ExternalActionSource<TParams, TState, TEvent, TInput>) {\n\t\tthis.spec = { id: actionId, source };\n\t}\n\n\t/** @public */\n\tlabel(label: string): this {\n\t\tthis.spec.label = label;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tdescription(description: string): this {\n\t\tthis.spec.description = description;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\twhen(condition: NonNullable<ProcessHumanTurnExternalActionSpec<TParams, TState>[\"when\"]>): this {\n\t\tthis.spec.when = condition;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\tthis.spec.to = turnId;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcomplete(): this {\n\t\tthis.spec.complete = true;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\tthis.spec.lifecycleStatus = status;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tpublishInput(\n\t\tproductName: string,\n\t\toptions: {\n\t\t\t/** @internal */\n\t\t\tinputField: string;\n\t\t},\n\t): this {\n\t\tthis.spec.publishInput = {\n\t\t\tproductName: normalizeProductName(productName),\n\t\t\tinputField: options.inputField,\n\t\t};\n\t\treturn this;\n\t}\n\n\t/** @public */\n\teffect(effect: ExternalSourceEffect<TParams, TState, TEvent, TInput>): this {\n\t\tthis.spec.effect = effect;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(): ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput> {\n\t\treturn this.spec as ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput>;\n\t}\n}\n\n/** @public */\nexport class HumanFlowBuilder<TParams = unknown, TState = unknown>\n\textends ExternalActionTurnBuilder<TParams, TState>\n\timplements FlowHumanTurn<TParams, TState>\n{\n\t/** @internal */\n\tprotected readonly turnKind = \"Human\";\n\tprivate reviewProductName: string | undefined;\n\tprivate reviewSemanticRef: ProcessSemanticEntryRefKey | undefined;\n\tprivate operatorAttentionValue: HumanTurnOperatorAttention | undefined;\n\tprivate turnCommentary: string | undefined;\n\tprivate notes: HumanTurnDefinition<TParams, TState>[\"notesFields\"] | undefined;\n\tprivate actions = new Map<string, HumanActionBuilder<TParams, TState>>();\n\n\t/** @public */\n\tget definition(): HumanTurnDefinition<TParams, TState> {\n\t\tif (!this.turnDescription) {\n\t\t\tthrow new Error(`Human turn '${this.turnId}' must declare .description(...)`);\n\t\t}\n\t\tconst externalActions = this.buildExternalActions();\n\t\treturn {\n\t\t\tkind: \"human\",\n\t\t\tdescription: this.turnDescription,\n\t\t\t...(this.reviewProductName ? { reviewProduct: this.reviewProductName } : {}),\n\t\t\t...(this.reviewSemanticRef ? { reviewSemanticRef: this.reviewSemanticRef } : {}),\n\t\t\t...(this.operatorAttentionValue ? { operatorAttention: this.operatorAttentionValue } : {}),\n\t\t\t...(this.notes ? { notesFields: this.notes } : {}),\n\t\t\t...(this.turnCommentary ? { commentary: this.turnCommentary } : {}),\n\t\t\tactions: Object.fromEntries(\n\t\t\t\t[...this.actions.entries()].map(([actionId, builder]) => [actionId, builder.build()]),\n\t\t\t),\n\t\t\t...(externalActions ? { externalActions } : {}),\n\t\t};\n\t}\n\n\t/** @public */\n\treviewProduct(productName: string): this {\n\t\tconst normalized = normalizeProductName(productName);\n\t\tthis.reviewProductName = normalized;\n\t\tthis.reviewSemanticRef =\n\t\t\tnormalized === \"plan\" ? \"plan\" : normalized === \"review\" ? \"review\" : undefined;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\toperatorAttention(attention: HumanTurnOperatorAttention): this {\n\t\tthis.operatorAttentionValue = attention;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tcommentary(commentary: string): this {\n\t\tthis.turnCommentary = commentary;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tnotesFields(notes: HumanTurnDefinition<TParams, TState>[\"notesFields\"]): this {\n\t\tthis.notes = notes;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\taction(\n\t\tactionId: string,\n\t\tconfigure: (\n\t\t\taction: HumanActionBuilder<TParams, TState>,\n\t\t) => HumanActionBuilder<TParams, TState> | undefined,\n\t): this {\n\t\tif (this.actions.has(actionId)) {\n\t\t\tthrow new Error(`Human turn '${this.turnId}' declares duplicate action '${actionId}'`);\n\t\t}\n\t\tconst builder = new HumanActionBuilder<TParams, TState>(actionId);\n\t\tconfigure(builder);\n\t\tthis.actions.set(actionId, builder);\n\t\treturn this;\n\t}\n}\n\n/** @public */\nexport class ExternalRouteBuilder<\n\tTParams = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTInput extends Record<string, unknown> = Record<string, unknown>,\n> implements FlowExternalTurn<TParams, TState>\n{\n\tprivate externalEffect: ExternalSourceEffect<TParams, TState, TEvent, TInput> | undefined;\n\tprivate target: FlowTargetSpec = null;\n\t/** @internal */\n\tconstructor(\n\t\tprivate readonly parent: ExternalFlowBuilder<TParams, TState>,\n\t\tprivate readonly source: ExternalActionSource<TParams, TState, TEvent, TInput>,\n\t) {}\n\n\t/** @internal */\n\tget id(): TurnId {\n\t\treturn this.parent.id;\n\t}\n\n\t/** @internal */\n\tget definition(): ExternalTurnDefinition<TParams, TState> {\n\t\treturn this.parent.definition;\n\t}\n\n\tprivate setTarget(next: Exclude<FlowTargetSpec, null>): this {\n\t\tif (this.target) {\n\t\t\tthrow new Error(\"External source route already declares a target\");\n\t\t}\n\t\tthis.target = next;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tto(turnId: TurnId): this {\n\t\treturn this.setTarget({ kind: \"to\", turnId });\n\t}\n\n\t/** @internal */\n\tcomplete(): this {\n\t\treturn this.setTarget({ kind: \"complete\" });\n\t}\n\n\t/** @internal */\n\tlifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {\n\t\treturn this.setTarget({ kind: \"lifecycleStatus\", status });\n\t}\n\n\t/** @internal */\n\tstate(\n\t\tfn: (input: {\n\t\t\t/** @internal */\n\t\t\tctx: FlowExternalSourceContext<TParams, TState, TEvent, TInput>;\n\t\t\t/** @internal */\n\t\t\tevent: TEvent;\n\t\t\t/** @internal */\n\t\t\tinput: TInput;\n\t\t}) => MaybePromise<TState>,\n\t): this {\n\t\tthis.externalEffect = async (ctx) => ({\n\t\t\tstate: await fn({ ctx, event: ctx.event, input: ctx.input }),\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\teffect(\n\t\tfn: (input: {\n\t\t\t/** @internal */\n\t\t\tctx: FlowExternalSourceContext<TParams, TState, TEvent, TInput>;\n\t\t\t/** @internal */\n\t\t\tevent: TEvent;\n\t\t\t/** @internal */\n\t\t\tinput: TInput;\n\t\t}) => MaybePromise<ProcessEffectPlan<TState> | undefined>,\n\t): this {\n\t\tthis.externalEffect = (ctx) => fn({ ctx, event: ctx.event, input: ctx.input });\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild() {\n\t\treturn {\n\t\t\t/** @internal */\n\t\t\tsource: this.source,\n\t\t\t...buildRouteTargetSpec(this.target),\n\t\t\t...(this.externalEffect\n\t\t\t\t? {\n\t\t\t\t\t\t/** @internal */\n\t\t\t\t\t\teffect: this.externalEffect,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n}\n\n/** @public */\nexport class ExternalFlowBuilder<TParams = unknown, TState = unknown>\n\textends DescribedTurnBuilder\n\timplements FlowExternalTurn<TParams, TState>\n{\n\tprivate routeBuilders: ExternalRouteBuilder<TParams, TState, unknown, Record<string, unknown>>[] =\n\t\t[];\n\n\t/** @internal */\n\tget definition(): ExternalTurnDefinition<TParams, TState> {\n\t\tif (!this.turnDescription) {\n\t\t\tthis.turnDescription =\n\t\t\t\tthis.routeBuilders[0]?.build().source.description ?? \"Wait for an external source\";\n\t\t}\n\t\tif (this.routeBuilders.length === 0) {\n\t\t\tthrow new Error(`External turn '${this.turnId}' must declare at least one .from(...) source`);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"external\",\n\t\t\tdescription: this.turnDescription,\n\t\t\ttransitions: this.routeBuilders.map((builder) => builder.build()),\n\t\t};\n\t}\n\n\t/** @public */\n\tfrom<TEvent = unknown, TInput extends Record<string, unknown> = Record<string, unknown>>(\n\t\tsource: ExternalActionSource<TParams, TState, TEvent, TInput>,\n\t): ExternalRouteBuilder<TParams, TState, TEvent, TInput> {\n\t\tconst builder = new ExternalRouteBuilder<TParams, TState, TEvent, TInput>(this, source);\n\t\tthis.routeBuilders.push(\n\t\t\tbuilder as unknown as ExternalRouteBuilder<TParams, TState, unknown, Record<string, unknown>>,\n\t\t);\n\t\treturn builder;\n\t}\n}\n\n/** @public */\ntype Hook<TApi> = (api: TApi) => void;\n\nfunction chainHooks<TApi>(hooks: readonly Hook<TApi>[]): Hook<TApi> {\n\treturn (api) => {\n\t\tfor (const hook of hooks) hook(api);\n\t};\n}\n\n/** @public */\nexport abstract class FlowComponentBuilder<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\treadonly turns: FlowTurn<TParams, TState>[] = [];\n\t/** @internal */\n\treadonly serverHooks: Hook<ServerProcessAPI<TParams, TState>>[] = [];\n\t/** @internal */\n\treadonly uiHooks: Hook<UiProcessAPI<TParams, TState>>[] = [];\n\t/** @internal */\n\treadonly launcherHooks: Hook<ProcessLauncherAPI<TParams>>[] = [];\n\t/** @internal */\n\treadonly watcherHooks: Hook<ProcessWatcherAPI<TParams>>[] = [];\n\n\t/** @public */\n\tturn(turn: FlowTurn<TParams, TState>): this {\n\t\tthis.turns.push(turn);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tserver(hook: Hook<ServerProcessAPI<TParams, TState>>): this {\n\t\tthis.serverHooks.push(hook);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\taction(definition: ProcessActionDefinition<TParams, TState>): this {\n\t\tthis.serverHooks.push((api) => api.action(definition));\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tui(hook: Hook<UiProcessAPI<TParams, TState>>): this {\n\t\tthis.uiHooks.push(hook);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tlauncher(\n\t\tdefinitionOrHook: ProcessLauncherDefinition<TParams> | Hook<ProcessLauncherAPI<TParams>>,\n\t): this {\n\t\tif (typeof definitionOrHook === \"function\") {\n\t\t\tthis.launcherHooks.push(definitionOrHook);\n\t\t} else {\n\t\t\tthis.launcherHooks.push((api) => api.launcher(definitionOrHook));\n\t\t}\n\t\treturn this;\n\t}\n\n\t/** @public */\n\twatcher<TEvent = unknown, TConfig = unknown>(\n\t\tdefinitionOrHook:\n\t\t\t| ProcessWatcherDefinition<TParams, TEvent, TConfig>\n\t\t\t| Hook<ProcessWatcherAPI<TParams>>,\n\t): this {\n\t\tif (typeof definitionOrHook === \"function\") {\n\t\t\tthis.watcherHooks.push(definitionOrHook);\n\t\t} else {\n\t\t\tthis.watcherHooks.push((api) => api.watcher(definitionOrHook));\n\t\t}\n\t\treturn this;\n\t}\n}\n\n/** @public */\nexport class FlowFragmentBuilder<TParams = unknown, TState = unknown> extends FlowComponentBuilder<\n\tTParams,\n\tTState\n> {\n\t/** @internal */\n\treadonly name: string;\n\n\t/** @internal */\n\tconstructor(name: string) {\n\t\tsuper();\n\t\tif (name.trim() === \"\") {\n\t\t\tthrow new Error(\"Flow fragment name must be non-empty\");\n\t\t}\n\t\tthis.name = name;\n\t}\n}\n\n/** @public */\nexport class FlowProcessBuilder<TParams = unknown, TState = unknown> extends FlowComponentBuilder<\n\tTParams,\n\tTState\n> {\n\tprivate readonly processId: string;\n\tprivate processDisplayName: string | null = null;\n\tprivate entryTurnId: TurnId | null = null;\n\tprivate readonly alternateEntryTurnIds: TurnId[] = [];\n\tprivate happyPathTurnIds: readonly TurnId[] | null = null;\n\tprivate paramsCodec: Codec<TParams> | null = null;\n\tprivate stateCodec: Codec<TState> | null = null;\n\tprivate initialStateFn: ((params: TParams) => TState) | null = null;\n\tprivate repositoryCredentialsFn: ExtensionProcessDefinition<\n\t\tTParams,\n\t\tTState\n\t>[\"repositoryCredentials\"];\n\tprivate storageSizeResolver: ExtensionProcessDefinition<TParams, TState>[\"resolveStorageSize\"];\n\tprivate processPiConfig: ProcessPiConfig | undefined;\n\tprivate developmentTools = false;\n\tprivate docker = false;\n\n\t/** @internal */\n\tconstructor(processId: string) {\n\t\tsuper();\n\t\tif (processId.trim() === \"\") {\n\t\t\tthrow new Error(\"Flow process id must be non-empty\");\n\t\t}\n\t\tthis.processId = processId;\n\t}\n\n\t/** @public */\n\tdisplayName(displayName: string): this {\n\t\tthis.processDisplayName = displayName;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tentry(turnId: TurnId): this {\n\t\tthis.entryTurnId = turnId;\n\t\treturn this;\n\t}\n\n\t/** Declare an additional turn that launchers may select as the first turn. @internal */\n\talternateEntry(turnId: TurnId): this {\n\t\tthis.alternateEntryTurnIds.push(turnId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Declare the happy path: the ordered spine of turns a successful run walks\n\t * through. Flow diagrams render this as the main line. Must start at the entry\n\t * turn and reference only declared turns without repeats.\n\t */\n\t/** @public */\n\thappyPath(...turnIds: readonly TurnId[]): this {\n\t\tthis.happyPathTurnIds = turnIds;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tcodecs(input: {\n\t\t/** @public */\n\t\tparams: Codec<TParams>;\n\t\t/** @public */\n\t\tstate: Codec<TState>;\n\t}): this {\n\t\tthis.paramsCodec = input.params;\n\t\tthis.stateCodec = input.state;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tinitialState(fn: (params: TParams) => TState): this {\n\t\tthis.initialStateFn = fn;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\trepositoryCredentials(\n\t\tfn: NonNullable<ExtensionProcessDefinition<TParams, TState>[\"repositoryCredentials\"]>,\n\t): this {\n\t\tthis.repositoryCredentialsFn = fn;\n\t\treturn this;\n\t}\n\n\t/** Resolve new process-volume capacity on the server; operator configuration wins. @internal */\n\tresolveStorageSize(\n\t\tfn: NonNullable<ExtensionProcessDefinition<TParams, TState>[\"resolveStorageSize\"]>,\n\t): this {\n\t\tthis.storageSizeResolver = fn;\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tpiConfig(config: ProcessPiConfig): this {\n\t\tthis.processPiConfig = config;\n\t\treturn this;\n\t}\n\n\t/** Declare runner-provided process runtime capabilities. @public */\n\truntime(capabilities: {\n\t\t/** @internal */\n\t\tdevelopmentTools?: boolean;\n\t\t/** @public */\n\t\tdocker?: boolean;\n\t}): this {\n\t\tthis.developmentTools = capabilities.developmentTools === true;\n\t\tthis.docker = capabilities.docker === true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tuse(fragment: FlowFragmentBuilder<TParams, TState>): this {\n\t\tthis.turns.push(...fragment.turns);\n\t\tthis.serverHooks.push(...fragment.serverHooks);\n\t\tthis.uiHooks.push(...fragment.uiHooks);\n\t\tthis.launcherHooks.push(...fragment.launcherHooks);\n\t\tthis.watcherHooks.push(...fragment.watcherHooks);\n\t\treturn this;\n\t}\n\n\t/** @public */\n\tdefine(): ExtensionProcessDefinition<TParams, TState> {\n\t\tif (!this.processDisplayName) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .displayName(...)`);\n\t\t}\n\t\tif (!this.entryTurnId) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .entry(turnId)`);\n\t\t}\n\t\tif (!this.paramsCodec || !this.stateCodec) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .codecs(...)`);\n\t\t}\n\t\tif (!this.initialStateFn) {\n\t\t\tthrow new Error(`Flow process '${this.processId}' must declare .initialState(...)`);\n\t\t}\n\n\t\tconst turns: TurnDefinitionRecord<TParams, TState> = {};\n\t\tfor (const turn of this.turns) {\n\t\t\tif (Object.hasOwn(turns, turn.id)) {\n\t\t\t\tthrow new Error(`Flow process '${this.processId}' declares duplicate turn '${turn.id}'`);\n\t\t\t}\n\t\t\tturns[turn.id] = turn.definition;\n\t\t}\n\n\t\tconst input: DefinedProcessInput<TParams, TState> = {\n\t\t\tid: this.processId,\n\t\t\tdisplayName: this.processDisplayName,\n\t\t\tentry: this.entryTurnId,\n\t\t\t...(this.alternateEntryTurnIds.length > 0\n\t\t\t\t? { alternateEntries: [...this.alternateEntryTurnIds] }\n\t\t\t\t: {}),\n\t\t\t...(this.happyPathTurnIds ? { happyPath: [...this.happyPathTurnIds] } : {}),\n\t\t\tparamsCodec: this.paramsCodec,\n\t\t\tstateCodec: this.stateCodec,\n\t\t\tinitialState: this.initialStateFn,\n\t\t\t...(this.developmentTools || this.docker\n\t\t\t\t? {\n\t\t\t\t\t\truntime: {\n\t\t\t\t\t\t\t...(this.developmentTools ? { developmentTools: true } : {}),\n\t\t\t\t\t\t\t...(this.docker ? { docker: true } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(this.repositoryCredentialsFn\n\t\t\t\t? { repositoryCredentials: this.repositoryCredentialsFn }\n\t\t\t\t: {}),\n\t\t\t...(this.storageSizeResolver ? { resolveStorageSize: this.storageSizeResolver } : {}),\n\t\t\t...(this.processPiConfig ? { piConfig: this.processPiConfig } : {}),\n\t\t\tturns,\n\t\t\t...(this.serverHooks.length > 0 ? { server: chainHooks(this.serverHooks) } : {}),\n\t\t\t...(this.uiHooks.length > 0 ? { ui: chainHooks(this.uiHooks) } : {}),\n\t\t\t...(this.launcherHooks.length > 0 ? { launchers: chainHooks(this.launcherHooks) } : {}),\n\t\t\t...(this.watcherHooks.length > 0 ? { watchers: chainHooks(this.watcherHooks) } : {}),\n\t\t};\n\t\tconst process = defineProcess(input);\n\t\tconst errors = validateProcessGraphProducts(\n\t\t\ttoProcessGraphView(process as unknown as ProcessGraphSource),\n\t\t);\n\t\tif (errors.length > 0)\n\t\t\tthrow new Error(`Flow process '${this.processId}': ${errors.join(\"; \")}`);\n\t\treturn process;\n\t}\n}\n\n/** @public */\nexport const flow = {\n\t/** @public */\n\tllm<TParams = unknown, TState = unknown>(turnId: TurnId): LlmFlowBuilder<TParams, TState> {\n\t\treturn new LlmFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\tautomatic<TParams = unknown, TState = unknown>(\n\t\tturnId: TurnId,\n\t): AutomaticFlowBuilder<TParams, TState> {\n\t\treturn new AutomaticFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\thuman<TParams = unknown, TState = unknown>(turnId: TurnId): HumanFlowBuilder<TParams, TState> {\n\t\treturn new HumanFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\texternal<TParams = unknown, TState = unknown>(\n\t\tturnId: TurnId,\n\t): ExternalFlowBuilder<TParams, TState> {\n\t\treturn new ExternalFlowBuilder<TParams, TState>(turnId);\n\t},\n\t/** @public */\n\tfragment<TParams = unknown, TState = unknown>(\n\t\tname: string,\n\t): FlowFragmentBuilder<TParams, TState> {\n\t\treturn new FlowFragmentBuilder<TParams, TState>(name);\n\t},\n\t/** @public */\n\tprocess<TParams = unknown, TState = unknown>(\n\t\tprocessId: string,\n\t): FlowProcessBuilder<TParams, TState> {\n\t\treturn new FlowProcessBuilder<TParams, TState>(processId);\n\t},\n};\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** @internal */\nexport async function atomicWriteUtf8(filePath: string, content: string): Promise<void> {\n\tconst dir = path.dirname(filePath);\n\tawait mkdir(dir, { recursive: true });\n\tconst tempPath = path.join(\n\t\tdir,\n\t\t`.${path.basename(filePath)}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tawait writeFile(tempPath, content, \"utf8\");\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\tawait unlink(tempPath).catch(() => {});\n\t\tthrow error;\n\t}\n}\n\n// The parent itself is not inside: callers require a strict descendant.\n/** @internal */\nexport function isPathInside(parent: string, child: string): boolean {\n\tconst relative = path.relative(parent, child);\n\treturn (\n\t\trelative !== \"\" &&\n\t\trelative !== \"..\" &&\n\t\t!relative.startsWith(`..${path.sep}`) &&\n\t\t!path.isAbsolute(relative)\n\t);\n}\n\n/** @internal */\nexport function hasErrorCode(error: unknown, code: string): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\t(error as { code?: unknown }).code === code\n\t);\n}\n\n/** @internal */\nexport function isEnoent(error: unknown): boolean {\n\treturn hasErrorCode(error, \"ENOENT\");\n}\n","import type {\n\tProcessSemanticEntryRefKey,\n\tProcessTurnTransition,\n\tProcessTurnType,\n\tSerializedProcessGraph,\n\tTurnId,\n} from \"@leitwerk-dev/domain\";\nimport { isValidProcessProductName } from \"@leitwerk-dev/domain\";\nimport type { TurnDefinition } from \"./define-process.js\";\nimport type { ExtensionProcessDefinition, ProcessTurnBinding } from \"./extension-api.js\";\nimport { getProcessTurnTransitions } from \"./process-definition-internals.js\";\n\n/** @internal */\nexport type ProcessGraphSource = ExtensionProcessDefinition<unknown, unknown>;\n/** @internal */\nexport type ProcessGraphRegistry = ReadonlyMap<string, ProcessGraphSource>;\n\n/** @internal */\nexport interface ProcessGraphTurnView {\n\t/** @internal */\n\tturnType: ProcessTurnType;\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\ttransitions: readonly ProcessTurnTransition[];\n\t/** @internal */\n\treviewProduct?: string;\n\t/** @internal */\n\tresultSemanticRef?: ProcessSemanticEntryRefKey;\n\t/** @internal */\n\tpublishedProduct?: string;\n\t/** @internal */\n\tpublishedProducts?: readonly string[];\n\t/** @internal */\n\tconsumedProducts?: readonly string[];\n\t/** @internal */\n\toptionalConsumedProducts?: readonly string[];\n\t/** @internal */\n\trequiredSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n\t/** @internal */\n\toptionalSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];\n\t/** @internal */\n\tturnResultMarkdownRequired?: boolean;\n}\n\n/** @internal */\nexport interface ProcessGraphView {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tprimaryEntryTurnId: TurnId;\n\t/** @internal */\n\tentryTurnIds: ReadonlySet<TurnId>;\n\t/** @internal */\n\thappyPath: readonly TurnId[] | null;\n\t/** @internal */\n\tturns: ReadonlyMap<TurnId, ProcessGraphTurnView>;\n}\n\nfunction turnPublishedProducts(definition: TurnDefinition<unknown, unknown>): string[] {\n\tconst products = new Set<string>();\n\tif (definition.kind === \"human\") {\n\t\tfor (const action of Object.values(definition.actions)) {\n\t\t\tfor (const field of action.form?.fields ?? []) {\n\t\t\t\tif (field.publish) {\n\t\t\t\t\tproducts.add(\n\t\t\t\t\t\ttypeof field.publish === \"object\" && field.publish.product\n\t\t\t\t\t\t\t? field.publish.product\n\t\t\t\t\t\t\t: field.id,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const action of Object.values(definition.externalActions ?? {})) {\n\t\t\tif (action.publishInput) {\n\t\t\t\tproducts.add(action.publishInput.productName);\n\t\t\t}\n\t\t}\n\t} else if (definition.kind === \"llm\" || definition.kind === \"automatic\") {\n\t\tfor (const outcome of Object.values(definition.outcomes ?? {})) {\n\t\t\tif (typeof outcome?.publishedProduct === \"string\") {\n\t\t\t\tproducts.add(outcome.publishedProduct);\n\t\t\t}\n\t\t}\n\t}\n\treturn [...products];\n}\n\nfunction toTurnView(\n\tbinding: ProcessTurnBinding<TurnDefinition<unknown, unknown>>,\n): ProcessGraphTurnView {\n\tconst definition = binding.definition;\n\tconst publishedProducts = turnPublishedProducts(definition);\n\treturn {\n\t\tturnType: definition.kind,\n\t\tdescription: definition.description,\n\t\ttransitions: getProcessTurnTransitions(binding),\n\t\t...(definition.kind === \"human\" && definition.reviewProduct\n\t\t\t? { reviewProduct: definition.reviewProduct }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.resultSemanticRef\n\t\t\t? { resultSemanticRef: definition.resultSemanticRef }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.publishedProduct\n\t\t\t? { publishedProduct: definition.publishedProduct }\n\t\t\t: {}),\n\t\t...(publishedProducts.length > 0 ? { publishedProducts } : {}),\n\t\t...(definition.kind === \"llm\" && definition.consumedProducts?.length\n\t\t\t? { consumedProducts: [...definition.consumedProducts] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.optionalConsumedProducts?.length\n\t\t\t? { optionalConsumedProducts: [...definition.optionalConsumedProducts] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.requiredSemanticMarkdownRefs?.length\n\t\t\t? { requiredSemanticMarkdownRefs: [...definition.requiredSemanticMarkdownRefs] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" && definition.optionalSemanticMarkdownRefs?.length\n\t\t\t? { optionalSemanticMarkdownRefs: [...definition.optionalSemanticMarkdownRefs] }\n\t\t\t: {}),\n\t\t...(definition.kind === \"llm\" &&\n\t\tdefinition.turnResultMarkdown &&\n\t\t\"required\" in definition.turnResultMarkdown &&\n\t\tdefinition.turnResultMarkdown.required === true\n\t\t\t? { turnResultMarkdownRequired: true }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Runtime adapter from an extension process definition to the internal graph view.\n * All server lifecycle, validation, model-selection and serialization code should use this view\n * instead of maintaining a second graph representation.\n */\n/** @internal */\nexport function toProcessGraphView(definition: ProcessGraphSource): ProcessGraphView {\n\tconst turns = new Map<TurnId, ProcessGraphTurnView>();\n\tfor (const [turnId, binding] of definition.turns) {\n\t\tturns.set(turnId, toTurnView(binding));\n\t}\n\treturn {\n\t\tid: definition.id,\n\t\tprimaryEntryTurnId: definition.entryTurnId,\n\t\tentryTurnIds: new Set([definition.entryTurnId, ...(definition.alternateEntryTurnIds ?? [])]),\n\t\thappyPath: definition.happyPath ? [...definition.happyPath] : null,\n\t\tturns,\n\t};\n}\n\n/** @internal */\nexport function hasProcessGraph(registry: ProcessGraphRegistry, processId: string): boolean {\n\treturn registry.has(processId);\n}\n\n/** @internal */\nexport function getProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): ProcessGraphView {\n\tconst definition = registry.get(processId);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown process definition: ${processId}`);\n\t}\n\treturn toProcessGraphView(definition);\n}\n\n/** @internal */\nexport function getAllProcessGraphs(registry: ProcessGraphRegistry): readonly ProcessGraphView[] {\n\treturn [...registry.values()].map((definition) => toProcessGraphView(definition));\n}\n\n/** @internal */\nexport function getProcessTurnGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n\tturnId: TurnId,\n): ProcessGraphTurnView | undefined {\n\treturn getProcessGraph(registry, processId).turns.get(turnId);\n}\n\n/** @internal */\nexport function getTurnTransitionsForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n\tturnId: TurnId,\n): readonly ProcessTurnTransition[] {\n\treturn getProcessTurnGraph(registry, processId, turnId)?.transitions ?? [];\n}\n\n/** @internal */\nexport function getReachableTurnIdsForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): readonly TurnId[] {\n\treturn [...getProcessGraph(registry, processId).turns.keys()];\n}\n\n/** @internal */\nexport function isTurnAvailableForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n\tturnId: TurnId,\n): boolean {\n\treturn getProcessGraph(registry, processId).turns.has(turnId);\n}\n\n/** @internal */\nexport function serializeProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): SerializedProcessGraph {\n\tconst definition = getProcessGraph(registry, processId);\n\tconst turnTransitions: Record<TurnId, ProcessTurnTransition[]> = {};\n\tfor (const [turnId, turn] of definition.turns) {\n\t\tturnTransitions[turnId] = turn.transitions.map((transition) => ({ ...transition }));\n\t}\n\treturn {\n\t\tid: definition.id,\n\t\tentryTurnIds: [...definition.entryTurnIds],\n\t\treachableTurnIds: [...definition.turns.keys()],\n\t\tturnTransitions,\n\t};\n}\n\n/** @internal */\nexport function listLlmTurnIdsForProcessGraph(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): readonly TurnId[] {\n\treturn [...getProcessGraph(registry, processId).turns.entries()]\n\t\t.filter(([, turn]) => turn.turnType === \"llm\")\n\t\t.map(([turnId]) => turnId);\n}\n\nfunction isTerminalLifecycleStatus(value: string | undefined): value is \"completed\" | \"aborted\" {\n\treturn value === \"completed\" || value === \"aborted\";\n}\n\n/** @internal */\nexport function validateProcessGraphEntryTurns(graph: ProcessGraphView): readonly string[] {\n\tconst errors: string[] = [];\n\tfor (const turnId of graph.entryTurnIds) {\n\t\tif (!graph.turns.has(turnId)) {\n\t\t\terrors.push(`Entry turn '${turnId}' is not declared in turns`);\n\t\t}\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateProcessGraphProducts(graph: ProcessGraphView): readonly string[] {\n\tconst errors: string[] = [];\n\tconst publishedProducts = new Set<string>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tconst productNames = [\n\t\t\t...(turn.publishedProduct ? [turn.publishedProduct] : []),\n\t\t\t...(turn.publishedProducts ?? []),\n\t\t];\n\t\tfor (const productName of productNames) {\n\t\t\tif (!isValidProcessProductName(productName)) {\n\t\t\t\terrors.push(`Turn '${turnId}' publishes invalid product '${productName}'`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpublishedProducts.add(productName);\n\t\t}\n\t}\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const productName of [\n\t\t\t...(turn.consumedProducts ?? []),\n\t\t\t...(turn.optionalConsumedProducts ?? []),\n\t\t]) {\n\t\t\tif (!isValidProcessProductName(productName)) {\n\t\t\t\terrors.push(`Turn '${turnId}' consumes invalid product '${productName}'`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!publishedProducts.has(productName)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn '${turnId}' consumes product '${productName}' that is never published by this process`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateProcessGraphTurnTransitions(graph: ProcessGraphView): readonly string[] {\n\tconst errors: string[] = [];\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst hasNextTurn = transition.nextTurnId !== undefined;\n\t\t\tconst hasLifecycleStatus = transition.lifecycleStatus !== undefined;\n\t\t\tif (hasNextTurn === hasLifecycleStatus) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn transition from '${turnId}' must declare exactly one target: nextTurnId or lifecycleStatus`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (transition.nextTurnId !== undefined && !graph.turns.has(transition.nextTurnId)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn transition from '${turnId}' references undeclared nextTurnId '${transition.nextTurnId}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttransition.lifecycleStatus !== undefined &&\n\t\t\t\t!isTerminalLifecycleStatus(transition.lifecycleStatus)\n\t\t\t) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Turn transition from '${turnId}' references invalid lifecycleStatus '${transition.lifecycleStatus}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n","import type { InputKind, InputSource, ProcessInputTarget } from \"@leitwerk-dev/domain\";\nimport type {\n\tProcessActionEffect,\n\tProcessActionExecution,\n\tProcessEffectPlan,\n\tProcessHumanTurnActionSpec,\n} from \"./define-process.js\";\n\n/** @internal */\ntype MaybePromise<T> = T | Promise<T>;\n/** @internal */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\nfunction appendQueuedInstruction<TState>(input: {\n\tplan: ProcessEffectPlan<TState> | undefined;\n\tbodyMarkdown: string | null | undefined;\n\tqueueTarget?: ProcessInputTarget;\n\tqueueSource?: InputSource;\n\tqueueKind?: InputKind;\n}) {\n\tif (input.bodyMarkdown == null) {\n\t\treturn input.plan;\n\t}\n\tif (input.bodyMarkdown.trim() === \"\") {\n\t\tthrow new Error(\"Queued instruction bodyMarkdown must not be empty\");\n\t}\n\treturn {\n\t\t...(input.plan ?? {}),\n\t\tqueueInput: [\n\t\t\t...(input.plan?.queueInput ?? []),\n\t\t\t{\n\t\t\t\tsource: input.queueSource ?? \"action_prompt\",\n\t\t\t\tkind: input.queueKind ?? \"instruction\",\n\t\t\t\t...(input.queueTarget ? { target: input.queueTarget } : {}),\n\t\t\t\tbodyMarkdown: input.bodyMarkdown,\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** @internal */\nexport type QueuedInstructionActionSpec<TParams = unknown, TState = unknown> = DistributiveOmit<\n\tProcessHumanTurnActionSpec<TParams, TState>,\n\t\"effect\"\n> & {\n\t/** @internal */\n\tqueueTarget?: ProcessInputTarget;\n\t/** @internal */\n\tqueueSource?: InputSource;\n\t/** @internal */\n\tqueueKind?: InputKind;\n\t/** @internal */\n\tresolveBodyMarkdown(\n\t\tinput: ProcessActionExecution<TParams, TState>,\n\t): MaybePromise<string | null | undefined>;\n\t/** @internal */\n\teffect?: ProcessActionEffect<TParams, TState>;\n};\n\n/** @internal */\nexport function queuedInstructionAction<TParams = unknown, TState = unknown>(\n\tspec: QueuedInstructionActionSpec<TParams, TState>,\n): ProcessHumanTurnActionSpec<TParams, TState> {\n\tconst { queueTarget, queueSource, queueKind, resolveBodyMarkdown, effect, ...rest } = spec;\n\treturn {\n\t\t...rest,\n\t\tasync effect(input) {\n\t\t\tconst bodyMarkdown = await resolveBodyMarkdown(input);\n\t\t\tconst plan = effect ? await effect(input) : undefined;\n\t\t\treturn appendQueuedInstruction({\n\t\t\t\tplan,\n\t\t\t\tbodyMarkdown,\n\t\t\t\tqueueTarget,\n\t\t\t\tqueueSource,\n\t\t\t\tqueueKind,\n\t\t\t});\n\t\t},\n\t} as ProcessHumanTurnActionSpec<TParams, TState>;\n}\n\n/** @internal */\nexport type RevisionActionSpec<TParams = unknown, TState = unknown> = DistributiveOmit<\n\tQueuedInstructionActionSpec<TParams, TState>,\n\t\"resolveBodyMarkdown\"\n> & {\n\t/** @internal */\n\tmessageFieldId?: string;\n\t/** @internal */\n\tmissingMessageError?: string;\n};\n\n/** @internal */\nexport function revisionAction<TParams = unknown, TState = unknown>(\n\tspec: RevisionActionSpec<TParams, TState>,\n): ProcessHumanTurnActionSpec<TParams, TState> {\n\tconst { messageFieldId = \"message\", missingMessageError, ...rest } = spec;\n\treturn queuedInstructionAction({\n\t\t...rest,\n\t\tresolveBodyMarkdown({ input }) {\n\t\t\tconst message = typeof input[messageFieldId] === \"string\" ? input[messageFieldId].trim() : \"\";\n\t\t\tif (!message) {\n\t\t\t\tthrow new Error(missingMessageError ?? `${messageFieldId} is required`);\n\t\t\t}\n\t\t\treturn message;\n\t\t},\n\t});\n}\n\n/** @internal */\nexport type AcceptedReviewHandoffActionSpec<TParams = unknown, TState = unknown> = DistributiveOmit<\n\tQueuedInstructionActionSpec<TParams, TState>,\n\t\"queueTarget\"\n> & {\n\t/** @internal */\n\tqueueTarget?: ProcessInputTarget;\n};\n\n/** @internal */\nexport function acceptedReviewHandoffAction<TParams = unknown, TState = unknown>(\n\tspec: AcceptedReviewHandoffActionSpec<TParams, TState>,\n): ProcessHumanTurnActionSpec<TParams, TState> {\n\treturn queuedInstructionAction({\n\t\t...spec,\n\t\tqueueTarget: spec.queueTarget ?? { semanticRef: \"currentPrimaryPathLeaf\" },\n\t});\n}\n","import type { CapabilityToken } from \"./capabilities.js\";\n\n/** @internal */\nexport interface ProvidedCapability<T = unknown> {\n\t/** @internal */\n\ttoken: CapabilityToken<T>;\n\t/** @internal */\n\tvalue: T;\n}\n\n/** @internal */\nexport function createCapabilityAccessor(provided: readonly ProvidedCapability[] = []): {\n\t/** @internal */\n\tprovide<T>(token: CapabilityToken<T>, value: T): void;\n\t/** @internal */\n\tget<T>(token: CapabilityToken<T>): T | T[] | undefined;\n\t/** @internal */\n\trequire<T>(token: CapabilityToken<T>): T | T[];\n} {\n\tconst singleCapabilities = new Map<string, unknown>();\n\tconst multiCapabilities = new Map<string, unknown[]>();\n\n\tfor (const entry of provided) {\n\t\tif (entry.token.cardinality === \"multi\") {\n\t\t\tconst list = multiCapabilities.get(entry.token.id) ?? [];\n\t\t\tlist.push(entry.value);\n\t\t\tmultiCapabilities.set(entry.token.id, list);\n\t\t\tcontinue;\n\t\t}\n\t\tsingleCapabilities.set(entry.token.id, entry.value);\n\t}\n\n\treturn {\n\t\tprovide(token, value) {\n\t\t\tif (token.cardinality === \"multi\") {\n\t\t\t\tconst list = multiCapabilities.get(token.id) ?? [];\n\t\t\t\tlist.push(value);\n\t\t\t\tmultiCapabilities.set(token.id, list);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (singleCapabilities.has(token.id)) {\n\t\t\t\tthrow new Error(`Capability '${token.id}' is already provided`);\n\t\t\t}\n\t\t\tsingleCapabilities.set(token.id, value);\n\t\t},\n\t\tget<T>(token: CapabilityToken<T>): T | T[] | undefined {\n\t\t\tif (token.cardinality === \"multi\") {\n\t\t\t\treturn [...(multiCapabilities.get(token.id) ?? [])] as T[];\n\t\t\t}\n\t\t\treturn singleCapabilities.get(token.id) as T | undefined;\n\t\t},\n\t\trequire<T>(token: CapabilityToken<T>): T | T[] {\n\t\t\tconst value = this.get(token);\n\t\t\tif (\n\t\t\t\tvalue === undefined ||\n\t\t\t\t(Array.isArray(value) && token.cardinality === \"multi\" && value.length === 0)\n\t\t\t) {\n\t\t\t\tthrow new Error(`Required capability '${token.id}' is not available`);\n\t\t\t}\n\t\t\treturn value;\n\t\t},\n\t};\n}\n","/** An HTTP failure without provider response bodies or credentials. @public */\nexport class IntegrationHttpError extends Error {\n\t/** @public */\n\tconstructor(\n\t\t/** @public */\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/** Shared transport; extensions own endpoint paths, credentials, and response types. @public */\nexport class IntegrationHttpClient {\n\t/** @internal */\n\tconstructor(\n\t\tprivate readonly provider: string,\n\t\tprivate readonly baseUrl: string,\n\t\tprivate readonly headers: Record<string, string>,\n\t\tprivate readonly pagination = {\n\t\t\t/** @internal */\n\t\t\tkey: \"per_page\",\n\t\t\t/** @internal */\n\t\t\tsize: 100,\n\t\t},\n\t) {}\n\n\t/** @internal */\n\tprotected async response(path: string, init: RequestInit = {}): Promise<Response> {\n\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...this.headers,\n\t\t\t\t...(init.body ? { \"Content-Type\": \"application/json\" } : {}),\n\t\t\t\t...init.headers,\n\t\t\t},\n\t\t});\n\t\tif (!response.ok)\n\t\t\tthrow new IntegrationHttpError(\n\t\t\t\tresponse.status,\n\t\t\t\t`${this.provider} ${init.method ?? \"GET\"} ${path} failed with ${response.status}`,\n\t\t\t);\n\t\treturn response;\n\t}\n\n\t/** @internal */\n\tprotected async request<T>(path: string, init: RequestInit = {}): Promise<T> {\n\t\tconst response = await this.response(path, init);\n\t\treturn response.status === 204 ? (undefined as T) : response.json();\n\t}\n\n\t/** @internal */\n\tprotected writeJson<T>(path: string, method: string, body: unknown, signal?: AbortSignal) {\n\t\treturn this.request<T>(path, { method, body: JSON.stringify(body), signal });\n\t}\n\n\t/** @internal */\n\tprotected async pages<T>(path: string, signal?: AbortSignal): Promise<T[]> {\n\t\tconst items: T[] = [];\n\t\tconst { key, size } = this.pagination;\n\t\tfor (let page = 1; ; page++) {\n\t\t\tconst separator = path.includes(\"?\") ? \"&\" : \"?\";\n\t\t\tconst batch = await this.request<T[]>(`${path}${separator}${key}=${size}&page=${page}`, {\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\titems.push(...batch);\n\t\t\tif (batch.length < size) return items;\n\t\t}\n\t}\n}\n","/** Validate and detach JSON data without silently dropping unsupported values. @public */\nexport function parseJsonData(\n\tvalue: unknown,\n\tmessage = \"Value must be JSON-serializable\",\n): unknown {\n\tconst ancestors = new Set<object>();\n\tfunction parse(value: unknown): unknown {\n\t\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\t\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\t\tif (!value || typeof value !== \"object\" || ancestors.has(value)) throw new Error(message);\n\t\tancestors.add(value);\n\t\ttry {\n\t\t\tif (Array.isArray(value)) return Array.from(value, parse);\n\t\t\tif (\n\t\t\t\t![Object.prototype, null].includes(Object.getPrototypeOf(value)) ||\n\t\t\t\tObject.getOwnPropertySymbols(value).length\n\t\t\t)\n\t\t\t\tthrow new Error(message);\n\t\t\treturn Object.fromEntries(Object.entries(value).map(([key, item]) => [key, parse(item)]));\n\t\t} finally {\n\t\t\tancestors.delete(value);\n\t\t}\n\t}\n\treturn parse(value);\n}\n","import { copiedUnknownRecordSchema as unknownRecordSchema } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\nimport type { LeafOutcomeCaptureResult, ProcessLeafOutcomeDefinition } from \"./extension-api.js\";\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.trim() !== \"\";\n}\n\n/** @internal */\nexport function validateProcessLeafOutcomeDefinition(def: ProcessLeafOutcomeDefinition): string[] {\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(def.rendererId)) {\n\t\terrors.push(\"Leaf outcome definition must declare a non-empty rendererId\");\n\t}\n\tif (typeof def.capture !== \"function\") {\n\t\terrors.push(`Leaf outcome '${String(def.rendererId)}' must declare a capture() function`);\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateLeafOutcomeCaptureResult(\n\tresult: unknown,\n\texpectedRendererId?: string,\n): string[] {\n\tconst errors: string[] = [];\n\tconst parsedResult = v.safeParse(unknownRecordSchema, result);\n\tif (!parsedResult.success) {\n\t\treturn [\"Leaf outcome capture result must be an object\"];\n\t}\n\tconst captureResult = parsedResult.output;\n\tif (!isNonEmptyString(captureResult.rendererId)) {\n\t\terrors.push(\"Leaf outcome capture result must include a non-empty rendererId\");\n\t} else if (expectedRendererId && captureResult.rendererId.trim() !== expectedRendererId.trim()) {\n\t\terrors.push(\n\t\t\t`Leaf outcome capture result rendererId '${captureResult.rendererId}' must match '${expectedRendererId}'`,\n\t\t);\n\t}\n\tif (!v.safeParse(unknownRecordSchema, captureResult.props).success) {\n\t\terrors.push(\"Leaf outcome capture result props must be an object\");\n\t}\n\tif (\n\t\tcaptureResult.schemaVersion !== undefined &&\n\t\t(typeof captureResult.schemaVersion !== \"number\" ||\n\t\t\t!Number.isInteger(captureResult.schemaVersion))\n\t) {\n\t\terrors.push(\"Leaf outcome capture result schemaVersion must be an integer when provided\");\n\t}\n\tif (\n\t\tcaptureResult.fallbackMarkdown !== undefined &&\n\t\tcaptureResult.fallbackMarkdown !== null &&\n\t\ttypeof captureResult.fallbackMarkdown !== \"string\"\n\t) {\n\t\terrors.push(\"Leaf outcome capture result fallbackMarkdown must be a string or null\");\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function normalizeLeafOutcomeCaptureResult(\n\tresult: LeafOutcomeCaptureResult,\n): LeafOutcomeCaptureResult {\n\treturn {\n\t\trendererId: result.rendererId.trim(),\n\t\t...(result.schemaVersion !== undefined ? { schemaVersion: result.schemaVersion } : {}),\n\t\tprops: { ...result.props },\n\t\t...(result.fallbackMarkdown !== undefined ? { fallbackMarkdown: result.fallbackMarkdown } : {}),\n\t};\n}\n","/** JSON values that may cross the server/worker bootstrap boundary. @public */\nexport type ProviderJsonPrimitive = string | number | boolean | null;\n/** @public */\nexport type ProviderJsonValue =\n\t| ProviderJsonPrimitive\n\t| ProviderJsonValue[]\n\t| {\n\t\t\t/** @internal */\n\t\t\t[key: string]: ProviderJsonValue;\n\t };\n/** @public */\nexport type ProviderJsonObject = {\n\t/** @internal */\n\t[key: string]: ProviderJsonValue;\n};\n\n/** @public */\nexport interface ConfiguredProviderModel {\n\t/** @public */\n\treadonly profileId: string;\n\t/** @public */\n\treadonly modelId: string;\n}\n\n/** @public */\nexport type ProviderAvailability = \"available\" | \"unavailable\" | \"stale\";\n\n/** @public */\nexport interface ProviderModelStatus {\n\t/** @public */\n\treadonly modelId: string;\n\t/** @public */\n\treadonly availability: ProviderAvailability;\n\t/** Safe operator-facing reason. It must not contain credential material. @internal */\n\treadonly safeReason?: string;\n}\n\n/** @public */\nexport interface ProviderCredentialStatus {\n\t/** @public */\n\treadonly available: boolean;\n\t/** @public */\n\treadonly revision: number | null;\n}\n\n/** @public */\nexport interface ModelProviderModelsContext<TConfig = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly configuredModels: readonly ConfiguredProviderModel[];\n\t/** @public */\n\treadonly credentialStatus: ProviderCredentialStatus;\n}\n\n/** @public */\nexport interface ProviderOptionChoice {\n\t/** @internal */\n\treadonly value: string;\n\t/** @internal */\n\treadonly label: string;\n}\n\n/** @public */\nexport interface ProviderOptionChoicesContext<TConfig = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly credentialStatus: ProviderCredentialStatus;\n}\n\n/** @internal */\nexport interface ProviderOptionDefaultContext<TConfig = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n}\n\n/** @public */\nexport interface ProviderOptionField<TConfig = unknown> {\n\t/** @public */\n\treadonly label: string;\n\t/** @public */\n\treadonly required?: boolean;\n\t/** @internal */\n\treadonly minLength?: number;\n\t/** @public */\n\treadonly maxLength?: number;\n\t/**\n\t * Explicit provider default. Dynamic choices are advisory and are never used\n\t * as an implicit default.\n\t */\n\t/** @internal */\n\treadonly defaultValue?:\n\t\t| string\n\t\t| null\n\t\t| ((ctx: ProviderOptionDefaultContext<TConfig>) => string | null | undefined);\n}\n\n/** @public */\nexport interface ProviderOptionsDefinition<TConfig = unknown> {\n\t/** @public */\n\treadonly fields: Readonly<Record<string, ProviderOptionField<TConfig>>>;\n\t/** @public */\n\tchoices?(\n\t\tctx: ProviderOptionChoicesContext<TConfig>,\n\t):\n\t\t| Readonly<Record<string, readonly ProviderOptionChoice[]>>\n\t\t| Promise<Readonly<Record<string, readonly ProviderOptionChoice[]>>>;\n}\n\n/** @public */\nexport function defineProviderOptions<TConfig = unknown>(\n\tdefinition: ProviderOptionsDefinition<TConfig>,\n): ProviderOptionsDefinition<TConfig> {\n\tfor (const [fieldId, field] of Object.entries(definition.fields)) {\n\t\tif (fieldId.trim() === \"\") {\n\t\t\tthrow new Error(\"Provider option field ids must not be empty\");\n\t\t}\n\t\tfor (const bound of [\"minLength\", \"maxLength\"] as const) {\n\t\t\tconst value = field[bound];\n\t\t\tif (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n\t\t\t\tthrow new Error(`Provider option '${fieldId}' ${bound} must be a non-negative integer`);\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tfield.minLength !== undefined &&\n\t\t\tfield.maxLength !== undefined &&\n\t\t\tfield.minLength > field.maxLength\n\t\t) {\n\t\t\tthrow new Error(`Provider option '${fieldId}' minLength must not exceed maxLength`);\n\t\t}\n\t}\n\treturn { ...definition, fields: { ...definition.fields } };\n}\n\n/** @internal */\nexport interface ProviderOptionsResolutionInput<TConfig = unknown> {\n\t/** @internal */\n\treadonly definition: ProviderOptionsDefinition<TConfig> | null | undefined;\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly explicit?: Readonly<Record<string, unknown>> | null;\n\t/** @internal */\n\treadonly profileDefaults?: Readonly<Record<string, unknown>> | null;\n}\n\n/** @internal */\nexport interface ProviderOptionValidationIssue {\n\t/** @internal */\n\treadonly fieldId: string;\n\t/** @internal */\n\treadonly code: \"unknown\" | \"not_string\" | \"too_short\" | \"too_long\" | \"required\";\n\t/** @internal */\n\treadonly message: string;\n}\n\n/** @internal */\nexport type ProviderOptionsResolution =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly ok: true;\n\t\t\t/** @internal */\n\t\t\treadonly value: Readonly<Record<string, string>>;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly ok: false;\n\t\t\t/** @internal */\n\t\t\treadonly issues: readonly ProviderOptionValidationIssue[];\n\t };\n\nfunction validateOptionValue<TConfig>(\n\tfieldId: string,\n\tfield: ProviderOptionField<TConfig>,\n\tvalue: unknown,\n): ProviderOptionValidationIssue | null {\n\tif (typeof value !== \"string\") {\n\t\treturn {\n\t\t\tfieldId,\n\t\t\tcode: \"not_string\",\n\t\t\tmessage: `Provider option '${fieldId}' must be a string`,\n\t\t};\n\t}\n\tif (field.minLength !== undefined && value.length < field.minLength) {\n\t\treturn {\n\t\t\tfieldId,\n\t\t\tcode: \"too_short\",\n\t\t\tmessage: `Provider option '${fieldId}' must contain at least ${field.minLength} characters`,\n\t\t};\n\t}\n\tif (field.maxLength !== undefined && value.length > field.maxLength) {\n\t\treturn {\n\t\t\tfieldId,\n\t\t\tcode: \"too_long\",\n\t\t\tmessage: `Provider option '${fieldId}' must contain at most ${field.maxLength} characters`,\n\t\t};\n\t}\n\treturn null;\n}\n\n/**\n * Resolve explicit values, profile defaults, then declared provider defaults.\n * Dynamic choices deliberately do not participate in validation or fallback.\n */\n/** @internal */\nexport function resolveProviderOptions<TConfig = unknown>(\n\tinput: ProviderOptionsResolutionInput<TConfig>,\n): ProviderOptionsResolution {\n\tconst fields = input.definition?.fields ?? {};\n\tconst issues: ProviderOptionValidationIssue[] = [];\n\tfor (const source of [input.explicit, input.profileDefaults]) {\n\t\tfor (const fieldId of Object.keys(source ?? {})) {\n\t\t\tif (!(fieldId in fields)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfieldId,\n\t\t\t\t\tcode: \"unknown\",\n\t\t\t\t\tmessage: `Unknown provider option '${fieldId}'`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tif (issues.length > 0) {\n\t\treturn { ok: false, issues };\n\t}\n\n\tconst resolved: Record<string, string> = {};\n\tfor (const [fieldId, field] of Object.entries(fields)) {\n\t\tconst explicit = input.explicit?.[fieldId];\n\t\tconst profileDefault = input.profileDefaults?.[fieldId];\n\t\tconst declaredDefault =\n\t\t\ttypeof field.defaultValue === \"function\"\n\t\t\t\t? field.defaultValue({ config: input.config })\n\t\t\t\t: field.defaultValue;\n\t\tconst value = explicit ?? profileDefault ?? declaredDefault;\n\t\tif (value === undefined || value === null) {\n\t\t\tif (field.required) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfieldId,\n\t\t\t\t\tcode: \"required\",\n\t\t\t\t\tmessage: `Provider option '${fieldId}' is required`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst issue = validateOptionValue(fieldId, field, value);\n\t\tif (issue) {\n\t\t\tissues.push(issue);\n\t\t\tcontinue;\n\t\t}\n\t\tresolved[fieldId] = value as string;\n\t}\n\treturn issues.length > 0 ? { ok: false, issues } : { ok: true, value: resolved };\n}\n\n/** Keep only fields declared by a newly selected provider. @internal */\nexport function filterProviderOptionsForDefinition<TConfig = unknown>(\n\tdefinition: ProviderOptionsDefinition<TConfig> | null | undefined,\n\tvalues: Readonly<Record<string, string>>,\n): Readonly<Record<string, string>> {\n\tconst fields = definition?.fields ?? {};\n\treturn Object.fromEntries(Object.entries(values).filter(([fieldId]) => fieldId in fields));\n}\n\n/**\n * Runtime-independent schema boundary for non-secret provider worker config.\n * Adapters may wrap Valibot, TypeBox, Zod, or another validator behind parse.\n */\n/** @public */\nexport interface ProviderWorkerConfigSchema<TValue extends ProviderJsonObject> {\n\t/** @public */\n\tparse(value: unknown): TValue;\n}\n\n/** @public */\nexport interface ProviderWorkerConfigContext<TConfig = unknown> {\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @internal */\n\treadonly options: Readonly<Record<string, string>>;\n}\n\n/** @public */\nexport interface ProviderWorkerConfigDefinition<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n> {\n\t/** @public */\n\treadonly version: number;\n\t/** @public */\n\treadonly schema: ProviderWorkerConfigSchema<TValue>;\n\t/** @public */\n\tresolve(ctx: ProviderWorkerConfigContext<TConfig>): TValue;\n}\n\n/** @public */\nexport function defineWorkerConfig<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n>(\n\tdefinition: ProviderWorkerConfigDefinition<TConfig, TValue>,\n): ProviderWorkerConfigDefinition<TConfig, TValue> {\n\tif (!Number.isInteger(definition.version) || definition.version < 1) {\n\t\tthrow new Error(\"Provider worker config version must be a positive integer\");\n\t}\n\treturn definition;\n}\n\n/** @public */\nexport interface PiWorkerReference<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n> {\n\t/** @public */\n\treadonly kind: \"extension_pi_worker\";\n\t/** @internal */\n\treadonly config?: ProviderWorkerConfigDefinition<TConfig, TValue>;\n\t/** Mutable, flat JSON credential files required by this provider's Pi extension. @internal */\n\treadonly credentialFiles?: readonly string[];\n}\n\n/** @public */\nexport interface PiServerReference {\n\t/** @internal */\n\treadonly kind: \"extension_pi_server\";\n}\n\n/** @public */\nexport interface PiServerGenerateTextInput<TConfig = unknown> {\n\t/** @public */\n\treadonly providerId: string;\n\t/** @public */\n\treadonly modelId: string;\n\t/** @public */\n\treadonly thinkingLevel: string;\n\t/** @public */\n\treadonly prompt: string;\n\t/** @public */\n\treadonly systemPrompt: string;\n\t/** @public */\n\treadonly maxTokens: number;\n\t/** @public */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly options: Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly secrets: Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly request: {\n\t\t/** @public */\n\t\treadonly timeoutMs?: number;\n\t\t/** @internal */\n\t\treadonly maxRetries?: number;\n\t\t/** @public */\n\t\treadonly maxRetryDelayMs: number;\n\t};\n}\n\n/** Server-only provider boundary for title generation and future cheap LLM consumers. @public */\nexport interface PiServerAdapter<TConfig = unknown> {\n\t/** @public */\n\tgenerateText(input: PiServerGenerateTextInput<TConfig>): Promise<string>;\n}\n\n/** @public */\nexport function definePiServerAdapter<TConfig = unknown>(\n\tadapter: PiServerAdapter<TConfig>,\n): PiServerAdapter<TConfig> {\n\tif (!adapter || typeof adapter.generateText !== \"function\") {\n\t\tthrow new Error(\"Pi server adapter must define generateText()\");\n\t}\n\treturn adapter;\n}\n\n/** @public */\nexport interface BuiltinPiProviderReference {\n\t/** @public */\n\treadonly kind: \"builtin_pi_provider\";\n\t/** @internal */\n\treadonly providerId: string;\n}\n\n/** @public */\nexport interface ConfiguredPiProviderReference<TConfig = unknown> {\n\t/** @public */\n\treadonly kind: \"configured_pi_provider\";\n\t/** @internal */\n\treadonly providerId: string;\n\t/** Resolve the credential-blind models.json document pinned into each worker snapshot. @internal */\n\tresolveModels(ctx: {\n\t\t/** @internal */\n\t\treadonly config: TConfig;\n\t}): ProviderJsonObject;\n}\n\n/** @public */\nexport function piWorker<TConfig = unknown, TValue extends ProviderJsonObject = ProviderJsonObject>(\n\tinput: {\n\t\t/** @public */\n\t\tconfig?: ProviderWorkerConfigDefinition<TConfig, TValue>;\n\t\t/** @public */\n\t\tcredentialFiles?: readonly string[];\n\t} = {},\n): PiWorkerReference<TConfig, TValue> {\n\tconst credentialFiles = input.credentialFiles?.map((file) => {\n\t\tif (!file || file.startsWith(\"/\") || file.includes(\"..\") || file.includes(\"\\\\\\\\\")) {\n\t\t\tthrow new Error(\"Pi worker credential file must be a relative path\");\n\t\t}\n\t\treturn file;\n\t});\n\treturn {\n\t\tkind: \"extension_pi_worker\",\n\t\t...input,\n\t\t...(credentialFiles ? { credentialFiles } : {}),\n\t};\n}\n\n/** @public */\nexport function piServer(): PiServerReference {\n\treturn { kind: \"extension_pi_server\" };\n}\n\n/** @public */\nexport function builtinPiProvider(providerId: string): BuiltinPiProviderReference {\n\tif (providerId.trim() === \"\") {\n\t\tthrow new Error(\"Built-in Pi provider id must not be empty\");\n\t}\n\treturn { kind: \"builtin_pi_provider\", providerId };\n}\n\n/** @internal */\nexport function configuredPiProvider<TConfig>(\n\tproviderId: string,\n\tresolveModels: ConfiguredPiProviderReference<TConfig>[\"resolveModels\"],\n): ConfiguredPiProviderReference<TConfig> {\n\tif (providerId.trim() === \"\") {\n\t\tthrow new Error(\"Configured Pi provider id must not be empty\");\n\t}\n\treturn { kind: \"configured_pi_provider\", providerId, resolveModels };\n}\n\n/** @public */\nexport type ModelProviderWorker<\n\tTConfig = unknown,\n\tTValue extends ProviderJsonObject = ProviderJsonObject,\n> =\n\t| PiWorkerReference<TConfig, TValue>\n\t| BuiltinPiProviderReference\n\t| ConfiguredPiProviderReference<TConfig>;\n\n/** @public */\nexport type ModelProviderServer = PiServerReference | BuiltinPiProviderReference;\n\n/** @public */\nexport interface ModelProviderSecretsContext<TConfig = unknown, TCredential = unknown> {\n\t/** @internal */\n\treadonly config: TConfig;\n\t/** @public */\n\treadonly credential: TCredential | null;\n\t/** @internal */\n\treadonly options: Readonly<Record<string, string>>;\n}\n\n/** @public */\nexport interface ParsedModelProviderConfig<TConfig = unknown, TCredential = unknown> {\n\t/** Restart-scoped, non-secret provider configuration. @public */\n\treadonly config: TConfig;\n\t/** Optional credential used only to initialize an empty durable credential store. @internal */\n\treadonly credential?: TCredential;\n}\n\n/** @public */\nexport interface ModelProviderCredentialDefinition<TCredential = unknown> {\n\t/** Validates configured, durable, and worker-refreshed credential data. @public */\n\tparse?(value: unknown): TCredential;\n}\n\n/** @public */\nexport interface ModelProviderDefinition<\n\tTConfig = unknown,\n\tTCredential = unknown,\n\tTWorkerConfig extends ProviderJsonObject = ProviderJsonObject,\n> {\n\t/** @public */\n\treadonly id: string;\n\t/** @public */\n\tparseConfig(raw: unknown): ParsedModelProviderConfig<TConfig, TCredential>;\n\t/** @public */\n\treadonly worker: ModelProviderWorker<TConfig, TWorkerConfig>;\n\t/** @public */\n\treadonly server?: ModelProviderServer;\n\t/** @public */\n\tmodels(\n\t\tctx: ModelProviderModelsContext<TConfig>,\n\t): readonly ProviderModelStatus[] | Promise<readonly ProviderModelStatus[]>;\n\t/** @public */\n\treadonly options?: ProviderOptionsDefinition<TConfig>;\n\t/** @public */\n\tsecrets(ctx: ModelProviderSecretsContext<TConfig, TCredential>): Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly credential?: ModelProviderCredentialDefinition<TCredential>;\n}\n\n/** @public */\nexport function defineModelProvider<\n\tTConfig = unknown,\n\tTCredential = unknown,\n\tTWorkerConfig extends ProviderJsonObject = ProviderJsonObject,\n>(\n\tdefinition: ModelProviderDefinition<TConfig, TCredential, TWorkerConfig>,\n): ModelProviderDefinition<TConfig, TCredential, TWorkerConfig> {\n\tif (definition.id.trim() === \"\") {\n\t\tthrow new Error(\"Model provider id must not be empty\");\n\t}\n\treturn definition;\n}\n\n/** Type-erased provider definition used after its typed boundary has been established. @public */\n// biome-ignore lint/suspicious/noExplicitAny: provider sets intentionally erase provider-owned generic types\nexport type ErasedModelProviderDefinition = ModelProviderDefinition<any, any, any>;\n\n/** @public */\nexport interface ModelProviderSetEntry {\n\t/** @public */\n\treadonly definition: ErasedModelProviderDefinition;\n\t/** Owner-scoped fragment passed to this provider's parseConfig(). @public */\n\treadonly rawConfig: unknown;\n}\n\n/** Resolves every provider owned by one extension from its owner-scoped configuration. @public */\nexport type ModelProviderSet = (ownerConfig: unknown) => readonly ModelProviderSetEntry[];\n\n/** @public */\nexport function defineModelProviders(resolve: ModelProviderSet): ModelProviderSet {\n\treturn resolve;\n}\n\n/** @public */\nexport interface PiWorkerSecretBag {\n\t/** @public */\n\tget(key: string): string | undefined;\n\t/** @public */\n\trequire(key: string): string;\n\t/** @public */\n\tkeys(): readonly string[];\n}\n\n/** @public */\nexport interface PiWorkerContributionContext {\n\t/** @public */\n\treadonly model: {\n\t\t/** @public */\n\t\treadonly providerId: string;\n\t\t/** @public */\n\t\treadonly modelId: string;\n\t};\n\t/** @public */\n\treadonly options: Readonly<Record<string, string>>;\n\t/** @public */\n\treadonly workerConfig: ProviderJsonObject | null;\n\t/** @public */\n\treadonly secrets: PiWorkerSecretBag;\n\t/** @public */\n\treport(event: Readonly<Record<string, ProviderJsonValue>>): void;\n}\n\n/** @public */\nexport type PiWorkerContribution = (\n\tpi: {\n\t\t/** @public */\n\t\tregisterProvider(name: string, config: object): void;\n\t},\n\tctx: PiWorkerContributionContext,\n) => void | Promise<void>;\n\n/** @public */\nexport function definePiWorker(contribution: PiWorkerContribution): PiWorkerContribution {\n\treturn contribution;\n}\n\n/**\n * Report each distinct configured model as available or unavailable based solely\n * on credential status. Providers that do not perform runtime model probing can\n * delegate their `models()` callback to this helper.\n */\n/** @public */\nexport function credentialBasedModelStatuses(\n\tconfiguredModels: readonly ConfiguredProviderModel[],\n\tcredentialStatus: ProviderCredentialStatus,\n\tunavailableReason: string,\n): readonly ProviderModelStatus[] {\n\treturn [...new Set(configuredModels.map((configured) => configured.modelId))].map((modelId) => ({\n\t\tmodelId,\n\t\tavailability: credentialStatus.available ? \"available\" : \"unavailable\",\n\t\t...(credentialStatus.available ? {} : { safeReason: unavailableReason }),\n\t}));\n}\n","import {\n\thumanizeProcessLabel,\n\ttype ProcessFlowEdge,\n\ttype ProcessFlowEndState,\n\ttype ProcessFlowNode,\n\ttype ProcessFlowView,\n\ttype ProcessTurnTerminalLifecycleStatus,\n\ttype ProcessTurnTransition,\n\ttype TurnId,\n\ttrimToNull,\n} from \"@leitwerk-dev/domain\";\nimport type { ProcessGraphTurnView, ProcessGraphView } from \"./process-graph.js\";\n\n/**\n * Human/operator turns are routing decisions: they pick which path the process\n * takes but perform no work themselves. They are collapsed out of the flow graph\n * so the chart shows only work nodes (LLM/automatic/server) and end states, with\n * the operator's decision surfaced as the edge label between the real nodes.\n */\nfunction isRoutingTurn(turn: ProcessGraphTurnView): boolean {\n\treturn turn.turnType === \"human\";\n}\n\n/**\n * Picks the work turn an operator decision is *about* — its anchor. A decision is\n * both a join (many work turns lead into it) and a split (the operator picks one\n * of several actions). Folding the split onto every join predecessor would invent\n * an N×M mesh of work→work edges that no single step actually connects (e.g. a\n * \"review implementation → simplify\" edge that does not exist in the process).\n *\n * Instead, every operator decision collapses into exactly one anchor work node:\n * - edges that lead *into* the decision are redirected to the anchor, and\n * - the decision's action edges are emitted *from* the anchor.\n *\n * That yields N+M edges around one real node instead of N×M fabricated ones, and\n * every surviving edge still maps to a single declared transition with one human\n * hop folded into the work node that owns the decision.\n *\n * The anchor is the work predecessor the decision belongs to, preferring a\n * predecessor on the declared happy path (earliest position), then the earliest\n * declared work predecessor. Decisions reached only from other decisions inherit\n * their predecessor decision's anchor.\n */\nfunction computeRoutingAnchors(\n\tgraph: ProcessGraphView,\n\troutingIds: ReadonlySet<TurnId>,\n): Map<TurnId, TurnId> {\n\t// Happy-path turns come first, then the remaining turns in declaration order.\n\tconst preferenceIndex = new Map(\n\t\t[...new Set([...(graph.happyPath ?? []), ...graph.turns.keys()])].map((turnId, index) => [\n\t\t\tturnId,\n\t\t\tindex,\n\t\t]),\n\t);\n\n\tconst workPredecessors = new Map<TurnId, TurnId[]>();\n\tconst routingPredecessors = new Map<TurnId, TurnId[]>();\n\tfor (const routingId of routingIds) {\n\t\tworkPredecessors.set(routingId, []);\n\t\troutingPredecessors.set(routingId, []);\n\t}\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst next = transition.nextTurnId;\n\t\t\tif (next === undefined || !routingIds.has(next) || next === turnId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (routingIds.has(turnId)) {\n\t\t\t\troutingPredecessors.get(next)?.push(turnId);\n\t\t\t} else {\n\t\t\t\tworkPredecessors.get(next)?.push(turnId);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst pickPreferred = (candidates: readonly TurnId[]): TurnId | undefined => {\n\t\tlet best: TurnId | undefined;\n\t\tlet bestIndex = Number.POSITIVE_INFINITY;\n\t\tfor (const candidate of candidates) {\n\t\t\tconst index = preferenceIndex.get(candidate) ?? Number.POSITIVE_INFINITY;\n\t\t\tif (best === undefined || index < bestIndex) {\n\t\t\t\tbest = candidate;\n\t\t\t\tbestIndex = index;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t};\n\n\tconst anchors = new Map<TurnId, TurnId>();\n\tfor (const routingId of routingIds) {\n\t\tconst preferred = pickPreferred(workPredecessors.get(routingId) ?? []);\n\t\tif (preferred !== undefined) {\n\t\t\tanchors.set(routingId, preferred);\n\t\t}\n\t}\n\n\t// Decisions reached only from other decisions resolve transitively to the\n\t// anchor of a predecessor decision. Iterate to a fixpoint.\n\tlet changed = true;\n\twhile (changed) {\n\t\tchanged = false;\n\t\tfor (const routingId of routingIds) {\n\t\t\tif (anchors.has(routingId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const predecessor of routingPredecessors.get(routingId) ?? []) {\n\t\t\t\tconst predecessorAnchor = anchors.get(predecessor);\n\t\t\t\tif (predecessorAnchor !== undefined) {\n\t\t\t\t\tanchors.set(routingId, predecessorAnchor);\n\t\t\t\t\tchanged = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Any decision still unresolved (an isolated decision-only cluster) falls back\n\t// to the first declared work turn so the graph stays connected and deterministic.\n\tconst fallbackWork = [...graph.turns.keys()].find((turnId) => !routingIds.has(turnId));\n\tif (fallbackWork !== undefined) {\n\t\tfor (const routingId of routingIds) {\n\t\t\tif (!anchors.has(routingId)) {\n\t\t\t\tanchors.set(routingId, fallbackWork);\n\t\t\t}\n\t\t}\n\t}\n\treturn anchors;\n}\n\nfunction redirectTransition(\n\ttransition: ProcessTurnTransition,\n\tresolveWork: (turnId: TurnId) => TurnId,\n): ProcessTurnTransition {\n\tconst label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);\n\tif (transition.lifecycleStatus !== undefined) {\n\t\treturn {\n\t\t\tlifecycleStatus: transition.lifecycleStatus,\n\t\t\t...(label ? { outcome: label } : {}),\n\t\t};\n\t}\n\tconst next = transition.nextTurnId;\n\tif (next === undefined) {\n\t\treturn { ...(label ? { outcome: label } : {}) };\n\t}\n\treturn {\n\t\tnextTurnId: resolveWork(next),\n\t\t...(label ? { outcome: label } : {}),\n\t};\n}\n\nfunction dedupeTransitions(transitions: readonly ProcessTurnTransition[]): ProcessTurnTransition[] {\n\tconst result = new Map<string, ProcessTurnTransition>();\n\tfor (const transition of transitions) {\n\t\tconst label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);\n\t\tconst key = `${transition.nextTurnId ?? \"\"}|${transition.lifecycleStatus ?? \"\"}|${label ?? \"\"}`;\n\t\tif (result.has(key)) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.set(key, transition);\n\t}\n\treturn [...result.values()];\n}\n\n/**\n * Removes routing (human) turns from a process graph by merging each one into a\n * single anchor work node (see {@link computeRoutingAnchors}). Edges into a\n * decision are redirected to its anchor, and the decision's action edges are\n * re-emitted from that anchor. Self-loops produced by the merge are left in place\n * here and dropped later during edge construction. Entry turns and the declared\n * happy path are remapped/filtered to stay consistent.\n */\n/** @internal */\nexport function collapseRoutingTurns(graph: ProcessGraphView): ProcessGraphView {\n\tconst routingIds = new Set<TurnId>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tif (isRoutingTurn(turn)) {\n\t\t\troutingIds.add(turnId);\n\t\t}\n\t}\n\tif (routingIds.size === 0 || routingIds.size === graph.turns.size) {\n\t\treturn graph;\n\t}\n\n\tconst anchors = computeRoutingAnchors(graph, routingIds);\n\tconst resolveWork = (turnId: TurnId): TurnId =>\n\t\troutingIds.has(turnId) ? (anchors.get(turnId) ?? turnId) : turnId;\n\n\t// Group each decision's action transitions onto its anchor work turn.\n\tconst inheritedByAnchor = new Map<TurnId, ProcessTurnTransition[]>();\n\tfor (const routingId of routingIds) {\n\t\tconst anchor = anchors.get(routingId);\n\t\tif (anchor === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst routingTurn = graph.turns.get(routingId);\n\t\tif (!routingTurn) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst bucket = inheritedByAnchor.get(anchor) ?? [];\n\t\tfor (const transition of routingTurn.transitions) {\n\t\t\tbucket.push(redirectTransition(transition, resolveWork));\n\t\t}\n\t\tinheritedByAnchor.set(anchor, bucket);\n\t}\n\n\tconst turns = new Map<TurnId, ProcessGraphTurnView>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tif (routingIds.has(turnId)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst transitions = [\n\t\t\t...turn.transitions.map((transition) => redirectTransition(transition, resolveWork)),\n\t\t\t...(inheritedByAnchor.get(turnId) ?? []),\n\t\t];\n\t\tturns.set(turnId, { ...turn, transitions: dedupeTransitions(transitions) });\n\t}\n\n\tconst entryTurnIds = new Set<TurnId>();\n\tfor (const entry of graph.entryTurnIds) {\n\t\tif (graph.turns.has(entry)) {\n\t\t\tentryTurnIds.add(resolveWork(entry));\n\t\t}\n\t}\n\n\tconst filteredHappyPath = graph.happyPath?.filter((turnId) => !routingIds.has(turnId)) ?? null;\n\n\treturn {\n\t\tid: graph.id,\n\t\tprimaryEntryTurnId: resolveWork(graph.primaryEntryTurnId),\n\t\tentryTurnIds,\n\t\thappyPath: filteredHappyPath && filteredHappyPath.length > 0 ? filteredHappyPath : null,\n\t\tturns,\n\t};\n}\n\n/**\n * Best-effort spine when a process does not declare an explicit happy path.\n * Walks `nextTurnId` edges breadth-first from the entry turn to the nearest turn\n * that can reach a `completed` terminal, preferring the shortest forward path and\n * breaking ties by transition declaration order. Returns `[entry]` when no\n * completing path exists.\n */\nfunction deriveSpine(graph: ProcessGraphView, entry: TurnId): TurnId[] {\n\tconst predecessor = new Map<TurnId, TurnId | null>([[entry, null]]);\n\tconst queue: TurnId[] = [entry];\n\tlet goal: TurnId | null = null;\n\tfor (const current of queue) {\n\t\tconst turn = graph.turns.get(current);\n\t\tif (!turn) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (turn.transitions.some((transition) => transition.lifecycleStatus === \"completed\")) {\n\t\t\tgoal = current;\n\t\t\tbreak;\n\t\t}\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst next = transition.nextTurnId;\n\t\t\tif (next === undefined || predecessor.has(next) || !graph.turns.has(next)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpredecessor.set(next, current);\n\t\t\tqueue.push(next);\n\t\t}\n\t}\n\n\tif (goal === null) {\n\t\treturn [entry];\n\t}\n\tconst reversed: TurnId[] = [];\n\tlet cursor: TurnId | null = goal;\n\twhile (cursor !== null) {\n\t\treversed.push(cursor);\n\t\tcursor = predecessor.get(cursor) ?? null;\n\t}\n\treturn reversed.reverse();\n}\n\n/**\n * Assigns each non-spine turn to the spine node it hangs off. A branch is anchored\n * to the lowest-index spine node that can reach it without passing through another\n * spine node, so offshoots attach to the earliest spine step that launches them.\n */\nfunction deriveBranchAnchors(\n\tgraph: ProcessGraphView,\n\tspineIndexByTurn: ReadonlyMap<TurnId, number>,\n): Map<TurnId, TurnId> {\n\tconst anchorByTurn = new Map<TurnId, TurnId>();\n\tconst orderedSpine = [...spineIndexByTurn.entries()]\n\t\t.sort((left, right) => left[1] - right[1])\n\t\t.map(([turnId]) => turnId);\n\n\tfor (const spineTurnId of orderedSpine) {\n\t\tconst stack: TurnId[] = [spineTurnId];\n\t\tconst visited = new Set<TurnId>([spineTurnId]);\n\t\twhile (stack.length > 0) {\n\t\t\tconst current = stack.pop() as TurnId;\n\t\t\tconst turn = graph.turns.get(current);\n\t\t\tif (!turn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const transition of turn.transitions) {\n\t\t\t\tconst next = transition.nextTurnId;\n\t\t\t\tif (next === undefined || !graph.turns.has(next) || visited.has(next)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvisited.add(next);\n\t\t\t\tif (spineIndexByTurn.has(next)) {\n\t\t\t\t\t// Stop at spine nodes; do not traverse through them.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!anchorByTurn.has(next)) {\n\t\t\t\t\tanchorByTurn.set(next, spineTurnId);\n\t\t\t\t}\n\t\t\t\tstack.push(next);\n\t\t\t}\n\t\t}\n\t}\n\treturn anchorByTurn;\n}\n\nfunction transitionLabel(transition: { outcome?: string; trigger?: string }): string | null {\n\t// Route every operator-facing edge label through the shared humanizer so the\n\t// diagram shows nice Title Case names (e.g. `approve_plan` -> `Approve Plan`),\n\t// consistent with action forms and ready for future localization.\n\tconst raw = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);\n\treturn raw === null ? null : humanizeProcessLabel(raw);\n}\n\n/**\n * Projects a process graph into a spine-first flow view for operator-facing\n * diagrams. The spine is the declared happy path (or a derived best-effort path\n * when none is declared); every other turn hangs off the spine as a branch.\n * The `aborted` end state is always present because abort is reachable from any\n * active turn, even when no explicit transition targets it.\n */\n/** @internal */\nexport function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowView {\n\tconst graph = collapseRoutingTurns(rawGraph);\n\tconst entryTurnIds = [...graph.entryTurnIds].filter((turnId) => graph.turns.has(turnId));\n\tconst primaryEntry = graph.turns.has(graph.primaryEntryTurnId)\n\t\t? graph.primaryEntryTurnId\n\t\t: [...graph.turns.keys()][0];\n\n\tconst declaredSpine = graph.happyPath?.filter((turnId) => graph.turns.has(turnId)) ?? null;\n\tconst spine =\n\t\tdeclaredSpine && declaredSpine.length > 0\n\t\t\t? [...declaredSpine]\n\t\t\t: primaryEntry !== undefined\n\t\t\t\t? deriveSpine(graph, primaryEntry)\n\t\t\t\t: [];\n\n\tconst spineIndexByTurn = new Map<TurnId, number>();\n\tspine.forEach((turnId, index) => {\n\t\tspineIndexByTurn.set(turnId, index);\n\t});\n\n\tconst anchorByTurn = deriveBranchAnchors(graph, spineIndexByTurn);\n\tconst entrySet = new Set(entryTurnIds);\n\n\tconst nodes: ProcessFlowNode[] = [];\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tconst spineIndex = spineIndexByTurn.get(turnId) ?? null;\n\t\tnodes.push({\n\t\t\tturnId,\n\t\t\tdescription: trimToNull(turn.description) ?? turnId,\n\t\t\tturnType: turn.turnType,\n\t\t\trole: spineIndex === null ? \"branch\" : \"spine\",\n\t\t\tspineIndex,\n\t\t\tanchorTurnId: spineIndex === null ? (anchorByTurn.get(turnId) ?? null) : null,\n\t\t\tisEntry: entrySet.has(turnId),\n\t\t});\n\t}\n\n\tconst edges: ProcessFlowEdge[] = [];\n\tconst terminalStatuses = new Set<ProcessTurnTerminalLifecycleStatus>();\n\tfor (const [turnId, turn] of graph.turns) {\n\t\tfor (const transition of turn.transitions) {\n\t\t\tconst label = transitionLabel(transition);\n\t\t\tif (transition.lifecycleStatus !== undefined) {\n\t\t\t\tterminalStatuses.add(transition.lifecycleStatus);\n\t\t\t\tedges.push({\n\t\t\t\t\tfrom: turnId,\n\t\t\t\t\tto: null,\n\t\t\t\t\tlifecycleStatus: transition.lifecycleStatus,\n\t\t\t\t\tkind: \"terminal\",\n\t\t\t\t\tlabel,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst next = transition.nextTurnId;\n\t\t\t// Skip self-loops: an edge that leaves and re-enters the same box adds\n\t\t\t// clutter without conveying additional flow.\n\t\t\tif (next === undefined || next === turnId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst fromIndex = spineIndexByTurn.get(turnId);\n\t\t\tconst toIndex = spineIndexByTurn.get(next);\n\t\t\tlet kind: ProcessFlowEdge[\"kind\"];\n\t\t\tif (fromIndex !== undefined && toIndex !== undefined) {\n\t\t\t\tkind = toIndex === fromIndex + 1 ? \"forward\" : \"loopback\";\n\t\t\t} else {\n\t\t\t\tkind = \"branch\";\n\t\t\t}\n\t\t\tedges.push({ from: turnId, to: next, lifecycleStatus: null, kind, label });\n\t\t}\n\t}\n\n\tconst endStates: ProcessFlowEndState[] = [];\n\tfor (const status of terminalStatuses) {\n\t\tendStates.push({ lifecycleStatus: status, synthetic: false });\n\t}\n\tif (!terminalStatuses.has(\"aborted\")) {\n\t\tendStates.push({ lifecycleStatus: \"aborted\", synthetic: true });\n\t}\n\tendStates.sort((left, right) => left.lifecycleStatus.localeCompare(right.lifecycleStatus));\n\n\treturn {\n\t\tprocessId: graph.id,\n\t\tentryTurnIds,\n\t\tspine,\n\t\tnodes,\n\t\tedges,\n\t\tendStates,\n\t};\n}\n","import type {\n\tExtensionProcessDefinition,\n\tProcessLauncherAPI,\n\tProcessLauncherDefinition,\n} from \"./extension-api.js\";\nimport { cloneMap, registerUnique } from \"./registry-utils.js\";\n\n/** @public */\nexport interface BuiltProcessLauncherDefinition<TParams = unknown> {\n\t/** @public */\n\tlaunchers: ReadonlyMap<string, ProcessLauncherDefinition<TParams>>;\n}\n\nfunction validateLauncherDefinition<TParams>(def: ProcessLauncherDefinition<TParams>): void {\n\tif (!def.id.trim()) {\n\t\tthrow new Error(\"Launcher id is required\");\n\t}\n\tif (!def.label.trim()) {\n\t\tthrow new Error(`Launcher '${def.id}' must define a non-empty label`);\n\t}\n\tif (!def.description.trim()) {\n\t\tthrow new Error(`Launcher '${def.id}' must define a non-empty description`);\n\t}\n\tif (def.visibility !== \"ui\") {\n\t\tthrow new Error(`Launcher '${def.id}' has unsupported visibility`);\n\t}\n\tif (!def.ui) {\n\t\tthrow new Error(`UI launcher '${def.id}' must define a ui block`);\n\t}\n}\n\n/** @internal */\nexport function createProcessLauncherBuilder<TParams = unknown>(): ProcessLauncherAPI<TParams> & {\n\t/** @internal */\n\tgetDefinition(): BuiltProcessLauncherDefinition<TParams>;\n} {\n\tconst launchers = new Map<string, ProcessLauncherDefinition<TParams>>();\n\n\treturn {\n\t\tlauncher(def: ProcessLauncherDefinition<TParams>) {\n\t\t\tregisterUnique(launchers, def.id, def, {\n\t\t\t\tduplicateMessage: `Launcher '${def.id}' is already registered`,\n\t\t\t\tvalidate: validateLauncherDefinition,\n\t\t\t});\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\tlaunchers: cloneMap(launchers),\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** @public */\nexport function buildProcessLaunchers<TParams = unknown, TState = unknown>(\n\tprocess: ExtensionProcessDefinition<TParams, TState>,\n): BuiltProcessLauncherDefinition<TParams> | undefined {\n\tif (!process.launchers) {\n\t\treturn undefined;\n\t}\n\tconst builder = createProcessLauncherBuilder<TParams>();\n\tprocess.launchers(builder);\n\treturn builder.getDefinition();\n}\n","import type {\n\tExtensionProcessDefinition,\n\tProcessWatcherAPI,\n\tProcessWatcherDefinition,\n} from \"./extension-api.js\";\nimport { cloneMap, registerUnique } from \"./registry-utils.js\";\n\n/** @public */\nexport interface BuiltProcessWatcherDefinition<TParams = unknown> {\n\t/** @public */\n\twatchers: ReadonlyMap<string, ProcessWatcherDefinition<TParams, unknown, unknown>>;\n}\n\nfunction validateWatcherDefinition<TParams>(\n\tdef: ProcessWatcherDefinition<TParams, unknown, unknown>,\n): void {\n\tif (!def.id.trim()) {\n\t\tthrow new Error(\"Process watcher id is required\");\n\t}\n\tif (!def.label.trim()) {\n\t\tthrow new Error(`Process watcher '${def.id}' must define a non-empty label`);\n\t}\n\tif (!def.description.trim()) {\n\t\tthrow new Error(`Process watcher '${def.id}' must define a non-empty description`);\n\t}\n\tif (!def.source || def.source.id.trim() === \"\") {\n\t\tthrow new Error(`Process watcher '${def.id}' must define a watcher source`);\n\t}\n}\n\n/** @internal */\nexport function createProcessWatcherBuilder<TParams = unknown>(): ProcessWatcherAPI<TParams> & {\n\t/** @internal */\n\tgetDefinition(): BuiltProcessWatcherDefinition<TParams>;\n} {\n\tconst watchers = new Map<string, ProcessWatcherDefinition<TParams, unknown, unknown>>();\n\n\treturn {\n\t\twatcher<TEvent = unknown, TConfig = unknown>(\n\t\t\tdef: ProcessWatcherDefinition<TParams, TEvent, TConfig>,\n\t\t) {\n\t\t\tregisterUnique(\n\t\t\t\twatchers,\n\t\t\t\tdef.id,\n\t\t\t\tdef as unknown as ProcessWatcherDefinition<TParams, unknown, unknown>,\n\t\t\t\t{\n\t\t\t\t\tduplicateMessage: `Process watcher '${def.id}' is already registered`,\n\t\t\t\t\tvalidate: validateWatcherDefinition,\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\twatchers: cloneMap(watchers),\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** @public */\nexport function buildProcessWatchers<TParams = unknown, TState = unknown>(\n\tprocess: ExtensionProcessDefinition<TParams, TState>,\n): BuiltProcessWatcherDefinition<TParams> | undefined {\n\tif (!process.watchers) {\n\t\treturn undefined;\n\t}\n\tconst builder = createProcessWatcherBuilder<TParams>();\n\tprocess.watchers(builder);\n\treturn builder.getDefinition();\n}\n","/** Object parameters for a tool bound to a current process project. @public */\nexport function projectParameters(\n\tproperties: Record<string, unknown> = {},\n\trequired: readonly string[] = Object.keys(properties),\n): Record<string, unknown> {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {\n\t\t\tprojectKey: { type: \"string\", description: \"Current process project key\" },\n\t\t\t...properties,\n\t\t},\n\t\trequired: [\"projectKey\", ...required],\n\t};\n}\n\n/** @public */\nexport function objectArg(\n\tvalue: unknown,\n\tmessage = \"Tool arguments must be an object\",\n): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(message);\n\treturn value as Record<string, unknown>;\n}\n\n/** Read required integration-tool arguments at the runtime boundary. @public */\nexport function stringArg(args: Record<string, unknown>, name: string): string {\n\tconst value = args[name];\n\tif (typeof value !== \"string\" || !value.trim())\n\t\tthrow new Error(`'${name}' must be a non-empty string`);\n\treturn value.trim();\n}\n\n/** @public */\nexport function numberArg(args: Record<string, unknown>, name: string): number {\n\tconst value = args[name];\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0)\n\t\tthrow new Error(`'${name}' must be a positive integer`);\n\treturn value;\n}\n","import type { LaunchModelConfigInput } from \"@leitwerk-dev/domain\";\nimport type { ProcessWatcherSource } from \"./extension-api.js\";\nimport { objectArg } from \"./tool-arguments.js\";\n\nconst record = (value: unknown, subject: string) =>\n\tobjectArg(value, `${subject} must be an object`);\n\nfunction nonEmptyString(value: unknown, path: string): string {\n\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\tthrow new Error(`${path} must be a non-empty string`);\n\t}\n\treturn value;\n}\n\n/** Parse the shared launch-model fragment nested inside extension-owned watcher config. @public */\nexport function parseProcessWatcherLaunchModelConfig(value: unknown): LaunchModelConfigInput & {\n\t/** @internal */\n\tskillIds: string[];\n} {\n\tif (value === undefined) return { defaultModelProfileId: null, turnConfigs: {}, skillIds: [] };\n\tconst launch = record(value, \"launch\");\n\tconst rawSkills = launch.skills === undefined ? [] : launch.skills;\n\tif (!Array.isArray(rawSkills)) throw new Error(\"launch.skills must be an array\");\n\tconst skillIds = rawSkills.map((skill, index) => nonEmptyString(skill, `launch.skills.${index}`));\n\tif (new Set(skillIds).size !== skillIds.length)\n\t\tthrow new Error(\"launch.skills contains duplicates\");\n\tconst rawTurns =\n\t\tlaunch.turn_configs === undefined ? {} : record(launch.turn_configs, \"launch.turn_configs\");\n\treturn {\n\t\tdefaultModelProfileId:\n\t\t\tlaunch.default_model_profile === undefined\n\t\t\t\t? null\n\t\t\t\t: nonEmptyString(launch.default_model_profile, \"launch.default_model_profile\"),\n\t\tturnConfigs: Object.fromEntries(\n\t\t\tObject.entries(rawTurns).map(([turnId, value]) => {\n\t\t\t\tconst turn = record(value, `launch.turn_configs.${turnId}`);\n\t\t\t\treturn [\n\t\t\t\t\tturnId,\n\t\t\t\t\t{\n\t\t\t\t\t\tmodelProfileId:\n\t\t\t\t\t\t\tturn.model_profile === undefined\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: nonEmptyString(turn.model_profile, `launch.turn_configs.${turnId}.model_profile`),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}),\n\t\t),\n\t\tskillIds,\n\t};\n}\n\n/** @public */\nexport function defineProcessWatcherSource<TConfig, TEvent = unknown>(\n\tsource: ProcessWatcherSource<TConfig, TEvent>,\n): ProcessWatcherSource<TConfig, TEvent> {\n\tif (source.id.trim() === \"\") {\n\t\tthrow new Error(\"Process watcher source id must not be empty\");\n\t}\n\tif (source.label.trim() === \"\") {\n\t\tthrow new Error(`Process watcher source '${source.id}' must define a non-empty label`);\n\t}\n\treturn source;\n}\n","import type { IntegrationToolExecutionContext } from \"./extension-api.js\";\nimport { objectArg } from \"./tool-arguments.js\";\n\n/** @public */\nexport interface RepositoryProjectBinding {\n\t/** @public */\n\towner: string;\n\t/** @public */\n\trepo: string;\n\t/** @public */\n\tprofile: string;\n}\n\n/** Validate an authorized project's binding, retaining extension-selected legacy metadata. @public */\nexport function resolveRepositoryProjectBinding(\n\tctx: Pick<IntegrationToolExecutionContext, \"project\" | \"process\">,\n\tprovider: string,\n\tlegacyMetadataKey?: string,\n): RepositoryProjectBinding {\n\tconst object = (value: unknown) => objectArg(value, `Invalid ${provider} project binding`);\n\tfunction text(value: unknown, key: string): string {\n\t\tif (typeof value !== \"string\" || !value.trim())\n\t\t\tthrow new Error(`${provider} binding ${key} must be a non-empty string`);\n\t\treturn value.trim();\n\t}\n\tif (!ctx.project || ctx.project.instanceId !== ctx.process.id)\n\t\tthrow new Error(\"An authorized process project is required\");\n\tconst metadata = object(ctx.project.metadata ?? {});\n\tconst useLegacy = legacyMetadataKey !== undefined && metadata[provider] === undefined;\n\tconst binding = object(metadata[useLegacy ? legacyMetadataKey : provider]);\n\tconst profile =\n\t\tuseLegacy || (legacyMetadataKey === undefined && binding.profile === undefined)\n\t\t\t? object(JSON.parse(ctx.process.paramsJson ?? \"{}\"))[`${provider}Profile`]\n\t\t\t: binding.profile;\n\treturn {\n\t\towner: text(binding.owner, \"owner\"),\n\t\trepo: text(binding.repo, \"repo\"),\n\t\tprofile: text(profile, \"profile\"),\n\t};\n}\n","import { asUnknownRecord } from \"@leitwerk-dev/domain\";\n\n/** @public */\nexport interface RepositoryFeedbackItem {\n\t/** @public */\n\tkind: \"conversation\" | \"review\" | \"inline\";\n\t/** @public */\n\tid: number;\n\t/** @public */\n\tbody: string;\n\t/** @public */\n\tcreatedAt: string;\n\t/** @public */\n\tauthor: string;\n\t/** @public */\n\tpath?: string;\n\t/** @public */\n\tline?: number | null;\n}\n\n/** Batch already-authorized, unseen feedback after its quiet period. @public */\nexport function repositoryFeedbackBatch(\n\tunseen: readonly RepositoryFeedbackItem[],\n\tconfig: RepositoryFeedbackBatchConfig,\n\tnow: number,\n): RepositoryFeedbackBatch | null {\n\tif (!unseen.length) return null;\n\tconst latest = Math.max(...unseen.map((item) => Date.parse(item.createdAt) || 0));\n\tif (now - latest < config.quietPeriodMs) return null;\n\tconst cursors = {\n\t\t/** @public */\n\t\tconversationCursor: config.conversationCursor,\n\t\t/** @public */\n\t\treviewCursor: config.reviewCursor,\n\t\t/** @public */\n\t\tinlineCursor: config.inlineCursor,\n\t};\n\tfor (const item of unseen) {\n\t\tconst key = `${item.kind}Cursor` as const;\n\t\tcursors[key] = Math.max(cursors[key], item.id);\n\t}\n\treturn {\n\t\t/** @public */\n\t\tevent: {\n\t\t\t/** @public */\n\t\t\tfeedbackIds: unseen.map(({ kind, id }) => ({\n\t\t\t\t/** @public */\n\t\t\t\tkind,\n\t\t\t\t/** @public */\n\t\t\t\tid,\n\t\t\t})),\n\t\t\t/** @public */\n\t\t\tcursors,\n\t\t},\n\t\t/** @public */\n\t\tmergeKey: `${cursors.conversationCursor}:${cursors.reviewCursor}:${cursors.inlineCursor}`,\n\t};\n}\n\n/** Normalize common forge feedback fields; reject empty bodies and missing identities. @public */\nexport function normalizeRepositoryFeedback(\n\tkind: RepositoryFeedbackItem[\"kind\"],\n\titem: Record<string, unknown>,\n): RepositoryFeedbackItem | null {\n\tconst body = typeof item.body === \"string\" ? item.body.trim() : \"\";\n\tconst user = asUnknownRecord(item.user) ?? {};\n\tif (!body || typeof item.id !== \"number\" || typeof user.login !== \"string\") return null;\n\treturn {\n\t\tkind,\n\t\tid: item.id,\n\t\tbody,\n\t\tcreatedAt:\n\t\t\ttypeof item.submitted_at === \"string\"\n\t\t\t\t? item.submitted_at\n\t\t\t\t: typeof item.created_at === \"string\"\n\t\t\t\t\t? item.created_at\n\t\t\t\t\t: new Date(0).toISOString(),\n\t\tauthor: user.login,\n\t\t...(typeof item.path === \"string\" ? { path: item.path } : {}),\n\t\t...(typeof item.line === \"number\" ? { line: item.line } : {}),\n\t};\n}\n/** @public */\nexport interface RepositoryFeedbackCursors {\n\t/** @public */\n\tconversationCursor: number;\n\t/** @public */\n\treviewCursor: number;\n\t/** @public */\n\tinlineCursor: number;\n}\n/** @public */\nexport interface RepositoryFeedbackBatchConfig extends RepositoryFeedbackCursors {\n\t/** @public */\n\tquietPeriodMs: number;\n}\n/** @public */\nexport interface RepositoryFeedbackBatch {\n\t/** @public */\n\tevent: {\n\t\t/** @public */\n\t\tfeedbackIds: {\n\t\t\t/** @public */\n\t\t\tkind: RepositoryFeedbackItem[\"kind\"];\n\t\t\t/** @public */\n\t\t\tid: number;\n\t\t}[];\n\t\t/** @public */\n\t\tcursors: RepositoryFeedbackCursors;\n\t};\n\t/** @public */\n\tmergeKey: string;\n}\n","import {\n\tWORKER_IPC_CONNECT_TOKEN_ENV,\n\tWORKER_IPC_RECONNECT_ENV,\n\tWORKER_SNAPSHOT_TOKEN_ENV,\n} from \"@leitwerk-dev/worker-protocol\";\n\n/** @public */\nexport type SubprocessEnvInput = Record<string, string | undefined>;\n\nexport const INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX = \"LEITWERK_INTERNAL_REPOSITORY_GIT_SSH_\";\nexport const INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX = \"LEITWERK_INTERNAL_REPOSITORY_GIT_HTTPS_\";\n\n/** @internal */\nexport const WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS = [\n\tWORKER_IPC_CONNECT_TOKEN_ENV,\n\tWORKER_IPC_RECONNECT_ENV,\n\tWORKER_SNAPSHOT_TOKEN_ENV,\n] as const;\n\nconst SENSITIVE_ENV_KEYS = new Set<string>([\n\t...WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS,\n\t\"SSH_AUTH_SOCK\",\n\t\"SSH_AGENT_PID\",\n\t\"GIT_SSH\",\n\t\"GIT_SSH_COMMAND\",\n\t\"GIT_ASKPASS\",\n\t\"SSH_ASKPASS\",\n]);\n\n/**\n * Builds an environment for worker-executed repository shell/tool commands.\n *\n * Worker IPC and session-snapshot credentials are valid only for the worker\n * process itself. Repository scripts, git hooks, package managers, and other\n * tool subprocesses must not receive them.\n */\n/** @public */\nexport function sanitizeWorkerSubprocessEnv(\n\tbaseEnv: SubprocessEnvInput = process.env,\n\toverrides: SubprocessEnvInput = {},\n): NodeJS.ProcessEnv {\n\tconst sanitized: NodeJS.ProcessEnv = {};\n\tfor (const [key, value] of Object.entries({ ...baseEnv, ...overrides })) {\n\t\tif (\n\t\t\tSENSITIVE_ENV_KEYS.has(key) ||\n\t\t\tkey.startsWith(INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX) ||\n\t\t\tkey.startsWith(INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX) ||\n\t\t\tkey.startsWith(\"GIT_CONFIG_\") ||\n\t\t\t/(?:^|_)(?:TOKEN|API_KEY|PASSWORD|SECRET)$/.test(key) ||\n\t\t\tvalue === undefined\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tsanitized[key] = value;\n\t}\n\treturn sanitized;\n}\n","import {\n\tINTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX,\n\tINTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX,\n\ttype SubprocessEnvInput,\n\tsanitizeWorkerSubprocessEnv,\n} from \"./subprocess-env.js\";\n\nfunction wrapperKey(projectKey: string): string {\n\treturn `${INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX}${encodeURIComponent(projectKey).replace(/%/g, \"_\")}`;\n}\n\n/** Worker-internal registration; the wrapper path is never copied to ordinary subprocesses. @internal */\nexport function setRepositoryGitSshWrapper(projectKey: string, wrapperPath: string): void {\n\tprocess.env[wrapperKey(projectKey)] = wrapperPath;\n}\n\n/** @internal */\nexport function clearRepositoryGitSshWrappers(): void {\n\tfor (const key of Object.keys(process.env)) {\n\t\tif (key.startsWith(INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX)) delete process.env[key];\n\t}\n}\n\n/** @internal */\nexport function setRepositoryGitHttpsHelper(projectKey: string, helperPath: string): void {\n\tprocess.env[`${INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX}${encodeURIComponent(projectKey)}`] =\n\t\thelperPath;\n}\n\n/** @internal */\nexport function clearRepositoryGitHttpsHelpers(): void {\n\tfor (const key of Object.keys(process.env)) {\n\t\tif (key.startsWith(INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX)) delete process.env[key];\n\t}\n}\n\n/** Safe environment for a trusted Git invocation for one process project. @public */\nexport function repositoryGitSubprocessEnv(\n\tprojectKey: string,\n\toverrides: SubprocessEnvInput = {},\n): NodeJS.ProcessEnv {\n\tconst env = sanitizeWorkerSubprocessEnv(process.env, overrides);\n\tconst wrapper = process.env[wrapperKey(projectKey)];\n\tif (wrapper) env.GIT_SSH = wrapper;\n\tconst helper =\n\t\tprocess.env[`${INTERNAL_REPOSITORY_GIT_HTTPS_ENV_PREFIX}${encodeURIComponent(projectKey)}`];\n\tif (helper) {\n\t\tconst config = [\n\t\t\t[\"credential.helper\", \"\"],\n\t\t\t[\"credential.helper\", `!${shellQuote(process.execPath)} ${shellQuote(helper)}`],\n\t\t\t[\"credential.useHttpPath\", \"true\"],\n\t\t\t[\"http.followRedirects\", \"false\"],\n\t\t\t[\"protocol.allow\", \"never\"],\n\t\t\t[\"protocol.https.allow\", \"always\"],\n\t\t];\n\t\tenv.GIT_CONFIG_COUNT = String(config.length);\n\t\tconfig.forEach(([key, value], index) => {\n\t\t\tenv[`GIT_CONFIG_KEY_${index}`] = key;\n\t\t\tenv[`GIT_CONFIG_VALUE_${index}`] = value;\n\t\t});\n\t\tenv.GIT_TERMINAL_PROMPT = \"0\";\n\t}\n\treturn env;\n}\n\n/** @public */\nexport function repositoryGitArgs(args: readonly string[]): string[] {\n\treturn [\"-c\", \"core.hooksPath=/dev/null\", ...args];\n}\n\nfunction shellQuote(value: string): string {\n\treturn \"'\" + value.replaceAll(\"'\", \"'\\\"'\\\"'\") + \"'\";\n}\n","import { IntegrationHttpClient } from \"./integration-http.js\";\nimport type { RepositoryIssue, RepositoryPullRequest } from \"./repository-types.js\";\n\n/** Common forge endpoints; extensions retain authentication and specialized operations. @public */\nexport class RepositoryHttpClient<Comment = Record<string, unknown>> extends IntegrationHttpClient {\n\t/** @internal */\n\tprotected repositoryPath(owner: string, repo: string): string {\n\t\treturn `/repos/${owner}/${repo}`;\n\t}\n\n\t/** @internal */\n\tgetIssue(owner: string, repo: string, number: number, signal?: AbortSignal) {\n\t\treturn this.request<RepositoryIssue>(`${this.repositoryPath(owner, repo)}/issues/${number}`, {\n\t\t\tsignal,\n\t\t});\n\t}\n\n\t/** @public */\n\tlistIssueComments(owner: string, repo: string, number: number, signal?: AbortSignal) {\n\t\treturn this.pages<Comment>(\n\t\t\t`${this.repositoryPath(owner, repo)}/issues/${number}/comments`,\n\t\t\tsignal,\n\t\t);\n\t}\n\n\t/** @public */\n\taddIssueComment(owner: string, repo: string, number: number, body: string, signal?: AbortSignal) {\n\t\treturn this.writeJson(\n\t\t\t`${this.repositoryPath(owner, repo)}/issues/${number}/comments`,\n\t\t\t\"POST\",\n\t\t\t{ body },\n\t\t\tsignal,\n\t\t);\n\t}\n\n\t/** @public */\n\tcreatePullRequest(\n\t\towner: string,\n\t\trepo: string,\n\t\tinput: {\n\t\t\t/** @public */\n\t\t\ttitle: string;\n\t\t\t/** @public */\n\t\t\tbody: string;\n\t\t\t/** @public */\n\t\t\thead: string;\n\t\t\t/** @public */\n\t\t\tbase: string;\n\t\t},\n\t) {\n\t\treturn this.writeJson<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls`,\n\t\t\t\"POST\",\n\t\t\tinput,\n\t\t);\n\t}\n\n\t/** @public */\n\tgetPullRequest(owner: string, repo: string, number: number, signal?: AbortSignal) {\n\t\treturn this.request<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls/${number}`,\n\t\t\t{ signal },\n\t\t);\n\t}\n\n\t/** @internal */\n\tlistPullRequests(owner: string, repo: string, state = \"open\") {\n\t\treturn this.pages<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls?state=${encodeURIComponent(state)}`,\n\t\t);\n\t}\n\n\t/** @public */\n\tupdatePullRequest(\n\t\towner: string,\n\t\trepo: string,\n\t\tnumber: number,\n\t\tpatch: Record<string, unknown>,\n\t\tsignal?: AbortSignal,\n\t) {\n\t\treturn this.writeJson<RepositoryPullRequest>(\n\t\t\t`${this.repositoryPath(owner, repo)}/pulls/${number}`,\n\t\t\t\"PATCH\",\n\t\t\tpatch,\n\t\t\tsignal,\n\t\t);\n\t}\n}\n","/** Canonical, credential-free HTTPS repository URL. Reject ambiguous Git credential paths. @public */\nexport function repositoryHttpsUrl(value: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow new Error(\"Repository authentication requires a valid HTTPS URL\");\n\t}\n\tif (\n\t\turl.protocol !== \"https:\" ||\n\t\turl.username ||\n\t\turl.password ||\n\t\turl.search ||\n\t\turl.hash ||\n\t\t!url.pathname.slice(1) ||\n\t\t/[%\\\\\\s]/.test(url.pathname) ||\n\t\turl.pathname.split(\"/\").some((part) => part === \".\" || part === \"..\") ||\n\t\turl.href !== value\n\t)\n\t\tthrow new Error(\"Repository authentication requires a canonical credential-free HTTPS URL\");\n\treturn url;\n}\n","import type { LaunchModelConfigInput } from \"@leitwerk-dev/domain\";\nimport { parseDurationMs } from \"@leitwerk-dev/watcher-utils\";\nimport { parseProcessWatcherLaunchModelConfig } from \"./process-watcher-source.js\";\nimport { objectArg } from \"./tool-arguments.js\";\n\n/** @public */\nexport interface RepositoryIssueWatcherConfig {\n\t/** @public */\n\tprofile: string;\n\t/** @public */\n\tpollInterval: string;\n\t/** @public */\n\trepositories: {\n\t\t/** @public */\n\t\tinclude: readonly string[];\n\t\t/** @public */\n\t\texclude: readonly string[];\n\t};\n\t/** @public */\n\tlabels: {\n\t\t/** @public */\n\t\ttrigger: string;\n\t\t/** @public */\n\t\tdone: string;\n\t};\n}\n\n/** @public */\nexport function matchesRepository(\n\tconfig: Pick<RepositoryIssueWatcherConfig, \"repositories\">,\n\trepository: {\n\t\t/** @public */\n\t\tfull_name: string;\n\t},\n): boolean {\n\tconst { include = [], exclude = [] } = config.repositories ?? {};\n\treturn (\n\t\t!exclude.includes(repository.full_name) &&\n\t\t(include.length === 0 || include.includes(repository.full_name))\n\t);\n}\n\nconst record = (value: unknown, subject: string) =>\n\tobjectArg(value, `${subject} must be an object`);\n\nfunction nonEmptyString(value: unknown, path: string): string {\n\tif (typeof value !== \"string\" || value.trim() === \"\")\n\t\tthrow new Error(`${path} must be a non-empty string`);\n\treturn value.trim();\n}\n\nfunction repositoryNames(value: unknown, path: string): readonly string[] {\n\tif (value === undefined) return [];\n\tif (!Array.isArray(value)) throw new Error(`${path} must be an array`);\n\treturn value.map((candidate, index) => {\n\t\tconst name = nonEmptyString(candidate, `${path}[${index}]`);\n\t\tif (!/^[^/\\s]+\\/[^/\\s]+$/.test(name))\n\t\t\tthrow new Error(`${path}[${index}] must use owner/name format`);\n\t\treturn name;\n\t});\n}\n\n/** Parse shared issue watcher fields; extensions choose the legacy type and label policy. @public */\nexport function parseRepositoryIssueWatcherConfig(\n\traw: unknown,\n\tlegacyType: string,\n\tdistinctLabels = false,\n): ParsedRepositoryIssueWatcherConfig {\n\tconst config = record(raw, \"watcher config\");\n\tif (config.type !== undefined && config.type !== legacyType)\n\t\tthrow new Error(`type must be '${legacyType}' when specified`);\n\tif (typeof config.enabled !== \"boolean\") throw new Error(\"enabled must be a boolean\");\n\tconst pollInterval = nonEmptyString(config.poll_interval, \"poll_interval\");\n\tif (parseDurationMs(pollInterval, -1, { allowHours: true }) <= 0)\n\t\tthrow new Error(\"poll_interval must be a positive duration\");\n\tconst labels = record(config.labels, \"labels\");\n\tconst repositories =\n\t\tconfig.repositories === undefined ? {} : record(config.repositories, \"repositories\");\n\tconst parsed: RepositoryIssueWatcherConfig = {\n\t\tprofile: nonEmptyString(config.profile, \"profile\"),\n\t\tpollInterval,\n\t\trepositories: {\n\t\t\tinclude: repositoryNames(repositories.include, \"repositories.include\"),\n\t\t\texclude: repositoryNames(repositories.exclude, \"repositories.exclude\"),\n\t\t},\n\t\tlabels: {\n\t\t\ttrigger: nonEmptyString(labels.trigger, \"labels.trigger\"),\n\t\t\tdone: nonEmptyString(labels.done, \"labels.done\"),\n\t\t},\n\t};\n\tif (distinctLabels && parsed.labels.trigger === parsed.labels.done)\n\t\tthrow new Error(\"Trigger and done labels must differ\");\n\treturn {\n\t\t/** @public */\n\t\tconfig: parsed,\n\t\t/** @public */\n\t\tenabled: config.enabled,\n\t\t/** @public */\n\t\tlaunchModelConfig: parseProcessWatcherLaunchModelConfig(config.launch),\n\t};\n}\n\n/** @public */\nexport function presentRepositoryIssueWatcherConfig(\n\tconfig: RepositoryIssueWatcherConfig,\n): RepositoryIssueWatcherPresentation {\n\treturn {\n\t\t/** @public */\n\t\ttargetSummary: `Profile ${config.profile} · trigger ${config.labels.trigger}`,\n\t\t/** @public */\n\t\tdetails: [\n\t\t\t{\n\t\t\t\t/** @public */\n\t\t\t\tlabel: \"Profile\",\n\t\t\t\t/** @public */\n\t\t\t\tvalue: config.profile,\n\t\t\t},\n\t\t\t{ label: \"Included repositories\", value: config.repositories.include.join(\", \") || \"all\" },\n\t\t\t{ label: \"Excluded repositories\", value: config.repositories.exclude.join(\", \") || \"none\" },\n\t\t\t{ label: \"Trigger label\", value: config.labels.trigger },\n\t\t\t{ label: \"Done label\", value: config.labels.done },\n\t\t\t{ label: \"Poll interval\", value: config.pollInterval },\n\t\t],\n\t};\n}\n/** @public */\nexport interface ParsedRepositoryIssueWatcherConfig {\n\t/** @public */\n\tconfig: RepositoryIssueWatcherConfig;\n\t/** @public */\n\tenabled: boolean;\n\t/** @public */\n\tlaunchModelConfig: LaunchModelConfigInput & {\n\t\t/** @public */\n\t\tskillIds: string[];\n\t};\n}\n/** @public */\nexport interface RepositoryIssueWatcherPresentation {\n\t/** @public */\n\ttargetSummary: string;\n\t/** @public */\n\tdetails: {\n\t\t/** @public */\n\t\tlabel: string;\n\t\t/** @public */\n\t\tvalue: string;\n\t}[];\n}\n","import { IntegrationHttpError } from \"./integration-http.js\";\n\n/** @internal */\nexport async function existingObject<T>(read: () => Promise<T>): Promise<T | null> {\n\ttry {\n\t\treturn await read();\n\t} catch (error) {\n\t\tif (error instanceof IntegrationHttpError && error.status === 404) return null;\n\t\tthrow error;\n\t}\n}\n\n/** @internal */\nexport function matchesPatch(current: object, patch: Record<string, unknown>): boolean {\n\tconst fields = current as Record<string, unknown>;\n\treturn Object.entries(patch).every(([key, expected]) => {\n\t\tconst labelKey = Array.isArray(expected) && typeof expected[0] === \"number\" ? \"id\" : \"name\";\n\t\tconst normalize = (value: unknown) =>\n\t\t\tkey === \"labels\" && Array.isArray(value)\n\t\t\t\t? [\n\t\t\t\t\t\t...new Set(\n\t\t\t\t\t\t\tvalue.map((label) =>\n\t\t\t\t\t\t\t\ttypeof label === \"object\" && label !== null ? label[labelKey] : label,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t].sort()\n\t\t\t\t: value;\n\t\treturn JSON.stringify(normalize(fields[key])) === JSON.stringify(normalize(expected));\n\t});\n}\n","import { asUnknownRecord } from \"@leitwerk-dev/domain\";\nimport type { RepositoryFeedbackBatchConfig } from \"./repository-feedback.js\";\n\n/** Parse common forge source fields, preserving polling defaults and permissive string handling. @public */\nexport function parseRepositoryPullRequestConfig(\n\tvalue: unknown,\n): RepositoryPullRequestSourceConfig | null {\n\tconst config = asUnknownRecord(value) ?? {};\n\tif (\n\t\ttypeof config.profile !== \"string\" ||\n\t\ttypeof config.owner !== \"string\" ||\n\t\ttypeof config.repo !== \"string\" ||\n\t\ttypeof config.prNumber !== \"number\"\n\t)\n\t\treturn null;\n\tconst terminalOutcome: \"merged\" | \"closed\" | undefined =\n\t\tconfig.terminalOutcome === \"merged\" || config.terminalOutcome === \"closed\"\n\t\t\t? config.terminalOutcome\n\t\t\t: undefined;\n\treturn {\n\t\t/** @public */\n\t\tprofile: config.profile,\n\t\t/** @public */\n\t\towner: config.owner,\n\t\t/** @public */\n\t\trepo: config.repo,\n\t\t/** @public */\n\t\tprNumber: config.prNumber,\n\t\t/** @public */\n\t\tpollInterval: typeof config.pollInterval === \"string\" ? config.pollInterval : \"30s\",\n\t\t/** @public */\n\t\tterminalOutcome,\n\t\t/** @public */\n\t\tdisabled: config.disabled === true,\n\t};\n}\n\n/** @public */\nexport function parseRepositoryFeedbackConfig(\n\tvalue: unknown,\n): RepositoryFeedbackSourceConfig | null {\n\tconst base = parseRepositoryPullRequestConfig(value);\n\tconst config = asUnknownRecord(value) ?? {};\n\tif (!base) return null;\n\treturn {\n\t\t...base,\n\t\t/** @public */\n\t\tconversationCursor:\n\t\t\ttypeof config.conversationCursor === \"number\" ? config.conversationCursor : 0,\n\t\t/** @public */\n\t\treviewCursor: typeof config.reviewCursor === \"number\" ? config.reviewCursor : 0,\n\t\t/** @public */\n\t\tinlineCursor: typeof config.inlineCursor === \"number\" ? config.inlineCursor : 0,\n\t\t/** @public */\n\t\tquietPeriodMs: typeof config.quietPeriodMs === \"number\" ? config.quietPeriodMs : 120_000,\n\t};\n}\n\n/** @public */\nexport function parseRepositoryIssueCancelledConfig(\n\tvalue: unknown,\n): RepositoryIssueCancelledSourceConfig | null {\n\tconst config = asUnknownRecord(value) ?? {};\n\tif (\n\t\ttypeof config.profile !== \"string\" ||\n\t\ttypeof config.owner !== \"string\" ||\n\t\ttypeof config.repo !== \"string\" ||\n\t\ttypeof config.issueNumber !== \"number\" ||\n\t\ttypeof config.triggerLabel !== \"string\"\n\t)\n\t\treturn null;\n\treturn {\n\t\t/** @public */\n\t\tprofile: config.profile,\n\t\t/** @public */\n\t\towner: config.owner,\n\t\t/** @public */\n\t\trepo: config.repo,\n\t\t/** @public */\n\t\tissueNumber: config.issueNumber,\n\t\t/** @public */\n\t\ttriggerLabel: config.triggerLabel,\n\t\t/** @public */\n\t\tpollInterval: typeof config.pollInterval === \"string\" ? config.pollInterval : \"30s\",\n\t};\n}\n/** @public */\nexport interface RepositoryPullRequestSourceConfig {\n\t/** @public */\n\tprofile: string;\n\t/** @public */\n\towner: string;\n\t/** @public */\n\trepo: string;\n\t/** @public */\n\tprNumber: number;\n\t/** @public */\n\tpollInterval: string;\n\t/** @public */\n\tterminalOutcome: \"merged\" | \"closed\" | undefined;\n\t/** @public */\n\tdisabled: boolean;\n}\n/** @public */\nexport interface RepositoryFeedbackSourceConfig\n\textends RepositoryPullRequestSourceConfig,\n\t\tRepositoryFeedbackBatchConfig {}\n/** @public */\nexport interface RepositoryIssueCancelledSourceConfig {\n\t/** @public */\n\tprofile: string;\n\t/** @public */\n\towner: string;\n\t/** @public */\n\trepo: string;\n\t/** @public */\n\tissueNumber: number;\n\t/** @public */\n\ttriggerLabel: string;\n\t/** @public */\n\tpollInterval: string;\n}\n","import {\n\tassertValidProcessProductName,\n\ttype ProcessTurnStartSelection,\n\tresolveProcessTurnStartSelection,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tAutomaticTurnDefinition,\n\tExternalTurnDefinition,\n\tHumanTurnDefinition,\n\tLlmTurnDefinition,\n\tProcessToolOutcomeSpec,\n\tTurnDefinition,\n} from \"./define-process.js\";\nimport { llmTurn, resolveHumanTurnView } from \"./define-process.js\";\nimport { validatePiBuiltInToolArray } from \"./pi-config.js\";\nimport { REQUIRED_MARKDOWN_RESULT_TURN_RESULT } from \"./tool-renderers.js\";\nimport {\n\ttype OutcomeToolParameterSpec,\n\ttype ProcessActionPreviewDefinition,\n\ttype ProcessActionSchedulingDefinition,\n\tRESERVED_INTEGRATION_TOOL_NAMES,\n} from \"./types.js\";\n\n/** @internal */\nexport function isLlmTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is LlmTurnDefinition<string, TParams, TState> {\n\treturn turnDef.kind === \"llm\";\n}\n\n/** @internal */\nexport function isAutomaticTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is AutomaticTurnDefinition<string, TParams, TState> {\n\treturn turnDef.kind === \"automatic\";\n}\n\n/** @internal */\nexport function isHumanTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is HumanTurnDefinition<TParams, TState> {\n\treturn turnDef.kind === \"human\";\n}\n\n/** @internal */\nexport function isExternalTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): turnDef is ExternalTurnDefinition<TParams, TState> {\n\treturn turnDef.kind === \"external\";\n}\n\n/** @internal */\nexport function resolveLlmTurnStartSelection<TOutcome extends string = string>(\n\tturnDef: Pick<LlmTurnDefinition<TOutcome>, \"branchType\" | \"startFrom\">,\n): ProcessTurnStartSelection {\n\treturn resolveProcessTurnStartSelection(turnDef);\n}\n\n/** @internal */\nexport function resolveLlmTurnRestorePrimaryLeafAfterTurn<TOutcome extends string = string>(\n\tturnDef: Pick<LlmTurnDefinition<TOutcome>, \"branchType\" | \"restorePrimaryLeafAfterTurn\">,\n): boolean {\n\treturn turnDef.restorePrimaryLeafAfterTurn ?? turnDef.branchType !== \"primary\";\n}\n\nexport function validateProcessActionPreviewDefinition(\n\tpreview: ProcessActionPreviewDefinition | undefined,\n\tcontext: string,\n): string[] {\n\tif (!preview) {\n\t\treturn [];\n\t}\n\tif (preview.kind === \"trigger\") {\n\t\treturn preview.trigger.trim() ? [] : [`${context} must declare a non-empty trigger preview`];\n\t}\n\tif (preview.kind === \"terminal\" || preview.turnId === null || preview.turnId.trim()) {\n\t\treturn [];\n\t}\n\treturn [`${context} must declare a non-empty fixed turn id when turnId is not null`];\n}\n\nexport function validateProcessActionSchedulingDefinition(\n\tscheduling: ProcessActionSchedulingDefinition | undefined,\n\tcontext: string,\n): string[] {\n\treturn validateProcessActionPreviewDefinition(scheduling?.preview, context);\n}\n\nfunction findDuplicateBy<TItem>(\n\titems: readonly TItem[],\n\tselectKey: (item: TItem) => string,\n): TItem | undefined {\n\tconst ids = new Set<string>();\n\tfor (const item of items) {\n\t\tconst key = selectKey(item);\n\t\tif (ids.has(key)) {\n\t\t\treturn item;\n\t\t}\n\t\tids.add(key);\n\t}\n\treturn undefined;\n}\n\nfunction validateProcessProductName(name: string): string[] {\n\ttry {\n\t\tassertValidProcessProductName(name);\n\t\treturn [];\n\t} catch (error) {\n\t\treturn [error instanceof Error ? error.message : String(error)];\n\t}\n}\n\nfunction validateOutcomeTurnResultContract<TParams = unknown, TState = unknown>(\n\tturnKindLabel: string,\n\tturnId: string,\n\toutcomes: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>> | undefined,\n\tturnEnd: unknown,\n): string[] {\n\tconst errors: string[] = [];\n\tconst hasOutcomeTools = Object.keys(outcomes ?? {}).length > 0;\n\tconst hasTurnEndResult = turnEnd !== undefined;\n\tif (!hasOutcomeTools && !hasTurnEndResult) {\n\t\terrors.push(\n\t\t\t`${turnKindLabel} turn '${turnId}' must declare at least one outcome tool or a turnEnd result`,\n\t\t);\n\t}\n\tif (hasOutcomeTools && hasTurnEndResult) {\n\t\terrors.push(`${turnKindLabel} turn '${turnId}' cannot declare both outcomes and turnEnd`);\n\t}\n\treturn errors;\n}\n\nfunction isValidOutcomeToolArrayItemType(type: unknown): boolean {\n\treturn (\n\t\ttype === \"string\" ||\n\t\ttype === \"number\" ||\n\t\ttype === \"boolean\" ||\n\t\ttype === \"object\" ||\n\t\ttype === \"array\"\n\t);\n}\n\nfunction validateOutcomeToolParameters<TParams = unknown, TState = unknown>(\n\tturnKindLabel: string,\n\tturnId: string,\n\toutcomes: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>> | undefined,\n): string[] {\n\tconst errors: string[] = [];\n\tfor (const [outcome, outcomeSpec] of Object.entries(outcomes ?? {}) as Array<\n\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t>) {\n\t\tif (outcomeSpec.publishedProduct) {\n\t\t\terrors.push(...validateProcessProductName(outcomeSpec.publishedProduct));\n\t\t\tconst parameterName = outcomeSpec.turnResultMarkdownParameter?.trim() ?? \"\";\n\t\t\tif (!parameterName) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' but does not declare a turn-result markdown parameter`,\n\t\t\t\t);\n\t\t\t} else if (!Object.hasOwn(outcomeSpec.parameters, parameterName)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' from missing parameter '${parameterName}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const [paramName, paramSpec] of Object.entries(outcomeSpec.parameters) as Array<\n\t\t\t[string, OutcomeToolParameterSpec]\n\t\t>) {\n\t\t\tif (paramSpec.minItems !== undefined && paramSpec.type !== \"array\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minItems but is not an array`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (paramSpec.minimum !== undefined && paramSpec.type !== \"number\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minimum but is not a number`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (paramSpec.items !== undefined && paramSpec.type !== \"array\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares array items but is not an array`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (paramSpec.type === \"array\") {\n\t\t\t\tif (!paramSpec.items) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' is an array and must declare items`,\n\t\t\t\t\t);\n\t\t\t\t} else if (!isValidOutcomeToolArrayItemType(paramSpec.items.type)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares unsupported array item type '${String(paramSpec.items.type)}'`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n\nfunction assertNoValidationErrors(errors: readonly string[]): void {\n\tif (errors.length > 0) {\n\t\tthrow new Error(errors.join(\"; \"));\n\t}\n}\n\nfunction validateTurnStartSelection(\n\tturnId: string,\n\tstartFrom: ProcessTurnStartSelection,\n\tcontext = \"startFrom\",\n): string[] {\n\tconst errors: string[] = [];\n\tif (startFrom.kind === \"entry\" && startFrom.entryId.trim() === \"\") {\n\t\terrors.push(`LLM turn '${turnId}' ${context} entry id must be non-empty`);\n\t}\n\tif (startFrom.kind === \"product_ref\") {\n\t\terrors.push(...validateProcessProductName(startFrom.productName));\n\t}\n\tif (\"fallback\" in startFrom && startFrom.fallback) {\n\t\terrors.push(...validateTurnStartSelection(turnId, startFrom.fallback, `${context} fallback`));\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateLlmTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n>(turnId: string, turnDef: LlmTurnDefinition<TOutcome, TParams, TState>): string[] {\n\tconst errors: string[] = [];\n\tconst declaredOutcomes = turnDef.outcomes;\n\tconst startFrom = resolveLlmTurnStartSelection(turnDef);\n\n\tif ((turnDef.completionMode ?? \"turn_end\") !== \"turn_end\") {\n\t\terrors.push(`LLM turn '${turnId}' must use completionMode 'turn_end'`);\n\t}\n\n\tconst declaredTurnEnd = turnDef.turnEnd;\n\terrors.push(\n\t\t...validateOutcomeTurnResultContract(\"LLM\", turnId, declaredOutcomes, declaredTurnEnd),\n\t);\n\n\tif (turnDef.branchType === \"root_branch\" && startFrom.kind === \"current_leaf\") {\n\t\terrors.push(\n\t\t\t`LLM turn '${turnId}' uses branchType 'root_branch' but starts from the current leaf`,\n\t\t);\n\t}\n\n\tif (turnDef.branchType === \"leaf_branch\" && startFrom.kind === \"session_root\") {\n\t\terrors.push(\n\t\t\t`LLM turn '${turnId}' uses branchType 'leaf_branch' but starts from the session root`,\n\t\t);\n\t}\n\n\terrors.push(...validateTurnStartSelection(turnId, startFrom));\n\n\tif (turnDef.askQuestions !== undefined && turnDef.askQuestions !== true) {\n\t\terrors.push(`LLM turn '${turnId}' askQuestions must be true when declared`);\n\t}\n\n\tif (!Array.isArray(turnDef.availableTools)) {\n\t\terrors.push(`LLM turn '${turnId}' must declare availableTools as an array`);\n\t} else {\n\t\terrors.push(\n\t\t\t...validatePiBuiltInToolArray(turnDef.availableTools, `LLM turn '${turnId}' availableTools`),\n\t\t);\n\t}\n\n\tif (turnDef.integrationTools !== undefined) {\n\t\tif (!Array.isArray(turnDef.integrationTools)) {\n\t\t\terrors.push(`LLM turn '${turnId}' integrationTools must be an array`);\n\t\t} else {\n\t\t\tconst seen = new Set<string>();\n\t\t\tconst conflictingNames = new Set<string>([\n\t\t\t\t...RESERVED_INTEGRATION_TOOL_NAMES,\n\t\t\t\t...Object.keys(declaredOutcomes ?? {}),\n\t\t\t]);\n\t\t\tfor (const name of turnDef.integrationTools) {\n\t\t\t\tif (typeof name !== \"string\" || name.trim() === \"\") {\n\t\t\t\t\terrors.push(`LLM turn '${turnId}' integration tool names must be non-empty strings`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (seen.has(name)) {\n\t\t\t\t\terrors.push(`LLM turn '${turnId}' declares duplicate integration tool '${name}'`);\n\t\t\t\t}\n\t\t\t\tif (conflictingNames.has(name)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`LLM turn '${turnId}' integration tool '${name}' conflicts with a built-in, framework, or outcome tool`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tseen.add(name);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (turnDef.turnResultMarkdown?.mode === \"tool_call\") {\n\t\tif (turnDef.turnResultMarkdown.toolName.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`LLM turn '${turnId}' tool-call turnResultMarkdown must use a non-empty toolName`,\n\t\t\t);\n\t\t}\n\t\tif (turnDef.turnResultMarkdown.path.trim() === \"\") {\n\t\t\terrors.push(`LLM turn '${turnId}' tool-call turnResultMarkdown must use a non-empty path`);\n\t\t}\n\t}\n\tif (turnDef.turnResultMarkdown?.mode === \"outcome_tool_argument\") {\n\t\tconst parameterName = turnDef.turnResultMarkdown.parameterName.trim();\n\t\tconst outcomeEntries = Object.entries(declaredOutcomes ?? {}) as Array<\n\t\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t\t>;\n\t\tif (parameterName === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`LLM turn '${turnId}' outcome-tool turnResultMarkdown must use a non-empty parameterName`,\n\t\t\t);\n\t\t}\n\t\tif (outcomeEntries.length === 0) {\n\t\t\terrors.push(\n\t\t\t\t`LLM turn '${turnId}' outcome-tool turnResultMarkdown requires at least one outcome tool`,\n\t\t\t);\n\t\t}\n\t\tfor (const [outcomeId, spec] of outcomeEntries) {\n\t\t\tif (parameterName in spec.parameters) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`LLM turn '${turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${parameterName}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\terrors.push(...validateOutcomeToolParameters(\"LLM\", turnId, declaredOutcomes));\n\terrors.push(...validateMappedTurn(turnId, turnDef));\n\n\treturn errors;\n}\n\nfunction validateMappedTurn<TOutcome extends string, TParams, TState>(\n\tturnId: string,\n\tturnDef: LlmTurnDefinition<TOutcome, TParams, TState>,\n): string[] {\n\tconst mapped = turnDef.forEach;\n\tif (mapped === undefined) return [];\n\tconst errors: string[] = [];\n\tfor (const name of [\"items\", \"key\", \"collect\"] as const) {\n\t\tif (typeof mapped[name] !== \"function\") {\n\t\t\terrors.push(`Mapped turn '${turnId}' must declare ${name}`);\n\t\t}\n\t}\n\tfor (const name of [\"itemCodec\", \"resultCodec\"] as const) {\n\t\tconst codec = mapped[name];\n\t\tif (typeof codec?.parse !== \"function\" || typeof codec?.serialize !== \"function\") {\n\t\t\terrors.push(`Mapped turn '${turnId}' must declare ${name}`);\n\t\t}\n\t}\n\tif (turnDef.turnEnd) {\n\t\terrors.push(`Mapped turn '${turnId}' must finish items through outcome tools`);\n\t}\n\tif (turnDef.publishedProduct) {\n\t\terrors.push(`Mapped turn '${turnId}' cannot publish a product from item turns`);\n\t}\n\tconst outcomes = Object.entries(turnDef.outcomes ?? {}) as Array<\n\t\t[string, ProcessToolOutcomeSpec<TParams, TState>]\n\t>;\n\tif (outcomes.length === 0) {\n\t\terrors.push(`Mapped turn '${turnId}' must declare at least one outcome tool`);\n\t}\n\tfor (const [outcomeId, spec] of outcomes) {\n\t\tif (\n\t\t\t\"branches\" in spec ||\n\t\t\tspec.to !== undefined ||\n\t\t\tspec.complete !== undefined ||\n\t\t\tspec.lifecycleStatus !== undefined ||\n\t\t\tspec.effect !== undefined ||\n\t\t\tspec.lifecycleIntent !== undefined ||\n\t\t\tspec.publishedProduct !== undefined\n\t\t) {\n\t\t\terrors.push(\n\t\t\t\t`Mapped turn '${turnId}' outcome '${outcomeId}' cannot route, change state, or publish`,\n\t\t\t);\n\t\t}\n\t\tif (typeof mapped.yields?.[outcomeId] !== \"function\") {\n\t\t\terrors.push(`Mapped turn '${turnId}' outcome '${outcomeId}' must declare a yield`);\n\t\t}\n\t}\n\tfor (const outcomeId of Object.keys(mapped.yields ?? {})) {\n\t\tif (!Object.hasOwn(turnDef.outcomes ?? {}, outcomeId)) {\n\t\t\terrors.push(`Mapped turn '${turnId}' yields undeclared outcome '${outcomeId}'`);\n\t\t}\n\t}\n\tconst routing = mapped.routing;\n\tif (routing?.kind === \"static\") {\n\t\tif ((routing.to === undefined) === (routing.lifecycleStatus === undefined)) {\n\t\t\terrors.push(`Mapped turn '${turnId}' collection must declare exactly one target`);\n\t\t}\n\t} else if (routing?.kind === \"branches\") {\n\t\tif (Object.keys(routing.branches).length === 0 || typeof routing.choose !== \"function\") {\n\t\t\terrors.push(`Mapped turn '${turnId}' collection routing needs branches and a chooser`);\n\t\t}\n\t} else {\n\t\terrors.push(`Mapped turn '${turnId}' must declare a collection route`);\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateAutomaticTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n>(turnId: string, turnDef: AutomaticTurnDefinition<TOutcome, TParams, TState>): string[] {\n\treturn [\n\t\t...validateOutcomeTurnResultContract(\"Automatic\", turnId, turnDef.outcomes, turnDef.turnEnd),\n\t\t...validateOutcomeToolParameters(\"Automatic\", turnId, turnDef.outcomes),\n\t];\n}\n\n/** @internal */\nexport function validateHumanTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnId: string,\n\tturnDef: HumanTurnDefinition<TParams, TState>,\n): string[] {\n\tconst errors: string[] = [];\n\n\ttry {\n\t\tresolveHumanTurnView({ turnId, turn: turnDef });\n\t} catch (error: unknown) {\n\t\terrors.push(error instanceof Error ? error.message : String(error));\n\t}\n\tif (turnDef.reviewProduct) {\n\t\terrors.push(...validateProcessProductName(turnDef.reviewProduct));\n\t}\n\n\tconst actionEntries = Object.entries(turnDef.actions) as Array<\n\t\t[string, HumanTurnDefinition<TParams, TState>[\"actions\"][string]]\n\t>;\n\tif (actionEntries.length === 0) {\n\t\terrors.push(`Human turn '${turnId}' must declare at least one action`);\n\t}\n\tfor (const [actionId, action] of actionEntries) {\n\t\tif (!action.acceptanceState) {\n\t\t\terrors.push(`Human turn '${turnId}' is missing an acceptance state for action '${actionId}'`);\n\t\t}\n\t\terrors.push(\n\t\t\t...validateProcessActionPreviewDefinition(\n\t\t\t\taction.preview,\n\t\t\t\t`Human turn '${turnId}' action '${actionId}' preview`,\n\t\t\t),\n\t\t);\n\t}\n\n\tconst externalTriggers = actionEntries.flatMap(([actionId, action]) =>\n\t\t(action.externalTriggers ?? []).map((trigger) => ({ actionId, trigger })),\n\t);\n\tif (findDuplicateBy(externalTriggers, ({ trigger }) => trigger.id) !== undefined) {\n\t\terrors.push(`Human turn '${turnId}' contains duplicate external trigger ids`);\n\t}\n\tif (findDuplicateBy(externalTriggers, ({ actionId }) => actionId) !== undefined) {\n\t\terrors.push(`Human turn '${turnId}' contains duplicate external trigger action ids`);\n\t}\n\tfor (const { actionId, trigger } of externalTriggers) {\n\t\tif (trigger.id.trim() === \"\") {\n\t\t\terrors.push(`Human turn '${turnId}' contains an external trigger with an empty id`);\n\t\t}\n\t\tif (actionId.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty actionId`,\n\t\t\t);\n\t\t}\n\t\tif (trigger.label.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty label`,\n\t\t\t);\n\t\t}\n\t\tif (trigger.description.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty description`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfor (const [externalActionId, externalAction] of Object.entries(turnDef.externalActions ?? {})) {\n\t\tif (externalActionId.trim() === \"\") {\n\t\t\terrors.push(`Human turn '${turnId}' contains an external action with an empty id`);\n\t\t}\n\t\tif (externalAction.id !== externalActionId) {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' has mismatched id '${externalAction.id}'`,\n\t\t\t);\n\t\t}\n\t\tif (externalAction.source.kind.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' must declare a non-empty source kind`,\n\t\t\t);\n\t\t}\n\t\tconst targetCount =\n\t\t\t(externalAction.to !== undefined ? 1 : 0) +\n\t\t\t(externalAction.complete === true ? 1 : 0) +\n\t\t\t(externalAction.lifecycleStatus !== undefined ? 1 : 0);\n\t\tif (targetCount !== 1) {\n\t\t\terrors.push(\n\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' must declare exactly one target`,\n\t\t\t);\n\t\t}\n\t\tif (externalAction.publishInput) {\n\t\t\terrors.push(...validateProcessProductName(externalAction.publishInput.productName));\n\t\t\tif (externalAction.publishInput.inputField.trim() === \"\") {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (externalAction.complete === true || externalAction.lifecycleStatus !== undefined) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Human turn '${turnId}' external action '${externalActionId}' cannot publish input on a terminal route`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst duplicateNote = findDuplicateBy(turnDef.notesFields ?? [], (field) => field.id);\n\tif (duplicateNote !== undefined) {\n\t\terrors.push(`Human turn '${turnId}' contains duplicate notes field id '${duplicateNote.id}'`);\n\t}\n\n\treturn errors;\n}\n\n/** @internal */\nexport function validateExternalTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnId: string,\n\tturnDef: ExternalTurnDefinition<TParams, TState>,\n): string[] {\n\tconst errors: string[] = [];\n\tif (turnDef.transitions.length === 0) {\n\t\terrors.push(`External turn '${turnId}' must declare at least one source transition`);\n\t}\n\tfor (const [index, transition] of turnDef.transitions.entries()) {\n\t\tif (transition.source.kind.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t`External turn '${turnId}' source transition ${index} must declare a non-empty kind`,\n\t\t\t);\n\t\t}\n\t\tconst targetCount =\n\t\t\t(transition.to !== undefined ? 1 : 0) +\n\t\t\t(transition.complete === true ? 1 : 0) +\n\t\t\t(transition.lifecycleStatus !== undefined ? 1 : 0);\n\t\tif (targetCount !== 1) {\n\t\t\terrors.push(\n\t\t\t\t`External turn '${turnId}' source transition ${index} must declare exactly one target`,\n\t\t\t);\n\t\t}\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function validateTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnId: string,\n\tturnDef: TurnDefinition<TParams, TState>,\n): string[];\n/** @internal */\nexport function validateTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnDef: TurnDefinition<TParams, TState>,\n): string[];\n/** @internal */\nexport function validateTurnDefinition<TParams = unknown, TState = unknown>(\n\tturnIdOrDef: string | TurnDefinition<TParams, TState>,\n\tturnDef?: TurnDefinition<TParams, TState>,\n): string[] {\n\tconst effectiveTurnDef = typeof turnIdOrDef === \"string\" ? turnDef : turnIdOrDef;\n\tconst effectiveTurnId =\n\t\ttypeof turnIdOrDef === \"string\"\n\t\t\t? turnIdOrDef\n\t\t\t: ((turnIdOrDef as { id?: string }).id ?? \"unknown_turn\");\n\tif (!effectiveTurnDef) {\n\t\treturn [\"Turn definition is required\"];\n\t}\n\treturn isLlmTurnDefinition(effectiveTurnDef)\n\t\t? validateLlmTurnDefinition(effectiveTurnId, effectiveTurnDef)\n\t\t: isAutomaticTurnDefinition(effectiveTurnDef)\n\t\t\t? validateAutomaticTurnDefinition(effectiveTurnId, effectiveTurnDef)\n\t\t\t: isHumanTurnDefinition(effectiveTurnDef)\n\t\t\t\t? validateHumanTurnDefinition(effectiveTurnId, effectiveTurnDef)\n\t\t\t\t: validateExternalTurnDefinition(effectiveTurnId, effectiveTurnDef);\n}\n\n/** @internal */\nexport function assertValidLlmTurnDefinition<\n\tTOutcome extends string = string,\n\tTParams = unknown,\n\tTState = unknown,\n>(turnId: string, turnDef: LlmTurnDefinition<TOutcome, TParams, TState>): void {\n\tassertNoValidationErrors(validateLlmTurnDefinition(turnId, turnDef));\n}\n\n/** @internal */\nexport function createRootBranchReviewTurn<\n\tTOutcome extends string,\n\tTParams = unknown,\n\tTState = unknown,\n>(\n\tdef: Omit<\n\t\tLlmTurnDefinition<TOutcome, TParams, TState>,\n\t\t\"kind\" | \"branchType\" | \"completionMode\" | \"startFrom\" | \"restorePrimaryLeafAfterTurn\"\n\t> &\n\t\tPartial<\n\t\t\tPick<\n\t\t\t\tLlmTurnDefinition<TOutcome, TParams, TState>,\n\t\t\t\t\"completionMode\" | \"startFrom\" | \"restorePrimaryLeafAfterTurn\"\n\t\t\t>\n\t\t>,\n): LlmTurnDefinition<TOutcome, TParams, TState> {\n\tconst {\n\t\tcompletionMode = \"turn_end\",\n\t\tstartFrom = { kind: \"session_root\" },\n\t\trestorePrimaryLeafAfterTurn = true,\n\t\tturnResultMarkdown = REQUIRED_MARKDOWN_RESULT_TURN_RESULT,\n\t\t...rest\n\t} = def;\n\n\treturn llmTurn({\n\t\tcompletionMode,\n\t\tbranchType: \"root_branch\",\n\t\tstartFrom,\n\t\trestorePrimaryLeafAfterTurn,\n\t\tturnResultMarkdown,\n\t\t...rest,\n\t});\n}\n","import {\n\tTOOL_CALL_RENDERER_VALUE_KINDS,\n\tTOOL_CALL_RENDERER_VALUE_SOURCES,\n\ttype ToolCallRendererDefinition,\n\ttype ToolCallRendererFieldDefinition,\n\ttype ToolCallRendererValueKind,\n\ttype ToolCallRendererValueSource,\n} from \"@leitwerk-dev/protocol/tool-renderer-contract\";\nimport type { TurnResultMarkdownBehavior } from \"./types.js\";\n\nexport {\n\tTOOL_CALL_RENDERER_VALUE_KINDS,\n\tTOOL_CALL_RENDERER_VALUE_SOURCES,\n\ttype ToolCallRendererDefinition,\n\ttype ToolCallRendererFieldDefinition,\n\ttype ToolCallRendererValueKind,\n\ttype ToolCallRendererValueSource,\n};\n\n/** @internal */\nexport const MARKDOWN_RESULT_TOOL_NAME = \"markdown_result\";\n/** @internal */\nexport const MARKDOWN_RESULT_TOOL_MARKDOWN_PATH = \"markdown\";\n\n/** @internal */\nexport const MARKDOWN_RESULT_TOOL_RENDERER: ToolCallRendererDefinition = {\n\ttoolName: MARKDOWN_RESULT_TOOL_NAME,\n\ttitle: \"Markdown result\",\n\tfields: [\n\t\t{\n\t\t\tid: \"markdown\",\n\t\t\tlabel: \"Rendered markdown\",\n\t\t\tkind: \"markdown\",\n\t\t\tsource: \"arguments\",\n\t\t\tpath: MARKDOWN_RESULT_TOOL_MARKDOWN_PATH,\n\t\t},\n\t],\n};\n\n/** @internal */\nexport const CORE_TOOL_CALL_RENDERERS: readonly ToolCallRendererDefinition[] = [\n\tMARKDOWN_RESULT_TOOL_RENDERER,\n];\n\n/** @public */\nexport const REQUIRED_MARKDOWN_RESULT_TURN_RESULT: TurnResultMarkdownBehavior = {\n\tmode: \"tool_call\",\n\ttoolName: MARKDOWN_RESULT_TOOL_NAME,\n\tpath: MARKDOWN_RESULT_TOOL_MARKDOWN_PATH,\n\trequired: true,\n};\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.trim() !== \"\";\n}\n\n/** @internal */\nexport function validateToolCallRendererDefinition(def: ToolCallRendererDefinition): string[] {\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(def.toolName)) {\n\t\terrors.push(\"Tool renderer must declare a non-empty toolName\");\n\t}\n\tif (!Array.isArray(def.fields) || def.fields.length === 0) {\n\t\terrors.push(`Tool renderer '${def.toolName}' must declare at least one field`);\n\t\treturn errors;\n\t}\n\tconst fieldIds = new Set<string>();\n\tfor (const field of def.fields) {\n\t\tif (!isNonEmptyString(field.id)) {\n\t\t\terrors.push(`Tool renderer '${def.toolName}' contains a field with an empty id`);\n\t\t}\n\t\tif (fieldIds.has(field.id)) {\n\t\t\terrors.push(`Tool renderer '${def.toolName}' contains duplicate field id '${field.id}'`);\n\t\t}\n\t\tfieldIds.add(field.id);\n\t\tif (!isNonEmptyString(field.label)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' must declare a non-empty label`,\n\t\t\t);\n\t\t}\n\t\tif (!TOOL_CALL_RENDERER_VALUE_KINDS.includes(field.kind)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' uses unknown kind '${String(field.kind)}'`,\n\t\t\t);\n\t\t}\n\t\tif (!TOOL_CALL_RENDERER_VALUE_SOURCES.includes(field.source)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' uses unknown source '${String(field.source)}'`,\n\t\t\t);\n\t\t}\n\t\tif (field.path !== undefined && !isNonEmptyString(field.path)) {\n\t\t\terrors.push(\n\t\t\t\t`Tool renderer '${def.toolName}' field '${field.id}' path must be non-empty when provided`,\n\t\t\t);\n\t\t}\n\t}\n\treturn errors;\n}\n","import type {\n\tProcessActionDefinition,\n\tProcessCleanupHandler,\n\tProcessTurnOutcomeEvent,\n\tServerProcessAPI,\n\tServerProcessContext,\n} from \"./extension-api.js\";\nimport { cloneArrayValueMap, cloneMap, registerUnique } from \"./registry-utils.js\";\nimport {\n\tvalidateProcessActionPreviewDefinition,\n\tvalidateProcessActionSchedulingDefinition,\n} from \"./turn-semantics.js\";\n\n/** @internal */\nexport type ServerTurnOutcomeHandler<TParams = unknown, TState = unknown> = (\n\tevent: ProcessTurnOutcomeEvent,\n\tctx: ServerProcessContext<TParams, TState>,\n) => void | Promise<void>;\n\n/** @internal */\nexport interface BuiltServerProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tactions: ReadonlyMap<string, ProcessActionDefinition<TParams, TState>>;\n\t/** @internal */\n\tturnOutcomeHandlers: ReadonlyMap<string, readonly ServerTurnOutcomeHandler<TParams, TState>[]>;\n\t/** @internal */\n\tcleanupHandlers: readonly ProcessCleanupHandler<TParams, TState>[];\n}\n\n/** @internal */\nexport function createServerProcessBuilder<TParams = unknown, TState = unknown>(): ServerProcessAPI<\n\tTParams,\n\tTState\n> & {\n\t/** @internal */\n\tgetDefinition(): BuiltServerProcessDefinition<TParams, TState>;\n} {\n\tconst actions = new Map<string, ProcessActionDefinition<TParams, TState>>();\n\tconst turnOutcomeHandlers = new Map<string, ServerTurnOutcomeHandler<TParams, TState>[]>();\n\tconst cleanupHandlers: ProcessCleanupHandler<TParams, TState>[] = [];\n\treturn {\n\t\taction(def) {\n\t\t\tregisterUnique(actions, def.id, def, {\n\t\t\t\tduplicateMessage: `Process action '${def.id}' is already registered`,\n\t\t\t\tvalidate: (value) => {\n\t\t\t\t\tif (!value.plan && !value.execute) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' must declare plan(...) or side-effect execute(...)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (value.execute && !value.plan && value.executionMode !== \"side_effect\") {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' with execute(...) must set executionMode: \"side_effect\"`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (value.executionMode === \"side_effect\" && !value.execute) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' with executionMode: \"side_effect\" must declare execute(...)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (value.executionMode === \"side_effect\" && value.scheduling) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Process action '${value.id}' with executionMode: \"side_effect\" cannot declare scheduling metadata`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst previewErrors = validateProcessActionPreviewDefinition(\n\t\t\t\t\t\tvalue.preview,\n\t\t\t\t\t\t`Process action '${value.id}' preview`,\n\t\t\t\t\t);\n\t\t\t\t\tif (previewErrors.length > 0) {\n\t\t\t\t\t\tthrow new Error(previewErrors.join(\"; \"));\n\t\t\t\t\t}\n\t\t\t\t\tconst schedulingErrors = validateProcessActionSchedulingDefinition(\n\t\t\t\t\t\tvalue.scheduling,\n\t\t\t\t\t\t`Process action '${value.id}' scheduling`,\n\t\t\t\t\t);\n\t\t\t\t\tif (schedulingErrors.length > 0) {\n\t\t\t\t\t\tthrow new Error(schedulingErrors.join(\"; \"));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tonTurnOutcome(turnId, handler) {\n\t\t\tconst handlers = turnOutcomeHandlers.get(turnId) ?? [];\n\t\t\thandlers.push(handler);\n\t\t\tturnOutcomeHandlers.set(turnId, handlers);\n\t\t},\n\t\tonCleanup(handler) {\n\t\t\tcleanupHandlers.push(handler);\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\tactions: cloneMap(actions),\n\t\t\t\tturnOutcomeHandlers: cloneArrayValueMap(turnOutcomeHandlers),\n\t\t\t\tcleanupHandlers: [...cleanupHandlers],\n\t\t\t};\n\t\t},\n\t};\n}\n","import {\n\tasUnknownRecord,\n\tcreateEmptyProcessProductRefs,\n\tcreateEmptyProcessSemanticEntryRefs,\n\ttype ProcessProductRefs,\n\ttype ProcessSemanticEntryRefs,\n\tparseProcessProductRefs,\n\tparseProcessSemanticEntryRefs,\n} from \"@leitwerk-dev/domain\";\nimport type { Codec } from \"./extension-api.js\";\n\n/** @public */\nexport interface StructuralProcessState {\n\t/** @internal */\n\tsemanticEntryRefs: ProcessSemanticEntryRefs;\n\t/** @internal */\n\tproductRefs: ProcessProductRefs;\n}\n\n/** @internal */\nexport const structuralStateCodec: Codec<StructuralProcessState> = {\n\tparse: parseStructuralProcessState,\n\tserialize: (value) => value,\n};\n\n/** @public */\nexport function createEmptyStructuralProcessState(): StructuralProcessState {\n\treturn {\n\t\tsemanticEntryRefs: createEmptyProcessSemanticEntryRefs(),\n\t\tproductRefs: createEmptyProcessProductRefs(),\n\t};\n}\n\n/** @public */\nexport function parseStructuralProcessState(value: unknown): StructuralProcessState {\n\tconst record = asUnknownRecord(value) ?? {};\n\treturn {\n\t\tsemanticEntryRefs: parseProcessSemanticEntryRefs(record.semanticEntryRefs),\n\t\tproductRefs: parseProcessProductRefs(record.productRefs),\n\t};\n}\n","import type {\n\tExtensionProcessDefinition,\n\tProcessLeafOutcomeDefinition,\n\tUiProcessAPI,\n} from \"./extension-api.js\";\nimport { validateProcessLeafOutcomeDefinition } from \"./leaf-outcomes.js\";\n\n/** @internal */\nexport interface BuiltUiProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tleafOutcome: ProcessLeafOutcomeDefinition<TParams, TState> | null;\n}\n\n/** @internal */\nexport function createUiProcessBuilder<TParams = unknown, TState = unknown>(): UiProcessAPI<\n\tTParams,\n\tTState\n> & {\n\t/** @internal */\n\tgetDefinition(): BuiltUiProcessDefinition<TParams, TState>;\n} {\n\tlet leafOutcome: ProcessLeafOutcomeDefinition<TParams, TState> | null = null;\n\n\treturn {\n\t\tleafOutcome(def) {\n\t\t\tif (leafOutcome) {\n\t\t\t\tthrow new Error(\"Leaf outcome is already registered\");\n\t\t\t}\n\t\t\tconst validationErrors = validateProcessLeafOutcomeDefinition(def);\n\t\t\tif (validationErrors.length > 0) {\n\t\t\t\tthrow new Error(validationErrors.join(\"; \"));\n\t\t\t}\n\t\t\tleafOutcome = def;\n\t\t},\n\t\tgetDefinition() {\n\t\t\treturn {\n\t\t\t\tleafOutcome,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** @internal */\nexport function buildUiProcessDefinition<TParams = unknown, TState = unknown>(\n\tprocess: ExtensionProcessDefinition<TParams, TState>,\n): BuiltUiProcessDefinition<TParams, TState> | undefined {\n\tif (!process.ui) {\n\t\treturn undefined;\n\t}\n\tconst builder = createUiProcessBuilder<TParams, TState>();\n\tprocess.ui(builder);\n\treturn builder.getDefinition();\n}\n","import type { TurnId } from \"@leitwerk-dev/domain\";\nimport type { WorkerProcessAPI, WorkerTurnHandler } from \"./extension-api.js\";\nimport { cloneMap, registerUnique } from \"./registry-utils.js\";\n\n/** @internal */\nexport interface BuiltWorkerProcessDefinition<TParams = unknown, TState = unknown> {\n\t/** @internal */\n\tstartTurnId: TurnId | null;\n\t/** @internal */\n\tturns: ReadonlyMap<TurnId, WorkerTurnHandler<TParams, TState>>;\n}\n\n/** @internal */\nexport function createWorkerProcessBuilder<TParams = unknown, TState = unknown>(): WorkerProcessAPI<\n\tTParams,\n\tTState\n> & {\n\t/** @internal */\n\tgetDefinition(): BuiltWorkerProcessDefinition<TParams, TState>;\n} {\n\tconst turns = new Map<TurnId, WorkerTurnHandler<TParams, TState>>();\n\tlet startTurnId: TurnId | null = null;\n\n\treturn {\n\t\tstart(turnId: TurnId): void {\n\t\t\tstartTurnId = turnId;\n\t\t},\n\t\tturn(turnId: TurnId, handler: WorkerTurnHandler<TParams, TState>): void {\n\t\t\tregisterUnique(turns, turnId, handler, {\n\t\t\t\tduplicateMessage: `Worker turn '${turnId}' is already registered`,\n\t\t\t});\n\t\t},\n\t\tgetDefinition(): BuiltWorkerProcessDefinition<TParams, TState> {\n\t\t\treturn {\n\t\t\t\tstartTurnId,\n\t\t\t\tturns: cloneMap(turns),\n\t\t\t};\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;AAYO,SAAS,sBACf,IACA,UAGI,CAAC,GACqB;AAC1B,SAAO;AAAA,IACN;AAAA,IACA,aAAa,QAAQ,eAAe;AAAA,EACrC;AACD;;;ACpBO,IAAM,mBAAiD;AAAA,EAC7D,QAAQ;AACP,WAAO,CAAC;AAAA,EACT;AAAA,EACA,UAAU,OAAO;AAChB,WAAO;AAAA,EACR;AACD;;;ACTO,IAAM,sCAAsC;AAG5C,IA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AA,EACD;AACD;","names":["path","compiled","process","current","path","assertValidProcessProductName","assertValidProcessProductName","path","project","key","process","path","value","humanizeProcessLabel","process","process","path","value","record","nonEmptyString","path","asUnknownRecord","assertValidProcessProductName","isNonEmptyString","assertValidProcessProductName","asUnknownRecord","record","process"]}