@directive-run/ai 1.22.0 → 1.23.1
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-TH2D22JP.cjs → chunk-2FPL5W2H.cjs} +7 -7
- package/dist/chunk-2FPL5W2H.cjs.map +1 -0
- package/dist/{chunk-G7CRWJT7.js → chunk-4VP67W7L.js} +15 -15
- package/dist/chunk-4VP67W7L.js.map +1 -0
- package/dist/{chunk-IR3IHBVQ.cjs → chunk-7JTR4QBA.cjs} +2 -2
- package/dist/{chunk-IR3IHBVQ.cjs.map → chunk-7JTR4QBA.cjs.map} +1 -1
- package/dist/{chunk-5JQ2A3JK.js → chunk-BZB3RDI2.js} +2 -2
- package/dist/{chunk-5JQ2A3JK.js.map → chunk-BZB3RDI2.js.map} +1 -1
- package/dist/{chunk-RHJAMXLS.js → chunk-EW77VF5K.js} +3 -3
- package/dist/{chunk-RHJAMXLS.js.map → chunk-EW77VF5K.js.map} +1 -1
- package/dist/{chunk-7EJN6TYX.cjs → chunk-F73AKFDB.cjs} +15 -15
- package/dist/chunk-F73AKFDB.cjs.map +1 -0
- package/dist/{chunk-VSVR4RFK.js → chunk-FSSCGRAM.js} +2 -2
- package/dist/chunk-FSSCGRAM.js.map +1 -0
- package/dist/{chunk-XGHNOSXT.cjs → chunk-JMG5GZAH.cjs} +4 -4
- package/dist/{chunk-XGHNOSXT.cjs.map → chunk-JMG5GZAH.cjs.map} +1 -1
- package/dist/{chunk-GTB6HTZV.js → chunk-MRKU3UXH.js} +2 -2
- package/dist/chunk-MRKU3UXH.js.map +1 -0
- package/dist/{chunk-ZGJ2XHGI.cjs → chunk-QMSLWAMH.cjs} +2 -2
- package/dist/chunk-QMSLWAMH.cjs.map +1 -0
- package/dist/{chunk-QRDBUGPO.js → chunk-XGOTVPN6.js} +3 -3
- package/dist/chunk-XGOTVPN6.js.map +1 -0
- package/dist/{chunk-MDXDPECP.cjs → chunk-Y4A4UJPU.cjs} +2 -2
- package/dist/chunk-Y4A4UJPU.cjs.map +1 -0
- package/dist/{debug-timeline-L13P-U2I.d.ts → debug-timeline-C5Dzs2r_.d.ts} +1 -1
- package/dist/{debug-timeline-DpnRMnLU.d.cts → debug-timeline-Sc9cxgxV.d.cts} +1 -1
- package/dist/devtools.cjs +1 -1
- package/dist/devtools.d.cts +5 -5
- package/dist/devtools.d.ts +5 -5
- package/dist/devtools.js +1 -1
- package/dist/evals.d.cts +2 -2
- package/dist/evals.d.ts +2 -2
- package/dist/gemini.d.cts +1 -1
- package/dist/gemini.d.ts +1 -1
- package/dist/{guardrails-export-CxCOi3sd.d.ts → guardrails-export-BL8ozXSj.d.ts} +5 -5
- package/dist/{guardrails-export-D3pKHiPp.d.cts → guardrails-export-ByaYNGvG.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-C9v10_tj.d.cts} +1 -1
- package/dist/{health-monitor-qL9RNMH3.d.ts → health-monitor-J2eKmP--.d.ts} +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +1 -1
- package/dist/multi-agent-orchestrator-DUMT67N5.cjs +2 -0
- package/dist/{multi-agent-orchestrator-OX2TKD5Y.cjs.map → multi-agent-orchestrator-DUMT67N5.cjs.map} +1 -1
- package/dist/{multi-agent-orchestrator-RMTLPKB4.js → multi-agent-orchestrator-ZZ63F75F.js} +2 -2
- package/dist/{multi-agent-orchestrator-RMTLPKB4.js.map → multi-agent-orchestrator-ZZ63F75F.js.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.d.cts +1 -1
- package/dist/ollama.d.ts +1 -1
- package/dist/openai.d.cts +1 -1
- package/dist/openai.d.ts +1 -1
- package/dist/{orchestrator-types-DxWn77qo.d.cts → orchestrator-types-BT-NIFOe.d.cts} +3 -3
- package/dist/{orchestrator-types-BxOJllSa.d.ts → orchestrator-types-DMuSD8Vq.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-6NoeLyrD.d.cts} +1 -0
- package/dist/{types-DJ09LjZX.d.ts → types-6NoeLyrD.d.ts} +1 -0
- package/package.json +2 -2
- package/dist/chunk-7EJN6TYX.cjs.map +0 -1
- package/dist/chunk-G7CRWJT7.js.map +0 -1
- package/dist/chunk-GTB6HTZV.js.map +0 -1
- package/dist/chunk-MDXDPECP.cjs.map +0 -1
- package/dist/chunk-QRDBUGPO.js.map +0 -1
- package/dist/chunk-TH2D22JP.cjs.map +0 -1
- package/dist/chunk-VSVR4RFK.js.map +0 -1
- package/dist/chunk-ZGJ2XHGI.cjs.map +0 -1
- package/dist/multi-agent-orchestrator-OX2TKD5Y.cjs +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent-orchestrator.ts"],"names":["MAX_CONVERSATION_MESSAGES","MAX_TOOL_CALLS","deprecatedModeWarned","createAgentOrchestrator","options","runner","factsSchema","init","constraints","resolvers","guardrails","onApprovalRequest","autoApproveToolCalls","maxTokenBudget","budgetWarningThreshold","onBudgetWarning","budgetEstimateTokens","retryInsideCircuit","plugins","rawDebug","approvalTimeoutMs","agentRetry","hooks","memory","circuitBreaker","selfHealing","outputSchema","maxSchemaRetries","checkpointStore","breakpoints","onBreakpoint","breakpointTimeoutMs","debug","MAX_VERBOSE_LENGTH","fireHook","name","event","hookError","RESERVED_ORCHESTRATOR_KEYS","key","combinedSchema","orchestratorBridgeSchema","t","runAgentWithGuardrailsFn","system","directiveConstraints","convertOrchestratorConstraints","facts","getAgentState","directiveResolvers","convertOrchestratorResolvers","agent","input","currentFacts","opts","requirementGuard","_req","context","currentAgent","setAgentState","timeline","createDebugTimeline","snapshotId","callbackPlugin","createCallbackPlugin","orchestratorModule","createModule","setApprovalState","setConversation","setToolCalls","setBreakpointState","setBridgeFact","state","getOrchestratorState","combinedFacts","allPlugins","createDebugTimelinePlugin","createSystem","inFlightReservation","resolveBudgetReservation","n","runAgentWithGuardrails","_currentFacts","callOptions","reserved","currentUsage","runAgentWithGuardrailsBody","withFallbackBudgetReservation","work","applySelfHealingFallback","error","fallbackRunner","rerouteEvent","fallbackAgent","runAgentWithGuardrailsInner","startTime","contextMessages","contextStr","m","metaStr","formatSystemMeta","bpContext","mods","handleBreakpoint","effectiveInputGuardrails","effectiveOutputGuardrails","inputGuardrailsList","g","normalizeGuardrail","guardrail","guardStartTime","result","executeGuardrailWithRetry","GuardrailError","effectiveSchema","effectiveRunner","withStructuredOutput","inner","a","i","o","executeAgentWithRetry","message","updated","getConversation","toolCall","toolCallGuardrails","guardResult","approvalId","approvalRequest","currentApproval","getApprovalState","waitForApproval","updatedToolCalls","getToolCalls","attempt","delayMs","outputGuardrailsList","shouldFireBudgetWarning","budgetPercentage","newTokenUsage","warningFired","getBridgeFact","callbackError","memoryError","outputStr","breakpointModifications","breakpointCancelReasons","waitForBreakpointResolution","bpId","signal","resolve","reject","settled","timeoutId","cleanupAll","onAbort","unsubscribe","BREAKPOINT_KEY","bpState","getBreakpointState","cancelReason","bpTimeout","type","match","matchBreakpoint","createBreakpointId","request","requestId","APPROVAL_KEY","approval","rejectedRequest","r","errorMsg","timeoutSeconds","getCombinedFacts","abortController","MAX_STREAM_BUFFER","chunks","waiters","closed","tokenCount","MAX_ACCUMULATED_OUTPUT","accumulatedOutput","abortHandler","cleanup","pushChunk","chunk","waiter","closeStream","liveContextUnsub","liveCfg","bridgeKeys","overlap","bk","notifyOn","interruptWhen","watched","store","lastSnapshot","current","changed","k","watchedChanged","shouldInterrupt","err","tearDownLiveContext","resultPromise","processedInput","inputGuardrails","currentConversation","newTokens","currentToolCalls","outputGuardrails","duration","stream","interruptInitiated","reason","timeoutMs","isIdle","start","MAX_APPROVAL_HISTORY","approved","MAX_REJECTION_HISTORY","rejected","cpOptions","cp","createCheckpointId","restoreOpts","validateCheckpoint","id","modifications","resolved","MAX_BREAKPOINT_HISTORY","cancelled"],"mappings":"maA4GA,IAAMA,EAAAA,CAA4B,GAAA,CAE5BC,GAAiB,GAAA,CAcnBC,EAAAA,CAAuB,KAAA,CA8bpB,SAASC,EAAAA,CAEdC,EAAAA,CAAuD,CACvD,GAAM,CACJ,MAAA,CAAAC,EAAAA,CACA,WAAA,CAAAC,EAAAA,CAAc,EAAC,CACf,IAAA,CAAAC,EAAAA,CACA,YAAAC,EAAAA,CAAc,EAAC,CACf,SAAA,CAAAC,EAAAA,CAAY,EAAC,CACb,UAAA,CAAAC,IAAa,EAAC,CACd,iBAAA,CAAAC,EAAAA,CACA,oBAAA,CAAAC,EAAAA,CAAuB,IAAA,CACvB,cAAA,CAAAC,EACA,sBAAA,CAAAC,EAAAA,CAAyB,EAAA,CACzB,eAAA,CAAAC,GACA,oBAAA,CAAAC,EAAAA,CACA,kBAAA,CAAAC,EAAAA,CAAqB,MACrB,OAAA,CAAAC,EAAAA,CAAU,EAAC,CACX,KAAA,CAAOC,EAAAA,CAAW,KAAA,CAClB,iBAAA,CAAAC,GAAoB,GAAA,CACpB,UAAA,CAAAC,EAAAA,CACA,KAAA,CAAAC,EAAAA,CAAQ,EAAC,CACT,MAAA,CAAAC,EACA,cAAA,CAAAC,GAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,EAAAA,CACA,gBAAA,CAAAC,EAAAA,CACA,gBAAAC,EAAAA,CACA,WAAA,CAAAC,CAAAA,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AAA,CACvCC,CACR,CAAC,EACH,CAAC,EACH,CAAA,CAEA,qBAAA,EAA6C,CAG3C,OAAO,CAAC,GAFQ1E,EAAmBpH,GAAAA,CAAO,KAAK,CAAA,CAE5B,OAAO,CAC5B,CAAA,CAEA,OAAA,EAAgB,CACdA,GAAAA,CAAO,OAAA,GACT,CACF,CAGF","file":"chunk-XGOTVPN6.js","sourcesContent":["/**\n * Agent Orchestrator — constraint-driven agent execution with guardrails.\n *\n * Single-agent orchestrator backed by a Directive System with reactive state,\n * constraints, guardrails, streaming, approval workflow, and lifecycle hooks.\n */\n\nimport type {\n ModuleSchema,\n Plugin,\n Requirement,\n SingleModuleSystem,\n System,\n} from \"@directive-run/core\";\nimport { createModule, t } from \"@directive-run/core\";\nimport { createSystem } from \"@directive-run/core\";\nimport {\n createCallbackPlugin,\n getBridgeFact,\n requirementGuard,\n setBridgeFact,\n} from \"@directive-run/core/adapter-utils\";\nimport type { CircuitBreaker } from \"@directive-run/core/plugins\";\nimport type { AgentMemory } from \"./memory.js\";\nimport { formatSystemMeta } from \"./meta-context.js\";\nimport type { StreamChunk as StreamChunkBase } from \"./streaming.js\";\n\nimport type {\n AgentLike,\n AgentRetryConfig,\n AgentRunner,\n ApprovalRequest,\n GuardrailFn,\n GuardrailsConfig,\n InputGuardrailData,\n NamedGuardrail,\n OrchestratorConstraint,\n OrchestratorLifecycleHooks,\n OrchestratorResolver,\n OrchestratorState,\n OutputGuardrailData,\n RejectedRequest,\n RerouteEvent,\n RunOptions,\n RunResult,\n SelfHealingConfig,\n} from \"./types.js\";\n\nimport {\n APPROVAL_KEY,\n BREAKPOINT_KEY,\n GuardrailError,\n orchestratorBridgeSchema,\n} from \"./types.js\";\n\nimport {\n type DebugTimeline,\n createDebugTimeline,\n createDebugTimelinePlugin,\n} from \"./debug-timeline.js\";\n\nimport {\n executeAgentWithRetry,\n executeGuardrailWithRetry,\n normalizeGuardrail,\n} from \"./guardrail-utils.js\";\n\nimport {\n convertOrchestratorConstraints,\n convertOrchestratorResolvers,\n getAgentState,\n getApprovalState,\n getBreakpointState,\n getConversation,\n getOrchestratorState,\n getToolCalls,\n setAgentState,\n setApprovalState,\n setBreakpointState,\n setConversation,\n setToolCalls,\n} from \"./orchestrator-bridge.js\";\n\nimport type {\n BreakpointConfig,\n BreakpointContext,\n BreakpointModifications,\n BreakpointRequest,\n} from \"./breakpoints.js\";\nimport {\n MAX_BREAKPOINT_HISTORY,\n createBreakpointId,\n matchBreakpoint,\n} from \"./breakpoints.js\";\nimport {\n type Checkpoint,\n type CheckpointStore,\n createCheckpointId,\n validateCheckpoint,\n} from \"./checkpoint.js\";\nimport {\n type SafeParseable,\n withStructuredOutput,\n} from \"./structured-output.js\";\n\n// Bridge accessors and constraint/resolver converters imported from orchestrator-bridge.ts\n\n/** Maximum conversation messages retained (FIFO eviction) */\nconst MAX_CONVERSATION_MESSAGES = 500;\n/** Maximum tool calls retained (FIFO eviction) */\nconst MAX_TOOL_CALLS = 200;\n\n/** Built-in pause requirement type */\ninterface PauseBudgetExceededReq extends Requirement {\n type: \"__PAUSE_BUDGET_EXCEEDED\";\n}\n\n// ============================================================================\n// Exported Types\n// ============================================================================\n\n// — one-shot deprecation warning for the v1.18.0 `mode` field\n// on `LiveContextOptions`. Module-scope so the warning fires once per\n// process, not per `runStream` call.\nlet deprecatedModeWarned = false;\n\n/** Orchestrator options */\nexport interface OrchestratorOptions<F extends Record<string, unknown>> {\n /** Function to run an agent */\n runner: AgentRunner;\n /**\n * Schema for custom facts tracked in the orchestrator's Directive System.\n * @example\n * ```typescript\n * import { t } from '@directive-run/core';\n * const orchestrator = createAgentOrchestrator({\n * factsSchema: { confidence: t.number(), category: t.string() },\n * // ...\n * });\n * ```\n */\n factsSchema?: Record<string, { _type: unknown; _validators: [] }>;\n /** Initialize additional facts */\n init?: (facts: F & OrchestratorState) => void;\n /** Constraints for orchestration */\n constraints?: Record<string, OrchestratorConstraint<F>>;\n /** Resolvers for orchestration */\n resolvers?: Record<string, OrchestratorResolver<F, Requirement>>;\n /** Guardrails */\n guardrails?: GuardrailsConfig;\n /** Callback for approval requests */\n onApprovalRequest?: (request: ApprovalRequest) => void;\n /**\n * Auto-approve tool calls\n * @default true\n */\n autoApproveToolCalls?: boolean;\n /**\n * Maximum token budget across all agent runs.\n *\n * When exceeded, agents are automatically paused with status \"paused\".\n * Check `facts.agent.tokenUsage` to see current usage.\n *\n * For more sophisticated cost management (per-user budgets, tiered pricing,\n * cost alerts), see the Cost Management section in the documentation.\n *\n * @example\n * ```typescript\n * const orchestrator = createAgentOrchestrator({\n * maxTokenBudget: 10000, // Pause after 10K tokens\n * });\n *\n * // Check if paused due to budget\n * if (orchestrator.facts.agent.status === 'paused') {\n * console.log('Budget exceeded:', orchestrator.facts.agent.tokenUsage);\n * }\n * ```\n */\n maxTokenBudget?: number;\n /** Fires when token usage reaches this percentage of maxTokenBudget (0-1). @default 0.8 */\n budgetWarningThreshold?: number;\n /** Callback when budget warning threshold is reached */\n onBudgetWarning?: (event: {\n currentTokens: number;\n maxBudget: number;\n percentage: number;\n }) => void;\n /**\n * Optional reservation hint for the budget pre-flight check. When set\n * (number or per-call callback), the orchestrator reserves that many\n * tokens for each in-flight call so concurrent runs cannot collectively\n * overshoot `maxTokenBudget`. Without this, the pre-flight only catches\n * the \"already over\" case — N concurrent runs can each individually\n * read `tokenUsage = 0` and overshoot together (TOCTOU).\n *\n * - `undefined` (default): pre-flight only checks the already-over\n * condition. Concurrent runs may still collectively overshoot.\n * - `number`: reserve this many tokens per call (typical small-agent\n * ceiling is 2000–8000).\n * - `(input, agent) => number`: per-call estimate.\n *\n * @example\n * ```ts\n * createAgentOrchestrator({\n * maxTokenBudget: 100_000,\n * budgetEstimateTokens: 5_000, // conservative reservation per call\n * });\n * ```\n */\n budgetEstimateTokens?: number | ((input: string, agent: AgentLike) => number);\n /**\n * Controls how `circuitBreaker` composes with `agentRetry`.\n *\n * Prior to v1.21, the orchestrator wrapped the entire retry loop in\n * one `circuitBreaker.execute(...)` call — `attempts: 3` +\n * `failureThreshold: 5` required 15 real upstream failures before the\n * breaker opened. That's the retry-storm anti-pattern: a transient\n * provider outage cost roughly `attempts × failureThreshold` calls\n * before any protection kicked in.\n *\n * The new default (`false`) routes each retry attempt through the\n * breaker individually. Each failed attempt counts toward\n * `failureThreshold`; if the breaker opens partway through retries,\n * the remaining attempts short-circuit and the orchestrator surfaces\n * the breaker's open-circuit error to the caller. This is the\n * correct semantic under sustained upstream failure.\n *\n * Set to `true` for the legacy behavior (one breaker call per\n * top-level run, retries hidden from the breaker).\n *\n * @default false\n */\n retryInsideCircuit?: boolean;\n /** Plugins */\n plugins?: Plugin[];\n /**\n * Enable debugging — `true` for default debug, or config object for advanced options\n * @default false\n */\n debug?: boolean | import(\"./types.js\").OrchestratorDebugConfig;\n /**\n * Approval timeout in milliseconds\n * @default 300000 (5 minutes)\n */\n approvalTimeoutMs?: number;\n /** Retry configuration for agent runs (no retries if not specified) */\n agentRetry?: AgentRetryConfig;\n /** Lifecycle hooks for observability */\n hooks?: OrchestratorLifecycleHooks;\n /**\n * Optional memory instance. When provided, context messages are auto-injected\n * into agent instructions before each run, and result messages are auto-stored.\n */\n memory?: AgentMemory;\n /**\n * Optional circuit breaker. Wraps every run() call.\n * When OPEN, throws CircuitBreakerOpenError instead of calling the agent.\n */\n circuitBreaker?: CircuitBreaker;\n /** Self-healing configuration for automatic fallback */\n selfHealing?: SelfHealingConfig;\n /**\n * Default schema for structured output. When set, agent output is parsed and\n * validated against this schema with automatic retry on failure.\n * Any Zod-compatible schema (anything with `safeParse`) works.\n */\n outputSchema?: SafeParseable<unknown>;\n /**\n * Max retries for structured output parsing.\n * @default 2\n */\n maxSchemaRetries?: number;\n /** Optional checkpoint store for save/restore workflow state. */\n checkpointStore?: CheckpointStore;\n /**\n * Breakpoint configurations for human-in-the-loop pause points.\n * Zero overhead when empty — guard checks at each insertion point.\n */\n breakpoints?: BreakpointConfig[];\n /** Callback fired when a breakpoint is hit and waiting for resolution. */\n onBreakpoint?: (request: BreakpointRequest) => void;\n /**\n * Timeout for breakpoint resolution in milliseconds.\n * @default 300000 (5 minutes)\n */\n breakpointTimeoutMs?: number;\n /**\n * Include system meta in agent instructions for structured LLM reasoning.\n * When true, constraint labels, resolver descriptions, fact annotations,\n * and module metadata are injected into the agent's system prompt.\n * @default false\n */\n metaContext?: boolean;\n}\n\n/** Streaming run result from orchestrator */\nexport interface OrchestratorStreamResult<T = unknown> {\n /** Async iterator for streaming chunks */\n stream: AsyncIterable<OrchestratorStreamChunk>;\n /** Promise that resolves to the final result */\n result: Promise<RunResult<T>>;\n /** Abort the stream */\n abort: () => void;\n /**\n * RFC 0005: cancel the in-flight generation but keep the\n * `liveContext` subscription attached. Distinct from `abort()`:\n * `abort` tears the AsyncIterable down AND detaches liveContext;\n * `interrupt` cancels the LLM run but leaves the orchestrator's\n * fact subscriptions alive so the next caller-driven prompt\n * continues against fresh facts. The optional `reason` lands on\n * the emitted `interrupted` chunk.\n */\n interrupt: (reason?: string) => void;\n}\n\n/** Stream chunk types for orchestrator — extends StreamChunk with approval events */\nexport type OrchestratorStreamChunk =\n | StreamChunkBase\n | { type: \"approval_required\"; requestId: string; toolName: string }\n | { type: \"approval_resolved\"; requestId: string; approved: boolean }\n /**\n * RFC 0005: a `liveContext`-watched fact changed. Carries the keys\n * whose values changed in this batch so the consumer can decide\n * whether to re-render the system prompt mid-stream. Always emitted\n * when `notifyOn: \"all-changes\"`; emitted only for keys whose\n * change `interruptWhen` returned `true` for when `notifyOn:\n * \"interrupt-only\"` (the default).\n */\n | { type: \"context_updated\"; changedKeys: readonly string[] }\n /**\n * RFC 0005: `liveContext.interruptWhen` returned `true` for at\n * least one changed key. The orchestrator aborted the in-flight\n * LLM run and emits this chunk with the partial output captured\n * up to the abort point. The consumer is responsible for\n * re-prompting via a fresh `runStream` call against the still-live\n * liveContext subscription (or for fully tearing the run down via\n * `result.abort()`). A follow-up RFC will add automatic re-invocation\n * once the design is settled.\n */\n | {\n type: \"interrupted\";\n reason: string;\n partialOutput: string;\n changedKeys: readonly string[];\n };\n\n/**\n * RFC 0005: live-context options for `runStream`. Wires a Directive\n * system's fact subscriptions into the in-flight LLM run so the\n * agent's view of the world stays in sync with reality.\n *\n * @example Market dashboard agent reacting to price ticks\n * ```ts\n * const result = orchestrator.runStream(agent, \"Summarize current state\", {\n * liveContext: {\n * system: marketSystem,\n * keys: [\"lastPrice\"],\n * interruptWhen: (facts) => Math.abs(facts.lastPrice - facts.openPrice) > 5,\n * },\n * });\n * ```\n */\nexport interface LiveContextOptions<\n F extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** The Directive system whose facts feed the agent. */\n system: System<any>;\n /**\n * Fact keys to watch. The orchestrator subscribes to fact-change\n * notifications keyed on these names. Other facts change without\n * notifying the agent — keep this list tight to bound work.\n */\n keys: readonly (keyof F & string)[];\n /**\n * Predicate run on every batch of fact changes that touches a\n * watched key. Return `true` to interrupt the in-flight LLM run.\n * Receives the FULL fact snapshot + the array of changed keys so\n * the predicate can look at correlations (price + volume, headSha +\n * prState, etc.). Optional — defaults to `() => true` (interrupt\n * on every watched-key change).\n */\n interruptWhen?: (facts: F, changedKeys: readonly string[]) => boolean;\n /**\n * @deprecated The `mode` field has no behavior in 1.x — the 1.18\n * landing ships a single behavior (abort the LLM run, emit an\n * `interrupted` chunk, hand control back to the caller; the caller\n * re-prompts via a fresh `runStream` or tears down via `abort()`).\n * The field was briefly added in 1.18.0 with two declared values\n * (`\"inject-system-message\"` and `\"restart\"`) but the orchestrator\n * never read it, so neither value did what its name implied.\n * Setting this field is a no-op at runtime and the orchestrator\n * emits a one-shot dev-mode warning when it's set to a non-default\n * value. The follow-up RFC for automatic re-prompt semantics will\n * re-introduce the field alongside an impl that actually reads it;\n * until then this slot is kept solely for source-compat with v1.18\n * call sites — pass nothing or remove the field for current\n * abort-and-emit behavior.\n */\n mode?: \"inject-system-message\" | \"restart\";\n /**\n * `\"all-changes\"` emits `context_updated` for every watched-key\n * batch (so the consumer can render a sidebar of fact deltas).\n * `\"interrupt-only\"` (default) emits only for changes that hit\n * `interruptWhen === true`. Choose the noisier variant when\n * you want a live view; choose the default when you only care\n * about the interruption moments.\n */\n notifyOn?: \"all-changes\" | \"interrupt-only\";\n /**\n * Optional hook fired on every watched-key change AFTER the\n * `interruptWhen` predicate runs but BEFORE the chunk emits.\n * Useful for logging / instrumentation that should fire regardless\n * of `notifyOn`.\n */\n onContextUpdate?: (changedKeys: readonly string[]) => void;\n}\n\n/** Per-call options for run() */\nexport interface RunCallOptions {\n /** Override output guardrails for this call only. Set to [] to skip. */\n outputGuardrails?: Array<\n GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>\n >;\n /** Override input guardrails for this call only. Set to [] to skip. */\n inputGuardrails?: Array<\n GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>\n >;\n /** Signal for abort */\n signal?: AbortSignal;\n /** Override structured output schema for this call. Set to `null` to opt out. */\n outputSchema?: SafeParseable<unknown> | null;\n /** Override max schema retries for this call. */\n maxSchemaRetries?: number;\n}\n\n/** Orchestrator instance */\nexport interface AgentOrchestrator<F extends Record<string, unknown>> {\n system: System<any>;\n facts: F & OrchestratorState;\n /** Run an agent with guardrails. Pass options to override guardrails per-call. */\n run<T>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): Promise<RunResult<T>>;\n /**\n * Run an agent with streaming support.\n * Returns an async iterator for chunks and a promise for the final result.\n *\n * @example\n * ```typescript\n * const { stream, result, abort } = orchestrator.runStream(agent, input);\n *\n * for await (const chunk of stream) {\n * if (chunk.type === 'token') process.stdout.write(chunk.data);\n * if (chunk.type === 'approval_required') showApprovalDialog(chunk);\n * if (chunk.type === 'guardrail_triggered') handleGuardrail(chunk);\n * }\n *\n * const finalResult = await result;\n * ```\n */\n runStream<T>(\n agent: AgentLike,\n input: string,\n options?: {\n signal?: AbortSignal;\n /**\n * RFC 0005: bind the in-flight LLM run to a Directive system's\n * facts. When a watched fact changes, the orchestrator emits a\n * `context_updated` chunk; when `interruptWhen` returns `true`,\n * the LLM run is aborted and an `interrupted` chunk lands on\n * the stream. The companion `createFactPIIGuardrail` plugin\n * MUST be wired on the same system when watched facts may\n * carry PII — `liveContext` expands the source → fact → prompt\n * bypass surface into mid-stream context updates.\n */\n liveContext?: LiveContextOptions<F & OrchestratorState>;\n },\n ): OrchestratorStreamResult<T>;\n /** Approve a pending request */\n approve(requestId: string): void;\n /** Reject a pending request */\n reject(requestId: string, reason?: string): void;\n /** Pause all agents */\n pause(): void;\n /** Resume agents */\n resume(): void;\n /** Reset conversation state */\n reset(): void;\n /** Total tokens consumed across all agent runs */\n readonly totalTokens: number;\n /** Debug timeline (null when debug is false) */\n readonly timeline: DebugTimeline | null;\n /** Wait until agent is idle. Resolves immediately if already idle. */\n waitForIdle(timeoutMs?: number): Promise<void>;\n /** Create a checkpoint of the current orchestrator state. Only valid when agent is not running. */\n checkpoint(options?: { label?: string }): Promise<Checkpoint>;\n /** Restore orchestrator state from a checkpoint. */\n restore(\n checkpoint: Checkpoint,\n options?: { restoreTimeline?: boolean },\n ): void;\n /** Resume a pending breakpoint, optionally with input modifications. */\n resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;\n /** Cancel a pending breakpoint with optional reason. */\n cancelBreakpoint(id: string, reason?: string): void;\n /** Get all currently pending breakpoint requests. */\n getPendingBreakpoints(): BreakpointRequest[];\n /** Destroy the orchestrator, releasing all resources. */\n destroy(): void;\n}\n\n// ============================================================================\n// Main Factory\n// ============================================================================\n\n/**\n * Create a constraint-driven agent orchestrator backed by a Directive System.\n *\n * Wraps a single agent runner with reactive state, guardrails, streaming,\n * approval workflows, breakpoints, structured output, and lifecycle hooks.\n * Constraints and resolvers let you declaratively control agent behavior\n * based on runtime facts.\n *\n * @param options - Orchestrator configuration including runner, guardrails, constraints, and plugins.\n * @returns An {@link AgentOrchestrator} instance with `run`, `runStream`, `approve`/`reject`, and checkpoint APIs.\n *\n * @example\n * ```typescript\n * import { run as runner } from '@openai/agents';\n *\n * const orchestrator = createAgentOrchestrator({\n * runner,\n * constraints: {\n * escalateToExpert: {\n * when: (facts) => facts.agent.output?.confidence < 0.7,\n * require: (facts) => ({\n * type: 'RUN_EXPERT_AGENT',\n * query: facts.agent.input,\n * }),\n * },\n * budgetExceeded: {\n * when: (facts) => facts.agent.tokenUsage > 10000,\n * require: { type: 'PAUSE_AGENTS' },\n * },\n * },\n * guardrails: {\n * input: [\n * async (data) => {\n * const hasPII = (await detectPII(data.input)).detected;\n * return { passed: !hasPII, reason: hasPII ? 'Contains PII' : undefined };\n * },\n * ],\n * output: [\n * async (data) => {\n * const isToxic = await checkToxicity(data.output);\n * return { passed: !isToxic, reason: isToxic ? 'Toxic content' : undefined };\n * },\n * ],\n * },\n * });\n *\n * // Run with guardrails and constraint-driven orchestration\n * const result = await orchestrator.run(myAgent, 'Hello, can you help me?');\n * ```\n *\n * @throws If autoApproveToolCalls is false but no onApprovalRequest callback is provided\n * @public\n */\nexport function createAgentOrchestrator<\n F extends Record<string, unknown> = Record<string, never>,\n>(options: OrchestratorOptions<F>): AgentOrchestrator<F> {\n const {\n runner,\n factsSchema = {},\n init,\n constraints = {},\n resolvers = {},\n guardrails = {},\n onApprovalRequest,\n autoApproveToolCalls = true,\n maxTokenBudget,\n budgetWarningThreshold = 0.8,\n onBudgetWarning,\n budgetEstimateTokens,\n retryInsideCircuit = false,\n plugins = [],\n debug: rawDebug = false,\n approvalTimeoutMs = 300000,\n agentRetry,\n hooks = {},\n memory,\n circuitBreaker,\n selfHealing,\n outputSchema,\n maxSchemaRetries,\n checkpointStore,\n breakpoints,\n onBreakpoint,\n breakpointTimeoutMs,\n } = options;\n\n // Normalize debug config\n const debug = typeof rawDebug === \"object\" ? true : !!rawDebug;\n const MAX_VERBOSE_LENGTH = 5000;\n\n // Warn if selfHealing is configured without circuitBreaker (selfHealing only triggers in CB error path)\n if (debug && selfHealing && !circuitBreaker) {\n console.warn(\n \"[Directive] selfHealing config has no effect without a circuitBreaker — \" +\n \"fallback behavior requires the circuit breaker to detect failures.\",\n );\n }\n\n // Validate budget warning threshold\n if (budgetWarningThreshold < 0 || budgetWarningThreshold > 1) {\n throw new Error(\n `[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${budgetWarningThreshold}`,\n );\n }\n\n // Enforce approval workflow configuration - require either auto-approve or callback\n if (!autoApproveToolCalls && !onApprovalRequest) {\n throw new Error(\n \"[Directive] Invalid approval configuration: autoApproveToolCalls is false but no onApprovalRequest callback provided. \" +\n \"Tool calls would wait for approval indefinitely. Either:\\n\" +\n \" - Set autoApproveToolCalls: true to auto-approve all tool calls\\n\" +\n \" - Provide an onApprovalRequest callback to handle approvals programmatically\",\n );\n }\n\n /** Safe hook caller — user-provided hooks must never crash the orchestrator */\n function fireHook<K extends keyof OrchestratorLifecycleHooks>(\n name: K,\n event: Parameters<NonNullable<OrchestratorLifecycleHooks[K]>>[0],\n ): void {\n try {\n (hooks[name] as ((e: typeof event) => void) | undefined)?.(event);\n } catch (hookError) {\n if (debug) {\n console.debug(`[Directive] hooks.${name} threw:`, hookError);\n }\n }\n }\n\n // Dev-mode: validate that user-provided facts keys don't collide with bridge state keys\n const RESERVED_ORCHESTRATOR_KEYS = [\n \"agent\",\n \"approval\",\n \"conversation\",\n \"toolCalls\",\n ];\n for (const key of Object.keys(factsSchema)) {\n if (RESERVED_ORCHESTRATOR_KEYS.includes(key)) {\n throw new Error(\n `[Directive] Facts schema key \"${key}\" conflicts with orchestrator state. Reserved keys: ${RESERVED_ORCHESTRATOR_KEYS.join(\", \")}. Rename your fact to avoid the collision.`,\n );\n }\n }\n\n // Build schema by combining bridge schema with user-provided schema\n const combinedSchema = {\n facts: {\n ...orchestratorBridgeSchema.facts,\n ...factsSchema,\n __budgetWarningFired: t.boolean(),\n },\n derivations: {},\n events: {},\n requirements: {},\n } satisfies ModuleSchema;\n\n // Forward declaration for runAgentWithGuardrails (used in resolver converter)\n // biome-ignore lint/style/useConst: forward declaration, assigned later\n let runAgentWithGuardrailsFn: <T>(\n agent: AgentLike,\n input: string,\n currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ) => Promise<RunResult<T>>;\n\n // Forward declaration for system (used in resolver converter)\n // biome-ignore lint/style/useConst: forward declaration, assigned later\n let system: SingleModuleSystem<any>;\n\n // Convert user constraints\n const directiveConstraints: Record<string, any> =\n convertOrchestratorConstraints<F>(constraints);\n\n // Add built-in budget limit constraint\n if (maxTokenBudget) {\n directiveConstraints.__budgetLimit = {\n priority: 100, // High priority\n when: (facts: any) => getAgentState(facts).tokenUsage > maxTokenBudget,\n require: { type: \"__PAUSE_BUDGET_EXCEEDED\" } as PauseBudgetExceededReq,\n };\n }\n\n // Convert user resolvers\n const directiveResolvers: Record<string, any> =\n convertOrchestratorResolvers<F>(\n resolvers,\n (agent, input, currentFacts, opts) =>\n runAgentWithGuardrailsFn(agent, input, currentFacts, opts),\n () => system.facts,\n );\n\n // Add built-in pause resolver\n directiveResolvers.__pause = {\n requirement: requirementGuard<PauseBudgetExceededReq>(\n \"__PAUSE_BUDGET_EXCEEDED\",\n ),\n resolve: async (_req: Requirement, context: any) => {\n const currentAgent = getAgentState(context.facts);\n setAgentState(context.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n };\n\n // ---- Debug Timeline setup ----\n let timeline: DebugTimeline | null = null;\n if (debug) {\n timeline = createDebugTimeline({\n getSnapshotId: () => {\n try {\n return (system as any).history?.currentIndex ?? null;\n } catch {\n return null;\n }\n },\n goToSnapshot: (snapshotId: number) => {\n try {\n (system as any).history?.goTo?.(snapshotId);\n } catch {\n // System may not support goTo\n }\n },\n });\n }\n\n // Create callback plugin for onApprovalRequest\n const callbackPlugin = createCallbackPlugin(\n \"directive-ai-callbacks\",\n {}, // No requirement callbacks needed, approval is handled separately\n );\n\n // Create module\n const orchestratorModule = createModule(\"directive-ai-orchestrator\", {\n schema: combinedSchema,\n init: (facts) => {\n setAgentState(facts, {\n status: \"idle\",\n currentAgent: null,\n input: null,\n output: null,\n error: null,\n tokenUsage: 0,\n turnCount: 0,\n startedAt: null,\n completedAt: null,\n });\n setApprovalState(facts, {\n pending: [],\n approved: [],\n rejected: [],\n });\n setConversation(facts, []);\n setToolCalls(facts, []);\n setBreakpointState(facts, { pending: [], resolved: [], cancelled: [] });\n setBridgeFact(facts, \"__budgetWarningFired\", false);\n if (init) {\n const state = getOrchestratorState(facts);\n const combinedFacts = { ...facts, ...state } as unknown as F &\n OrchestratorState;\n init(combinedFacts);\n }\n },\n constraints: directiveConstraints,\n resolvers: directiveResolvers as any,\n });\n\n // Build plugins array with optional timeline plugin\n const allPlugins = [...plugins, callbackPlugin];\n if (debug && timeline) {\n allPlugins.push(\n createDebugTimelinePlugin(timeline, () => {\n try {\n return (system as any).history?.currentIndex ?? null;\n } catch {\n return null;\n }\n }),\n );\n }\n\n // Create system\n system = createSystem({\n module: orchestratorModule,\n plugins: allPlugins,\n history: debug ? true : undefined,\n });\n\n system.start();\n\n // ---- R1 C7 — Budget pre-flight + TOCTOU reservation ----\n //\n // The legacy budget constraint fires AFTER `tokenUsage` is updated,\n // so a single run can overshoot by the full call cost AND N\n // concurrent runs can each individually pass the post-call check\n // collectively overshooting by N * maxTokenBudget.\n //\n // `inFlightReservation` tracks tokens reserved for currently-running\n // calls. The pre-flight check at the top of `runAgentWithGuardrails`\n // rejects when current usage PLUS reservations PLUS this call's\n // estimate would exceed the cap. When `budgetEstimateTokens` is\n // undefined (default), the reservation stays 0 and the pre-flight\n // only catches the \"already over\" case — a strict back-compat\n // behavior for consumers that didn't ship the new option.\n const inFlightReservation = { count: 0 };\n\n function resolveBudgetReservation(agent: AgentLike, input: string): number {\n if (budgetEstimateTokens === undefined) return 0;\n if (typeof budgetEstimateTokens === \"number\") {\n return Math.max(0, Math.floor(budgetEstimateTokens));\n }\n try {\n const n = budgetEstimateTokens(input, agent);\n return Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 0;\n } catch {\n return 0;\n }\n }\n\n // Helper to run agent with guardrails\n async function runAgentWithGuardrails<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ): Promise<RunResult<T>> {\n // ---- Budget pre-flight (R1 C7) ----\n //\n // Reject BEFORE the LLM call when current usage + in-flight\n // reservations + this call's estimated cost would exceed the cap.\n // This closes the post-call constraint's TOCTOU window: with the\n // old behavior N concurrent runs each saw `tokenUsage = 0 < cap`,\n // all proceeded, and total spend was N * maxTokenBudget.\n //\n // When `budgetEstimateTokens` is undefined (default), `reserved`\n // is 0 — the check then only rejects when usage is already at or\n // past the cap (back-compat for consumers that haven't adopted\n // the reservation hint).\n let reserved = 0;\n if (maxTokenBudget) {\n const currentUsage = getAgentState(system.facts).tokenUsage;\n reserved = resolveBudgetReservation(agent, input);\n const projected = currentUsage + inFlightReservation.count + reserved;\n if (projected > maxTokenBudget) {\n throw new Error(\n `[Directive] Agent budget would be exceeded by this call: current=${currentUsage} + in-flight=${inFlightReservation.count} + estimate=${reserved} > maxTokenBudget=${maxTokenBudget}. Raise \\`maxTokenBudget\\`, lower \\`budgetEstimateTokens\\`, or reset \\`tokenUsage\\`.`,\n );\n }\n inFlightReservation.count += reserved;\n }\n\n try {\n return await runAgentWithGuardrailsBody<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n );\n } finally {\n if (maxTokenBudget && reserved > 0) {\n inFlightReservation.count = Math.max(\n 0,\n inFlightReservation.count - reserved,\n );\n }\n }\n }\n\n /**\n * Self-healing fallback chain shared by both CB composition strategies.\n * Tries `fallbackRunners` (in order), then `fallbackAgent`, then the\n * `fallback-response` degradation policy. Re-throws the original\n * error when no fallback succeeds (or `selfHealing` is not configured).\n */\n /**\n * Reserve tokens for a fallback call against the running budget,\n * invoke the work, and release the reservation in `finally`. Without\n * this, fallback runners and the fallback agent bypass the\n * pre-flight reservation that the primary path runs in\n * `runAgentWithGuardrails` — a primary failure caused by budget\n * pressure would then drive the fallback into the SAME overshoot\n * the pre-flight existed to prevent.\n *\n * When `budgetEstimateTokens` is undefined (default), `reserve()`\n * returns 0 and this is a no-op — the back-compat path.\n */\n async function withFallbackBudgetReservation<T>(\n agent: AgentLike,\n input: string,\n work: () => Promise<RunResult<T>>,\n ): Promise<RunResult<T>> {\n const reserved = resolveBudgetReservation(agent, input);\n if (reserved <= 0) {\n return await work();\n }\n inFlightReservation.count += reserved;\n try {\n return await work();\n } finally {\n inFlightReservation.count = Math.max(\n 0,\n inFlightReservation.count - reserved,\n );\n }\n }\n\n async function applySelfHealingFallback<T>(\n error: unknown,\n agent: AgentLike,\n input: string,\n opts?: RunOptions,\n ): Promise<RunResult<T>> {\n if (!selfHealing) throw error;\n\n if (selfHealing.fallbackRunners) {\n for (const fallbackRunner of selfHealing.fallbackRunners) {\n try {\n const rerouteEvent: RerouteEvent = {\n originalAgent: agent.name,\n reroutedTo: \"fallback-runner\",\n reason: error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n try {\n selfHealing.onReroute?.(rerouteEvent);\n } catch {\n /* non-fatal */\n }\n if (timeline) {\n timeline.record({\n type: \"reroute\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n from: agent.name,\n to: \"fallback-runner\",\n reason: error instanceof Error ? error.message : String(error),\n });\n }\n return await withFallbackBudgetReservation<T>(agent, input, () =>\n fallbackRunner<T>(agent, input, opts),\n );\n } catch {\n // Try next fallback\n }\n }\n }\n\n if (selfHealing.fallbackAgent) {\n try {\n const rerouteEvent: RerouteEvent = {\n originalAgent: agent.name,\n reroutedTo: selfHealing.fallbackAgent.name,\n reason: error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n try {\n selfHealing.onReroute?.(rerouteEvent);\n } catch {\n /* non-fatal */\n }\n if (timeline) {\n timeline.record({\n type: \"reroute\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n from: agent.name,\n to: selfHealing.fallbackAgent.name,\n reason: error instanceof Error ? error.message : String(error),\n });\n }\n const fallbackAgent = selfHealing.fallbackAgent;\n return await withFallbackBudgetReservation<T>(\n fallbackAgent,\n input,\n () => runner<T>(fallbackAgent, input, opts),\n );\n } catch {\n // Fallback agent also failed\n }\n }\n\n if (\n selfHealing.degradation === \"fallback-response\" &&\n selfHealing.fallbackResponse !== undefined\n ) {\n return {\n output: selfHealing.fallbackResponse as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n\n throw error;\n }\n\n async function runAgentWithGuardrailsBody<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ): Promise<RunResult<T>> {\n // ---- Circuit-breaker composition (R1 Distrib C2) ----\n //\n // Two strategies, controlled by `retryInsideCircuit`:\n //\n // - `false` (default, the bug fix): the breaker wraps each retry\n // attempt INSIDE `executeAgentWithRetry` (see Inner). The outer\n // path here runs Inner directly. Self-healing fallback still\n // fires when the breaker open-circuits or every attempt fails.\n // - `true` (legacy): the breaker wraps the whole Inner call so\n // retries are hidden from the breaker.\n if (circuitBreaker && retryInsideCircuit) {\n // Legacy strategy: CB wraps the whole Inner (including its retry\n // loop). Hidden retries don't count toward `failureThreshold`.\n try {\n return await circuitBreaker.execute(() =>\n runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n ),\n );\n } catch (error) {\n return applySelfHealingFallback<T>(error, agent, input, opts);\n }\n }\n\n // New-default + no-CB strategy: Inner runs once. When CB is\n // configured, Inner wraps each retry attempt with CB internally\n // (see `effectiveRunner` setup in Inner). Self-healing still kicks\n // in if Inner ultimately throws.\n try {\n return await runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n );\n } catch (error) {\n if (circuitBreaker || selfHealing) {\n return applySelfHealingFallback<T>(error, agent, input, opts);\n }\n throw error;\n }\n }\n\n async function runAgentWithGuardrailsInner<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ): Promise<RunResult<T>> {\n const startTime = Date.now();\n\n // Inject memory context into agent instructions if memory is configured\n if (memory) {\n const contextMessages = memory.getContextMessages();\n if (contextMessages.length > 0) {\n const contextStr = contextMessages\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\");\n agent = {\n ...agent,\n instructions: `${agent.instructions ?? \"\"}\\n\\nConversation context:\\n${contextStr}`,\n };\n }\n }\n\n // Inject system meta context if enabled\n if (options.metaContext) {\n const metaStr = formatSystemMeta(system.inspect());\n if (metaStr) {\n agent = {\n ...agent,\n instructions: `${agent.instructions ?? \"\"}\\n\\n${metaStr}`,\n };\n }\n }\n\n // Breakpoint: pre_input_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_input_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_input_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Resolve which guardrails to use: per-call override > orchestrator defaults\n const effectiveInputGuardrails =\n callOptions?.inputGuardrails !== undefined\n ? callOptions.inputGuardrails\n : (guardrails.input ?? []);\n const effectiveOutputGuardrails =\n callOptions?.outputGuardrails !== undefined\n ? callOptions.outputGuardrails\n : (guardrails.output ?? []);\n\n // Run input guardrails BEFORE agent_start so timeline shows correct order\n const inputGuardrailsList = effectiveInputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"input\"),\n );\n for (const guardrail of inputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input, agentName: agent.name },\n context,\n );\n // Call onGuardrailCheck hook\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"input\",\n passed: result.passed,\n reason: result.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!result.passed) {\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (result.transformed !== undefined) {\n input = result.transformed as string;\n }\n }\n\n // Call onAgentStart hook (after guardrails pass)\n fireHook(\"onAgentStart\", {\n agentName: agent.name,\n input,\n timestamp: startTime,\n });\n\n if (timeline) {\n timeline.record({\n type: \"agent_start\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n inputLength: input.length,\n modelId: agent.model ?? undefined,\n ...(agent.instructions\n ? { instructions: agent.instructions.slice(0, MAX_VERBOSE_LENGTH) }\n : {}),\n input: input.slice(0, MAX_VERBOSE_LENGTH),\n });\n }\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input,\n startedAt: Date.now(),\n });\n });\n\n // Breakpoint: pre_agent_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_agent_run\",\n };\n const mods = await handleBreakpoint(\n \"pre_agent_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Structured output wrapping\n const effectiveSchema =\n callOptions?.outputSchema !== undefined\n ? callOptions.outputSchema\n : outputSchema;\n\n let effectiveRunner = runner;\n if (effectiveSchema) {\n effectiveRunner = withStructuredOutput(runner, {\n schema: effectiveSchema,\n maxRetries: callOptions?.maxSchemaRetries ?? maxSchemaRetries ?? 2,\n });\n }\n\n // Circuit-breaker per attempt (R1 Distrib C2). When `circuitBreaker`\n // is configured and `retryInsideCircuit` is false (the new default),\n // wrap the runner so every retry attempt inside\n // `executeAgentWithRetry` is gated by the breaker. Each failure\n // counts toward `failureThreshold`; an open breaker short-circuits\n // remaining retries.\n if (circuitBreaker && !retryInsideCircuit) {\n const inner = effectiveRunner;\n effectiveRunner = (<U>(a: AgentLike, i: string, o?: RunOptions) =>\n circuitBreaker!.execute(() =>\n inner<U>(a, i, o),\n )) as typeof effectiveRunner;\n }\n\n // Run the agent with retry support\n const result = await executeAgentWithRetry<T>(\n effectiveRunner,\n agent,\n input,\n {\n ...opts,\n signal: opts?.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n const updated = [...currentConversation, message];\n setConversation(\n system.facts,\n updated.length > MAX_CONVERSATION_MESSAGES\n ? updated.slice(-MAX_CONVERSATION_MESSAGES)\n : updated,\n );\n opts?.onMessage?.(message);\n },\n onToolCall: async (toolCall) => {\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"toolCall\"),\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input },\n context,\n );\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"toolCall\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n\n // Wait for approval (pass signal so abort cancels the wait)\n await waitForApproval(\n approvalId,\n callOptions?.signal ?? opts?.signal,\n );\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n const updatedToolCalls = [...currentToolCalls, toolCall];\n setToolCalls(\n system.facts,\n updatedToolCalls.length > MAX_TOOL_CALLS\n ? updatedToolCalls.slice(-MAX_TOOL_CALLS)\n : updatedToolCalls,\n );\n opts?.onToolCall?.(toolCall);\n },\n },\n agentRetry\n ? {\n ...agentRetry,\n onRetry: (attempt, error, delayMs) => {\n agentRetry.onRetry?.(attempt, error, delayMs);\n fireHook(\"onAgentRetry\", {\n agentName: agent.name,\n input,\n attempt,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n }\n : undefined,\n );\n\n // Breakpoint: pre_output_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_output_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_output_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Run output guardrails with retry support\n const outputGuardrailsList = effectiveOutputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"output\"),\n );\n for (const guardrail of outputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input,\n messages: result.messages,\n },\n context,\n );\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"output\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update state\n let shouldFireBudgetWarning = false;\n let budgetPercentage = 0;\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n const newTokenUsage = currentAgent.tokenUsage + result.totalTokens;\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: newTokenUsage,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n\n // Check budget warning threshold\n if (maxTokenBudget && onBudgetWarning) {\n budgetPercentage = newTokenUsage / maxTokenBudget;\n const warningFired = getBridgeFact<boolean>(\n system.facts,\n \"__budgetWarningFired\",\n );\n if (budgetPercentage >= budgetWarningThreshold && !warningFired) {\n setBridgeFact(system.facts, \"__budgetWarningFired\", true);\n shouldFireBudgetWarning = true;\n }\n }\n });\n\n // Fire budget warning callback outside of batch (callbacks shouldn't run inside batch)\n if (shouldFireBudgetWarning) {\n try {\n onBudgetWarning!({\n currentTokens: getAgentState(system.facts).tokenUsage,\n maxBudget: maxTokenBudget!,\n percentage: budgetPercentage,\n });\n } catch (callbackError) {\n if (debug) {\n console.debug(\n \"[Directive Orchestrator] onBudgetWarning threw:\",\n callbackError,\n );\n }\n }\n }\n\n // Store messages in memory if configured (best-effort)\n if (memory && result.messages.length > 0) {\n try {\n memory.addMessages(result.messages);\n } catch (memoryError) {\n if (debug) {\n console.debug(\"[Directive] Memory addMessages failed:\", memoryError);\n }\n }\n }\n\n // Call onAgentComplete hook\n fireHook(\"onAgentComplete\", {\n agentName: agent.name,\n input,\n output: result.output,\n tokenUsage: result.totalTokens,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n\n if (timeline) {\n const outputStr =\n typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output);\n timeline.record({\n type: \"agent_complete\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n outputLength: outputStr?.length ?? 0,\n totalTokens: result.totalTokens,\n inputTokens: result.tokenUsage?.inputTokens ?? 0,\n outputTokens: result.tokenUsage?.outputTokens ?? 0,\n durationMs: Date.now() - startTime,\n modelId: agent.model ?? undefined,\n output: outputStr.slice(0, MAX_VERBOSE_LENGTH),\n });\n }\n\n // Breakpoint: post_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"post_run\",\n };\n const mods = await handleBreakpoint(\n \"post_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n return result;\n }\n\n // Assign the function to the forward-declared variable\n runAgentWithGuardrailsFn = runAgentWithGuardrails;\n\n // ---- Breakpoint infrastructure ----\n const breakpointModifications = new Map<string, BreakpointModifications>();\n const breakpointCancelReasons = new Map<string, string>();\n\n function waitForBreakpointResolution(\n bpId: string,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for breakpoint\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Breakpoint wait for ${bpId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe(\n [BREAKPOINT_KEY],\n () => {\n if (settled) {\n return;\n }\n\n const bpState = getBreakpointState(system.facts);\n if (bpState.resolved.includes(bpId)) {\n cleanupAll();\n const mods = breakpointModifications.get(bpId) ?? null;\n breakpointModifications.delete(bpId);\n resolve(mods);\n } else if (bpState.cancelled.includes(bpId)) {\n cleanupAll();\n breakpointModifications.delete(bpId);\n const cancelReason = breakpointCancelReasons.get(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n cancelReason\n ? `Breakpoint ${bpId} was cancelled: ${cancelReason}`\n : `Breakpoint ${bpId} was cancelled`,\n ),\n );\n }\n },\n );\n\n const bpTimeout = breakpointTimeoutMs ?? 300000;\n timeoutId = setTimeout(() => {\n if (settled) {\n return;\n }\n\n cleanupAll();\n breakpointModifications.delete(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n `[Directive] Breakpoint timeout: ${bpId} not resolved within ${Math.round(bpTimeout / 1000)}s`,\n ),\n );\n }, bpTimeout);\n });\n }\n\n async function handleBreakpoint(\n type: string,\n context: BreakpointContext,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (!breakpoints || breakpoints.length === 0) {\n return null;\n }\n\n const match = matchBreakpoint(\n breakpoints as BreakpointConfig<string>[],\n type,\n context,\n );\n if (!match) {\n return null;\n }\n\n const bpId = createBreakpointId();\n const request: BreakpointRequest = {\n id: bpId,\n type,\n agentId: context.agentId,\n input: context.input,\n label: match.label,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n setBreakpointState(system.facts, {\n ...bpState,\n pending: [...bpState.pending, request],\n });\n });\n\n try {\n onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n try {\n hooks.onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_hit\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n breakpointType: type,\n label: match.label,\n });\n }\n\n const mods = await waitForBreakpointResolution(bpId, signal);\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_resumed\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n modified: !!mods?.input,\n skipped: !!mods?.skip,\n });\n }\n\n return mods;\n }\n\n // Wait for approval with configurable timeout and abort signal support\n function waitForApproval(\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for approval\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Approval wait for ${requestId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe([APPROVAL_KEY], () => {\n if (settled) {\n return;\n }\n\n const approval = getApprovalState(system.facts);\n if (approval.approved.includes(requestId)) {\n cleanupAll();\n resolve();\n } else {\n const rejectedRequest = approval.rejected.find(\n (r) => r.id === requestId,\n );\n if (rejectedRequest) {\n cleanupAll();\n const errorMsg = rejectedRequest.reason\n ? `Request ${requestId} rejected: ${rejectedRequest.reason}`\n : `Request ${requestId} rejected`;\n reject(new Error(errorMsg));\n }\n }\n });\n\n // Set timeout to prevent indefinite hanging (uses configured approvalTimeoutMs)\n timeoutId = setTimeout(() => {\n if (settled) {\n return;\n }\n\n cleanupAll();\n const timeoutSeconds = Math.round(approvalTimeoutMs / 1000);\n reject(\n new Error(\n `[Directive] Approval timeout: Request ${requestId} not resolved within ${timeoutSeconds}s.\\nSolutions:\\n 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()\\n 2. Set autoApproveToolCalls: true to auto-approve\\n 3. Increase approvalTimeoutMs (current: ${approvalTimeoutMs}ms)\\nSee: https://directive.run/docs/ai/running-agents`,\n ),\n );\n }, approvalTimeoutMs);\n });\n }\n\n /** Get facts as the combined type for external access */\n function getCombinedFacts(): F & OrchestratorState {\n const state = getOrchestratorState(system.facts);\n\n return { ...state } as unknown as F & OrchestratorState;\n }\n\n const orchestrator: AgentOrchestrator<F> = {\n system: system as unknown as System<any>,\n get facts() {\n return getCombinedFacts();\n },\n get totalTokens() {\n return getAgentState(system.facts).tokenUsage;\n },\n get timeline() {\n return timeline;\n },\n\n async run<T>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): Promise<RunResult<T>> {\n return runAgentWithGuardrails<T>(\n agent,\n input,\n getCombinedFacts(),\n undefined,\n options,\n );\n },\n\n runStream<T>(\n agent: AgentLike,\n input: string,\n options: {\n signal?: AbortSignal;\n liveContext?: LiveContextOptions<F & OrchestratorState>;\n } = {},\n ): OrchestratorStreamResult<T> {\n const abortController = new AbortController();\n const MAX_STREAM_BUFFER = 10_000;\n const chunks: OrchestratorStreamChunk[] = [];\n const waiters: Array<(chunk: OrchestratorStreamChunk | null) => void> =\n [];\n let closed = false;\n const startTime = Date.now();\n let tokenCount = 0;\n const MAX_ACCUMULATED_OUTPUT = 100_000;\n let accumulatedOutput = \"\";\n\n // Combine external abort signal\n let abortHandler: (() => void) | undefined;\n if (options.signal) {\n abortHandler = () => abortController.abort();\n options.signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n const cleanup = () => {\n if (abortHandler && options.signal) {\n options.signal.removeEventListener(\"abort\", abortHandler);\n }\n };\n\n // Push a chunk to the stream\n const pushChunk = (chunk: OrchestratorStreamChunk) => {\n if (closed) return;\n const waiter = waiters.shift();\n if (waiter) {\n waiter(chunk);\n } else {\n chunks.push(chunk);\n // FIFO eviction when buffer exceeds max\n if (chunks.length > MAX_STREAM_BUFFER) {\n chunks.shift();\n }\n }\n };\n\n // Close the stream\n const closeStream = () => {\n closed = true;\n cleanup();\n for (const waiter of waiters) {\n waiter(null);\n }\n waiters.length = 0;\n };\n\n // RFC 0005: wire liveContext subscriptions BEFORE the resultPromise\n // IIFE constructs (which starts running synchronously). Even though\n // the IIFE's sync prefix today does no fact-mutating work before\n // its first await, hoisting the subscription removes any latent\n // race where a future IIFE prefix change could synchronously\n // mutate facts before subscribe wires up. The subscription\n // callback closes over `closed`, `pushChunk`, `accumulatedOutput`,\n // and `abortController` — all declared above and live by the\n // time a fact change can fire (which requires the IIFE to yield).\n //\n // RFC 0005 dev-mode guard: warn when liveContext.system === the\n // orchestrator's own system AND watched keys overlap bridge-state\n // keys. Without this, the orchestrator's own setAgentState calls\n // could trigger interruptWhen → abort, self-looping the run.\n let liveContextUnsub: (() => void) | null = null;\n const liveCfg = options.liveContext;\n if (liveCfg) {\n // — `mode` was briefly part of `LiveContextOptions` in\n // v1.18.0, removed in v1.19.0, and re-added as @deprecated in\n // v1.19.1+ for source-compat with v1.18 call sites. The field\n // is intentionally a runtime no-op; emit a one-shot warning\n // when a consumer actually sets it so they know to drop it.\n if ((liveCfg as any).mode !== undefined && !deprecatedModeWarned) {\n deprecatedModeWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n \"[Directive] liveContext.mode is deprecated and has no runtime behavior — \" +\n \"the 1.x landing ships abort-and-emit only. Remove the field; \" +\n \"automatic re-prompt semantics will return in a follow-up RFC.\",\n );\n }\n if (debug && (liveCfg.system as unknown) === (system as unknown)) {\n const bridgeKeys = [\"agent\", \"conversation\", \"approvalState\"];\n const overlap = liveCfg.keys.filter((k) =>\n bridgeKeys.some((bk) => k.startsWith(bk)),\n );\n if (overlap.length > 0) {\n console.warn(\n `[Directive] liveContext watches bridge-state keys (${overlap.join(\", \")}) on the orchestrator's own system. The orchestrator's own setAgentState / setConversation / approvalState writes will trigger interruptWhen, self-looping the run. Use a separate system for liveContext, or scope \\`keys\\` to user-fact namespaces.`,\n );\n }\n }\n const notifyOn = liveCfg.notifyOn ?? \"interrupt-only\";\n const interruptWhen = liveCfg.interruptWhen ?? (() => true);\n const watched = new Set(liveCfg.keys);\n // The system's facts $store exposes a key-scoped subscribe via\n // the same shape the breakpoint + approval waiters elsewhere\n // in this file use. We re-use that surface without touching\n // the bridge primitive itself.\n const store = (\n liveCfg.system as unknown as {\n facts: {\n $store: {\n subscribe?: (\n keys: readonly string[],\n listener: () => void,\n ) => () => void;\n toObject?: () => Record<string, unknown>;\n };\n };\n }\n ).facts.$store;\n if (typeof store?.subscribe === \"function\") {\n let lastSnapshot: Record<string, unknown> = store.toObject?.() ?? {};\n liveContextUnsub = store.subscribe(liveCfg.keys, () => {\n if (closed) return;\n const current = store.toObject?.() ?? {};\n const changed: string[] = [];\n for (const k of liveCfg.keys) {\n if (current[k] !== lastSnapshot[k]) changed.push(k);\n }\n lastSnapshot = current;\n if (changed.length === 0) return;\n const watchedChanged = changed.filter((k) => watched.has(k));\n if (watchedChanged.length === 0) return;\n // — run `interruptWhen` FIRST so `onContextUpdate`\n // can observe the interruption decision before the chunk\n // emits — matches the documented contract on\n // `LiveContextOptions.onContextUpdate` (\"fired AFTER the\n // interruptWhen predicate runs but BEFORE the chunk\n // emits\"). The previous order let consumer-supplied\n // callbacks fire blindly.\n //\n // Both callbacks are wrapped in try/catch: a throw inside\n // `interruptWhen` or `onContextUpdate` used to propagate\n // back through `notifyKey` → `flush` → the source's\n // publish handler, killing the publisher entirely. The\n // try/catch confines the failure to a console.error and\n // continues the notify cycle so downstream listeners\n // (audit-ledger, logging) still fire.\n let shouldInterrupt = false;\n try {\n shouldInterrupt = interruptWhen(current as any, watchedChanged);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n \"[Directive] liveContext.interruptWhen threw — treating as non-interrupt\",\n err,\n );\n shouldInterrupt = false;\n }\n try {\n liveCfg.onContextUpdate?.(watchedChanged);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n \"[Directive] liveContext.onContextUpdate threw\",\n err,\n );\n }\n if (shouldInterrupt) {\n pushChunk({\n type: \"interrupted\",\n reason: \"liveContext.interruptWhen\",\n partialOutput: accumulatedOutput,\n changedKeys: watchedChanged,\n });\n abortController.abort();\n } else if (notifyOn === \"all-changes\") {\n pushChunk({\n type: \"context_updated\",\n changedKeys: watchedChanged,\n });\n }\n });\n }\n }\n\n const tearDownLiveContext = (): void => {\n if (liveContextUnsub) {\n liveContextUnsub();\n liveContextUnsub = null;\n }\n };\n\n // Run the agent with streaming callbacks\n const resultPromise = (async (): Promise<RunResult<T>> => {\n pushChunk({\n type: \"progress\",\n phase: \"starting\",\n message: \"Running input guardrails\",\n });\n\n try {\n // Run input guardrails first with retry support\n let processedInput = input;\n const inputGuardrails = (guardrails.input ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"input\"),\n );\n for (const guardrail of inputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input: processedInput, agentName: agent.name },\n context,\n );\n if (!result.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: result.reason ?? \"Input validation failed\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (result.transformed !== undefined) {\n processedInput = result.transformed as string;\n }\n }\n\n pushChunk({\n type: \"progress\",\n phase: \"generating\",\n message: \"Starting agent\",\n });\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input: processedInput,\n startedAt: Date.now(),\n });\n });\n\n // Run agent with streaming callbacks and retry support\n const result = await executeAgentWithRetry<T>(\n runner,\n agent,\n processedInput,\n {\n signal: abortController.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n setConversation(system.facts, [\n ...currentConversation,\n message,\n ]);\n pushChunk({ type: \"message\", message });\n\n // Approximate token counting from content\n if (message.role === \"assistant\" && message.content) {\n const newTokens = Math.ceil(message.content.length / 4);\n tokenCount += newTokens;\n accumulatedOutput += message.content;\n if (accumulatedOutput.length > MAX_ACCUMULATED_OUTPUT) {\n accumulatedOutput = accumulatedOutput.slice(\n -MAX_ACCUMULATED_OUTPUT,\n );\n }\n pushChunk({\n type: \"token\",\n data: message.content,\n tokenCount,\n });\n }\n },\n onToolCall: async (toolCall) => {\n pushChunk({\n type: \"tool_start\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n arguments: toolCall.arguments,\n });\n\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map(\n (g, i) => normalizeGuardrail(g, i, \"toolCall\"),\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input: processedInput },\n context,\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Tool call blocked\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input: processedInput,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n pushChunk({\n type: \"approval_required\",\n requestId: approvalId,\n toolName: toolCall.name,\n });\n\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n await waitForApproval(approvalId, abortController.signal);\n pushChunk({\n type: \"approval_resolved\",\n requestId: approvalId,\n approved: true,\n });\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n setToolCalls(system.facts, [...currentToolCalls, toolCall]);\n\n if (toolCall.result) {\n pushChunk({\n type: \"tool_end\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n result: toolCall.result,\n });\n }\n },\n },\n agentRetry,\n );\n\n // Run output guardrails\n pushChunk({\n type: \"progress\",\n phase: \"finishing\",\n message: \"Running output guardrails\",\n });\n\n const outputGuardrails = (guardrails.output ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"output\"),\n );\n for (const guardrail of outputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input: processedInput,\n messages: result.messages,\n },\n context,\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Output validation failed\",\n partialOutput:\n typeof result.output === \"string\" ? result.output : \"\",\n stopped: true,\n });\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update final state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: currentAgent.tokenUsage + result.totalTokens,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n });\n\n const duration = Date.now() - startTime;\n pushChunk({\n type: \"done\",\n totalTokens: result.totalTokens,\n duration,\n droppedTokens: 0,\n });\n closeStream();\n\n return result;\n } catch (error) {\n pushChunk({\n type: \"error\",\n error: error instanceof Error ? error : new Error(String(error)),\n });\n closeStream();\n throw error;\n }\n })();\n\n // Prevent unhandled rejection if caller only consumes stream (not .result)\n resultPromise.catch(() => {});\n\n // Create async iterator\n const stream: AsyncIterable<OrchestratorStreamChunk> = {\n [Symbol.asyncIterator](): AsyncIterator<OrchestratorStreamChunk> {\n return {\n async next(): Promise<IteratorResult<OrchestratorStreamChunk>> {\n if (chunks.length > 0) {\n return { done: false, value: chunks.shift()! };\n }\n if (closed) {\n return { done: true, value: undefined };\n }\n\n return new Promise<IteratorResult<OrchestratorStreamChunk>>(\n (resolve) => {\n waiters.push((chunk) => {\n if (chunk === null) {\n resolve({ done: true, value: undefined });\n } else {\n resolve({ done: false, value: chunk });\n }\n });\n },\n );\n },\n };\n },\n };\n\n // Track whether the abort came from interrupt() — if so, the\n // resultPromise.finally MUST NOT tear down the liveContext\n // subscription. The whole differentiator of interrupt vs abort\n // is that interrupt cancels the LLM run but keeps the\n // subscription alive so the next caller-driven prompt continues\n // against fresh facts. Without this flag the abort triggers the\n // resultPromise's catch path → reject → finally → tearDown, and\n // the subscription dies anyway.\n let interruptInitiated = false;\n\n // .finally returns a new promise that re-rejects when resultPromise\n // rejects; swallow with .catch so a rejected resultPromise (e.g. a\n // guardrail block) doesn't surface as an unhandled rejection when\n // the caller only consumes the stream side of the contract.\n resultPromise\n .finally(() => {\n if (!interruptInitiated) {\n tearDownLiveContext();\n }\n })\n .catch(() => {});\n\n return {\n stream,\n result: resultPromise,\n abort: () => {\n abortController.abort();\n tearDownLiveContext();\n closeStream();\n },\n interrupt: (reason?: string) => {\n // RFC 0005: distinct from `abort()` — cancel the in-flight\n // LLM run but leave `liveContext` subscriptions alive so\n // the next caller-driven prompt continues against fresh\n // facts. The interrupted chunk lands with the reason if\n // provided.\n //\n // Set the interrupt flag BEFORE aborting so the\n // resultPromise.finally above sees it and skips\n // tearDownLiveContext. The caller is responsible for\n // either kicking off a new runStream (against the live\n // subscription) or calling abort() to fully tear down.\n interruptInitiated = true;\n pushChunk({\n type: \"interrupted\",\n reason: reason ?? \"caller.interrupt\",\n partialOutput: accumulatedOutput,\n changedKeys: [],\n });\n abortController.abort();\n },\n };\n },\n\n async waitForIdle(timeoutMs?: number): Promise<void> {\n const isIdle = () => getAgentState(system.facts).status !== \"running\";\n if (isIdle()) {\n return;\n }\n\n const start = Date.now();\n while (!isIdle()) {\n if (timeoutMs !== undefined && Date.now() - start > timeoutMs) {\n throw new Error(\"[Directive Orchestrator] waitForIdle timed out\");\n }\n await new Promise((r) => setTimeout(r, 50));\n }\n },\n\n approve(requestId: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug)\n console.debug(\n `[Directive] approve() ignored: no pending request \"${requestId}\"`,\n );\n\n return;\n }\n const MAX_APPROVAL_HISTORY = 200;\n const approved = [...approval.approved, requestId];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n approved:\n approved.length > MAX_APPROVAL_HISTORY\n ? approved.slice(-MAX_APPROVAL_HISTORY)\n : approved,\n });\n });\n },\n\n reject(requestId: string, reason?: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug)\n console.debug(\n `[Directive] reject() ignored: no pending request \"${requestId}\"`,\n );\n\n return;\n }\n if (reason && debug) {\n console.debug(`[Directive] Request ${requestId} rejected: ${reason}`);\n }\n const rejectedRequest: RejectedRequest = {\n id: requestId,\n reason,\n rejectedAt: Date.now(),\n };\n const MAX_REJECTION_HISTORY = 200;\n const rejected = [...approval.rejected, rejectedRequest];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n rejected:\n rejected.length > MAX_REJECTION_HISTORY\n ? rejected.slice(-MAX_REJECTION_HISTORY)\n : rejected,\n });\n });\n },\n\n pause(): void {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n\n resume(): void {\n const agent = getAgentState(system.facts);\n if (agent.status === \"paused\") {\n setAgentState(system.facts, {\n ...agent,\n status: agent.currentAgent ? \"running\" : \"idle\",\n });\n }\n },\n\n reset(): void {\n system.batch(() => {\n setAgentState(system.facts, {\n status: \"idle\",\n currentAgent: null,\n input: null,\n output: null,\n error: null,\n tokenUsage: 0,\n turnCount: 0,\n startedAt: null,\n completedAt: null,\n });\n setApprovalState(system.facts, {\n pending: [],\n approved: [],\n rejected: [],\n });\n setConversation(system.facts, []);\n setToolCalls(system.facts, []);\n setBreakpointState(system.facts, {\n pending: [],\n resolved: [],\n cancelled: [],\n });\n setBridgeFact(system.facts, \"__budgetWarningFired\", false);\n });\n breakpointModifications.clear();\n breakpointCancelReasons.clear();\n },\n\n async checkpoint(cpOptions?: { label?: string }): Promise<Checkpoint> {\n const agentState = getAgentState(system.facts);\n if (agentState.status === \"running\") {\n throw new Error(\"[Directive] Cannot checkpoint while agent is running\");\n }\n if (!system.history?.export) {\n throw new Error(\n \"[Directive] Checkpointing requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n const cp: Checkpoint = {\n version: 1,\n id: createCheckpointId(),\n createdAt: new Date().toISOString(),\n label: cpOptions?.label,\n systemExport: system.history.export(),\n timelineExport: timeline?.export() ?? null,\n localState: { type: \"single\" },\n memoryExport: memory ? ((memory as any).export?.() ?? null) : null,\n orchestratorType: \"single\",\n };\n\n if (checkpointStore) {\n await checkpointStore.save(cp);\n }\n\n return cp;\n },\n\n restore(cp: Checkpoint, restoreOpts?: { restoreTimeline?: boolean }): void {\n if (!validateCheckpoint(cp)) {\n throw new Error(\"[Directive] Invalid checkpoint data\");\n }\n if (cp.orchestratorType !== \"single\") {\n throw new Error(\n \"[Directive] Cannot restore multi-agent checkpoint in single-agent orchestrator\",\n );\n }\n if (!system.history?.import) {\n throw new Error(\n \"[Directive] Restoring a checkpoint requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n system.history.import(cp.systemExport);\n\n if (\n restoreOpts?.restoreTimeline !== false &&\n cp.timelineExport &&\n timeline\n ) {\n timeline.import(cp.timelineExport);\n }\n\n if (cp.memoryExport !== null && memory && (memory as any).import) {\n (memory as any).import(cp.memoryExport);\n }\n },\n\n resumeBreakpoint(\n id: string,\n modifications?: BreakpointModifications,\n ): void {\n if (modifications) {\n breakpointModifications.set(id, modifications);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const resolved = [...bpState.resolved, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n resolved:\n resolved.length > MAX_BREAKPOINT_HISTORY\n ? resolved.slice(-MAX_BREAKPOINT_HISTORY)\n : resolved,\n });\n });\n },\n\n cancelBreakpoint(id: string, reason?: string): void {\n if (reason) {\n breakpointCancelReasons.set(id, reason);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const cancelled = [...bpState.cancelled, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n cancelled:\n cancelled.length > MAX_BREAKPOINT_HISTORY\n ? cancelled.slice(-MAX_BREAKPOINT_HISTORY)\n : cancelled,\n });\n });\n },\n\n getPendingBreakpoints(): BreakpointRequest[] {\n const bpState = getBreakpointState(system.facts);\n\n return [...bpState.pending];\n },\n\n destroy(): void {\n system.destroy();\n },\n };\n\n return orchestrator;\n}\n"]}
|
|
@@ -26,5 +26,5 @@ ${R}`.trim()},c=[],b,d=0,I={maxPredicateBytes:p,maxOperatorCount:u,maxArrayOpera
|
|
|
26
26
|
|
|
27
27
|
Emit the predicate now.`:M(P,l,c[c.length-1].details??c[c.length-1].reason),m;try{m=await r(T,j,{signal:$});}catch(S){if($?.aborted)throw new Error("aborted");c.push({attempt:d,reason:`LLM runner threw: ${S instanceof Error?S.message:String(S)}`});continue}let F=typeof m.output=="string"?m.output:JSON.stringify(m.output);b=F;let h=B(F,l,I);if(h.ok)return {predicate:h.predicate,attempts:d,errors:c,lastRawOutput:b};c.push({attempt:d,reason:h.reason,details:h.details});}return {predicate:null,attempts:d,errors:c,lastRawOutput:b}}function v(t,e){let n=core.getSchemaFieldKinds(t),r=[];for(let[o,a]of n.entries()){if(e&&!o.startsWith(e))continue;let i=core.getOperatorsForKind(a);r.push(`${o}: ${s(a)} \u2014 ops: ${i.join(", ")}`);}return r.join(`
|
|
28
28
|
`)}function E(t,e){return e??`Emit a Directive FactPredicate (JSON tree of facts and operators) matching the user's intent. Schema:
|
|
29
|
-
${t}`}function G(t,e={}){let n=v(t,e.factPath),r=e.name??"emit_predicate",o=E(n,e.description);return {type:"function",function:{name:r,description:o,parameters:{type:"object",properties:{predicate:{type:"object"}},required:["predicate"]}},schemaSummary:n}}function U(t,e={}){let n=v(t,e.factPath),r=e.name??"emit_predicate",o=E(n,e.description);return {name:r,description:o,input_schema:{type:"object",properties:{predicate:{type:"object"}},required:["predicate"]},schemaSummary:n}}function Q(t,e={}){return U(t,e)}async function Z(t){let e=await k(t);if(e.predicate===null)throw new f(`[Directive] predicateFromIntentWithProvenance: failed after ${e.attempts} attempt(s). Last error: ${e.errors[e.errors.length-1]?.reason??"unknown"}`,e.attempts,e.errors,e.lastRawOutput);let n=t.redact?t.redact(t.intent):t.intent,r=t.agent?.model??"unknown",o=core.predicateHash(e.predicate),a=await C(n),i=t.redactIntent?{model:r,intentHash:a,attemptCount:e.attempts,emittedAt:new Date().toISOString(),predicateHash:o}:{model:r,intent:n,intentHash:a,attemptCount:e.attempts,emittedAt:new Date().toISOString(),predicateHash:o};return {predicate:e.predicate,provenance:i}}exports.a=f;exports.b=X;exports.c=k;exports.d=G;exports.e=U;exports.f=Q;exports.g=Z;//# sourceMappingURL=chunk-
|
|
30
|
-
//# sourceMappingURL=chunk-
|
|
29
|
+
${t}`}function G(t,e={}){let n=v(t,e.factPath),r=e.name??"emit_predicate",o=E(n,e.description);return {type:"function",function:{name:r,description:o,parameters:{type:"object",properties:{predicate:{type:"object"}},required:["predicate"]}},schemaSummary:n}}function U(t,e={}){let n=v(t,e.factPath),r=e.name??"emit_predicate",o=E(n,e.description);return {name:r,description:o,input_schema:{type:"object",properties:{predicate:{type:"object"}},required:["predicate"]},schemaSummary:n}}function Q(t,e={}){return U(t,e)}async function Z(t){let e=await k(t);if(e.predicate===null)throw new f(`[Directive] predicateFromIntentWithProvenance: failed after ${e.attempts} attempt(s). Last error: ${e.errors[e.errors.length-1]?.reason??"unknown"}`,e.attempts,e.errors,e.lastRawOutput);let n=t.redact?t.redact(t.intent):t.intent,r=t.agent?.model??"unknown",o=core.predicateHash(e.predicate),a=await C(n),i=t.redactIntent?{model:r,intentHash:a,attemptCount:e.attempts,emittedAt:new Date().toISOString(),predicateHash:o}:{model:r,intent:n,intentHash:a,attemptCount:e.attempts,emittedAt:new Date().toISOString(),predicateHash:o};return {predicate:e.predicate,provenance:i}}exports.a=f;exports.b=X;exports.c=k;exports.d=G;exports.e=U;exports.f=Q;exports.g=Z;//# sourceMappingURL=chunk-Y4A4UJPU.cjs.map
|
|
30
|
+
//# sourceMappingURL=chunk-Y4A4UJPU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/predicate-from-intent.ts"],"names":["djb2Hash","str","hash","i","hashStringSha256","raw","subtle","enc","buf","bytes","hex","b","PredicateFromIntentError","message","attempts","errors","lastRawOutput","SYSTEM_PROMPT_HEADER","renderKindForPrompt","node","nullableTag","k","v","buildSystemPrompt","kindMap","factPath","lines","path","ops","getOperatorsForKind","buildErrorFeedback","intent","pathsToShow","e","shown","remaining","validateOneAttempt","rawOutput","opts","parsed","extractJsonFromOutput","err","validatePredicate","schemaResult","validatePredicateAgainstSchema","DEFAULT_MAX_RETRIES","DEFAULT_MAX_PREDICATE_BYTES","DEFAULT_MAX_OPERATOR_COUNT","DEFAULT_MAX_ARRAY_OPERAND_LENGTH","predicateFromIntent","result","predicateFromIntentRaw","rawIntent","schema","runner","agent","maxRetries","maxPredicateBytes","maxOperatorCount","maxArrayOperandLength","redact","signal","getSchemaFieldKinds","systemPrompt","baseAgent","promptAgent","attempt","validateOpts","input","runResult","validated","buildSchemaSummary","buildDescription","summary","override","predicateToolSpecOpenAI","name","description","predicateToolSpecAnthropic","predicateToolSpec","predicateFromIntentWithProvenance","sanitizedIntent","model","predicateHashValue","predicateHash","intentHash","provenance"],"mappings":"uGAmDA,SAASA,CAAAA,CAASC,CAAAA,CAAqB,CACrC,IAAIC,CAAAA,CAAO,IAAA,CACX,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAI,MAAA,CAAQE,CAAAA,EAAAA,CAC9BD,CAA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,CAAa,MAAMjF,CAAAA,CAAiB6E,CAAe,CAAA,CAEnDK,CAAAA,CAA4ChD,CAAAA,CAAK,YAAA,CACnD,CACE,KAAA,CAAA4C,CAAAA,CACA,UAAA,CAAAG,CAAAA,CACA,YAAA,CAAchF,CAAAA,CAAI,QAAA,CAClB,SAAA,CAAW,IAAI,IAAA,EAAK,CAAE,WAAA,EAAY,CAClC,aAAA,CAAe8E,CACjB,CAAA,CACA,CACE,KAAA,CAAAD,CAAAA,CACA,MAAA,CAAQD,CAAAA,CACR,UAAA,CAAAI,CAAAA,CACA,YAAA,CAAchF,CAAAA,CAAI,QAAA,CAClB,SAAA,CAAW,IAAI,IAAA,GAAO,WAAA,EAAY,CAClC,aAAA,CAAe8E,CACjB,CAAA,CAEJ,OAAO,CACL,SAAA,CAAW9E,CAAAA,CAAI,SAAA,CACf,UAAA,CAAAiF,CACF,CACF","file":"chunk-Y4A4UJPU.cjs","sourcesContent":["/**\n * predicateFromIntent — let an LLM emit a typed FactPredicate as JSON,\n * structurally + semantically validated before it ever reaches your\n * constraint engine.\n *\n * Pipeline per call attempt:\n *\n * 1. Output-size check (reject before JSON.parse for DoS guard)\n * 2. JSON.parse via extractJsonFromOutput (handles surrounding prose)\n * 3. validatePredicate (structural: closed operator set, depth, JSON safety)\n * 4. Operator-count check\n * 5. validatePredicateAgainstSchema (semantic: operator-on-kind matrix)\n *\n * On any failure: a structured error message — including the offending\n * clause's path, the allowed operators for that fact's kind, and the\n * original schema kinds — is fed back to the LLM in the next attempt.\n *\n * Returns the validated FactPredicate. Throws PredicateFromIntentError\n * on retry exhaustion. NEVER returns a partial / unvalidated predicate.\n */\n\nimport {\n type FactPredicate,\n type SchemaKindNode,\n type SchemaValidationError,\n getOperatorsForKind,\n getSchemaFieldKinds,\n predicateHash,\n validatePredicate,\n validatePredicateAgainstSchema,\n} from \"@directive-run/core\";\n\nimport { extractJsonFromOutput } from \"./structured-output.js\";\nimport type { AgentLike, AgentRunner } from \"./types.js\";\n\n// ============================================================================\n// Hashing helpers\n// ============================================================================\n//\n// Provenance hashing has two flavors:\n//\n// - `predicateHash(spec)` — synchronous djb2 of a stable-stringified\n// predicate. Imported from `@directive-run/core` (the supported,\n// semver-stable surface). Two semantically-identical predicates emitted\n// with different whitespace / key-order produce the same hash. (N3)\n//\n// - `hashStringSha256(str)` — async SHA-256 via crypto.subtle when\n// available, djb2 fallback otherwise. Used for `intentHash` —\n// intents are free-form strings, no canonicalization to do.\n//\n\nfunction djb2Hash(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n\n return (hash >>> 0).toString(16);\n}\n\nasync function hashStringSha256(raw: string): Promise<string> {\n // Prefer crypto.subtle SHA-256 when available (browsers, Node 19+, workers).\n // Fall back to a sync djb2 — collision-prone, but adequate for telemetry\n // alongside the persisted predicate.\n try {\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto\n ?.subtle;\n if (subtle && typeof subtle.digest === \"function\") {\n const enc = new TextEncoder();\n const buf = await subtle.digest(\"SHA-256\", enc.encode(raw));\n const bytes = new Uint8Array(buf);\n let hex = \"\";\n for (const b of bytes) {\n hex += b.toString(16).padStart(2, \"0\");\n }\n\n return hex;\n }\n } catch {\n // fall through to djb2\n }\n\n return djb2Hash(raw);\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PredicateFromIntentOptions<_F = Record<string, unknown>> {\n /** Natural-language intent (untrusted user input — sanitize via `redact`). */\n intent: string;\n /**\n * Module schema (must expose builders with `_typeName` or `_kind`).\n * Pass either `{ facts: {...} }` or a bare `Record<string, builder>`.\n */\n schema: unknown;\n /** AgentRunner from `@directive-run/ai` adapters (createOpenAIRunner, etc.). */\n runner: AgentRunner;\n /**\n * Optional agent override. Default is `{ name: \"predicate-emitter\" }`\n * with our system prompt; pass `instructions` to append additional\n * context.\n */\n agent?: AgentLike;\n /**\n * Optional dotted-path namespace; useful for cross-module systems\n * where the LLM should emit a predicate over `auth.token` (default:\n * the schema's root facts).\n */\n factPath?: string;\n /** Max retries on validation failure. Default 3. */\n maxRetries?: number;\n /**\n * Hard byte cap on the LLM's raw output, BEFORE JSON.parse. Defaults\n * to 64 KiB. A larger predicate is rejected outright; protects\n * against multi-MB-payload DoS where the predicate is technically\n * structurally valid.\n */\n maxPredicateBytes?: number;\n /**\n * Hard cap on the number of operator clauses in the predicate.\n * Defaults to 256. Protects against `{ $any: [{ x: 1 }, … x100,000 ] }`\n * style operator-count exhaustion.\n */\n maxOperatorCount?: number;\n /**\n * Optional sanitizer applied to `intent` BEFORE it lands in the\n * system prompt. Useful for stripping or redacting user-controlled\n * content that looks like prompt-injection.\n */\n redact?: (intent: string) => string;\n /**\n * Hard cap on the length of each `$in` / `$nin` array operand the LLM\n * may emit. Defaults to 1000. Forwarded to\n * `validatePredicateAgainstSchema`'s `maxArrayOperandLength`.\n */\n maxArrayOperandLength?: number;\n /**\n * Optional `AbortSignal` for cooperative cancellation. (N6)\n *\n * The retry loop checks `signal.aborted` between attempts AND forwards\n * the signal into the runner call itself (`runner(agent, input, { signal })`).\n * Whether the in-flight LLM call honors the signal depends on the runner:\n * fetch-based adapters (the bundled OpenAI / Anthropic / Ollama runners)\n * thread it through to `fetch`, so the network call aborts mid-stream.\n * A custom runner that ignores the signal still delivers cancellation\n * at the next retry boundary.\n *\n * On abort: throws `Error(\"aborted\")`.\n *\n * NOTE: `predicateFromIntent` does NOT limit in-flight calls — callers\n * MUST wrap with a concurrency limiter (e.g. `p-limit`) to bound\n * fan-out under load.\n */\n signal?: AbortSignal;\n /**\n * When `true`, the {@link PredicateFromIntentProvenance} returned by\n * `predicateFromIntentWithProvenance` omits the raw `intent` string and\n * stores only the SHA-256 `intentHash`. Use this in PII-sensitive\n * contexts where the original intent must not be persisted. (M6)\n *\n * **Default `false` for back-compat.** For PII-sensitive deployments,\n * ALWAYS set `redactIntent: true` — the raw intent may contain\n * user-supplied content (names, emails, medical or financial details,\n * customer messages) that becomes a permanent record in\n * `provenance.intent`. The default is opt-in only because flipping it\n * now would silently strip diagnostic data from existing callers; v2\n * may flip this default.\n *\n * Pair with a `redact:` sanitizer when the intent itself must be\n * scrubbed BEFORE it lands in the LLM prompt — `redactIntent` controls\n * only what enters the provenance record, not what the LLM sees.\n */\n redactIntent?: boolean;\n}\n\nexport interface PredicateFromIntentDiagnostics<F = Record<string, unknown>> {\n /** The validated predicate (`null` if all retries failed). */\n predicate: FactPredicate<F> | null;\n /** Number of LLM calls actually made. */\n attempts: number;\n /** Errors encountered across all attempts (most recent last). */\n errors: ReadonlyArray<{\n attempt: number;\n reason: string;\n details?: readonly SchemaValidationError[];\n }>;\n /** The raw LLM output from the final attempt — useful for debugging. */\n lastRawOutput?: string;\n}\n\n/** Thrown by `predicateFromIntent` on retry exhaustion. `predicateFromIntentRaw` returns these as a diagnostics payload instead. */\nexport class PredicateFromIntentError extends Error {\n override readonly name = \"PredicateFromIntentError\";\n constructor(\n message: string,\n public readonly attempts: number,\n public readonly errors: ReadonlyArray<{\n attempt: number;\n reason: string;\n details?: readonly SchemaValidationError[];\n }>,\n public readonly lastRawOutput: string | undefined,\n ) {\n super(message);\n }\n}\n\n// ============================================================================\n// Prompt builder\n// ============================================================================\n\nconst SYSTEM_PROMPT_HEADER = `You emit ONLY a JSON object describing a Directive FactPredicate — no prose, no markdown fences, no explanation.\n\nA FactPredicate is a JSON tree of fact paths and operators:\n- Object form (preferred): { \"factName\": { \"$op\": operand }, \"otherFact\": { \"$op\": operand } }\n- Combinators: { \"$all\": [predicateA, predicateB] }, { \"$any\": [...] }, { \"$not\": predicate }\n- Bare value (equality shortcut): { \"factName\": value }\n\nOperator set (CLOSED — only these are valid):\n $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists, $between,\n $matches, $startsWith, $endsWith, $contains, $changed\nCombinators: $all, $any, $not\n\nEach operator is only valid for certain kinds (see below). Emit ONLY operators valid for the fact's kind.\n`;\n\nfunction renderKindForPrompt(node: SchemaKindNode): string {\n const nullableTag = node.nullable ? \" (nullable)\" : \"\";\n switch (node.kind) {\n case \"literal\":\n return `literal ${JSON.stringify(node.value)} (${node.primitive})${nullableTag}`;\n case \"enum\":\n return `enum ${JSON.stringify(node.values)} (${node.primitive})${nullableTag}`;\n case \"array\":\n return `array of ${renderKindForPrompt(node.element)}${nullableTag}`;\n case \"tuple\":\n return `tuple [${node.elements.map(renderKindForPrompt).join(\", \")}]${nullableTag}`;\n case \"object\":\n return `object { ${Object.entries(node.shape)\n .map(([k, v]) => `${k}: ${renderKindForPrompt(v)}`)\n .join(\", \")} }${nullableTag}`;\n case \"record\":\n return `record<string, ${renderKindForPrompt(node.value)}>${nullableTag}`;\n case \"union\":\n return `union (${node.members.map(renderKindForPrompt).join(\" | \")})${nullableTag}`;\n case \"branded\":\n return `branded(${renderKindForPrompt(node.inner)})${nullableTag}`;\n default:\n return `${node.kind}${nullableTag}`;\n }\n}\n\nfunction buildSystemPrompt(\n kindMap: Map<string, SchemaKindNode>,\n factPath?: string,\n): string {\n const lines: string[] = [SYSTEM_PROMPT_HEADER];\n\n lines.push(\"\\nFacts in this schema (path → kind → allowed operators):\");\n for (const [path, node] of kindMap.entries()) {\n if (factPath && !path.startsWith(factPath)) continue;\n const ops = getOperatorsForKind(node);\n lines.push(\n ` ${path}: ${renderKindForPrompt(node)} — allowed: ${ops.join(\", \")}`,\n );\n }\n if (factPath) {\n lines.push(\n `\\nThe user intent will be over the namespace \"${factPath}\". Use only facts at or below that path.`,\n );\n }\n\n lines.push(\n '\\nRespond with ONLY the JSON predicate object. No prose. No markdown fences. No \"Here is...\".',\n );\n\n return lines.join(\"\\n\");\n}\n\nfunction buildErrorFeedback(\n intent: string,\n kindMap: Map<string, SchemaKindNode>,\n errors: readonly SchemaValidationError[] | string,\n): string {\n const lines: string[] = [];\n lines.push(\n \"Your previous response was rejected. Original intent (still applies):\",\n );\n lines.push(` ${intent}`);\n\n // M16: When we have structured errors, scope the schema reminder to only\n // the offending fact paths instead of dumping the full schema. Falls back\n // to the full schema for non-structural failures (string errors).\n let pathsToShow: Set<string> | null = null;\n\n if (typeof errors === \"string\") {\n lines.push(`\\nReason: ${errors}`);\n } else {\n lines.push(\"\\nValidation errors (fix every one):\");\n pathsToShow = new Set();\n for (const e of errors) {\n lines.push(` - path \"${e.path}\", op \"${e.op}\": ${e.reason}`);\n if (e.allowedOps && e.allowedOps.length > 0) {\n lines.push(\n ` → allowed operators for this fact: ${e.allowedOps.join(\", \")}`,\n );\n }\n // Collect every path mentioned by an error. If a path isn't in the\n // kindMap (unknown fact), the offending key may be a dotted prefix of\n // a real fact — include the closest known ancestor too.\n pathsToShow.add(e.path);\n }\n }\n\n lines.push(\"\\nSchema reminder:\");\n if (pathsToShow && pathsToShow.size > 0) {\n let shown = 0;\n for (const path of pathsToShow) {\n const node = kindMap.get(path);\n if (node) {\n const ops = getOperatorsForKind(node);\n lines.push(\n ` ${path}: ${renderKindForPrompt(node)} — allowed: ${ops.join(\", \")}`,\n );\n shown++;\n } else {\n lines.push(\n ` ${path}: (not in schema — pick from the available facts below)`,\n );\n }\n }\n const remaining = kindMap.size - shown;\n if (remaining > 0) {\n lines.push(\n ` …and ${remaining} more fact(s) available — ask if you need the full list.`,\n );\n }\n } else {\n for (const [path, node] of kindMap.entries()) {\n const ops = getOperatorsForKind(node);\n lines.push(\n ` ${path}: ${renderKindForPrompt(node)} — allowed: ${ops.join(\", \")}`,\n );\n }\n }\n\n lines.push(\"\\nEmit ONLY a corrected JSON FactPredicate object. No prose.\");\n\n return lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Validation pipeline (one attempt)\n// ============================================================================\n\nfunction validateOneAttempt(\n rawOutput: string,\n kindMap: Map<string, SchemaKindNode>,\n opts: {\n maxPredicateBytes: number;\n maxOperatorCount: number;\n maxArrayOperandLength: number;\n },\n):\n | { ok: true; predicate: unknown }\n | { ok: false; reason: string; details?: readonly SchemaValidationError[] } {\n // 1. Byte cap (pre-parse — kills 10MB-payload DoS)\n if (rawOutput.length > opts.maxPredicateBytes) {\n return {\n ok: false,\n reason: `Output exceeded maxPredicateBytes=${opts.maxPredicateBytes} (got ${rawOutput.length}). Emit a smaller predicate.`,\n };\n }\n\n // 2. JSON parse (handles surrounding prose)\n let parsed: unknown;\n try {\n parsed = extractJsonFromOutput(rawOutput);\n } catch (err) {\n return {\n ok: false,\n reason: `Could not extract JSON from output: ${\n err instanceof Error ? err.message : String(err)\n }`,\n };\n }\n\n // 3. Structural validation (closed operator set, depth, JSON-safety)\n try {\n validatePredicate(parsed);\n } catch (err) {\n return {\n ok: false,\n reason: `Structural validation failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n };\n }\n\n // 4 + 5. Operator-count cap + array-operand cap + schema validation\n const schemaResult = validatePredicateAgainstSchema(parsed, kindMap, {\n maxOperatorCount: opts.maxOperatorCount,\n maxArrayOperandLength: opts.maxArrayOperandLength,\n });\n\n if (!schemaResult.ok) {\n return {\n ok: false,\n reason: `Predicate has ${schemaResult.errors.length} schema-validation error(s).`,\n details: schemaResult.errors,\n };\n }\n\n return { ok: true, predicate: parsed };\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_PREDICATE_BYTES = 65_536; // 64 KiB\nconst DEFAULT_MAX_OPERATOR_COUNT = 256;\nconst DEFAULT_MAX_ARRAY_OPERAND_LENGTH = 1000;\n\n/**\n * Ask an LLM to emit a FactPredicate matching the user's intent, then\n * validate it structurally + semantically before returning. On validation\n * failure, retries with structured error feedback in the next prompt.\n *\n * Throws {@link PredicateFromIntentError} on retry exhaustion. NEVER\n * returns a partial / unvalidated predicate.\n *\n * **Rate limiting:** this function does NOT limit in-flight calls. Wrap\n * with a concurrency limiter (e.g. `p-limit` / `Bottleneck`) before\n * exposing it to user-driven traffic. Pass an `AbortSignal` via `opts.signal`\n * for cooperative cancellation between retry attempts.\n *\n * @example\n * ```ts\n * import { createOpenAIRunner } from \"@directive-run/ai/openai\";\n * import { predicateFromIntent } from \"@directive-run/ai\";\n *\n * const runner = createOpenAIRunner({ apiKey, model: \"gpt-4o-mini\" });\n *\n * const predicate = await predicateFromIntent({\n * intent: \"checkout is unblocked when the cart total is at least 50\",\n * schema: myModule.schema,\n * runner,\n * });\n * // → { cartTotal: { $gte: 50 } }\n * ```\n */\nexport async function predicateFromIntent<F = Record<string, unknown>>(\n opts: PredicateFromIntentOptions<F>,\n): Promise<FactPredicate<F>> {\n const result = await predicateFromIntentRaw(opts);\n if (result.predicate === null) {\n throw new PredicateFromIntentError(\n `[Directive] predicateFromIntent: failed after ${result.attempts} attempt(s). Last error: ${\n result.errors[result.errors.length - 1]?.reason ?? \"unknown\"\n }`,\n result.attempts,\n result.errors,\n result.lastRawOutput,\n );\n }\n\n return result.predicate;\n}\n\n/**\n * Lower-level variant — returns the validated predicate (or null) plus\n * full diagnostics. Use when you want to surface validation telemetry,\n * preview the LLM's last raw output, or display per-attempt errors in\n * a UI.\n */\nexport async function predicateFromIntentRaw<F = Record<string, unknown>>(\n opts: PredicateFromIntentOptions<F>,\n): Promise<PredicateFromIntentDiagnostics<F>> {\n const {\n intent: rawIntent,\n schema,\n runner,\n agent,\n factPath,\n maxRetries = DEFAULT_MAX_RETRIES,\n maxPredicateBytes = DEFAULT_MAX_PREDICATE_BYTES,\n maxOperatorCount = DEFAULT_MAX_OPERATOR_COUNT,\n maxArrayOperandLength = DEFAULT_MAX_ARRAY_OPERAND_LENGTH,\n redact,\n signal,\n } = opts;\n\n if (typeof rawIntent !== \"string\" || rawIntent.length === 0) {\n throw new Error(\n \"[Directive] predicateFromIntent: `intent` must be a non-empty string.\",\n );\n }\n\n const intent = redact ? redact(rawIntent) : rawIntent;\n const kindMap = getSchemaFieldKinds(schema);\n\n if (kindMap.size === 0) {\n throw new Error(\n \"[Directive] predicateFromIntent: schema has no introspectable facts. Pass a module schema or a bare facts record.\",\n );\n }\n\n const systemPrompt = buildSystemPrompt(kindMap, factPath);\n const baseAgent: AgentLike = agent ?? { name: \"predicate-emitter\" };\n const promptAgent: AgentLike = {\n ...baseAgent,\n instructions: `${baseAgent.instructions ?? \"\"}\\n\\n${systemPrompt}`.trim(),\n };\n\n const errors: Array<{\n attempt: number;\n reason: string;\n details?: readonly SchemaValidationError[];\n }> = [];\n\n let lastRawOutput: string | undefined;\n let attempt = 0;\n const validateOpts = {\n maxPredicateBytes,\n maxOperatorCount,\n maxArrayOperandLength,\n };\n\n while (attempt < maxRetries + 1) {\n // M7: cooperative cancellation — bail between attempts when aborted.\n if (signal?.aborted) {\n throw new Error(\"aborted\");\n }\n attempt++;\n const input =\n attempt === 1\n ? `Intent: ${intent}\\n\\nEmit the predicate now.`\n : buildErrorFeedback(\n intent,\n kindMap,\n errors[errors.length - 1]!.details ??\n errors[errors.length - 1]!.reason,\n );\n\n let runResult: Awaited<ReturnType<typeof runner>>;\n try {\n // (N6) Forward the abort signal to the runner so in-flight LLM\n // calls can be cancelled mid-fetch. fetch-based adapters honor\n // this via the underlying fetch's `signal` option. Custom runners\n // that ignore the third arg fall back to between-retry cancellation.\n runResult = await runner(promptAgent, input, { signal });\n } catch (err) {\n // If the abort happened during the in-flight call (and the runner\n // honored it), surface that as a plain `Error(\"aborted\")` rather\n // than burning a retry attempt on a cancellation error.\n if (signal?.aborted) {\n throw new Error(\"aborted\");\n }\n errors.push({\n attempt,\n reason: `LLM runner threw: ${err instanceof Error ? err.message : String(err)}`,\n });\n continue;\n }\n\n const rawOutput =\n typeof runResult.output === \"string\"\n ? runResult.output\n : JSON.stringify(runResult.output);\n lastRawOutput = rawOutput;\n\n const validated = validateOneAttempt(rawOutput, kindMap, validateOpts);\n\n if (validated.ok) {\n return {\n predicate: validated.predicate as FactPredicate<F>,\n attempts: attempt,\n errors,\n lastRawOutput,\n };\n }\n\n errors.push({\n attempt,\n reason: validated.reason,\n details: validated.details,\n });\n }\n\n return {\n predicate: null,\n attempts: attempt,\n errors,\n lastRawOutput,\n };\n}\n\n// ============================================================================\n// Tool-spec presets (OpenAI + Anthropic function-calling)\n// ============================================================================\n\nexport interface PredicateToolSpecOptions {\n /** Tool name. Default `\"emit_predicate\"`. */\n name?: string;\n /** Tool description. Default: a one-liner describing predicate emission. */\n description?: string;\n /** Optional dotted-path namespace to restrict the tool's scope. */\n factPath?: string;\n}\n\n/**\n * Anthropic Messages API tool shape. Drop into the `tools: [...]` array.\n * Anthropic's API expects `input_schema` at the top level of the tool.\n */\nexport interface PredicateToolSpecAnthropic {\n name: string;\n description: string;\n input_schema: {\n type: \"object\";\n properties: { predicate: { type: \"object\" } };\n required: [\"predicate\"];\n };\n /** Human-readable schema description — embed in your tool's \"description\" if your provider concatenates them. */\n schemaSummary: string;\n}\n\n/**\n * OpenAI Chat Completions / Responses API tool shape. Drop into the\n * `tools: [...]` array. OpenAI nests the function payload under\n * `function: { name, description, parameters }`.\n */\nexport interface PredicateToolSpecOpenAI {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: \"object\";\n properties: { predicate: { type: \"object\" } };\n required: [\"predicate\"];\n };\n };\n /** Human-readable schema description — embed in your tool's \"description\" if your provider concatenates them. */\n schemaSummary: string;\n}\n\n/**\n * @deprecated Use {@link PredicateToolSpecAnthropic} (or\n * {@link PredicateToolSpecOpenAI}) directly. Kept as an alias for the\n * pre-split shape that v1.12.x callers depend on; identical to\n * `PredicateToolSpecAnthropic`.\n */\nexport type PredicateToolSpec = PredicateToolSpecAnthropic;\n\nfunction buildSchemaSummary(\n schema: unknown,\n factPath: string | undefined,\n): string {\n const kindMap = getSchemaFieldKinds(schema);\n const lines: string[] = [];\n for (const [path, node] of kindMap.entries()) {\n if (factPath && !path.startsWith(factPath)) continue;\n const ops = getOperatorsForKind(node);\n lines.push(\n `${path}: ${renderKindForPrompt(node)} — ops: ${ops.join(\", \")}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction buildDescription(summary: string, override?: string): string {\n return (\n override ??\n `Emit a Directive FactPredicate (JSON tree of facts and operators) matching the user's intent. Schema:\\n${summary}`\n );\n}\n\n/**\n * OpenAI Chat Completions / Responses API tool spec for predicate\n * emission. Drop the result into your `tools: [...]` array; the model\n * will be told to emit a predicate matching this schema.\n *\n * @example\n * ```ts\n * const tool = predicateToolSpecOpenAI(myModule.schema, { name: \"set_checkout_rule\" });\n *\n * await openai.chat.completions.create({\n * model: \"gpt-4o-mini\",\n * tools: [tool],\n * messages: [...],\n * });\n * ```\n */\nexport function predicateToolSpecOpenAI(\n schema: unknown,\n opts: PredicateToolSpecOptions = {},\n): PredicateToolSpecOpenAI {\n const summary = buildSchemaSummary(schema, opts.factPath);\n const name = opts.name ?? \"emit_predicate\";\n const description = buildDescription(summary, opts.description);\n\n return {\n type: \"function\",\n function: {\n name,\n description,\n parameters: {\n type: \"object\",\n properties: { predicate: { type: \"object\" } },\n required: [\"predicate\"],\n },\n },\n schemaSummary: summary,\n };\n}\n\n/**\n * Anthropic Messages API tool spec for predicate emission. Drop the\n * result into your `tools: [...]` array; the model will be told to emit\n * a predicate matching this schema.\n *\n * @example\n * ```ts\n * const tool = predicateToolSpecAnthropic(myModule.schema, { name: \"set_checkout_rule\" });\n *\n * await anthropic.messages.create({\n * model: \"claude-3-5-sonnet-latest\",\n * tools: [tool],\n * messages: [...],\n * });\n * ```\n */\nexport function predicateToolSpecAnthropic(\n schema: unknown,\n opts: PredicateToolSpecOptions = {},\n): PredicateToolSpecAnthropic {\n const summary = buildSchemaSummary(schema, opts.factPath);\n const name = opts.name ?? \"emit_predicate\";\n const description = buildDescription(summary, opts.description);\n\n return {\n name,\n description,\n input_schema: {\n type: \"object\",\n properties: { predicate: { type: \"object\" } },\n required: [\"predicate\"],\n },\n schemaSummary: summary,\n };\n}\n\n/**\n * @deprecated Use {@link predicateToolSpecAnthropic} (or\n * {@link predicateToolSpecOpenAI}) directly. Back-compat alias for\n * v1.12.x callers — emits the Anthropic shape, unchanged.\n */\nexport function predicateToolSpec(\n schema: unknown,\n opts: PredicateToolSpecOptions = {},\n): PredicateToolSpec {\n return predicateToolSpecAnthropic(schema, opts);\n}\n\n// ============================================================================\n// Provenance (M24)\n// ============================================================================\n\nexport interface PredicateFromIntentProvenance {\n /**\n * Resolved model name when the caller passes `agent: { model }`,\n * otherwise `\"unknown\"`.\n *\n * NOTE: most callers omit `agent` (the default `predicate-emitter`\n * agent has no model field set), so `model` is `\"unknown\"` by default.\n * v1 does NOT read provider-detected model strings from `RunResult` —\n * that requires every adapter to surface `runResult.model`, which the\n * current `AgentRunner` contract does not. Tracked for v2; callers who\n * need provider attribution today should pass `agent: { name, model: \"...\" }`.\n */\n readonly model: string;\n /**\n * Sanitized intent string actually sent to the LLM (post-redact). When\n * `redactIntent: true` was passed, this field is omitted entirely — only\n * `intentHash` is populated.\n */\n readonly intent?: string;\n /**\n * SHA-256 hex hash of the sanitized intent string (or djb2 fallback\n * when `crypto.subtle` is unavailable). Always present — even when\n * `intent` is omitted via `redactIntent`. (M6)\n */\n readonly intentHash: string;\n /** Number of LLM calls that ran before the final predicate was accepted. */\n readonly attemptCount: number;\n /** ISO timestamp when the predicate was returned. */\n readonly emittedAt: string;\n /**\n * Hash of the VALIDATED predicate (canonicalized via stableStringify\n * before hashing). Two semantically-identical predicates emitted with\n * different whitespace or key order produce the SAME `predicateHash`.\n * Sufficient as a tamper-evident pointer alongside the persisted\n * predicate. (N3)\n *\n * Renamed from `rawOutputHash` in v1.13.x — the old name hashed the\n * raw LLM output string, which made two whitespace-different responses\n * for the same logical predicate hash differently. Callers persisting\n * the old `rawOutputHash` value should re-derive it from the stored\n * predicate using `hashObject(predicate)` from `@directive-run/core/internals`.\n */\n readonly predicateHash: string;\n}\n\nexport interface PredicateFromIntentWithProvenanceResult<\n F = Record<string, unknown>,\n> {\n readonly predicate: FactPredicate<F>;\n readonly provenance: PredicateFromIntentProvenance;\n}\n\n/**\n * Like {@link predicateFromIntent} but additionally returns a structured\n * provenance record — the model name, sanitized intent (or its hash),\n * attempt count, timestamp, and a canonical hash of the validated\n * predicate.\n *\n * **Production deployments MUST persist the provenance record alongside\n * the predicate.** Without it, auditing \"where did this rule come from?\"\n * becomes guesswork.\n *\n * Throws {@link PredicateFromIntentError} on retry exhaustion — same\n * semantics as the un-provenanced variant.\n *\n * **PII guidance (M6):** pass `redactIntent: true` to omit the raw\n * intent from the provenance record and persist only the `intentHash`.\n * Useful when the intent itself is sensitive (medical, financial,\n * customer messages, etc.).\n *\n * **Hash semantics (N3):**\n * - `predicateHash` hashes the VALIDATED predicate object via stable\n * stringification — two whitespace-different LLM outputs that parse to\n * the same predicate produce the same hash.\n * - `intentHash` hashes the sanitized intent STRING (SHA-256 when\n * available, djb2 fallback).\n *\n * @example\n * ```ts\n * const { predicate, provenance } = await predicateFromIntentWithProvenance({\n * intent: \"block checkout when cart > 10k\",\n * schema: checkoutModule.schema,\n * runner,\n * agent: { name: \"predicate-emitter\", model: \"gpt-4o-mini\" },\n * redactIntent: false, // default: store both intent + intentHash\n * });\n *\n * await db.predicates.insert({\n * predicate,\n * model: provenance.model,\n * intent: provenance.intent, // omitted when redactIntent: true\n * intentHash: provenance.intentHash,\n * emittedAt: provenance.emittedAt,\n * predicateHash: provenance.predicateHash,\n * attempts: provenance.attemptCount,\n * });\n * ```\n */\nexport async function predicateFromIntentWithProvenance<\n F = Record<string, unknown>,\n>(\n opts: PredicateFromIntentOptions<F>,\n): Promise<PredicateFromIntentWithProvenanceResult<F>> {\n const raw = await predicateFromIntentRaw(opts);\n if (raw.predicate === null) {\n throw new PredicateFromIntentError(\n `[Directive] predicateFromIntentWithProvenance: failed after ${raw.attempts} attempt(s). Last error: ${\n raw.errors[raw.errors.length - 1]?.reason ?? \"unknown\"\n }`,\n raw.attempts,\n raw.errors,\n raw.lastRawOutput,\n );\n }\n\n const sanitizedIntent = opts.redact ? opts.redact(opts.intent) : opts.intent;\n const model = opts.agent?.model ?? \"unknown\";\n // (N3) Hash the VALIDATED predicate (stable canonical form), not the\n // raw LLM output — two semantically-identical responses with different\n // whitespace / key order produce the same hash. Uses the supported\n // public `predicateHash` helper from `@directive-run/core`.\n const predicateHashValue = predicateHash(raw.predicate);\n // (M6) Always hash the intent; raw intent string is included only when\n // `redactIntent` is not set.\n const intentHash = await hashStringSha256(sanitizedIntent);\n\n const provenance: PredicateFromIntentProvenance = opts.redactIntent\n ? {\n model,\n intentHash,\n attemptCount: raw.attempts,\n emittedAt: new Date().toISOString(),\n predicateHash: predicateHashValue,\n }\n : {\n model,\n intent: sanitizedIntent,\n intentHash,\n attemptCount: raw.attempts,\n emittedAt: new Date().toISOString(),\n predicateHash: predicateHashValue,\n };\n\n return {\n predicate: raw.predicate,\n provenance,\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Plugin } from '@directive-run/core';
|
|
2
|
-
import { l as DebugEvent, g as DebugEventType } from './types-
|
|
2
|
+
import { l as DebugEvent, g as DebugEventType } from './types-6NoeLyrD.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Debug Timeline — AI-specific event log with snapshot correlation.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Plugin } from '@directive-run/core';
|
|
2
|
-
import { l as DebugEvent, g as DebugEventType } from './types-
|
|
2
|
+
import { l as DebugEvent, g as DebugEventType } from './types-6NoeLyrD.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Debug Timeline — AI-specific event log with snapshot correlation.
|
package/dist/devtools.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk7JTR4QBA_cjs=require('./chunk-7JTR4QBA.cjs'),chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs');Object.defineProperty(exports,"connectDevTools",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.b}});Object.defineProperty(exports,"createDevToolsServer",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.a}});Object.defineProperty(exports,"createWsTransport",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.c}});Object.defineProperty(exports,"createDebugTimeline",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.a}});Object.defineProperty(exports,"createDebugTimelinePlugin",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.b}});Object.defineProperty(exports,"createHealthMonitor",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.c}});//# sourceMappingURL=devtools.cjs.map
|
|
2
2
|
//# sourceMappingURL=devtools.cjs.map
|
package/dist/devtools.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { D as DebugTimeline } from './debug-timeline-
|
|
2
|
-
export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-
|
|
3
|
-
import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-
|
|
4
|
-
export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-
|
|
5
|
-
import { l as DebugEvent, b8 as BreakpointState } from './types-
|
|
1
|
+
import { D as DebugTimeline } from './debug-timeline-Sc9cxgxV.cjs';
|
|
2
|
+
export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-Sc9cxgxV.cjs';
|
|
3
|
+
import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-C9v10_tj.cjs';
|
|
4
|
+
export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-C9v10_tj.cjs';
|
|
5
|
+
import { l as DebugEvent, b8 as BreakpointState } from './types-6NoeLyrD.cjs';
|
|
6
6
|
import '@directive-run/core';
|
|
7
7
|
|
|
8
8
|
/**
|
package/dist/devtools.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { D as DebugTimeline } from './debug-timeline-
|
|
2
|
-
export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-
|
|
3
|
-
import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-
|
|
4
|
-
export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-
|
|
5
|
-
import { l as DebugEvent, b8 as BreakpointState } from './types-
|
|
1
|
+
import { D as DebugTimeline } from './debug-timeline-C5Dzs2r_.js';
|
|
2
|
+
export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-C5Dzs2r_.js';
|
|
3
|
+
import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-J2eKmP--.js';
|
|
4
|
+
export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-J2eKmP--.js';
|
|
5
|
+
import { l as DebugEvent, b8 as BreakpointState } from './types-6NoeLyrD.js';
|
|
6
6
|
import '@directive-run/core';
|
|
7
7
|
|
|
8
8
|
/**
|
package/dist/devtools.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-
|
|
1
|
+
export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-BZB3RDI2.js';export{a as createDebugTimeline,b as createDebugTimelinePlugin,c as createHealthMonitor}from'./chunk-FBT73WFY.js';//# sourceMappingURL=devtools.js.map
|
|
2
2
|
//# sourceMappingURL=devtools.js.map
|
package/dist/evals.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as DebugTimeline } from './debug-timeline-
|
|
2
|
-
import { q as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-
|
|
1
|
+
import { D as DebugTimeline } from './debug-timeline-Sc9cxgxV.cjs';
|
|
2
|
+
import { q as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-6NoeLyrD.cjs';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/evals.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as DebugTimeline } from './debug-timeline-
|
|
2
|
-
import { q as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-
|
|
1
|
+
import { D as DebugTimeline } from './debug-timeline-C5Dzs2r_.js';
|
|
2
|
+
import { q as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-6NoeLyrD.js';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/gemini.d.cts
CHANGED
package/dist/gemini.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { m as GuardrailFn, I as InputGuardrailData, O as OutputGuardrailData, aW as SchemaValidator, T as ToolCallGuardrailData } from './types-
|
|
1
|
+
import { m as GuardrailFn, I as InputGuardrailData, O as OutputGuardrailData, aW as SchemaValidator, T as ToolCallGuardrailData } from './types-6NoeLyrD.js';
|
|
2
2
|
import { a as Embedding } from './semantic-cache-DM7ev7NQ.js';
|
|
3
3
|
import { Plugin } from '@directive-run/core';
|
|
4
4
|
|
|
@@ -217,10 +217,10 @@ declare function createContentFilterGuardrail(options: {
|
|
|
217
217
|
/**
|
|
218
218
|
* Fact-PII Guardrail — input guardrail at the fact-store boundary
|
|
219
219
|
*
|
|
220
|
-
* Closes the source → fact → agent prompt PII bypass
|
|
221
|
-
*
|
|
222
|
-
*
|
|
223
|
-
*
|
|
220
|
+
* Closes the source → fact → agent prompt PII bypass that
|
|
221
|
+
* `createPIIGuardrail` alone can't reach: `createPIIGuardrail` only
|
|
222
|
+
* inspects the `data.input` string at runStream entry, so PII that a
|
|
223
|
+
* source publishes into a fact (a Supabase realtime row carrying a
|
|
224
224
|
* customer email, a webhook payload with a SSN, an MCP server's
|
|
225
225
|
* resource notification with a card number) reaches the agent's
|
|
226
226
|
* prompt — via fact injection — without ever hitting the input
|