@directive-run/ai 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/ann-index-27QV9tPC.d.ts +616 -0
  2. package/dist/ann-index-HoZFIUA-.d.cts +616 -0
  3. package/dist/anthropic.d.cts +1 -1
  4. package/dist/anthropic.d.ts +1 -1
  5. package/dist/{chunk-UZKM276C.cjs → chunk-2PG26JZU.cjs} +4 -4
  6. package/dist/chunk-2PG26JZU.cjs.map +1 -0
  7. package/dist/chunk-MIHH5GPT.js +16 -0
  8. package/dist/chunk-MIHH5GPT.js.map +1 -0
  9. package/dist/{debug-timeline-L13P-U2I.d.ts → debug-timeline-BGcPa0JO.d.ts} +1 -1
  10. package/dist/{debug-timeline-DpnRMnLU.d.cts → debug-timeline-Dn1lC_gK.d.cts} +1 -1
  11. package/dist/devtools.d.cts +5 -5
  12. package/dist/devtools.d.ts +5 -5
  13. package/dist/evals.d.cts +2 -2
  14. package/dist/evals.d.ts +2 -2
  15. package/dist/gemini.d.cts +1 -1
  16. package/dist/gemini.d.ts +1 -1
  17. package/dist/guardrails.cjs +1 -1
  18. package/dist/guardrails.cjs.map +1 -1
  19. package/dist/guardrails.d.cts +164 -592
  20. package/dist/guardrails.d.ts +164 -592
  21. package/dist/guardrails.js +1 -1
  22. package/dist/guardrails.js.map +1 -1
  23. package/dist/{health-monitor-C6xoXrQz.d.cts → health-monitor-Cq5sDvid.d.cts} +1 -1
  24. package/dist/{health-monitor-qL9RNMH3.d.ts → health-monitor-DtwmIJkb.d.ts} +1 -1
  25. package/dist/index.cjs +2 -2
  26. package/dist/index.d.cts +10 -10
  27. package/dist/index.d.ts +10 -10
  28. package/dist/index.js +1 -1
  29. package/dist/multi-agent.d.cts +6 -6
  30. package/dist/multi-agent.d.ts +6 -6
  31. package/dist/ollama.d.cts +1 -1
  32. package/dist/ollama.d.ts +1 -1
  33. package/dist/openai.d.cts +2 -2
  34. package/dist/openai.d.ts +2 -2
  35. package/dist/{orchestrator-types-D5cFRt3s.d.ts → orchestrator-types-C5D5JZUj.d.ts} +8 -23
  36. package/dist/{orchestrator-types-Dlfcvdxw.d.cts → orchestrator-types-s0766dDB.d.cts} +8 -23
  37. package/dist/predicate.d.cts +1 -1
  38. package/dist/predicate.d.ts +1 -1
  39. package/dist/{semantic-cache-DM7ev7NQ.d.cts → semantic-cache-Ba0-jEwb.d.cts} +1 -1
  40. package/dist/{semantic-cache-DM7ev7NQ.d.ts → semantic-cache-Ba0-jEwb.d.ts} +1 -1
  41. package/dist/testing.cjs +1 -1
  42. package/dist/testing.d.cts +4 -4
  43. package/dist/testing.d.ts +4 -4
  44. package/dist/testing.js +1 -1
  45. package/dist/{types-DJ09LjZX.d.cts → types-CUp1N0uU.d.cts} +1 -1
  46. package/dist/{types-DJ09LjZX.d.ts → types-CUp1N0uU.d.ts} +1 -1
  47. package/package.json +2 -2
  48. package/dist/chunk-D72LIBH2.js +0 -16
  49. package/dist/chunk-D72LIBH2.js.map +0 -1
  50. package/dist/chunk-UZKM276C.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent-orchestrator.ts"],"names":["MAX_CONVERSATION_MESSAGES","MAX_TOOL_CALLS","createAgentOrchestrator","options","runner","factsSchema","init","constraints","resolvers","guardrails","onApprovalRequest","autoApproveToolCalls","maxTokenBudget","budgetWarningThreshold","onBudgetWarning","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","runAgentWithGuardrails","_currentFacts","callOptions","runAgentWithGuardrailsInner","error","fallbackRunner","rerouteEvent","startTime","contextMessages","contextStr","m","metaStr","formatSystemMeta","bpContext","mods","handleBreakpoint","effectiveInputGuardrails","effectiveOutputGuardrails","inputGuardrailsList","g","i","normalizeGuardrail","guardrail","guardStartTime","result","executeGuardrailWithRetry","GuardrailError","effectiveSchema","effectiveRunner","withStructuredOutput","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","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","resol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CAAUC,CAAAA,CAAmBvG,GAAAA,CAAO,KAAK,EACzC+K,CAAAA,CAAY,CAAC,GAAGzE,GAAAA,CAAQ,SAAA,CAAWqE,CAAE,EAC3CjJ,CAAAA,CAAmB1B,GAAAA,CAAO,KAAA,CAAO,CAC/B,GAAGsG,GAAAA,CACH,QAASA,GAAAA,CAAQ,OAAA,CAAQ,MAAA,CAAQa,CAAAA,EAAMA,CAAAA,CAAE,EAAA,GAAOwD,CAAE,CAAA,CAClD,SAAA,CACEI,CAAAA,CAAU,MAAA,CAASD,CAAAA,CACfC,CAAAA,CAAU,KAAA,CAAM,CAACD,CAAsB,CAAA,CACvCC,CACR,CAAC,EACH,CAAC,EACH,CAAA,CAEA,qBAAA,EAA6C,CAG3C,OAAO,CAAC,GAFQxE,EAAmBvG,GAAAA,CAAO,KAAK,CAAA,CAE5B,OAAO,CAC5B,CAAA,CAEA,OAAA,EAAgB,CACdA,GAAAA,CAAO,OAAA,GACT,CACF,CAGF","file":"chunk-MIHH5GPT.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/** 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 = createOrchestrator({\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 /** 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 // biome-ignore lint/suspicious/noExplicitAny: System type varies per consumer\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 // RFC 0005 originally reserved a `mode: \"inject-system-message\" |\n // \"restart\"` field for choosing how the orchestrator continues after\n // `interruptWhen` fires. The 1.18 landing ships a single behavior\n // (abort the LLM run, emit an `interrupted` chunk, hand control back\n // to the caller — caller re-prompts via a fresh `runStream` or tears\n // down via `abort()`). The field was removed in R13 because the impl\n // never read it; ship a follow-up RFC + field together when automatic\n // re-prompt semantics are settled.\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 // biome-ignore lint/suspicious/noExplicitAny: System type varies\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 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 // biome-ignore lint/suspicious/noExplicitAny: System type varies\n let system: SingleModuleSystem<any>;\n\n // Convert user constraints\n // biome-ignore lint/suspicious/noExplicitAny: Constraint types are complex\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 // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n when: (facts: any) => getAgentState(facts).tokenUsage > maxTokenBudget,\n require: { type: \"__PAUSE_BUDGET_EXCEEDED\" } as PauseBudgetExceededReq,\n };\n }\n\n // Convert user resolvers\n // biome-ignore lint/suspicious/noExplicitAny: Resolver types are complex\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 // biome-ignore lint/suspicious/noExplicitAny: Context type varies\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 // biome-ignore lint/suspicious/noExplicitAny: Bridge module uses dynamic constraints/resolvers\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 // 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 // Wrap in circuit breaker if configured\n if (circuitBreaker) {\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 // Self-healing fallback\n if (selfHealing) {\n // Try fallback runners in order\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:\n 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:\n error instanceof Error ? error.message : String(error),\n });\n }\n\n return await fallbackRunner<T>(agent, input, opts);\n } catch {\n // Try next fallback\n }\n }\n }\n\n // Try fallback agent\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:\n error instanceof Error ? error.message : String(error),\n });\n }\n\n return await runner<T>(selfHealing.fallbackAgent, input, opts);\n } catch {\n // Fallback agent also failed\n }\n }\n\n // Apply degradation policy\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\n return runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\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 // 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 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. ` +\n \"The orchestrator's own setAgentState / setConversation / approvalState writes will trigger interruptWhen, \" +\n \"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 liveCfg.onContextUpdate?.(watchedChanged);\n // biome-ignore lint/suspicious/noExplicitAny: facts type per consumer\n const shouldInterrupt = interruptWhen(\n current as any,\n watchedChanged,\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 (R11 found this).\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"]}
@@ -1,5 +1,5 @@
1
1
  import { Plugin } from '@directive-run/core';
2
- import { l as DebugEvent, g as DebugEventType } from './types-DJ09LjZX.js';
2
+ import { l as DebugEvent, g as DebugEventType } from './types-CUp1N0uU.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-DJ09LjZX.cjs';
2
+ import { l as DebugEvent, g as DebugEventType } from './types-CUp1N0uU.cjs';
3
3
 
4
4
  /**
5
5
  * Debug Timeline — AI-specific event log with snapshot correlation.
@@ -1,8 +1,8 @@
1
- import { D as DebugTimeline } from './debug-timeline-DpnRMnLU.cjs';
2
- export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-DpnRMnLU.cjs';
3
- import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-C6xoXrQz.cjs';
4
- export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-C6xoXrQz.cjs';
5
- import { l as DebugEvent, b8 as BreakpointState } from './types-DJ09LjZX.cjs';
1
+ import { D as DebugTimeline } from './debug-timeline-Dn1lC_gK.cjs';
2
+ export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-Dn1lC_gK.cjs';
3
+ import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-Cq5sDvid.cjs';
4
+ export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-Cq5sDvid.cjs';
5
+ import { l as DebugEvent, b8 as BreakpointState } from './types-CUp1N0uU.cjs';
6
6
  import '@directive-run/core';
7
7
 
8
8
  /**
@@ -1,8 +1,8 @@
1
- import { D as DebugTimeline } from './debug-timeline-L13P-U2I.js';
2
- export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-L13P-U2I.js';
3
- import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-qL9RNMH3.js';
4
- export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-qL9RNMH3.js';
5
- import { l as DebugEvent, b8 as BreakpointState } from './types-DJ09LjZX.js';
1
+ import { D as DebugTimeline } from './debug-timeline-BGcPa0JO.js';
2
+ export { a as DebugTimelineListener, b as DebugTimelineOptions, c as createDebugTimeline, d as createDebugTimelinePlugin } from './debug-timeline-BGcPa0JO.js';
3
+ import { A as AgentHealthMetrics, H as HealthMonitor } from './health-monitor-DtwmIJkb.js';
4
+ export { a as HealthCircuitState, c as createHealthMonitor } from './health-monitor-DtwmIJkb.js';
5
+ import { l as DebugEvent, b8 as BreakpointState } from './types-CUp1N0uU.js';
6
6
  import '@directive-run/core';
7
7
 
8
8
  /**
package/dist/evals.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { D as DebugTimeline } from './debug-timeline-DpnRMnLU.cjs';
2
- import { q as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-DJ09LjZX.cjs';
1
+ import { D as DebugTimeline } from './debug-timeline-Dn1lC_gK.cjs';
2
+ import { r as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-CUp1N0uU.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-L13P-U2I.js';
2
- import { q as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-DJ09LjZX.js';
1
+ import { D as DebugTimeline } from './debug-timeline-BGcPa0JO.js';
2
+ import { r as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-CUp1N0uU.js';
3
3
  import '@directive-run/core';
4
4
 
5
5
  /**
package/dist/gemini.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-DJ09LjZX.cjs';
1
+ import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-CUp1N0uU.cjs';
2
2
  import '@directive-run/core';
3
3
 
4
4
  /**
package/dist/gemini.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-DJ09LjZX.js';
1
+ import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-CUp1N0uU.js';
2
2
  import '@directive-run/core';
3
3
 
4
4
  /**
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkCAA6Q4YY_cjs=require('./chunk-CAA6Q4YY.cjs');require('./chunk-K64WKZ22.cjs');Object.defineProperty(exports,"DEFAULT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.n}});Object.defineProperty(exports,"STRICT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.o}});Object.defineProperty(exports,"createBatchedEmbedder",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.z}});Object.defineProperty(exports,"createBruteForceIndex",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.A}});Object.defineProperty(exports,"createContentFilterGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.h}});Object.defineProperty(exports,"createEnhancedPIIGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.j}});Object.defineProperty(exports,"createInMemoryStorage",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.v}});Object.defineProperty(exports,"createLengthGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.g}});Object.defineProperty(exports,"createModerationGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.b}});Object.defineProperty(exports,"createOutputPIIGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.k}});Object.defineProperty(exports,"createOutputSchemaGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.e}});Object.defineProperty(exports,"createOutputTypeGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.f}});Object.defineProperty(exports,"createPIIGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.a}});Object.defineProperty(exports,"createPromptInjectionGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.r}});Object.defineProperty(exports,"createRateLimitGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.c}});Object.defineProperty(exports,"createSemanticCache",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.w}});Object.defineProperty(exports,"createSemanticCacheGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.x}});Object.defineProperty(exports,"createTestEmbedder",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.y}});Object.defineProperty(exports,"createToolGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.d}});Object.defineProperty(exports,"createUntrustedContentGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.t}});Object.defineProperty(exports,"createVPTreeIndex",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.B}});Object.defineProperty(exports,"detectAndRedactPII",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.m}});Object.defineProperty(exports,"detectPII",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.l}});Object.defineProperty(exports,"detectPromptInjection",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.p}});Object.defineProperty(exports,"markUntrustedContent",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.s}});Object.defineProperty(exports,"redactPII",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.i}});Object.defineProperty(exports,"sanitizeInjection",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.q}});//# sourceMappingURL=guardrails.cjs.map
1
+ 'use strict';var chunkCAA6Q4YY_cjs=require('./chunk-CAA6Q4YY.cjs');require('./chunk-K64WKZ22.cjs');function X(I){let n=I.replace(/[\s-]/g,"");if(n.length<13||n.length>19||!/^\d+$/.test(n))return false;let l=0,c=false;for(let a=n.length-1;a>=0;a--){let i=n[a];if(!i)continue;let u=Number.parseInt(i,10);c&&(u*=2,u>9&&(u-=9)),l+=u,c=!c;}return l%10===0}var ee=[{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g,redactionToken:"[SSN]"},{type:"credit_card",regex:/\b((?:\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|\d{13,19})\b/g,validate:X,redactionToken:"[CREDIT_CARD]"},{type:"email",regex:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,redactionToken:"[EMAIL]"}];function te(I,n){let l=[];for(let c of ee){if(!n.has(c.type))continue;c.regex.lastIndex=0;let a;for(;(a=c.regex.exec(I))!==null;)c.validate&&!c.validate(a[0])||l.push({type:c.type,value:a[0],start:a.index,end:a.index+a[0].length});}return l}function F(I,n){if(n.length===0)return I;let l=[...n].sort((i,u)=>u.start-i.start),c={ssn:"[SSN]",credit_card:"[CREDIT_CARD]",email:"[EMAIL]"},a=I;for(let i of l)a=a.slice(0,i.start)+c[i.type]+a.slice(i.end);return a}function re(I={}){let{mode:n="redact",types:l=["ssn","credit_card","email"],includeKeys:c=[],excludeKeys:a=[],onBlocked:i,customDetector:u,walkDepth:x=1}=I,P=new Set(l),m=new Set(c),C=new Set(a),T=Math.max(1,Math.min(5,Math.floor(x))),y=false,h=null;function k(t){if(y)return;y=true,h=t;let r=t.meta?.byTag?.("pii");if(r)for(let e of r)e.type==="fact"&&e.id&&!C.has(e.id)&&m.add(e.id);}function S(t){let r=[];if(P.size>0)for(let e of te(t,P))r.push(e);if(u)for(let e of u(t))r.push(e);return r}function p(t,r=T){if(typeof t=="string"){let e=S(t);return e.length===0?{matched:false}:{matched:true,redacted:F(t,e),detected:e}}if(r<=0)return {matched:false};if(Array.isArray(t)){let e=null,o=[];for(let d=0;d<t.length;d++){let s=p(t[d],r);if(s.matched){e===null&&(e=[...t]),e[d]=s.redacted;for(let f of s.detected)o.push(f);}}return e===null?{matched:false}:{matched:true,redacted:e,detected:o}}if(t&&typeof t=="object"){let e=null,o=[];for(let[d,s]of Object.entries(t))if(typeof s=="string"){let f=S(s);if(f.length===0)continue;e===null&&(e={...t}),e[d]=F(s,f);for(let g of f)o.push(g);}else if(r>1&&s&&typeof s=="object"){let f=p(s,r-1);if(!f.matched)continue;e===null&&(e={...t}),e[d]=f.redacted;for(let g of f.detected)o.push(g);}return e===null?{matched:false}:{matched:true,redacted:e,detected:o}}return {matched:false}}return {name:"fact-pii-guardrail",onInit(t){k(t);},onFactSet(t,r,e){if(!y||!m.has(t))return;let o=p(r);if(!o.matched||(i?.(t,o.detected,n),n==="alert"))return;let d=h?.facts;if(d?.$store?.set)try{d.$store.set(t,o.redacted);}catch{}},onFactsBatch(t){if(y)for(let r of t){if(r.type!=="set"||!m.has(r.key))continue;let e=p(r.value);if(!e.matched||(i?.(r.key,e.detected,n),n==="alert"))continue;try{r.value=e.redacted;}catch{}let o=h?.facts;if(o?.$store?.set)try{o.$store.set(r.key,e.redacted);}catch{}}}}}Object.defineProperty(exports,"DEFAULT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.n}});Object.defineProperty(exports,"STRICT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.o}});Object.defineProperty(exports,"createBatchedEmbedder",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.z}});Object.defineProperty(exports,"createBruteForceIndex",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.A}});Object.defineProperty(exports,"createContentFilterGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.h}});Object.defineProperty(exports,"createEnhancedPIIGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.j}});Object.defineProperty(exports,"createInMemoryStorage",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.v}});Object.defineProperty(exports,"createLengthGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.g}});Object.defineProperty(exports,"createModerationGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.b}});Object.defineProperty(exports,"createOutputPIIGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.k}});Object.defineProperty(exports,"createOutputSchemaGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.e}});Object.defineProperty(exports,"createOutputTypeGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.f}});Object.defineProperty(exports,"createPIIGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.a}});Object.defineProperty(exports,"createPromptInjectionGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.r}});Object.defineProperty(exports,"createRateLimitGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.c}});Object.defineProperty(exports,"createSemanticCache",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.w}});Object.defineProperty(exports,"createSemanticCacheGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.x}});Object.defineProperty(exports,"createTestEmbedder",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.y}});Object.defineProperty(exports,"createToolGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.d}});Object.defineProperty(exports,"createUntrustedContentGuardrail",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.t}});Object.defineProperty(exports,"createVPTreeIndex",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.B}});Object.defineProperty(exports,"detectAndRedactPII",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.m}});Object.defineProperty(exports,"detectPII",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.l}});Object.defineProperty(exports,"detectPromptInjection",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.p}});Object.defineProperty(exports,"markUntrustedContent",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.s}});Object.defineProperty(exports,"redactPII",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.i}});Object.defineProperty(exports,"sanitizeInjection",{enumerable:true,get:function(){return chunkCAA6Q4YY_cjs.q}});exports.createFactPIIGuardrail=re;//# sourceMappingURL=guardrails.cjs.map
2
2
  //# sourceMappingURL=guardrails.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"guardrails.cjs"}
1
+ {"version":3,"sources":["../src/guardrails/fact-pii.ts"],"names":["luhnValid","value","digits","sum","isEven","i","ch","d","SYNC_PATTERNS","scanText","text","types","out","pattern","match","redactText","matches","sorted","a","b","tokenByType","m","createFactPIIGuardrail","options","mode","includeKeys","excludeKeys","onBlocked","customDetector","walkDepth","typeSet","screenedKeys","excludedSet","effectiveWalkDepth","initialized","systemRef","initScreenedKeys","system","piiTagged","entry","runScan","all","inspect","depth","detected","mutatedArr","nested","mutated","k","v","key","_prev","result","facts","changes","change"],"mappings":"mGAgHA,SAASA,EAAUC,CAAAA,CAAwB,CACzC,IAAMC,CAAAA,CAASD,CAAAA,CAAM,QAAQ,QAAA,CAAU,EAAE,EAEzC,GADIC,CAAAA,CAAO,OAAS,EAAA,EAAMA,CAAAA,CAAO,OAAS,EAAA,EACtC,CAAC,QAAQ,IAAA,CAAKA,CAAM,CAAA,CAAG,OAAO,OAClC,IAAIC,CAAAA,CAAM,EACNC,CAAAA,CAAS,KAAA,CACb,QAASC,CAAAA,CAAIH,CAAAA,CAAO,OAAS,CAAA,CAAGG,CAAAA,EAAK,EAAGA,CAAAA,EAAAA,CAAK,CAC3C,IAAMC,CAAAA,CAAKJ,CAAAA,CAAOG,CAAC,CAAA,CACnB,GAAI,CAACC,CAAAA,CAAI,SACT,IAAIC,CAAAA,CAAI,OAAO,QAAA,CAASD,CAAAA,CAAI,EAAE,CAAA,CAC1BF,CAAAA,GACFG,GAAK,CAAA,CACDA,CAAAA,CAAI,IAAGA,CAAAA,EAAK,CAAA,CAAA,CAAA,CAElBJ,GAAOI,CAAAA,CACPH,CAAAA,CAAS,CAACA,EACZ,CACA,OAAOD,CAAAA,CAAM,EAAA,GAAO,CACtB,CAeA,IAAMK,GAA+B,CACnC,CACE,KAAM,KAAA,CACN,KAAA,CAAO,yBACP,cAAA,CAAgB,OAClB,EACA,CACE,IAAA,CAAM,cACN,KAAA,CAAO,6DAAA,CACP,SAAUR,CAAAA,CACV,cAAA,CAAgB,eAClB,CAAA,CACA,CACE,IAAA,CAAM,OAAA,CACN,MAAO,6CAAA,CACP,cAAA,CAAgB,SAClB,CACF,CAAA,CAEA,SAASS,EAAAA,CACPC,CAAAA,CACAC,EACgB,CAChB,IAAMC,EAAsB,EAAC,CAC7B,QAAWC,CAAAA,IAAWL,EAAAA,CAAe,CACnC,GAAI,CAACG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AG,OAC5B,IAAME,EAASV,CAAAA,CAAQzC,CAAK,EAG5B,GAFI,CAACmD,EAAO,OAAA,GACZzB,CAAAA,GAAYuB,EAAKE,CAAAA,CAAO,QAAA,CAAU5B,CAAI,CAAA,CAClCA,CAAAA,GAAS,SAAS,OAMtB,IAAM6B,CAAAA,CAASlB,CAAAA,EAAmD,MAClE,GAAIkB,CAAAA,EAAO,QAAQ,GAAA,CACjB,GAAI,CACFA,CAAAA,CAAM,MAAA,CAAO,IAAIH,CAAAA,CAAKE,CAAAA,CAAO,QAAQ,EACvC,CAAA,KAAQ,CAGR,CAEJ,CAAA,CAEA,aAAaE,CAAAA,CAAS,CACpB,GAAKpB,CAAAA,CACL,IAAA,IAAWqB,KAAUD,CAAAA,CAAS,CAE5B,GADIC,CAAAA,CAAO,IAAA,GAAS,OAChB,CAACxB,CAAAA,CAAa,IAAIwB,CAAAA,CAAO,GAAG,EAAG,SACnC,IAAMH,EAASV,CAAAA,CAAQa,CAAAA,CAAO,KAAK,CAAA,CAGnC,GAFI,CAACH,CAAAA,CAAO,UACZzB,CAAAA,GAAY4B,CAAAA,CAAO,IAAKH,CAAAA,CAAO,QAAA,CAAU5B,CAAI,CAAA,CACzCA,CAAAA,GAAS,SAAS,SAItB,GAAI,CACD+B,CAAAA,CAA8B,KAAA,CAAQH,EAAO,SAChD,CAAA,KAAQ,CAER,CAIA,IAAMC,EAASlB,CAAAA,EAAmD,KAAA,CAClE,GAAIkB,CAAAA,EAAO,MAAA,EAAQ,IACjB,GAAI,CACFA,EAAM,MAAA,CAAO,GAAA,CAAIE,EAAO,GAAA,CAAKH,CAAAA,CAAO,QAAQ,EAC9C,CAAA,KAAQ,CAER,CAEJ,CACF,CACF,CACF","file":"guardrails.cjs","sourcesContent":["/**\n * Fact-PII Guardrail — input guardrail at the fact-store boundary\n *\n * Closes the source → fact → agent prompt PII bypass surfaced by R5's\n * red-team / privacy / AI-integration reviewers: `createPIIGuardrail`\n * only inspects the `data.input` string at runStream entry, so PII that\n * a source publishes into a fact (a Supabase realtime row carrying a\n * customer email, a webhook payload with a SSN, an MCP server's\n * resource notification with a card number) reaches the agent's\n * prompt — via fact injection — without ever hitting the input\n * guardrail chain.\n *\n * This plugin runs as a Directive plugin (`onFactSet` / `onFactsBatch`),\n * scans every write to a pii-tagged fact against a sync regex matcher\n * for the three highest-volume PII categories (SSN, credit card, email),\n * and either **redacts** the value (the default — safe shipping posture)\n * or **rejects** the write (throws so the source's publish handler can\n * surface the violation). Operators wire it once at `createSystem`; no\n * per-source / per-fact changes are required.\n *\n * The async PII detector from `pii-enhanced.ts` is unsuitable here:\n * `onFactSet` is synchronous and a deferred detection would let the\n * raw PII reach observers + breakpoints + audit-ledger before the\n * redaction completed. Built-in matching is therefore inlined as\n * synchronous regex. Consumers who need richer detection pass a\n * synchronous `customDetector`.\n *\n * @example Defensive (redact PII writes into pii-tagged facts)\n * ```ts\n * import { createSystem, t } from '@directive-run/core';\n * import { createFactPIIGuardrail } from '@directive-run/ai/guardrails';\n *\n * const customer = createModule('customer', {\n * schema: {\n * facts: {\n * email: t.string().meta({ tags: ['pii'] }),\n * ssn: t.string().meta({ tags: ['pii'] }),\n * },\n * },\n * sources: {\n * supabase: { attach: (publish) => subscribe(publish) },\n * },\n * });\n *\n * const system = createSystem({\n * module: customer,\n * plugins: [\n * createFactPIIGuardrail({\n * mode: 'redact',\n * onBlocked: (key, detected) => {\n * console.warn(`[fact-pii] redacted ${detected.length} match(es) in ${key}`);\n * },\n * }),\n * ],\n * });\n * ```\n *\n * @example Monitor-only (alert on every PII match; don't mutate the fact)\n * ```ts\n * createFactPIIGuardrail({\n * mode: 'alert',\n * onBlocked: (key) => Sentry.captureException(new Error(`pii match: ${key}`)),\n * });\n * ```\n *\n * @example Allow specific keys (not just by tag)\n * ```ts\n * createFactPIIGuardrail({\n * includeKeys: ['customer.email', 'customer.phone'],\n * });\n * ```\n */\n\nimport type { Plugin, System } from \"@directive-run/core\";\n\n// ============================================================================\n// Sync PII patterns\n// ============================================================================\n\n/**\n * Public match record for a single PII finding. Mirrors `DetectedPII` from\n * `pii-enhanced.ts` so a downstream guardrail can normalize against either\n * detection path.\n */\nexport interface FactPIIMatch {\n type: FactPIICategory;\n value: string;\n start: number;\n end: number;\n}\n\n/** PII categories the built-in synchronous detector covers. */\nexport type FactPIICategory = \"ssn\" | \"credit_card\" | \"email\";\n\ninterface SyncPattern {\n type: FactPIICategory;\n regex: RegExp;\n /**\n * Optional post-regex validator. Returning false drops the match.\n * Used by credit-card detection to apply the Luhn algorithm (mirrors\n * the validator in `pii-enhanced.ts`) so phone numbers / tracking IDs\n * formatted with separators don't mass-redact as credit cards.\n */\n validate?: (value: string) => boolean;\n redactionToken: string;\n}\n\n/**\n * Luhn checksum — drops credit-card false positives the regex would\n * otherwise pull in (any 13-19 digit sequence with separators). Mirrors\n * the validator in `pii-enhanced.ts` so the two detection paths agree.\n */\nfunction luhnValid(value: string): boolean {\n const digits = value.replace(/[\\s-]/g, \"\");\n if (digits.length < 13 || digits.length > 19) return false;\n if (!/^\\d+$/.test(digits)) return false;\n let sum = 0;\n let isEven = false;\n for (let i = digits.length - 1; i >= 0; i--) {\n const ch = digits[i];\n if (!ch) continue;\n let d = Number.parseInt(ch, 10);\n if (isEven) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n isEven = !isEven;\n }\n return sum % 10 === 0;\n}\n\n// Synchronous patterns. These mirror the highest-volume categories from\n// pii-enhanced.ts; richer detection (addresses, names, phones) is the\n// caller's responsibility via `customDetector` because they require\n// context-aware logic that's a poor fit for a per-fact-write hook.\n//\n// SSN pattern accepts the canonical XXX-XX-XXXX format. Internal IDs\n// formatted the same way will false-positive; the trade-off favors\n// safety (the redaction token is harmless if applied to a non-SSN).\n//\n// Credit-card pattern combines the broad 13-19-digit regex with a Luhn\n// validator so phone numbers, tracking IDs, and other long digit\n// sequences with separators are NOT swept up. This mirrors how\n// `pii-enhanced.ts` keeps its credit-card detection accurate.\nconst SYNC_PATTERNS: SyncPattern[] = [\n {\n type: \"ssn\",\n regex: /\\b\\d{3}-\\d{2}-\\d{4}\\b/g,\n redactionToken: \"[SSN]\",\n },\n {\n type: \"credit_card\",\n regex: /\\b((?:\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4})|\\d{13,19})\\b/g,\n validate: luhnValid,\n redactionToken: \"[CREDIT_CARD]\",\n },\n {\n type: \"email\",\n regex: /\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi,\n redactionToken: \"[EMAIL]\",\n },\n];\n\nfunction scanText(\n text: string,\n types: ReadonlySet<FactPIICategory>,\n): FactPIIMatch[] {\n const out: FactPIIMatch[] = [];\n for (const pattern of SYNC_PATTERNS) {\n if (!types.has(pattern.type)) continue;\n pattern.regex.lastIndex = 0;\n let match: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic exec loop\n while ((match = pattern.regex.exec(text)) !== null) {\n if (pattern.validate && !pattern.validate(match[0])) continue;\n out.push({\n type: pattern.type,\n value: match[0],\n start: match.index,\n end: match.index + match[0].length,\n });\n }\n }\n return out;\n}\n\nfunction redactText(text: string, matches: FactPIIMatch[]): string {\n if (matches.length === 0) return text;\n // Sort matches by start position descending so splicing doesn't shift\n // subsequent offsets.\n const sorted = [...matches].sort((a, b) => b.start - a.start);\n const tokenByType: Record<FactPIICategory, string> = {\n ssn: \"[SSN]\",\n credit_card: \"[CREDIT_CARD]\",\n email: \"[EMAIL]\",\n };\n let out = text;\n for (const m of sorted) {\n out = out.slice(0, m.start) + tokenByType[m.type] + out.slice(m.end);\n }\n return out;\n}\n\n// ============================================================================\n// Options\n// ============================================================================\n\n/**\n * Behavior when a pii-tagged fact's incoming value contains detected PII.\n *\n * - `\"redact\"` (default): the fact is rewritten with redacted text (e.g.\n * `\"[SSN]\"`) via a follow-up store write. The system briefly observes\n * the raw value during the same microtask the publish landed in, then\n * the redacted value overwrites it before any reconcile / agent runs.\n * Safe shipping posture for production: the LLM call always sees the\n * redacted value.\n * - `\"alert\"`: fire `onBlocked` but DO NOT mutate the fact. The raw value\n * stays in the store. Use this for monitoring-only deployments where\n * the source's transport is already trusted but a regression detector\n * is needed (paging ops on every match).\n *\n * Note: Directive plugin hooks (`onFactSet`, `onFactsBatch`) are\n * wrapped by the plugin manager's `safeCall` so a throw from inside the\n * hook is swallowed. The guardrail therefore cannot reject the write\n * itself — it can only observe + redact-via-followup-write or alert.\n * For hard rejection at the publish boundary, a future RFC will add a\n * pre-commit transform hook on the source primitive.\n */\nexport type FactPIIGuardrailMode = \"redact\" | \"alert\";\n\nexport interface FactPIIGuardrailOptions {\n /** Default: `\"redact\"` */\n mode?: FactPIIGuardrailMode;\n /**\n * Built-in categories to scan for. Default: all three (`ssn`,\n * `credit_card`, `email`). Pass `[]` to opt out of the built-ins and\n * rely entirely on `customDetector`.\n */\n types?: readonly FactPIICategory[];\n /**\n * Specific fact keys to scan in addition to the auto-detected\n * `pii`-tagged set. Useful when a consumer can't change the schema's\n * meta but knows the key should be screened.\n */\n includeKeys?: readonly string[];\n /**\n * Exclude these fact keys even if they're pii-tagged. Escape hatch for\n * a key that's already pre-sanitized upstream of the manager.\n */\n excludeKeys?: readonly string[];\n /**\n * Called whenever the guardrail detects PII and acts on it. Receives the\n * fact key, the detected matches, and the action that was taken. Fires\n * AFTER redact + before any throw in `reject` mode. Use this to alert\n * SREs without coupling the guardrail to a specific logging backend.\n */\n onBlocked?: (\n key: string,\n detected: readonly FactPIIMatch[],\n action: FactPIIGuardrailMode,\n ) => void;\n /**\n * Custom synchronous detector that runs alongside the built-in regex\n * scanner. The union of detections is acted on. Useful when the\n * consumer ships a domain-specific PII detector (e.g. internal\n * account-number format). MUST be synchronous — `onFactSet` cannot\n * await deferred work.\n */\n customDetector?: (text: string) => readonly FactPIIMatch[];\n /**\n * Maximum nesting depth to walk when scanning a structured fact\n * value. Default `1` — the scanner inspects top-level strings, then\n * descends one level into the object/array. Arrays and plain objects\n * count as one depth level each. Maps and Sets are still NOT walked\n * by the built-in scanner; PII inside those structures must go\n * through a `customDetector`.\n *\n * Per R13-C6 the walker recurses into arrays (Supabase realtime\n * payloads ship as `payload.new = [{...}]`, MCP resource lists ship\n * as arrays — those shapes silently bypassed the Tier 0 guard before).\n *\n * Consumers with deeply-nested PII shapes have two options:\n * 1. Pass `walkDepth: 2` (or higher) — the scanner walks plain\n * objects and arrays to that depth. Maps and Sets are still\n * skipped.\n * 2. Pass a `customDetector` that walks the consumer-specific shape\n * and returns concrete matches — the right answer for\n * domain-specific structures (Maps, Sets, getters, Symbol keys).\n *\n * Maximum is `5` to prevent pathological recursion on cyclic\n * structures. Passing anything higher clamps to `5`.\n *\n * Property iteration uses `Object.entries`, which skips\n * Symbol-keyed properties and non-enumerable string keys. If you\n * store PII under a Symbol key (unusual), a `customDetector` is the\n * right escape hatch.\n */\n walkDepth?: number;\n}\n\n// ============================================================================\n// Plugin factory\n// ============================================================================\n\ninterface MetaCapableSystem {\n meta?: {\n byTag?: (tag: string) => Array<{ type?: string; id?: string }>;\n };\n facts?: {\n $store?: {\n set?: (k: string, v: unknown) => void;\n };\n };\n}\n\n/**\n * Create a Directive plugin that scans pii-tagged fact writes for PII and\n * redacts or rejects them at the manager boundary.\n *\n * Wire it once at `createSystem({ plugins: [...] })`. The plugin caches\n * the pii-tagged key set on `onInit` so per-write hooks are O(1) lookups.\n *\n * @returns a `Plugin` instance ready to add to `SystemConfig.plugins`.\n */\nexport function createFactPIIGuardrail(\n options: FactPIIGuardrailOptions = {},\n): Plugin {\n const {\n mode = \"redact\",\n types = [\"ssn\", \"credit_card\", \"email\"] as const,\n includeKeys = [],\n excludeKeys = [],\n onBlocked,\n customDetector,\n walkDepth = 1,\n } = options;\n\n const typeSet = new Set<FactPIICategory>(types);\n const screenedKeys = new Set<string>(includeKeys);\n const excludedSet = new Set(excludeKeys);\n // Clamp walkDepth to [1, 5]. Lower bound prevents accidental no-op\n // scans (`walkDepth: 0` would skip even top-level string members);\n // upper bound caps pathological recursion on cyclic structures.\n const effectiveWalkDepth = Math.max(1, Math.min(5, Math.floor(walkDepth)));\n let initialized = false;\n let systemRef: System | null = null;\n\n function initScreenedKeys(system: System): void {\n if (initialized) return;\n initialized = true;\n systemRef = system;\n const piiTagged = (system as unknown as MetaCapableSystem).meta?.byTag?.(\n \"pii\",\n );\n if (!piiTagged) return;\n for (const entry of piiTagged) {\n // MetaMatch shape: { type: \"fact\" | \"module\" | \"event\" | ..., id: string, meta }.\n // We screen FACT-typed matches only — agent prompts read facts, not\n // event / constraint / derivation metadata.\n if (entry.type !== \"fact\") continue;\n if (entry.id && !excludedSet.has(entry.id)) {\n screenedKeys.add(entry.id);\n }\n }\n }\n\n function runScan(text: string): FactPIIMatch[] {\n const all: FactPIIMatch[] = [];\n if (typeSet.size > 0) {\n for (const m of scanText(text, typeSet)) all.push(m);\n }\n if (customDetector) {\n for (const m of customDetector(text)) all.push(m);\n }\n return all;\n }\n\n function inspect(\n value: unknown,\n depth: number = effectiveWalkDepth,\n ):\n | { matched: false }\n | { matched: true; redacted: unknown; detected: FactPIIMatch[] } {\n if (typeof value === \"string\") {\n const detected = runScan(value);\n if (detected.length === 0) return { matched: false };\n return { matched: true, redacted: redactText(value, detected), detected };\n }\n if (depth <= 0) return { matched: false };\n if (Array.isArray(value)) {\n // Walk array elements at the same depth budget — R13 found that\n // real Supabase realtime payloads ship as `payload.new = [{ ... }]`\n // and MCP resource notifications ship as arrays of resources, so\n // skipping arrays silently no-ops the Tier 0 guard on the\n // dominant production ingest shape. Each element is inspected\n // independently; the array is rebuilt only if at least one\n // element matched. Symbol keys, Maps, and Sets are still out of\n // scope (caller must wire a `customDetector` for those).\n let mutatedArr: unknown[] | null = null;\n const all: FactPIIMatch[] = [];\n for (let i = 0; i < value.length; i++) {\n const nested = inspect(value[i], depth);\n if (!nested.matched) continue;\n if (mutatedArr === null) mutatedArr = [...value];\n mutatedArr[i] = nested.redacted;\n for (const d of nested.detected) all.push(d);\n }\n if (mutatedArr === null) return { matched: false };\n return { matched: true, redacted: mutatedArr, detected: all };\n }\n if (value && typeof value === \"object\") {\n // Walk plain objects up to `walkDepth` levels deep so a source\n // publishing a nested PII shape (e.g. `{ profile: { email } }`) is\n // screened when the consumer opts into `walkDepth: 2+`. Maps and\n // Sets are out of scope — pass a `customDetector` for those.\n // Symbol-keyed properties are NOT walked because `Object.entries`\n // skips them (documented in the JSDoc at the top of this file).\n let mutated: Record<string, unknown> | null = null;\n const all: FactPIIMatch[] = [];\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (typeof v === \"string\") {\n const detected = runScan(v);\n if (detected.length === 0) continue;\n if (mutated === null) {\n mutated = { ...(value as Record<string, unknown>) };\n }\n mutated[k] = redactText(v, detected);\n for (const d of detected) all.push(d);\n } else if (depth > 1 && v && typeof v === \"object\") {\n // Includes arrays — recurse and let the array branch above\n // handle the structural walk. Burns one depth level whether\n // the child is an array or another plain object so the\n // configured walkDepth bounds total recursion.\n const nested = inspect(v, depth - 1);\n if (!nested.matched) continue;\n if (mutated === null) {\n mutated = { ...(value as Record<string, unknown>) };\n }\n mutated[k] = nested.redacted;\n for (const d of nested.detected) all.push(d);\n }\n }\n if (mutated === null) return { matched: false };\n return { matched: true, redacted: mutated, detected: all };\n }\n return { matched: false };\n }\n\n return {\n name: \"fact-pii-guardrail\",\n\n onInit(system) {\n initScreenedKeys(system);\n },\n\n onFactSet(key, value, _prev) {\n if (!initialized) return;\n if (!screenedKeys.has(key)) return;\n const result = inspect(value);\n if (!result.matched) return;\n onBlocked?.(key, result.detected, mode);\n if (mode === \"alert\") return;\n // Redact mode: schedule a follow-up store write. `onFactSet` fires\n // post-commit, so the raw value briefly exists in the store; the\n // follow-up write overwrites it before the next reconcile / agent\n // read. Subscribers that snapshot the raw value during the same\n // microtask see it; the LLM call after the next settle does not.\n const facts = (systemRef as unknown as MetaCapableSystem | null)?.facts;\n if (facts?.$store?.set) {\n try {\n facts.$store.set(key, result.redacted);\n } catch {\n // Store rejected (e.g. unknown key, mid-destroy). onBlocked\n // already fired so the consumer has the signal.\n }\n }\n },\n\n onFactsBatch(changes) {\n if (!initialized) return;\n for (const change of changes) {\n if (change.type !== \"set\") continue;\n if (!screenedKeys.has(change.key)) continue;\n const result = inspect(change.value);\n if (!result.matched) continue;\n onBlocked?.(change.key, result.detected, mode);\n if (mode === \"alert\") continue;\n // Best-effort in-place mutation of the change record so post-batch\n // subscribers reading `change.value` see the redacted value\n // immediately. Frozen change records fall through silently.\n try {\n (change as { value: unknown }).value = result.redacted;\n } catch {\n // Frozen change record — fall through.\n }\n // Follow-up store write so the next read of `system.facts.<key>`\n // returns the redacted value too. Required because the batch\n // already committed the raw value at this point.\n const facts = (systemRef as unknown as MetaCapableSystem | null)?.facts;\n if (facts?.$store?.set) {\n try {\n facts.$store.set(change.key, result.redacted);\n } catch {\n /* store may reject mid-destroy; onBlocked already fired */\n }\n }\n }\n },\n };\n}\n"]}