@remoraflow/core 0.1.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/LICENSE +674 -0
- package/README.md +110 -0
- package/dist/compiler/index.d.ts +25 -0
- package/dist/compiler/index.d.ts.map +1 -0
- package/dist/compiler/passes/apply-best-practices.d.ts +19 -0
- package/dist/compiler/passes/apply-best-practices.d.ts.map +1 -0
- package/dist/compiler/passes/build-graph.d.ts +7 -0
- package/dist/compiler/passes/build-graph.d.ts.map +1 -0
- package/dist/compiler/passes/generate-constrained-tool-schemas.d.ts +4 -0
- package/dist/compiler/passes/generate-constrained-tool-schemas.d.ts.map +1 -0
- package/dist/compiler/passes/validate-control-flow.d.ts +4 -0
- package/dist/compiler/passes/validate-control-flow.d.ts.map +1 -0
- package/dist/compiler/passes/validate-foreach-target.d.ts +4 -0
- package/dist/compiler/passes/validate-foreach-target.d.ts.map +1 -0
- package/dist/compiler/passes/validate-jmespath.d.ts +4 -0
- package/dist/compiler/passes/validate-jmespath.d.ts.map +1 -0
- package/dist/compiler/passes/validate-limits.d.ts +9 -0
- package/dist/compiler/passes/validate-limits.d.ts.map +1 -0
- package/dist/compiler/passes/validate-references.d.ts +4 -0
- package/dist/compiler/passes/validate-references.d.ts.map +1 -0
- package/dist/compiler/passes/validate-tools.d.ts +4 -0
- package/dist/compiler/passes/validate-tools.d.ts.map +1 -0
- package/dist/compiler/types.d.ts +100 -0
- package/dist/compiler/types.d.ts.map +1 -0
- package/dist/compiler/utils/graph.d.ts +35 -0
- package/dist/compiler/utils/graph.d.ts.map +1 -0
- package/dist/compiler/utils/jmespath-helpers.d.ts +34 -0
- package/dist/compiler/utils/jmespath-helpers.d.ts.map +1 -0
- package/dist/compiler/utils/schema.d.ts +33 -0
- package/dist/compiler/utils/schema.d.ts.map +1 -0
- package/dist/example-tasks.d.ts +834 -0
- package/dist/example-tasks.d.ts.map +1 -0
- package/dist/executor/context.d.ts +42 -0
- package/dist/executor/context.d.ts.map +1 -0
- package/dist/executor/errors.d.ts +57 -0
- package/dist/executor/errors.d.ts.map +1 -0
- package/dist/executor/executor-types.d.ts +117 -0
- package/dist/executor/executor-types.d.ts.map +1 -0
- package/dist/executor/helpers.d.ts +21 -0
- package/dist/executor/helpers.d.ts.map +1 -0
- package/dist/executor/index.d.ts +16 -0
- package/dist/executor/index.d.ts.map +1 -0
- package/dist/executor/schema-inference.d.ts +3 -0
- package/dist/executor/schema-inference.d.ts.map +1 -0
- package/dist/executor/state.d.ts +292 -0
- package/dist/executor/state.d.ts.map +1 -0
- package/dist/executor/steps/agent-loop.d.ts +15 -0
- package/dist/executor/steps/agent-loop.d.ts.map +1 -0
- package/dist/executor/steps/end.d.ts +5 -0
- package/dist/executor/steps/end.d.ts.map +1 -0
- package/dist/executor/steps/extract-data.d.ts +15 -0
- package/dist/executor/steps/extract-data.d.ts.map +1 -0
- package/dist/executor/steps/for-each.d.ts +11 -0
- package/dist/executor/steps/for-each.d.ts.map +1 -0
- package/dist/executor/steps/llm-prompt.d.ts +13 -0
- package/dist/executor/steps/llm-prompt.d.ts.map +1 -0
- package/dist/executor/steps/sleep.d.ts +7 -0
- package/dist/executor/steps/sleep.d.ts.map +1 -0
- package/dist/executor/steps/start.d.ts +2 -0
- package/dist/executor/steps/start.d.ts.map +1 -0
- package/dist/executor/steps/switch-case.d.ts +11 -0
- package/dist/executor/steps/switch-case.d.ts.map +1 -0
- package/dist/executor/steps/tool-call.d.ts +9 -0
- package/dist/executor/steps/tool-call.d.ts.map +1 -0
- package/dist/executor/steps/wait-for-condition.d.ts +8 -0
- package/dist/executor/steps/wait-for-condition.d.ts.map +1 -0
- package/dist/generator/index.d.ts +59 -0
- package/dist/generator/index.d.ts.map +1 -0
- package/dist/generator/prompt.d.ts +6 -0
- package/dist/generator/prompt.d.ts.map +1 -0
- package/dist/lib.d.ts +15 -0
- package/dist/lib.d.ts.map +1 -0
- package/dist/lib.js +3566 -0
- package/dist/lib.js.map +42 -0
- package/dist/types.d.ts +481 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +54 -0
package/dist/lib.js.map
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/compiler/index.ts", "../src/compiler/passes/apply-best-practices.ts", "../src/compiler/utils/graph.ts", "../src/compiler/passes/build-graph.ts", "../src/compiler/passes/generate-constrained-tool-schemas.ts", "../src/compiler/utils/schema.ts", "../src/compiler/passes/validate-control-flow.ts", "../src/compiler/passes/validate-foreach-target.ts", "../src/compiler/utils/jmespath-helpers.ts", "../src/compiler/passes/validate-jmespath.ts", "../src/compiler/passes/validate-limits.ts", "../src/compiler/passes/validate-references.ts", "../src/compiler/passes/validate-tools.ts", "../src/executor/errors.ts", "../src/executor/context.ts", "../src/executor/state.ts", "../src/executor/executor-types.ts", "../src/executor/steps/agent-loop.ts", "../src/executor/helpers.ts", "../src/executor/steps/end.ts", "../src/executor/steps/extract-data.ts", "../src/executor/schema-inference.ts", "../src/executor/steps/for-each.ts", "../src/executor/steps/llm-prompt.ts", "../src/executor/steps/sleep.ts", "../src/executor/steps/start.ts", "../src/executor/steps/switch-case.ts", "../src/executor/steps/tool-call.ts", "../src/executor/steps/wait-for-condition.ts", "../src/executor/index.ts", "../src/generator/index.ts", "../src/types.ts", "../src/generator/prompt.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { ToolSet } from \"ai\";\nimport { asSchema } from \"ai\";\nimport type { WorkflowDefinition } from \"../types\";\nimport { applyBestPractices } from \"./passes/apply-best-practices\";\nimport { buildGraph } from \"./passes/build-graph\";\nimport { generateConstrainedToolSchemas } from \"./passes/generate-constrained-tool-schemas\";\nimport { validateControlFlow } from \"./passes/validate-control-flow\";\nimport { validateForeachTarget } from \"./passes/validate-foreach-target\";\nimport { validateJmespath } from \"./passes/validate-jmespath\";\nimport { validateLimits } from \"./passes/validate-limits\";\nimport { validateReferences } from \"./passes/validate-references\";\nimport { validateTools } from \"./passes/validate-tools\";\nimport type {\n\tCompilerLimits,\n\tCompilerResult,\n\tConstrainedToolSchemaMap,\n\tDiagnostic,\n\tToolDefinitionMap,\n} from \"./types\";\n\n/**\n * Compiles a workflow definition through a multi-pass validation pipeline,\n * producing an execution graph and structured diagnostics.\n *\n * Passes: graph construction, reference validation, control flow validation,\n * JMESPath validation, tool validation, for-each target validation, and\n * best-practice transformations.\n *\n * @param workflow - The workflow definition to compile.\n * @param options - Optional configuration.\n * @param options.tools - Tool definitions to validate tool-call steps against.\n * When provided, enables tool input validation and constrained schema generation.\n * @returns A {@link CompilerResult} containing diagnostics, the execution graph\n * (if structurally valid), an optimized workflow (if error-free), and\n * constrained tool schemas (if tools were provided).\n */\nexport async function compileWorkflow(\n\tworkflow: WorkflowDefinition,\n\toptions?: {\n\t\ttools?: ToolSet;\n\t\tlimits?: CompilerLimits;\n\t},\n): Promise<CompilerResult> {\n\tconst diagnostics: Diagnostic[] = [];\n\n\t// Pass 1: Build execution graph\n\tconst graphResult = buildGraph(workflow);\n\tdiagnostics.push(...graphResult.diagnostics);\n\n\t// Pass 2: Validate step references\n\tconst refDiagnostics = validateReferences(workflow);\n\t// Deduplicate MISSING_INITIAL_STEP (emitted by both build-graph and validate-references)\n\tfor (const d of refDiagnostics) {\n\t\tif (\n\t\t\td.code === \"MISSING_INITIAL_STEP\" &&\n\t\t\tdiagnostics.some((e) => e.code === \"MISSING_INITIAL_STEP\")\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push(d);\n\t}\n\n\t// Pass 2b: Validate sleep/wait literal values against configured limits\n\tdiagnostics.push(...validateLimits(workflow, options?.limits));\n\n\t// Pass 3: Extract tool schemas (needed by control flow and for-each validation)\n\tlet constrainedToolSchemas: ConstrainedToolSchemaMap | null = null;\n\tlet toolSchemas: ToolDefinitionMap | null = null;\n\tif (options?.tools) {\n\t\ttoolSchemas = await extractToolSchemas(options.tools);\n\t\tdiagnostics.push(...validateTools(workflow, toolSchemas));\n\t\tconstrainedToolSchemas = generateConstrainedToolSchemas(\n\t\t\tworkflow,\n\t\t\ttoolSchemas,\n\t\t);\n\t}\n\n\t// Pass 4+: Only proceed with graph-dependent passes if we have a valid graph\n\tif (graphResult.graph) {\n\t\tdiagnostics.push(\n\t\t\t...validateControlFlow(workflow, graphResult.graph, toolSchemas),\n\t\t);\n\n\t\tdiagnostics.push(...validateJmespath(workflow, graphResult.graph));\n\n\t\t// Validate for-each targets resolve to array types\n\t\tif (toolSchemas) {\n\t\t\tdiagnostics.push(\n\t\t\t\t...validateForeachTarget(workflow, graphResult.graph, toolSchemas),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Final pass: apply best-practice transformations (non-destructive)\n\tconst hasErrors = diagnostics.some((d) => d.severity === \"error\");\n\tlet optimizedWorkflow: WorkflowDefinition | null = null;\n\tif (graphResult.graph && !hasErrors) {\n\t\tconst bpResult = applyBestPractices(workflow, graphResult.graph);\n\t\toptimizedWorkflow = bpResult.workflow;\n\t\tdiagnostics.push(...bpResult.diagnostics);\n\t}\n\n\treturn {\n\t\tdiagnostics,\n\t\tgraph: graphResult.graph,\n\t\tworkflow: optimizedWorkflow,\n\t\tconstrainedToolSchemas,\n\t};\n}\n\nasync function extractToolSchemas(tools: ToolSet): Promise<ToolDefinitionMap> {\n\tconst schemas: ToolDefinitionMap = {};\n\tfor (const [name, toolDef] of Object.entries(tools)) {\n\t\tconst jsonSchema = await asSchema(toolDef.inputSchema).jsonSchema;\n\t\tschemas[name] = {\n\t\t\tinputSchema: jsonSchema as ToolDefinitionMap[string][\"inputSchema\"],\n\t\t};\n\t\tif (toolDef.outputSchema) {\n\t\t\tschemas[name].outputSchema = (await asSchema(toolDef.outputSchema)\n\t\t\t\t.jsonSchema) as Record<string, unknown>;\n\t\t}\n\t}\n\treturn schemas;\n}\n\nexport type {\n\tCompilerLimits,\n\tCompilerResult,\n\tConstrainedToolSchema,\n\tConstrainedToolSchemaMap,\n\tDiagnostic,\n\tDiagnosticCode,\n\tDiagnosticLocation,\n\tDiagnosticSeverity,\n\tExecutionGraph,\n} from \"./types\";\n",
|
|
6
|
+
"import type { WorkflowDefinition, WorkflowStep } from \"../../types\";\nimport type { Diagnostic, ExecutionGraph } from \"../types\";\n\ninterface BestPracticeRuleResult {\n\tworkflow: WorkflowDefinition;\n\tdiagnostics: Diagnostic[];\n}\n\n/**\n * A best-practice rule that can non-destructively modify a workflow.\n * Each rule receives a deep-cloned workflow and the execution graph,\n * and returns the (possibly modified) workflow along with any diagnostics.\n */\nexport type BestPracticeRule = (\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n) => BestPracticeRuleResult;\n\n/**\n * Registry of best-practice rules applied in order.\n * Add new rules here to have them run automatically.\n */\nconst rules: BestPracticeRule[] = [addMissingStartStep, addMissingEndSteps];\n\n/**\n * Applies all registered best-practice rules to a deep copy of the workflow.\n * The original workflow is never mutated.\n */\nexport function applyBestPractices(\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n): BestPracticeRuleResult {\n\tlet result = structuredClone(workflow);\n\tconst allDiagnostics: Diagnostic[] = [];\n\n\tfor (const rule of rules) {\n\t\tconst ruleResult = rule(result, graph);\n\t\tresult = ruleResult.workflow;\n\t\tallDiagnostics.push(...ruleResult.diagnostics);\n\t}\n\n\treturn { workflow: result, diagnostics: allDiagnostics };\n}\n\n/**\n * Ensures the workflow has a start step. If none exists, one is\n * auto-inserted with an empty input schema.\n */\nfunction addMissingStartStep(\n\tworkflow: WorkflowDefinition,\n\t_graph: ExecutionGraph,\n): BestPracticeRuleResult {\n\tconst diagnostics: Diagnostic[] = [];\n\n\tconst hasStartStep = workflow.steps.some((s) => s.type === \"start\");\n\tif (hasStartStep) {\n\t\treturn { workflow, diagnostics };\n\t}\n\n\tconst startStepId = \"__start\";\n\tconst oldInitialStepId = workflow.initialStepId;\n\n\tconst startStep: WorkflowStep = {\n\t\tid: startStepId,\n\t\tname: \"Start\",\n\t\tdescription: \"Auto-generated start step\",\n\t\ttype: \"start\",\n\t\tnextStepId: oldInitialStepId,\n\t};\n\n\tworkflow.steps.unshift(startStep);\n\tworkflow.initialStepId = startStepId;\n\n\tdiagnostics.push({\n\t\tseverity: \"warning\",\n\t\tlocation: { stepId: null, field: \"initialStepId\" },\n\t\tmessage:\n\t\t\t\"Workflow has no start step; one was automatically added with an empty input schema\",\n\t\tcode: \"MISSING_START_STEP\",\n\t});\n\n\treturn { workflow, diagnostics };\n}\n\n/**\n * Ensures every terminal step (a step with no nextStepId that isn't\n * already an \"end\" step) gets an explicit \"end\" step appended.\n */\nfunction addMissingEndSteps(\n\tworkflow: WorkflowDefinition,\n\t_graph: ExecutionGraph,\n): BestPracticeRuleResult {\n\tconst newEndSteps: WorkflowStep[] = [];\n\n\tfor (const step of workflow.steps) {\n\t\tif (step.type === \"end\") continue;\n\t\tif (step.nextStepId) continue;\n\n\t\tconst endStepId = `${step.id}_end`;\n\t\tstep.nextStepId = endStepId;\n\t\tnewEndSteps.push({\n\t\t\tid: endStepId,\n\t\t\tname: \"End\",\n\t\t\tdescription: `End of chain after ${step.id}`,\n\t\t\ttype: \"end\",\n\t\t});\n\t}\n\n\tworkflow.steps.push(...newEndSteps);\n\treturn { workflow, diagnostics: [] };\n}\n",
|
|
7
|
+
"import type { WorkflowStep } from \"../../types\";\n\nexport function buildStepIndex(steps: WorkflowStep[]): {\n\tindex: Map<string, WorkflowStep>;\n\tduplicates: string[];\n} {\n\tconst index = new Map<string, WorkflowStep>();\n\tconst duplicates: string[] = [];\n\n\tfor (const step of steps) {\n\t\tif (index.has(step.id)) {\n\t\t\tduplicates.push(step.id);\n\t\t} else {\n\t\t\tindex.set(step.id, step);\n\t\t}\n\t}\n\n\treturn { index, duplicates };\n}\n\nexport function computeSuccessors(\n\tstepIndex: Map<string, WorkflowStep>,\n): Map<string, Set<string>> {\n\tconst successors = new Map<string, Set<string>>();\n\n\tfor (const [id, step] of stepIndex) {\n\t\tconst succs = new Set<string>();\n\n\t\tif (step.nextStepId) {\n\t\t\tsuccs.add(step.nextStepId);\n\t\t}\n\n\t\tif (step.type === \"switch-case\") {\n\t\t\tfor (const c of step.params.cases) {\n\t\t\t\tsuccs.add(c.branchBodyStepId);\n\t\t\t}\n\t\t}\n\n\t\tif (step.type === \"for-each\") {\n\t\t\tsuccs.add(step.params.loopBodyStepId);\n\t\t}\n\n\t\tif (step.type === \"wait-for-condition\") {\n\t\t\tsuccs.add(step.params.conditionStepId);\n\t\t}\n\n\t\tsuccessors.set(id, succs);\n\t}\n\n\treturn successors;\n}\n\nexport function computeReachability(\n\tinitialStepId: string,\n\tsuccessors: Map<string, Set<string>>,\n): Set<string> {\n\tconst reachable = new Set<string>();\n\tconst queue = [initialStepId];\n\n\twhile (queue.length > 0) {\n\t\tconst current = queue.shift();\n\t\tif (current === undefined) break;\n\t\tif (reachable.has(current)) continue;\n\t\treachable.add(current);\n\n\t\tconst succs = successors.get(current);\n\t\tif (succs) {\n\t\t\tfor (const s of succs) {\n\t\t\t\tif (!reachable.has(s)) {\n\t\t\t\t\tqueue.push(s);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn reachable;\n}\n\n/**\n * Detect cycles using DFS with white/gray/black coloring.\n * Returns arrays of step IDs forming each detected cycle.\n */\nexport function detectCycles(\n\tstepIndex: Map<string, WorkflowStep>,\n\tsuccessors: Map<string, Set<string>>,\n): string[][] {\n\tconst WHITE = 0;\n\tconst GRAY = 1;\n\tconst BLACK = 2;\n\n\tconst color = new Map<string, number>();\n\tfor (const id of stepIndex.keys()) {\n\t\tcolor.set(id, WHITE);\n\t}\n\n\tconst cycles: string[][] = [];\n\tconst path: string[] = [];\n\n\tfunction dfs(node: string) {\n\t\tif (!stepIndex.has(node)) return;\n\n\t\tcolor.set(node, GRAY);\n\t\tpath.push(node);\n\n\t\tconst succs = successors.get(node);\n\t\tif (succs) {\n\t\t\tfor (const next of succs) {\n\t\t\t\tif (!stepIndex.has(next)) continue;\n\n\t\t\t\tconst c = color.get(next);\n\t\t\t\tif (c === undefined) continue;\n\t\t\t\tif (c === GRAY) {\n\t\t\t\t\t// Found a cycle — extract the cycle from the path\n\t\t\t\t\tconst cycleStart = path.indexOf(next);\n\t\t\t\t\tcycles.push(path.slice(cycleStart));\n\t\t\t\t} else if (c === WHITE) {\n\t\t\t\t\tdfs(next);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpath.pop();\n\t\tcolor.set(node, BLACK);\n\t}\n\n\tfor (const id of stepIndex.keys()) {\n\t\tif (color.get(id) === WHITE) {\n\t\t\tdfs(id);\n\t\t}\n\t}\n\n\treturn cycles;\n}\n\n/**\n * Compute the set of predecessor step IDs for each step.\n * A predecessor of step X is any step that must have executed before X\n * in the execution order.\n *\n * This uses topological order: for each step, its predecessors are the\n * union of all steps that can reach it via successor edges.\n */\nexport function computePredecessors(\n\ttopologicalOrder: string[],\n\tsuccessors: Map<string, Set<string>>,\n): Map<string, Set<string>> {\n\tconst predecessors = new Map<string, Set<string>>();\n\n\tfor (const id of topologicalOrder) {\n\t\tpredecessors.set(id, new Set());\n\t}\n\n\tfor (const id of topologicalOrder) {\n\t\tconst succs = successors.get(id);\n\t\tif (!succs) continue;\n\n\t\tfor (const succ of succs) {\n\t\t\tconst predSet = predecessors.get(succ);\n\t\t\tif (!predSet) continue;\n\n\t\t\t// succ's predecessors include id and all of id's predecessors\n\t\t\tpredSet.add(id);\n\t\t\tconst idPreds = predecessors.get(id);\n\t\t\tif (idPreds) {\n\t\t\t\tfor (const p of idPreds) {\n\t\t\t\t\tpredSet.add(p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn predecessors;\n}\n\n/**\n * Compute topological order using Kahn's algorithm.\n * Returns null if cycles exist.\n */\nexport function topologicalSort(\n\tstepIds: string[],\n\tsuccessors: Map<string, Set<string>>,\n): string[] | null {\n\tconst inDegree = new Map<string, number>();\n\tconst stepIdSet = new Set(stepIds);\n\n\tfor (const id of stepIds) {\n\t\tinDegree.set(id, 0);\n\t}\n\n\tfor (const id of stepIds) {\n\t\tconst succs = successors.get(id);\n\t\tif (!succs) continue;\n\t\tfor (const s of succs) {\n\t\t\tif (stepIdSet.has(s)) {\n\t\t\t\tinDegree.set(s, (inDegree.get(s) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst queue: string[] = [];\n\tfor (const [id, deg] of inDegree) {\n\t\tif (deg === 0) queue.push(id);\n\t}\n\n\tconst order: string[] = [];\n\twhile (queue.length > 0) {\n\t\tconst node = queue.shift();\n\t\tif (node === undefined) break;\n\t\torder.push(node);\n\n\t\tconst succs = successors.get(node);\n\t\tif (!succs) continue;\n\t\tfor (const s of succs) {\n\t\t\tif (!stepIdSet.has(s)) continue;\n\t\t\tconst currentDeg = inDegree.get(s);\n\t\t\tif (currentDeg === undefined) continue;\n\t\t\tconst newDeg = currentDeg - 1;\n\t\t\tinDegree.set(s, newDeg);\n\t\t\tif (newDeg === 0) {\n\t\t\t\tqueue.push(s);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn order.length === stepIds.length ? order : null;\n}\n\n/**\n * Walk the execution graph to determine which loop variables (itemName)\n * are in scope at each step, and which steps belong to a body (loop or branch).\n */\nexport function computeLoopScopesAndOwnership(\n\tinitialStepId: string,\n\tstepIndex: Map<string, WorkflowStep>,\n): {\n\tloopVariablesInScope: Map<string, Set<string>>;\n\tbodyOwnership: Map<string, string>;\n} {\n\tconst loopVariablesInScope = new Map<string, Set<string>>();\n\tconst bodyOwnership = new Map<string, string>();\n\n\tfunction walkChain(\n\t\tstartId: string,\n\t\tloopVars: Set<string>,\n\t\townerStepId: string | null,\n\t) {\n\t\t// First pass: claim all steps on this chain (following nextStepId only)\n\t\t// This ensures the main chain is claimed before body sub-chains,\n\t\t// so body chains can't accidentally claim main-chain steps.\n\t\tlet currentId: string | undefined = startId;\n\t\tconst chainSteps: import(\"../../types\").WorkflowStep[] = [];\n\n\t\twhile (currentId) {\n\t\t\tif (loopVariablesInScope.has(currentId)) break;\n\n\t\t\tconst step = stepIndex.get(currentId);\n\t\t\tif (!step) break;\n\n\t\t\tloopVariablesInScope.set(currentId, new Set(loopVars));\n\t\t\tif (ownerStepId !== null) {\n\t\t\t\tbodyOwnership.set(currentId, ownerStepId);\n\t\t\t}\n\n\t\t\tchainSteps.push(step);\n\t\t\tcurrentId = step.nextStepId;\n\t\t}\n\n\t\t// Second pass: recurse into control flow sub-chains (bodies)\n\t\tfor (const step of chainSteps) {\n\t\t\tif (step.type === \"for-each\") {\n\t\t\t\tconst innerVars = new Set(loopVars);\n\t\t\t\tinnerVars.add(step.params.itemName);\n\t\t\t\twalkChain(step.params.loopBodyStepId, innerVars, step.id);\n\t\t\t}\n\n\t\t\tif (step.type === \"switch-case\") {\n\t\t\t\tfor (const c of step.params.cases) {\n\t\t\t\t\twalkChain(c.branchBodyStepId, loopVars, step.id);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (step.type === \"wait-for-condition\") {\n\t\t\t\twalkChain(step.params.conditionStepId, loopVars, step.id);\n\t\t\t}\n\t\t}\n\t}\n\n\twalkChain(initialStepId, new Set(), null);\n\n\treturn { loopVariablesInScope, bodyOwnership };\n}\n",
|
|
8
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type { Diagnostic, ExecutionGraph } from \"../types\";\nimport {\n\tbuildStepIndex,\n\tcomputeLoopScopesAndOwnership,\n\tcomputePredecessors,\n\tcomputeReachability,\n\tcomputeSuccessors,\n\tdetectCycles,\n\ttopologicalSort,\n} from \"../utils/graph\";\n\nexport function buildGraph(workflow: WorkflowDefinition): {\n\tgraph: ExecutionGraph | null;\n\tdiagnostics: Diagnostic[];\n} {\n\tconst diagnostics: Diagnostic[] = [];\n\n\t// Validate step ID format\n\tconst VALID_STEP_ID = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\tfor (const step of workflow.steps) {\n\t\tif (!VALID_STEP_ID.test(step.id)) {\n\t\t\tdiagnostics.push({\n\t\t\t\tseverity: \"error\",\n\t\t\t\tlocation: { stepId: step.id, field: \"id\" },\n\t\t\t\tmessage: `Step ID '${step.id}' is invalid — must match [a-zA-Z_][a-zA-Z0-9_]* (use underscores, not hyphens)`,\n\t\t\t\tcode: \"INVALID_STEP_ID\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// Validate itemName format and shadowing\n\tconst stepIdSet = new Set(workflow.steps.map((s) => s.id));\n\tfor (const step of workflow.steps) {\n\t\tif (step.type === \"for-each\") {\n\t\t\tconst { itemName } = step.params;\n\t\t\tif (!VALID_STEP_ID.test(itemName)) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId: step.id, field: \"params.itemName\" },\n\t\t\t\t\tmessage: `Item name '${itemName}' is invalid — must match [a-zA-Z_][a-zA-Z0-9_]*`,\n\t\t\t\t\tcode: \"INVALID_ITEM_NAME\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (stepIdSet.has(itemName)) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tlocation: { stepId: step.id, field: \"params.itemName\" },\n\t\t\t\t\tmessage: `Item name '${itemName}' shadows step ID '${itemName}' — references to '${itemName}' inside the loop body will resolve to the loop variable, not the step output`,\n\t\t\t\t\tcode: \"ITEM_NAME_SHADOWS_STEP_ID\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build step index, detect duplicates\n\tconst { index: stepIndex, duplicates } = buildStepIndex(workflow.steps);\n\tfor (const dupId of duplicates) {\n\t\tdiagnostics.push({\n\t\t\tseverity: \"error\",\n\t\t\tlocation: { stepId: dupId, field: \"id\" },\n\t\t\tmessage: `Duplicate step ID '${dupId}'`,\n\t\t\tcode: \"DUPLICATE_STEP_ID\",\n\t\t});\n\t}\n\n\t// Check initialStepId exists\n\tif (!stepIndex.has(workflow.initialStepId)) {\n\t\tdiagnostics.push({\n\t\t\tseverity: \"error\",\n\t\t\tlocation: { stepId: null, field: \"initialStepId\" },\n\t\t\tmessage: `Initial step '${workflow.initialStepId}' does not exist`,\n\t\t\tcode: \"MISSING_INITIAL_STEP\",\n\t\t});\n\t\t// Can't build a graph without a valid initial step\n\t\treturn { graph: null, diagnostics };\n\t}\n\n\t// If there are duplicate IDs, the step index is unreliable\n\tif (duplicates.length > 0) {\n\t\treturn { graph: null, diagnostics };\n\t}\n\n\tconst successors = computeSuccessors(stepIndex);\n\n\t// Detect cycles\n\tconst cycles = detectCycles(stepIndex, successors);\n\tfor (const cycle of cycles) {\n\t\tconst firstStep = cycle[0];\n\t\tif (!firstStep) continue;\n\t\tdiagnostics.push({\n\t\t\tseverity: \"error\",\n\t\t\tlocation: { stepId: firstStep, field: \"nextStepId\" },\n\t\t\tmessage: `Cycle detected: ${cycle.join(\" → \")} → ${firstStep}`,\n\t\t\tcode: \"CYCLE_DETECTED\",\n\t\t});\n\t}\n\n\t// Compute reachability\n\tconst reachableSteps = computeReachability(\n\t\tworkflow.initialStepId,\n\t\tsuccessors,\n\t);\n\n\t// Warn about unreachable steps\n\tfor (const [id] of stepIndex) {\n\t\tif (!reachableSteps.has(id)) {\n\t\t\tdiagnostics.push({\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tlocation: { stepId: id, field: \"id\" },\n\t\t\t\tmessage: `Step '${id}' is not reachable from initial step '${workflow.initialStepId}'`,\n\t\t\t\tcode: \"UNREACHABLE_STEP\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// If cycles exist, we can't compute topological order or predecessors\n\tif (cycles.length > 0) {\n\t\treturn { graph: null, diagnostics };\n\t}\n\n\t// Compute topological order\n\tconst reachableIds = [...reachableSteps];\n\tconst topologicalOrder = topologicalSort(reachableIds, successors);\n\tif (!topologicalOrder) {\n\t\t// Shouldn't happen since we already checked for cycles\n\t\treturn { graph: null, diagnostics };\n\t}\n\n\t// Compute predecessors\n\tconst predecessors = computePredecessors(topologicalOrder, successors);\n\n\t// Compute loop variable scopes and body ownership\n\tconst { loopVariablesInScope, bodyOwnership } = computeLoopScopesAndOwnership(\n\t\tworkflow.initialStepId,\n\t\tstepIndex,\n\t);\n\n\treturn {\n\t\tgraph: {\n\t\t\tstepIndex,\n\t\t\tsuccessors,\n\t\t\tpredecessors,\n\t\t\ttopologicalOrder,\n\t\t\treachableSteps,\n\t\t\tloopVariablesInScope,\n\t\t\tbodyOwnership,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n",
|
|
9
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type {\n\tConstrainedToolSchema,\n\tConstrainedToolSchemaMap,\n\tToolDefinitionMap,\n} from \"../types\";\n\n// ─── Internal Types ──────────────────────────────────────────────\n\ninterface CallSiteKeyInfo {\n\ttype: \"literal\";\n\tvalue: unknown;\n}\n\ninterface CallSiteKeyDynamic {\n\ttype: \"jmespath\";\n}\n\ninterface CallSiteInfo {\n\tstepId: string;\n\tkeys: Map<string, CallSiteKeyInfo | CallSiteKeyDynamic>;\n}\n\n// ─── Phase 1: Collect Call Sites ─────────────────────────────────\n\nfunction collectCallSites(\n\tworkflow: WorkflowDefinition,\n): Map<string, CallSiteInfo[]> {\n\tconst callSitesByTool = new Map<string, CallSiteInfo[]>();\n\n\tfor (const step of workflow.steps) {\n\t\tif (step.type !== \"tool-call\") continue;\n\n\t\tconst { toolName, toolInput } = step.params;\n\t\tconst keys = new Map<string, CallSiteKeyInfo | CallSiteKeyDynamic>();\n\n\t\tfor (const [key, expr] of Object.entries(toolInput)) {\n\t\t\tconst expression = expr as { type: string; value?: unknown };\n\t\t\tif (expression.type === \"literal\") {\n\t\t\t\tkeys.set(key, { type: \"literal\", value: expression.value });\n\t\t\t} else {\n\t\t\t\tkeys.set(key, { type: \"jmespath\" });\n\t\t\t}\n\t\t}\n\n\t\tlet sites = callSitesByTool.get(toolName);\n\t\tif (!sites) {\n\t\t\tsites = [];\n\t\t\tcallSitesByTool.set(toolName, sites);\n\t\t}\n\t\tsites.push({ stepId: step.id, keys });\n\t}\n\n\treturn callSitesByTool;\n}\n\n// ─── Phase 2–3: Analyze and Constrain Properties ─────────────────\n\nfunction constrainProperty(\n\tcallSites: CallSiteInfo[],\n\tkey: string,\n\toriginalPropertySchema: unknown,\n): { schema: unknown; allLiteral: boolean; providedInAll: boolean } {\n\tlet providedCount = 0;\n\tlet allLiteral = true;\n\tconst literalValues: unknown[] = [];\n\tconst seen = new Set<string>();\n\n\tfor (const site of callSites) {\n\t\tconst entry = site.keys.get(key);\n\t\tif (!entry) continue;\n\n\t\tprovidedCount++;\n\n\t\tif (entry.type === \"jmespath\") {\n\t\t\tallLiteral = false;\n\t\t} else {\n\t\t\tconst serialized = JSON.stringify(entry.value);\n\t\t\tif (!seen.has(serialized)) {\n\t\t\t\tseen.add(serialized);\n\t\t\t\tliteralValues.push(entry.value);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst providedInAll = providedCount === callSites.length;\n\n\tif (!allLiteral) {\n\t\treturn { schema: originalPropertySchema, allLiteral: false, providedInAll };\n\t}\n\n\tconst original =\n\t\toriginalPropertySchema && typeof originalPropertySchema === \"object\"\n\t\t\t? (originalPropertySchema as Record<string, unknown>)\n\t\t\t: {};\n\n\tif (literalValues.length === 1) {\n\t\treturn {\n\t\t\tschema: { ...original, const: literalValues[0] },\n\t\t\tallLiteral: true,\n\t\t\tprovidedInAll,\n\t\t};\n\t}\n\n\treturn {\n\t\tschema: { ...original, enum: literalValues },\n\t\tallLiteral: true,\n\t\tprovidedInAll,\n\t};\n}\n\n// ─── Phase 4: Assemble Constrained Schemas ───────────────────────\n\nexport function generateConstrainedToolSchemas(\n\tworkflow: WorkflowDefinition,\n\ttools: ToolDefinitionMap,\n): ConstrainedToolSchemaMap {\n\tconst callSitesByTool = collectCallSites(workflow);\n\tconst result: ConstrainedToolSchemaMap = {};\n\n\tfor (const [toolName, callSites] of callSitesByTool) {\n\t\tconst toolDef = tools[toolName];\n\t\tif (!toolDef) continue; // Unknown tool — already reported by validate-tools\n\n\t\tconst originalProperties = toolDef.inputSchema.properties ?? {};\n\n\t\t// Collect all keys used across any call site\n\t\tconst allUsedKeys = new Set<string>();\n\t\tfor (const site of callSites) {\n\t\t\tfor (const key of site.keys.keys()) {\n\t\t\t\tallUsedKeys.add(key);\n\t\t\t}\n\t\t}\n\n\t\tconst constrainedProperties: Record<string, unknown> = {};\n\t\tconst requiredKeys: string[] = [];\n\t\tlet fullyStatic = true;\n\n\t\tfor (const key of allUsedKeys) {\n\t\t\tconst originalProp = originalProperties[key];\n\t\t\tif (originalProp === undefined) continue; // Extra key not in schema — skip\n\n\t\t\tconst { schema, allLiteral, providedInAll } = constrainProperty(\n\t\t\t\tcallSites,\n\t\t\t\tkey,\n\t\t\t\toriginalProp,\n\t\t\t);\n\n\t\t\tconstrainedProperties[key] = schema;\n\n\t\t\tif (providedInAll) {\n\t\t\t\trequiredKeys.push(key);\n\t\t\t}\n\n\t\t\tif (!allLiteral) {\n\t\t\t\tfullyStatic = false;\n\t\t\t}\n\t\t}\n\n\t\tconst constrained: ConstrainedToolSchema = {\n\t\t\tinputSchema: {\n\t\t\t\trequired: requiredKeys.sort(),\n\t\t\t\tproperties: constrainedProperties,\n\t\t\t},\n\t\t\tfullyStatic,\n\t\t\tcallSites: callSites.map((s) => s.stepId).sort(),\n\t\t};\n\n\t\tif (toolDef.outputSchema) {\n\t\t\tconstrained.outputSchema = toolDef.outputSchema;\n\t\t}\n\n\t\tresult[toolName] = constrained;\n\t}\n\n\t// Agent-loop tools are used dynamically — the agent decides what inputs\n\t// to pass at runtime. Mark them as not fully static and add call sites.\n\tfor (const step of workflow.steps) {\n\t\tif (step.type !== \"agent-loop\") continue;\n\t\tfor (const toolName of step.params.tools) {\n\t\t\tif (result[toolName]) {\n\t\t\t\tresult[toolName].fullyStatic = false;\n\t\t\t\tif (!result[toolName].callSites.includes(step.id)) {\n\t\t\t\t\tresult[toolName].callSites.push(step.id);\n\t\t\t\t\tresult[toolName].callSites.sort();\n\t\t\t\t}\n\t\t\t} else if (tools[toolName]) {\n\t\t\t\t// Tool is only used by agent-loop, not by any tool-call step\n\t\t\t\tconst toolDef = tools[toolName];\n\t\t\t\tconst constrained: ConstrainedToolSchema = {\n\t\t\t\t\tinputSchema: {\n\t\t\t\t\t\trequired: [],\n\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t},\n\t\t\t\t\tfullyStatic: false,\n\t\t\t\t\tcallSites: [step.id],\n\t\t\t\t};\n\t\t\t\tif (toolDef.outputSchema) {\n\t\t\t\t\tconstrained.outputSchema = toolDef.outputSchema;\n\t\t\t\t}\n\t\t\t\tresult[toolName] = constrained;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n",
|
|
10
|
+
"import type { WorkflowDefinition, WorkflowStep } from \"../../types\";\nimport type { ExecutionGraph, ToolDefinitionMap } from \"../types\";\n\n/**\n * Parse a simple dotted JMESPath expression (e.g. \"step_id.field.nested\")\n * into path segments. Returns null for complex expressions (filters,\n * projections, functions, etc.).\n */\nexport function parseSimplePath(expression: string): string[] | null {\n\tif (!/^[a-zA-Z_][a-zA-Z0-9_]*(\\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(expression)) {\n\t\treturn null;\n\t}\n\treturn expression.split(\".\");\n}\n\n/**\n * Walk a JSON Schema along a dotted path, resolving through `properties`\n * at each segment. Returns null if the path can't be resolved.\n */\nexport function resolvePath(\n\tschema: Record<string, unknown>,\n\tpath: string[],\n): Record<string, unknown> | null {\n\tlet current = schema;\n\tfor (const segment of path) {\n\t\tconst properties = current.properties as\n\t\t\t| Record<string, Record<string, unknown>>\n\t\t\t| undefined;\n\t\tif (!properties?.[segment]) return null;\n\t\tcurrent = properties[segment];\n\t}\n\treturn current;\n}\n\n/**\n * Extract the `type` string from a JSON Schema object.\n */\nexport function getSchemaType(schema: Record<string, unknown>): string | null {\n\tif (typeof schema.type === \"string\") return schema.type;\n\treturn null;\n}\n\n/**\n * Find property names in a schema that are arrays.\n */\nexport function findArrayProperties(schema: Record<string, unknown>): string[] {\n\tconst properties = schema.properties as\n\t\t| Record<string, Record<string, unknown>>\n\t\t| undefined;\n\tif (!properties) return [];\n\treturn Object.entries(properties)\n\t\t.filter(([_, propSchema]) => propSchema.type === \"array\")\n\t\t.map(([name]) => name);\n}\n\n/**\n * Resolve the output schema of a workflow step. Returns null if the\n * output schema is unknown or can't be determined statically.\n */\nexport function getStepOutputSchema(\n\tstep: WorkflowStep,\n\ttools: ToolDefinitionMap | null,\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n): Record<string, unknown> | null {\n\tswitch (step.type) {\n\t\tcase \"tool-call\": {\n\t\t\tif (!tools) return null;\n\t\t\tconst toolDef = tools[step.params.toolName];\n\t\t\treturn toolDef?.outputSchema ?? null;\n\t\t}\n\t\tcase \"llm-prompt\":\n\t\tcase \"extract-data\":\n\t\tcase \"agent-loop\":\n\t\t\treturn (step.params.outputFormat as Record<string, unknown>) ?? null;\n\t\tcase \"for-each\": {\n\t\t\t// for-each produces an array whose items have the shape of the loop body's last output\n\t\t\tconst bodyItemSchema = resolveChainOutputSchema(\n\t\t\t\tstep.params.loopBodyStepId,\n\t\t\t\ttools,\n\t\t\t\tworkflow,\n\t\t\t\tgraph,\n\t\t\t);\n\t\t\tif (!bodyItemSchema) return null;\n\t\t\treturn { type: \"array\", items: bodyItemSchema };\n\t\t}\n\t\tcase \"switch-case\":\n\t\t\t// Can't statically determine which branch runs; return null\n\t\t\t// (individual branches are checked separately via output points)\n\t\t\treturn null;\n\t\tcase \"start\":\n\t\t\treturn null;\n\t\tcase \"end\":\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Resolve the output schema that a chain produces by walking it to its\n * terminal step and returning that step's output schema.\n */\nfunction resolveChainOutputSchema(\n\tstartId: string,\n\ttools: ToolDefinitionMap | null,\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n): Record<string, unknown> | null {\n\tlet currentId: string | undefined = startId;\n\tconst visited = new Set<string>();\n\n\twhile (currentId) {\n\t\tif (visited.has(currentId)) break;\n\t\tvisited.add(currentId);\n\n\t\tconst step = graph.stepIndex.get(currentId);\n\t\tif (!step) break;\n\n\t\tif (!step.nextStepId) {\n\t\t\treturn getStepOutputSchema(step, tools, workflow, graph);\n\t\t}\n\n\t\tcurrentId = step.nextStepId;\n\t}\n\n\treturn null;\n}\n\n/**\n * Resolve a JMESPath output expression to a JSON Schema by tracing\n * through step output schemas. Only handles simple dotted paths.\n * Returns null for complex expressions or when schemas are unavailable.\n */\nexport function resolveExpressionSchema(\n\texpression: string,\n\t_endStepId: string,\n\ttools: ToolDefinitionMap | null,\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n): Record<string, unknown> | null {\n\tconst segments = parseSimplePath(expression);\n\tif (!segments) return null;\n\n\tconst [rootId, ...fieldPath] = segments;\n\tif (!rootId) return null;\n\n\tlet rootSchema: Record<string, unknown> | null = null;\n\tif (rootId === \"input\" && workflow.inputSchema) {\n\t\trootSchema = workflow.inputSchema as Record<string, unknown>;\n\t} else {\n\t\tconst referencedStep = graph.stepIndex.get(rootId);\n\t\tif (!referencedStep) return null;\n\t\trootSchema = getStepOutputSchema(referencedStep, tools, workflow, graph);\n\t}\n\n\tif (!rootSchema) return null;\n\n\tif (fieldPath.length === 0) return rootSchema;\n\treturn resolvePath(rootSchema, fieldPath);\n}\n",
|
|
11
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type { Diagnostic, ExecutionGraph, ToolDefinitionMap } from \"../types\";\nimport { resolveExpressionSchema } from \"../utils/schema\";\n\nexport function validateControlFlow(\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n\ttools?: ToolDefinitionMap | null,\n): Diagnostic[] {\n\tconst diagnostics: Diagnostic[] = [];\n\n\tfor (const step of workflow.steps) {\n\t\t// End steps should not have nextStepId\n\t\tif (step.type === \"end\" && step.nextStepId) {\n\t\t\tdiagnostics.push({\n\t\t\t\tseverity: \"error\",\n\t\t\t\tlocation: { stepId: step.id, field: \"nextStepId\" },\n\t\t\t\tmessage: `End step '${step.id}' should not have a nextStepId`,\n\t\t\t\tcode: \"END_STEP_HAS_NEXT\",\n\t\t\t});\n\t\t}\n\n\t\t// Switch-case: at most one default case\n\t\tif (step.type === \"switch-case\") {\n\t\t\tconst defaultCount = step.params.cases.filter(\n\t\t\t\t(c) => c.value.type === \"default\",\n\t\t\t).length;\n\t\t\tif (defaultCount > 1) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId: step.id, field: \"params.cases\" },\n\t\t\t\t\tmessage: `Switch-case step '${step.id}' has ${defaultCount} default cases (expected at most 1)`,\n\t\t\t\t\tcode: \"MULTIPLE_DEFAULT_CASES\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Validate branch bodies don't escape\n\t\t\tfor (const [i, c] of step.params.cases.entries()) {\n\t\t\t\tconst escapes = checkBodyEscapes(c.branchBodyStepId, step.id, graph);\n\t\t\t\tif (escapes) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\tlocation: {\n\t\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\t\tfield: `params.cases[${i}].branchBodyStepId`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmessage: `Branch body starting at '${c.branchBodyStepId}' in step '${step.id}' has a step ('${escapes.escapingStep}') whose nextStepId points outside the branch body to '${escapes.target}'`,\n\t\t\t\t\t\tcode: \"BRANCH_BODY_ESCAPES\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// For-each: validate loop body doesn't escape\n\t\tif (step.type === \"for-each\") {\n\t\t\tconst escapes = checkBodyEscapes(\n\t\t\t\tstep.params.loopBodyStepId,\n\t\t\t\tstep.id,\n\t\t\t\tgraph,\n\t\t\t);\n\t\t\tif (escapes) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tlocation: {\n\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\tfield: \"params.loopBodyStepId\",\n\t\t\t\t\t},\n\t\t\t\t\tmessage: `Loop body starting at '${step.params.loopBodyStepId}' in step '${step.id}' has a step ('${escapes.escapingStep}') whose nextStepId points outside the loop body to '${escapes.target}'`,\n\t\t\t\t\tcode: \"LOOP_BODY_ESCAPES\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Wait-for-condition: validate condition body doesn't escape\n\t\tif (step.type === \"wait-for-condition\") {\n\t\t\tconst escapes = checkBodyEscapes(\n\t\t\t\tstep.params.conditionStepId,\n\t\t\t\tstep.id,\n\t\t\t\tgraph,\n\t\t\t);\n\t\t\tif (escapes) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tlocation: {\n\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\tfield: \"params.conditionStepId\",\n\t\t\t\t\t},\n\t\t\t\t\tmessage: `Condition body starting at '${step.params.conditionStepId}' in step '${step.id}' has a step ('${escapes.escapingStep}') whose nextStepId points outside the condition body to '${escapes.target}'`,\n\t\t\t\t\tcode: \"CONDITION_BODY_ESCAPES\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Output consistency checks\n\tif (workflow.outputSchema) {\n\t\t// Check that all execution paths reach an end step with a valid output expression\n\t\tconst outputPoints = findWorkflowOutputPoints(\n\t\t\tworkflow.initialStepId,\n\t\t\tgraph,\n\t\t);\n\t\tfor (const point of outputPoints) {\n\t\t\tif (point.type === \"missing_end\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId: point.stepId, field: \"nextStepId\" },\n\t\t\t\t\tmessage: `Step '${point.stepId}' is a terminal step but is not an end step; all execution paths must terminate at an end step when outputSchema is declared`,\n\t\t\t\t\tcode: \"PATH_MISSING_END_STEP\",\n\t\t\t\t});\n\t\t\t} else if (point.type === \"end_without_output\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId: point.stepId, field: \"params\" },\n\t\t\t\t\tmessage: `End step '${point.stepId}' has no output expression, but the workflow declares an outputSchema`,\n\t\t\t\t\tcode: \"END_STEP_MISSING_OUTPUT\",\n\t\t\t\t});\n\t\t\t} else if (point.type === \"end_with_output\") {\n\t\t\t\t// Validate output shapes against outputSchema at compile time\n\t\t\t\tconst step = graph.stepIndex.get(point.stepId);\n\t\t\t\tif (step?.type === \"end\" && step.params?.output) {\n\t\t\t\t\tconst expr = step.params.output;\n\t\t\t\t\tconst outputSchema = workflow.outputSchema as Record<string, unknown>;\n\t\t\t\t\tif (expr.type === \"literal\") {\n\t\t\t\t\t\tdiagnostics.push(\n\t\t\t\t\t\t\t...validateOutputShapeMismatch(\n\t\t\t\t\t\t\t\texpr.value,\n\t\t\t\t\t\t\t\toutputSchema,\n\t\t\t\t\t\t\t\tpoint.stepId,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (expr.type === \"jmespath\") {\n\t\t\t\t\t\tconst resolvedSchema = resolveExpressionSchema(\n\t\t\t\t\t\t\texpr.expression,\n\t\t\t\t\t\t\tpoint.stepId,\n\t\t\t\t\t\t\ttools ?? null,\n\t\t\t\t\t\t\tworkflow,\n\t\t\t\t\t\t\tgraph,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (resolvedSchema) {\n\t\t\t\t\t\t\tdiagnostics.push(\n\t\t\t\t\t\t\t\t...validateSchemaCompatibility(\n\t\t\t\t\t\t\t\t\tresolvedSchema,\n\t\t\t\t\t\t\t\t\toutputSchema,\n\t\t\t\t\t\t\t\t\tpoint.stepId,\n\t\t\t\t\t\t\t\t\texpr.expression,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (const step of workflow.steps) {\n\t\t\tif (step.type === \"end\" && step.params?.output) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tlocation: { stepId: step.id, field: \"params.output\" },\n\t\t\t\t\tmessage: `End step '${step.id}' has an output expression, but the workflow does not declare an outputSchema`,\n\t\t\t\t\tcode: \"END_STEP_UNEXPECTED_OUTPUT\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Check if a body chain (loop body or branch body) has a step whose\n * nextStepId points outside the body. Follow the chain from startId\n * through nextStepId links; all steps in this chain should be owned\n * by parentStepId.\n */\nfunction checkBodyEscapes(\n\tstartId: string,\n\tparentStepId: string,\n\tgraph: ExecutionGraph,\n): { escapingStep: string; target: string } | null {\n\tlet currentId: string | undefined = startId;\n\tconst visited = new Set<string>();\n\n\twhile (currentId) {\n\t\tif (visited.has(currentId)) break;\n\t\tvisited.add(currentId);\n\n\t\tconst step = graph.stepIndex.get(currentId);\n\t\tif (!step) break;\n\n\t\tif (step.nextStepId) {\n\t\t\t// Check if the next step is still owned by the same parent\n\t\t\tconst nextOwner = graph.bodyOwnership.get(step.nextStepId);\n\t\t\tconst currentOwner = graph.bodyOwnership.get(currentId);\n\n\t\t\t// The next step is escaping if:\n\t\t\t// 1. The current step is in the body (owned by parentStepId)\n\t\t\t// 2. The next step is NOT in the body (not owned by parentStepId)\n\t\t\tif (\n\t\t\t\t(currentOwner === parentStepId || currentId === startId) &&\n\t\t\t\tnextOwner !== parentStepId\n\t\t\t) {\n\t\t\t\treturn { escapingStep: currentId, target: step.nextStepId };\n\t\t\t}\n\t\t}\n\n\t\tcurrentId = step.nextStepId;\n\t}\n\n\treturn null;\n}\n\ntype OutputPoint =\n\t| { type: \"end_with_output\"; stepId: string }\n\t| { type: \"end_without_output\"; stepId: string }\n\t| { type: \"missing_end\"; stepId: string };\n\n/**\n * Find all workflow output points — the terminal positions where execution\n * stops and produces the workflow's final output. This walks the main chain\n * and recurses into branch/loop bodies when they are terminal (the parent\n * step has no nextStepId).\n */\nfunction findWorkflowOutputPoints(\n\tstartId: string,\n\tgraph: ExecutionGraph,\n): OutputPoint[] {\n\treturn collectOutputPoints(startId, graph, new Set());\n}\n\nfunction collectOutputPoints(\n\tstartId: string,\n\tgraph: ExecutionGraph,\n\tvisited: Set<string>,\n): OutputPoint[] {\n\tconst points: OutputPoint[] = [];\n\tlet currentId: string | undefined = startId;\n\n\twhile (currentId) {\n\t\tif (visited.has(currentId)) break;\n\t\tvisited.add(currentId);\n\n\t\tconst step = graph.stepIndex.get(currentId);\n\t\tif (!step) break;\n\n\t\tif (!step.nextStepId) {\n\t\t\t// This is a terminal step on this chain\n\t\t\tif (step.type === \"end\") {\n\t\t\t\tpoints.push({\n\t\t\t\t\ttype: step.params?.output ? \"end_with_output\" : \"end_without_output\",\n\t\t\t\t\tstepId: step.id,\n\t\t\t\t});\n\t\t\t} else if (step.type === \"switch-case\") {\n\t\t\t\t// Terminal switch-case: each branch is an output point\n\t\t\t\tfor (const c of step.params.cases) {\n\t\t\t\t\tpoints.push(\n\t\t\t\t\t\t...collectOutputPoints(c.branchBodyStepId, graph, visited),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (step.type === \"for-each\") {\n\t\t\t\t// Terminal for-each: loop body determines output shape\n\t\t\t\tpoints.push(\n\t\t\t\t\t...collectOutputPoints(step.params.loopBodyStepId, graph, visited),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Non-end, non-branching terminal step — path doesn't reach an end step\n\t\t\t\tpoints.push({ type: \"missing_end\", stepId: step.id });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcurrentId = step.nextStepId;\n\t}\n\n\treturn points;\n}\n\n/**\n * Validate a literal output value against the outputSchema at compile time.\n */\nfunction validateOutputShapeMismatch(\n\tvalue: unknown,\n\tschema: Record<string, unknown>,\n\tstepId: string,\n): Diagnostic[] {\n\tconst diagnostics: Diagnostic[] = [];\n\tconst expectedType = schema.type;\n\n\tif (typeof expectedType !== \"string\") return diagnostics;\n\n\tconst actualType = getValueType(value);\n\tif (expectedType !== actualType) {\n\t\tdiagnostics.push({\n\t\t\tseverity: \"error\",\n\t\t\tlocation: { stepId, field: \"params.output\" },\n\t\t\tmessage: `End step '${stepId}' output literal has type '${actualType}' but outputSchema expects '${expectedType}'`,\n\t\t\tcode: \"LITERAL_OUTPUT_SHAPE_MISMATCH\",\n\t\t});\n\t\treturn diagnostics;\n\t}\n\n\t// For objects, validate required fields and property types\n\tif (\n\t\texpectedType === \"object\" &&\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value)\n\t) {\n\t\tconst obj = value as Record<string, unknown>;\n\t\tconst required = schema.required;\n\t\tif (Array.isArray(required)) {\n\t\t\tconst missing = required.filter(\n\t\t\t\t(key: unknown) => typeof key === \"string\" && !((key as string) in obj),\n\t\t\t);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId, field: \"params.output\" },\n\t\t\t\t\tmessage: `End step '${stepId}' output literal is missing required field(s): ${missing.join(\", \")}`,\n\t\t\t\t\tcode: \"LITERAL_OUTPUT_SHAPE_MISMATCH\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst properties = schema.properties;\n\t\tif (properties && typeof properties === \"object\") {\n\t\t\tfor (const [key, val] of Object.entries(obj)) {\n\t\t\t\tconst propSchema = (properties as Record<string, unknown>)[key];\n\t\t\t\tif (\n\t\t\t\t\tpropSchema &&\n\t\t\t\t\ttypeof propSchema === \"object\" &&\n\t\t\t\t\t\"type\" in propSchema\n\t\t\t\t) {\n\t\t\t\t\tconst propExpected = (propSchema as { type: string }).type;\n\t\t\t\t\tconst propActual = getValueType(val);\n\t\t\t\t\tif (propExpected !== propActual) {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\t\tlocation: { stepId, field: \"params.output\" },\n\t\t\t\t\t\t\tmessage: `End step '${stepId}' output literal field '${key}' has type '${propActual}' but schema expects '${propExpected}'`,\n\t\t\t\t\t\t\tcode: \"LITERAL_OUTPUT_SHAPE_MISMATCH\",\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diagnostics;\n}\n\nfunction getValueType(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"array\";\n\treturn typeof value;\n}\n\n/**\n * Validate that a resolved JMESPath expression schema is compatible with\n * the declared outputSchema. Checks root type and, for objects, required\n * fields and property types.\n */\nfunction validateSchemaCompatibility(\n\tresolvedSchema: Record<string, unknown>,\n\toutputSchema: Record<string, unknown>,\n\tstepId: string,\n\texpression: string,\n): Diagnostic[] {\n\tconst diagnostics: Diagnostic[] = [];\n\tconst expectedType = outputSchema.type;\n\tconst resolvedType = resolvedSchema.type;\n\n\tif (typeof expectedType !== \"string\" || typeof resolvedType !== \"string\") {\n\t\treturn diagnostics;\n\t}\n\n\t// Root type check\n\tif (expectedType !== resolvedType) {\n\t\tdiagnostics.push({\n\t\t\tseverity: \"error\",\n\t\t\tlocation: { stepId, field: \"params.output\" },\n\t\t\tmessage: `End step '${stepId}' output expression '${expression}' resolves to type '${resolvedType}' but outputSchema expects '${expectedType}'`,\n\t\t\tcode: \"LITERAL_OUTPUT_SHAPE_MISMATCH\",\n\t\t});\n\t\treturn diagnostics;\n\t}\n\n\t// For objects, check required fields and property types\n\tif (expectedType === \"object\") {\n\t\tconst expectedRequired = outputSchema.required;\n\t\tconst resolvedProps = (resolvedSchema.properties ?? {}) as Record<\n\t\t\tstring,\n\t\t\tRecord<string, unknown>\n\t\t>;\n\n\t\tif (Array.isArray(expectedRequired)) {\n\t\t\tconst missing = expectedRequired.filter(\n\t\t\t\t(key: unknown) =>\n\t\t\t\t\ttypeof key === \"string\" && !((key as string) in resolvedProps),\n\t\t\t);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId, field: \"params.output\" },\n\t\t\t\t\tmessage: `End step '${stepId}' output expression '${expression}' schema is missing required field(s): ${missing.join(\", \")}`,\n\t\t\t\t\tcode: \"LITERAL_OUTPUT_SHAPE_MISMATCH\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst expectedProps = (outputSchema.properties ?? {}) as Record<\n\t\t\tstring,\n\t\t\tRecord<string, unknown>\n\t\t>;\n\t\tfor (const [key, expectedPropSchema] of Object.entries(expectedProps)) {\n\t\t\tconst resolvedPropSchema = resolvedProps[key];\n\t\t\tif (!resolvedPropSchema) continue;\n\t\t\tconst expectedPropType = expectedPropSchema.type;\n\t\t\tconst resolvedPropType = resolvedPropSchema.type;\n\t\t\tif (\n\t\t\t\ttypeof expectedPropType === \"string\" &&\n\t\t\t\ttypeof resolvedPropType === \"string\" &&\n\t\t\t\texpectedPropType !== resolvedPropType\n\t\t\t) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId, field: \"params.output\" },\n\t\t\t\t\tmessage: `End step '${stepId}' output expression '${expression}' field '${key}' has type '${resolvedPropType}' but outputSchema expects '${expectedPropType}'`,\n\t\t\t\t\tcode: \"LITERAL_OUTPUT_SHAPE_MISMATCH\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diagnostics;\n}\n",
|
|
12
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type { Diagnostic, ExecutionGraph, ToolDefinitionMap } from \"../types\";\nimport {\n\tfindArrayProperties,\n\tgetSchemaType,\n\tgetStepOutputSchema,\n\tparseSimplePath,\n\tresolvePath,\n} from \"../utils/schema\";\n\nexport function validateForeachTarget(\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n\ttools: ToolDefinitionMap,\n): Diagnostic[] {\n\tconst diagnostics: Diagnostic[] = [];\n\n\tfor (const step of workflow.steps) {\n\t\tif (step.type !== \"for-each\") continue;\n\t\tif (step.params.target.type !== \"jmespath\") continue;\n\n\t\tconst expression = step.params.target.expression;\n\n\t\t// Only handle simple dotted paths (e.g. \"step_id\" or \"step_id.field\")\n\t\tconst segments = parseSimplePath(expression);\n\t\tif (!segments) continue;\n\n\t\tconst [rootId, ...fieldPath] = segments;\n\t\tif (!rootId) continue;\n\n\t\tlet outputSchema: Record<string, unknown> | null = null;\n\t\tif (rootId === \"input\" && workflow.inputSchema) {\n\t\t\toutputSchema = workflow.inputSchema as Record<string, unknown>;\n\t\t} else {\n\t\t\tconst referencedStep = graph.stepIndex.get(rootId);\n\t\t\tif (!referencedStep) continue; // Handled by jmespath validation\n\t\t\toutputSchema = getStepOutputSchema(\n\t\t\t\treferencedStep,\n\t\t\t\ttools,\n\t\t\t\tworkflow,\n\t\t\t\tgraph,\n\t\t\t);\n\t\t}\n\t\tif (!outputSchema) continue;\n\n\t\tconst resolvedSchema = resolvePath(outputSchema, fieldPath);\n\t\tif (!resolvedSchema) continue;\n\n\t\tconst resolvedType = getSchemaType(resolvedSchema);\n\t\tif (resolvedType === \"array\") continue;\n\n\t\tif (resolvedType === \"object\") {\n\t\t\tconst suggestions = findArrayProperties(resolvedSchema);\n\t\t\tconst hint =\n\t\t\t\tsuggestions.length > 0\n\t\t\t\t\t? ` Did you mean ${suggestions.map((s) => `'${rootId}.${s}'`).join(\" or \")}?`\n\t\t\t\t\t: \"\";\n\n\t\t\tdiagnostics.push({\n\t\t\t\tseverity: \"error\",\n\t\t\t\tlocation: { stepId: step.id, field: \"params.target\" },\n\t\t\t\tmessage: `for-each target '${expression}' resolves to an object, not an array.${hint}`,\n\t\t\t\tcode: \"FOREACH_TARGET_NOT_ARRAY\",\n\t\t\t});\n\t\t} else if (resolvedType !== null) {\n\t\t\tdiagnostics.push({\n\t\t\t\tseverity: \"error\",\n\t\t\t\tlocation: { stepId: step.id, field: \"params.target\" },\n\t\t\t\tmessage: `for-each target '${expression}' resolves to type '${resolvedType}', not an array.`,\n\t\t\t\tcode: \"FOREACH_TARGET_NOT_ARRAY\",\n\t\t\t});\n\t\t}\n\t}\n\n\treturn diagnostics;\n}\n",
|
|
13
|
+
"import { compile } from \"@jmespath-community/jmespath\";\n\n/**\n * Validate that a JMESPath expression is syntactically valid.\n */\nexport function validateJmespathSyntax(\n\texpression: string,\n): { valid: true } | { valid: false; error: string } {\n\ttry {\n\t\tcompile(expression);\n\t\treturn { valid: true };\n\t} catch (e) {\n\t\treturn { valid: false, error: (e as Error).message };\n\t}\n}\n\ninterface ASTNode {\n\ttype: string;\n\tname?: string;\n\tleft?: ASTNode;\n\tright?: ASTNode;\n\tchildren?: ASTNode[];\n\tcondition?: ASTNode;\n\t[key: string]: unknown;\n}\n\n/**\n * Extract root identifiers from a JMESPath AST.\n * A \"root identifier\" is a Field node that represents a top-level\n * reference (e.g., `stepId` in `stepId.field`, `foo` in `length(foo.bar)`).\n *\n * We walk the AST and collect Field nodes that appear in \"root position\" —\n * meaning they are the leftmost leaf in a chain of Subexpressions,\n * or standalone fields, or the first field in a function argument.\n */\nexport function extractRootIdentifiers(expression: string): string[] {\n\tlet ast: ASTNode;\n\ttry {\n\t\tast = compile(expression) as unknown as ASTNode;\n\t} catch {\n\t\treturn [];\n\t}\n\n\tconst roots = new Set<string>();\n\tcollectRoots(ast, roots);\n\treturn [...roots];\n}\n\nfunction collectRoots(node: ASTNode, roots: Set<string>): void {\n\tif (!node || typeof node !== \"object\") return;\n\n\tswitch (node.type) {\n\t\tcase \"Field\":\n\t\t\t// Standalone field — this IS a root reference\n\t\t\tif (node.name) roots.add(node.name);\n\t\t\tbreak;\n\n\t\tcase \"Subexpression\":\n\t\t\t// Only the leftmost field in the chain is a root\n\t\t\tif (node.left) collectLeftmostRoot(node.left, roots);\n\t\t\tbreak;\n\n\t\tcase \"FilterProjection\":\n\t\t\t// Only the left side contains root references.\n\t\t\t// The condition and right are relative to the filtered items,\n\t\t\t// NOT root-level references.\n\t\t\tif (node.left) collectLeftmostRoot(node.left, roots);\n\t\t\tbreak;\n\n\t\tcase \"Projection\":\n\t\tcase \"Flatten\":\n\t\t\t// The left side contains the root; right is relative\n\t\t\tif (node.left) collectLeftmostRoot(node.left, roots);\n\t\t\tbreak;\n\n\t\tcase \"Function\":\n\t\t\t// Recurse into function arguments\n\t\t\tif (node.children) {\n\t\t\t\tfor (const child of node.children) {\n\t\t\t\t\tcollectRoots(child, roots);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase \"MultiSelectList\":\n\t\tcase \"MultiSelectHash\":\n\t\t\tif (node.children) {\n\t\t\t\tfor (const child of node.children) {\n\t\t\t\t\tcollectRoots(child, roots);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase \"Comparator\":\n\t\tcase \"And\":\n\t\tcase \"Or\":\n\t\tcase \"Arithmetic\":\n\t\t\tif (node.left) collectRoots(node.left, roots);\n\t\t\tif (node.right) collectRoots(node.right, roots);\n\t\t\tbreak;\n\n\t\tcase \"Not\":\n\t\tcase \"Negate\":\n\t\t\tif (node.children?.[0]) collectRoots(node.children[0], roots);\n\t\t\tbreak;\n\n\t\tcase \"Pipe\":\n\t\t\t// Only the left side of a pipe has root references from the data\n\t\t\tif (node.left) collectRoots(node.left, roots);\n\t\t\tbreak;\n\n\t\tcase \"IndexExpression\":\n\t\t\tif (node.left) collectLeftmostRoot(node.left, roots);\n\t\t\tbreak;\n\n\t\tcase \"ValueProjection\":\n\t\tcase \"Slice\":\n\t\t\tif (node.left) collectLeftmostRoot(node.left, roots);\n\t\t\tbreak;\n\n\t\tcase \"Literal\":\n\t\tcase \"Current\":\n\t\tcase \"Identity\":\n\t\tcase \"Expref\":\n\t\t\t// No root references\n\t\t\tbreak;\n\n\t\tcase \"KeyValuePair\": {\n\t\t\tconst kvValue = (node as Record<string, ASTNode>).value;\n\t\t\tif (kvValue) {\n\t\t\t\tcollectRoots(kvValue, roots);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\t// Unknown node type — try to recurse into known fields\n\t\t\tif (node.left) collectRoots(node.left, roots);\n\t\t\tif (node.right) collectRoots(node.right, roots);\n\t\t\tif (node.children) {\n\t\t\t\tfor (const child of node.children) {\n\t\t\t\t\tcollectRoots(child, roots);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Follow the left side of subexpressions/projections to find the\n * leftmost root field.\n */\nfunction collectLeftmostRoot(node: ASTNode, roots: Set<string>): void {\n\tif (!node) return;\n\n\tswitch (node.type) {\n\t\tcase \"Field\":\n\t\t\tif (node.name) roots.add(node.name);\n\t\t\tbreak;\n\t\tcase \"Subexpression\":\n\t\t\tif (node.left) collectLeftmostRoot(node.left, roots);\n\t\t\tbreak;\n\t\tcase \"FilterProjection\":\n\t\tcase \"Projection\":\n\t\tcase \"Flatten\":\n\t\tcase \"IndexExpression\":\n\t\tcase \"ValueProjection\":\n\t\tcase \"Slice\":\n\t\t\tif (node.left) collectLeftmostRoot(node.left, roots);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t// For other types (like Arithmetic for hyphenated IDs), fall through\n\t\t\tcollectRoots(node, roots);\n\t\t\tbreak;\n\t}\n}\n\nexport interface TemplateExpression {\n\texpression: string;\n\tstart: number;\n\tend: number;\n}\n\nexport interface TemplateExtractionResult {\n\texpressions: TemplateExpression[];\n\tunclosed: number[]; // start positions of unclosed ${\n}\n\n/**\n * Extract all ${...} template expressions from an llm-prompt template string.\n * Also reports positions of unclosed ${ sequences.\n */\nexport function extractTemplateExpressions(\n\ttemplate: string,\n): TemplateExtractionResult {\n\tconst expressions: TemplateExpression[] = [];\n\tconst unclosed: number[] = [];\n\tlet i = 0;\n\n\twhile (i < template.length) {\n\t\tif (template[i] === \"$\" && template[i + 1] === \"{\") {\n\t\t\tconst start = i;\n\t\t\ti += 2; // Skip ${\n\t\t\tlet depth = 1;\n\t\t\tconst exprStart = i;\n\n\t\t\twhile (i < template.length && depth > 0) {\n\t\t\t\tif (template[i] === \"{\") depth++;\n\t\t\t\telse if (template[i] === \"}\") depth--;\n\t\t\t\tif (depth > 0) i++;\n\t\t\t}\n\n\t\t\tif (depth === 0) {\n\t\t\t\tconst expression = template.slice(exprStart, i);\n\t\t\t\texpressions.push({ expression, start, end: i + 1 });\n\t\t\t\ti++; // Skip closing }\n\t\t\t} else {\n\t\t\t\tunclosed.push(start);\n\t\t\t}\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n\n\treturn { expressions, unclosed };\n}\n",
|
|
14
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type { Diagnostic, ExecutionGraph } from \"../types\";\nimport {\n\textractRootIdentifiers,\n\textractTemplateExpressions,\n\tvalidateJmespathSyntax,\n} from \"../utils/jmespath-helpers\";\n\ninterface ExpressionInfo {\n\texpression: string;\n\tstepId: string;\n\tfield: string;\n}\n\nexport function validateJmespath(\n\tworkflow: WorkflowDefinition,\n\tgraph: ExecutionGraph,\n): Diagnostic[] {\n\tconst diagnostics: Diagnostic[] = [];\n\n\t// Collect all JMESPath expressions with location info\n\tconst { expressions, templateDiagnostics } = collectExpressions(workflow);\n\tdiagnostics.push(...templateDiagnostics);\n\n\tfor (const expr of expressions) {\n\t\t// Syntax validation\n\t\tconst syntaxResult = validateJmespathSyntax(expr.expression);\n\t\tif (!syntaxResult.valid) {\n\t\t\tdiagnostics.push({\n\t\t\t\tseverity: \"error\",\n\t\t\t\tlocation: { stepId: expr.stepId, field: expr.field },\n\t\t\t\tmessage: `Invalid JMESPath syntax in '${expr.expression}': ${syntaxResult.error}`,\n\t\t\t\tcode: \"JMESPATH_SYNTAX_ERROR\",\n\t\t\t});\n\t\t\tcontinue; // Can't do scope validation on invalid syntax\n\t\t}\n\n\t\t// Scope/reference validation\n\t\tvalidateExpressionScope(expr, graph, !!workflow.inputSchema, diagnostics);\n\t}\n\n\treturn diagnostics;\n}\n\nfunction collectFromExpressionValue(\n\tval: { type: string; expression?: string; template?: string },\n\tstepId: string,\n\tfield: string,\n\texpressions: ExpressionInfo[],\n\ttemplateDiagnostics: Diagnostic[],\n): void {\n\tif (val.type === \"jmespath\" && val.expression) {\n\t\texpressions.push({\n\t\t\texpression: val.expression,\n\t\t\tstepId,\n\t\t\tfield: `${field}.expression`,\n\t\t});\n\t} else if (val.type === \"template\" && val.template) {\n\t\tconst { expressions: templateExprs, unclosed } = extractTemplateExpressions(\n\t\t\tval.template,\n\t\t);\n\t\tfor (const te of templateExprs) {\n\t\t\texpressions.push({\n\t\t\t\texpression: te.expression,\n\t\t\t\tstepId,\n\t\t\t\tfield: `${field}.template[${te.start}:${te.end}]`,\n\t\t\t});\n\t\t}\n\t\tfor (const pos of unclosed) {\n\t\t\ttemplateDiagnostics.push({\n\t\t\t\tseverity: \"error\",\n\t\t\t\tlocation: { stepId, field: `${field}.template[${pos}]` },\n\t\t\t\tmessage: `Unclosed template expression at position ${pos} in template`,\n\t\t\t\tcode: \"UNCLOSED_TEMPLATE_EXPRESSION\",\n\t\t\t});\n\t\t}\n\t}\n}\n\nfunction collectExpressions(workflow: WorkflowDefinition): {\n\texpressions: ExpressionInfo[];\n\ttemplateDiagnostics: Diagnostic[];\n} {\n\tconst expressions: ExpressionInfo[] = [];\n\tconst templateDiagnostics: Diagnostic[] = [];\n\n\tfor (const step of workflow.steps) {\n\t\tswitch (step.type) {\n\t\t\tcase \"tool-call\":\n\t\t\t\tfor (const [key, val] of Object.entries(step.params.toolInput)) {\n\t\t\t\t\tcollectFromExpressionValue(\n\t\t\t\t\t\tval,\n\t\t\t\t\t\tstep.id,\n\t\t\t\t\t\t`params.toolInput.${key}`,\n\t\t\t\t\t\texpressions,\n\t\t\t\t\t\ttemplateDiagnostics,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"switch-case\":\n\t\t\t\tcollectFromExpressionValue(\n\t\t\t\t\tstep.params.switchOn,\n\t\t\t\t\tstep.id,\n\t\t\t\t\t\"params.switchOn\",\n\t\t\t\t\texpressions,\n\t\t\t\t\ttemplateDiagnostics,\n\t\t\t\t);\n\t\t\t\tfor (const [i, c] of step.params.cases.entries()) {\n\t\t\t\t\tcollectFromExpressionValue(\n\t\t\t\t\t\tc.value,\n\t\t\t\t\t\tstep.id,\n\t\t\t\t\t\t`params.cases[${i}].value`,\n\t\t\t\t\t\texpressions,\n\t\t\t\t\t\ttemplateDiagnostics,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"for-each\":\n\t\t\t\tcollectFromExpressionValue(\n\t\t\t\t\tstep.params.target,\n\t\t\t\t\tstep.id,\n\t\t\t\t\t\"params.target\",\n\t\t\t\t\texpressions,\n\t\t\t\t\ttemplateDiagnostics,\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"extract-data\":\n\t\t\t\tcollectFromExpressionValue(\n\t\t\t\t\tstep.params.sourceData,\n\t\t\t\t\tstep.id,\n\t\t\t\t\t\"params.sourceData\",\n\t\t\t\t\texpressions,\n\t\t\t\t\ttemplateDiagnostics,\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"start\":\n\t\t\t\tbreak;\n\n\t\t\tcase \"end\":\n\t\t\t\tif (step.params?.output) {\n\t\t\t\t\tcollectFromExpressionValue(\n\t\t\t\t\t\tstep.params.output,\n\t\t\t\t\t\tstep.id,\n\t\t\t\t\t\t\"params.output\",\n\t\t\t\t\t\texpressions,\n\t\t\t\t\t\ttemplateDiagnostics,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"llm-prompt\": {\n\t\t\t\tconst { expressions: templateExprs, unclosed } =\n\t\t\t\t\textractTemplateExpressions(step.params.prompt);\n\t\t\t\tfor (const te of templateExprs) {\n\t\t\t\t\texpressions.push({\n\t\t\t\t\t\texpression: te.expression,\n\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\tfield: `params.prompt[${te.start}:${te.end}]`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (const pos of unclosed) {\n\t\t\t\t\ttemplateDiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: {\n\t\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\t\tfield: `params.prompt[${pos}]`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmessage: `Unclosed template expression at position ${pos} in prompt`,\n\t\t\t\t\t\tcode: \"UNCLOSED_TEMPLATE_EXPRESSION\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"agent-loop\": {\n\t\t\t\tconst { expressions: templateExprs, unclosed } =\n\t\t\t\t\textractTemplateExpressions(step.params.instructions);\n\t\t\t\tfor (const te of templateExprs) {\n\t\t\t\t\texpressions.push({\n\t\t\t\t\t\texpression: te.expression,\n\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\tfield: `params.instructions[${te.start}:${te.end}]`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (const pos of unclosed) {\n\t\t\t\t\ttemplateDiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: {\n\t\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\t\tfield: `params.instructions[${pos}]`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmessage: `Unclosed template expression at position ${pos} in instructions`,\n\t\t\t\t\t\tcode: \"UNCLOSED_TEMPLATE_EXPRESSION\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (step.params.maxSteps) {\n\t\t\t\t\tcollectFromExpressionValue(\n\t\t\t\t\t\tstep.params.maxSteps,\n\t\t\t\t\t\tstep.id,\n\t\t\t\t\t\t\"params.maxSteps\",\n\t\t\t\t\t\texpressions,\n\t\t\t\t\t\ttemplateDiagnostics,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { expressions, templateDiagnostics };\n}\n\nfunction validateExpressionScope(\n\texpr: ExpressionInfo,\n\tgraph: ExecutionGraph,\n\thasInputSchema: boolean,\n\tdiagnostics: Diagnostic[],\n): void {\n\tconst astRoots = extractRootIdentifiers(expr.expression);\n\tconst loopVars = graph.loopVariablesInScope.get(expr.stepId);\n\tconst predecessors = graph.predecessors.get(expr.stepId);\n\n\tfor (const root of astRoots) {\n\t\t// Skip if it's the workflow input alias\n\t\tif (root === \"input\" && hasInputSchema) continue;\n\n\t\t// Skip if it's a loop variable in scope\n\t\tif (loopVars?.has(root)) continue;\n\n\t\t// Check if it's a step ID\n\t\tif (graph.stepIndex.has(root)) {\n\t\t\t// Check if the step is a predecessor (has executed before this step)\n\t\t\tif (predecessors && !predecessors.has(root)) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tlocation: { stepId: expr.stepId, field: expr.field },\n\t\t\t\t\tmessage: `Expression '${expr.expression}' references step '${root}' which may not have executed before step '${expr.stepId}'`,\n\t\t\t\t\tcode: \"JMESPATH_FORWARD_REFERENCE\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tdiagnostics.push({\n\t\t\tseverity: \"error\",\n\t\t\tlocation: { stepId: expr.stepId, field: expr.field },\n\t\t\tmessage: `Expression '${expr.expression}' references '${root}' which is not a known step ID or loop variable in scope`,\n\t\t\tcode: \"JMESPATH_INVALID_ROOT_REFERENCE\",\n\t\t});\n\t}\n}\n",
|
|
15
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type { CompilerLimits, Diagnostic } from \"../types\";\n\nconst DEFAULT_LIMITS: Required<CompilerLimits> = {\n\tmaxAttempts: Number.POSITIVE_INFINITY,\n\tmaxSleepMs: 300_000, // 5 minutes\n\tmaxBackoffMultiplier: 2,\n\tminBackoffMultiplier: 1,\n\tmaxTimeoutMs: 600_000, // 10 minutes\n};\n\n/**\n * Validates literal values in sleep/wait-for-condition steps against\n * configured upper/lower bounds. Only checks expressions with\n * type === 'literal' — JMESPath expressions are unknown at compile time.\n */\nexport function validateLimits(\n\tworkflow: WorkflowDefinition,\n\tlimits?: CompilerLimits,\n): Diagnostic[] {\n\tconst resolved = { ...DEFAULT_LIMITS, ...limits };\n\tconst diagnostics: Diagnostic[] = [];\n\n\tfor (const step of workflow.steps) {\n\t\tif (step.type === \"sleep\") {\n\t\t\tconst expr = step.params.durationMs;\n\t\t\tif (expr.type === \"literal\" && typeof expr.value === \"number\") {\n\t\t\t\tif (expr.value > resolved.maxSleepMs) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: { stepId: step.id, field: \"params.durationMs\" },\n\t\t\t\t\t\tmessage: `Sleep duration ${expr.value}ms exceeds limit of ${resolved.maxSleepMs}ms`,\n\t\t\t\t\t\tcode: \"SLEEP_DURATION_EXCEEDS_LIMIT\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (step.type === \"wait-for-condition\") {\n\t\t\tconst { maxAttempts, intervalMs, backoffMultiplier, timeoutMs } =\n\t\t\t\tstep.params;\n\n\t\t\tif (\n\t\t\t\tmaxAttempts?.type === \"literal\" &&\n\t\t\t\ttypeof maxAttempts.value === \"number\"\n\t\t\t) {\n\t\t\t\tif (maxAttempts.value > resolved.maxAttempts) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: { stepId: step.id, field: \"params.maxAttempts\" },\n\t\t\t\t\t\tmessage: `maxAttempts ${maxAttempts.value} exceeds limit of ${resolved.maxAttempts}`,\n\t\t\t\t\t\tcode: \"WAIT_ATTEMPTS_EXCEEDS_LIMIT\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tintervalMs?.type === \"literal\" &&\n\t\t\t\ttypeof intervalMs.value === \"number\"\n\t\t\t) {\n\t\t\t\tif (intervalMs.value > resolved.maxSleepMs) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: { stepId: step.id, field: \"params.intervalMs\" },\n\t\t\t\t\t\tmessage: `intervalMs ${intervalMs.value}ms exceeds limit of ${resolved.maxSleepMs}ms`,\n\t\t\t\t\t\tcode: \"WAIT_INTERVAL_EXCEEDS_LIMIT\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tbackoffMultiplier?.type === \"literal\" &&\n\t\t\t\ttypeof backoffMultiplier.value === \"number\"\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\tbackoffMultiplier.value < resolved.minBackoffMultiplier ||\n\t\t\t\t\tbackoffMultiplier.value > resolved.maxBackoffMultiplier\n\t\t\t\t) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: { stepId: step.id, field: \"params.backoffMultiplier\" },\n\t\t\t\t\t\tmessage: `backoffMultiplier ${backoffMultiplier.value} is outside allowed range [${resolved.minBackoffMultiplier}, ${resolved.maxBackoffMultiplier}]`,\n\t\t\t\t\t\tcode: \"BACKOFF_MULTIPLIER_OUT_OF_RANGE\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\ttimeoutMs?.type === \"literal\" &&\n\t\t\t\ttypeof timeoutMs.value === \"number\"\n\t\t\t) {\n\t\t\t\tif (timeoutMs.value > resolved.maxTimeoutMs) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: { stepId: step.id, field: \"params.timeoutMs\" },\n\t\t\t\t\t\tmessage: `timeoutMs ${timeoutMs.value}ms exceeds limit of ${resolved.maxTimeoutMs}ms`,\n\t\t\t\t\t\tcode: \"WAIT_TIMEOUT_EXCEEDS_LIMIT\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diagnostics;\n}\n",
|
|
16
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type { Diagnostic } from \"../types\";\n\nexport function validateReferences(workflow: WorkflowDefinition): Diagnostic[] {\n\tconst diagnostics: Diagnostic[] = [];\n\tconst stepIds = new Set(workflow.steps.map((s) => s.id));\n\n\t// Check initialStepId\n\tif (!stepIds.has(workflow.initialStepId)) {\n\t\tdiagnostics.push({\n\t\t\tseverity: \"error\",\n\t\t\tlocation: { stepId: null, field: \"initialStepId\" },\n\t\t\tmessage: `Initial step '${workflow.initialStepId}' does not exist`,\n\t\t\tcode: \"MISSING_INITIAL_STEP\",\n\t\t});\n\t}\n\n\tfor (const step of workflow.steps) {\n\t\t// Check nextStepId\n\t\tif (step.nextStepId && !stepIds.has(step.nextStepId)) {\n\t\t\tdiagnostics.push({\n\t\t\t\tseverity: \"error\",\n\t\t\t\tlocation: { stepId: step.id, field: \"nextStepId\" },\n\t\t\t\tmessage: `Step '${step.id}' references non-existent next step '${step.nextStepId}'`,\n\t\t\t\tcode: \"MISSING_NEXT_STEP\",\n\t\t\t});\n\t\t}\n\n\t\t// Check branchBodyStepId in switch-case\n\t\tif (step.type === \"switch-case\") {\n\t\t\tfor (const [i, c] of step.params.cases.entries()) {\n\t\t\t\tif (!stepIds.has(c.branchBodyStepId)) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: {\n\t\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\t\tfield: `params.cases[${i}].branchBodyStepId`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmessage: `Step '${step.id}' case ${i} references non-existent branch body step '${c.branchBodyStepId}'`,\n\t\t\t\t\t\tcode: \"MISSING_BRANCH_BODY_STEP\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check loopBodyStepId in for-each\n\t\tif (step.type === \"for-each\") {\n\t\t\tif (!stepIds.has(step.params.loopBodyStepId)) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: {\n\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\tfield: \"params.loopBodyStepId\",\n\t\t\t\t\t},\n\t\t\t\t\tmessage: `Step '${step.id}' references non-existent loop body step '${step.params.loopBodyStepId}'`,\n\t\t\t\t\tcode: \"MISSING_LOOP_BODY_STEP\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Check conditionStepId in wait-for-condition\n\t\tif (step.type === \"wait-for-condition\") {\n\t\t\tif (!stepIds.has(step.params.conditionStepId)) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: {\n\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\tfield: \"params.conditionStepId\",\n\t\t\t\t\t},\n\t\t\t\t\tmessage: `Step '${step.id}' references non-existent condition body step '${step.params.conditionStepId}'`,\n\t\t\t\t\tcode: \"MISSING_CONDITION_BODY_STEP\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diagnostics;\n}\n",
|
|
17
|
+
"import type { WorkflowDefinition } from \"../../types\";\nimport type { Diagnostic, ToolDefinitionMap } from \"../types\";\n\nexport function validateTools(\n\tworkflow: WorkflowDefinition,\n\ttools: ToolDefinitionMap,\n): Diagnostic[] {\n\tconst diagnostics: Diagnostic[] = [];\n\n\tfor (const step of workflow.steps) {\n\t\tif (step.type === \"tool-call\") {\n\t\t\tconst { toolName, toolInput } = step.params;\n\n\t\t\t// Check tool exists\n\t\t\tconst toolDef = tools[toolName];\n\t\t\tif (!toolDef) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\tlocation: { stepId: step.id, field: \"params.toolName\" },\n\t\t\t\t\tmessage: `Step '${step.id}' references unknown tool '${toolName}'`,\n\t\t\t\t\tcode: \"UNKNOWN_TOOL\",\n\t\t\t\t});\n\t\t\t\tcontinue; // Can't validate inputs for unknown tool\n\t\t\t}\n\n\t\t\tconst schemaProperties = toolDef.inputSchema.properties ?? {};\n\t\t\tconst requiredKeys = new Set(toolDef.inputSchema.required ?? []);\n\t\t\tconst definedKeys = new Set(Object.keys(schemaProperties));\n\t\t\tconst providedKeys = new Set(Object.keys(toolInput));\n\n\t\t\t// Check for extra keys (provided but not in schema)\n\t\t\tfor (const key of providedKeys) {\n\t\t\t\tif (!definedKeys.has(key)) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\tlocation: {\n\t\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\t\tfield: `params.toolInput.${key}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmessage: `Step '${step.id}' provides input key '${key}' which is not defined in tool '${toolName}' schema`,\n\t\t\t\t\t\tcode: \"EXTRA_TOOL_INPUT_KEY\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check for missing required keys\n\t\t\tfor (const key of requiredKeys) {\n\t\t\t\tif (!providedKeys.has(key)) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: { stepId: step.id, field: \"params.toolInput\" },\n\t\t\t\t\t\tmessage: `Step '${step.id}' is missing required input key '${key}' for tool '${toolName}'`,\n\t\t\t\t\t\tcode: \"MISSING_TOOL_INPUT_KEY\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate tool references in agent-loop steps\n\t\tif (step.type === \"agent-loop\") {\n\t\t\tfor (const [i, toolName] of step.params.tools.entries()) {\n\t\t\t\tif (!tools[toolName]) {\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tlocation: {\n\t\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\t\tfield: `params.tools[${i}]`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmessage: `Step '${step.id}' references unknown tool '${toolName}'`,\n\t\t\t\t\t\tcode: \"UNKNOWN_TOOL\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diagnostics;\n}\n",
|
|
18
|
+
"// ─── Recovery & Classification Types ────────────────────────────\n\n/** Strategy for recovering from a step execution error. */\nexport type RecoveryStrategy =\n\t| \"none\"\n\t| \"retry\"\n\t| \"llm-transform\"\n\t| \"llm-reprompt\";\n\n/**\n * High-level category of a step execution error.\n * - `configuration` — the workflow is misconfigured (missing tools, no agent)\n * - `validation` — input or output data doesn't match the expected schema\n * - `external-service` — a tool or LLM call failed\n * - `expression` — a JMESPath or template expression failed to evaluate\n * - `output-quality` — the LLM produced output that couldn't be parsed\n */\nexport type ErrorCategory =\n\t| \"configuration\"\n\t| \"validation\"\n\t| \"external-service\"\n\t| \"expression\"\n\t| \"output-quality\";\n\n/** Machine-readable error code identifying the specific failure. */\nexport type ErrorCode =\n\t// configuration — workflow is misconfigured\n\t| \"TOOL_NOT_FOUND\"\n\t| \"TOOL_MISSING_EXECUTE\"\n\t| \"AGENT_NOT_PROVIDED\"\n\t// validation — input/output data doesn't match expected schema/type\n\t| \"TOOL_INPUT_VALIDATION_FAILED\"\n\t| \"FOREACH_TARGET_NOT_ARRAY\"\n\t| \"WORKFLOW_OUTPUT_VALIDATION_FAILED\"\n\t// external-service — external service failure\n\t| \"TOOL_EXECUTION_FAILED\"\n\t| \"LLM_API_ERROR\"\n\t| \"LLM_RATE_LIMITED\"\n\t| \"LLM_NETWORK_ERROR\"\n\t| \"LLM_NO_CONTENT\"\n\t// expression — JMESPath or template evaluation failure\n\t| \"JMESPATH_EVALUATION_ERROR\"\n\t| \"TEMPLATE_INTERPOLATION_ERROR\"\n\t// output-quality — LLM produced unparseable/unusable output\n\t| \"LLM_OUTPUT_PARSE_ERROR\"\n\t// extraction — probe mode failures\n\t| \"EXTRACTION_GAVE_UP\"\n\t// wait — wait/sleep step errors\n\t| \"SLEEP_INVALID_DURATION\"\n\t| \"WAIT_CONDITION_TIMEOUT\"\n\t| \"WAIT_CONDITION_MAX_ATTEMPTS\"\n\t// execution limits — aggregate time bounds\n\t| \"EXECUTION_TOTAL_TIMEOUT\"\n\t| \"EXECUTION_ACTIVE_TIMEOUT\";\n\n// ─── Base Error Class ───────────────────────────────────────────\n\n/**\n * Base error class for all step execution failures. Contains the step ID,\n * error code, error category, and optional cause. All executor error classes\n * extend this.\n */\nexport class StepExecutionError extends Error {\n\toverride readonly name = \"StepExecutionError\";\n\n\tconstructor(\n\t\tpublic readonly stepId: string,\n\t\tpublic readonly code: ErrorCode,\n\t\tpublic readonly category: ErrorCategory,\n\t\tmessage: string,\n\t\tpublic override readonly cause?: unknown,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n// ─── Category Subclasses ────────────────────────────────────────\n\n/** Thrown when the workflow is misconfigured (missing tools, missing agent, missing execute function). Not retryable. */\nexport class ConfigurationError extends StepExecutionError {\n\tconstructor(stepId: string, code: ErrorCode, message: string) {\n\t\tsuper(stepId, code, \"configuration\", message);\n\t}\n}\n\n/** Thrown when input or output data doesn't match the expected schema. Not retryable. */\nexport class ValidationError extends StepExecutionError {\n\tconstructor(\n\t\tstepId: string,\n\t\tcode: ErrorCode,\n\t\tmessage: string,\n\t\tpublic readonly input: unknown,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(stepId, code, \"validation\", message, cause);\n\t}\n}\n\n/** Thrown when a tool execution or LLM API call fails. May be retryable (check {@link isRetryable}). */\nexport class ExternalServiceError extends StepExecutionError {\n\tconstructor(\n\t\tstepId: string,\n\t\tcode: ErrorCode,\n\t\tmessage: string,\n\t\tcause?: unknown,\n\t\tpublic readonly statusCode?: number,\n\t\tpublic readonly isRetryable: boolean = true,\n\t) {\n\t\tsuper(stepId, code, \"external-service\", message, cause);\n\t}\n}\n\n/** Thrown when a JMESPath expression or template interpolation fails to evaluate. Not retryable. */\nexport class ExpressionError extends StepExecutionError {\n\tconstructor(\n\t\tstepId: string,\n\t\tcode: ErrorCode,\n\t\tmessage: string,\n\t\tpublic readonly expression: string,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(stepId, code, \"expression\", message, cause);\n\t}\n}\n\n/** Thrown when an LLM produces output that can't be parsed as valid JSON. Retryable via automatic retry. */\nexport class OutputQualityError extends StepExecutionError {\n\tconstructor(\n\t\tstepId: string,\n\t\tcode: ErrorCode,\n\t\tmessage: string,\n\t\tpublic readonly rawOutput: unknown,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(stepId, code, \"output-quality\", message, cause);\n\t}\n}\n\n/** Thrown when the LLM determines that the requested data cannot be found or extracted from the source data during probe mode. Not retryable. */\nexport class ExtractionError extends StepExecutionError {\n\tconstructor(\n\t\tstepId: string,\n\t\tmessage: string,\n\t\tpublic readonly reason: string,\n\t) {\n\t\tsuper(stepId, \"EXTRACTION_GAVE_UP\", \"output-quality\", message);\n\t}\n}\n",
|
|
19
|
+
"import { ExternalServiceError } from \"./errors\";\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface WaitForConditionOptions {\n\tmaxAttempts: number;\n\tintervalMs: number;\n\tbackoffMultiplier: number;\n\ttimeoutMs?: number;\n}\n\n/**\n * Injectable execution context for durable execution environments.\n *\n * In a durable environment (AWS Step Functions, Temporal, Inngest, etc.),\n * each `step()` runs in its own execution environment. The workflow code\n * **outside** of `step()` closures re-executes on every resume, so it\n * must be idempotent (pure reads, expression evaluation, scope construction).\n * Code **inside** a `step()` closure runs exactly once — the environment\n * records its result and replays the cached value on subsequent resumes\n * instead of re-executing the function.\n */\nexport interface DurableContext {\n\t/**\n\t * Wrap a step that should execute exactly once. In durable environments,\n\t * `fn` runs on the first invocation and its result is persisted; on\n\t * subsequent resumes the cached result is returned without calling `fn`\n\t * again. All code outside `step()` must be idempotent because it\n\t * re-runs on every resume.\n\t * Default: executes the function directly (passthrough).\n\t */\n\tstep: (name: string, fn: () => Promise<unknown>) => Promise<unknown>;\n\n\t/**\n\t * Sleep for the given duration. In durable environments,\n\t * this uses a durable timer that survives process restarts.\n\t * Default: setTimeout-based promise.\n\t */\n\tsleep: (name: string, durationMs: number) => Promise<void>;\n\n\t/**\n\t * Wait for a condition by polling. In durable environments,\n\t * this might use waitForCallback or durable polling.\n\t * Default: loop with setTimeout + backoff.\n\t */\n\twaitForCondition: (\n\t\tname: string,\n\t\tcheckFn: () => Promise<unknown>,\n\t\toptions: WaitForConditionOptions,\n\t) => Promise<unknown>;\n}\n\n// ─── Default Implementation ──────────────────────────────────────\n\nexport function createDefaultDurableContext(): DurableContext {\n\treturn {\n\t\tstep: (_name, fn) => fn(),\n\n\t\tsleep: (_name, ms) => new Promise((r) => setTimeout(r, ms)),\n\n\t\twaitForCondition: async (_name, checkFn, opts) => {\n\t\t\tlet delay = opts.intervalMs;\n\t\t\tconst deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : undefined;\n\n\t\t\tfor (let attempt = 0; attempt < opts.maxAttempts; attempt++) {\n\t\t\t\tconst result = await checkFn();\n\t\t\t\tif (result) return result;\n\n\t\t\t\tif (deadline && Date.now() + delay > deadline) {\n\t\t\t\t\tthrow new ExternalServiceError(\n\t\t\t\t\t\t_name,\n\t\t\t\t\t\t\"WAIT_CONDITION_TIMEOUT\",\n\t\t\t\t\t\t`wait-for-condition '${_name}' timed out after ${opts.timeoutMs}ms`,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t\t\tdelay *= opts.backoffMultiplier;\n\t\t\t}\n\n\t\t\tthrow new ExternalServiceError(\n\t\t\t\t_name,\n\t\t\t\t\"WAIT_CONDITION_MAX_ATTEMPTS\",\n\t\t\t\t`wait-for-condition '${_name}' exceeded ${opts.maxAttempts} attempts`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t},\n\t};\n}\n",
|
|
20
|
+
"import { type } from \"arktype\";\nimport type { StepExecutionError } from \"./errors\";\n\n// ─── Enums ───────────────────────────────────────────────────────\n\nexport const stepStatusSchema = type(\n\t\"'pending' | 'running' | 'completed' | 'failed' | 'skipped'\",\n);\nexport type StepStatus = typeof stepStatusSchema.infer;\n\nexport const runStatusSchema = type(\n\t\"'pending' | 'running' | 'completed' | 'failed'\",\n);\nexport type RunStatus = typeof runStatusSchema.infer;\n\n// ─── Serializable Snapshots ──────────────────────────────────────\n\nexport const errorSnapshotSchema = type({\n\tcode: \"string\",\n\tcategory: \"string\",\n\tmessage: \"string\",\n\t\"stepId?\": \"string\",\n\t\"statusCode?\": \"number\",\n\t\"isRetryable?\": \"boolean\",\n});\nexport type ErrorSnapshot = typeof errorSnapshotSchema.infer;\n\nexport const retryRecordSchema = type({\n\tattempt: \"number\",\n\tstartedAt: \"string\",\n\tfailedAt: \"string\",\n\terrorCode: \"string\",\n\terrorMessage: \"string\",\n});\nexport type RetryRecord = typeof retryRecordSchema.infer;\n\n// ─── Execution Path ──────────────────────────────────────────────\n\nexport const executionPathSegmentSchema = type({\n\ttype: \"'for-each'\",\n\tstepId: \"string\",\n\titerationIndex: \"number\",\n\titemValue: \"unknown\",\n})\n\t.or({\n\t\ttype: \"'switch-case'\",\n\t\tstepId: \"string\",\n\t\tmatchedCaseIndex: \"number\",\n\t\tmatchedValue: \"unknown\",\n\t})\n\t.or({\n\t\ttype: \"'wait-for-condition'\",\n\t\tstepId: \"string\",\n\t\tpollAttempt: \"number\",\n\t});\nexport type ExecutionPathSegment = typeof executionPathSegmentSchema.infer;\n\n// ─── Trace Entries ──────────────────────────────────────────────\n\nexport const traceEntrySchema = type({\n\ttype: \"'log'\",\n\tmessage: \"string\",\n\t\"data?\": \"unknown\",\n}).or({\n\ttype: \"'agent-step'\",\n\tstep: \"unknown\",\n});\nexport type TraceEntry = typeof traceEntrySchema.infer;\n\n// ─── Step Execution Record ───────────────────────────────────────\n\nexport const stepExecutionRecordSchema = type({\n\tstepId: \"string\",\n\tstatus: stepStatusSchema,\n\t\"startedAt?\": \"string\",\n\t\"completedAt?\": \"string\",\n\t\"durationMs?\": \"number\",\n\t\"output?\": \"unknown\",\n\t\"error?\": errorSnapshotSchema,\n\t\"resolvedInputs?\": \"unknown\",\n\t\"trace?\": [traceEntrySchema, \"[]\"],\n\tretries: [retryRecordSchema, \"[]\"],\n\tpath: [executionPathSegmentSchema, \"[]\"],\n});\nexport type StepExecutionRecord = typeof stepExecutionRecordSchema.infer;\n\n// ─── Execution State ─────────────────────────────────────────────\n\nexport const executionStateSchema = type({\n\trunId: \"string\",\n\tstatus: runStatusSchema,\n\tstartedAt: \"string\",\n\t\"completedAt?\": \"string\",\n\t\"durationMs?\": \"number\",\n\tstepRecords: [stepExecutionRecordSchema, \"[]\"],\n\t\"output?\": \"unknown\",\n\t\"error?\": errorSnapshotSchema,\n});\nexport type ExecutionState = typeof executionStateSchema.infer;\n\n// ─── Deltas ──────────────────────────────────────────────────────\n\nexport const executionDeltaSchema = type({\n\ttype: \"'run-started'\",\n\trunId: \"string\",\n\tstartedAt: \"string\",\n})\n\t.or({\n\t\ttype: \"'step-started'\",\n\t\tstepId: \"string\",\n\t\tpath: [executionPathSegmentSchema, \"[]\"],\n\t\tstartedAt: \"string\",\n\t})\n\t.or({\n\t\ttype: \"'step-completed'\",\n\t\tstepId: \"string\",\n\t\tpath: [executionPathSegmentSchema, \"[]\"],\n\t\tcompletedAt: \"string\",\n\t\tdurationMs: \"number\",\n\t\toutput: \"unknown\",\n\t\t\"resolvedInputs?\": \"unknown\",\n\t\t\"trace?\": [traceEntrySchema, \"[]\"],\n\t})\n\t.or({\n\t\ttype: \"'step-failed'\",\n\t\tstepId: \"string\",\n\t\tpath: [executionPathSegmentSchema, \"[]\"],\n\t\tfailedAt: \"string\",\n\t\tdurationMs: \"number\",\n\t\terror: errorSnapshotSchema,\n\t\t\"resolvedInputs?\": \"unknown\",\n\t})\n\t.or({\n\t\ttype: \"'step-retry'\",\n\t\tstepId: \"string\",\n\t\tpath: [executionPathSegmentSchema, \"[]\"],\n\t\tretry: retryRecordSchema,\n\t})\n\t.or({\n\t\ttype: \"'run-completed'\",\n\t\trunId: \"string\",\n\t\tcompletedAt: \"string\",\n\t\tdurationMs: \"number\",\n\t\t\"output?\": \"unknown\",\n\t})\n\t.or({\n\t\ttype: \"'run-failed'\",\n\t\trunId: \"string\",\n\t\tfailedAt: \"string\",\n\t\tdurationMs: \"number\",\n\t\terror: errorSnapshotSchema,\n\t});\nexport type ExecutionDelta = typeof executionDeltaSchema.infer;\n\n// ─── Helpers ─────────────────────────────────────────────────────\n\n/** Convert a StepExecutionError class instance to a serializable snapshot. */\nexport function snapshotError(err: StepExecutionError): ErrorSnapshot {\n\tconst snapshot: ErrorSnapshot = {\n\t\tcode: err.code,\n\t\tcategory: err.category,\n\t\tmessage: err.message,\n\t};\n\tif (err.stepId) snapshot.stepId = err.stepId;\n\tif (\"statusCode\" in err && typeof err.statusCode === \"number\") {\n\t\tsnapshot.statusCode = err.statusCode;\n\t}\n\tif (\"isRetryable\" in err && typeof err.isRetryable === \"boolean\") {\n\t\tsnapshot.isRetryable = err.isRetryable;\n\t}\n\treturn snapshot;\n}\n\n// ─── Path Matching ───────────────────────────────────────────────\n\nfunction segmentsEqual(\n\tsa: ExecutionPathSegment,\n\tsb: ExecutionPathSegment,\n): boolean {\n\tif (sa.type !== sb.type || sa.stepId !== sb.stepId) return false;\n\tif (sa.type === \"for-each\" && sb.type === \"for-each\") {\n\t\treturn sa.iterationIndex === sb.iterationIndex;\n\t}\n\tif (sa.type === \"switch-case\" && sb.type === \"switch-case\") {\n\t\treturn sa.matchedCaseIndex === sb.matchedCaseIndex;\n\t}\n\tif (sa.type === \"wait-for-condition\" && sb.type === \"wait-for-condition\") {\n\t\treturn sa.pollAttempt === sb.pollAttempt;\n\t}\n\treturn true;\n}\n\nfunction pathsEqual(\n\ta: ExecutionPathSegment[],\n\tb: ExecutionPathSegment[],\n): boolean {\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tconst sa = a[i] as ExecutionPathSegment;\n\t\tconst sb = b[i] as ExecutionPathSegment;\n\t\tif (!segmentsEqual(sa, sb)) return false;\n\t}\n\treturn true;\n}\n\nfunction findRecordIndex(\n\trecords: StepExecutionRecord[],\n\tstepId: string,\n\tpath: ExecutionPathSegment[],\n): number {\n\tfor (let i = records.length - 1; i >= 0; i--) {\n\t\tconst record = records[i] as StepExecutionRecord;\n\t\tif (record.stepId === stepId && pathsEqual(record.path, path)) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\n// ─── Pure Reducer ────────────────────────────────────────────────\n\n/** Apply a delta to an execution state, returning a new state. Pure — no mutations. */\nexport function applyDelta(\n\tstate: ExecutionState,\n\tdelta: ExecutionDelta,\n): ExecutionState {\n\tswitch (delta.type) {\n\t\tcase \"run-started\":\n\t\t\treturn { ...state, status: \"running\", startedAt: delta.startedAt };\n\n\t\tcase \"step-started\": {\n\t\t\tconst record: StepExecutionRecord = {\n\t\t\t\tstepId: delta.stepId,\n\t\t\t\tstatus: \"running\",\n\t\t\t\tstartedAt: delta.startedAt,\n\t\t\t\tretries: [],\n\t\t\t\tpath: delta.path,\n\t\t\t};\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tstepRecords: [...state.stepRecords, record],\n\t\t\t};\n\t\t}\n\n\t\tcase \"step-completed\": {\n\t\t\tconst records = [...state.stepRecords];\n\t\t\tconst idx = findRecordIndex(records, delta.stepId, delta.path);\n\t\t\tif (idx >= 0) {\n\t\t\t\tconst existing = records[idx] as StepExecutionRecord;\n\t\t\t\tconst updated: StepExecutionRecord = {\n\t\t\t\t\t...existing,\n\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\tcompletedAt: delta.completedAt,\n\t\t\t\t\tdurationMs: delta.durationMs,\n\t\t\t\t\toutput: delta.output,\n\t\t\t\t};\n\t\t\t\tif (delta.resolvedInputs !== undefined) {\n\t\t\t\t\tupdated.resolvedInputs = delta.resolvedInputs;\n\t\t\t\t}\n\t\t\t\tif (delta.trace !== undefined) {\n\t\t\t\t\tupdated.trace = delta.trace;\n\t\t\t\t}\n\t\t\t\trecords[idx] = updated;\n\t\t\t}\n\t\t\treturn { ...state, stepRecords: records };\n\t\t}\n\n\t\tcase \"step-failed\": {\n\t\t\tconst records = [...state.stepRecords];\n\t\t\tconst idx = findRecordIndex(records, delta.stepId, delta.path);\n\t\t\tif (idx >= 0) {\n\t\t\t\tconst existing = records[idx] as StepExecutionRecord;\n\t\t\t\tconst updated: StepExecutionRecord = {\n\t\t\t\t\t...existing,\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tcompletedAt: delta.failedAt,\n\t\t\t\t\tdurationMs: delta.durationMs,\n\t\t\t\t\terror: delta.error,\n\t\t\t\t};\n\t\t\t\tif (delta.resolvedInputs !== undefined) {\n\t\t\t\t\tupdated.resolvedInputs = delta.resolvedInputs;\n\t\t\t\t}\n\t\t\t\trecords[idx] = updated;\n\t\t\t}\n\t\t\treturn { ...state, stepRecords: records };\n\t\t}\n\n\t\tcase \"step-retry\": {\n\t\t\tconst records = [...state.stepRecords];\n\t\t\tconst idx = findRecordIndex(records, delta.stepId, delta.path);\n\t\t\tif (idx >= 0) {\n\t\t\t\tconst existing = records[idx] as StepExecutionRecord;\n\t\t\t\trecords[idx] = {\n\t\t\t\t\t...existing,\n\t\t\t\t\tretries: [...existing.retries, delta.retry],\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ...state, stepRecords: records };\n\t\t}\n\n\t\tcase \"run-completed\":\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tcompletedAt: delta.completedAt,\n\t\t\t\tdurationMs: delta.durationMs,\n\t\t\t\toutput: delta.output,\n\t\t\t};\n\n\t\tcase \"run-failed\":\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tcompletedAt: delta.failedAt,\n\t\t\t\tdurationMs: delta.durationMs,\n\t\t\t\terror: delta.error,\n\t\t\t};\n\t}\n}\n",
|
|
21
|
+
"import type { Agent, LanguageModel, ToolSet } from \"ai\";\nimport type { WorkflowStep } from \"../types\";\nimport type { DurableContext } from \"./context\";\nimport type { ErrorCode } from \"./errors\";\nimport { ExternalServiceError, type StepExecutionError } from \"./errors\";\nimport type {\n\tExecutionDelta,\n\tExecutionPathSegment,\n\tExecutionState,\n\tRetryRecord,\n\tTraceEntry,\n} from \"./state\";\nimport { applyDelta, snapshotError } from \"./state\";\n\n// ─── Public Types ────────────────────────────────────────────────\n\n/** The result of executing a workflow. */\nexport interface ExecutionResult {\n\t/** Whether the workflow completed without errors. */\n\tsuccess: boolean;\n\t/** Map of step ID to that step's output value. */\n\tstepOutputs: Record<string, unknown>;\n\t/** The workflow's final output (from the `end` step's output expression), if any. */\n\toutput?: unknown;\n\t/** The error that caused execution to fail, if `success` is `false`. */\n\terror?: StepExecutionError;\n\t/** The final execution state snapshot after the run completes. */\n\texecutionState: ExecutionState;\n}\n\nexport interface ExecutorLimits {\n\t/** Max wall-clock time from start to finish, including sleeps/waits. Default: 600_000 (10 min). */\n\tmaxTotalMs?: number;\n\t/** Max active execution time (inside step() + checkFn, excluding sleeps/waits). Default: 300_000 (5 min). */\n\tmaxActiveMs?: number;\n\t/** Soft cap on sleep durationMs and wait intervalMs. Clamped silently. Default: 300_000 (5 min). */\n\tmaxSleepMs?: number;\n\t/** Soft cap on wait-for-condition maxAttempts. Clamped silently. Default: Infinity (unbounded). */\n\tmaxAttempts?: number;\n\t/** Soft cap on backoffMultiplier upper bound. Clamped silently. Default: 2. */\n\tmaxBackoffMultiplier?: number;\n\t/** Soft cap on backoffMultiplier lower bound. Clamped silently. Default: 1. */\n\tminBackoffMultiplier?: number;\n\t/** Soft cap on wait-for-condition timeoutMs. Clamped silently. Default: 600_000 (10 min). */\n\tmaxTimeoutMs?: number;\n\t/** Byte threshold above which extract-data uses probe mode instead of inline data. Default: 50_000 (50KB). */\n\tprobeThresholdBytes?: number;\n\t/** Maximum bytes returned per probe-data call. Default: 10_000 (10KB). */\n\tprobeResultMaxBytes?: number;\n\t/** Maximum probe steps for extract-data probe mode. Default: 10. */\n\tprobeMaxSteps?: number;\n}\n\n/** Options for {@link executeWorkflow}. */\nexport interface ExecuteWorkflowOptions {\n\t/** Tool definitions. Every tool referenced by a `tool-call` step must be present with an `execute` function. */\n\ttools: ToolSet;\n\t/** An AI SDK `LanguageModel` for `llm-prompt`, `extract-data`, and `agent-loop` steps. Required if the workflow contains LLM steps. */\n\tmodel?: LanguageModel;\n\t/** An AI SDK `Agent` to use for `agent-loop` steps. When provided, agent-loop steps use the Agent's own tools\n\t * and describe the expected output shape in the prompt. The bare `model` is then used to coerce the Agent's\n\t * text output into the structured format. Only applies to `agent-loop` steps. */\n\t// biome-ignore lint/suspicious/noExplicitAny: Agent generic params are irrelevant here\n\tagent?: Agent<any, any, any>;\n\t/** Input values passed to the workflow's `start` step. Validated against the start step's `inputSchema`. */\n\tinputs?: Record<string, unknown>;\n\t/** Maximum number of retries for recoverable errors (rate limits, network errors, parse failures). Defaults to 3. */\n\tmaxRetries?: number;\n\t/** Base delay in milliseconds for exponential backoff between retries. Defaults to 1000. */\n\tretryDelayMs?: number;\n\t/** Called when a step begins execution. */\n\tonStepStart?: (stepId: string, step: WorkflowStep) => void;\n\t/** Called when a step completes successfully. */\n\tonStepComplete?: (stepId: string, output: unknown) => void;\n\t/** Called on every state transition with the full execution state and the idempotent delta that produced it. */\n\tonStateChange?: (state: ExecutionState, delta: ExecutionDelta) => void;\n\t/** Injectable durable execution context. Default: simple in-process implementation. */\n\tcontext?: DurableContext;\n\t/** Execution limits for sleep/wait/timeout bounds. */\n\tlimits?: ExecutorLimits;\n}\n\n// ─── Internal Types ──────────────────────────────────────────────\n\nexport type Expression =\n\t| { type: \"literal\"; value: unknown }\n\t| { type: \"jmespath\"; expression: string }\n\t| { type: \"template\"; template: string };\n\n/**\n * Internal resolved options. Currently identical to the public options\n * but kept as a separate type for future internal-only fields.\n */\nexport type ResolvedExecuteWorkflowOptions = ExecuteWorkflowOptions;\n\n/**\n * Callback type for `executeChain`, injected into structural steps\n * (switch-case, for-each, wait-for-condition) to avoid circular imports.\n */\nexport type ExecuteChainFn = (\n\tstartStepId: string,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tcontext: DurableContext,\n\ttimer: ExecutionTimer | undefined,\n\tstateManager: ExecutionStateManager | undefined,\n\texecPath: ExecutionPathSegment[],\n) => Promise<unknown>;\n\n// ─── Execution Timer ─────────────────────────────────────────────\n\nexport const DEFAULT_EXECUTOR_LIMITS: Required<ExecutorLimits> = {\n\tmaxTotalMs: 600_000, // 10 minutes\n\tmaxActiveMs: 300_000, // 5 minutes\n\tmaxSleepMs: 300_000, // 5 minutes\n\tmaxAttempts: Number.POSITIVE_INFINITY,\n\tmaxBackoffMultiplier: 2,\n\tminBackoffMultiplier: 1,\n\tmaxTimeoutMs: 600_000, // 10 minutes\n\tprobeThresholdBytes: 50_000, // 50KB\n\tprobeResultMaxBytes: 10_000, // 10KB\n\tprobeMaxSteps: 10,\n};\n\nexport class ExecutionTimer {\n\tprivate readonly startTime = Date.now();\n\tprivate activeMs = 0;\n\tprivate activeStart: number | null = null;\n\tprivate readonly limits: Required<ExecutorLimits>;\n\n\tconstructor(limits?: ExecutorLimits) {\n\t\tthis.limits = { ...DEFAULT_EXECUTOR_LIMITS, ...limits };\n\t}\n\n\tget resolvedLimits(): Required<ExecutorLimits> {\n\t\treturn this.limits;\n\t}\n\n\t/** Call before entering active work (step execution, condition check). */\n\tbeginActive(): void {\n\t\tthis.activeStart = Date.now();\n\t}\n\n\t/** Call after active work completes. Checks active timeout. */\n\tendActive(stepId: string): void {\n\t\tif (this.activeStart !== null) {\n\t\t\tthis.activeMs += Date.now() - this.activeStart;\n\t\t\tthis.activeStart = null;\n\t\t}\n\t\tif (this.activeMs > this.limits.maxActiveMs) {\n\t\t\tthrow new ExternalServiceError(\n\t\t\t\tstepId,\n\t\t\t\t\"EXECUTION_ACTIVE_TIMEOUT\" as ErrorCode,\n\t\t\t\t`Active execution time ${this.activeMs}ms exceeded limit of ${this.limits.maxActiveMs}ms`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Check total wall-clock timeout before starting a step. */\n\tcheckTotal(stepId: string): void {\n\t\tconst elapsed = Date.now() - this.startTime;\n\t\tif (elapsed > this.limits.maxTotalMs) {\n\t\t\tthrow new ExternalServiceError(\n\t\t\t\tstepId,\n\t\t\t\t\"EXECUTION_TOTAL_TIMEOUT\" as ErrorCode,\n\t\t\t\t`Total execution time ${elapsed}ms exceeded limit of ${this.limits.maxTotalMs}ms`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ─── Execution State Manager ─────────────────────────────────────\n\nexport class ExecutionStateManager {\n\tprivate state: ExecutionState;\n\tprivate readonly onChange?: (\n\t\tstate: ExecutionState,\n\t\tdelta: ExecutionDelta,\n\t) => void;\n\n\tconstructor(\n\t\tonChange?: (state: ExecutionState, delta: ExecutionDelta) => void,\n\t) {\n\t\tthis.state = {\n\t\t\trunId: crypto.randomUUID(),\n\t\t\tstatus: \"pending\",\n\t\t\tstartedAt: new Date().toISOString(),\n\t\t\tstepRecords: [],\n\t\t};\n\t\tthis.onChange = onChange;\n\t}\n\n\tget currentState(): ExecutionState {\n\t\treturn this.state;\n\t}\n\n\tprivate emit(delta: ExecutionDelta): void {\n\t\tthis.state = applyDelta(this.state, delta);\n\t\tthis.onChange?.(this.state, delta);\n\t}\n\n\trunStarted(): void {\n\t\tthis.emit({\n\t\t\ttype: \"run-started\",\n\t\t\trunId: this.state.runId,\n\t\t\tstartedAt: this.state.startedAt,\n\t\t});\n\t}\n\n\tstepStarted(stepId: string, path: ExecutionPathSegment[]): void {\n\t\tthis.emit({\n\t\t\ttype: \"step-started\",\n\t\t\tstepId,\n\t\t\tpath,\n\t\t\tstartedAt: new Date().toISOString(),\n\t\t});\n\t}\n\n\tstepCompleted(\n\t\tstepId: string,\n\t\tpath: ExecutionPathSegment[],\n\t\toutput: unknown,\n\t\tdurationMs: number,\n\t\tresolvedInputs?: unknown,\n\t\ttrace?: TraceEntry[],\n\t): void {\n\t\tthis.emit({\n\t\t\ttype: \"step-completed\",\n\t\t\tstepId,\n\t\t\tpath,\n\t\t\tcompletedAt: new Date().toISOString(),\n\t\t\tdurationMs,\n\t\t\toutput,\n\t\t\tresolvedInputs,\n\t\t\ttrace,\n\t\t});\n\t}\n\n\tstepFailed(\n\t\tstepId: string,\n\t\tpath: ExecutionPathSegment[],\n\t\terror: StepExecutionError,\n\t\tdurationMs: number,\n\t\tresolvedInputs?: unknown,\n\t): void {\n\t\tthis.emit({\n\t\t\ttype: \"step-failed\",\n\t\t\tstepId,\n\t\t\tpath,\n\t\t\tfailedAt: new Date().toISOString(),\n\t\t\tdurationMs,\n\t\t\terror: snapshotError(error),\n\t\t\tresolvedInputs,\n\t\t});\n\t}\n\n\tretryAttempted(\n\t\tstepId: string,\n\t\tpath: ExecutionPathSegment[],\n\t\tretry: RetryRecord,\n\t): void {\n\t\tthis.emit({\n\t\t\ttype: \"step-retry\",\n\t\t\tstepId,\n\t\t\tpath,\n\t\t\tretry,\n\t\t});\n\t}\n\n\trunCompleted(output?: unknown): void {\n\t\tconst startMs = new Date(this.state.startedAt).getTime();\n\t\tthis.emit({\n\t\t\ttype: \"run-completed\",\n\t\t\trunId: this.state.runId,\n\t\t\tcompletedAt: new Date().toISOString(),\n\t\t\tdurationMs: Date.now() - startMs,\n\t\t\toutput,\n\t\t});\n\t}\n\n\trunFailed(error: StepExecutionError): void {\n\t\tconst startMs = new Date(this.state.startedAt).getTime();\n\t\tthis.emit({\n\t\t\ttype: \"run-failed\",\n\t\t\trunId: this.state.runId,\n\t\t\tfailedAt: new Date().toISOString(),\n\t\t\tdurationMs: Date.now() - startMs,\n\t\t\terror: snapshotError(error),\n\t\t});\n\t}\n}\n",
|
|
22
|
+
"import type { Agent, LanguageModel, ToolSet } from \"ai\";\nimport {\n\tgenerateText,\n\tjsonSchema,\n\tOutput,\n\tstepCountIs,\n\tToolLoopAgent,\n} from \"ai\";\nimport type { WorkflowStep } from \"../../types\";\nimport {\n\tConfigurationError,\n\tExtractionError,\n\tStepExecutionError,\n\tValidationError,\n} from \"../errors\";\nimport type {\n\tExecutorLimits,\n\tExpression,\n\tResolvedExecuteWorkflowOptions,\n} from \"../executor-types\";\nimport {\n\tclassifyLlmError,\n\tcreateGiveUpTool,\n\tcreateProbeDataTool,\n\tevaluateExpression,\n\tinterpolateTemplate,\n} from \"../helpers\";\nimport type { TraceEntry } from \"../state\";\n\ntype StepOutput = { output: unknown; trace?: TraceEntry[] };\n\nexport async function executeAgentLoop(\n\tstep: WorkflowStep & { type: \"agent-loop\" },\n\tscope: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tlimits: Required<ExecutorLimits>,\n): Promise<StepOutput> {\n\tif (!options.model) {\n\t\tthrow new ConfigurationError(\n\t\t\tstep.id,\n\t\t\t\"AGENT_NOT_PROVIDED\",\n\t\t\t\"agent-loop steps require a LanguageModel to be provided\",\n\t\t);\n\t}\n\n\tconst interpolatedInstructions = interpolateTemplate(\n\t\tstep.params.instructions,\n\t\tscope,\n\t\tstep.id,\n\t);\n\n\tconst outputSchema = jsonSchema(\n\t\tstep.params.outputFormat as Parameters<typeof jsonSchema>[0],\n\t);\n\n\tif (options.agent) {\n\t\treturn executeWithAgent(\n\t\t\tstep,\n\t\t\tinterpolatedInstructions,\n\t\t\toptions.agent,\n\t\t\toptions.model,\n\t\t\toutputSchema,\n\t\t\tstep.params.outputFormat,\n\t\t);\n\t}\n\n\treturn executeWithModel(\n\t\tstep,\n\t\tinterpolatedInstructions,\n\t\tscope,\n\t\toptions,\n\t\toptions.model,\n\t\tlimits,\n\t\toutputSchema,\n\t);\n}\n\n/** Agent path: use the provided Agent with its own tools, then coerce output with the bare model. */\nasync function executeWithAgent(\n\tstep: WorkflowStep & { type: \"agent-loop\" },\n\tinterpolatedInstructions: string,\n\tagent: Agent,\n\tmodel: LanguageModel,\n\toutputSchema: ReturnType<typeof jsonSchema>,\n\trawOutputFormat: unknown,\n): Promise<StepOutput> {\n\tconst schemaStr = JSON.stringify(rawOutputFormat, null, 2);\n\tconst prompt = `${interpolatedInstructions}\\n\\nWhen you have completed the task, respond with your final answer. Your response should contain the following structured information matching this JSON Schema:\\n\\`\\`\\`json\\n${schemaStr}\\n\\`\\`\\`\\n\\nInclude all the required fields in your response.`;\n\n\ttry {\n\t\tconst result = await agent.generate({ prompt });\n\n\t\t// Coerce the Agent's text output into structured output using the bare model.\n\t\t// A give-up tool is provided so the model can signal if the Agent's output\n\t\t// cannot be meaningfully parsed into the expected schema.\n\t\tconst giveUp = createGiveUpTool();\n\t\tconst coerced = await generateText({\n\t\t\tmodel,\n\t\t\toutput: Output.object({ schema: outputSchema }),\n\t\t\ttools: { \"give-up\": giveUp.tool },\n\t\t\tprompt: `Extract the structured data from the following text. Return only the data matching the schema. If the text does not contain enough information to populate the required fields, call the give-up tool with an explanation.\\n\\nText:\\n${result.text}`,\n\t\t});\n\n\t\tif (giveUp.getReason() !== undefined) {\n\t\t\tthrow new ExtractionError(\n\t\t\t\tstep.id,\n\t\t\t\t`Could not coerce agent output into expected schema: ${giveUp.getReason()}`,\n\t\t\t\tgiveUp.getReason() as string,\n\t\t\t);\n\t\t}\n\n\t\tconst trace: TraceEntry[] = [\n\t\t\t...result.steps.map((s): TraceEntry => ({ type: \"agent-step\", step: s })),\n\t\t\t...coerced.steps.map(\n\t\t\t\t(s): TraceEntry => ({ type: \"agent-step\", step: s }),\n\t\t\t),\n\t\t];\n\n\t\treturn { output: coerced.output, trace };\n\t} catch (e) {\n\t\tif (e instanceof StepExecutionError) throw e;\n\t\tthrow classifyLlmError(step.id, e);\n\t}\n}\n\n/** LanguageModel path: subset tools from options.tools, use ToolLoopAgent with structured output. */\nasync function executeWithModel(\n\tstep: WorkflowStep & { type: \"agent-loop\" },\n\tinterpolatedInstructions: string,\n\tscope: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tmodel: LanguageModel,\n\tlimits: Required<ExecutorLimits>,\n\toutputSchema: ReturnType<typeof jsonSchema>,\n): Promise<StepOutput> {\n\t// Subset tools to only those listed in step.params.tools\n\tconst subsetTools: ToolSet = {};\n\tfor (const toolName of step.params.tools) {\n\t\tconst toolDef = options.tools[toolName];\n\t\tif (!toolDef) {\n\t\t\tthrow new ConfigurationError(\n\t\t\t\tstep.id,\n\t\t\t\t\"TOOL_NOT_FOUND\",\n\t\t\t\t`agent-loop step references tool '${toolName}' which is not in the provided tool set`,\n\t\t\t);\n\t\t}\n\t\tif (!toolDef.execute) {\n\t\t\tthrow new ConfigurationError(\n\t\t\t\tstep.id,\n\t\t\t\t\"TOOL_MISSING_EXECUTE\",\n\t\t\t\t`agent-loop step references tool '${toolName}' which has no execute function`,\n\t\t\t);\n\t\t}\n\t\tsubsetTools[toolName] = toolDef;\n\t}\n\n\t// Inject built-in probe-data and give-up tools\n\tconst probeDataTool = createProbeDataTool(scope, limits);\n\tconst giveUp = createGiveUpTool();\n\tsubsetTools[\"probe-data\"] = probeDataTool;\n\tsubsetTools[\"give-up\"] = giveUp.tool;\n\n\t// Evaluate maxSteps (default: 10)\n\tconst maxSteps = step.params.maxSteps\n\t\t? evaluateExpression(step.params.maxSteps as Expression, scope, step.id)\n\t\t: 10;\n\tif (typeof maxSteps !== \"number\" || maxSteps < 1) {\n\t\tthrow new ValidationError(\n\t\t\tstep.id,\n\t\t\t\"TOOL_INPUT_VALIDATION_FAILED\",\n\t\t\t`agent-loop maxSteps must be a positive number, got ${typeof maxSteps === \"number\" ? maxSteps : typeof maxSteps}`,\n\t\t\tmaxSteps,\n\t\t);\n\t}\n\n\tconst agent = new ToolLoopAgent({\n\t\tmodel,\n\t\ttools: subsetTools,\n\t\toutput: Output.object({ schema: outputSchema }),\n\t\tstopWhen: [\n\t\t\t() => giveUp?.getReason() !== undefined,\n\t\t\tstepCountIs(Math.floor(maxSteps)),\n\t\t],\n\t});\n\n\ttry {\n\t\tconst result = await agent.generate({ prompt: interpolatedInstructions });\n\n\t\t// Check if the agent gave up before returning structured output\n\t\tif (giveUp.getReason() !== undefined) {\n\t\t\tthrow new ExtractionError(\n\t\t\t\tstep.id,\n\t\t\t\t`Agent gave up: ${giveUp.getReason()}`,\n\t\t\t\tgiveUp.getReason() as string,\n\t\t\t);\n\t\t}\n\n\t\tconst trace: TraceEntry[] = result.steps.map((s) => ({\n\t\t\ttype: \"agent-step\" as const,\n\t\t\tstep: s,\n\t\t}));\n\n\t\treturn { output: result.output, trace };\n\t} catch (e) {\n\t\tif (e instanceof StepExecutionError) throw e;\n\t\tthrow classifyLlmError(step.id, e);\n\t}\n}\n\nexport function resolveAgentLoopInputs(\n\tstep: WorkflowStep & { type: \"agent-loop\" },\n\tscope: Record<string, unknown>,\n): unknown {\n\ttry {\n\t\treturn {\n\t\t\tinstructions: interpolateTemplate(\n\t\t\t\tstep.params.instructions,\n\t\t\t\tscope,\n\t\t\t\tstep.id,\n\t\t\t),\n\t\t};\n\t} catch {\n\t\treturn { instructions: step.params.instructions };\n\t}\n}\n",
|
|
23
|
+
"import { search } from \"@jmespath-community/jmespath\";\nimport {\n\tAPICallError,\n\tJSONParseError,\n\tNoContentGeneratedError,\n\tRetryError,\n\tTypeValidationError,\n\ttool,\n} from \"ai\";\nimport { type as arktype } from \"arktype\";\nimport { extractTemplateExpressions } from \"../compiler/utils/jmespath-helpers\";\nimport type { ErrorCode } from \"./errors\";\nimport {\n\tExpressionError,\n\tExternalServiceError,\n\tOutputQualityError,\n\ttype StepExecutionError,\n} from \"./errors\";\nimport type { Expression } from \"./executor-types\";\n\n// ─── Helpers ─────────────────────────────────────────────────────\n\nexport function stripCodeFence(text: string): string {\n\tconst match = text.match(/^```(?:\\w*)\\s*\\n?([\\s\\S]*?)\\n?\\s*```\\s*$/);\n\treturn match?.[1] ?? text;\n}\n\n// ─── Expression Evaluation ───────────────────────────────────────\n\nexport function evaluateExpression(\n\texpr: Expression,\n\tscope: Record<string, unknown>,\n\tstepId: string,\n): unknown {\n\tif (expr.type === \"literal\") {\n\t\treturn expr.value;\n\t}\n\tif (expr.type === \"template\") {\n\t\treturn interpolateTemplate(expr.template, scope, stepId);\n\t}\n\ttry {\n\t\treturn search(scope as Parameters<typeof search>[0], expr.expression);\n\t} catch (e) {\n\t\tthrow new ExpressionError(\n\t\t\tstepId,\n\t\t\t\"JMESPATH_EVALUATION_ERROR\",\n\t\t\t`JMESPath expression '${expr.expression}' failed: ${e instanceof Error ? e.message : String(e)}`,\n\t\t\texpr.expression,\n\t\t\te,\n\t\t);\n\t}\n}\n\nexport function stringifyValue(value: unknown): string {\n\tif (value === null || value === undefined) return \"\";\n\tif (typeof value === \"object\") return JSON.stringify(value);\n\treturn String(value);\n}\n\nexport function interpolateTemplate(\n\ttemplate: string,\n\tscope: Record<string, unknown>,\n\tstepId: string,\n): string {\n\tconst { expressions } = extractTemplateExpressions(template);\n\tif (expressions.length === 0) return template;\n\n\tlet result = \"\";\n\tlet lastEnd = 0;\n\tfor (const expr of expressions) {\n\t\tresult += template.slice(lastEnd, expr.start);\n\t\ttry {\n\t\t\tconst value = search(\n\t\t\t\tscope as Parameters<typeof search>[0],\n\t\t\t\texpr.expression,\n\t\t\t);\n\t\t\tresult += stringifyValue(value);\n\t\t} catch (e) {\n\t\t\tthrow new ExpressionError(\n\t\t\t\tstepId,\n\t\t\t\t\"TEMPLATE_INTERPOLATION_ERROR\",\n\t\t\t\t`Template expression '${expr.expression}' failed: ${e instanceof Error ? e.message : String(e)}`,\n\t\t\t\texpr.expression,\n\t\t\t\te,\n\t\t\t);\n\t\t}\n\t\tlastEnd = expr.end;\n\t}\n\tresult += template.slice(lastEnd);\n\treturn result;\n}\n\n// ─── LLM Error Classification ───────────────────────────────────\n\nexport function classifyLlmError(\n\tstepId: string,\n\te: unknown,\n): StepExecutionError {\n\tif (APICallError.isInstance(e)) {\n\t\tconst code: ErrorCode =\n\t\t\te.statusCode === 429 ? \"LLM_RATE_LIMITED\" : \"LLM_API_ERROR\";\n\t\treturn new ExternalServiceError(\n\t\t\tstepId,\n\t\t\tcode,\n\t\t\te.message,\n\t\t\te,\n\t\t\te.statusCode,\n\t\t\te.isRetryable ?? true,\n\t\t);\n\t}\n\tif (RetryError.isInstance(e)) {\n\t\treturn new ExternalServiceError(\n\t\t\tstepId,\n\t\t\t\"LLM_API_ERROR\",\n\t\t\te.message,\n\t\t\te,\n\t\t\tundefined,\n\t\t\tfalse,\n\t\t);\n\t}\n\tif (NoContentGeneratedError.isInstance(e)) {\n\t\treturn new ExternalServiceError(\n\t\t\tstepId,\n\t\t\t\"LLM_NO_CONTENT\",\n\t\t\te.message,\n\t\t\te,\n\t\t\tundefined,\n\t\t\ttrue,\n\t\t);\n\t}\n\tif (TypeValidationError.isInstance(e)) {\n\t\treturn new OutputQualityError(\n\t\t\tstepId,\n\t\t\t\"LLM_OUTPUT_PARSE_ERROR\",\n\t\t\t`LLM output could not be parsed: ${e.message}`,\n\t\t\te.value,\n\t\t\te,\n\t\t);\n\t}\n\tif (JSONParseError.isInstance(e)) {\n\t\treturn new OutputQualityError(\n\t\t\tstepId,\n\t\t\t\"LLM_OUTPUT_PARSE_ERROR\",\n\t\t\t`LLM output could not be parsed: ${e.message}`,\n\t\t\te.text,\n\t\t\te,\n\t\t);\n\t}\n\treturn new ExternalServiceError(\n\t\tstepId,\n\t\t\"LLM_NETWORK_ERROR\",\n\t\te instanceof Error ? e.message : String(e),\n\t\te,\n\t\tundefined,\n\t\ttrue,\n\t);\n}\n\n// ─── Shared Probe Tools ──────────────────────────────────────────\n\nexport function createProbeDataTool(\n\tsourceData: unknown,\n\tlimits: { probeResultMaxBytes: number },\n) {\n\treturn tool({\n\t\tdescription:\n\t\t\t\"Query the available data using a JMESPath expression. Returns the matching subset of the data.\",\n\t\tinputSchema: arktype({\n\t\t\texpression: [\n\t\t\t\t\"string\",\n\t\t\t\t\"@\",\n\t\t\t\t\"A JMESPath expression to evaluate against the data. Examples: 'users[0]', 'users[*].name', 'metadata.total', 'users[?age > `30`].name'\",\n\t\t\t],\n\t\t}),\n\t\texecute: async ({ expression }) => {\n\t\t\ttry {\n\t\t\t\tconst result = search(\n\t\t\t\t\tsourceData as Parameters<typeof search>[0],\n\t\t\t\t\texpression,\n\t\t\t\t);\n\t\t\t\tconst resultStr =\n\t\t\t\t\ttypeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n\t\t\t\tif (\n\t\t\t\t\tnew TextEncoder().encode(resultStr).byteLength >\n\t\t\t\t\tlimits.probeResultMaxBytes\n\t\t\t\t) {\n\t\t\t\t\tconst truncated = resultStr.slice(0, limits.probeResultMaxBytes);\n\t\t\t\t\treturn `${truncated}\\n\\n[TRUNCATED - result exceeded ${limits.probeResultMaxBytes} bytes. Use a more specific JMESPath expression to narrow the result.]`;\n\t\t\t\t}\n\t\t\t\treturn resultStr;\n\t\t\t} catch (e) {\n\t\t\t\treturn `JMESPath error: ${e instanceof Error ? e.message : String(e)}. Check your expression syntax.`;\n\t\t\t}\n\t\t},\n\t});\n}\n\nexport function createGiveUpTool() {\n\tlet reason: string | undefined;\n\tconst giveUpTool = tool({\n\t\tdescription:\n\t\t\t\"Call this if you determine you cannot complete the task or find/extract the requested data.\",\n\t\tinputSchema: arktype({\n\t\t\treason: [\n\t\t\t\t\"string\",\n\t\t\t\t\"@\",\n\t\t\t\t\"Explanation of why the task cannot be completed\",\n\t\t\t],\n\t\t}),\n\t\texecute: async ({ reason: r }) => {\n\t\t\treason = r;\n\t\t\treturn { acknowledged: true };\n\t\t},\n\t});\n\treturn {\n\t\ttool: giveUpTool,\n\t\tgetReason: () => reason,\n\t};\n}\n",
|
|
24
|
+
"import type { WorkflowStep } from \"../../types\";\nimport type { Expression } from \"../executor-types\";\nimport { evaluateExpression } from \"../helpers\";\n\nexport function executeEnd(\n\tstep: WorkflowStep & { type: \"end\" },\n\tscope: Record<string, unknown>,\n): unknown {\n\tif (step.params?.output) {\n\t\treturn evaluateExpression(step.params.output as Expression, scope, step.id);\n\t}\n\treturn undefined;\n}\n",
|
|
25
|
+
"import { safeValidateTypes } from \"@ai-sdk/provider-utils\";\nimport { search } from \"@jmespath-community/jmespath\";\nimport {\n\tjsonSchema,\n\ttype LanguageModel,\n\tOutput,\n\tstepCountIs,\n\tToolLoopAgent,\n\ttool,\n} from \"ai\";\nimport type { WorkflowStep } from \"../../types\";\nimport {\n\tConfigurationError,\n\tExtractionError,\n\tOutputQualityError,\n\tStepExecutionError,\n} from \"../errors\";\nimport type {\n\tExecutorLimits,\n\tExpression,\n\tResolvedExecuteWorkflowOptions,\n} from \"../executor-types\";\nimport {\n\tclassifyLlmError,\n\tcreateGiveUpTool,\n\tcreateProbeDataTool,\n\tevaluateExpression,\n} from \"../helpers\";\nimport { summarizeObjectStructure } from \"../schema-inference\";\nimport type { TraceEntry } from \"../state\";\n\ntype StepOutput = { output: unknown; trace?: TraceEntry[] };\n\nexport async function executeExtractData(\n\tstep: WorkflowStep & { type: \"extract-data\" },\n\tscope: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tlimits: Required<ExecutorLimits>,\n): Promise<StepOutput> {\n\tif (!options.model) {\n\t\tthrow new ConfigurationError(\n\t\t\tstep.id,\n\t\t\t\"AGENT_NOT_PROVIDED\",\n\t\t\t\"extract-data steps require a LanguageModel to be provided\",\n\t\t);\n\t}\n\tconst { model } = options;\n\n\tconst sourceData = evaluateExpression(\n\t\tstep.params.sourceData as Expression,\n\t\tscope,\n\t\tstep.id,\n\t);\n\tconst sourceStr =\n\t\ttypeof sourceData === \"string\"\n\t\t\t? sourceData\n\t\t\t: JSON.stringify(sourceData, null, 2);\n\n\t// Determine if we need probe mode: data is large, we have a raw model,\n\t// and the source data is structured (not plain text)\n\tconst byteLength = new TextEncoder().encode(sourceStr).byteLength;\n\tlet useProbeMode = byteLength > limits.probeThresholdBytes;\n\n\t// If source data is a string, check if it's parseable JSON — probe mode\n\t// needs structured data for schema inference and JMESPath queries\n\tif (useProbeMode && typeof sourceData === \"string\") {\n\t\ttry {\n\t\t\tJSON.parse(sourceData);\n\t\t} catch {\n\t\t\tuseProbeMode = false;\n\t\t}\n\t}\n\n\tif (useProbeMode) {\n\t\tconst structuredData =\n\t\t\ttypeof sourceData === \"string\" ? JSON.parse(sourceData) : sourceData;\n\t\treturn executeExtractDataProbe(step, structuredData, model, limits);\n\t}\n\n\t// Inline mode: send all data in the prompt with structured output\n\tconst agent = new ToolLoopAgent({\n\t\tmodel: model,\n\t\toutput: Output.object({\n\t\t\tschema: jsonSchema(\n\t\t\t\tstep.params.outputFormat as Parameters<typeof jsonSchema>[0],\n\t\t\t),\n\t\t}),\n\t\tstopWhen: stepCountIs(1),\n\t});\n\tconst prompt = `Extract the following structured data from the provided source data.\\n\\nSource data:\\n${sourceStr}`;\n\ttry {\n\t\tconst result = await agent.generate({ prompt });\n\t\tconst trace: TraceEntry[] = result.steps.map((s) => ({\n\t\t\ttype: \"agent-step\" as const,\n\t\t\tstep: s,\n\t\t}));\n\t\treturn { output: result.output, trace };\n\t} catch (e) {\n\t\tif (e instanceof StepExecutionError) throw e;\n\t\tthrow classifyLlmError(step.id, e);\n\t}\n}\n\nasync function executeExtractDataProbe(\n\tstep: WorkflowStep & { type: \"extract-data\" },\n\tsourceData: unknown,\n\tmodel: LanguageModel,\n\tlimits: Required<ExecutorLimits>,\n): Promise<StepOutput> {\n\tconst structureSummary = summarizeObjectStructure(sourceData as object, 2);\n\n\t// Closure variable for capturing submit-result output\n\tlet submittedResult: unknown;\n\n\tconst outputSchema = jsonSchema(\n\t\tstep.params.outputFormat as Parameters<typeof jsonSchema>[0],\n\t);\n\n\tconst probeDataTool = createProbeDataTool(sourceData, limits);\n\tconst giveUp = createGiveUpTool();\n\n\tconst submitResultTool = tool({\n\t\tdescription:\n\t\t\t\"Submit the extracted data. Provide either `data` (the object directly) or `expression` (a JMESPath expression that evaluates to it). The result is validated against the target schema.\",\n\t\tinputSchema: jsonSchema<{ data?: unknown; expression?: string }>({\n\t\t\ttype: \"object\" as const,\n\t\t\tproperties: {\n\t\t\t\tdata: { description: \"The extracted data object directly\" },\n\t\t\t\texpression: {\n\t\t\t\t\ttype: \"string\" as const,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"A JMESPath expression that evaluates to the extracted data\",\n\t\t\t\t},\n\t\t\t},\n\t\t}),\n\t\texecute: async (input) => {\n\t\t\tlet result: unknown;\n\n\t\t\tif (input.expression !== undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tresult = search(\n\t\t\t\t\t\tsourceData as Parameters<typeof search>[0],\n\t\t\t\t\t\tinput.expression,\n\t\t\t\t\t);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`JMESPath error: ${e instanceof Error ? e.message : String(e)}. Fix the expression and try again.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (input.data !== undefined) {\n\t\t\t\tresult = input.data;\n\t\t\t} else {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Provide either `data` or `expression` to submit a result.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate against the output schema\n\t\t\tconst validation = await safeValidateTypes({\n\t\t\t\tvalue: result,\n\t\t\t\tschema: outputSchema,\n\t\t\t});\n\t\t\tif (!validation.success) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Result does not match the target output schema: ${validation.error.message}. Fix the data or expression and try again.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsubmittedResult = validation.value;\n\t\t\treturn { success: true };\n\t\t},\n\t});\n\n\tconst agent = new ToolLoopAgent({\n\t\tmodel,\n\t\ttools: {\n\t\t\t\"probe-data\": probeDataTool,\n\t\t\t\"submit-result\": submitResultTool,\n\t\t\t\"give-up\": giveUp.tool,\n\t\t},\n\t\tstopWhen: [\n\t\t\t() => submittedResult !== undefined || giveUp.getReason() !== undefined,\n\t\t\tstepCountIs(limits.probeMaxSteps),\n\t\t],\n\t});\n\n\tconst schemaStr = JSON.stringify(step.params.outputFormat, null, 2);\n\tconst prompt = `You need to extract structured data from a large dataset. The data is too large to include directly, so you have three tools:\n\n- probe-data: Query the data with a JMESPath expression to explore its contents.\n- submit-result: Submit the final extraction. Pass either \\`data\\` (the object directly) or \\`expression\\` (a JMESPath expression that evaluates to it). The result is validated against the target schema — if invalid, you'll get an error and can retry.\n- give-up: Call this if you determine the requested data cannot be found or extracted.\n\n## Data Structure Summary\n\\`\\`\\`\n${structureSummary}\n\\`\\`\\`\n\n## Target Output Schema\n\\`\\`\\`json\n${schemaStr}\n\\`\\`\\`\n\n## Instructions\n1. Use probe-data with JMESPath expressions to explore and extract values you need.\n2. When you have all the data, call submit-result with either the data directly or a JMESPath expression that produces it.\n3. If the data you need is not present or cannot be extracted, call give-up with a reason.`;\n\n\tlet result: Awaited<ReturnType<typeof agent.generate>>;\n\ttry {\n\t\tresult = await agent.generate({ prompt });\n\t} catch (e) {\n\t\tif (e instanceof StepExecutionError) throw e;\n\t\tthrow classifyLlmError(step.id, e);\n\t}\n\n\tconst trace: TraceEntry[] = result.steps.map((s) => ({\n\t\ttype: \"agent-step\" as const,\n\t\tstep: s,\n\t}));\n\n\tif (submittedResult !== undefined) {\n\t\treturn { output: submittedResult, trace };\n\t}\n\n\tif (giveUp.getReason() !== undefined) {\n\t\tthrow new ExtractionError(\n\t\t\tstep.id,\n\t\t\t`LLM was unable to extract the requested data: ${giveUp.getReason()}`,\n\t\t\tgiveUp.getReason() as string,\n\t\t);\n\t}\n\n\tthrow new OutputQualityError(\n\t\tstep.id,\n\t\t\"LLM_OUTPUT_PARSE_ERROR\",\n\t\t\"extract-data probe mode exhausted all steps without submitting a result\",\n\t\tundefined,\n\t);\n}\n\nexport function resolveExtractDataInputs(\n\tstep: WorkflowStep & { type: \"extract-data\" },\n\tscope: Record<string, unknown>,\n): unknown {\n\ttry {\n\t\treturn {\n\t\t\tsourceData: evaluateExpression(\n\t\t\t\tstep.params.sourceData as Expression,\n\t\t\t\tscope,\n\t\t\t\tstep.id,\n\t\t\t),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n",
|
|
26
|
+
"function deepEqual(a: unknown, b: unknown): boolean {\n\treturn JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Strips array length annotations from a schema so that structural comparison\n * ignores differences like string[1] vs string[2]. Used for dictionary detection\n * where values have the same shape but varying array sizes.\n */\nfunction normalizeSchemaShape(schema: unknown): unknown {\n\tif (schema === null || schema === undefined) return schema;\n\tif (typeof schema === \"string\") return schema;\n\tif (Array.isArray(schema)) {\n\t\t// Uniform array [elementSchema, length] → normalize element, drop length\n\t\tif (schema.length === 2 && typeof schema[1] === \"number\") {\n\t\t\treturn [normalizeSchemaShape(schema[0]), 0];\n\t\t}\n\t\treturn schema.map(normalizeSchemaShape);\n\t}\n\tif (typeof schema === \"object\") {\n\t\tconst normalized: Record<string, unknown> = {};\n\t\tfor (const [key, val] of Object.entries(schema)) {\n\t\t\tnormalized[key] = normalizeSchemaShape(val);\n\t\t}\n\t\treturn normalized;\n\t}\n\treturn schema;\n}\n\nfunction mostCommon<T>(arr: T[]): T | null {\n\tif (arr.length === 0) return null;\n\n\tconst counts = new Map<number, { element: T; count: number }>();\n\n\tarr.forEach((item) => {\n\t\tlet found = false;\n\t\tfor (const [_idx, entry] of counts.entries()) {\n\t\t\tif (deepEqual(item, entry.element)) {\n\t\t\t\tentry.count++;\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!found) {\n\t\t\tcounts.set(counts.size, { element: item, count: 1 });\n\t\t}\n\t});\n\n\tlet max = { element: arr[0] as T, count: 0 };\n\tfor (const entry of counts.values()) {\n\t\tif (entry.count > max.count) max = entry;\n\t}\n\n\treturn max.element;\n}\n\nexport function inferSchema(\n\tvalue: unknown,\n\ttypes: unknown[] = [],\n\tmaxKeys = 20,\n) {\n\tlet schema: unknown;\n\tif (value === null) {\n\t\tschema = \"null\";\n\t} else if (value === undefined) {\n\t\tschema = \"undefined\";\n\t} else if (typeof value === \"object\") {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst elementSchemas = value.map((element) =>\n\t\t\t\tinferSchema(element, types, maxKeys),\n\t\t\t);\n\n\t\t\tconst mostCommonElementSchema = mostCommon(elementSchemas);\n\n\t\t\tconst percentUniformSchemas =\n\t\t\t\telementSchemas.filter((schema) =>\n\t\t\t\t\tdeepEqual(schema, mostCommonElementSchema),\n\t\t\t\t).length / elementSchemas.length;\n\n\t\t\tconst allElementsHaveSameSchema = percentUniformSchemas >= 0.5;\n\n\t\t\tif (allElementsHaveSameSchema) {\n\t\t\t\tschema = [mostCommonElementSchema, value.length];\n\t\t\t} else {\n\t\t\t\tschema = elementSchemas;\n\t\t\t}\n\t\t} else {\n\t\t\tconst keys = Object.keys(value);\n\t\t\tconst totalKeys = keys.length;\n\n\t\t\t// Check for dictionary pattern: many keys with identical complex value schemas\n\t\t\t// Sample up to maxKeys to avoid expensive inference on very large objects\n\t\t\tif (totalKeys >= 3) {\n\t\t\t\tconst sampleKeys = keys.slice(0, maxKeys);\n\t\t\t\tconst valueSchemas = sampleKeys.map((key) =>\n\t\t\t\t\tinferSchema((value as Record<string, unknown>)[key], [], maxKeys),\n\t\t\t\t);\n\n\t\t\t\t// Compare normalized schemas (ignoring array lengths)\n\t\t\t\tconst normalizedSchemas = valueSchemas.map(normalizeSchemaShape);\n\t\t\t\tconst mostCommonNormalized = mostCommon(normalizedSchemas);\n\n\t\t\t\tif (\n\t\t\t\t\tmostCommonNormalized !== null &&\n\t\t\t\t\ttypeof mostCommonNormalized === \"object\" &&\n\t\t\t\t\tmostCommonNormalized !== null\n\t\t\t\t) {\n\t\t\t\t\tconst uniformCount = normalizedSchemas.filter((s) =>\n\t\t\t\t\t\tdeepEqual(s, mostCommonNormalized),\n\t\t\t\t\t).length;\n\t\t\t\t\tconst percentUniform = uniformCount / sampleKeys.length;\n\n\t\t\t\t\tif (uniformCount >= 3 && percentUniform >= 0.75) {\n\t\t\t\t\t\t// Use the first matching (non-normalized) schema as representative\n\t\t\t\t\t\tconst representativeSchema = valueSchemas.find((s) =>\n\t\t\t\t\t\t\tdeepEqual(normalizeSchemaShape(s), mostCommonNormalized),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tschema = {\n\t\t\t\t\t\t\t__dict: [representativeSchema, totalKeys],\n\t\t\t\t\t\t};\n\t\t\t\t\t\ttypes.push(schema);\n\t\t\t\t\t\treturn schema;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst _schema: Record<string, unknown> = {};\n\t\t\tconst keysToInclude = keys.slice(0, maxKeys);\n\n\t\t\tfor (const key of keysToInclude) {\n\t\t\t\t_schema[key] = inferSchema(\n\t\t\t\t\t(value as Record<string, unknown>)[key],\n\t\t\t\t\ttypes,\n\t\t\t\t\tmaxKeys,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (totalKeys > maxKeys) {\n\t\t\t\t_schema[`...${totalKeys - maxKeys} more keys`] = \"truncated\";\n\t\t\t}\n\n\t\t\tschema = _schema;\n\t\t}\n\t} else if (typeof value === \"string\") {\n\t\tschema = \"string\";\n\t} else if (typeof value === \"number\") {\n\t\tschema = \"number\";\n\t} else if (typeof value === \"boolean\") {\n\t\tschema = \"boolean\";\n\t} else {\n\t\tschema = \"unknown\";\n\t}\n\n\ttypes.push(schema);\n\treturn schema;\n}\n\nfunction schemaToString(schema: unknown, indent?: string | number): string {\n\tconst indentStr = typeof indent === \"number\" ? \" \".repeat(indent) : indent;\n\tconst pretty = indentStr !== undefined;\n\n\tfunction stringify(value: unknown, depth = 0): string {\n\t\t// Handle null and undefined\n\t\tif (value === null) return \"null\";\n\t\tif (value === undefined) return \"undefined\";\n\n\t\t// Handle primitive types (strings)\n\t\tif (typeof value === \"string\") return value;\n\n\t\t// Handle arrays - check if it's the special [schema, length] format\n\t\tif (Array.isArray(value)) {\n\t\t\t// Check if this is a uniform array representation: [schema, length]\n\t\t\tif (value.length === 2 && typeof value[1] === \"number\") {\n\t\t\t\t// Transform [schema, length] -> schema[length]\n\t\t\t\treturn `${stringify(value[0], depth)}[${value[1]}]`;\n\t\t\t}\n\n\t\t\t// Otherwise it's a heterogeneous array, stringify each element\n\t\t\tif (!pretty || !indentStr) {\n\t\t\t\treturn `[${value.map((v) => stringify(v, depth)).join(\", \")}]`;\n\t\t\t}\n\n\t\t\tconst currentIndent = indentStr.repeat(depth);\n\t\t\tconst nextIndent = indentStr.repeat(depth + 1);\n\t\t\tconst items = value\n\t\t\t\t.map((v) => `${nextIndent}${stringify(v, depth + 1)}`)\n\t\t\t\t.join(\",\\n\");\n\t\t\treturn `[\\n${items}\\n${currentIndent}]`;\n\t\t}\n\n\t\t// Handle objects\n\t\tif (typeof value === \"object\") {\n\t\t\t// Check for dictionary marker: { __dict: [valueSchema, count] }\n\t\t\tconst entries = Object.entries(value);\n\t\t\tconst first = entries[0];\n\t\t\tif (\n\t\t\t\tentries.length === 1 &&\n\t\t\t\tfirst !== undefined &&\n\t\t\t\tfirst[0] === \"__dict\" &&\n\t\t\t\tArray.isArray(first[1]) &&\n\t\t\t\tfirst[1].length === 2 &&\n\t\t\t\ttypeof first[1][1] === \"number\"\n\t\t\t) {\n\t\t\t\tconst [valueSchema, count] = first[1];\n\t\t\t\tif (!pretty || !indentStr) {\n\t\t\t\t\treturn `{ [key]: ${stringify(valueSchema, depth)} }[${count}]`;\n\t\t\t\t}\n\t\t\t\tconst currentIndent = indentStr.repeat(depth);\n\t\t\t\tconst nextIndent = indentStr.repeat(depth + 1);\n\t\t\t\treturn `{\\n${nextIndent}[key]: ${stringify(valueSchema, depth + 1)}\\n${currentIndent}}[${count}]`;\n\t\t\t}\n\n\t\t\tif (!pretty || !indentStr) {\n\t\t\t\tconst formatted = entries\n\t\t\t\t\t.map(([key, val]) => `${key}: ${stringify(val, depth)}`)\n\t\t\t\t\t.join(\", \");\n\t\t\t\treturn `{ ${formatted} }`;\n\t\t\t}\n\n\t\t\tconst currentIndent = indentStr.repeat(depth);\n\t\t\tconst nextIndent = indentStr.repeat(depth + 1);\n\t\t\tconst formatted = entries\n\t\t\t\t.map(\n\t\t\t\t\t([key, val]) => `${nextIndent}${key}: ${stringify(val, depth + 1)}`,\n\t\t\t\t)\n\t\t\t\t.join(\",\\n\");\n\t\t\treturn `{\\n${formatted}\\n${currentIndent}}`;\n\t\t}\n\n\t\t// Fallback to JSON.stringify for other types\n\t\treturn JSON.stringify(value);\n\t}\n\n\treturn stringify(schema);\n}\n\nexport function summarizeObjectStructure(\n\tvalue: object,\n\tindent?: string | number,\n) {\n\tconst schema = inferSchema(value);\n\treturn schemaToString(schema, indent);\n}\n",
|
|
27
|
+
"import type { WorkflowStep } from \"../../types\";\nimport type { DurableContext } from \"../context\";\nimport { ValidationError } from \"../errors\";\nimport type {\n\tExecuteChainFn,\n\tExecutionStateManager,\n\tExpression,\n\tResolvedExecuteWorkflowOptions,\n} from \"../executor-types\";\nimport { evaluateExpression } from \"../helpers\";\nimport type { ExecutionPathSegment } from \"../state\";\n\nexport async function executeForEach(\n\tstep: WorkflowStep & { type: \"for-each\" },\n\tscope: Record<string, unknown>,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tcontext: DurableContext,\n\tstateManager: ExecutionStateManager | undefined,\n\texecPath: ExecutionPathSegment[],\n\texecuteChain: ExecuteChainFn,\n): Promise<unknown[]> {\n\tconst target = evaluateExpression(\n\t\tstep.params.target as Expression,\n\t\tscope,\n\t\tstep.id,\n\t);\n\n\tif (!Array.isArray(target)) {\n\t\tthrow new ValidationError(\n\t\t\tstep.id,\n\t\t\t\"FOREACH_TARGET_NOT_ARRAY\",\n\t\t\t`for-each target must be an array, got ${typeof target}`,\n\t\t\ttarget,\n\t\t);\n\t}\n\n\tconst results: unknown[] = [];\n\tfor (let i = 0; i < target.length; i++) {\n\t\tconst item = target[i];\n\t\tconst iterationPath: ExecutionPathSegment[] = [\n\t\t\t...execPath,\n\t\t\t{\n\t\t\t\ttype: \"for-each\" as const,\n\t\t\t\tstepId: step.id,\n\t\t\t\titerationIndex: i,\n\t\t\t\titemValue: item,\n\t\t\t},\n\t\t];\n\t\tconst innerLoopVars = { ...loopVars, [step.params.itemName]: item };\n\t\tconst lastOutput = await executeChain(\n\t\t\tstep.params.loopBodyStepId,\n\t\t\tstepIndex,\n\t\t\tstepOutputs,\n\t\t\tinnerLoopVars,\n\t\t\toptions,\n\t\t\tcontext,\n\t\t\tundefined,\n\t\t\tstateManager,\n\t\t\titerationPath,\n\t\t);\n\t\tresults.push(lastOutput);\n\t}\n\treturn results;\n}\n\nexport function resolveForEachInputs(\n\tstep: WorkflowStep & { type: \"for-each\" },\n\tscope: Record<string, unknown>,\n): unknown {\n\ttry {\n\t\treturn {\n\t\t\ttarget: evaluateExpression(\n\t\t\t\tstep.params.target as Expression,\n\t\t\t\tscope,\n\t\t\t\tstep.id,\n\t\t\t),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n",
|
|
28
|
+
"import { jsonSchema, Output, stepCountIs, ToolLoopAgent } from \"ai\";\nimport type { WorkflowStep } from \"../../types\";\nimport { ConfigurationError, StepExecutionError } from \"../errors\";\nimport type { ResolvedExecuteWorkflowOptions } from \"../executor-types\";\nimport { classifyLlmError, interpolateTemplate } from \"../helpers\";\nimport type { TraceEntry } from \"../state\";\n\nexport async function executeLlmPrompt(\n\tstep: WorkflowStep & { type: \"llm-prompt\" },\n\tscope: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n): Promise<{ output: unknown; trace?: TraceEntry[] }> {\n\tif (!options.model) {\n\t\tthrow new ConfigurationError(\n\t\t\tstep.id,\n\t\t\t\"AGENT_NOT_PROVIDED\",\n\t\t\t\"llm-prompt steps require a LanguageModel to be provided\",\n\t\t);\n\t}\n\n\tconst prompt = interpolateTemplate(step.params.prompt, scope, step.id);\n\n\tconst agent = new ToolLoopAgent({\n\t\tmodel: options.model,\n\t\toutput: Output.object({\n\t\t\tschema: jsonSchema(\n\t\t\t\tstep.params.outputFormat as Parameters<typeof jsonSchema>[0],\n\t\t\t),\n\t\t}),\n\t\tstopWhen: stepCountIs(1),\n\t});\n\n\ttry {\n\t\tconst result = await agent.generate({ prompt });\n\t\tconst trace: TraceEntry[] = result.steps.map((s) => ({\n\t\t\ttype: \"agent-step\" as const,\n\t\t\tstep: s,\n\t\t}));\n\t\treturn { output: result.output, trace };\n\t} catch (e) {\n\t\tif (e instanceof StepExecutionError) throw e;\n\t\tthrow classifyLlmError(step.id, e);\n\t}\n}\n\nexport function resolveLlmPromptInputs(\n\tstep: WorkflowStep & { type: \"llm-prompt\" },\n\tscope: Record<string, unknown>,\n): unknown {\n\ttry {\n\t\treturn {\n\t\t\tprompt: interpolateTemplate(step.params.prompt, scope, step.id),\n\t\t};\n\t} catch {\n\t\treturn { prompt: step.params.prompt };\n\t}\n}\n",
|
|
29
|
+
"import type { WorkflowStep } from \"../../types\";\nimport type { DurableContext } from \"../context\";\nimport { ValidationError } from \"../errors\";\nimport type { ExecutionTimer, Expression } from \"../executor-types\";\nimport { evaluateExpression } from \"../helpers\";\n\nexport async function executeSleep(\n\tstep: WorkflowStep & { type: \"sleep\" },\n\tscope: Record<string, unknown>,\n\tcontext: DurableContext,\n\ttimer: ExecutionTimer,\n): Promise<void> {\n\tconst durationMs = evaluateExpression(\n\t\tstep.params.durationMs as Expression,\n\t\tscope,\n\t\tstep.id,\n\t);\n\tif (typeof durationMs !== \"number\" || durationMs < 0) {\n\t\tthrow new ValidationError(\n\t\t\tstep.id,\n\t\t\t\"SLEEP_INVALID_DURATION\",\n\t\t\t`sleep durationMs must be a non-negative number, got ${typeof durationMs === \"number\" ? durationMs : typeof durationMs}`,\n\t\t\tdurationMs,\n\t\t);\n\t}\n\tconst clamped = Math.min(durationMs, timer.resolvedLimits.maxSleepMs);\n\tawait context.sleep(step.id, clamped);\n}\n",
|
|
30
|
+
"export function executeStart(): undefined {\n\treturn undefined;\n}\n",
|
|
31
|
+
"import type { WorkflowStep } from \"../../types\";\nimport type { DurableContext } from \"../context\";\nimport type {\n\tExecuteChainFn,\n\tExecutionStateManager,\n\tExpression,\n\tResolvedExecuteWorkflowOptions,\n} from \"../executor-types\";\nimport { evaluateExpression } from \"../helpers\";\nimport type { ExecutionPathSegment } from \"../state\";\n\nexport async function executeSwitchCase(\n\tstep: WorkflowStep & { type: \"switch-case\" },\n\tscope: Record<string, unknown>,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tcontext: DurableContext,\n\tstateManager: ExecutionStateManager | undefined,\n\texecPath: ExecutionPathSegment[],\n\texecuteChain: ExecuteChainFn,\n): Promise<unknown> {\n\tconst switchValue = evaluateExpression(\n\t\tstep.params.switchOn as Expression,\n\t\tscope,\n\t\tstep.id,\n\t);\n\n\tlet matchedBranchId: string | undefined;\n\tlet defaultBranchId: string | undefined;\n\tlet matchedCaseIndex = -1;\n\n\tfor (let i = 0; i < step.params.cases.length; i++) {\n\t\tconst c = step.params.cases[i] as (typeof step.params.cases)[number];\n\t\tif (c.value.type === \"default\") {\n\t\t\tdefaultBranchId = c.branchBodyStepId;\n\t\t\tif (matchedCaseIndex === -1) matchedCaseIndex = i;\n\t\t} else {\n\t\t\tconst caseValue = evaluateExpression(\n\t\t\t\tc.value as Expression,\n\t\t\t\tscope,\n\t\t\t\tstep.id,\n\t\t\t);\n\t\t\tif (caseValue === switchValue) {\n\t\t\t\tmatchedBranchId = c.branchBodyStepId;\n\t\t\t\tmatchedCaseIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst selectedBranchId = matchedBranchId ?? defaultBranchId;\n\tif (!selectedBranchId) {\n\t\treturn undefined;\n\t}\n\n\tconst branchPath: ExecutionPathSegment[] = [\n\t\t...execPath,\n\t\t{\n\t\t\ttype: \"switch-case\" as const,\n\t\t\tstepId: step.id,\n\t\t\tmatchedCaseIndex,\n\t\t\tmatchedValue: switchValue,\n\t\t},\n\t];\n\n\treturn await executeChain(\n\t\tselectedBranchId,\n\t\tstepIndex,\n\t\tstepOutputs,\n\t\tloopVars,\n\t\toptions,\n\t\tcontext,\n\t\tundefined,\n\t\tstateManager,\n\t\tbranchPath,\n\t);\n}\n\nexport function resolveSwitchCaseInputs(\n\tstep: WorkflowStep & { type: \"switch-case\" },\n\tscope: Record<string, unknown>,\n): unknown {\n\ttry {\n\t\treturn {\n\t\t\tswitchOn: evaluateExpression(\n\t\t\t\tstep.params.switchOn as Expression,\n\t\t\t\tscope,\n\t\t\t\tstep.id,\n\t\t\t),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n",
|
|
32
|
+
"import { safeValidateTypes } from \"@ai-sdk/provider-utils\";\nimport type { ToolSet } from \"ai\";\nimport type { WorkflowStep } from \"../../types\";\nimport {\n\tConfigurationError,\n\tExternalServiceError,\n\tValidationError,\n} from \"../errors\";\nimport type { Expression } from \"../executor-types\";\nimport { evaluateExpression } from \"../helpers\";\n\nexport async function executeToolCall(\n\tstep: WorkflowStep & { type: \"tool-call\" },\n\tscope: Record<string, unknown>,\n\ttools: ToolSet,\n): Promise<unknown> {\n\t// Tool existence and executability are validated in pre-flight checks\n\tconst toolDef = tools[step.params.toolName];\n\tif (!toolDef?.execute) {\n\t\tthrow new ConfigurationError(\n\t\t\tstep.id,\n\t\t\t\"TOOL_NOT_FOUND\",\n\t\t\t`Tool '${step.params.toolName}' not found or has no execute function`,\n\t\t);\n\t}\n\n\tconst resolvedInput: Record<string, unknown> = {};\n\tfor (const [key, expr] of Object.entries(step.params.toolInput)) {\n\t\tresolvedInput[key] = evaluateExpression(expr as Expression, scope, step.id);\n\t}\n\n\tif (toolDef.inputSchema) {\n\t\tconst validation = await safeValidateTypes({\n\t\t\tvalue: resolvedInput,\n\t\t\tschema: toolDef.inputSchema,\n\t\t});\n\t\tif (!validation.success) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tstep.id,\n\t\t\t\t\"TOOL_INPUT_VALIDATION_FAILED\",\n\t\t\t\t`Tool '${step.params.toolName}' input validation failed: ${validation.error.message}`,\n\t\t\t\tresolvedInput,\n\t\t\t\tvalidation.error,\n\t\t\t);\n\t\t}\n\t}\n\n\ttry {\n\t\treturn await toolDef.execute(resolvedInput, {\n\t\t\ttoolCallId: step.id,\n\t\t\tmessages: [],\n\t\t});\n\t} catch (e) {\n\t\tthrow new ExternalServiceError(\n\t\t\tstep.id,\n\t\t\t\"TOOL_EXECUTION_FAILED\",\n\t\t\te instanceof Error ? e.message : String(e),\n\t\t\te,\n\t\t);\n\t}\n}\n\nexport function resolveToolCallInputs(\n\tstep: WorkflowStep & { type: \"tool-call\" },\n\tscope: Record<string, unknown>,\n): unknown {\n\tconst resolved: Record<string, unknown> = {};\n\tfor (const [key, expr] of Object.entries(step.params.toolInput)) {\n\t\ttry {\n\t\t\tresolved[key] = evaluateExpression(expr as Expression, scope, step.id);\n\t\t} catch {\n\t\t\tresolved[key] = `<error resolving ${key}>`;\n\t\t}\n\t}\n\treturn resolved;\n}\n",
|
|
33
|
+
"import type { WorkflowStep } from \"../../types\";\nimport type { DurableContext } from \"../context\";\nimport type {\n\tExecuteChainFn,\n\tExecutionStateManager,\n\tExecutionTimer,\n\tExpression,\n\tResolvedExecuteWorkflowOptions,\n} from \"../executor-types\";\nimport { evaluateExpression } from \"../helpers\";\nimport type { ExecutionPathSegment } from \"../state\";\n\nexport async function executeWaitForCondition(\n\tstep: WorkflowStep & { type: \"wait-for-condition\" },\n\tscope: Record<string, unknown>,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tcontext: DurableContext,\n\ttimer: ExecutionTimer,\n\tstateManager: ExecutionStateManager | undefined,\n\texecPath: ExecutionPathSegment[],\n\texecuteChain: ExecuteChainFn,\n): Promise<unknown> {\n\tconst limits = timer.resolvedLimits;\n\n\tconst maxAttempts = Math.min(\n\t\tstep.params.maxAttempts\n\t\t\t? (evaluateExpression(\n\t\t\t\t\tstep.params.maxAttempts as Expression,\n\t\t\t\t\tscope,\n\t\t\t\t\tstep.id,\n\t\t\t\t) as number)\n\t\t\t: 10,\n\t\tlimits.maxAttempts,\n\t);\n\tconst intervalMs = Math.min(\n\t\tstep.params.intervalMs\n\t\t\t? (evaluateExpression(\n\t\t\t\t\tstep.params.intervalMs as Expression,\n\t\t\t\t\tscope,\n\t\t\t\t\tstep.id,\n\t\t\t\t) as number)\n\t\t\t: 1000,\n\t\tlimits.maxSleepMs,\n\t);\n\tconst rawBackoff = step.params.backoffMultiplier\n\t\t? (evaluateExpression(\n\t\t\t\tstep.params.backoffMultiplier as Expression,\n\t\t\t\tscope,\n\t\t\t\tstep.id,\n\t\t\t) as number)\n\t\t: 1;\n\tconst backoffMultiplier = Math.max(\n\t\tlimits.minBackoffMultiplier,\n\t\tMath.min(rawBackoff, limits.maxBackoffMultiplier),\n\t);\n\tconst timeoutMs = step.params.timeoutMs\n\t\t? Math.min(\n\t\t\t\tevaluateExpression(\n\t\t\t\t\tstep.params.timeoutMs as Expression,\n\t\t\t\t\tscope,\n\t\t\t\t\tstep.id,\n\t\t\t\t) as number,\n\t\t\t\tlimits.maxTimeoutMs,\n\t\t\t)\n\t\t: undefined;\n\n\tlet pollAttempt = 0;\n\treturn context.waitForCondition(\n\t\tstep.id,\n\t\tasync () => {\n\t\t\tconst pollPath: ExecutionPathSegment[] = [\n\t\t\t\t...execPath,\n\t\t\t\t{\n\t\t\t\t\ttype: \"wait-for-condition\" as const,\n\t\t\t\t\tstepId: step.id,\n\t\t\t\t\tpollAttempt: pollAttempt++,\n\t\t\t\t},\n\t\t\t];\n\t\t\ttimer.beginActive();\n\t\t\ttry {\n\t\t\t\tawait executeChain(\n\t\t\t\t\tstep.params.conditionStepId,\n\t\t\t\t\tstepIndex,\n\t\t\t\t\tstepOutputs,\n\t\t\t\t\tloopVars,\n\t\t\t\t\toptions,\n\t\t\t\t\tcontext,\n\t\t\t\t\tundefined,\n\t\t\t\t\tstateManager,\n\t\t\t\t\tpollPath,\n\t\t\t\t);\n\t\t\t\tconst updatedScope = { ...stepOutputs, ...loopVars };\n\t\t\t\treturn evaluateExpression(\n\t\t\t\t\tstep.params.condition as Expression,\n\t\t\t\t\tupdatedScope,\n\t\t\t\t\tstep.id,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\ttimer.endActive(step.id);\n\t\t\t}\n\t\t},\n\t\t{ maxAttempts, intervalMs, backoffMultiplier, timeoutMs },\n\t);\n}\n",
|
|
34
|
+
"import type { WorkflowDefinition, WorkflowStep } from \"../types\";\nimport { createDefaultDurableContext, type DurableContext } from \"./context\";\nimport {\n\tConfigurationError,\n\tExternalServiceError,\n\tStepExecutionError,\n\tValidationError,\n} from \"./errors\";\nimport {\n\ttype ExecuteChainFn,\n\ttype ExecuteWorkflowOptions,\n\ttype ExecutionResult,\n\tExecutionStateManager,\n\tExecutionTimer,\n\ttype ResolvedExecuteWorkflowOptions,\n} from \"./executor-types\";\nimport type { ExecutionPathSegment, TraceEntry } from \"./state\";\n\nexport type {\n\tExecuteWorkflowOptions,\n\tExecutionResult,\n\tExecutorLimits,\n} from \"./executor-types\";\n\n// ─── Step Imports ────────────────────────────────────────────────\n\nimport { executeAgentLoop, resolveAgentLoopInputs } from \"./steps/agent-loop\";\nimport { executeEnd } from \"./steps/end\";\nimport {\n\texecuteExtractData,\n\tresolveExtractDataInputs,\n} from \"./steps/extract-data\";\nimport { executeForEach, resolveForEachInputs } from \"./steps/for-each\";\nimport { executeLlmPrompt, resolveLlmPromptInputs } from \"./steps/llm-prompt\";\nimport { executeSleep } from \"./steps/sleep\";\nimport { executeStart } from \"./steps/start\";\nimport {\n\texecuteSwitchCase,\n\tresolveSwitchCaseInputs,\n} from \"./steps/switch-case\";\nimport { executeToolCall, resolveToolCallInputs } from \"./steps/tool-call\";\nimport { executeWaitForCondition } from \"./steps/wait-for-condition\";\n\n// ─── Input Validation ────────────────────────────────────────────\n\nfunction validateWorkflowInputs(\n\tinputSchema: Record<string, unknown> | undefined,\n\tinputs: Record<string, unknown>,\n): void {\n\tif (!inputSchema || typeof inputSchema !== \"object\") return;\n\n\tconst required = inputSchema.required;\n\tif (Array.isArray(required)) {\n\t\tconst missing = required.filter(\n\t\t\t(key: unknown) => typeof key === \"string\" && !(key in inputs),\n\t\t);\n\t\tif (missing.length > 0) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"input\",\n\t\t\t\t\"TOOL_INPUT_VALIDATION_FAILED\",\n\t\t\t\t`Workflow input validation failed: missing required input(s): ${missing.join(\", \")}`,\n\t\t\t\tinputs,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst properties = inputSchema.properties;\n\tif (properties && typeof properties === \"object\") {\n\t\tfor (const [key, value] of Object.entries(inputs)) {\n\t\t\tconst propSchema = (properties as Record<string, unknown>)[key];\n\t\t\tif (\n\t\t\t\tpropSchema &&\n\t\t\t\ttypeof propSchema === \"object\" &&\n\t\t\t\t\"type\" in propSchema\n\t\t\t) {\n\t\t\t\tconst expectedType = (propSchema as { type: string }).type;\n\t\t\t\tconst actualType = typeof value;\n\t\t\t\tif (expectedType === \"integer\" || expectedType === \"number\") {\n\t\t\t\t\tif (actualType !== \"number\") {\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\"input\",\n\t\t\t\t\t\t\t\"TOOL_INPUT_VALIDATION_FAILED\",\n\t\t\t\t\t\t\t`Workflow input validation failed: input '${key}' expected type '${expectedType}' but got '${actualType}'`,\n\t\t\t\t\t\t\tinputs,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (expectedType === \"array\") {\n\t\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\"input\",\n\t\t\t\t\t\t\t\"TOOL_INPUT_VALIDATION_FAILED\",\n\t\t\t\t\t\t\t`Workflow input validation failed: input '${key}' expected type 'array' but got '${actualType}'`,\n\t\t\t\t\t\t\tinputs,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (actualType !== expectedType) {\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\"input\",\n\t\t\t\t\t\t\"TOOL_INPUT_VALIDATION_FAILED\",\n\t\t\t\t\t\t`Workflow input validation failed: input '${key}' expected type '${expectedType}' but got '${actualType}'`,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ─── Output Validation ──────────────────────────────────────────\n\nfunction validateWorkflowOutput(\n\toutputSchema: Record<string, unknown>,\n\toutput: unknown,\n\tendStepId: string,\n): void {\n\tconst expectedType = outputSchema.type;\n\tif (typeof expectedType === \"string\") {\n\t\tif (\n\t\t\texpectedType === \"object\" &&\n\t\t\t(typeof output !== \"object\" || output === null)\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tendStepId,\n\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t`Workflow output validation failed: expected type 'object' but got '${output === null ? \"null\" : typeof output}'`,\n\t\t\t\toutput,\n\t\t\t);\n\t\t}\n\t\tif (expectedType === \"array\" && !Array.isArray(output)) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tendStepId,\n\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t`Workflow output validation failed: expected type 'array' but got '${typeof output}'`,\n\t\t\t\toutput,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(expectedType === \"string\" || expectedType === \"boolean\") &&\n\t\t\ttypeof output !== expectedType\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tendStepId,\n\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t`Workflow output validation failed: expected type '${expectedType}' but got '${typeof output}'`,\n\t\t\t\toutput,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(expectedType === \"number\" || expectedType === \"integer\") &&\n\t\t\ttypeof output !== \"number\"\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tendStepId,\n\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t`Workflow output validation failed: expected type '${expectedType}' but got '${typeof output}'`,\n\t\t\t\toutput,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (typeof output === \"object\" && output !== null && !Array.isArray(output)) {\n\t\tconst required = outputSchema.required;\n\t\tif (Array.isArray(required)) {\n\t\t\tconst missing = required.filter(\n\t\t\t\t(key: unknown) =>\n\t\t\t\t\ttypeof key === \"string\" &&\n\t\t\t\t\t!(key in (output as Record<string, unknown>)),\n\t\t\t);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\tendStepId,\n\t\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t\t`Workflow output validation failed: missing required field(s): ${missing.join(\", \")}`,\n\t\t\t\t\toutput,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst properties = outputSchema.properties;\n\t\tif (properties && typeof properties === \"object\") {\n\t\t\tfor (const [key, value] of Object.entries(\n\t\t\t\toutput as Record<string, unknown>,\n\t\t\t)) {\n\t\t\t\tconst propSchema = (properties as Record<string, unknown>)[key];\n\t\t\t\tif (\n\t\t\t\t\tpropSchema &&\n\t\t\t\t\ttypeof propSchema === \"object\" &&\n\t\t\t\t\t\"type\" in propSchema\n\t\t\t\t) {\n\t\t\t\t\tconst propExpectedType = (propSchema as { type: string }).type;\n\t\t\t\t\tconst actualType = typeof value;\n\t\t\t\t\tif (propExpectedType === \"integer\" || propExpectedType === \"number\") {\n\t\t\t\t\t\tif (actualType !== \"number\") {\n\t\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\tendStepId,\n\t\t\t\t\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t\t\t\t\t`Workflow output validation failed: field '${key}' expected type '${propExpectedType}' but got '${actualType}'`,\n\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (propExpectedType === \"array\") {\n\t\t\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t\tendStepId,\n\t\t\t\t\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t\t\t\t\t`Workflow output validation failed: field '${key}' expected type 'array' but got '${actualType}'`,\n\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (actualType !== propExpectedType) {\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\tendStepId,\n\t\t\t\t\t\t\t\"WORKFLOW_OUTPUT_VALIDATION_FAILED\",\n\t\t\t\t\t\t\t`Workflow output validation failed: field '${key}' expected type '${propExpectedType}' but got '${actualType}'`,\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ─── Resolve Step Inputs (for viewer display) ───────────────────\n\nfunction resolveStepInputs(\n\tstep: WorkflowStep,\n\tscope: Record<string, unknown>,\n): unknown {\n\tswitch (step.type) {\n\t\tcase \"tool-call\":\n\t\t\treturn resolveToolCallInputs(step, scope);\n\t\tcase \"llm-prompt\":\n\t\t\treturn resolveLlmPromptInputs(step, scope);\n\t\tcase \"extract-data\":\n\t\t\treturn resolveExtractDataInputs(step, scope);\n\t\tcase \"switch-case\":\n\t\t\treturn resolveSwitchCaseInputs(step, scope);\n\t\tcase \"for-each\":\n\t\t\treturn resolveForEachInputs(step, scope);\n\t\tcase \"agent-loop\":\n\t\t\treturn resolveAgentLoopInputs(step, scope);\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n// ─── Step Dispatch ───────────────────────────────────────────────\n\n/** Return type for executeStep. LLM steps may attach trace entries for debugging. */\ntype StepOutput = {\n\toutput: unknown;\n\ttrace?: TraceEntry[];\n};\n\nasync function executeStep(\n\tstep: WorkflowStep,\n\tscope: Record<string, unknown>,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tcontext: DurableContext,\n\ttimer: ExecutionTimer,\n\tstateManager?: ExecutionStateManager,\n\texecPath: ExecutionPathSegment[] = [],\n): Promise<StepOutput> {\n\tswitch (step.type) {\n\t\tcase \"llm-prompt\":\n\t\t\treturn executeLlmPrompt(step, scope, options);\n\t\tcase \"extract-data\":\n\t\t\treturn executeExtractData(step, scope, options, timer.resolvedLimits);\n\t\tcase \"agent-loop\":\n\t\t\treturn executeAgentLoop(step, scope, options, timer.resolvedLimits);\n\t\tcase \"tool-call\":\n\t\t\treturn { output: await executeToolCall(step, scope, options.tools) };\n\t\tcase \"switch-case\":\n\t\t\treturn {\n\t\t\t\toutput: await executeSwitchCase(\n\t\t\t\t\tstep,\n\t\t\t\t\tscope,\n\t\t\t\t\tstepIndex,\n\t\t\t\t\tstepOutputs,\n\t\t\t\t\tloopVars,\n\t\t\t\t\toptions,\n\t\t\t\t\tcontext,\n\t\t\t\t\tstateManager,\n\t\t\t\t\texecPath,\n\t\t\t\t\texecuteChain,\n\t\t\t\t),\n\t\t\t};\n\t\tcase \"for-each\":\n\t\t\treturn {\n\t\t\t\toutput: await executeForEach(\n\t\t\t\t\tstep,\n\t\t\t\t\tscope,\n\t\t\t\t\tstepIndex,\n\t\t\t\t\tstepOutputs,\n\t\t\t\t\tloopVars,\n\t\t\t\t\toptions,\n\t\t\t\t\tcontext,\n\t\t\t\t\tstateManager,\n\t\t\t\t\texecPath,\n\t\t\t\t\texecuteChain,\n\t\t\t\t),\n\t\t\t};\n\t\tcase \"sleep\":\n\t\t\treturn { output: await executeSleep(step, scope, context, timer) };\n\t\tcase \"wait-for-condition\":\n\t\t\treturn {\n\t\t\t\toutput: await executeWaitForCondition(\n\t\t\t\t\tstep,\n\t\t\t\t\tscope,\n\t\t\t\t\tstepIndex,\n\t\t\t\t\tstepOutputs,\n\t\t\t\t\tloopVars,\n\t\t\t\t\toptions,\n\t\t\t\t\tcontext,\n\t\t\t\t\ttimer,\n\t\t\t\t\tstateManager,\n\t\t\t\t\texecPath,\n\t\t\t\t\texecuteChain,\n\t\t\t\t),\n\t\t\t};\n\t\tcase \"start\":\n\t\t\treturn { output: await executeStart() };\n\t\tcase \"end\":\n\t\t\treturn { output: await executeEnd(step, scope) };\n\t}\n}\n\n// ─── Error Recovery ──────────────────────────────────────────────\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_BASE_DELAY_MS = 1000;\n\nasync function retryStep(\n\tstep: WorkflowStep,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\toriginalError: StepExecutionError,\n\tcontext: DurableContext,\n\ttimer: ExecutionTimer,\n\tstateManager?: ExecutionStateManager,\n\texecPath: ExecutionPathSegment[] = [],\n): Promise<StepOutput> {\n\tconst maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n\tconst baseDelay = options.retryDelayMs ?? DEFAULT_BASE_DELAY_MS;\n\tconst scope = { ...stepOutputs, ...loopVars };\n\tfor (let attempt = 1; attempt <= maxRetries; attempt++) {\n\t\tconst retryStartedAt = new Date().toISOString();\n\t\tawait context.sleep(\n\t\t\t`${step.id}_retry_${attempt}`,\n\t\t\tbaseDelay * 2 ** (attempt - 1),\n\t\t);\n\t\ttry {\n\t\t\treturn await executeStep(\n\t\t\t\tstep,\n\t\t\t\tscope,\n\t\t\t\tstepIndex,\n\t\t\t\tstepOutputs,\n\t\t\t\tloopVars,\n\t\t\t\toptions,\n\t\t\t\tcontext,\n\t\t\t\ttimer,\n\t\t\t\tstateManager,\n\t\t\t\texecPath,\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tstateManager?.retryAttempted(step.id, execPath, {\n\t\t\t\tattempt,\n\t\t\t\tstartedAt: retryStartedAt,\n\t\t\t\tfailedAt: new Date().toISOString(),\n\t\t\t\terrorCode: e instanceof StepExecutionError ? e.code : \"UNKNOWN\",\n\t\t\t\terrorMessage: e instanceof Error ? e.message : String(e),\n\t\t\t});\n\t\t\tif (attempt === maxRetries) throw originalError;\n\t\t}\n\t}\n\tthrow originalError;\n}\n\nasync function recoverFromError(\n\terror: StepExecutionError,\n\tstep: WorkflowStep,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tcontext: DurableContext,\n\ttimer: ExecutionTimer,\n\tstateManager?: ExecutionStateManager,\n\texecPath: ExecutionPathSegment[] = [],\n): Promise<StepOutput> {\n\tswitch (error.code) {\n\t\tcase \"LLM_RATE_LIMITED\":\n\t\tcase \"LLM_NETWORK_ERROR\":\n\t\tcase \"LLM_NO_CONTENT\":\n\t\tcase \"LLM_OUTPUT_PARSE_ERROR\":\n\t\t\treturn retryStep(\n\t\t\t\tstep,\n\t\t\t\tstepIndex,\n\t\t\t\tstepOutputs,\n\t\t\t\tloopVars,\n\t\t\t\toptions,\n\t\t\t\terror,\n\t\t\t\tcontext,\n\t\t\t\ttimer,\n\t\t\t\tstateManager,\n\t\t\t\texecPath,\n\t\t\t);\n\n\t\tcase \"LLM_API_ERROR\":\n\t\t\tif (error instanceof ExternalServiceError && error.isRetryable) {\n\t\t\t\treturn retryStep(\n\t\t\t\t\tstep,\n\t\t\t\t\tstepIndex,\n\t\t\t\t\tstepOutputs,\n\t\t\t\t\tloopVars,\n\t\t\t\t\toptions,\n\t\t\t\t\terror,\n\t\t\t\t\tcontext,\n\t\t\t\t\ttimer,\n\t\t\t\t\tstateManager,\n\t\t\t\t\texecPath,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\n\t\tdefault:\n\t\t\tthrow error;\n\t}\n}\n\n// ─── Chain Execution ─────────────────────────────────────────────\n\n// In a durable execution environment, code outside context.step() re-runs\n// on every resume. All code in this loop body outside the context.step()\n// call must therefore be idempotent: pure reads (stepIndex lookups,\n// nextStepId traversal), scope construction, and writing the same cached\n// step output back into stepOutputs.\nconst executeChain: ExecuteChainFn = async function executeChain(\n\tstartStepId: string,\n\tstepIndex: Map<string, WorkflowStep>,\n\tstepOutputs: Record<string, unknown>,\n\tloopVars: Record<string, unknown>,\n\toptions: ResolvedExecuteWorkflowOptions,\n\tcontext: DurableContext,\n\ttimer?: ExecutionTimer,\n\tstateManager?: ExecutionStateManager,\n\texecPath: ExecutionPathSegment[] = [],\n): Promise<unknown> {\n\tlet currentStepId: string | undefined = startStepId;\n\tlet lastOutput: unknown;\n\n\twhile (currentStepId) {\n\t\tconst step = stepIndex.get(currentStepId);\n\t\tif (!step) {\n\t\t\t// Defensive: the compiler and pre-flight checks should prevent this\n\t\t\tthrow new Error(`Step '${currentStepId}' not found`);\n\t\t}\n\n\t\ttimer?.checkTotal(step.id);\n\t\tconst stepStartTime = Date.now();\n\t\tstateManager?.stepStarted(step.id, execPath);\n\t\toptions.onStepStart?.(step.id, step);\n\n\t\tconst scope = { ...stepOutputs, ...loopVars };\n\t\tconst resolvedInputs = stateManager\n\t\t\t? resolveStepInputs(step, scope)\n\t\t\t: undefined;\n\t\tlet stepResult: StepOutput;\n\n\t\ttry {\n\t\t\ttimer?.beginActive();\n\t\t\ttry {\n\t\t\t\tstepResult = (await context.step(step.id, () =>\n\t\t\t\t\texecuteStep(\n\t\t\t\t\t\tstep,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tstepOutputs,\n\t\t\t\t\t\tloopVars,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\ttimer ?? new ExecutionTimer(),\n\t\t\t\t\t\tstateManager,\n\t\t\t\t\t\texecPath,\n\t\t\t\t\t),\n\t\t\t\t)) as StepOutput;\n\t\t\t} finally {\n\t\t\t\ttimer?.endActive(step.id);\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (!(e instanceof StepExecutionError)) {\n\t\t\t\tconst durationMs = Date.now() - stepStartTime;\n\t\t\t\tconst wrappedError = new ExternalServiceError(\n\t\t\t\t\tstep.id,\n\t\t\t\t\t\"TOOL_EXECUTION_FAILED\",\n\t\t\t\t\te instanceof Error ? e.message : String(e),\n\t\t\t\t\te,\n\t\t\t\t\tundefined,\n\t\t\t\t\tfalse,\n\t\t\t\t);\n\t\t\t\tstateManager?.stepFailed(\n\t\t\t\t\tstep.id,\n\t\t\t\t\texecPath,\n\t\t\t\t\twrappedError,\n\t\t\t\t\tdurationMs,\n\t\t\t\t\tresolvedInputs,\n\t\t\t\t);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tstepResult = await recoverFromError(\n\t\t\t\te,\n\t\t\t\tstep,\n\t\t\t\tstepIndex,\n\t\t\t\tstepOutputs,\n\t\t\t\tloopVars,\n\t\t\t\toptions,\n\t\t\t\tcontext,\n\t\t\t\ttimer ?? new ExecutionTimer(),\n\t\t\t\tstateManager,\n\t\t\t\texecPath,\n\t\t\t);\n\t\t}\n\n\t\tconst durationMs = Date.now() - stepStartTime;\n\t\tstepOutputs[step.id] = stepResult.output;\n\t\tlastOutput = stepResult.output;\n\t\tstateManager?.stepCompleted(\n\t\t\tstep.id,\n\t\t\texecPath,\n\t\t\tstepResult.output,\n\t\t\tdurationMs,\n\t\t\tresolvedInputs,\n\t\t\tstepResult.trace,\n\t\t);\n\t\toptions.onStepComplete?.(step.id, stepResult.output);\n\n\t\tcurrentStepId = step.nextStepId;\n\t}\n\n\treturn lastOutput;\n};\n\n// ─── Pre-flight Validation ───────────────────────────────────────\n\nfunction validateWorkflowConfig(\n\tworkflow: WorkflowDefinition,\n\toptions: ResolvedExecuteWorkflowOptions,\n): void {\n\tconst needsAgent = workflow.steps.some(\n\t\t(s) =>\n\t\t\ts.type === \"llm-prompt\" ||\n\t\t\ts.type === \"extract-data\" ||\n\t\t\ts.type === \"agent-loop\",\n\t);\n\tif (needsAgent && !options.model) {\n\t\tconst llmStep = workflow.steps.find(\n\t\t\t(s) =>\n\t\t\t\ts.type === \"llm-prompt\" ||\n\t\t\t\ts.type === \"extract-data\" ||\n\t\t\t\ts.type === \"agent-loop\",\n\t\t);\n\t\tthrow new ConfigurationError(\n\t\t\tllmStep?.id ?? \"unknown\",\n\t\t\t\"AGENT_NOT_PROVIDED\",\n\t\t\t\"Workflow contains LLM/agent steps but no agent was provided\",\n\t\t);\n\t}\n\n\tfor (const step of workflow.steps) {\n\t\tif (step.type === \"tool-call\") {\n\t\t\tconst toolDef = options.tools[step.params.toolName];\n\t\t\tif (!toolDef) {\n\t\t\t\tthrow new ConfigurationError(\n\t\t\t\t\tstep.id,\n\t\t\t\t\t\"TOOL_NOT_FOUND\",\n\t\t\t\t\t`Tool '${step.params.toolName}' not found`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!toolDef.execute) {\n\t\t\t\tthrow new ConfigurationError(\n\t\t\t\t\tstep.id,\n\t\t\t\t\t\"TOOL_MISSING_EXECUTE\",\n\t\t\t\t\t`Tool '${step.params.toolName}' has no execute function`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (step.type === \"agent-loop\" && !options.agent) {\n\t\t\t// When an Agent is provided, tools come from the Agent itself;\n\t\t\t// only validate tool references when using the LanguageModel path\n\t\t\tfor (const toolName of step.params.tools) {\n\t\t\t\tconst toolDef = options.tools[toolName];\n\t\t\t\tif (!toolDef) {\n\t\t\t\t\tthrow new ConfigurationError(\n\t\t\t\t\t\tstep.id,\n\t\t\t\t\t\t\"TOOL_NOT_FOUND\",\n\t\t\t\t\t\t`Tool '${toolName}' referenced in agent-loop step not found`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!toolDef.execute) {\n\t\t\t\t\tthrow new ConfigurationError(\n\t\t\t\t\t\tstep.id,\n\t\t\t\t\t\t\"TOOL_MISSING_EXECUTE\",\n\t\t\t\t\t\t`Tool '${toolName}' referenced in agent-loop step has no execute function`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ─── Public API ──────────────────────────────────────────────────\n\n/**\n * Executes a compiled workflow by walking its step graph from `initialStepId`.\n *\n * Handles all step types (tool calls, LLM prompts, data extraction, branching,\n * loops) and supports automatic retry with exponential backoff for recoverable\n * errors (rate limits, network failures, LLM parse errors).\n *\n * @param workflow - The workflow definition to execute (should be compiled first via {@link compileWorkflow}).\n * @param options - Execution options including tools, agent, inputs, and callbacks.\n * @returns An {@link ExecutionResult} with success status, all step outputs, and the final workflow output.\n */\nexport async function executeWorkflow(\n\tworkflow: WorkflowDefinition,\n\toptions: ExecuteWorkflowOptions,\n): Promise<ExecutionResult> {\n\tconst stepIndex = new Map<string, WorkflowStep>();\n\tfor (const step of workflow.steps) {\n\t\tstepIndex.set(step.id, step);\n\t}\n\n\tconst stepOutputs: Record<string, unknown> = {};\n\n\tconst resolvedOptions: ResolvedExecuteWorkflowOptions = options;\n\tconst resolvedContext = options.context ?? createDefaultDurableContext();\n\tconst timer = new ExecutionTimer(options.limits);\n\tconst stateManager = new ExecutionStateManager(options.onStateChange);\n\tstateManager.runStarted();\n\n\ttry {\n\t\tvalidateWorkflowConfig(workflow, resolvedOptions);\n\n\t\tconst inputs = options.inputs ?? {};\n\t\tvalidateWorkflowInputs(\n\t\t\tworkflow.inputSchema as Record<string, unknown> | undefined,\n\t\t\tinputs,\n\t\t);\n\t\tstepOutputs.input = inputs;\n\n\t\tconst chainOutput = await executeChain(\n\t\t\tworkflow.initialStepId,\n\t\t\tstepIndex,\n\t\t\tstepOutputs,\n\t\t\t{},\n\t\t\tresolvedOptions,\n\t\t\tresolvedContext,\n\t\t\ttimer,\n\t\t\tstateManager,\n\t\t\t[],\n\t\t);\n\n\t\tif (workflow.outputSchema) {\n\t\t\t// Find the terminating end step for error reporting\n\t\t\tlet endStepId = \"unknown\";\n\t\t\tfor (const step of workflow.steps) {\n\t\t\t\tif (step.type === \"end\" && step.id in stepOutputs) {\n\t\t\t\t\tendStepId = step.id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvalidateWorkflowOutput(\n\t\t\t\tworkflow.outputSchema as Record<string, unknown>,\n\t\t\t\tchainOutput,\n\t\t\t\tendStepId,\n\t\t\t);\n\t\t}\n\n\t\tstateManager.runCompleted(chainOutput);\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tstepOutputs,\n\t\t\toutput: chainOutput,\n\t\t\texecutionState: stateManager.currentState,\n\t\t};\n\t} catch (e) {\n\t\tconst error =\n\t\t\te instanceof StepExecutionError\n\t\t\t\t? e\n\t\t\t\t: new ExternalServiceError(\n\t\t\t\t\t\t\"unknown\",\n\t\t\t\t\t\t\"TOOL_EXECUTION_FAILED\",\n\t\t\t\t\t\te instanceof Error ? e.message : String(e),\n\t\t\t\t\t\te,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t);\n\t\tstateManager.runFailed(error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tstepOutputs,\n\t\t\terror,\n\t\t\texecutionState: stateManager.currentState,\n\t\t};\n\t}\n}\n",
|
|
35
|
+
"import type { LanguageModel, ToolSet } from \"ai\";\nimport { generateText, stepCountIs, tool } from \"ai\";\nimport { type as arktype } from \"arktype\";\nimport { compileWorkflow } from \"../compiler\";\nimport type { Diagnostic } from \"../compiler/types\";\nimport type { WorkflowDefinition } from \"../types\";\nimport { workflowDefinitionSchema } from \"../types\";\nimport {\n\tbuildWorkflowGenerationPrompt,\n\tformatDiagnostics,\n\tserializeToolsForPrompt,\n} from \"./prompt\";\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** Options for {@link generateWorkflow}. */\nexport interface GenerateWorkflowOptions {\n\t/** The language model to use for generating the workflow. */\n\tmodel: LanguageModel;\n\t/** Available tools the generated workflow can reference. All tools must have an `outputSchema`. */\n\ttools: ToolSet;\n\t/** Natural language description of the task the workflow should accomplish. */\n\ttask: string;\n\t/** Maximum number of generation attempts if the LLM produces invalid workflows. Defaults to 3. */\n\tmaxRetries?: number;\n\t/** Additional instructions appended to the system prompt to guide workflow generation. */\n\tadditionalInstructions?: string;\n}\n\n/** The result of generating a workflow via LLM. */\nexport interface GenerateWorkflowResult {\n\t/** The generated workflow, or `null` if all attempts produced invalid workflows. */\n\tworkflow: WorkflowDefinition | null;\n\t/** Diagnostics from the last compilation attempt. */\n\tdiagnostics: Diagnostic[];\n\t/** Total number of generation attempts made. */\n\tattempts: number;\n}\n\n/** Options for {@link createWorkflowGeneratorTool}. */\nexport interface WorkflowGeneratorToolOptions {\n\t/** The language model to use for generation. */\n\tmodel: LanguageModel;\n\t/** Available tools the generated workflow can reference. */\n\ttools?: ToolSet;\n\t/** Maximum number of generation attempts. Defaults to 3. */\n\tmaxRetries?: number;\n\t/** Additional instructions appended to the system prompt to guide workflow generation. */\n\tadditionalInstructions?: string;\n}\n\n// ─── generateWorkflow ────────────────────────────────────────────\n\n/**\n * Uses an LLM to generate a validated workflow definition from a natural language\n * task description. The LLM produces a workflow via tool call, which is then compiled\n * and validated. If compilation fails, diagnostics are fed back to the LLM for\n * correction, up to `maxRetries` attempts.\n *\n * @param options - Generation options including model, tools, and task description.\n * @returns A {@link GenerateWorkflowResult} with the generated workflow (or null), diagnostics, and attempt count.\n * @throws If any tool in `options.tools` is missing an `outputSchema`.\n */\nexport async function generateWorkflow(\n\toptions: GenerateWorkflowOptions,\n): Promise<GenerateWorkflowResult> {\n\tconst {\n\t\tmodel,\n\t\ttools,\n\t\ttask,\n\t\tmaxRetries = 3,\n\t\tadditionalInstructions,\n\t} = options;\n\n\tconst missingOutputSchema = Object.entries(tools)\n\t\t.filter(([_, t]) => !t.outputSchema)\n\t\t.map(([name]) => name);\n\tif (missingOutputSchema.length > 0) {\n\t\tthrow new Error(\n\t\t\t`All tools must have an outputSchema. Missing: ${missingOutputSchema.join(\", \")}`,\n\t\t);\n\t}\n\n\tconst serializedTools = await serializeToolsForPrompt(tools);\n\tconst systemPrompt = buildWorkflowGenerationPrompt(\n\t\tserializedTools,\n\t\tadditionalInstructions,\n\t);\n\n\tlet successWorkflow: WorkflowDefinition | null = null;\n\tlet lastDiagnostics: Diagnostic[] = [];\n\tlet attempts = 0;\n\n\tconst createWorkflowTool = tool({\n\t\tdescription: \"Create a workflow definition\",\n\t\tinputSchema: workflowDefinitionSchema,\n\t\texecute: async (workflowDef) => {\n\t\t\tattempts++;\n\t\t\tconst result = await compileWorkflow(workflowDef, { tools });\n\t\t\tlastDiagnostics = result.diagnostics;\n\n\t\t\tconst errors = result.diagnostics.filter((d) => d.severity === \"error\");\n\t\t\tif (errors.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terrors: formatDiagnostics(result.diagnostics),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tsuccessWorkflow = result.workflow ?? workflowDef;\n\t\t\treturn { success: true };\n\t\t},\n\t});\n\n\tawait generateText({\n\t\tmodel,\n\t\tsystem: systemPrompt,\n\t\tprompt: `Create a workflow to accomplish the following task:\\n\\n${task}`,\n\t\ttools: { createWorkflow: createWorkflowTool },\n\t\ttoolChoice: { type: \"tool\", toolName: \"createWorkflow\" },\n\t\tstopWhen: [stepCountIs(maxRetries + 1), () => successWorkflow !== null],\n\t});\n\n\treturn {\n\t\tworkflow: successWorkflow,\n\t\tdiagnostics: lastDiagnostics,\n\t\tattempts,\n\t};\n}\n\n// ─── createWorkflowGeneratorTool ─────────────────────────────────\n\n/**\n * Creates an AI SDK tool that generates validated workflow definitions from\n * natural language task descriptions. Useful for giving an agent the ability\n * to create workflows on the fly.\n *\n * @param options - Configuration including the model and available tools.\n * @returns An AI SDK `tool` that accepts a `{ task: string }` input and returns a {@link GenerateWorkflowResult}.\n */\nexport function createWorkflowGeneratorTool(\n\toptions: WorkflowGeneratorToolOptions,\n) {\n\tconst {\n\t\tmodel,\n\t\ttools: baseTools,\n\t\tmaxRetries,\n\t\tadditionalInstructions,\n\t} = options;\n\n\treturn tool({\n\t\tdescription:\n\t\t\t\"Generate a validated workflow definition from a natural language task description\",\n\t\tinputSchema: arktype({ task: \"string\" }),\n\t\texecute: async ({ task }) => {\n\t\t\treturn generateWorkflow({\n\t\t\t\tmodel,\n\t\t\t\ttools: baseTools ?? {},\n\t\t\t\ttask,\n\t\t\t\tmaxRetries,\n\t\t\t\tadditionalInstructions,\n\t\t\t});\n\t\t},\n\t});\n}\n",
|
|
36
|
+
"import { type } from \"arktype\";\n\nconst expressionSchema = type({\n\ttype: \"'literal'\",\n\tvalue: \"unknown\",\n})\n\t.or({\n\t\ttype: \"'jmespath'\",\n\t\texpression: \"string\",\n\t})\n\t.or({\n\t\ttype: \"'template'\",\n\t\ttemplate: \"string\",\n\t})\n\t.describe(\n\t\t\"a value that must always be wrapped as an expression object — use { type: 'literal', value: ... } for any static value (strings, numbers, booleans, etc.), { type: 'jmespath', expression: '...' } for dynamic data extracted from previous steps' outputs (via their step ids, e.g. `stepId.someKey`) or loop variables (e.g. `itemName.someKey` within a for-each loop body), or { type: 'template', template: '...' } for string interpolation with embedded JMESPath expressions using ${...} syntax (e.g. 'Hello ${user.name}, order ${order.id}') — template expressions always resolve to a string\",\n\t);\n\nconst toolCallParamsSchema = type({\n\ttype: \"'tool-call'\",\n\tparams: {\n\t\ttoolName: \"string\",\n\t\ttoolInput: [\n\t\t\t{\n\t\t\t\t\"[string]\": expressionSchema,\n\t\t\t},\n\t\t\t\"@\",\n\t\t\t\"a map of input parameter names to their values; ALL values must be wrapped as expression objects — even static strings like email addresses must use { type: 'literal', value: '...' }, never plain primitives\",\n\t\t],\n\t},\n}).describe(\n\t\"a step that calls a tool with specified input parameters (which can be static values or expressions)\",\n);\n\nconst switchCaseParamsSchema = type({\n\ttype: \"'switch-case'\",\n\tparams: {\n\t\tswitchOn: expressionSchema,\n\t\tcases: [\n\t\t\t{\n\t\t\t\tvalue: expressionSchema.or({ type: \"'default'\" }),\n\t\t\t\tbranchBodyStepId: [\n\t\t\t\t\t\"string\",\n\t\t\t\t\t\"@\",\n\t\t\t\t\t\"the id of the first step in the branch body chain to execute if this case matches\",\n\t\t\t\t],\n\t\t\t},\n\t\t\t\"[]\",\n\t\t],\n\t},\n}).describe(\n\t\"a step that branches to different step chains based on the value of an expression; each case's chain runs until a step with no nextStepId, at which point execution continues with this step's nextStepId; a case with type 'default' serves as the fallback if no other case matches\",\n);\n\nconst forEachParamsSchema = type({\n\ttype: \"'for-each'\",\n\tparams: {\n\t\ttarget: expressionSchema,\n\t\titemName: [\n\t\t\t\"string\",\n\t\t\t\"@\",\n\t\t\t\"the name to refer to the current item in the list within expressions in the loop body\",\n\t\t],\n\t\tloopBodyStepId: [\n\t\t\t\"string\",\n\t\t\t\"@\",\n\t\t\t\"the id of the first step in the loop body chain to execute for each item in the list\",\n\t\t],\n\t},\n}).describe(\n\t\"a step that iterates over a list and executes a chain of steps for each item; the loop body chain runs until a step with no nextStepId, at which point the next iteration begins; once all items are exhausted, execution continues with this step's nextStepId\",\n);\n\nconst llmPromptSchema = type({\n\ttype: \"'llm-prompt'\",\n\tparams: {\n\t\tprompt: [\n\t\t\t\"string\",\n\t\t\t\"@\",\n\t\t\t\"a template string where JMESPath expressions can be embedded using ${...} syntax (e.g. 'Hello ${user.name}, you have ${length(user.messages)} messages'). All data from previous steps is available via their step ids (e.g. ${stepId.someKey}), and loop variables are available within for-each loop bodies (e.g. ${itemName.someKey})\",\n\t\t],\n\t\toutputFormat: [\n\t\t\t\"object\",\n\t\t\t\"@\",\n\t\t\t\"JSON schema specifying the output format expected from the LLM\",\n\t\t],\n\t},\n}).describe(\n\t\"a step that prompts an LLM with a text prompt to produce an output in a specified format\",\n);\n\nconst extractDataParamsSchema = type({\n\ttype: \"'extract-data'\",\n\tparams: {\n\t\tsourceData: [expressionSchema, \"@\", \"the data to extract information from\"],\n\t\toutputFormat: [\n\t\t\t\"object\",\n\t\t\t\"@\",\n\t\t\t\"JSON schema specifying the output format expected from the data extraction\",\n\t\t],\n\t},\n}).describe(\n\t\"a step that uses an LLM to extract structured data from a larger blob of source data (e.g. llm responses or tool outputs with unknown output formats) based on a specified output format\",\n);\n\nconst sleepParamsSchema = type({\n\ttype: \"'sleep'\",\n\tparams: {\n\t\tdurationMs: expressionSchema,\n\t},\n}).describe(\n\t\"a step that pauses workflow execution for a specified duration in milliseconds; the durationMs parameter must evaluate to a non-negative number\",\n);\n\nconst waitForConditionParamsSchema = type({\n\ttype: \"'wait-for-condition'\",\n\tparams: {\n\t\tconditionStepId: [\n\t\t\t\"string\",\n\t\t\t\"@\",\n\t\t\t\"the id of the first step in the condition-check chain that will be executed on each polling attempt; this chain runs until a step with no nextStepId, then the condition expression is evaluated\",\n\t\t],\n\t\tcondition: [\n\t\t\texpressionSchema,\n\t\t\t\"@\",\n\t\t\t\"an expression evaluated after each execution of the condition-check chain; if it evaluates to a truthy value, the wait completes with that value as its output; all step outputs from the condition chain are available in scope for this expression\",\n\t\t],\n\t\t\"maxAttempts?\": [\n\t\t\texpressionSchema,\n\t\t\t\"@\",\n\t\t\t\"maximum number of polling attempts before giving up (default: 10)\",\n\t\t],\n\t\t\"intervalMs?\": [\n\t\t\texpressionSchema,\n\t\t\t\"@\",\n\t\t\t\"milliseconds to wait between polling attempts (default: 1000)\",\n\t\t],\n\t\t\"backoffMultiplier?\": [\n\t\t\texpressionSchema,\n\t\t\t\"@\",\n\t\t\t\"multiply the interval by this factor after each attempt (default: 1, i.e. no backoff; use 2 for exponential backoff)\",\n\t\t],\n\t\t\"timeoutMs?\": [\n\t\t\texpressionSchema,\n\t\t\t\"@\",\n\t\t\t\"hard timeout in milliseconds; if the total elapsed time exceeds this, the step fails regardless of remaining attempts\",\n\t\t],\n\t},\n}).describe(\n\t\"a step that repeatedly executes a condition-check chain (starting at conditionStepId) and then evaluates the condition expression against the updated scope; if the condition expression evaluates to a truthy value, the step completes with that value as its output; otherwise it waits for intervalMs milliseconds (multiplied by backoffMultiplier after each attempt) and tries again, up to maxAttempts times or until timeoutMs milliseconds have elapsed; the condition-check chain runs until a step with no nextStepId, at which point the condition expression is evaluated; all step outputs from the condition chain are available in scope for the condition expression\",\n);\n\nconst agentLoopParamsSchema = type({\n\ttype: \"'agent-loop'\",\n\tparams: {\n\t\tinstructions: [\n\t\t\t\"string\",\n\t\t\t\"@\",\n\t\t\t\"a template string with task instructions for the agent; JMESPath expressions can be embedded using ${...} syntax (e.g. 'Research ${input.topic} and summarize findings'). All data from previous steps is available via their step ids, and loop variables are available within for-each loop bodies\",\n\t\t],\n\t\ttools: [\n\t\t\t[\"string\", \"[]\"],\n\t\t\t\"@\",\n\t\t\t\"names of tools from the workflow's tool set that the agent is allowed to use\",\n\t\t],\n\t\toutputFormat: [\n\t\t\t\"object\",\n\t\t\t\"@\",\n\t\t\t\"JSON schema specifying the structured output format expected from the agent\",\n\t\t],\n\t\t\"maxSteps?\": [\n\t\t\texpressionSchema,\n\t\t\t\"@\",\n\t\t\t\"maximum number of tool-calling steps the agent may take (default: 10)\",\n\t\t],\n\t},\n}).describe(\n\t\"a step that delegates work to an autonomous agent with its own tool-calling loop; USE SPARINGLY — this sacrifices the determinism that is the core value of the workflow DSL. Prefer explicit tool-call, llm-prompt, and control flow steps whenever the task can be decomposed into predictable operations\",\n);\n\nconst startParamsSchema = type({\n\ttype: \"'start'\",\n}).describe(\n\t\"a step that marks the entry point of a workflow; a no-op marker whose execution continues to the next step\",\n);\n\nconst endSchema = type({\n\ttype: \"'end'\",\n\t\"params?\": {\n\t\toutput: expressionSchema,\n\t},\n}).describe(\n\t\"a step that indicates the end of a branch; optionally specify an output expression whose evaluated value becomes the workflow's output\",\n);\n\nconst workflowStepSchema = type({\n\tid: /^[a-zA-Z_][a-zA-Z0-9_]+$/,\n\tname: \"string\",\n\tdescription: \"string\",\n\t\"nextStepId?\": \"string\",\n}).and(\n\ttoolCallParamsSchema\n\t\t.or(llmPromptSchema)\n\t\t.or(extractDataParamsSchema)\n\t\t.or(switchCaseParamsSchema)\n\t\t.or(forEachParamsSchema)\n\t\t.or(sleepParamsSchema)\n\t\t.or(waitForConditionParamsSchema)\n\t\t.or(agentLoopParamsSchema)\n\t\t.or(startParamsSchema)\n\t\t.or(endSchema),\n);\n\n/**\n * ArkType schema for validating workflow definitions. Use this to validate\n * workflow JSON before passing it to {@link compileWorkflow}.\n */\nexport const workflowDefinitionSchema = type({\n\tinitialStepId: \"string\",\n\t\"inputSchema?\": [\n\t\t\"object\",\n\t\t\"@\",\n\t\t\"an optional JSON Schema object defining the inputs required to run the workflow; the executor validates provided inputs against this schema, and the validated inputs become available in JMESPath scope via the root identifier 'input' (e.g. input.fieldName)\",\n\t],\n\t\"outputSchema?\": [\n\t\t\"object\",\n\t\t\"@\",\n\t\t\"an optional JSON Schema object declaring the shape of the workflow's output; when present, the value produced by the end step's output expression will be validated against this schema\",\n\t],\n\tsteps: [\n\t\t[workflowStepSchema, \"[]\"],\n\t\t\"@\",\n\t\t\"a list of steps to execute in the workflow; these should be in no particular order as execution flow is determined by the nextStepId fields and branching logic within the steps\",\n\t],\n});\n\n/**\n * A single step in a workflow. Each step has a type that determines its behavior:\n * - `start` — entry point, declares input schema\n * - `tool-call` — calls a tool with literal or expression-based arguments\n * - `llm-prompt` — prompts an LLM with template string interpolation\n * - `extract-data` — uses an LLM to extract structured data from unstructured source\n * - `switch-case` — branches to different step chains based on an expression value\n * - `for-each` — iterates over an array, executing a chain of steps per item\n * - `agent-loop` — delegates work to an autonomous agent with its own tool-calling loop (use sparingly)\n * - `end` — terminates a branch, optionally producing workflow output\n */\nexport type WorkflowStep = typeof workflowStepSchema.infer;\n\n/**\n * A complete workflow definition. Contains an initial step ID and an ordered list of steps.\n * Execution flow is determined by each step's `nextStepId` and branching/looping logic,\n * not by the order of steps in the array.\n */\nexport type WorkflowDefinition = typeof workflowDefinitionSchema.infer;\n",
|
|
37
|
+
"import { asSchema, type ToolSet } from \"ai\";\nimport type { Diagnostic } from \"../compiler/types\";\n\nexport async function serializeToolsForPrompt(tools: ToolSet): Promise<string> {\n\treturn JSON.stringify(\n\t\tawait Promise.all(\n\t\t\tObject.entries(tools).map(async ([toolName, toolDef]) => ({\n\t\t\t\tname: toolName,\n\t\t\t\tdescription: toolDef.description,\n\t\t\t\tinputSchema: await asSchema(toolDef.inputSchema).jsonSchema,\n\t\t\t\toutputSchema: toolDef.outputSchema\n\t\t\t\t\t? await asSchema(toolDef.outputSchema).jsonSchema\n\t\t\t\t\t: undefined,\n\t\t\t})),\n\t\t),\n\t);\n}\n\nexport function buildWorkflowGenerationPrompt(\n\tserializedTools: string,\n\tadditionalInstructions?: string,\n): string {\n\treturn `You are a workflow architect. Your job is to design a workflow definition in the remora DSL that accomplishes a given task using the provided tools. You MUST call the createWorkflow tool with a valid workflow definition.\n\n## Workflow Structure\n\nA workflow has:\n- \\`initialStepId\\`: the id of the first step to execute\n- \\`inputSchema\\` (optional): a JSON Schema object defining the inputs required to run the workflow. When present, provided inputs are validated against this schema and become available in JMESPath expressions via the root identifier \\`input\\` (e.g. \\`input.fieldName\\`).\n- \\`outputSchema\\` (optional): a JSON Schema object declaring the shape of the workflow's output. When present, every \\`end\\` step should have an \\`output\\` expression that evaluates to a value matching this schema.\n- \\`steps\\`: an array of step objects (order does not matter — execution flow is determined by nextStepId links)\n\n## Step Common Fields\n\nEvery step has:\n- \\`id\\`: unique identifier matching /^[a-zA-Z_][a-zA-Z0-9_]+$/ (letters, digits, underscores; at least 2 characters)\n- \\`name\\`: human-readable name\n- \\`description\\`: what this step does\n- \\`type\\`: one of the step types below\n- \\`nextStepId\\` (optional): id of the next step to execute after this one\n\n## Step Types\n\n### start\nA no-op marker that indicates the entry point of a workflow. It takes no parameters. Workflow inputs are declared via \\`inputSchema\\` on the workflow definition itself, not on the start step.\n\\`\\`\\`json\n{\n \"type\": \"start\"\n}\n\\`\\`\\`\n\n### tool-call\nCalls a tool with input parameters. All values in toolInput MUST be expression objects.\n\\`\\`\\`json\n{\n \"type\": \"tool-call\",\n \"params\": {\n \"toolName\": \"name-of-tool\",\n \"toolInput\": {\n \"paramName\": { \"type\": \"literal\", \"value\": \"static value\" },\n \"otherParam\": { \"type\": \"jmespath\", \"expression\": \"previous_step.someField\" }\n }\n }\n}\n\\`\\`\\`\n\n### llm-prompt\nPrompts an LLM with a template string to produce structured output. Use \\${...} syntax to embed JMESPath expressions in the prompt.\n\\`\\`\\`json\n{\n \"type\": \"llm-prompt\",\n \"params\": {\n \"prompt\": \"Classify this ticket: \\${get_tickets.tickets[0].subject}\",\n \"outputFormat\": { \"type\": \"object\", \"properties\": { \"category\": { \"type\": \"string\" } }, \"required\": [\"category\"] }\n }\n}\n\\`\\`\\`\n\n### extract-data\nUses an LLM to extract structured data from a source. Use when you need to parse unstructured or semi-structured data into a known shape.\n\\`\\`\\`json\n{\n \"type\": \"extract-data\",\n \"params\": {\n \"sourceData\": { \"type\": \"jmespath\", \"expression\": \"previous_step.rawContent\" },\n \"outputFormat\": { \"type\": \"object\", \"properties\": { ... }, \"required\": [...] }\n }\n}\n\\`\\`\\`\n\n### switch-case\nBranches execution based on a value. Each case's branch chain runs until a step with no nextStepId, then execution continues with this step's nextStepId. Use \\`{ \"type\": \"default\" }\\` for a fallback case.\n\\`\\`\\`json\n{\n \"type\": \"switch-case\",\n \"params\": {\n \"switchOn\": { \"type\": \"jmespath\", \"expression\": \"classify.category\" },\n \"cases\": [\n {\n \"value\": { \"type\": \"literal\", \"value\": \"critical\" },\n \"branchBodyStepId\": \"handle_critical\"\n },\n {\n \"value\": { \"type\": \"default\" },\n \"branchBodyStepId\": \"handle_other\"\n }\n ]\n }\n}\n\\`\\`\\`\n\n### for-each\nIterates over a list and executes a chain of steps for each item. The loop body chain runs until a step with no nextStepId, then the next iteration begins. After all items, execution continues with this step's nextStepId. The \\`itemName\\` becomes a scoped variable accessible only within the loop body.\n\\`\\`\\`json\n{\n \"type\": \"for-each\",\n \"params\": {\n \"target\": { \"type\": \"jmespath\", \"expression\": \"get_items.items\" },\n \"itemName\": \"item\",\n \"loopBodyStepId\": \"process_item\"\n }\n}\n\\`\\`\\`\n\n### sleep\nPauses workflow execution for a fixed duration. Use when you need to wait between operations (e.g., rate limiting, propagation delays).\n\\`\\`\\`json\n{\n \"type\": \"sleep\",\n \"params\": {\n \"durationMs\": { \"type\": \"literal\", \"value\": 5000 }\n }\n}\n\\`\\`\\`\n\n### wait-for-condition\nRepeatedly executes a condition-check chain and evaluates a condition expression until it returns a truthy value. Use when you need to poll for a state change (e.g., waiting for a job to complete, a resource to become available).\n\nThe \\`conditionStepId\\` points to the first step of a sub-chain that will be executed on each polling attempt. After the chain runs, the \\`condition\\` expression is evaluated against the current scope (including all outputs from the condition chain). If the result is truthy, the wait-for-condition step completes with that value as its output. Otherwise, it waits and retries.\n\nOptional parameters control polling behavior:\n- \\`maxAttempts\\`: maximum number of polling attempts (default: 10)\n- \\`intervalMs\\`: milliseconds between attempts (default: 1000)\n- \\`backoffMultiplier\\`: multiply interval by this after each attempt (default: 1, i.e. no backoff; use 2 for exponential)\n- \\`timeoutMs\\`: hard timeout in milliseconds (optional)\n\\`\\`\\`json\n{\n \"type\": \"wait-for-condition\",\n \"params\": {\n \"conditionStepId\": \"poll_status\",\n \"condition\": { \"type\": \"jmespath\", \"expression\": \"poll_status.status == 'complete'\" },\n \"maxAttempts\": { \"type\": \"literal\", \"value\": 30 },\n \"intervalMs\": { \"type\": \"literal\", \"value\": 2000 },\n \"backoffMultiplier\": { \"type\": \"literal\", \"value\": 1.5 },\n \"timeoutMs\": { \"type\": \"literal\", \"value\": 120000 }\n }\n}\n\\`\\`\\`\n\n### agent-loop\n**USE SPARINGLY.** Delegates work to an autonomous agent with its own tool-calling loop. This step sacrifices the determinism that is the core value of the workflow DSL. Only use when the task genuinely cannot be decomposed into predictable tool-call, llm-prompt, and control flow steps (e.g., open-ended research tasks, complex multi-step reasoning that depends on intermediate results in unpredictable ways).\n\nThe agent receives the interpolated \\`instructions\\` as a prompt, has access to the listed \\`tools\\`, and must produce output matching \\`outputFormat\\`. The \\`maxSteps\\` parameter bounds the number of tool-calling iterations (default: 10).\n\\`\\`\\`json\n{\n \"type\": \"agent-loop\",\n \"params\": {\n \"instructions\": \"Research \\${input.topic} using the available search tools and compile a summary with at least 3 sources.\",\n \"tools\": [\"web_search\", \"fetch_page\"],\n \"outputFormat\": {\n \"type\": \"object\",\n \"properties\": {\n \"summary\": { \"type\": \"string\" },\n \"sources\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n },\n \"required\": [\"summary\", \"sources\"]\n },\n \"maxSteps\": { \"type\": \"literal\", \"value\": 15 }\n }\n}\n\\`\\`\\`\n\n### end\nMarks the end of a branch or the workflow. Must NOT have a nextStepId. Optionally, specify an output expression whose value becomes the workflow's return value.\n\\`\\`\\`json\n{\n \"type\": \"end\"\n}\n\\`\\`\\`\n\nWith output (when the workflow declares an outputSchema):\n\\`\\`\\`json\n{\n \"type\": \"end\",\n \"params\": {\n \"output\": { \"type\": \"jmespath\", \"expression\": \"summarize.result\" }\n }\n}\n\\`\\`\\`\n\n## Expression System\n\nEvery dynamic value must be an expression object:\n\n1. **Literal** — for static values known at design time:\n \\`{ \"type\": \"literal\", \"value\": <any value> }\\`\n\n2. **JMESPath** — for referencing data from previous steps, workflow inputs, or loop variables:\n \\`{ \"type\": \"jmespath\", \"expression\": \"<expression>\" }\\`\n The root of a JMESPath expression must be one of: the \\`input\\` alias (e.g. \\`input.orderId\\`) for workflow inputs, a step id (e.g. \\`get_orders.orders\\`) for previous step outputs, or a loop variable name (e.g. \\`item.id\\` within a for-each body).\n\n3. **Template strings** (llm-prompt only) — embed JMESPath in the prompt string using \\${...}:\n \\`\"Summarize: \\${fetch_data.content}\"\\`\n These are NOT expression objects — they appear directly in the prompt string.\n\n## Structural Rules\n\n1. Step IDs must be unique and match /^[a-zA-Z_][a-zA-Z0-9_]+$/.\n2. Steps link via nextStepId. Omitting nextStepId ends the chain.\n3. Branch body chains (switch-case), loop body chains (for-each), and condition body chains (wait-for-condition) must terminate — their last step must NOT have a nextStepId. Do NOT point them back to the parent or outside the body.\n4. Only reference step IDs of steps that will have executed before the current step (no forward references).\n5. Do not create cycles (for-each handles iteration — you do not need to loop manually).\n6. end steps must NOT have a nextStepId.\n\n## Available Tools\n\nEach tool below includes an \\`outputSchema\\` describing the shape of its return value. Use the output schema to construct correct JMESPath expressions. For example, if a tool returns \\`{ \"type\": \"object\", \"properties\": { \"orders\": { \"type\": \"array\", ... } } }\\`, reference the array as \\`step_id.orders\\`, not \\`step_id\\` alone.\n\n${serializedTools}\n\n## Common Mistakes\n\n1. NEVER use bare primitives in toolInput. ALL values must be expression objects.\n WRONG: \\`{ \"email\": \"user@example.com\" }\\`\n RIGHT: \\`{ \"email\": { \"type\": \"literal\", \"value\": \"user@example.com\" } }\\`\n\n2. Do NOT give end steps a nextStepId.\n\n3. Branch/loop body chains must terminate (last step has no nextStepId). Do NOT point them outside their scope.\n\n4. JMESPath expressions reference step outputs by step ID as the root identifier (e.g. \\`\"get_orders.orders[0].id\"\\`), and workflow inputs via the \\`input\\` alias (e.g. \\`\"input.orderId\"\\`).\n\n5. For-each itemName is a scoped variable accessible ONLY within the loop body steps.\n\n6. Step IDs must be at least 2 characters long.\n\n7. for-each target must resolve to an ARRAY. Check the tool's outputSchema to determine the correct path.\n WRONG: \\`\"target\": { \"type\": \"jmespath\", \"expression\": \"get_orders\" }\\` (when get_orders returns an object with an \\`orders\\` array property)\n RIGHT: \\`\"target\": { \"type\": \"jmespath\", \"expression\": \"get_orders.orders\" }\\`\n\n8. If the workflow needs to return structured data, declare an \\`outputSchema\\` on the workflow and give every \\`end\\` step an \\`output\\` expression that evaluates to a value matching it.\n\n9. wait-for-condition requires both \\`conditionStepId\\` (the chain to execute on each polling attempt) AND \\`condition\\` (the expression to evaluate after the chain runs). The condition expression is evaluated AFTER the chain runs, using the updated scope with all step outputs from the condition chain.\n\n10. Prefer explicit tool-call, llm-prompt, switch-case, and for-each steps over agent-loop. Only use agent-loop when the task is genuinely open-ended and cannot be decomposed into deterministic steps.${additionalInstructions ? `\\n\\n## Additional Instructions\\n\\n${additionalInstructions}` : \"\"}`;\n}\n\nexport function formatDiagnostics(diagnostics: Diagnostic[]): string {\n\tconst errors = diagnostics.filter((d) => d.severity === \"error\");\n\tif (errors.length === 0) return \"No errors.\";\n\treturn errors\n\t\t.map((d) => {\n\t\t\tconst loc = d.location\n\t\t\t\t? ` (at step ${d.location.stepId}${d.location.field ? `, field ${d.location.field}` : \"\"})`\n\t\t\t\t: \"\";\n\t\t\treturn `- [${d.code}] ${d.message}${loc}`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n"
|
|
38
|
+
],
|
|
39
|
+
"mappings": ";AACA;;;ACqBA,IAAM,QAA4B,CAAC,qBAAqB,kBAAkB;AAMnE,SAAS,kBAAkB,CACjC,UACA,OACyB;AAAA,EACzB,IAAI,SAAS,gBAAgB,QAAQ;AAAA,EACrC,MAAM,iBAA+B,CAAC;AAAA,EAEtC,WAAW,QAAQ,OAAO;AAAA,IACzB,MAAM,aAAa,KAAK,QAAQ,KAAK;AAAA,IACrC,SAAS,WAAW;AAAA,IACpB,eAAe,KAAK,GAAG,WA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