@cuylabs/agent-core 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +216 -41
  2. package/dist/builder-RcTZuYnO.d.ts +34 -0
  3. package/dist/capabilities/index.d.ts +97 -0
  4. package/dist/capabilities/index.js +46 -0
  5. package/dist/chunk-6TDTQJ4P.js +116 -0
  6. package/dist/chunk-7MUFEN4K.js +559 -0
  7. package/dist/chunk-BDBZ3SLK.js +745 -0
  8. package/dist/chunk-DWYX7ASF.js +26 -0
  9. package/dist/chunk-FG4MD5MU.js +54 -0
  10. package/dist/chunk-IMGQOTU2.js +2019 -0
  11. package/dist/chunk-IVUJDISU.js +556 -0
  12. package/dist/chunk-LRHOS4ZN.js +584 -0
  13. package/dist/chunk-OTUGSCED.js +691 -0
  14. package/dist/chunk-P6YF7USR.js +182 -0
  15. package/dist/chunk-QAQADS4X.js +258 -0
  16. package/dist/chunk-QWFMX226.js +879 -0
  17. package/dist/{chunk-6VKLWNRE.js → chunk-SDSBEQXG.js} +1 -132
  18. package/dist/chunk-VBWWUHWI.js +724 -0
  19. package/dist/chunk-VEKUXUVF.js +41 -0
  20. package/dist/chunk-X635CM2F.js +305 -0
  21. package/dist/chunk-YUUJK53A.js +91 -0
  22. package/dist/chunk-ZXAKHMWH.js +283 -0
  23. package/dist/config-D2xeGEHK.d.ts +52 -0
  24. package/dist/context/index.d.ts +259 -0
  25. package/dist/context/index.js +26 -0
  26. package/dist/identifiers-BLUxFqV_.d.ts +12 -0
  27. package/dist/index-p0kOsVsE.d.ts +1067 -0
  28. package/dist/index-tmhaADz5.d.ts +198 -0
  29. package/dist/index.d.ts +185 -4316
  30. package/dist/index.js +1238 -5368
  31. package/dist/mcp/index.d.ts +26 -0
  32. package/dist/mcp/index.js +14 -0
  33. package/dist/messages-BYWGn8TY.d.ts +110 -0
  34. package/dist/middleware/index.d.ts +7 -0
  35. package/dist/middleware/index.js +12 -0
  36. package/dist/models/index.d.ts +33 -0
  37. package/dist/models/index.js +12 -0
  38. package/dist/network-D76DS5ot.d.ts +5 -0
  39. package/dist/prompt/index.d.ts +224 -0
  40. package/dist/prompt/index.js +45 -0
  41. package/dist/reasoning/index.d.ts +71 -0
  42. package/dist/reasoning/index.js +47 -0
  43. package/dist/registry-CuRWWtcT.d.ts +164 -0
  44. package/dist/resolver-DOfZ-xuk.d.ts +254 -0
  45. package/dist/runner-C7aMP_x3.d.ts +596 -0
  46. package/dist/runtime/index.d.ts +357 -0
  47. package/dist/runtime/index.js +64 -0
  48. package/dist/session-manager-Uawm2Le7.d.ts +274 -0
  49. package/dist/skill/index.d.ts +103 -0
  50. package/dist/skill/index.js +39 -0
  51. package/dist/storage/index.d.ts +167 -0
  52. package/dist/storage/index.js +50 -0
  53. package/dist/sub-agent/index.d.ts +14 -0
  54. package/dist/sub-agent/index.js +15 -0
  55. package/dist/tool/index.d.ts +173 -1
  56. package/dist/tool/index.js +12 -3
  57. package/dist/tool-DYp6-cC3.d.ts +239 -0
  58. package/dist/tool-pFAnJc5Y.d.ts +419 -0
  59. package/dist/tracker-DClqYqTj.d.ts +96 -0
  60. package/dist/tracking/index.d.ts +109 -0
  61. package/dist/tracking/index.js +20 -0
  62. package/dist/types-CQaXbRsS.d.ts +47 -0
  63. package/dist/types-MM1JoX5T.d.ts +810 -0
  64. package/dist/types-VQgymC1N.d.ts +156 -0
  65. package/package.json +89 -5
  66. package/dist/index-QR704uRr.d.ts +0 -472
@@ -0,0 +1,810 @@
1
+ import { StreamTextResult, ToolSet, Output, LanguageModel, ModelMessage, TelemetrySettings } from 'ai';
2
+ import { T as Tool } from './tool-pFAnJc5Y.js';
3
+ import { d as ToolHost, e as TurnTrackerContext, N as NormalizedToolReplayPolicy } from './tool-DYp6-cC3.js';
4
+ import { d as ProcessorResult, A as AgentEvent, M as MiddlewareRunner, e as AgentTurnBoundaryKind } from './runner-C7aMP_x3.js';
5
+ import { R as ReasoningLevel } from './types-CQaXbRsS.js';
6
+ import { T as TokenUsage, M as Message } from './messages-BYWGn8TY.js';
7
+
8
+ /**
9
+ * Stream types for @cuylabs/agent-core
10
+ *
11
+ * Defines the canonical StreamChunk union and related types
12
+ * for both AI SDK native and custom stream providers.
13
+ */
14
+ /**
15
+ * Stream chunk types (AI SDK compatible + custom streams)
16
+ *
17
+ * This is the single canonical definition — used by both the
18
+ * streaming module and custom stream providers.
19
+ */
20
+ type StreamChunk = {
21
+ type: "text-start";
22
+ } | {
23
+ type: "text-delta";
24
+ text: string;
25
+ } | {
26
+ type: "text-end";
27
+ } | {
28
+ type: "reasoning-start";
29
+ id: string;
30
+ } | {
31
+ type: "reasoning-delta";
32
+ id: string;
33
+ text: string;
34
+ } | {
35
+ type: "reasoning-end";
36
+ id: string;
37
+ } | {
38
+ type: "tool-call";
39
+ toolName: string;
40
+ toolCallId: string;
41
+ input: unknown;
42
+ } | {
43
+ type: "tool-result";
44
+ toolName: string;
45
+ toolCallId: string;
46
+ output: unknown;
47
+ } | {
48
+ type: "tool-error";
49
+ toolName: string;
50
+ toolCallId: string;
51
+ error: unknown;
52
+ } | {
53
+ type: "finish-step";
54
+ usage?: {
55
+ inputTokens?: number;
56
+ outputTokens?: number;
57
+ totalTokens?: number;
58
+ };
59
+ finishReason?: string;
60
+ } | {
61
+ type: "finish";
62
+ totalUsage?: {
63
+ inputTokens?: number;
64
+ outputTokens?: number;
65
+ totalTokens?: number;
66
+ };
67
+ } | {
68
+ type: "error";
69
+ error: unknown;
70
+ } | {
71
+ type: "start-step";
72
+ } | {
73
+ type: "start";
74
+ } | {
75
+ type: "abort";
76
+ } | {
77
+ type: "computer-call";
78
+ callId: string;
79
+ action: unknown;
80
+ pendingSafetyChecks?: unknown[];
81
+ } | {
82
+ type: "step-usage";
83
+ usage: {
84
+ inputTokens: number;
85
+ outputTokens: number;
86
+ totalTokens: number;
87
+ };
88
+ };
89
+ /**
90
+ * Custom stream provider function type.
91
+ *
92
+ * This matches the signature needed for agent-core's LLM module,
93
+ * returning a StreamProviderResult-compatible object.
94
+ */
95
+ type StreamProvider = (input: StreamProviderInput) => Promise<StreamProviderResult>;
96
+ /**
97
+ * Input for custom stream providers
98
+ */
99
+ interface StreamProviderInput {
100
+ /** System prompt */
101
+ system: string;
102
+ /** Messages to send */
103
+ messages: Array<{
104
+ role: string;
105
+ content: unknown;
106
+ }>;
107
+ /** Abort signal */
108
+ abortSignal?: AbortSignal;
109
+ /** Max iterations */
110
+ maxSteps?: number;
111
+ }
112
+ /**
113
+ * Result from custom stream providers (AI SDK StreamTextResult compatible)
114
+ */
115
+ interface StreamProviderResult {
116
+ /** Async iterable of stream chunks */
117
+ fullStream: AsyncIterable<StreamChunk>;
118
+ /** Promise resolving to final text */
119
+ text: Promise<string>;
120
+ /** Promise resolving to usage stats */
121
+ usage: Promise<{
122
+ inputTokens: number;
123
+ outputTokens: number;
124
+ totalTokens: number;
125
+ }>;
126
+ /** Promise resolving to finish reason */
127
+ finishReason: Promise<string>;
128
+ }
129
+ /**
130
+ * Configuration for stream provider factory.
131
+ * Contains everything needed to create a stream provider for a specific model.
132
+ */
133
+ interface StreamProviderConfig {
134
+ /** API key to use */
135
+ apiKey?: string;
136
+ /** Display dimensions */
137
+ display?: {
138
+ width: number;
139
+ height: number;
140
+ };
141
+ /** Environment type */
142
+ environment?: string;
143
+ /** Enable debug logging */
144
+ debug?: boolean;
145
+ }
146
+ /**
147
+ * Stream provider factory - creates a stream provider for a given model.
148
+ *
149
+ * This is attached to enhanced tools (like computer tools) to allow
150
+ * the Agent to automatically configure the right stream provider
151
+ * when a model requires custom handling (e.g., OpenAI computer-use-preview).
152
+ */
153
+ type StreamProviderFactory = (modelId: string, config: StreamProviderConfig) => StreamProvider;
154
+ /**
155
+ * Enhanced tools array with additional capabilities.
156
+ *
157
+ * This extends the standard Tool.AnyInfo[] with optional metadata
158
+ * that the Agent can use for automatic configuration.
159
+ */
160
+ interface EnhancedTools extends Array<unknown> {
161
+ /**
162
+ * Factory to create a stream provider for models that need custom streaming.
163
+ * Called by the Agent when it detects a model that requires special handling.
164
+ */
165
+ __streamProviderFactory?: StreamProviderFactory;
166
+ /**
167
+ * Model patterns that require the custom stream provider.
168
+ * Used by the Agent to detect when to use the factory.
169
+ * Default patterns: ["computer-use-preview"]
170
+ */
171
+ __customStreamModels?: string[];
172
+ }
173
+
174
+ /**
175
+ * Doom-loop handling contracts for repeated tool invocations.
176
+ */
177
+ /**
178
+ * Response from a doom-loop handler.
179
+ */
180
+ type DoomLoopAction = "allow" | "deny" | "remember";
181
+ /**
182
+ * Doom-loop detection request.
183
+ */
184
+ interface DoomLoopRequest {
185
+ /** The tool being called repeatedly */
186
+ tool: string;
187
+ /** How many times it has been called with the same input */
188
+ repeatCount: number;
189
+ /** The repeated input */
190
+ input: unknown;
191
+ /** Session ID */
192
+ sessionId: string;
193
+ }
194
+ /**
195
+ * Handler for doom-loop situations.
196
+ */
197
+ type DoomLoopHandler = (request: DoomLoopRequest) => Promise<DoomLoopAction>;
198
+
199
+ /**
200
+ * Intervention Controller for @cuylabs/agent-core
201
+ *
202
+ * Manages mid-turn message injection into running agent turns.
203
+ * Uses Vercel AI SDK v6's `prepareStep` hook for zero-overhead
204
+ * integration at step boundaries (between LLM calls in a multi-step turn).
205
+ *
206
+ * Instead of polling a queue after each tool execution, this leverages
207
+ * the SDK's native step lifecycle. The
208
+ * `prepareStep` callback fires before every LLM call, giving us a
209
+ * natural injection point with no custom loop machinery.
210
+ *
211
+ * Two injection modes:
212
+ * - **Immediate**: `intervene(msg)` — injected at the next step boundary
213
+ * - **Deferred**: `queueNext(msg)` — held until the turn completes
214
+ */
215
+ /** A queued intervention message waiting to be applied */
216
+ interface PendingIntervention {
217
+ /** Unique identifier for tracking */
218
+ readonly id: string;
219
+ /** The user message to inject */
220
+ readonly message: string;
221
+ /** When the intervention was created */
222
+ readonly createdAt: Date;
223
+ }
224
+ /**
225
+ * Callback fired when an intervention is applied to a step.
226
+ *
227
+ * The agent uses this to push `intervention-applied` events into
228
+ * the streaming event queue so they reach the consumer in the
229
+ * correct order relative to other events.
230
+ */
231
+ type OnInterventionApplied = (intervention: PendingIntervention) => void;
232
+ /**
233
+ * Manages mid-turn message injection for agents.
234
+ *
235
+ * This is the core primitive that connects user redirection intent
236
+ * to the AI SDK's multi-step loop. The flow:
237
+ *
238
+ * 1. Consumer calls `agent.intervene("focus on auth.ts")` from any async context
239
+ * 2. The message is queued as a `PendingIntervention`
240
+ * 3. At the next step boundary, `prepareStep` drains the queue
241
+ * 4. The message is appended to the LLM's input messages
242
+ * 5. The LLM responds to the redirect naturally
243
+ *
244
+ * Thread safety: All operations are synchronous and run on the
245
+ * same event loop. No locks needed — Node.js guarantees ordering.
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * const ctrl = new InterventionController();
250
+ *
251
+ * // Queue an intervention (from a UI handler, WebSocket, etc.)
252
+ * const id = ctrl.intervene("stop refactoring, fix the failing test first");
253
+ *
254
+ * // Later, in prepareStep:
255
+ * const pending = ctrl.drainImmediate();
256
+ * // → [{ id, message: "stop refactoring...", createdAt }]
257
+ * ```
258
+ */
259
+ declare class InterventionController {
260
+ /** Immediate interventions — applied at the next step boundary */
261
+ private immediate;
262
+ /** Deferred messages — held until the turn completes */
263
+ private deferred;
264
+ /**
265
+ * Callback fired when an intervention is wired into a step.
266
+ * Set by the Agent before starting a chat turn, cleared after.
267
+ */
268
+ onApplied?: OnInterventionApplied;
269
+ /**
270
+ * Inject a message at the next LLM step boundary.
271
+ *
272
+ * The message is appended as a user message to the conversation
273
+ * before the next LLM call in the current multi-step turn. The
274
+ * LLM will see it and can adjust its behavior accordingly.
275
+ *
276
+ * Safe to call from any async context while `chat()` is running.
277
+ * If called when no turn is active, the message will be picked up
278
+ * by the first step of the next `chat()` call.
279
+ *
280
+ * @param message - The user message to inject
281
+ * @returns Intervention ID for tracking
282
+ */
283
+ intervene(message: string): string;
284
+ /**
285
+ * Drain and return all pending immediate interventions.
286
+ * The internal queue is cleared atomically.
287
+ *
288
+ * @internal Called by the LLM stream's `prepareStep` hook
289
+ */
290
+ drainImmediate(): PendingIntervention[];
291
+ /** Whether there are pending immediate interventions */
292
+ get hasPending(): boolean;
293
+ /** Number of pending immediate interventions */
294
+ get pendingCount(): number;
295
+ /**
296
+ * Queue a message for after the current turn completes.
297
+ *
298
+ * Unlike `intervene()`, this does **not** inject mid-turn. The
299
+ * message is held and available via `drainDeferred()` after
300
+ * `chat()` finishes. The consumer decides whether to send it
301
+ * as a new turn.
302
+ *
303
+ * @param message - The message to queue
304
+ * @returns Intervention ID for tracking
305
+ */
306
+ queueNext(message: string): string;
307
+ /**
308
+ * Drain and return all deferred messages.
309
+ * The internal queue is cleared atomically.
310
+ */
311
+ drainDeferred(): PendingIntervention[];
312
+ /** Whether there are deferred messages */
313
+ get hasDeferred(): boolean;
314
+ /** Number of deferred messages */
315
+ get deferredCount(): number;
316
+ /** Clear all queues (immediate + deferred) */
317
+ clear(): void;
318
+ /** Reset the controller for a new turn (clears onApplied, keeps queues) */
319
+ resetCallbacks(): void;
320
+ }
321
+
322
+ /**
323
+ * Options for processing a streamed model result.
324
+ */
325
+ interface ProcessorOptions {
326
+ /** Session ID (optional - for tracking purposes) */
327
+ sessionID?: string;
328
+ /** Abort signal */
329
+ abort: AbortSignal;
330
+ /** Event callback */
331
+ onEvent: (event: AgentEvent) => void | Promise<void>;
332
+ /** Doom loop threshold (default: 3) */
333
+ doomLoopThreshold?: number;
334
+ /** Enforce doom loop (throw error vs warn) when no handler is provided */
335
+ enforceDoomLoop?: boolean;
336
+ /**
337
+ * Handler for doom loop detection.
338
+ * Allows user choice: allow, deny, or remember.
339
+ */
340
+ onDoomLoop?: DoomLoopHandler;
341
+ /** Tools that are "remembered" (allowed without asking) */
342
+ rememberedDoomLoopTools?: Set<string>;
343
+ /** Token limit for context overflow detection */
344
+ contextTokenLimit?: number;
345
+ /** Callback for context overflow */
346
+ onContextOverflow?: (tokens: number, limit: number) => void | Promise<void>;
347
+ /** Current step number */
348
+ currentStep?: number;
349
+ /** Max steps */
350
+ maxSteps?: number;
351
+ }
352
+ /**
353
+ * Result of stream processing.
354
+ */
355
+ interface ProcessorOutput {
356
+ /** Processing result */
357
+ result: ProcessorResult;
358
+ /** Accumulated text */
359
+ text: string;
360
+ /** Tool results */
361
+ toolResults: Array<{
362
+ toolName: string;
363
+ toolCallId: string;
364
+ result: unknown;
365
+ }>;
366
+ /** Final usage */
367
+ usage?: TokenUsage;
368
+ /** Finish reason reported by the most recent completed step */
369
+ finishReason?: string;
370
+ /** Error if any */
371
+ error?: Error;
372
+ }
373
+
374
+ type ErrorCategory = "rate_limit" | "overloaded" | "auth" | "invalid_request" | "context_overflow" | "content_filter" | "network" | "timeout" | "cancelled" | "unknown";
375
+ interface ResponseHeaders {
376
+ "retry-after"?: string;
377
+ "retry-after-ms"?: string;
378
+ "x-ratelimit-remaining"?: string;
379
+ "x-ratelimit-reset"?: string;
380
+ [key: string]: string | undefined;
381
+ }
382
+ interface LLMErrorOptions {
383
+ message: string;
384
+ category?: ErrorCategory;
385
+ status?: number;
386
+ headers?: ResponseHeaders;
387
+ cause?: Error;
388
+ provider?: string;
389
+ model?: string;
390
+ }
391
+
392
+ declare class LLMError extends Error {
393
+ readonly category: ErrorCategory;
394
+ readonly status?: number;
395
+ readonly headers?: ResponseHeaders;
396
+ readonly provider?: string;
397
+ readonly model?: string;
398
+ readonly isRetryable: boolean;
399
+ readonly retryDelayMs?: number;
400
+ constructor(options: LLMErrorOptions);
401
+ static from(error: unknown, context?: Partial<LLMErrorOptions>): LLMError;
402
+ get description(): string;
403
+ }
404
+
405
+ /**
406
+ * Retry logic with exponential backoff for @cuylabs/agent-core
407
+ *
408
+ * Provides configurable retry behavior with header-aware delays,
409
+ * exponential backoff, and abort signal support.
410
+ */
411
+
412
+ /**
413
+ * Retry configuration
414
+ */
415
+ interface RetryConfig {
416
+ /** Maximum number of retry attempts (default: 3) */
417
+ maxAttempts?: number;
418
+ /** Initial delay in ms (default: 2000) */
419
+ initialDelayMs?: number;
420
+ /** Backoff multiplier (default: 2) */
421
+ backoffFactor?: number;
422
+ /** Maximum delay without headers in ms (default: 30000) */
423
+ maxDelayMs?: number;
424
+ /** Whether to jitter delays (default: true) */
425
+ jitter?: boolean;
426
+ /** Callback when retrying */
427
+ onRetry?: (attempt: number, delayMs: number, error: LLMError) => void;
428
+ }
429
+ /**
430
+ * Default retry configuration
431
+ */
432
+ declare const DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, "onRetry">>;
433
+ /**
434
+ * Tracks retry state across attempts
435
+ */
436
+ interface RetryState {
437
+ /** Current attempt number (1-indexed) */
438
+ attempt: number;
439
+ /** Total errors encountered */
440
+ errors: LLMError[];
441
+ /** Whether more retries are available */
442
+ canRetry: boolean;
443
+ /** Delay until next retry (if applicable) */
444
+ nextDelayMs?: number;
445
+ }
446
+ /**
447
+ * Creates initial retry state
448
+ */
449
+ declare function createRetryState(): RetryState;
450
+ /**
451
+ * Calculate delay for a retry attempt
452
+ */
453
+ declare function calculateDelay(attempt: number, error: LLMError | undefined, config: Required<Omit<RetryConfig, "onRetry">>): number;
454
+ /**
455
+ * Sleep for a duration, respecting abort signal
456
+ */
457
+ declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
458
+ /**
459
+ * Execute a function with retry logic
460
+ */
461
+ declare function withRetry<T>(fn: (attempt: number) => Promise<T>, config?: RetryConfig, signal?: AbortSignal): Promise<T>;
462
+ /**
463
+ * Options for retry handler
464
+ */
465
+ interface RetryHandlerOptions extends RetryConfig {
466
+ /** Abort signal */
467
+ signal?: AbortSignal;
468
+ }
469
+ /**
470
+ * Creates a retry handler that wraps stream creation
471
+ */
472
+ declare function createRetryHandler(options?: RetryHandlerOptions): <T>(createStream: (attempt: number) => Promise<T>) => Promise<T>;
473
+ /**
474
+ * Checks if more retries should be attempted
475
+ */
476
+ declare function shouldRetry(error: unknown, attempt: number, maxAttempts?: number): boolean;
477
+
478
+ /** Stream result type - uses default Output for text streaming. */
479
+ type LLMStreamResult = StreamTextResult<ToolSet, Output.Output<string, string, never>>;
480
+
481
+ /**
482
+ * Custom stream result type - compatible shape from external providers.
483
+ */
484
+ type CustomStreamResult = {
485
+ fullStream: AsyncIterable<StreamChunk>;
486
+ text: Promise<string>;
487
+ usage: Promise<{
488
+ inputTokens: number;
489
+ outputTokens: number;
490
+ totalTokens: number;
491
+ }>;
492
+ finishReason: Promise<string>;
493
+ };
494
+ /** Union type for stream results - either AI SDK or custom. */
495
+ type AnyStreamResult = LLMStreamResult | CustomStreamResult;
496
+ /** Default max output tokens. */
497
+ declare const OUTPUT_TOKEN_MAX = 32000;
498
+ /**
499
+ * @deprecated Use StreamProvider from types instead.
500
+ */
501
+ type CustomStreamProvider = StreamProvider;
502
+ /** Control whether AI SDK tool definitions auto-execute or only expose calls. */
503
+ type ToolExecutionMode = "auto" | "plan";
504
+ /**
505
+ * Input for LLM stream creation.
506
+ */
507
+ interface LLMStreamInput {
508
+ /** Session ID */
509
+ sessionID: string;
510
+ /** Model to use */
511
+ model: LanguageModel;
512
+ /** System prompt parts */
513
+ system: string[];
514
+ /** Messages to send */
515
+ messages: ModelMessage[];
516
+ /** Abort signal */
517
+ abort: AbortSignal;
518
+ /** Tools to use */
519
+ tools: Record<string, Tool.Info>;
520
+ /** Whether tools should auto-execute or only be surfaced as tool calls. */
521
+ toolExecutionMode?: ToolExecutionMode;
522
+ /** Working directory */
523
+ cwd: string;
524
+ /** Execution environment for tools */
525
+ host?: ToolHost;
526
+ /** Temperature */
527
+ temperature?: number;
528
+ /** Top-p */
529
+ topP?: number;
530
+ /** Max output tokens */
531
+ maxOutputTokens?: number;
532
+ /** Max steps (tool iterations) */
533
+ maxSteps?: number;
534
+ /** Reasoning level for extended-thinking models */
535
+ reasoningLevel?: ReasoningLevel;
536
+ /** Retry configuration */
537
+ retry?: RetryConfig;
538
+ /** Callback for step completion */
539
+ onStepFinish?: (step: StepInfo) => void | Promise<void>;
540
+ /** Custom stream provider */
541
+ customStreamProvider?: StreamProvider;
542
+ /** Turn tracker for automatic file baseline capture */
543
+ turnTracker?: TurnTrackerContext;
544
+ /** Pre-built MCP tools */
545
+ mcpTools?: ToolSet;
546
+ /** Intervention controller for mid-turn message injection */
547
+ intervention?: InterventionController;
548
+ /** Middleware runner for lifecycle hooks */
549
+ middleware?: MiddlewareRunner;
550
+ /** AI SDK telemetry settings */
551
+ telemetry?: TelemetrySettings;
552
+ }
553
+ /**
554
+ * Step information surfaced to callers.
555
+ */
556
+ interface StepInfo {
557
+ toolResults?: Array<{
558
+ toolName: string;
559
+ toolCallId: string;
560
+ output: unknown;
561
+ }>;
562
+ usage?: {
563
+ inputTokens?: number;
564
+ outputTokens?: number;
565
+ totalTokens?: number;
566
+ };
567
+ finishReason?: string;
568
+ }
569
+
570
+ interface AgentTurnEngineOptions {
571
+ sessionId: string;
572
+ startedAt: string;
573
+ getToolReplayPolicy?: (toolName: string) => NormalizedToolReplayPolicy | undefined;
574
+ }
575
+ interface AgentTurnBoundaryMetadata {
576
+ step?: number;
577
+ messageRole?: Message["role"];
578
+ pendingToolCallCount?: number;
579
+ }
580
+ interface AgentTurnStepCommitToolCall {
581
+ toolCallId: string;
582
+ toolName: string;
583
+ args: unknown;
584
+ replayPolicy?: NormalizedToolReplayPolicy;
585
+ }
586
+ interface AgentTurnStepCommitToolResult {
587
+ toolCallId: string;
588
+ toolName: string;
589
+ result: unknown;
590
+ replayPolicy?: NormalizedToolReplayPolicy;
591
+ }
592
+ interface AgentTurnStepCommitSnapshot {
593
+ toolCalls: AgentTurnStepCommitToolCall[];
594
+ toolResults: AgentTurnStepCommitToolResult[];
595
+ }
596
+ interface CreateAgentTurnStepCommitBatchOptions {
597
+ assistantMessageId?: string;
598
+ toolMessageIds?: Record<string, string>;
599
+ createdAt?: Date;
600
+ }
601
+ interface AgentTurnCommitBatch {
602
+ startBoundary: AgentEvent & {
603
+ type: "turn-boundary";
604
+ };
605
+ finishBoundary: AgentEvent & {
606
+ type: "turn-boundary";
607
+ };
608
+ messages: Message[];
609
+ }
610
+ interface AgentTurnOutputCommitOptions {
611
+ text: string;
612
+ usage?: TokenUsage;
613
+ createdAt?: Date;
614
+ id?: string;
615
+ }
616
+ type AgentTurnBoundaryEvent = AgentEvent & {
617
+ type: "turn-boundary";
618
+ };
619
+
620
+ type AgentTurnPhase = "initializing" | "committing-input" | "running-model" | "running-tools" | "committing-step" | "committing-output" | "completed" | "failed";
621
+ interface AgentTurnBoundarySnapshot {
622
+ kind: AgentTurnBoundaryKind;
623
+ createdAt: string;
624
+ step?: number;
625
+ messageRole?: "system" | "user" | "assistant" | "tool";
626
+ pendingToolCallCount?: number;
627
+ }
628
+ interface AgentTurnActiveToolCall {
629
+ toolCallId: string;
630
+ toolName: string;
631
+ input: unknown;
632
+ startedAt: string;
633
+ replayPolicy?: NormalizedToolReplayPolicy;
634
+ }
635
+ interface AgentTurnResolvedToolCall {
636
+ toolCallId: string;
637
+ toolName: string;
638
+ outcome: "result" | "error";
639
+ value: unknown;
640
+ resolvedAt: string;
641
+ replayPolicy?: NormalizedToolReplayPolicy;
642
+ }
643
+ /**
644
+ * Neutral state model for a single in-flight agent turn.
645
+ *
646
+ * This is intentionally infrastructure-agnostic. Runtime adapters can persist
647
+ * or inspect it without coupling `agent-core` to Dapr, queues, or workflow
648
+ * engines. The current shape is suitable for durable tracking and forms the
649
+ * basis for future workflow-level resume support.
650
+ */
651
+ interface AgentTurnState {
652
+ sessionId: string;
653
+ phase: AgentTurnPhase;
654
+ step: number;
655
+ maxSteps?: number;
656
+ response: string;
657
+ usage: TokenUsage;
658
+ eventCount: number;
659
+ activeToolCalls: AgentTurnActiveToolCall[];
660
+ resolvedToolCalls: AgentTurnResolvedToolCall[];
661
+ lastFinishReason?: string;
662
+ lastBoundary?: AgentTurnBoundarySnapshot;
663
+ lastEvent?: AgentEvent;
664
+ error?: string;
665
+ startedAt: string;
666
+ updatedAt: string;
667
+ }
668
+ interface CreateAgentTurnStateOptions {
669
+ sessionId: string;
670
+ startedAt: string;
671
+ }
672
+ interface AgentTurnStateAdvanceOptions {
673
+ toolReplayPolicy?: NormalizedToolReplayPolicy;
674
+ }
675
+ /**
676
+ * Create the initial neutral state for a single agent turn.
677
+ */
678
+ declare function createAgentTurnState(options: CreateAgentTurnStateOptions): AgentTurnState;
679
+ /**
680
+ * Advance neutral turn state from a streamed `AgentEvent`.
681
+ *
682
+ * This reducer deliberately models coarse but deterministic boundaries:
683
+ * step start, tool activity, step finish, completion, and failure. Runtime
684
+ * adapters can persist the resulting state now, and future resume-capable
685
+ * engines can build on the same state transitions.
686
+ */
687
+ declare function advanceAgentTurnState(state: AgentTurnState, event: AgentEvent, updatedAt: string, options?: AgentTurnStateAdvanceOptions): AgentTurnState;
688
+ /**
689
+ * Mark the turn as failed when execution aborts without a terminal `error`
690
+ * event. This covers exceptions thrown by the stream itself or runtime
691
+ * wrappers around the loop.
692
+ */
693
+ declare function failAgentTurnState(state: AgentTurnState, error: Error, updatedAt: string): AgentTurnState;
694
+
695
+ /**
696
+ * Neutral internal turn engine for one in-flight agent turn.
697
+ */
698
+ declare class AgentTurnEngine {
699
+ private turnState;
700
+ private readonly pendingToolCalls;
701
+ private readonly pendingToolResults;
702
+ private readonly getToolReplayPolicy?;
703
+ constructor(options: AgentTurnEngineOptions);
704
+ getState(): AgentTurnState;
705
+ hasPendingToolCalls(): boolean;
706
+ createStepCommitSnapshot(): AgentTurnStepCommitSnapshot | undefined;
707
+ recordEvent(event: AgentEvent, updatedAt: string): AgentTurnState;
708
+ createBoundaryEvent(boundary: AgentTurnBoundaryKind, metadata?: AgentTurnBoundaryMetadata): AgentTurnBoundaryEvent;
709
+ createInputCommit(options: {
710
+ content: string;
711
+ system?: string;
712
+ createdAt?: Date;
713
+ id?: string;
714
+ }): AgentTurnCommitBatch;
715
+ createInterventionCommit(options: {
716
+ id: string;
717
+ content: string;
718
+ createdAt?: Date;
719
+ }): AgentTurnCommitBatch;
720
+ consumeStepCommit(step: number): AgentTurnCommitBatch | undefined;
721
+ createOutputCommit(options: AgentTurnOutputCommitOptions): AgentTurnCommitBatch | undefined;
722
+ }
723
+ declare function createAgentTurnEngine(options: AgentTurnEngineOptions): AgentTurnEngine;
724
+
725
+ interface AgentTurnCommitOptions {
726
+ emitMessages?: boolean;
727
+ }
728
+ type AgentTurnCommitApplier = (batch: AgentTurnCommitBatch, options?: AgentTurnCommitOptions) => AsyncGenerator<AgentEvent>;
729
+ interface AgentTurnStepRuntimeConfig {
730
+ model: LanguageModel;
731
+ cwd: string;
732
+ temperature?: number;
733
+ topP?: number;
734
+ maxOutputTokens?: number;
735
+ maxSteps: number;
736
+ doomLoopThreshold?: number;
737
+ enforceDoomLoop?: boolean;
738
+ onDoomLoop?: DoomLoopHandler;
739
+ contextWindow?: number;
740
+ streamProvider?: StreamProvider;
741
+ telemetry?: TelemetrySettings;
742
+ }
743
+ interface PrepareModelStepOptions {
744
+ sessionId: string;
745
+ step: number;
746
+ systemPrompts: string[];
747
+ messages: Message[];
748
+ toModelMessages: (messages: Message[]) => ModelMessage[];
749
+ abort: AbortSignal;
750
+ tools: Record<string, Tool.Info>;
751
+ mcpTools?: ToolSet;
752
+ config: AgentTurnStepRuntimeConfig;
753
+ host?: ToolHost;
754
+ turnTracker?: TurnTrackerContext;
755
+ intervention?: InterventionController;
756
+ middleware?: MiddlewareRunner;
757
+ reasoningLevel?: ReasoningLevel;
758
+ toolExecutionMode?: ToolExecutionMode;
759
+ }
760
+ interface PreparedAgentModelStep {
761
+ step: number;
762
+ messages: Message[];
763
+ modelMessages: ModelMessage[];
764
+ llmInput: LLMStreamInput;
765
+ processor: {
766
+ maxSteps: number;
767
+ doomLoopThreshold?: number;
768
+ enforceDoomLoop?: boolean;
769
+ onDoomLoop?: DoomLoopHandler;
770
+ contextTokenLimit?: number;
771
+ };
772
+ }
773
+ interface RunModelStepOptions {
774
+ preparedStep: PreparedAgentModelStep;
775
+ turnEngine: AgentTurnEngine;
776
+ applyCommitBatch: AgentTurnCommitApplier;
777
+ rememberedDoomLoopTools?: Set<string>;
778
+ }
779
+ interface CommitStepOptions {
780
+ step: number;
781
+ finishReason?: string;
782
+ turnEngine: AgentTurnEngine;
783
+ applyCommitBatch: AgentTurnCommitApplier;
784
+ }
785
+ interface CommitOutputOptions {
786
+ text: string;
787
+ usage?: ProcessorOutput["usage"];
788
+ turnEngine: AgentTurnEngine;
789
+ applyCommitBatch: AgentTurnCommitApplier;
790
+ }
791
+ interface RunToolBatchOptions {
792
+ sessionId: string;
793
+ snapshot: AgentTurnStepCommitSnapshot;
794
+ tools: Record<string, Tool.Info>;
795
+ cwd: string;
796
+ abort: AbortSignal;
797
+ host?: ToolHost;
798
+ turnTracker?: TurnTrackerContext;
799
+ middleware?: MiddlewareRunner;
800
+ turnState?: AgentTurnState;
801
+ }
802
+ interface RunToolBatchResult {
803
+ snapshot: AgentTurnStepCommitSnapshot;
804
+ turnState?: AgentTurnState;
805
+ events: Array<Extract<AgentEvent, {
806
+ type: "tool-result" | "tool-error";
807
+ }>>;
808
+ }
809
+
810
+ export { type StreamProviderFactory as $, type AnyStreamResult as A, LLMError as B, type CommitOutputOptions as C, DEFAULT_RETRY_CONFIG as D, type ErrorCategory as E, type LLMErrorOptions as F, type LLMStreamResult as G, type OnInterventionApplied as H, InterventionController as I, type PendingIntervention as J, type PrepareModelStepOptions as K, type LLMStreamInput as L, type PreparedAgentModelStep as M, type RetryConfig as N, OUTPUT_TOKEN_MAX as O, type ProcessorOptions as P, type RetryHandlerOptions as Q, type ResponseHeaders as R, type RetryState as S, type ToolExecutionMode as T, type RunModelStepOptions as U, type RunToolBatchOptions as V, type RunToolBatchResult as W, type StepInfo as X, type StreamChunk as Y, type StreamProvider as Z, type StreamProviderConfig as _, type ProcessorOutput as a, type StreamProviderInput as a0, type StreamProviderResult as a1, advanceAgentTurnState as a2, calculateDelay as a3, createAgentTurnEngine as a4, createAgentTurnState as a5, createRetryHandler as a6, createRetryState as a7, failAgentTurnState as a8, shouldRetry as a9, sleep as aa, withRetry as ab, type AgentTurnActiveToolCall as b, type AgentTurnBoundaryMetadata as c, type AgentTurnBoundarySnapshot as d, type AgentTurnCommitApplier as e, type AgentTurnCommitBatch as f, type AgentTurnCommitOptions as g, AgentTurnEngine as h, type AgentTurnEngineOptions as i, type AgentTurnPhase as j, type AgentTurnResolvedToolCall as k, type AgentTurnState as l, type AgentTurnStateAdvanceOptions as m, type AgentTurnStepCommitSnapshot as n, type AgentTurnStepCommitToolCall as o, type AgentTurnStepCommitToolResult as p, type AgentTurnStepRuntimeConfig as q, type CommitStepOptions as r, type CreateAgentTurnStateOptions as s, type CreateAgentTurnStepCommitBatchOptions as t, type CustomStreamProvider as u, type CustomStreamResult as v, type DoomLoopAction as w, type DoomLoopHandler as x, type DoomLoopRequest as y, type EnhancedTools as z };