@directive-run/ai 1.13.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anthropic.d.cts +1 -1
- package/dist/anthropic.d.ts +1 -1
- package/dist/chunk-56LYSE63.js +6 -0
- package/dist/chunk-56LYSE63.js.map +1 -0
- package/dist/chunk-5JQ2A3JK.js +2 -0
- package/dist/chunk-5JQ2A3JK.js.map +1 -0
- package/dist/chunk-7DPTXZZI.cjs +67 -0
- package/dist/chunk-7DPTXZZI.cjs.map +1 -0
- package/dist/chunk-BFSRYCOS.js +4 -0
- package/dist/chunk-BFSRYCOS.js.map +1 -0
- package/dist/chunk-C6MQ4WL6.cjs +11 -0
- package/dist/chunk-C6MQ4WL6.cjs.map +1 -0
- package/dist/chunk-CAA6Q4YY.cjs +4 -0
- package/dist/chunk-CAA6Q4YY.cjs.map +1 -0
- package/dist/chunk-D5APTMCT.cjs +16 -0
- package/dist/chunk-D5APTMCT.cjs.map +1 -0
- package/dist/chunk-FBT73WFY.js +2 -0
- package/dist/chunk-FBT73WFY.js.map +1 -0
- package/dist/chunk-FN4GUZAI.js +67 -0
- package/dist/chunk-FN4GUZAI.js.map +1 -0
- package/dist/chunk-GTB6HTZV.js +30 -0
- package/dist/chunk-GTB6HTZV.js.map +1 -0
- package/dist/chunk-HRR45JZX.js +7 -0
- package/dist/chunk-HRR45JZX.js.map +1 -0
- package/dist/chunk-IR3IHBVQ.cjs +2 -0
- package/dist/chunk-IR3IHBVQ.cjs.map +1 -0
- package/dist/chunk-J2Q5KKPN.js +37 -0
- package/dist/chunk-J2Q5KKPN.js.map +1 -0
- package/dist/chunk-K64WKZ22.cjs +2 -0
- package/dist/chunk-K64WKZ22.cjs.map +1 -0
- package/dist/chunk-MDXDPECP.cjs +30 -0
- package/dist/chunk-MDXDPECP.cjs.map +1 -0
- package/dist/chunk-PB276BX2.cjs +6 -0
- package/dist/chunk-PB276BX2.cjs.map +1 -0
- package/dist/chunk-UR5BMWEN.js +2 -0
- package/dist/chunk-UR5BMWEN.js.map +1 -0
- package/dist/chunk-V2FCPNPP.js +11 -0
- package/dist/chunk-V2FCPNPP.js.map +1 -0
- package/dist/chunk-WCQK3JOR.cjs +7 -0
- package/dist/chunk-WCQK3JOR.cjs.map +1 -0
- package/dist/chunk-WOFIBIPW.cjs +2 -0
- package/dist/chunk-WOFIBIPW.cjs.map +1 -0
- package/dist/chunk-XN5LUOVS.cjs +37 -0
- package/dist/chunk-XN5LUOVS.cjs.map +1 -0
- package/dist/chunk-YT4QN3KO.js +16 -0
- package/dist/chunk-YT4QN3KO.js.map +1 -0
- package/dist/debug-timeline-DpnRMnLU.d.cts +87 -0
- package/dist/debug-timeline-L13P-U2I.d.ts +87 -0
- package/dist/devtools.cjs +2 -0
- package/dist/devtools.cjs.map +1 -0
- package/dist/devtools.d.cts +354 -0
- package/dist/devtools.d.ts +354 -0
- package/dist/devtools.js +2 -0
- package/dist/devtools.js.map +1 -0
- package/dist/evals.cjs +2 -0
- package/dist/evals.cjs.map +1 -0
- package/dist/evals.d.cts +361 -0
- package/dist/evals.d.ts +361 -0
- package/dist/evals.js +2 -0
- package/dist/evals.js.map +1 -0
- package/dist/gemini.cjs +1 -1
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.d.cts +1 -1
- package/dist/gemini.d.ts +1 -1
- package/dist/gemini.js +1 -1
- package/dist/gemini.js.map +1 -1
- package/dist/guardrails.cjs +2 -0
- package/dist/guardrails.cjs.map +1 -0
- package/dist/guardrails.d.cts +618 -0
- package/dist/guardrails.d.ts +618 -0
- package/dist/guardrails.js +2 -0
- package/dist/guardrails.js.map +1 -0
- package/dist/health-monitor-C6xoXrQz.d.cts +55 -0
- package/dist/health-monitor-qL9RNMH3.d.ts +55 -0
- package/dist/index.cjs +21 -99
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1197 -4735
- package/dist/index.d.ts +1197 -4735
- package/dist/index.js +21 -99
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +2 -0
- package/dist/mcp.cjs.map +1 -0
- package/dist/mcp.d.cts +450 -0
- package/dist/mcp.d.ts +450 -0
- package/dist/mcp.js +2 -0
- package/dist/mcp.js.map +1 -0
- package/dist/multi-agent-orchestrator-KFYIDKTF.cjs +2 -0
- package/dist/{multi-agent-orchestrator-KFGTEGE5.cjs.map → multi-agent-orchestrator-KFYIDKTF.cjs.map} +1 -1
- package/dist/multi-agent-orchestrator-ZHSMWIKP.js +2 -0
- package/dist/{multi-agent-orchestrator-4PXNYRHB.js.map → multi-agent-orchestrator-ZHSMWIKP.js.map} +1 -1
- package/dist/multi-agent.cjs +2 -0
- package/dist/multi-agent.cjs.map +1 -0
- package/dist/multi-agent.d.cts +1429 -0
- package/dist/multi-agent.d.ts +1429 -0
- package/dist/multi-agent.js +2 -0
- package/dist/multi-agent.js.map +1 -0
- package/dist/ollama.d.cts +1 -1
- package/dist/ollama.d.ts +1 -1
- package/dist/openai.cjs +1 -1
- package/dist/openai.cjs.map +1 -1
- package/dist/openai.d.cts +2 -2
- package/dist/openai.d.ts +2 -2
- package/dist/openai.js +1 -1
- package/dist/openai.js.map +1 -1
- package/dist/{orchestrator-types-CTfIKk0W.d.ts → orchestrator-types-CbNE7Rjp.d.cts} +6 -139
- package/dist/{orchestrator-types-Bh8r3_Sq.d.cts → orchestrator-types-ZK9lv5Sm.d.ts} +6 -139
- package/dist/predicate.cjs +2 -0
- package/dist/predicate.cjs.map +1 -0
- package/dist/predicate.d.cts +371 -0
- package/dist/predicate.d.ts +371 -0
- package/dist/predicate.js +2 -0
- package/dist/predicate.js.map +1 -0
- package/dist/{semantic-cache-nBpQqILc.d.cts → semantic-cache-DM7ev7NQ.d.cts} +1 -1
- package/dist/{semantic-cache-nBpQqILc.d.ts → semantic-cache-DM7ev7NQ.d.ts} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +4 -2
- package/dist/testing.d.ts +4 -2
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/{types-CRmwFnVk.d.cts → types-DJ09LjZX.d.cts} +1 -1
- package/dist/{types-CRmwFnVk.d.ts → types-DJ09LjZX.d.ts} +1 -1
- package/package.json +32 -2
- package/dist/chunk-Q3PQLWBR.js +0 -16
- package/dist/chunk-Q3PQLWBR.js.map +0 -1
- package/dist/chunk-RW4R3O5P.js +0 -72
- package/dist/chunk-RW4R3O5P.js.map +0 -1
- package/dist/chunk-X3VQ5F7D.cjs +0 -72
- package/dist/chunk-X3VQ5F7D.cjs.map +0 -1
- package/dist/chunk-XV2QSBBE.cjs +0 -16
- package/dist/chunk-XV2QSBBE.cjs.map +0 -1
- package/dist/multi-agent-orchestrator-4PXNYRHB.js +0 -2
- package/dist/multi-agent-orchestrator-KFGTEGE5.cjs +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pattern-mermaid.ts","../src/communication.ts","../src/goal-utils.ts"],"names":["sanitizeId","name","sanitizeLabel","ch","SHAPE_WRAPPERS","wrapNode","id","label","type","shapes","shape","open","close","deduplicateAgents","agents","counts","a","indices","result","sanitized","idx","topoSort","nodes","inDegree","adjacency","key","node","dep","queue","deg","ordered","current","neighbors","neighbor","newDeg","insertIdx","q","isSerializedPattern","p","obj","n","buildPreamble","direction","theme","lines","ALLOWED_TYPES","renderParallel","taskIds","handlers","inputNode","mergeNode","handler","nodeType","handlerNode","renderSequential","renderSupervisor","supId","supNode","worker","wId","wNode","renderDag","sorted","rendered","nodeId","nodeLabel","deps","depId","depNode","depLabel","depType","from","to","renderRace","outputNode","renderReflect","producerId","evalId","producerType","producerNode","evalNode","renderGoal","nodeEntries","producerMap","edgeSet","sortedEntries","b","requires","producer","fromNode","edgeKey","fromId","fromType","toType","renderDebate","judgeId","judgeNode","patternToMermaid","pattern","options","serialized","patternToJSON","preamble","body","generateId","createMessageBus","config","maxHistory","defaultTtlMs","maxPendingPerAgent","persistence","onDelivery","onDeliveryError","subscriptions","messageHistory","messageIndex","pendingMessages","matchesFilter","message","filter","topic","isExpired","getRecipients","deliverMessage","recipients","deliveredTo","deliveryPromises","recipientId","recipientSubs","pending","sub","error","partial","removed","err","agentId","subId","subscription","subs","index","s","existing","msg","limit","messages","m","createAgentNetwork","bus","initialAgents","defaultTimeout","onAgentOnline","onAgentOffline","responseWaiters","info","handleResponse","correlationId","waiter","wasOffline","agent","capability","sender","action","payload","timeout","resolve","reject","timer","task","context","question","createResponder","network","request","response","createDelegator","delegationHandler","delegation","start","createPubSub","topicHandlers","update","topics","wrappedHandlers","wrappedHandler","content","safeSatisfaction","val","buildGraph","agentIds","decl","edges","order","queueIdx","orderSet","inCycle","roots","consumedBy","edge","leaves","getDependencyGraph","graph","validateGoal","errors","warnings","allProduced","planGoal","initialFactKeys","maxSteps","externalDeps","availableFacts","completedAgents","steps","stepNum","readyAgents","producedFacts","unreachableAgents","explainGoal","metric","sat","satDelta","agentList","factList","prevSatisfaction","delta","description","relaxations","r","firstSatisfaction","lastSatisfaction","status","relaxationNote","errorNote","summary"],"mappings":"mEAsCA,SAASA,CAAAA,CAAWC,CAAAA,CAAsB,CACxC,OAAOA,CAAAA,CAAK,OAAA,CAAQ,eAAA,CAAiB,GAAG,CAC1C,CAGA,SAASC,CAAAA,CAAcD,CAAAA,CAAsB,CAC3C,OAAOA,CAAAA,CACJ,OAAA,CAAQ,UAAA,CAAY,GAAG,CAAA,CACvB,OAAA,CAAQ,gBAAA,CAAmBE,CAAAA,EAAO,CAAA,CAAA,EAAIA,CAAAA,CAAG,UAAA,CAAW,CAAC,CAAC,CAAA,CAAA,CAAG,CAC9D,CAEA,IAAMC,CAAAA,CAAmD,CACvD,MAAA,CAAQ,CAAC,GAAA,CAAK,GAAG,CAAA,CACjB,KAAA,CAAO,CAAC,GAAA,CAAK,GAAG,CAAA,CAChB,OAAA,CAAS,CAAC,IAAA,CAAM,IAAI,CAAA,CACpB,OAAA,CAAS,CAAC,IAAA,CAAM,IA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S,CAAA,CACxBuK,CAAAA,CACEvK,CAAAA,CAAO,WAAA,CAAYA,EAAO,WAAA,CAAY,MAAA,CAAS,CAAC,CAAA,CAAG,YACrD,CAAA,CAAE,OAAA,CAAQ,CAAC,CAAA,CACX,GAAA,CAEAmN,EAASnN,CAAAA,CAAO,QAAA,CAAW,eAAA,CAAkB,mBAAA,CAC7CoN,EACJpN,CAAAA,CAAO,WAAA,CAAY,MAAA,CAAS,CAAA,CACxB,IAAIA,CAAAA,CAAO,WAAA,CAAY,MAAM,CAAA,uBAAA,CAAA,CAC7B,GACAqN,CAAAA,CAAYrN,CAAAA,CAAO,MAAQ,CAAA,QAAA,EAAWA,CAAAA,CAAO,KAAK,CAAA,CAAA,CAAK,EAAA,CAEvDsN,CAAAA,CAAU,CAAA,EAAGH,CAAM,CAAA,IAAA,EAAOnN,CAAAA,CAAO,KAAK,CAAA,UAAA,EAAaA,EAAO,WAAA,CAAY,cAAA,EAAgB,CAAA,SAAA,EAAYA,EAAO,UAAU,CAAA,mBAAA,EAAsBiN,CAAiB,CAAA,QAAA,EAAMC,CAAgB,IAAIE,CAAc,CAAA,EAAGC,CAAS,CAAA,CAAA,CAEpN,OAAO,CACL,QAAA,CAAUrN,CAAAA,CAAO,QAAA,CACjB,QAAAsN,CAAAA,CACA,KAAA,CAAArB,CAAAA,CACA,WAAA,CAAAc,EACA,WAAA,CAAa/M,CAAAA,CAAO,YACpB,UAAA,CAAYA,CAAAA,CAAO,UACrB,CACF","file":"chunk-PB276BX2.cjs","sourcesContent":["import { patternToJSON } from \"./multi-agent-orchestrator.js\";\nimport type {\n ExecutionPattern,\n SerializedDagNode,\n SerializedPattern,\n} from \"./multi-agent-orchestrator.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type MermaidDirection = \"LR\" | \"TD\" | \"TB\" | \"RL\" | \"BT\";\n\nexport interface MermaidNodeShapes {\n /** Shape for agent nodes. @default \"square\" */\n agent?: \"square\" | \"round\" | \"stadium\" | \"hexagon\";\n /** Shape for task nodes. @default \"hexagon\" */\n task?: \"square\" | \"round\" | \"stadium\" | \"hexagon\";\n /** Shape for virtual nodes (Input, Output, Merge). @default \"circle\" */\n virtual?: \"circle\" | \"square\" | \"round\" | \"stadium\";\n}\n\nexport interface MermaidOptions {\n /** Graph flow direction. @default \"LR\" */\n direction?: MermaidDirection;\n /** Emits %%{init}%% preamble when set. */\n theme?: \"default\" | \"dark\" | \"forest\" | \"neutral\";\n /** Node shape overrides. */\n shapes?: MermaidNodeShapes;\n /** Set of task IDs — used to render task nodes with distinct shapes. */\n taskIds?: ReadonlySet<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Replace non-alphanumeric chars with `_` for Mermaid-safe node IDs. */\nfunction sanitizeId(name: string): string {\n return name.replace(/[^a-zA-Z0-9]/g, \"_\");\n}\n\n/** Escape characters that have special meaning in Mermaid labels. */\nfunction sanitizeLabel(name: string): string {\n return name\n .replace(/[\\r\\n]+/g, \" \")\n .replace(/[[\\](){}|<>\"]/g, (ch) => `#${ch.charCodeAt(0)};`);\n}\n\nconst SHAPE_WRAPPERS: Record<string, [string, string]> = {\n square: [\"[\", \"]\"],\n round: [\"(\", \")\"],\n stadium: [\"([\", \"])\"],\n hexagon: [\"{{\", \"}}\"],\n circle: [\"((\", \"))\"],\n};\n\n/** Produce `id[label]` or `id((label))` etc. based on shape config. */\nfunction wrapNode(\n id: string,\n label: string,\n type: \"agent\" | \"virtual\" | \"task\",\n shapes?: MermaidNodeShapes,\n): string {\n let shape: string;\n if (type === \"task\") {\n shape = shapes?.task ?? \"hexagon\";\n } else if (type === \"agent\") {\n shape = shapes?.agent ?? \"square\";\n } else {\n shape = shapes?.virtual ?? \"circle\";\n }\n const [open, close] = SHAPE_WRAPPERS[shape]!;\n\n return `${id}${open}${sanitizeLabel(label)}${close}`;\n}\n\n/**\n * When the same agent appears multiple times (parallel/race), append `_1`, `_2`\n * suffixes to IDs and adjust labels to `agent #1`, etc.\n */\nfunction deduplicateAgents(\n agents: string[],\n): Array<{ id: string; label: string }> {\n const counts = new Map<string, number>();\n for (const a of agents) {\n counts.set(a, (counts.get(a) ?? 0) + 1);\n }\n\n const indices = new Map<string, number>();\n const result: Array<{ id: string; label: string }> = [];\n\n for (const a of agents) {\n const sanitized = sanitizeId(a);\n if (counts.get(a)! > 1) {\n const idx = (indices.get(a) ?? 0) + 1;\n indices.set(a, idx);\n result.push({ id: `${sanitized}_${idx}`, label: `${a} #${idx}` });\n } else {\n result.push({ id: sanitized, label: a });\n }\n }\n\n return result;\n}\n\n/**\n * Kahn's algorithm with alphabetical tie-breaking for deterministic DAG ordering.\n * Returns node keys in topological order.\n */\nfunction topoSort(nodes: Record<string, SerializedDagNode>): string[] {\n const inDegree = new Map<string, number>();\n const adjacency = new Map<string, string[]>();\n\n for (const key of Object.keys(nodes)) {\n if (!inDegree.has(key)) {\n inDegree.set(key, 0);\n }\n if (!adjacency.has(key)) {\n adjacency.set(key, []);\n }\n }\n\n for (const [key, node] of Object.entries(nodes)) {\n for (const dep of node.deps ?? []) {\n adjacency.get(dep)!.push(key);\n inDegree.set(key, (inDegree.get(key) ?? 0) + 1);\n }\n }\n\n // Seed queue with zero-indegree nodes, sorted alphabetically\n const queue: string[] = [];\n for (const [key, deg] of inDegree) {\n if (deg === 0) {\n queue.push(key);\n }\n }\n queue.sort();\n\n const ordered: string[] = [];\n while (queue.length > 0) {\n const current = queue.shift()!;\n ordered.push(current);\n\n const neighbors = adjacency.get(current) ?? [];\n // Sort to maintain determinism\n neighbors.sort();\n\n for (const neighbor of neighbors) {\n const newDeg = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) {\n // Insert in sorted position\n const insertIdx = queue.findIndex((q) => q > neighbor);\n if (insertIdx === -1) {\n queue.push(neighbor);\n } else {\n queue.splice(insertIdx, 0, neighbor);\n }\n }\n }\n }\n\n return ordered;\n}\n\n/** Check if input is already serialized (no function fields). */\nfunction isSerializedPattern(\n p: ExecutionPattern<unknown> | SerializedPattern,\n): p is SerializedPattern {\n // SerializedPattern never has function-valued fields.\n // Check a few known function fields to distinguish.\n const obj = p as Record<string, unknown>;\n if (obj.type === \"parallel\" && typeof obj.merge === \"function\") {\n return false;\n }\n if (obj.type === \"sequential\" && typeof obj.transform === \"function\") {\n return false;\n }\n if (obj.type === \"supervisor\" && typeof obj.extract === \"function\") {\n return false;\n }\n if (obj.type === \"dag\" && typeof obj.merge === \"function\") {\n return false;\n }\n if (obj.type === \"reflect\" && typeof obj.parseEvaluation === \"function\") {\n return false;\n }\n if (obj.type === \"race\" && typeof obj.extract === \"function\") {\n return false;\n }\n if (obj.type === \"debate\" && typeof obj.extract === \"function\") {\n return false;\n }\n if (\n obj.type === \"goal\" &&\n (typeof obj.when === \"function\" ||\n typeof obj.satisfaction === \"function\" ||\n typeof obj.extract === \"function\")\n ) {\n return false;\n }\n\n // Also check: if a dag node has `when` or `transform` functions, not serialized\n if (obj.type === \"dag\" && obj.nodes) {\n for (const node of Object.values(obj.nodes as Record<string, unknown>)) {\n const n = node as Record<string, unknown>;\n if (typeof n.when === \"function\" || typeof n.transform === \"function\") {\n return false;\n }\n }\n }\n\n // Also check: if a goal node has `buildInput` or `extractOutput` functions, not serialized\n if (obj.type === \"goal\" && obj.nodes) {\n for (const node of Object.values(obj.nodes as Record<string, unknown>)) {\n const n = node as Record<string, unknown>;\n if (\n typeof n.buildInput === \"function\" ||\n typeof n.extractOutput === \"function\"\n ) {\n return false;\n }\n }\n }\n\n return true;\n}\n\n/** Build the preamble: optional %%{init}%% + graph directive. */\nfunction buildPreamble(direction: MermaidDirection, theme?: string): string {\n const lines: string[] = [];\n if (theme) {\n lines.push(`%%{init: {'theme': '${theme}'}}%%`);\n }\n lines.push(`graph ${direction}`);\n\n return lines.join(\"\\n\");\n}\n\nconst ALLOWED_TYPES = new Set([\n \"parallel\",\n \"sequential\",\n \"supervisor\",\n \"dag\",\n \"reflect\",\n \"race\",\n \"debate\",\n \"goal\",\n]);\n\n// ---------------------------------------------------------------------------\n// Renderers\n// ---------------------------------------------------------------------------\n\nfunction renderParallel(\n p: Extract<SerializedPattern, { type: \"parallel\" }>,\n shapes?: MermaidNodeShapes,\n taskIds?: ReadonlySet<string>,\n): string[] {\n const handlers = deduplicateAgents(p.handlers);\n const inputNode = wrapNode(\"__input\", \"Input\", \"virtual\", shapes);\n const mergeNode = wrapNode(\"__merge\", \"Merge\", \"virtual\", shapes);\n const lines: string[] = [];\n\n for (const handler of handlers) {\n const nodeType = taskIds?.has(handler.label)\n ? (\"task\" as const)\n : (\"agent\" as const);\n const handlerNode = wrapNode(handler.id, handler.label, nodeType, shapes);\n lines.push(` ${inputNode} --> ${handlerNode}`);\n lines.push(` ${handlerNode} --> ${mergeNode}`);\n }\n\n return lines;\n}\n\nfunction renderSequential(\n p: Extract<SerializedPattern, { type: \"sequential\" }>,\n shapes?: MermaidNodeShapes,\n taskIds?: ReadonlySet<string>,\n): string[] {\n if (p.handlers.length === 0) {\n return [];\n }\n\n const handlers = p.handlers.map((a) => ({\n id: sanitizeId(a),\n label: a,\n }));\n\n const nodes = handlers.map((a) =>\n wrapNode(a.id, a.label, taskIds?.has(a.label) ? \"task\" : \"agent\", shapes),\n );\n\n return [` ${nodes.join(\" --> \")}`];\n}\n\nfunction renderSupervisor(\n p: Extract<SerializedPattern, { type: \"supervisor\" }>,\n shapes?: MermaidNodeShapes,\n): string[] {\n const supId = sanitizeId(p.supervisor);\n const supNode = wrapNode(supId, p.supervisor, \"agent\", shapes);\n const lines: string[] = [];\n\n for (const worker of p.workers) {\n const wId = sanitizeId(worker);\n const wNode = wrapNode(wId, worker, \"agent\", shapes);\n lines.push(` ${supNode} -->|delegate| ${wNode}`);\n lines.push(` ${wNode} -->|result| ${supNode}`);\n }\n\n return lines;\n}\n\nfunction renderDag(\n p: Extract<SerializedPattern, { type: \"dag\" }>,\n shapes?: MermaidNodeShapes,\n taskIds?: ReadonlySet<string>,\n): string[] {\n const sorted = topoSort(p.nodes);\n const lines: string[] = [];\n const rendered = new Set<string>();\n\n for (const key of sorted) {\n const node = p.nodes[key]!;\n const nodeId = sanitizeId(key);\n const nodeLabel = node.handler;\n const nodeType = taskIds?.has(node.handler)\n ? (\"task\" as const)\n : (\"agent\" as const);\n\n if (!node.deps || node.deps.length === 0) {\n if (!rendered.has(nodeId)) {\n lines.push(` ${wrapNode(nodeId, nodeLabel, nodeType, shapes)}`);\n rendered.add(nodeId);\n }\n }\n\n const deps = [...(node.deps ?? [])].sort();\n for (const dep of deps) {\n const depId = sanitizeId(dep);\n const depNode = p.nodes[dep]!;\n const depLabel = depNode.handler;\n const depType = taskIds?.has(depNode.handler)\n ? (\"task\" as const)\n : (\"agent\" as const);\n const from = wrapNode(depId, depLabel, depType, shapes);\n const to = wrapNode(nodeId, nodeLabel, nodeType, shapes);\n lines.push(` ${from} --> ${to}`);\n rendered.add(depId);\n rendered.add(nodeId);\n }\n }\n\n return lines;\n}\n\nfunction renderRace(\n p: Extract<SerializedPattern, { type: \"race\" }>,\n shapes?: MermaidNodeShapes,\n taskIds?: ReadonlySet<string>,\n): string[] {\n const handlers = deduplicateAgents(p.handlers);\n const inputNode = wrapNode(\"__input\", \"Input\", \"virtual\", shapes);\n const outputNode = wrapNode(\"__output\", \"Output\", \"virtual\", shapes);\n const lines: string[] = [];\n\n for (const handler of handlers) {\n const nodeType = taskIds?.has(handler.label)\n ? (\"task\" as const)\n : (\"agent\" as const);\n const handlerNode = wrapNode(handler.id, handler.label, nodeType, shapes);\n lines.push(` ${inputNode} --> ${handlerNode}`);\n lines.push(` ${handlerNode} -.-> ${outputNode}`);\n }\n\n return lines;\n}\n\nfunction renderReflect(\n p: Extract<SerializedPattern, { type: \"reflect\" }>,\n shapes?: MermaidNodeShapes,\n taskIds?: ReadonlySet<string>,\n): string[] {\n const producerId = sanitizeId(p.handler);\n const evalId = sanitizeId(p.evaluator);\n const producerType = taskIds?.has(p.handler)\n ? (\"task\" as const)\n : (\"agent\" as const);\n const producerNode = wrapNode(producerId, p.handler, producerType, shapes);\n const evalNode = wrapNode(evalId, p.evaluator, \"agent\", shapes);\n const outputNode = wrapNode(\"__output\", \"Output\", \"virtual\", shapes);\n\n return [\n ` ${producerNode} --> ${evalNode}`,\n ` ${evalNode} -->|feedback| ${producerNode}`,\n ` ${evalNode} -->|pass| ${outputNode}`,\n ];\n}\n\nfunction renderGoal(\n p: Extract<SerializedPattern, { type: \"goal\" }>,\n shapes?: MermaidNodeShapes,\n taskIds?: ReadonlySet<string>,\n): string[] {\n const nodeEntries = Object.entries(p.nodes);\n const lines: string[] = [];\n\n // Build a map: factKey → nodeId that produces it\n const producerMap = new Map<string, string>();\n for (const [nodeId, node] of nodeEntries) {\n for (const key of node.produces) {\n producerMap.set(key, nodeId);\n }\n }\n\n // Build edges from produces/requires declarations\n const rendered = new Set<string>();\n const edgeSet = new Set<string>();\n\n // Sort node entries for determinism\n const sortedEntries = [...nodeEntries].sort(([a], [b]) => a.localeCompare(b));\n\n for (const [nodeId, node] of sortedEntries) {\n const id = sanitizeId(nodeId);\n const requires = [...(node.requires ?? [])].sort();\n\n if (requires.length === 0) {\n if (!rendered.has(id)) {\n const nodeType = taskIds?.has(node.handler)\n ? (\"task\" as const)\n : (\"agent\" as const);\n lines.push(` ${wrapNode(id, node.handler, nodeType, shapes)}`);\n rendered.add(id);\n }\n }\n\n for (const key of requires) {\n const producer = producerMap.get(key);\n if (producer && producer !== nodeId) {\n const fromNode = p.nodes[producer];\n if (!fromNode) {\n continue;\n }\n const edgeKey = `${producer}->${nodeId}`;\n if (!edgeSet.has(edgeKey)) {\n const fromId = sanitizeId(producer);\n const fromType = taskIds?.has(fromNode.handler)\n ? (\"task\" as const)\n : (\"agent\" as const);\n const toType = taskIds?.has(node.handler)\n ? (\"task\" as const)\n : (\"agent\" as const);\n const from = wrapNode(fromId, fromNode.handler, fromType, shapes);\n const to = wrapNode(id, node.handler, toType, shapes);\n lines.push(` ${from} -->|${sanitizeLabel(key)}| ${to}`);\n rendered.add(fromId);\n rendered.add(id);\n edgeSet.add(edgeKey);\n }\n }\n }\n }\n\n // Render any isolated nodes (no incoming or outgoing edges)\n for (const [nodeId, node] of sortedEntries) {\n const id = sanitizeId(nodeId);\n if (!rendered.has(id)) {\n const nodeType = taskIds?.has(node.handler)\n ? (\"task\" as const)\n : (\"agent\" as const);\n lines.push(` ${wrapNode(id, node.handler, nodeType, shapes)}`);\n rendered.add(id);\n }\n }\n\n return lines;\n}\n\nfunction renderDebate(\n p: Extract<SerializedPattern, { type: \"debate\" }>,\n shapes?: MermaidNodeShapes,\n taskIds?: ReadonlySet<string>,\n): string[] {\n const handlers = deduplicateAgents(p.handlers);\n const judgeId = sanitizeId(p.evaluator);\n const judgeNode = wrapNode(judgeId, p.evaluator, \"agent\", shapes);\n const outputNode = wrapNode(\"__output\", \"Output\", \"virtual\", shapes);\n const lines: string[] = [];\n\n for (const handler of handlers) {\n const nodeType = taskIds?.has(handler.label)\n ? (\"task\" as const)\n : (\"agent\" as const);\n const handlerNode = wrapNode(handler.id, handler.label, nodeType, shapes);\n lines.push(` ${handlerNode} --> ${judgeNode}`);\n lines.push(` ${judgeNode} -->|next round| ${handlerNode}`);\n }\n\n lines.push(` ${judgeNode} --> ${outputNode}`);\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\n/**\n * Convert an execution pattern to a Mermaid diagram string.\n *\n * Accepts both runtime `ExecutionPattern` (with function callbacks) and\n * pre-serialized `SerializedPattern`. Normalizes internally via `patternToJSON()`\n * when it detects function-valued fields.\n *\n * @example\n * ```typescript\n * const p = dag({ fetch: { handler: \"fetcher\" }, report: { handler: \"reporter\", deps: [\"fetch\"] } });\n * console.log(patternToMermaid(p, { direction: \"TD\" }));\n * // graph TD\n * // fetch[fetcher]\n * // fetch[fetcher] --> report[reporter]\n * ```\n *\n * @throws If pattern type is not one of the 8 known types.\n */\nexport function patternToMermaid(\n pattern: ExecutionPattern<unknown> | SerializedPattern,\n options?: MermaidOptions,\n): string {\n const direction = options?.direction ?? \"LR\";\n const shapes = options?.shapes;\n const taskIds = options?.taskIds;\n\n // Normalize to SerializedPattern\n const serialized: SerializedPattern = isSerializedPattern(pattern)\n ? pattern\n : patternToJSON(pattern as ExecutionPattern<unknown>);\n\n if (!ALLOWED_TYPES.has(serialized.type)) {\n throw new Error(\n `[Directive] patternToMermaid: unknown pattern type \"${serialized.type}\"`,\n );\n }\n\n const preamble = buildPreamble(direction, options?.theme);\n let body: string[] = [];\n\n switch (serialized.type) {\n case \"parallel\":\n body = renderParallel(serialized, shapes, taskIds);\n break;\n case \"sequential\":\n body = renderSequential(serialized, shapes, taskIds);\n break;\n case \"supervisor\":\n body = renderSupervisor(serialized, shapes);\n break;\n case \"dag\":\n body = renderDag(serialized, shapes, taskIds);\n break;\n case \"race\":\n body = renderRace(serialized, shapes, taskIds);\n break;\n case \"reflect\":\n body = renderReflect(serialized, shapes, taskIds);\n break;\n case \"debate\":\n body = renderDebate(serialized, shapes, taskIds);\n break;\n case \"goal\":\n body = renderGoal(serialized, shapes, taskIds);\n break;\n }\n\n return `${preamble}\\n${body.join(\"\\n\")}\\n`;\n}\n","/**\n * Agent-to-Agent Communication Protocol\n *\n * Provides structured communication channels between agents for coordination,\n * delegation, and knowledge sharing without central orchestration.\n *\n * @example\n * ```typescript\n * import { createAgentNetwork, createMessageBus } from '@directive-run/ai';\n *\n * const messageBus = createMessageBus();\n *\n * const network = createAgentNetwork({\n * bus: messageBus,\n * agents: {\n * researcher: { capabilities: ['search', 'analyze'] },\n * writer: { capabilities: ['draft', 'edit'] },\n * reviewer: { capabilities: ['review', 'approve'] },\n * },\n * });\n *\n * // Agents can send messages to each other\n * await network.send('researcher', 'writer', {\n * type: 'DELEGATION',\n * task: 'Draft an article based on this research',\n * context: { findings: [...] },\n * });\n * ```\n */\n\n// ============================================================================\n// Message Types\n// ============================================================================\n\n/** Base message structure */\nexport interface AgentMessage {\n id: string;\n type: AgentMessageType;\n from: string;\n to: string | string[] | \"*\"; // Single agent, multiple agents, or broadcast\n timestamp: number;\n correlationId?: string; // For request-response patterns\n replyTo?: string; // Message ID this is replying to\n priority?: \"low\" | \"normal\" | \"high\" | \"urgent\";\n ttlMs?: number; // Time-to-live\n metadata?: Record<string, unknown>;\n}\n\n/** Message types for agent communication */\nexport type AgentMessageType =\n | \"REQUEST\" // Request another agent to do something\n | \"RESPONSE\" // Response to a request\n | \"DELEGATION\" // Delegate a task to another agent\n | \"DELEGATION_RESULT\" // Result of a delegated task\n | \"QUERY\" // Ask for information\n | \"INFORM\" // Share information without expecting response\n | \"SUBSCRIBE\" // Subscribe to updates\n | \"UNSUBSCRIBE\" // Unsubscribe from updates\n | \"UPDATE\" // Push update to subscribers\n | \"ACK\" // Acknowledgment\n | \"NACK\" // Negative acknowledgment (rejection)\n | \"PING\" // Health check\n | \"PONG\" // Health check response\n | \"CUSTOM\"; // Custom message type\n\n/** Request message */\nexport interface RequestMessage extends AgentMessage {\n type: \"REQUEST\";\n action: string;\n payload: Record<string, unknown>;\n timeout?: number;\n}\n\n/** Response message */\nexport interface ResponseMessage extends AgentMessage {\n type: \"RESPONSE\";\n success: boolean;\n result?: unknown;\n error?: string;\n}\n\n/** Delegation message */\nexport interface DelegationMessage extends AgentMessage {\n type: \"DELEGATION\";\n task: string;\n context: Record<string, unknown>;\n constraints?: {\n deadline?: number;\n maxCost?: number;\n requiredCapabilities?: string[];\n };\n}\n\n/** Delegation result message */\nexport interface DelegationResultMessage extends AgentMessage {\n type: \"DELEGATION_RESULT\";\n success: boolean;\n result?: unknown;\n error?: string;\n metrics?: {\n durationMs: number;\n tokensUsed?: number;\n cost?: number;\n };\n}\n\n/** Query message */\nexport interface QueryMessage extends AgentMessage {\n type: \"QUERY\";\n question: string;\n context?: Record<string, unknown>;\n}\n\n/** Inform message */\nexport interface InformMessage extends AgentMessage {\n type: \"INFORM\";\n topic: string;\n content: unknown;\n}\n\n/** Subscribe message */\nexport interface SubscribeMessage extends AgentMessage {\n type: \"SUBSCRIBE\";\n topics: string[];\n}\n\n/** Update message */\nexport interface UpdateMessage extends AgentMessage {\n type: \"UPDATE\";\n topic: string;\n content: unknown;\n}\n\n/** Union of all message types */\nexport type TypedAgentMessage =\n | RequestMessage\n | ResponseMessage\n | DelegationMessage\n | DelegationResultMessage\n | QueryMessage\n | InformMessage\n | SubscribeMessage\n | UpdateMessage\n | (AgentMessage & {\n type: \"UNSUBSCRIBE\" | \"ACK\" | \"NACK\" | \"PING\" | \"PONG\" | \"CUSTOM\";\n });\n\n// ============================================================================\n// Message Bus Types\n// ============================================================================\n\n/** Message handler function */\nexport type MessageHandler = (\n message: TypedAgentMessage,\n) => void | Promise<void>;\n\n/** Subscription to messages */\nexport interface Subscription {\n id: string;\n agentId: string;\n handler: MessageHandler;\n filter?: MessageFilter;\n unsubscribe: () => void;\n}\n\n/** Message filter criteria */\nexport interface MessageFilter {\n types?: AgentMessageType[];\n from?: string | string[];\n topics?: string[];\n priority?: (\"low\" | \"normal\" | \"high\" | \"urgent\")[];\n custom?: (message: TypedAgentMessage) => boolean;\n}\n\n/** Message bus configuration */\nexport interface MessageBusConfig {\n /** Maximum messages to retain in history */\n maxHistory?: number;\n /** Default TTL for messages */\n defaultTtlMs?: number;\n /** Maximum pending messages per offline agent (prevents unbounded queue growth) */\n maxPendingPerAgent?: number;\n /** Enable message persistence */\n persistence?: MessagePersistence;\n /** Callback when message is delivered */\n onDelivery?: (message: TypedAgentMessage, recipients: string[]) => void;\n /** Callback when message delivery fails */\n onDeliveryError?: (message: TypedAgentMessage, error: Error) => void;\n}\n\n/** Message persistence interface */\nexport interface MessagePersistence {\n save(message: TypedAgentMessage): Promise<void>;\n load(agentId: string, since?: number): Promise<TypedAgentMessage[]>;\n delete(messageId: string): Promise<void>;\n clear(agentId?: string): Promise<void>;\n}\n\n/** Message bus instance */\nexport interface MessageBus {\n /** Publish a message */\n publish(message: Omit<TypedAgentMessage, \"id\" | \"timestamp\">): string;\n /** Subscribe to messages */\n subscribe(\n agentId: string,\n handler: MessageHandler,\n filter?: MessageFilter,\n ): Subscription;\n /** Get message history */\n getHistory(filter?: MessageFilter, limit?: number): TypedAgentMessage[];\n /** Get a specific message by ID */\n getMessage(id: string): TypedAgentMessage | undefined;\n /** Get pending messages for an agent */\n getPending(agentId: string): TypedAgentMessage[];\n /** Clear all messages and data */\n clear(): void;\n /** Destroy the message bus, clearing all data and subscriptions */\n destroy(): void;\n}\n\n// ============================================================================\n// Message Bus Factory\n// ============================================================================\n\nfunction generateId(): string {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`\n );\n}\n\n/**\n * Create a message bus for agent communication.\n *\n * @example\n * ```typescript\n * const bus = createMessageBus({ maxHistory: 1000 });\n *\n * // Subscribe to messages\n * bus.subscribe('writer', (msg) => {\n * console.log(`Writer received: ${msg.type}`);\n * });\n *\n * // Publish a message\n * bus.publish({\n * type: 'DELEGATION',\n * from: 'researcher',\n * to: 'writer',\n * task: 'Write summary',\n * context: { data: '...' },\n * });\n * ```\n */\n/**\n * Note: `publish()` is fire-and-forget -- it returns the message ID synchronously\n * before delivery completes. Use `onDelivery` / `onDeliveryError` callbacks in\n * config to track delivery status if needed.\n */\nexport function createMessageBus(config: MessageBusConfig = {}): MessageBus {\n const {\n maxHistory = 1000,\n defaultTtlMs = 3600000, // 1 hour\n maxPendingPerAgent = 100,\n persistence,\n onDelivery,\n onDeliveryError,\n } = config;\n\n const subscriptions = new Map<string, Subscription[]>();\n const messageHistory: TypedAgentMessage[] = [];\n const messageIndex = new Map<string, TypedAgentMessage>(); // O(1) lookup by ID\n const pendingMessages = new Map<string, TypedAgentMessage[]>();\n\n function matchesFilter(\n message: TypedAgentMessage,\n filter: MessageFilter,\n ): boolean {\n if (filter.types && !filter.types.includes(message.type)) {\n return false;\n }\n if (filter.from) {\n const fromList = Array.isArray(filter.from) ? filter.from : [filter.from];\n if (!fromList.includes(message.from)) {\n return false;\n }\n }\n if (filter.topics) {\n const topic = (message as InformMessage | UpdateMessage).topic;\n if (topic && !filter.topics.includes(topic)) {\n return false;\n }\n }\n if (\n filter.priority &&\n message.priority &&\n !filter.priority.includes(message.priority)\n ) {\n return false;\n }\n if (filter.custom && !filter.custom(message)) {\n return false;\n }\n return true;\n }\n\n function isExpired(message: TypedAgentMessage): boolean {\n if (!message.ttlMs) return false;\n return Date.now() - message.timestamp > message.ttlMs;\n }\n\n function getRecipients(message: TypedAgentMessage): string[] {\n if (message.to === \"*\") {\n return Array.from(subscriptions.keys());\n }\n if (Array.isArray(message.to)) {\n return message.to;\n }\n return [message.to];\n }\n\n async function deliverMessage(message: TypedAgentMessage): Promise<void> {\n // Skip expired messages\n if (isExpired(message)) return;\n\n const recipients = getRecipients(message);\n const deliveredTo: string[] = [];\n\n // Build delivery promises for all recipients in parallel\n const deliveryPromises: Promise<void>[] = [];\n\n for (const recipientId of recipients) {\n const recipientSubs = subscriptions.get(recipientId) ?? [];\n\n if (recipientSubs.length === 0) {\n // Queue message for offline agent (bounded)\n const pending = pendingMessages.get(recipientId) ?? [];\n pending.push(message);\n // Drop oldest if over limit\n while (pending.length > maxPendingPerAgent) {\n pending.shift();\n }\n pendingMessages.set(recipientId, pending);\n continue;\n }\n\n for (const sub of recipientSubs) {\n if (!sub.filter || matchesFilter(message, sub.filter)) {\n deliveryPromises.push(\n Promise.resolve(sub.handler(message)).then(\n () => {\n deliveredTo.push(recipientId);\n },\n (error) => {\n onDeliveryError?.(\n message,\n error instanceof Error ? error : new Error(String(error)),\n );\n },\n ),\n );\n }\n }\n }\n\n // Wait for all deliveries to settle in parallel\n if (deliveryPromises.length > 0) {\n await Promise.allSettled(deliveryPromises);\n }\n\n if (deliveredTo.length > 0) {\n onDelivery?.(message, deliveredTo);\n }\n\n // Persist if configured\n if (persistence) {\n await persistence.save(message);\n }\n }\n\n return {\n publish(partial: Omit<TypedAgentMessage, \"id\" | \"timestamp\">): string {\n const message: TypedAgentMessage = {\n ...partial,\n id: generateId(),\n timestamp: Date.now(),\n priority: partial.priority ?? \"normal\",\n ttlMs: partial.ttlMs ?? defaultTtlMs,\n } as TypedAgentMessage;\n\n // Add to history and index\n messageHistory.push(message);\n messageIndex.set(message.id, message);\n\n // Trim old messages (remove from both history and index)\n while (messageHistory.length > maxHistory) {\n const removed = messageHistory.shift();\n if (removed) {\n messageIndex.delete(removed.id);\n }\n }\n\n // Deliver asynchronously\n deliverMessage(message).catch((error) => {\n const err = error instanceof Error ? error : new Error(String(error));\n if (onDeliveryError) {\n onDeliveryError(message, err);\n } else {\n console.error(\"[Directive MessageBus] Delivery error:\", err);\n }\n });\n\n return message.id;\n },\n\n subscribe(\n agentId: string,\n handler: MessageHandler,\n filter?: MessageFilter,\n ): Subscription {\n const subId = generateId();\n\n const subscription: Subscription = {\n id: subId,\n agentId,\n handler,\n filter,\n unsubscribe: () => {\n const subs = subscriptions.get(agentId) ?? [];\n const index = subs.findIndex((s) => s.id === subId);\n if (index >= 0) {\n subs.splice(index, 1);\n }\n },\n };\n\n const existing = subscriptions.get(agentId) ?? [];\n existing.push(subscription);\n subscriptions.set(agentId, existing);\n\n // Deliver pending messages\n const pending = pendingMessages.get(agentId) ?? [];\n pendingMessages.delete(agentId);\n for (const msg of pending) {\n if (!filter || matchesFilter(msg, filter)) {\n const result = handler(msg);\n if (result instanceof Promise) {\n result.catch((error) => {\n const err =\n error instanceof Error ? error : new Error(String(error));\n if (onDeliveryError) {\n onDeliveryError(msg, err);\n } else {\n console.error(\n \"[Directive MessageBus] Pending delivery error:\",\n err,\n );\n }\n });\n }\n }\n }\n\n return subscription;\n },\n\n getHistory(filter?: MessageFilter, limit = 100): TypedAgentMessage[] {\n let messages = messageHistory.filter((m) => !isExpired(m));\n\n if (filter) {\n messages = messages.filter((m) => matchesFilter(m, filter));\n }\n\n return messages.slice(-limit);\n },\n\n getMessage(id: string): TypedAgentMessage | undefined {\n const msg = messageIndex.get(id);\n if (msg && isExpired(msg)) return undefined;\n return msg;\n },\n\n getPending(agentId: string): TypedAgentMessage[] {\n const pending = pendingMessages.get(agentId) ?? [];\n return pending.filter((m) => !isExpired(m));\n },\n\n clear(): void {\n messageHistory.length = 0;\n messageIndex.clear();\n pendingMessages.clear();\n },\n\n destroy(): void {\n messageHistory.length = 0;\n messageIndex.clear();\n pendingMessages.clear();\n subscriptions.clear();\n },\n };\n}\n\n// ============================================================================\n// Agent Network Types\n// ============================================================================\n\n/** Agent registration info */\nexport interface AgentInfo {\n id: string;\n capabilities: string[];\n status: \"online\" | \"offline\" | \"busy\";\n lastSeen: number;\n metadata?: Record<string, unknown>;\n}\n\n/** Agent network configuration */\nexport interface AgentNetworkConfig {\n /** Message bus to use */\n bus: MessageBus;\n /** Registered agents */\n agents?: Record<string, Omit<AgentInfo, \"id\" | \"lastSeen\" | \"status\">>;\n /** Timeout for request-response patterns */\n defaultTimeout?: number;\n /** Callback when agent comes online */\n onAgentOnline?: (agentId: string) => void;\n /** Callback when agent goes offline */\n onAgentOffline?: (agentId: string) => void;\n}\n\n/** Agent network instance */\nexport interface AgentNetwork {\n /** Register an agent */\n register(\n id: string,\n info: Omit<AgentInfo, \"id\" | \"lastSeen\" | \"status\">,\n ): void;\n /** Unregister an agent */\n unregister(id: string): void;\n /** Get agent info */\n getAgent(id: string): AgentInfo | undefined;\n /** Get all agents */\n getAgents(): AgentInfo[];\n /** Find agents by capability */\n findByCapability(capability: string): AgentInfo[];\n /** Send a message */\n send(\n from: string,\n to: string | string[],\n message: Partial<TypedAgentMessage>,\n ): string;\n /** Send a request and wait for response */\n request(\n from: string,\n to: string,\n action: string,\n payload: Record<string, unknown>,\n timeout?: number,\n ): Promise<ResponseMessage>;\n /** Delegate a task */\n delegate(\n from: string,\n to: string,\n task: string,\n context: Record<string, unknown>,\n ): Promise<DelegationResultMessage>;\n /** Query an agent */\n query(\n from: string,\n to: string,\n question: string,\n context?: Record<string, unknown>,\n ): Promise<ResponseMessage>;\n /** Broadcast to all agents */\n broadcast(from: string, message: Partial<TypedAgentMessage>): string;\n /** Subscribe an agent to messages */\n listen(\n agentId: string,\n handler: MessageHandler,\n filter?: MessageFilter,\n ): Subscription;\n /** Get the message bus */\n getBus(): MessageBus;\n /** Destroy the network, clearing pending waiters and timers */\n destroy(): void;\n}\n\n// ============================================================================\n// Agent Network Factory\n// ============================================================================\n\n/**\n * Create an agent network for coordinated communication.\n *\n * @example\n * ```typescript\n * const network = createAgentNetwork({\n * bus: createMessageBus(),\n * agents: {\n * researcher: { capabilities: ['search', 'summarize'] },\n * writer: { capabilities: ['draft', 'edit'] },\n * reviewer: { capabilities: ['review', 'approve'] },\n * },\n * });\n *\n * // Delegate a task\n * const result = await network.delegate(\n * 'researcher',\n * 'writer',\n * 'Write an article about AI safety',\n * { research: findingsData }\n * );\n *\n * // Query for information\n * const answer = await network.query(\n * 'writer',\n * 'reviewer',\n * 'Is this paragraph technically accurate?',\n * { text: '...' }\n * );\n * ```\n */\nexport function createAgentNetwork(config: AgentNetworkConfig): AgentNetwork {\n const {\n bus,\n agents: initialAgents = {},\n defaultTimeout = 30000,\n onAgentOnline,\n onAgentOffline,\n } = config;\n\n const agents = new Map<string, AgentInfo>();\n const responseWaiters = new Map<\n string,\n {\n resolve: (msg: ResponseMessage | DelegationResultMessage) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n\n // Initialize agents\n for (const [id, info] of Object.entries(initialAgents)) {\n agents.set(id, {\n ...info,\n id,\n status: \"offline\",\n lastSeen: Date.now(),\n });\n }\n\n // Handle response messages\n function handleResponse(message: TypedAgentMessage): void {\n if (message.type !== \"RESPONSE\" && message.type !== \"DELEGATION_RESULT\") {\n return;\n }\n\n const correlationId = message.correlationId ?? message.replyTo;\n if (!correlationId) return;\n\n const waiter = responseWaiters.get(correlationId);\n if (waiter) {\n clearTimeout(waiter.timer);\n responseWaiters.delete(correlationId);\n waiter.resolve(message as ResponseMessage | DelegationResultMessage);\n }\n }\n\n return {\n register(\n id: string,\n info: Omit<AgentInfo, \"id\" | \"lastSeen\" | \"status\">,\n ): void {\n const wasOffline =\n !agents.has(id) || agents.get(id)?.status === \"offline\";\n\n agents.set(id, {\n ...info,\n id,\n status: \"online\",\n lastSeen: Date.now(),\n });\n\n if (wasOffline) {\n onAgentOnline?.(id);\n }\n },\n\n unregister(id: string): void {\n const agent = agents.get(id);\n if (agent) {\n agent.status = \"offline\";\n onAgentOffline?.(id);\n }\n },\n\n getAgent(id: string): AgentInfo | undefined {\n return agents.get(id);\n },\n\n getAgents(): AgentInfo[] {\n return Array.from(agents.values());\n },\n\n findByCapability(capability: string): AgentInfo[] {\n return Array.from(agents.values()).filter(\n (agent) =>\n agent.capabilities.includes(capability) && agent.status === \"online\",\n );\n },\n\n send(\n from: string,\n to: string | string[],\n message: Partial<TypedAgentMessage>,\n ): string {\n // Update sender's lastSeen\n const sender = agents.get(from);\n if (sender) {\n sender.lastSeen = Date.now();\n sender.status = \"online\";\n }\n\n return bus.publish({\n ...message,\n from,\n to,\n type: message.type ?? \"CUSTOM\",\n } as Omit<TypedAgentMessage, \"id\" | \"timestamp\">);\n },\n\n async request(\n from: string,\n to: string,\n action: string,\n payload: Record<string, unknown>,\n timeout = defaultTimeout,\n ): Promise<ResponseMessage> {\n return new Promise((resolve, reject) => {\n // Generate a correlation ID upfront so subscription can listen before publish\n const correlationId = generateId();\n\n // Subscribe BEFORE publishing to avoid race condition with fast responders\n const sub = bus.subscribe(\n from,\n (msg) => {\n if (\n msg.correlationId === correlationId ||\n msg.replyTo === correlationId\n ) {\n sub.unsubscribe();\n handleResponse(msg);\n }\n },\n { types: [\"RESPONSE\"] },\n );\n\n const timer = setTimeout(() => {\n sub.unsubscribe(); // Clean up subscription on timeout\n responseWaiters.delete(correlationId);\n reject(\n new Error(\n `[Directive Communication] Request timeout after ${timeout}ms`,\n ),\n );\n }, timeout);\n\n responseWaiters.set(correlationId, {\n resolve: resolve as (\n msg: ResponseMessage | DelegationResultMessage,\n ) => void,\n reject,\n timer,\n });\n\n bus.publish({\n type: \"REQUEST\",\n from,\n to,\n action,\n payload,\n timeout,\n correlationId,\n } as Omit<RequestMessage, \"id\" | \"timestamp\"> & {\n correlationId: string;\n });\n });\n },\n\n async delegate(\n from: string,\n to: string,\n task: string,\n context: Record<string, unknown>,\n ): Promise<DelegationResultMessage> {\n return new Promise((resolve, reject) => {\n const correlationId = generateId();\n\n // Subscribe BEFORE publishing to avoid race condition\n const sub = bus.subscribe(\n from,\n (msg) => {\n if (\n msg.correlationId === correlationId ||\n msg.replyTo === correlationId\n ) {\n sub.unsubscribe();\n handleResponse(msg);\n }\n },\n { types: [\"DELEGATION_RESULT\"] },\n );\n\n const timer = setTimeout(() => {\n sub.unsubscribe();\n responseWaiters.delete(correlationId);\n reject(\n new Error(\n `[Directive Communication] Delegation timeout after ${defaultTimeout}ms`,\n ),\n );\n }, defaultTimeout);\n\n responseWaiters.set(correlationId, {\n resolve: resolve as (\n msg: ResponseMessage | DelegationResultMessage,\n ) => void,\n reject,\n timer,\n });\n\n bus.publish({\n type: \"DELEGATION\",\n from,\n to,\n task,\n context,\n correlationId,\n } as Omit<DelegationMessage, \"id\" | \"timestamp\"> & {\n correlationId: string;\n });\n });\n },\n\n async query(\n from: string,\n to: string,\n question: string,\n context?: Record<string, unknown>,\n ): Promise<ResponseMessage> {\n return new Promise((resolve, reject) => {\n const correlationId = generateId();\n\n // Subscribe BEFORE publishing to avoid race condition\n const sub = bus.subscribe(\n from,\n (msg) => {\n if (\n msg.correlationId === correlationId ||\n msg.replyTo === correlationId\n ) {\n sub.unsubscribe();\n handleResponse(msg);\n }\n },\n { types: [\"RESPONSE\"] },\n );\n\n const timer = setTimeout(() => {\n sub.unsubscribe();\n responseWaiters.delete(correlationId);\n reject(\n new Error(\n `[Directive Communication] Query timeout after ${defaultTimeout}ms`,\n ),\n );\n }, defaultTimeout);\n\n responseWaiters.set(correlationId, {\n resolve: resolve as (\n msg: ResponseMessage | DelegationResultMessage,\n ) => void,\n reject,\n timer,\n });\n\n bus.publish({\n type: \"QUERY\",\n from,\n to,\n question,\n context,\n correlationId,\n } as Omit<QueryMessage, \"id\" | \"timestamp\"> & {\n correlationId: string;\n });\n });\n },\n\n broadcast(from: string, message: Partial<TypedAgentMessage>): string {\n return bus.publish({\n ...message,\n from,\n to: \"*\",\n type: message.type ?? \"INFORM\",\n } as Omit<TypedAgentMessage, \"id\" | \"timestamp\">);\n },\n\n listen(\n agentId: string,\n handler: MessageHandler,\n filter?: MessageFilter,\n ): Subscription {\n // Mark agent as online\n const agent = agents.get(agentId);\n if (agent) {\n agent.status = \"online\";\n agent.lastSeen = Date.now();\n onAgentOnline?.(agentId);\n }\n\n return bus.subscribe(agentId, handler, filter);\n },\n\n getBus(): MessageBus {\n return bus;\n },\n\n destroy(): void {\n // Clear all pending response waiters and their timers\n for (const [, waiter] of responseWaiters) {\n clearTimeout(waiter.timer);\n }\n responseWaiters.clear();\n agents.clear();\n },\n };\n}\n\n// ============================================================================\n// Communication Patterns\n// ============================================================================\n\n/**\n * Create a request-response helper for handling incoming requests.\n *\n * @example\n * ```typescript\n * const responder = createResponder(network, 'writer');\n *\n * responder.onRequest('draft', async (payload) => {\n * const draft = await generateDraft(payload.topic);\n * return { success: true, result: draft };\n * });\n * ```\n */\nexport function createResponder(network: AgentNetwork, agentId: string) {\n const handlers = new Map<\n string,\n (\n payload: Record<string, unknown>,\n ) => Promise<{ success: boolean; result?: unknown; error?: string }>\n >();\n\n const subscription = network.listen(\n agentId,\n async (message) => {\n if (message.type === \"REQUEST\") {\n const request = message as RequestMessage;\n const handler = handlers.get(request.action);\n\n let response: Partial<ResponseMessage>;\n if (handler) {\n try {\n const result = await handler(request.payload);\n response = {\n type: \"RESPONSE\",\n success: result.success,\n result: result.result,\n error: result.error,\n };\n } catch (error) {\n response = {\n type: \"RESPONSE\",\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n } else {\n response = {\n type: \"RESPONSE\",\n success: false,\n error: `Unknown action: ${request.action}`,\n };\n }\n\n network.send(agentId, message.from, {\n ...response,\n correlationId: message.correlationId ?? message.id,\n replyTo: message.correlationId ?? message.id,\n });\n }\n },\n { types: [\"REQUEST\"] },\n );\n\n return {\n onRequest(\n action: string,\n handler: (\n payload: Record<string, unknown>,\n ) => Promise<{ success: boolean; result?: unknown; error?: string }>,\n ): void {\n handlers.set(action, handler);\n },\n\n /** Remove a request handler */\n offRequest(action: string): void {\n handlers.delete(action);\n },\n\n /** Destroy this responder, unsubscribing from network */\n destroy(): void {\n subscription.unsubscribe();\n handlers.clear();\n },\n };\n}\n\n/**\n * Create a task delegator for handling incoming delegations.\n *\n * @example\n * ```typescript\n * const delegator = createDelegator(network, 'writer');\n *\n * delegator.onDelegation(async (task, context) => {\n * const result = await executeTask(task, context);\n * return {\n * success: true,\n * result,\n * metrics: { durationMs: 1500, tokensUsed: 500 },\n * };\n * });\n * ```\n */\nexport function createDelegator(network: AgentNetwork, agentId: string) {\n let delegationHandler:\n | ((\n task: string,\n context: Record<string, unknown>,\n ) => Promise<{\n success: boolean;\n result?: unknown;\n error?: string;\n metrics?: { durationMs: number; tokensUsed?: number; cost?: number };\n }>)\n | null = null;\n\n const subscription = network.listen(\n agentId,\n async (message) => {\n if (message.type === \"DELEGATION\" && delegationHandler) {\n const delegation = message as DelegationMessage;\n const start = Date.now();\n\n let result: Partial<DelegationResultMessage>;\n try {\n const response = await delegationHandler(\n delegation.task,\n delegation.context,\n );\n result = {\n type: \"DELEGATION_RESULT\",\n success: response.success,\n result: response.result,\n error: response.error,\n metrics: response.metrics ?? { durationMs: Date.now() - start },\n };\n } catch (error) {\n result = {\n type: \"DELEGATION_RESULT\",\n success: false,\n error: error instanceof Error ? error.message : String(error),\n metrics: { durationMs: Date.now() - start },\n };\n }\n\n network.send(agentId, message.from, {\n ...result,\n correlationId: message.correlationId ?? message.id,\n replyTo: message.correlationId ?? message.id,\n });\n }\n },\n { types: [\"DELEGATION\"] },\n );\n\n return {\n onDelegation(\n handler: (\n task: string,\n context: Record<string, unknown>,\n ) => Promise<{\n success: boolean;\n result?: unknown;\n error?: string;\n metrics?: { durationMs: number; tokensUsed?: number; cost?: number };\n }>,\n ): void {\n delegationHandler = handler;\n },\n\n /** Remove the delegation handler */\n offDelegation(): void {\n delegationHandler = null;\n },\n\n /** Destroy this delegator, unsubscribing from network */\n destroy(): void {\n subscription.unsubscribe();\n delegationHandler = null;\n },\n };\n}\n\n/**\n * Create a pub/sub helper for topic-based communication.\n *\n * @example\n * ```typescript\n * const pubsub = createPubSub(network, 'analyst');\n *\n * // Subscribe to topics\n * pubsub.subscribe(['market-updates', 'alerts'], (topic, content) => {\n * console.log(`Received ${topic}:`, content);\n * });\n *\n * // Publish to topics\n * pubsub.publish('market-updates', { price: 100, change: 5 });\n * ```\n */\nexport function createPubSub(network: AgentNetwork, agentId: string) {\n const topicHandlers = new Map<string, Array<(content: unknown) => void>>();\n\n const subscription = network.listen(\n agentId,\n (message) => {\n if (message.type === \"UPDATE\") {\n const update = message as UpdateMessage;\n const handlers = topicHandlers.get(update.topic) ?? [];\n for (const handler of handlers) {\n handler(update.content);\n }\n }\n },\n { types: [\"UPDATE\"] },\n );\n\n return {\n subscribe(\n topics: string[],\n handler: (topic: string, content: unknown) => void,\n ): () => void {\n // Track wrapped handlers per-subscribe call for proper cleanup\n const wrappedHandlers = new Map<string, (content: unknown) => void>();\n\n for (const topic of topics) {\n const handlers = topicHandlers.get(topic) ?? [];\n const wrappedHandler = (content: unknown) => handler(topic, content);\n wrappedHandlers.set(topic, wrappedHandler);\n handlers.push(wrappedHandler);\n topicHandlers.set(topic, handlers);\n }\n\n // Announce subscription\n network.broadcast(agentId, {\n type: \"SUBSCRIBE\",\n topics,\n } as Partial<SubscribeMessage>);\n\n return () => {\n // Only remove this subscription's handlers, not all handlers for the topic\n for (const [topic, wrappedHandler] of wrappedHandlers) {\n const handlers = topicHandlers.get(topic);\n if (handlers) {\n const idx = handlers.indexOf(wrappedHandler);\n if (idx >= 0) handlers.splice(idx, 1);\n if (handlers.length === 0) topicHandlers.delete(topic);\n }\n }\n wrappedHandlers.clear();\n network.broadcast(agentId, {\n type: \"UNSUBSCRIBE\",\n topics,\n } as Partial<AgentMessage & { type: \"UNSUBSCRIBE\"; topics: string[] }>);\n };\n },\n\n publish(topic: string, content: unknown): void {\n network.broadcast(agentId, {\n type: \"UPDATE\",\n topic,\n content,\n } as Partial<UpdateMessage>);\n },\n\n /** Destroy this pub/sub, unsubscribing from network and clearing handlers */\n destroy(): void {\n subscription.unsubscribe();\n topicHandlers.clear();\n },\n };\n}\n","/**\n * Standalone utilities for goal planning and validation.\n *\n * These functions work with the same `produces` / `requires` agent\n * declarations used by the goal pattern, without requiring an\n * orchestrator instance.\n *\n * @example\n * ```typescript\n * import { validateGoal, planGoal, getDependencyGraph } from '@directive-run/ai';\n *\n * const agents = {\n * fetcher: { produces: ['data'], requires: [] },\n * analyzer: { produces: ['analysis'], requires: ['data'] },\n * reporter: { produces: ['report'], requires: ['analysis'] },\n * };\n *\n * // Validate — cycle detection, missing deps, warnings\n * const validation = validateGoal(agents);\n *\n * // Plan — dry-run without executing agents\n * const plan = planGoal(agents, ['query']);\n *\n * // Graph — topological order, roots, leaves, edges\n * const graph = getDependencyGraph(agents);\n * ```\n *\n * @module\n */\n\nimport type { GoalResult, GoalStepMetrics, RelaxationRecord } from \"./types.js\";\n\n/** Clamp non-finite satisfaction values to 0 */\nfunction safeSatisfaction(val: number): number {\n if (!Number.isFinite(val)) {\n return 0;\n }\n\n return val;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Minimal agent declaration for goal utilities (subset of GoalNode) */\nexport interface GoalAgentDeclaration {\n /** Fact keys this agent writes as output */\n produces: string[];\n /** Fact keys this agent reads as input */\n requires?: string[];\n}\n\n/** Edge in the inferred dependency graph */\nexport interface GoalDependencyEdge {\n from: string;\n to: string;\n /** Fact key that creates this dependency */\n factKey: string;\n}\n\n/** Inferred dependency graph from produces/requires analysis */\nexport interface GoalDependencyGraph {\n /** Agent IDs in topological order (roots first) */\n order: string[];\n /** Edges between agents */\n edges: GoalDependencyEdge[];\n /** Root agents (no unfulfilled requires from other agents) */\n roots: string[];\n /** Leaf agents (nothing depends on their produces) */\n leaves: string[];\n /** Map of fact key to agent ID that produces it */\n producers: Map<string, string>;\n}\n\n/** Validation result */\nexport interface GoalValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n}\n\n/** A single step in an execution plan */\nexport interface GoalPlanStep {\n /** Step number (1-based) */\n step: number;\n /** Agent IDs that would run in this step (parallel) */\n agents: string[];\n /** Fact keys available at the start of this step */\n availableFacts: string[];\n /** Fact keys produced after this step completes */\n producedFacts: string[];\n}\n\n/** Result of a planGoal() dry-run */\nexport interface GoalExecutionPlan {\n /** Ordered steps showing which agents run when */\n steps: GoalPlanStep[];\n /** Agents that can never run (requires never satisfiable) */\n unreachableAgents: string[];\n /** Required fact keys that no agent produces (must be in initial facts) */\n externalDeps: string[];\n /** Whether the plan can potentially reach all agents */\n feasible: boolean;\n}\n\n// ============================================================================\n// Internal: Topological Sort (Kahn's Algorithm)\n// ============================================================================\n\nfunction buildGraph(\n agents: Record<string, GoalAgentDeclaration>,\n): GoalDependencyGraph {\n const agentIds = Object.keys(agents);\n\n // Build a map: factKey → agentId that produces it\n const producerMap = new Map<string, string>();\n for (const [agentId, decl] of Object.entries(agents)) {\n for (const key of decl.produces) {\n if (producerMap.has(key)) {\n throw new Error(\n `[Directive Goal] Fact key \"${key}\" is produced by both \"${producerMap.get(key)}\" and \"${agentId}\". Each fact key must have exactly one producer.`,\n );\n }\n producerMap.set(key, agentId);\n }\n }\n\n // Build edges: agent B requires fact X → agent A produces fact X → edge A→B\n const edges: GoalDependencyEdge[] = [];\n const inDegree = new Map<string, number>();\n const adjacency = new Map<string, string[]>();\n\n for (const id of agentIds) {\n inDegree.set(id, 0);\n adjacency.set(id, []);\n }\n\n for (const [agentId, decl] of Object.entries(agents)) {\n for (const key of decl.requires ?? []) {\n const producer = producerMap.get(key);\n if (producer && producer !== agentId) {\n edges.push({ from: producer, to: agentId, factKey: key });\n adjacency.get(producer)!.push(agentId);\n inDegree.set(agentId, (inDegree.get(agentId) ?? 0) + 1);\n }\n }\n }\n\n // Topological sort (Kahn's algorithm)\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) {\n queue.push(id);\n }\n }\n\n const order: string[] = [];\n let queueIdx = 0;\n while (queueIdx < queue.length) {\n const current = queue[queueIdx++]!;\n order.push(current);\n\n for (const neighbor of adjacency.get(current) ?? []) {\n const newDeg = (inDegree.get(neighbor) ?? 1) - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) {\n queue.push(neighbor);\n }\n }\n }\n\n if (order.length !== agentIds.length) {\n const orderSet = new Set(order);\n const inCycle = agentIds.filter((id) => !orderSet.has(id));\n\n throw new Error(\n `[Directive Goal] Circular dependency detected among agents: ${inCycle.join(\", \")}. Review their produces/requires declarations.`,\n );\n }\n\n // Identify roots and leaves\n const roots = order.filter((id) => {\n const decl = agents[id]!;\n const requires = decl.requires ?? [];\n\n return requires.every(\n (key) => !producerMap.has(key) || producerMap.get(key) === id,\n );\n });\n\n const consumedBy = new Set<string>();\n for (const edge of edges) {\n consumedBy.add(edge.from);\n }\n const leaves = agentIds.filter((id) => !consumedBy.has(id));\n\n return { order, edges, roots, leaves, producers: producerMap };\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Get the dependency graph for a set of agent declarations.\n *\n * Uses Kahn's algorithm (topological sort) to compute execution order\n * and detect circular dependencies.\n *\n * @throws If agents form a circular dependency or a fact key has multiple producers.\n *\n * @example\n * ```typescript\n * const graph = getDependencyGraph({\n * fetcher: { produces: ['data'], requires: [] },\n * analyzer: { produces: ['analysis'], requires: ['data'] },\n * });\n *\n * console.log(graph.order); // ['fetcher', 'analyzer']\n * console.log(graph.roots); // ['fetcher']\n * console.log(graph.leaves); // ['analyzer']\n * ```\n */\nexport function getDependencyGraph(\n agents: Record<string, GoalAgentDeclaration>,\n): GoalDependencyGraph {\n const graph = buildGraph(agents);\n\n return {\n order: [...graph.order],\n edges: [...graph.edges],\n roots: [...graph.roots],\n leaves: [...graph.leaves],\n producers: new Map(graph.producers),\n };\n}\n\n/**\n * Validate a set of agent declarations for goal execution.\n *\n * Checks for:\n * - Circular dependencies\n * - Duplicate producers (same fact key produced by multiple agents)\n * - Agents with no `produces` (will never contribute)\n * - Required fact keys that no agent produces (must be in initial facts)\n *\n * @example\n * ```typescript\n * const result = validateGoal({\n * fetcher: { produces: ['data'] },\n * analyzer: { produces: ['analysis'], requires: ['data'] },\n * });\n *\n * if (!result.valid) {\n * console.error(result.errors);\n * }\n * ```\n */\nexport function validateGoal(\n agents: Record<string, GoalAgentDeclaration>,\n): GoalValidationResult {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n if (Object.keys(agents).length === 0) {\n errors.push(\"No agents declared\");\n }\n\n for (const [id, decl] of Object.entries(agents)) {\n if (decl.produces.length === 0) {\n warnings.push(`Agent \"${id}\" has no produces — it will never contribute`);\n }\n }\n\n const allProduced = new Set<string>();\n for (const decl of Object.values(agents)) {\n for (const key of decl.produces) {\n allProduced.add(key);\n }\n }\n\n for (const [id, decl] of Object.entries(agents)) {\n for (const key of decl.requires ?? []) {\n if (!allProduced.has(key)) {\n warnings.push(\n `Agent \"${id}\" requires \"${key}\" which no agent produces — must be in initial facts`,\n );\n }\n }\n }\n\n try {\n buildGraph(agents);\n } catch (err) {\n errors.push(err instanceof Error ? err.message : String(err));\n }\n\n return { valid: errors.length === 0, errors, warnings };\n}\n\n/**\n * Dry-run goal execution to preview the plan without running agents.\n *\n * Shows which agents would run in each step, which facts would be produced,\n * and whether any agents are unreachable.\n *\n * @param agents - Agent declarations with produces/requires\n * @param initialFactKeys - Fact keys available at the start (not values, just keys)\n * @param maxSteps - Maximum steps to simulate (default: 50)\n *\n * @example\n * ```typescript\n * const plan = planGoal(\n * {\n * fetcher: { produces: ['data'] },\n * analyzer: { produces: ['analysis'], requires: ['data'] },\n * reporter: { produces: ['report'], requires: ['analysis'] },\n * },\n * ['query'],\n * );\n *\n * console.log(plan.feasible); // true\n * console.log(plan.steps); // 3 steps: fetcher → analyzer → reporter\n * ```\n */\nexport function planGoal(\n agents: Record<string, GoalAgentDeclaration>,\n initialFactKeys: string[] = [],\n maxSteps = 50,\n): GoalExecutionPlan {\n const graph = buildGraph(agents);\n\n const allProduced = new Set<string>();\n for (const decl of Object.values(agents)) {\n for (const key of decl.produces) {\n allProduced.add(key);\n }\n }\n\n // External deps: fact keys required by agents that no agent produces\n const externalDeps: string[] = [];\n for (const decl of Object.values(agents)) {\n for (const key of decl.requires ?? []) {\n if (!allProduced.has(key)) {\n externalDeps.push(key);\n }\n }\n }\n\n const availableFacts = new Set(initialFactKeys);\n const completedAgents = new Set<string>();\n const steps: GoalPlanStep[] = [];\n\n for (let stepNum = 1; stepNum <= maxSteps; stepNum++) {\n const readyAgents = graph.order.filter((agentId) => {\n if (completedAgents.has(agentId)) {\n return false;\n }\n const decl = agents[agentId]!;\n const requires = decl.requires ?? [];\n\n return requires.every((key) => availableFacts.has(key));\n });\n\n if (readyAgents.length === 0) {\n break;\n }\n\n const producedFacts: string[] = [];\n for (const agentId of readyAgents) {\n completedAgents.add(agentId);\n for (const key of agents[agentId]!.produces) {\n if (!availableFacts.has(key)) {\n producedFacts.push(key);\n availableFacts.add(key);\n }\n }\n }\n\n steps.push({\n step: stepNum,\n agents: readyAgents,\n availableFacts: [...availableFacts],\n producedFacts,\n });\n }\n\n const unreachableAgents = Object.keys(agents).filter(\n (id) => !completedAgents.has(id),\n );\n\n return {\n steps,\n unreachableAgents,\n externalDeps: [...new Set(externalDeps)],\n feasible: unreachableAgents.length === 0,\n };\n}\n\n// ============================================================================\n// Explain Goal\n// ============================================================================\n\n/** A single line in a goal execution explanation */\nexport interface GoalExplanationStep {\n step: number;\n agents: string[];\n factsProduced: string[];\n satisfaction: number;\n satisfactionDelta: number;\n durationMs: number;\n tokensConsumed: number;\n /** Human-readable description of what happened */\n description: string;\n}\n\n/** Structured explanation of a goal execution */\nexport interface GoalExplanation {\n /** Whether the goal was achieved */\n achieved: boolean;\n /** Human-readable summary */\n summary: string;\n /** Per-step explanations */\n steps: GoalExplanationStep[];\n /** Relaxation events with descriptions */\n relaxations: Array<{\n step: number;\n label: string;\n strategy: string;\n description: string;\n }>;\n /** Total tokens consumed */\n totalTokens: number;\n /** Total duration (ms) */\n durationMs: number;\n}\n\n/**\n * Generate a human-readable explanation of a goal execution result.\n *\n * Takes a `GoalResult` and returns a structured explanation of why each\n * agent ran, how satisfaction progressed, and what relaxations were applied.\n *\n * @example\n * ```typescript\n * const result = await orchestrator.runGoal(nodes, input, when, options);\n * const explanation = explainGoal(result);\n *\n * console.log(explanation.summary);\n * // \"Goal achieved in 3 steps (1,247 tokens, 892ms). Satisfaction: 0 → 1.\"\n *\n * for (const step of explanation.steps) {\n * console.log(step.description);\n * // \"Step 1: Ran fetcher. Produced: data. Satisfaction: 0 → 0.3 (+0.3).\"\n * }\n * ```\n */\nexport function explainGoal<T = unknown>(\n result: GoalResult<T>,\n): GoalExplanation {\n const steps: GoalExplanationStep[] = result.stepMetrics.map(\n (metric: GoalStepMetrics) => {\n const sat = safeSatisfaction(metric.satisfaction);\n const satDelta = safeSatisfaction(metric.satisfactionDelta);\n const agentList = metric.nodesRun.join(\", \");\n const factList =\n metric.factsProduced.length > 0\n ? metric.factsProduced.join(\", \")\n : \"none\";\n const prevSatisfaction = +safeSatisfaction(sat - satDelta).toFixed(3);\n const delta =\n satDelta >= 0 ? `+${satDelta.toFixed(3)}` : satDelta.toFixed(3);\n\n const description =\n `Step ${metric.step}: Ran ${agentList}. ` +\n `Produced: ${factList}. ` +\n `Satisfaction: ${prevSatisfaction} → ${sat.toFixed(3)} (${delta}). ` +\n `${metric.tokensConsumed} tokens, ${metric.durationMs}ms.`;\n\n return {\n step: metric.step,\n agents: metric.nodesRun,\n factsProduced: metric.factsProduced,\n satisfaction: sat,\n satisfactionDelta: satDelta,\n durationMs: metric.durationMs,\n tokensConsumed: metric.tokensConsumed,\n description,\n };\n },\n );\n\n const relaxations = result.relaxations.map((r: RelaxationRecord) => {\n let description: string;\n switch (r.strategy) {\n case \"allow_rerun\":\n description = `Step ${r.step}: Applied relaxation \"${r.label}\" — re-enabled completed nodes for another run.`;\n break;\n case \"inject_facts\":\n description = `Step ${r.step}: Applied relaxation \"${r.label}\" — injected fact values to unblock dependencies.`;\n break;\n case \"accept_partial\":\n description = `Step ${r.step}: Applied relaxation \"${r.label}\" — accepted current facts as partial result.`;\n break;\n case \"alternative_nodes\":\n description = `Step ${r.step}: Applied relaxation \"${r.label}\" — added alternative nodes to the graph.`;\n break;\n case \"custom\":\n description = `Step ${r.step}: Applied relaxation \"${r.label}\" — ran custom recovery logic.`;\n break;\n default:\n description = `Step ${r.step}: Applied relaxation \"${r.label}\" (${r.strategy}).`;\n }\n\n return {\n step: r.step,\n label: r.label,\n strategy: r.strategy,\n description,\n };\n });\n\n const firstSatisfaction =\n result.stepMetrics.length > 0\n ? safeSatisfaction(\n result.stepMetrics[0]!.satisfaction -\n result.stepMetrics[0]!.satisfactionDelta,\n ).toFixed(3)\n : \"0\";\n const lastSatisfaction =\n result.stepMetrics.length > 0\n ? safeSatisfaction(\n result.stepMetrics[result.stepMetrics.length - 1]!.satisfaction,\n ).toFixed(3)\n : \"0\";\n\n const status = result.achieved ? \"Goal achieved\" : \"Goal not achieved\";\n const relaxationNote =\n result.relaxations.length > 0\n ? ` ${result.relaxations.length} relaxation(s) applied.`\n : \"\";\n const errorNote = result.error ? ` Error: ${result.error}` : \"\";\n\n const summary = `${status} in ${result.steps} step(s) (${result.totalTokens.toLocaleString()} tokens, ${result.durationMs}ms). Satisfaction: ${firstSatisfaction} → ${lastSatisfaction}.${relaxationNote}${errorNote}`;\n\n return {\n achieved: result.achieved,\n summary,\n steps,\n relaxations,\n totalTokens: result.totalTokens,\n durationMs: result.durationMs,\n };\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {t}from'@directive-run/core';var n=class extends Error{code;guardrailName;guardrailType;userMessage;agentName;constructor(e){super(e.message,{cause:e.cause}),this.name="GuardrailError",this.code=e.code,this.guardrailName=e.guardrailName,this.guardrailType=e.guardrailType,this.userMessage=e.userMessage??e.message,this.agentName=e.agentName,Object.defineProperty(this,"input",{value:e.input,enumerable:false,writable:false,configurable:false}),Object.defineProperty(this,"data",{value:e.data,enumerable:false,writable:false,configurable:false});}toJSON(){return {name:this.name,code:this.code,message:this.message,guardrailName:this.guardrailName,guardrailType:this.guardrailType,userMessage:this.userMessage,agentName:this.agentName}}};function g(r){return r instanceof n}var a="__agent",o="__approval",s="__conversation",i="__toolCalls",u="__breakpoints";var d="__scratchpad",l={facts:{[a]:t.object(),[o]:t.object(),[s]:t.array(),[i]:t.array(),[u]:t.object()},derivations:{},events:{},requirements:{}};export{n as a,g as b,a as c,o as d,s as e,i as f,u as g,d as h,l as i};//# sourceMappingURL=chunk-UR5BMWEN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-UR5BMWEN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"names":["GuardrailError","options","isGuardrailError","error","AGENT_KEY","APPROVAL_KEY","CONVERSATION_KEY","TOOL_CALLS_KEY","BREAKPOINT_KEY","SCRATCHPAD_KEY","orchestratorBridgeSchema"],"mappings":"oCA8jBO,IAAMA,EAAN,cAA6B,KAAM,CAC/B,IAAA,CACA,aAAA,CACA,aAAA,CACA,WAAA,CAEA,UAGT,WAAA,CAAYC,CAAAA,CAUT,CACD,KAAA,CAAMA,CAAAA,CAAQ,QAAS,CAAE,KAAA,CAAOA,CAAAA,CAAQ,KAAM,CAAC,CAAA,CAC/C,IAAA,CAAK,KAAO,gBAAA,CACZ,IAAA,CAAK,KAAOA,CAAAA,CAAQ,IAAA,CACpB,IAAA,CAAK,aAAA,CAAgBA,EAAQ,aAAA,CAC7B,IAAA,CAAK,cAAgBA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,YAAA,CAAc,EAChB","file":"chunk-UR5BMWEN.js","sourcesContent":["/**\n * Shared types for AI adapter — used by orchestrator, guardrails, helpers, and stack.\n */\n\nimport type {\n ModuleSchema,\n Requirement,\n SchemaType,\n} from \"@directive-run/core\";\nimport { t } from \"@directive-run/core\";\nimport type {\n BreakpointRequest,\n BreakpointState as BreakpointStateFromBreakpoints,\n} from \"./breakpoints.js\";\n\n// ============================================================================\n// Agent Types (LLM-agnostic)\n// ============================================================================\n\n/** Simplified Agent interface */\nexport interface AgentLike {\n name: string;\n instructions?: string;\n model?: string;\n tools?: unknown[];\n}\n\n/** Agent run result */\nexport interface RunResult<T = unknown> {\n output: T;\n messages: Message[];\n toolCalls: ToolCall[];\n totalTokens: number;\n /** Breakdown of input vs output tokens, when available from the provider */\n tokenUsage?: TokenUsage;\n /** True when result was served from semantic cache */\n isCached?: boolean;\n}\n\n/** Breakdown of token usage by input/output */\nexport interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n}\n\n/** Message from agent run */\nexport interface Message {\n role: \"user\" | \"assistant\" | \"tool\" | \"system\";\n content: string;\n toolCallId?: string;\n}\n\n/** Tool call record */\nexport interface ToolCall {\n id: string;\n name: string;\n arguments: string;\n result?: string;\n}\n\n/** Run function type */\nexport type AgentRunner = <T = unknown>(\n agent: AgentLike,\n input: string,\n options?: RunOptions,\n) => Promise<RunResult<T>>;\n\n/** Callback-based streaming run function (e.g. for SSE-based LLM APIs) */\nexport type StreamingCallbackRunner = (\n agent: AgentLike,\n input: string,\n callbacks: {\n onToken?: (token: string) => void;\n onToolStart?: (tool: string, id: string, args: string) => void;\n onToolEnd?: (tool: string, id: string, result: string) => void;\n onMessage?: (message: Message) => void;\n signal?: AbortSignal;\n },\n) => Promise<RunResult<unknown>>;\n\n/** Run options */\nexport interface RunOptions {\n maxTurns?: number;\n signal?: AbortSignal;\n onMessage?: (message: Message) => void;\n onToolCall?: (toolCall: ToolCall) => void | Promise<void>;\n}\n\n// ============================================================================\n// Adapter Lifecycle Hooks\n// ============================================================================\n\n/**\n * Lifecycle hooks for adapter-level observability.\n *\n * Attach to any adapter (runner or streaming runner) to trace, log,\n * or measure individual LLM calls without modifying application code.\n *\n * @example\n * ```typescript\n * const runner = createOpenAIRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * hooks: {\n * onBeforeCall: ({ agent, input }) => console.log(`→ ${agent.name}`, input.slice(0, 50)),\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * metrics.track('llm_call', { durationMs, ...tokenUsage });\n * },\n * onError: ({ error }) => Sentry.captureException(error),\n * },\n * });\n * ```\n */\nexport interface AdapterHooks {\n /** Fires before each LLM API call. */\n onBeforeCall?: (event: {\n agent: AgentLike;\n input: string;\n timestamp: number;\n }) => void;\n\n /** Fires after a successful LLM API call. */\n onAfterCall?: (event: {\n agent: AgentLike;\n input: string;\n output: string;\n totalTokens: number;\n tokenUsage: TokenUsage;\n durationMs: number;\n timestamp: number;\n }) => void;\n\n /** Fires when an LLM API call fails. */\n onError?: (event: {\n agent: AgentLike;\n input: string;\n error: Error;\n durationMs: number;\n timestamp: number;\n }) => void;\n}\n\n// ============================================================================\n// Guardrail Types\n// ============================================================================\n\n/** Guardrail function */\nexport type GuardrailFn<T = unknown> = (\n data: T,\n context: GuardrailContext,\n) => GuardrailResult | Promise<GuardrailResult>;\n\n/** Guardrail context */\nexport interface GuardrailContext {\n agentName: string;\n input: string;\n facts: Record<string, unknown>;\n}\n\n/** Guardrail result */\nexport interface GuardrailResult {\n passed: boolean;\n reason?: string;\n transformed?: unknown;\n}\n\n/** Input guardrail data */\nexport interface InputGuardrailData {\n input: string;\n agentName: string;\n}\n\n/** Output guardrail data */\nexport interface OutputGuardrailData {\n output: unknown;\n agentName: string;\n input: string;\n messages: Message[];\n}\n\n/** Tool call guardrail data */\nexport interface ToolCallGuardrailData {\n toolCall: ToolCall;\n agentName: string;\n input: string;\n}\n\n/** Retry configuration for guardrails */\nexport interface GuardrailRetryConfig {\n /** Total attempts (1 = no retries, 2 = one retry, etc.). @default 1 */\n attempts?: number;\n /** @default \"exponential\" */\n backoff?: \"exponential\" | \"linear\" | \"fixed\";\n /** @default 100 */\n baseDelayMs?: number;\n /** @default 5000 */\n maxDelayMs?: number;\n}\n\n/** Named guardrail for better debugging */\nexport interface NamedGuardrail<T = unknown> {\n name: string;\n fn: GuardrailFn<T>;\n /** @default true */\n critical?: boolean;\n retry?: GuardrailRetryConfig;\n}\n\n/** Guardrails configuration */\nexport interface GuardrailsConfig {\n input?: Array<\n GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>\n >;\n output?: Array<\n GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>\n >;\n toolCall?: Array<\n GuardrailFn<ToolCallGuardrailData> | NamedGuardrail<ToolCallGuardrailData>\n >;\n}\n\n// ============================================================================\n// Retry Configuration\n// ============================================================================\n\n/** Retry configuration for agent runs */\nexport interface AgentRetryConfig {\n /** @default 1 */\n attempts?: number;\n /** @default \"exponential\" */\n backoff?: \"exponential\" | \"linear\" | \"fixed\";\n /** @default 1000 */\n baseDelayMs?: number;\n /** @default 30000 */\n maxDelayMs?: number;\n isRetryable?: (error: Error) => boolean;\n onRetry?: (attempt: number, error: Error, delayMs: number) => void;\n}\n\n// ============================================================================\n// Orchestrator State Types\n// ============================================================================\n\n/** Agent state in facts */\nexport interface AgentState {\n status: \"idle\" | \"running\" | \"paused\" | \"completed\" | \"error\";\n currentAgent: string | null;\n input: string | null;\n output: unknown | null;\n error: string | null;\n tokenUsage: number;\n turnCount: number;\n startedAt: number | null;\n completedAt: number | null;\n}\n\n/** Approval state */\nexport interface ApprovalState {\n pending: ApprovalRequest[];\n approved: string[];\n rejected: RejectedRequest[];\n}\n\n/** Rejected request with tracking information */\nexport interface RejectedRequest {\n id: string;\n reason?: string;\n rejectedAt: number;\n}\n\n/** Approval request */\nexport interface ApprovalRequest {\n id: string;\n type: \"tool_call\" | \"output\" | \"handoff\";\n agentName: string;\n description: string;\n data: unknown;\n requestedAt: number;\n}\n\n/** Combined orchestrator state */\nexport interface OrchestratorState {\n agent: AgentState;\n approval: ApprovalState;\n conversation: Message[];\n toolCalls: ToolCall[];\n}\n\n// ============================================================================\n// Orchestrator Config Types\n// ============================================================================\n\n/** Constraint for orchestrator */\nexport interface OrchestratorConstraint<F extends Record<string, unknown>> {\n when: (facts: F & OrchestratorState) => boolean | Promise<boolean>;\n require: Requirement | ((facts: F & OrchestratorState) => Requirement);\n priority?: number;\n}\n\n/** Resolver context for orchestrator */\nexport interface OrchestratorResolverContext<\n F extends Record<string, unknown>,\n> {\n facts: F & OrchestratorState;\n runAgent: <T>(\n agent: AgentLike,\n input: string,\n options?: RunOptions,\n ) => Promise<RunResult<T>>;\n signal: AbortSignal;\n}\n\n/** Resolver for orchestrator */\nexport interface OrchestratorResolver<\n F extends Record<string, unknown>,\n R extends Requirement = Requirement,\n> {\n requirement: (req: Requirement) => req is R;\n key?: (req: R) => string;\n resolve: (\n req: R,\n context: OrchestratorResolverContext<F>,\n ) => void | Promise<void>;\n}\n\n/** Lifecycle hooks for observability */\nexport interface OrchestratorLifecycleHooks {\n onAgentStart?: (event: {\n agentName: string;\n input: string;\n timestamp: number;\n }) => void;\n onAgentComplete?: (event: {\n agentName: string;\n input: string;\n output: unknown;\n tokenUsage: number;\n durationMs: number;\n timestamp: number;\n }) => void;\n onAgentError?: (event: {\n agentName: string;\n input: string;\n error: Error;\n durationMs: number;\n timestamp: number;\n }) => void;\n onGuardrailCheck?: (event: {\n agentId?: string;\n guardrailName: string;\n guardrailType: \"input\" | \"output\" | \"toolCall\";\n passed: boolean;\n reason?: string;\n durationMs: number;\n timestamp: number;\n }) => void;\n onAgentRetry?: (event: {\n agentName: string;\n input: string;\n attempt: number;\n error: Error;\n delayMs: number;\n timestamp: number;\n }) => void;\n /** Called when a breakpoint is hit and waiting for resolution. */\n onBreakpoint?: (request: BreakpointRequest) => void;\n}\n\n/** Lifecycle hooks for multi-agent orchestrator observability */\nexport interface MultiAgentLifecycleHooks {\n onAgentStart?: (event: {\n agentId: string;\n agentName: string;\n input: string;\n timestamp: number;\n }) => void;\n onAgentComplete?: (event: {\n agentId: string;\n agentName: string;\n input: string;\n output: unknown;\n tokenUsage: number;\n durationMs: number;\n timestamp: number;\n }) => void;\n onAgentError?: (event: {\n agentId: string;\n agentName: string;\n input: string;\n error: Error;\n durationMs: number;\n timestamp: number;\n }) => void;\n onGuardrailCheck?: (event: {\n agentId: string;\n guardrailName: string;\n guardrailType: \"input\" | \"output\" | \"toolCall\";\n passed: boolean;\n reason?: string;\n durationMs: number;\n timestamp: number;\n }) => void;\n onAgentRetry?: (event: {\n agentId: string;\n agentName: string;\n input: string;\n attempt: number;\n error: Error;\n delayMs: number;\n timestamp: number;\n }) => void;\n onHandoff?: (request: {\n id: string;\n fromAgent: string;\n toAgent: string;\n input: string;\n requestedAt: number;\n }) => void;\n onHandoffComplete?: (result: {\n request: { id: string; fromAgent: string; toAgent: string };\n completedAt: number;\n }) => void;\n onPatternStart?: (event: {\n patternId: string;\n patternType:\n | \"parallel\"\n | \"sequential\"\n | \"supervisor\"\n | \"dag\"\n | \"reflect\"\n | \"race\"\n | \"debate\"\n | \"goal\";\n input: string;\n timestamp: number;\n }) => void;\n onPatternComplete?: (event: {\n patternId: string;\n patternType:\n | \"parallel\"\n | \"sequential\"\n | \"supervisor\"\n | \"dag\"\n | \"reflect\"\n | \"race\"\n | \"debate\"\n | \"goal\";\n durationMs: number;\n timestamp: number;\n error?: Error;\n }) => void;\n onDagNodeStart?: (event: {\n patternId: string;\n nodeId: string;\n agentId: string;\n nodeType: \"agent\" | \"task\";\n timestamp: number;\n }) => void;\n onDagNodeComplete?: (event: {\n patternId: string;\n nodeId: string;\n agentId: string;\n nodeType: \"agent\" | \"task\";\n durationMs: number;\n timestamp: number;\n }) => void;\n onDagNodeError?: (event: {\n patternId: string;\n nodeId: string;\n agentId: string;\n nodeType: \"agent\" | \"task\";\n error: Error;\n durationMs: number;\n timestamp: number;\n }) => void;\n onDagNodeSkipped?: (event: {\n patternId: string;\n nodeId: string;\n agentId: string;\n nodeType: \"agent\" | \"task\";\n reason: string;\n timestamp: number;\n }) => void;\n onHealthChange?: (event: {\n agentId: string;\n oldScore: number;\n newScore: number;\n timestamp: number;\n }) => void;\n onReroute?: (event: RerouteEvent) => void;\n /** Called when a breakpoint is hit and waiting for resolution. */\n onBreakpoint?: (request: BreakpointRequest) => void;\n /** Called when a cross-agent derivation value updates */\n onDerivationUpdate?: (event: {\n derivationId: string;\n value: unknown;\n timestamp: number;\n }) => void;\n /** Called when a cross-agent derivation throws an error */\n onDerivationError?: (event: {\n derivationId: string;\n error: Error;\n timestamp: number;\n }) => void;\n /** Called when scratchpad values are updated */\n onScratchpadUpdate?: (event: { keys: string[]; timestamp: number }) => void;\n /** Called when a task starts executing */\n onTaskStart?: (event: {\n patternId: string;\n taskId: string;\n label: string;\n timestamp: number;\n }) => void;\n /** Called when a task completes successfully */\n onTaskComplete?: (event: {\n patternId: string;\n taskId: string;\n label: string;\n durationMs: number;\n timestamp: number;\n }) => void;\n /** Called when a task fails */\n onTaskError?: (event: {\n patternId: string;\n taskId: string;\n label: string;\n error: Error;\n durationMs: number;\n timestamp: number;\n }) => void;\n /** Called when a task reports progress */\n onTaskProgress?: (event: {\n patternId: string;\n taskId: string;\n label: string;\n percent: number;\n message?: string;\n timestamp: number;\n }) => void;\n /** Called when a pattern checkpoint is saved */\n onCheckpointSave?: (event: {\n checkpointId: string;\n patternType: string;\n step: number;\n timestamp: number;\n }) => void;\n /** Called when a checkpoint save fails */\n onCheckpointError?: (event: {\n patternType: string;\n step: number;\n error: Error;\n timestamp: number;\n }) => void;\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/** Error codes for guardrail errors */\nexport type GuardrailErrorCode =\n | \"INPUT_GUARDRAIL_FAILED\"\n | \"OUTPUT_GUARDRAIL_FAILED\"\n | \"TOOL_CALL_GUARDRAIL_FAILED\"\n | \"APPROVAL_REJECTED\"\n | \"BUDGET_EXCEEDED\"\n | \"RATE_LIMIT_EXCEEDED\"\n | \"AGENT_ERROR\";\n\n/**\n * Structured error for guardrail failures.\n *\n * **Security:** The `input` and `data` properties are non-enumerable to prevent\n * accidental leakage of sensitive data via JSON.stringify or console.log.\n */\nexport class GuardrailError extends Error {\n readonly code: GuardrailErrorCode;\n readonly guardrailName: string;\n readonly guardrailType: \"input\" | \"output\" | \"toolCall\";\n readonly userMessage: string;\n declare readonly data: unknown;\n readonly agentName: string;\n declare readonly input: string;\n\n constructor(options: {\n code: GuardrailErrorCode;\n message: string;\n guardrailName: string;\n guardrailType: \"input\" | \"output\" | \"toolCall\";\n userMessage?: string;\n data?: unknown;\n agentName: string;\n input: string;\n cause?: Error;\n }) {\n super(options.message, { cause: options.cause });\n this.name = \"GuardrailError\";\n this.code = options.code;\n this.guardrailName = options.guardrailName;\n this.guardrailType = options.guardrailType;\n this.userMessage = options.userMessage ?? options.message;\n this.agentName = options.agentName;\n\n Object.defineProperty(this, \"input\", {\n value: options.input,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(this, \"data\", {\n value: options.data,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n guardrailName: this.guardrailName,\n guardrailType: this.guardrailType,\n userMessage: this.userMessage,\n agentName: this.agentName,\n };\n }\n}\n\n/** Check if an error is a GuardrailError. */\nexport function isGuardrailError(error: unknown): error is GuardrailError {\n return error instanceof GuardrailError;\n}\n\n// ============================================================================\n// Schema Validation Types (used by built-in guardrails)\n// ============================================================================\n\n/** Schema validation result */\nexport interface SchemaValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/** Schema validator function type */\nexport type SchemaValidator<_T = unknown> = (\n value: unknown,\n) => SchemaValidationResult | boolean;\n\n// ============================================================================\n// Bridge Schema Constants\n// ============================================================================\n\nexport const AGENT_KEY = \"__agent\" as const;\nexport const APPROVAL_KEY = \"__approval\" as const;\nexport const CONVERSATION_KEY = \"__conversation\" as const;\nexport const TOOL_CALLS_KEY = \"__toolCalls\" as const;\nexport const BREAKPOINT_KEY = \"__breakpoints\" as const;\n\n// ============================================================================\n// DAG Execution Types (Multi-Agent)\n// ============================================================================\n\n/** Status of a DAG node during execution */\nexport type DagNodeStatus =\n | \"pending\"\n | \"ready\"\n | \"running\"\n | \"completed\"\n | \"error\"\n | \"skipped\";\n\n/** Execution context available to DAG node callbacks */\nexport interface DagExecutionContext {\n /** Original input to the DAG */\n input: string;\n /** Outputs keyed by node ID (populated as nodes complete) */\n outputs: Record<string, unknown>;\n /** Statuses keyed by node ID */\n statuses: Record<string, DagNodeStatus>;\n /** Error messages keyed by node ID */\n errors: Record<string, string>;\n /** Full RunResult keyed by node ID */\n results: Record<string, RunResult<unknown>>;\n}\n\n/** A node in a DAG execution pattern */\nexport interface DagNode {\n /** Registered handler ID (agent or task) to run for this node */\n handler: string;\n /** Upstream node IDs this node depends on */\n deps?: string[];\n /** Conditional edge — evaluated when deps are met. @default unconditional */\n when?: (context: DagExecutionContext) => boolean;\n /** Build input string for this node's agent. @default JSON.stringify(upstream outputs) */\n transform?: (context: DagExecutionContext) => string;\n /** Per-node timeout (ms) */\n timeout?: number;\n /** Tiebreaker when multiple nodes are ready (higher = first). @default 0 */\n priority?: number;\n}\n\n/** DAG execution pattern — nodes are agents, edges are reactive conditions */\nexport interface DagPattern<T = unknown> {\n type: \"dag\";\n /** Nodes keyed by node ID */\n nodes: Record<string, DagNode>;\n /** Merge all node outputs into the final result */\n merge: (context: DagExecutionContext) => T | Promise<T>;\n /** Overall DAG timeout (ms) */\n timeout?: number;\n /** Maximum nodes running concurrently. @default Infinity. Consider setting this to avoid API rate limits. */\n maxConcurrent?: number;\n /** Error handling strategy. @default \"fail\" */\n onNodeError?: \"fail\" | \"skip-downstream\" | \"continue\";\n /** Checkpoint configuration for mid-execution fault tolerance */\n checkpoint?: PatternCheckpointConfig;\n}\n\n// ============================================================================\n// Debug Configuration\n// ============================================================================\n\n/** Debug configuration for orchestrators */\nexport interface OrchestratorDebugConfig {\n verboseTimeline?: boolean;\n}\n\n// ============================================================================\n// Debug Timeline Types\n// ============================================================================\n\n/** All debug event types */\nexport type DebugEventType =\n | \"agent_start\"\n | \"agent_complete\"\n | \"agent_error\"\n | \"agent_retry\"\n | \"guardrail_check\"\n | \"constraint_evaluate\"\n | \"resolver_start\"\n | \"resolver_complete\"\n | \"resolver_error\"\n | \"approval_request\"\n | \"approval_response\"\n | \"handoff_start\"\n | \"handoff_complete\"\n | \"pattern_start\"\n | \"pattern_complete\"\n | \"dag_node_update\"\n | \"breakpoint_hit\"\n | \"breakpoint_resumed\"\n | \"derivation_update\"\n | \"scratchpad_update\"\n | \"reflection_iteration\"\n | \"race_start\"\n | \"race_winner\"\n | \"race_cancelled\"\n | \"debate_round\"\n | \"reroute\"\n | \"checkpoint_save\"\n | \"checkpoint_restore\"\n | \"task_start\"\n | \"task_complete\"\n | \"task_error\"\n | \"task_progress\"\n | \"goal_step\";\n\n/** Base debug event */\nexport interface DebugEventBase {\n id: number;\n type: DebugEventType;\n timestamp: number;\n agentId?: string;\n snapshotId: number | null;\n}\n\n/** Agent start event */\nexport interface AgentStartEvent extends DebugEventBase {\n type: \"agent_start\";\n agentId: string;\n inputLength: number;\n /** Truncated input text (max 5000 chars) */\n input?: string;\n}\n\n/** Agent complete event */\nexport interface AgentCompleteEvent extends DebugEventBase {\n type: \"agent_complete\";\n agentId: string;\n outputLength: number;\n totalTokens: number;\n inputTokens: number;\n outputTokens: number;\n durationMs: number;\n modelId?: string;\n /** Truncated output text (max 5000 chars) */\n output?: string;\n}\n\n/** Agent error event */\nexport interface AgentErrorEvent extends DebugEventBase {\n type: \"agent_error\";\n agentId: string;\n errorMessage: string;\n durationMs: number;\n}\n\n/** Agent retry event */\nexport interface AgentRetryEvent extends DebugEventBase {\n type: \"agent_retry\";\n agentId: string;\n attempt: number;\n errorMessage: string;\n delayMs: number;\n}\n\n/** Guardrail check event */\nexport interface GuardrailCheckEvent extends DebugEventBase {\n type: \"guardrail_check\";\n guardrailName: string;\n guardrailType: \"input\" | \"output\" | \"toolCall\";\n passed: boolean;\n reason?: string;\n durationMs: number;\n}\n\n/** Constraint evaluate event */\nexport interface ConstraintEvaluateEvent extends DebugEventBase {\n type: \"constraint_evaluate\";\n constraintId: string;\n fired: boolean;\n}\n\n/** Resolver start event */\nexport interface ResolverStartEvent extends DebugEventBase {\n type: \"resolver_start\";\n resolverId: string;\n requirementType: string;\n}\n\n/** Resolver complete event */\nexport interface ResolverCompleteEvent extends DebugEventBase {\n type: \"resolver_complete\";\n resolverId: string;\n durationMs: number;\n}\n\n/** Resolver error event */\nexport interface ResolverErrorEvent extends DebugEventBase {\n type: \"resolver_error\";\n resolverId: string;\n errorMessage: string;\n durationMs: number;\n}\n\n/** Approval request event */\nexport interface ApprovalRequestEvent extends DebugEventBase {\n type: \"approval_request\";\n requestId: string;\n approvalType: \"tool_call\" | \"output\" | \"handoff\";\n}\n\n/** Approval response event */\nexport interface ApprovalResponseEvent extends DebugEventBase {\n type: \"approval_response\";\n requestId: string;\n approved: boolean;\n reason?: string;\n}\n\n/** Handoff start event */\nexport interface HandoffStartEvent extends DebugEventBase {\n type: \"handoff_start\";\n fromAgent: string;\n toAgent: string;\n}\n\n/** Handoff complete event */\nexport interface HandoffCompleteEvent extends DebugEventBase {\n type: \"handoff_complete\";\n fromAgent: string;\n toAgent: string;\n durationMs: number;\n}\n\n/** Pattern start event */\nexport interface PatternStartEvent extends DebugEventBase {\n type: \"pattern_start\";\n patternId: string;\n patternType:\n | \"parallel\"\n | \"sequential\"\n | \"supervisor\"\n | \"dag\"\n | \"reflect\"\n | \"race\"\n | \"debate\"\n | \"goal\";\n /** All handler IDs in this pattern (agents + tasks) */\n handlers?: string[];\n /** Which handler IDs are tasks (rest are agents) */\n taskIds?: string[];\n}\n\n/** Pattern complete event */\nexport interface PatternCompleteEvent extends DebugEventBase {\n type: \"pattern_complete\";\n patternId: string;\n patternType:\n | \"parallel\"\n | \"sequential\"\n | \"supervisor\"\n | \"dag\"\n | \"reflect\"\n | \"race\"\n | \"debate\"\n | \"goal\";\n durationMs: number;\n error?: string;\n}\n\n/** DAG node update event */\nexport interface DagNodeUpdateEvent extends DebugEventBase {\n type: \"dag_node_update\";\n nodeId: string;\n status: DagNodeStatus;\n deps?: string[];\n}\n\n/** Breakpoint hit event */\nexport interface BreakpointHitEvent extends DebugEventBase {\n type: \"breakpoint_hit\";\n breakpointId: string;\n breakpointType: string;\n label?: string;\n}\n\n/** Breakpoint resumed event */\nexport interface BreakpointResumedEvent extends DebugEventBase {\n type: \"breakpoint_resumed\";\n breakpointId: string;\n modified: boolean;\n skipped: boolean;\n}\n\n/** Derivation update event */\nexport interface DerivationUpdateEvent extends DebugEventBase {\n type: \"derivation_update\";\n derivationId: string;\n valueType: string;\n}\n\n/** Scratchpad update event */\nexport interface ScratchpadUpdateEvent extends DebugEventBase {\n type: \"scratchpad_update\";\n keys: string[];\n}\n\n/** Reflection iteration event */\nexport interface ReflectionIterationEvent extends DebugEventBase {\n type: \"reflection_iteration\";\n iteration: number;\n passed: boolean;\n score?: number;\n durationMs: number;\n producerTokens: number;\n evaluatorTokens: number;\n}\n\n/** Race start event */\nexport interface RaceStartEvent extends DebugEventBase {\n type: \"race_start\";\n patternId: string;\n agents: string[];\n}\n\n/** Race winner event */\nexport interface RaceWinnerEvent extends DebugEventBase {\n type: \"race_winner\";\n patternId: string;\n winnerId: string;\n durationMs: number;\n}\n\n/** Race cancelled event */\nexport interface RaceCancelledEvent extends DebugEventBase {\n type: \"race_cancelled\";\n patternId: string;\n cancelledIds: string[];\n reason: \"winner_found\" | \"timeout\" | \"all_failed\";\n}\n\n/** Debate round event — emitted after each round's judgement */\nexport interface DebateRoundEvent extends DebugEventBase {\n type: \"debate_round\";\n patternId: string;\n round: number;\n totalRounds: number;\n winnerId: string;\n score?: number;\n agentCount: number;\n}\n\n/** Reroute debug event recorded when self-healing reroutes to an alternate agent */\nexport interface RerouteDebugEvent extends DebugEventBase {\n type: \"reroute\";\n agentId: string;\n from: string;\n to: string;\n reason: string;\n}\n\n/** Checkpoint save event */\nexport interface CheckpointSaveEvent extends DebugEventBase {\n type: \"checkpoint_save\";\n checkpointId: string;\n patternType: string;\n step: number;\n}\n\n/** Checkpoint restore event */\nexport interface CheckpointRestoreEvent extends DebugEventBase {\n type: \"checkpoint_restore\";\n checkpointId: string;\n patternType: string;\n step: number;\n}\n\n/** Task start event */\nexport interface TaskStartEvent extends DebugEventBase {\n type: \"task_start\";\n taskId: string;\n label: string;\n description?: string;\n inputLength: number;\n}\n\n/** Task complete event */\nexport interface TaskCompleteEvent extends DebugEventBase {\n type: \"task_complete\";\n taskId: string;\n label: string;\n durationMs: number;\n}\n\n/** Task error event */\nexport interface TaskErrorEvent extends DebugEventBase {\n type: \"task_error\";\n taskId: string;\n label: string;\n error: string;\n durationMs: number;\n attempt?: number;\n}\n\n/** Task progress event */\nexport interface TaskProgressEvent extends DebugEventBase {\n type: \"task_progress\";\n taskId: string;\n label: string;\n percent: number;\n message?: string;\n}\n\n/** Goal step event — emitted for each agent invocation within a goal step */\nexport interface GoalStepEvent extends DebugEventBase {\n type: \"goal_step\";\n agentId: string;\n step: number;\n nodeId: string;\n satisfaction: number;\n satisfactionDelta: number;\n}\n\n/** Union of all debug event types */\nexport type DebugEvent =\n | AgentStartEvent\n | AgentCompleteEvent\n | AgentErrorEvent\n | AgentRetryEvent\n | GuardrailCheckEvent\n | ConstraintEvaluateEvent\n | ResolverStartEvent\n | ResolverCompleteEvent\n | ResolverErrorEvent\n | ApprovalRequestEvent\n | ApprovalResponseEvent\n | HandoffStartEvent\n | HandoffCompleteEvent\n | PatternStartEvent\n | PatternCompleteEvent\n | DagNodeUpdateEvent\n | BreakpointHitEvent\n | BreakpointResumedEvent\n | DerivationUpdateEvent\n | ScratchpadUpdateEvent\n | ReflectionIterationEvent\n | RaceStartEvent\n | RaceWinnerEvent\n | RaceCancelledEvent\n | DebateRoundEvent\n | RerouteDebugEvent\n | CheckpointSaveEvent\n | CheckpointRestoreEvent\n | TaskStartEvent\n | TaskCompleteEvent\n | TaskErrorEvent\n | TaskProgressEvent\n | GoalStepEvent;\n\n// ============================================================================\n// Self-Healing Types\n// ============================================================================\n\n/** Health state for an agent stored in facts */\nexport interface AgentHealthState {\n circuitState: \"CLOSED\" | \"OPEN\" | \"HALF_OPEN\";\n healthScore: number;\n lastUpdated: number;\n}\n\n/** Reroute event fired when an agent is rerouted */\nexport interface RerouteEvent {\n originalAgent: string;\n reroutedTo: string;\n reason: string;\n timestamp: number;\n}\n\n/** Health monitor configuration */\nexport interface HealthMonitorConfig {\n /** Rolling window for metrics (ms). @default 60000 */\n windowMs?: number;\n /** Weights for health score computation (must sum to ~1.0) */\n weights?: {\n /** Weight for success rate (0-1). @default 0.5 */\n successRate?: number;\n /** Weight for latency (0-1). @default 0.3 */\n latency?: number;\n /** Weight for circuit state (0-1). @default 0.2 */\n circuitState?: number;\n };\n /** Max latency considered \"normal\" (ms). @default 5000 */\n maxNormalLatencyMs?: number;\n /** Max events per agent before FIFO eviction. @default 1000 */\n maxEventsPerAgent?: number;\n}\n\n/** Self-healing configuration for single-agent orchestrator */\nexport interface SelfHealingConfig {\n /** Fallback runners to try in order when primary CB is open */\n fallbackRunners?: AgentRunner[];\n /** Fallback agent to try when all runners fail */\n fallbackAgent?: AgentLike;\n /** Circuit breaker config for primary runner */\n circuitBreaker?: AgentCircuitBreakerConfig;\n /** Health score below which to trigger reroute. @default 30 */\n healthThreshold?: number;\n /** Behavior when all fallbacks exhausted */\n degradation?: \"reject\" | \"fallback-response\";\n /** Static response to return when degradation is \"fallback-response\" */\n fallbackResponse?: unknown;\n /** Callback when reroute occurs */\n onReroute?: (event: RerouteEvent) => void;\n}\n\n/** Self-healing configuration for multi-agent orchestrator */\nexport interface MultiAgentSelfHealingConfig {\n /** Default circuit breaker config for agents without their own */\n circuitBreakerDefaults?: AgentCircuitBreakerConfig;\n /** Health score below which to trigger reroute. @default 30 */\n healthThreshold?: number;\n /** Explicit equivalency groups (group name → agent IDs) */\n equivalencyGroups?: Record<string, string[]>;\n /** Use capability matching for implicit equivalency. @default true */\n useCapabilities?: boolean;\n /** Strategy for selecting equivalent agent */\n selectionStrategy?: \"healthiest\" | \"round-robin\";\n /** Behavior when all equivalents are down */\n degradation?: \"reject\" | \"fallback-response\";\n /** Static response for \"fallback-response\" degradation */\n fallbackResponse?: unknown;\n /** Callback when reroute occurs */\n onReroute?: (event: RerouteEvent) => void;\n /** Callback when agent health changes */\n onHealthChange?: (event: {\n agentId: string;\n oldScore: number;\n newScore: number;\n }) => void;\n /** Health monitor configuration */\n healthMonitor?: HealthMonitorConfig;\n}\n\n/** Circuit breaker config for AI agent self-healing (simplified subset of core CircuitBreakerConfig) */\nexport interface AgentCircuitBreakerConfig {\n /** Number of failures before opening. @default 5 */\n failureThreshold?: number;\n /** Time before trying half-open (ms). @default 30000 */\n resetTimeoutMs?: number;\n /** Successes needed to close from half-open. @default 2 */\n halfOpenSuccesses?: number;\n /** State change callback */\n onStateChange?: (from: string, to: string) => void;\n}\n\n/** Internal key for health state in coordinator facts */\nexport const HEALTH_KEY = \"__agentHealth\" as const;\n\n/** Breakpoint state stored in bridge schema — canonical definition in breakpoints.ts */\nexport type BreakpointState = BreakpointStateFromBreakpoints;\n\n// ============================================================================\n// Cross-Agent Derivation Types\n// ============================================================================\n\n/** Snapshot of all agent states for cross-agent derivations */\nexport interface CrossAgentSnapshot {\n agents: Record<\n string,\n {\n status: \"idle\" | \"running\" | \"completed\" | \"error\";\n lastInput?: string;\n lastOutput?: unknown;\n lastError?: string;\n runCount: number;\n totalTokens: number;\n }\n >;\n coordinator: { globalTokens: number; status: string };\n scratchpad?: Record<string, unknown>;\n}\n\n/** Function that computes a derived value from a cross-agent snapshot */\nexport type CrossAgentDerivationFn<T = unknown> = (\n snapshot: CrossAgentSnapshot,\n) => T;\n\n// ============================================================================\n// Shared Scratchpad Types\n// ============================================================================\n\n/** Internal key for scratchpad fact on coordinator module */\nexport const SCRATCHPAD_KEY = \"__scratchpad\" as const;\n\n/** Shared scratchpad interface for multi-agent collaboration */\nexport interface Scratchpad<\n T extends Record<string, unknown> = Record<string, unknown>,\n> {\n get<K extends keyof T>(key: K): T[K];\n set<K extends keyof T>(key: K, value: T[K]): void;\n /** Check if a key exists in the scratchpad */\n has<K extends keyof T>(key: K): boolean;\n /** Delete a key from the scratchpad */\n delete<K extends keyof T>(key: K): void;\n update(values: Partial<T>): void;\n getAll(): T;\n subscribe(\n keys: (keyof T)[],\n callback: (key: keyof T, value: unknown) => void,\n ): () => void;\n onChange(callback: (key: string, value: unknown) => void): () => void;\n reset(): void;\n}\n\n// ============================================================================\n// Goal Pattern Types\n// ============================================================================\n\n/** A node in a goal execution pattern */\nexport interface GoalNode {\n /** Handler ID — agent or task registered on the orchestrator */\n handler: string;\n /** Fact keys this node can produce */\n produces: string[];\n /** Fact keys this node needs (must be satisfied before running) */\n requires?: string[];\n /** Allow re-run if input facts change after completion */\n allowRerun?: boolean;\n /** Priority for selection when multiple nodes are ready. Higher = first */\n priority?: number;\n /** Build the input string from current facts */\n buildInput?: (facts: Record<string, unknown>) => string;\n /** Extract output facts from the agent's result */\n extractOutput?: (result: RunResult<unknown>) => Record<string, unknown>;\n}\n\n/** Goal step metrics */\nexport interface GoalStepMetrics {\n step: number;\n durationMs: number;\n nodesRun: string[];\n factsProduced: string[];\n satisfaction: number;\n satisfactionDelta: number;\n tokensConsumed: number;\n}\n\n/** Goal progress metrics */\nexport interface GoalMetrics {\n satisfaction: number;\n progressRate: number;\n estimatedStepsRemaining: number | null;\n decelerating: boolean;\n}\n\n/** Agent selection strategy for goal pattern */\nexport interface AgentSelectionStrategy {\n /**\n * Select which ready agents to run this step.\n *\n * @param readyAgents - Agent IDs whose `requires` are satisfied\n * @param metrics - Per-agent performance metrics (runs, avgSatisfactionDelta, tokens)\n * @param goalMetrics - Global goal progress metrics. Built-in strategies use per-agent\n * metrics only; this parameter enables custom strategies that account for overall goal\n * progress (e.g., switching to cheaper agents as satisfaction approaches 1.0).\n */\n select: (\n readyAgents: string[],\n metrics: Record<\n string,\n { runs: number; avgSatisfactionDelta: number; tokens: number }\n >,\n goalMetrics: GoalMetrics,\n ) => string[];\n}\n\n/** Relaxation context passed to custom relaxation strategies */\nexport interface RelaxationContext {\n step: number;\n facts: Record<string, unknown>;\n metrics: GoalMetrics;\n completedNodes: Set<string>;\n failedNodes: Map<string, number>;\n}\n\n/** Relaxation strategy for when goal pursuit stalls */\nexport type RelaxationStrategy =\n | { type: \"allow_rerun\"; nodes: string[] }\n | { type: \"alternative_nodes\"; nodes: GoalNode[] }\n | { type: \"inject_facts\"; facts: Record<string, unknown> }\n | { type: \"accept_partial\" }\n | {\n type: \"custom\";\n apply: (context: RelaxationContext) => void | Promise<void>;\n };\n\n/** Relaxation tier — progressively applied when goal pursuit stalls */\nexport interface RelaxationTier {\n label: string;\n /** Steps of no progress before applying. @default 3 */\n afterStallSteps?: number;\n strategy: RelaxationStrategy;\n}\n\n/** Record of a relaxation event */\nexport interface RelaxationRecord {\n step: number;\n tierIndex: number;\n label: string;\n strategy: RelaxationStrategy[\"type\"];\n}\n\n/** Goal execution pattern — declare desired state, let the runtime resolve */\nexport interface GoalPattern<T = unknown> {\n type: \"goal\";\n /** Nodes with produces/requires declarations */\n nodes: Record<string, GoalNode>;\n /** Goal condition — when this returns true, the goal is achieved */\n when: (facts: Record<string, unknown>) => boolean;\n /** Quantitative satisfaction: 0.0 to 1.0. Enables progress tracking.\n * If omitted, binary: 0.0 when when() is false, 1.0 when true. */\n satisfaction?: (facts: Record<string, unknown>) => number;\n /** Max goal steps. @default 50 */\n maxSteps?: number;\n /** Extract final result from achieved facts */\n extract?: (facts: Record<string, unknown>) => T;\n /** Timeout in ms. @default 300000 */\n timeout?: number;\n /** Abort signal */\n signal?: AbortSignal;\n /** Agent selection strategy. @default \"all-ready\" */\n selectionStrategy?: AgentSelectionStrategy;\n /** Relaxation tiers — progressively applied when goal pursuit stalls */\n relaxation?: RelaxationTier[];\n /** Lifecycle hooks */\n onStep?: (\n step: number,\n facts: Record<string, unknown>,\n readyAgents: string[],\n ) => void;\n onStall?: (step: number, metrics: GoalMetrics) => void;\n /** Checkpoint configuration for mid-execution fault tolerance */\n checkpoint?: PatternCheckpointConfig;\n}\n\n/** Result of a goal pattern execution */\nexport interface GoalResult<T = unknown> {\n /** Whether the when() condition was satisfied */\n achieved: boolean;\n /** Final value (from extract, or raw facts) */\n result: T;\n /** Final facts state */\n facts: Record<string, unknown>;\n /** Nodes that ran, in execution order */\n executionOrder: string[];\n /** Per-node results */\n nodeResults: Record<string, RunResult<unknown>>;\n /** Total goal steps taken */\n steps: number;\n /** Total tokens consumed */\n totalTokens: number;\n /** Total duration (ms) */\n durationMs: number;\n /** Per-step metrics (satisfaction, nodes run, etc.) */\n stepMetrics: GoalStepMetrics[];\n /** Relaxation events applied */\n relaxations: RelaxationRecord[];\n /** Error message if goal was not achieved */\n error?: string;\n}\n\n// ============================================================================\n// Pattern Checkpoint Types (Universal)\n// ============================================================================\n\n/** Universal checkpoint configuration for all execution patterns */\nexport interface PatternCheckpointConfig {\n /** Save a checkpoint every N steps/rounds/iterations. @default 5 */\n everyN?: number;\n /** Checkpoint store. Uses the orchestrator's store if not provided. */\n store?: import(\"./checkpoint.js\").CheckpointStore;\n /** Label prefix for checkpoints. @default pattern type name */\n labelPrefix?: string;\n /** Conditional: only save when this returns true */\n when?: (context: CheckpointContext) => boolean;\n}\n\n/** Context passed to conditional checkpoint predicates */\nexport interface CheckpointContext {\n /** Current step/round/iteration number */\n step: number;\n /** Pattern type identifier */\n patternType: string;\n /** Pattern-specific facts (goal only) */\n facts?: Record<string, unknown>;\n /** Satisfaction score 0-1 (goal only) */\n satisfaction?: number;\n}\n\nexport type GoalCheckpointConfig = PatternCheckpointConfig;\n\n// ---- Common checkpoint state fields ----\n\n/** Common fields present on all pattern checkpoint states */\nexport interface PatternCheckpointBase {\n /** Checkpoint format version */\n version: 1;\n /** Unique ID */\n id: string;\n /** ISO timestamp */\n createdAt: string;\n /** User label */\n label?: string;\n /** Pattern ID */\n patternId: string;\n /** Total expected steps/rounds/iterations (null for unbounded) */\n stepsTotal?: number | null;\n}\n\n// ---- Per-pattern checkpoint states ----\n\n/** Checkpoint state for sequential pattern */\nexport interface SequentialCheckpointState extends PatternCheckpointBase {\n type: \"sequential\";\n /** Next agent index to run */\n step: number;\n /** Current input for the next agent */\n currentInput: string;\n /** Results collected so far (output + tokens) */\n results: Array<{ agentId: string; output: unknown; totalTokens: number }>;\n}\n\n/** Checkpoint state for supervisor pattern */\nexport interface SupervisorCheckpointState extends PatternCheckpointBase {\n type: \"supervisor\";\n /** Next round number */\n round: number;\n /** Last supervisor output */\n supervisorOutput: unknown;\n /** Worker results so far */\n workerResults: Array<{ output: unknown; totalTokens: number }>;\n /** Current input to supervisor */\n currentInput: string;\n}\n\n/** Checkpoint state for reflect pattern */\nexport interface ReflectCheckpointState extends PatternCheckpointBase {\n type: \"reflect\";\n /** Next iteration number */\n iteration: number;\n /** Current effective input */\n effectiveInput: string;\n /** Iteration history */\n history: Array<{\n iteration: number;\n passed: boolean;\n score?: number;\n feedback?: string;\n durationMs: number;\n producerTokens: number;\n evaluatorTokens: number;\n }>;\n /** Producer outputs so far */\n producerOutputs: Array<{ output: unknown; score?: number }>;\n /** Last producer output */\n lastProducerOutput: unknown | null;\n}\n\n/** Checkpoint state for debate pattern */\nexport interface DebateCheckpointState extends PatternCheckpointBase {\n type: \"debate\";\n /** Next round number */\n round: number;\n /** Current input for the round */\n currentInput: string;\n /** Completed rounds */\n rounds: Array<{\n proposals: Array<{ agentId: string; output: unknown }>;\n judgement: { winnerId: string; feedback?: string; score?: number };\n }>;\n /** Last winning agent ID */\n lastWinnerId: string;\n /** Last winning output */\n lastWinnerOutput: unknown;\n /** Tokens consumed so far */\n tokensConsumed: number;\n}\n\n/** Checkpoint state for DAG pattern */\nexport interface DagCheckpointState extends PatternCheckpointBase {\n type: \"dag\";\n /** Per-node statuses */\n statuses: Record<string, DagNodeStatus>;\n /** Per-node outputs */\n outputs: Record<string, unknown>;\n /** Per-node errors */\n errors: Record<string, string>;\n /** Number of completed nodes */\n completedCount: number;\n /** Full results (output + tokens per node) */\n nodeResults: Record<string, { output: unknown; totalTokens: number }>;\n /** Original input */\n input: string;\n}\n\n/** Serializable mid-goal state for save/resume */\nexport interface GoalCheckpointState extends PatternCheckpointBase {\n /** Pattern type discriminator */\n type: \"goal\";\n /** Current step */\n step: number;\n /** Current facts snapshot */\n facts: Record<string, unknown>;\n /** Completed node IDs */\n completedNodes: string[];\n /** Failed node IDs with consecutive failure counts */\n failedNodes: Record<string, number>;\n /** Node input hashes (for allowRerun detection) */\n nodeInputHashes: Record<string, string>;\n /** Per-node results (serialized — output only, not the full RunResult) */\n nodeOutputs: Record<string, { output: unknown; totalTokens: number }>;\n /** Execution order so far */\n executionOrder: string[];\n /** Step metrics collected so far */\n stepMetrics: GoalStepMetrics[];\n /** Relaxations applied so far */\n relaxations: RelaxationRecord[];\n /** Applied relaxation tier index */\n appliedRelaxationTiers: number;\n /** Stall step counter */\n stallSteps: number;\n /** Last satisfaction value */\n lastSatisfaction: number;\n /** Per-agent metrics */\n agentMetrics: Record<\n string,\n { runs: number; totalDelta: number; tokens: number }\n >;\n}\n\n/** Discriminated union of all pattern checkpoint states */\nexport type PatternCheckpointState =\n | SequentialCheckpointState\n | SupervisorCheckpointState\n | ReflectCheckpointState\n | DebateCheckpointState\n | DagCheckpointState\n | GoalCheckpointState;\n\n// ---- Checkpoint utilities ----\n\n/** Progress computed from a checkpoint state */\nexport interface CheckpointProgress {\n /** 0-100 percentage complete */\n percentage: number;\n /** Steps/rounds/iterations completed */\n stepsCompleted: number;\n /** Total expected steps (null for unbounded patterns) */\n stepsTotal: number | null;\n /** Tokens consumed so far */\n tokensConsumed: number;\n /** Estimated tokens remaining (null when unknowable) */\n estimatedTokensRemaining: number | null;\n /** Estimated steps remaining (null when unknowable) */\n estimatedStepsRemaining: number | null;\n}\n\n/** Diff between two checkpoint states */\nexport interface CheckpointDiff {\n /** Pattern type */\n patternType: string;\n /** Step/round/iteration difference */\n stepDelta: number;\n /** Token difference */\n tokensDelta: number;\n /** Fact changes (goal only) */\n facts?: {\n added: string[];\n removed: string[];\n changed: Array<{ key: string; before: unknown; after: unknown }>;\n };\n /** Nodes completed between checkpoints (DAG/goal) */\n nodesCompleted?: string[];\n}\n\n/** Bridge schema for orchestrator (internal plumbing — types cast to bypass t.object constraint) */\nexport const orchestratorBridgeSchema = {\n facts: {\n [AGENT_KEY]: t.object() as unknown as SchemaType<AgentState>,\n [APPROVAL_KEY]: t.object() as unknown as SchemaType<ApprovalState>,\n [CONVERSATION_KEY]: t.array() as unknown as SchemaType<Message[]>,\n [TOOL_CALLS_KEY]: t.array() as unknown as SchemaType<ToolCall[]>,\n [BREAKPOINT_KEY]: t.object() as unknown as SchemaType<BreakpointState>,\n },\n derivations: {},\n events: {},\n requirements: {},\n} satisfies ModuleSchema;\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
function O(i,a=false){let c=false,g=[],s=[],P=a?(m,...v)=>console.debug(`[MCP Stub] ${m}`,...v):()=>{};return {async connect(){P(`Connecting to ${i.name} (${i.transport})`),c=true;},async disconnect(){c=false;},isConnected(){return c},getCapabilities(){return {tools:true,resources:true,prompts:true}},async listTools(){return g},async callTool(m,v){return P(`Calling tool ${m}`,v),{content:[{type:"text",text:`Stub result for ${m}`}]}},async listResources(){return s},async readResource(m){return P(`Reading resource ${m}`),{contents:[{uri:m,text:`Stub content for ${m}`}]}},async listPrompts(){return []},async getPrompt(m){return {messages:[{role:"user",content:{type:"text",text:`Stub prompt ${m}`}}]}}}}function _(i,a,c){let g=Date.now(),s=i.get(a);return !s||g>s.resetTime?(i.set(a,{count:1,resetTime:g+6e4}),true):s.count>=c?false:(s.count++,true)}function F(i){let{servers:a,toolConstraints:c={},resourceMappings:g=[],events:s={},autoConnect:P=false,autoReconnect:m=true,debug:v=false,allowDirectCalls:h=false}=i;!i.clientFactory&&(typeof process<"u"&&process.env?.NODE_ENV==="production"?console.warn(`[Directive MCP] WARNING: Using stub MCP client in production!
|
|
2
|
+
The stub client returns mock data and does not connect to real MCP servers.
|
|
3
|
+
Provide a real 'clientFactory' option to connect to actual MCP servers:
|
|
4
|
+
|
|
5
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
6
|
+
|
|
7
|
+
const adapter = createMCPAdapter({
|
|
8
|
+
servers: [...],
|
|
9
|
+
clientFactory: (config) => new Client(config),
|
|
10
|
+
});`):v&&console.debug("[Directive MCP] Using stub client for development. Provide 'clientFactory' for production use."));let b=i.clientFactory??(e=>O(e,v)),A=i.approvalTimeoutMs??3e5,n={servers:new Map,toolConstraints:new Map(Object.entries(c)),rateLimiters:new Map,pendingApprovals:new Map,approvedRequests:new Set,rejectedRequests:new Set},E=0,d=new Map,M=new Map;function D(e){return new Promise((t,r)=>{if(n.approvedRequests.has(e)){n.approvedRequests.delete(e),n.pendingApprovals.delete(e),s.onApprovalResolved?.(e,true),t();return}if(n.rejectedRequests.has(e)){n.rejectedRequests.delete(e),n.pendingApprovals.delete(e);let l=M.get(e);M.delete(e),s.onApprovalResolved?.(e,false),r(new Error(`[Directive MCP] Tool call request ${e} was rejected${l?`: ${l}`:""}`));return}let o=setTimeout(()=>{d.delete(e),n.pendingApprovals.delete(e),r(new Error(`[Directive MCP] Approval timeout: Request ${e} was not approved or rejected within ${A}ms. Call adapter.approve("${e}") or adapter.reject("${e}") to resolve.`));},A);d.set(e,{resolve:t,reject:r,timeoutId:o});})}function $(e,t,r){let o=d.get(e);o?(clearTimeout(o.timeoutId),d.delete(e),n.pendingApprovals.delete(e),s.onApprovalResolved?.(e,t),t?o.resolve():o.reject(new Error(`[Directive MCP] Tool call request ${e} was rejected${r?`: ${r}`:""}`))):(t?n.approvedRequests.add(e):(n.rejectedRequests.add(e),r&&M.set(e,r)),setTimeout(()=>{n.approvedRequests.delete(e),n.rejectedRequests.delete(e),M.delete(e),n.pendingApprovals.delete(e);},A));}let w=new Map;for(let e of a)n.servers.set(e.name,{config:e,client:null,tools:[],resources:[],status:"disconnected"}),w.set(e.name,{timer:null,attempts:0,maxAttempts:e.retry?.maxAttempts??10,baseDelay:e.retry?.backoffMs??5e3});function x(e){let t=/[;|&$`><]/;if(e.command&&t.test(e.command))throw new Error(`[Directive MCP] Stdio command for server '${e.name}' contains shell metacharacters: '${e.command}'. This may indicate a command injection vulnerability. Use 'args' for command arguments instead.`);if(e.args){for(let r of e.args)if(t.test(r))throw new Error(`[Directive MCP] Stdio argument for server '${e.name}' contains shell metacharacters: '${r}'. This may indicate a command injection vulnerability.`)}}async function S(e){let t=n.servers.get(e);if(!t)throw new Error(`Unknown MCP server: ${e}`);if(t.status!=="connected"){t.config.transport==="stdio"&&x(t.config),t.status="connecting";try{let r=b(t.config);await r.connect(),t.client=r,t.status="connected";let o=w.get(e);o&&(o.attempts=0,o.timer&&(clearTimeout(o.timer),o.timer=null)),r.getCapabilities().tools&&(t.tools=await r.listTools()),r.getCapabilities().resources&&(t.resources=await r.listResources()),t.lastSync=Date.now(),s.onConnect?.(e);}catch(r){if(t.status="error",t.error=r instanceof Error?r:new Error(String(r)),s.onError?.(e,t.error),m){let o=w.get(e);if(o&&o.attempts<o.maxAttempts){o.attempts++;let l=Math.min(o.baseDelay*2**(o.attempts-1)+Math.random()*1e3,6e4);o.timer=setTimeout(()=>{o.timer=null,S(e).catch(()=>{});},l);}else o&&console.error(`[Directive MCP] Max reconnect attempts (${o.maxAttempts}) reached for server '${e}'. Call adapter.connectServer("${e}") to retry manually.`);}throw t.error}}}async function T(e){let t=w.get(e);t?.timer&&(clearTimeout(t.timer),t.timer=null,t.attempts=0);let r=n.servers.get(e);if(!(!r||!r.client))try{await r.client.disconnect();}finally{r.status="disconnected",r.client=null,s.onDisconnect?.(e);}}async function k(e,t,r,o){let l=n.servers.get(e);if(!l)throw new Error(`[Directive MCP] Unknown server '${e}'. Available servers: ${Array.from(n.servers.keys()).join(", ")||"(none)"}`);if(!l.client)throw new Error(`[Directive MCP] Server '${e}' is not connected. Call 'adapter.connect()' or 'adapter.connectServer("${e}")' first.`);let f=`${e}.${t}`,u=n.toolConstraints.get(f);if(u){if(u.rateLimit){let p=n.rateLimiters.get(f);if(!_(n.rateLimiters,f,u.rateLimit)){let C=p?.resetTime?new Date(p.resetTime).toISOString():"unknown";throw new Error(`[Directive MCP] Rate limit exceeded for '${f}': ${p?.count??0}/${u.rateLimit} requests per minute. Resets at ${C}.`)}}if(u.maxArgSize){let p=JSON.stringify(r).length;if(p>u.maxArgSize)throw new Error(`Arguments exceed max size (${p} > ${u.maxArgSize})`)}if(u.when&&!await u.when(o,r))throw new Error(`Constraint not satisfied for ${f}`);if(u.requireApproval){let p=`approval-${++E}-${Date.now()}`,C={id:p,server:e,tool:t,args:r,requestedAt:Date.now()};n.pendingApprovals.set(p,C),s.onApprovalRequest?.(C),await D(p);}}s.onToolCall?.(e,t,r);let R=await Promise.race([l.client.callTool(t,r),new Promise((p,C)=>setTimeout(()=>C(new Error(`Tool call timeout: ${f}`)),u?.timeout??3e4))]);return s.onToolResult?.(e,t,R),R}let j={name:"mcp-adapter",onInit:async()=>{P&&await Promise.all(Array.from(n.servers.keys()).map(e=>S(e).catch(t=>console.error(`Failed to connect to ${e}:`,t))));},onDestroy:async()=>{for(let e of w.values())e.timer&&(clearTimeout(e.timer),e.timer=null);for(let[,e]of d)clearTimeout(e.timeoutId),e.reject(new Error("[Directive MCP] Adapter destroyed while awaiting approval"));d.clear(),await Promise.all(Array.from(n.servers.keys()).map(e=>T(e).catch(t=>console.error(`Failed to disconnect from ${e}:`,t))));}};async function L(e){for(let t of g)for(let[r,o]of n.servers)if(o.client){for(let l of o.resources)if(typeof t.pattern=="string"?U(l.uri,t.pattern):t.pattern.test(l.uri))try{let u=await o.client.readResource(l.uri),R=u.contents[0]?.text??"",p=t.transform?t.transform(R):R;e[t.factKey]=p,s.onResourceUpdate?.(r,l.uri,u);}catch(u){console.error(`Failed to sync resource ${l.uri}:`,u);}}}return {plugin:j,async connect(){await Promise.all(Array.from(n.servers.keys()).map(S));},connectServer:S,async disconnect(){await Promise.all(Array.from(n.servers.keys()).map(T));},disconnectServer:T,getTools(){let e=new Map;for(let[t,r]of n.servers)e.set(t,r.tools);return e},getResources(){let e=new Map;for(let[t,r]of n.servers)e.set(t,r.resources);return e},async callTool(e,t,r,o){return k(e,t,r,o)},async callToolDirect(e,t,r){if(!h)throw new Error("[Directive] callToolDirect is disabled by default. Pass { allowDirectCalls: true } to enable unconstrained tool calls.");process.env.NODE_ENV!=="production"&&console.warn("[Directive] callToolDirect bypasses all constraints (rate limits, approvals, timeouts).");let o=n.servers.get(e);if(!o)throw new Error(`[Directive MCP] Unknown server '${e}'. Available servers: ${Array.from(n.servers.keys()).join(", ")||"(none)"}`);if(!o.client)throw new Error(`[Directive MCP] Server '${e}' is not connected. Call 'adapter.connect()' or 'adapter.connectServer("${e}")' first.`);s.onToolCall?.(e,t,r);let l=await o.client.callTool(t,r);return s.onToolResult?.(e,t,l),l},async readResource(e,t){let r=n.servers.get(e);if(!r)throw new Error(`[Directive MCP] Unknown server '${e}'. Available servers: ${Array.from(n.servers.keys()).join(", ")||"(none)"}`);if(!r.client)throw new Error(`[Directive MCP] Server '${e}' is not connected. Call 'adapter.connect()' or 'adapter.connectServer("${e}")' first.`);let o=await r.client.readResource(t);return s.onResourceUpdate?.(e,t,o),o},syncResources:L,getServerStatus(e){return n.servers.get(e)},getAllServerStatuses(){return new Map(n.servers)},approve(e){if(!n.pendingApprovals.get(e)&&!d.has(e))throw new Error(`[Directive MCP] No pending approval request with ID '${e}'. Pending requests: ${Array.from(n.pendingApprovals.keys()).join(", ")||"(none)"}`);$(e,true);},reject(e,t){if(!n.pendingApprovals.get(e)&&!d.has(e))throw new Error(`[Directive MCP] No pending approval request with ID '${e}'. Pending requests: ${Array.from(n.pendingApprovals.keys()).join(", ")||"(none)"}`);$(e,false,t);},getPendingApprovals(){return Array.from(n.pendingApprovals.values())},getRejectionReason(e){return M.get(e)}}}var y=new Map,N=200;function U(i,a){let c=y.get(a);if(!c){let g=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/\*/g,"\0STAR\0").replace(/\?/g,"\0QUESTION\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\0GLOBSTAR\0/g,".*").replace(/\0STAR\0/g,"[^/]*").replace(/\0QUESTION\0/g,".");if(c=new RegExp(`^${g}$`),y.size>=N){let s=y.keys().next().value;s!==void 0&&y.delete(s);}y.set(a,c);}return c.test(i)}function G(i){let a=[];for(let[c,g]of i)for(let s of g)a.push({type:"function",function:{name:`${c}.${s.name}`,description:s.description??`Tool: ${s.name}`,parameters:s.inputSchema}});return a}function z(i,a,c){return {type:"MCP_CALL_TOOL",server:i,tool:a,args:c}}function B(i,a){return {type:"MCP_READ_RESOURCE",server:i,uri:a}}function K(i,a,c){return {type:"MCP_GET_PROMPT",server:i,prompt:a,args:c}}function W(i,a){return {type:"MCP_SYNC_RESOURCES",server:i,pattern:a}}export{F as a,G as b,z as c,B as d,K as e,W as f};//# sourceMappingURL=chunk-V2FCPNPP.js.map
|
|
11
|
+
//# sourceMappingURL=chunk-V2FCPNPP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp.ts"],"names":["createStubClient","config","debug","connected","tools","resources","log","msg","args","name","uri","checkRateLimit","rateLimiters","key","limit","now","limiter","createMCPAdapter","servers","toolConstraints","resourceMappings","events","autoConnect","autoReconnect","allowDirectCalls","clientFactory","serverConfig","approvalTimeoutMs","state","approvalCounter","approvalWaiters","rejectionReasons","waitForApproval","requestId","resolve","reject","reason","timeoutId","resolveApproval","approved","waiter","reconnectState","validateStdioCommand","shellMetachars","arg","connectServer","serverState","client","rState","error","delay","disconnectServer","callToolWithConstraints","server","tool","facts","constraintKey","constraint","resetAt","argSize","approvalRequest","result","_","plugin","e","syncResources","mapping","serverName","resource","matchGlob","content","value","globCache","MAX_GLOB_CACHE_SIZE","str","pattern","regex","regexPattern","firstKey","convertToolsForLLM","serverTools","mcpCallTool","mcpReadResource","mcpGetPrompt","prompt","mcpSyncResources"],"mappings":"AAiKA,SAASA,CAAAA,CAAiBC,CAAAA,CAAyBC,CAAAA,CAAQ,KAAA,CAAkB,CAC3E,IAAIC,CAAAA,CAAY,KAAA,CACVC,CAAAA,CAAmB,EAAC,CACpBC,CAAAA,CAA2B,EAAC,CAE5BC,CAAAA,CAAMJ,CAAAA,CACR,CAACK,CAAAA,CAAAA,GAAgBC,CAAAA,GACf,OAAA,CAAQ,KAAA,CAAM,CAAA,WAAA,EAAcD,CAAG,CAAA,CAAA,CAAI,GAAGC,CAAI,CAAA,CAC5C,IAAM,CAAC,CAAA,CAEX,OAAO,CACL,MAAM,OAAA,EAAU,CACdF,CAAAA,CAAI,CAAA,cAAA,EAAiBL,CAAAA,CAAO,IAAI,CAAA,EAAA,EAAKA,CAAAA,CAAO,SAAS,CAAA,CAAA,CAAG,CAAA,CACxDE,CAAAA,CAAY,KACd,CAAA,CACA,MAAM,UAAA,EAAa,CACjBA,CAAAA,CAAY,MACd,CAAA,CACA,WAAA,EAAc,CACZ,OAAOA,CACT,CAAA,CACA,eAAA,EAAkB,CAChB,OAAO,CAAE,KAAA,CAAO,IAAA,CAAM,SAAA,CAAW,IAAA,CAAM,OAAA,CAAS,IAAK,CACvD,CAAA,CACA,MAAM,SAAA,EAAY,CAChB,OAAOC,CACT,CAAA,CACA,MAAM,QAAA,CAASK,CAAAA,CAAcD,CAAAA,CAA+B,CAC1D,OAAAF,CAAAA,CAAI,CAAA,aAAA,EAAgBG,CAAI,CAAA,CAAA,CAAID,CAAI,CAAA,CACzB,CACL,OAAA,CAAS,CAAC,CAAE,IAAA,CAAM,MAAA,CAAiB,IAAA,CAAM,CAAA,gBAAA,EAAmBC,CAAI,CAAA,CAAG,CAAC,CACtE,CACF,CAAA,CACA,MAAM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IAAMyD,CAAAA,CAOD,EAAC,CAEN,IAAA,GAAW,CAACR,CAAAA,CAAQ2B,CAAW,IAAK5E,CAAAA,CAClC,IAAA,IAAWkD,KAAQ0B,CAAAA,CACjBnB,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,SAAU,CACR,IAAA,CAAM,GAAGR,CAAM,CAAA,CAAA,EAAIC,EAAK,IAAI,CAAA,CAAA,CAC5B,WAAA,CAAaA,CAAAA,CAAK,WAAA,EAAe,CAAA,MAAA,EAASA,EAAK,IAAI,CAAA,CAAA,CACnD,WAAYA,CAAAA,CAAK,WACnB,CACF,CAAC,CAAA,CAIL,OAAOO,CACT,CAWO,SAASoB,EACd5B,CAAAA,CACAC,CAAAA,CACA9C,EACwB,CACxB,OAAO,CAAE,IAAA,CAAM,eAAA,CAAiB,MAAA,CAAA6C,CAAAA,CAAQ,IAAA,CAAAC,CAAAA,CAAM,KAAA9C,CAAK,CACrD,CAKO,SAAS0E,CAAAA,CACd7B,EACA3C,CAAAA,CAC4B,CAC5B,OAAO,CAAE,IAAA,CAAM,mBAAA,CAAqB,OAAA2C,CAAAA,CAAQ,GAAA,CAAA3C,CAAI,CAClD,CAKO,SAASyE,CAAAA,CACd9B,CAAAA,CACA+B,CAAAA,CACA5E,CAAAA,CACyB,CACzB,OAAO,CAAE,IAAA,CAAM,gBAAA,CAAkB,OAAA6C,CAAAA,CAAQ,MAAA,CAAA+B,EAAQ,IAAA,CAAA5E,CAAK,CACxD,CAKO,SAAS6E,CAAAA,CACdhC,EACAsB,CAAAA,CAC6B,CAC7B,OAAO,CAAE,IAAA,CAAM,qBAAsB,MAAA,CAAAtB,CAAAA,CAAQ,OAAA,CAAAsB,CAAQ,CACvD","file":"chunk-V2FCPNPP.js","sourcesContent":["/**\n * MCP Adapter - Model Context Protocol Integration for Directive\n *\n * Provides seamless integration between Directive's constraint system and MCP servers:\n * - MCP tools become Directive resolvers with constraint-driven access control\n * - MCP resources sync to Directive facts\n * - MCP prompts available through requirements\n *\n * @example\n * ```typescript\n * import { createMCPAdapter } from '@directive-run/ai';\n *\n * const mcpAdapter = createMCPAdapter({\n * servers: [\n * { name: 'filesystem', transport: 'stdio', command: 'mcp-server-filesystem' },\n * { name: 'github', transport: 'sse', url: 'https://mcp.github.com' }\n * ],\n * toolConstraints: {\n * 'filesystem.write': { requireApproval: true },\n * 'github.create_pr': { when: (facts) => facts.reviewComplete }\n * }\n * });\n *\n * const system = createSystem({\n * module: myModule,\n * plugins: [mcpAdapter.plugin]\n * });\n * ```\n */\n\nimport type { Plugin } from \"@directive-run/core\";\nimport type {\n MCPAdapterConfig,\n MCPApprovalRequest,\n MCPCallToolRequirement,\n MCPClient,\n MCPGetPromptRequirement,\n MCPReadResourceRequirement,\n MCPResource,\n MCPResourceMapping,\n MCPResourceResult,\n MCPServerConfig,\n MCPSyncResourcesRequirement,\n MCPTool,\n MCPToolConstraint,\n MCPToolResult,\n} from \"./mcp-types.js\";\n\n// ============================================================================\n// MCP Adapter State\n// ============================================================================\n\n/** State of an MCP server connection */\ninterface MCPServerState {\n config: MCPServerConfig;\n client: MCPClient | null;\n tools: MCPTool[];\n resources: MCPResource[];\n status: \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n error?: Error;\n lastSync?: number;\n}\n\n/** Internal state for the adapter */\ninterface MCPAdapterState {\n servers: Map<string, MCPServerState>;\n toolConstraints: Map<string, MCPToolConstraint>;\n resourceMappings: MCPResourceMapping[];\n rateLimiters: Map<string, { count: number; resetTime: number }>;\n /** Pending approval requests */\n pendingApprovals: Map<string, MCPApprovalRequest>;\n /** Approved request IDs */\n approvedRequests: Set<string>;\n /** Rejected request IDs */\n rejectedRequests: Set<string>;\n}\n\n// ============================================================================\n// MCP Adapter Instance\n// ============================================================================\n\n/** MCP Adapter instance */\nexport interface MCPAdapter {\n /** Plugin to add to Directive system */\n plugin: Plugin;\n /** Connect to all configured servers */\n connect(): Promise<void>;\n /** Connect to a specific server */\n connectServer(name: string): Promise<void>;\n /** Disconnect from all servers */\n disconnect(): Promise<void>;\n /** Disconnect from a specific server */\n disconnectServer(name: string): Promise<void>;\n /** Get all available tools across all servers */\n getTools(): Map<string, MCPTool[]>;\n /** Get all available resources across all servers */\n getResources(): Map<string, MCPResource[]>;\n /**\n * Call a tool with constraint checking (recommended).\n * Applies rate limits, argument size limits, approval workflow, and custom constraints.\n * @param server - Server name\n * @param tool - Tool name\n * @param args - Tool arguments\n * @param facts - Current facts for constraint evaluation\n */\n callTool(\n server: string,\n tool: string,\n args: Record<string, unknown>,\n facts: Record<string, unknown>,\n ): Promise<MCPToolResult>;\n /**\n * Call a tool directly, bypassing all constraints (rate limits, approvals, etc.).\n * Use only for trusted internal calls where constraint checking is not needed.\n */\n callToolDirect(\n server: string,\n tool: string,\n args: Record<string, unknown>,\n ): Promise<MCPToolResult>;\n /** Read a resource directly */\n readResource(server: string, uri: string): Promise<MCPResourceResult>;\n /** Sync resources to facts */\n syncResources(facts: Record<string, unknown>): Promise<void>;\n /** Get server status */\n getServerStatus(name: string): MCPServerState | undefined;\n /** Get all server statuses */\n getAllServerStatuses(): Map<string, MCPServerState>;\n /** Approve a pending tool call request */\n approve(requestId: string): void;\n /** Reject a pending tool call request */\n reject(requestId: string, reason?: string): void;\n /** Get pending approval requests */\n getPendingApprovals(): MCPApprovalRequest[];\n /** Get the rejection reason for a request (if available) */\n getRejectionReason(requestId: string): string | undefined;\n}\n\n// ============================================================================\n// Default MCP Client (Stub)\n// ============================================================================\n\n/**\n * Create a stub MCP client for development/testing.\n *\n * **Important:** This stub is for development only. In production, provide\n * a real MCP client via the `clientFactory` option:\n *\n * @example\n * ```typescript\n * import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\n *\n * const adapter = createMCPAdapter({\n * servers: [...],\n * clientFactory: (config) => new Client(config),\n * });\n * ```\n *\n * @param config - Server configuration\n * @param debug - Enable debug logging (default: false)\n */\nfunction createStubClient(config: MCPServerConfig, debug = false): MCPClient {\n let connected = false;\n const tools: MCPTool[] = [];\n const resources: MCPResource[] = [];\n\n const log = debug\n ? (msg: string, ...args: unknown[]) =>\n console.debug(`[MCP Stub] ${msg}`, ...args)\n : () => {};\n\n return {\n async connect() {\n log(`Connecting to ${config.name} (${config.transport})`);\n connected = true;\n },\n async disconnect() {\n connected = false;\n },\n isConnected() {\n return connected;\n },\n getCapabilities() {\n return { tools: true, resources: true, prompts: true };\n },\n async listTools() {\n return tools;\n },\n async callTool(name: string, args: Record<string, unknown>) {\n log(`Calling tool ${name}`, args);\n return {\n content: [{ type: \"text\" as const, text: `Stub result for ${name}` }],\n };\n },\n async listResources() {\n return resources;\n },\n async readResource(uri: string) {\n log(`Reading resource ${uri}`);\n return {\n contents: [{ uri, text: `Stub content for ${uri}` }],\n };\n },\n async listPrompts() {\n return [];\n },\n async getPrompt(name: string) {\n return {\n messages: [\n {\n role: \"user\" as const,\n content: { type: \"text\" as const, text: `Stub prompt ${name}` },\n },\n ],\n };\n },\n };\n}\n\n// ============================================================================\n// Rate Limiter\n// ============================================================================\n\nfunction checkRateLimit(\n rateLimiters: Map<string, { count: number; resetTime: number }>,\n key: string,\n limit: number,\n): boolean {\n const now = Date.now();\n const limiter = rateLimiters.get(key);\n\n if (!limiter || now > limiter.resetTime) {\n rateLimiters.set(key, { count: 1, resetTime: now + 60000 });\n return true;\n }\n\n if (limiter.count >= limit) {\n return false;\n }\n\n limiter.count++;\n return true;\n}\n\n// ============================================================================\n// MCP Adapter Factory\n// ============================================================================\n\n/**\n * Create an MCP adapter for Directive integration.\n *\n * @example\n * ```typescript\n * const adapter = createMCPAdapter({\n * servers: [\n * { name: 'fs', transport: 'stdio', command: 'mcp-server-filesystem' },\n * ],\n * toolConstraints: {\n * 'fs.write_file': {\n * requireApproval: true,\n * maxArgSize: 10000,\n * timeout: 30000,\n * },\n * },\n * resourceMappings: [\n * {\n * pattern: 'file://*.json',\n * factKey: 'jsonFiles',\n * mode: 'poll',\n * pollInterval: 5000,\n * },\n * ],\n * });\n *\n * // Add to system\n * const system = createSystem({\n * module: myModule,\n * plugins: [adapter.plugin],\n * });\n *\n * // Connect to servers\n * await adapter.connect();\n * ```\n */\nexport function createMCPAdapter(config: MCPAdapterConfig): MCPAdapter {\n const {\n servers,\n toolConstraints = {},\n resourceMappings = [],\n events = {},\n autoConnect = false,\n autoReconnect = true,\n debug = false,\n allowDirectCalls = false,\n } = config;\n\n // Warn if using stub client in production\n const usingStubClient = !config.clientFactory;\n if (usingStubClient) {\n const isProduction =\n typeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\";\n if (isProduction) {\n console.warn(\n \"[Directive MCP] WARNING: Using stub MCP client in production!\\n\" +\n \"The stub client returns mock data and does not connect to real MCP servers.\\n\" +\n \"Provide a real 'clientFactory' option to connect to actual MCP servers:\\n\\n\" +\n \" import { Client } from '@modelcontextprotocol/sdk/client/index.js';\\n\\n\" +\n \" const adapter = createMCPAdapter({\\n\" +\n \" servers: [...],\\n\" +\n \" clientFactory: (config) => new Client(config),\\n\" +\n \" });\",\n );\n } else if (debug) {\n console.debug(\n \"[Directive MCP] Using stub client for development. \" +\n \"Provide 'clientFactory' for production use.\",\n );\n }\n }\n\n const clientFactory =\n config.clientFactory ??\n ((serverConfig: MCPServerConfig) => createStubClient(serverConfig, debug));\n const approvalTimeoutMs = config.approvalTimeoutMs ?? 300000;\n\n // Initialize state\n const state: MCPAdapterState = {\n servers: new Map(),\n toolConstraints: new Map(Object.entries(toolConstraints)),\n resourceMappings,\n rateLimiters: new Map(),\n pendingApprovals: new Map(),\n approvedRequests: new Set(),\n rejectedRequests: new Set(),\n };\n\n // Approval ID counter\n let approvalCounter = 0;\n\n // Promise-based approval waiting (no polling)\n const approvalWaiters = new Map<\n string,\n {\n resolve: () => void;\n reject: (error: Error) => void;\n timeoutId: ReturnType<typeof setTimeout>;\n }\n >();\n\n // Rejection reasons storage\n const rejectionReasons = new Map<string, string>();\n\n // Wait for approval with timeout - Promise-based, no polling\n function waitForApproval(requestId: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // Check if already resolved\n if (state.approvedRequests.has(requestId)) {\n state.approvedRequests.delete(requestId);\n state.pendingApprovals.delete(requestId);\n events.onApprovalResolved?.(requestId, true);\n resolve();\n return;\n }\n if (state.rejectedRequests.has(requestId)) {\n state.rejectedRequests.delete(requestId);\n state.pendingApprovals.delete(requestId);\n const reason = rejectionReasons.get(requestId);\n rejectionReasons.delete(requestId);\n events.onApprovalResolved?.(requestId, false);\n reject(\n new Error(\n `[Directive MCP] Tool call request ${requestId} was rejected${reason ? `: ${reason}` : \"\"}`,\n ),\n );\n return;\n }\n\n // Set up timeout\n const timeoutId = setTimeout(() => {\n approvalWaiters.delete(requestId);\n state.pendingApprovals.delete(requestId);\n reject(\n new Error(\n `[Directive MCP] Approval timeout: Request ${requestId} was not approved or rejected within ${approvalTimeoutMs}ms. ` +\n `Call adapter.approve(\"${requestId}\") or adapter.reject(\"${requestId}\") to resolve.`,\n ),\n );\n }, approvalTimeoutMs);\n\n // Store waiter for later resolution\n approvalWaiters.set(requestId, { resolve, reject, timeoutId });\n });\n }\n\n // Resolve an approval (called by approve/reject)\n function resolveApproval(\n requestId: string,\n approved: boolean,\n reason?: string,\n ): void {\n const waiter = approvalWaiters.get(requestId);\n if (waiter) {\n clearTimeout(waiter.timeoutId);\n approvalWaiters.delete(requestId);\n state.pendingApprovals.delete(requestId);\n events.onApprovalResolved?.(requestId, approved);\n\n if (approved) {\n waiter.resolve();\n } else {\n waiter.reject(\n new Error(\n `[Directive MCP] Tool call request ${requestId} was rejected${reason ? `: ${reason}` : \"\"}`,\n ),\n );\n }\n } else {\n // Waiter not yet created, store for immediate resolution with TTL cleanup\n if (approved) {\n state.approvedRequests.add(requestId);\n } else {\n state.rejectedRequests.add(requestId);\n if (reason) {\n rejectionReasons.set(requestId, reason);\n }\n }\n // Auto-cleanup pre-resolved state after approval timeout to prevent memory leaks\n setTimeout(() => {\n state.approvedRequests.delete(requestId);\n state.rejectedRequests.delete(requestId);\n rejectionReasons.delete(requestId);\n state.pendingApprovals.delete(requestId);\n }, approvalTimeoutMs);\n }\n }\n\n // Track reconnect state per server\n const reconnectState = new Map<\n string,\n {\n timer: ReturnType<typeof setTimeout> | null;\n attempts: number;\n maxAttempts: number;\n baseDelay: number;\n }\n >();\n\n // Initialize server states\n for (const serverConfig of servers) {\n state.servers.set(serverConfig.name, {\n config: serverConfig,\n client: null,\n tools: [],\n resources: [],\n status: \"disconnected\",\n });\n reconnectState.set(serverConfig.name, {\n timer: null,\n attempts: 0,\n maxAttempts: serverConfig.retry?.maxAttempts ?? 10,\n baseDelay: serverConfig.retry?.backoffMs ?? 5000,\n });\n }\n\n // Validate stdio command to prevent shell injection\n function validateStdioCommand(serverConfig: MCPServerConfig): void {\n const shellMetachars = /[;|&$`><]/;\n\n if (serverConfig.command) {\n if (shellMetachars.test(serverConfig.command)) {\n throw new Error(\n `[Directive MCP] Stdio command for server '${serverConfig.name}' contains shell metacharacters: '${serverConfig.command}'. This may indicate a command injection vulnerability. Use 'args' for command arguments instead.`,\n );\n }\n }\n\n if (serverConfig.args) {\n for (const arg of serverConfig.args) {\n if (shellMetachars.test(arg)) {\n throw new Error(\n `[Directive MCP] Stdio argument for server '${serverConfig.name}' contains shell metacharacters: '${arg}'. This may indicate a command injection vulnerability.`,\n );\n }\n }\n }\n }\n\n // Connect to a server\n async function connectServer(name: string): Promise<void> {\n const serverState = state.servers.get(name);\n if (!serverState) {\n throw new Error(`Unknown MCP server: ${name}`);\n }\n\n if (serverState.status === \"connected\") {\n return;\n }\n\n // Validate stdio commands before connecting\n if (serverState.config.transport === \"stdio\") {\n validateStdioCommand(serverState.config);\n }\n\n serverState.status = \"connecting\";\n\n try {\n const client = clientFactory(serverState.config);\n await client.connect();\n\n serverState.client = client;\n serverState.status = \"connected\";\n\n // Reset reconnect state on successful connection\n const rState = reconnectState.get(name);\n if (rState) {\n rState.attempts = 0;\n if (rState.timer) {\n clearTimeout(rState.timer);\n rState.timer = null;\n }\n }\n\n // Fetch available tools and resources\n if (client.getCapabilities().tools) {\n serverState.tools = await client.listTools();\n }\n if (client.getCapabilities().resources) {\n serverState.resources = await client.listResources();\n }\n\n serverState.lastSync = Date.now();\n events.onConnect?.(name);\n } catch (error) {\n serverState.status = \"error\";\n serverState.error =\n error instanceof Error ? error : new Error(String(error));\n events.onError?.(name, serverState.error);\n\n if (autoReconnect) {\n const rState = reconnectState.get(name);\n if (rState && rState.attempts < rState.maxAttempts) {\n rState.attempts++;\n // Exponential backoff with jitter, capped at 60s\n const delay = Math.min(\n rState.baseDelay * 2 ** (rState.attempts - 1) +\n Math.random() * 1000,\n 60000,\n );\n rState.timer = setTimeout(() => {\n rState.timer = null;\n connectServer(name).catch(() => {}); // Error handled in next iteration\n }, delay);\n } else if (rState) {\n console.error(\n `[Directive MCP] Max reconnect attempts (${rState.maxAttempts}) reached for server '${name}'. ` +\n `Call adapter.connectServer(\"${name}\") to retry manually.`,\n );\n }\n }\n\n throw serverState.error;\n }\n }\n\n // Disconnect from a server\n async function disconnectServer(name: string): Promise<void> {\n // Clear any pending reconnect timer\n const rState = reconnectState.get(name);\n if (rState?.timer) {\n clearTimeout(rState.timer);\n rState.timer = null;\n rState.attempts = 0;\n }\n\n const serverState = state.servers.get(name);\n if (!serverState || !serverState.client) {\n return;\n }\n\n try {\n await serverState.client.disconnect();\n } finally {\n serverState.status = \"disconnected\";\n serverState.client = null;\n events.onDisconnect?.(name);\n }\n }\n\n // Call a tool with constraint checking\n async function callToolWithConstraints(\n server: string,\n tool: string,\n args: Record<string, unknown>,\n facts: Record<string, unknown>,\n ): Promise<MCPToolResult> {\n const serverState = state.servers.get(server);\n if (!serverState) {\n throw new Error(\n `[Directive MCP] Unknown server '${server}'. ` +\n `Available servers: ${Array.from(state.servers.keys()).join(\", \") || \"(none)\"}`,\n );\n }\n if (!serverState.client) {\n throw new Error(\n `[Directive MCP] Server '${server}' is not connected. ` +\n `Call 'adapter.connect()' or 'adapter.connectServer(\"${server}\")' first.`,\n );\n }\n\n const constraintKey = `${server}.${tool}`;\n const constraint = state.toolConstraints.get(constraintKey);\n\n // Check constraints\n if (constraint) {\n // Check rate limit\n if (constraint.rateLimit) {\n const limiter = state.rateLimiters.get(constraintKey);\n if (\n !checkRateLimit(\n state.rateLimiters,\n constraintKey,\n constraint.rateLimit,\n )\n ) {\n const resetAt = limiter?.resetTime\n ? new Date(limiter.resetTime).toISOString()\n : \"unknown\";\n throw new Error(\n `[Directive MCP] Rate limit exceeded for '${constraintKey}': ` +\n `${limiter?.count ?? 0}/${constraint.rateLimit} requests per minute. ` +\n `Resets at ${resetAt}.`,\n );\n }\n }\n\n // Check max arg size\n if (constraint.maxArgSize) {\n const argSize = JSON.stringify(args).length;\n if (argSize > constraint.maxArgSize) {\n throw new Error(\n `Arguments exceed max size (${argSize} > ${constraint.maxArgSize})`,\n );\n }\n }\n\n // Check custom constraint\n if (constraint.when) {\n const allowed = await constraint.when(facts, args);\n if (!allowed) {\n throw new Error(`Constraint not satisfied for ${constraintKey}`);\n }\n }\n\n // Check if approval is required\n if (constraint.requireApproval) {\n const requestId = `approval-${++approvalCounter}-${Date.now()}`;\n const approvalRequest: MCPApprovalRequest = {\n id: requestId,\n server,\n tool,\n args,\n requestedAt: Date.now(),\n };\n\n state.pendingApprovals.set(requestId, approvalRequest);\n events.onApprovalRequest?.(approvalRequest);\n\n // Wait for approval or rejection\n await waitForApproval(requestId);\n }\n }\n\n events.onToolCall?.(server, tool, args);\n\n // Call the tool\n const result = await Promise.race([\n serverState.client.callTool(tool, args),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`Tool call timeout: ${constraintKey}`)),\n constraint?.timeout ?? 30000,\n ),\n ),\n ]);\n\n events.onToolResult?.(server, tool, result);\n\n return result;\n }\n\n // Create plugin\n const plugin: Plugin = {\n name: \"mcp-adapter\",\n\n onInit: async () => {\n if (autoConnect) {\n await Promise.all(\n Array.from(state.servers.keys()).map((name) =>\n connectServer(name).catch((e) =>\n console.error(`Failed to connect to ${name}:`, e),\n ),\n ),\n );\n }\n },\n\n onDestroy: async () => {\n // Clear all reconnect timers\n for (const rState of reconnectState.values()) {\n if (rState.timer) {\n clearTimeout(rState.timer);\n rState.timer = null;\n }\n }\n\n // Reject all pending approval waiters\n for (const [, waiter] of approvalWaiters) {\n clearTimeout(waiter.timeoutId);\n waiter.reject(\n new Error(\n \"[Directive MCP] Adapter destroyed while awaiting approval\",\n ),\n );\n }\n approvalWaiters.clear();\n\n await Promise.all(\n Array.from(state.servers.keys()).map((name) =>\n disconnectServer(name).catch((e) =>\n console.error(`Failed to disconnect from ${name}:`, e),\n ),\n ),\n );\n },\n };\n\n // Sync resources to facts\n async function syncResources(facts: Record<string, unknown>): Promise<void> {\n for (const mapping of resourceMappings) {\n for (const [serverName, serverState] of state.servers) {\n if (!serverState.client) continue;\n\n for (const resource of serverState.resources) {\n // Check if resource matches pattern\n const matches =\n typeof mapping.pattern === \"string\"\n ? matchGlob(resource.uri, mapping.pattern)\n : mapping.pattern.test(resource.uri);\n\n if (matches) {\n try {\n const result = await serverState.client.readResource(\n resource.uri,\n );\n const content = result.contents[0]?.text ?? \"\";\n const value = mapping.transform\n ? mapping.transform(content)\n : content;\n\n facts[mapping.factKey] = value;\n events.onResourceUpdate?.(serverName, resource.uri, result);\n } catch (error) {\n console.error(`Failed to sync resource ${resource.uri}:`, error);\n }\n }\n }\n }\n }\n }\n\n return {\n plugin,\n\n async connect() {\n await Promise.all(Array.from(state.servers.keys()).map(connectServer));\n },\n\n connectServer,\n\n async disconnect() {\n await Promise.all(Array.from(state.servers.keys()).map(disconnectServer));\n },\n\n disconnectServer,\n\n getTools() {\n const tools = new Map<string, MCPTool[]>();\n for (const [name, serverState] of state.servers) {\n tools.set(name, serverState.tools);\n }\n return tools;\n },\n\n getResources() {\n const resources = new Map<string, MCPResource[]>();\n for (const [name, serverState] of state.servers) {\n resources.set(name, serverState.resources);\n }\n return resources;\n },\n\n async callTool(server, tool, args, facts) {\n return callToolWithConstraints(server, tool, args, facts);\n },\n\n async callToolDirect(server, tool, args) {\n if (!allowDirectCalls) {\n throw new Error(\n \"[Directive] callToolDirect is disabled by default. Pass { allowDirectCalls: true } to enable unconstrained tool calls.\",\n );\n }\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[Directive] callToolDirect bypasses all constraints (rate limits, approvals, timeouts).\",\n );\n }\n const serverState = state.servers.get(server);\n if (!serverState) {\n throw new Error(\n `[Directive MCP] Unknown server '${server}'. ` +\n `Available servers: ${Array.from(state.servers.keys()).join(\", \") || \"(none)\"}`,\n );\n }\n if (!serverState.client) {\n throw new Error(\n `[Directive MCP] Server '${server}' is not connected. ` +\n `Call 'adapter.connect()' or 'adapter.connectServer(\"${server}\")' first.`,\n );\n }\n events.onToolCall?.(server, tool, args);\n const result = await serverState.client.callTool(tool, args);\n events.onToolResult?.(server, tool, result);\n return result;\n },\n\n async readResource(server, uri) {\n const serverState = state.servers.get(server);\n if (!serverState) {\n throw new Error(\n `[Directive MCP] Unknown server '${server}'. ` +\n `Available servers: ${Array.from(state.servers.keys()).join(\", \") || \"(none)\"}`,\n );\n }\n if (!serverState.client) {\n throw new Error(\n `[Directive MCP] Server '${server}' is not connected. ` +\n `Call 'adapter.connect()' or 'adapter.connectServer(\"${server}\")' first.`,\n );\n }\n const result = await serverState.client.readResource(uri);\n events.onResourceUpdate?.(server, uri, result);\n return result;\n },\n\n syncResources,\n\n getServerStatus(name) {\n return state.servers.get(name);\n },\n\n getAllServerStatuses() {\n return new Map(state.servers);\n },\n\n approve(requestId: string) {\n const request = state.pendingApprovals.get(requestId);\n if (!request && !approvalWaiters.has(requestId)) {\n throw new Error(\n `[Directive MCP] No pending approval request with ID '${requestId}'. ` +\n `Pending requests: ${Array.from(state.pendingApprovals.keys()).join(\", \") || \"(none)\"}`,\n );\n }\n resolveApproval(requestId, true);\n },\n\n reject(requestId: string, reason?: string) {\n const request = state.pendingApprovals.get(requestId);\n if (!request && !approvalWaiters.has(requestId)) {\n throw new Error(\n `[Directive MCP] No pending approval request with ID '${requestId}'. ` +\n `Pending requests: ${Array.from(state.pendingApprovals.keys()).join(\", \") || \"(none)\"}`,\n );\n }\n resolveApproval(requestId, false, reason);\n },\n\n getPendingApprovals() {\n return Array.from(state.pendingApprovals.values());\n },\n\n getRejectionReason(requestId: string): string | undefined {\n return rejectionReasons.get(requestId);\n },\n };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/** Cache for compiled glob patterns to avoid repeated regex compilation */\nconst globCache = new Map<string, RegExp>();\nconst MAX_GLOB_CACHE_SIZE = 200;\n\n/** Simple glob matching (supports * and **) with caching */\nfunction matchGlob(str: string, pattern: string): boolean {\n let regex = globCache.get(pattern);\n if (!regex) {\n // Escape all regex metacharacters first, then convert glob wildcards\n const regexPattern = pattern\n .replace(/\\*\\*/g, \"\\0GLOBSTAR\\0\")\n .replace(/\\*/g, \"\\0STAR\\0\")\n .replace(/\\?/g, \"\\0QUESTION\\0\")\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\0GLOBSTAR\\0/g, \".*\")\n .replace(/\\0STAR\\0/g, \"[^/]*\")\n .replace(/\\0QUESTION\\0/g, \".\");\n regex = new RegExp(`^${regexPattern}$`);\n\n // LRU eviction: delete oldest entry when cache is full\n if (globCache.size >= MAX_GLOB_CACHE_SIZE) {\n const firstKey = globCache.keys().next().value;\n if (firstKey !== undefined) globCache.delete(firstKey);\n }\n globCache.set(pattern, regex);\n }\n return regex.test(str);\n}\n\n/**\n * Convert MCP tools to a format suitable for LLM tool calling.\n *\n * @example\n * ```typescript\n * const adapter = createMCPAdapter({ servers: [...] });\n * await adapter.connect();\n *\n * const tools = adapter.getTools();\n * const llmTools = convertToolsForLLM(tools);\n * // Use with OpenAI/Anthropic/etc.\n * ```\n */\nexport function convertToolsForLLM(tools: Map<string, MCPTool[]>): Array<{\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n}> {\n const result: Array<{\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }> = [];\n\n for (const [server, serverTools] of tools) {\n for (const tool of serverTools) {\n result.push({\n type: \"function\",\n function: {\n name: `${server}.${tool.name}`,\n description: tool.description ?? `Tool: ${tool.name}`,\n parameters: tool.inputSchema,\n },\n });\n }\n }\n\n return result;\n}\n\n/**\n * Create a requirement to call an MCP tool.\n *\n * @example\n * ```typescript\n * const req = mcpCallTool('filesystem', 'read_file', { path: '/etc/hosts' });\n * // { type: 'MCP_CALL_TOOL', server: 'filesystem', tool: 'read_file', args: { path: '/etc/hosts' } }\n * ```\n */\nexport function mcpCallTool(\n server: string,\n tool: string,\n args: Record<string, unknown>,\n): MCPCallToolRequirement {\n return { type: \"MCP_CALL_TOOL\", server, tool, args };\n}\n\n/**\n * Create a requirement to read an MCP resource.\n */\nexport function mcpReadResource(\n server: string,\n uri: string,\n): MCPReadResourceRequirement {\n return { type: \"MCP_READ_RESOURCE\", server, uri };\n}\n\n/**\n * Create a requirement to get an MCP prompt.\n */\nexport function mcpGetPrompt(\n server: string,\n prompt: string,\n args?: Record<string, string>,\n): MCPGetPromptRequirement {\n return { type: \"MCP_GET_PROMPT\", server, prompt, args };\n}\n\n/**\n * Create a requirement to sync MCP resources.\n */\nexport function mcpSyncResources(\n server?: string,\n pattern?: string | RegExp,\n): MCPSyncResourcesRequirement {\n return { type: \"MCP_SYNC_RESOURCES\", server, pattern };\n}\n\n// Re-export types\nexport * from \"./mcp-types.js\";\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
'use strict';var internals=require('@directive-run/core/internals');function R(t){if(!internals.isPrototypeSafe(t))throw new Error("[Directive] structured-output: extracted JSON contains unsafe prototype keys")}var O=1048576;function k(t){if(t.length>O)throw new Error(`[Directive] Output too large for JSON extraction (${t.length} chars, max ${O}).`);let n=t.trim();try{let e=JSON.parse(n);return R(e),e}catch(e){if(e instanceof Error&&e.message.startsWith("[Directive] structured-output:"))throw e}let r=n.indexOf("{"),s=n.indexOf("["),i,f,l;if(r===-1&&s===-1)throw new Error("[Directive] No JSON object or array found in output");r===-1?(i=s,f="[",l="]"):s===-1?(i=r,f="{",l="}"):(i=Math.min(r,s),f=i===r?"{":"[",l=i===r?"}":"]");let p=0,d=false,g=false;for(let e=i;e<n.length;e++){let a=n[e];if(g){g=false;continue}if(a==="\\"){g=true;continue}if(a==='"'){d=!d;continue}if(!d){if(a===f)p++;else if(a===l&&(p--,p===0)){let u=n.slice(i,e+1),o;try{o=JSON.parse(u);}catch{let h=u.replace(/"(?:[^"\\]|\\.)*"/g,c=>c.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"));o=JSON.parse(h);}return R(o),o}}}throw new Error("[Directive] No valid JSON found in output")}function y(t){return t?t.issues&&t.issues.length>0?t.issues.map(n=>n.message).join("; "):t.message??"Validation failed":"Validation failed"}function J(t,n){let{schema:r,maxRetries:s=2,extractJson:i=k,schemaDescription:f}=n;if(!Number.isFinite(s)||s<0)throw new Error("[Directive] withStructuredOutput: maxRetries must be a non-negative finite number.");let l=f??r.description??"the specified JSON schema";return async(p,d,g)=>{let e={...p,instructions:`${p.instructions??""}
|
|
2
|
+
|
|
3
|
+
IMPORTANT: Respond with valid JSON matching ${l}. Output ONLY the JSON object, no additional text or markdown formatting.`},a,u;for(let o=0;o<=s;o++){let h=o===0?d:`${d}
|
|
4
|
+
|
|
5
|
+
Your previous response was not valid JSON. Error: ${u}
|
|
6
|
+
Please try again with valid JSON only.`,c=await t(e,h,g);a=c;let x=typeof c.output=="string"?c.output:JSON.stringify(c.output);try{let m=i(x),w=r.safeParse(m);if(w.success)return {...c,output:w.data};u=y(w.error);}catch(m){u=m instanceof Error?m.message:String(m);}}throw new S(`[Directive] Failed to get valid structured output after ${s+1} attempts: ${u}`,a)}}var S=class extends Error{lastResult;constructor(n,r){super(n),this.name="StructuredOutputError",this.lastResult=r;}};exports.a=k;exports.b=J;exports.c=S;//# sourceMappingURL=chunk-WCQK3JOR.cjs.map
|
|
7
|
+
//# sourceMappingURL=chunk-WCQK3JOR.cjs.map
|