@directive-run/ai 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +7 -0
  2. package/dist/anthropic.cjs +2 -3
  3. package/dist/anthropic.cjs.map +1 -1
  4. package/dist/anthropic.d.cts +1 -1
  5. package/dist/anthropic.d.ts +1 -1
  6. package/dist/anthropic.js +2 -3
  7. package/dist/anthropic.js.map +1 -1
  8. package/dist/chunk-265ZKXYE.js +3 -0
  9. package/dist/chunk-265ZKXYE.js.map +1 -0
  10. package/dist/chunk-7EJPXKDP.js +50 -0
  11. package/dist/chunk-7EJPXKDP.js.map +1 -0
  12. package/dist/chunk-B4ATEGA2.cjs +50 -0
  13. package/dist/chunk-B4ATEGA2.cjs.map +1 -0
  14. package/dist/chunk-MNYANBNX.js +14 -0
  15. package/dist/chunk-MNYANBNX.js.map +1 -0
  16. package/dist/chunk-QXMXSHYS.cjs +3 -0
  17. package/dist/chunk-QXMXSHYS.cjs.map +1 -0
  18. package/dist/chunk-W6MVJKWN.cjs +3 -0
  19. package/dist/chunk-W6MVJKWN.cjs.map +1 -0
  20. package/dist/chunk-W6WZBQER.js +3 -0
  21. package/dist/chunk-W6WZBQER.js.map +1 -0
  22. package/dist/chunk-WCJFIC22.cjs +14 -0
  23. package/dist/chunk-WCJFIC22.cjs.map +1 -0
  24. package/dist/gemini.cjs +2 -3
  25. package/dist/gemini.cjs.map +1 -1
  26. package/dist/gemini.d.cts +1 -1
  27. package/dist/gemini.d.ts +1 -1
  28. package/dist/gemini.js +2 -3
  29. package/dist/gemini.js.map +1 -1
  30. package/dist/index.cjs +30 -89
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +194 -27
  33. package/dist/index.d.ts +194 -27
  34. package/dist/index.js +30 -89
  35. package/dist/index.js.map +1 -1
  36. package/dist/multi-agent-orchestrator-FEHVHZXA.js +2 -0
  37. package/dist/multi-agent-orchestrator-FEHVHZXA.js.map +1 -0
  38. package/dist/multi-agent-orchestrator-QWJNM4EZ.cjs +2 -0
  39. package/dist/multi-agent-orchestrator-QWJNM4EZ.cjs.map +1 -0
  40. package/dist/ollama.cjs +2 -2
  41. package/dist/ollama.cjs.map +1 -1
  42. package/dist/ollama.d.cts +1 -1
  43. package/dist/ollama.d.ts +1 -1
  44. package/dist/ollama.js +2 -2
  45. package/dist/ollama.js.map +1 -1
  46. package/dist/openai.cjs +2 -3
  47. package/dist/openai.cjs.map +1 -1
  48. package/dist/openai.d.cts +2 -2
  49. package/dist/openai.d.ts +2 -2
  50. package/dist/openai.js +2 -3
  51. package/dist/openai.js.map +1 -1
  52. package/dist/{multi-agent-orchestrator-DHp8gHXi.d.ts → orchestrator-types-DryFJyW9.d.ts} +6 -142
  53. package/dist/{multi-agent-orchestrator-C3VKkLzg.d.cts → orchestrator-types-tATJCBi5.d.cts} +6 -142
  54. package/dist/{semantic-cache-F0psCRuz.d.cts → semantic-cache-nBpQqILc.d.cts} +5 -5
  55. package/dist/{semantic-cache-F0psCRuz.d.ts → semantic-cache-nBpQqILc.d.ts} +5 -5
  56. package/dist/testing.cjs +1 -48
  57. package/dist/testing.cjs.map +1 -1
  58. package/dist/testing.d.cts +2 -2
  59. package/dist/testing.d.ts +2 -2
  60. package/dist/testing.js +1 -48
  61. package/dist/testing.js.map +1 -1
  62. package/dist/{types-BM-6xZf_.d.cts → types-CRmwFnVk.d.cts} +1 -1
  63. package/dist/{types-BM-6xZf_.d.ts → types-CRmwFnVk.d.ts} +1 -1
  64. package/package.json +3 -3
package/dist/index.d.cts CHANGED
@@ -1,11 +1,11 @@
1
- import { G as GuardrailFn, I as InputGuardrailData, O as OutputGuardrailData, S as SchemaValidator, T as ToolCallGuardrailData, A as AgentLike, M as Message, a as AdapterHooks, b as AgentRunner, c as ApprovalState, d as AgentState, e as AgentSelectionStrategy, D as DagNode, f as DagExecutionContext, g as DagPattern, h as GoalNode, R as RelaxationTier, i as GoalMetrics, P as PatternCheckpointConfig, j as GoalPattern, k as RunResult, l as OrchestratorConstraint, m as RunOptions, n as DebugEvent, B as BreakpointState, o as GoalResult } from './types-BM-6xZf_.cjs';
2
- export { p as AgentCircuitBreakerConfig, q as AgentCompleteEvent, r as AgentErrorEvent, s as AgentHealthState, t as AgentRetryConfig, u as AgentRetryEvent, v as AgentStartEvent, w as ApprovalRequest, x as ApprovalRequestEvent, y as ApprovalResponseEvent, z as BreakpointConfig, C as BreakpointContext, E as BreakpointHitEvent, F as BreakpointModifications, H as BreakpointRequest, J as BreakpointResumedEvent, K as BreakpointState, L as BreakpointType, N as Checkpoint, Q as CheckpointContext, U as CheckpointDiff, V as CheckpointLocalState, W as CheckpointProgress, X as CheckpointRestoreEvent, Y as CheckpointSaveEvent, Z as CheckpointStore, _ as ConstraintEvaluateEvent, $ as CrossAgentDerivationFn, a0 as CrossAgentSnapshot, a1 as DagCheckpointState, a2 as DagNodeStatus, a3 as DagNodeUpdateEvent, a4 as DebateCheckpointState, a5 as DebateRoundEvent, a6 as DebugEventBase, a7 as DebugEventType, a8 as DerivationUpdateEvent, a9 as GoalCheckpointConfig, aa as GoalCheckpointState, ab as GoalStepMetrics, ac as GuardrailCheckEvent, ad as GuardrailContext, ae as GuardrailError, af as GuardrailErrorCode, ag as GuardrailResult, ah as GuardrailRetryConfig, ai as GuardrailsConfig, aj as HandoffCompleteEvent, ak as HandoffStartEvent, al as HealthMonitorConfig, am as InMemoryCheckpointStore, an as InMemoryCheckpointStoreOptions, ao as MAX_BREAKPOINT_HISTORY, ap as MultiAgentBreakpointType, aq as MultiAgentCheckpointLocalState, ar as MultiAgentLifecycleHooks, as as MultiAgentSelfHealingConfig, at as NamedGuardrail, au as OrchestratorDebugConfig, av as OrchestratorLifecycleHooks, aw as OrchestratorResolver, ax as OrchestratorResolverContext, ay as OrchestratorState, az as PatternCheckpointBase, aA as PatternCheckpointState, aB as PatternCompleteEvent, aC as PatternStartEvent, aD as RaceCancelledEvent, aE as RaceStartEvent, aF as RaceWinnerEvent, aG as ReflectCheckpointState, aH as ReflectionIterationEvent, aI as RejectedRequest, aJ as RelaxationContext, aK as RelaxationRecord, aL as RelaxationStrategy, aM as RerouteDebugEvent, aN as RerouteEvent, aO as ResolverCompleteEvent, aP as ResolverErrorEvent, aQ as ResolverStartEvent, aR as SchemaValidationResult, aS as Scratchpad, aT as ScratchpadUpdateEvent, aU as SelfHealingConfig, aV as SequentialCheckpointState, aW as SingleAgentCheckpointLocalState, aX as StreamingCallbackRunner, aY as SupervisorCheckpointState, aZ as TaskCompleteEvent, a_ as TaskErrorEvent, a$ as TaskProgressEvent, b0 as TaskStartEvent, b1 as TokenUsage, b2 as ToolCall, b3 as createBreakpointId, b4 as createCheckpointId, b5 as createInitialBreakpointState, b6 as isGuardrailError, b7 as matchBreakpoint, b8 as validateCheckpoint } from './types-BM-6xZf_.cjs';
3
- import { P as ParallelPattern, R as RacePattern, a as ReflectionEvaluation, b as ReflectIterationRecord, c as ReflectPattern, S as SequentialPattern, d as SupervisorPattern, E as ExecutionPattern, D as DebatePattern, A as AgentRegistry, M as MultiAgentOrchestrator, e as RunAgentRequirement, f as DebateResult, g as AgentHealthMetrics, h as DebugTimeline, H as HealthMonitor } from './multi-agent-orchestrator-C3VKkLzg.cjs';
4
- export { i as AgentMemory, j as AgentMemoryConfig, k as AgentOrchestrator, l as AgentRegistration, B as BackpressureStrategy, m as DebugTimelineListener, n as DebugTimelineOptions, o as DoneChunk, p as ErrorChunk, G as GuardrailTriggeredChunk, q as HandoffRequest, r as HandoffResult, s as HealthCircuitState, t as MemoryManageResult, u as MemoryState, v as MemoryStrategy, w as MemoryStrategyConfig, x as MemoryStrategyResult, y as MergedTaggedStreamResult, z as MessageChunk, C as MessageSummarizer, F as MultiAgentOrchestratorOptions, I as MultiAgentRunCallOptions, J as MultiAgentState, K as MultiplexedStreamChunk, L as MultiplexedStreamResult, O as OrchestratorOptions, N as OrchestratorStreamChunk, Q as OrchestratorStreamResult, T as ProgressChunk, U as RaceResult, V as RaceSuccessEntry, W as ReflectionConfig, X as ReflectionContext, Y as ReflectionEvaluator, Z as ReflectionExhaustedError, _ as RunCallOptions, $ as SafeParseResult, a0 as SafeParseable, a1 as Semaphore, a2 as StreamChunk, a3 as StreamRunOptions, a4 as StreamRunner, a5 as StreamingGuardrail, a6 as StreamingGuardrailResult, a7 as StreamingRunResult, a8 as StructuredOutputConfig, a9 as StructuredOutputError, aa as TaskContext, ab as TaskRegistration, ac as TokenChunk, ad as ToolEndChunk, ae as ToolStartChunk, af as adaptOutputGuardrail, ag as collectTokens, ah as combineStreamingGuardrails, ai as createAgentMemory, aj as createAgentOrchestrator, ak as createDebugTimeline, al as createDebugTimelinePlugin, am as createHealthMonitor, an as createHybridStrategy, ao as createKeyPointsSummarizer, ap as createLLMSummarizer, aq as createLengthStreamingGuardrail, ar as createMultiAgentOrchestrator, as as createPatternStreamingGuardrail, at as createSlidingWindowStrategy, au as createStreamingRunner, av as createTokenBasedStrategy, aw as createToxicityStreamingGuardrail, ax as createTruncationSummarizer, ay as diffCheckpoints, az as extractJsonFromOutput, aA as filterStream, aB as forkFromCheckpoint, aC as getCheckpointProgress, aD as getPatternStep, aE as mapStream, aF as mergeTaggedStreams, aG as tapStream, aH as withReflection, aI as withStructuredOutput } from './multi-agent-orchestrator-C3VKkLzg.cjs';
1
+ import { G as GuardrailFn, I as InputGuardrailData, O as OutputGuardrailData, S as SchemaValidator, T as ToolCallGuardrailData, A as AgentLike, M as Message, a as AdapterHooks, b as AgentRunner, c as ApprovalState, d as AgentState, P as PatternCheckpointState, C as CheckpointDiff, e as CheckpointStore, f as CheckpointProgress, g as AgentSelectionStrategy, D as DagNode, h as DagExecutionContext, i as DagPattern, j as GoalNode, R as RelaxationTier, k as GoalMetrics, l as PatternCheckpointConfig, m as GoalPattern, n as RunResult, o as OrchestratorConstraint, p as RunOptions, q as DebugEvent, B as BreakpointState, r as GoalResult } from './types-CRmwFnVk.cjs';
2
+ export { s as AgentCircuitBreakerConfig, t as AgentCompleteEvent, u as AgentErrorEvent, v as AgentHealthState, w as AgentRetryConfig, x as AgentRetryEvent, y as AgentStartEvent, z as ApprovalRequest, E as ApprovalRequestEvent, F as ApprovalResponseEvent, H as BreakpointConfig, J as BreakpointContext, K as BreakpointHitEvent, L as BreakpointModifications, N as BreakpointRequest, Q as BreakpointResumedEvent, U as BreakpointState, V as BreakpointType, W as Checkpoint, X as CheckpointContext, Y as CheckpointLocalState, Z as CheckpointRestoreEvent, _ as CheckpointSaveEvent, $ as ConstraintEvaluateEvent, a0 as CrossAgentDerivationFn, a1 as CrossAgentSnapshot, a2 as DagCheckpointState, a3 as DagNodeStatus, a4 as DagNodeUpdateEvent, a5 as DebateCheckpointState, a6 as DebateRoundEvent, a7 as DebugEventBase, a8 as DebugEventType, a9 as DerivationUpdateEvent, aa as GoalCheckpointConfig, ab as GoalCheckpointState, ac as GoalStepMetrics, ad as GuardrailCheckEvent, ae as GuardrailContext, af as GuardrailError, ag as GuardrailErrorCode, ah as GuardrailResult, ai as GuardrailRetryConfig, aj as GuardrailsConfig, ak as HandoffCompleteEvent, al as HandoffStartEvent, am as HealthMonitorConfig, an as InMemoryCheckpointStore, ao as InMemoryCheckpointStoreOptions, ap as MAX_BREAKPOINT_HISTORY, aq as MultiAgentBreakpointType, ar as MultiAgentCheckpointLocalState, as as MultiAgentLifecycleHooks, at as MultiAgentSelfHealingConfig, au as NamedGuardrail, av as OrchestratorDebugConfig, aw as OrchestratorLifecycleHooks, ax as OrchestratorResolver, ay as OrchestratorResolverContext, az as OrchestratorState, aA as PatternCheckpointBase, aB as PatternCompleteEvent, aC as PatternStartEvent, aD as RaceCancelledEvent, aE as RaceStartEvent, aF as RaceWinnerEvent, aG as ReflectCheckpointState, aH as ReflectionIterationEvent, aI as RejectedRequest, aJ as RelaxationContext, aK as RelaxationRecord, aL as RelaxationStrategy, aM as RerouteDebugEvent, aN as RerouteEvent, aO as ResolverCompleteEvent, aP as ResolverErrorEvent, aQ as ResolverStartEvent, aR as SchemaValidationResult, aS as Scratchpad, aT as ScratchpadUpdateEvent, aU as SelfHealingConfig, aV as SequentialCheckpointState, aW as SingleAgentCheckpointLocalState, aX as StreamingCallbackRunner, aY as SupervisorCheckpointState, aZ as TaskCompleteEvent, a_ as TaskErrorEvent, a$ as TaskProgressEvent, b0 as TaskStartEvent, b1 as TokenUsage, b2 as ToolCall, b3 as createBreakpointId, b4 as createCheckpointId, b5 as createInitialBreakpointState, b6 as isGuardrailError, b7 as matchBreakpoint, b8 as validateCheckpoint } from './types-CRmwFnVk.cjs';
3
+ import { M as MultiAgentOrchestratorOptions, a as MultiAgentOrchestrator, P as ParallelPattern, R as RacePattern, b as ReflectionEvaluation, c as ReflectIterationRecord, d as ReflectPattern, S as SequentialPattern, e as SupervisorPattern, E as ExecutionPattern, D as DebatePattern, A as AgentRegistry, f as RunAgentRequirement, g as DebateResult, h as AgentHealthMetrics, i as DebugTimeline, H as HealthMonitor } from './orchestrator-types-tATJCBi5.cjs';
4
+ export { j as AgentMemory, k as AgentMemoryConfig, l as AgentOrchestrator, m as AgentRegistration, B as BackpressureStrategy, n as DebugTimelineListener, o as DebugTimelineOptions, p as DoneChunk, q as ErrorChunk, G as GuardrailTriggeredChunk, r as HandoffRequest, s as HandoffResult, t as HealthCircuitState, u as MemoryManageResult, v as MemoryState, w as MemoryStrategy, x as MemoryStrategyConfig, y as MemoryStrategyResult, z as MergedTaggedStreamResult, C as MessageChunk, F as MessageSummarizer, I as MultiAgentRunCallOptions, J as MultiAgentState, K as MultiplexedStreamChunk, L as MultiplexedStreamResult, O as OrchestratorOptions, N as OrchestratorStreamChunk, Q as OrchestratorStreamResult, T as ProgressChunk, U as RaceResult, V as RaceSuccessEntry, W as ReflectionConfig, X as ReflectionContext, Y as ReflectionEvaluator, Z as ReflectionExhaustedError, _ as RunCallOptions, $ as SafeParseResult, a0 as SafeParseable, a1 as StreamChunk, a2 as StreamRunOptions, a3 as StreamRunner, a4 as StreamingGuardrail, a5 as StreamingGuardrailResult, a6 as StreamingRunResult, a7 as StructuredOutputConfig, a8 as StructuredOutputError, a9 as TaskContext, aa as TaskRegistration, ab as TokenChunk, ac as ToolEndChunk, ad as ToolStartChunk, ae as adaptOutputGuardrail, af as collectTokens, ag as combineStreamingGuardrails, ah as createAgentMemory, ai as createAgentOrchestrator, aj as createDebugTimeline, ak as createDebugTimelinePlugin, al as createHealthMonitor, am as createHybridStrategy, an as createKeyPointsSummarizer, ao as createLLMSummarizer, ap as createLengthStreamingGuardrail, aq as createPatternStreamingGuardrail, ar as createSlidingWindowStrategy, as as createStreamingRunner, at as createTokenBasedStrategy, au as createToxicityStreamingGuardrail, av as createTruncationSummarizer, aw as extractJsonFromOutput, ax as filterStream, ay as mapStream, az as mergeTaggedStreams, aA as tapStream, aB as withReflection, aC as withStructuredOutput } from './orchestrator-types-tATJCBi5.cjs';
5
5
  export { AggregatedMetric, AlertConfig, AlertEvent, CircuitBreaker, CircuitBreakerConfig, CircuitBreakerOpenError, CircuitBreakerStats, CircuitState, DashboardData, MetricDataPoint, MetricType, OTLPExporter, OTLPExporterConfig, ObservabilityConfig, ObservabilityInstance, TraceSpan, createCircuitBreaker, createOTLPExporter } from '@directive-run/core/plugins';
6
6
  import { ModuleSchema, Plugin } from '@directive-run/core';
7
- import { E as Embedding, a as EmbedderFn } from './semantic-cache-F0psCRuz.cjs';
8
- export { B as BatchedEmbedder, C as CacheEntry, b as CacheLookupResult, c as CacheStats, S as SemanticCache, d as SemanticCacheConfig, e as SemanticCacheStorage, f as createBatchedEmbedder, g as createInMemoryStorage, h as createSemanticCache, i as createSemanticCacheGuardrail, j as createTestEmbedder } from './semantic-cache-F0psCRuz.cjs';
7
+ import { E as Embedding, a as EmbedderFn } from './semantic-cache-nBpQqILc.cjs';
8
+ export { B as BatchedEmbedder, C as CacheEntry, b as CacheLookupResult, c as CacheStats, S as SemanticCache, d as SemanticCacheConfig, e as SemanticCacheStorage, f as createBatchedEmbedder, g as createInMemoryStorage, h as createSemanticCache, i as createSemanticCacheGuardrail, j as createTestEmbedder } from './semantic-cache-nBpQqILc.cjs';
9
9
 
10
10
  /**
11
11
  * Built-in guardrails for AI adapter — PII, moderation, rate limiting, tool allowlists, schema validation.
@@ -367,6 +367,98 @@ type RunnerMiddleware = (runner: AgentRunner) => AgentRunner;
367
367
  */
368
368
  declare function pipe(runner: AgentRunner, ...middlewares: RunnerMiddleware[]): AgentRunner;
369
369
 
370
+ /**
371
+ * Async semaphore for controlling concurrent access.
372
+ * Uses a queue-based approach instead of polling for efficiency.
373
+ *
374
+ * @example
375
+ * ```typescript
376
+ * import { Semaphore } from '@directive-run/ai';
377
+ *
378
+ * const sem = new Semaphore(3); // Allow 3 concurrent operations
379
+ *
380
+ * async function doWork() {
381
+ * const release = await sem.acquire();
382
+ * try {
383
+ * await performWork();
384
+ * } finally {
385
+ * release();
386
+ * }
387
+ * }
388
+ * ```
389
+ */
390
+ declare class Semaphore {
391
+ private count;
392
+ private readonly maxPermits;
393
+ private readonly queue;
394
+ constructor(max: number);
395
+ /** Create a one-shot release function that guards against double-release */
396
+ private createReleaseFn;
397
+ /** Acquire a permit, optionally with abort signal support */
398
+ acquire(signal?: AbortSignal): Promise<() => void>;
399
+ /** Non-blocking acquire — returns null if no permits available */
400
+ tryAcquire(): (() => void) | null;
401
+ private release;
402
+ /** Get current available permits */
403
+ get available(): number;
404
+ /** Get number of waiters in queue */
405
+ get waiting(): number;
406
+ /** Get maximum permits */
407
+ get max(): number;
408
+ /** Reject all pending waiters with an error and reset permits */
409
+ drain(): void;
410
+ }
411
+ /**
412
+ * Get the current step/round/iteration count from a pattern checkpoint state.
413
+ *
414
+ * Maps each pattern type to its natural progress counter: `step` for sequential
415
+ * and goal, `round` for supervisor and debate, `iteration` for reflect, and
416
+ * `completedCount` for DAG.
417
+ *
418
+ * @param state - The pattern checkpoint state to inspect.
419
+ * @returns The current progress count for the pattern.
420
+ */
421
+ declare function getPatternStep(state: PatternCheckpointState): number;
422
+ /**
423
+ * Compute progress metrics from a pattern checkpoint state.
424
+ *
425
+ * Returns percentage complete, steps completed/remaining, tokens consumed,
426
+ * and estimated tokens remaining (when computable). Each pattern type
427
+ * calculates these metrics from its own state structure.
428
+ *
429
+ * @param state - The pattern checkpoint state to analyze.
430
+ * @returns A {@link CheckpointProgress} object with completion metrics.
431
+ */
432
+ declare function getCheckpointProgress(state: PatternCheckpointState): CheckpointProgress;
433
+ /**
434
+ * Compute the diff between two checkpoint states of the same pattern type.
435
+ *
436
+ * Returns the delta in steps, tokens, and time between checkpoints.
437
+ * Useful for understanding how much progress occurred between saves.
438
+ *
439
+ * @param a - The earlier checkpoint state.
440
+ * @param b - The later checkpoint state.
441
+ * @returns A {@link CheckpointDiff} with step, token, and time deltas.
442
+ * @throws If the two checkpoints have different pattern types.
443
+ */
444
+ declare function diffCheckpoints(a: PatternCheckpointState, b: PatternCheckpointState): CheckpointDiff;
445
+ /**
446
+ * Fork an orchestrator from a checkpoint — creates a new independent orchestrator
447
+ * restored to the checkpoint's state, ready to diverge from that point.
448
+ *
449
+ * @param options - The original orchestrator options used to create the orchestrator
450
+ * @param checkpointStore - The checkpoint store containing the checkpoint
451
+ * @param checkpointId - The ID of the checkpoint to fork from
452
+ * @returns A new independent MultiAgentOrchestrator restored to checkpoint state
453
+ *
454
+ * @example
455
+ * ```typescript
456
+ * const forked = await forkFromCheckpoint(orchestratorOptions, store, "ckpt_abc123");
457
+ * const result = await forked.replay("ckpt_abc123", pattern, { input: "new input" });
458
+ * ```
459
+ */
460
+ declare function forkFromCheckpoint(options: MultiAgentOrchestratorOptions, checkpointStore: CheckpointStore, checkpointId: string): Promise<MultiAgentOrchestrator>;
461
+
370
462
  /**
371
463
  * Create a parallel execution pattern that runs handlers concurrently and merges results.
372
464
  *
@@ -686,8 +778,7 @@ declare function patternToJSON(pattern: ExecutionPattern<unknown>): SerializedPa
686
778
  * @remarks
687
779
  * Returns the data structure with all function fields set to `undefined`.
688
780
  * Supply callbacks via the optional `overrides` parameter to re-attach
689
- * runtime behavior. Handles legacy field migrations (`agent` to `handler`,
690
- * `agents` to `handlers`, `converge` to `goal`).
781
+ * runtime behavior.
691
782
  *
692
783
  * @param json - The serialized pattern from {@link patternToJSON} or persisted storage.
693
784
  * @param overrides - Optional partial pattern to re-attach function callbacks (e.g. `merge`, `extract`).
@@ -1017,6 +1108,82 @@ interface SpawnPoolConfig {
1017
1108
  */
1018
1109
  declare function spawnPool(when: (facts: Record<string, unknown>) => boolean, config: SpawnPoolConfig): OrchestratorConstraint<Record<string, unknown>>;
1019
1110
 
1111
+ /**
1112
+ * Multi-Agent Orchestration Patterns
1113
+ *
1114
+ * Provides patterns for coordinating multiple AI agents:
1115
+ * - Parallel execution with result merging
1116
+ * - Sequential pipelines
1117
+ * - Supervisor patterns with worker delegation
1118
+ * - Constraint-driven agent selection
1119
+ *
1120
+ * @example
1121
+ * ```typescript
1122
+ * import { createMultiAgentOrchestrator } from '@directive-run/ai';
1123
+ *
1124
+ * const orchestrator = createMultiAgentOrchestrator({
1125
+ * agents: {
1126
+ * researcher: { agent: researchAgent, maxConcurrent: 3 },
1127
+ * writer: { agent: writerAgent, maxConcurrent: 1 },
1128
+ * reviewer: { agent: reviewerAgent, maxConcurrent: 1 },
1129
+ * },
1130
+ * patterns: {
1131
+ * parallelResearch: {
1132
+ * type: 'parallel',
1133
+ * handlers: ['researcher', 'researcher', 'researcher'],
1134
+ * merge: (results) => combineResearch(results),
1135
+ * },
1136
+ * },
1137
+ * });
1138
+ * ```
1139
+ */
1140
+
1141
+ /**
1142
+ * Create a multi-agent orchestrator backed by a Directive System.
1143
+ *
1144
+ * Each registered agent becomes a namespaced Directive module with reactive state,
1145
+ * constraint evaluation, guardrails, streaming, approval, memory, retry, budget,
1146
+ * hooks, and time-travel debugging -- all features at parity with {@link createAgentOrchestrator}.
1147
+ *
1148
+ * @param options - Orchestrator configuration including runner, agent registry, patterns, guardrails, and plugins.
1149
+ * @returns A {@link MultiAgentOrchestrator} instance with `runAgent`, `runPattern`, `handoff`, and checkpoint APIs.
1150
+ *
1151
+ * @example
1152
+ * ```typescript
1153
+ * const orchestrator = createMultiAgentOrchestrator({
1154
+ * runner,
1155
+ * agents: {
1156
+ * researcher: { agent: researchAgent, maxConcurrent: 3 },
1157
+ * writer: { agent: writerAgent },
1158
+ * reviewer: { agent: reviewerAgent },
1159
+ * },
1160
+ * guardrails: {
1161
+ * input: [detectPII],
1162
+ * output: [checkToxicity],
1163
+ * },
1164
+ * hooks: {
1165
+ * onAgentStart: ({ agentId, input }) => console.log(`${agentId}: ${input}`),
1166
+ * },
1167
+ * maxTokenBudget: 50000,
1168
+ * debug: true,
1169
+ * });
1170
+ *
1171
+ * // Run with full guardrails + approval + streaming
1172
+ * const result = await orchestrator.runAgent('researcher', 'What is AI?');
1173
+ *
1174
+ * // Stream agent output
1175
+ * const { stream } = orchestrator.runAgentStream('writer', 'Write about AI');
1176
+ * for await (const chunk of stream) {
1177
+ * if (chunk.type === 'token') process.stdout.write(chunk.data);
1178
+ * }
1179
+ * ```
1180
+ *
1181
+ * @throws If a pattern references an agent that is not in the registry
1182
+ * @throws If autoApproveToolCalls is false but no onApprovalRequest callback is provided
1183
+ * @public
1184
+ */
1185
+ declare function createMultiAgentOrchestrator(options: MultiAgentOrchestratorOptions): MultiAgentOrchestrator;
1186
+
1020
1187
  type MermaidDirection = "LR" | "TD" | "TB" | "RL" | "BT";
1021
1188
  interface MermaidNodeShapes {
1022
1189
  /** Shape for agent nodes. @default "square" */
@@ -1218,8 +1385,8 @@ interface MessageBus {
1218
1385
  getPending(agentId: string): TypedAgentMessage[];
1219
1386
  /** Clear all messages and data */
1220
1387
  clear(): void;
1221
- /** Dispose of the message bus, clearing all data and subscriptions */
1222
- dispose(): void;
1388
+ /** Destroy the message bus, clearing all data and subscriptions */
1389
+ destroy(): void;
1223
1390
  }
1224
1391
  /**
1225
1392
  * Create a message bus for agent communication.
@@ -1296,8 +1463,8 @@ interface AgentNetwork {
1296
1463
  listen(agentId: string, handler: MessageHandler, filter?: MessageFilter): Subscription;
1297
1464
  /** Get the message bus */
1298
1465
  getBus(): MessageBus;
1299
- /** Dispose of the network, clearing pending waiters and timers */
1300
- dispose(): void;
1466
+ /** Destroy the network, clearing pending waiters and timers */
1467
+ destroy(): void;
1301
1468
  }
1302
1469
  /**
1303
1470
  * Create an agent network for coordinated communication.
@@ -1352,8 +1519,8 @@ declare function createResponder(network: AgentNetwork, agentId: string): {
1352
1519
  }>): void;
1353
1520
  /** Remove a request handler */
1354
1521
  offRequest(action: string): void;
1355
- /** Dispose of this responder, unsubscribing from network */
1356
- dispose(): void;
1522
+ /** Destroy this responder, unsubscribing from network */
1523
+ destroy(): void;
1357
1524
  };
1358
1525
  /**
1359
1526
  * Create a task delegator for handling incoming delegations.
@@ -1385,8 +1552,8 @@ declare function createDelegator(network: AgentNetwork, agentId: string): {
1385
1552
  }>): void;
1386
1553
  /** Remove the delegation handler */
1387
1554
  offDelegation(): void;
1388
- /** Dispose of this delegator, unsubscribing from network */
1389
- dispose(): void;
1555
+ /** Destroy this delegator, unsubscribing from network */
1556
+ destroy(): void;
1390
1557
  };
1391
1558
  /**
1392
1559
  * Create a pub/sub helper for topic-based communication.
@@ -1407,8 +1574,8 @@ declare function createDelegator(network: AgentNetwork, agentId: string): {
1407
1574
  declare function createPubSub(network: AgentNetwork, agentId: string): {
1408
1575
  subscribe(topics: string[], handler: (topic: string, content: unknown) => void): () => void;
1409
1576
  publish(topic: string, content: unknown): void;
1410
- /** Dispose of this pub/sub, unsubscribing from network and clearing handlers */
1411
- dispose(): void;
1577
+ /** Destroy this pub/sub, unsubscribing from network and clearing handlers */
1578
+ destroy(): void;
1412
1579
  };
1413
1580
 
1414
1581
  /**
@@ -1715,8 +1882,8 @@ interface AuditInstance {
1715
1882
  prune(): number;
1716
1883
  /** Get audit statistics */
1717
1884
  getStats(): AuditStats;
1718
- /** Dispose of the instance (clears timers, flushes exports) */
1719
- dispose(): Promise<void>;
1885
+ /** Destroy the instance (clears timers, flushes exports) */
1886
+ destroy(): Promise<void>;
1720
1887
  /** Create a plugin for a directive system */
1721
1888
  createPlugin<M extends ModuleSchema>(): Plugin<M>;
1722
1889
  /** Add a custom audit entry */
@@ -2494,8 +2661,8 @@ interface RAGStorage {
2494
2661
  }>>;
2495
2662
  /** Reload storage (clear cache, re-read from source) */
2496
2663
  reload?(): Promise<void>;
2497
- /** Dispose of resources */
2498
- dispose?(): void;
2664
+ /** Destroy and release resources */
2665
+ destroy?(): void;
2499
2666
  }
2500
2667
  interface RAGEnricherConfig {
2501
2668
  /** Function to generate query embeddings */
@@ -3059,7 +3226,7 @@ declare function withModelSelection(runner: AgentRunner, configOrRules: ModelSel
3059
3226
  * await queue.flush();
3060
3227
  *
3061
3228
  * // Clean up (flushes remaining calls)
3062
- * await queue.dispose();
3229
+ * await queue.destroy();
3063
3230
  * ```
3064
3231
  */
3065
3232
 
@@ -3078,8 +3245,8 @@ interface BatchQueue {
3078
3245
  flush(): Promise<void>;
3079
3246
  /** Get the number of pending calls. */
3080
3247
  readonly pending: number;
3081
- /** Dispose the queue, flushing remaining calls. */
3082
- dispose(): Promise<void>;
3248
+ /** Destroy the queue, flushing remaining calls. */
3249
+ destroy(): Promise<void>;
3083
3250
  }
3084
3251
  /**
3085
3252
  * Create a batch queue for grouping agent calls.
@@ -3100,7 +3267,7 @@ interface BatchQueue {
3100
3267
  * ]);
3101
3268
  *
3102
3269
  * // Clean up
3103
- * await queue.dispose();
3270
+ * await queue.destroy();
3104
3271
  * ```
3105
3272
  */
3106
3273
  declare function createBatchQueue(runner: AgentRunner, config?: BatchQueueConfig): BatchQueue;
@@ -4722,4 +4889,4 @@ interface OtelPlugin {
4722
4889
  */
4723
4890
  declare function createOtelPlugin(config: OtelPluginConfig): OtelPlugin;
4724
4891
 
4725
- export { type ANNIndex, type ANNSearchResult, AdapterHooks, AgentHealthMetrics, type AgentInfo, AgentLike, type AgentMessage, type AgentMessageType, type AgentNetwork, type AgentNetworkConfig, AgentRegistry, AgentRunner, AgentSelectionStrategy, 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 ConnectDevToolsOptions, type ConstraintRouterConfig, type ConstraintRouterRunner, type CreateRunnerOptions, DEFAULT_INJECTION_PATTERNS, DagExecutionContext, DagNode, DagPattern, type DebateConfig, DebatePattern, DebateResult, DebugEvent, DebugTimeline, type DelegationMessage, type DelegationResultMessage, type DevToolsClient, type DevToolsClientMessage, type DevToolsCompatibleOrchestrator, type DevToolsServer, type DevToolsServerConfig, type DevToolsServerMessage, type DevToolsSnapshot, type DevToolsTransport, EmbedderFn, Embedding, type EnhancedPIIGuardrailOptions, type EvalAgentSummary, type EvalAssertOptions, type EvalCase, type EvalCaseResult, type EvalContext, type EvalCostOptions, type EvalCriterion, type EvalCriterionFn, type EvalJudgeOptions, type EvalLatencyOptions, type EvalMatchOptions, type EvalOutputLengthOptions, type EvalResults, type EvalSafetyOptions, type EvalScore, type EvalSemanticOptions, type EvalStructureOptions, type EvalSuite, type EvalSuiteConfig, ExecutionPattern, type FallbackConfig, type GoalAgentDeclaration, type GoalDependencyEdge, type GoalDependencyGraph, type GoalExecutionPlan, type GoalExplanation, type GoalExplanationStep, GoalMetrics, GoalNode, GoalPattern, type GoalPlanStep, GoalResult, type GoalValidationResult, GuardrailFn, HealthMonitor, type InformMessage, InputGuardrailData, type JSONFileStoreOptions, type MCPAdapter, type MCPAdapterConfig, type MCPApprovalRequest, type MCPCallToolRequirement, type MCPGetPromptRequirement, type MCPReadResourceRequirement, type MCPRequirement, type MCPResource, type MCPServerConfig, type MCPSyncResourcesRequirement, type MCPTool, type MCPToolConstraint, type MCPToolResult, type MermaidDirection, type MermaidNodeShapes, type MermaidOptions, Message, type MessageBus, type MessageBusConfig, type MessageFilter, type MessageHandler, type ModelRule, type ModelSelectionConfig, MultiAgentOrchestrator, OrchestratorConstraint, type OtelPlugin, type OtelPluginConfig, type OtelSpan, OtelStatusCode, type OtelTracer, OutputGuardrailData, ParallelPattern, type ParsedResponse, PatternCheckpointConfig, type PromptInjectionGuardrailOptions, type ProviderStats, type QueryMessage, type RAGChunk, type RAGEnrichOptions, type RAGEnricher, type RAGEnricherConfig, type RAGStorage, RacePattern, type RateLimitGuardrail, ReflectIterationRecord, ReflectPattern, ReflectionEvaluation, RelaxationTier, type RequestMessage, type ResponseMessage, type RetryConfig, RetryExhaustedError, type RoutingConstraint, type RoutingFacts, type RoutingProvider, RunAgentRequirement, RunOptions, RunResult, type RunnerMiddleware, type SSEEvent, type SSETransport, type SSETransportConfig, STRICT_INJECTION_PATTERNS, SchemaValidator, SequentialPattern, type SerializedDagNode, type SerializedGoalNode, type SerializedPattern, type SpanData, type SpawnOnConditionOptions, type SpawnPoolConfig, type StreamChannel, type StreamChannelConfig, type StreamChannelState, type Subscription, SupervisorPattern, type TokenPricing, ToolCallGuardrailData, type TypedAgentMessage, type UpdateMessage, type VPTreeIndexConfig, type WsTransportConfig, aggregateTokens, allReadyStrategy, byAgentName, byInputLength, byPattern, capabilityRoute, collectOutputs, composePatterns, concatResults, connectDevTools, convertToolsForLLM, costEfficientStrategy, createAgentAuditHandlers, createAgentNetwork, createAuditTrail, createBatchQueue, createBidirectionalStream, createBruteForceIndex, createCompliance, createConstraintRouter, createContentFilterGuardrail, createDelegator, createDevToolsServer, createEnhancedPIIGuardrail, createEvalSuite, createInMemoryComplianceStorage, createJSONFileStore, createLengthGuardrail, createMCPAdapter, createMessageBus, createModerationGuardrail, createOtelPlugin, createOutputPIIGuardrail, createOutputSchemaGuardrail, createOutputTypeGuardrail, createPIIGuardrail, createPromptInjectionGuardrail, createPubSub, createRAGEnricher, createRateLimitGuardrail, createResponder, createRunner, createSSETransport, createStreamChannel, createToolGuardrail, createUntrustedContentGuardrail, createVPTreeIndex, createWsTransport, dag, debate, derivedConstraint, detectPII, detectPromptInjection, estimateCost, evalAssert, evalCoherence, evalCost, evalFaithfulness, evalJudge, evalLatency, evalMatch, evalOutputLength, evalRelevance, evalSafety, evalStructure, explainGoal, findAgentsByCapability, getDependencyGraph, goal, hasPendingApprovals, highestImpactStrategy, isAgentRunning, markUntrustedContent, mcpCallTool, mcpGetPrompt, mcpReadResource, mcpSyncResources, mergeStreams, parallel, parseHttpStatus, parseRetryAfter, patternFromJSON, patternToJSON, patternToMermaid, pickBestResult, pipe, pipeThrough, planGoal, race, redactPII, reflect, runAgentRequirement, runDebate, sanitizeInjection, selectAgent, sequential, spawnOnCondition, spawnPool, supervisor, validateBaseURL, validateGoal, withBudget, withFallback, withModelSelection, withRetry };
4892
+ export { type ANNIndex, type ANNSearchResult, AdapterHooks, AgentHealthMetrics, type AgentInfo, AgentLike, type AgentMessage, type AgentMessageType, type AgentNetwork, type AgentNetworkConfig, AgentRegistry, AgentRunner, AgentSelectionStrategy, AgentState, AllProvidersFailedError, ApprovalState, type AuditEventType, type AuditInstance, type AuditPluginConfig, type BatchQueue, type BatchQueueConfig, type BidirectionalStream, type BudgetConfig, type BudgetExceededDetails, BudgetExceededError, type BudgetRunner, type BudgetWindow, CheckpointDiff, CheckpointProgress, CheckpointStore, type ComplianceConfig, type ComplianceInstance, type ComplianceStorage, type ConnectDevToolsOptions, type ConstraintRouterConfig, type ConstraintRouterRunner, type CreateRunnerOptions, DEFAULT_INJECTION_PATTERNS, DagExecutionContext, DagNode, DagPattern, type DebateConfig, DebatePattern, DebateResult, DebugEvent, DebugTimeline, type DelegationMessage, type DelegationResultMessage, type DevToolsClient, type DevToolsClientMessage, type DevToolsCompatibleOrchestrator, type DevToolsServer, type DevToolsServerConfig, type DevToolsServerMessage, type DevToolsSnapshot, type DevToolsTransport, EmbedderFn, Embedding, type EnhancedPIIGuardrailOptions, type EvalAgentSummary, type EvalAssertOptions, type EvalCase, type EvalCaseResult, type EvalContext, type EvalCostOptions, type EvalCriterion, type EvalCriterionFn, type EvalJudgeOptions, type EvalLatencyOptions, type EvalMatchOptions, type EvalOutputLengthOptions, type EvalResults, type EvalSafetyOptions, type EvalScore, type EvalSemanticOptions, type EvalStructureOptions, type EvalSuite, type EvalSuiteConfig, ExecutionPattern, type FallbackConfig, type GoalAgentDeclaration, type GoalDependencyEdge, type GoalDependencyGraph, type GoalExecutionPlan, type GoalExplanation, type GoalExplanationStep, GoalMetrics, GoalNode, GoalPattern, type GoalPlanStep, GoalResult, type GoalValidationResult, GuardrailFn, HealthMonitor, type InformMessage, InputGuardrailData, type JSONFileStoreOptions, type MCPAdapter, type MCPAdapterConfig, type MCPApprovalRequest, type MCPCallToolRequirement, type MCPGetPromptRequirement, type MCPReadResourceRequirement, type MCPRequirement, type MCPResource, type MCPServerConfig, type MCPSyncResourcesRequirement, type MCPTool, type MCPToolConstraint, type MCPToolResult, type MermaidDirection, type MermaidNodeShapes, type MermaidOptions, Message, type MessageBus, type MessageBusConfig, type MessageFilter, type MessageHandler, type ModelRule, type ModelSelectionConfig, MultiAgentOrchestrator, MultiAgentOrchestratorOptions, OrchestratorConstraint, type OtelPlugin, type OtelPluginConfig, type OtelSpan, OtelStatusCode, type OtelTracer, OutputGuardrailData, ParallelPattern, type ParsedResponse, PatternCheckpointConfig, PatternCheckpointState, type PromptInjectionGuardrailOptions, type ProviderStats, type QueryMessage, type RAGChunk, type RAGEnrichOptions, type RAGEnricher, type RAGEnricherConfig, type RAGStorage, RacePattern, type RateLimitGuardrail, ReflectIterationRecord, ReflectPattern, ReflectionEvaluation, RelaxationTier, type RequestMessage, type ResponseMessage, type RetryConfig, RetryExhaustedError, type RoutingConstraint, type RoutingFacts, type RoutingProvider, RunAgentRequirement, RunOptions, RunResult, type RunnerMiddleware, type SSEEvent, type SSETransport, type SSETransportConfig, STRICT_INJECTION_PATTERNS, SchemaValidator, Semaphore, SequentialPattern, type SerializedDagNode, type SerializedGoalNode, type SerializedPattern, type SpanData, type SpawnOnConditionOptions, type SpawnPoolConfig, type StreamChannel, type StreamChannelConfig, type StreamChannelState, type Subscription, SupervisorPattern, type TokenPricing, ToolCallGuardrailData, type TypedAgentMessage, type UpdateMessage, type VPTreeIndexConfig, type WsTransportConfig, aggregateTokens, allReadyStrategy, byAgentName, byInputLength, byPattern, capabilityRoute, collectOutputs, composePatterns, concatResults, connectDevTools, convertToolsForLLM, costEfficientStrategy, createAgentAuditHandlers, createAgentNetwork, createAuditTrail, createBatchQueue, createBidirectionalStream, createBruteForceIndex, createCompliance, createConstraintRouter, createContentFilterGuardrail, createDelegator, createDevToolsServer, createEnhancedPIIGuardrail, createEvalSuite, createInMemoryComplianceStorage, createJSONFileStore, createLengthGuardrail, createMCPAdapter, createMessageBus, createModerationGuardrail, createMultiAgentOrchestrator, createOtelPlugin, createOutputPIIGuardrail, createOutputSchemaGuardrail, createOutputTypeGuardrail, createPIIGuardrail, createPromptInjectionGuardrail, createPubSub, createRAGEnricher, createRateLimitGuardrail, createResponder, createRunner, createSSETransport, createStreamChannel, createToolGuardrail, createUntrustedContentGuardrail, createVPTreeIndex, createWsTransport, dag, debate, derivedConstraint, detectPII, detectPromptInjection, diffCheckpoints, estimateCost, evalAssert, evalCoherence, evalCost, evalFaithfulness, evalJudge, evalLatency, evalMatch, evalOutputLength, evalRelevance, evalSafety, evalStructure, explainGoal, findAgentsByCapability, forkFromCheckpoint, getCheckpointProgress, getDependencyGraph, getPatternStep, goal, hasPendingApprovals, highestImpactStrategy, isAgentRunning, markUntrustedContent, mcpCallTool, mcpGetPrompt, mcpReadResource, mcpSyncResources, mergeStreams, parallel, parseHttpStatus, parseRetryAfter, patternFromJSON, patternToJSON, patternToMermaid, pickBestResult, pipe, pipeThrough, planGoal, race, redactPII, reflect, runAgentRequirement, runDebate, sanitizeInjection, selectAgent, sequential, spawnOnCondition, spawnPool, supervisor, validateBaseURL, validateGoal, withBudget, withFallback, withModelSelection, withRetry };