@axiom-lattice/core 2.1.79 → 2.1.80
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/dist/chunk-C5HUS7YV.mjs +331 -0
- package/dist/chunk-C5HUS7YV.mjs.map +1 -0
- package/dist/chunk-FN4TRQK4.mjs +1258 -0
- package/dist/chunk-FN4TRQK4.mjs.map +1 -0
- package/dist/compile-SYSKVQHB.mjs +9 -0
- package/dist/compile-SYSKVQHB.mjs.map +1 -0
- package/dist/index.d.mts +122 -3
- package/dist/index.d.ts +122 -3
- package/dist/index.js +2602 -765
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +776 -588
- package/dist/index.mjs.map +1 -1
- package/dist/memory_lattice-E66HTTVV.mjs +13 -0
- package/dist/memory_lattice-E66HTTVV.mjs.map +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workflow/compile.ts","../src/workflow/utils.ts","../src/workflow/normalize.ts"],"sourcesContent":["/**\n * Workflow DSL → LangGraph StateGraph compiler\n *\n * Takes a WorkflowDSL (concise), expands it to InternalDSL,\n * and compiles it into a runnable LangGraph CompiledStateGraph.\n */\nimport {\n StateGraph,\n START,\n END,\n type CompiledStateGraph,\n type AnnotationRoot,\n} from \"@langchain/langgraph\";\nimport type { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport type {\n WorkflowDSL,\n InternalDSL,\n InternalEdgeRule,\n WorkflowTrackingStore,\n} from \"@axiom-lattice/protocols\";\nimport {\n buildStateAnnotation,\n createNodeHandler,\n resolvePath,\n type ResolveAgentFn,\n} from \"./utils\";\nimport { expand } from \"./normalize\";\n\n/**\n * Compile a Workflow DSL into a LangGraph StateGraph.\n *\n * @param dsl The WorkflowDSL definition\n * @param resolveAgent Function to resolve agent ref → CompiledStateGraph\n * @param checkpointer Checkpoint saver for state persistence\n * @returns Compiled LangGraph StateGraph ready for invocation\n */\nexport function compileWorkflow(\n dsl: WorkflowDSL,\n resolveAgent: ResolveAgentFn,\n checkpointer: BaseCheckpointSaver,\n trackingStore?: WorkflowTrackingStore\n): CompiledStateGraph<any, any, any, any, any> {\n console.log(`[WF COMPILE] compiling \"${dsl.name}\" | stepCount=${dsl.steps.length}`);\n // 0. Expand concise DSL → InternalDSL\n const ir = expand(dsl);\n\n // 1. Validate expanded DSL\n validateAndThrow(ir);\n console.log(`[WF COMPILE] validation passed`);\n\n // 2. Build state annotation\n const StateAnnotation: AnnotationRoot<any> = buildStateAnnotation(ir.state?.fields);\n\n // 3. Create StateGraph builder\n const builder = new StateGraph(StateAnnotation);\n\n // 4. Register all node handlers\n for (const node of ir.nodes) {\n console.log(`[WF COMPILE] registering node: id=${node.id} type=${node.type} name=${node.name}`);\n const handler = createNodeHandler(node, resolveAgent, trackingStore);\n (builder as any).addNode(node.id, handler);\n }\n\n // 5. Implicit edges: terminal nodes → END\n for (const node of ir.nodes) {\n if (node.type === \"terminal\") {\n (builder as any).addEdge(node.id, END);\n }\n }\n\n // 6. Register edges\n for (const edge of ir.edges) {\n const from = edge.from === \"START\" ? START : edge.from;\n\n if (edge.type === \"conditional\") {\n if (!edge.rule) {\n throw new Error(`Conditional edge from \"${edge.from}\" has no rule`);\n }\n const router = buildRouter(edge.rule);\n (builder as any).addConditionalEdges(from, router, edge.rule.mapping);\n } else {\n const targets = Array.isArray(edge.to) ? edge.to : [edge.to!];\n for (const to of targets) {\n (builder as any).addEdge(from, to === \"END\" ? END : to);\n }\n }\n }\n\n // 7. Compile and return\n const graph = builder.compile({ checkpointer, name: ir.name });\n console.log(`[WF COMPILE] graph compiled successfully, ready to run`);\n return graph;\n}\n\n// ─── DSL Validation ────────────────────────────────────────────────────────\n\nexport interface WorkflowValidationError {\n type: \"error\" | \"warning\";\n message: string;\n}\n\n/** Validate an expanded InternalDSL for structural correctness. */\nexport function validateDSL(dsl: InternalDSL): WorkflowValidationError[] {\n const errors: WorkflowValidationError[] = [];\n const nodeIds = new Set<string>();\n\n for (const node of dsl.nodes) {\n if (nodeIds.has(node.id)) {\n errors.push({ type: \"error\", message: `Duplicate node id \"${node.id}\"` });\n }\n nodeIds.add(node.id);\n }\n\n const terminalIds = new Set(\n dsl.nodes.filter((n) => n.type === \"terminal\").map((n) => n.id)\n );\n const declaredFields = new Set(Object.keys(dsl.state?.fields ?? {}));\n\n for (const edge of dsl.edges) {\n if (edge.from !== \"START\" && !nodeIds.has(edge.from)) {\n errors.push({ type: \"error\", message: `Edge from \"${edge.from}\" references unknown node` });\n }\n if (edge.from !== \"START\" && terminalIds.has(edge.from)) {\n errors.push({ type: \"error\", message: `Terminal node \"${edge.from}\" cannot have outgoing edges` });\n }\n const targets = Array.isArray(edge.to) ? edge.to : edge.to ? [edge.to] : [];\n for (const to of targets) {\n if (to !== \"END\" && !nodeIds.has(to)) {\n errors.push({ type: \"error\", message: `Edge to \"${to}\" references unknown node` });\n }\n }\n if (edge.type === \"conditional\" && edge.rule) {\n for (const targetId of Object.values(edge.rule.mapping)) {\n if (targetId !== \"END\" && !nodeIds.has(targetId)) {\n errors.push({ type: \"error\", message: `Conditional edge mapping references unknown node \"${targetId}\"` });\n }\n }\n if (edge.rule.type === \"state_field\" && edge.rule.field) {\n if (!declaredFields.has(edge.rule.field)) {\n errors.push({ type: \"warning\", message: `Conditional edge reads \"${edge.rule.field}\" but it is not declared in state.fields` });\n }\n }\n }\n }\n\n for (const node of dsl.nodes) {\n if (node.type === \"terminal\") {\n const hasIncoming = dsl.edges.some((e) => {\n const targets = Array.isArray(e.to) ? e.to : e.to ? [e.to] : [];\n return targets.includes(node.id) ||\n (e.type === \"conditional\" && e.rule && Object.values(e.rule.mapping).includes(node.id));\n });\n if (!hasIncoming) {\n errors.push({ type: \"warning\", message: `Terminal node \"${node.id}\" has no incoming edge` });\n }\n }\n }\n\n return errors;\n}\n\nfunction validateAndThrow(dsl: InternalDSL): void {\n const errors = validateDSL(dsl);\n const critical = errors.filter((e) => e.type === \"error\");\n if (critical.length > 0) {\n throw new Error(critical.map((e) => e.message).join(\"; \"));\n }\n}\n\n// ─── Router Builder ────────────────────────────────────────────────────────\n\nfunction buildRouter(rule: InternalEdgeRule): (state: Record<string, unknown>) => string {\n if (rule.type === \"state_field\") {\n if (!rule.field) throw new Error(\"state_field rule requires a field name\");\n return (state: Record<string, unknown>) => {\n const value = resolvePath(state, `state.${rule.field!}`);\n const key = String(value);\n if (rule.mapping[key] !== undefined) return key;\n if (rule.mapping[\"default\"] !== undefined) return \"default\";\n throw new Error(\n `Conditional router produced key \"${key}\" (from field \"${rule.field}\"), ` +\n `but it is not in mapping: ${JSON.stringify(Object.keys(rule.mapping))}`\n );\n };\n }\n\n if (rule.type === \"expression\") {\n if (!rule.code) throw new Error(\"expression rule requires code\");\n const fn = new Function(\"state\", `return ${rule.code}`) as (state: Record<string, unknown>) => unknown;\n return (state: Record<string, unknown>) => {\n const value = fn(state);\n const key = String(value);\n if (rule.mapping[key] !== undefined) return key;\n if (rule.mapping[\"default\"] !== undefined) return \"default\";\n throw new Error(\n `Conditional router produced key \"${key}\" (from expression \"${rule.code}\"), ` +\n `but it is not in mapping: ${JSON.stringify(Object.keys(rule.mapping))}`\n );\n };\n }\n\n throw new Error(`Unknown rule type: ${(rule as InternalEdgeRule).type}`);\n}\n","/**\n * Workflow DSL compilation utilities\n *\n * State annotation builder, template rendering, input/output handling,\n * and node handler factories for all 4 node types (agent, human_feedback, map, terminal).\n */\nimport {\n Annotation,\n} from \"@langchain/langgraph\";\nimport type { AnnotationRoot } from \"@langchain/langgraph\";\nimport { HumanMessage, SystemMessage, type BaseMessage } from \"@langchain/core/messages\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\nimport type { AgentClient } from \"../agent_lattice/types\";\nimport type {\n WorkflowTrackingStore,\n WorkflowRunStatus,\n StepType,\n} from \"@axiom-lattice/protocols\";\nimport type {\n InternalStateField,\n InternalNode,\n InternalAgentNode,\n InternalHumanFeedbackNode,\n InternalMapNode,\n InternalTerminalNode,\n InternalInputNode,\n InternalInput,\n} from \"@axiom-lattice/protocols\";\n\n// ─── Types ─────────────────────────────────────────────────────────────────\n\nexport type ResolveAgentFn = (ref?: string, responseFormat?: Record<string, unknown>, stepType?: string) => Promise<AgentClient>;\n\n// ─── buildStateAnnotation ──────────────────────────────────────────────────\n\n/**\n * Build a LangGraph Annotation.Root from DSL state.fields.\n * Always adds an implicit `phase` field for progress tracking.\n */\nexport function buildStateAnnotation(\n fields?: Record<string, InternalStateField>\n): AnnotationRoot<any> {\n const annotations: Record<string, any> = {};\n\n if (fields) {\n for (const [key, field] of Object.entries(fields)) {\n annotations[key] = Annotation({\n default: () => field.default ?? defaultValueForType(field.type),\n reducer: buildReducer(field.reducer ?? \"replace\"),\n });\n }\n }\n\n // Implicit messages field — used by Agent.agentExecutor to read result\n if (!annotations[\"messages\"]) {\n annotations[\"messages\"] = Annotation<BaseMessage[]>({\n default: () => [],\n reducer: (prev: BaseMessage[], next: BaseMessage[]) => [...prev, ...next],\n });\n }\n\n // Implicit phase field — written by every node\n annotations[\"phase\"] = Annotation<string>({\n default: () => \"init\",\n reducer: (_prev: string, next: string) => next,\n });\n\n // Implicit status field — written by terminal nodes\n if (!annotations[\"status\"]) {\n annotations[\"status\"] = Annotation<string>({\n default: () => \"\",\n reducer: (_prev: string, next: string) => next,\n });\n }\n\n // Implicit _runId field — set by input node, read by agent/human/map nodes for RunStep tracking\n if (!annotations[\"_runId\"]) {\n annotations[\"_runId\"] = Annotation<string | undefined>({\n default: () => undefined,\n reducer: (_prev: string | undefined, next: string | undefined) => next ?? _prev,\n });\n }\n\n return Annotation.Root(annotations);\n}\n\nfunction defaultValueForType(type: string): unknown {\n switch (type) {\n case \"string\": return \"\";\n case \"number\": return null;\n case \"boolean\": return false;\n case \"object\": return null;\n case \"array\": return [];\n default: return null;\n }\n}\n\nfunction buildReducer(kind: string) {\n switch (kind) {\n case \"append\":\n return (prev: unknown, next: unknown) => {\n const arr = Array.isArray(prev) ? prev : [];\n return arr.concat(Array.isArray(next) ? next : [next]);\n };\n case \"merge\":\n return (prev: unknown, next: unknown) => {\n const obj = (prev && typeof prev === \"object\" && !Array.isArray(prev)) ? prev as Record<string, unknown> : {};\n const merge = (next && typeof next === \"object\" && !Array.isArray(next)) ? next as Record<string, unknown> : {};\n return { ...obj, ...merge };\n };\n case \"replace\":\n default:\n return (_prev: unknown, next: unknown) => next;\n }\n}\n\n// ─── resolvePath ───────────────────────────────────────────────────────────\n\n/**\n * Resolve a dot/bracket path against a state object.\n * Strips leading \"state.\" prefix automatically.\n *\n * @example\n * resolvePath({ a: { b: [{ c: 1 }] } }, \"state.a.b[0].c\") // → 1\n */\nexport function resolvePath(obj: Record<string, unknown>, path: string): unknown {\n const cleanPath = path.startsWith(\"state.\") ? path.slice(6) : path;\n // Split on dots and bracket notation: a.b[0].c → [\"a\", \"b\", \"0\", \"c\"]\n const parts = cleanPath.split(/\\.|\\[|\\]\\.?/).filter(Boolean);\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || current === undefined) return undefined;\n if (typeof current === \"object\") {\n current = (current as Record<string, unknown>)[part];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n// ─── renderTemplate ────────────────────────────────────────────────────────\n\n/**\n * Render a template string replacing `${state.path}`, `${item.path}`, and\n * custom item-key shortcuts like `${<key>.path}` (when `<key>` matches a\n * top-level property of the item context).\n *\n * @param template Template string with ${...} placeholders\n * @param state Current workflow state\n * @param item Optional item context (for map nodes). Keys in this object\n * become valid template prefixes (e.g. itemKey=\"row\" → ${row.name}).\n */\nexport function renderTemplate(\n template: string,\n state: Record<string, unknown>,\n item?: Record<string, unknown>\n): string {\n return template.replace(/\\$\\{([^}]+)\\}/g, (_match, expr: string) => {\n const trimmed = expr.trim();\n\n if (trimmed.startsWith(\"state.\")) {\n const val = resolvePath(state, trimmed);\n return val === undefined ? \"\" : formatValue(val);\n }\n\n if (trimmed.startsWith(\"item.\") || trimmed === \"item\") {\n if (!item) return \"\";\n if (trimmed === \"item\") {\n if (typeof item === \"object\" && \"item\" in item) {\n return formatValue((item as Record<string, unknown>).item);\n }\n return formatValue(item);\n }\n const itemPath = trimmed;\n const val = resolvePath({ item } as Record<string, unknown>, itemPath);\n return val === undefined ? \"\" : formatValue(val);\n }\n\n // Custom itemKey shortcut: ${row.name} when item = { row: {...} }\n if (item && typeof item === \"object\") {\n const firstSeg = trimmed.split(\".\")[0];\n if (firstSeg in (item as Record<string, unknown>)) {\n const val = resolvePath({ item } as Record<string, unknown>, `item.${trimmed}`);\n return val === undefined ? \"\" : formatValue(val);\n }\n }\n\n // Unknown prefix — leave placeholder as-is to surface the error\n return `\\${${trimmed}}`;\n });\n}\n\nfunction formatValue(val: unknown): string {\n if (typeof val === \"string\") return val;\n if (val === null || val === undefined) return \"\";\n if (Array.isArray(val)) {\n const parts = val.map((item: Record<string, any>) => {\n const content = item?.content ?? item?.kwargs?.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return (content as Array<Record<string, any>>)\n .filter((c: Record<string, any>) => c?.type === \"text\")\n .map((c: Record<string, any>) => String(c.text ?? \"\"))\n .join(\"\\n\");\n }\n if (content && typeof content === \"object\") return JSON.stringify(content, null, 2);\n // Not a message object — render the item itself\n if (item && typeof item === \"object\") return JSON.stringify(item, null, 2);\n return String(item);\n });\n const result = parts.filter(Boolean).join(\"\\n\");\n return result || JSON.stringify(val, null, 2);\n }\n return JSON.stringify(val, null, 2);\n}\n\n// ─── buildInput ────────────────────────────────────────────────────────────\n\n/**\n * Build input for LangGraph agent invocation from DSL input specification.\n * Returns a partial state with messages, suitable for graph.invoke().\n *\n * When outputSchema is provided, it is converted into a readable JSON example\n * and appended to the prompt so the LLM knows exactly what shape to output.\n */\nexport function buildInput(\n input: InternalInput | undefined,\n state: Record<string, unknown>,\n item?: Record<string, unknown>,\n outputSchema?: Record<string, unknown>\n): { messages: BaseMessage[] } {\n let prompt = input?.template\n ? renderTemplate(input.template, state, item)\n : \"\";\n\n if (outputSchema) {\n const example = schemaToExample(outputSchema);\n const schemaInstruction = `\\n\\nOutput must be valid JSON in exactly this shape. Return ONLY the JSON, no other text or markdown:\\n${example}`;\n prompt = prompt + schemaInstruction;\n }\n\n return { messages: [new HumanMessage(prompt)] };\n}\n\n/**\n * Convert a JSON Schema definition into a readable JSON example for the LLM.\n *\n * Handles standard JSON Schema:\n * { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } } }\n * → { \"name\": \"<string>\" }\n *\n * { \"type\": \"array\", \"items\": { \"type\": \"object\", \"properties\": { ... } } }\n * → [{ ... }]\n *\n * Also handles legacy shorthand for backward compat:\n * { \"field\": \"string\" } → { \"field\": \"<string>\" }\n * { \"items\": [\"object\"] } → { \"items\": [{ ... }] }\n */\nfunction schemaToExample(schema: Record<string, unknown>): string {\n const example = schemaValueToExample(schema);\n return JSON.stringify(example, null, 2);\n}\n\nfunction schemaValueToExample(value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value !== \"object\") return value;\n\n const obj = value as Record<string, unknown>;\n\n if (obj.type === \"string\") return \"<string>\";\n if (obj.type === \"number\") return \"<number>\";\n if (obj.type === \"boolean\") return \"<boolean>\";\n if (obj.type === \"integer\") return \"<integer>\";\n\n if (obj.type === \"array\" && obj.items) {\n return [schemaValueToExample(obj.items)];\n }\n\n if (obj.type === \"object\" && obj.properties && typeof obj.properties === \"object\") {\n const example: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj.properties as Record<string, unknown>)) {\n example[k] = schemaValueToExample(v);\n }\n return example;\n }\n\n if (obj.type === \"object\") return {};\n\n if (Array.isArray(value)) {\n if (value.length === 1) {\n return [schemaValueToExample(value[0])];\n }\n return value.map(schemaValueToExample);\n }\n\n const example: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n example[k] = schemaValueToExample(v);\n }\n return example;\n}\n\n// ─── extractOutput ─────────────────────────────────────────────────────────\n\n/**\n * Extract structured output from a sub-agent invocation result.\n *\n * Priority order:\n * 1. result.structuredResponse — langchain's tool strategy stores parsed output here\n * 2. result.messages — scan backwards for last AIMessage content (native JSON schema /\n * legacy text-based structured output)\n * 3. result itself (minus messages)\n */\nexport function extractOutput(\n result: Record<string, unknown>,\n): unknown {\n // Tool strategy: langchain stores the parsed structured output directly\n if (\"structuredResponse\" in result && result.structuredResponse !== undefined) {\n return result.structuredResponse;\n }\n\n // Scan messages backwards for the last AIMessage\n const messages = result.messages as BaseMessage[] | undefined;\n if (messages && Array.isArray(messages)) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg._getType() === \"ai\") {\n const content = msg.content;\n // Already structured (from native json_schema / withStructuredOutput)\n if (typeof content === \"object\" && content !== null && !Array.isArray(content)) {\n return content;\n }\n // Array content — extract text parts and try JSON parse\n if (Array.isArray(content)) {\n const textParts = content\n .filter((c): c is { type: \"text\"; text: string } =>\n typeof c === \"object\" && c !== null && (c as Record<string, unknown>).type === \"text\"\n )\n .map((c) => c.text)\n .join(\"\\n\");\n if (textParts) {\n try { return JSON.parse(textParts); } catch {\n const fenced = extractJsonFromFence(textParts);\n if (fenced !== undefined) return fenced;\n return textParts;\n }\n }\n return content;\n }\n // String — try JSON parse\n if (typeof content === \"string\") {\n try {\n return JSON.parse(content);\n } catch {\n // Try extracting from ```json ... ``` or ``` ... ``` fences\n const fenced = extractJsonFromFence(content);\n if (fenced !== undefined) return fenced;\n return content;\n }\n }\n return content;\n }\n }\n }\n\n // Fallback: return entire result (minus messages for cleanliness)\n const { messages: _msgs, ...rest } = result;\n void _msgs;\n return rest;\n}\n\n/**\n * Extract JSON from a markdown fenced code block.\n * Handles both ```json ... ``` and ``` ... ```.\n */\nfunction extractJsonFromFence(text: string): unknown | undefined {\n const jsonFence = text.match(/```json\\s*\\n([\\s\\S]*?)```/);\n if (jsonFence) {\n try { return JSON.parse(jsonFence[1].trim()); } catch { /* continue */ }\n }\n const plainFence = text.match(/```\\s*\\n([\\s\\S]*?)```/);\n if (plainFence) {\n try { return JSON.parse(plainFence[1].trim()); } catch { /* continue */ }\n }\n return undefined;\n}\n\n// ─── parallelLimit ─────────────────────────────────────────────────────────\n\n/**\n * Process items in parallel with a concurrency limit (simple semaphore).\n */\nexport async function parallelLimit<T, R>(\n items: T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let index = 0;\n\n async function worker(): Promise<void> {\n while (index < items.length) {\n const i = index++;\n results[i] = await fn(items[i], i);\n }\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));\n return results;\n}\n\n// ─── invokeWithRetry ───────────────────────────────────────────────────────\n\n/**\n * Invoke a function with retry logic and optional timeout.\n */\nexport async function invokeWithRetry<T>(\n fn: () => Promise<T>,\n maxRetries: number,\n retryOn?: string[],\n timeoutMs?: number\n): Promise<T> {\n let lastError: unknown;\n for (let i = 0; i <= maxRetries; i++) {\n try {\n const promise = fn();\n if (timeoutMs && timeoutMs > 0) {\n return await withTimeout(promise, timeoutMs);\n }\n return await promise;\n } catch (err) {\n // GraphInterrupt is control flow, never retry it\n if ((err as any)?.name === \"GraphInterrupt\") {\n throw err;\n }\n lastError = err;\n if (i === maxRetries) throw err;\n if (retryOn?.length) {\n const errName = (err as Error)?.name ?? \"\";\n if (!retryOn.includes(errName)) throw err;\n }\n }\n }\n throw lastError;\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) =>\n setTimeout(() => reject(new Error(`Operation timed out after ${ms}ms`)), ms)\n ),\n ]);\n}\n\n// ─── Node Handler Factories ────────────────────────────────────────────────\n\n/**\n * Create a handler for an `agent` node.\n *\n * Resolves the agent by ref, builds input, invokes with retry,\n * extracts output, and returns a state update.\n */\nexport function createAgentNode(\n node: InternalAgentNode,\n resolveAgent: ResolveAgentFn,\n trackingStore?: WorkflowTrackingStore\n): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>> {\n return async (state, config) => {\n // _runId is set by the input node (createWorkflowRun record ID)\n const runId = (state as Record<string, unknown>)._runId as string | undefined;\n const tenantId = config?.configurable?.tenantId as string ?? \"default\";\n const startedAt = Date.now();\n let stepId: string | undefined;\n\n if (trackingStore && runId) {\n trackingStore.updateWorkflowRun(runId, {\n status: \"running\",\n completedAt: null,\n }).catch(() => {});\n }\n\n try {\n console.log(`[WF][${node.id}] START \"${node.name}\" | hasSchema=${!!node.output?.schema}`);\n const responseFormat = node.output?.schema as Record<string, unknown> | undefined;\n console.log(`[WF][${node.id}] resolving agent...`);\n const client = await resolveAgent(node.ref, responseFormat, node.type);\n console.log(`[WF][${node.id}] agent resolved, building input...`);\n\n // When using native structured output, skip text-based schema injection\n const input = buildInput(\n node.input, state, undefined,\n responseFormat ? undefined : (node.output?.schema as Record<string, unknown> | undefined)\n );\n const renderedInput = (input.messages[0]?.content as string) ?? \"\";\n console.log(`[WF][${node.id}] === INPUT (full) ===\\n${renderedInput}\\n=== END INPUT ===`);\n\n // Create tracking step with rendered input\n if (trackingStore && runId) {\n const step = await trackingStore.upsertRunStep({\n runId, tenantId, stepType: node.type as StepType,\n stepName: node.name,\n input: { template: node.input?.template, rendered: renderedInput },\n }).catch((e) => { console.warn(\"Failed to upsert run step:\", (e as Error).message); return null; });\n stepId = step?.id;\n // On resume after interrupt, step status was \"interrupted\" — reset to \"running\"\n if (step && (step as any).status === \"interrupted\") {\n trackingStore.updateRunStep(runId, step.id, { status: \"running\" }).catch(() => {});\n }\n }\n const subConfig = {\n ...config,\n configurable: {\n ...(config?.configurable ?? {}),\n thread_id: `${config?.configurable?.thread_id ?? \"default\"}:${node.id}`,\n },\n };\n\n let result: Record<string, unknown>;\n try {\n console.log(`[WF][${node.id}] invoking agent.invoke()...`);\n result = await invokeWithRetry(\n () => client.invoke(input, subConfig),\n node.config?.maxRetries ?? 0,\n node.config?.retryOn,\n node.config?.timeout\n ) as Record<string, unknown>;\n console.log(`[WF][${node.id}] invoke SUCCESS, extracting output...`);\n } catch (err) {\n // GraphInterrupt is LangGraph's control-flow mechanism for pausing.\n // Mark the step as interrupted and re-throw.\n if ((err as any)?.name === \"GraphInterrupt\") {\n if (trackingStore && runId && stepId) {\n trackingStore.updateRunStep(runId, stepId, { status: \"interrupted\" }).catch(() => {});\n }\n if (trackingStore && runId) {\n trackingStore.updateWorkflowRun(runId, { status: \"interrupted\", completedAt: null }).catch(() => {});\n }\n throw err;\n }\n\n // Fallback: if structured output fails (e.g. thinking mode rejects tool_choice),\n // retry with text-based schema injection using the default agent\n const errMsg = (err as Error)?.message ?? \"\";\n console.log(`[WF][${node.id}] invoke FAILED: ${errMsg}`);\n if (responseFormat && (\n errMsg.includes(\"tool_choice\") ||\n errMsg.includes(\"thinking\") ||\n errMsg.includes(\"reasoning\") ||\n errMsg.includes(\"InvalidParameter\")\n )) {\n console.log(`[WF][${node.id}] attempting fallback (text-based schema injection)...`);\n const fallbackClient = await resolveAgent(node.ref, undefined, node.type);\n const fallbackInput = buildInput(node.input, state, undefined, responseFormat);\n result = await invokeWithRetry(\n () => fallbackClient.invoke(fallbackInput, subConfig),\n node.config?.maxRetries ?? 0,\n node.config?.retryOn,\n node.config?.timeout\n ) as Record<string, unknown>;\n console.log(`[WF][${node.id}] fallback invoke SUCCESS`);\n } else {\n throw err;\n }\n }\n\n const output = extractOutput(result as Record<string, unknown>);\n console.log(`[WF][${node.id}] === OUTPUT (full) | key=${node.output?.key} ===\\n${JSON.stringify(output, null, 2)}\\n=== END OUTPUT ===`);\n const update: Record<string, unknown> = { phase: node.id };\n if (node.output?.key) {\n update[node.output.key] = output;\n }\n\n // Propagate sub-agent AI messages to workflow messages so\n // Agent.agentExecutor → result.messages.map() finds AI replies\n const subMessages = (result as Record<string, unknown>).messages as BaseMessage[] | undefined;\n if (subMessages && Array.isArray(subMessages)) {\n const aiMessages = subMessages.filter((m: any) => {\n const t = typeof m._getType === \"function\" ? m._getType() : (m.role ?? m.type);\n return t === \"ai\";\n });\n if (aiMessages.length > 0) {\n update.messages = aiMessages;\n }\n }\n console.log(`[WF][${node.id}] DONE (${Date.now() - startedAt}ms)`);\n\n if (trackingStore && runId && stepId) {\n trackingStore.updateRunStep(runId, stepId, {\n status: \"completed\",\n output: output as Record<string, any>,\n completedAt: new Date(),\n durationMs: Date.now() - startedAt,\n }).catch((e) => { console.warn(\"Failed to update run step:\", (e as Error).message); });\n }\n\n return update;\n } catch (err) {\n // GraphInterrupt is not an error — let it propagate to LangGraph runtime.\n if ((err as any)?.name === \"GraphInterrupt\") {\n throw err;\n }\n\n if (trackingStore && runId) {\n if (stepId) {\n trackingStore.updateRunStep(runId, stepId, {\n status: \"failed\",\n errorMessage: (err as Error).message,\n completedAt: new Date(),\n durationMs: Date.now() - startedAt,\n }).catch((e) => { console.warn(\"Failed to update run step:\", (e as Error).message); });\n }\n trackingStore.updateWorkflowRun(runId, {\n status: \"failed\",\n errorMessage: (err as Error).message,\n completedAt: new Date(),\n }).catch((e) => { console.warn(\"Failed to finalize WorkflowRun:\", (e as Error).message); });\n }\n throw err;\n }\n };\n}\n\n/**\n * Create a handler for a `human_feedback` node.\n *\n * Invokes an agent with the rendered prompt. The agent can use the\n * `ask_user_to_clarify` tool to ask the user structured questions;\n * the clarify middleware handles the interrupt/resume cycle automatically.\n * Agent output is extracted and written to state.\n */\nexport function createHumanFeedbackNode(\n node: InternalHumanFeedbackNode,\n resolveAgent: ResolveAgentFn,\n trackingStore?: WorkflowTrackingStore\n): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>> {\n return async (state, config) => {\n const runId = (state as Record<string, unknown>)._runId as string | undefined;\n const tenantId = config?.configurable?.tenantId as string ?? \"default\";\n const startedAt = Date.now();\n let stepId: string | undefined;\n\n if (trackingStore && runId) {\n trackingStore.updateWorkflowRun(runId, {\n status: \"running\",\n completedAt: null,\n }).catch(() => {});\n }\n\n try {\n console.log(`[WF][${node.id}] HUMAN_FEEDBACK START \"${node.config?.title || node.name}\"`);\n\n const responseFormat = node.output?.schema as Record<string, unknown> | undefined;\n const client = await resolveAgent(undefined, responseFormat, node.type);\n console.log(`[WF][${node.id}] agent resolved, building input...`);\n\n const input = buildInput(\n node.input, state, undefined,\n responseFormat ? undefined : (node.output?.schema as Record<string, unknown> | undefined)\n );\n\n // Capture the human prompt BEFORE prepending system instruction,\n // so logging and tracking record the actual prompt text.\n const humanContent = (input.messages[0]?.content as string) ?? \"\";\n\n // Prepend system instruction so the agent follows a strict SOP:\n // present content → ask user → wait for response → output result.\n input.messages = [\n new SystemMessage(\n \"Follow this exact procedure. Do NOT skip any step.\\n\\n\" +\n \"STEP 1: Read the prompt. It contains content to present to the user \" +\n \"and a question to ask.\\n\\n\" +\n \"STEP 2: Call ask_user_to_clarify. Your question text MUST contain \" +\n \"the ACTUAL content from the prompt — copy-paste the relevant text, \" +\n \"data, or facts directly into the question. A question like \\\"Do you \" +\n \"approve this recommendation?\\\" is WRONG because the user has no idea \" +\n \"what the recommendation says. Instead: \\\"Do you approve this \" +\n \"recommendation: [paste the actual recommendation text here]?\\\"\\n\\n\" +\n \"STEP 3: The tool will pause. The user will see your questions and \" +\n \"respond. You will receive their answers.\\n\\n\" +\n \"STEP 4: Based on the user's answers, produce your final output.\"\n ),\n ...input.messages,\n ];\n\n const renderedInput = humanContent;\n\n if (trackingStore && runId) {\n const step = await trackingStore.upsertRunStep({\n runId, tenantId, stepType: node.type as StepType,\n stepName: node.name,\n input: { template: node.input?.template, rendered: renderedInput },\n }).catch((e) => { console.warn(\"Failed to upsert run step:\", (e as Error).message); return null; });\n stepId = step?.id;\n // On resume after interrupt, step status was \"interrupted\" — reset to \"running\"\n if (step && (step as any).status === \"interrupted\") {\n trackingStore.updateRunStep(runId, step.id, { status: \"running\" }).catch(() => {});\n }\n }\n\n const subConfig = {\n ...config,\n configurable: {\n ...(config?.configurable ?? {}),\n thread_id: `${config?.configurable?.thread_id ?? \"default\"}:${node.id}`,\n },\n };\n\n console.log(`[WF][${node.id}] === INPUT (full) ===\\n${renderedInput}\\n=== END INPUT ===`);\n const result = await invokeWithRetry(\n () => client.invoke(input, subConfig),\n node.config?.maxRetries ?? 0,\n node.config?.retryOn,\n node.config?.timeout\n ) as Record<string, unknown>;\n console.log(`[WF][${node.id}] invoke SUCCESS, extracting output...`);\n\n const output = extractOutput(result as Record<string, unknown>);\n console.log(`[WF][${node.id}] === OUTPUT (full) | key=${node.output?.key} ===\\n${JSON.stringify(output, null, 2)}\\n=== END OUTPUT ===`);\n\n const update: Record<string, unknown> = { phase: node.id };\n if (node.output?.key) {\n update[node.output.key] = output;\n }\n if (output && typeof output === \"object\" && !Array.isArray(output)) {\n Object.assign(update, output as Record<string, unknown>);\n }\n\n // Propagate sub-agent AI messages to workflow messages\n const subMessages = (result as Record<string, unknown>).messages as BaseMessage[] | undefined;\n if (subMessages && Array.isArray(subMessages)) {\n const aiMessages = subMessages.filter((m: any) => {\n const t = typeof m._getType === \"function\" ? m._getType() : (m.role ?? m.type);\n return t === \"ai\";\n });\n if (aiMessages.length > 0) {\n update.messages = aiMessages;\n }\n }\n\n console.log(`[WF][${node.id}] DONE (${Date.now() - startedAt}ms)`);\n\n if (trackingStore && runId && stepId) {\n trackingStore.updateRunStep(runId, stepId, {\n status: \"completed\",\n output: output as Record<string, any>,\n completedAt: new Date(),\n durationMs: Date.now() - startedAt,\n }).catch((e) => { console.warn(\"Failed to update run step:\", (e as Error).message); });\n }\n\n return update;\n } catch (err) {\n // GraphInterrupt is NOT an error — it's LangGraph's control-flow mechanism\n // for checkpointing and pausing the graph. Mark the step as interrupted\n // before re-throwing so the tracking store reflects the correct state.\n if ((err as any)?.name === \"GraphInterrupt\") {\n if (trackingStore && runId && stepId) {\n trackingStore.updateRunStep(runId, stepId, {\n status: \"interrupted\",\n }).catch(() => {});\n }\n if (trackingStore && runId) {\n trackingStore.updateWorkflowRun(runId, {\n status: \"interrupted\",\n completedAt: null,\n }).catch(() => {});\n }\n throw err;\n }\n\n if (trackingStore && runId) {\n if (stepId) {\n trackingStore.updateRunStep(runId, stepId, {\n status: \"failed\",\n errorMessage: (err as Error).message,\n completedAt: new Date(),\n durationMs: Date.now() - startedAt,\n }).catch((e) => { console.warn(\"Failed to update run step:\", (e as Error).message); });\n }\n trackingStore.updateWorkflowRun(runId, {\n status: \"failed\",\n errorMessage: (err as Error).message,\n completedAt: new Date(),\n }).catch((e) => { console.warn(\"Failed to finalize WorkflowRun:\", (e as Error).message); });\n }\n throw err;\n }\n };\n}\n\n/**\n * Create a handler for a `map` node.\n *\n * Reads the source array from state, batches items, processes each\n * item through the inner agent in parallel (with concurrency control),\n * and optionally calls a reduce agent to aggregate results.\n */\nexport function createMapNode(\n node: InternalMapNode,\n resolveAgent: ResolveAgentFn,\n trackingStore?: WorkflowTrackingStore\n): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>> {\n return async (state, config) => {\n const runId = (state as Record<string, unknown>)._runId as string | undefined;\n const tenantId = config?.configurable?.tenantId as string ?? \"default\";\n const startedAt = Date.now();\n let stepId: string | undefined;\n\n if (trackingStore && runId) {\n trackingStore.updateWorkflowRun(runId, {\n status: \"running\",\n completedAt: null,\n }).catch(() => {});\n }\n\n try {\n // 1. Read source array\n const items = resolvePath(state, node.source);\n\n if (trackingStore && runId) {\n const step = await trackingStore.upsertRunStep({\n runId, tenantId, stepType: node.type as StepType,\n stepName: node.name,\n input: { source: node.source, itemCount: Array.isArray(items) ? items.length : 0 },\n }).catch((e) => { console.warn(\"Failed to upsert run step:\", (e as Error).message); return null; });\n stepId = step?.id;\n // On resume after interrupt, step status was \"interrupted\" — reset to \"running\"\n if (step && (step as any).status === \"interrupted\") {\n trackingStore.updateRunStep(runId, step.id, { status: \"running\" }).catch(() => {});\n }\n }\n\n if (!Array.isArray(items)) {\n throw new Error(\n `Map source \"${node.source}\" resolved to ${typeof items}, expected array`\n );\n }\n\n const batchSize = node.config?.batchSize ?? 50;\n const maxConcurrency = node.config?.maxConcurrency ?? 10;\n const innerConcurrency = node.config?.innerConcurrency ?? 5;\n const itemKey = node.itemKey ?? \"item\";\n\n // 2. Resolve inner agent once\n const innerClient = await resolveAgent(node.node.ref, node.node.schema, node.type);\n\n // 3. Batch and process\n const batches = chunk(items, batchSize);\n\n const batchResults = await parallelLimit(batches, maxConcurrency, async (batch) => {\n // Process items within this batch\n const itemResults = await parallelLimit(batch as Record<string, unknown>[], innerConcurrency, async (item, itemIdx) => {\n const itemCtx: Record<string, unknown> = { [itemKey]: item };\n const input = buildInput(node.node.input, state, itemCtx);\n\n const subConfig = {\n ...config,\n configurable: {\n ...(config?.configurable ?? {}),\n thread_id: `${config?.configurable?.thread_id ?? \"default\"}:${node.id}:item:${itemIdx}`,\n },\n };\n\n const result = await invokeWithRetry(\n () => innerClient.invoke(input, subConfig),\n node.config?.maxRetries ?? 0,\n node.config?.retryOn,\n node.config?.timeout\n );\n return extractOutput(result as Record<string, unknown>);\n });\n\n return itemResults;\n });\n\n // 4. Flatten results\n const allResults = batchResults.flat();\n\n // 5. Optional reduce\n let finalOutput: unknown = allResults;\n if (node.reduce) {\n const reduceClient = await resolveAgent(node.reduce.ref, node.reduce.schema, node.type);\n const tempResultsKey = node.output?.key ?? `${node.id}_results`;\n const tempState = { ...state, [tempResultsKey]: allResults };\n const reduceInput = buildInput(node.reduce.input, tempState);\n const reduceResult = await invokeWithRetry(\n () => reduceClient.invoke(reduceInput, {\n ...config,\n configurable: {\n ...(config?.configurable ?? {}),\n thread_id: `${config?.configurable?.thread_id ?? \"default\"}:${node.id}:reduce`,\n },\n }),\n node.config?.maxRetries ?? 0,\n node.config?.retryOn,\n node.config?.timeout\n );\n finalOutput = extractOutput(reduceResult as Record<string, unknown>);\n }\n\n const update: Record<string, unknown> = { phase: node.id };\n if (node.output?.key) {\n update[node.output.key] = finalOutput;\n }\n\n if (trackingStore && runId && stepId) {\n trackingStore.updateRunStep(runId, stepId, {\n status: \"completed\",\n output: finalOutput as Record<string, any>,\n completedAt: new Date(),\n durationMs: Date.now() - startedAt,\n }).catch((e) => { console.warn(\"Failed to update run step:\", (e as Error).message); });\n }\n\n return update;\n } catch (err) {\n // GraphInterrupt is not an error — mark interrupted and let it propagate.\n if ((err as any)?.name === \"GraphInterrupt\") {\n if (trackingStore && runId && stepId) {\n trackingStore.updateRunStep(runId, stepId, { status: \"interrupted\" }).catch(() => {});\n }\n if (trackingStore && runId) {\n trackingStore.updateWorkflowRun(runId, { status: \"interrupted\", completedAt: null }).catch(() => {});\n }\n throw err;\n }\n\n console.error(`[WF][${node.id}] FAILED after ${Date.now() - startedAt}ms:`, (err as Error).stack || (err as Error).message);\n if (trackingStore && runId) {\n if (stepId) {\n trackingStore.updateRunStep(runId, stepId, {\n status: \"failed\",\n errorMessage: (err as Error).message,\n completedAt: new Date(),\n durationMs: Date.now() - startedAt,\n }).catch(() => {});\n }\n trackingStore.updateWorkflowRun(runId, {\n status: \"failed\",\n errorMessage: (err as Error).message,\n completedAt: new Date(),\n }).catch(() => {});\n }\n throw err;\n }\n };\n}\n\n/**\n * Create a handler for an `input` node.\n *\n * Captures the user's initial message into state.input and creates a\n * WorkflowRun tracking record if a tracking store is available.\n * The generated runId flows to downstream step tracking via state._runId.\n */\nexport function createInputNode(\n node: InternalInputNode,\n trackingStore?: WorkflowTrackingStore\n): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>> {\n return async (state, config) => {\n const tenantId = (config?.configurable?.tenantId as string) ?? \"default\";\n const threadId = (config?.configurable?.thread_id as string) ?? \"default\";\n const assistantId = (config?.configurable?.assistantId as string)\n || (config?.configurable?.assistant_id as string)\n || \"unknown\";\n\n const messages = (state as Record<string, unknown>).messages as BaseMessage[] | undefined;\n const humanMsg = messages?.find(m => m._getType() === \"human\");\n const inputText = typeof humanMsg?.content === \"string\"\n ? humanMsg.content\n : JSON.stringify(humanMsg?.content ?? \"\");\n console.log(`[WF][n_input] input captured: \"${inputText.slice(0, 200)}\"`);\n\n const update: Record<string, unknown> = { phase: node.id };\n if (node.output?.key) update[node.output.key] = inputText;\n\n if (trackingStore && !(state as Record<string, unknown>)._runId) {\n try {\n const run = await trackingStore.createWorkflowRun({\n tenantId,\n assistantId,\n threadId,\n topologyEdges: [],\n metadata: { workflowName: node.name },\n });\n update._runId = run.id;\n\n // Also create a RunStep for the input node itself\n await trackingStore.createRunStep({\n runId: run.id,\n tenantId,\n stepType: node.type as StepType,\n stepName: node.name,\n input: { rendered: inputText },\n }).catch((e) => { console.warn(\"Failed to create input run step:\", (e as Error).message); });\n } catch (e) {\n console.warn(\"Failed to create workflow run:\", (e as Error).message);\n }\n }\n\n return update;\n };\n}\n\n/**\n * Map InternalTerminalNode status to WorkflowRunStatus.\n */\nfunction terminalStatusToRunStatus(\n status: InternalTerminalNode[\"status\"]\n): WorkflowRunStatus {\n switch (status) {\n case \"failed\":\n return \"failed\";\n case \"cancelled\":\n return \"cancelled\";\n case \"success\":\n default:\n return \"completed\";\n }\n}\n\n/**\n * Create a handler for a `terminal` node.\n *\n * Sets the status field in state and finalizes the WorkflowRun tracking record.\n * An implicit edge to END is added during graph compilation.\n */\nexport function createTerminalNode(\n node: InternalTerminalNode,\n trackingStore?: WorkflowTrackingStore\n): (state: Record<string, unknown>) => Promise<Partial<Record<string, unknown>>> {\n const runStatus = terminalStatusToRunStatus(node.status);\n\n return async (state: Record<string, unknown>) => {\n const runId = state._runId as string | undefined;\n\n if (trackingStore && runId) {\n try {\n await trackingStore.updateWorkflowRun(runId, {\n status: runStatus,\n completedAt: new Date(),\n });\n } catch (e) {\n console.warn(`[WF][terminal] Failed to finalize WorkflowRun \"${runId}\":`, (e as Error).message);\n }\n\n try {\n await trackingStore.createRunStep({\n runId,\n tenantId: (state._tenantId as string) ?? \"default\",\n stepType: \"terminal\",\n stepName: node.name,\n input: { status: node.status },\n });\n } catch (e) {\n console.warn(`[WF][terminal] Failed to create terminal RunStep:`, (e as Error).message);\n }\n }\n\n return {\n status: node.status,\n phase: node.id,\n };\n };\n}\n\n// ─── Handler Dispatcher ────────────────────────────────────────────────────\n\n/**\n * Dispatch to the correct handler factory based on node type.\n */\nexport function createNodeHandler(\n node: InternalNode,\n resolveAgent: ResolveAgentFn,\n trackingStore?: WorkflowTrackingStore\n): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>> {\n switch (node.type) {\n case \"agent\":\n return createAgentNode(node as InternalAgentNode, resolveAgent, trackingStore);\n case \"human_feedback\":\n return createHumanFeedbackNode(node as InternalHumanFeedbackNode, resolveAgent, trackingStore);\n case \"map\":\n return createMapNode(node as InternalMapNode, resolveAgent, trackingStore);\n case \"terminal\":\n return createTerminalNode(node as InternalTerminalNode, trackingStore);\n case \"input\":\n return createInputNode(node as InternalInputNode, trackingStore) as any;\n default:\n throw new Error(`Unknown node type: ${(node as InternalNode).type}`);\n }\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction chunk<T>(arr: T[], size: number): T[][] {\n const result: T[][] = [];\n for (let i = 0; i < arr.length; i += size) {\n result.push(arr.slice(i, i + size));\n }\n return result;\n}\n","/**\n * expand — WorkflowDSL (concise) → InternalDSL (expanded IR).\n */\nimport type {\n InternalDSL,\n InternalNode,\n InternalEdge,\n InternalStateField,\n} from \"@axiom-lattice/protocols\";\nimport type {\n WorkflowDSL,\n WorkflowStep,\n AgentStep,\n ConditionStep,\n HumanStep,\n MapStep,\n ParallelStep,\n EndStep,\n} from \"@axiom-lattice/protocols\";\n\nlet _counter = 0;\nfunction uid(prefix: string): string { return `${prefix}_${_counter++}`; }\nfunction nodeId(stepId: string): string { return `n_${stepId}`; }\n\nfunction translate(template: string): string {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (_m, expr: string) => {\n const t = expr.trim();\n if (t === \"item\") return \"${item}\";\n return `\\${state.${t}}`;\n });\n}\n\nfunction inferFieldType(id: string): InternalStateField {\n if (/s$|list|array|items|results/i.test(id)) return { type: \"array\", default: [] };\n return { type: \"string\" };\n}\n\ninterface StepExpansion { nodes: InternalNode[]; edges: InternalEdge[]; entryId: string; exitIds: string[]; }\n\nfunction expandStep(step: WorkflowStep): StepExpansion {\n switch (step.type ?? \"agent\") {\n case \"agent\": return expandAgent(step as AgentStep);\n case \"human\": return expandHuman(step as HumanStep);\n case \"condition\": return expandCondition(step as ConditionStep);\n case \"map\": return expandMap(step as MapStep);\n case \"parallel\": return expandParallel(step as ParallelStep);\n case \"end\": return expandEnd(step as EndStep);\n }\n}\n\n/**\n * Validate that a schema is in standard JSON Schema format.\n * Only { \"type\": \"object\", \"properties\": { ... } } is accepted.\n * Legacy shorthand like { \"field\": \"string\" } is rejected.\n */\nfunction validateSchema(schema: Record<string, unknown>, stepId: string): void {\n if (schema.type !== \"object\") {\n throw new Error(\n `Step \"${stepId}\": schema.type must be \"object\", got \"${String(schema.type)}\". ` +\n `Use standard JSON Schema: { \"type\": \"object\", \"properties\": { ... } }`\n );\n }\n if (!schema.properties || typeof schema.properties !== \"object\") {\n throw new Error(\n `Step \"${stepId}\": schema must have a \"properties\" object. ` +\n `Legacy shorthand like { \"field\": \"string\" } is not supported. ` +\n `Use: { \"type\": \"object\", \"properties\": { \"field\": { \"type\": \"string\" } } }`\n );\n }\n}\n\nfunction expandAgent(s: AgentStep): StepExpansion {\n const sid = s.id || uid(\"agent\");\n const nid = nodeId(sid);\n if (s.schema !== undefined && s.schema !== null) {\n if (typeof s.schema !== \"object\") {\n throw new Error(\n `Step \"${sid}\": schema must be a JSON Schema object, ` +\n `e.g. { \"type\": \"object\", \"properties\": { ... } }. ` +\n `Got ${typeof s.schema} (${JSON.stringify(s.schema)}).`\n );\n }\n validateSchema(s.schema as Record<string, unknown>, sid);\n }\n const schema = s.schema && typeof s.schema === \"object\"\n ? (s.schema as Record<string, unknown>)\n : undefined;\n console.log(`[WF EXPAND] agent step id=\"${sid}\" nodeId=\"${nid}\" | hasSchema=${!!schema}`);\n return {\n nodes: [{ id: nid, type: \"agent\", name: sid, input: { template: translate(s.prompt) }, output: { key: sid, ...(schema ? { schema } : {}) } }],\n edges: [], entryId: nid, exitIds: [nid],\n };\n}\n\nfunction expandHuman(s: HumanStep): StepExpansion {\n const sid = s.id || uid(\"human\");\n const nid = nodeId(sid);\n\n if (s.schema !== undefined && s.schema !== null) {\n if (typeof s.schema !== \"object\") {\n throw new Error(\n `Step \"${sid}\": schema must be a JSON Schema object, ` +\n `e.g. { \"type\": \"object\", \"properties\": { ... } }. ` +\n `Got ${typeof s.schema} (${JSON.stringify(s.schema)}).`\n );\n }\n validateSchema(s.schema as Record<string, unknown>, sid);\n }\n\n const schema = s.schema && typeof s.schema === \"object\"\n ? (s.schema as Record<string, unknown>)\n : undefined;\n return {\n nodes: [{ id: nid, type: \"human_feedback\", name: sid, config: { title: s.title ?? sid }, input: { template: translate(s.prompt) }, output: { key: sid, ...(schema ? { schema } : {}) } }],\n edges: [], entryId: nid, exitIds: [nid],\n };\n}\n\nfunction expandCondition(s: ConditionStep): StepExpansion {\n const sid = s.id || uid(\"cond\");\n const nid = nodeId(sid);\n\n if (s.branches) {\n const branchExps: Record<string, StepsExpansion> = {};\n for (const [key, steps] of Object.entries(s.branches)) {\n branchExps[key] = expandSteps(Array.isArray(steps) ? steps : [steps]);\n }\n const allNodes = Object.values(branchExps).flatMap((e) => e.nodes);\n const allEdges = Object.values(branchExps).flatMap((e) => e.edges);\n const allExitIds = [...new Set(Object.values(branchExps).flatMap((e) => e.exitIds))];\n const branchEntryIds = Object.fromEntries(\n Object.entries(branchExps).map(([k, v]) => [k, v.entryId])\n );\n return {\n nodes: allNodes, edges: allEdges,\n entryId: nid, exitIds: allExitIds,\n branchEntryIds,\n } as StepExpansion & { branchEntryIds: Record<string, string> };\n }\n\n if (!s.then) {\n throw new Error(`Condition step \"${sid}\": must have either \"then\" or \"branches\"`);\n }\n\n const thenSteps = Array.isArray(s.then!) ? s.then! : [s.then!];\n const elseSteps = s.else ? (Array.isArray(s.else) ? s.else : [s.else]) : [];\n const thenExp = expandSteps(thenSteps);\n const elseExp = expandSteps(elseSteps);\n return {\n nodes: [...thenExp.nodes, ...elseExp.nodes], edges: [...thenExp.edges, ...elseExp.edges],\n entryId: nid, exitIds: [...thenExp.exitIds, ...elseExp.exitIds],\n thenEntryId: thenExp.entryId, elseEntryId: elseExp.entryId,\n } as StepExpansion & { thenEntryId: string; elseEntryId: string };\n}\n\nfunction expandMap(s: MapStep): StepExpansion {\n const sid = s.id;\n const nid = nodeId(sid);\n const inner = s.each;\n return {\n nodes: [{\n id: nid, type: \"map\", name: sid, source: `state.${s.source}`, itemKey: \"item\",\n config: { batchSize: s.batch ?? 50, maxConcurrency: s.concurrency ?? 5, innerConcurrency: s.concurrency ?? 5 },\n node: { type: \"agent\", input: inner.prompt ? { template: translate(inner.prompt) } : undefined, ...(inner.schema && typeof inner.schema === \"object\" ? { schema: inner.schema as Record<string, unknown> } : {}) },\n ...(s.reduce ? { reduce: { input: s.reduce.prompt ? { template: translate(s.reduce.prompt) } : undefined, ...(s.reduce.schema && typeof s.reduce.schema === \"object\" ? { schema: s.reduce.schema as Record<string, unknown> } : {}) } } : {}),\n output: { key: sid },\n }],\n edges: [], entryId: nid, exitIds: [nid],\n };\n}\n\nfunction expandParallel(s: ParallelStep): StepExpansion {\n const nodes: InternalNode[] = [];\n const edges: InternalEdge[] = [];\n const entryIds: string[] = [];\n const exitIds: string[] = [];\n for (const step of s.steps) {\n const exp = expandStep(step);\n nodes.push(...exp.nodes); edges.push(...exp.edges);\n entryIds.push(exp.entryId);\n if (exp.exitIds.length > 0) exitIds.push(...exp.exitIds);\n }\n return { nodes, edges, entryId: entryIds[0], exitIds };\n}\n\nfunction expandEnd(s: EndStep): StepExpansion {\n const sid = uid(\"end\");\n const nid = nodeId(sid);\n return { nodes: [{ id: nid, type: \"terminal\", name: sid, status: s.status ?? \"success\" }], edges: [], entryId: nid, exitIds: [] };\n}\n\ninterface StepsExpansion { nodes: InternalNode[]; edges: InternalEdge[]; entryId: string; exitIds: string[]; }\n\nfunction expandSteps(steps: WorkflowStep[], fromStart = false): StepsExpansion {\n if (steps.length === 0) return { nodes: [], edges: [], entryId: \"END\", exitIds: [\"END\"] };\n const allNodes: InternalNode[] = [];\n const allEdges: InternalEdge[] = [];\n let prevExitIds: string[] = [];\n let firstEntryId: string | null = null;\n for (let i = 0; i < steps.length; i++) {\n const exp = expandStep(steps[i]);\n if (exp.nodes.length > 0) allNodes.push(...exp.nodes);\n if (exp.edges.length > 0) allEdges.push(...exp.edges);\n if (firstEntryId === null) firstEntryId = exp.entryId;\n if (prevExitIds.length > 0) addEdge(steps[i], exp, prevExitIds, allEdges);\n else if (fromStart && i === 0) addEdge(steps[i], exp, [\"START\"], allEdges);\n prevExitIds = exp.exitIds.length > 0 ? exp.exitIds : prevExitIds;\n }\n return { nodes: allNodes, edges: allEdges, entryId: firstEntryId || \"END\", exitIds: prevExitIds };\n}\n\n/**\n * Convert a condition expression's first state-field identifier to bracket\n * notation so hyphenated step ids (e.g. \"classify-doc\") don't break\n * JavaScript parsing as subtraction.\n *\n * \"classify-doc.classification === 'report'\" → \"state[\\\"classify-doc\\\"].classification === 'report'\"\n * \"count > 5\" → \"state[\\\"count\\\"] > 5\"\n */\nfunction toSafeStateExpr(expr: string): string {\n const match = expr.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)/);\n if (!match) return `state.${expr}`;\n const field = match[0];\n const rest = expr.slice(field.length);\n return `state[\"${field}\"]${rest}`;\n}\n\nfunction addEdge(step: WorkflowStep, exp: StepExpansion, fromIds: string[], allEdges: InternalEdge[]) {\n if ((step as ConditionStep).type === \"condition\") {\n const s = step as ConditionStep;\n\n if (s.if.includes(\"{{\")) {\n throw new Error(\n `Condition step \"${s.id || \"unnamed\"}\": the \\`if\\` field contains \"{{\". ` +\n `Use a plain state field name or JavaScript expression (e.g. \"intent\", \"score >= 60\"). ` +\n `Template markers {{...}} are only for \\`prompt\\` fields, not \\`if\\`. ` +\n `Found: \"${s.if}\"`\n );\n }\n\n if (s.branches) {\n // Switch mode: expression returns the field value directly, mapping uses branch keys\n const condExp = exp as StepExpansion & { branchEntryIds: Record<string, string> };\n const exprCode = toSafeStateExpr(s.if);\n const mapping: Record<string, string> = {};\n for (const [key, branchId] of Object.entries(condExp.branchEntryIds)) {\n if (branchId) mapping[key] = branchId;\n }\n for (const fromId of fromIds) allEdges.push({ from: fromId, type: \"conditional\", rule: { type: \"expression\", code: exprCode, mapping } });\n } else {\n // Classic if/else mode: ternary expression → 'then' | 'else'\n const condExp = exp as StepExpansion & { thenEntryId: string; elseEntryId: string };\n const exprCode = `${toSafeStateExpr(s.if!)} ? 'then' : 'else'`;\n const mapping: Record<string, string> = {};\n if (condExp.thenEntryId) mapping.then = condExp.thenEntryId;\n if (condExp.elseEntryId) mapping.else = condExp.elseEntryId;\n for (const fromId of fromIds) allEdges.push({ from: fromId, type: \"conditional\", rule: { type: \"expression\", code: exprCode, mapping } });\n }\n } else if ((step as ParallelStep).type === \"parallel\") {\n for (const fromId of fromIds) {\n for (const sub of (step as ParallelStep).steps) allEdges.push({ from: fromId, to: expandStep(sub).entryId });\n }\n } else {\n for (const fromId of fromIds) allEdges.push({ from: fromId, to: exp.entryId });\n }\n}\n\nfunction collectIds(steps: WorkflowStep[]): string[] {\n const ids: string[] = [];\n function walk(s: WorkflowStep) {\n const id = s.type === \"condition\" ? (s as ConditionStep).id || uid(\"cond\")\n : s.type === \"parallel\" ? (s as ParallelStep).id || uid(\"par\")\n : s.type === \"end\" ? uid(\"end\")\n : (s as AgentStep).id\n || (s as HumanStep).id\n || uid(\"human\");\n if (s.type !== \"end\" && s.type !== \"condition\") ids.push(id);\n if (s.type === \"condition\") {\n const c = s as ConditionStep;\n if (c.branches) {\n for (const steps of Object.values(c.branches)) {\n (Array.isArray(steps) ? steps : [steps]).forEach(walk);\n }\n } else {\n (Array.isArray(c.then!) ? c.then! : [c.then!]).forEach(walk);\n if (c.else) (Array.isArray(c.else) ? c.else : [c.else]).forEach(walk);\n }\n }\n if (s.type === \"parallel\") (s as ParallelStep).steps.forEach(walk);\n }\n steps.forEach(walk);\n return [...new Set(ids)];\n}\n\nfunction collectSourceIds(steps: WorkflowStep[]): string[] {\n const ids: string[] = [];\n function walk(s: WorkflowStep) {\n if (s.type === \"map\") ids.push((s as MapStep).source);\n if (s.type === \"condition\") {\n const c = s as ConditionStep;\n if (c.branches) {\n for (const steps of Object.values(c.branches)) {\n (Array.isArray(steps) ? steps : [steps]).forEach(walk);\n }\n } else {\n (Array.isArray(c.then!) ? c.then! : [c.then!]).forEach(walk);\n if (c.else) (Array.isArray(c.else) ? c.else : [c.else]).forEach(walk);\n }\n }\n if (s.type === \"parallel\") (s as ParallelStep).steps.forEach(walk);\n }\n steps.forEach(walk);\n return [...new Set(ids)];\n}\n\nexport function expand(dsl: WorkflowDSL): InternalDSL {\n _counter = 0;\n console.log(`[WF EXPAND] expanding workflow \"${dsl.name}\" | stepCount=${dsl.steps.length}`);\n const inputNode: InternalNode = {\n id: \"n_input\", type: \"input\", name: \"input\", output: { key: \"input\" },\n };\n const expanded = expandSteps(dsl.steps, true);\n // Replace START→* links with START→n_input→*, or START→n_input→END for empty\n const edges: InternalEdge[] = expanded.entryId === \"END\"\n ? [{ from: \"START\", to: \"n_input\" }]\n : [\n ...expanded.edges.map(e => ({ ...e, from: e.from === \"START\" ? \"n_input\" : e.from })),\n { from: \"START\", to: \"n_input\" },\n ];\n\n const nodes = [inputNode, ...expanded.nodes];\n const ids = collectIds(dsl.steps);\n const sourceIds = collectSourceIds(dsl.steps);\n const fields: Record<string, InternalStateField> = { input: { type: \"string\" } };\n for (const id of ids) fields[id] = inferFieldType(id);\n for (const id of sourceIds) { if (!fields[id]) fields[id] = inferFieldType(id); }\n const result: InternalDSL = { version: \"1.0\", name: dsl.name, state: { fields }, nodes, edges };\n console.log(`[WF EXPAND] done | nodeCount=${result.nodes.length} | nodeIds=[${result.nodes.map(n => `${n.id}:${n.type}`).join(\", \")}] | fieldIds=[${Object.keys(fields).join(\", \")}]`);\n return result;\n}\n"],"mappings":";AAMA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAG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AAC,CAAC;AAAA,MACxE;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,sBAAuB,KAA0B,IAAI,EAAE;AACzE;","names":["example","steps"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/index.d.mts
CHANGED
|
@@ -8,7 +8,7 @@ import { BaseLanguageModelInput, LanguageModelLike, BaseLanguageModel } from '@l
|
|
|
8
8
|
import { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
9
9
|
import { ChatResult } from '@langchain/core/outputs';
|
|
10
10
|
import * as _axiom_lattice_protocols from '@axiom-lattice/protocols';
|
|
11
|
-
import { LLMConfig, SemanticMetricsServerConfig, MetricMeta, MetricQueryResult, DataSource, SemanticMetricsQueryRequest, SemanticMetricsQueryResponse, TableQueryRequest, TableQueryResponse, ExecuteSqlQueryRequest, ExecuteSqlQueryResponse, MetricsServerType, MetricsServerConfig, ToolConfig, ToolExecutor, AgentConfig, MiddlewareType, GraphBuildOptions, MessageChunk, MessageChunkType, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, ThreadStore, AssistantStore, SkillStore, WorkspaceStore, ProjectStore, DatabaseConfigStore, MetricsServerConfigStore, McpServerConfigStore, UserStore, TenantStore, UserTenantLinkStore, WorkflowTrackingStore, EvalStore, ChannelInstallationStore, BindingRegistry, A2AApiKeyStore, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, Skill, CreateSkillRequest, SkillStoreContext, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, User, CreateUserRequest, UpdateUserRequest, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationRequest, UpdateChannelInstallationRequest, Binding, CreateBindingInput, A2AApiKeyRecord, CreateA2AApiKeyInput, A2AApiKeyEntry, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient } from '@axiom-lattice/protocols';
|
|
11
|
+
import { LLMConfig, SemanticMetricsServerConfig, MetricMeta, MetricQueryResult, DataSource, SemanticMetricsQueryRequest, SemanticMetricsQueryResponse, TableQueryRequest, TableQueryResponse, ExecuteSqlQueryRequest, ExecuteSqlQueryResponse, MetricsServerType, MetricsServerConfig, ToolConfig, ToolExecutor, AgentConfig, MiddlewareType, GraphBuildOptions, MessageChunk, MessageChunkType, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, ThreadStore, AssistantStore, SkillStore, WorkspaceStore, ProjectStore, DatabaseConfigStore, MetricsServerConfigStore, McpServerConfigStore, UserStore, TenantStore, UserTenantLinkStore, WorkflowTrackingStore, EvalStore, ChannelInstallationStore, BindingRegistry, A2AApiKeyStore, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, Skill, CreateSkillRequest, SkillStoreContext, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, User, CreateUserRequest, UpdateUserRequest, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationRequest, UpdateChannelInstallationRequest, Binding, CreateBindingInput, A2AApiKeyRecord, CreateA2AApiKeyInput, A2AApiKeyEntry, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient, InternalStateField, InternalInput, InternalNode, InternalAgentNode, InternalHumanFeedbackNode, InternalMapNode, InternalTerminalNode, WorkflowDSL, InternalDSL } from '@axiom-lattice/protocols';
|
|
12
12
|
export { _axiom_lattice_protocols as Protocols };
|
|
13
13
|
export { AgentConfig, AgentType, GraphBuildOptions, MemoryType } from '@axiom-lattice/protocols';
|
|
14
14
|
import * as langchain from 'langchain';
|
|
@@ -26,7 +26,7 @@ import { Connection, MultiServerMCPClient } from '@langchain/mcp-adapters';
|
|
|
26
26
|
import { SandboxClient } from '@agent-infra/sandbox';
|
|
27
27
|
import { Sandbox } from 'e2b';
|
|
28
28
|
import { Sandbox as Sandbox$1 } from '@daytonaio/sdk';
|
|
29
|
-
import { Runnable } from '@langchain/core/runnables';
|
|
29
|
+
import { Runnable, RunnableConfig } from '@langchain/core/runnables';
|
|
30
30
|
import { InteropZodObject } from '@langchain/core/utils/types';
|
|
31
31
|
|
|
32
32
|
/**
|
|
@@ -1711,6 +1711,7 @@ interface AgentBuildParams {
|
|
|
1711
1711
|
}>;
|
|
1712
1712
|
prompt: string;
|
|
1713
1713
|
stateSchema?: z$1.ZodObject<any, any, any, any, any>;
|
|
1714
|
+
responseFormat?: any;
|
|
1714
1715
|
tenantId?: string;
|
|
1715
1716
|
}
|
|
1716
1717
|
|
|
@@ -6425,4 +6426,122 @@ interface UnknownToolHandlerConfig {
|
|
|
6425
6426
|
*/
|
|
6426
6427
|
declare function createUnknownToolHandlerMiddleware(config?: UnknownToolHandlerConfig): AgentMiddleware;
|
|
6427
6428
|
|
|
6428
|
-
|
|
6429
|
+
type ResolveAgentFn = (ref?: string, responseFormat?: Record<string, unknown>, stepType?: string) => Promise<AgentClient>;
|
|
6430
|
+
/**
|
|
6431
|
+
* Build a LangGraph Annotation.Root from DSL state.fields.
|
|
6432
|
+
* Always adds an implicit `phase` field for progress tracking.
|
|
6433
|
+
*/
|
|
6434
|
+
declare function buildStateAnnotation(fields?: Record<string, InternalStateField>): AnnotationRoot<any>;
|
|
6435
|
+
/**
|
|
6436
|
+
* Resolve a dot/bracket path against a state object.
|
|
6437
|
+
* Strips leading "state." prefix automatically.
|
|
6438
|
+
*
|
|
6439
|
+
* @example
|
|
6440
|
+
* resolvePath({ a: { b: [{ c: 1 }] } }, "state.a.b[0].c") // → 1
|
|
6441
|
+
*/
|
|
6442
|
+
declare function resolvePath(obj: Record<string, unknown>, path: string): unknown;
|
|
6443
|
+
/**
|
|
6444
|
+
* Render a template string replacing `${state.path}`, `${item.path}`, and
|
|
6445
|
+
* custom item-key shortcuts like `${<key>.path}` (when `<key>` matches a
|
|
6446
|
+
* top-level property of the item context).
|
|
6447
|
+
*
|
|
6448
|
+
* @param template Template string with ${...} placeholders
|
|
6449
|
+
* @param state Current workflow state
|
|
6450
|
+
* @param item Optional item context (for map nodes). Keys in this object
|
|
6451
|
+
* become valid template prefixes (e.g. itemKey="row" → ${row.name}).
|
|
6452
|
+
*/
|
|
6453
|
+
declare function renderTemplate(template: string, state: Record<string, unknown>, item?: Record<string, unknown>): string;
|
|
6454
|
+
/**
|
|
6455
|
+
* Build input for LangGraph agent invocation from DSL input specification.
|
|
6456
|
+
* Returns a partial state with messages, suitable for graph.invoke().
|
|
6457
|
+
*
|
|
6458
|
+
* When outputSchema is provided, it is converted into a readable JSON example
|
|
6459
|
+
* and appended to the prompt so the LLM knows exactly what shape to output.
|
|
6460
|
+
*/
|
|
6461
|
+
declare function buildInput(input: InternalInput | undefined, state: Record<string, unknown>, item?: Record<string, unknown>, outputSchema?: Record<string, unknown>): {
|
|
6462
|
+
messages: BaseMessage[];
|
|
6463
|
+
};
|
|
6464
|
+
/**
|
|
6465
|
+
* Extract structured output from a sub-agent invocation result.
|
|
6466
|
+
*
|
|
6467
|
+
* Priority order:
|
|
6468
|
+
* 1. result.structuredResponse — langchain's tool strategy stores parsed output here
|
|
6469
|
+
* 2. result.messages — scan backwards for last AIMessage content (native JSON schema /
|
|
6470
|
+
* legacy text-based structured output)
|
|
6471
|
+
* 3. result itself (minus messages)
|
|
6472
|
+
*/
|
|
6473
|
+
declare function extractOutput(result: Record<string, unknown>): unknown;
|
|
6474
|
+
/**
|
|
6475
|
+
* Process items in parallel with a concurrency limit (simple semaphore).
|
|
6476
|
+
*/
|
|
6477
|
+
declare function parallelLimit<T, R>(items: T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
|
|
6478
|
+
/**
|
|
6479
|
+
* Invoke a function with retry logic and optional timeout.
|
|
6480
|
+
*/
|
|
6481
|
+
declare function invokeWithRetry<T>(fn: () => Promise<T>, maxRetries: number, retryOn?: string[], timeoutMs?: number): Promise<T>;
|
|
6482
|
+
/**
|
|
6483
|
+
* Create a handler for an `agent` node.
|
|
6484
|
+
*
|
|
6485
|
+
* Resolves the agent by ref, builds input, invokes with retry,
|
|
6486
|
+
* extracts output, and returns a state update.
|
|
6487
|
+
*/
|
|
6488
|
+
declare function createAgentNode(node: InternalAgentNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6489
|
+
/**
|
|
6490
|
+
* Create a handler for a `human_feedback` node.
|
|
6491
|
+
*
|
|
6492
|
+
* Invokes an agent with the rendered prompt. The agent can use the
|
|
6493
|
+
* `ask_user_to_clarify` tool to ask the user structured questions;
|
|
6494
|
+
* the clarify middleware handles the interrupt/resume cycle automatically.
|
|
6495
|
+
* Agent output is extracted and written to state.
|
|
6496
|
+
*/
|
|
6497
|
+
declare function createHumanFeedbackNode(node: InternalHumanFeedbackNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6498
|
+
/**
|
|
6499
|
+
* Create a handler for a `map` node.
|
|
6500
|
+
*
|
|
6501
|
+
* Reads the source array from state, batches items, processes each
|
|
6502
|
+
* item through the inner agent in parallel (with concurrency control),
|
|
6503
|
+
* and optionally calls a reduce agent to aggregate results.
|
|
6504
|
+
*/
|
|
6505
|
+
declare function createMapNode(node: InternalMapNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6506
|
+
/**
|
|
6507
|
+
* Create a handler for a `terminal` node.
|
|
6508
|
+
*
|
|
6509
|
+
* Sets the status field in state and finalizes the WorkflowRun tracking record.
|
|
6510
|
+
* An implicit edge to END is added during graph compilation.
|
|
6511
|
+
*/
|
|
6512
|
+
declare function createTerminalNode(node: InternalTerminalNode, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>) => Promise<Partial<Record<string, unknown>>>;
|
|
6513
|
+
/**
|
|
6514
|
+
* Dispatch to the correct handler factory based on node type.
|
|
6515
|
+
*/
|
|
6516
|
+
declare function createNodeHandler(node: InternalNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6517
|
+
|
|
6518
|
+
/**
|
|
6519
|
+
* Workflow DSL → LangGraph StateGraph compiler
|
|
6520
|
+
*
|
|
6521
|
+
* Takes a WorkflowDSL (concise), expands it to InternalDSL,
|
|
6522
|
+
* and compiles it into a runnable LangGraph CompiledStateGraph.
|
|
6523
|
+
*/
|
|
6524
|
+
|
|
6525
|
+
/**
|
|
6526
|
+
* Compile a Workflow DSL into a LangGraph StateGraph.
|
|
6527
|
+
*
|
|
6528
|
+
* @param dsl The WorkflowDSL definition
|
|
6529
|
+
* @param resolveAgent Function to resolve agent ref → CompiledStateGraph
|
|
6530
|
+
* @param checkpointer Checkpoint saver for state persistence
|
|
6531
|
+
* @returns Compiled LangGraph StateGraph ready for invocation
|
|
6532
|
+
*/
|
|
6533
|
+
declare function compileWorkflow(dsl: WorkflowDSL, resolveAgent: ResolveAgentFn, checkpointer: BaseCheckpointSaver, trackingStore?: WorkflowTrackingStore): CompiledStateGraph<any, any, any, any, any>;
|
|
6534
|
+
interface WorkflowValidationError {
|
|
6535
|
+
type: "error" | "warning";
|
|
6536
|
+
message: string;
|
|
6537
|
+
}
|
|
6538
|
+
/** Validate an expanded InternalDSL for structural correctness. */
|
|
6539
|
+
declare function validateDSL(dsl: InternalDSL): WorkflowValidationError[];
|
|
6540
|
+
|
|
6541
|
+
/**
|
|
6542
|
+
* expand — WorkflowDSL (concise) → InternalDSL (expanded IR).
|
|
6543
|
+
*/
|
|
6544
|
+
|
|
6545
|
+
declare function expand(dsl: WorkflowDSL): InternalDSL;
|
|
6546
|
+
|
|
6547
|
+
export { AGENT_TASK_EVENT, type AddMessageParams, Agent, type AgentClient, type AgentExecutor, AgentInstanceManager, type AgentLattice, AgentLatticeManager, type AgentLifecycleEventName, AgentManager, type AgentStreamExecutor, type AgentThreadInterface, BUILTIN_SKILLS, type BackendFactory, type BackendProtocol, type BufferStats, type Chunk, ChunkBuffer, ChunkBufferLatticeManager, type ColumnInfo, CompositeBackend, ConsoleLoggerClient, type CreateProcessingAgentParams, type CreateSandboxProviderConfig, type CronFields, CustomMetricsClient, type CustomMiddlewareFactory, CustomMiddlewareRegistry, type DatabaseConfig, type DatabaseType, DaytonaInstance, DaytonaProvider, type DaytonaProviderConfig, DefaultScheduleClient, E2BInstance, E2BProvider, type E2BProviderConfig, EMPTY_CONTENT_WARNING, type EditResult, type EmbeddingsLatticeInterface, EmbeddingsLatticeManager, type EnsureMicrosandboxInput, type FileData, type FileInfo, FileSystemSkillStore, type FileSystemSkillStoreOptions, FilesystemBackend, type FsEntry, type GrepMatch, type IMessageQueueStore, type IMetricsServerClient, type ISqlDatabase, InMemoryA2AApiKeyStore, InMemoryAssistantStore, InMemoryBindingStore, InMemoryChannelInstallationStore, InMemoryChunkBuffer, InMemoryDatabaseConfigStore, InMemoryMailboxStore, InMemoryTaskListStore, InMemoryTenantStore, InMemoryThreadMessageQueueStore, InMemoryThreadStore, InMemoryUserStore, InMemoryUserTenantLinkStore, LINE_NUMBER_WIDTH, type LangGraphStateChecker, type LoggerLattice, LoggerLatticeManager, MAX_LINE_LENGTH, type MailboxMessage, type MailboxStore, type McpLatticeInterface, McpLatticeManager, type McpServerInfo, MemoryBackend, MemoryLatticeManager, MemoryQueueClient, MemoryScheduleStorage, type MessageCompletedEvent, type MessageFailedEvent, type MessageStartedEvent, MessageType, MetricsServerManager, MicrosandboxRemoteInstance, MicrosandboxRemoteProvider, type MicrosandboxRemoteProviderClient, type MicrosandboxRemoteProviderConfig, MicrosandboxServiceClient, type MicrosandboxServiceClientConfig, type MicrosandboxShellExecInput, type ModelConfig, type ModelLatticeInterface, ModelLatticeManager, MysqlDatabase, type PendingMessage, PinoLoggerClient, PostgresDatabase, PrometheusClient, type QueryResult, type QueueLattice, QueueLatticeManager, QueueMode, type QueuePendingEvent, RemoteSandboxInstance, RemoteSandboxProvider, type RemoteSandboxProviderConfig, type ResolveAgentFn, type RunSandboxConfig, type RuntimeModelConfig, type SandboxFileInfo, type SandboxFileService, SandboxFilesystem, type SandboxInstance, type SandboxIsolationLevel, SandboxLatticeManager, type SandboxManagerProtocol, type SandboxProvider, type SandboxShellService, SandboxSkillStore, type SandboxSkillStoreOptions, type SandboxVolumeDefinition, type ScheduleLattice, ScheduleLatticeManager, type SchedulerMiddlewareOptions, SemanticMetricsClient, type SkillLattice, SkillLatticeManager, type SkillMeta, type SkillResource, SqlDatabaseManager, type StateAndStore, StateBackend, StoreBackend, type StoreLattice, StoreLatticeManager, type StoreType, type StoreTypeMap, TOOL_RESULT_TOKEN_LIMIT, TRUNCATION_GUIDANCE, type TableInfo, type TableSchema, type TaskEvent, type TaskListStore, type TaskSpec, TaskStatus, type TaskUpdatable, TeamAgentGraphBuilder, type TeamConfig, type TeamMiddlewareOptions, type TeamTask, type TeammateSpec, type TeammateToolsOptions, type ThreadBuffer, type ThreadBufferConfig, type ThreadBusyEvent, type ThreadIdleEvent, type ThreadInfo, type ThreadQueueConfig, type ThreadState, ThreadStatus, type ThreadStatusChangedEvent, type ToolDefinition, type ToolLattice, ToolLatticeManager, type TopologyEdge, type UnknownToolHandlerConfig, type VectorStoreLatticeInterface, VectorStoreLatticeManager, VolumeFilesystem, type VolumeFsClient, type WorkflowValidationError, type WriteResult, agentInstanceManager, agentLatticeManager, buildGrepResultsDict, buildInput, buildNamedVolumeName, buildSandboxMetadataEnv, buildSkillFile, buildStateAnnotation, checkEmptyContent, clearEncryptionKeyCache, compileWorkflow, computeSandboxName, configureStores, createAgentNode, createAgentTeam, createExecuteSqlQueryTool, createFileData, createHumanFeedbackNode, createInfoSqlTool, createListMetricsDataSourcesTool, createListMetricsServersTool, createListTablesSqlTool, createMapNode, createModelSelectorMiddleware, createNodeHandler, createProcessingAgent, createQueryCheckerSqlTool, createQueryMetricDefinitionTool, createQueryMetricsListTool, createQuerySemanticMetricDataTool, createQuerySqlTool, createQueryTableDefinitionTool, createQueryTablesListTool, createSandboxProvider, createSchedulerMiddleware, createTeamMiddleware, createTeammateTools, createTerminalNode, createUnknownToolHandlerMiddleware, createWidgetMiddleware, decrypt, describeCronExpression, embeddingsLatticeManager, encrypt, ensureBuiltinAgentsForTenant, eventBus, eventBus as eventBusDefault, expand, extractFetcherError, extractOutput, fileDataToString, formatContentWithLineNumbers, formatGrepMatches, formatGrepResults, formatReadResponse, getAgentClient, getAgentConfig, getAllAgentConfigs, getAllBuiltInSkillMetas, getAllToolDefinitions, getBindingRegistry, getBuiltInSkillContent, getBuiltInSkillMeta, getBuiltInSkillNames, getCheckpointSaver, getChunkBuffer, getEmbeddingsClient, getEmbeddingsLattice, getEncryptionKey, getLoggerLattice, getModelLattice, getNextCronTime, getQueueLattice, getSandBoxManager, getScheduleLattice, getStoreLattice, getToolClient, getToolDefinition, getToolLattice, getVectorStoreClient, getVectorStoreLattice, globSearchFiles, grepMatchesFromFiles, grepSearchFiles, hasChunkBuffer, invokeWithRetry, isBuiltInSkill, isUsingDefaultKey, isValidCronExpression, isValidSandboxName, isValidSkillName, loggerLatticeManager, mcpManager, metricsServerManager, modelLatticeManager, normalizeSandboxName, parallelLimit, parseCronExpression, parseSkillFrontmatter, performStringReplacement, queueLatticeManager, registerAgentLattice, registerAgentLatticeWithTenant, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerLoggerLattice, registerModelLattice, registerQueueLattice, registerScheduleLattice, registerStoreLattice, registerTeammateAgent, registerToolLattice, registerVectorStoreLattice, renderTemplate, resolvePath, sandboxLatticeManager, sanitizeToolCallId, scheduleLatticeManager, setBindingRegistry, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, toolLatticeManager, truncateIfTooLong, unregisterTeammateAgent, updateFileData, validateAgentInput, validateDSL, validateEncryptionKey, validatePath, validateSkillName, validateToolInput, vectorStoreLatticeManager };
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { BaseLanguageModelInput, LanguageModelLike, BaseLanguageModel } from '@l
|
|
|
8
8
|
import { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
9
9
|
import { ChatResult } from '@langchain/core/outputs';
|
|
10
10
|
import * as _axiom_lattice_protocols from '@axiom-lattice/protocols';
|
|
11
|
-
import { LLMConfig, SemanticMetricsServerConfig, MetricMeta, MetricQueryResult, DataSource, SemanticMetricsQueryRequest, SemanticMetricsQueryResponse, TableQueryRequest, TableQueryResponse, ExecuteSqlQueryRequest, ExecuteSqlQueryResponse, MetricsServerType, MetricsServerConfig, ToolConfig, ToolExecutor, AgentConfig, MiddlewareType, GraphBuildOptions, MessageChunk, MessageChunkType, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, ThreadStore, AssistantStore, SkillStore, WorkspaceStore, ProjectStore, DatabaseConfigStore, MetricsServerConfigStore, McpServerConfigStore, UserStore, TenantStore, UserTenantLinkStore, WorkflowTrackingStore, EvalStore, ChannelInstallationStore, BindingRegistry, A2AApiKeyStore, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, Skill, CreateSkillRequest, SkillStoreContext, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, User, CreateUserRequest, UpdateUserRequest, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationRequest, UpdateChannelInstallationRequest, Binding, CreateBindingInput, A2AApiKeyRecord, CreateA2AApiKeyInput, A2AApiKeyEntry, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient } from '@axiom-lattice/protocols';
|
|
11
|
+
import { LLMConfig, SemanticMetricsServerConfig, MetricMeta, MetricQueryResult, DataSource, SemanticMetricsQueryRequest, SemanticMetricsQueryResponse, TableQueryRequest, TableQueryResponse, ExecuteSqlQueryRequest, ExecuteSqlQueryResponse, MetricsServerType, MetricsServerConfig, ToolConfig, ToolExecutor, AgentConfig, MiddlewareType, GraphBuildOptions, MessageChunk, MessageChunkType, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, ThreadStore, AssistantStore, SkillStore, WorkspaceStore, ProjectStore, DatabaseConfigStore, MetricsServerConfigStore, McpServerConfigStore, UserStore, TenantStore, UserTenantLinkStore, WorkflowTrackingStore, EvalStore, ChannelInstallationStore, BindingRegistry, A2AApiKeyStore, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, Skill, CreateSkillRequest, SkillStoreContext, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, User, CreateUserRequest, UpdateUserRequest, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationRequest, UpdateChannelInstallationRequest, Binding, CreateBindingInput, A2AApiKeyRecord, CreateA2AApiKeyInput, A2AApiKeyEntry, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient, InternalStateField, InternalInput, InternalNode, InternalAgentNode, InternalHumanFeedbackNode, InternalMapNode, InternalTerminalNode, WorkflowDSL, InternalDSL } from '@axiom-lattice/protocols';
|
|
12
12
|
export { _axiom_lattice_protocols as Protocols };
|
|
13
13
|
export { AgentConfig, AgentType, GraphBuildOptions, MemoryType } from '@axiom-lattice/protocols';
|
|
14
14
|
import * as langchain from 'langchain';
|
|
@@ -26,7 +26,7 @@ import { Connection, MultiServerMCPClient } from '@langchain/mcp-adapters';
|
|
|
26
26
|
import { SandboxClient } from '@agent-infra/sandbox';
|
|
27
27
|
import { Sandbox } from 'e2b';
|
|
28
28
|
import { Sandbox as Sandbox$1 } from '@daytonaio/sdk';
|
|
29
|
-
import { Runnable } from '@langchain/core/runnables';
|
|
29
|
+
import { Runnable, RunnableConfig } from '@langchain/core/runnables';
|
|
30
30
|
import { InteropZodObject } from '@langchain/core/utils/types';
|
|
31
31
|
|
|
32
32
|
/**
|
|
@@ -1711,6 +1711,7 @@ interface AgentBuildParams {
|
|
|
1711
1711
|
}>;
|
|
1712
1712
|
prompt: string;
|
|
1713
1713
|
stateSchema?: z$1.ZodObject<any, any, any, any, any>;
|
|
1714
|
+
responseFormat?: any;
|
|
1714
1715
|
tenantId?: string;
|
|
1715
1716
|
}
|
|
1716
1717
|
|
|
@@ -6425,4 +6426,122 @@ interface UnknownToolHandlerConfig {
|
|
|
6425
6426
|
*/
|
|
6426
6427
|
declare function createUnknownToolHandlerMiddleware(config?: UnknownToolHandlerConfig): AgentMiddleware;
|
|
6427
6428
|
|
|
6428
|
-
|
|
6429
|
+
type ResolveAgentFn = (ref?: string, responseFormat?: Record<string, unknown>, stepType?: string) => Promise<AgentClient>;
|
|
6430
|
+
/**
|
|
6431
|
+
* Build a LangGraph Annotation.Root from DSL state.fields.
|
|
6432
|
+
* Always adds an implicit `phase` field for progress tracking.
|
|
6433
|
+
*/
|
|
6434
|
+
declare function buildStateAnnotation(fields?: Record<string, InternalStateField>): AnnotationRoot<any>;
|
|
6435
|
+
/**
|
|
6436
|
+
* Resolve a dot/bracket path against a state object.
|
|
6437
|
+
* Strips leading "state." prefix automatically.
|
|
6438
|
+
*
|
|
6439
|
+
* @example
|
|
6440
|
+
* resolvePath({ a: { b: [{ c: 1 }] } }, "state.a.b[0].c") // → 1
|
|
6441
|
+
*/
|
|
6442
|
+
declare function resolvePath(obj: Record<string, unknown>, path: string): unknown;
|
|
6443
|
+
/**
|
|
6444
|
+
* Render a template string replacing `${state.path}`, `${item.path}`, and
|
|
6445
|
+
* custom item-key shortcuts like `${<key>.path}` (when `<key>` matches a
|
|
6446
|
+
* top-level property of the item context).
|
|
6447
|
+
*
|
|
6448
|
+
* @param template Template string with ${...} placeholders
|
|
6449
|
+
* @param state Current workflow state
|
|
6450
|
+
* @param item Optional item context (for map nodes). Keys in this object
|
|
6451
|
+
* become valid template prefixes (e.g. itemKey="row" → ${row.name}).
|
|
6452
|
+
*/
|
|
6453
|
+
declare function renderTemplate(template: string, state: Record<string, unknown>, item?: Record<string, unknown>): string;
|
|
6454
|
+
/**
|
|
6455
|
+
* Build input for LangGraph agent invocation from DSL input specification.
|
|
6456
|
+
* Returns a partial state with messages, suitable for graph.invoke().
|
|
6457
|
+
*
|
|
6458
|
+
* When outputSchema is provided, it is converted into a readable JSON example
|
|
6459
|
+
* and appended to the prompt so the LLM knows exactly what shape to output.
|
|
6460
|
+
*/
|
|
6461
|
+
declare function buildInput(input: InternalInput | undefined, state: Record<string, unknown>, item?: Record<string, unknown>, outputSchema?: Record<string, unknown>): {
|
|
6462
|
+
messages: BaseMessage[];
|
|
6463
|
+
};
|
|
6464
|
+
/**
|
|
6465
|
+
* Extract structured output from a sub-agent invocation result.
|
|
6466
|
+
*
|
|
6467
|
+
* Priority order:
|
|
6468
|
+
* 1. result.structuredResponse — langchain's tool strategy stores parsed output here
|
|
6469
|
+
* 2. result.messages — scan backwards for last AIMessage content (native JSON schema /
|
|
6470
|
+
* legacy text-based structured output)
|
|
6471
|
+
* 3. result itself (minus messages)
|
|
6472
|
+
*/
|
|
6473
|
+
declare function extractOutput(result: Record<string, unknown>): unknown;
|
|
6474
|
+
/**
|
|
6475
|
+
* Process items in parallel with a concurrency limit (simple semaphore).
|
|
6476
|
+
*/
|
|
6477
|
+
declare function parallelLimit<T, R>(items: T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
|
|
6478
|
+
/**
|
|
6479
|
+
* Invoke a function with retry logic and optional timeout.
|
|
6480
|
+
*/
|
|
6481
|
+
declare function invokeWithRetry<T>(fn: () => Promise<T>, maxRetries: number, retryOn?: string[], timeoutMs?: number): Promise<T>;
|
|
6482
|
+
/**
|
|
6483
|
+
* Create a handler for an `agent` node.
|
|
6484
|
+
*
|
|
6485
|
+
* Resolves the agent by ref, builds input, invokes with retry,
|
|
6486
|
+
* extracts output, and returns a state update.
|
|
6487
|
+
*/
|
|
6488
|
+
declare function createAgentNode(node: InternalAgentNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6489
|
+
/**
|
|
6490
|
+
* Create a handler for a `human_feedback` node.
|
|
6491
|
+
*
|
|
6492
|
+
* Invokes an agent with the rendered prompt. The agent can use the
|
|
6493
|
+
* `ask_user_to_clarify` tool to ask the user structured questions;
|
|
6494
|
+
* the clarify middleware handles the interrupt/resume cycle automatically.
|
|
6495
|
+
* Agent output is extracted and written to state.
|
|
6496
|
+
*/
|
|
6497
|
+
declare function createHumanFeedbackNode(node: InternalHumanFeedbackNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6498
|
+
/**
|
|
6499
|
+
* Create a handler for a `map` node.
|
|
6500
|
+
*
|
|
6501
|
+
* Reads the source array from state, batches items, processes each
|
|
6502
|
+
* item through the inner agent in parallel (with concurrency control),
|
|
6503
|
+
* and optionally calls a reduce agent to aggregate results.
|
|
6504
|
+
*/
|
|
6505
|
+
declare function createMapNode(node: InternalMapNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6506
|
+
/**
|
|
6507
|
+
* Create a handler for a `terminal` node.
|
|
6508
|
+
*
|
|
6509
|
+
* Sets the status field in state and finalizes the WorkflowRun tracking record.
|
|
6510
|
+
* An implicit edge to END is added during graph compilation.
|
|
6511
|
+
*/
|
|
6512
|
+
declare function createTerminalNode(node: InternalTerminalNode, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>) => Promise<Partial<Record<string, unknown>>>;
|
|
6513
|
+
/**
|
|
6514
|
+
* Dispatch to the correct handler factory based on node type.
|
|
6515
|
+
*/
|
|
6516
|
+
declare function createNodeHandler(node: InternalNode, resolveAgent: ResolveAgentFn, trackingStore?: WorkflowTrackingStore): (state: Record<string, unknown>, config?: RunnableConfig) => Promise<Partial<Record<string, unknown>>>;
|
|
6517
|
+
|
|
6518
|
+
/**
|
|
6519
|
+
* Workflow DSL → LangGraph StateGraph compiler
|
|
6520
|
+
*
|
|
6521
|
+
* Takes a WorkflowDSL (concise), expands it to InternalDSL,
|
|
6522
|
+
* and compiles it into a runnable LangGraph CompiledStateGraph.
|
|
6523
|
+
*/
|
|
6524
|
+
|
|
6525
|
+
/**
|
|
6526
|
+
* Compile a Workflow DSL into a LangGraph StateGraph.
|
|
6527
|
+
*
|
|
6528
|
+
* @param dsl The WorkflowDSL definition
|
|
6529
|
+
* @param resolveAgent Function to resolve agent ref → CompiledStateGraph
|
|
6530
|
+
* @param checkpointer Checkpoint saver for state persistence
|
|
6531
|
+
* @returns Compiled LangGraph StateGraph ready for invocation
|
|
6532
|
+
*/
|
|
6533
|
+
declare function compileWorkflow(dsl: WorkflowDSL, resolveAgent: ResolveAgentFn, checkpointer: BaseCheckpointSaver, trackingStore?: WorkflowTrackingStore): CompiledStateGraph<any, any, any, any, any>;
|
|
6534
|
+
interface WorkflowValidationError {
|
|
6535
|
+
type: "error" | "warning";
|
|
6536
|
+
message: string;
|
|
6537
|
+
}
|
|
6538
|
+
/** Validate an expanded InternalDSL for structural correctness. */
|
|
6539
|
+
declare function validateDSL(dsl: InternalDSL): WorkflowValidationError[];
|
|
6540
|
+
|
|
6541
|
+
/**
|
|
6542
|
+
* expand — WorkflowDSL (concise) → InternalDSL (expanded IR).
|
|
6543
|
+
*/
|
|
6544
|
+
|
|
6545
|
+
declare function expand(dsl: WorkflowDSL): InternalDSL;
|
|
6546
|
+
|
|
6547
|
+
export { AGENT_TASK_EVENT, type AddMessageParams, Agent, type AgentClient, type AgentExecutor, AgentInstanceManager, type AgentLattice, AgentLatticeManager, type AgentLifecycleEventName, AgentManager, type AgentStreamExecutor, type AgentThreadInterface, BUILTIN_SKILLS, type BackendFactory, type BackendProtocol, type BufferStats, type Chunk, ChunkBuffer, ChunkBufferLatticeManager, type ColumnInfo, CompositeBackend, ConsoleLoggerClient, type CreateProcessingAgentParams, type CreateSandboxProviderConfig, type CronFields, CustomMetricsClient, type CustomMiddlewareFactory, CustomMiddlewareRegistry, type DatabaseConfig, type DatabaseType, DaytonaInstance, DaytonaProvider, type DaytonaProviderConfig, DefaultScheduleClient, E2BInstance, E2BProvider, type E2BProviderConfig, EMPTY_CONTENT_WARNING, type EditResult, type EmbeddingsLatticeInterface, EmbeddingsLatticeManager, type EnsureMicrosandboxInput, type FileData, type FileInfo, FileSystemSkillStore, type FileSystemSkillStoreOptions, FilesystemBackend, type FsEntry, type GrepMatch, type IMessageQueueStore, type IMetricsServerClient, type ISqlDatabase, InMemoryA2AApiKeyStore, InMemoryAssistantStore, InMemoryBindingStore, InMemoryChannelInstallationStore, InMemoryChunkBuffer, InMemoryDatabaseConfigStore, InMemoryMailboxStore, InMemoryTaskListStore, InMemoryTenantStore, InMemoryThreadMessageQueueStore, InMemoryThreadStore, InMemoryUserStore, InMemoryUserTenantLinkStore, LINE_NUMBER_WIDTH, type LangGraphStateChecker, type LoggerLattice, LoggerLatticeManager, MAX_LINE_LENGTH, type MailboxMessage, type MailboxStore, type McpLatticeInterface, McpLatticeManager, type McpServerInfo, MemoryBackend, MemoryLatticeManager, MemoryQueueClient, MemoryScheduleStorage, type MessageCompletedEvent, type MessageFailedEvent, type MessageStartedEvent, MessageType, MetricsServerManager, MicrosandboxRemoteInstance, MicrosandboxRemoteProvider, type MicrosandboxRemoteProviderClient, type MicrosandboxRemoteProviderConfig, MicrosandboxServiceClient, type MicrosandboxServiceClientConfig, type MicrosandboxShellExecInput, type ModelConfig, type ModelLatticeInterface, ModelLatticeManager, MysqlDatabase, type PendingMessage, PinoLoggerClient, PostgresDatabase, PrometheusClient, type QueryResult, type QueueLattice, QueueLatticeManager, QueueMode, type QueuePendingEvent, RemoteSandboxInstance, RemoteSandboxProvider, type RemoteSandboxProviderConfig, type ResolveAgentFn, type RunSandboxConfig, type RuntimeModelConfig, type SandboxFileInfo, type SandboxFileService, SandboxFilesystem, type SandboxInstance, type SandboxIsolationLevel, SandboxLatticeManager, type SandboxManagerProtocol, type SandboxProvider, type SandboxShellService, SandboxSkillStore, type SandboxSkillStoreOptions, type SandboxVolumeDefinition, type ScheduleLattice, ScheduleLatticeManager, type SchedulerMiddlewareOptions, SemanticMetricsClient, type SkillLattice, SkillLatticeManager, type SkillMeta, type SkillResource, SqlDatabaseManager, type StateAndStore, StateBackend, StoreBackend, type StoreLattice, StoreLatticeManager, type StoreType, type StoreTypeMap, TOOL_RESULT_TOKEN_LIMIT, TRUNCATION_GUIDANCE, type TableInfo, type TableSchema, type TaskEvent, type TaskListStore, type TaskSpec, TaskStatus, type TaskUpdatable, TeamAgentGraphBuilder, type TeamConfig, type TeamMiddlewareOptions, type TeamTask, type TeammateSpec, type TeammateToolsOptions, type ThreadBuffer, type ThreadBufferConfig, type ThreadBusyEvent, type ThreadIdleEvent, type ThreadInfo, type ThreadQueueConfig, type ThreadState, ThreadStatus, type ThreadStatusChangedEvent, type ToolDefinition, type ToolLattice, ToolLatticeManager, type TopologyEdge, type UnknownToolHandlerConfig, type VectorStoreLatticeInterface, VectorStoreLatticeManager, VolumeFilesystem, type VolumeFsClient, type WorkflowValidationError, type WriteResult, agentInstanceManager, agentLatticeManager, buildGrepResultsDict, buildInput, buildNamedVolumeName, buildSandboxMetadataEnv, buildSkillFile, buildStateAnnotation, checkEmptyContent, clearEncryptionKeyCache, compileWorkflow, computeSandboxName, configureStores, createAgentNode, createAgentTeam, createExecuteSqlQueryTool, createFileData, createHumanFeedbackNode, createInfoSqlTool, createListMetricsDataSourcesTool, createListMetricsServersTool, createListTablesSqlTool, createMapNode, createModelSelectorMiddleware, createNodeHandler, createProcessingAgent, createQueryCheckerSqlTool, createQueryMetricDefinitionTool, createQueryMetricsListTool, createQuerySemanticMetricDataTool, createQuerySqlTool, createQueryTableDefinitionTool, createQueryTablesListTool, createSandboxProvider, createSchedulerMiddleware, createTeamMiddleware, createTeammateTools, createTerminalNode, createUnknownToolHandlerMiddleware, createWidgetMiddleware, decrypt, describeCronExpression, embeddingsLatticeManager, encrypt, ensureBuiltinAgentsForTenant, eventBus, eventBus as eventBusDefault, expand, extractFetcherError, extractOutput, fileDataToString, formatContentWithLineNumbers, formatGrepMatches, formatGrepResults, formatReadResponse, getAgentClient, getAgentConfig, getAllAgentConfigs, getAllBuiltInSkillMetas, getAllToolDefinitions, getBindingRegistry, getBuiltInSkillContent, getBuiltInSkillMeta, getBuiltInSkillNames, getCheckpointSaver, getChunkBuffer, getEmbeddingsClient, getEmbeddingsLattice, getEncryptionKey, getLoggerLattice, getModelLattice, getNextCronTime, getQueueLattice, getSandBoxManager, getScheduleLattice, getStoreLattice, getToolClient, getToolDefinition, getToolLattice, getVectorStoreClient, getVectorStoreLattice, globSearchFiles, grepMatchesFromFiles, grepSearchFiles, hasChunkBuffer, invokeWithRetry, isBuiltInSkill, isUsingDefaultKey, isValidCronExpression, isValidSandboxName, isValidSkillName, loggerLatticeManager, mcpManager, metricsServerManager, modelLatticeManager, normalizeSandboxName, parallelLimit, parseCronExpression, parseSkillFrontmatter, performStringReplacement, queueLatticeManager, registerAgentLattice, registerAgentLatticeWithTenant, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerLoggerLattice, registerModelLattice, registerQueueLattice, registerScheduleLattice, registerStoreLattice, registerTeammateAgent, registerToolLattice, registerVectorStoreLattice, renderTemplate, resolvePath, sandboxLatticeManager, sanitizeToolCallId, scheduleLatticeManager, setBindingRegistry, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, toolLatticeManager, truncateIfTooLong, unregisterTeammateAgent, updateFileData, validateAgentInput, validateDSL, validateEncryptionKey, validatePath, validateSkillName, validateToolInput, vectorStoreLatticeManager };
|