@directive-run/ai 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { M as Message$1, e as RunResult, A as AgentLike, G as GuardrailFn, O as OutputGuardrailData, aX as StreamingCallbackRunner, D as DebugEvent, a1 as DebugEventType, b as AgentRunner, aw as OrchestratorState, aq as NamedGuardrail, I as InputGuardrailData, C as Checkpoint, u as BreakpointModifications, v as BreakpointRequest, ar as OrchestratorConstraint, au as OrchestratorResolver, af as GuardrailsConfig, o as ApprovalRequest, as as OrchestratorDebugConfig, k as AgentRetryConfig, at as OrchestratorLifecycleHooks, aU as SelfHealingConfig, L as CheckpointStore, r as BreakpointConfig, ai as HealthMonitorConfig, R as RunOptions, T as ToolCallGuardrailData, ay as PatternCheckpointConfig, Z as DagPattern, a7 as GoalPattern, a6 as GoalNode, m as AgentSelectionStrategy, aL as RelaxationTier, f as GoalResult, a4 as GoalCheckpointState, aV as SequentialCheckpointState, aY as SupervisorCheckpointState, aF as ReflectCheckpointState, _ as DebateCheckpointState, U as DagCheckpointState, aS as Scratchpad, ao as MultiAgentLifecycleHooks, ap as MultiAgentSelfHealingConfig, am as MultiAgentBreakpointType, P as CrossAgentDerivationFn, W as DagNode, V as DagExecutionContext, az as PatternCheckpointState, E as CheckpointDiff, H as CheckpointProgress, a5 as GoalMetrics } from './types-Co4BzMiH.js';
1
+ import { M as Message$1, e as RunResult, A as AgentLike, G as GuardrailFn, O as OutputGuardrailData, aX as StreamingCallbackRunner, D as DebugEvent, a1 as DebugEventType, b as AgentRunner, aw as OrchestratorState, aq as NamedGuardrail, I as InputGuardrailData, C as Checkpoint, u as BreakpointModifications, v as BreakpointRequest, ar as OrchestratorConstraint, au as OrchestratorResolver, af as GuardrailsConfig, o as ApprovalRequest, as as OrchestratorDebugConfig, k as AgentRetryConfig, at as OrchestratorLifecycleHooks, aU as SelfHealingConfig, L as CheckpointStore, r as BreakpointConfig, ai as HealthMonitorConfig, R as RunOptions, T as ToolCallGuardrailData, ay as PatternCheckpointConfig, Z as DagPattern, a7 as GoalPattern, a6 as GoalNode, m as AgentSelectionStrategy, aL as RelaxationTier, f as GoalResult, a4 as GoalCheckpointState, aV as SequentialCheckpointState, aY as SupervisorCheckpointState, aF as ReflectCheckpointState, _ as DebateCheckpointState, U as DagCheckpointState, aS as Scratchpad, ao as MultiAgentLifecycleHooks, ap as MultiAgentSelfHealingConfig, am as MultiAgentBreakpointType, P as CrossAgentDerivationFn, W as DagNode, V as DagExecutionContext, az as PatternCheckpointState, E as CheckpointDiff, H as CheckpointProgress, a5 as GoalMetrics } from './types-D5veI9su.js';
2
2
  import { Plugin, System, Requirement } from '@directive-run/core';
3
3
  import { CircuitBreaker } from '@directive-run/core/plugins';
4
4
 
@@ -130,9 +130,13 @@ interface AgentMemory {
130
130
  import(state: MemoryState): void;
131
131
  }
132
132
  /**
133
- * Create a sliding window memory strategy.
133
+ * Create a sliding window memory strategy that keeps the most recent N messages.
134
134
  *
135
- * Keeps the most recent N messages, moving older ones to summarization.
135
+ * Messages beyond `maxMessages` are moved to the summarization queue.
136
+ * The most recent `preserveRecentCount` messages are always kept.
137
+ *
138
+ * @param defaultConfig - Default strategy configuration (can be overridden per-call).
139
+ * @returns A {@link MemoryStrategy} function.
136
140
  *
137
141
  * @example
138
142
  * ```typescript
@@ -141,12 +145,17 @@ interface AgentMemory {
141
145
  * preserveRecentCount: 10,
142
146
  * });
143
147
  * ```
148
+ * @public
144
149
  */
145
150
  declare function createSlidingWindowStrategy(defaultConfig?: MemoryStrategyConfig): MemoryStrategy;
146
151
  /**
147
- * Create a token-based memory strategy.
152
+ * Create a token-based memory strategy that keeps messages until a token limit is reached.
153
+ *
154
+ * Adds messages from newest to oldest until `maxTokens` would be exceeded,
155
+ * then moves the remaining older messages to the summarization queue.
148
156
  *
149
- * Keeps messages until a token limit is reached, then moves older ones to summarization.
157
+ * @param defaultConfig - Default strategy configuration (can be overridden per-call).
158
+ * @returns A {@link MemoryStrategy} function.
150
159
  *
151
160
  * @example
152
161
  * ```typescript
@@ -155,11 +164,18 @@ declare function createSlidingWindowStrategy(defaultConfig?: MemoryStrategyConfi
155
164
  * preserveRecentCount: 5,
156
165
  * });
157
166
  * ```
167
+ * @public
158
168
  */
159
169
  declare function createTokenBasedStrategy(defaultConfig?: MemoryStrategyConfig): MemoryStrategy;
160
170
  /**
161
171
  * Create a hybrid strategy that combines message count and token limits.
162
172
  *
173
+ * Applies both {@link createSlidingWindowStrategy} and {@link createTokenBasedStrategy},
174
+ * then uses whichever result keeps fewer messages (the more restrictive outcome).
175
+ *
176
+ * @param defaultConfig - Default strategy configuration (can be overridden per-call).
177
+ * @returns A {@link MemoryStrategy} function.
178
+ *
163
179
  * @example
164
180
  * ```typescript
165
181
  * const strategy = createHybridStrategy({
@@ -168,10 +184,18 @@ declare function createTokenBasedStrategy(defaultConfig?: MemoryStrategyConfig):
168
184
  * preserveRecentCount: 5,
169
185
  * });
170
186
  * ```
187
+ * @public
171
188
  */
172
189
  declare function createHybridStrategy(defaultConfig?: MemoryStrategyConfig): MemoryStrategy;
173
190
  /**
174
- * Create an agent memory instance.
191
+ * Create an agent memory instance for managing conversation history.
192
+ *
193
+ * Provides sliding window management, automatic summarization of older messages,
194
+ * and import/export for persistence. Pass the returned instance to an orchestrator's
195
+ * `memory` option to auto-inject context and auto-store results.
196
+ *
197
+ * @param config - Memory configuration including strategy, optional summarizer, and auto-manage settings.
198
+ * @returns An {@link AgentMemory} instance with `addMessage`, `getContextMessages`, `manage`, and `export`/`import` APIs.
175
199
  *
176
200
  * @example
177
201
  * ```typescript
@@ -190,20 +214,38 @@ declare function createHybridStrategy(defaultConfig?: MemoryStrategyConfig): Mem
190
214
  * autoManage: true,
191
215
  * });
192
216
  * ```
217
+ * @public
193
218
  */
194
219
  declare function createAgentMemory(config: AgentMemoryConfig): AgentMemory;
195
220
  /**
196
- * Create a simple truncation "summarizer" that just returns key points.
197
- * Useful for testing or when LLM summarization isn't needed.
221
+ * Create a simple truncation summarizer that clips messages to a maximum length.
222
+ *
223
+ * Useful for testing or when LLM-based summarization is not needed.
224
+ * Concatenates non-system messages with role prefixes and truncates to `maxLength`.
225
+ *
226
+ * @param maxLength - Maximum character length of the summary (default: 500).
227
+ * @returns A {@link MessageSummarizer} function.
228
+ * @public
198
229
  */
199
230
  declare function createTruncationSummarizer(maxLength?: number): MessageSummarizer;
200
231
  /**
201
- * Create a summarizer that extracts only user questions and key assistant answers.
232
+ * Create a summarizer that extracts user questions from messages.
233
+ *
234
+ * Scans for sentences ending with `?` in user messages and lists them as key topics.
235
+ *
236
+ * @returns A {@link MessageSummarizer} function.
237
+ * @public
202
238
  */
203
239
  declare function createKeyPointsSummarizer(): MessageSummarizer;
204
240
  /**
205
- * Create a summarizer factory for LLM-based summarization.
206
- * You provide the LLM call function, this handles the prompt.
241
+ * Create a summarizer that delegates to an LLM for conversation compression.
242
+ *
243
+ * You provide the LLM call function; this handles prompt construction
244
+ * including length limits and key-fact preservation instructions.
245
+ *
246
+ * @param llmCall - Async function that sends a prompt to an LLM and returns the response text.
247
+ * @param options - Optional `maxSummaryLength` and `preserveKeyFacts` settings.
248
+ * @returns A {@link MessageSummarizer} function.
207
249
  *
208
250
  * @example
209
251
  * ```typescript
@@ -215,6 +257,7 @@ declare function createKeyPointsSummarizer(): MessageSummarizer;
215
257
  * return response.choices[0].message.content ?? '';
216
258
  * });
217
259
  * ```
260
+ * @public
218
261
  */
219
262
  declare function createLLMSummarizer(llmCall: (prompt: string) => Promise<string>, options?: {
220
263
  maxSummaryLength?: number;
@@ -549,6 +592,12 @@ interface MergedTaggedStreamResult {
549
592
  /** Number of chunks dropped due to buffer overflow */
550
593
  getDroppedCount: () => number;
551
594
  }
595
+ /**
596
+ * Merge multiple tagged async iterables into a single multiplexed stream.
597
+ *
598
+ * @param sources - Array of tagged source streams to merge.
599
+ * @returns A merged stream result with a `getDroppedCount` accessor.
600
+ */
552
601
  declare function mergeTaggedStreams(sources: TaggedSource[]): MergedTaggedStreamResult;
553
602
 
554
603
  /**
@@ -953,11 +1002,19 @@ interface AgentOrchestrator<F extends Record<string, unknown>> {
953
1002
  dispose(): void;
954
1003
  }
955
1004
  /**
956
- * Create a constraint-driven agent orchestrator.
1005
+ * Create a constraint-driven agent orchestrator backed by a Directive System.
1006
+ *
1007
+ * Wraps a single agent runner with reactive state, guardrails, streaming,
1008
+ * approval workflows, breakpoints, structured output, and lifecycle hooks.
1009
+ * Constraints and resolvers let you declaratively control agent behavior
1010
+ * based on runtime facts.
1011
+ *
1012
+ * @param options - Orchestrator configuration including runner, guardrails, constraints, and plugins.
1013
+ * @returns An {@link AgentOrchestrator} instance with `run`, `runStream`, `approve`/`reject`, and checkpoint APIs.
957
1014
  *
958
1015
  * @example
959
1016
  * ```typescript
960
- * import { run as runner } from '@openai/agents'
1017
+ * import { run as runner } from '@openai/agents';
961
1018
  *
962
1019
  * const orchestrator = createAgentOrchestrator({
963
1020
  * runner,
@@ -994,10 +1051,63 @@ interface AgentOrchestrator<F extends Record<string, unknown>> {
994
1051
  * const result = await orchestrator.run(myAgent, 'Hello, can you help me?');
995
1052
  * ```
996
1053
  *
997
- * @throws {Error} If autoApproveToolCalls is false but no onApprovalRequest callback is provided
1054
+ * @throws If autoApproveToolCalls is false but no onApprovalRequest callback is provided
1055
+ * @public
998
1056
  */
999
1057
  declare function createAgentOrchestrator<F extends Record<string, unknown> = Record<string, never>>(options: OrchestratorOptions<F>): AgentOrchestrator<F>;
1000
1058
 
1059
+ /**
1060
+ * Health Monitor — tracks per-agent health metrics for self-healing networks.
1061
+ *
1062
+ * Pure computation module with zero Directive dependency.
1063
+ * Maintains a rolling window of success/failure events and computes a health
1064
+ * score from 0-100 based on configurable weights.
1065
+ *
1066
+ * @module
1067
+ */
1068
+
1069
+ /** Circuit state values */
1070
+ type HealthCircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
1071
+ /** Per-agent health metrics */
1072
+ interface AgentHealthMetrics {
1073
+ agentId: string;
1074
+ circuitState: HealthCircuitState;
1075
+ successRate: number;
1076
+ avgLatencyMs: number;
1077
+ recentFailures: number;
1078
+ recentSuccesses: number;
1079
+ healthScore: number;
1080
+ /** Last N error messages (most recent last) */
1081
+ lastErrors: string[];
1082
+ }
1083
+ /** Health monitor instance */
1084
+ interface HealthMonitor {
1085
+ recordSuccess(agentId: string, latencyMs: number): void;
1086
+ recordFailure(agentId: string, latencyMs: number, error?: Error): void;
1087
+ getMetrics(agentId: string): AgentHealthMetrics;
1088
+ getAllMetrics(): Record<string, AgentHealthMetrics>;
1089
+ /** Returns a 0-100 health score. Returns 50 (neutral) when no data is available for the agent. */
1090
+ getHealthScore(agentId: string): number;
1091
+ updateCircuitState(agentId: string, state: HealthCircuitState): void;
1092
+ /** Reset all metrics. Useful for testing. */
1093
+ reset(): void;
1094
+ }
1095
+ /**
1096
+ * Create a health monitor that tracks per-agent metrics.
1097
+ *
1098
+ * @example
1099
+ * ```typescript
1100
+ * const monitor = createHealthMonitor({ windowMs: 30000 });
1101
+ *
1102
+ * monitor.recordSuccess("agent-a", 120);
1103
+ * monitor.recordFailure("agent-a", 5000, new Error("timeout"));
1104
+ *
1105
+ * const score = monitor.getHealthScore("agent-a");
1106
+ * console.log(score); // 0-100
1107
+ * ```
1108
+ */
1109
+ declare function createHealthMonitor(config?: HealthMonitorConfig): HealthMonitor;
1110
+
1001
1111
  /**
1002
1112
  * Agent Reflection / Self-Improvement
1003
1113
  *
@@ -1099,62 +1209,38 @@ declare class ReflectionExhaustedError extends Error {
1099
1209
  declare function withReflection<T = unknown>(runner: AgentRunner, config: ReflectionConfig<T>): AgentRunner;
1100
1210
 
1101
1211
  /**
1102
- * Health Monitor tracks per-agent health metrics for self-healing networks.
1212
+ * Get the current step/round/iteration count from a pattern checkpoint state.
1103
1213
  *
1104
- * Pure computation module with zero Directive dependency.
1105
- * Maintains a rolling window of success/failure events and computes a health
1106
- * score from 0-100 based on configurable weights.
1214
+ * Maps each pattern type to its natural progress counter: `step` for sequential
1215
+ * and goal, `round` for supervisor and debate, `iteration` for reflect, and
1216
+ * `completedCount` for DAG.
1107
1217
  *
1108
- * @module
1218
+ * @param state - The pattern checkpoint state to inspect.
1219
+ * @returns The current progress count for the pattern.
1109
1220
  */
1110
-
1111
- /** Circuit state values */
1112
- type HealthCircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
1113
- /** Per-agent health metrics */
1114
- interface AgentHealthMetrics {
1115
- agentId: string;
1116
- circuitState: HealthCircuitState;
1117
- successRate: number;
1118
- avgLatencyMs: number;
1119
- recentFailures: number;
1120
- recentSuccesses: number;
1121
- healthScore: number;
1122
- /** Last N error messages (most recent last) */
1123
- lastErrors: string[];
1124
- }
1125
- /** Health monitor instance */
1126
- interface HealthMonitor {
1127
- recordSuccess(agentId: string, latencyMs: number): void;
1128
- recordFailure(agentId: string, latencyMs: number, error?: Error): void;
1129
- getMetrics(agentId: string): AgentHealthMetrics;
1130
- getAllMetrics(): Record<string, AgentHealthMetrics>;
1131
- /** Returns a 0-100 health score. Returns 50 (neutral) when no data is available for the agent. */
1132
- getHealthScore(agentId: string): number;
1133
- updateCircuitState(agentId: string, state: HealthCircuitState): void;
1134
- /** Reset all metrics. Useful for testing. */
1135
- reset(): void;
1136
- }
1221
+ declare function getPatternStep(state: PatternCheckpointState): number;
1137
1222
  /**
1138
- * Create a health monitor that tracks per-agent metrics.
1139
- *
1140
- * @example
1141
- * ```typescript
1142
- * const monitor = createHealthMonitor({ windowMs: 30000 });
1223
+ * Compute progress metrics from a pattern checkpoint state.
1143
1224
  *
1144
- * monitor.recordSuccess("agent-a", 120);
1145
- * monitor.recordFailure("agent-a", 5000, new Error("timeout"));
1225
+ * Returns percentage complete, steps completed/remaining, tokens consumed,
1226
+ * and estimated tokens remaining (when computable). Each pattern type
1227
+ * calculates these metrics from its own state structure.
1146
1228
  *
1147
- * const score = monitor.getHealthScore("agent-a");
1148
- * console.log(score); // 0-100
1149
- * ```
1229
+ * @param state - The pattern checkpoint state to analyze.
1230
+ * @returns A {@link CheckpointProgress} object with completion metrics.
1150
1231
  */
1151
- declare function createHealthMonitor(config?: HealthMonitorConfig): HealthMonitor;
1152
-
1153
- /** Get the current step/round/iteration count from a pattern checkpoint state */
1154
- declare function getPatternStep(state: PatternCheckpointState): number;
1155
- /** Compute progress from a pattern checkpoint state */
1156
1232
  declare function getCheckpointProgress(state: PatternCheckpointState): CheckpointProgress;
1157
- /** Compute the diff between two checkpoint states */
1233
+ /**
1234
+ * Compute the diff between two checkpoint states of the same pattern type.
1235
+ *
1236
+ * Returns the delta in steps, tokens, and time between checkpoints.
1237
+ * Useful for understanding how much progress occurred between saves.
1238
+ *
1239
+ * @param a - The earlier checkpoint state.
1240
+ * @param b - The later checkpoint state.
1241
+ * @returns A {@link CheckpointDiff} with step, token, and time deltas.
1242
+ * @throws If the two checkpoints have different pattern types.
1243
+ */
1158
1244
  declare function diffCheckpoints(a: PatternCheckpointState, b: PatternCheckpointState): CheckpointDiff;
1159
1245
  /**
1160
1246
  * Fork an orchestrator from a checkpoint — creates a new independent orchestrator
@@ -1256,25 +1342,25 @@ interface AgentRegistration {
1256
1342
  interface AgentRegistry {
1257
1343
  [agentId: string]: AgentRegistration;
1258
1344
  }
1259
- /** Parallel execution pattern - run agents concurrently and merge results */
1345
+ /** Parallel execution pattern - run handlers concurrently and merge results */
1260
1346
  interface ParallelPattern<T = unknown> {
1261
1347
  type: "parallel";
1262
- /** Agent IDs to run in parallel (can repeat for multiple instances) */
1263
- agents: string[];
1264
- /** Function to merge results from all agents */
1348
+ /** Handler IDs (agents or tasks) to run in parallel (can repeat for multiple instances) */
1349
+ handlers: string[];
1350
+ /** Function to merge results from all handlers */
1265
1351
  merge: (results: RunResult<unknown>[]) => T | Promise<T>;
1266
- /** Minimum successful results required. @default agents.length */
1352
+ /** Minimum successful results required. @default handlers.length */
1267
1353
  minSuccess?: number;
1268
1354
  /** Overall timeout (ms) */
1269
1355
  timeout?: number;
1270
1356
  }
1271
- /** Sequential execution pattern - pipeline of agents */
1357
+ /** Sequential execution pattern - pipeline of handlers */
1272
1358
  interface SequentialPattern<T = unknown> {
1273
1359
  type: "sequential";
1274
- /** Agent IDs in execution order */
1275
- agents: string[];
1360
+ /** Handler IDs (agents or tasks) in execution order */
1361
+ handlers: string[];
1276
1362
  /** Transform output to next input. @default JSON.stringify */
1277
- transform?: (output: unknown, agentId: string, index: number) => string;
1363
+ transform?: (output: unknown, handlerId: string, index: number) => string;
1278
1364
  /** Final result extractor */
1279
1365
  extract?: (output: unknown) => T;
1280
1366
  /** Continue on error. @default false */
@@ -1313,8 +1399,8 @@ interface ReflectIterationRecord {
1313
1399
  */
1314
1400
  interface ReflectPattern<T = unknown> {
1315
1401
  type: "reflect";
1316
- /** Producer agent ID */
1317
- agent: string;
1402
+ /** Producer handler ID (agent or task) */
1403
+ handler: string;
1318
1404
  /** Evaluator agent ID (receives output as input) */
1319
1405
  evaluator: string;
1320
1406
  /** Maximum iterations. @default 2 */
@@ -1345,8 +1431,8 @@ interface ReflectPattern<T = unknown> {
1345
1431
  */
1346
1432
  interface RacePattern<T = unknown> {
1347
1433
  type: "race";
1348
- /** Agent IDs to race */
1349
- agents: string[];
1434
+ /** Handler IDs (agents or tasks) to race */
1435
+ handlers: string[];
1350
1436
  /** Extract result from winning RunResult (receives full RunResult for access to tokens/metadata). @default output field */
1351
1437
  extract?: (result: RunResult<unknown>) => T;
1352
1438
  /** Overall timeout (ms) */
@@ -1391,8 +1477,8 @@ interface RaceResult<T = unknown> {
1391
1477
  */
1392
1478
  interface DebatePattern<T = unknown> {
1393
1479
  type: "debate";
1394
- /** Agent IDs that will generate competing proposals */
1395
- agents: string[];
1480
+ /** Handler IDs (agents or tasks) that will generate competing proposals */
1481
+ handlers: string[];
1396
1482
  /** Evaluator agent ID that judges proposals */
1397
1483
  evaluator: string;
1398
1484
  /** Maximum rounds of debate. @default 2 */
@@ -1437,12 +1523,57 @@ interface RunAgentRequirement extends Requirement {
1437
1523
  input: string;
1438
1524
  context?: Record<string, unknown>;
1439
1525
  }
1526
+ /** Read-only context passed to task functions */
1527
+ interface TaskContext {
1528
+ /** The ID of this task */
1529
+ taskId: string;
1530
+ /** Conversation history from orchestrator memory (read-only deep copy) */
1531
+ memory: ReadonlyArray<{
1532
+ role: string;
1533
+ content: string;
1534
+ }>;
1535
+ /** Current scratchpad state (read-only deep copy) */
1536
+ scratchpad: Readonly<Record<string, unknown>>;
1537
+ /** Read the state of any registered agent or task (status, lastOutput, lastError, totalTokens) */
1538
+ readAgentState: (nodeId: string) => Readonly<{
1539
+ status: string;
1540
+ lastOutput?: string;
1541
+ lastError?: string;
1542
+ totalTokens: number;
1543
+ }> | undefined;
1544
+ /** Report intermediate progress (0-100) for DevTools timeline */
1545
+ reportProgress: (percent: number, message?: string) => void;
1546
+ }
1547
+ /** Configuration for a registered task (imperative code) */
1548
+ interface TaskRegistration {
1549
+ /** The function to execute. Receives input, abort signal, and context. */
1550
+ run: (input: string, signal: AbortSignal, context: TaskContext) => unknown | Promise<unknown>;
1551
+ /** Display label for DevTools graph. Defaults to task ID. */
1552
+ label?: string;
1553
+ /** Description for DevTools tooltip/detail panel. */
1554
+ description?: string;
1555
+ /** Timeout (ms) */
1556
+ timeout?: number;
1557
+ /** Max concurrent executions of this task. @default 1 */
1558
+ maxConcurrent?: number;
1559
+ /** Optional retry configuration for transient failures */
1560
+ retry?: {
1561
+ /** Max number of attempts (including the first try) */
1562
+ attempts: number;
1563
+ /** Backoff strategy between retries. @default 'fixed' */
1564
+ backoff?: "fixed" | "exponential";
1565
+ /** Base delay between retries (ms). @default 1000 */
1566
+ delayMs?: number;
1567
+ };
1568
+ }
1440
1569
  /** Multi-agent orchestrator options */
1441
1570
  interface MultiAgentOrchestratorOptions {
1442
1571
  /** Base run function */
1443
1572
  runner: AgentRunner;
1444
1573
  /** Registered agents */
1445
1574
  agents: AgentRegistry;
1575
+ /** Imperative code tasks, referenced by ID in patterns (same namespace as agents) */
1576
+ tasks?: Record<string, TaskRegistration>;
1446
1577
  /** Execution patterns */
1447
1578
  patterns?: Record<string, ExecutionPattern>;
1448
1579
  /** Handoff callbacks */
@@ -1524,6 +1655,8 @@ interface MultiAgentRunCallOptions extends RunOptions {
1524
1655
  outputSchema?: SafeParseable<unknown> | null;
1525
1656
  /** Override max schema retries for this call. */
1526
1657
  maxSchemaRetries?: number;
1658
+ /** Pattern ID that initiated this run (for lifecycle hooks). Set internally by pattern executors. */
1659
+ patternId?: string;
1527
1660
  }
1528
1661
  /** Multi-agent orchestrator instance */
1529
1662
  interface MultiAgentOrchestrator {
@@ -1579,6 +1712,35 @@ interface MultiAgentOrchestrator {
1579
1712
  unregisterAgent(agentId: string): void;
1580
1713
  /** Get registered agent IDs */
1581
1714
  getAgentIds(): string[];
1715
+ /** Register a new task dynamically */
1716
+ registerTask(taskId: string, registration: TaskRegistration): void;
1717
+ /** Unregister a task */
1718
+ unregisterTask(taskId: string): void;
1719
+ /** Get registered task IDs */
1720
+ getTaskIds(): string[];
1721
+ /** Get task registry info (labels + descriptions) */
1722
+ getTaskRegistry(): Record<string, {
1723
+ label?: string;
1724
+ description?: string;
1725
+ }>;
1726
+ /** Get task state */
1727
+ getTaskState(taskId: string): {
1728
+ status: string;
1729
+ lastOutput?: unknown;
1730
+ lastError?: string;
1731
+ startTime?: number;
1732
+ durationMs?: number;
1733
+ } | undefined;
1734
+ /** Get all task states */
1735
+ getAllTaskStates(): Record<string, {
1736
+ status: string;
1737
+ lastOutput?: unknown;
1738
+ lastError?: string;
1739
+ startTime?: number;
1740
+ durationMs?: number;
1741
+ }>;
1742
+ /** Get all handler IDs (agents + tasks combined) */
1743
+ getNodeIds(): string[];
1582
1744
  /** Get agent state */
1583
1745
  getAgentState(agentId: string): MultiAgentState["__agents"][string] | undefined;
1584
1746
  /** Get all agent states */
@@ -1684,7 +1846,6 @@ interface MultiAgentOrchestrator {
1684
1846
  }): Promise<T>;
1685
1847
  /**
1686
1848
  * Get reflection iteration history from last runReflectPattern call.
1687
- * @deprecated Use the `history` field on the return value from `runReflect()` instead.
1688
1849
  */
1689
1850
  getLastReflectionHistory(): ReflectIterationRecord[] | null;
1690
1851
  /** Cross-agent derived values (frozen snapshot). Empty when derive not configured. */
@@ -1701,7 +1862,10 @@ interface MultiAgentOrchestrator {
1701
1862
  *
1702
1863
  * Each registered agent becomes a namespaced Directive module with reactive state,
1703
1864
  * constraint evaluation, guardrails, streaming, approval, memory, retry, budget,
1704
- * hooks, and time-travel debugging all features at parity with `createAgentOrchestrator`.
1865
+ * hooks, and time-travel debugging -- all features at parity with {@link createAgentOrchestrator}.
1866
+ *
1867
+ * @param options - Orchestrator configuration including runner, agent registry, patterns, guardrails, and plugins.
1868
+ * @returns A {@link MultiAgentOrchestrator} instance with `runAgent`, `runPattern`, `handoff`, and checkpoint APIs.
1705
1869
  *
1706
1870
  * @example
1707
1871
  * ```typescript
@@ -1733,62 +1897,68 @@ interface MultiAgentOrchestrator {
1733
1897
  * }
1734
1898
  * ```
1735
1899
  *
1736
- * @throws {Error} If a pattern references an agent that is not in the registry
1737
- * @throws {Error} If autoApproveToolCalls is false but no onApprovalRequest callback is provided
1900
+ * @throws If a pattern references an agent that is not in the registry
1901
+ * @throws If autoApproveToolCalls is false but no onApprovalRequest callback is provided
1902
+ * @public
1738
1903
  */
1739
1904
  declare function createMultiAgentOrchestrator(options: MultiAgentOrchestratorOptions): MultiAgentOrchestrator;
1740
1905
  /**
1741
- * Create a parallel pattern configuration.
1906
+ * Create a parallel execution pattern that runs handlers concurrently and merges results.
1742
1907
  *
1743
- * @param agents - Agent IDs to run concurrently
1744
- * @param merge - Combine all agent results into a single output
1745
- * @param config.merge - Receives all successful RunResults (array may be shorter than agents.length when minSuccess is set). Returns the merged result.
1746
- * @param options - Optional `minSuccess` and `timeout` overrides
1908
+ * @param handlers - Handler IDs (agents or tasks) to run concurrently.
1909
+ * @param merge - Combine all handler results into a single output (array may be shorter than handlers when `minSuccess` is set).
1910
+ * @param options - Optional `minSuccess` and `timeout` overrides.
1911
+ * @returns A {@link ParallelPattern} configuration object.
1747
1912
  *
1748
1913
  * @example
1749
1914
  * ```typescript
1750
1915
  * const researchPattern = parallel(
1751
1916
  * ['researcher', 'researcher', 'researcher'],
1752
- * (results) => results.map(r => r.output).join('\n')
1917
+ * (results) => results.map(r => r.output).join('\n'),
1753
1918
  * );
1754
1919
  * ```
1755
1920
  */
1756
- declare function parallel<T>(agents: string[], merge: (results: RunResult<unknown>[]) => T | Promise<T>, options?: {
1921
+ declare function parallel<T>(handlers: string[], merge: (results: RunResult<unknown>[]) => T | Promise<T>, options?: {
1757
1922
  minSuccess?: number;
1758
1923
  timeout?: number;
1759
1924
  }): ParallelPattern<T>;
1760
1925
  /**
1761
- * Create a sequential pattern configuration.
1926
+ * Create a sequential execution pattern that pipes output from one handler to the next.
1762
1927
  *
1763
- * @param agents - Agent IDs to run in order (output of each feeds into the next)
1764
- * @param options - Optional `transform`, `extract`, `continueOnError`
1928
+ * @param handlers - Handler IDs (agents or tasks) to run in order, where each handler's output feeds as input to the next.
1929
+ * @param options - Optional `transform`, `extract`, and `continueOnError` overrides.
1930
+ * @returns A {@link SequentialPattern} configuration object.
1765
1931
  *
1766
1932
  * @example
1767
1933
  * ```typescript
1768
1934
  * const writeReviewPattern = sequential(
1769
1935
  * ['writer', 'reviewer'],
1770
- * { transform: (output) => `Review this: ${output}` }
1936
+ * { transform: (output) => `Review this: ${output}` },
1771
1937
  * );
1772
1938
  * ```
1773
1939
  */
1774
- declare function sequential<T>(agents: string[], options?: {
1775
- transform?: (output: unknown, agentId: string, index: number) => string;
1940
+ declare function sequential<T>(handlers: string[], options?: {
1941
+ transform?: (output: unknown, handlerId: string, index: number) => string;
1776
1942
  extract?: (output: unknown) => T;
1777
1943
  continueOnError?: boolean;
1778
1944
  }): SequentialPattern<T>;
1779
1945
  /**
1780
- * Create a supervisor pattern configuration.
1946
+ * Create a supervisor pattern where a coordinating agent delegates work to a pool of workers.
1947
+ *
1948
+ * The supervisor runs first, then dispatches tasks to workers based on its output.
1949
+ * This repeats for up to `maxRounds` until the supervisor signals completion.
1781
1950
  *
1782
- * @param supervisorAgent - Agent ID that coordinates the workers
1783
- * @param workers - Agent IDs for the worker pool
1784
- * @param options - Optional `maxRounds` and `extract`
1951
+ * @param supervisorAgent - Agent ID that coordinates the workers.
1952
+ * @param workers - Agent IDs for the worker pool.
1953
+ * @param options - Optional `maxRounds` and `extract` overrides.
1954
+ * @returns A {@link SupervisorPattern} configuration object.
1785
1955
  *
1786
1956
  * @example
1787
1957
  * ```typescript
1788
1958
  * const managedPattern = supervisor(
1789
1959
  * 'manager',
1790
1960
  * ['worker1', 'worker2'],
1791
- * { maxRounds: 3 }
1961
+ * { maxRounds: 3 },
1792
1962
  * );
1793
1963
  * ```
1794
1964
  */
@@ -1797,19 +1967,23 @@ declare function supervisor<T>(supervisorAgent: string, workers: string[], optio
1797
1967
  extract?: (supervisorOutput: unknown, workerResults: RunResult<unknown>[]) => T;
1798
1968
  }): SupervisorPattern<T>;
1799
1969
  /**
1800
- * Create a DAG execution pattern.
1970
+ * Create a directed acyclic graph (DAG) execution pattern.
1801
1971
  *
1802
- * @param nodes - Node definitions keyed by ID, each with `agent` and optional `deps`
1803
- * @param merge - Combine DAG outputs into a single result (defaults to `context.outputs`)
1804
- * @param options - Optional `timeout`, `maxConcurrent`, `onNodeError`
1972
+ * Nodes run concurrently when their dependencies are satisfied. The runtime
1973
+ * validates the graph is acyclic and that all dependency references are valid.
1974
+ *
1975
+ * @param nodes - Node definitions keyed by ID, each with a `handler` and optional `deps` array.
1976
+ * @param merge - Combine DAG outputs into a single result (defaults to `context.outputs`).
1977
+ * @param options - Optional `timeout`, `maxConcurrent`, and `onNodeError` strategy.
1978
+ * @returns A {@link DagPattern} configuration object.
1805
1979
  *
1806
1980
  * @example
1807
1981
  * ```typescript
1808
1982
  * const researchPipeline = dag(
1809
1983
  * {
1810
- * fetch: { agent: 'fetcher' },
1811
- * analyze: { agent: 'analyzer', deps: ['fetch'] },
1812
- * summarize: { agent: 'summarizer', deps: ['analyze'] },
1984
+ * fetch: { handler: 'fetcher' },
1985
+ * analyze: { handler: 'analyzer', deps: ['fetch'] },
1986
+ * summarize: { handler: 'summarizer', deps: ['analyze'] },
1813
1987
  * },
1814
1988
  * (context) => context.outputs.summarize,
1815
1989
  * );
@@ -1829,18 +2003,23 @@ declare function dag<T = Record<string, unknown>>(nodes: Record<string, DagNode>
1829
2003
  onNodeError?: "fail" | "skip-downstream" | "continue";
1830
2004
  }): DagPattern<T>;
1831
2005
  /**
1832
- * Create a reflect pattern configuration.
2006
+ * Create a reflect pattern that iterates between a producer and evaluator until quality is met.
2007
+ *
2008
+ * The producer generates output, then the evaluator scores it. If the score
2009
+ * is below the threshold, the producer retries with evaluator feedback,
2010
+ * up to `maxIterations` times.
1833
2011
  *
1834
- * @param agent - Producer agent ID that generates output
1835
- * @param evaluator - Evaluator agent ID that judges quality
1836
- * @param options - Optional iteration, parsing, signal, and threshold config
2012
+ * @param handler - Producer handler ID (agent or task) that generates output.
2013
+ * @param evaluator - Evaluator handler ID that judges quality and provides feedback.
2014
+ * @param options - Optional iteration, parsing, signal, and threshold configuration.
2015
+ * @returns A {@link ReflectPattern} configuration object.
1837
2016
  *
1838
2017
  * @example
1839
2018
  * ```typescript
1840
2019
  * const reviewPattern = reflect('writer', 'reviewer', { maxIterations: 2 });
1841
2020
  * ```
1842
2021
  */
1843
- declare function reflect<T>(agent: string, evaluator: string, options?: {
2022
+ declare function reflect<T>(handler: string, evaluator: string, options?: {
1844
2023
  maxIterations?: number;
1845
2024
  parseEvaluation?: (output: unknown) => ReflectionEvaluation;
1846
2025
  buildRetryInput?: (input: string, feedback: string, iteration: number) => string;
@@ -1852,41 +2031,51 @@ declare function reflect<T>(agent: string, evaluator: string, options?: {
1852
2031
  threshold?: number | ((iteration: number) => number);
1853
2032
  }): ReflectPattern<T>;
1854
2033
  /**
1855
- * Create a race pattern configuration.
2034
+ * Create a race pattern that runs handlers concurrently and returns the first successful result.
1856
2035
  *
1857
- * @param agents - Agent IDs to race concurrently
1858
- * @param options - Optional `extract`, `timeout`, `minSuccess`, `signal`
2036
+ * All handlers start simultaneously. The first to complete successfully wins;
2037
+ * remaining handlers are aborted. Use `minSuccess` to wait for N results before picking.
2038
+ *
2039
+ * @param handlers - Handler IDs (agents or tasks) to race concurrently.
2040
+ * @param options - Optional `extract`, `timeout`, `minSuccess`, and `signal` overrides.
2041
+ * @returns A {@link RacePattern} configuration object.
1859
2042
  *
1860
2043
  * @example
1861
2044
  * ```typescript
1862
2045
  * const fastest = race(['fast-model', 'smart-model'], { timeout: 5000 });
1863
2046
  * ```
1864
2047
  */
1865
- declare function race<T>(agents: string[], options?: {
2048
+ declare function race<T>(handlers: string[], options?: {
1866
2049
  extract?: (result: RunResult<unknown>) => T;
1867
2050
  timeout?: number;
1868
2051
  minSuccess?: number;
1869
2052
  signal?: AbortSignal;
1870
2053
  }): RacePattern<T>;
1871
2054
  /**
1872
- * Create a goal execution pattern.
2055
+ * Create a goal-driven execution pattern where agents are selected and run
2056
+ * until a goal condition is satisfied.
1873
2057
  *
1874
2058
  * Declare what each agent produces and requires. The runtime automatically
1875
2059
  * infers the execution graph from dependency analysis and drives agents
1876
- * to goal achievement.
2060
+ * toward goal achievement, with optional satisfaction scoring and relaxation tiers.
2061
+ *
2062
+ * @param nodes - Goal node definitions keyed by ID, each declaring `produces`, `requires`, and a `handler`.
2063
+ * @param when - Predicate that returns `true` when the goal is achieved.
2064
+ * @param options - Optional `satisfaction`, `maxSteps`, `extract`, `timeout`, `selectionStrategy`, and `relaxation` config.
2065
+ * @returns A {@link GoalPattern} configuration object.
1877
2066
  *
1878
2067
  * @example
1879
2068
  * ```typescript
1880
2069
  * const pipeline = goal(
1881
2070
  * {
1882
2071
  * researcher: {
1883
- * agent: "researcher",
2072
+ * handler: "researcher",
1884
2073
  * produces: ["research.findings"],
1885
2074
  * requires: ["research.topic"],
1886
2075
  * extractOutput: (r) => ({ "research.findings": r.output }),
1887
2076
  * },
1888
2077
  * writer: {
1889
- * agent: "writer",
2078
+ * handler: "writer",
1890
2079
  * produces: ["article.draft"],
1891
2080
  * requires: ["research.findings"],
1892
2081
  * extractOutput: (r) => ({ "article.draft": r.output }),
@@ -1910,23 +2099,40 @@ declare function goal<T = Record<string, unknown>>(nodes: Record<string, GoalNod
1910
2099
  checkpoint?: PatternCheckpointConfig;
1911
2100
  }): GoalPattern<T>;
1912
2101
  /**
1913
- * Selection strategy: run all ready agents (default).
2102
+ * Create a selection strategy that runs all ready agents concurrently.
2103
+ *
2104
+ * This is the default strategy for {@link goal} patterns.
2105
+ *
2106
+ * @returns An {@link AgentSelectionStrategy} that selects every ready agent.
1914
2107
  */
1915
2108
  declare function allReadyStrategy(): AgentSelectionStrategy;
1916
2109
  /**
1917
- * Selection strategy: pick agents with the highest historical impact.
2110
+ * Create a selection strategy that picks agents with the highest historical impact.
2111
+ *
2112
+ * Sorts ready agents by average satisfaction delta (descending) and selects the top N.
1918
2113
  *
1919
- * Sorts by average satisfaction delta (descending) and picks the top N.
2114
+ * @param opts - Optional `topN` to limit how many agents are selected (default: 3).
2115
+ * @returns An {@link AgentSelectionStrategy} that prioritizes high-impact agents.
1920
2116
  */
1921
2117
  declare function highestImpactStrategy(opts?: {
1922
2118
  topN?: number;
1923
2119
  }): AgentSelectionStrategy;
1924
2120
  /**
1925
- * Selection strategy: prefer agents that consume fewer tokens per satisfaction delta.
2121
+ * Create a selection strategy that prefers agents with lower token cost per satisfaction delta.
2122
+ *
2123
+ * Agents without historical metrics are prioritized first (to gather data).
2124
+ *
2125
+ * @returns An {@link AgentSelectionStrategy} that optimizes for cost efficiency.
1926
2126
  */
1927
2127
  declare function costEfficientStrategy(): AgentSelectionStrategy;
1928
2128
  /**
1929
- * Create an agent selection constraint.
2129
+ * Create a constraint that routes to a specific agent when a condition is met.
2130
+ *
2131
+ * @param when - Predicate that triggers the constraint (may be async).
2132
+ * @param agent - Agent ID or function returning an agent ID to route to.
2133
+ * @param input - Input string or function returning the input for the selected agent.
2134
+ * @param priority - Optional constraint priority (higher = evaluated first).
2135
+ * @returns An {@link OrchestratorConstraint} that emits a `RUN_AGENT` requirement.
1930
2136
  *
1931
2137
  * @example
1932
2138
  * ```typescript
@@ -1934,14 +2140,19 @@ declare function costEfficientStrategy(): AgentSelectionStrategy;
1934
2140
  * routeToExpert: selectAgent(
1935
2141
  * (facts) => facts.complexity > 0.8,
1936
2142
  * 'expert',
1937
- * (facts) => facts.query
2143
+ * (facts) => facts.query,
1938
2144
  * ),
1939
2145
  * };
1940
2146
  * ```
1941
2147
  */
1942
2148
  declare function selectAgent(when: (facts: Record<string, unknown>) => boolean | Promise<boolean>, agent: string | ((facts: Record<string, unknown>) => string), input: string | ((facts: Record<string, unknown>) => string), priority?: number): OrchestratorConstraint<Record<string, unknown>>;
1943
2149
  /**
1944
- * Create a RUN_AGENT requirement.
2150
+ * Create a `RUN_AGENT` requirement object for use in constraint `require()` functions.
2151
+ *
2152
+ * @param agent - The agent ID to run.
2153
+ * @param input - The input string for the agent.
2154
+ * @param context - Optional additional context passed to the agent runner.
2155
+ * @returns A `RUN_AGENT` {@link RunAgentRequirement} object.
1945
2156
  *
1946
2157
  * @example
1947
2158
  * ```typescript
@@ -1955,31 +2166,49 @@ declare function selectAgent(when: (facts: Record<string, unknown>) => boolean |
1955
2166
  */
1956
2167
  declare function runAgentRequirement(agent: string, input: string, context?: Record<string, unknown>): RunAgentRequirement;
1957
2168
  /**
1958
- * Merge results by concatenating outputs.
2169
+ * Merge run results by concatenating their outputs into a single string.
2170
+ *
2171
+ * @param results - Array of run results to concatenate.
2172
+ * @param separator - String inserted between outputs (default: `"\n\n"`).
2173
+ * @returns The concatenated output string.
1959
2174
  */
1960
2175
  declare function concatResults(results: RunResult<unknown>[], separator?: string): string;
1961
2176
  /**
1962
- * Merge results by picking the best one based on a scoring function.
2177
+ * Pick the highest-scoring result from an array using a scoring function.
2178
+ *
2179
+ * @param results - Array of run results to compare.
2180
+ * @param score - Function that assigns a numeric score to each result (higher wins).
2181
+ * @returns The {@link RunResult} with the highest score.
2182
+ * @throws If the results array is empty.
1963
2183
  */
1964
2184
  declare function pickBestResult<T>(results: RunResult<T>[], score: (result: RunResult<T>) => number): RunResult<T>;
1965
2185
  /**
1966
- * Merge results into an array of outputs.
2186
+ * Extract the `output` value from each run result into an array.
2187
+ *
2188
+ * @param results - Array of run results to collect from.
2189
+ * @returns An array of output values in the same order as the input results.
1967
2190
  */
1968
2191
  declare function collectOutputs<T>(results: RunResult<T>[]): T[];
1969
2192
  /**
1970
- * Aggregate token counts from results.
2193
+ * Sum the total token counts from an array of run results.
2194
+ *
2195
+ * @param results - Array of run results to aggregate.
2196
+ * @returns The total number of tokens consumed across all results.
1971
2197
  */
1972
2198
  declare function aggregateTokens(results: RunResult<unknown>[]): number;
1973
2199
  /**
1974
- * Compose multiple patterns into a pipeline where each pattern's
1975
- * output feeds as input to the next. Returns an async function
1976
- * that runs the pipeline on a given orchestrator.
2200
+ * Compose multiple execution patterns into a pipeline where each pattern's
2201
+ * output feeds as input to the next.
1977
2202
  *
2203
+ * @remarks
1978
2204
  * Between patterns, output is converted to a string input:
1979
2205
  * - `string` output passes through directly
1980
2206
  * - Objects are JSON-stringified
1981
2207
  * - Optionally provide a `transform` to customize between steps
1982
2208
  *
2209
+ * @param patterns - One or more execution patterns to chain together.
2210
+ * @returns An async function that runs the pipeline on a given orchestrator.
2211
+ *
1983
2212
  * @example
1984
2213
  * ```typescript
1985
2214
  * const workflow = composePatterns(
@@ -1992,10 +2221,11 @@ declare function aggregateTokens(results: RunResult<unknown>[]): number;
1992
2221
  */
1993
2222
  declare function composePatterns(...patterns: ExecutionPattern[]): (orchestrator: MultiAgentOrchestrator, input: string) => Promise<unknown>;
1994
2223
  /**
1995
- * Create a capability-based agent selector.
2224
+ * Find agents in a registry that match all required capabilities.
1996
2225
  *
1997
- * Given a registry and required capabilities, returns the agent IDs
1998
- * that match all required capabilities.
2226
+ * @param registry - The agent registry to search.
2227
+ * @param requiredCapabilities - Capabilities that each matching agent must have.
2228
+ * @returns An array of agent IDs whose `capabilities` include every required capability.
1999
2229
  *
2000
2230
  * @example
2001
2231
  * ```typescript
@@ -2007,14 +2237,20 @@ declare function composePatterns(...patterns: ExecutionPattern[]): (orchestrator
2007
2237
  *
2008
2238
  * const matches = findAgentsByCapability(agents, ['search']);
2009
2239
  * // Returns ['researcher']
2010
- *
2011
- * const matches2 = findAgentsByCapability(agents, ['write', 'edit']);
2012
- * // Returns ['writer']
2013
2240
  * ```
2014
2241
  */
2015
2242
  declare function findAgentsByCapability(registry: AgentRegistry, requiredCapabilities: string[]): string[];
2016
2243
  /**
2017
- * Create a constraint that auto-routes to an agent based on capabilities.
2244
+ * Create a constraint that auto-routes to an agent based on required capabilities.
2245
+ *
2246
+ * When the condition fires, it finds agents matching the capabilities returned by
2247
+ * `getCapabilities`, then emits a `RUN_AGENT` requirement for the best match.
2248
+ *
2249
+ * @param registry - The agent registry to search for matching capabilities.
2250
+ * @param getCapabilities - Function that extracts required capabilities from facts.
2251
+ * @param getInput - Function that extracts the input string from facts.
2252
+ * @param options - Optional `priority` and custom `select` function.
2253
+ * @returns An {@link OrchestratorConstraint} that routes to a capability-matched agent.
2018
2254
  *
2019
2255
  * @example
2020
2256
  * ```typescript
@@ -2039,11 +2275,14 @@ interface SpawnOnConditionOptions {
2039
2275
  context?: Record<string, unknown>;
2040
2276
  }
2041
2277
  /**
2042
- * Create a constraint that auto-runs an agent when a condition is met.
2278
+ * Create a constraint that auto-runs a single agent when a condition is met.
2043
2279
  *
2044
- * The orchestrator's built-in RUN_AGENT resolver handles execution
2280
+ * The orchestrator's built-in `RUN_AGENT` resolver handles execution --
2045
2281
  * you only need to add this to your `constraints` config.
2046
2282
  *
2283
+ * @param config - Condition, agent ID, input builder, and optional priority/context.
2284
+ * @returns An {@link OrchestratorConstraint} that emits a `RUN_AGENT` requirement.
2285
+ *
2047
2286
  * @example
2048
2287
  * ```typescript
2049
2288
  * const orchestrator = createMultiAgentOrchestrator({
@@ -2066,7 +2305,6 @@ declare function spawnOnCondition(config: {
2066
2305
  priority?: number;
2067
2306
  /** Additional context passed to the agent */
2068
2307
  context?: Record<string, unknown>;
2069
- /** @deprecated Use top-level `priority` and `context` instead */
2070
2308
  options?: SpawnOnConditionOptions;
2071
2309
  }): OrchestratorConstraint<Record<string, unknown>>;
2072
2310
  /** Configuration for the debate() factory and runDebate() imperative API. @see DebatePattern */
@@ -2074,13 +2312,15 @@ type DebateConfig<T = unknown> = Omit<DebatePattern<T>, "type">;
2074
2312
  /**
2075
2313
  * Create a debate pattern where agents compete and an evaluator picks the best.
2076
2314
  *
2315
+ * @remarks
2077
2316
  * Flow:
2078
2317
  * 1. All agents produce proposals in parallel
2079
2318
  * 2. Evaluator receives all proposals and picks a winner
2080
2319
  * 3. Optionally repeat with evaluator feedback for refinement
2081
2320
  *
2082
- * @param config - Debate configuration with `agents`, `evaluator`, and optional settings
2083
- * @see runDebate for the imperative API
2321
+ * @param config - Debate configuration with `handlers`, `evaluator`, and optional settings.
2322
+ * @returns A {@link DebatePattern} configuration object.
2323
+ * @see {@link runDebate} for the imperative API
2084
2324
  *
2085
2325
  * @example
2086
2326
  * ```typescript
@@ -2092,7 +2332,7 @@ type DebateConfig<T = unknown> = Omit<DebatePattern<T>, "type">;
2092
2332
  * },
2093
2333
  * patterns: {
2094
2334
  * debate: debate({
2095
- * agents: ['optimist', 'pessimist'],
2335
+ * handlers: ['optimist', 'pessimist'],
2096
2336
  * evaluator: 'judge',
2097
2337
  * maxRounds: 2,
2098
2338
  * }),
@@ -2104,23 +2344,30 @@ type DebateConfig<T = unknown> = Omit<DebatePattern<T>, "type">;
2104
2344
  */
2105
2345
  declare function debate<T = unknown>(config: DebateConfig<T>): DebatePattern<T>;
2106
2346
  /**
2107
- * Run a debate imperatively on an orchestrator (no pattern registration needed).
2347
+ * Run a debate imperatively on an orchestrator without pattern registration.
2348
+ *
2108
2349
  * Delegates to `orchestrator.runDebate()` so that lifecycle hooks, debug timeline,
2109
2350
  * and signal propagation all work correctly.
2110
2351
  *
2111
- * @param orchestrator - The multi-agent orchestrator instance
2112
- * @param config - Debate configuration with agents, evaluator, and optional settings
2113
- * @param input - The initial input/prompt for the debate
2114
- * @see debate for the declarative pattern API
2115
- * @returns The winning agent's output, the winner ID, and all proposals from each round
2352
+ * @param orchestrator - The multi-agent orchestrator instance to run the debate on.
2353
+ * @param config - Debate configuration with agents, evaluator, and optional settings.
2354
+ * @param input - The initial input/prompt for the debate.
2355
+ * @returns The winning agent's output, the winner ID, and all proposals from each round.
2356
+ * @see {@link debate} for the declarative pattern API
2116
2357
  */
2117
2358
  declare function runDebate<T>(orchestrator: MultiAgentOrchestrator, config: DebateConfig<T>, input: string): Promise<DebateResult<T>>;
2118
2359
  /**
2119
2360
  * Create a constraint that fires when a cross-agent derivation meets a condition.
2120
2361
  *
2362
+ * @remarks
2121
2363
  * Wire this into the orchestrator's `derive` config and `constraints` config together.
2122
2364
  * The constraint's `when()` reads the derivation value from the orchestrator's derived snapshot.
2123
2365
  *
2366
+ * @param derivationId - The ID of the cross-agent derivation to watch.
2367
+ * @param condition - Predicate that receives the derivation value and returns `true` when the constraint should fire.
2368
+ * @param action - Agent ID, input builder, and optional priority/context for the emitted requirement.
2369
+ * @returns An {@link OrchestratorConstraint} that emits a `RUN_AGENT` requirement when the derivation condition is met.
2370
+ *
2124
2371
  * @example
2125
2372
  * ```typescript
2126
2373
  * const orchestrator = createMultiAgentOrchestrator({
@@ -2159,11 +2406,15 @@ interface SpawnPoolConfig {
2159
2406
  /**
2160
2407
  * Create a constraint that spawns a pool of agent instances when a condition is met.
2161
2408
  *
2162
- * Unlike `spawnOnCondition` (which spawns one agent), `spawnPool` can target N agents.
2163
- * However, only **one requirement is emitted per constraint evaluation cycle** the constraint
2409
+ * @remarks
2410
+ * Unlike {@link spawnOnCondition} (which spawns one agent), `spawnPool` can target N agents.
2411
+ * However, only one requirement is emitted per constraint evaluation cycle -- the constraint
2164
2412
  * re-fires on subsequent cycles as long as `when()` returns true, spawning one agent per cycle.
2165
2413
  *
2166
- * @see spawnOnCondition for spawning a single agent
2414
+ * @param when - Predicate that triggers the pool spawn.
2415
+ * @param config - Pool configuration with agent ID, input builder, count, and optional priority/context.
2416
+ * @returns An {@link OrchestratorConstraint} that emits `RUN_AGENT` requirements.
2417
+ * @see {@link spawnOnCondition} for spawning a single agent
2167
2418
  *
2168
2419
  * @example
2169
2420
  * ```typescript
@@ -2185,7 +2436,8 @@ interface SpawnPoolConfig {
2185
2436
  declare function spawnPool(when: (facts: Record<string, unknown>) => boolean, config: SpawnPoolConfig): OrchestratorConstraint<Record<string, unknown>>;
2186
2437
  /** Serialized DAG node (functions stripped) */
2187
2438
  interface SerializedDagNode {
2188
- agent: string;
2439
+ handler: string;
2440
+ agent?: string;
2189
2441
  deps?: string[];
2190
2442
  timeout?: number;
2191
2443
  priority?: number;
@@ -2193,12 +2445,12 @@ interface SerializedDagNode {
2193
2445
  /** JSON-safe representation of any execution pattern (all functions stripped) */
2194
2446
  type SerializedPattern = {
2195
2447
  type: "parallel";
2196
- agents: string[];
2448
+ handlers: string[];
2197
2449
  minSuccess?: number;
2198
2450
  timeout?: number;
2199
2451
  } | {
2200
2452
  type: "sequential";
2201
- agents: string[];
2453
+ handlers: string[];
2202
2454
  continueOnError?: boolean;
2203
2455
  } | {
2204
2456
  type: "supervisor";
@@ -2213,7 +2465,7 @@ type SerializedPattern = {
2213
2465
  onNodeError?: "fail" | "skip-downstream" | "continue";
2214
2466
  } | {
2215
2467
  type: "reflect";
2216
- agent: string;
2468
+ handler: string;
2217
2469
  evaluator: string;
2218
2470
  maxIterations?: number;
2219
2471
  onExhausted?: "accept-last" | "accept-best" | "throw";
@@ -2221,12 +2473,12 @@ type SerializedPattern = {
2221
2473
  threshold?: number;
2222
2474
  } | {
2223
2475
  type: "race";
2224
- agents: string[];
2476
+ handlers: string[];
2225
2477
  timeout?: number;
2226
2478
  minSuccess?: number;
2227
2479
  } | {
2228
2480
  type: "debate";
2229
- agents: string[];
2481
+ handlers: string[];
2230
2482
  evaluator: string;
2231
2483
  maxRounds?: number;
2232
2484
  timeout?: number;
@@ -2238,7 +2490,8 @@ type SerializedPattern = {
2238
2490
  };
2239
2491
  /** Serialized goal node (functions stripped) */
2240
2492
  interface SerializedGoalNode {
2241
- agent: string;
2493
+ handler: string;
2494
+ agent?: string;
2242
2495
  produces: string[];
2243
2496
  requires?: string[];
2244
2497
  allowRerun?: boolean;
@@ -2247,31 +2500,42 @@ interface SerializedGoalNode {
2247
2500
  /**
2248
2501
  * Serialize an execution pattern to a JSON-safe object.
2249
2502
  *
2503
+ * @remarks
2250
2504
  * Strips all function callbacks and runtime objects (AbortSignal) while
2251
- * preserving the topology which agents, in what structure, with what
2505
+ * preserving the topology -- which agents, in what structure, with what
2252
2506
  * numeric/string/boolean options.
2253
2507
  *
2254
2508
  * Use this for visual editors, LLM-generated plans, persistence, or
2255
2509
  * debugging. Restore with {@link patternFromJSON}.
2256
2510
  *
2257
- * Note: Function-form `threshold` on reflect patterns is not serializable and will be dropped.
2511
+ * Function-form `threshold` on reflect patterns is not serializable and will be dropped.
2258
2512
  * Re-supply it via `overrides` when calling {@link patternFromJSON}.
2259
2513
  *
2514
+ * @param pattern - The execution pattern to serialize.
2515
+ * @returns A {@link SerializedPattern} safe for `JSON.stringify`.
2516
+ *
2260
2517
  * @example
2261
2518
  * ```typescript
2262
- * const p = parallel({ agents: ["a", "b"], merge: (r) => r });
2519
+ * const p = parallel(['a', 'b'], (r) => r);
2263
2520
  * const json = patternToJSON(p);
2264
- * // { type: "parallel", agents: ["a", "b"] }
2521
+ * // { type: "parallel", handlers: ["a", "b"] }
2265
2522
  * localStorage.setItem("plan", JSON.stringify(json));
2266
2523
  * ```
2267
2524
  */
2268
2525
  declare function patternToJSON(pattern: ExecutionPattern<unknown>): SerializedPattern;
2269
2526
  /**
2270
- * Restore an execution pattern from its serialized form.
2527
+ * Restore an execution pattern from its serialized JSON form.
2271
2528
  *
2529
+ * @remarks
2272
2530
  * Returns the data structure with all function fields set to `undefined`.
2273
2531
  * Supply callbacks via the optional `overrides` parameter to re-attach
2274
- * runtime behavior.
2532
+ * runtime behavior. Handles legacy field migrations (`agent` to `handler`,
2533
+ * `agents` to `handlers`, `converge` to `goal`).
2534
+ *
2535
+ * @param json - The serialized pattern from {@link patternToJSON} or persisted storage.
2536
+ * @param overrides - Optional partial pattern to re-attach function callbacks (e.g. `merge`, `extract`).
2537
+ * @returns A fully typed {@link ExecutionPattern} ready for use with the imperative API.
2538
+ * @throws If the pattern type is invalid or unknown.
2275
2539
  *
2276
2540
  * @example
2277
2541
  * ```typescript
@@ -2279,12 +2543,11 @@ declare function patternToJSON(pattern: ExecutionPattern<unknown>): SerializedPa
2279
2543
  * const pattern = patternFromJSON<string[]>(json, {
2280
2544
  * merge: (results) => results.map(r => r.output as string),
2281
2545
  * });
2282
- * // Use the imperative API — runPattern takes a registered pattern ID, not an object
2283
2546
  * if (pattern.type === "parallel") {
2284
- * const result = await orchestrator.runParallel(pattern.agents, input, pattern.merge);
2547
+ * const result = await orchestrator.runParallel(pattern.handlers, input, pattern.merge);
2285
2548
  * }
2286
2549
  * ```
2287
2550
  */
2288
2551
  declare function patternFromJSON<T = unknown>(json: SerializedPattern, overrides?: Partial<ExecutionPattern<T>>): ExecutionPattern<T>;
2289
2552
 
2290
- export { type SafeParseResult as $, type AgentHealthMetrics as A, type BackpressureStrategy as B, type MultiplexedStreamChunk as C, type DebugTimeline as D, type ExecutionPattern as E, type MultiplexedStreamResult as F, type GuardrailTriggeredChunk as G, type HealthMonitor as H, type OrchestratorStreamChunk as I, type OrchestratorStreamResult as J, type ProgressChunk as K, type RaceResult as L, type MemoryManageResult as M, type RaceSuccessEntry as N, type OrchestratorOptions as O, type ParallelPattern as P, type ReflectIterationRecord as Q, type RacePattern as R, type SerializedPattern as S, type ReflectPattern as T, type ReflectionConfig as U, type ReflectionContext as V, type ReflectionEvaluation as W, type ReflectionEvaluator as X, ReflectionExhaustedError as Y, type RunAgentRequirement as Z, type RunCallOptions as _, type AgentMemory as a, race as a$, type SafeParseable as a0, Semaphore as a1, type SequentialPattern as a2, type SerializedDagNode as a3, type SerializedGoalNode as a4, type SpawnOnConditionOptions as a5, type SpawnPoolConfig as a6, type StreamChunk as a7, type StreamRunOptions as a8, type StreamRunner as a9, createLLMSummarizer as aA, createLengthStreamingGuardrail as aB, createMultiAgentOrchestrator as aC, createPatternStreamingGuardrail as aD, createSlidingWindowStrategy as aE, createStreamingRunner as aF, createTokenBasedStrategy as aG, createToxicityStreamingGuardrail as aH, createTruncationSummarizer as aI, dag as aJ, debate as aK, derivedConstraint as aL, diffCheckpoints as aM, extractJsonFromOutput as aN, filterStream as aO, findAgentsByCapability as aP, forkFromCheckpoint as aQ, getCheckpointProgress as aR, getPatternStep as aS, goal as aT, highestImpactStrategy as aU, mapStream as aV, mergeTaggedStreams as aW, parallel as aX, patternFromJSON as aY, patternToJSON as aZ, pickBestResult as a_, type StreamingGuardrail as aa, type StreamingGuardrailResult as ab, type StreamingRunResult as ac, type StructuredOutputConfig as ad, StructuredOutputError as ae, type SupervisorPattern as af, type TokenChunk as ag, type ToolEndChunk as ah, type ToolStartChunk as ai, adaptOutputGuardrail as aj, aggregateTokens as ak, allReadyStrategy as al, capabilityRoute as am, collectOutputs as an, collectTokens as ao, combineStreamingGuardrails as ap, composePatterns as aq, concatResults as ar, costEfficientStrategy as as, createAgentMemory as at, createAgentOrchestrator as au, createDebugTimeline as av, createDebugTimelinePlugin as aw, createHealthMonitor as ax, createHybridStrategy as ay, createKeyPointsSummarizer as az, type AgentMemoryConfig as b, reflect as b0, runAgentRequirement as b1, runDebate as b2, selectAgent as b3, sequential as b4, spawnOnCondition as b5, spawnPool as b6, supervisor as b7, tapStream as b8, withReflection as b9, withStructuredOutput as ba, type AgentOrchestrator as c, type AgentRegistration as d, type AgentRegistry as e, type DebateConfig as f, type DebatePattern as g, type DebateResult as h, type DebugTimelineListener as i, type DebugTimelineOptions as j, type DoneChunk as k, type ErrorChunk as l, type HandoffRequest as m, type HandoffResult as n, type HealthCircuitState as o, type MemoryState as p, type MemoryStrategy as q, type MemoryStrategyConfig as r, type MemoryStrategyResult as s, type MergedTaggedStreamResult as t, type MessageChunk as u, type MessageSummarizer as v, type MultiAgentOrchestrator as w, type MultiAgentOrchestratorOptions as x, type MultiAgentRunCallOptions as y, type MultiAgentState as z };
2553
+ export { type SafeParseResult as $, type AgentHealthMetrics as A, type BackpressureStrategy as B, type MultiplexedStreamChunk as C, type DebugTimeline as D, type ExecutionPattern as E, type MultiplexedStreamResult as F, type GuardrailTriggeredChunk as G, type HealthMonitor as H, type OrchestratorStreamChunk as I, type OrchestratorStreamResult as J, type ProgressChunk as K, type RaceResult as L, type MemoryManageResult as M, type RaceSuccessEntry as N, type OrchestratorOptions as O, type ParallelPattern as P, type ReflectIterationRecord as Q, type RacePattern as R, type SerializedPattern as S, type ReflectPattern as T, type ReflectionConfig as U, type ReflectionContext as V, type ReflectionEvaluation as W, type ReflectionEvaluator as X, ReflectionExhaustedError as Y, type RunAgentRequirement as Z, type RunCallOptions as _, type AgentMemory as a, patternToJSON as a$, type SafeParseable as a0, Semaphore as a1, type SequentialPattern as a2, type SerializedDagNode as a3, type SerializedGoalNode as a4, type SpawnOnConditionOptions as a5, type SpawnPoolConfig as a6, type StreamChunk as a7, type StreamRunOptions as a8, type StreamRunner as a9, createHybridStrategy as aA, createKeyPointsSummarizer as aB, createLLMSummarizer as aC, createLengthStreamingGuardrail as aD, createMultiAgentOrchestrator as aE, createPatternStreamingGuardrail as aF, createSlidingWindowStrategy as aG, createStreamingRunner as aH, createTokenBasedStrategy as aI, createToxicityStreamingGuardrail as aJ, createTruncationSummarizer as aK, dag as aL, debate as aM, derivedConstraint as aN, diffCheckpoints as aO, extractJsonFromOutput as aP, filterStream as aQ, findAgentsByCapability as aR, forkFromCheckpoint as aS, getCheckpointProgress as aT, getPatternStep as aU, goal as aV, highestImpactStrategy as aW, mapStream as aX, mergeTaggedStreams as aY, parallel as aZ, patternFromJSON as a_, type StreamingGuardrail as aa, type StreamingGuardrailResult as ab, type StreamingRunResult as ac, type StructuredOutputConfig as ad, StructuredOutputError as ae, type SupervisorPattern as af, type TaskContext as ag, type TaskRegistration as ah, type TokenChunk as ai, type ToolEndChunk as aj, type ToolStartChunk as ak, adaptOutputGuardrail as al, aggregateTokens as am, allReadyStrategy as an, capabilityRoute as ao, collectOutputs as ap, collectTokens as aq, combineStreamingGuardrails as ar, composePatterns as as, concatResults as at, costEfficientStrategy as au, createAgentMemory as av, createAgentOrchestrator as aw, createDebugTimeline as ax, createDebugTimelinePlugin as ay, createHealthMonitor as az, type AgentMemoryConfig as b, pickBestResult as b0, race as b1, reflect as b2, runAgentRequirement as b3, runDebate as b4, selectAgent as b5, sequential as b6, spawnOnCondition as b7, spawnPool as b8, supervisor as b9, tapStream as ba, withReflection as bb, withStructuredOutput as bc, type AgentOrchestrator as c, type AgentRegistration as d, type AgentRegistry as e, type DebateConfig as f, type DebatePattern as g, type DebateResult as h, type DebugTimelineListener as i, type DebugTimelineOptions as j, type DoneChunk as k, type ErrorChunk as l, type HandoffRequest as m, type HandoffResult as n, type HealthCircuitState as o, type MemoryState as p, type MemoryStrategy as q, type MemoryStrategyConfig as r, type MemoryStrategyResult as s, type MergedTaggedStreamResult as t, type MessageChunk as u, type MessageSummarizer as v, type MultiAgentOrchestrator as w, type MultiAgentOrchestratorOptions as x, type MultiAgentRunCallOptions as y, type MultiAgentState as z };