@bratsos/workflow-engine 0.6.0 → 0.8.0
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.
- package/README.md +93 -0
- package/dist/{chunk-2MWO6UVR.js → chunk-NANAXHS5.js} +2 -2
- package/dist/chunk-NANAXHS5.js.map +1 -0
- package/dist/{chunk-DIADEUGZ.js → chunk-TWYPSP7P.js} +99 -7
- package/dist/chunk-TWYPSP7P.js.map +1 -0
- package/dist/{chunk-HKGZ2WHJ.js → chunk-WWK2SPN7.js} +16 -9
- package/dist/chunk-WWK2SPN7.js.map +1 -0
- package/dist/{chunk-HOGDFLCG.js → chunk-XPWAEYOO.js} +449 -59
- package/dist/chunk-XPWAEYOO.js.map +1 -0
- package/dist/{client-llB6XpHS.d.ts → client-YFKVt4p7.d.ts} +10 -21
- package/dist/client.d.ts +4 -4
- package/dist/client.js +1 -1
- package/dist/conventions/index.d.ts +114 -0
- package/dist/conventions/index.js +95 -0
- package/dist/conventions/index.js.map +1 -0
- package/dist/{events-D_P24UaY.d.ts → events-B3XPPu0c.d.ts} +23 -1
- package/dist/{index-sGgV8JNu.d.ts → index-CL0KmlyW.d.ts} +10 -1
- package/dist/index.d.ts +10 -10
- package/dist/index.js +5 -5
- package/dist/{interface-DCdddCe0.d.ts → interface-BPz138Hf.d.ts} +110 -2
- package/dist/kernel/index.d.ts +6 -6
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/testing/index.d.ts +3 -3
- package/dist/persistence/index.d.ts +2 -2
- package/dist/persistence/index.js +2 -2
- package/dist/persistence/prisma/index.d.ts +2 -2
- package/dist/persistence/prisma/index.js +2 -2
- package/dist/{plugins-Oyo_iu0l.d.ts → plugins-zT-aIcEZ.d.ts} +63 -4
- package/dist/{ports-ChGnJcn2.d.ts → ports-DUL4hlQr.d.ts} +11 -2
- package/dist/{stage-_7BKqqUG.d.ts → stage-WuK0mfrC.d.ts} +81 -1
- package/dist/testing/index.d.ts +8 -1
- package/dist/testing/index.js +88 -2
- package/dist/testing/index.js.map +1 -1
- package/package.json +6 -1
- package/skills/workflow-engine/SKILL.md +58 -1
- package/skills/workflow-engine/migrations/README.md +275 -0
- package/skills/workflow-engine/migrations/migrate-0.7-to-0.8.md +528 -0
- package/skills/workflow-engine/references/10-annotations.md +479 -0
- package/dist/chunk-2MWO6UVR.js.map +0 -1
- package/dist/chunk-DIADEUGZ.js.map +0 -1
- package/dist/chunk-HKGZ2WHJ.js.map +0 -1
- package/dist/chunk-HOGDFLCG.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts","../src/kernel/errors.ts","../src/kernel/helpers/load-workflow-context.ts","../src/kernel/helpers/save-stage-output.ts","../src/kernel/helpers/annotation-buffer.ts","../src/kernel/helpers/annotation-events.ts","../src/kernel/helpers/create-storage-shim.ts","../src/kernel/helpers/legacy-metadata-shim.ts","../src/kernel/helpers/resolve-execution-group-output.ts","../src/kernel/helpers/save-stage-artifacts.ts","../src/kernel/handlers/job-execute.ts","../src/kernel/handlers/lease-reap-stale.ts","../src/kernel/handlers/outbox-flush.ts","../src/kernel/handlers/plugin-replay-dlq.ts","../src/kernel/handlers/run-cancel.ts","../src/kernel/handlers/run-claim-pending.ts","../src/kernel/handlers/run-create.ts","../src/kernel/handlers/run-reap-stuck.ts","../src/kernel/handlers/run-rerun-from.ts","../src/kernel/handlers/run-transition.ts","../src/kernel/handlers/stage-poll-suspended.ts","../src/kernel/kernel.ts","../src/kernel/plugins.ts"],"names":["TERMINAL_STATUSES","toOutboxEvents"],"mappings":";;;AAkEoC,EAAE,MAAA,CAAO;AAAA,EAC3C,OAAA,EAAS,EAAE,MAAA,EAAO;AAAA,EAClB,SAAA,EAAW,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC/B,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC5B,WAAA,EAAa,EAAE,MAAA,EAA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AA,CAAI,SAAS,KAAK,EAAC;AACnD,MAAA,QAAA,CAAS,KAAK,MAA0B,CAAA;AACxC,MAAA,cAAA,CAAe,GAAA,CAAI,WAAW,QAAQ,CAAA;AAAA,IACxC;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IAEA,MAAM,KAAK,KAAA,EAAmC;AAC5C,MAAA,MAAM,QAAA,GAAW,cAAA,CAAe,GAAA,CAAI,KAAA,CAAM,IAAI,CAAA;AAC9C,MAAA,IAAI,CAAC,QAAA,IAAY,QAAA,CAAS,MAAA,KAAW,CAAA,EAAG;AAExC,MAAA,KAAA,MAAW,UAAU,QAAA,EAAU;AAC7B,QAAA,MAAM,MAAA,CAAO,OAAO,KAAY,CAAA;AAAA,MAClC;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-XPWAEYOO.js","sourcesContent":["/**\n * Core type definitions for Workflow System v2\n *\n * See WORKFLOW_SYSTEM_PROPOSAL.md for full architectural details\n */\n\nimport { z } from \"zod\";\n\n// ============================================================================\n// Progress & Metrics\n// ============================================================================\n\nexport interface ProgressUpdate {\n stageId: string;\n stageName: string;\n progress: number; // 0-100\n message: string;\n details?: Record<string, unknown>;\n}\n\nexport interface StageMetrics {\n startTime: number;\n endTime: number;\n duration: number;\n itemsProcessed?: number;\n itemsProduced?: number;\n aiCalls?: number;\n totalTokens?: number;\n totalCost?: number;\n}\n\n// ============================================================================\n// Embedding Support\n// ============================================================================\n\nexport interface EmbeddingResult {\n id: string;\n content: string;\n embedding: number[];\n similarity?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface EmbeddingInfo {\n model: string;\n dimensions: number;\n results: EmbeddingResult[];\n totalProcessed?: number;\n averageSimilarity?: number;\n}\n\n// ============================================================================\n// Stage Results\n// ============================================================================\n\nexport interface StageResult<TOutput> {\n output: TOutput;\n metrics: StageMetrics;\n artifacts?: Record<string, unknown>;\n embeddings?: EmbeddingInfo;\n}\n\n// ============================================================================\n// Suspended State (for async-batch operations)\n// ============================================================================\n\nexport const SuspendedStateSchema = z.object({\n batchId: z.string(),\n statusUrl: z.string().optional(),\n apiKey: z.string().optional(),\n submittedAt: z.string(), // ISO date string\n pollInterval: z.number(), // milliseconds\n maxWaitTime: z.number(), // milliseconds\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport interface SuspendedResult {\n suspended: true;\n state: z.infer<typeof SuspendedStateSchema>;\n pollConfig: {\n pollInterval: number;\n maxWaitTime: number;\n nextPollAt: Date;\n };\n metrics: StageMetrics;\n}\n\n// ============================================================================\n// Completion Check Result (for orchestrator polling)\n// ============================================================================\n\nexport interface CompletionCheckResult<TOutput> {\n ready: boolean;\n output?: TOutput;\n error?: string;\n nextCheckIn?: number; // Optional: override next poll interval\n metrics?: StageMetrics;\n embeddings?: EmbeddingInfo;\n}\n\n// ============================================================================\n// Log Levels\n// ============================================================================\n\nexport type LogLevel = \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\";\n\n// ============================================================================\n// Stage Mode\n// ============================================================================\n\nexport type StageMode =\n | \"sync\" // Execute and return immediately\n | \"async-batch\"; // Start batch job, return suspended state (separate poller handles completion)\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport function isSuspendedResult<T>(\n result: StageResult<T> | SuspendedResult,\n): result is SuspendedResult {\n return \"suspended\" in result && result.suspended === true;\n}\n\nexport function isStageResult<T>(\n result: StageResult<T> | SuspendedResult,\n): result is StageResult<T> {\n return !isSuspendedResult(result);\n}\n","export class IdempotencyInProgressError extends Error {\n constructor(\n public readonly key: string,\n public readonly commandType: string,\n ) {\n super(\n `Command \"${commandType}\" with idempotency key \"${key}\" is already in progress`,\n );\n this.name = \"IdempotencyInProgressError\";\n }\n}\n\n/**\n * Thrown inside a Phase 3 / Phase 2 transaction when the run status has\n * become non-RUNNING (typically because `run.cancel` committed between\n * the handler's initial ghost check and the transactional write). Used\n * as a sentinel to roll back the transaction cleanly; the handler\n * catches it and returns a ghost outcome to the caller.\n *\n * Without this guard, a cancel committing during stage execution could\n * still let Phase 3 commit stage updates, outbox events, and\n * annotations against an already-cancelled run.\n */\nexport class RunNotRunningError extends Error {\n constructor(\n public readonly workflowRunId: string,\n public readonly currentStatus: string,\n ) {\n super(\n `Run ${workflowRunId} is ${currentStatus}, not RUNNING — transactional write aborted`,\n );\n this.name = \"RunNotRunningError\";\n }\n}\n","/**\n * Load workflow context from completed stages.\n *\n * For each completed stage, loads the output from BlobStore using\n * the _artifactKey stored in stage.outputData.\n */\n\nimport type { KernelDeps } from \"../kernel.js\";\n\nexport async function loadWorkflowContext(\n workflowRunId: string,\n deps: KernelDeps,\n): Promise<Record<string, unknown>> {\n const completedStages = await deps.persistence.getStagesByRun(workflowRunId, {\n status: \"COMPLETED\",\n orderBy: \"asc\",\n });\n\n const context: Record<string, unknown> = {};\n\n for (const stage of completedStages) {\n const outputData = stage.outputData as any;\n if (outputData?._artifactKey) {\n context[stage.stageId] = await deps.blobStore.get(\n outputData._artifactKey,\n );\n } else if (outputData && typeof outputData === \"object\") {\n context[stage.stageId] = outputData;\n }\n }\n\n return context;\n}\n","/**\n * Save stage output to BlobStore and return the blob key.\n *\n * The key is stored in stage.outputData._artifactKey so that\n * loadWorkflowContext() can retrieve it later.\n */\n\nimport type { KernelDeps } from \"../kernel.js\";\n\nexport async function saveStageOutput(\n runId: string,\n workflowType: string,\n stageId: string,\n output: unknown,\n deps: KernelDeps,\n): Promise<string> {\n const key = `workflow-v2/${workflowType}/${runId}/${stageId}/output.json`;\n await deps.blobStore.put(key, output);\n return key;\n}\n","/**\n * AnnotationBuffer\n *\n * Small flushable list used to collect `ctx.annotate(...)` calls made\n * during a stage's `execute()` or `checkCompletion()`. The kernel\n * handler flushes the buffer inside the stage-completion transaction\n * so annotations persist atomically with the stage outcome.\n *\n * This is what makes annotations durable rather than fire-and-forget:\n * - On stage success → flush inside the success transaction\n * - On stage failure → flush inside the failure transaction (so\n * annotations recorded before a thrown error still persist)\n * - On Phase-2 stale-version rollback in stage-poll-suspended →\n * buffer is discarded together with the rolled-back stage update,\n * preventing the \"phantom annotation\" race\n */\n\nimport type { AnnotateOpts } from \"../../core/stage\";\nimport type { CreateAnnotationInput } from \"../../persistence/interface\";\n\n/**\n * Normalize the three `ctx.annotate(...)` call forms into a flat list of\n * `{ key, value, opts }` records. Handlers wire these into the\n * AnnotationBuffer with their own stage-scope fields.\n *\n * Forms:\n * - typedKey: `(key: TypedKey<T>, value: T, opts?)` — object with a\n * string `key` property and no `attributes` field\n * - string: `(key: string, value: unknown, opts?)`\n * - batch: `(args: { attributes, actor?, payload?, idempotencyKey? })`\n */\nexport function normalizeAnnotateArgs(\n args: unknown[],\n): Array<{ key: string; value: unknown; opts: AnnotateOpts | undefined }> {\n const first = args[0];\n\n if (typeof first === \"string\") {\n return [\n { key: first, value: args[1], opts: args[2] as AnnotateOpts | undefined },\n ];\n }\n\n if (\n first !== null &&\n typeof first === \"object\" &&\n \"key\" in first &&\n typeof (first as { key: unknown }).key === \"string\" &&\n !(\"attributes\" in first)\n ) {\n // TypedKey form\n return [\n {\n key: (first as { key: string }).key,\n value: args[1],\n opts: args[2] as AnnotateOpts | undefined,\n },\n ];\n }\n\n // Batch form\n const batch = first as {\n attributes?: Record<string, unknown>;\n actor?: AnnotateOpts[\"actor\"];\n payload?: AnnotateOpts[\"payload\"];\n idempotencyKey?: AnnotateOpts[\"idempotencyKey\"];\n emitEvent?: AnnotateOpts[\"emitEvent\"];\n };\n const attributes = batch?.attributes ?? {};\n const opts: AnnotateOpts = {\n actor: batch.actor,\n payload: batch.payload,\n idempotencyKey: batch.idempotencyKey,\n emitEvent: batch.emitEvent,\n };\n return Object.entries(attributes).map(([key, value]) => ({\n key,\n value,\n opts,\n }));\n}\n\nexport class AnnotationBuffer {\n private items: CreateAnnotationInput[] = [];\n\n push(input: CreateAnnotationInput): void {\n this.items.push(input);\n }\n\n /**\n * Return all buffered items and clear the buffer. Idempotent — calling\n * flush again returns an empty array.\n */\n flush(): CreateAnnotationInput[] {\n const out = this.items;\n this.items = [];\n return out;\n }\n\n size(): number {\n return this.items.length;\n }\n}\n\nexport function createAnnotationBuffer(): AnnotationBuffer {\n return new AnnotationBuffer();\n}\n","/**\n * Build `annotation:created` events from `CreateAnnotationInput` rows\n * that have opted into outbox emission. Used by both stage-scope flush\n * paths (job-execute, stage-poll-suspended) and external attach (kernel\n * annotations helper) so the event shape is consistent everywhere.\n */\n\nimport type { CreateAnnotationInput } from \"../../persistence/interface\";\nimport type { AnnotationCreatedEvent } from \"../events\";\n\nexport function buildAnnotationEvents(\n inputs: ReadonlyArray<CreateAnnotationInput>,\n now: Date,\n): AnnotationCreatedEvent[] {\n return inputs\n .filter((input) => input.emitEvent === true)\n .map((input) => ({\n type: \"annotation:created\" as const,\n timestamp: now,\n workflowRunId: input.workflowRunId,\n key: input.key,\n value: input.value,\n scope: input.scope,\n scopeId: input.scopeId ?? undefined,\n attempt: input.attempt,\n actorKind: input.actor?.kind,\n actorId: input.actor?.id,\n actorVersion: input.actor?.version,\n }));\n}\n","/**\n * Shared StageStorage implementation backed by BlobStore.\n *\n * Used by both job-execute and stage-poll-suspended handlers.\n */\n\nimport type { StageStorage } from \"../../core/stage.js\";\nimport type { KernelDeps } from \"../kernel.js\";\n\nexport function createStorageShim(\n workflowRunId: string,\n workflowType: string,\n deps: KernelDeps,\n): StageStorage {\n return {\n async save<T>(key: string, data: T): Promise<void> {\n await deps.blobStore.put(key, data);\n },\n\n async load<T>(key: string): Promise<T> {\n return deps.blobStore.get(key) as Promise<T>;\n },\n\n async exists(key: string): Promise<boolean> {\n return deps.blobStore.has(key);\n },\n\n async delete(key: string): Promise<void> {\n return deps.blobStore.delete(key);\n },\n\n getStageKey(stageId: string, suffix?: string): string {\n const base = `workflow-v2/${workflowType}/${workflowRunId}/${stageId}`;\n return suffix ? `${base}/${suffix}` : `${base}/output.json`;\n },\n };\n}\n","/**\n * Legacy metadata shim\n *\n * Synthesizes virtual `legacy.metadata.*` annotation records from a\n * run's `WorkflowRun.metadata` JSON column. Implements the transition\n * path documented in the 0.7→0.8 migration:\n *\n * - `WorkflowRun.metadata` is deprecated but remains source of truth\n * for legacy rows.\n * - `kernel.annotations.list(runId)` materializes the legacy column\n * as if it had been migrated, so consumers can query unified\n * provenance without an explicit data migration.\n * - No dual-write. The column stays as the canonical store for\n * legacy rows until a future major version, at which point a bulk\n * migration script ships and the column is removed.\n */\n\nimport type {\n AnnotationFilters,\n WorkflowAnnotationRecord,\n WorkflowRunRecord,\n} from \"../../persistence/interface\";\n\n/**\n * Build virtual annotation rows from `run.metadata`, applying the same\n * filter set that `listAnnotations` honors. Returns `[]` if there is no\n * metadata to project or the filter excludes run-scope rows.\n *\n * Synthesized rows carry a deterministic ID prefixed `synthesized:` so\n * they are distinguishable from real persisted rows. Their `createdAt`\n * is the run's `createdAt` (legacy metadata has no per-key timestamp).\n */\nexport function synthesizeLegacyMetadata(\n run: Pick<WorkflowRunRecord, \"id\" | \"createdAt\" | \"metadata\">,\n filters: AnnotationFilters = {},\n): WorkflowAnnotationRecord[] {\n if (!run.metadata || typeof run.metadata !== \"object\") return [];\n if (Array.isArray(run.metadata)) return [];\n\n // Synthesis only emits run-scope rows. Skip if the filter excludes\n // run scope, or filters on stage-only dimensions.\n if (filters.scope !== undefined && filters.scope !== \"run\") return [];\n if (filters.scopeId !== undefined && filters.scopeId !== null) return [];\n if (filters.actorId !== undefined) return [];\n if (filters.actorKind !== undefined) return [];\n if (filters.attempt !== undefined && filters.attempt !== 0) return [];\n\n // Time-range filters compare against the run's createdAt.\n if (filters.since !== undefined && run.createdAt < filters.since) return [];\n if (filters.until !== undefined && run.createdAt > filters.until) return [];\n\n const rows: WorkflowAnnotationRecord[] = [];\n for (const [originalKey, value] of Object.entries(\n run.metadata as Record<string, unknown>,\n )) {\n const key = `legacy.metadata.${originalKey}`;\n\n if (filters.key !== undefined && filters.key !== key) continue;\n if (filters.keyPrefix !== undefined && !key.startsWith(filters.keyPrefix))\n continue;\n\n rows.push({\n id: `synthesized:${run.id}:${originalKey}`,\n createdAt: run.createdAt,\n workflowRunId: run.id,\n workflowStageRecordId: null,\n attempt: 0,\n scope: \"run\",\n scopeId: null,\n actorKind: null,\n actorId: null,\n actorVersion: null,\n key,\n value,\n payload: null,\n idempotencyKey: null,\n });\n }\n\n return rows;\n}\n\n/**\n * Decide whether `kernel.annotations.list` should bother fetching the\n * run to attempt synthesis. The check is cheap and avoids a `getRun()`\n * round-trip when the filter clearly excludes legacy rows.\n */\nexport function filterCouldMatchLegacy(filters: AnnotationFilters): boolean {\n if (filters.scope !== undefined && filters.scope !== \"run\") return false;\n if (filters.scopeId !== undefined && filters.scopeId !== null) return false;\n if (filters.actorId !== undefined) return false;\n if (filters.actorKind !== undefined) return false;\n if (filters.attempt !== undefined && filters.attempt !== 0) return false;\n if (filters.key !== undefined && !filters.key.startsWith(\"legacy.metadata.\"))\n return false;\n if (filters.keyPrefix !== undefined) {\n // Either the prefix is a sub-prefix of \"legacy.metadata.\" (could match)\n // or \"legacy.metadata.\" is a sub-prefix of the filter (also could match)\n if (\n !\"legacy.metadata.\".startsWith(filters.keyPrefix) &&\n !filters.keyPrefix.startsWith(\"legacy.metadata.\")\n ) {\n return false;\n }\n }\n return true;\n}\n","/**\n * Resolve the output of an execution group from the workflow context.\n *\n * - Single-stage group → returns that stage's output directly.\n * - Multi-stage (parallel) group → returns an object keyed by stage ID.\n */\n\nimport type { Workflow } from \"../../core/workflow.js\";\n\nexport function resolveExecutionGroupOutput(\n workflow: Workflow<any, any>,\n groupIndex: number,\n workflowContext: Record<string, unknown>,\n): unknown {\n const stages = workflow.getStagesInExecutionGroup(groupIndex);\n\n if (stages.length === 0) return undefined;\n\n if (stages.length === 1) {\n return workflowContext[stages[0].id];\n }\n\n // Parallel group → merge outputs keyed by stage ID\n const merged: Record<string, unknown> = {};\n for (const stage of stages) {\n if (workflowContext[stage.id] !== undefined) {\n merged[stage.id] = workflowContext[stage.id];\n }\n }\n return merged;\n}\n","/**\n * Save stage artifacts to BlobStore using deterministic per-stage keys.\n */\n\nimport type { KernelDeps } from \"../kernel.js\";\n\nexport async function saveStageArtifacts(\n runId: string,\n workflowType: string,\n stageId: string,\n artifacts: Record<string, unknown>,\n deps: KernelDeps,\n): Promise<Record<string, string>> {\n const artifactKeys: Record<string, string> = {};\n\n for (const [artifactName, artifact] of Object.entries(artifacts)) {\n const encodedName = encodeURIComponent(artifactName);\n const key = `workflow-v2/${workflowType}/${runId}/${stageId}/artifacts/${encodedName}.json`;\n await deps.blobStore.put(key, artifact);\n artifactKeys[artifactName] = key;\n }\n\n return artifactKeys;\n}\n","/**\n * Handler: job.execute\n *\n * Executes a single stage within a workflow run using a multi-phase\n * transaction pattern:\n *\n * Phase 1 (Start): upsert stage to RUNNING + write stage:started\n * outbox event in one transaction. Commits\n * immediately so RUNNING is visible.\n *\n * Phase 2 (Execute): run stageDef.execute() outside any database\n * transaction. Progress events are collected\n * in memory.\n *\n * Phase 3 (Complete): update stage to COMPLETED/SUSPENDED/FAILED +\n * write completion outbox event (and progress\n * events) in one transaction.\n *\n * This avoids holding a database transaction open for the duration of\n * potentially long-running stage execution (AI calls, HTTP requests,\n * etc.). If the process crashes between Phase 1 and Phase 3, the\n * stage stays RUNNING and lease.reapStale will retry the job.\n */\n\nimport type { StageContext } from \"../../core/stage\";\nimport type { ProgressUpdate } from \"../../core/types\";\nimport { isSuspendedResult } from \"../../core/types\";\nimport type { Workflow } from \"../../core/workflow\";\nimport type {\n CreateAnnotationInput,\n CreateOutboxEventInput,\n} from \"../../persistence/interface\";\nimport type { JobExecuteCommand, JobExecuteResult } from \"../commands\";\nimport { RunNotRunningError } from \"../errors\";\nimport type { KernelEvent } from \"../events\";\nimport {\n buildAnnotationEvents,\n createAnnotationBuffer,\n createStorageShim,\n loadWorkflowContext,\n normalizeAnnotateArgs,\n resolveExecutionGroupOutput,\n saveStageArtifacts,\n saveStageOutput,\n} from \"../helpers/index.js\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\n// ---------------------------------------------------------------------------\n// Helper: resolve stage input\n// ---------------------------------------------------------------------------\n\nfunction resolveStageInput(\n workflow: Workflow<any, any>,\n stageId: string,\n workflowRun: { input: any },\n workflowContext: Record<string, unknown>,\n): unknown {\n const groupIndex = workflow.getExecutionGroupIndex(stageId);\n\n // First execution group always uses workflow input\n if (groupIndex <= 1) return workflowRun.input;\n\n // Resolve the previous execution group's output.\n // For single-stage groups this returns that stage's output directly.\n // For parallel groups this returns an object keyed by stage ID.\n const prevOutput = resolveExecutionGroupOutput(\n workflow,\n groupIndex - 1,\n workflowContext,\n );\n\n return prevOutput ?? workflowRun.input;\n}\n\n// ---------------------------------------------------------------------------\n// Helper: build outbox event inputs from kernel events\n// ---------------------------------------------------------------------------\n\nfunction toOutboxEvents(\n workflowRunId: string,\n causationId: string,\n events: KernelEvent[],\n): CreateOutboxEventInput[] {\n return events.map((event) => ({\n workflowRunId,\n eventType: event.type,\n payload: event,\n causationId,\n occurredAt: event.timestamp,\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport async function handleJobExecute(\n command: JobExecuteCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<JobExecuteResult>> {\n const { workflowRunId, workflowId, stageId, config } = command;\n const startTime = deps.clock.now().getTime();\n const causationId = command.idempotencyKey ?? crypto.randomUUID();\n\n // ── Pre-flight (no transaction) ──────────────────────────────────\n // Read-only lookups: workflow def, stage def, run record, context.\n\n const workflow = deps.registry.getWorkflow(workflowId);\n if (!workflow)\n throw new Error(`Workflow ${workflowId} not found in registry`);\n\n const stageDef = workflow.getStage(stageId);\n if (!stageDef)\n throw new Error(`Stage ${stageId} not found in workflow ${workflowId}`);\n\n const workflowRun = await deps.persistence.getRun(workflowRunId);\n if (!workflowRun) throw new Error(`WorkflowRun ${workflowRunId} not found`);\n\n // Guard against ghost jobs — only execute if run is actively RUNNING\n if (workflowRun.status !== \"RUNNING\") {\n return {\n outcome: \"failed\" as const,\n ghost: true,\n error: `Run ${workflowRunId} is ${workflowRun.status}, expected RUNNING — ghost job discarded`,\n _events: [],\n };\n }\n\n const workflowContext = await loadWorkflowContext(workflowRunId, deps);\n\n // ── Phase 1: Start transaction ───────────────────────────────────\n // Upsert stage to RUNNING and write stage:started outbox event.\n // Commits immediately so RUNNING status is visible to observers.\n\n const stageRecord = await deps.persistence.withTransaction(async (tx) => {\n const record = await tx.upsertStage({\n workflowRunId,\n stageId,\n create: {\n workflowRunId,\n stageId,\n stageName: stageDef.name,\n stageNumber: workflow.getStageIndex(stageId) + 1,\n executionGroup: workflow.getExecutionGroupIndex(stageId),\n status: \"RUNNING\",\n startedAt: deps.clock.now(),\n config: config as any,\n },\n update: {\n status: \"RUNNING\",\n startedAt: deps.clock.now(),\n },\n });\n\n await tx.appendOutboxEvents(\n toOutboxEvents(workflowRunId, causationId, [\n {\n type: \"stage:started\",\n timestamp: deps.clock.now(),\n workflowRunId,\n stageId,\n stageName: stageDef.name,\n stageNumber: record.stageNumber,\n },\n ]),\n );\n\n return record;\n });\n\n // ── Phase 2: Execute (no transaction) ────────────────────────────\n // The stage's execute() function runs outside any database\n // transaction. Progress events are collected in memory and\n // written to the outbox in Phase 3.\n\n const progressEvents: KernelEvent[] = [];\n\n // Buffer declared outside the try block so the failure-path catch can\n // still flush any annotations the stage recorded before the throw.\n const annotationBuffer = createAnnotationBuffer();\n\n try {\n // Resolve and validate input\n const rawInput = resolveStageInput(\n workflow,\n stageId,\n workflowRun,\n workflowContext,\n );\n const validatedInput = stageDef.inputSchema.parse(rawInput);\n\n // Parse config\n let stageConfig = (config as any)[stageId] || {};\n try {\n if (stageDef.configSchema) {\n stageConfig = stageDef.configSchema.parse(stageConfig);\n }\n } catch {\n // Fall back to raw config on parse failure\n }\n\n // Build log function (fire-and-forget, no transaction needed)\n const logFn = async (\n level: any,\n message: string,\n meta?: Record<string, unknown>,\n ) => {\n await deps.persistence\n .createLog({\n workflowRunId,\n workflowStageId: stageRecord.id,\n level: level as any,\n message,\n metadata: meta,\n })\n .catch(() => {});\n };\n\n // Stage annotate function: pushes to the buffer declared above.\n // Flushed inside the Phase 3 transaction so annotations persist\n // atomically with the stage outcome (or are dropped if the\n // transaction rolls back). Supports all three call forms (TypedKey,\n // string, batch) via the shared normalizer.\n const annotateFn = ((...args: unknown[]) => {\n const stageScopeFields = {\n workflowRunId,\n workflowStageRecordId: stageRecord.id,\n attempt: stageRecord.attempt,\n scope: \"stage\" as const,\n scopeId: stageId,\n };\n for (const { key, value, opts } of normalizeAnnotateArgs(args)) {\n // Skip undefined values — OTel pattern lets callers write\n // ctx.annotate(\"x.id\", maybeId) without guarding.\n if (value === undefined || value === null) continue;\n annotationBuffer.push({\n ...stageScopeFields,\n actor: opts?.actor,\n key,\n value,\n payload: opts?.payload,\n idempotencyKey: opts?.idempotencyKey,\n emitEvent: opts?.emitEvent,\n } satisfies CreateAnnotationInput);\n }\n }) as StageContext<any, any, any>[\"annotate\"];\n\n // Build context\n const context: StageContext<any, any, any> = {\n workflowRunId,\n stageId,\n stageNumber: stageRecord.stageNumber,\n stageName: stageDef.name,\n stageRecordId: stageRecord.id,\n input: validatedInput,\n config: stageConfig,\n resumeState: stageRecord.suspendedState as any,\n onProgress: (update: ProgressUpdate) => {\n progressEvents.push({\n type: \"stage:progress\",\n timestamp: deps.clock.now(),\n workflowRunId,\n stageId,\n progress: update.progress,\n message: update.message,\n details: update.details,\n });\n },\n onLog: logFn,\n log: logFn,\n annotate: annotateFn,\n storage: createStorageShim(workflowRunId, workflowRun.workflowType, deps),\n workflowContext,\n };\n\n // Execute the stage — this is the potentially long-running part\n const result = await stageDef.execute(context);\n\n // Re-check run status — the run may have been cancelled during execution\n const currentRunStatus = await deps.persistence.getRunStatus(workflowRunId);\n if (currentRunStatus !== \"RUNNING\") {\n return {\n outcome: \"failed\" as const,\n ghost: true,\n error: `Run ${workflowRunId} was ${currentRunStatus} after stage execution — result discarded`,\n _events: [],\n };\n }\n\n // ── Phase 3a: Complete transaction (success) ─────────────────\n if (isSuspendedResult(result)) {\n const { state, pollConfig, metrics } = result;\n const nextPollAt = new Date(\n pollConfig.nextPollAt?.getTime() ??\n deps.clock.now().getTime() + (pollConfig.pollInterval || 60000),\n );\n\n const bufferedAnnotations = annotationBuffer.flush();\n try {\n await deps.persistence.withTransaction(async (tx) => {\n // Status guard: if cancel committed between the ghost check\n // and this transaction, abort to roll back atomically.\n const currentStatus = await tx.getRunStatus(workflowRunId);\n if (currentStatus !== \"RUNNING\") {\n throw new RunNotRunningError(\n workflowRunId,\n currentStatus ?? \"DELETED\",\n );\n }\n\n await tx.updateStage(stageRecord.id, {\n status: \"SUSPENDED\",\n suspendedState: state as any,\n nextPollAt,\n pollInterval: pollConfig.pollInterval,\n maxWaitUntil: pollConfig.maxWaitTime\n ? new Date(deps.clock.now().getTime() + pollConfig.maxWaitTime)\n : undefined,\n metrics: metrics as any,\n });\n\n if (bufferedAnnotations.length > 0) {\n await tx.appendAnnotations(bufferedAnnotations);\n }\n\n const suspendedEvent: KernelEvent = {\n type: \"stage:suspended\",\n timestamp: deps.clock.now(),\n workflowRunId,\n stageId,\n stageName: stageDef.name,\n nextPollAt,\n };\n\n await tx.appendOutboxEvents(\n toOutboxEvents(workflowRunId, causationId, [\n ...progressEvents,\n suspendedEvent,\n ...buildAnnotationEvents(bufferedAnnotations, deps.clock.now()),\n ]),\n );\n });\n } catch (txError) {\n if (txError instanceof RunNotRunningError) {\n return {\n outcome: \"failed\" as const,\n ghost: true,\n error: txError.message,\n _events: [],\n };\n }\n throw txError;\n }\n\n return { outcome: \"suspended\" as const, nextPollAt, _events: [] };\n } else {\n const duration = deps.clock.now().getTime() - startTime;\n\n // Save output to blob store (not a DB operation)\n const outputKey = await saveStageOutput(\n workflowRunId,\n workflowRun.workflowType,\n stageId,\n result.output,\n deps,\n );\n const artifactKeys =\n result.artifacts && Object.keys(result.artifacts).length > 0\n ? await saveStageArtifacts(\n workflowRunId,\n workflowRun.workflowType,\n stageId,\n result.artifacts,\n deps,\n )\n : undefined;\n\n const bufferedAnnotations = annotationBuffer.flush();\n try {\n await deps.persistence.withTransaction(async (tx) => {\n const currentStatus = await tx.getRunStatus(workflowRunId);\n if (currentStatus !== \"RUNNING\") {\n throw new RunNotRunningError(\n workflowRunId,\n currentStatus ?? \"DELETED\",\n );\n }\n\n await tx.updateStage(stageRecord.id, {\n status: \"COMPLETED\",\n completedAt: deps.clock.now(),\n duration,\n outputData: {\n _artifactKey: outputKey,\n ...(artifactKeys ? { _artifactKeys: artifactKeys } : {}),\n } as any,\n metrics: result.metrics as any,\n embeddingInfo: result.embeddings as any,\n });\n\n if (bufferedAnnotations.length > 0) {\n await tx.appendAnnotations(bufferedAnnotations);\n }\n\n const completedEvent: KernelEvent = {\n type: \"stage:completed\",\n timestamp: deps.clock.now(),\n workflowRunId,\n stageId,\n stageName: stageDef.name,\n duration,\n };\n\n await tx.appendOutboxEvents(\n toOutboxEvents(workflowRunId, causationId, [\n ...progressEvents,\n completedEvent,\n ...buildAnnotationEvents(bufferedAnnotations, deps.clock.now()),\n ]),\n );\n });\n } catch (txError) {\n if (txError instanceof RunNotRunningError) {\n return {\n outcome: \"failed\" as const,\n ghost: true,\n error: txError.message,\n _events: [],\n };\n }\n throw txError;\n }\n\n return {\n outcome: \"completed\" as const,\n output: result.output,\n _events: [],\n };\n }\n } catch (error) {\n // ── Phase 3b: Complete transaction (failure) ─────────────────\n // The stage's execute() threw. Write FAILED status + outbox\n // event. If Phase 3 itself fails, re-throw the original error\n // so the idempotency key is released and the job can be retried.\n const errorMessage = error instanceof Error ? error.message : String(error);\n const duration = deps.clock.now().getTime() - startTime;\n\n // Flush any annotations recorded before the throw so they persist\n // alongside the FAILED stage outcome. If the failure transaction\n // itself rolls back, the buffer (already drained here) is lost —\n // matching the all-or-nothing semantics of the outbox events.\n const bufferedAnnotations = annotationBuffer.flush();\n try {\n await deps.persistence.withTransaction(async (tx) => {\n const currentStatus = await tx.getRunStatus(workflowRunId);\n if (currentStatus !== \"RUNNING\") {\n throw new RunNotRunningError(\n workflowRunId,\n currentStatus ?? \"DELETED\",\n );\n }\n\n await tx.updateStage(stageRecord.id, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n duration,\n errorMessage,\n });\n\n if (bufferedAnnotations.length > 0) {\n await tx.appendAnnotations(bufferedAnnotations);\n }\n\n const failedEvent: KernelEvent = {\n type: \"stage:failed\",\n timestamp: deps.clock.now(),\n workflowRunId,\n stageId,\n stageName: stageDef.name,\n error: errorMessage,\n };\n\n await tx.appendOutboxEvents(\n toOutboxEvents(workflowRunId, causationId, [\n ...progressEvents,\n failedEvent,\n ...buildAnnotationEvents(bufferedAnnotations, deps.clock.now()),\n ]),\n );\n });\n } catch (txError) {\n if (txError instanceof RunNotRunningError) {\n // Run was cancelled mid-failure-flow. Treat as ghost; the\n // stage stays RUNNING and run.cancel's cascade has already\n // handled (or will handle) cleanup.\n return {\n outcome: \"failed\" as const,\n ghost: true,\n error: txError.message,\n _events: [],\n };\n }\n // Phase 3 itself failed for some other reason. Stage stays\n // RUNNING. Re-throw the original error so the idempotency key\n // is released and lease.reapStale can retry the job.\n throw error;\n }\n\n await deps.persistence\n .createLog({\n workflowRunId,\n workflowStageId: stageRecord.id,\n level: \"ERROR\",\n message: errorMessage,\n })\n .catch(() => {});\n\n return { outcome: \"failed\" as const, error: errorMessage, _events: [] };\n }\n}\n","/**\n * Handler: lease.reapStale\n *\n * Releases stale job leases that have exceeded the threshold.\n */\n\nimport type { LeaseReapStaleCommand, LeaseReapStaleResult } from \"../commands\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\nexport async function handleLeaseReapStale(\n command: LeaseReapStaleCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<LeaseReapStaleResult>> {\n const released = await deps.jobTransport.releaseStaleJobs(\n command.staleThresholdMs,\n );\n\n return { released, _events: [] };\n}\n","/**\n * Handler: outbox.flush\n *\n * Reads unpublished outbox events and publishes them through EventSink.\n * Events are emitted in order (workflowRunId, sequence) and marked as\n * published after successful emission.\n *\n * On handler failure:\n * - Increments retryCount on the outbox event\n * - If retryCount >= maxRetries, moves event to DLQ\n * - Event is NOT marked as published (will retry on next flush)\n *\n * This handler returns _events: [] — it does NOT produce new outbox events.\n */\n\nimport type { OutboxFlushCommand, OutboxFlushResult } from \"../commands\";\nimport type { KernelEvent } from \"../events\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\nimport type { PluginRunner } from \"../plugins\";\n\nexport async function handleOutboxFlush(\n command: OutboxFlushCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<OutboxFlushResult>> {\n const limit = command.maxEvents ?? 100;\n const events = await deps.persistence.getUnpublishedOutboxEvents(limit);\n\n // Determine maxRetries from EventSink (if it's a PluginRunner)\n const maxRetries = (deps.eventSink as Partial<PluginRunner>).maxRetries ?? 3;\n\n const publishedIds: string[] = [];\n\n for (const outboxEvent of events) {\n try {\n await deps.eventSink.emit(outboxEvent.payload as KernelEvent);\n publishedIds.push(outboxEvent.id);\n } catch {\n const newCount = await deps.persistence.incrementOutboxRetryCount(\n outboxEvent.id,\n );\n if (newCount >= maxRetries) {\n await deps.persistence.moveOutboxEventToDLQ(outboxEvent.id);\n }\n // Event stays unpublished — will retry on next flush (unless DLQ'd)\n }\n }\n\n if (publishedIds.length > 0) {\n await deps.persistence.markOutboxEventsPublished(publishedIds);\n }\n\n return { published: publishedIds.length, _events: [] };\n}\n","/**\n * Handler: plugin.replayDLQ\n *\n * Resets DLQ outbox events (dlqAt and retryCount) so they are\n * picked up by the next outbox.flush invocation.\n *\n * This handler returns _events: [] — it does NOT produce new outbox events.\n */\n\nimport type {\n PluginReplayDLQCommand,\n PluginReplayDLQResult,\n} from \"../commands\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\nexport async function handlePluginReplayDLQ(\n command: PluginReplayDLQCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<PluginReplayDLQResult>> {\n const maxEvents = command.maxEvents ?? 100;\n const replayed = await deps.persistence.replayDLQEvents(maxEvents);\n return { replayed, _events: [] };\n}\n","/**\n * Handler: run.cancel\n *\n * Cancels a running workflow authoritatively:\n * 1. Marks the run as CANCELLED\n * 2. Marks all non-terminal stages as CANCELLED\n * 3. Cancels queued/suspended jobs via job transport\n */\n\nimport type { RunCancelCommand, RunCancelResult } from \"../commands\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\nconst TERMINAL_STATUSES = new Set([\"COMPLETED\", \"FAILED\", \"CANCELLED\"]);\n\nexport async function handleRunCancel(\n command: RunCancelCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<RunCancelResult>> {\n const run = await deps.persistence.getRun(command.workflowRunId);\n\n if (!run || TERMINAL_STATUSES.has(run.status)) {\n return { cancelled: false, _events: [] };\n }\n\n // 1. Mark run as CANCELLED\n await deps.persistence.updateRun(command.workflowRunId, {\n status: \"CANCELLED\",\n completedAt: deps.clock.now(),\n });\n\n // 2. Mark all non-terminal stages as CANCELLED\n const stages = await deps.persistence.getStagesByRun(command.workflowRunId);\n for (const stage of stages) {\n if (!TERMINAL_STATUSES.has(stage.status)) {\n await deps.persistence.updateStage(stage.id, {\n status: \"CANCELLED\",\n completedAt: deps.clock.now(),\n nextPollAt: null,\n });\n }\n }\n\n // 3. Cancel queued/suspended jobs\n await deps.jobTransport.cancelByRun(command.workflowRunId);\n\n return {\n cancelled: true,\n _events: [\n {\n type: \"workflow:cancelled\",\n timestamp: deps.clock.now(),\n workflowRunId: command.workflowRunId,\n reason: command.reason,\n },\n ],\n };\n}\n","/**\n * Handler: run.claimPending\n *\n * Claims pending workflow runs, creates first-stage records, and enqueues\n * their jobs for processing.\n */\n\nimport type {\n RunClaimPendingCommand,\n RunClaimPendingResult,\n} from \"../commands\";\nimport type { KernelEvent } from \"../events\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\nexport async function handleRunClaimPending(\n command: RunClaimPendingCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<RunClaimPendingResult>> {\n const maxClaims = command.maxClaims ?? 10;\n const claimed: Array<{\n workflowRunId: string;\n workflowId: string;\n jobIds: string[];\n }> = [];\n const events: KernelEvent[] = [];\n\n for (let i = 0; i < maxClaims; i++) {\n const run = await deps.persistence.claimNextPendingRun();\n if (!run) break;\n\n try {\n const workflow = deps.registry.getWorkflow(run.workflowId);\n if (!workflow) {\n const error = `Workflow ${run.workflowId} not found in registry`;\n const failedAt = deps.clock.now();\n await deps.persistence.updateRun(run.id, {\n status: \"FAILED\",\n completedAt: failedAt,\n output: {\n error: {\n code: \"WORKFLOW_NOT_FOUND\",\n message: error,\n workerId: command.workerId,\n },\n },\n });\n await deps.persistence\n .createLog({\n workflowRunId: run.id,\n level: \"ERROR\",\n message: error,\n metadata: {\n workerId: command.workerId,\n code: \"WORKFLOW_NOT_FOUND\",\n },\n })\n .catch(() => {});\n events.push({\n type: \"workflow:failed\",\n timestamp: failedAt,\n workflowRunId: run.id,\n error,\n });\n continue;\n }\n\n const stages = workflow.getStagesInExecutionGroup(1);\n if (stages.length === 0) {\n const error = `Workflow ${run.workflowId} has no stages in execution group 1`;\n const failedAt = deps.clock.now();\n await deps.persistence.updateRun(run.id, {\n status: \"FAILED\",\n completedAt: failedAt,\n output: {\n error: {\n code: \"EMPTY_STAGE_GRAPH\",\n message: error,\n workerId: command.workerId,\n },\n },\n });\n await deps.persistence\n .createLog({\n workflowRunId: run.id,\n level: \"ERROR\",\n message: error,\n metadata: {\n workerId: command.workerId,\n code: \"EMPTY_STAGE_GRAPH\",\n },\n })\n .catch(() => {});\n events.push({\n type: \"workflow:failed\",\n timestamp: failedAt,\n workflowRunId: run.id,\n error,\n });\n continue;\n }\n\n // Upsert stage records (idempotent — handles orphaned stages from previous failed claims)\n const stagesToEnqueue: typeof stages = [];\n for (const stage of stages) {\n const record = await deps.persistence.upsertStage({\n workflowRunId: run.id,\n stageId: stage.id,\n create: {\n workflowRunId: run.id,\n stageId: stage.id,\n stageName: stage.name,\n stageNumber: workflow.getStageIndex(stage.id) + 1,\n executionGroup: 1,\n status: \"PENDING\",\n config: (run.config as any)?.[stage.id] || {},\n },\n update: {},\n });\n if (record.status === \"PENDING\") {\n stagesToEnqueue.push(stage);\n }\n }\n\n // Enqueue jobs only for stages that are PENDING (skip RUNNING/COMPLETED/SUSPENDED)\n const jobIds =\n stagesToEnqueue.length > 0\n ? await deps.jobTransport.enqueueParallel(\n stagesToEnqueue.map((stage) => ({\n workflowRunId: run.id,\n workflowId: run.workflowId,\n stageId: stage.id,\n priority: run.priority,\n payload: { config: run.config || {} },\n })),\n )\n : [];\n\n events.push({\n type: \"workflow:started\",\n timestamp: deps.clock.now(),\n workflowRunId: run.id,\n });\n\n claimed.push({\n workflowRunId: run.id,\n workflowId: run.workflowId,\n jobIds,\n });\n } catch (err) {\n const error =\n err instanceof Error ? err.message : \"Unknown error during claim\";\n const failedAt = deps.clock.now();\n await deps.persistence\n .updateRun(run.id, {\n status: \"FAILED\",\n completedAt: failedAt,\n output: {\n error: {\n code: \"CLAIM_FAILED\",\n message: error,\n workerId: command.workerId,\n },\n },\n })\n .catch(() => {});\n await deps.persistence\n .createLog({\n workflowRunId: run.id,\n level: \"ERROR\",\n message: error,\n metadata: {\n workerId: command.workerId,\n code: \"CLAIM_FAILED\",\n },\n })\n .catch(() => {});\n events.push({\n type: \"workflow:failed\",\n timestamp: failedAt,\n workflowRunId: run.id,\n error,\n });\n continue;\n }\n }\n\n return { claimed, _events: events };\n}\n","/**\n * Handler: run.create\n *\n * Creates a new workflow run record after validating input and config.\n * Run-creation annotations (if provided) are written in the same\n * transaction.\n */\n\nimport type { CreateAnnotationInput } from \"../../persistence/interface\";\nimport type { RunCreateCommand, RunCreateResult } from \"../commands\";\nimport type { KernelEvent } from \"../events\";\nimport { buildAnnotationEvents } from \"../helpers/index.js\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\nexport async function handleRunCreate(\n command: RunCreateCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<RunCreateResult>> {\n // 1. Get workflow from registry\n const workflow = deps.registry.getWorkflow(command.workflowId);\n if (!workflow) {\n throw new Error(`Workflow ${command.workflowId} not found in registry`);\n }\n\n // 2. Validate input against workflow's input schema\n try {\n workflow.inputSchema.parse(command.input);\n } catch (error) {\n throw new Error(`Invalid workflow input: ${error}`);\n }\n\n // 3. Get default config and merge with provided config\n const defaultConfig = workflow.getDefaultConfig?.() ?? {};\n const mergedConfig = { ...defaultConfig, ...command.config };\n\n // 4. Validate merged config\n const configValidation = workflow.validateConfig(mergedConfig);\n if (!configValidation.valid) {\n const errors = configValidation.errors\n .map((e) => `${e.stageId}: ${e.error}`)\n .join(\", \");\n throw new Error(`Invalid workflow config: ${errors}`);\n }\n\n // 5. Calculate priority\n const priority = command.priority ?? 5;\n\n // 6. Create the run record\n const run = await deps.persistence.createRun({\n workflowId: command.workflowId,\n workflowName: workflow.name,\n workflowType: command.workflowId,\n input: command.input,\n config: mergedConfig,\n priority,\n metadata: command.metadata,\n });\n\n // 7. Attach run-creation annotations, if any (atomic with createRun\n // since this handler runs inside kernel.dispatch's withTransaction).\n const annotationEvents: KernelEvent[] = [];\n if (command.annotations && command.annotations.length > 0) {\n const annotationInputs: CreateAnnotationInput[] = [];\n for (const entry of command.annotations) {\n for (const [key, value] of Object.entries(entry.attributes)) {\n // Skip undefined and null values (OTel pattern; Prisma requires\n // explicit Prisma.JsonNull for JSON null and we don't want to\n // leak that into the public API).\n if (value === undefined || value === null) continue;\n annotationInputs.push({\n workflowRunId: run.id,\n scope: \"run\",\n actor: entry.actor,\n key,\n value,\n payload: entry.payload,\n idempotencyKey: entry.idempotencyKey,\n emitEvent: entry.emitEvent,\n });\n }\n }\n if (annotationInputs.length > 0) {\n await deps.persistence.appendAnnotations(annotationInputs);\n annotationEvents.push(\n ...buildAnnotationEvents(annotationInputs, deps.clock.now()),\n );\n }\n }\n\n return {\n workflowRunId: run.id,\n status: \"PENDING\" as const,\n _events: [\n {\n type: \"workflow:created\",\n timestamp: deps.clock.now(),\n workflowRunId: run.id,\n workflowId: command.workflowId,\n },\n ...annotationEvents,\n ],\n };\n}\n","import type { RunReapStuckCommand, RunReapStuckResult } from \"../commands\";\nimport type { KernelEvent } from \"../events\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\nexport async function handleRunReapStuck(\n command: RunReapStuckCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<RunReapStuckResult>> {\n const events: KernelEvent[] = [];\n const stuckSince = new Date(\n deps.clock.now().getTime() - command.stuckThresholdMs,\n );\n\n const stuckRuns = await deps.persistence.getStuckRuns(stuckSince);\n let failed = 0;\n\n for (const run of stuckRuns) {\n const stages = await deps.persistence.getStagesByRun(run.id);\n\n // Status guard: only update if run is still RUNNING to avoid\n // overwriting a run that recovered between query and update.\n const currentStatus = await deps.persistence.getRunStatus(run.id);\n if (currentStatus !== \"RUNNING\") {\n continue;\n }\n\n await deps.persistence.updateRun(run.id, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n output: {\n error: {\n code: \"STUCK_RUN_REAPED\",\n message: `Run stuck for >${command.stuckThresholdMs}ms with no activity`,\n stageStatuses: stages.map((s) => ({\n stageId: s.stageId,\n status: s.status,\n })),\n },\n },\n });\n\n events.push({\n type: \"workflow:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: run.id,\n error: `Stuck run reaped after ${command.stuckThresholdMs}ms inactivity`,\n });\n\n failed++;\n }\n\n return { transitioned: 0, failed, _events: events };\n}\n","/**\n * Handler: run.rerunFrom\n *\n * Reruns a workflow from a specific stage. Deletes stage records and\n * blob artifacts at/after the target execution group, resets the run\n * to RUNNING, creates new stage records, and enqueues jobs.\n *\n * Works for both COMPLETED runs (rerun from any stage) and FAILED runs\n * (retry from the failed stage).\n */\n\nimport type { RunRerunFromCommand, RunRerunFromResult } from \"../commands\";\nimport type { KernelEvent } from \"../events\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\nexport async function handleRunRerunFrom(\n command: RunRerunFromCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<RunRerunFromResult>> {\n const { workflowRunId, fromStageId } = command;\n const events: KernelEvent[] = [];\n\n // 1. Load run\n const run = await deps.persistence.getRun(workflowRunId);\n if (!run) throw new Error(`WorkflowRun ${workflowRunId} not found`);\n\n // 2. Validate run is in a rerunnable state\n if (run.status !== \"COMPLETED\" && run.status !== \"FAILED\") {\n throw new Error(\n `Cannot rerun workflow in ${run.status} state. Must be COMPLETED or FAILED.`,\n );\n }\n\n // 3. Load workflow definition\n const workflow = deps.registry.getWorkflow(run.workflowId);\n if (!workflow)\n throw new Error(`Workflow ${run.workflowId} not found in registry`);\n\n // 4. Validate stage exists in workflow\n const stageDef = workflow.getStage(fromStageId);\n if (!stageDef) {\n throw new Error(\n `Stage ${fromStageId} not found in workflow ${run.workflowId}`,\n );\n }\n\n // 5. Get the execution group of the target stage\n const targetGroup = workflow.getExecutionGroupIndex(fromStageId);\n\n // 6. Get all existing stage records\n const existingStages = await deps.persistence.getStagesByRun(workflowRunId);\n\n // 7. Validate: stages before the target group must have been executed\n if (targetGroup > 1) {\n const priorStages = existingStages.filter(\n (s) => s.executionGroup < targetGroup,\n );\n if (priorStages.length === 0) {\n throw new Error(\n `Cannot rerun from stage ${fromStageId}: previous stages have not been executed`,\n );\n }\n }\n\n // 8. Find stages to delete (at or after the target group)\n const stagesToDelete = existingStages.filter(\n (s) => s.executionGroup >= targetGroup,\n );\n const deletedStageIds = stagesToDelete.map((s) => s.stageId);\n\n // Capture the highest attempt across the stages we're about to delete.\n // New stage records will be created with attempt = (max prior + 1) so\n // annotations from the new execution can be distinguished from those\n // surviving the rerun (annotations have `onDelete: SetNull` on the\n // stage relation, so their attempt value sticks even though their\n // workflowStageRecordId is nulled).\n const priorMaxAttempt = stagesToDelete.reduce(\n (max, s) => (s.attempt > max ? s.attempt : max),\n 0,\n );\n const newAttempt = priorMaxAttempt + 1;\n\n // 9. Delete blob artifacts for stages being removed (full prefix cleanup)\n for (const stage of stagesToDelete) {\n const prefix = `workflow-v2/${run.workflowType}/${workflowRunId}/${stage.stageId}/`;\n const keys = await deps.blobStore.list(prefix).catch(() => [] as string[]);\n for (const key of keys) {\n await deps.blobStore.delete(key).catch(() => {});\n }\n }\n\n // 10. Delete stage records\n for (const stage of stagesToDelete) {\n await deps.persistence.deleteStage(stage.id);\n }\n\n // 11. Reset run to RUNNING\n await deps.persistence.updateRun(workflowRunId, {\n status: \"RUNNING\",\n startedAt: deps.clock.now(),\n completedAt: null,\n duration: null,\n output: null,\n totalCost: 0,\n totalTokens: 0,\n });\n\n // 12. Create new stage records for the target execution group\n const targetStages = workflow.getStagesInExecutionGroup(targetGroup);\n for (const stage of targetStages) {\n await deps.persistence.createStage({\n workflowRunId,\n stageId: stage.id,\n stageName: stage.name,\n stageNumber: workflow.getStageIndex(stage.id) + 1,\n executionGroup: targetGroup,\n attempt: newAttempt,\n status: \"PENDING\",\n config: (run.config as any)?.[stage.id] || {},\n });\n }\n\n // 13. Enqueue jobs\n await deps.jobTransport.enqueueParallel(\n targetStages.map((stage) => ({\n workflowRunId,\n workflowId: run.workflowId,\n stageId: stage.id,\n priority: run.priority,\n payload: { config: run.config || {} },\n })),\n );\n\n // 14. Emit workflow:started event (restarted)\n events.push({\n type: \"workflow:started\",\n timestamp: deps.clock.now(),\n workflowRunId,\n });\n\n return {\n workflowRunId,\n fromStageId,\n deletedStages: deletedStageIds,\n _events: events,\n };\n}\n","/**\n * Handler: run.transition\n *\n * Advances a workflow run to its next execution group, or marks it as\n * completed/failed depending on the current state of its stages.\n *\n * Extracted from WorkflowRuntime.transitionWorkflow() and completeWorkflow().\n */\n\nimport type { Workflow } from \"../../core/workflow\";\nimport { StaleVersionError } from \"../../persistence/interface.js\";\nimport type { RunTransitionCommand, RunTransitionResult } from \"../commands\";\nimport type { KernelEvent } from \"../events\";\nimport {\n loadWorkflowContext,\n resolveExecutionGroupOutput,\n} from \"../helpers/index.js\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\nimport type { WorkflowRunRecord } from \"../ports\";\n\n// ---------------------------------------------------------------------------\n// Terminal statuses -- a run in one of these states cannot be transitioned.\n// ---------------------------------------------------------------------------\n\nconst TERMINAL_STATUSES = new Set([\"COMPLETED\", \"FAILED\", \"CANCELLED\"]);\n\n// ---------------------------------------------------------------------------\n// Active statuses -- if any stage is in one of these states the run is still\n// in-flight and should not be transitioned yet.\n// ---------------------------------------------------------------------------\n\nconst ACTIVE_STATUSES = new Set([\"RUNNING\", \"PENDING\", \"SUSPENDED\"]);\n\n// ---------------------------------------------------------------------------\n// Helper: enqueue an execution group\n// ---------------------------------------------------------------------------\n\nasync function claimRunTransition(\n run: WorkflowRunRecord,\n deps: KernelDeps,\n): Promise<boolean> {\n try {\n await deps.persistence.updateRun(run.id, {\n expectedVersion: run.version,\n });\n return true;\n } catch (error) {\n if (error instanceof StaleVersionError) {\n return false;\n }\n throw error;\n }\n}\n\nasync function enqueueExecutionGroup(\n run: WorkflowRunRecord,\n workflow: Workflow<any, any>,\n groupIndex: number,\n deps: KernelDeps,\n): Promise<string[]> {\n const stages = workflow.getStagesInExecutionGroup(groupIndex);\n\n // Compute the current run-level attempt by taking the max attempt\n // across all existing stages. After `run.rerunFrom` bumps the target\n // group's stage records to a new attempt, this propagates the same\n // attempt to downstream groups created here, so annotations from a\n // single rerun span share one attempt value (and are distinguishable\n // from prior-attempt annotations preserved via SetNull).\n const existingStages = await deps.persistence.getStagesByRun(run.id);\n const currentAttempt = existingStages.reduce(\n (max, s) => (s.attempt > max ? s.attempt : max),\n 0,\n );\n\n const stagesToEnqueue: typeof stages = [];\n for (const stage of stages) {\n const record = await deps.persistence.upsertStage({\n workflowRunId: run.id,\n stageId: stage.id,\n create: {\n workflowRunId: run.id,\n stageId: stage.id,\n stageName: stage.name,\n stageNumber: workflow.getStageIndex(stage.id) + 1,\n executionGroup: groupIndex,\n attempt: currentAttempt,\n status: \"PENDING\",\n config: (run.config as any)?.[stage.id] || {},\n },\n update: {},\n });\n if (record.status === \"PENDING\") {\n stagesToEnqueue.push(stage);\n }\n }\n\n if (stagesToEnqueue.length === 0) return [];\n\n return deps.jobTransport.enqueueParallel(\n stagesToEnqueue.map((stage) => ({\n workflowRunId: run.id,\n workflowId: run.workflowId,\n stageId: stage.id,\n priority: run.priority,\n payload: { config: run.config || {} },\n })),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport async function handleRunTransition(\n command: RunTransitionCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<RunTransitionResult>> {\n const events: KernelEvent[] = [];\n\n // 1. Get run from persistence\n const run = await deps.persistence.getRun(command.workflowRunId);\n if (!run) {\n return { action: \"noop\" as const, _events: [] };\n }\n\n // 2. If run is already in a terminal state, nothing to do\n if (TERMINAL_STATUSES.has(run.status)) {\n return { action: \"noop\" as const, _events: [] };\n }\n\n // 3. Get workflow definition from registry\n const workflow = deps.registry.getWorkflow(run.workflowId);\n if (!workflow) {\n return { action: \"noop\" as const, _events: [] };\n }\n\n // 4. Get all stages for this run\n const stages = await deps.persistence.getStagesByRun(command.workflowRunId);\n\n // 5. If no stages exist, this is the first transition -- enqueue group 1\n if (stages.length === 0) {\n if (!(await claimRunTransition(run, deps))) {\n return { action: \"noop\" as const, _events: [] };\n }\n await enqueueExecutionGroup(run, workflow, 1, deps);\n\n events.push({\n type: \"workflow:started\",\n timestamp: deps.clock.now(),\n workflowRunId: run.id,\n });\n\n return { action: \"advanced\" as const, nextGroup: 1, _events: events };\n }\n\n // 6. If any stage is still active, the run is in-flight -- noop\n const hasActive = stages.some((s) => ACTIVE_STATUSES.has(s.status));\n if (hasActive) {\n return { action: \"noop\" as const, _events: [] };\n }\n\n // 7. If any stage has failed, mark the entire run as failed\n const failedStage = stages.find((s) => s.status === \"FAILED\");\n if (failedStage) {\n if (!(await claimRunTransition(run, deps))) {\n return { action: \"noop\" as const, _events: [] };\n }\n await deps.persistence.updateRun(command.workflowRunId, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n });\n\n events.push({\n type: \"workflow:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: command.workflowRunId,\n error: failedStage.errorMessage || \"Stage failed\",\n });\n\n return { action: \"failed\" as const, _events: events };\n }\n\n // 8. Find the maximum execution group among completed stages\n const maxGroup = stages.reduce(\n (max, s) => (s.executionGroup > max ? s.executionGroup : max),\n 0,\n );\n\n // 9. Get stages in the next execution group\n const nextGroupStages = workflow.getStagesInExecutionGroup(maxGroup + 1);\n\n // 10. If there are stages in the next group, enqueue them\n if (nextGroupStages.length > 0) {\n if (!(await claimRunTransition(run, deps))) {\n return { action: \"noop\" as const, _events: [] };\n }\n await enqueueExecutionGroup(run, workflow, maxGroup + 1, deps);\n return {\n action: \"advanced\" as const,\n nextGroup: maxGroup + 1,\n _events: events,\n };\n }\n\n // 11. No next group -- the workflow is complete\n let totalCost = 0;\n let totalTokens = 0;\n\n for (const stage of stages) {\n const metrics = stage.metrics as any;\n if (metrics) {\n totalCost += metrics.totalCost ?? 0;\n totalTokens += metrics.totalTokens ?? 0;\n }\n }\n\n const duration = deps.clock.now().getTime() - run.createdAt.getTime();\n\n // Resolve the final execution group's output for persistence\n const workflowContext = await loadWorkflowContext(\n command.workflowRunId,\n deps,\n );\n const output = resolveExecutionGroupOutput(\n workflow,\n maxGroup,\n workflowContext,\n );\n\n if (!(await claimRunTransition(run, deps))) {\n return { action: \"noop\" as const, _events: [] };\n }\n\n await deps.persistence.updateRun(command.workflowRunId, {\n status: \"COMPLETED\",\n completedAt: deps.clock.now(),\n duration,\n output,\n totalCost,\n totalTokens,\n });\n\n events.push({\n type: \"workflow:completed\",\n timestamp: deps.clock.now(),\n workflowRunId: command.workflowRunId,\n duration,\n output,\n totalCost,\n totalTokens,\n });\n\n return { action: \"completed\" as const, _events: events };\n}\n","/**\n * Handler: stage.pollSuspended\n *\n * Polls suspended stages whose nextPollAt has passed, calls each stage's\n * checkCompletion() method, and either resumes (completes) or re-schedules\n * them for a future poll.\n *\n * Uses a multi-phase pattern per stage so that checkCompletion() — which\n * typically makes external HTTP calls to batch providers — runs outside\n * any database transaction:\n *\n * Phase 1 (no transaction): Call checkCompletion() — external I/O\n * Phase 2 (transaction): Persist results + append outbox events\n *\n * This avoids Prisma P2028 interactive-transaction timeout errors when\n * batch provider APIs are slow to respond.\n */\n\nimport type { CheckCompletionContext } from \"../../core/stage\";\nimport {\n type CreateAnnotationInput,\n type CreateOutboxEventInput,\n StaleVersionError,\n} from \"../../persistence/interface\";\nimport type {\n StagePollSuspendedCommand,\n StagePollSuspendedResult,\n} from \"../commands\";\nimport { RunNotRunningError } from \"../errors\";\nimport type { KernelEvent } from \"../events\";\nimport {\n buildAnnotationEvents,\n createAnnotationBuffer,\n createStorageShim,\n normalizeAnnotateArgs,\n saveStageOutput,\n} from \"../helpers/index.js\";\nimport type { HandlerResult, KernelDeps } from \"../kernel\";\n\n// ---------------------------------------------------------------------------\n// Helper: build outbox event inputs from kernel events\n// ---------------------------------------------------------------------------\n\nfunction toOutboxEvents(\n workflowRunId: string,\n events: KernelEvent[],\n): CreateOutboxEventInput[] {\n const causationId = crypto.randomUUID();\n return events.map((event) => ({\n workflowRunId,\n eventType: event.type,\n payload: event,\n causationId,\n occurredAt: event.timestamp,\n }));\n}\n\nasync function markStageCancelled(\n stageId: string,\n deps: KernelDeps,\n): Promise<void> {\n await deps.persistence.updateStage(stageId, {\n status: \"CANCELLED\",\n completedAt: deps.clock.now(),\n nextPollAt: null,\n });\n}\n\nasync function withClaimedRun<T>(\n workflowRunId: string,\n expectedVersion: number,\n deps: KernelDeps,\n fn: (tx: KernelDeps[\"persistence\"]) => Promise<T>,\n): Promise<\n | { status: \"claimed\"; value: T }\n | { status: \"stale\" }\n | { status: \"cancelled\"; runStatus: string }\n> {\n try {\n const value = await deps.persistence.withTransaction(async (tx) => {\n // Status guard: if cancel committed between the outer\n // status check and this transaction, abort to roll back the\n // pending writes (stage update, annotations, outbox events).\n const runStatus = await tx.getRunStatus(workflowRunId);\n if (runStatus !== \"RUNNING\") {\n throw new RunNotRunningError(workflowRunId, runStatus ?? \"DELETED\");\n }\n await tx.updateRun(workflowRunId, {\n expectedVersion,\n });\n return fn(tx);\n });\n return { status: \"claimed\", value };\n } catch (error) {\n if (error instanceof StaleVersionError) {\n return { status: \"stale\" };\n }\n if (error instanceof RunNotRunningError) {\n return { status: \"cancelled\", runStatus: error.currentStatus };\n }\n throw error;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport async function handleStagePollSuspended(\n command: StagePollSuspendedCommand,\n deps: KernelDeps,\n): Promise<HandlerResult<StagePollSuspendedResult>> {\n const maxChecks = command.maxChecks ?? 50;\n\n // 1. Get suspended stages that are ready to be polled (no transaction)\n const suspendedStages = await deps.persistence.getSuspendedStages(\n deps.clock.now(),\n );\n\n // 2. Limit to maxChecks\n const stagesToCheck = suspendedStages.slice(0, maxChecks);\n\n let checked = 0;\n let resumed = 0;\n let failed = 0;\n const resumedWorkflowRunIds = new Set<string>();\n\n // 3. Process each suspended stage\n for (const stageRecord of stagesToCheck) {\n checked++;\n\n // 3a. Get workflow run (no transaction — read-only lookup)\n const run = await deps.persistence.getRun(stageRecord.workflowRunId);\n if (!run) continue;\n\n // 3a.1 Skip cancelled runs — mark the suspended stage as cancelled\n if (run.status === \"CANCELLED\") {\n await markStageCancelled(stageRecord.id, deps);\n continue;\n }\n\n // 3b. Get workflow from registry\n const workflow = deps.registry.getWorkflow(run.workflowId);\n if (!workflow) {\n await deps.persistence.withTransaction(async (tx) => {\n await tx.updateStage(stageRecord.id, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n errorMessage: `Workflow ${run.workflowId} not found in registry`,\n });\n await tx.appendOutboxEvents(\n toOutboxEvents(stageRecord.workflowRunId, [\n {\n type: \"stage:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: stageRecord.workflowRunId,\n stageId: stageRecord.stageId,\n stageName: stageRecord.stageName,\n error: `Workflow ${run.workflowId} not found in registry`,\n },\n ]),\n );\n });\n failed++;\n continue;\n }\n\n // 3c. Get stage definition\n const stageDef = workflow.getStage(stageRecord.stageId);\n if (!stageDef || !stageDef.checkCompletion) {\n const errorMsg = !stageDef\n ? `Stage ${stageRecord.stageId} not found in workflow ${run.workflowId}`\n : `Stage ${stageRecord.stageId} does not support checkCompletion`;\n\n await deps.persistence.withTransaction(async (tx) => {\n await tx.updateStage(stageRecord.id, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n errorMessage: errorMsg,\n });\n await tx.appendOutboxEvents(\n toOutboxEvents(stageRecord.workflowRunId, [\n {\n type: \"stage:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: stageRecord.workflowRunId,\n stageId: stageRecord.stageId,\n stageName: stageRecord.stageName,\n error: errorMsg,\n },\n ]),\n );\n });\n failed++;\n continue;\n }\n\n // 3d. Create storage shim and log function (uses non-transactional deps)\n const storage = createStorageShim(\n stageRecord.workflowRunId,\n run.workflowType,\n deps,\n );\n\n const logFn = async (\n level: any,\n message: string,\n meta?: Record<string, unknown>,\n ) => {\n await deps.persistence\n .createLog({\n workflowRunId: stageRecord.workflowRunId,\n workflowStageId: stageRecord.id,\n level: level as any,\n message,\n metadata: meta,\n })\n .catch(() => {});\n };\n\n // Buffer annotations made during checkCompletion. Flushed inside\n // the Phase-2 transaction (via withClaimedRun) so they persist\n // atomically with the stage outcome — or are dropped if the\n // transaction rolls back on StaleVersionError, preventing the\n // phantom-annotation race the adversarial review surfaced.\n const annotationBuffer = createAnnotationBuffer();\n const annotateFn = ((...args: unknown[]) => {\n const stageScopeFields = {\n workflowRunId: stageRecord.workflowRunId,\n workflowStageRecordId: stageRecord.id,\n attempt: stageRecord.attempt,\n scope: \"stage\" as const,\n scopeId: stageRecord.stageId,\n };\n for (const { key, value, opts } of normalizeAnnotateArgs(args)) {\n if (value === undefined || value === null) continue;\n annotationBuffer.push({\n ...stageScopeFields,\n actor: opts?.actor,\n key,\n value,\n payload: opts?.payload,\n idempotencyKey: opts?.idempotencyKey,\n emitEvent: opts?.emitEvent,\n } satisfies CreateAnnotationInput);\n }\n }) as CheckCompletionContext<unknown>[\"annotate\"];\n\n // 3e. Build check context\n const checkContext = {\n workflowRunId: run.id,\n stageId: stageRecord.stageId,\n stageRecordId: stageRecord.id,\n config: stageRecord.config || {},\n log: logFn,\n onLog: logFn,\n annotate: annotateFn,\n storage,\n };\n\n try {\n // ── Phase 1: checkCompletion (no transaction) ──────────────────\n // External HTTP calls happen here — no DB connection held open.\n const checkResult = await stageDef.checkCompletion(\n stageRecord.suspendedState as any,\n checkContext,\n );\n\n // ── Phase 2: persist results (transaction) ─────────────────────\n if (checkResult.error) {\n const bufferedAnnotations = annotationBuffer.flush();\n const claimResult = await withClaimedRun(\n stageRecord.workflowRunId,\n run.version,\n deps,\n async (tx) => {\n await tx.updateStage(stageRecord.id, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n errorMessage: checkResult.error,\n nextPollAt: null,\n });\n\n await tx.updateRun(stageRecord.workflowRunId, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n });\n\n if (bufferedAnnotations.length > 0) {\n await tx.appendAnnotations(bufferedAnnotations);\n }\n\n await tx.appendOutboxEvents(\n toOutboxEvents(stageRecord.workflowRunId, [\n {\n type: \"stage:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: stageRecord.workflowRunId,\n stageId: stageRecord.stageId,\n stageName: stageRecord.stageName,\n error: checkResult.error!,\n },\n {\n type: \"workflow:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: stageRecord.workflowRunId,\n error: checkResult.error!,\n },\n ...buildAnnotationEvents(bufferedAnnotations, deps.clock.now()),\n ]),\n );\n },\n );\n\n if (claimResult.status === \"stale\") {\n const latestStatus = await deps.persistence.getRunStatus(\n stageRecord.workflowRunId,\n );\n if (latestStatus === \"CANCELLED\") {\n await markStageCancelled(stageRecord.id, deps);\n }\n continue;\n }\n if (claimResult.status === \"cancelled\") {\n // Run was cancelled between our outer status check and the\n // Phase 2 transaction. Mark this suspended stage as cancelled\n // and move on; the Phase 2 writes (stage update, annotations,\n // outbox events) all rolled back atomically.\n await markStageCancelled(stageRecord.id, deps);\n continue;\n }\n\n failed++;\n } else if (checkResult.ready) {\n // Save output to blob store (not a DB operation)\n let outputRef: { _artifactKey: string } | undefined;\n if (checkResult.output !== undefined) {\n let validatedOutput = checkResult.output;\n try {\n validatedOutput = stageDef.outputSchema.parse(checkResult.output);\n } catch {\n // Fall back to raw output on validation failure\n }\n\n const outputKey = await saveStageOutput(\n stageRecord.workflowRunId,\n run.workflowType,\n stageRecord.stageId,\n validatedOutput,\n deps,\n );\n outputRef = { _artifactKey: outputKey };\n }\n\n const duration =\n deps.clock.now().getTime() -\n (stageRecord.startedAt?.getTime() ?? deps.clock.now().getTime());\n\n const bufferedAnnotations = annotationBuffer.flush();\n const claimResult = await withClaimedRun(\n stageRecord.workflowRunId,\n run.version,\n deps,\n async (tx) => {\n await tx.updateStage(stageRecord.id, {\n status: \"COMPLETED\",\n completedAt: deps.clock.now(),\n duration,\n outputData: outputRef as any,\n nextPollAt: null,\n metrics: checkResult.metrics as any,\n embeddingInfo: checkResult.embeddings as any,\n });\n\n if (bufferedAnnotations.length > 0) {\n await tx.appendAnnotations(bufferedAnnotations);\n }\n\n await tx.appendOutboxEvents(\n toOutboxEvents(stageRecord.workflowRunId, [\n {\n type: \"stage:completed\",\n timestamp: deps.clock.now(),\n workflowRunId: stageRecord.workflowRunId,\n stageId: stageRecord.stageId,\n stageName: stageRecord.stageName,\n duration,\n },\n ...buildAnnotationEvents(bufferedAnnotations, deps.clock.now()),\n ]),\n );\n },\n );\n\n if (claimResult.status === \"stale\") {\n const latestStatus = await deps.persistence.getRunStatus(\n stageRecord.workflowRunId,\n );\n if (latestStatus === \"CANCELLED\") {\n await markStageCancelled(stageRecord.id, deps);\n }\n continue;\n }\n if (claimResult.status === \"cancelled\") {\n // Run was cancelled between our outer status check and the\n // Phase 2 transaction. Mark this suspended stage as cancelled\n // and move on; the Phase 2 writes (stage update, annotations,\n // outbox events) all rolled back atomically.\n await markStageCancelled(stageRecord.id, deps);\n continue;\n }\n\n resumed++;\n resumedWorkflowRunIds.add(stageRecord.workflowRunId);\n } else {\n // Not ready -- update nextPollAt for next check\n const pollInterval =\n checkResult.nextCheckIn ?? stageRecord.pollInterval ?? 60000;\n\n const nextPollAt = new Date(deps.clock.now().getTime() + pollInterval);\n\n const bufferedAnnotations = annotationBuffer.flush();\n const claimResult = await withClaimedRun(\n stageRecord.workflowRunId,\n run.version,\n deps,\n async (tx) => {\n await tx.updateStage(stageRecord.id, {\n nextPollAt,\n });\n\n if (bufferedAnnotations.length > 0) {\n await tx.appendAnnotations(bufferedAnnotations);\n }\n },\n );\n\n if (claimResult.status === \"stale\") {\n const latestStatus = await deps.persistence.getRunStatus(\n stageRecord.workflowRunId,\n );\n if (latestStatus === \"CANCELLED\") {\n await markStageCancelled(stageRecord.id, deps);\n }\n continue;\n }\n if (claimResult.status === \"cancelled\") {\n // Run was cancelled between our outer status check and the\n // Phase 2 transaction. Mark this suspended stage as cancelled\n // and move on; the Phase 2 writes (stage update, annotations,\n // outbox events) all rolled back atomically.\n await markStageCancelled(stageRecord.id, deps);\n continue;\n }\n }\n } catch (error) {\n // Unexpected error during checkCompletion\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n // Flush any annotations recorded before the throw so they\n // persist alongside the FAILED outcome.\n const bufferedAnnotations = annotationBuffer.flush();\n const claimResult = await withClaimedRun(\n stageRecord.workflowRunId,\n run.version,\n deps,\n async (tx) => {\n await tx.updateStage(stageRecord.id, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n errorMessage,\n nextPollAt: null,\n });\n\n await tx.updateRun(stageRecord.workflowRunId, {\n status: \"FAILED\",\n completedAt: deps.clock.now(),\n });\n\n if (bufferedAnnotations.length > 0) {\n await tx.appendAnnotations(bufferedAnnotations);\n }\n\n await tx.appendOutboxEvents(\n toOutboxEvents(stageRecord.workflowRunId, [\n {\n type: \"stage:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: stageRecord.workflowRunId,\n stageId: stageRecord.stageId,\n stageName: stageRecord.stageName,\n error: errorMessage,\n },\n {\n type: \"workflow:failed\",\n timestamp: deps.clock.now(),\n workflowRunId: stageRecord.workflowRunId,\n error: errorMessage,\n },\n ...buildAnnotationEvents(bufferedAnnotations, deps.clock.now()),\n ]),\n );\n },\n );\n\n if (claimResult.status === \"stale\") {\n const latestStatus = await deps.persistence.getRunStatus(\n stageRecord.workflowRunId,\n );\n if (latestStatus === \"CANCELLED\") {\n await markStageCancelled(stageRecord.id, deps);\n }\n continue;\n }\n if (claimResult.status === \"cancelled\") {\n await markStageCancelled(stageRecord.id, deps);\n continue;\n }\n\n failed++;\n }\n }\n\n // Events are written directly to outbox per-stage above, so _events is empty\n return {\n checked,\n resumed,\n failed,\n resumedWorkflowRunIds: [...resumedWorkflowRunIds],\n _events: [],\n };\n}\n","/**\n * Kernel Factory\n *\n * Creates a Kernel instance with a typed `dispatch` method that routes\n * commands to their corresponding handlers. Events are written to a\n * transactional outbox (not emitted directly). Use the `outbox.flush`\n * command to publish pending outbox events through EventSink.\n *\n * Most commands execute inside a single database transaction (handler\n * logic + outbox event writes). Two exceptions manage their own\n * transactions to avoid holding connections during external I/O:\n *\n * - `job.execute` — multi-phase pattern (see `handlers/job-execute.ts`)\n * - `stage.pollSuspended` — per-stage transactions so that\n * checkCompletion() HTTP calls run outside any transaction\n * (see `handlers/stage-poll-suspended.ts`)\n *\n * Commands with idempotency keys are deduplicated: a replay returns the\n * cached result without re-executing the handler.\n */\n\nimport type { Workflow } from \"../core/workflow\";\nimport type {\n AnnotationActor,\n AnnotationFilters,\n AnnotationScope,\n CreateAnnotationInput,\n CreateOutboxEventInput,\n WorkflowAnnotationRecord,\n} from \"../persistence/interface\";\nimport type {\n CommandResult,\n JobExecuteCommand,\n KernelCommand,\n LeaseReapStaleCommand,\n OutboxFlushCommand,\n PluginReplayDLQCommand,\n RunCancelCommand,\n RunClaimPendingCommand,\n RunCreateCommand,\n RunReapStuckCommand,\n RunRerunFromCommand,\n RunTransitionCommand,\n StagePollSuspendedCommand,\n} from \"./commands\";\nimport { IdempotencyInProgressError } from \"./errors\";\nimport type { KernelEvent } from \"./events\";\nimport { handleJobExecute } from \"./handlers/job-execute\";\nimport { handleLeaseReapStale } from \"./handlers/lease-reap-stale\";\nimport { handleOutboxFlush } from \"./handlers/outbox-flush\";\nimport { handlePluginReplayDLQ } from \"./handlers/plugin-replay-dlq\";\nimport { handleRunCancel } from \"./handlers/run-cancel\";\nimport { handleRunClaimPending } from \"./handlers/run-claim-pending\";\nimport { handleRunCreate } from \"./handlers/run-create\";\nimport { handleRunReapStuck } from \"./handlers/run-reap-stuck\";\nimport { handleRunRerunFrom } from \"./handlers/run-rerun-from\";\nimport { handleRunTransition } from \"./handlers/run-transition\";\nimport { handleStagePollSuspended } from \"./handlers/stage-poll-suspended\";\nimport {\n buildAnnotationEvents,\n filterCouldMatchLegacy,\n synthesizeLegacyMetadata,\n} from \"./helpers/index.js\";\nimport type {\n BlobStore,\n Clock,\n EventSink,\n JobTransport,\n Persistence,\n Scheduler,\n} from \"./ports\";\n\n// ============================================================================\n// Public interfaces\n// ============================================================================\n\nexport interface WorkflowRegistry {\n getWorkflow(id: string): Workflow<any, any> | undefined;\n}\n\nexport interface KernelConfig {\n persistence: Persistence;\n blobStore: BlobStore;\n jobTransport: JobTransport;\n eventSink: EventSink;\n scheduler: Scheduler;\n clock: Clock;\n registry: WorkflowRegistry;\n}\n\n/** Input for the public `kernel.annotations.attach` helper. */\nexport interface AnnotateAttachInput {\n attributes: Record<string, unknown>;\n actor?: AnnotationActor;\n /**\n * Defaults to \"run\". Set to \"stage\" with `scopeId` to scope an\n * annotation to a specific stage (e.g., from a plugin observing\n * stage events).\n */\n scope?: AnnotationScope;\n scopeId?: string | null;\n workflowStageRecordId?: string | null;\n attempt?: number;\n payload?: Record<string, unknown>;\n idempotencyKey?: string;\n /**\n * If true, the engine writes an `annotation:created` outbox event\n * for each attribute in this batch, in the same transaction as the\n * annotation rows. Off by default.\n */\n emitEvent?: boolean;\n}\n\n/**\n * Public helpers for working with annotations directly — for plugins,\n * post-hoc reviews, external integrations, and query tooling. The\n * `attach` path commits in a single transaction; the `list` path is a\n * read-only query honoring the persistence-port filters.\n */\nexport interface KernelAnnotations {\n attach(workflowRunId: string, input: AnnotateAttachInput): Promise<void>;\n list(\n workflowRunId: string,\n filters?: AnnotationFilters,\n ): Promise<WorkflowAnnotationRecord[]>;\n}\n\nexport interface Kernel {\n dispatch<T extends KernelCommand>(command: T): Promise<CommandResult<T>>;\n annotations: KernelAnnotations;\n}\n\n// ============================================================================\n// Shared dependency bundle passed to every handler\n// ============================================================================\n\nexport interface KernelDeps {\n persistence: Persistence;\n blobStore: BlobStore;\n jobTransport: JobTransport;\n eventSink: EventSink;\n scheduler: Scheduler;\n clock: Clock;\n registry: WorkflowRegistry;\n}\n\n// ============================================================================\n// Internal handler result type (includes _events for central emission)\n// ============================================================================\n\nexport type HandlerResult<T> = T & { _events: KernelEvent[] };\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Extract idempotency key from commands that carry one. */\nfunction getIdempotencyKey(command: KernelCommand): string | undefined {\n if (command.type === \"run.create\") return command.idempotencyKey;\n if (command.type === \"job.execute\") return command.idempotencyKey;\n return undefined;\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createKernel(config: KernelConfig): Kernel {\n const {\n persistence,\n blobStore,\n jobTransport,\n eventSink,\n scheduler,\n clock,\n registry,\n } = config;\n\n const deps: KernelDeps = {\n persistence,\n blobStore,\n jobTransport,\n eventSink,\n scheduler,\n clock,\n registry,\n };\n\n async function dispatch<T extends KernelCommand>(\n command: T,\n ): Promise<CommandResult<T>> {\n // -----------------------------------------------------------------\n // outbox.flush routes directly — no outbox write, no idempotency\n // -----------------------------------------------------------------\n if (command.type === \"outbox.flush\") {\n const result = await handleOutboxFlush(\n command as OutboxFlushCommand,\n deps,\n );\n const { _events: _, ...publicResult } = result;\n return publicResult as CommandResult<T>;\n }\n\n // -----------------------------------------------------------------\n // plugin.replayDLQ routes directly — no outbox write, no idempotency\n // -----------------------------------------------------------------\n if (command.type === \"plugin.replayDLQ\") {\n const result = await handlePluginReplayDLQ(\n command as PluginReplayDLQCommand,\n deps,\n );\n const { _events: _, ...publicResult } = result;\n return publicResult as CommandResult<T>;\n }\n\n // -----------------------------------------------------------------\n // stage.pollSuspended manages its own per-stage transactions so\n // that checkCompletion() (which makes external HTTP calls) does\n // not hold a database transaction open.\n // -----------------------------------------------------------------\n if (command.type === \"stage.pollSuspended\") {\n const result = await handleStagePollSuspended(\n command as StagePollSuspendedCommand,\n deps,\n );\n const { _events: _, ...publicResult } = result;\n return publicResult as CommandResult<T>;\n }\n\n // -----------------------------------------------------------------\n // job.execute manages its own multi-phase transactions so that\n // RUNNING status is visible immediately and long-running stage\n // execution does not hold a database transaction open.\n // -----------------------------------------------------------------\n if (command.type === \"job.execute\") {\n const jobCommand = command as JobExecuteCommand;\n const jobIdempotencyKey = jobCommand.idempotencyKey;\n let jobIdempotencyAcquired = false;\n\n if (jobIdempotencyKey) {\n const acquired = await persistence.acquireIdempotencyKey(\n jobIdempotencyKey,\n command.type,\n );\n if (acquired.status === \"replay\") {\n return acquired.result as CommandResult<T>;\n }\n if (acquired.status === \"in_progress\") {\n throw new IdempotencyInProgressError(jobIdempotencyKey, command.type);\n }\n jobIdempotencyAcquired = true;\n }\n\n try {\n const result = await handleJobExecute(jobCommand, deps);\n const { _events: _, ...publicResult } = result;\n\n if (jobIdempotencyKey && jobIdempotencyAcquired) {\n await persistence.completeIdempotencyKey(\n jobIdempotencyKey,\n command.type,\n publicResult,\n );\n }\n\n return publicResult as CommandResult<T>;\n } catch (error) {\n if (jobIdempotencyKey && jobIdempotencyAcquired) {\n await persistence\n .releaseIdempotencyKey(jobIdempotencyKey, command.type)\n .catch(() => {});\n }\n throw error;\n }\n }\n\n // -----------------------------------------------------------------\n // Idempotency acquisition\n // -----------------------------------------------------------------\n const idempotencyKey = getIdempotencyKey(command);\n let idempotencyAcquired = false;\n\n if (idempotencyKey) {\n const acquired = await persistence.acquireIdempotencyKey(\n idempotencyKey,\n command.type,\n );\n\n if (acquired.status === \"replay\") {\n return acquired.result as CommandResult<T>;\n }\n if (acquired.status === \"in_progress\") {\n throw new IdempotencyInProgressError(idempotencyKey, command.type);\n }\n idempotencyAcquired = true;\n }\n\n try {\n // ---------------------------------------------------------------\n // Route to handler + append outbox events in one transaction\n // ---------------------------------------------------------------\n const publicResult = await persistence.withTransaction(async (tx) => {\n const txDeps: KernelDeps = { ...deps, persistence: tx };\n let result: HandlerResult<any>;\n\n switch (command.type) {\n case \"run.create\":\n result = await handleRunCreate(command as RunCreateCommand, txDeps);\n break;\n case \"run.claimPending\":\n result = await handleRunClaimPending(\n command as RunClaimPendingCommand,\n txDeps,\n );\n break;\n case \"run.transition\":\n result = await handleRunTransition(\n command as RunTransitionCommand,\n txDeps,\n );\n break;\n case \"run.cancel\":\n result = await handleRunCancel(command as RunCancelCommand, txDeps);\n break;\n case \"run.rerunFrom\":\n result = await handleRunRerunFrom(\n command as RunRerunFromCommand,\n txDeps,\n );\n break;\n case \"lease.reapStale\":\n result = await handleLeaseReapStale(\n command as LeaseReapStaleCommand,\n txDeps,\n );\n break;\n case \"run.reapStuck\":\n result = await handleRunReapStuck(\n command as RunReapStuckCommand,\n txDeps,\n );\n break;\n default: {\n const _exhaustive: never = command;\n throw new Error(\n `Unknown command type: ${(_exhaustive as KernelCommand).type}`,\n );\n }\n }\n\n const events = result._events as KernelEvent[];\n if (events.length > 0) {\n const causationId = idempotencyKey ?? crypto.randomUUID();\n const outboxEvents: CreateOutboxEventInput[] = events.map(\n (event) => ({\n workflowRunId: event.workflowRunId,\n eventType: event.type,\n payload: event,\n causationId,\n occurredAt: event.timestamp,\n }),\n );\n await tx.appendOutboxEvents(outboxEvents);\n }\n\n const { _events: _, ...stripped } = result;\n return stripped as CommandResult<T>;\n });\n\n if (idempotencyKey && idempotencyAcquired) {\n await persistence.completeIdempotencyKey(\n idempotencyKey,\n command.type,\n publicResult,\n );\n }\n\n return publicResult;\n } catch (error) {\n if (idempotencyKey && idempotencyAcquired) {\n await persistence\n .releaseIdempotencyKey(idempotencyKey, command.type)\n .catch(() => {});\n }\n throw error;\n }\n }\n\n const annotations: KernelAnnotations = {\n async attach(workflowRunId, input) {\n const scope = input.scope ?? \"run\";\n const inputs: CreateAnnotationInput[] = [];\n for (const [key, value] of Object.entries(input.attributes)) {\n // Skip `undefined` values (OTel pattern). This lets callers write\n // { \"x.id\": maybeId } without guarding — present-or-absent.\n if (value === undefined || value === null) continue;\n inputs.push({\n workflowRunId,\n workflowStageRecordId: input.workflowStageRecordId ?? null,\n attempt: input.attempt,\n scope,\n scopeId: input.scopeId ?? null,\n actor: input.actor,\n key,\n value,\n payload: input.payload,\n idempotencyKey: input.idempotencyKey,\n emitEvent: input.emitEvent,\n });\n }\n if (inputs.length === 0) return;\n // One causation id per attach call — matches the kernel's\n // dispatch convention where all events from a single command\n // share a causationId. Prefer the caller's idempotency key when\n // supplied (stable across retries); otherwise a fresh UUID.\n const causationId = input.idempotencyKey ?? crypto.randomUUID();\n // Wrap in a transaction so all attributes commit atomically.\n // Without this, an external-attach batch could partial-commit if\n // the persistence layer fails mid-write.\n await persistence.withTransaction(async (tx) => {\n await tx.appendAnnotations(inputs);\n const events = buildAnnotationEvents(inputs, clock.now());\n if (events.length > 0) {\n await tx.appendOutboxEvents(\n events.map((event) => ({\n workflowRunId: event.workflowRunId,\n eventType: event.type,\n payload: event,\n causationId,\n occurredAt: event.timestamp,\n })),\n );\n }\n });\n },\n async list(workflowRunId, filters) {\n const persisted = await persistence.listAnnotations(\n workflowRunId,\n filters,\n );\n\n // Lazy migration shim for the deprecated WorkflowRun.metadata\n // column. Synthesize virtual `legacy.metadata.*` rows iff:\n // - the filter could match legacy keys (cheap pre-check)\n // - AND no migrated `legacy.metadata.*` rows exist on the run\n // (detected via a separate, filter-agnostic query so that\n // a consumer's narrow filter — e.g. `{ keyPrefix: \"x\" }` or\n // a low `limit` — can't hide an already-migrated row and\n // trigger spurious synthesis)\n // See helpers/legacy-metadata-shim.ts for the contract.\n if (!filterCouldMatchLegacy(filters ?? {})) return persisted;\n\n const migrationCheck = await persistence.listAnnotations(workflowRunId, {\n keyPrefix: \"legacy.metadata.\",\n limit: 1,\n });\n if (migrationCheck.length > 0) return persisted;\n\n const run = await persistence.getRun(workflowRunId);\n if (!run) return persisted;\n const synthesized = synthesizeLegacyMetadata(run, filters);\n if (synthesized.length === 0) return persisted;\n\n const merged = [...persisted, ...synthesized].sort((a, b) => {\n const cmp = a.createdAt.getTime() - b.createdAt.getTime();\n if (cmp !== 0) return cmp;\n return a.id.localeCompare(b.id);\n });\n\n const limit = filters?.limit ?? 1000;\n return merged.slice(0, limit);\n },\n };\n\n return { dispatch, annotations };\n}\n","/**\n * Plugin Runner\n *\n * A concrete EventSink implementation that routes kernel events\n * to registered plugin handlers. Used as the eventSink when the\n * consumer wants domain side-effects on workflow events.\n */\n\nimport type { KernelEvent, KernelEventType } from \"./events.js\";\nimport type { EventSink } from \"./ports.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PluginDefinition<T extends KernelEventType = KernelEventType> {\n readonly id: string;\n readonly name: string;\n readonly on: readonly T[];\n handle(event: Extract<KernelEvent, { type: T }>): Promise<void>;\n}\n\nexport interface PluginRunnerConfig {\n plugins: PluginDefinition[];\n /** Max retries before an event moves to DLQ (default: 3). */\n maxRetries?: number;\n}\n\nexport interface PluginRunner extends EventSink {\n /** Max retries before DLQ. Exposed so outbox.flush can read it. */\n readonly maxRetries: number;\n}\n\n// ============================================================================\n// definePlugin\n// ============================================================================\n\nexport function definePlugin<T extends KernelEventType>(\n definition: PluginDefinition<T>,\n): PluginDefinition<T> {\n return definition;\n}\n\n// ============================================================================\n// createPluginRunner\n// ============================================================================\n\nexport function createPluginRunner(config: PluginRunnerConfig): PluginRunner {\n const { plugins, maxRetries = 3 } = config;\n\n // Pre-index plugins by event type for O(1) lookup\n const handlersByType = new Map<string, PluginDefinition[]>();\n for (const plugin of plugins) {\n for (const eventType of plugin.on) {\n const existing = handlersByType.get(eventType) ?? [];\n existing.push(plugin as PluginDefinition);\n handlersByType.set(eventType, existing);\n }\n }\n\n return {\n maxRetries,\n\n async emit(event: KernelEvent): Promise<void> {\n const matching = handlersByType.get(event.type);\n if (!matching || matching.length === 0) return;\n\n for (const plugin of matching) {\n await plugin.handle(event as any);\n }\n },\n };\n}\n"]}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import * as _ai_sdk_provider from '@ai-sdk/provider';
|
|
1
2
|
import { EmbeddingModelV3 } from '@ai-sdk/provider';
|
|
2
3
|
import { ToolSet, generateText, StepResult, streamText } from 'ai';
|
|
3
4
|
import z$1, { z } from 'zod';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import './events-
|
|
5
|
+
import { k as AICallLogger } from './interface-BPz138Hf.js';
|
|
6
|
+
import { c as StageContext, d as SuspendedStateSchema, C as CheckCompletionContext, e as CompletionCheckResult, a as Stage } from './stage-WuK0mfrC.js';
|
|
7
|
+
import './events-B3XPPu0c.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Schema Helpers and Utilities
|
|
@@ -483,23 +484,6 @@ declare class ModelStatsTracker {
|
|
|
483
484
|
*/
|
|
484
485
|
declare function printAvailableModels(): void;
|
|
485
486
|
|
|
486
|
-
/**
|
|
487
|
-
* AI Helper - Unified AI interaction tracking with hierarchical topics
|
|
488
|
-
*
|
|
489
|
-
* This is the new unified AI tracking system that replaces workflow-specific tracking.
|
|
490
|
-
* It supports:
|
|
491
|
-
* - Hierarchical topics for flexible categorization (e.g., "workflow.abc.stage.extraction")
|
|
492
|
-
* - All AI call types: generateText, generateObject, embed, streamText, batch
|
|
493
|
-
* - Automatic cost calculation with batch discounts
|
|
494
|
-
* - Persistent DB logging to AICall table
|
|
495
|
-
*
|
|
496
|
-
* @example
|
|
497
|
-
* ```typescript
|
|
498
|
-
* const ai = createAIHelper("workflow.abc123").createChild("stage", "extraction");
|
|
499
|
-
* const result = await ai.generateText("gemini-2.5-flash", prompt);
|
|
500
|
-
* ```
|
|
501
|
-
*/
|
|
502
|
-
|
|
503
487
|
/**
|
|
504
488
|
* Register a custom embedding provider factory.
|
|
505
489
|
*
|
|
@@ -516,6 +500,11 @@ declare function printAvailableModels(): void;
|
|
|
516
500
|
* ```
|
|
517
501
|
*/
|
|
518
502
|
declare function registerEmbeddingProvider(providerName: string, factory: (modelId: string) => EmbeddingModelV3): void;
|
|
503
|
+
/**
|
|
504
|
+
* Custom provider resolver. Given a ModelConfig, return an AI SDK
|
|
505
|
+
* LanguageModel to use, or null/undefined to fall back to built-in resolution.
|
|
506
|
+
*/
|
|
507
|
+
type ProviderResolver = (modelConfig: ModelConfig) => _ai_sdk_provider.LanguageModelV3 | null | undefined;
|
|
519
508
|
type AICallType = "text" | "object" | "embed" | "stream" | "batch";
|
|
520
509
|
interface AITextResult {
|
|
521
510
|
text: string;
|
|
@@ -741,6 +730,6 @@ interface AIHelper {
|
|
|
741
730
|
* const result = await ai.generateText("gemini-2.5-flash", prompt);
|
|
742
731
|
* ```
|
|
743
732
|
*/
|
|
744
|
-
declare function createAIHelper(topic: string, logger: AICallLogger, logContext?: LogContext): AIHelper;
|
|
733
|
+
declare function createAIHelper(topic: string, logger: AICallLogger, logContext?: LogContext, providerResolver?: ProviderResolver): AIHelper;
|
|
745
734
|
|
|
746
735
|
export { type AIBatch as A, type BatchLogFn as B, getModelById as C, DEFAULT_MODEL_KEY as D, type EmbedOptions as E, getRegisteredModel as F, listModels as G, listRegisteredModels as H, type InferInput as I, modelSupportsBatch as J, printAvailableModels as K, type LogContext as L, ModelKey as M, NoInputSchema as N, type ObjectOptions as O, registerEmbeddingProvider as P, registerModels as Q, type RecordCallParams as R, type SimpleStageResult as S, type TextOptions as T, requireStageOutput as U, type ModelFilter as V, type AIBatchHandle as a, type AIBatchProvider as b, type AIBatchRequest as c, type AIBatchResult as d, type AICallType as e, type AIEmbedResult as f, type AIHelper as g, type AIObjectResult as h, type AIStreamResult as i, type AITextResult as j, AVAILABLE_MODELS as k, type AsyncBatchStageDefinition as l, type EnhancedStageContext as m, type ModelConfig as n, type ModelRegistry as o, type ModelStats as p, ModelStatsTracker as q, type ModelSyncConfig as r, type StreamOptions as s, type SyncStageDefinition as t, calculateCost as u, createAIHelper as v, defineAsyncBatchStage as w, defineStage as x, getDefaultModel as y, getModel as z };
|
package/dist/client.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { g as AIHelper, k as AVAILABLE_MODELS, l as AsyncBatchStageDefinition, D as DEFAULT_MODEL_KEY, m as EnhancedStageContext, I as InferInput, n as ModelConfig, V as ModelFilter, M as ModelKey, o as ModelRegistry, N as NoInputSchema, S as SimpleStageResult, t as SyncStageDefinition, u as calculateCost, w as defineAsyncBatchStage, x as defineStage, G as listModels, J as modelSupportsBatch, Q as registerModels } from './client-
|
|
2
|
-
export { K as KernelEvent, a as KernelEventType, S as StageCompletedEvent, b as StageFailedEvent, c as StageProgressEvent, d as StageStartedEvent, e as StageSuspendedEvent, W as WorkflowCancelledEvent, f as WorkflowCompletedEvent, g as WorkflowCreatedEvent, h as WorkflowFailedEvent, i as WorkflowStartedEvent, j as WorkflowSuspendedEvent } from './events-
|
|
1
|
+
export { g as AIHelper, k as AVAILABLE_MODELS, l as AsyncBatchStageDefinition, D as DEFAULT_MODEL_KEY, m as EnhancedStageContext, I as InferInput, n as ModelConfig, V as ModelFilter, M as ModelKey, o as ModelRegistry, N as NoInputSchema, S as SimpleStageResult, t as SyncStageDefinition, u as calculateCost, w as defineAsyncBatchStage, x as defineStage, G as listModels, J as modelSupportsBatch, Q as registerModels } from './client-YFKVt4p7.js';
|
|
2
|
+
export { K as KernelEvent, a as KernelEventType, S as StageCompletedEvent, b as StageFailedEvent, c as StageProgressEvent, d as StageStartedEvent, e as StageSuspendedEvent, W as WorkflowCancelledEvent, f as WorkflowCompletedEvent, g as WorkflowCreatedEvent, h as WorkflowFailedEvent, i as WorkflowStartedEvent, j as WorkflowSuspendedEvent } from './events-B3XPPu0c.js';
|
|
3
3
|
import '@ai-sdk/provider';
|
|
4
4
|
import 'ai';
|
|
5
5
|
import 'zod';
|
|
6
|
-
import './interface-
|
|
7
|
-
import './stage-
|
|
6
|
+
import './interface-BPz138Hf.js';
|
|
7
|
+
import './stage-WuK0mfrC.js';
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { AVAILABLE_MODELS, DEFAULT_MODEL_KEY, ModelKey, NoInputSchema, calculateCost, defineAsyncBatchStage, defineStage, listModels, modelSupportsBatch, registerModels } from './chunk-
|
|
1
|
+
export { AVAILABLE_MODELS, DEFAULT_MODEL_KEY, ModelKey, NoInputSchema, calculateCost, defineAsyncBatchStage, defineStage, listModels, modelSupportsBatch, registerModels } from './chunk-WWK2SPN7.js';
|
|
2
2
|
import './chunk-MUWP5SF2.js';
|
|
3
3
|
//# sourceMappingURL=client.js.map
|
|
4
4
|
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { T as TypedKey, S as Stability } from '../stage-WuK0mfrC.js';
|
|
2
|
+
import 'zod';
|
|
3
|
+
import '../interface-BPz138Hf.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @bratsos/workflow-engine/conventions
|
|
7
|
+
*
|
|
8
|
+
* Well-known annotation keys for common provenance scenarios — trigger
|
|
9
|
+
* context, decisions, approvals, revisions. Inspired by OpenTelemetry
|
|
10
|
+
* semantic conventions: dot-namespaced flat keys, value type linked to
|
|
11
|
+
* the key via TypeScript phantom-type inference.
|
|
12
|
+
*
|
|
13
|
+
* ## Usage
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { Trigger, Decision } from "@bratsos/workflow-engine/conventions";
|
|
17
|
+
*
|
|
18
|
+
* // Type-checked: value must match the TypedKey<T> parameter.
|
|
19
|
+
* ctx.annotate(Decision.outcome, "low");
|
|
20
|
+
* ctx.annotate(Decision.confidence, 0.42);
|
|
21
|
+
* ctx.annotate(Decision.confidence, "high"); // ❌ TS error
|
|
22
|
+
*
|
|
23
|
+
* // Custom org-defined keys keep working with the string form:
|
|
24
|
+
* ctx.annotate("acme.compliance.signoff", "alice@acme.com");
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* ## Versioning policy
|
|
28
|
+
*
|
|
29
|
+
* - Keys are **immutable once `stable`**. Additions only.
|
|
30
|
+
* - Renames and value-type changes ship as **new keys**; the old key
|
|
31
|
+
* gets a `@deprecated` JSDoc tag.
|
|
32
|
+
* - We deliberately do **not** copy OpenTelemetry's
|
|
33
|
+
* `OTEL_SEMCONV_STABILITY_OPT_IN` env-var dance — versioning is
|
|
34
|
+
* handled through semver and JSDoc.
|
|
35
|
+
*
|
|
36
|
+
* See `src/conventions/README.md` for the full policy.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Define a well-known annotation key. The value-type parameter `T` is
|
|
41
|
+
* phantom — never set at runtime, used only for TypeScript inference
|
|
42
|
+
* when the key is passed to `ctx.annotate(key, value)`.
|
|
43
|
+
*/
|
|
44
|
+
declare function typedKey<T = unknown>(key: string, meta?: {
|
|
45
|
+
stability?: Stability;
|
|
46
|
+
description?: string;
|
|
47
|
+
}): TypedKey<T>;
|
|
48
|
+
/**
|
|
49
|
+
* Trigger conventions describe how a workflow run was initiated:
|
|
50
|
+
* caller identity, source system, parent run, free-text reason.
|
|
51
|
+
*
|
|
52
|
+
* Attach at `run.create` time via the `annotations` parameter.
|
|
53
|
+
*/
|
|
54
|
+
declare const Trigger: {
|
|
55
|
+
/** What system or path initiated the run, e.g. `"webhook:zendesk"`, `"manual:cli"`, `"schedule:cron"`. */
|
|
56
|
+
readonly source: TypedKey<string>;
|
|
57
|
+
/** Run ID of the prior run when this run is a follow-up / retry / chained execution. */
|
|
58
|
+
readonly parentRunId: TypedKey<string>;
|
|
59
|
+
/** Free-text reason — `"auto-triage on ticket create"`, `"manual rerun after policy change"`, etc. */
|
|
60
|
+
readonly reason: TypedKey<string>;
|
|
61
|
+
/** Actor kind discriminator — recommended values: `"user"`, `"agent"`, `"system"`. Open string. */
|
|
62
|
+
readonly actorKind: TypedKey<string>;
|
|
63
|
+
/** Stable identifier for the actor — user email, agent name, service identifier. */
|
|
64
|
+
readonly actorId: TypedKey<string>;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Decision conventions describe choices an agent or stage made
|
|
68
|
+
* during execution: the chosen outcome, the reasoning, evidence,
|
|
69
|
+
* alternatives that were considered.
|
|
70
|
+
*
|
|
71
|
+
* Attach from inside `ctx.annotate(...)` within a stage's `execute()`.
|
|
72
|
+
*/
|
|
73
|
+
declare const Decision: {
|
|
74
|
+
/** The chosen outcome. Shape is consumer-defined; `unknown` here for flexibility. */
|
|
75
|
+
readonly outcome: TypedKey<unknown>;
|
|
76
|
+
/** Free-text rationale — why the agent picked this outcome. */
|
|
77
|
+
readonly rationale: TypedKey<string>;
|
|
78
|
+
/** Confidence score, typically `0`–`1`. */
|
|
79
|
+
readonly confidence: TypedKey<number>;
|
|
80
|
+
/** Alternative outcomes that were considered but not selected. */
|
|
81
|
+
readonly alternatives: TypedKey<unknown[]>;
|
|
82
|
+
/** Whether a fallback heuristic was used (e.g., AI confidence below threshold). */
|
|
83
|
+
readonly usedFallback: TypedKey<boolean>;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Approval conventions describe sign-off events on runs or stages.
|
|
87
|
+
* Pluralization follows the OTel rule: `approvers` is plural because a
|
|
88
|
+
* single approval can have multiple approvers; the value type is
|
|
89
|
+
* always `string[]`, even with one approver.
|
|
90
|
+
*/
|
|
91
|
+
declare const Approval: {
|
|
92
|
+
/** Identifiers of all approvers. Always an array — `["alice"]` for a single approver. */
|
|
93
|
+
readonly approvers: TypedKey<string[]>;
|
|
94
|
+
/** When the approval was recorded. ISO 8601. */
|
|
95
|
+
readonly timestamp: TypedKey<string>;
|
|
96
|
+
/** Version of the policy the approval was checked against. */
|
|
97
|
+
readonly policyVersion: TypedKey<string>;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Revision conventions describe a run as a revision of a prior run:
|
|
101
|
+
* a deliberate redo, a corrected attempt, a manual override.
|
|
102
|
+
*
|
|
103
|
+
* Distinct from `Trigger.parentRunId` — that's any causal parent
|
|
104
|
+
* (including independent follow-ups), revision is specifically
|
|
105
|
+
* "this run supersedes that one."
|
|
106
|
+
*/
|
|
107
|
+
declare const Revision: {
|
|
108
|
+
/** Run ID this revision supersedes. */
|
|
109
|
+
readonly previousRunId: TypedKey<string>;
|
|
110
|
+
/** Why this revision was created. */
|
|
111
|
+
readonly reason: TypedKey<string>;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export { Approval, Decision, Revision, Stability, Trigger, TypedKey, typedKey };
|