@directive-run/ai 1.23.0 → 1.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -0
- package/dist/anthropic.cjs +1 -1
- package/dist/anthropic.cjs.map +1 -1
- package/dist/anthropic.d.cts +33 -1
- package/dist/anthropic.d.ts +33 -1
- package/dist/anthropic.js +1 -1
- package/dist/anthropic.js.map +1 -1
- package/dist/{chunk-MPMBFW2P.cjs → chunk-25OLDNZ3.cjs} +3 -3
- package/dist/chunk-25OLDNZ3.cjs.map +1 -0
- package/dist/chunk-2Y4YWZDV.js +3 -0
- package/dist/chunk-2Y4YWZDV.js.map +1 -0
- package/dist/{chunk-J2Q5KKPN.js → chunk-437ADRES.js} +3 -3
- package/dist/{chunk-J2Q5KKPN.js.map → chunk-437ADRES.js.map} +1 -1
- package/dist/{chunk-ESJQSOKJ.cjs → chunk-4LENWYLG.cjs} +7 -7
- package/dist/{chunk-ESJQSOKJ.cjs.map → chunk-4LENWYLG.cjs.map} +1 -1
- package/dist/chunk-4TDH6ZTX.cjs +3 -0
- package/dist/chunk-4TDH6ZTX.cjs.map +1 -0
- package/dist/{chunk-K64WKZ22.cjs → chunk-AEX7HKNM.cjs} +2 -2
- package/dist/chunk-AEX7HKNM.cjs.map +1 -0
- package/dist/{chunk-7KCLEIAG.js → chunk-CMH5TJGN.js} +15 -15
- package/dist/chunk-CMH5TJGN.js.map +1 -0
- package/dist/{chunk-LOHC2KP5.js → chunk-EUB4NVVN.js} +3 -3
- package/dist/{chunk-LOHC2KP5.js.map → chunk-EUB4NVVN.js.map} +1 -1
- package/dist/{chunk-CXWHLEBQ.js → chunk-H7UFBMLV.js} +3 -3
- package/dist/{chunk-CXWHLEBQ.js.map → chunk-H7UFBMLV.js.map} +1 -1
- package/dist/{chunk-TEPEQE42.js → chunk-L6H6Y6IK.js} +3 -3
- package/dist/chunk-L6H6Y6IK.js.map +1 -0
- package/dist/{chunk-PEM2LPOC.cjs → chunk-L7QHLH6U.cjs} +4 -4
- package/dist/{chunk-PEM2LPOC.cjs.map → chunk-L7QHLH6U.cjs.map} +1 -1
- package/dist/{chunk-GWWZXJOG.cjs → chunk-LPTC3N2Z.cjs} +15 -15
- package/dist/chunk-LPTC3N2Z.cjs.map +1 -0
- package/dist/{chunk-GTB6HTZV.js → chunk-MRKU3UXH.js} +2 -2
- package/dist/chunk-MRKU3UXH.js.map +1 -0
- package/dist/{chunk-UR5BMWEN.js → chunk-XMEJN4FA.js} +2 -2
- package/dist/chunk-XMEJN4FA.js.map +1 -0
- package/dist/{chunk-MDXDPECP.cjs → chunk-Y4A4UJPU.cjs} +2 -2
- package/dist/chunk-Y4A4UJPU.cjs.map +1 -0
- package/dist/{chunk-XN5LUOVS.cjs → chunk-ZUNORULG.cjs} +7 -7
- package/dist/{chunk-XN5LUOVS.cjs.map → chunk-ZUNORULG.cjs.map} +1 -1
- package/dist/{debug-timeline-DpnRMnLU.d.cts → debug-timeline-B_bXRStF.d.cts} +1 -1
- package/dist/{debug-timeline-L13P-U2I.d.ts → debug-timeline-Btt-iaak.d.ts} +1 -1
- package/dist/devtools.d.cts +5 -5
- package/dist/devtools.d.ts +5 -5
- package/dist/evals.cjs +1 -1
- package/dist/evals.d.cts +2 -2
- package/dist/evals.d.ts +2 -2
- package/dist/evals.js +1 -1
- package/dist/gemini.cjs +1 -1
- package/dist/gemini.d.cts +1 -1
- package/dist/gemini.d.ts +1 -1
- package/dist/gemini.js +1 -1
- package/dist/{guardrails-export-CxCOi3sd.d.ts → guardrails-export-lvaBJlt6.d.ts} +5 -5
- package/dist/{guardrails-export-D3pKHiPp.d.cts → guardrails-export-pmpQjIKb.d.cts} +5 -5
- package/dist/guardrails.cjs +1 -1
- package/dist/guardrails.d.cts +2 -2
- package/dist/guardrails.d.ts +2 -2
- package/dist/guardrails.js +1 -1
- package/dist/{health-monitor-C6xoXrQz.d.cts → health-monitor-DqAzufyM.d.cts} +1 -1
- package/dist/{health-monitor-qL9RNMH3.d.ts → health-monitor-DrlBF6n9.d.ts} +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +12 -8
- package/dist/index.d.ts +12 -8
- package/dist/index.js +1 -1
- package/dist/{multi-agent-orchestrator-FIF4GLVR.js → multi-agent-orchestrator-PI7X7ZGP.js} +2 -2
- package/dist/{multi-agent-orchestrator-FIF4GLVR.js.map → multi-agent-orchestrator-PI7X7ZGP.js.map} +1 -1
- package/dist/multi-agent-orchestrator-Z5NK4HIJ.cjs +2 -0
- package/dist/{multi-agent-orchestrator-PHDHFCW3.cjs.map → multi-agent-orchestrator-Z5NK4HIJ.cjs.map} +1 -1
- package/dist/multi-agent.cjs +1 -1
- package/dist/multi-agent.d.cts +6 -6
- package/dist/multi-agent.d.ts +6 -6
- package/dist/multi-agent.js +1 -1
- package/dist/ollama.cjs +1 -1
- package/dist/ollama.d.cts +1 -1
- package/dist/ollama.d.ts +1 -1
- package/dist/ollama.js +1 -1
- package/dist/openai.cjs +1 -1
- package/dist/openai.d.cts +1 -1
- package/dist/openai.d.ts +1 -1
- package/dist/openai.js +1 -1
- package/dist/{orchestrator-types-DxWn77qo.d.cts → orchestrator-types-B9nrJYFx.d.cts} +3 -3
- package/dist/{orchestrator-types-BxOJllSa.d.ts → orchestrator-types-ByqFuu3O.d.ts} +3 -3
- package/dist/predicate.cjs +1 -1
- package/dist/predicate.d.cts +2 -2
- package/dist/predicate.d.ts +2 -2
- package/dist/predicate.js +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +4 -4
- package/dist/testing.d.ts +4 -4
- package/dist/testing.js +1 -1
- package/dist/{types-DJ09LjZX.d.cts → types-BzpGfUA2.d.cts} +11 -0
- package/dist/{types-DJ09LjZX.d.ts → types-BzpGfUA2.d.ts} +11 -0
- package/package.json +2 -2
- package/dist/chunk-3WO4MWJM.cjs +0 -3
- package/dist/chunk-3WO4MWJM.cjs.map +0 -1
- package/dist/chunk-7KCLEIAG.js.map +0 -1
- package/dist/chunk-GTB6HTZV.js.map +0 -1
- package/dist/chunk-GWWZXJOG.cjs.map +0 -1
- package/dist/chunk-K64WKZ22.cjs.map +0 -1
- package/dist/chunk-MDXDPECP.cjs.map +0 -1
- package/dist/chunk-MPMBFW2P.cjs.map +0 -1
- package/dist/chunk-TEPEQE42.js.map +0 -1
- package/dist/chunk-UR5BMWEN.js.map +0 -1
- package/dist/chunk-ZFLHWJ56.js +0 -3
- package/dist/chunk-ZFLHWJ56.js.map +0 -1
- package/dist/multi-agent-orchestrator-PHDHFCW3.cjs +0 -2
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';function x(t){return t.status==="running"}function C(t){return t.pending.length>0}function O(t,e){return t/1e6*e}var y=new Set(["http:","https:"]);function L(t){try{let e=new URL(t);if(!y.has(e.protocol))throw new Error(`[Directive] Invalid baseURL protocol "${e.protocol}" \u2013 only http: and https: are allowed`)}catch(e){throw e instanceof Error&&e.message.startsWith("[Directive]")?e:new Error(`[Directive] Invalid baseURL "${t}" \u2013 must be a valid URL (e.g. "https://api.openai.com/v1")`)}}function S(t){let e=t.filter(s=>s!==void 0);if(e.length===0)return;if(e.length===1)return e[0];let l=AbortSignal.any;if(typeof l=="function")return l(e);let r=new AbortController,p=e.find(s=>s.aborted);if(p)return r.abort(p.reason??void 0),r.signal;for(let s of e)s.addEventListener("abort",()=>{r.abort(s.reason??void 0);},{once:true});return r.signal}function M(t){let{fetch:e=globalThis.fetch,buildRequest:l,parseResponse:r,parseOutput:p,hooks:s}=t,b=p??(o=>{try{return JSON.parse(o)}catch{return o}});return async(o,a,f)=>{let g=Date.now();s?.onBeforeCall?.({agent:o,input:a,timestamp:g});let d=[{role:"user",content:a}];try{let{url:i,init:u}=l(o,a,d),h=S([u.signal??void 0,f?.signal]),m=h?{...u,signal:h}:u,c=await e(i,m);if(!c.ok){let R=await c.text().catch(()=>"");throw new Error(`[Directive] AgentRunner request failed: ${c.status} ${c.statusText}${R?` \u2013 ${R.slice(0,300)}`:""}`)}let n=await r(c,d),k={inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,...n.cacheReadTokens!=null?{cacheReadTokens:n.cacheReadTokens}:{},...n.cacheCreationTokens!=null?{cacheCreationTokens:n.cacheCreationTokens}:{}},T={role:"assistant",content:n.text},A=[...d,T];f?.onMessage?.(T);let w=Date.now()-g;return s?.onAfterCall?.({agent:o,input:a,output:n.text,totalTokens:n.totalTokens,tokenUsage:k,durationMs:w,timestamp:Date.now()}),{output:b(n.text),messages:A,toolCalls:[],totalTokens:n.totalTokens,tokenUsage:k}}catch(i){let u=Date.now()-g;throw i instanceof Error&&s?.onError?.({agent:o,input:a,error:i,durationMs:u,timestamp:Date.now()}),i}}}
|
|
2
|
+
exports.a=x;exports.b=C;exports.c=O;exports.d=L;exports.e=S;exports.f=M;//# sourceMappingURL=chunk-4TDH6ZTX.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-4TDH6ZTX.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent-utils.ts"],"names":["isAgentRunning","state","hasPendingApprovals","estimateCost","tokenUsage","ratePerMillionTokens","ALLOWED_PROTOCOLS","validateBaseURL","baseURL","url","err","combineSignals","signals","live","anyFn","controller","already","createRunner","options","fetchFn","buildRequest","parseResponse","parseOutput","hooks","parse","text","agent","input","runOptions","startTime","messages","init","combined","fetchInit","response","errBody","parsed","assistantMessage","allMessages","durationMs"],"mappings":"aA0BO,SAASA,CAAAA,CAAeC,CAAAA,CAA4B,CACzD,OAAOA,CAAAA,CAAM,SAAW,SAC1B,CAQO,SAASC,CAAAA,CAAoBD,CAAAA,CAA+B,CACjE,OAAOA,CAAAA,CAAM,OAAA,CAAQ,MAAA,CAAS,CAChC,CAiBO,SAASE,EACdC,CAAAA,CACAC,CAAAA,CACQ,CACR,OAAQD,CAAAA,CAAa,GAAA,CAAaC,CACpC,CAMA,IAAMC,CAAAA,CAAoB,IAAI,GAAA,CAAI,CAAC,QAAS,QAAQ,CA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CAAA,CAEM,CACL,MAAA,CAAQf,CAAAA,CAASY,CAAAA,CAAO,IAAI,CAAA,CAC5B,QAAA,CAAUE,EACV,SAAA,CAAW,EAAC,CACZ,WAAA,CAAaF,CAAAA,CAAO,WAAA,CACpB,WAAAhC,CACF,CACF,CAAA,MAASM,CAAAA,CAAK,CACZ,IAAM6B,EAAa,IAAA,CAAK,GAAA,EAAI,CAAIV,CAAAA,CAChC,MAAInB,CAAAA,YAAe,OACjBa,CAAAA,EAAO,OAAA,GAAU,CACf,KAAA,CAAAG,CAAAA,CACA,KAAA,CAAAC,EACA,KAAA,CAAOjB,CAAAA,CACP,UAAA,CAAA6B,CAAAA,CACA,SAAA,CAAW,IAAA,CAAK,GAAA,EAClB,CAAC,CAAA,CAGG7B,CACR,CACF,CACF","file":"chunk-4TDH6ZTX.cjs","sourcesContent":["/**\n * Agent utilities — createRunner, estimateCost, state queries, URL validation.\n */\n\nimport type {\n AdapterHooks,\n AgentLike,\n AgentRunner,\n AgentState,\n ApprovalState,\n Message,\n RunOptions,\n RunResult,\n TokenUsage,\n} from \"./types.js\";\n\n// ============================================================================\n// State Query Helpers\n// ============================================================================\n\n/**\n * Check whether an agent is currently executing a run.\n *\n * @param state - The current {@link AgentState} to inspect.\n * @returns `true` when the agent status is `\"running\"`.\n */\nexport function isAgentRunning(state: AgentState): boolean {\n return state.status === \"running\";\n}\n\n/**\n * Check whether there are tool-call approvals waiting for user confirmation.\n *\n * @param state - The current {@link ApprovalState} to inspect.\n * @returns `true` when one or more approvals are pending.\n */\nexport function hasPendingApprovals(state: ApprovalState): boolean {\n return state.pending.length > 0;\n}\n\n// ============================================================================\n// Cost Estimation\n// ============================================================================\n\n/**\n * Estimate the dollar cost of an agent run based on total token usage.\n *\n * @remarks\n * No default rate is provided — callers must supply the current per-million-token\n * price to avoid silently using stale pricing.\n *\n * @param tokenUsage - Total number of tokens consumed (input + output).\n * @param ratePerMillionTokens - Cost in dollars per one million tokens.\n * @returns Estimated cost in dollars.\n */\nexport function estimateCost(\n tokenUsage: number,\n ratePerMillionTokens: number,\n): number {\n return (tokenUsage / 1_000_000) * ratePerMillionTokens;\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\nconst ALLOWED_PROTOCOLS = new Set([\"http:\", \"https:\"]);\n\n/**\n * Validate that a base URL uses the `http:` or `https:` protocol.\n * Throws immediately at adapter creation time (not at call time) to surface\n * configuration errors before any LLM requests are made.\n *\n * @param baseURL - The base URL string to validate.\n * @throws When the URL is malformed or uses a protocol other than `http:` or `https:`.\n */\nexport function validateBaseURL(baseURL: string): void {\n try {\n const url = new URL(baseURL);\n if (!ALLOWED_PROTOCOLS.has(url.protocol)) {\n throw new Error(\n `[Directive] Invalid baseURL protocol \"${url.protocol}\" – only http: and https: are allowed`,\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith(\"[Directive]\")) {\n throw err;\n }\n\n throw new Error(\n `[Directive] Invalid baseURL \"${baseURL}\" – must be a valid URL (e.g. \"https://api.openai.com/v1\")`,\n );\n }\n}\n\n// ============================================================================\n// AbortSignal combination helper\n// ============================================================================\n\n/**\n * Combine multiple `AbortSignal`s into one — the resulting signal aborts\n * as soon as ANY input signal aborts. Falls back to a manual controller\n * wiring on runtimes without `AbortSignal.any` (Node < 20).\n *\n * @internal\n */\nexport function combineSignals(\n signals: ReadonlyArray<AbortSignal | undefined>,\n): AbortSignal | undefined {\n const live = signals.filter((s): s is AbortSignal => s !== undefined);\n if (live.length === 0) return undefined;\n if (live.length === 1) return live[0];\n\n // Prefer the standard helper when available (Node 20.3+, modern browsers).\n const anyFn = (\n AbortSignal as unknown as {\n any?: (signals: readonly AbortSignal[]) => AbortSignal;\n }\n ).any;\n if (typeof anyFn === \"function\") {\n return anyFn(live);\n }\n\n // Fallback: manual controller. If any input is already aborted, the\n // result is too — wire listeners for the rest.\n const controller = new AbortController();\n const already = live.find((s) => s.aborted);\n if (already) {\n controller.abort(\n (already as AbortSignal & { reason?: unknown }).reason ?? undefined,\n );\n\n return controller.signal;\n }\n for (const s of live) {\n s.addEventListener(\n \"abort\",\n () => {\n controller.abort(\n (s as AbortSignal & { reason?: unknown }).reason ?? undefined,\n );\n },\n { once: true },\n );\n }\n\n return controller.signal;\n}\n\n// ============================================================================\n// createRunner Helper\n// ============================================================================\n\n/** Parsed response from an LLM provider */\nexport interface ParsedResponse {\n text: string;\n totalTokens: number;\n /** Input token count, when available from the provider */\n inputTokens?: number;\n /** Output token count, when available from the provider */\n outputTokens?: number;\n /** Prompt-cache read token count, when available from the provider */\n cacheReadTokens?: number;\n /** Prompt-cache creation token count, when available from the provider */\n cacheCreationTokens?: number;\n}\n\n/** Options for creating an AgentRunner from buildRequest/parseResponse */\nexport interface CreateRunnerOptions {\n fetch?: typeof globalThis.fetch;\n buildRequest: (\n agent: AgentLike,\n input: string,\n messages: Message[],\n ) => { url: string; init: RequestInit };\n parseResponse: (\n response: Response,\n messages: Message[],\n ) => Promise<ParsedResponse>;\n parseOutput?: <T>(text: string) => T;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n}\n\n/**\n * Create an {@link AgentRunner} from `buildRequest`/`parseResponse` helpers, reducing\n * ~50 lines of fetch boilerplate to ~20 lines of configuration.\n *\n * @remarks\n * Supports lifecycle hooks for observability:\n * - `onBeforeCall` fires before each API request\n * - `onAfterCall` fires after a successful response (includes token breakdown)\n * - `onError` fires when the request fails\n *\n * Output parsing defaults to `JSON.parse` with a string fallback. Supply a custom\n * `parseOutput` to override (e.g. for structured output schemas).\n *\n * @param options - Configuration for the runner, including request building, response parsing, and hooks.\n * @returns An {@link AgentRunner} function that performs LLM calls via fetch.\n *\n * @example\n * ```typescript\n * const runClaude = createRunner({\n * buildRequest: (agent, input) => ({\n * url: \"/api/claude\",\n * init: {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * model: agent.model ?? \"claude-haiku-4-5-20251001\",\n * system: agent.instructions ?? \"\",\n * messages: [{ role: \"user\", content: input }],\n * }),\n * },\n * }),\n * parseResponse: async (res) => {\n * const data = await res.json();\n * const inputTokens = data.usage?.input_tokens ?? 0;\n * const outputTokens = data.usage?.output_tokens ?? 0;\n * return {\n * text: data.content?.[0]?.text ?? \"\",\n * totalTokens: inputTokens + outputTokens,\n * inputTokens,\n * outputTokens,\n * };\n * },\n * hooks: {\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * console.log(`LLM call: ${durationMs}ms, ${tokenUsage.inputTokens}in/${tokenUsage.outputTokens}out`);\n * },\n * },\n * });\n * ```\n *\n * @public\n */\nexport function createRunner(options: CreateRunnerOptions): AgentRunner {\n const {\n fetch: fetchFn = globalThis.fetch,\n buildRequest,\n parseResponse,\n parseOutput,\n hooks,\n } = options;\n\n const defaultParseOutput = <T>(text: string): T => {\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n };\n\n const parse = parseOutput ?? defaultParseOutput;\n\n return async <T = unknown>(\n agent: AgentLike,\n input: string,\n runOptions?: RunOptions,\n ): Promise<RunResult<T>> => {\n const startTime = Date.now();\n hooks?.onBeforeCall?.({ agent, input, timestamp: startTime });\n\n const messages: Message[] = [{ role: \"user\", content: input }];\n\n try {\n const { url, init } = buildRequest(agent, input, messages);\n\n // (Sec MAJOR) Combine signals — `buildRequest` may set\n // `init.signal` (e.g. `AbortSignal.timeout(timeoutMs)`) and the\n // caller may pass their own via `runOptions.signal`. Naively\n // overwriting one with the other silently disables whichever was\n // dropped. `combineSignals` aborts as soon as either fires.\n const combined = combineSignals([\n init.signal ?? undefined,\n runOptions?.signal,\n ]);\n const fetchInit: RequestInit = combined\n ? { ...init, signal: combined }\n : init;\n\n const response = await fetchFn(url, fetchInit);\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] AgentRunner request failed: ${response.status} ${response.statusText}${errBody ? ` – ${errBody.slice(0, 300)}` : \"\"}`,\n );\n }\n\n const parsed = await parseResponse(response, messages);\n const tokenUsage: TokenUsage = {\n inputTokens: parsed.inputTokens ?? 0,\n outputTokens: parsed.outputTokens ?? 0,\n ...(parsed.cacheReadTokens != null\n ? { cacheReadTokens: parsed.cacheReadTokens }\n : {}),\n ...(parsed.cacheCreationTokens != null\n ? { cacheCreationTokens: parsed.cacheCreationTokens }\n : {}),\n };\n\n const assistantMessage: Message = {\n role: \"assistant\",\n content: parsed.text,\n };\n const allMessages: Message[] = [...messages, assistantMessage];\n\n runOptions?.onMessage?.(assistantMessage);\n\n const durationMs = Date.now() - startTime;\n hooks?.onAfterCall?.({\n agent,\n input,\n output: parsed.text,\n totalTokens: parsed.totalTokens,\n tokenUsage,\n durationMs,\n timestamp: Date.now(),\n });\n\n return {\n output: parse<T>(parsed.text),\n messages: allMessages,\n toolCalls: [],\n totalTokens: parsed.totalTokens,\n tokenUsage,\n };\n } catch (err) {\n const durationMs = Date.now() - startTime;\n if (err instanceof Error) {\n hooks?.onError?.({\n agent,\n input,\n error: err,\n durationMs,\n timestamp: Date.now(),\n });\n }\n\n throw err;\n }\n };\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var core=require('@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]:core.t.object(),[o]:core.t.object(),[s]:core.t.array(),[i]:core.t.array(),[u]:core.t.object()},derivations:{},events:{},requirements:{}};exports.a=n;exports.b=g;exports.c=a;exports.d=o;exports.e=s;exports.f=i;exports.g=u;exports.h=d;exports.i=l;//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var core=require('@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]:core.t.object(),[o]:core.t.object(),[s]:core.t.array(),[i]:core.t.array(),[u]:core.t.object()},derivations:{},events:{},requirements:{}};exports.a=n;exports.b=g;exports.c=a;exports.d=o;exports.e=s;exports.f=i;exports.g=u;exports.h=d;exports.i=l;//# sourceMappingURL=chunk-AEX7HKNM.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-AEX7HKNM.cjs.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","t"],"mappings":"qDAwkBO,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,CAAA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,CAAgB,EAAGK,OAAE,KAAA,EAAM,CAC5B,CAACJ,CAAc,EAAGI,MAAA,CAAE,KAAA,GACpB,CAACH,CAAc,EAAGG,MAAA,CAAE,MAAA,EACtB,CAAA,CACA,WAAA,CAAa,EAAC,CACd,MAAA,CAAQ,EAAC,CACT,YAAA,CAAc,EAChB","file":"chunk-AEX7HKNM.cjs","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 * Tokens read from the provider's prompt cache, when available.\n * Populated by adapters with prompt-caching enabled (e.g. Anthropic).\n */\n cacheReadTokens?: number;\n /**\n * Tokens written to the provider's prompt cache, when available.\n * Populated by adapters with prompt-caching enabled (e.g. Anthropic).\n */\n cacheCreationTokens?: 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"]}
|