@bratsos/workflow-engine 0.5.1 → 0.7.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.
Files changed (41) hide show
  1. package/README.md +65 -12
  2. package/dist/{chunk-RZY5YRGL.js → chunk-2HEV5ZJL.js} +2 -2
  3. package/dist/chunk-2HEV5ZJL.js.map +1 -0
  4. package/dist/{chunk-WQPZ6KON.js → chunk-5C7LRNM7.js} +280 -93
  5. package/dist/chunk-5C7LRNM7.js.map +1 -0
  6. package/dist/{chunk-PHLNTR5Z.js → chunk-Q2XDO3UF.js} +28 -7
  7. package/dist/chunk-Q2XDO3UF.js.map +1 -0
  8. package/dist/{chunk-ZYMT2PAO.js → chunk-WWK2SPN7.js} +16 -37
  9. package/dist/chunk-WWK2SPN7.js.map +1 -0
  10. package/dist/{client-oLD5ilXp.d.ts → client-DYs5wlHp.d.ts} +17 -99
  11. package/dist/client.d.ts +4 -3
  12. package/dist/client.js +1 -1
  13. package/dist/events-D_P24UaY.d.ts +105 -0
  14. package/dist/{index-CVkkGnxx.d.ts → index-aNuJ2QgN.d.ts} +11 -1
  15. package/dist/index.d.ts +184 -32
  16. package/dist/index.js +41 -9
  17. package/dist/index.js.map +1 -1
  18. package/dist/{interface-TsryH4d7.d.ts → interface-BeEPzTFy.d.ts} +9 -3
  19. package/dist/kernel/index.d.ts +6 -5
  20. package/dist/kernel/index.js +2 -1
  21. package/dist/kernel/testing/index.d.ts +3 -2
  22. package/dist/persistence/index.d.ts +2 -2
  23. package/dist/persistence/index.js +2 -2
  24. package/dist/persistence/prisma/index.d.ts +2 -2
  25. package/dist/persistence/prisma/index.js +2 -2
  26. package/dist/{plugins-C94AT8Wr.d.ts → plugins-Cl0WVVrE.d.ts} +9 -6
  27. package/dist/{ports-855bktyD.d.ts → ports-swhiWFw4.d.ts} +5 -106
  28. package/dist/{stage-BPw7m9Wx.d.ts → stage-_7BKqqUG.d.ts} +2 -2
  29. package/dist/testing/index.d.ts +2 -1
  30. package/dist/testing/index.js +25 -6
  31. package/dist/testing/index.js.map +1 -1
  32. package/package.json +1 -1
  33. package/skills/workflow-engine/SKILL.md +30 -11
  34. package/skills/workflow-engine/references/02-workflow-builder.md +2 -0
  35. package/skills/workflow-engine/references/03-runtime-setup.md +1 -1
  36. package/skills/workflow-engine/references/08-common-patterns.md +2 -1
  37. package/skills/workflow-engine/references/09-troubleshooting.md +4 -3
  38. package/dist/chunk-PHLNTR5Z.js.map +0 -1
  39. package/dist/chunk-RZY5YRGL.js.map +0 -1
  40. package/dist/chunk-WQPZ6KON.js.map +0 -1
  41. package/dist/chunk-ZYMT2PAO.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,12 +1,44 @@
1
- import { ModelKey } from './chunk-ZYMT2PAO.js';
2
- export { AVAILABLE_MODELS, AnthropicBatchProvider, DEFAULT_MODEL_KEY, GoogleBatchProvider, ModelKey, ModelStatsTracker, NoInputSchema, OpenAIBatchProvider, calculateCost, createAIHelper, defineAsyncBatchStage, defineStage, getBestProviderForModel, getDefaultModel, getModel, getModelById, getRegisteredModel, listModels, listRegisteredModels, modelSupportsBatch, printAvailableModels, registerEmbeddingProvider, registerModels, requireStageOutput, resolveModelForProvider } from './chunk-ZYMT2PAO.js';
1
+ import { ModelKey } from './chunk-WWK2SPN7.js';
2
+ export { AVAILABLE_MODELS, AnthropicBatchProvider, DEFAULT_MODEL_KEY, GoogleBatchProvider, ModelKey, ModelStatsTracker, NoInputSchema, OpenAIBatchProvider, calculateCost, createAIHelper, defineAsyncBatchStage, defineStage, getBestProviderForModel, getDefaultModel, getModel, getModelById, getRegisteredModel, listModels, listRegisteredModels, modelSupportsBatch, printAvailableModels, registerEmbeddingProvider, registerModels, requireStageOutput, resolveModelForProvider } from './chunk-WWK2SPN7.js';
3
3
  import './chunk-D7RVRRM2.js';
4
- export { PrismaAICallLogger, PrismaJobQueue, PrismaWorkflowPersistence, createPrismaAICallLogger, createPrismaJobQueue, createPrismaWorkflowPersistence } from './chunk-PHLNTR5Z.js';
4
+ export { PrismaAICallLogger, PrismaJobQueue, PrismaWorkflowPersistence, createPrismaAICallLogger, createPrismaJobQueue, createPrismaWorkflowPersistence } from './chunk-Q2XDO3UF.js';
5
5
  import './chunk-MUWP5SF2.js';
6
- export { StaleVersionError } from './chunk-RZY5YRGL.js';
7
- export { IdempotencyInProgressError, createKernel, createPluginRunner, definePlugin } from './chunk-WQPZ6KON.js';
6
+ export { IdempotencyInProgressError, createKernel, createPluginRunner, definePlugin } from './chunk-5C7LRNM7.js';
7
+ export { StaleVersionError } from './chunk-2HEV5ZJL.js';
8
8
  import { z } from 'zod';
9
9
 
10
+ // src/core/stage-ids.ts
11
+ function toConstantCase(stageId) {
12
+ return stageId.toUpperCase().replace(/-/g, "_");
13
+ }
14
+ function createStageIds(workflow) {
15
+ const stageIds = workflow.getStageIds();
16
+ const result = {};
17
+ for (const id of stageIds) {
18
+ const key = toConstantCase(id);
19
+ result[key] = id;
20
+ }
21
+ return Object.freeze(result);
22
+ }
23
+ function defineStageIds(stageIds) {
24
+ const result = {};
25
+ for (const id of stageIds) {
26
+ const key = toConstantCase(id);
27
+ result[key] = id;
28
+ }
29
+ return Object.freeze(result);
30
+ }
31
+ function isValidStageId(workflow, stageId) {
32
+ return workflow.hasStage(stageId);
33
+ }
34
+ function assertValidStageId(workflow, stageId) {
35
+ if (!workflow.hasStage(stageId)) {
36
+ const validIds = workflow.getStageIds();
37
+ throw new Error(
38
+ `Invalid stage ID: "${stageId}". Valid stage IDs for workflow "${workflow.id}": ${validIds.join(", ")}`
39
+ );
40
+ }
41
+ }
10
42
  var Workflow = class {
11
43
  constructor(id, name, description, inputSchema, outputSchema, stages, contextType) {
12
44
  this.id = id;
@@ -280,7 +312,7 @@ var WorkflowBuilder = class {
280
312
  * Add multiple stages that execute in parallel
281
313
  *
282
314
  * All stages receive the same input (current output)
283
- * Their outputs are merged into an object by index AND accumulated in context by stage ID.
315
+ * Their outputs are merged into an object by stage ID and accumulated in context.
284
316
  *
285
317
  * Note: This accepts stages regardless of strict input type matching.
286
318
  * This is necessary because stages using passthrough() can accept objects
@@ -313,8 +345,8 @@ var WorkflowBuilder = class {
313
345
  }
314
346
  const mergedSchema = z.object(
315
347
  stages.reduce(
316
- (acc, stage, index) => {
317
- acc[index] = stage.outputSchema;
348
+ (acc, stage) => {
349
+ acc[stage.id] = stage.outputSchema;
318
350
  return acc;
319
351
  },
320
352
  {}
@@ -394,6 +426,6 @@ z.object({
394
426
  temperature: z.number().min(0).max(2).default(0.7)
395
427
  });
396
428
 
397
- export { AIConfigSchema, ConcurrencyConfigSchema, DebugConfigSchema, FeatureFlagsConfigSchema, Workflow, WorkflowBuilder, withAIConfig, withConcurrency, withFeatureFlags, withStandardConfig };
429
+ export { AIConfigSchema, ConcurrencyConfigSchema, DebugConfigSchema, FeatureFlagsConfigSchema, Workflow, WorkflowBuilder, assertValidStageId, createStageIds, defineStageIds, isValidStageId, withAIConfig, withConcurrency, withFeatureFlags, withStandardConfig };
398
430
  //# sourceMappingURL=index.js.map
399
431
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/workflow.ts","../src/core/config-presets.ts"],"names":["node","z"],"mappings":";;;;;;;;;AA2CO,IAAM,WAAN,MAIL;AAAA,EACA,YACkB,EAAA,EACA,IAAA,EACA,aACA,WAAA,EACA,YAAA,EACC,QACD,WAAA,EAChB;AAPgB,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AACA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AACA,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACC,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACD,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMH,gBAAA,G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A,EAAO,EAAGA,CAAAA,CAAE,OAAA,EAAS,CAAA,CAAE,OAAA,CAAQ,EAAE;AAC5D,CAAC;AAOM,IAAM,iBAAA,GAAoBA,EAAE,MAAA,CAAO;AAAA;AAAA,EAExC,OAAA,EAASA,CAAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA;AAAA;AAAA,EAElC,MAAA,EAAQA,CAAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK;AACnC,CAAC;AAmBM,SAAS,aAAsC,MAAA,EAAwB;AAC5E,EAAA,OAAO,MAAA,CAAO,MAAM,cAAc,CAAA;AACpC;AAaO,SAAS,gBACd,MAAA,EACA;AACA,EAAA,OAAO,MAAA,CAAO,MAAM,uBAAuB,CAAA;AAC7C;AAaO,SAAS,iBACd,MAAA,EACA;AACA,EAAA,OAAO,MAAA,CAAO,MAAM,wBAAwB,CAAA;AAC9C;AAiCO,SAAS,mBACd,MAAA,EACA;AACA,EAAA,OAAO,MAAA,CACJ,MAAM,cAAc,CAAA,CACpB,MAAM,uBAAuB,CAAA,CAC7B,MAAM,wBAAwB,CAAA;AACnC;AAiDiCA,CAAAA,CAAE,MAAA,CAAO,EAAE;AAKPA,EAAE,MAAA,CAAO;AAAA,EAC5C,KAAA,EAAO,QAAA,CAAS,OAAA,CAAQ,kBAAkB,CAAA;AAAA,EAC1C,WAAA,EAAaA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,OAAA,CAAQ,GAAG;AACnD,CAAC","file":"index.js","sourcesContent":["/**\n * Workflow Builder - Fluent API for composing type-safe workflows\n *\n * Workflows are composed of stages that are executed sequentially or in parallel.\n * The builder ensures type safety: output of one stage matches input of next stage.\n *\n * ## Type System Features\n *\n * ### Automatic Context Inference\n * The workflow context type is automatically accumulated as you pipe stages.\n * Use `InferWorkflowContext<typeof workflow>` to extract the context type.\n *\n * ```typescript\n * const workflow = new WorkflowBuilder(...)\n * .pipe(stage1)\n * .pipe(stage2)\n * .build();\n *\n * // Auto-generated type\n * type MyContext = InferWorkflowContext<typeof workflow>;\n * // = { \"stage-1\": Stage1Output, \"stage-2\": Stage2Output }\n * ```\n *\n * ### Stage ID Constants\n * Use `workflow.stageIds` for type-safe stage ID references.\n */\n\nimport { z } from \"zod\";\nimport type { Stage } from \"./stage\";\n\n// ============================================================================\n// Stage Node - Represents a stage in the execution plan\n// ============================================================================\n\nexport interface StageNode {\n stage: Stage<any, any, any>;\n executionGroup: number; // For parallel execution grouping\n}\n\n// ============================================================================\n// Workflow - Complete workflow definition\n// ============================================================================\n\nexport class Workflow<\n TInput extends z.ZodTypeAny,\n TOutput extends z.ZodTypeAny,\n TContext extends Record<string, unknown> = {},\n> {\n constructor(\n public readonly id: string,\n public readonly name: string,\n public readonly description: string,\n public readonly inputSchema: TInput,\n public readonly outputSchema: TOutput,\n private readonly stages: StageNode[],\n public readonly contextType?: TContext, // Type-only, for inference\n ) {}\n\n /**\n * Get execution plan as groups of stages\n * Stages in the same group can be executed in parallel\n */\n getExecutionPlan(): StageNode[][] {\n const groups = new Map<number, StageNode[]>();\n\n for (const node of this.stages) {\n const group = groups.get(node.executionGroup) || [];\n group.push(node);\n groups.set(node.executionGroup, group);\n }\n\n // Return groups in order\n const sortedGroups = Array.from(groups.keys()).sort((a, b) => a - b);\n return sortedGroups.map((groupNum) => {\n const group = groups.get(groupNum);\n if (!group) throw new Error(`Group ${groupNum} not found`);\n return group;\n });\n }\n\n /**\n * Get a specific stage by ID\n */\n getStage(stageId: string): Stage<any, any, any> | undefined {\n const node = this.stages.find((n) => n.stage.id === stageId);\n return node?.stage;\n }\n\n /**\n * Get all stages in order\n */\n getAllStages(): StageNode[] {\n return [...this.stages];\n }\n\n /**\n * Get a visual representation of the workflow execution order\n */\n getExecutionOrder(): string {\n const executionPlan = this.getExecutionPlan();\n const lines: string[] = [];\n\n lines.push(`Workflow: ${this.name} (${this.id})`);\n lines.push(`Total stages: ${this.stages.length}`);\n lines.push(`Execution groups: ${executionPlan.length}`);\n lines.push(\"\");\n lines.push(\"Execution Order:\");\n lines.push(\"================\");\n\n for (let i = 0; i < executionPlan.length; i++) {\n const group = executionPlan[i];\n const groupNumber = i + 1;\n\n if (group.length === 1) {\n // Sequential stage\n const stage = group[0].stage;\n lines.push(`${groupNumber}. ${stage.name} (${stage.id})`);\n if (stage.description) {\n lines.push(` ${stage.description}`);\n }\n } else {\n // Parallel stages\n lines.push(`${groupNumber}. [PARALLEL]`);\n for (const node of group) {\n const stage = node.stage;\n lines.push(` - ${stage.name} (${stage.id})`);\n if (stage.description) {\n lines.push(` ${stage.description}`);\n }\n }\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Get all stage IDs in execution order\n *\n * @returns Array of stage IDs\n *\n * @example\n * ```typescript\n * const ids = workflow.getStageIds();\n * // [\"data-extraction\", \"guidelines\", \"generator\"]\n * ```\n */\n getStageIds(): string[] {\n return this.stages.map((node) => node.stage.id);\n }\n\n /**\n * Check if a stage ID exists in this workflow\n *\n * @param stageId - The stage ID to check\n * @returns true if the stage exists\n */\n hasStage(stageId: string): boolean {\n return this.stages.some((node) => node.stage.id === stageId);\n }\n\n /**\n * Validate workflow configuration before execution\n * Checks that all stage configs match their schemas\n *\n * @param config - Configuration object with keys matching stage IDs\n * @returns Validation result with any errors\n */\n validateConfig(config: Record<string, unknown>): {\n valid: boolean;\n errors: Array<{ stageId: string; error: string }>;\n } {\n const errors: Array<{ stageId: string; error: string }> = [];\n\n for (const node of this.stages) {\n const stage = node.stage;\n const stageConfig = config[stage.id] || {};\n\n try {\n stage.configSchema.parse(stageConfig);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errorMessages = error.issues\n .map((e: z.ZodIssue) => `${e.path.join(\".\")}: ${e.message}`)\n .join(\"; \");\n errors.push({\n stageId: stage.id,\n error: `Config validation failed: ${errorMessages}`,\n });\n } else {\n errors.push({\n stageId: stage.id,\n error: String(error),\n });\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n }\n\n /**\n * Estimate total cost for the workflow\n */\n estimateCost(\n input: z.infer<TInput>,\n config: Record<string, unknown>,\n ): number {\n let totalCost = 0;\n const currentInput = input;\n\n for (const node of this.stages) {\n if (node.stage.estimateCost) {\n const stageConfig = config[node.stage.id] || {};\n totalCost += node.stage.estimateCost(currentInput, stageConfig);\n }\n // Note: We can't accurately propagate input for estimation without execution\n // This is a rough estimate only\n }\n\n return totalCost;\n }\n\n /**\n * Get configuration schemas for all stages in this workflow\n * Returns a map of stageId → { schema, defaults, name, description }\n */\n getStageConfigs(): Record<\n string,\n {\n schema: z.ZodTypeAny;\n defaults: Record<string, unknown>;\n name: string;\n description?: string;\n }\n > {\n const configs: Record<\n string,\n {\n schema: z.ZodTypeAny;\n defaults: Record<string, unknown>;\n name: string;\n description?: string;\n }\n > = {};\n\n for (const node of this.stages) {\n const stage = node.stage;\n\n // Extract defaults from schema\n const defaults: Record<string, unknown> = {};\n\n if (stage.configSchema instanceof z.ZodObject) {\n const shape = stage.configSchema.shape as Record<string, z.ZodTypeAny>;\n for (const [key, fieldSchema] of Object.entries(shape)) {\n let unwrapped = fieldSchema;\n\n // Unwrap ZodOptional if present\n if (unwrapped instanceof z.ZodOptional) {\n unwrapped = (unwrapped._def as any).innerType;\n }\n\n // Check for ZodDefault\n if (unwrapped instanceof z.ZodDefault) {\n const defaultValueFn = (unwrapped._def as any).defaultValue;\n defaults[key] =\n typeof defaultValueFn === \"function\"\n ? defaultValueFn()\n : defaultValueFn;\n }\n }\n }\n\n configs[stage.id] = {\n schema: stage.configSchema,\n defaults,\n name: stage.name,\n description: stage.description,\n };\n }\n\n return configs;\n }\n\n /**\n * Generate default configuration object for all stages\n * Automatically discovers all stage configs - add/remove stages and this updates automatically\n */\n getDefaultConfig(): Record<string, Record<string, unknown>> {\n const stageConfigs = this.getStageConfigs();\n const config: Record<string, Record<string, unknown>> = {};\n\n for (const [stageId, meta] of Object.entries(stageConfigs)) {\n config[stageId] = meta.defaults;\n }\n\n return config;\n }\n /**\n * Get all stages in a specific execution group\n */\n getStagesInExecutionGroup(groupIndex: number): Stage<any, any, any>[] {\n return this.stages\n .filter((node) => node.executionGroup === groupIndex)\n .map((node) => node.stage);\n }\n\n /**\n * Get the sequential index of a stage (0-based)\n */\n getStageIndex(stageId: string): number {\n return this.stages.findIndex((node) => node.stage.id === stageId);\n }\n\n /**\n * Get the execution group index for a stage\n */\n getExecutionGroupIndex(stageId: string): number {\n const node = this.stages.find((node) => node.stage.id === stageId);\n if (!node) throw new Error(`Stage ${stageId} not found in workflow`);\n return node.executionGroup;\n }\n\n /**\n * Get the ID of the stage immediately preceding the given stage\n */\n getPreviousStageId(stageId: string): string | undefined {\n const index = this.getStageIndex(stageId);\n if (index <= 0) return undefined;\n return this.stages[index - 1].stage.id;\n }\n}\n\n// ============================================================================\n// Workflow Builder - Fluent API with Context Accumulation\n// ============================================================================\n\nexport class WorkflowBuilder<\n TInput extends z.ZodTypeAny,\n TCurrentOutput extends z.ZodTypeAny,\n TContext extends Record<string, unknown> = {},\n> {\n private stages: StageNode[] = [];\n private currentExecutionGroup = 0;\n\n constructor(\n private id: string,\n private name: string,\n private description: string,\n private inputSchema: TInput,\n private currentOutputSchema: TCurrentOutput,\n ) {}\n\n /**\n * Add a stage to the workflow (sequential execution)\n *\n * Automatically accumulates the stage's output in the context under its stage ID.\n * This provides type-safe access to all previous stage outputs.\n *\n * Note: This accepts any stage regardless of strict input type matching.\n * This is necessary because stages using passthrough() can accept objects\n * with additional fields beyond what's declared in their input schema.\n * Runtime validation via Zod ensures type safety at execution time.\n *\n * Validates that all declared dependencies exist in the workflow.\n */\n pipe<\n TStageInput extends z.ZodTypeAny,\n TStageOutput extends z.ZodTypeAny,\n TStageConfig extends z.ZodTypeAny,\n TStageContext extends Record<string, unknown>,\n >(\n stage: Stage<TStageInput, TStageOutput, TStageConfig, TStageContext>,\n ): WorkflowBuilder<\n TInput,\n TStageOutput,\n TContext & { [x: string]: z.infer<TStageOutput> }\n > {\n // Validate stage dependencies\n if (stage.dependencies) {\n const existingStageIds = this.stages.map((s) => s.stage.id);\n const missingDeps = stage.dependencies.filter(\n (dep) => !existingStageIds.includes(dep),\n );\n\n if (missingDeps.length > 0) {\n throw new Error(\n `Stage \"${stage.id}\" has missing dependencies: ${missingDeps.join(\", \")}. ` +\n `These stages must be added to the workflow before \"${stage.id}\". ` +\n `Current stages: ${\n existingStageIds.length === 0\n ? \"(none)\"\n : existingStageIds.join(\", \")\n }`,\n );\n }\n }\n\n this.currentExecutionGroup++;\n\n this.stages.push({\n stage: stage as Stage<any, any, any, any>,\n executionGroup: this.currentExecutionGroup,\n });\n\n // Return builder with new output type and accumulated context\n const builder = this as unknown as WorkflowBuilder<\n TInput,\n TStageOutput,\n TContext & { [x: string]: z.infer<TStageOutput> }\n >;\n (builder as any).currentOutputSchema = stage.outputSchema;\n\n return builder;\n }\n\n /**\n * Add a stage with strict input type checking\n *\n * Note: pipeStrict() and pipeLoose() have been removed as they were\n * just aliases for pipe(). Use pipe() for all stage chaining.\n */\n\n /**\n * Add multiple stages that execute in parallel\n *\n * All stages receive the same input (current output)\n * Their outputs are merged into an object by index AND accumulated in context by stage ID.\n *\n * Note: This accepts stages regardless of strict input type matching.\n * This is necessary because stages using passthrough() can accept objects\n * with additional fields. Runtime validation via Zod ensures type safety.\n *\n * Validates that all declared dependencies exist in the workflow.\n */\n parallel<\n TStages extends {\n id: string;\n outputSchema: z.ZodTypeAny;\n dependencies?: string[];\n }[],\n >(\n stages: [...TStages],\n ): WorkflowBuilder<\n TInput,\n z.ZodTypeAny,\n TContext & {\n [K in TStages[number][\"id\"]]: TStages[number] extends {\n outputSchema: infer O;\n }\n ? O extends z.ZodTypeAny\n ? z.infer<O>\n : never\n : never;\n }\n > {\n // Validate dependencies for all parallel stages\n const existingStageIds = this.stages.map((s) => s.stage.id);\n\n for (const stage of stages) {\n if (stage.dependencies) {\n const missingDeps = stage.dependencies.filter(\n (dep) => !existingStageIds.includes(dep),\n );\n\n if (missingDeps.length > 0) {\n throw new Error(\n `Stage \"${stage.id}\" (in parallel group) has missing dependencies: ${missingDeps.join(\n \", \",\n )}. ` +\n `These stages must be added to the workflow before this parallel group. ` +\n `Current stages: ${\n existingStageIds.length === 0\n ? \"(none)\"\n : existingStageIds.join(\", \")\n }`,\n );\n }\n }\n }\n\n this.currentExecutionGroup++;\n\n // Add all stages to same execution group\n for (const stage of stages) {\n this.stages.push({\n stage: stage as Stage<any, any, any, any>,\n executionGroup: this.currentExecutionGroup,\n });\n }\n\n // Create merged output schema\n const mergedSchema = z.object(\n stages.reduce(\n (acc, stage, index) => {\n acc[index] = stage.outputSchema;\n return acc;\n },\n {} as Record<number, z.ZodTypeAny>,\n ),\n ) as any;\n\n const builder = this as unknown as WorkflowBuilder<\n TInput,\n any,\n TContext & {\n [K in TStages[number][\"id\"]]: TStages[number] extends Stage<\n any,\n infer O,\n any\n >\n ? z.infer<O>\n : never;\n }\n >;\n builder.currentOutputSchema = mergedSchema;\n\n return builder as any;\n }\n\n /**\n * Build the final workflow\n */\n build(): Workflow<TInput, TCurrentOutput, TContext> {\n return new Workflow(\n this.id,\n this.name,\n this.description,\n this.inputSchema,\n this.currentOutputSchema,\n this.stages,\n );\n }\n\n /**\n * Get current stage count\n */\n getStageCount(): number {\n return this.stages.length;\n }\n\n /**\n * Get execution group count\n */\n getExecutionGroupCount(): number {\n return this.currentExecutionGroup;\n }\n}\n\n// ============================================================================\n// Type Inference Utilities (Supplementary to Code Generator)\n// ============================================================================\n\n/**\n * NOTE: For most use cases, prefer using the generated types from `__generated__.ts`\n * which are created by running `pnpm generate:workflow-types`.\n *\n * These inference utilities are useful for:\n * - Quick prototyping before running the generator\n * - Dynamic workflows not covered by the generator\n * - Type assertions in tests\n */\n\n/**\n * Extract the workflow context type from a Workflow instance\n *\n * The workflow context type is automatically accumulated as stages are piped.\n * Each stage's output is added to the context under its stage ID.\n *\n * @example\n * ```typescript\n * const workflow = new WorkflowBuilder(...)\n * .pipe(dataExtractionStage) // id: \"data-extraction\"\n * .pipe(guidelinesStage) // id: \"guidelines\"\n * .build();\n *\n * // Extract context type automatically\n * type MyWorkflowContext = InferWorkflowContext<typeof workflow>;\n * // = {\n * // \"data-extraction\": DataExtractionOutput;\n * // \"guidelines\": GuidelinesOutput;\n * // }\n *\n * // Use in stage definitions\n * export const myStage = defineStage<\n * \"none\",\n * typeof OutputSchema,\n * typeof ConfigSchema,\n * MyWorkflowContext\n * >({ ... });\n * ```\n */\nexport type InferWorkflowContext<W> = W extends Workflow<any, any, infer C>\n ? C\n : never;\n\n/**\n * Extract the input type from a Workflow instance\n *\n * @example\n * ```typescript\n * type Input = InferWorkflowInput<typeof myWorkflow>;\n * ```\n */\nexport type InferWorkflowInput<W> = W extends Workflow<infer I, any, any>\n ? z.infer<I>\n : never;\n\n/**\n * Extract the output type from a Workflow instance\n *\n * @example\n * ```typescript\n * type Output = InferWorkflowOutput<typeof myWorkflow>;\n * ```\n */\nexport type InferWorkflowOutput<W> = W extends Workflow<any, infer O, any>\n ? z.infer<O>\n : never;\n\n/**\n * Extract stage IDs as a union type from a Workflow instance\n *\n * Useful for creating type-safe stage ID references.\n *\n * @example\n * ```typescript\n * type StageId = InferWorkflowStageIds<typeof myWorkflow>;\n * // = \"data-extraction\" | \"guidelines\" | \"generator\"\n *\n * function getStageOutput(stageId: StageId) { ... }\n * ```\n */\nexport type InferWorkflowStageIds<W> = W extends Workflow<any, any, infer C>\n ? keyof C & string\n : never;\n\n/**\n * Get the output type for a specific stage ID from a Workflow\n *\n * @example\n * ```typescript\n * type DataOutput = InferStageOutputById<typeof workflow, \"data-extraction\">;\n * ```\n */\nexport type InferStageOutputById<W, K extends string> = W extends Workflow<\n any,\n any,\n infer C\n>\n ? K extends keyof C\n ? C[K]\n : never\n : never;\n","/**\n * Config Presets - Common configuration patterns for workflow stages\n *\n * These presets provide standardized schemas for common stage configurations,\n * reducing boilerplate and ensuring consistency across stages.\n *\n * @example\n * ```typescript\n * import { defineStage } from \"./stage-factory\";\n * import { withAIConfig, withStandardConfig } from \"./config-presets\";\n *\n * // Use AI-focused config preset\n * const myStage = defineStage({\n * id: \"my-stage\",\n * name: \"My Stage\",\n * schemas: {\n * input: z.object({ data: z.string() }),\n * output: z.object({ result: z.string() }),\n * config: withAIConfig(z.object({\n * customField: z.string(),\n * })),\n * },\n * async execute(ctx) {\n * // ctx.config.model, ctx.config.temperature available\n * // plus ctx.config.customField\n * },\n * });\n *\n * // Use standard config preset (includes AI + concurrency + feature flags)\n * const fullStage = defineStage({\n * id: \"full-stage\",\n * name: \"Full Stage\",\n * schemas: {\n * input: \"none\",\n * output: z.object({ result: z.string() }),\n * config: withStandardConfig(z.object({\n * specificOption: z.boolean().default(true),\n * })),\n * },\n * async execute(ctx) {\n * // All standard config + custom fields available\n * },\n * });\n * ```\n */\n\nimport { z } from \"zod\";\nimport { ModelKey } from \"../ai/model-helper\";\n\n// ============================================================================\n// Base Config Schemas\n// ============================================================================\n\n/**\n * AI/LLM configuration options\n */\nexport const AIConfigSchema = z.object({\n /** The model to use for AI operations */\n model: ModelKey.default(\"gemini-2.5-flash\"),\n /** Temperature for AI generations (0-2) */\n temperature: z.number().min(0).max(2).default(0.7),\n /** Maximum tokens to generate (undefined = model default) */\n maxTokens: z.number().positive().optional(),\n});\n\nexport type AIConfig = z.infer<typeof AIConfigSchema>;\n\n/**\n * Concurrency and rate limiting configuration\n */\nexport const ConcurrencyConfigSchema = z.object({\n /** Maximum concurrent operations (for parallel processing) */\n concurrency: z.number().positive().default(5),\n /** Delay between operations in milliseconds (rate limiting) */\n delayMs: z.number().nonnegative().default(0),\n /** Maximum retries on failure */\n maxRetries: z.number().nonnegative().default(3),\n});\n\nexport type ConcurrencyConfig = z.infer<typeof ConcurrencyConfigSchema>;\n\n/**\n * Feature flag configuration for conditional behavior\n */\nexport const FeatureFlagsConfigSchema = z.object({\n /** Feature flags for conditional stage behavior */\n featureFlags: z.record(z.string(), z.boolean()).default({}),\n});\n\nexport type FeatureFlagsConfig = z.infer<typeof FeatureFlagsConfigSchema>;\n\n/**\n * Logging and debugging configuration\n */\nexport const DebugConfigSchema = z.object({\n /** Enable verbose logging */\n verbose: z.boolean().default(false),\n /** Dry run mode (no side effects) */\n dryRun: z.boolean().default(false),\n});\n\nexport type DebugConfig = z.infer<typeof DebugConfigSchema>;\n\n// ============================================================================\n// Preset Combinators\n// ============================================================================\n\n/**\n * Add AI configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withAIConfig(z.object({\n * customField: z.string(),\n * }));\n * // Result has: model, temperature, maxTokens, customField\n * ```\n */\nexport function withAIConfig<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.merge(AIConfigSchema);\n}\n\n/**\n * Add concurrency configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withConcurrency(z.object({\n * items: z.array(z.string()),\n * }));\n * // Result has: concurrency, delayMs, maxRetries, items\n * ```\n */\nexport function withConcurrency<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema.merge(ConcurrencyConfigSchema);\n}\n\n/**\n * Add feature flags configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withFeatureFlags(z.object({\n * setting: z.boolean(),\n * }));\n * // Result has: featureFlags, setting\n * ```\n */\nexport function withFeatureFlags<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema.merge(FeatureFlagsConfigSchema);\n}\n\n/**\n * Add debug configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withDebug(z.object({\n * processType: z.string(),\n * }));\n * // Result has: verbose, dryRun, processType\n * ```\n */\nexport function withDebug<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.merge(DebugConfigSchema);\n}\n\n/**\n * Standard config preset combining AI + Concurrency + Feature Flags\n *\n * This is the recommended preset for most stages that need:\n * - AI/LLM operations\n * - Parallel processing\n * - Feature flagging\n *\n * @example\n * ```typescript\n * const myConfig = withStandardConfig(z.object({\n * customOption: z.boolean().default(true),\n * }));\n * // Result has all standard fields plus customOption\n * ```\n */\nexport function withStandardConfig<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema\n .merge(AIConfigSchema)\n .merge(ConcurrencyConfigSchema)\n .merge(FeatureFlagsConfigSchema);\n}\n\n/**\n * Full config preset with all available options including debug\n *\n * @example\n * ```typescript\n * const myConfig = withFullConfig(z.object({\n * specificField: z.number(),\n * }));\n * // Result has AI + Concurrency + FeatureFlags + Debug + specificField\n * ```\n */\nexport function withFullConfig<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema\n .merge(AIConfigSchema)\n .merge(ConcurrencyConfigSchema)\n .merge(FeatureFlagsConfigSchema)\n .merge(DebugConfigSchema);\n}\n\n// ============================================================================\n// Preset Type Helpers\n// ============================================================================\n\n/**\n * Extract the inferred type from a config created with presets\n */\nexport type InferConfig<T extends z.ZodTypeAny> = z.infer<T>;\n\n/**\n * Standard config type (AI + Concurrency + FeatureFlags)\n */\nexport type StandardConfig = AIConfig & ConcurrencyConfig & FeatureFlagsConfig;\n\n/**\n * Full config type (Standard + Debug)\n */\nexport type FullConfig = StandardConfig & DebugConfig;\n\n// ============================================================================\n// Utility Schemas\n// ============================================================================\n\n/**\n * Empty config schema - for stages that don't need configuration\n */\nexport const EmptyConfigSchema = z.object({});\n\n/**\n * Minimal AI config - just model and temperature\n */\nexport const MinimalAIConfigSchema = z.object({\n model: ModelKey.default(\"gemini-2.5-flash\"),\n temperature: z.number().min(0).max(2).default(0.7),\n});\n\nexport type MinimalAIConfig = z.infer<typeof MinimalAIConfigSchema>;\n"]}
1
+ {"version":3,"sources":["../src/core/stage-ids.ts","../src/core/workflow.ts","../src/core/config-presets.ts"],"names":["node","z"],"mappings":";;;;;;;;;;AAiEA,SAAS,eAAe,OAAA,EAAyB;AAC/C,EAAA,OAAO,OAAA,CAAQ,WAAA,EAAY,CAAE,OAAA,CAAQ,MAAM,GAAG,CAA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AAC","file":"index.js","sourcesContent":["/**\n * Stage ID Utilities - Type-safe stage ID management\n *\n * Provides utilities for creating type-safe stage ID constants and\n * branded types to prevent typos in stage ID references.\n *\n * ## Usage Patterns\n *\n * ### Pattern 1: Create Stage IDs from a Workflow (Recommended)\n *\n * ```typescript\n * import { createStageIds } from \"~/lib/workflow-v2/core/stage-ids\";\n *\n * export const STAGE_IDS = createStageIds(certificateWorkflow);\n * // = {\n * // DATA_EXTRACTION: \"data-extraction\",\n * // GUIDELINES: \"guidelines\",\n * // GENERATOR: \"generator\",\n * // } as const\n *\n * // Use in stage definitions\n * dependencies: [STAGE_IDS.DATA_EXTRACTION], // Autocomplete!\n * ```\n *\n * ### Pattern 2: Define Stage IDs First (For Complex Workflows)\n *\n * ```typescript\n * export const CERTIFICATE_STAGES = defineStageIds([\n * \"data-extraction\",\n * \"guidelines\",\n * \"legal-guidance\",\n * \"unified-smart-retrieval\",\n * \"analysis-synthesis\",\n * \"generator\",\n * ] as const);\n *\n * // Type: { DATA_EXTRACTION: \"data-extraction\", ... }\n * // With validation that stages match workflow definition\n * ```\n *\n * ### Pattern 3: Use with InferWorkflowStageIds\n *\n * ```typescript\n * import type { InferWorkflowStageIds } from \"~/lib/workflow-v2/core/workflow\";\n *\n * type CertificateStageId = InferWorkflowStageIds<typeof certificateWorkflow>;\n * // = \"data-extraction\" | \"guidelines\" | \"generator\" | ...\n *\n * function requireStage(stageId: CertificateStageId) { ... }\n * ```\n */\n\nimport type { Workflow } from \"./workflow\";\n\n// ============================================================================\n// Stage ID Helpers\n// ============================================================================\n\n/**\n * Convert a kebab-case stage ID to SCREAMING_SNAKE_CASE\n *\n * @example\n * toConstantCase(\"data-extraction\") // \"DATA_EXTRACTION\"\n * toConstantCase(\"unified-smart-retrieval\") // \"UNIFIED_SMART_RETRIEVAL\"\n */\nfunction toConstantCase(stageId: string): string {\n return stageId.toUpperCase().replace(/-/g, \"_\");\n}\n\n/**\n * Create a type-safe stage ID constants object from a workflow\n *\n * Extracts all stage IDs from a workflow and creates a frozen object\n * with SCREAMING_SNAKE_CASE keys for autocomplete and type safety.\n *\n * @example\n * ```typescript\n * import { certificateWorkflow } from \"./certificate-workflow\";\n *\n * export const STAGE_IDS = createStageIds(certificateWorkflow);\n * // = {\n * // DATA_EXTRACTION: \"data-extraction\",\n * // GUIDELINES: \"guidelines\",\n * // LEGAL_GUIDANCE: \"legal-guidance\",\n * // GENERATOR: \"generator\",\n * // } as const\n *\n * // Use in code with autocomplete:\n * const data = ctx.require(STAGE_IDS.DATA_EXTRACTION);\n * ```\n */\nexport function createStageIds<W extends Workflow<any, any, any>>(\n workflow: W,\n): StageIdConstants<W> {\n const stageIds = workflow.getStageIds();\n const result: Record<string, string> = {};\n\n for (const id of stageIds) {\n const key = toConstantCase(id);\n result[key] = id;\n }\n\n return Object.freeze(result) as StageIdConstants<W>;\n}\n\n/**\n * Define stage IDs from a tuple of string literals\n *\n * Use this when you want to define stage IDs before building the workflow,\n * or when you need to share stage IDs across multiple files.\n *\n * @example\n * ```typescript\n * // Define stage IDs first\n * export const CERTIFICATE_STAGES = defineStageIds([\n * \"data-extraction\",\n * \"guidelines\",\n * \"legal-guidance\",\n * \"generator\",\n * ] as const);\n *\n * // Use in stage definitions\n * dependencies: [CERTIFICATE_STAGES.DATA_EXTRACTION],\n *\n * // Type-safe access\n * type StageId = typeof CERTIFICATE_STAGES[keyof typeof CERTIFICATE_STAGES];\n * // = \"data-extraction\" | \"guidelines\" | ...\n * ```\n */\nexport function defineStageIds<const T extends readonly string[]>(\n stageIds: T,\n): DefineStageIdsResult<T> {\n const result: Record<string, string> = {};\n\n for (const id of stageIds) {\n const key = toConstantCase(id);\n result[key] = id;\n }\n\n return Object.freeze(result) as DefineStageIdsResult<T>;\n}\n\n/**\n * Validate that a stage ID exists in a workflow\n *\n * Use this for runtime validation when the stage ID comes from user input.\n *\n * @example\n * ```typescript\n * const stageId = request.params.stageId;\n *\n * if (!isValidStageId(certificateWorkflow, stageId)) {\n * throw new Error(`Invalid stage ID: ${stageId}`);\n * }\n * ```\n */\nexport function isValidStageId<W extends Workflow<any, any, any>>(\n workflow: W,\n stageId: string,\n): stageId is WorkflowStageId<W> {\n return workflow.hasStage(stageId);\n}\n\n/**\n * Assert that a stage ID exists in a workflow\n *\n * Throws an error with helpful message if the stage ID is invalid.\n *\n * @example\n * ```typescript\n * assertValidStageId(certificateWorkflow, stageId);\n * // Now TypeScript knows stageId is a valid stage ID\n * ```\n */\nexport function assertValidStageId<W extends Workflow<any, any, any>>(\n workflow: W,\n stageId: string,\n): asserts stageId is WorkflowStageId<W> {\n if (!workflow.hasStage(stageId)) {\n const validIds = workflow.getStageIds();\n throw new Error(\n `Invalid stage ID: \"${stageId}\". ` +\n `Valid stage IDs for workflow \"${workflow.id}\": ${validIds.join(\", \")}`,\n );\n }\n}\n\n// ============================================================================\n// Type Utilities\n// ============================================================================\n\n/**\n * Extract stage IDs as a string union from a Workflow type\n *\n * @example\n * ```typescript\n * type StageId = WorkflowStageId<typeof certificateWorkflow>;\n * // = \"data-extraction\" | \"guidelines\" | \"generator\" | ...\n * ```\n */\nexport type WorkflowStageId<W extends Workflow<any, any, any>> =\n W extends Workflow<any, any, infer C> ? keyof C & string : never;\n\n/**\n * Result type for createStageIds function\n *\n * Maps each stage ID to a SCREAMING_SNAKE_CASE key.\n */\ntype StageIdConstants<W extends Workflow<any, any, any>> = {\n readonly [K in WorkflowStageId<W> as Uppercase<\n K extends string ? ReplaceHyphens<K> : never\n >]: K;\n};\n\n/**\n * Result type for defineStageIds function\n */\ntype DefineStageIdsResult<T extends readonly string[]> = {\n readonly [K in T[number] as Uppercase<\n K extends string ? ReplaceHyphens<K> : never\n >]: K;\n};\n\n/**\n * Helper type to replace hyphens with underscores\n */\ntype ReplaceHyphens<S extends string> = S extends `${infer Head}-${infer Tail}`\n ? `${Head}_${ReplaceHyphens<Tail>}`\n : S;\n\n// ============================================================================\n// Stage ID Validation Types\n// ============================================================================\n\n/**\n * Validate that stage IDs match a workflow's expected stages\n *\n * Use this to ensure stage ID constants are in sync with the workflow.\n *\n * @example\n * ```typescript\n * // This will cause a compile error if stage IDs don't match\n * const STAGE_IDS: ValidateStageIds<\n * typeof certificateWorkflow,\n * typeof CERTIFICATE_STAGES\n * > = CERTIFICATE_STAGES;\n * ```\n */\nexport type ValidateStageIds<\n W extends Workflow<any, any, any>,\n T extends Record<string, string>,\n> = {\n [K in keyof T]: T[K] extends WorkflowStageId<W>\n ? T[K]\n : `Error: \"${T[K] & string}\" is not a valid stage ID in workflow`;\n};\n","/**\n * Workflow Builder - Fluent API for composing type-safe workflows\n *\n * Workflows are composed of stages that are executed sequentially or in parallel.\n * The builder ensures type safety: output of one stage matches input of next stage.\n *\n * ## Type System Features\n *\n * ### Automatic Context Inference\n * The workflow context type is automatically accumulated as you pipe stages.\n * Use `InferWorkflowContext<typeof workflow>` to extract the context type.\n *\n * ```typescript\n * const workflow = new WorkflowBuilder(...)\n * .pipe(stage1)\n * .pipe(stage2)\n * .build();\n *\n * // Auto-generated type\n * type MyContext = InferWorkflowContext<typeof workflow>;\n * // = { \"stage-1\": Stage1Output, \"stage-2\": Stage2Output }\n * ```\n *\n * ### Stage ID Constants\n * Use `workflow.stageIds` for type-safe stage ID references.\n */\n\nimport { z } from \"zod\";\nimport type { Stage } from \"./stage\";\n\n// ============================================================================\n// Stage Node - Represents a stage in the execution plan\n// ============================================================================\n\nexport interface StageNode {\n stage: Stage<any, any, any>;\n executionGroup: number; // For parallel execution grouping\n}\n\n// ============================================================================\n// Workflow - Complete workflow definition\n// ============================================================================\n\nexport class Workflow<\n TInput extends z.ZodTypeAny,\n TOutput extends z.ZodTypeAny,\n TContext extends Record<string, unknown> = {},\n> {\n constructor(\n public readonly id: string,\n public readonly name: string,\n public readonly description: string,\n public readonly inputSchema: TInput,\n public readonly outputSchema: TOutput,\n private readonly stages: StageNode[],\n public readonly contextType?: TContext, // Type-only, for inference\n ) {}\n\n /**\n * Get execution plan as groups of stages\n * Stages in the same group can be executed in parallel\n */\n getExecutionPlan(): StageNode[][] {\n const groups = new Map<number, StageNode[]>();\n\n for (const node of this.stages) {\n const group = groups.get(node.executionGroup) || [];\n group.push(node);\n groups.set(node.executionGroup, group);\n }\n\n // Return groups in order\n const sortedGroups = Array.from(groups.keys()).sort((a, b) => a - b);\n return sortedGroups.map((groupNum) => {\n const group = groups.get(groupNum);\n if (!group) throw new Error(`Group ${groupNum} not found`);\n return group;\n });\n }\n\n /**\n * Get a specific stage by ID\n */\n getStage(stageId: string): Stage<any, any, any> | undefined {\n const node = this.stages.find((n) => n.stage.id === stageId);\n return node?.stage;\n }\n\n /**\n * Get all stages in order\n */\n getAllStages(): StageNode[] {\n return [...this.stages];\n }\n\n /**\n * Get a visual representation of the workflow execution order\n */\n getExecutionOrder(): string {\n const executionPlan = this.getExecutionPlan();\n const lines: string[] = [];\n\n lines.push(`Workflow: ${this.name} (${this.id})`);\n lines.push(`Total stages: ${this.stages.length}`);\n lines.push(`Execution groups: ${executionPlan.length}`);\n lines.push(\"\");\n lines.push(\"Execution Order:\");\n lines.push(\"================\");\n\n for (let i = 0; i < executionPlan.length; i++) {\n const group = executionPlan[i];\n const groupNumber = i + 1;\n\n if (group.length === 1) {\n // Sequential stage\n const stage = group[0].stage;\n lines.push(`${groupNumber}. ${stage.name} (${stage.id})`);\n if (stage.description) {\n lines.push(` ${stage.description}`);\n }\n } else {\n // Parallel stages\n lines.push(`${groupNumber}. [PARALLEL]`);\n for (const node of group) {\n const stage = node.stage;\n lines.push(` - ${stage.name} (${stage.id})`);\n if (stage.description) {\n lines.push(` ${stage.description}`);\n }\n }\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Get all stage IDs in execution order\n *\n * @returns Array of stage IDs\n *\n * @example\n * ```typescript\n * const ids = workflow.getStageIds();\n * // [\"data-extraction\", \"guidelines\", \"generator\"]\n * ```\n */\n getStageIds(): string[] {\n return this.stages.map((node) => node.stage.id);\n }\n\n /**\n * Check if a stage ID exists in this workflow\n *\n * @param stageId - The stage ID to check\n * @returns true if the stage exists\n */\n hasStage(stageId: string): boolean {\n return this.stages.some((node) => node.stage.id === stageId);\n }\n\n /**\n * Validate workflow configuration before execution\n * Checks that all stage configs match their schemas\n *\n * @param config - Configuration object with keys matching stage IDs\n * @returns Validation result with any errors\n */\n validateConfig(config: Record<string, unknown>): {\n valid: boolean;\n errors: Array<{ stageId: string; error: string }>;\n } {\n const errors: Array<{ stageId: string; error: string }> = [];\n\n for (const node of this.stages) {\n const stage = node.stage;\n const stageConfig = config[stage.id] || {};\n\n try {\n stage.configSchema.parse(stageConfig);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errorMessages = error.issues\n .map((e: z.ZodIssue) => `${e.path.join(\".\")}: ${e.message}`)\n .join(\"; \");\n errors.push({\n stageId: stage.id,\n error: `Config validation failed: ${errorMessages}`,\n });\n } else {\n errors.push({\n stageId: stage.id,\n error: String(error),\n });\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n }\n\n /**\n * Estimate total cost for the workflow\n */\n estimateCost(\n input: z.infer<TInput>,\n config: Record<string, unknown>,\n ): number {\n let totalCost = 0;\n const currentInput = input;\n\n for (const node of this.stages) {\n if (node.stage.estimateCost) {\n const stageConfig = config[node.stage.id] || {};\n totalCost += node.stage.estimateCost(currentInput, stageConfig);\n }\n // Note: We can't accurately propagate input for estimation without execution\n // This is a rough estimate only\n }\n\n return totalCost;\n }\n\n /**\n * Get configuration schemas for all stages in this workflow\n * Returns a map of stageId → { schema, defaults, name, description }\n */\n getStageConfigs(): Record<\n string,\n {\n schema: z.ZodTypeAny;\n defaults: Record<string, unknown>;\n name: string;\n description?: string;\n }\n > {\n const configs: Record<\n string,\n {\n schema: z.ZodTypeAny;\n defaults: Record<string, unknown>;\n name: string;\n description?: string;\n }\n > = {};\n\n for (const node of this.stages) {\n const stage = node.stage;\n\n // Extract defaults from schema\n const defaults: Record<string, unknown> = {};\n\n if (stage.configSchema instanceof z.ZodObject) {\n const shape = stage.configSchema.shape as Record<string, z.ZodTypeAny>;\n for (const [key, fieldSchema] of Object.entries(shape)) {\n let unwrapped = fieldSchema;\n\n // Unwrap ZodOptional if present\n if (unwrapped instanceof z.ZodOptional) {\n unwrapped = (unwrapped._def as any).innerType;\n }\n\n // Check for ZodDefault\n if (unwrapped instanceof z.ZodDefault) {\n const defaultValueFn = (unwrapped._def as any).defaultValue;\n defaults[key] =\n typeof defaultValueFn === \"function\"\n ? defaultValueFn()\n : defaultValueFn;\n }\n }\n }\n\n configs[stage.id] = {\n schema: stage.configSchema,\n defaults,\n name: stage.name,\n description: stage.description,\n };\n }\n\n return configs;\n }\n\n /**\n * Generate default configuration object for all stages\n * Automatically discovers all stage configs - add/remove stages and this updates automatically\n */\n getDefaultConfig(): Record<string, Record<string, unknown>> {\n const stageConfigs = this.getStageConfigs();\n const config: Record<string, Record<string, unknown>> = {};\n\n for (const [stageId, meta] of Object.entries(stageConfigs)) {\n config[stageId] = meta.defaults;\n }\n\n return config;\n }\n /**\n * Get all stages in a specific execution group\n */\n getStagesInExecutionGroup(groupIndex: number): Stage<any, any, any>[] {\n return this.stages\n .filter((node) => node.executionGroup === groupIndex)\n .map((node) => node.stage);\n }\n\n /**\n * Get the sequential index of a stage (0-based)\n */\n getStageIndex(stageId: string): number {\n return this.stages.findIndex((node) => node.stage.id === stageId);\n }\n\n /**\n * Get the execution group index for a stage\n */\n getExecutionGroupIndex(stageId: string): number {\n const node = this.stages.find((node) => node.stage.id === stageId);\n if (!node) throw new Error(`Stage ${stageId} not found in workflow`);\n return node.executionGroup;\n }\n\n /**\n * Get the ID of the stage immediately preceding the given stage\n */\n getPreviousStageId(stageId: string): string | undefined {\n const index = this.getStageIndex(stageId);\n if (index <= 0) return undefined;\n return this.stages[index - 1].stage.id;\n }\n}\n\n// ============================================================================\n// Workflow Builder - Fluent API with Context Accumulation\n// ============================================================================\n\nexport class WorkflowBuilder<\n TInput extends z.ZodTypeAny,\n TCurrentOutput extends z.ZodTypeAny,\n TContext extends Record<string, unknown> = {},\n> {\n private stages: StageNode[] = [];\n private currentExecutionGroup = 0;\n\n constructor(\n private id: string,\n private name: string,\n private description: string,\n private inputSchema: TInput,\n private currentOutputSchema: TCurrentOutput,\n ) {}\n\n /**\n * Add a stage to the workflow (sequential execution)\n *\n * Automatically accumulates the stage's output in the context under its stage ID.\n * This provides type-safe access to all previous stage outputs.\n *\n * Note: This accepts any stage regardless of strict input type matching.\n * This is necessary because stages using passthrough() can accept objects\n * with additional fields beyond what's declared in their input schema.\n * Runtime validation via Zod ensures type safety at execution time.\n *\n * Validates that all declared dependencies exist in the workflow.\n */\n pipe<\n TStageInput extends z.ZodTypeAny,\n TStageOutput extends z.ZodTypeAny,\n TStageConfig extends z.ZodTypeAny,\n TStageContext extends Record<string, unknown>,\n TStageId extends string = string,\n >(\n stage: Stage<\n TStageInput,\n TStageOutput,\n TStageConfig,\n TStageContext,\n TStageId\n >,\n ): WorkflowBuilder<\n TInput,\n TStageOutput,\n TContext & { [K in TStageId]: z.infer<TStageOutput> }\n > {\n // Validate stage dependencies\n if (stage.dependencies) {\n const existingStageIds = this.stages.map((s) => s.stage.id);\n const missingDeps = stage.dependencies.filter(\n (dep) => !existingStageIds.includes(dep),\n );\n\n if (missingDeps.length > 0) {\n throw new Error(\n `Stage \"${stage.id}\" has missing dependencies: ${missingDeps.join(\", \")}. ` +\n `These stages must be added to the workflow before \"${stage.id}\". ` +\n `Current stages: ${\n existingStageIds.length === 0\n ? \"(none)\"\n : existingStageIds.join(\", \")\n }`,\n );\n }\n }\n\n this.currentExecutionGroup++;\n\n this.stages.push({\n stage: stage as Stage<any, any, any, any>,\n executionGroup: this.currentExecutionGroup,\n });\n\n // Return builder with new output type and accumulated context\n const builder = this as unknown as WorkflowBuilder<\n TInput,\n TStageOutput,\n TContext & { [K in TStageId]: z.infer<TStageOutput> }\n >;\n (builder as any).currentOutputSchema = stage.outputSchema;\n\n return builder;\n }\n\n /**\n * Add a stage with strict input type checking\n *\n * Note: pipeStrict() and pipeLoose() have been removed as they were\n * just aliases for pipe(). Use pipe() for all stage chaining.\n */\n\n /**\n * Add multiple stages that execute in parallel\n *\n * All stages receive the same input (current output)\n * Their outputs are merged into an object by stage ID and accumulated in context.\n *\n * Note: This accepts stages regardless of strict input type matching.\n * This is necessary because stages using passthrough() can accept objects\n * with additional fields. Runtime validation via Zod ensures type safety.\n *\n * Validates that all declared dependencies exist in the workflow.\n */\n parallel<\n TStages extends {\n id: string;\n outputSchema: z.ZodTypeAny;\n dependencies?: string[];\n }[],\n >(\n stages: [...TStages],\n ): WorkflowBuilder<\n TInput,\n z.ZodTypeAny,\n TContext & {\n [K in TStages[number][\"id\"]]: TStages[number] extends {\n outputSchema: infer O;\n }\n ? O extends z.ZodTypeAny\n ? z.infer<O>\n : never\n : never;\n }\n > {\n // Validate dependencies for all parallel stages\n const existingStageIds = this.stages.map((s) => s.stage.id);\n\n for (const stage of stages) {\n if (stage.dependencies) {\n const missingDeps = stage.dependencies.filter(\n (dep) => !existingStageIds.includes(dep),\n );\n\n if (missingDeps.length > 0) {\n throw new Error(\n `Stage \"${stage.id}\" (in parallel group) has missing dependencies: ${missingDeps.join(\n \", \",\n )}. ` +\n `These stages must be added to the workflow before this parallel group. ` +\n `Current stages: ${\n existingStageIds.length === 0\n ? \"(none)\"\n : existingStageIds.join(\", \")\n }`,\n );\n }\n }\n }\n\n this.currentExecutionGroup++;\n\n // Add all stages to same execution group\n for (const stage of stages) {\n this.stages.push({\n stage: stage as Stage<any, any, any, any>,\n executionGroup: this.currentExecutionGroup,\n });\n }\n\n // Create merged output schema keyed by stage ID\n const mergedSchema = z.object(\n stages.reduce(\n (acc, stage) => {\n acc[stage.id] = stage.outputSchema;\n return acc;\n },\n {} as Record<string, z.ZodTypeAny>,\n ),\n ) as any;\n\n const builder = this as unknown as WorkflowBuilder<\n TInput,\n any,\n TContext & {\n [K in TStages[number][\"id\"]]: TStages[number] extends Stage<\n any,\n infer O,\n any\n >\n ? z.infer<O>\n : never;\n }\n >;\n builder.currentOutputSchema = mergedSchema;\n\n return builder as any;\n }\n\n /**\n * Build the final workflow\n */\n build(): Workflow<TInput, TCurrentOutput, TContext> {\n return new Workflow(\n this.id,\n this.name,\n this.description,\n this.inputSchema,\n this.currentOutputSchema,\n this.stages,\n );\n }\n\n /**\n * Get current stage count\n */\n getStageCount(): number {\n return this.stages.length;\n }\n\n /**\n * Get execution group count\n */\n getExecutionGroupCount(): number {\n return this.currentExecutionGroup;\n }\n}\n\n// ============================================================================\n// Type Inference Utilities (Supplementary to Code Generator)\n// ============================================================================\n\n/**\n * NOTE: For most use cases, prefer using the generated types from `__generated__.ts`\n * which are created by running `pnpm generate:workflow-types`.\n *\n * These inference utilities are useful for:\n * - Quick prototyping before running the generator\n * - Dynamic workflows not covered by the generator\n * - Type assertions in tests\n */\n\n/**\n * Extract the workflow context type from a Workflow instance\n *\n * The workflow context type is automatically accumulated as stages are piped.\n * Each stage's output is added to the context under its stage ID.\n *\n * @example\n * ```typescript\n * const workflow = new WorkflowBuilder(...)\n * .pipe(dataExtractionStage) // id: \"data-extraction\"\n * .pipe(guidelinesStage) // id: \"guidelines\"\n * .build();\n *\n * // Extract context type automatically\n * type MyWorkflowContext = InferWorkflowContext<typeof workflow>;\n * // = {\n * // \"data-extraction\": DataExtractionOutput;\n * // \"guidelines\": GuidelinesOutput;\n * // }\n *\n * // Use in stage definitions\n * export const myStage = defineStage<\n * \"none\",\n * typeof OutputSchema,\n * typeof ConfigSchema,\n * MyWorkflowContext\n * >({ ... });\n * ```\n */\nexport type InferWorkflowContext<W> = W extends Workflow<any, any, infer C>\n ? C\n : never;\n\n/**\n * Extract the input type from a Workflow instance\n *\n * @example\n * ```typescript\n * type Input = InferWorkflowInput<typeof myWorkflow>;\n * ```\n */\nexport type InferWorkflowInput<W> = W extends Workflow<infer I, any, any>\n ? z.infer<I>\n : never;\n\n/**\n * Extract the output type from a Workflow instance\n *\n * @example\n * ```typescript\n * type Output = InferWorkflowOutput<typeof myWorkflow>;\n * ```\n */\nexport type InferWorkflowOutput<W> = W extends Workflow<any, infer O, any>\n ? z.infer<O>\n : never;\n\n/**\n * Extract stage IDs as a union type from a Workflow instance\n *\n * Useful for creating type-safe stage ID references.\n *\n * @example\n * ```typescript\n * type StageId = InferWorkflowStageIds<typeof myWorkflow>;\n * // = \"data-extraction\" | \"guidelines\" | \"generator\"\n *\n * function getStageOutput(stageId: StageId) { ... }\n * ```\n */\nexport type InferWorkflowStageIds<W> = W extends Workflow<any, any, infer C>\n ? keyof C & string\n : never;\n\n/**\n * Get the output type for a specific stage ID from a Workflow\n *\n * @example\n * ```typescript\n * type DataOutput = InferStageOutputById<typeof workflow, \"data-extraction\">;\n * ```\n */\nexport type InferStageOutputById<W, K extends string> = W extends Workflow<\n any,\n any,\n infer C\n>\n ? K extends keyof C\n ? C[K]\n : never\n : never;\n","/**\n * Config Presets - Common configuration patterns for workflow stages\n *\n * These presets provide standardized schemas for common stage configurations,\n * reducing boilerplate and ensuring consistency across stages.\n *\n * @example\n * ```typescript\n * import { defineStage } from \"./stage-factory\";\n * import { withAIConfig, withStandardConfig } from \"./config-presets\";\n *\n * // Use AI-focused config preset\n * const myStage = defineStage({\n * id: \"my-stage\",\n * name: \"My Stage\",\n * schemas: {\n * input: z.object({ data: z.string() }),\n * output: z.object({ result: z.string() }),\n * config: withAIConfig(z.object({\n * customField: z.string(),\n * })),\n * },\n * async execute(ctx) {\n * // ctx.config.model, ctx.config.temperature available\n * // plus ctx.config.customField\n * },\n * });\n *\n * // Use standard config preset (includes AI + concurrency + feature flags)\n * const fullStage = defineStage({\n * id: \"full-stage\",\n * name: \"Full Stage\",\n * schemas: {\n * input: \"none\",\n * output: z.object({ result: z.string() }),\n * config: withStandardConfig(z.object({\n * specificOption: z.boolean().default(true),\n * })),\n * },\n * async execute(ctx) {\n * // All standard config + custom fields available\n * },\n * });\n * ```\n */\n\nimport { z } from \"zod\";\nimport { ModelKey } from \"../ai/model-helper\";\n\n// ============================================================================\n// Base Config Schemas\n// ============================================================================\n\n/**\n * AI/LLM configuration options\n */\nexport const AIConfigSchema = z.object({\n /** The model to use for AI operations */\n model: ModelKey.default(\"gemini-2.5-flash\"),\n /** Temperature for AI generations (0-2) */\n temperature: z.number().min(0).max(2).default(0.7),\n /** Maximum tokens to generate (undefined = model default) */\n maxTokens: z.number().positive().optional(),\n});\n\nexport type AIConfig = z.infer<typeof AIConfigSchema>;\n\n/**\n * Concurrency and rate limiting configuration\n */\nexport const ConcurrencyConfigSchema = z.object({\n /** Maximum concurrent operations (for parallel processing) */\n concurrency: z.number().positive().default(5),\n /** Delay between operations in milliseconds (rate limiting) */\n delayMs: z.number().nonnegative().default(0),\n /** Maximum retries on failure */\n maxRetries: z.number().nonnegative().default(3),\n});\n\nexport type ConcurrencyConfig = z.infer<typeof ConcurrencyConfigSchema>;\n\n/**\n * Feature flag configuration for conditional behavior\n */\nexport const FeatureFlagsConfigSchema = z.object({\n /** Feature flags for conditional stage behavior */\n featureFlags: z.record(z.string(), z.boolean()).default({}),\n});\n\nexport type FeatureFlagsConfig = z.infer<typeof FeatureFlagsConfigSchema>;\n\n/**\n * Logging and debugging configuration\n */\nexport const DebugConfigSchema = z.object({\n /** Enable verbose logging */\n verbose: z.boolean().default(false),\n /** Dry run mode (no side effects) */\n dryRun: z.boolean().default(false),\n});\n\nexport type DebugConfig = z.infer<typeof DebugConfigSchema>;\n\n// ============================================================================\n// Preset Combinators\n// ============================================================================\n\n/**\n * Add AI configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withAIConfig(z.object({\n * customField: z.string(),\n * }));\n * // Result has: model, temperature, maxTokens, customField\n * ```\n */\nexport function withAIConfig<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.merge(AIConfigSchema);\n}\n\n/**\n * Add concurrency configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withConcurrency(z.object({\n * items: z.array(z.string()),\n * }));\n * // Result has: concurrency, delayMs, maxRetries, items\n * ```\n */\nexport function withConcurrency<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema.merge(ConcurrencyConfigSchema);\n}\n\n/**\n * Add feature flags configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withFeatureFlags(z.object({\n * setting: z.boolean(),\n * }));\n * // Result has: featureFlags, setting\n * ```\n */\nexport function withFeatureFlags<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema.merge(FeatureFlagsConfigSchema);\n}\n\n/**\n * Add debug configuration to any schema\n *\n * @example\n * ```typescript\n * const myConfig = withDebug(z.object({\n * processType: z.string(),\n * }));\n * // Result has: verbose, dryRun, processType\n * ```\n */\nexport function withDebug<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.merge(DebugConfigSchema);\n}\n\n/**\n * Standard config preset combining AI + Concurrency + Feature Flags\n *\n * This is the recommended preset for most stages that need:\n * - AI/LLM operations\n * - Parallel processing\n * - Feature flagging\n *\n * @example\n * ```typescript\n * const myConfig = withStandardConfig(z.object({\n * customOption: z.boolean().default(true),\n * }));\n * // Result has all standard fields plus customOption\n * ```\n */\nexport function withStandardConfig<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema\n .merge(AIConfigSchema)\n .merge(ConcurrencyConfigSchema)\n .merge(FeatureFlagsConfigSchema);\n}\n\n/**\n * Full config preset with all available options including debug\n *\n * @example\n * ```typescript\n * const myConfig = withFullConfig(z.object({\n * specificField: z.number(),\n * }));\n * // Result has AI + Concurrency + FeatureFlags + Debug + specificField\n * ```\n */\nexport function withFullConfig<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n return schema\n .merge(AIConfigSchema)\n .merge(ConcurrencyConfigSchema)\n .merge(FeatureFlagsConfigSchema)\n .merge(DebugConfigSchema);\n}\n\n// ============================================================================\n// Preset Type Helpers\n// ============================================================================\n\n/**\n * Extract the inferred type from a config created with presets\n */\nexport type InferConfig<T extends z.ZodTypeAny> = z.infer<T>;\n\n/**\n * Standard config type (AI + Concurrency + FeatureFlags)\n */\nexport type StandardConfig = AIConfig & ConcurrencyConfig & FeatureFlagsConfig;\n\n/**\n * Full config type (Standard + Debug)\n */\nexport type FullConfig = StandardConfig & DebugConfig;\n\n// ============================================================================\n// Utility Schemas\n// ============================================================================\n\n/**\n * Empty config schema - for stages that don't need configuration\n */\nexport const EmptyConfigSchema = z.object({});\n\n/**\n * Minimal AI config - just model and temperature\n */\nexport const MinimalAIConfigSchema = z.object({\n model: ModelKey.default(\"gemini-2.5-flash\"),\n temperature: z.number().min(0).max(2).default(0.7),\n});\n\nexport type MinimalAIConfig = z.infer<typeof MinimalAIConfigSchema>;\n"]}
@@ -55,6 +55,7 @@ interface WorkflowRunRecord {
55
55
  totalCost: number;
56
56
  totalTokens: number;
57
57
  priority: number;
58
+ metadata: unknown | null;
58
59
  }
59
60
  interface WorkflowStageRecord {
60
61
  id: string;
@@ -169,14 +170,14 @@ interface CreateRunInput {
169
170
  input: unknown;
170
171
  config?: unknown;
171
172
  priority?: number;
172
- /** Optional metadata for domain-specific fields */
173
+ /** Optional metadata stored as JSON on the run record. NOT spread into Prisma fields. */
173
174
  metadata?: Record<string, unknown>;
174
175
  }
175
176
  interface UpdateRunInput {
176
177
  status?: WorkflowStatus;
177
178
  startedAt?: Date;
178
179
  completedAt?: Date | null;
179
- duration?: number;
180
+ duration?: number | null;
180
181
  output?: unknown;
181
182
  totalCost?: number;
182
183
  totalTokens?: number;
@@ -407,6 +408,11 @@ interface JobQueue {
407
408
  * Release stale locks (for crashed workers)
408
409
  */
409
410
  releaseStaleJobs(staleThresholdMs?: number): Promise<number>;
411
+ /**
412
+ * Cancel all pending/suspended jobs for a workflow run.
413
+ * Returns count of cancelled jobs.
414
+ */
415
+ cancelByRun(workflowRunId: string): Promise<number>;
410
416
  }
411
417
 
412
- export { type AICallLogger as A, type CreateOutboxEventInput as C, type DequeueResult as D, type EnqueueJobInput as E, type IdempotencyRecord as I, type JobQueue as J, type LogLevel as L, type OutboxRecord as O, type Status as S, type UpdateRunInput as U, type WorkflowRunRecord as W, type CreateRunInput as a, type CreateStageInput as b, type WorkflowStageRecord as c, type UpsertStageInput as d, type UpdateStageInput as e, type CreateLogInput as f, type CreateAICallInput as g, type AIHelperStats as h, type AICallRecord as i, type JobRecord as j, type JobStatus as k, type WorkflowPersistence as l, type WorkflowStatus as m, type WorkflowStageStatus as n, type SaveArtifactInput as o, type WorkflowArtifactRecord as p, type WorkflowLogRecord as q, type ArtifactType as r, StaleVersionError as s };
418
+ export { type AICallLogger as A, type CreateRunInput as C, type DequeueResult as D, type EnqueueJobInput as E, type IdempotencyRecord as I, type JobQueue as J, type LogLevel as L, type OutboxRecord as O, type Status as S, type UpdateRunInput as U, type WorkflowRunRecord as W, type CreateStageInput as a, type WorkflowStageRecord as b, type UpsertStageInput as c, type UpdateStageInput as d, type CreateLogInput as e, type CreateOutboxEventInput as f, type CreateAICallInput as g, type AIHelperStats as h, type AICallRecord as i, type JobRecord as j, type JobStatus as k, type WorkflowPersistence as l, type WorkflowStatus as m, type WorkflowStageStatus as n, type SaveArtifactInput as o, type WorkflowArtifactRecord as p, type WorkflowLogRecord as q, type ArtifactType as r, StaleVersionError as s };
@@ -1,9 +1,10 @@
1
- import { K as KernelDeps } from '../plugins-C94AT8Wr.js';
2
- export { C as CommandResult, I as IdempotencyInProgressError, J as JobExecuteCommand, a as JobExecuteResult, b as Kernel, c as KernelCommand, d as KernelCommandType, e as KernelConfig, L as LeaseReapStaleCommand, f as LeaseReapStaleResult, O as OutboxFlushCommand, g as OutboxFlushResult, P as PluginDefinition, h as PluginReplayDLQCommand, i as PluginReplayDLQResult, j as PluginRunner, k as PluginRunnerConfig, R as RunCancelCommand, l as RunCancelResult, m as RunClaimPendingCommand, n as RunClaimPendingResult, o as RunCreateCommand, p as RunCreateResult, q as RunRerunFromCommand, r as RunRerunFromResult, s as RunTransitionCommand, t as RunTransitionResult, S as StagePollSuspendedCommand, u as StagePollSuspendedResult, W as WorkflowRegistry, v as createKernel, w as createPluginRunner, x as definePlugin } from '../plugins-C94AT8Wr.js';
3
- export { B as BlobStore, C as Clock, E as EventSink, J as JobTransport, K as KernelEvent, a as KernelEventType, P as Persistence, S as Scheduler, b as StageCompletedEvent, c as StageFailedEvent, d as StageProgressEvent, e as StageStartedEvent, f as StageSuspendedEvent, W as WorkflowCancelledEvent, g as WorkflowCompletedEvent, h as WorkflowCreatedEvent, i as WorkflowFailedEvent, j as WorkflowStartedEvent, k as WorkflowSuspendedEvent } from '../ports-855bktyD.js';
4
- export { C as CreateOutboxEventInput, I as IdempotencyRecord, O as OutboxRecord } from '../interface-TsryH4d7.js';
1
+ import { K as KernelDeps } from '../plugins-Cl0WVVrE.js';
2
+ export { C as CommandResult, I as IdempotencyInProgressError, J as JobExecuteCommand, a as JobExecuteResult, b as Kernel, c as KernelCommand, d as KernelCommandType, e as KernelConfig, L as LeaseReapStaleCommand, f as LeaseReapStaleResult, O as OutboxFlushCommand, g as OutboxFlushResult, P as PluginDefinition, h as PluginReplayDLQCommand, i as PluginReplayDLQResult, j as PluginRunner, k as PluginRunnerConfig, R as RunCancelCommand, l as RunCancelResult, m as RunClaimPendingCommand, n as RunClaimPendingResult, o as RunCreateCommand, p as RunCreateResult, q as RunRerunFromCommand, r as RunRerunFromResult, s as RunTransitionCommand, t as RunTransitionResult, S as StagePollSuspendedCommand, u as StagePollSuspendedResult, W as WorkflowRegistry, v as createKernel, w as createPluginRunner, x as definePlugin } from '../plugins-Cl0WVVrE.js';
3
+ 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-D_P24UaY.js';
4
+ export { B as BlobStore, C as Clock, E as EventSink, J as JobTransport, P as Persistence, S as Scheduler } from '../ports-swhiWFw4.js';
5
+ export { f as CreateOutboxEventInput, I as IdempotencyRecord, O as OutboxRecord } from '../interface-BeEPzTFy.js';
5
6
  import 'zod';
6
- import '../stage-BPw7m9Wx.js';
7
+ import '../stage-_7BKqqUG.js';
7
8
 
8
9
  /**
9
10
  * Load workflow context from completed stages.
@@ -1,3 +1,4 @@
1
- export { IdempotencyInProgressError, createKernel, createPluginRunner, definePlugin, loadWorkflowContext, saveStageOutput } from '../chunk-WQPZ6KON.js';
1
+ export { IdempotencyInProgressError, createKernel, createPluginRunner, definePlugin, loadWorkflowContext, saveStageOutput } from '../chunk-5C7LRNM7.js';
2
+ import '../chunk-2HEV5ZJL.js';
2
3
  //# sourceMappingURL=index.js.map
3
4
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,6 @@
1
- import { E as EventSink, K as KernelEvent, a as KernelEventType, C as Clock, B as BlobStore, S as Scheduler } from '../../ports-855bktyD.js';
2
- import '../../interface-TsryH4d7.js';
1
+ import { K as KernelEvent, a as KernelEventType } from '../../events-D_P24UaY.js';
2
+ import { E as EventSink, C as Clock, B as BlobStore, S as Scheduler } from '../../ports-swhiWFw4.js';
3
+ import '../../interface-BeEPzTFy.js';
3
4
 
4
5
  declare class CollectingEventSink implements EventSink {
5
6
  readonly events: KernelEvent[];
@@ -1,2 +1,2 @@
1
- export { A as AICallLogger, i as AICallRecord, h as AIHelperStats, r as ArtifactType, g as CreateAICallInput, f as CreateLogInput, a as CreateRunInput, b as CreateStageInput, D as DequeueResult, E as EnqueueJobInput, J as JobQueue, j as JobRecord, k as JobStatus, L as LogLevel, o as SaveArtifactInput, S as Status, U as UpdateRunInput, e as UpdateStageInput, d as UpsertStageInput, p as WorkflowArtifactRecord, q as WorkflowLogRecord, l as WorkflowPersistence, W as WorkflowRunRecord, c as WorkflowStageRecord, n as WorkflowStageStatus, m as WorkflowStatus } from '../interface-TsryH4d7.js';
2
- export { P as PrismaAICallLogger, a as PrismaJobQueue, c as PrismaWorkflowPersistence, e as createPrismaAICallLogger, f as createPrismaJobQueue, g as createPrismaWorkflowPersistence } from '../index-CVkkGnxx.js';
1
+ export { A as AICallLogger, i as AICallRecord, h as AIHelperStats, r as ArtifactType, g as CreateAICallInput, e as CreateLogInput, C as CreateRunInput, a as CreateStageInput, D as DequeueResult, E as EnqueueJobInput, J as JobQueue, j as JobRecord, k as JobStatus, L as LogLevel, o as SaveArtifactInput, S as Status, U as UpdateRunInput, d as UpdateStageInput, c as UpsertStageInput, p as WorkflowArtifactRecord, q as WorkflowLogRecord, l as WorkflowPersistence, W as WorkflowRunRecord, b as WorkflowStageRecord, n as WorkflowStageStatus, m as WorkflowStatus } from '../interface-BeEPzTFy.js';
2
+ export { P as PrismaAICallLogger, a as PrismaJobQueue, c as PrismaWorkflowPersistence, e as createPrismaAICallLogger, f as createPrismaJobQueue, g as createPrismaWorkflowPersistence } from '../index-aNuJ2QgN.js';
@@ -1,6 +1,6 @@
1
1
  import '../chunk-D7RVRRM2.js';
2
- export { PrismaAICallLogger, PrismaJobQueue, PrismaWorkflowPersistence, createPrismaAICallLogger, createPrismaJobQueue, createPrismaWorkflowPersistence } from '../chunk-PHLNTR5Z.js';
2
+ export { PrismaAICallLogger, PrismaJobQueue, PrismaWorkflowPersistence, createPrismaAICallLogger, createPrismaJobQueue, createPrismaWorkflowPersistence } from '../chunk-Q2XDO3UF.js';
3
3
  import '../chunk-MUWP5SF2.js';
4
- import '../chunk-RZY5YRGL.js';
4
+ import '../chunk-2HEV5ZJL.js';
5
5
  //# sourceMappingURL=index.js.map
6
6
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
- export { D as DatabaseType, P as PrismaAICallLogger, a as PrismaJobQueue, b as PrismaJobQueueOptions, c as PrismaWorkflowPersistence, d as PrismaWorkflowPersistenceOptions, e as createPrismaAICallLogger, f as createPrismaJobQueue, g as createPrismaWorkflowPersistence } from '../../index-CVkkGnxx.js';
2
- import '../../interface-TsryH4d7.js';
1
+ export { D as DatabaseType, P as PrismaAICallLogger, a as PrismaJobQueue, b as PrismaJobQueueOptions, c as PrismaWorkflowPersistence, d as PrismaWorkflowPersistenceOptions, e as createPrismaAICallLogger, f as createPrismaJobQueue, g as createPrismaWorkflowPersistence } from '../../index-aNuJ2QgN.js';
2
+ import '../../interface-BeEPzTFy.js';
3
3
 
4
4
  /**
5
5
  * Prisma Enum Compatibility Layer
@@ -1,5 +1,5 @@
1
- export { PrismaAICallLogger, PrismaJobQueue, PrismaWorkflowPersistence, createEnumHelper, createPrismaAICallLogger, createPrismaJobQueue, createPrismaWorkflowPersistence } from '../../chunk-PHLNTR5Z.js';
1
+ export { PrismaAICallLogger, PrismaJobQueue, PrismaWorkflowPersistence, createEnumHelper, createPrismaAICallLogger, createPrismaJobQueue, createPrismaWorkflowPersistence } from '../../chunk-Q2XDO3UF.js';
2
2
  import '../../chunk-MUWP5SF2.js';
3
- import '../../chunk-RZY5YRGL.js';
3
+ import '../../chunk-2HEV5ZJL.js';
4
4
  //# sourceMappingURL=index.js.map
5
5
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
- import { S as Stage } from './stage-BPw7m9Wx.js';
3
- import { P as Persistence, B as BlobStore, J as JobTransport, E as EventSink, S as Scheduler, C as Clock, a as KernelEventType, K as KernelEvent } from './ports-855bktyD.js';
2
+ import { S as Stage } from './stage-_7BKqqUG.js';
3
+ import { P as Persistence, B as BlobStore, J as JobTransport, E as EventSink, S as Scheduler, C as Clock } from './ports-swhiWFw4.js';
4
+ import { a as KernelEventType, K as KernelEvent } from './events-D_P24UaY.js';
4
5
 
5
6
  /**
6
7
  * Workflow Builder - Fluent API for composing type-safe workflows
@@ -150,8 +151,8 @@ declare class WorkflowBuilder<TInput extends z.ZodTypeAny, TCurrentOutput extend
150
151
  *
151
152
  * Validates that all declared dependencies exist in the workflow.
152
153
  */
153
- pipe<TStageInput extends z.ZodTypeAny, TStageOutput extends z.ZodTypeAny, TStageConfig extends z.ZodTypeAny, TStageContext extends Record<string, unknown>>(stage: Stage<TStageInput, TStageOutput, TStageConfig, TStageContext>): WorkflowBuilder<TInput, TStageOutput, TContext & {
154
- [x: string]: z.infer<TStageOutput>;
154
+ pipe<TStageInput extends z.ZodTypeAny, TStageOutput extends z.ZodTypeAny, TStageConfig extends z.ZodTypeAny, TStageContext extends Record<string, unknown>, TStageId extends string = string>(stage: Stage<TStageInput, TStageOutput, TStageConfig, TStageContext, TStageId>): WorkflowBuilder<TInput, TStageOutput, TContext & {
155
+ [K in TStageId]: z.infer<TStageOutput>;
155
156
  }>;
156
157
  /**
157
158
  * Add a stage with strict input type checking
@@ -163,7 +164,7 @@ declare class WorkflowBuilder<TInput extends z.ZodTypeAny, TCurrentOutput extend
163
164
  * Add multiple stages that execute in parallel
164
165
  *
165
166
  * All stages receive the same input (current output)
166
- * Their outputs are merged into an object by index AND accumulated in context by stage ID.
167
+ * Their outputs are merged into an object by stage ID and accumulated in context.
167
168
  *
168
169
  * Note: This accepts stages regardless of strict input type matching.
169
170
  * This is necessary because stages using passthrough() can accept objects
@@ -293,6 +294,8 @@ interface JobExecuteResult {
293
294
  readonly output?: unknown;
294
295
  readonly error?: string;
295
296
  readonly nextPollAt?: Date;
297
+ /** True when the job was discarded because the run is no longer RUNNING. */
298
+ readonly ghost?: boolean;
296
299
  }
297
300
  /** Polls suspended stages to check if they can be resumed. */
298
301
  interface StagePollSuspendedCommand {
@@ -431,4 +434,4 @@ interface PluginRunner extends EventSink {
431
434
  declare function definePlugin<T extends KernelEventType>(definition: PluginDefinition<T>): PluginDefinition<T>;
432
435
  declare function createPluginRunner(config: PluginRunnerConfig): PluginRunner;
433
436
 
434
- export { WorkflowBuilder as A, type CommandResult as C, IdempotencyInProgressError as I, type JobExecuteCommand as J, type KernelDeps as K, type LeaseReapStaleCommand as L, type OutboxFlushCommand as O, type PluginDefinition as P, type RunCancelCommand as R, type StagePollSuspendedCommand as S, type WorkflowRegistry as W, type JobExecuteResult as a, type Kernel as b, type KernelCommand as c, type KernelCommandType as d, type KernelConfig as e, type LeaseReapStaleResult as f, type OutboxFlushResult as g, type PluginReplayDLQCommand as h, type PluginReplayDLQResult as i, type PluginRunner as j, type PluginRunnerConfig as k, type RunCancelResult as l, type RunClaimPendingCommand as m, type RunClaimPendingResult as n, type RunCreateCommand as o, type RunCreateResult as p, type RunRerunFromCommand as q, type RunRerunFromResult as r, type RunTransitionCommand as s, type RunTransitionResult as t, type StagePollSuspendedResult as u, createKernel as v, createPluginRunner as w, definePlugin as x, type InferWorkflowStageIds as y, Workflow as z };
437
+ export { WorkflowBuilder as A, type CommandResult as C, IdempotencyInProgressError as I, type JobExecuteCommand as J, type KernelDeps as K, type LeaseReapStaleCommand as L, type OutboxFlushCommand as O, type PluginDefinition as P, type RunCancelCommand as R, type StagePollSuspendedCommand as S, type WorkflowRegistry as W, type JobExecuteResult as a, type Kernel as b, type KernelCommand as c, type KernelCommandType as d, type KernelConfig as e, type LeaseReapStaleResult as f, type OutboxFlushResult as g, type PluginReplayDLQCommand as h, type PluginReplayDLQResult as i, type PluginRunner as j, type PluginRunnerConfig as k, type RunCancelResult as l, type RunClaimPendingCommand as m, type RunClaimPendingResult as n, type RunCreateCommand as o, type RunCreateResult as p, type RunRerunFromCommand as q, type RunRerunFromResult as r, type RunTransitionCommand as s, type RunTransitionResult as t, type StagePollSuspendedResult as u, createKernel as v, createPluginRunner as w, definePlugin as x, Workflow as y, type InferWorkflowStageIds as z };
@@ -1,108 +1,5 @@
1
- import { E as EnqueueJobInput, D as DequeueResult, a as CreateRunInput, W as WorkflowRunRecord, U as UpdateRunInput, S as Status, b as CreateStageInput, c as WorkflowStageRecord, d as UpsertStageInput, e as UpdateStageInput, f as CreateLogInput, C as CreateOutboxEventInput, O as OutboxRecord } from './interface-TsryH4d7.js';
2
-
3
- /**
4
- * Kernel Event Types
5
- *
6
- * Discriminated union of all events emitted by the workflow kernel.
7
- * Each event carries a string literal `type` discriminant, a `timestamp`,
8
- * and a `workflowRunId` that scopes the event to a specific run.
9
- *
10
- * This file contains ONLY types -- no runtime code.
11
- */
12
- /** Emitted when a new workflow run record is created. */
13
- interface WorkflowCreatedEvent {
14
- readonly type: "workflow:created";
15
- readonly timestamp: Date;
16
- readonly workflowRunId: string;
17
- readonly workflowId: string;
18
- }
19
- /** Emitted when a workflow run begins execution. */
20
- interface WorkflowStartedEvent {
21
- readonly type: "workflow:started";
22
- readonly timestamp: Date;
23
- readonly workflowRunId: string;
24
- }
25
- /** Emitted when a workflow run finishes successfully. */
26
- interface WorkflowCompletedEvent {
27
- readonly type: "workflow:completed";
28
- readonly timestamp: Date;
29
- readonly workflowRunId: string;
30
- readonly duration?: number;
31
- readonly totalCost?: number;
32
- readonly totalTokens?: number;
33
- readonly output?: unknown;
34
- }
35
- /** Emitted when a workflow run terminates due to an unrecoverable error. */
36
- interface WorkflowFailedEvent {
37
- readonly type: "workflow:failed";
38
- readonly timestamp: Date;
39
- readonly workflowRunId: string;
40
- readonly error: string;
41
- }
42
- /** Emitted when a workflow run is cancelled by an external request. */
43
- interface WorkflowCancelledEvent {
44
- readonly type: "workflow:cancelled";
45
- readonly timestamp: Date;
46
- readonly workflowRunId: string;
47
- readonly reason?: string;
48
- }
49
- /** Emitted when a workflow run suspends, waiting on an external signal. */
50
- interface WorkflowSuspendedEvent {
51
- readonly type: "workflow:suspended";
52
- readonly timestamp: Date;
53
- readonly workflowRunId: string;
54
- readonly stageId: string;
55
- }
56
- /** Emitted when a stage begins execution. */
57
- interface StageStartedEvent {
58
- readonly type: "stage:started";
59
- readonly timestamp: Date;
60
- readonly workflowRunId: string;
61
- readonly stageId: string;
62
- readonly stageName: string;
63
- readonly stageNumber: number;
64
- }
65
- /** Emitted when a stage completes successfully. */
66
- interface StageCompletedEvent {
67
- readonly type: "stage:completed";
68
- readonly timestamp: Date;
69
- readonly workflowRunId: string;
70
- readonly stageId: string;
71
- readonly stageName: string;
72
- readonly duration: number;
73
- }
74
- /** Emitted when a stage suspends, awaiting a future poll. */
75
- interface StageSuspendedEvent {
76
- readonly type: "stage:suspended";
77
- readonly timestamp: Date;
78
- readonly workflowRunId: string;
79
- readonly stageId: string;
80
- readonly stageName: string;
81
- readonly nextPollAt: Date;
82
- }
83
- /** Emitted when a stage fails with an error. */
84
- interface StageFailedEvent {
85
- readonly type: "stage:failed";
86
- readonly timestamp: Date;
87
- readonly workflowRunId: string;
88
- readonly stageId: string;
89
- readonly stageName: string;
90
- readonly error: string;
91
- }
92
- /** Emitted to report incremental progress within a stage. */
93
- interface StageProgressEvent {
94
- readonly type: "stage:progress";
95
- readonly timestamp: Date;
96
- readonly workflowRunId: string;
97
- readonly stageId: string;
98
- readonly progress: number;
99
- readonly message: string;
100
- readonly details?: Record<string, unknown>;
101
- }
102
- /** Discriminated union of every kernel event. */
103
- type KernelEvent = WorkflowCreatedEvent | WorkflowStartedEvent | WorkflowCompletedEvent | WorkflowFailedEvent | WorkflowCancelledEvent | WorkflowSuspendedEvent | StageStartedEvent | StageCompletedEvent | StageSuspendedEvent | StageFailedEvent | StageProgressEvent;
104
- /** String literal union of all kernel event type discriminants. */
105
- type KernelEventType = KernelEvent["type"];
1
+ import { E as EnqueueJobInput, D as DequeueResult, C as CreateRunInput, W as WorkflowRunRecord, U as UpdateRunInput, S as Status, a as CreateStageInput, b as WorkflowStageRecord, c as UpsertStageInput, d as UpdateStageInput, e as CreateLogInput, f as CreateOutboxEventInput, O as OutboxRecord } from './interface-BeEPzTFy.js';
2
+ import { K as KernelEvent } from './events-D_P24UaY.js';
106
3
 
107
4
  /**
108
5
  * Kernel Port Interfaces
@@ -232,6 +129,8 @@ interface JobTransport {
232
129
  }>>;
233
130
  /** Release stale locks (for crashed workers). */
234
131
  releaseStaleJobs(staleThresholdMs?: number): Promise<number>;
132
+ /** Cancel all pending/suspended jobs for a workflow run. Returns count cancelled. */
133
+ cancelByRun(workflowRunId: string): Promise<number>;
235
134
  }
236
135
  /** Event publishing (replaces global EventBus). */
237
136
  interface EventSink {
@@ -243,4 +142,4 @@ interface Scheduler {
243
142
  cancel(commandType: string, correlationId: string): Promise<void>;
244
143
  }
245
144
 
246
- export type { BlobStore as B, Clock as C, EventSink as E, JobTransport as J, KernelEvent as K, Persistence as P, Scheduler as S, WorkflowCancelledEvent as W, KernelEventType as a, StageCompletedEvent as b, StageFailedEvent as c, StageProgressEvent as d, StageStartedEvent as e, StageSuspendedEvent as f, WorkflowCompletedEvent as g, WorkflowCreatedEvent as h, WorkflowFailedEvent as i, WorkflowStartedEvent as j, WorkflowSuspendedEvent as k };
145
+ export type { BlobStore as B, Clock as C, EventSink as E, JobTransport as J, Persistence as P, Scheduler as S };
@@ -120,8 +120,8 @@ interface CheckCompletionContext<TConfig> {
120
120
  log: (level: LogLevel, message: string, meta?: Record<string, unknown>) => void;
121
121
  storage: StageStorage;
122
122
  }
123
- interface Stage<TInput extends z.ZodTypeAny, TOutput extends z.ZodTypeAny, TConfig extends z.ZodTypeAny, TWorkflowContext = Record<string, unknown>> {
124
- id: string;
123
+ interface Stage<TInput extends z.ZodTypeAny, TOutput extends z.ZodTypeAny, TConfig extends z.ZodTypeAny, TWorkflowContext = Record<string, unknown>, TId extends string = string> {
124
+ id: TId;
125
125
  name: string;
126
126
  description?: string;
127
127
  /**
@@ -1,4 +1,4 @@
1
- import { A as AICallLogger, g as CreateAICallInput, h as AIHelperStats, i as AICallRecord, J as JobQueue, E as EnqueueJobInput, D as DequeueResult, j as JobRecord, k as JobStatus, l as WorkflowPersistence, a as CreateRunInput, W as WorkflowRunRecord, U as UpdateRunInput, m as WorkflowStatus, b as CreateStageInput, c as WorkflowStageRecord, d as UpsertStageInput, e as UpdateStageInput, n as WorkflowStageStatus, f as CreateLogInput, C as CreateOutboxEventInput, O as OutboxRecord, o as SaveArtifactInput, p as WorkflowArtifactRecord, q as WorkflowLogRecord } from '../interface-TsryH4d7.js';
1
+ import { A as AICallLogger, g as CreateAICallInput, h as AIHelperStats, i as AICallRecord, J as JobQueue, E as EnqueueJobInput, D as DequeueResult, j as JobRecord, k as JobStatus, l as WorkflowPersistence, C as CreateRunInput, W as WorkflowRunRecord, U as UpdateRunInput, m as WorkflowStatus, a as CreateStageInput, b as WorkflowStageRecord, c as UpsertStageInput, d as UpdateStageInput, n as WorkflowStageStatus, e as CreateLogInput, f as CreateOutboxEventInput, O as OutboxRecord, o as SaveArtifactInput, p as WorkflowArtifactRecord, q as WorkflowLogRecord } from '../interface-BeEPzTFy.js';
2
2
 
3
3
  /**
4
4
  * In-Memory AI Call Logger
@@ -121,6 +121,7 @@ declare class InMemoryJobQueue implements JobQueue {
121
121
  workflowRunId: string;
122
122
  }>>;
123
123
  releaseStaleJobs(staleThresholdMs?: number): Promise<number>;
124
+ cancelByRun(workflowRunId: string): Promise<number>;
124
125
  /**
125
126
  * Clear all jobs - useful between tests
126
127
  */