import { z } from 'zod'; import { a as Stage } from './stage-DHgQdIcT.js'; import { i as AnnotationActor, v as AnnotationScope, A as AnnotationFilters, g as WorkflowAnnotationRecord } from './interface-DMzwv0lD.js'; import { P as Persistence, B as BlobStore, J as JobTransport, E as EventSink, S as Scheduler, C as Clock, A as ActivityExecutor } from './ports-HqlAB_lY.js'; import { a as KernelEventType, K as KernelEvent } from './events-B3XPPu0c.js'; /** * Workflow Builder - Fluent API for composing type-safe workflows * * Workflows are composed of stages that are executed sequentially or in parallel. * The builder ensures type safety: output of one stage matches input of next stage. * * ## Type System Features * * ### Automatic Context Inference * The workflow context type is automatically accumulated as you pipe stages. * Use `InferWorkflowContext` to extract the context type. * * ```typescript * const workflow = new WorkflowBuilder(...) * .pipe(stage1) * .pipe(stage2) * .build(); * * // Auto-generated type * type MyContext = InferWorkflowContext; * // = { "stage-1": Stage1Output, "stage-2": Stage2Output } * ``` * * ### Stage ID Constants * Use `workflow.stageIds` for type-safe stage ID references. */ interface StageNode { stage: Stage; executionGroup: number; } declare class Workflow = {}> { readonly id: string; readonly name: string; readonly description: string; readonly inputSchema: TInput; readonly outputSchema: TOutput; private readonly stages; readonly contextType?: TContext | undefined; constructor(id: string, name: string, description: string, inputSchema: TInput, outputSchema: TOutput, stages: StageNode[], contextType?: TContext | undefined); /** * Get execution plan as groups of stages * Stages in the same group can be executed in parallel */ getExecutionPlan(): StageNode[][]; /** * Get a specific stage by ID */ getStage(stageId: string): Stage | undefined; /** * Get all stages in order */ getAllStages(): StageNode[]; /** * Get a visual representation of the workflow execution order */ getExecutionOrder(): string; /** * Get all stage IDs in execution order * * @returns Array of stage IDs * * @example * ```typescript * const ids = workflow.getStageIds(); * // ["data-extraction", "guidelines", "generator"] * ``` */ getStageIds(): string[]; /** * Check if a stage ID exists in this workflow * * @param stageId - The stage ID to check * @returns true if the stage exists */ hasStage(stageId: string): boolean; /** * Validate workflow configuration before execution * Checks that all stage configs match their schemas * * @param config - Configuration object with keys matching stage IDs * @returns Validation result with any errors */ validateConfig(config: Record): { valid: boolean; errors: Array<{ stageId: string; error: string; }>; }; /** * Estimate total cost for the workflow */ estimateCost(input: z.infer, config: Record): number; /** * Get configuration schemas for all stages in this workflow * Returns a map of stageId → { schema, defaults, name, description } */ getStageConfigs(): Record; name: string; description?: string; }>; /** * Generate default configuration object for all stages * Automatically discovers all stage configs - add/remove stages and this updates automatically */ getDefaultConfig(): Record>; /** * Get all stages in a specific execution group */ getStagesInExecutionGroup(groupIndex: number): Stage[]; /** * Get the sequential index of a stage (0-based) */ getStageIndex(stageId: string): number; /** * Get the execution group index for a stage */ getExecutionGroupIndex(stageId: string): number; /** * Get the ID of the stage immediately preceding the given stage */ getPreviousStageId(stageId: string): string | undefined; } declare class WorkflowBuilder = {}> { private id; private name; private description; private inputSchema; private currentOutputSchema; private stages; private currentExecutionGroup; constructor(id: string, name: string, description: string, inputSchema: TInput, currentOutputSchema: TCurrentOutput); /** * Add a stage to the workflow (sequential execution) * * Automatically accumulates the stage's output in the context under its stage ID. * This provides type-safe access to all previous stage outputs. * * Note: This accepts any stage regardless of strict input type matching. * This is necessary because stages using passthrough() can accept objects * with additional fields beyond what's declared in their input schema. * Runtime validation via Zod ensures type safety at execution time. * * Validates that all declared dependencies exist in the workflow. */ pipe, TStageId extends string = string>(stage: Stage): WorkflowBuilder; }>; /** * Add a stage with strict input type checking * * Note: pipeStrict() and pipeLoose() have been removed as they were * just aliases for pipe(). Use pipe() for all stage chaining. */ /** * Add multiple stages that execute in parallel * * All stages receive the same input (current output) * Their outputs are merged into an object by stage ID and accumulated in context. * * Note: This accepts stages regardless of strict input type matching. * This is necessary because stages using passthrough() can accept objects * with additional fields. Runtime validation via Zod ensures type safety. * * Validates that all declared dependencies exist in the workflow. */ parallel(stages: [...TStages]): WorkflowBuilder : never : never; }>; /** * Build the final workflow */ build(): Workflow; /** * Get current stage count */ getStageCount(): number; /** * Get execution group count */ getExecutionGroupCount(): number; } /** * Extract stage IDs as a union type from a Workflow instance * * Useful for creating type-safe stage ID references. * * @example * ```typescript * type StageId = InferWorkflowStageIds; * // = "data-extraction" | "guidelines" | "generator" * * function getStageOutput(stageId: StageId) { ... } * ``` */ type InferWorkflowStageIds = W extends Workflow ? keyof C & string : never; /** * Kernel Command Types * * Discriminated union of commands accepted by the kernel's dispatch * interface, together with a conditional `CommandResult` type that maps * each command to its corresponding result. * * This file contains ONLY types -- no runtime code. */ /** Annotation to attach at run-creation time. */ interface RunCreateAnnotation { readonly attributes: Record; readonly actor?: AnnotationActor; readonly payload?: Record; readonly idempotencyKey?: string; /** * If true, the engine writes an `annotation:created` outbox event for * each attribute in this batch, in the same transaction as the run * creation. Off by default. */ readonly emitEvent?: boolean; } /** Creates a new workflow run. */ interface RunCreateCommand { readonly type: "run.create"; readonly idempotencyKey: string; readonly workflowId: string; readonly input: Record; readonly config?: Record; readonly priority?: number; /** * @deprecated since 0.8.0. Use `annotations` instead — annotations are * queryable, indexed, and follow stable conventions. `metadata` will be * removed in 1.0. */ readonly metadata?: Record; /** * Annotations to attach at run creation time. Each entry becomes one * row per attribute, sharing the supplied envelope (actor / payload / * idempotencyKey). Written inside the same transaction as the run. */ readonly annotations?: ReadonlyArray; } /** Result of a `run.create` command. */ interface RunCreateResult { readonly workflowRunId: string; readonly status: "PENDING"; } /** Claims pending runs and enqueues first-stage jobs. */ interface RunClaimPendingCommand { readonly type: "run.claimPending"; readonly workerId: string; readonly maxClaims?: number; } /** Result of a `run.claimPending` command. */ interface RunClaimPendingResult { readonly claimed: ReadonlyArray<{ readonly workflowRunId: string; readonly workflowId: string; readonly jobIds: string[]; }>; } /** Advances a workflow to the next stage group or completes it. */ interface RunTransitionCommand { readonly type: "run.transition"; readonly workflowRunId: string; } /** Result of a `run.transition` command. */ interface RunTransitionResult { readonly action: "advanced" | "completed" | "failed" | "noop"; readonly nextGroup?: number; } /** Cancels a running workflow. */ interface RunCancelCommand { readonly type: "run.cancel"; readonly workflowRunId: string; readonly reason?: string; } /** Result of a `run.cancel` command. */ interface RunCancelResult { readonly cancelled: boolean; } /** Reruns a workflow from a specific stage, deleting stages at/after that point. */ interface RunRerunFromCommand { readonly type: "run.rerunFrom"; readonly workflowRunId: string; readonly fromStageId: string; } /** Result of a `run.rerunFrom` command. */ interface RunRerunFromResult { readonly workflowRunId: string; readonly fromStageId: string; readonly deletedStages: string[]; } /** Executes a single stage within a workflow run. */ interface JobExecuteCommand { readonly type: "job.execute"; readonly idempotencyKey?: string; readonly workflowRunId: string; readonly workflowId: string; readonly stageId: string; readonly config: Record; } /** Result of a `job.execute` command. */ interface JobExecuteResult { readonly outcome: "completed" | "suspended" | "failed"; readonly output?: unknown; readonly error?: string; readonly nextPollAt?: Date; /** True when the job was discarded because the run is no longer RUNNING. */ readonly ghost?: boolean; } /** Polls suspended stages to check if they can be resumed. */ interface StagePollSuspendedCommand { readonly type: "stage.pollSuspended"; readonly maxChecks?: number; } /** Result of a `stage.pollSuspended` command. */ interface StagePollSuspendedResult { readonly checked: number; readonly resumed: number; readonly failed: number; readonly resumedWorkflowRunIds: string[]; } /** Releases stale job leases that have exceeded the threshold. */ interface LeaseReapStaleCommand { readonly type: "lease.reapStale"; readonly staleThresholdMs: number; } /** Result of a `lease.reapStale` command. */ interface LeaseReapStaleResult { readonly released: number; } /** Publishes pending outbox events through EventSink. */ interface OutboxFlushCommand { readonly type: "outbox.flush"; readonly maxEvents?: number; } /** Result of an `outbox.flush` command. */ interface OutboxFlushResult { readonly published: number; } /** Replays DLQ outbox events for reprocessing. */ interface PluginReplayDLQCommand { readonly type: "plugin.replayDLQ"; readonly maxEvents?: number; } /** Result of a `plugin.replayDLQ` command. */ interface PluginReplayDLQResult { readonly replayed: number; } /** Detects and handles RUNNING runs with no recent activity. */ interface RunReapStuckCommand { readonly type: "run.reapStuck"; readonly stuckThresholdMs: number; } /** Result of a `run.reapStuck` command. */ interface RunReapStuckResult { readonly transitioned: number; readonly failed: number; } /** Discriminated union of every kernel command. */ type KernelCommand = RunCreateCommand | RunClaimPendingCommand | RunTransitionCommand | RunCancelCommand | RunRerunFromCommand | JobExecuteCommand | StagePollSuspendedCommand | LeaseReapStaleCommand | OutboxFlushCommand | PluginReplayDLQCommand | RunReapStuckCommand; /** String literal union of all kernel command type discriminants. */ type KernelCommandType = KernelCommand["type"]; /** Maps a `KernelCommand` to its corresponding result type. */ type CommandResult = T extends RunCreateCommand ? RunCreateResult : T extends RunClaimPendingCommand ? RunClaimPendingResult : T extends RunTransitionCommand ? RunTransitionResult : T extends RunCancelCommand ? RunCancelResult : T extends RunRerunFromCommand ? RunRerunFromResult : T extends JobExecuteCommand ? JobExecuteResult : T extends StagePollSuspendedCommand ? StagePollSuspendedResult : T extends LeaseReapStaleCommand ? LeaseReapStaleResult : T extends OutboxFlushCommand ? OutboxFlushResult : T extends PluginReplayDLQCommand ? PluginReplayDLQResult : T extends RunReapStuckCommand ? RunReapStuckResult : never; declare class IdempotencyInProgressError extends Error { readonly key: string; readonly commandType: string; constructor(key: string, commandType: string); } /** * Kernel Factory * * Creates a Kernel instance with a typed `dispatch` method that routes * commands to their corresponding handlers. Events are written to a * transactional outbox (not emitted directly). Use the `outbox.flush` * command to publish pending outbox events through EventSink. * * Most commands execute inside a single database transaction (handler * logic + outbox event writes). Two exceptions manage their own * transactions to avoid holding connections during external I/O: * * - `job.execute` — multi-phase pattern (see `handlers/job-execute.ts`) * - `stage.pollSuspended` — per-stage transactions so that * checkCompletion() HTTP calls run outside any transaction * (see `handlers/stage-poll-suspended.ts`) * * Commands with idempotency keys are deduplicated: a replay returns the * cached result without re-executing the handler. */ interface WorkflowRegistry { getWorkflow(id: string): Workflow | undefined; } interface KernelConfig { persistence: Persistence; blobStore: BlobStore; jobTransport: JobTransport; eventSink: EventSink; scheduler: Scheduler; clock: Clock; registry: WorkflowRegistry; executor?: ActivityExecutor; } /** Input for the public `kernel.annotations.attach` helper. */ interface AnnotateAttachInput { attributes: Record; actor?: AnnotationActor; /** * Defaults to "run". Set to "stage" with `scopeId` to scope an * annotation to a specific stage (e.g., from a plugin observing * stage events). */ scope?: AnnotationScope; scopeId?: string | null; workflowStageRecordId?: string | null; attempt?: number; payload?: Record; idempotencyKey?: string; /** * If true, the engine writes an `annotation:created` outbox event * for each attribute in this batch, in the same transaction as the * annotation rows. Off by default. */ emitEvent?: boolean; } /** * Public helpers for working with annotations directly — for plugins, * post-hoc reviews, external integrations, and query tooling. The * `attach` path commits in a single transaction; the `list` path is a * read-only query honoring the persistence-port filters. */ interface KernelAnnotations { attach(workflowRunId: string, input: AnnotateAttachInput): Promise; list(workflowRunId: string, filters?: AnnotationFilters): Promise; } interface Kernel { dispatch(command: T): Promise>; annotations: KernelAnnotations; } interface KernelDeps { persistence: Persistence; blobStore: BlobStore; jobTransport: JobTransport; eventSink: EventSink; scheduler: Scheduler; clock: Clock; registry: WorkflowRegistry; executor: ActivityExecutor; } declare function createKernel(config: KernelConfig): Kernel; /** * Plugin Runner * * A concrete EventSink implementation that routes kernel events * to registered plugin handlers. Used as the eventSink when the * consumer wants domain side-effects on workflow events. */ interface PluginDefinition { readonly id: string; readonly name: string; readonly on: readonly T[]; handle(event: Extract): Promise; } interface PluginRunnerConfig { plugins: PluginDefinition[]; /** Max retries before an event moves to DLQ (default: 3). */ maxRetries?: number; } interface PluginRunner extends EventSink { /** Max retries before DLQ. Exposed so outbox.flush can read it. */ readonly maxRetries: number; } declare function definePlugin(definition: PluginDefinition): PluginDefinition; declare function createPluginRunner(config: PluginRunnerConfig): PluginRunner; export { type AnnotateAttachInput as A, Workflow as B, type CommandResult as C, type InferWorkflowStageIds as D, WorkflowBuilder as E, IdempotencyInProgressError as I, type JobExecuteCommand as J, type KernelDeps as K, type LeaseReapStaleCommand as L, type OutboxFlushCommand as O, type PluginDefinition as P, type RunCancelCommand as R, type StagePollSuspendedCommand as S, type WorkflowRegistry as W, type JobExecuteResult as a, type Kernel as b, type KernelAnnotations as c, type KernelCommand as d, type KernelCommandType as e, type KernelConfig as f, type LeaseReapStaleResult as g, type OutboxFlushResult as h, type PluginReplayDLQCommand as i, type PluginReplayDLQResult as j, type PluginRunner as k, type PluginRunnerConfig as l, type RunCancelResult as m, type RunClaimPendingCommand as n, type RunClaimPendingResult as o, type RunCreateAnnotation as p, type RunCreateCommand as q, type RunCreateResult as r, type RunRerunFromCommand as s, type RunRerunFromResult as t, type RunTransitionCommand as u, type RunTransitionResult as v, type StagePollSuspendedResult as w, createKernel as x, createPluginRunner as y, definePlugin as z };