@directive-run/ai 1.17.2 → 1.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-7DPTXZZI.cjs → chunk-7EJN6TYX.cjs} +4 -4
- package/dist/chunk-7EJN6TYX.cjs.map +1 -0
- package/dist/chunk-D72LIBH2.js +16 -0
- package/dist/chunk-D72LIBH2.js.map +1 -0
- package/dist/{chunk-FN4GUZAI.js → chunk-G7CRWJT7.js} +4 -4
- package/dist/chunk-G7CRWJT7.js.map +1 -0
- package/dist/{chunk-56LYSE63.js → chunk-RHJAMXLS.js} +3 -3
- package/dist/{chunk-56LYSE63.js.map → chunk-RHJAMXLS.js.map} +1 -1
- package/dist/chunk-UZKM276C.cjs +16 -0
- package/dist/chunk-UZKM276C.cjs.map +1 -0
- package/dist/{chunk-PB276BX2.cjs → chunk-XGHNOSXT.cjs} +4 -4
- package/dist/{chunk-PB276BX2.cjs.map → chunk-XGHNOSXT.cjs.map} +1 -1
- package/dist/index.cjs +15 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +85 -2
- package/dist/index.d.ts +85 -2
- package/dist/index.js +15 -15
- package/dist/index.js.map +1 -1
- package/dist/multi-agent-orchestrator-OX2TKD5Y.cjs +2 -0
- package/dist/{multi-agent-orchestrator-KFYIDKTF.cjs.map → multi-agent-orchestrator-OX2TKD5Y.cjs.map} +1 -1
- package/dist/{multi-agent-orchestrator-ZHSMWIKP.js → multi-agent-orchestrator-RMTLPKB4.js} +2 -2
- package/dist/{multi-agent-orchestrator-ZHSMWIKP.js.map → multi-agent-orchestrator-RMTLPKB4.js.map} +1 -1
- package/dist/multi-agent.cjs +1 -1
- package/dist/multi-agent.d.cts +2 -2
- package/dist/multi-agent.d.ts +2 -2
- package/dist/multi-agent.js +1 -1
- package/dist/{orchestrator-types-ZK9lv5Sm.d.ts → orchestrator-types-D5cFRt3s.d.ts} +115 -0
- package/dist/{orchestrator-types-CbNE7Rjp.d.cts → orchestrator-types-Dlfcvdxw.d.cts} +115 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-7DPTXZZI.cjs.map +0 -1
- package/dist/chunk-D5APTMCT.cjs +0 -16
- package/dist/chunk-D5APTMCT.cjs.map +0 -1
- package/dist/chunk-FN4GUZAI.js.map +0 -1
- package/dist/chunk-YT4QN3KO.js +0 -16
- package/dist/chunk-YT4QN3KO.js.map +0 -1
- package/dist/multi-agent-orchestrator-KFYIDKTF.cjs +0 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { b as AgentLike, M as Message, o as AdapterHooks, c as AgentRunner, a1 as ApprovalState, a2 as AgentState, m as GuardrailFn, I as InputGuardrailData, R as RunOptions, q as RunResult } from './types-DJ09LjZX.cjs';
|
|
2
2
|
export { a3 as AgentCircuitBreakerConfig, a4 as AgentCompleteEvent, a5 as AgentErrorEvent, a6 as AgentHealthState, w as AgentRetryConfig, a7 as AgentRetryEvent, J as AgentSelectionStrategy, a8 as AgentStartEvent, A as ApprovalRequest, a9 as ApprovalRequestEvent, aa as ApprovalResponseEvent, z as BreakpointConfig, ab as BreakpointContext, ac as BreakpointHitEvent, B as BreakpointModifications, d as BreakpointRequest, ad as BreakpointResumedEvent, ae as BreakpointState, af as BreakpointType, C as Checkpoint, ag as CheckpointContext, ah as CheckpointDiff, ai as CheckpointLocalState, aj as CheckpointProgress, ak as CheckpointRestoreEvent, al as CheckpointSaveEvent, h as CheckpointStore, am as ConstraintEvaluateEvent, a0 as CrossAgentDerivationFn, an as CrossAgentSnapshot, Y as DagCheckpointState, D as DagExecutionContext, j as DagNode, e as DagNodeStatus, ao as DagNodeUpdateEvent, k as DagPattern, X as DebateCheckpointState, ap as DebateRoundEvent, l as DebugEvent, aq as DebugEventBase, g as DebugEventType, ar as DerivationUpdateEvent, as as GoalCheckpointConfig, Q as GoalCheckpointState, at as GoalMetrics, F as GoalNode, E as GoalPattern, L as GoalResult, au as GoalStepMetrics, av as GuardrailCheckEvent, n as GuardrailContext, aw as GuardrailError, ax as GuardrailErrorCode, G as GuardrailResult, ay as GuardrailRetryConfig, u as GuardrailsConfig, az as HandoffCompleteEvent, aA as HandoffStartEvent, H as HealthMonitorConfig, i as InMemoryCheckpointStore, aB as InMemoryCheckpointStoreOptions, aC as MAX_BREAKPOINT_HISTORY, $ as MultiAgentBreakpointType, aD as MultiAgentCheckpointLocalState, Z as MultiAgentLifecycleHooks, _ as MultiAgentSelfHealingConfig, N as NamedGuardrail, s as OrchestratorConstraint, v as OrchestratorDebugConfig, x as OrchestratorLifecycleHooks, t as OrchestratorResolver, aE as OrchestratorResolverContext, r as OrchestratorState, O as OutputGuardrailData, aF as PatternCheckpointBase, P as PatternCheckpointConfig, aG as PatternCheckpointState, aH as PatternCompleteEvent, aI as PatternStartEvent, aJ as RaceCancelledEvent, aK as RaceStartEvent, aL as RaceWinnerEvent, W as ReflectCheckpointState, aM as ReflectionIterationEvent, aN as RejectedRequest, aO as RelaxationContext, aP as RelaxationRecord, aQ as RelaxationStrategy, K as RelaxationTier, aR as RerouteDebugEvent, f as RerouteEvent, aS as ResolverCompleteEvent, aT as ResolverErrorEvent, aU as ResolverStartEvent, aV as SchemaValidationResult, aW as SchemaValidator, S as Scratchpad, aX as ScratchpadUpdateEvent, y as SelfHealingConfig, U as SequentialCheckpointState, aY as SingleAgentCheckpointLocalState, p as StreamingCallbackRunner, V as SupervisorCheckpointState, aZ as TaskCompleteEvent, a_ as TaskErrorEvent, a$ as TaskProgressEvent, b0 as TaskStartEvent, b1 as TokenUsage, a as ToolCall, T as ToolCallGuardrailData, b2 as createBreakpointId, b3 as createCheckpointId, b4 as createInitialBreakpointState, b5 as isGuardrailError, b6 as matchBreakpoint, b7 as validateCheckpoint } from './types-DJ09LjZX.cjs';
|
|
3
|
-
export { c as AgentMemory, d as AgentMemoryConfig, A as AgentOrchestrator, e as AgentRegistration, f as AgentRegistry, B as BackpressureStrategy, D as DebatePattern, g as DebateResult, h as DoneChunk, E as ErrorChunk, i as ExecutionPattern, G as GuardrailTriggeredChunk, H as HandoffRequest, j as HandoffResult, k as MemoryManageResult, l as MemoryState, m as MemoryStrategy, n as MemoryStrategyConfig, o as MemoryStrategyResult, p as MergedTaggedStreamResult, q as MessageChunk, r as MessageSummarizer, M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, s as MultiAgentRunCallOptions, t as MultiAgentState, b as MultiplexedStreamChunk, u as MultiplexedStreamResult, O as OrchestratorOptions, v as OrchestratorStreamChunk, w as OrchestratorStreamResult, P as ParallelPattern, x as ProgressChunk, y as RacePattern, z as RaceResult, C as RaceSuccessEntry, F as ReflectIterationRecord, I as ReflectPattern, J as ReflectionConfig, K as ReflectionContext, L as ReflectionEvaluation, R as ReflectionEvaluator, N as ReflectionExhaustedError, Q as RunAgentRequirement, S as RunCallOptions, U as SafeParseResult, V as SafeParseable, W as SequentialPattern, X as StreamChunk, Y as StreamRunOptions, Z as StreamRunner, _ as StreamingGuardrail, $ as StreamingGuardrailResult, a0 as StreamingRunResult, a1 as StructuredOutputConfig, a2 as StructuredOutputError, a3 as SupervisorPattern, a4 as TaskContext, T as TaskRegistration, a5 as TokenChunk, a6 as ToolEndChunk, a7 as ToolStartChunk, a8 as adaptOutputGuardrail, a9 as collectTokens, aa as combineStreamingGuardrails, ab as createAgentMemory, ac as createAgentOrchestrator, ad as createHybridStrategy, ae as createKeyPointsSummarizer, af as createLLMSummarizer, ag as createLengthStreamingGuardrail, ah as createPatternStreamingGuardrail, ai as createSlidingWindowStrategy, aj as createStreamingRunner, ak as createTokenBasedStrategy, al as createToxicityStreamingGuardrail, am as createTruncationSummarizer, an as extractJsonFromOutput, ao as filterStream, ap as mapStream, aq as mergeTaggedStreams, ar as tapStream, as as withReflection, at as withStructuredOutput } from './orchestrator-types-
|
|
3
|
+
export { c as AgentMemory, d as AgentMemoryConfig, A as AgentOrchestrator, e as AgentRegistration, f as AgentRegistry, B as BackpressureStrategy, D as DebatePattern, g as DebateResult, h as DoneChunk, E as ErrorChunk, i as ExecutionPattern, G as GuardrailTriggeredChunk, H as HandoffRequest, j as HandoffResult, k as MemoryManageResult, l as MemoryState, m as MemoryStrategy, n as MemoryStrategyConfig, o as MemoryStrategyResult, p as MergedTaggedStreamResult, q as MessageChunk, r as MessageSummarizer, M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, s as MultiAgentRunCallOptions, t as MultiAgentState, b as MultiplexedStreamChunk, u as MultiplexedStreamResult, O as OrchestratorOptions, v as OrchestratorStreamChunk, w as OrchestratorStreamResult, P as ParallelPattern, x as ProgressChunk, y as RacePattern, z as RaceResult, C as RaceSuccessEntry, F as ReflectIterationRecord, I as ReflectPattern, J as ReflectionConfig, K as ReflectionContext, L as ReflectionEvaluation, R as ReflectionEvaluator, N as ReflectionExhaustedError, Q as RunAgentRequirement, S as RunCallOptions, U as SafeParseResult, V as SafeParseable, W as SequentialPattern, X as StreamChunk, Y as StreamRunOptions, Z as StreamRunner, _ as StreamingGuardrail, $ as StreamingGuardrailResult, a0 as StreamingRunResult, a1 as StructuredOutputConfig, a2 as StructuredOutputError, a3 as SupervisorPattern, a4 as TaskContext, T as TaskRegistration, a5 as TokenChunk, a6 as ToolEndChunk, a7 as ToolStartChunk, a8 as adaptOutputGuardrail, a9 as collectTokens, aa as combineStreamingGuardrails, ab as createAgentMemory, ac as createAgentOrchestrator, ad as createHybridStrategy, ae as createKeyPointsSummarizer, af as createLLMSummarizer, ag as createLengthStreamingGuardrail, ah as createPatternStreamingGuardrail, ai as createSlidingWindowStrategy, aj as createStreamingRunner, ak as createTokenBasedStrategy, al as createToxicityStreamingGuardrail, am as createTruncationSummarizer, an as extractJsonFromOutput, ao as filterStream, ap as mapStream, aq as mergeTaggedStreams, ar as tapStream, as as withReflection, at as withStructuredOutput } from './orchestrator-types-Dlfcvdxw.cjs';
|
|
4
4
|
import { PIIType, RedactionStyle } from './guardrails.cjs';
|
|
5
5
|
export { ANNIndex, ANNSearchResult, DEFAULT_INJECTION_PATTERNS, DetectedPII, EnhancedPIIGuardrailOptions, InjectionDetectionResult, PIIDetectionResult, PIIDetector, PromptInjectionGuardrailOptions, RateLimitGuardrail, STRICT_INJECTION_PATTERNS, VPTreeIndexConfig, createBruteForceIndex, createContentFilterGuardrail, createEnhancedPIIGuardrail, createLengthGuardrail, createModerationGuardrail, createOutputPIIGuardrail, createOutputSchemaGuardrail, createOutputTypeGuardrail, createPIIGuardrail, createPromptInjectionGuardrail, createRateLimitGuardrail, createToolGuardrail, createUntrustedContentGuardrail, createVPTreeIndex, detectAndRedactPII, detectPII, detectPromptInjection, markUntrustedContent, redactPII, sanitizeInjection } from './guardrails.cjs';
|
|
6
6
|
export { AgentInfo, AgentMessage, AgentMessageType, AgentNetwork, AgentNetworkConfig, DebateConfig, DelegationMessage, DelegationResultMessage, GoalAgentDeclaration, GoalDependencyEdge, GoalDependencyGraph, GoalExecutionPlan, GoalExplanation, GoalExplanationStep, GoalPlanStep, GoalValidationResult, InformMessage, MermaidDirection, MermaidNodeShapes, MermaidOptions, MessageBus, MessageBusConfig, MessageFilter, MessageHandler, QueryMessage, RequestMessage, ResponseMessage, Semaphore, SerializedDagNode, SerializedGoalNode, SerializedPattern, SpawnOnConditionOptions, SpawnPoolConfig, Subscription, TypedAgentMessage, UpdateMessage, aggregateTokens, allReadyStrategy, capabilityRoute, collectOutputs, composePatterns, concatResults, costEfficientStrategy, createAgentNetwork, createDelegator, createMessageBus, createMultiAgentOrchestrator, createPubSub, createResponder, dag, debate, derivedConstraint, diffCheckpoints, explainGoal, findAgentsByCapability, forkFromCheckpoint, getCheckpointProgress, getDependencyGraph, getPatternStep, goal, highestImpactStrategy, parallel, patternFromJSON, patternToJSON, patternToMermaid, pickBestResult, planGoal, race, reflect, runAgentRequirement, runDebate, selectAgent, sequential, spawnOnCondition, spawnPool, supervisor, validateGoal } from './multi-agent.cjs';
|
|
@@ -1806,4 +1806,87 @@ interface OtelPlugin {
|
|
|
1806
1806
|
*/
|
|
1807
1807
|
declare function createOtelPlugin(config: OtelPluginConfig): OtelPlugin;
|
|
1808
1808
|
|
|
1809
|
-
|
|
1809
|
+
/**
|
|
1810
|
+
* OTel × Sources — emit source-lifecycle spans from `system.observe()`
|
|
1811
|
+
*
|
|
1812
|
+
* The R5 observability reviewer found `@directive-run/ai/otel.ts`
|
|
1813
|
+
* subscribes only to the AI `DebugTimeline` event stream — so the four
|
|
1814
|
+
* `ObservationEvent.source.*` variants (`source.attach`,
|
|
1815
|
+
* `source.publish`, `source.detach`, `source.error`) shipped by the
|
|
1816
|
+
* source primitive never reach the OTel exporter. SREs running with
|
|
1817
|
+
* `createOtelPlugin` see agent spans but cannot answer "which source
|
|
1818
|
+
* is publishing?" or "did source `mcp` error attach?" from their
|
|
1819
|
+
* tracing backend.
|
|
1820
|
+
*
|
|
1821
|
+
* This module closes the gap as a focused helper (NOT a second OTel
|
|
1822
|
+
* plugin) so a single `OtelTracer` can carry both AI and core source
|
|
1823
|
+
* spans. Wire it once at `createSystem` time:
|
|
1824
|
+
*
|
|
1825
|
+
* @example Wire source events into the same OTel tracer as the AI plugin
|
|
1826
|
+
* ```ts
|
|
1827
|
+
* import { trace } from "@opentelemetry/api";
|
|
1828
|
+
* import { createSystem } from "@directive-run/core";
|
|
1829
|
+
* import { createOtelPlugin, attachSourcesToOtel } from "@directive-run/ai";
|
|
1830
|
+
*
|
|
1831
|
+
* const tracer = trace.getTracer("directive-app");
|
|
1832
|
+
* const otel = createOtelPlugin({ serviceName: "my-app", tracer });
|
|
1833
|
+
*
|
|
1834
|
+
* const system = createSystem({ module });
|
|
1835
|
+
* otel.attach(orchestrator.timeline); // existing AI wiring
|
|
1836
|
+
* const unsub = attachSourcesToOtel(system, { // NEW — source.* spans
|
|
1837
|
+
* tracer,
|
|
1838
|
+
* serviceName: "my-app",
|
|
1839
|
+
* });
|
|
1840
|
+
*
|
|
1841
|
+
* system.start();
|
|
1842
|
+
*
|
|
1843
|
+
* // Later
|
|
1844
|
+
* unsub();
|
|
1845
|
+
* ```
|
|
1846
|
+
*
|
|
1847
|
+
* Spans emitted:
|
|
1848
|
+
*
|
|
1849
|
+
* - `directive.source.attach` — short-duration (start → end same tick)
|
|
1850
|
+
* span with attributes `source.id`, `source.module_id`, plus
|
|
1851
|
+
* `attached_at` timestamp.
|
|
1852
|
+
* - `directive.source.publish` — short-duration counter span (NOT a
|
|
1853
|
+
* per-publish full span; events of this kind are emitted as
|
|
1854
|
+
* span EVENTS on a long-lived per-source "active" span so cardinality
|
|
1855
|
+
* stays bounded).
|
|
1856
|
+
* - `directive.source.detach` — short-duration span, ends the matching
|
|
1857
|
+
* "active" parent.
|
|
1858
|
+
* - `directive.source.error` — error-status span carrying the phase
|
|
1859
|
+
* (`attach`/`cleanup`/`runtime` per RFC 0008) and the truncated
|
|
1860
|
+
* message from R6/R7.
|
|
1861
|
+
*
|
|
1862
|
+
* Cardinality budget: ONE active span per (sourceId, moduleId) at a
|
|
1863
|
+
* time. Publishes attach as span events (cheap), not as new spans. At
|
|
1864
|
+
* 10 sources × 100 publishes/sec the exporter sees 1000 events/sec on
|
|
1865
|
+
* 10 long-lived spans — well within typical OTel collector budgets.
|
|
1866
|
+
*/
|
|
1867
|
+
|
|
1868
|
+
interface SourcesOtelOptions {
|
|
1869
|
+
/** Tracer to emit spans through. */
|
|
1870
|
+
tracer: OtelTracer;
|
|
1871
|
+
/** Service name attribute for every span. */
|
|
1872
|
+
serviceName: string;
|
|
1873
|
+
/** Span name prefix. Default: `"directive.source"`. */
|
|
1874
|
+
spanPrefix?: string;
|
|
1875
|
+
/**
|
|
1876
|
+
* Optional sampling for publish events. Sources at very high publish
|
|
1877
|
+
* rate (price ticks, cursor moves) may want to drop most publish
|
|
1878
|
+
* events from the trace. Default: `1.0` (every publish recorded as
|
|
1879
|
+
* an event on the active span).
|
|
1880
|
+
*/
|
|
1881
|
+
publishSampleRate?: number;
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Subscribe to a system's source-lifecycle events and emit OTel spans
|
|
1885
|
+
* for each. Returns an unsubscribe to detach.
|
|
1886
|
+
*
|
|
1887
|
+
* @returns a function that detaches the OTel wiring without affecting
|
|
1888
|
+
* other observers.
|
|
1889
|
+
*/
|
|
1890
|
+
declare function attachSourcesToOtel(system: unknown, options: SourcesOtelOptions): () => void;
|
|
1891
|
+
|
|
1892
|
+
export { AdapterHooks, AgentLike, AgentRunner, AgentState, AllProvidersFailedError, ApprovalState, type AuditEventType, type AuditInstance, type AuditPluginConfig, type BatchQueue, type BatchQueueConfig, type BidirectionalStream, type BudgetConfig, type BudgetExceededDetails, BudgetExceededError, type BudgetRunner, type BudgetWindow, type ComplianceConfig, type ComplianceInstance, type ComplianceStorage, type ConstraintRouterConfig, type ConstraintRouterRunner, type CreateRunnerOptions, DebugTimeline, EmbedderFn, Embedding, type FallbackConfig, GuardrailFn, InputGuardrailData, type JSONFileStoreOptions, Message, type ModelRule, type ModelSelectionConfig, type OtelPlugin, type OtelPluginConfig, type OtelSpan, OtelStatusCode, type OtelTracer, PIIType, type ParsedResponse, type ProviderStats, type RAGChunk, type RAGEnrichOptions, type RAGEnricher, type RAGEnricherConfig, type RAGStorage, RedactionStyle, type RetryConfig, RetryExhaustedError, type RoutingConstraint, type RoutingFacts, type RoutingProvider, RunOptions, RunResult, type RunnerMiddleware, type SSEEvent, type SSETransport, type SSETransportConfig, type SourcesOtelOptions, type SpanData, type StreamChannel, type StreamChannelConfig, type StreamChannelState, type TokenPricing, attachSourcesToOtel, byAgentName, byInputLength, byPattern, createAgentAuditHandlers, createAuditTrail, createBatchQueue, createBidirectionalStream, createCompliance, createConstraintRouter, createInMemoryComplianceStorage, createJSONFileStore, createOtelPlugin, createRAGEnricher, createRunner, createSSETransport, createStreamChannel, estimateCost, formatSystemMeta, hasPendingApprovals, isAgentRunning, mergeStreams, parseHttpStatus, parseRetryAfter, pipe, pipeThrough, toAIContext, validateBaseURL, withBudget, withFallback, withModelSelection, withRetry };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { b as AgentLike, M as Message, o as AdapterHooks, c as AgentRunner, a1 as ApprovalState, a2 as AgentState, m as GuardrailFn, I as InputGuardrailData, R as RunOptions, q as RunResult } from './types-DJ09LjZX.js';
|
|
2
2
|
export { a3 as AgentCircuitBreakerConfig, a4 as AgentCompleteEvent, a5 as AgentErrorEvent, a6 as AgentHealthState, w as AgentRetryConfig, a7 as AgentRetryEvent, J as AgentSelectionStrategy, a8 as AgentStartEvent, A as ApprovalRequest, a9 as ApprovalRequestEvent, aa as ApprovalResponseEvent, z as BreakpointConfig, ab as BreakpointContext, ac as BreakpointHitEvent, B as BreakpointModifications, d as BreakpointRequest, ad as BreakpointResumedEvent, ae as BreakpointState, af as BreakpointType, C as Checkpoint, ag as CheckpointContext, ah as CheckpointDiff, ai as CheckpointLocalState, aj as CheckpointProgress, ak as CheckpointRestoreEvent, al as CheckpointSaveEvent, h as CheckpointStore, am as ConstraintEvaluateEvent, a0 as CrossAgentDerivationFn, an as CrossAgentSnapshot, Y as DagCheckpointState, D as DagExecutionContext, j as DagNode, e as DagNodeStatus, ao as DagNodeUpdateEvent, k as DagPattern, X as DebateCheckpointState, ap as DebateRoundEvent, l as DebugEvent, aq as DebugEventBase, g as DebugEventType, ar as DerivationUpdateEvent, as as GoalCheckpointConfig, Q as GoalCheckpointState, at as GoalMetrics, F as GoalNode, E as GoalPattern, L as GoalResult, au as GoalStepMetrics, av as GuardrailCheckEvent, n as GuardrailContext, aw as GuardrailError, ax as GuardrailErrorCode, G as GuardrailResult, ay as GuardrailRetryConfig, u as GuardrailsConfig, az as HandoffCompleteEvent, aA as HandoffStartEvent, H as HealthMonitorConfig, i as InMemoryCheckpointStore, aB as InMemoryCheckpointStoreOptions, aC as MAX_BREAKPOINT_HISTORY, $ as MultiAgentBreakpointType, aD as MultiAgentCheckpointLocalState, Z as MultiAgentLifecycleHooks, _ as MultiAgentSelfHealingConfig, N as NamedGuardrail, s as OrchestratorConstraint, v as OrchestratorDebugConfig, x as OrchestratorLifecycleHooks, t as OrchestratorResolver, aE as OrchestratorResolverContext, r as OrchestratorState, O as OutputGuardrailData, aF as PatternCheckpointBase, P as PatternCheckpointConfig, aG as PatternCheckpointState, aH as PatternCompleteEvent, aI as PatternStartEvent, aJ as RaceCancelledEvent, aK as RaceStartEvent, aL as RaceWinnerEvent, W as ReflectCheckpointState, aM as ReflectionIterationEvent, aN as RejectedRequest, aO as RelaxationContext, aP as RelaxationRecord, aQ as RelaxationStrategy, K as RelaxationTier, aR as RerouteDebugEvent, f as RerouteEvent, aS as ResolverCompleteEvent, aT as ResolverErrorEvent, aU as ResolverStartEvent, aV as SchemaValidationResult, aW as SchemaValidator, S as Scratchpad, aX as ScratchpadUpdateEvent, y as SelfHealingConfig, U as SequentialCheckpointState, aY as SingleAgentCheckpointLocalState, p as StreamingCallbackRunner, V as SupervisorCheckpointState, aZ as TaskCompleteEvent, a_ as TaskErrorEvent, a$ as TaskProgressEvent, b0 as TaskStartEvent, b1 as TokenUsage, a as ToolCall, T as ToolCallGuardrailData, b2 as createBreakpointId, b3 as createCheckpointId, b4 as createInitialBreakpointState, b5 as isGuardrailError, b6 as matchBreakpoint, b7 as validateCheckpoint } from './types-DJ09LjZX.js';
|
|
3
|
-
export { c as AgentMemory, d as AgentMemoryConfig, A as AgentOrchestrator, e as AgentRegistration, f as AgentRegistry, B as BackpressureStrategy, D as DebatePattern, g as DebateResult, h as DoneChunk, E as ErrorChunk, i as ExecutionPattern, G as GuardrailTriggeredChunk, H as HandoffRequest, j as HandoffResult, k as MemoryManageResult, l as MemoryState, m as MemoryStrategy, n as MemoryStrategyConfig, o as MemoryStrategyResult, p as MergedTaggedStreamResult, q as MessageChunk, r as MessageSummarizer, M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, s as MultiAgentRunCallOptions, t as MultiAgentState, b as MultiplexedStreamChunk, u as MultiplexedStreamResult, O as OrchestratorOptions, v as OrchestratorStreamChunk, w as OrchestratorStreamResult, P as ParallelPattern, x as ProgressChunk, y as RacePattern, z as RaceResult, C as RaceSuccessEntry, F as ReflectIterationRecord, I as ReflectPattern, J as ReflectionConfig, K as ReflectionContext, L as ReflectionEvaluation, R as ReflectionEvaluator, N as ReflectionExhaustedError, Q as RunAgentRequirement, S as RunCallOptions, U as SafeParseResult, V as SafeParseable, W as SequentialPattern, X as StreamChunk, Y as StreamRunOptions, Z as StreamRunner, _ as StreamingGuardrail, $ as StreamingGuardrailResult, a0 as StreamingRunResult, a1 as StructuredOutputConfig, a2 as StructuredOutputError, a3 as SupervisorPattern, a4 as TaskContext, T as TaskRegistration, a5 as TokenChunk, a6 as ToolEndChunk, a7 as ToolStartChunk, a8 as adaptOutputGuardrail, a9 as collectTokens, aa as combineStreamingGuardrails, ab as createAgentMemory, ac as createAgentOrchestrator, ad as createHybridStrategy, ae as createKeyPointsSummarizer, af as createLLMSummarizer, ag as createLengthStreamingGuardrail, ah as createPatternStreamingGuardrail, ai as createSlidingWindowStrategy, aj as createStreamingRunner, ak as createTokenBasedStrategy, al as createToxicityStreamingGuardrail, am as createTruncationSummarizer, an as extractJsonFromOutput, ao as filterStream, ap as mapStream, aq as mergeTaggedStreams, ar as tapStream, as as withReflection, at as withStructuredOutput } from './orchestrator-types-
|
|
3
|
+
export { c as AgentMemory, d as AgentMemoryConfig, A as AgentOrchestrator, e as AgentRegistration, f as AgentRegistry, B as BackpressureStrategy, D as DebatePattern, g as DebateResult, h as DoneChunk, E as ErrorChunk, i as ExecutionPattern, G as GuardrailTriggeredChunk, H as HandoffRequest, j as HandoffResult, k as MemoryManageResult, l as MemoryState, m as MemoryStrategy, n as MemoryStrategyConfig, o as MemoryStrategyResult, p as MergedTaggedStreamResult, q as MessageChunk, r as MessageSummarizer, M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, s as MultiAgentRunCallOptions, t as MultiAgentState, b as MultiplexedStreamChunk, u as MultiplexedStreamResult, O as OrchestratorOptions, v as OrchestratorStreamChunk, w as OrchestratorStreamResult, P as ParallelPattern, x as ProgressChunk, y as RacePattern, z as RaceResult, C as RaceSuccessEntry, F as ReflectIterationRecord, I as ReflectPattern, J as ReflectionConfig, K as ReflectionContext, L as ReflectionEvaluation, R as ReflectionEvaluator, N as ReflectionExhaustedError, Q as RunAgentRequirement, S as RunCallOptions, U as SafeParseResult, V as SafeParseable, W as SequentialPattern, X as StreamChunk, Y as StreamRunOptions, Z as StreamRunner, _ as StreamingGuardrail, $ as StreamingGuardrailResult, a0 as StreamingRunResult, a1 as StructuredOutputConfig, a2 as StructuredOutputError, a3 as SupervisorPattern, a4 as TaskContext, T as TaskRegistration, a5 as TokenChunk, a6 as ToolEndChunk, a7 as ToolStartChunk, a8 as adaptOutputGuardrail, a9 as collectTokens, aa as combineStreamingGuardrails, ab as createAgentMemory, ac as createAgentOrchestrator, ad as createHybridStrategy, ae as createKeyPointsSummarizer, af as createLLMSummarizer, ag as createLengthStreamingGuardrail, ah as createPatternStreamingGuardrail, ai as createSlidingWindowStrategy, aj as createStreamingRunner, ak as createTokenBasedStrategy, al as createToxicityStreamingGuardrail, am as createTruncationSummarizer, an as extractJsonFromOutput, ao as filterStream, ap as mapStream, aq as mergeTaggedStreams, ar as tapStream, as as withReflection, at as withStructuredOutput } from './orchestrator-types-D5cFRt3s.js';
|
|
4
4
|
import { PIIType, RedactionStyle } from './guardrails.js';
|
|
5
5
|
export { ANNIndex, ANNSearchResult, DEFAULT_INJECTION_PATTERNS, DetectedPII, EnhancedPIIGuardrailOptions, InjectionDetectionResult, PIIDetectionResult, PIIDetector, PromptInjectionGuardrailOptions, RateLimitGuardrail, STRICT_INJECTION_PATTERNS, VPTreeIndexConfig, createBruteForceIndex, createContentFilterGuardrail, createEnhancedPIIGuardrail, createLengthGuardrail, createModerationGuardrail, createOutputPIIGuardrail, createOutputSchemaGuardrail, createOutputTypeGuardrail, createPIIGuardrail, createPromptInjectionGuardrail, createRateLimitGuardrail, createToolGuardrail, createUntrustedContentGuardrail, createVPTreeIndex, detectAndRedactPII, detectPII, detectPromptInjection, markUntrustedContent, redactPII, sanitizeInjection } from './guardrails.js';
|
|
6
6
|
export { AgentInfo, AgentMessage, AgentMessageType, AgentNetwork, AgentNetworkConfig, DebateConfig, DelegationMessage, DelegationResultMessage, GoalAgentDeclaration, GoalDependencyEdge, GoalDependencyGraph, GoalExecutionPlan, GoalExplanation, GoalExplanationStep, GoalPlanStep, GoalValidationResult, InformMessage, MermaidDirection, MermaidNodeShapes, MermaidOptions, MessageBus, MessageBusConfig, MessageFilter, MessageHandler, QueryMessage, RequestMessage, ResponseMessage, Semaphore, SerializedDagNode, SerializedGoalNode, SerializedPattern, SpawnOnConditionOptions, SpawnPoolConfig, Subscription, TypedAgentMessage, UpdateMessage, aggregateTokens, allReadyStrategy, capabilityRoute, collectOutputs, composePatterns, concatResults, costEfficientStrategy, createAgentNetwork, createDelegator, createMessageBus, createMultiAgentOrchestrator, createPubSub, createResponder, dag, debate, derivedConstraint, diffCheckpoints, explainGoal, findAgentsByCapability, forkFromCheckpoint, getCheckpointProgress, getDependencyGraph, getPatternStep, goal, highestImpactStrategy, parallel, patternFromJSON, patternToJSON, patternToMermaid, pickBestResult, planGoal, race, reflect, runAgentRequirement, runDebate, selectAgent, sequential, spawnOnCondition, spawnPool, supervisor, validateGoal } from './multi-agent.js';
|
|
@@ -1806,4 +1806,87 @@ interface OtelPlugin {
|
|
|
1806
1806
|
*/
|
|
1807
1807
|
declare function createOtelPlugin(config: OtelPluginConfig): OtelPlugin;
|
|
1808
1808
|
|
|
1809
|
-
|
|
1809
|
+
/**
|
|
1810
|
+
* OTel × Sources — emit source-lifecycle spans from `system.observe()`
|
|
1811
|
+
*
|
|
1812
|
+
* The R5 observability reviewer found `@directive-run/ai/otel.ts`
|
|
1813
|
+
* subscribes only to the AI `DebugTimeline` event stream — so the four
|
|
1814
|
+
* `ObservationEvent.source.*` variants (`source.attach`,
|
|
1815
|
+
* `source.publish`, `source.detach`, `source.error`) shipped by the
|
|
1816
|
+
* source primitive never reach the OTel exporter. SREs running with
|
|
1817
|
+
* `createOtelPlugin` see agent spans but cannot answer "which source
|
|
1818
|
+
* is publishing?" or "did source `mcp` error attach?" from their
|
|
1819
|
+
* tracing backend.
|
|
1820
|
+
*
|
|
1821
|
+
* This module closes the gap as a focused helper (NOT a second OTel
|
|
1822
|
+
* plugin) so a single `OtelTracer` can carry both AI and core source
|
|
1823
|
+
* spans. Wire it once at `createSystem` time:
|
|
1824
|
+
*
|
|
1825
|
+
* @example Wire source events into the same OTel tracer as the AI plugin
|
|
1826
|
+
* ```ts
|
|
1827
|
+
* import { trace } from "@opentelemetry/api";
|
|
1828
|
+
* import { createSystem } from "@directive-run/core";
|
|
1829
|
+
* import { createOtelPlugin, attachSourcesToOtel } from "@directive-run/ai";
|
|
1830
|
+
*
|
|
1831
|
+
* const tracer = trace.getTracer("directive-app");
|
|
1832
|
+
* const otel = createOtelPlugin({ serviceName: "my-app", tracer });
|
|
1833
|
+
*
|
|
1834
|
+
* const system = createSystem({ module });
|
|
1835
|
+
* otel.attach(orchestrator.timeline); // existing AI wiring
|
|
1836
|
+
* const unsub = attachSourcesToOtel(system, { // NEW — source.* spans
|
|
1837
|
+
* tracer,
|
|
1838
|
+
* serviceName: "my-app",
|
|
1839
|
+
* });
|
|
1840
|
+
*
|
|
1841
|
+
* system.start();
|
|
1842
|
+
*
|
|
1843
|
+
* // Later
|
|
1844
|
+
* unsub();
|
|
1845
|
+
* ```
|
|
1846
|
+
*
|
|
1847
|
+
* Spans emitted:
|
|
1848
|
+
*
|
|
1849
|
+
* - `directive.source.attach` — short-duration (start → end same tick)
|
|
1850
|
+
* span with attributes `source.id`, `source.module_id`, plus
|
|
1851
|
+
* `attached_at` timestamp.
|
|
1852
|
+
* - `directive.source.publish` — short-duration counter span (NOT a
|
|
1853
|
+
* per-publish full span; events of this kind are emitted as
|
|
1854
|
+
* span EVENTS on a long-lived per-source "active" span so cardinality
|
|
1855
|
+
* stays bounded).
|
|
1856
|
+
* - `directive.source.detach` — short-duration span, ends the matching
|
|
1857
|
+
* "active" parent.
|
|
1858
|
+
* - `directive.source.error` — error-status span carrying the phase
|
|
1859
|
+
* (`attach`/`cleanup`/`runtime` per RFC 0008) and the truncated
|
|
1860
|
+
* message from R6/R7.
|
|
1861
|
+
*
|
|
1862
|
+
* Cardinality budget: ONE active span per (sourceId, moduleId) at a
|
|
1863
|
+
* time. Publishes attach as span events (cheap), not as new spans. At
|
|
1864
|
+
* 10 sources × 100 publishes/sec the exporter sees 1000 events/sec on
|
|
1865
|
+
* 10 long-lived spans — well within typical OTel collector budgets.
|
|
1866
|
+
*/
|
|
1867
|
+
|
|
1868
|
+
interface SourcesOtelOptions {
|
|
1869
|
+
/** Tracer to emit spans through. */
|
|
1870
|
+
tracer: OtelTracer;
|
|
1871
|
+
/** Service name attribute for every span. */
|
|
1872
|
+
serviceName: string;
|
|
1873
|
+
/** Span name prefix. Default: `"directive.source"`. */
|
|
1874
|
+
spanPrefix?: string;
|
|
1875
|
+
/**
|
|
1876
|
+
* Optional sampling for publish events. Sources at very high publish
|
|
1877
|
+
* rate (price ticks, cursor moves) may want to drop most publish
|
|
1878
|
+
* events from the trace. Default: `1.0` (every publish recorded as
|
|
1879
|
+
* an event on the active span).
|
|
1880
|
+
*/
|
|
1881
|
+
publishSampleRate?: number;
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Subscribe to a system's source-lifecycle events and emit OTel spans
|
|
1885
|
+
* for each. Returns an unsubscribe to detach.
|
|
1886
|
+
*
|
|
1887
|
+
* @returns a function that detaches the OTel wiring without affecting
|
|
1888
|
+
* other observers.
|
|
1889
|
+
*/
|
|
1890
|
+
declare function attachSourcesToOtel(system: unknown, options: SourcesOtelOptions): () => void;
|
|
1891
|
+
|
|
1892
|
+
export { AdapterHooks, AgentLike, AgentRunner, AgentState, AllProvidersFailedError, ApprovalState, type AuditEventType, type AuditInstance, type AuditPluginConfig, type BatchQueue, type BatchQueueConfig, type BidirectionalStream, type BudgetConfig, type BudgetExceededDetails, BudgetExceededError, type BudgetRunner, type BudgetWindow, type ComplianceConfig, type ComplianceInstance, type ComplianceStorage, type ConstraintRouterConfig, type ConstraintRouterRunner, type CreateRunnerOptions, DebugTimeline, EmbedderFn, Embedding, type FallbackConfig, GuardrailFn, InputGuardrailData, type JSONFileStoreOptions, Message, type ModelRule, type ModelSelectionConfig, type OtelPlugin, type OtelPluginConfig, type OtelSpan, OtelStatusCode, type OtelTracer, PIIType, type ParsedResponse, type ProviderStats, type RAGChunk, type RAGEnrichOptions, type RAGEnricher, type RAGEnricherConfig, type RAGStorage, RedactionStyle, type RetryConfig, RetryExhaustedError, type RoutingConstraint, type RoutingFacts, type RoutingProvider, RunOptions, RunResult, type RunnerMiddleware, type SSEEvent, type SSETransport, type SSETransportConfig, type SourcesOtelOptions, type SpanData, type StreamChannel, type StreamChannelConfig, type StreamChannelState, type TokenPricing, attachSourcesToOtel, byAgentName, byInputLength, byPattern, createAgentAuditHandlers, createAuditTrail, createBatchQueue, createBidirectionalStream, createCompliance, createConstraintRouter, createInMemoryComplianceStorage, createJSONFileStore, createOtelPlugin, createRAGEnricher, createRunner, createSSETransport, createStreamChannel, estimateCost, formatSystemMeta, hasPendingApprovals, isAgentRunning, mergeStreams, parseHttpStatus, parseRetryAfter, pipe, pipeThrough, toAIContext, validateBaseURL, withBudget, withFallback, withModelSelection, withRetry };
|
package/dist/index.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
import {u,l,i}from'./chunk-BFSRYCOS.js';export{n as DEFAULT_INJECTION_PATTERNS,o as STRICT_INJECTION_PATTERNS,z as createBatchedEmbedder,A as createBruteForceIndex,h as createContentFilterGuardrail,j as createEnhancedPIIGuardrail,v as createInMemoryStorage,g as createLengthGuardrail,b as createModerationGuardrail,k as createOutputPIIGuardrail,e as createOutputSchemaGuardrail,f as createOutputTypeGuardrail,a as createPIIGuardrail,r as createPromptInjectionGuardrail,c as createRateLimitGuardrail,w as createSemanticCache,x as createSemanticCacheGuardrail,y as createTestEmbedder,d as createToolGuardrail,t as createUntrustedContentGuardrail,B as createVPTreeIndex,m as detectAndRedactPII,l as detectPII,p as detectPromptInjection,s as markUntrustedContent,i as redactPII,q as sanitizeInjection}from'./chunk-BFSRYCOS.js';export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-5JQ2A3JK.js';export{k as createEvalSuite,l as evalAssert,j as evalCoherence,a as evalCost,h as evalFaithfulness,f as evalJudge,b as evalLatency,g as evalMatch,c as evalOutputLength,i as evalRelevance,d as evalSafety,e as evalStructure}from'./chunk-J2Q5KKPN.js';export{b as convertToolsForLLM,a as createMCPAdapter,c as mcpCallTool,e as mcpGetPrompt,d as mcpReadResource,f as mcpSyncResources}from'./chunk-V2FCPNPP.js';export{a as createAgentOrchestrator}from'./chunk-
|
|
1
|
+
import {u,l,i}from'./chunk-BFSRYCOS.js';export{n as DEFAULT_INJECTION_PATTERNS,o as STRICT_INJECTION_PATTERNS,z as createBatchedEmbedder,A as createBruteForceIndex,h as createContentFilterGuardrail,j as createEnhancedPIIGuardrail,v as createInMemoryStorage,g as createLengthGuardrail,b as createModerationGuardrail,k as createOutputPIIGuardrail,e as createOutputSchemaGuardrail,f as createOutputTypeGuardrail,a as createPIIGuardrail,r as createPromptInjectionGuardrail,c as createRateLimitGuardrail,w as createSemanticCache,x as createSemanticCacheGuardrail,y as createTestEmbedder,d as createToolGuardrail,t as createUntrustedContentGuardrail,B as createVPTreeIndex,m as detectAndRedactPII,l as detectPII,p as detectPromptInjection,s as markUntrustedContent,i as redactPII,q as sanitizeInjection}from'./chunk-BFSRYCOS.js';export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-5JQ2A3JK.js';export{k as createEvalSuite,l as evalAssert,j as evalCoherence,a as evalCost,h as evalFaithfulness,f as evalJudge,b as evalLatency,g as evalMatch,c as evalOutputLength,i as evalRelevance,d as evalSafety,e as evalStructure}from'./chunk-J2Q5KKPN.js';export{b as convertToolsForLLM,a as createMCPAdapter,c as mcpCallTool,e as mcpGetPrompt,d as mcpReadResource,f as mcpSyncResources}from'./chunk-V2FCPNPP.js';export{a as createAgentOrchestrator}from'./chunk-D72LIBH2.js';export{f as createRunner,c as estimateCost,b as hasPendingApprovals,a as isAgentRunning,d as validateBaseURL}from'./chunk-ZFLHWJ56.js';export{c as createAgentNetwork,e as createDelegator,b as createMessageBus,f as createPubSub,d as createResponder,j as explainGoal,g as getDependencyGraph,a as patternToMermaid,i as planGoal,h as validateGoal}from'./chunk-RHJAMXLS.js';export{y as InMemoryCheckpointStore,s as MAX_BREAKPOINT_HISTORY,K as ReflectionExhaustedError,N as Semaphore,E as adaptOutputGuardrail,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,F as collectTokens,D as combineStreamingGuardrails,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,t as createBreakpointId,w as createCheckpointId,v as createInitialBreakpointState,B as createLengthStreamingGuardrail,ra as createMultiAgentOrchestrator,C as createPatternStreamingGuardrail,z as createStreamingRunner,A as createToxicityStreamingGuardrail,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,H as filterStream,ka as findAgentsByCapability,R as forkFromCheckpoint,a as formatSystemMeta,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,I as mapStream,u as matchBreakpoint,J as mergeTaggedStreams,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,ma as spawnOnCondition,qa as spawnPool,V as supervisor,G as tapStream,b as toAIContext,x as validateCheckpoint,L as withReflection}from'./chunk-G7CRWJT7.js';export{a as GuardrailError,b as isGuardrailError}from'./chunk-UR5BMWEN.js';export{a as createDebugTimeline,b as createDebugTimelinePlugin,c as createHealthMonitor}from'./chunk-FBT73WFY.js';export{a as PredicateFromIntentError,b as predicateFromIntent,c as predicateFromIntentRaw,g as predicateFromIntentWithProvenance,f as predicateToolSpec,e as predicateToolSpecAnthropic,d as predicateToolSpecOpenAI}from'./chunk-GTB6HTZV.js';export{c as StructuredOutputError,a as extractJsonFromOutput,b as withStructuredOutput}from'./chunk-HRR45JZX.js';export{CircuitBreakerOpenError,createCircuitBreaker,createOTLPExporter}from'@directive-run/core/plugins';import _ from'path';function Ur(r,...e){let t=r;for(let n of e)t=n(t);return t}function j(r,e){let t=typeof r.content=="string"?r.content:JSON.stringify(r.content);return Math.ceil(t.length/4)}function V(r,e){return r.reduce((t,n)=>t+j(n),0)}function X(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxMessages??100,c=n.preserveRecentCount??5;if(e.length<=s)return {keep:[...e],toSummarize:[],estimatedTokens:V(e)};let o=e.slice(-c),u=e.slice(0,-c),a=Math.max(0,s-c),y=u.slice(-a),p=u.slice(0,-a||void 0),h=[...y,...o];return {keep:h,toSummarize:p.length>0?p:[],estimatedTokens:V(h)}}}function Y(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxTokens??4e3,c=n.preserveRecentCount??5,o=n.countSystemMessages??true,u=e.slice(-c),a=e.slice(0,-c),y=u.reduce((l,g)=>!o&&g.role==="system"?l:l+j(g),0),p=[],h=[],m=y;for(let l=a.length-1;l>=0;l--){let g=a[l],C=!o&&g.role==="system"?0:j(g);if(m+C<=s)p.unshift(g),m+=C;else {h.push(...a.slice(0,l+1));break}}return {keep:[...p,...u],toSummarize:h,estimatedTokens:m}}}function Hr(r={}){let e=X(r),t=Y(r);return (n,s={})=>{let c={...r,...s},o=e(n,c),u=t(n,c);return o.keep.length<=u.keep.length?o:u}}function Vr(r){let{strategy:e,summarizer:t,strategyConfig:n={},autoManage:s=false,onMemoryManaged:c,onManageError:o,maxContextTokens:u}=r,a={messages:[],summaries:[],totalMessagesProcessed:0,estimatedTokens:0},y=false;async function p(){if(y)return {messagesBefore:a.messages.length,messagesAfter:a.messages.length,messagesSummarized:0,estimatedTokensBefore:a.estimatedTokens,estimatedTokensAfter:a.estimatedTokens};y=true;try{let m=a.messages.length,l=a.estimatedTokens,g=e(a.messages,n);if(g.toSummarize.length===0)return {messagesBefore:m,messagesAfter:m,messagesSummarized:0,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};let C;t&&g.toSummarize.length>0&&(C=await t(g.toSummarize),a.summaries.push({content:C,messagesCount:g.toSummarize.length,createdAt:Date.now()})),a.messages=g.keep,a.estimatedTokens=g.estimatedTokens;let E={messagesBefore:m,messagesAfter:a.messages.length,messagesSummarized:g.toSummarize.length,summary:C,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};return c?.(E),E}finally{y=false;}}function h(){if(y)return;e(a.messages,n).toSummarize.length>0&&p().catch(l=>{let g=l instanceof Error?l:new Error(String(l));o?o(g):console.error("[Directive Memory] Auto-manage error:",g);});}return {getState(){return {...a,messages:[...a.messages],summaries:a.summaries.map(m=>({...m}))}},addMessage(m){a.messages.push(m),a.totalMessagesProcessed++,a.estimatedTokens+=j(m),s&&h();},addMessages(m){for(let l of m)a.messages.push(l),a.totalMessagesProcessed++,a.estimatedTokens+=j(l);s&&h();},getContextMessages(){let m=[];if(a.summaries.length>0){let l=a.summaries.map(g=>g.content).join(`
|
|
2
2
|
|
|
3
3
|
---
|
|
4
4
|
|
|
5
|
-
`);
|
|
5
|
+
`);m.push({role:"system",content:`[Previous conversation summary]
|
|
6
6
|
|
|
7
|
-
${
|
|
7
|
+
${l}`});}if(m.push(...a.messages),u){let l=V(m);l>u&&console.warn(`[Directive Memory] Context messages (${l} tokens) exceed maxContextTokens (${u}). Consider calling manage() or reducing message count.`);}return m},manage:p,isManaging(){return y},clear(){a={messages:[],summaries:[],totalMessagesProcessed:0,estimatedTokens:0};},export(){return {...a,messages:[...a.messages],summaries:a.summaries.map(m=>({...m}))}},import(m){a={...m,messages:[...m.messages],summaries:m.summaries.map(l=>({...l}))};}}}function Kr(r=500){return async e=>{let t=e.filter(n=>n.role!=="system").map(n=>{let s=typeof n.content=="string"?n.content:JSON.stringify(n.content);return `${n.role}: ${s.slice(0,100)}${s.length>100?"...":""}`}).join(`
|
|
8
8
|
`);return t.length<=r?t:`${t.slice(0,r)}
|
|
9
9
|
[truncated]`}}function Wr(){return async r=>{let e=[];for(let t of r)if(t.role==="user"){let s=(typeof t.content=="string"?t.content:JSON.stringify(t.content)).match(/[^.!?]*\?/g);s&&e.push(...s.map(c=>`Q: ${c.trim()}`));}return e.length===0?`[${r.length} messages processed - no key questions found]`:`Key topics discussed:
|
|
10
10
|
${e.join(`
|
|
11
|
-
`)}`}}function Jr(r,e={}){let{maxSummaryLength:t=500,preserveKeyFacts:n=true}=e;return async s=>{let c=s.filter(u=>u.role!=="system").map(u=>{let
|
|
11
|
+
`)}`}}function Jr(r,e={}){let{maxSummaryLength:t=500,preserveKeyFacts:n=true}=e;return async s=>{let c=s.filter(u=>u.role!=="system").map(u=>{let a=typeof u.content=="string"?u.content:JSON.stringify(u.content);return `${u.role.toUpperCase()}: ${a}`}).join(`
|
|
12
12
|
|
|
13
|
-
`),
|
|
13
|
+
`),o=`Summarize the following conversation in ${t} characters or less.
|
|
14
14
|
${n?"Preserve key facts, decisions, and action items.":""}
|
|
15
15
|
Focus on information that would be useful context for continuing the conversation.
|
|
16
16
|
|
|
17
17
|
CONVERSATION:
|
|
18
18
|
${c}
|
|
19
19
|
|
|
20
|
-
SUMMARY:`;return r(
|
|
21
|
-
`)||
|
|
22
|
-
`)}function ln(){let r=new Map,e=new Map,t=new Map;return {async getSubjectData(n,s){let c=[];for(let[
|
|
20
|
+
SUMMARY:`;return r(o)}}var qr=1e4,Qr=10080*60*1e3,Xr=6e4,Z="0".repeat(64);function Yr(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function Zr(r){return new TextEncoder().encode(r)}function en(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}async function ee(r){let e=Zr(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return en(new Uint8Array(t))}function te(r){let{id:e,timestamp:t,eventType:n,previousHash:s,payload:c,actorId:o,sessionId:u}=r;return JSON.stringify({id:e,timestamp:t,eventType:n,previousHash:s,payload:c,actorId:o,sessionId:u})}function tn(r){return JSON.parse(JSON.stringify(r))}async function rn(r,e){let t=tn(r);async function n(s){if(typeof s=="string"){let c=await l(s,{types:e.types,minConfidence:e.minConfidence??.7});if(c.detected){let o=e.allowlist?c.items.filter(u=>!e.allowlist.includes(u.value.toLowerCase())):c.items;if(o.length>0)return i(s,o,e.redactionStyle)}return s}if(Array.isArray(s))return Promise.all(s.map(n));if(s&&typeof s=="object"){let c={};for(let[o,u]of Object.entries(s))c[o]=await n(u);return c}return s}for(let[s,c]of Object.entries(t))t[s]=await n(c);return t}function nn(r={}){let{maxEntries:e=qr,retentionMs:t=Qr,exportInterval:n=Xr,exporter:s,piiMasking:c,signing:o,sessionId:u,actorId:a,events:y={}}=r,p=[],h=0,m=0,l=0,g=true,C;function E(){return p.length===0?Z:p[p.length-1].hash}async function S(d,f,b){let A={id:Yr(),timestamp:Date.now(),eventType:d,previousHash:E(),payload:f,actorId:a,sessionId:u};c?.enabled&&(A.maskedPayload=await rn(f,c));let x=te(A),w=await ee(x),P={...A,hash:w};for(o&&(P.signature=await o.signFn(w)),p.push(P);p.length>e;)p.shift(),m++,h>0&&h--;return y.onEntryAdded?.(P),P}return s&&n>0&&(C=setInterval(async()=>{try{let d=p.slice(h);d.length>0&&(await s(d),l+=d.length,h=p.length);}catch(d){y.onExportError?.(d instanceof Error?d:new Error(String(d)),p.slice(h));}},n)),{getEntries(d){let f=[...p];if(d){if(d.eventTypes?.length){let b=new Set(d.eventTypes);f=f.filter(A=>b.has(A.eventType));}d.actorId&&(f=f.filter(b=>b.actorId===d.actorId)),d.sessionId&&(f=f.filter(b=>b.sessionId===d.sessionId)),d.since!==void 0&&(f=f.filter(b=>b.timestamp>=d.since)),d.until!==void 0&&(f=f.filter(b=>b.timestamp<=d.until)),d.offset!==void 0&&(f=f.slice(d.offset)),d.limit!==void 0&&(f=f.slice(0,d.limit));}return f},async verifyChain(){if(p.length===0)return {valid:true,entriesVerified:0,verifiedAt:Date.now()};p[0].previousHash;for(let f=0;f<p.length;f++){let b=p[f],A=te({id:b.id,timestamp:b.timestamp,eventType:b.eventType,previousHash:b.previousHash,payload:b.payload,actorId:b.actorId,sessionId:b.sessionId}),x=await ee(A);if(b.hash!==x){g=false;let w={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:x,actualHash:b.hash},verifiedAt:Date.now()};return y.onChainBroken?.(w),w}if(f>0){let w=p[f-1];if(b.previousHash!==w.hash){g=false;let P={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:w.hash,actualHash:b.previousHash},verifiedAt:Date.now()};return y.onChainBroken?.(P),P}}if(o?.verifyFn&&b.signature&&!await o.verifyFn(b.hash,b.signature)){g=false;let P={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:"signature-invalid",actualHash:b.signature},verifiedAt:Date.now()};return y.onChainBroken?.(P),P}}return g=true,{valid:true,entriesVerified:p.length,verifiedAt:Date.now()}},async export(d){let f=[...p];return d!==void 0&&(f=f.filter(b=>b.timestamp>=d)),s&&f.length>0&&(await s(f),l+=f.length),f},prune(){let d=Date.now()-t,f=p.length;for(;p.length>0&&p[0].timestamp<d;)p.shift(),h>0&&h--;let b=f-p.length;return m+=b,b},getStats(){let d={};for(let f of p)d[f.eventType]=(d[f.eventType]??0)+1;return {totalEntries:p.length,byEventType:d,oldestEntry:p[0]?.timestamp,newestEntry:p[p.length-1]?.timestamp,entriesPruned:m,entriesExported:l,chainIntegrity:g}},async destroy(){if(C&&(clearInterval(C),C=void 0),s)try{let d=p.slice(h);d.length>0&&(await s(d),l+=d.length);}catch(d){y.onExportError?.(d instanceof Error?d:new Error(String(d)),p.slice(h));}},addEntry(d,f){return S(d,f)},createPlugin(){return {name:"audit-trail",onFactSet:(d,f,b)=>{S("fact.set",{key:d,value:f,prev:b}).catch(console.error);},onFactsBatch:d=>{S("fact.batch",{changes:d.map(f=>({key:f.key,value:f.value,prev:f.prev}))}).catch(console.error);},onRequirementCreated:d=>{S("requirement.created",{id:d.id,type:d.requirement.type,payload:d.requirement}).catch(console.error);},onRequirementMet:(d,f)=>{S("requirement.met",{id:d.id,type:d.requirement.type,byResolver:f}).catch(console.error);},onResolverStart:(d,f)=>{S("resolver.start",{resolver:d,requirementId:f.id,requirementType:f.requirement.type}).catch(console.error);},onResolverComplete:(d,f,b)=>{S("resolver.complete",{resolver:d,requirementId:f.id,requirementType:f.requirement.type,duration:b}).catch(console.error);},onResolverError:(d,f,b)=>{S("resolver.error",{resolver:d,requirementId:f.id,requirementType:f.requirement.type,error:b instanceof Error?b.message:String(b)}).catch(console.error);},onError:d=>{S("error.occurred",{source:d.source,sourceId:d.sourceId,message:d.message,context:d.context}).catch(console.error);},onErrorRecovery:(d,f)=>{S("error.recovery",{source:d.source,message:d.message,strategy:f}).catch(console.error);}}}}}function on(r){return {onAgentStart:(e,t)=>{r.addEntry("agent.run.start",{agentName:e,input:t});},onAgentComplete:(e,t,n,s)=>{r.addEntry("agent.run.complete",{agentName:e,output:t,tokens:n,cost:s});},onAgentError:(e,t)=>{r.addEntry("agent.run.error",{agentName:e,error:t.message,stack:t.stack});},onToolStart:(e,t,n)=>{r.addEntry("tool.call.start",{toolName:e,toolCallId:t,args:n});},onToolComplete:(e,t,n)=>{r.addEntry("tool.call.complete",{toolName:e,toolCallId:t,result:n});},onToolError:(e,t,n)=>{r.addEntry("tool.call.error",{toolName:e,toolCallId:t,error:n.message});},onApprovalRequested:(e,t,n)=>{r.addEntry("approval.requested",{toolName:e,toolCallId:t,args:n});},onApprovalGranted:(e,t)=>{r.addEntry("approval.granted",{toolName:e,toolCallId:t});},onApprovalDenied:(e,t,n)=>{r.addEntry("approval.denied",{toolName:e,toolCallId:t,reason:n});}}}function an(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function sn(r){return new TextEncoder().encode(r)}function cn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}async function re(r){let e=sn(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return cn(new Uint8Array(t))}function un(r){if(r.length===0)return "";let e=new Set;for(let s of r)for(let c of Object.keys(s))e.add(c);let t=Array.from(e),n=[t.join(",")];for(let s of r){let c=t.map(o=>{let u=s[o];if(u==null)return "";if(typeof u=="object")return JSON.stringify(u).replace(/"/g,'""');let a=String(u);return a.includes(",")||a.includes(`
|
|
21
|
+
`)||a.includes('"')?`"${a.replace(/"/g,'""')}"`:a});n.push(c.join(","));}return n.join(`
|
|
22
|
+
`)}function ln(){let r=new Map,e=new Map,t=new Map;return {async getSubjectData(n,s){let c=[];for(let[o,u]of r){if(s&&!s.includes(o))continue;let a=u.get(n);a&&a.length>0&&c.push({category:o,records:[...a]});}return c},async deleteSubjectData(n,s){let c=0;for(let[o,u]of r){if(s&&!s.includes(o))continue;let a=u.get(n);a&&(c+=a.length,u.delete(n));}return c},async anonymizeSubjectData(n,s){let c=0;for(let[o,u]of r){if(s&&!s.includes(o))continue;let a=u.get(n);if(a)for(let y of a)y.data={...y.data,_anonymized:true,_anonymizedAt:Date.now()},c++;}return c},async getExpiredData(n,s){let c=[],o=r.get(n);if(o)for(let u of o.values())for(let a of u)a.createdAt<s&&c.push({id:a.id,createdAt:a.createdAt});return c},async deleteByIds(n){let s=new Set(n),c=0;for(let o of r.values())for(let[u,a]of o){let y=a.filter(p=>!s.has(p.id));y.length!==a.length&&(c+=a.length-y.length,y.length===0?o.delete(u):o.set(u,y));}return c},async storeConsent(n){e.set(`${n.subjectId}:${n.purpose}`,n);},async getConsent(n,s){return e.get(`${n}:${s}`)??null},async getConsentsBySubject(n){let s=[];for(let[c,o]of e)c.startsWith(`${n}:`)&&s.push(o);return s},async getConsentsByPurpose(n){let s=[];for(let[c,o]of e)c.endsWith(`:${n}`)&&s.push(o);return s},async storeDeletionCertificate(n){t.set(n.subjectId,n);}}}function dn(r){let{storage:e,retention:t,exportExpirationMs:n=864e5,events:s={}}=r,c={async grant(o,u,a={}){let y={subjectId:o,purpose:u,granted:true,grantedAt:Date.now(),expiresAt:a.expiresAt,source:a.source,version:a.version};return await e.storeConsent(y),s.onConsentChange?.(y),y},async revoke(o,u){let a=await e.getConsent(o,u);if(!a)return null;let y={...a,granted:false,revokedAt:Date.now()};return await e.storeConsent(y),s.onConsentChange?.(y),y},async check(o,u){let a=await e.getConsent(o,u);return !(!a||!a.granted||a.expiresAt&&a.expiresAt<Date.now())},async getForSubject(o){return e.getConsentsBySubject(o)},async getForPurpose(o){return e.getConsentsByPurpose(o)}};return {async exportData(o){try{let u=await e.getSubjectData(o.subjectId,o.categories),a=[],y=[];for(let{category:l,records:g}of u){y.push(l);for(let C of g)a.push({category:l,...C});}if(o.includeAudit&&e.getAuditEntries){let l=await e.getAuditEntries(o.subjectId);y.push("audit");for(let g of l)a.push({category:"audit",id:g.id,data:g.payload,createdAt:g.timestamp});}let p;o.format==="csv"?p=un(a.map(l=>({category:l.category,id:l.id,createdAt:new Date(l.createdAt).toISOString(),...l.data}))):p=JSON.stringify({subjectId:o.subjectId,exportedAt:new Date().toISOString(),recordCount:a.length,categories:y,records:a},null,2);let h=await re(p),m={success:!0,subjectId:o.subjectId,format:o.format,data:p,categories:y,recordCount:a.length,checksum:h,exportedAt:Date.now(),expiresAt:Date.now()+n};return s.onExport?.(m),m}catch(u){return {success:false,subjectId:o.subjectId,format:o.format,data:"",categories:[],recordCount:0,checksum:"",exportedAt:Date.now(),error:u instanceof Error?u.message:String(u)}}},async deleteData(o){try{let u=0,a=[];o.anonymize?u=await e.anonymizeSubjectData(o.subjectId,o.categories):u=await e.deleteSubjectData(o.subjectId,o.categories),o.categories?a.push(...o.categories):o.scope==="all"&&a.push("all");let y=JSON.stringify({subjectId:o.subjectId,type:o.anonymize?"anonymization":"hard",scope:o.scope,categories:a,recordCount:u,deletedAt:Date.now(),reason:o.reason}),p={id:an(),subjectId:o.subjectId,type:o.anonymize?"anonymization":"hard",scope:o.scope,categories:a,recordCount:u,deletedAt:Date.now(),reason:o.reason,hash:await re(y)};await e.storeDeletionCertificate(p);let h={success:!0,subjectId:o.subjectId,scope:o.scope,anonymized:o.anonymize??!1,recordsAffected:u,categoriesAffected:a,certificate:p,deletedAt:Date.now()};return s.onDelete?.(h),h}catch(u){return {success:false,subjectId:o.subjectId,scope:o.scope,anonymized:o.anonymize??false,recordsAffected:0,categoriesAffected:[],certificate:{id:"error",subjectId:o.subjectId,type:"hard",scope:o.scope,categories:[],recordCount:0,deletedAt:Date.now(),hash:""},deletedAt:Date.now(),error:u instanceof Error?u.message:String(u)}}},consent:c,async enforceRetention(){if(!t)return 0;let o=0,u=Date.now(),a=new Set;if(t.categoryRetention)for(let y of Object.keys(t.categoryRetention))a.add(y);a.add("default");for(let y of a){let p=t.categoryRetention?.[y]??t.defaultRetentionMs,h=u-p,m=await e.getExpiredData(y,h);if(m.length>0){await t.onBeforeDelete?.({category:y,count:m.length});let l=await e.deleteByIds(m.map(g=>g.id));o+=l,t.onAfterDelete?.({category:y,count:l}),s.onRetentionEnforced?.(y,l);}}return o},createConsentGuardrail(o){return async u=>{let y=u.input.match(/user[_-]?id[:\s]*([a-zA-Z0-9-]+)/i)?.[1];return y?await c.check(y,o)?{passed:true}:{passed:false,reason:`No consent for '${o}' from subject ${y}`}:{passed:true}}},async getDeletionCertificate(o){return null}}}function K(r={}){let{bufferSize:e=100}=r;if(e<1||!Number.isFinite(e))throw new Error(`[Directive StreamChannel] bufferSize must be >= 1, got ${e}`);let t=[],n="open",s=null,c=null,o=null,u=false;function a(l){if(c){let g=c;c=null,g.resolve({value:l,done:false});}}function y(){if(c){let l=c;c=null,l.resolve({value:void 0,done:true});}}function p(l){if(c){let g=c;c=null,u=false,g.reject(l);}}function h(){if(o){let l=o;o=null,l();}}return {async send(l){if(n!=="open")throw new Error(`[Directive StreamChannel] Cannot send to ${n} channel${r.name?` "${r.name}"`:""}`);if(c){a(l);return}if(t.length>=e){if(await new Promise(g=>{o=g;}),n!=="open")throw new Error(`[Directive StreamChannel] Cannot send to ${n} channel${r.name?` "${r.name}"`:""}`);if(c){a(l);return}}t.push(l);},end(){n==="open"&&(n="closed",y());},error(l){n==="open"&&(n="error",s=l,p(l),h());},getState(){return n},bufferedCount(){return t.length},[Symbol.asyncIterator](){if(u)throw new Error("[Directive StreamChannel] Channel only supports a single consumer. Create a separate channel for each consumer.");return u=true,{next(){if(n==="error"&&s)return u=false,Promise.reject(s);if(t.length>0){let l=t.shift();return h(),Promise.resolve({value:l,done:false})}return n==="closed"?(u=false,Promise.resolve({value:void 0,done:true})):new Promise((l,g)=>{c={resolve:l,reject:g};})},return(){return n="closed",t.length=0,u=false,h(),Promise.resolve({value:void 0,done:true})}}}}}function pn(r){let e=K(r),t=K(r);return {sideA:{send:n=>e.send(n),receive:t,close(){e.end(),t.end();}},sideB:{send:n=>t.send(n),receive:e,close(){e.end(),t.end();}}}}async function gn(r,e,t){try{for await(let n of r){let s=await t(n);await e.send(s);}e.end();}catch(n){e.error(n instanceof Error?n:new Error(String(n)));}}function mn(...r){return {[Symbol.asyncIterator](){let t=[],n=0,s=null,c=null,o=false,u=false,a=[];function y(p){if(s){let h=s;return s=null,h(p),true}return false}for(let p of r){let h=p[Symbol.asyncIterator]();a.push(h),(async()=>{try{for(;!o;){let m=await h.next();if(m.done||o)break;y({value:m.value,done:!1})||(t.length<1e4?t.push(m.value):u||(u=!0,console.warn("[Directive mergeStreams] Buffer exceeded 10000 items. Values are being dropped. Ensure the consumer keeps up or use bounded StreamChannel sources.")));}}catch(m){o||(o=true,c=m instanceof Error?m:new Error(String(m)),y({value:void 0,done:true}));}n++,n>=r.length&&!o&&y({value:void 0,done:true});})();}return {next(){return c?Promise.reject(c):t.length>0?Promise.resolve({value:t.shift(),done:false}):n>=r.length?Promise.resolve({value:void 0,done:true}):new Promise(p=>{s=p;})},return(){o=true,t.length=0;for(let p of a)p.return?.({value:void 0,done:true});if(s){let p=s;s=null,p({value:void 0,done:true});}return Promise.resolve({value:void 0,done:true})}}}}}function fn(r,e){let t=r.metadata.title??"",n=r.metadata.section??"",s=r.metadata.url??"";return `${t&&n&&s?`[${t} \u2014 ${n}](${s})`:t||r.id}
|
|
23
23
|
${r.content}`}function yn(r,e){return r.length===0?"":`Relevant documentation context:
|
|
24
24
|
|
|
25
25
|
${r.join(`
|
|
26
26
|
|
|
27
|
-
`)}`}function hn(r,e,t){return Math.max(e,Math.min(t,r))}function
|
|
27
|
+
`)}`}function hn(r,e,t){return Math.max(e,Math.min(t,r))}function vn(r){let{embedder:e,storage:t,topK:n=5,minSimilarity:s=.3,formatChunk:c=fn,formatContext:o=yn,onError:u$1}=r,a=hn(s,0,1);typeof process<"u"&&process.env?.NODE_ENV==="development"&&s!==a&&console.warn(`[Directive] RAG: minSimilarity ${s} clamped to ${a} (valid range: 0-1)`);async function y(h,m){let l=Math.max(1,Math.floor(m??n));if(t.search)return t.search(await e(h),l,a);let g=await e(h),E=(await t.getChunks()).map(S=>({...S,similarity:u(g,S.embedding)}));return E.sort((S,d)=>d.similarity-S.similarity),E.filter(S=>S.similarity>=a).slice(0,l)}async function p(h,m={}){let{prefix:l,history:g,topK:C,filter:E}=m,S=[];try{S=await y(h,C);}catch(A){u$1?.(A instanceof Error?A:new Error(String(A)));}E&&(S=S.filter(A=>E(A)));let d=S.map(A=>c(A,A.similarity)),f=o(d,h),b=[];if(l&&b.push(l),f&&b.push(f),g&&g.length>0){let A=g.map(x=>`${x.role.charAt(0).toUpperCase()+x.role.slice(1)}: ${x.content}`).join(`
|
|
28
28
|
|
|
29
|
-
`);
|
|
30
|
-
${A}`);}return
|
|
29
|
+
`);b.push(`Previous conversation:
|
|
30
|
+
${A}`);}return b.push(h),b.join(`
|
|
31
31
|
|
|
32
32
|
---
|
|
33
33
|
|
|
34
|
-
`)}return {retrieve:
|
|
34
|
+
`)}return {retrieve:y,enrich:p}}function Sn(r,e){let t=_.resolve(r);if(t.split(_.sep).includes(".."))throw new Error(`[Directive] File path escapes allowed directory: ${r}`);if(e){let s=_.resolve(e)+_.sep;if(!t.startsWith(s)&&t!==s.slice(0,-1))throw new Error(`[Directive] File path escapes allowed directory: ${r}`)}return t}function bn(r){let{filePath:e,mapEntry:t,ttlMs:n=0,baseDir:s}=r,c=Sn(e,s),o=null,u=0;async function a(){if(o&&(n===0||Date.now()-u<n))return o;try{let p=await(await import('fs')).promises.readFile(c,"utf-8"),h=JSON.parse(p);return o=t?h.map(t):h,u=Date.now(),o}catch(y){return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[Directive] JSONFileStore: failed to load ${c}:`,y),o=[],u=Date.now(),o}}return {async getChunks(){return a()},async size(){return (await a()).length},async reload(){o=null,u=0,await a();},destroy(){o=null,u=0;}}}var ne="AI service temporarily unavailable. Please try again.";function Cn(r={}){let{maxResponseChars:e=Number.POSITIVE_INFINITY,truncationMessage:t=`
|
|
35
35
|
|
|
36
|
-
*[Response truncated]*`,heartbeatIntervalMs:n=0,errorMessages:s,headers:c}=r;if(e<0)throw new RangeError("maxResponseChars must be non-negative");if(n<0)throw new RangeError("heartbeatIntervalMs must be non-negative");function
|
|
36
|
+
*[Response truncated]*`,heartbeatIntervalMs:n=0,errorMessages:s,headers:c}=r;if(e<0)throw new RangeError("maxResponseChars must be non-negative");if(n<0)throw new RangeError("heartbeatIntervalMs must be non-negative");function o(y){if(typeof s=="function")try{return s(y)}catch{return ne}if(s&&typeof s=="object"){let p=y!=null&&typeof y=="object"&&"code"in y&&typeof y.code=="string"?y.code:void 0;if(p&&p in s)return s[p]}return ne}function u(y,p,h,m){let l=new TextEncoder;function g(C){return l.encode(`data: ${JSON.stringify(C)}
|
|
37
37
|
|
|
38
|
-
`)}return new ReadableStream({async start(C){let E=null,
|
|
38
|
+
`)}return new ReadableStream({async start(C){let E=null,S=null;try{n>0&&(E=setInterval(()=>{try{C.enqueue(g({type:"heartbeat",timestamp:Date.now()}));}catch{}},n)),S=y.stream(p,h,{signal:m?.signal});let d=0,f=!1;for await(let b of S){if(d+=b.length,d>e){C.enqueue(g({type:"truncated",text:t})),C.enqueue(g({type:"done"})),f=!0,S.abort();break}C.enqueue(g({type:"text",text:b}));}try{await S.result;}catch{}f||C.enqueue(g({type:"done"}));}catch(d){let f=o(d);C.enqueue(g({type:"error",message:f}));}finally{E&&clearInterval(E),C.close();}}})}let a={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...c};return {toResponse(y,p,h,m){let l=u(y,p,h,m);return new Response(l,{headers:a})},toStream(y,p,h,m){return u(y,p,h,m)}}}var G=class extends Error{retryCount;lastError;constructor(e,t){super(`[Directive] All ${e} retries exhausted: ${t.message}`),this.name="RetryExhaustedError",this.retryCount=e,this.lastError=t,this.cause=t;}},Rn=new Set([400,401,403,404,422]);function W(r){let e=r;if(typeof e.status=="number"&&e.status>=100&&e.status<=599)return e.status;if(typeof e.statusCode=="number"&&e.statusCode>=100&&e.statusCode<=599)return e.statusCode;let n=(r.message.length>1e3?r.message.slice(0,1e3):r.message).match(/(?:failed|error|status|http)[:\s]+(\d{3})\b/i);if(!n)return null;let s=Number(n[1]);return s>=100&&s<=599?s:null}function oe(r){let e=r;if(typeof e.retryAfter=="number"&&e.retryAfter>0)return e.retryAfter*1e3;let n=(r.message.length>1e3?r.message.slice(0,1e3):r.message).match(/retry[- ]?after[:\s]+(\d+)/i);if(!n)return null;let s=Number(n[1]);return s>0?s*1e3:null}function En(r,e,t){let n=e*2**(r-1),s=Math.random()*e*.5,c=n+s;return Math.min(c,t)}function An(r,e,t,n){if(W(r)===429){let c=oe(r);if(c!==null)return Math.min(c,n)}return En(e,t,n)}function Tn(r){let e=W(r);return e===null?true:!Rn.has(e)}function wn(r,e={}){let{maxRetries:t=3,baseDelayMs:n=1e3,maxDelayMs:s=3e4,isRetryable:c,onRetry:o}=e;if(!Number.isFinite(t)||t<0)throw new Error("[Directive] withRetry: maxRetries must be a non-negative finite number.");if(!Number.isFinite(n)||n<0)throw new Error("[Directive] withRetry: baseDelayMs must be a non-negative finite number.");if(!Number.isFinite(s)||s<0)throw new Error("[Directive] withRetry: maxDelayMs must be a non-negative finite number.");return async(u,a,y)=>{let p;for(let h=0;h<=t;h++)try{return await r(u,a,y)}catch(m){if(p=m instanceof Error?m:new Error(String(m)),h>=t)break;if(c)try{if(!c(p))break}catch{break}if(!Tn(p))break;let l=An(p,h+1,n,s);try{o?.(h+1,p,l);}catch{}let g=y?.signal;if(g?.aborted)break;await new Promise((C,E)=>{let S=setTimeout(()=>{g?.removeEventListener("abort",d),C();},l);function d(){clearTimeout(S),E(g.reason??new Error("Aborted"));}g&&g.addEventListener("abort",d,{once:true});});}throw new G(t,p)}}var F=class extends Error{errors;constructor(e){let t=e.map((n,s)=>` [${s}] ${n.message}`).join(`
|
|
39
39
|
`);super(`[Directive] All ${e.length} providers failed:
|
|
40
|
-
${t}`),this.name="AllProvidersFailedError",this.errors=Object.freeze([...e]),e.length>0&&(this.cause=e[e.length-1]);}};function kn(r,e={}){if(r.length===0)throw new Error("[Directive] withFallback requires at least one runner.");let{shouldFallback:t,onFallback:n}=e;return async(s,c,a)=>{let u=[];for(let o=0;o<r.length;o++)try{return await r[o](s,c,a)}catch(m){let d=m instanceof Error?m:new Error(String(m));if(u.push(d),o<r.length-1){if(t)try{if(!t(d))break}catch{break}try{n?.(o,o+1,d);}catch{}}}throw new F(u)}}var G=class extends Error{estimated;remaining;window;constructor(e){super(`[Directive] Budget exceeded (${e.window}): estimated $${e.estimated.toFixed(4)}, remaining $${e.remaining.toFixed(4)}`),this.name="BudgetExceededError",this.estimated=e.estimated,this.remaining=e.remaining,this.window=e.window;}},$=class{entries=[];record(e){this.entries.push({timestamp:Date.now(),cost:e});}getCostInWindow(e){let t=Date.now()-e;this.prune(t);let n=0;for(let s of this.entries)s.timestamp>=t&&(n+=s.cost);return n}prune(e){let t=0;for(;t<this.entries.length&&this.entries[t].timestamp<e;)t++;t>0&&this.entries.splice(0,t);}clear(){this.entries=[];}},ae={hour:3600*1e3,day:1440*60*1e3};function xn(r,e){return Math.ceil(r.length/e)}function se(r,e){return r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function ie(r,e,t=1){let n=Math.ceil(r*t);return r/1e6*e.inputPerMillion+n/1e6*e.outputPerMillion}function Mn(r,e){let{maxCostPerCall:t,budgets:n=[],pricing:s,charsPerToken:c=4,estimatedOutputMultiplier:a=1,onBudgetExceeded:u}=e;if(!Number.isFinite(c)||c<=0)throw new Error("[Directive] withBudget: charsPerToken must be a positive finite number.");if(t!=null&&(!Number.isFinite(t)||t<0))throw new Error("[Directive] withBudget: maxCostPerCall must be a non-negative finite number.");if(!Number.isFinite(a)||a<0)throw new Error("[Directive] withBudget: estimatedOutputMultiplier must be a non-negative finite number.");t!=null&&!s&&console.warn("[Directive] withBudget: maxCostPerCall has no effect without pricing. Provide a pricing config to enable per-call cost estimation.");for(let y of n)if(!Number.isFinite(y.maxCost)||y.maxCost<0)throw new Error(`[Directive] withBudget: budgets[${y.window}].maxCost must be a non-negative finite number.`);let o=new Map;for(let y of n)o.set(y.window,new $);let m=new $,d=async(y,p,f)=>{let C=xn(p,c);if(t!=null&&s){let v=ie(C,s,a);if(v>t){let l={estimated:v,remaining:t,window:"per-call"};try{u?.(l);}catch{}throw new G(l)}}for(let v of n){let l=ae[v.window],S=o.get(v.window).getCostInWindow(l),A=v.maxCost-S,x=ie(C,v.pricing,a);if(x>A){let w={estimated:x,remaining:Math.max(0,A),window:v.window};try{u?.(w);}catch{}throw new G(w)}}let E=await r(y,p,f);if(E.tokenUsage){for(let v of n){let l=o.get(v.window),g=se(E.tokenUsage,v.pricing);l.record(g);}if(s&&n.length===0){let v=se(E.tokenUsage,s);m.record(v);}}return E};function b(y){let p=o.get(y);if(!p)return 0;let f=ae[y];return p.getCostInWindow(f)}return d.getSpent=b,d}function In(r,e){return {match:(t,n)=>n.length<=r,model:e}}function Pn(r,e){return {match:t=>t.name===r,model:e}}function Dn(r,e){return {match:(t,n)=>(r.lastIndex=0,r.test(n)),model:e}}function On(r,e){let t=Array.isArray(e)?{rules:e}:e,{rules:n,onModelSelected:s}=t;return async(c,a,u)=>{let o=c.model;for(let d of n)try{if(d.match(c,a)){o=d.model;break}}catch{}try{s?.(c.model,o);}catch{}let m=o!==c.model?{...c,model:o}:c;return r(m,a,u)}}function Bn(r,e={}){let{maxBatchSize:t=20,maxWaitMs:n=5e3,concurrency:s=5}=e;if(!Number.isFinite(t)||t<1)throw new Error("[Directive] createBatchQueue: maxBatchSize must be a positive finite number (>= 1).");if(!Number.isFinite(n)||n<0)throw new Error("[Directive] createBatchQueue: maxWaitMs must be a non-negative finite number.");if(!Number.isFinite(s)||s<1)throw new Error("[Directive] createBatchQueue: concurrency must be a positive finite number (>= 1).");let c=[],a=null,u=false,o=null;function m(){a===null&&(a=setTimeout(()=>{a=null,y().catch(()=>{});},n));}function d(){a!==null&&(clearTimeout(a),a=null);}async function b(p){let f=0;async function C(){for(;f<p.length;){let v=f++,l=p[v];try{let g=await r(l.agent,l.input,l.options);l.resolve(g);}catch(g){l.reject(g instanceof Error?g:new Error(String(g)));}}}let E=Array.from({length:Math.min(s,p.length)},()=>C());await Promise.all(E);}async function y(){if(o&&await o,c.length===0)return;d();let p=c.splice(0);o=b(p).finally(()=>{o=null,c.length>0&&m();}),await o;}return {submit(p,f,C){return u?Promise.reject(new Error("[Directive] BatchQueue has been destroyed.")):new Promise((E,v)=>{c.push({agent:p,input:f,options:C,resolve:E,reject:v}),c.length>=t?(d(),y().catch(()=>{})):m();})},async flush(){await y();},get pending(){return c.length},async destroy(){u||(u=true,d(),c.length>0&&await y());}}}function ce(){return {callCount:0,errorCount:0,totalCost:0,avgLatencyMs:0,lastErrorAt:null}}function jn(r,e){return !r||!e?0:r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function Gn(r){let{providers:e,defaultProvider:t,constraints:n=[],onProviderSelected:s,errorCooldownMs:c=3e4,preferCheapest:a=false}=r;if(!Number.isFinite(c)||c<0)throw new Error("[Directive] createConstraintRouter: errorCooldownMs must be a non-negative finite number.");let u=new Map;for(let f of e)u.set(f.name,f);if(!u.has(t))throw new Error(`[Directive] Default provider "${t}" not found in providers list.`);let o={totalCost:0,callCount:0,errorCount:0,lastProvider:null,avgLatencyMs:0,providers:Object.create(null)};for(let f of e)o.providers[f.name]=ce();let m=0,d=[...n].sort((f,C)=>(C.priority??0)-(f.priority??0));function b(){let f=Date.now();for(let E of d)try{if(E.when(o)){let v=u.get(E.provider);if(v)return {provider:v,reason:"constraint"}}}catch{}let C=e.filter(E=>{let v=o.providers[E.name];return v?!(v.lastErrorAt&&f-v.lastErrorAt<c):true});if(a&&C.length>0){let E=[...C].sort((v,l)=>{let g=v.pricing?v.pricing.inputPerMillion+v.pricing.outputPerMillion:Number.POSITIVE_INFINITY,S=l.pricing?l.pricing.inputPerMillion+l.pricing.outputPerMillion:Number.POSITIVE_INFINITY;return g!==S?g-S:v.name===t?-1:l.name===t?1:0});if(E[0]!==u.get(t))return {provider:E[0],reason:"cheapest"}}return C.length>0&&!C.some(E=>E.name===t)?{provider:C[0],reason:"default"}:{provider:u.get(t),reason:"default"}}function y(f,C,E,v,l){let g=o.providers[f]??ce();if(g.callCount++,o.callCount++,l)g.errorCount++,o.errorCount++,g.lastErrorAt=Date.now();else {let A=jn(E,v);g.totalCost+=A,o.totalCost+=A;}m+=C,o.avgLatencyMs=m/o.callCount;let S=g.callCount>0?(g.avgLatencyMs*(g.callCount-1)+C)/g.callCount:C;g.avgLatencyMs=S,o.providers[f]=g,o.lastProvider=f;}let p=async(f,C,E)=>{let{provider:v,reason:l}=b();try{s?.(v.name,l);}catch{}let g=Date.now();try{let S=await v.runner(f,C,E),A=Date.now()-g;return y(v.name,A,S.tokenUsage,v.pricing),S}catch(S){let A=Date.now()-g,x=S instanceof Error?S:new Error(String(S));throw y(v.name,A,void 0,v.pricing,x),x}};return Object.defineProperty(p,"facts",{get:()=>{let f=Object.create(null);for(let C of Object.keys(o.providers))f[C]={...o.providers[C]};return {...o,providers:f}},enumerable:true}),p}var I={UNSET:0,OK:1,ERROR:2},L=class{constructor(e,t,n,s,c,a){this.name=e;this.spanId=t;this.traceId=n;this.parentSpanId=s;this.onEnd=a;if(this.startTime=Date.now(),c)for(let[u,o]of Object.entries(c))this.attributes[u]=o;}attributes=Object.create(null);spanEvents=[];status={code:I.UNSET};startTime;endTime=0;setAttribute(e,t){this.attributes[e]=t;}addEvent(e,t){this.spanEvents.push({name:e,attributes:t,timestamp:Date.now()});}setStatus(e){this.status=e;}end(){this.endTime=Date.now(),this.onEnd?.(this);}toSpanData(){return {name:this.name,traceId:this.traceId,spanId:this.spanId,parentSpanId:this.parentSpanId,attributes:{...this.attributes},events:[...this.spanEvents],status:{...this.status},startTime:this.startTime,endTime:this.endTime,durationMs:this.endTime-this.startTime}}},J=class{spans=[];startSpan(e,t){let n=t?.spanId??`fallback-${crypto.randomUUID()}`,s=t?.traceId??`fallback-${crypto.randomUUID()}`,c=t?.parentSpanId;return new L(e,n,s,c,t?.attributes,a=>{this.spans.push(a.toSpanData());})}clear(){this.spans.length=0;}};function _n(r){let e=r.spanPrefix??"directive.ai",t=r.instrumentEvents,n=r.spanTtlMs??3e5,s=!r.tracer,c=s?new J:null,a=r.tracer??c,u=0;function o(){return `${Date.now().toString(36)}-${(u++).toString(36)}`}function m(){return `${Date.now().toString(36)}-${crypto.randomUUID().slice(0,8)}`}let d=new Map,b=0,y=new Map,p=[],f=null,C=false;function E(i){return t?t.has(i):true}function v(i,h){return `${i}:${h}:${b++}`}function l(i,h){let R=`${i}:${h}`,T=y.get(R);if(T){for(let k=T.length-1;k>=0;k--){let O=d.get(T[k]);if(O)return {key:T[k],entry:O}}y.delete(R);}return null}function g(i,h,R,T){let k=`${i}:${h}`;T.indexKey=k,d.set(R,T);let O=y.get(k);O?O.push(R):y.set(k,[R]);}function S(i){let h=d.get(i);d.delete(i);let R=h?.indexKey;if(R){let T=y.get(R);if(T){let k=T.indexOf(i);k!==-1&&T.splice(k,1),T.length===0&&y.delete(R);}}}function A(){let i=Date.now();if(d.size<1e4){for(let[R,T]of d)i-T.startTime>n&&(M(T,"directive.stale",true),D(T,{code:I.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(T),S(R),true);return void 0}for(let[h,R]of d)i-R.startTime>n&&(M(R,"directive.stale",true),D(R,{code:I.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(R),S(h));}function x(i,h,R){let T=o(),k=R?.traceId??m(),O=R?.spanId,B;s?B=a.startSpan(i,{attributes:h,spanId:T,traceId:k,parentSpanId:O}):B=a.startSpan(i,{attributes:h});let z={span:B,spanId:T,traceId:k,startTime:Date.now()};return s||(z.shadow={span:B,name:i,spanId:T,traceId:k,parentSpanId:O,attributes:{...h},events:[],status:{code:I.UNSET},startTime:z.startTime}),{span:B,entry:z}}function w(i){i.span.end(),r.onSpanEnd&&r.onSpanEnd(P(i));}function P(i){if(i.span instanceof L)return i.span.toSpanData();if(i.shadow){let R=Date.now();return {name:i.shadow.name,traceId:i.shadow.traceId,spanId:i.shadow.spanId,parentSpanId:i.shadow.parentSpanId,attributes:{...i.shadow.attributes},events:[...i.shadow.events],status:{...i.shadow.status},startTime:i.shadow.startTime,endTime:R,durationMs:R-i.shadow.startTime}}let h=Date.now();return {name:"unknown",traceId:i.traceId,spanId:i.spanId,attributes:{},events:[],status:{code:I.UNSET},startTime:i.startTime,endTime:h,durationMs:h-i.startTime}}function M(i,h,R){i.span.setAttribute(h,R),i.shadow&&(i.shadow.attributes[h]=R);}function q(i,h,R){i.span.addEvent(h,R),i.shadow&&i.shadow.events.push({name:h,attributes:R,timestamp:Date.now()});}function D(i,h){i.span.setStatus(h),i.shadow&&(i.shadow.status={...h});}function ue(i){if(E(i.type))switch(A(),i.type){case "agent_start":le(i);break;case "agent_complete":de(i);break;case "agent_error":pe(i);break;case "guardrail_check":ge(i);break;case "constraint_evaluate":me(i);break;case "resolver_start":fe(i);break;case "resolver_complete":ye(i);break;case "resolver_error":he(i);break;case "pattern_start":Se(i);break;case "pattern_complete":ve(i);break;default:if(i.agentId){let h=l("agent",i.agentId);h&&q(h.entry,i.type,{"event.id":i.id,"event.timestamp":i.timestamp});}}}function le(i){let h=p.length>0?p[p.length-1]:null,{entry:R}=x(`${e}.agent.run`,{"directive.service":r.serviceName,"directive.agent.name":i.agentId,"directive.agent.input_length":i.inputLength,"gen_ai.operation.name":"agent.run","gen_ai.agent.name":i.agentId},h),T=v("agent",i.agentId);g("agent",i.agentId,T,R);}function de(i){let h=l("agent",i.agentId);h&&(M(h.entry,"directive.agent.output_length",i.outputLength),M(h.entry,"directive.agent.total_tokens",i.totalTokens),M(h.entry,"directive.agent.duration_ms",i.durationMs),M(h.entry,"gen_ai.usage.total_tokens",i.totalTokens),D(h.entry,{code:I.OK}),w(h.entry),S(h.key));}function pe(i){let h=l("agent",i.agentId);h&&(M(h.entry,"directive.agent.duration_ms",i.durationMs),M(h.entry,"directive.agent.error",i.errorMessage),M(h.entry,"gen_ai.error.message",i.errorMessage),D(h.entry,{code:I.ERROR,message:i.errorMessage}),w(h.entry),S(h.key));}function ge(i){let h=i.agentId?l("agent",i.agentId)?.entry??null:null,{entry:R}=x(`${e}.guardrail.check`,{"directive.service":r.serviceName,"directive.guardrail.name":i.guardrailName,"directive.guardrail.type":i.guardrailType,"directive.guardrail.passed":i.passed,"directive.guardrail.duration_ms":i.durationMs,"gen_ai.guardrail.name":i.guardrailName,"gen_ai.guardrail.type":i.guardrailType,"gen_ai.guardrail.passed":i.passed},h);i.reason&&M(R,"directive.guardrail.reason",i.reason),D(R,{code:i.passed?I.OK:I.ERROR,message:i.passed?void 0:i.reason}),w(R);}function me(i){if(i.agentId){let R=l("agent",i.agentId);if(R){q(R.entry,"constraint_evaluate",{"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired});return}}let{entry:h}=x(`${e}.constraint.evaluate`,{"directive.service":r.serviceName,"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired},null);D(h,{code:I.OK}),w(h);}function fe(i){let R=(i.agentId?l("agent",i.agentId)?.entry??null:null)??(p.length>0?p[p.length-1]:null),{entry:T}=x(`${e}.resolver.execute`,{"directive.service":r.serviceName,"directive.resolver.id":i.resolverId,"directive.resolver.requirement_type":i.requirementType},R),k=v("resolver",i.resolverId);g("resolver",i.resolverId,k,T);}function ye(i){let h=l("resolver",i.resolverId);h&&(M(h.entry,"directive.resolver.duration_ms",i.durationMs),D(h.entry,{code:I.OK}),w(h.entry),S(h.key));}function he(i){let h=l("resolver",i.resolverId);h&&(M(h.entry,"directive.resolver.duration_ms",i.durationMs),M(h.entry,"directive.resolver.error",i.errorMessage),D(h.entry,{code:I.ERROR,message:i.errorMessage}),w(h.entry),S(h.key));}function Se(i){let h=p.length>0?p[p.length-1]:null,{entry:R}=x(`${e}.pattern.${i.patternType}`,{"directive.service":r.serviceName,"directive.pattern.id":i.patternId,"directive.pattern.type":i.patternType},h),T=v("pattern",i.patternId);g("pattern",i.patternId,T,R),p.length<100&&p.push(R);}function ve(i){let h=l("pattern",i.patternId);if(h){M(h.entry,"directive.pattern.duration_ms",i.durationMs),i.error?(M(h.entry,"directive.pattern.error",i.error),D(h.entry,{code:I.ERROR,message:i.error})):D(h.entry,{code:I.OK}),w(h.entry),S(h.key);let R=p.indexOf(h.entry);R!==-1&&p.splice(R,1);}}return {attach(i){if(f&&f!==i)throw new Error("[Directive OTEL] Plugin already attached to a different timeline. Create a new plugin instance.");f=i;let h=i.subscribe(ue),R=setInterval(A,Math.min(n,6e4));return ()=>{h(),clearInterval(R),f=null;for(let[T,k]of d)M(k,"directive.detached",true),D(k,{code:I.ERROR,message:"Plugin detached while span was active"}),w(k);d.clear(),y.clear(),p.length=0;}},getSpans(){return c?[...c.spans]:(C||(C=true,typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[Directive OTEL] getSpans() returns [] when using an external tracer. Use the onSpanEnd callback to collect span data instead.")),[])},clearSpans(){c?.clear();},getTracer(){return a},getActiveSpanCount(){return d.size}}}export{F as AllProvidersFailedError,G as BudgetExceededError,I as OtelStatusCode,N as RetryExhaustedError,Pn as byAgentName,In as byInputLength,Dn as byPattern,on as createAgentAuditHandlers,Vr as createAgentMemory,nn as createAuditTrail,Bn as createBatchQueue,pn as createBidirectionalStream,dn as createCompliance,Gn as createConstraintRouter,Hr as createHybridStrategy,ln as createInMemoryComplianceStorage,bn as createJSONFileStore,Wr as createKeyPointsSummarizer,Jr as createLLMSummarizer,_n as createOtelPlugin,Sn as createRAGEnricher,Cn as createSSETransport,X as createSlidingWindowStrategy,K as createStreamChannel,Y as createTokenBasedStrategy,Kr as createTruncationSummarizer,mn as mergeStreams,W as parseHttpStatus,oe as parseRetryAfter,Ur as pipe,gn as pipeThrough,Mn as withBudget,kn as withFallback,On as withModelSelection,wn as withRetry};//# sourceMappingURL=index.js.map
|
|
40
|
+
${t}`),this.name="AllProvidersFailedError",this.errors=Object.freeze([...e]),e.length>0&&(this.cause=e[e.length-1]);}};function kn(r,e={}){if(r.length===0)throw new Error("[Directive] withFallback requires at least one runner.");let{shouldFallback:t,onFallback:n}=e;return async(s,c,o)=>{let u=[];for(let a=0;a<r.length;a++)try{return await r[a](s,c,o)}catch(y){let p=y instanceof Error?y:new Error(String(y));if(u.push(p),a<r.length-1){if(t)try{if(!t(p))break}catch{break}try{n?.(a,a+1,p);}catch{}}}throw new F(u)}}var N=class extends Error{estimated;remaining;window;constructor(e){super(`[Directive] Budget exceeded (${e.window}): estimated $${e.estimated.toFixed(4)}, remaining $${e.remaining.toFixed(4)}`),this.name="BudgetExceededError",this.estimated=e.estimated,this.remaining=e.remaining,this.window=e.window;}},$=class{entries=[];record(e){this.entries.push({timestamp:Date.now(),cost:e});}getCostInWindow(e){let t=Date.now()-e;this.prune(t);let n=0;for(let s of this.entries)s.timestamp>=t&&(n+=s.cost);return n}prune(e){let t=0;for(;t<this.entries.length&&this.entries[t].timestamp<e;)t++;t>0&&this.entries.splice(0,t);}clear(){this.entries=[];}},ae={hour:3600*1e3,day:1440*60*1e3};function xn(r,e){return Math.ceil(r.length/e)}function se(r,e){return r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function ie(r,e,t=1){let n=Math.ceil(r*t);return r/1e6*e.inputPerMillion+n/1e6*e.outputPerMillion}function Mn(r,e){let{maxCostPerCall:t,budgets:n=[],pricing:s,charsPerToken:c=4,estimatedOutputMultiplier:o=1,onBudgetExceeded:u}=e;if(!Number.isFinite(c)||c<=0)throw new Error("[Directive] withBudget: charsPerToken must be a positive finite number.");if(t!=null&&(!Number.isFinite(t)||t<0))throw new Error("[Directive] withBudget: maxCostPerCall must be a non-negative finite number.");if(!Number.isFinite(o)||o<0)throw new Error("[Directive] withBudget: estimatedOutputMultiplier must be a non-negative finite number.");t!=null&&!s&&console.warn("[Directive] withBudget: maxCostPerCall has no effect without pricing. Provide a pricing config to enable per-call cost estimation.");for(let m of n)if(!Number.isFinite(m.maxCost)||m.maxCost<0)throw new Error(`[Directive] withBudget: budgets[${m.window}].maxCost must be a non-negative finite number.`);let a=new Map;for(let m of n)a.set(m.window,new $);let y=new $,p=async(m,l,g)=>{let C=xn(l,c);if(t!=null&&s){let S=ie(C,s,o);if(S>t){let d={estimated:S,remaining:t,window:"per-call"};try{u?.(d);}catch{}throw new N(d)}}for(let S of n){let d=ae[S.window],b=a.get(S.window).getCostInWindow(d),A=S.maxCost-b,x=ie(C,S.pricing,o);if(x>A){let w={estimated:x,remaining:Math.max(0,A),window:S.window};try{u?.(w);}catch{}throw new N(w)}}let E=await r(m,l,g);if(E.tokenUsage){for(let S of n){let d=a.get(S.window),f=se(E.tokenUsage,S.pricing);d.record(f);}if(s&&n.length===0){let S=se(E.tokenUsage,s);y.record(S);}}return E};function h(m){let l=a.get(m);if(!l)return 0;let g=ae[m];return l.getCostInWindow(g)}return p.getSpent=h,p}function In(r,e){return {match:(t,n)=>n.length<=r,model:e}}function Pn(r,e){return {match:t=>t.name===r,model:e}}function Dn(r,e){return {match:(t,n)=>(r.lastIndex=0,r.test(n)),model:e}}function On(r,e){let t=Array.isArray(e)?{rules:e}:e,{rules:n,onModelSelected:s}=t;return async(c,o,u)=>{let a=c.model;for(let p of n)try{if(p.match(c,o)){a=p.model;break}}catch{}try{s?.(c.model,a);}catch{}let y=a!==c.model?{...c,model:a}:c;return r(y,o,u)}}function Bn(r,e={}){let{maxBatchSize:t=20,maxWaitMs:n=5e3,concurrency:s=5}=e;if(!Number.isFinite(t)||t<1)throw new Error("[Directive] createBatchQueue: maxBatchSize must be a positive finite number (>= 1).");if(!Number.isFinite(n)||n<0)throw new Error("[Directive] createBatchQueue: maxWaitMs must be a non-negative finite number.");if(!Number.isFinite(s)||s<1)throw new Error("[Directive] createBatchQueue: concurrency must be a positive finite number (>= 1).");let c=[],o=null,u=false,a=null;function y(){o===null&&(o=setTimeout(()=>{o=null,m().catch(()=>{});},n));}function p(){o!==null&&(clearTimeout(o),o=null);}async function h(l){let g=0;async function C(){for(;g<l.length;){let S=g++,d=l[S];try{let f=await r(d.agent,d.input,d.options);d.resolve(f);}catch(f){d.reject(f instanceof Error?f:new Error(String(f)));}}}let E=Array.from({length:Math.min(s,l.length)},()=>C());await Promise.all(E);}async function m(){if(a&&await a,c.length===0)return;p();let l=c.splice(0);a=h(l).finally(()=>{a=null,c.length>0&&y();}),await a;}return {submit(l,g,C){return u?Promise.reject(new Error("[Directive] BatchQueue has been destroyed.")):new Promise((E,S)=>{c.push({agent:l,input:g,options:C,resolve:E,reject:S}),c.length>=t?(p(),m().catch(()=>{})):y();})},async flush(){await m();},get pending(){return c.length},async destroy(){u||(u=true,p(),c.length>0&&await m());}}}function ce(){return {callCount:0,errorCount:0,totalCost:0,avgLatencyMs:0,lastErrorAt:null}}function jn(r,e){return !r||!e?0:r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function Nn(r){let{providers:e,defaultProvider:t,constraints:n=[],onProviderSelected:s,errorCooldownMs:c=3e4,preferCheapest:o=false}=r;if(!Number.isFinite(c)||c<0)throw new Error("[Directive] createConstraintRouter: errorCooldownMs must be a non-negative finite number.");let u=new Map;for(let g of e)u.set(g.name,g);if(!u.has(t))throw new Error(`[Directive] Default provider "${t}" not found in providers list.`);let a={totalCost:0,callCount:0,errorCount:0,lastProvider:null,avgLatencyMs:0,providers:Object.create(null)};for(let g of e)a.providers[g.name]=ce();let y=0,p=[...n].sort((g,C)=>(C.priority??0)-(g.priority??0));function h(){let g=Date.now();for(let E of p)try{if(E.when(a)){let S=u.get(E.provider);if(S)return {provider:S,reason:"constraint"}}}catch{}let C=e.filter(E=>{let S=a.providers[E.name];return S?!(S.lastErrorAt&&g-S.lastErrorAt<c):true});if(o&&C.length>0){let E=[...C].sort((S,d)=>{let f=S.pricing?S.pricing.inputPerMillion+S.pricing.outputPerMillion:Number.POSITIVE_INFINITY,b=d.pricing?d.pricing.inputPerMillion+d.pricing.outputPerMillion:Number.POSITIVE_INFINITY;return f!==b?f-b:S.name===t?-1:d.name===t?1:0});if(E[0]!==u.get(t))return {provider:E[0],reason:"cheapest"}}return C.length>0&&!C.some(E=>E.name===t)?{provider:C[0],reason:"default"}:{provider:u.get(t),reason:"default"}}function m(g,C,E,S,d){let f=a.providers[g]??ce();if(f.callCount++,a.callCount++,d)f.errorCount++,a.errorCount++,f.lastErrorAt=Date.now();else {let A=jn(E,S);f.totalCost+=A,a.totalCost+=A;}y+=C,a.avgLatencyMs=y/a.callCount;let b=f.callCount>0?(f.avgLatencyMs*(f.callCount-1)+C)/f.callCount:C;f.avgLatencyMs=b,a.providers[g]=f,a.lastProvider=g;}let l=async(g,C,E)=>{let{provider:S,reason:d}=h();try{s?.(S.name,d);}catch{}let f=Date.now();try{let b=await S.runner(g,C,E),A=Date.now()-f;return m(S.name,A,b.tokenUsage,S.pricing),b}catch(b){let A=Date.now()-f,x=b instanceof Error?b:new Error(String(b));throw m(S.name,A,void 0,S.pricing,x),x}};return Object.defineProperty(l,"facts",{get:()=>{let g=Object.create(null);for(let C of Object.keys(a.providers))g[C]={...a.providers[C]};return {...a,providers:g}},enumerable:true}),l}var M={UNSET:0,OK:1,ERROR:2},L=class{constructor(e,t,n,s,c,o){this.name=e;this.spanId=t;this.traceId=n;this.parentSpanId=s;this.onEnd=o;if(this.startTime=Date.now(),c)for(let[u,a]of Object.entries(c))this.attributes[u]=a;}attributes=Object.create(null);spanEvents=[];status={code:M.UNSET};startTime;endTime=0;setAttribute(e,t){this.attributes[e]=t;}addEvent(e,t){this.spanEvents.push({name:e,attributes:t,timestamp:Date.now()});}setStatus(e){this.status=e;}end(){this.endTime=Date.now(),this.onEnd?.(this);}toSpanData(){return {name:this.name,traceId:this.traceId,spanId:this.spanId,parentSpanId:this.parentSpanId,attributes:{...this.attributes},events:[...this.spanEvents],status:{...this.status},startTime:this.startTime,endTime:this.endTime,durationMs:this.endTime-this.startTime}}},J=class{spans=[];startSpan(e,t){let n=t?.spanId??`fallback-${crypto.randomUUID()}`,s=t?.traceId??`fallback-${crypto.randomUUID()}`,c=t?.parentSpanId;return new L(e,n,s,c,t?.attributes,o=>{this.spans.push(o.toSpanData());})}clear(){this.spans.length=0;}};function _n(r){let e=r.spanPrefix??"directive.ai",t=r.instrumentEvents,n=r.spanTtlMs??3e5,s=!r.tracer,c=s?new J:null,o=r.tracer??c,u=0;function a(){return `${Date.now().toString(36)}-${(u++).toString(36)}`}function y(){return `${Date.now().toString(36)}-${crypto.randomUUID().slice(0,8)}`}let p=new Map,h=0,m=new Map,l=[],g=null,C=false;function E(i){return t?t.has(i):true}function S(i,v){return `${i}:${v}:${h++}`}function d(i,v){let R=`${i}:${v}`,T=m.get(R);if(T){for(let k=T.length-1;k>=0;k--){let O=p.get(T[k]);if(O)return {key:T[k],entry:O}}m.delete(R);}return null}function f(i,v,R,T){let k=`${i}:${v}`;T.indexKey=k,p.set(R,T);let O=m.get(k);O?O.push(R):m.set(k,[R]);}function b(i){let v=p.get(i);p.delete(i);let R=v?.indexKey;if(R){let T=m.get(R);if(T){let k=T.indexOf(i);k!==-1&&T.splice(k,1),T.length===0&&m.delete(R);}}}function A(){let i=Date.now();if(p.size<1e4){for(let[R,T]of p)i-T.startTime>n&&(I(T,"directive.stale",true),D(T,{code:M.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(T),b(R),true);return void 0}for(let[v,R]of p)i-R.startTime>n&&(I(R,"directive.stale",true),D(R,{code:M.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(R),b(v));}function x(i,v,R){let T=a(),k=R?.traceId??y(),O=R?.spanId,B;s?B=o.startSpan(i,{attributes:v,spanId:T,traceId:k,parentSpanId:O}):B=o.startSpan(i,{attributes:v});let z={span:B,spanId:T,traceId:k,startTime:Date.now()};return s||(z.shadow={span:B,name:i,spanId:T,traceId:k,parentSpanId:O,attributes:{...v},events:[],status:{code:M.UNSET},startTime:z.startTime}),{span:B,entry:z}}function w(i){i.span.end(),r.onSpanEnd&&r.onSpanEnd(P(i));}function P(i){if(i.span instanceof L)return i.span.toSpanData();if(i.shadow){let R=Date.now();return {name:i.shadow.name,traceId:i.shadow.traceId,spanId:i.shadow.spanId,parentSpanId:i.shadow.parentSpanId,attributes:{...i.shadow.attributes},events:[...i.shadow.events],status:{...i.shadow.status},startTime:i.shadow.startTime,endTime:R,durationMs:R-i.shadow.startTime}}let v=Date.now();return {name:"unknown",traceId:i.traceId,spanId:i.spanId,attributes:{},events:[],status:{code:M.UNSET},startTime:i.startTime,endTime:v,durationMs:v-i.startTime}}function I(i,v,R){i.span.setAttribute(v,R),i.shadow&&(i.shadow.attributes[v]=R);}function q(i,v,R){i.span.addEvent(v,R),i.shadow&&i.shadow.events.push({name:v,attributes:R,timestamp:Date.now()});}function D(i,v){i.span.setStatus(v),i.shadow&&(i.shadow.status={...v});}function ue(i){if(E(i.type))switch(A(),i.type){case "agent_start":le(i);break;case "agent_complete":de(i);break;case "agent_error":pe(i);break;case "guardrail_check":ge(i);break;case "constraint_evaluate":me(i);break;case "resolver_start":fe(i);break;case "resolver_complete":ye(i);break;case "resolver_error":he(i);break;case "pattern_start":ve(i);break;case "pattern_complete":Se(i);break;default:if(i.agentId){let v=d("agent",i.agentId);v&&q(v.entry,i.type,{"event.id":i.id,"event.timestamp":i.timestamp});}}}function le(i){let v=l.length>0?l[l.length-1]:null,{entry:R}=x(`${e}.agent.run`,{"directive.service":r.serviceName,"directive.agent.name":i.agentId,"directive.agent.input_length":i.inputLength,"gen_ai.operation.name":"agent.run","gen_ai.agent.name":i.agentId},v),T=S("agent",i.agentId);f("agent",i.agentId,T,R);}function de(i){let v=d("agent",i.agentId);v&&(I(v.entry,"directive.agent.output_length",i.outputLength),I(v.entry,"directive.agent.total_tokens",i.totalTokens),I(v.entry,"directive.agent.duration_ms",i.durationMs),I(v.entry,"gen_ai.usage.total_tokens",i.totalTokens),D(v.entry,{code:M.OK}),w(v.entry),b(v.key));}function pe(i){let v=d("agent",i.agentId);v&&(I(v.entry,"directive.agent.duration_ms",i.durationMs),I(v.entry,"directive.agent.error",i.errorMessage),I(v.entry,"gen_ai.error.message",i.errorMessage),D(v.entry,{code:M.ERROR,message:i.errorMessage}),w(v.entry),b(v.key));}function ge(i){let v=i.agentId?d("agent",i.agentId)?.entry??null:null,{entry:R}=x(`${e}.guardrail.check`,{"directive.service":r.serviceName,"directive.guardrail.name":i.guardrailName,"directive.guardrail.type":i.guardrailType,"directive.guardrail.passed":i.passed,"directive.guardrail.duration_ms":i.durationMs,"gen_ai.guardrail.name":i.guardrailName,"gen_ai.guardrail.type":i.guardrailType,"gen_ai.guardrail.passed":i.passed},v);i.reason&&I(R,"directive.guardrail.reason",i.reason),D(R,{code:i.passed?M.OK:M.ERROR,message:i.passed?void 0:i.reason}),w(R);}function me(i){if(i.agentId){let R=d("agent",i.agentId);if(R){q(R.entry,"constraint_evaluate",{"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired});return}}let{entry:v}=x(`${e}.constraint.evaluate`,{"directive.service":r.serviceName,"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired},null);D(v,{code:M.OK}),w(v);}function fe(i){let R=(i.agentId?d("agent",i.agentId)?.entry??null:null)??(l.length>0?l[l.length-1]:null),{entry:T}=x(`${e}.resolver.execute`,{"directive.service":r.serviceName,"directive.resolver.id":i.resolverId,"directive.resolver.requirement_type":i.requirementType},R),k=S("resolver",i.resolverId);f("resolver",i.resolverId,k,T);}function ye(i){let v=d("resolver",i.resolverId);v&&(I(v.entry,"directive.resolver.duration_ms",i.durationMs),D(v.entry,{code:M.OK}),w(v.entry),b(v.key));}function he(i){let v=d("resolver",i.resolverId);v&&(I(v.entry,"directive.resolver.duration_ms",i.durationMs),I(v.entry,"directive.resolver.error",i.errorMessage),D(v.entry,{code:M.ERROR,message:i.errorMessage}),w(v.entry),b(v.key));}function ve(i){let v=l.length>0?l[l.length-1]:null,{entry:R}=x(`${e}.pattern.${i.patternType}`,{"directive.service":r.serviceName,"directive.pattern.id":i.patternId,"directive.pattern.type":i.patternType},v),T=S("pattern",i.patternId);f("pattern",i.patternId,T,R),l.length<100&&l.push(R);}function Se(i){let v=d("pattern",i.patternId);if(v){I(v.entry,"directive.pattern.duration_ms",i.durationMs),i.error?(I(v.entry,"directive.pattern.error",i.error),D(v.entry,{code:M.ERROR,message:i.error})):D(v.entry,{code:M.OK}),w(v.entry),b(v.key);let R=l.indexOf(v.entry);R!==-1&&l.splice(R,1);}}return {attach(i){if(g&&g!==i)throw new Error("[Directive OTEL] Plugin already attached to a different timeline. Create a new plugin instance.");g=i;let v=i.subscribe(ue),R=setInterval(A,Math.min(n,6e4));return ()=>{v(),clearInterval(R),g=null;for(let[T,k]of p)I(k,"directive.detached",true),D(k,{code:M.ERROR,message:"Plugin detached while span was active"}),w(k);p.clear(),m.clear(),l.length=0;}},getSpans(){return c?[...c.spans]:(C||(C=true,typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[Directive OTEL] getSpans() returns [] when using an external tracer. Use the onSpanEnd callback to collect span data instead.")),[])},clearSpans(){c?.clear();},getTracer(){return o},getActiveSpanCount(){return p.size}}}function Gn(r,e){let{tracer:t,serviceName:n,spanPrefix:s="directive.source",publishSampleRate:c=1}=e,o=new Map;function u(h,m){return `${m}::${h}`}function a(h,m){return {"service.name":n,"source.id":h,"source.module_id":m}}function y(h){switch(h.type){case "source.attach":{let m=h.id,l=h.moduleId,g=t.startSpan(`${s}.attached`,{attributes:{...a(m,l),"directive.attached":true}});o.set(u(m,l),{span:g,startedAt:Date.now()});break}case "source.publish":{if(c<1&&Math.random()>c)break;let m=h.id,l=h.moduleId,g=h.eventName,C=o.get(u(m,l));if(!C)break;C.span.addEvent("publish",{"source.event_name":g,"timestamp.ms":Date.now()});break}case "source.detach":{let m=h.id,l=h.moduleId,g=o.get(u(m,l));if(!g)break;g.span.setStatus({code:M.OK}),g.span.end(),o.delete(u(m,l));break}case "source.error":{let m=h.id,l=h.moduleId,g=h.phase,C=h.error,E=C instanceof Error?C.message:typeof C=="string"?C:String(C),S=t.startSpan(`${s}.error`,{attributes:{...a(m,l),"directive.phase":g,"error.message":E}});S.setStatus({code:M.ERROR,message:E}),S.end();let d=o.get(u(m,l));d&&d.span.addEvent("error",{"directive.phase":g,"error.message":E});break}}}let p=r.observe(y);return ()=>{p();for(let[,h]of o)h.span.setAttribute("directive.detached",true),h.span.setStatus({code:M.OK}),h.span.end();o.clear();}}export{F as AllProvidersFailedError,N as BudgetExceededError,M as OtelStatusCode,G as RetryExhaustedError,Gn as attachSourcesToOtel,Pn as byAgentName,In as byInputLength,Dn as byPattern,on as createAgentAuditHandlers,Vr as createAgentMemory,nn as createAuditTrail,Bn as createBatchQueue,pn as createBidirectionalStream,dn as createCompliance,Nn as createConstraintRouter,Hr as createHybridStrategy,ln as createInMemoryComplianceStorage,bn as createJSONFileStore,Wr as createKeyPointsSummarizer,Jr as createLLMSummarizer,_n as createOtelPlugin,vn as createRAGEnricher,Cn as createSSETransport,X as createSlidingWindowStrategy,K as createStreamChannel,Y as createTokenBasedStrategy,Kr as createTruncationSummarizer,mn as mergeStreams,W as parseHttpStatus,oe as parseRetryAfter,Ur as pipe,gn as pipeThrough,Mn as withBudget,kn as withFallback,On as withModelSelection,wn as withRetry};//# sourceMappingURL=index.js.map
|
|
41
41
|
//# sourceMappingURL=index.js.map
|