goatchain 0.0.2

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.
@@ -0,0 +1,3328 @@
1
+ import { CallToolResult, ContentBlock, ImageContent, TextContent, Tool } from "@modelcontextprotocol/sdk/types.js";
2
+
3
+ //#region src/types/common.d.ts
4
+
5
+ /**
6
+ * Message content can be a single block or array of blocks
7
+ */
8
+ type MessageContent = string | ContentBlock | ContentBlock[];
9
+ /**
10
+ * JSON Schema property definition for nested properties
11
+ */
12
+ interface JSONSchemaProperty {
13
+ type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';
14
+ description?: string;
15
+ enum?: unknown[];
16
+ items?: JSONSchemaProperty;
17
+ properties?: Record<string, JSONSchemaProperty>;
18
+ required?: string[];
19
+ default?: unknown;
20
+ /** Allow additional JSON Schema properties */
21
+ [key: string]: unknown;
22
+ }
23
+ /**
24
+ * MCP-compatible Tool input schema.
25
+ * Per MCP spec, tool inputSchema must have type "object".
26
+ */
27
+ interface ToolInputSchema {
28
+ type: 'object';
29
+ properties?: Record<string, JSONSchemaProperty>;
30
+ required?: string[];
31
+ /** Allow additional JSON Schema properties */
32
+ [key: string]: unknown;
33
+ }
34
+ /**
35
+ * Tool call request from LLM
36
+ */
37
+ interface ToolCall {
38
+ id: string;
39
+ type: 'function';
40
+ function: {
41
+ name: string;
42
+ arguments: string | Record<string, unknown>;
43
+ };
44
+ }
45
+ /**
46
+ * Token usage statistics
47
+ */
48
+ interface Usage {
49
+ promptTokens: number;
50
+ completionTokens: number;
51
+ totalTokens: number;
52
+ }
53
+ //#endregion
54
+ //#region src/model/types.d.ts
55
+ type ProviderId = string;
56
+ type ModelId = string;
57
+ /**
58
+ * Options for chat completion requests
59
+ */
60
+ interface ChatOptions {
61
+ /**
62
+ * Temperature for response randomness (0-2)
63
+ */
64
+ temperature?: number;
65
+ /**
66
+ * Maximum tokens to generate
67
+ */
68
+ maxTokens?: number;
69
+ /**
70
+ * Stop sequences
71
+ */
72
+ stop?: string[];
73
+ /**
74
+ * Tools available to the model
75
+ */
76
+ tools?: OpenAITool[];
77
+ }
78
+ /**
79
+ * OpenAI-compatible tool format
80
+ */
81
+ interface OpenAITool {
82
+ type: 'function';
83
+ function: {
84
+ name: string;
85
+ description: string;
86
+ parameters: Record<string, unknown>;
87
+ };
88
+ }
89
+ /**
90
+ * Non-streaming chat response
91
+ */
92
+ interface ChatResponse {
93
+ message: Message;
94
+ usage?: {
95
+ promptTokens: number;
96
+ completionTokens: number;
97
+ totalTokens: number;
98
+ };
99
+ }
100
+ /**
101
+ * Stream event from model
102
+ */
103
+ type StreamEvent = {
104
+ type: 'text_delta';
105
+ delta: string;
106
+ } | {
107
+ type: 'tool_call';
108
+ toolCall: ToolCall;
109
+ } | {
110
+ type: 'thinking_start';
111
+ } | {
112
+ type: 'thinking_delta';
113
+ content: string;
114
+ } | {
115
+ type: 'thinking_end';
116
+ content?: string;
117
+ } | {
118
+ type: 'usage';
119
+ usage: {
120
+ promptTokens: number;
121
+ completionTokens: number;
122
+ totalTokens: number;
123
+ };
124
+ } | {
125
+ type: 'done';
126
+ };
127
+ /**
128
+ * Unified stream interface that supports both legacy and new API styles.
129
+ */
130
+ interface ModelStreamFn {
131
+ /**
132
+ * Legacy stream method for BaseModel compatibility.
133
+ */
134
+ (messages: Message[], options?: ChatOptions): AsyncIterable<StreamEvent | ModelStreamEvent>;
135
+ /**
136
+ * New stream method for ModelContract compatibility.
137
+ */
138
+ (request: Omit<ModelRequest, 'model'> & {
139
+ model?: ModelRef;
140
+ }): AsyncIterable<StreamEvent | ModelStreamEvent>;
141
+ }
142
+ /**
143
+ * BaseModel-compatible model client interface.
144
+ *
145
+ * This matches the shape expected by `BaseModel`/Agent.
146
+ * It supports both legacy API (messages array) and new ModelContract API (request object).
147
+ */
148
+ interface ModelClient {
149
+ readonly modelId: string;
150
+ /**
151
+ * Optional: current default model reference (provider + modelId).
152
+ * Only available on clients that support multi-provider routing.
153
+ */
154
+ readonly modelRef?: ModelRef;
155
+ /**
156
+ * Optional: available model references (e.g. routing fallback order).
157
+ * Only available on clients that support multi-provider routing.
158
+ */
159
+ readonly modelRefs?: ModelRef[];
160
+ /**
161
+ * Set a new default model ID for subsequent requests.
162
+ *
163
+ * This allows switching the model without recreating the entire client.
164
+ * Only works with models from the same provider.
165
+ *
166
+ * @param modelId - New model ID to use
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * model.setModelId('gpt-4')
171
+ * // All subsequent requests will use gpt-4
172
+ * ```
173
+ */
174
+ setModelId?: (modelId: string) => void;
175
+ /**
176
+ * Legacy invoke method for BaseModel compatibility.
177
+ * Takes Message array and returns ChatResponse.
178
+ */
179
+ invoke: (messages: Message[], options?: ChatOptions) => Promise<ChatResponse>;
180
+ /**
181
+ * Stream method supporting both legacy and new API styles.
182
+ */
183
+ stream: ModelStreamFn;
184
+ /**
185
+ * Run method from ModelContractClient for new API style.
186
+ * Optional for legacy implementations.
187
+ */
188
+ run?: (request: Omit<ModelRequest, 'model'> & {
189
+ model?: ModelRef;
190
+ }) => Promise<ModelRunResult>;
191
+ }
192
+ interface ModelRef {
193
+ provider: ProviderId;
194
+ modelId: ModelId;
195
+ }
196
+ interface CoreCapabilities {
197
+ streaming: boolean;
198
+ toolCalling: boolean;
199
+ vision: boolean;
200
+ audioIn: boolean;
201
+ audioOut: boolean;
202
+ jsonSchema: {
203
+ strict: boolean;
204
+ };
205
+ maxContextTokens: number;
206
+ maxOutputTokens?: number;
207
+ attachments: {
208
+ image: boolean;
209
+ file: boolean;
210
+ video: boolean;
211
+ };
212
+ }
213
+ type ModelStopReason = 'final' | 'tool_call' | 'length' | 'error' | 'cancelled';
214
+ type ModelDeltaChunk = {
215
+ kind: 'text';
216
+ text: string;
217
+ } | {
218
+ kind: 'tool_call_delta';
219
+ callId: string;
220
+ toolId?: string;
221
+ argsTextDelta?: string;
222
+ } | {
223
+ kind: 'thinking_start';
224
+ } | {
225
+ kind: 'thinking_delta';
226
+ text: string;
227
+ } | {
228
+ kind: 'thinking_end';
229
+ text?: string;
230
+ } | {
231
+ kind: 'citation_delta';
232
+ data: unknown;
233
+ } | {
234
+ kind: 'annotation';
235
+ name: string;
236
+ data: unknown;
237
+ };
238
+ type ModelStreamEvent = {
239
+ type: 'response_start';
240
+ requestId: string;
241
+ model: ModelRef;
242
+ } | {
243
+ type: 'delta';
244
+ requestId: string;
245
+ chunk: ModelDeltaChunk;
246
+ } | {
247
+ type: 'response_end';
248
+ requestId: string;
249
+ stopReason: ModelStopReason;
250
+ usage?: unknown;
251
+ } | {
252
+ type: 'error';
253
+ requestId: string;
254
+ error: {
255
+ code: string;
256
+ message: string;
257
+ retryable?: boolean;
258
+ };
259
+ };
260
+ interface ModelRequest {
261
+ requestId?: string;
262
+ model: ModelRef;
263
+ /**
264
+ * Simple text input (used when messages is not provided).
265
+ * Either `input` or `messages` should be provided.
266
+ */
267
+ input?: string;
268
+ instructions?: string;
269
+ /**
270
+ * Opaque metadata for tracing/auditing across systems.
271
+ * Keep it JSON-serializable; providers may impose size/shape limits.
272
+ */
273
+ metadata?: Record<string, string | number | boolean | null>;
274
+ /**
275
+ * Model "reasoning" / thinking controls (best-effort; provider-specific).
276
+ * For OpenAI Responses API this is passed through as `reasoning`.
277
+ */
278
+ reasoning?: Record<string, unknown>;
279
+ /**
280
+ * Messages in OpenAI format (for multi-turn conversations).
281
+ * If provided, this takes precedence over `input` for building the conversation.
282
+ */
283
+ messages?: Message[];
284
+ /**
285
+ * Tools available to the model in OpenAI format.
286
+ */
287
+ tools?: OpenAITool[];
288
+ maxOutputTokens?: number;
289
+ stop?: string[];
290
+ temperature?: number;
291
+ topP?: number;
292
+ presencePenalty?: number;
293
+ frequencyPenalty?: number;
294
+ seed?: number;
295
+ signal?: AbortSignal;
296
+ stream?: boolean;
297
+ timeoutMs?: number;
298
+ }
299
+ interface ModelRunResult {
300
+ requestId: string;
301
+ model: ModelRef;
302
+ text: string;
303
+ stopReason: ModelStopReason;
304
+ usage?: unknown;
305
+ }
306
+ //#endregion
307
+ //#region src/tool/types.d.ts
308
+ /**
309
+ * Risk level classification for tools.
310
+ *
311
+ * Used to determine whether user approval is required before execution:
312
+ * - 'safe': No risk, read-only operations (e.g., Read, Glob, Grep)
313
+ * - 'low': Low risk, minimal side effects (e.g., WebSearch, TodoWrite)
314
+ * - 'medium': Medium risk, reversible changes
315
+ * - 'high': High risk, file modifications (e.g., Write, Edit)
316
+ * - 'critical': Critical risk, arbitrary command execution (e.g., Bash)
317
+ */
318
+ type RiskLevel = 'safe' | 'low' | 'medium' | 'high' | 'critical';
319
+ /**
320
+ * Result of tool approval decision.
321
+ */
322
+ interface ToolApprovalResult {
323
+ /** Whether the tool execution is approved */
324
+ approved: boolean;
325
+ /** Optional reason for rejection (shown in tool result) */
326
+ reason?: string;
327
+ }
328
+ type ToolApprovalStrategy = 'high_risk' | 'all';
329
+ /**
330
+ * Configuration for tool approval behavior.
331
+ */
332
+ interface ToolApprovalSettings {
333
+ /**
334
+ * Which tool calls require approval.
335
+ * - 'high_risk' (default): only riskLevel 'high' and 'critical'
336
+ * - 'all': every tool call
337
+ */
338
+ strategy?: ToolApprovalStrategy;
339
+ /**
340
+ * If true, skip all approval checks (useful for "autoApprove" mode).
341
+ */
342
+ autoApprove?: boolean;
343
+ /**
344
+ * Pre-supplied approval decisions keyed by tool_call_id.
345
+ * Useful for "pause → ask user → resume" flows.
346
+ */
347
+ decisions?: Record<string, ToolApprovalResult>;
348
+ }
349
+ /**
350
+ * Tool-visible usage stats.
351
+ *
352
+ * Mirrors the common `Usage` shape and allows optional per-request breakdowns.
353
+ * This is local-only runtime data (not sent to the LLM).
354
+ */
355
+ interface ToolRunUsage extends Usage {
356
+ requestUsageEntries?: unknown[];
357
+ }
358
+ /**
359
+ * Runtime context passed to tools during execution.
360
+ *
361
+ * This is intentionally small and capability-oriented:
362
+ * - identity: sessionId/agentId
363
+ * - control: AbortSignal
364
+ */
365
+ interface ToolExecutionContext {
366
+ sessionId: string;
367
+ agentId: string;
368
+ /**
369
+ * User-provided runtime context for tool execution.
370
+ * This is local-only data and is NOT sent to the LLM.
371
+ *
372
+ * Put your dependencies/state/cache/logger/userId/db client here.
373
+ * Prefer providing a strongly-typed `TContext` instead of `any`.
374
+ */
375
+ signal?: AbortSignal;
376
+ usage?: ToolRunUsage;
377
+ }
378
+ /**
379
+ * Safe input shape for callers to provide context/capabilities/metadata.
380
+ * Identity fields are filled by the Agent at runtime.
381
+ */
382
+ interface ToolExecutionContextInput {
383
+ /**
384
+ * Optional approval configuration.
385
+ */
386
+ approval?: ToolApprovalSettings;
387
+ }
388
+ //#endregion
389
+ //#region src/types/message.d.ts
390
+ /**
391
+ * Role types for messages
392
+ */
393
+ type MessageRole = 'system' | 'user' | 'assistant' | 'tool';
394
+ /**
395
+ * System message for setting agent behavior
396
+ */
397
+ interface SystemMessage {
398
+ role: 'system';
399
+ content: MessageContent;
400
+ tools?: Tool[];
401
+ }
402
+ /**
403
+ * User input message
404
+ */
405
+ interface UserMessage {
406
+ role: 'user';
407
+ content: MessageContent;
408
+ name?: string;
409
+ }
410
+ /**
411
+ * Assistant response message
412
+ */
413
+ interface AssistantMessage {
414
+ role: 'assistant';
415
+ content: MessageContent;
416
+ reasoning_content?: string;
417
+ tool_calls?: ToolCall[];
418
+ }
419
+ /**
420
+ * Tool execution result message
421
+ */
422
+ interface ToolMessage {
423
+ role: 'tool';
424
+ content: MessageContent;
425
+ tool_call_id: string;
426
+ name?: string;
427
+ isError?: boolean;
428
+ }
429
+ /**
430
+ * Union type for all message types
431
+ */
432
+ type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
433
+ //#endregion
434
+ //#region src/types/snapshot.d.ts
435
+ /**
436
+ * Model configuration for snapshots (serializable)
437
+ */
438
+ interface ModelConfig {
439
+ /**
440
+ * Model identifier (e.g., "gpt-4o", "claude-3-opus")
441
+ */
442
+ modelId: string;
443
+ /**
444
+ * Provider name (e.g., "openai", "anthropic")
445
+ */
446
+ provider?: string;
447
+ /**
448
+ * Model-specific configuration
449
+ */
450
+ config?: Record<string, unknown>;
451
+ }
452
+ /**
453
+ * Default chat options that can be configured at agent level
454
+ */
455
+ interface DefaultChatOptions {
456
+ /**
457
+ * Temperature for response randomness (0-2)
458
+ */
459
+ temperature?: number;
460
+ /**
461
+ * Maximum tokens to generate
462
+ */
463
+ maxTokens?: number;
464
+ /**
465
+ * Stop sequences
466
+ */
467
+ stop?: string[];
468
+ }
469
+ /**
470
+ * Session status
471
+ */
472
+ type SessionStatus = 'active' | 'paused' | 'completed' | 'error' | 'archived';
473
+ /**
474
+ * Session state information
475
+ */
476
+ interface SessionState {
477
+ /**
478
+ * Current session status
479
+ */
480
+ status: SessionStatus;
481
+ /**
482
+ * Last update timestamp (ms)
483
+ */
484
+ updatedAt: number;
485
+ /**
486
+ * Last activity timestamp (ms)
487
+ */
488
+ lastActiveAt: number;
489
+ /**
490
+ * User-defined session title
491
+ */
492
+ title?: string;
493
+ /**
494
+ * Error message if status is 'error'
495
+ */
496
+ errorMessage?: string;
497
+ }
498
+ /**
499
+ * Session-level configuration overrides
500
+ * These override the parent agent's configuration for this session only
501
+ */
502
+ interface SessionConfigOverride {
503
+ /**
504
+ * Override model for this session
505
+ */
506
+ model?: ModelConfig;
507
+ /**
508
+ * Override system prompt for this session
509
+ */
510
+ systemPromptOverride?: string;
511
+ /**
512
+ * Override chat options for this session
513
+ */
514
+ chatOptions?: DefaultChatOptions;
515
+ /**
516
+ * Tools to disable for this session
517
+ */
518
+ disabledTools?: string[];
519
+ }
520
+ /**
521
+ * Conversation context containing message history
522
+ */
523
+ interface ConversationContext {
524
+ /**
525
+ * Full message history
526
+ */
527
+ messages: Message[];
528
+ /**
529
+ * Total message count
530
+ */
531
+ messageCount: number;
532
+ /**
533
+ * Preview of the last message (for list display)
534
+ */
535
+ lastMessagePreview?: string;
536
+ /**
537
+ * Number of tool calls made in this session
538
+ */
539
+ toolCallCount: number;
540
+ }
541
+ /**
542
+ * Session usage statistics
543
+ */
544
+ interface SessionStats {
545
+ /**
546
+ * Token usage for this session
547
+ */
548
+ usage: {
549
+ promptTokens: number;
550
+ completionTokens: number;
551
+ totalTokens: number;
552
+ };
553
+ /**
554
+ * Number of assistant responses
555
+ */
556
+ responseCount: number;
557
+ /**
558
+ * Average response time in milliseconds
559
+ */
560
+ avgResponseTime?: number;
561
+ }
562
+ /**
563
+ * Complete Session snapshot for serialization/persistence
564
+ */
565
+ interface SessionSnapshot {
566
+ /**
567
+ * Unique session identifier
568
+ */
569
+ id: string;
570
+ /**
571
+ * Creation timestamp (ms)
572
+ */
573
+ createdAt: number;
574
+ /**
575
+ * Session state information
576
+ */
577
+ state: SessionState;
578
+ /**
579
+ * Session-level configuration overrides
580
+ */
581
+ configOverride?: SessionConfigOverride;
582
+ /**
583
+ * Conversation context with message history
584
+ */
585
+ context: ConversationContext;
586
+ /**
587
+ * Usage statistics
588
+ */
589
+ stats: SessionStats;
590
+ /**
591
+ * User-defined metadata
592
+ */
593
+ metadata?: Record<string, unknown>;
594
+ }
595
+ /**
596
+ * Model configuration stored in checkpoint (serializable)
597
+ */
598
+ interface CheckpointModelConfig {
599
+ /**
600
+ * Model identifier (e.g., "gpt-4o", "claude-3-opus")
601
+ */
602
+ modelId: string;
603
+ /**
604
+ * Provider name (e.g., "openai", "anthropic")
605
+ */
606
+ provider?: string;
607
+ /**
608
+ * Model-specific configuration
609
+ */
610
+ config?: Record<string, unknown>;
611
+ }
612
+ /**
613
+ * Request parameters stored in checkpoint
614
+ */
615
+ interface CheckpointRequestParams {
616
+ /**
617
+ * Temperature for response randomness
618
+ */
619
+ temperature?: number;
620
+ /**
621
+ * Maximum tokens to generate
622
+ */
623
+ maxTokens?: number;
624
+ /**
625
+ * Stop sequences
626
+ */
627
+ stop?: string[];
628
+ /**
629
+ * Additional model-specific parameters
630
+ */
631
+ [key: string]: unknown;
632
+ }
633
+ /**
634
+ * Checkpoint of AgentLoopState for persistence and resumption.
635
+ *
636
+ * This captures the complete runtime state of an agent loop execution,
637
+ * allowing it to be saved and restored for:
638
+ * - Resuming interrupted executions
639
+ * - Debugging and inspection
640
+ * - Audit logging
641
+ */
642
+ interface AgentLoopCheckpoint {
643
+ /**
644
+ * Session ID for this execution
645
+ */
646
+ sessionId: string;
647
+ /**
648
+ * Agent ID
649
+ */
650
+ agentId: string;
651
+ /**
652
+ * Agent name (for display purposes)
653
+ */
654
+ agentName?: string;
655
+ /**
656
+ * Current loop iteration (0-indexed)
657
+ */
658
+ iteration: number;
659
+ /**
660
+ * Current phase of execution
661
+ */
662
+ phase?: 'llm_call' | 'tool_execution' | 'approval_pending' | 'completed';
663
+ /**
664
+ * Current status description (human readable)
665
+ */
666
+ status?: string;
667
+ /**
668
+ * Model configuration at checkpoint time
669
+ */
670
+ modelConfig?: CheckpointModelConfig;
671
+ /**
672
+ * Model request parameters at checkpoint time
673
+ */
674
+ requestParams?: CheckpointRequestParams;
675
+ /**
676
+ * Full message history
677
+ */
678
+ messages: Message[];
679
+ /**
680
+ * Pending tool calls (serialized)
681
+ */
682
+ pendingToolCalls: ToolCallWithResult[];
683
+ /**
684
+ * Text response accumulated so far
685
+ */
686
+ currentResponse: string;
687
+ /**
688
+ * Thinking/reasoning content (if any)
689
+ */
690
+ currentThinking?: string;
691
+ /**
692
+ * Whether the loop should continue
693
+ */
694
+ shouldContinue: boolean;
695
+ /**
696
+ * Stop reason (if stopped)
697
+ */
698
+ stopReason?: 'max_iterations' | 'final_response' | 'error' | 'cancelled' | 'approval_required';
699
+ /**
700
+ * Stop reason reported by the last model call (if available).
701
+ */
702
+ lastModelStopReason?: ModelStopReason;
703
+ /**
704
+ * Cumulative token usage
705
+ */
706
+ usage: Usage;
707
+ /**
708
+ * Custom metadata
709
+ */
710
+ metadata: Record<string, unknown>;
711
+ /**
712
+ * Timestamp when this checkpoint was saved (ms)
713
+ */
714
+ savedAt: number;
715
+ }
716
+ //#endregion
717
+ //#region src/types/event.d.ts
718
+ /**
719
+ * Event types for streaming responses
720
+ */
721
+ type AgentEventType = 'text_start' | 'text_delta' | 'text_end' | 'tool_call_start' | 'tool_call_delta' | 'tool_call_end' | 'tool_result' | 'tool_approval_requested' | 'requires_action' | 'tool_skipped' | 'thinking_start' | 'thinking_delta' | 'thinking_end' | 'done' | 'iteration_start' | 'iteration_end' | 'session_created';
722
+ /**
723
+ * Base event interface
724
+ */
725
+ interface BaseEvent {
726
+ type: AgentEventType;
727
+ /** Session identifier for this event */
728
+ sessionId: string;
729
+ }
730
+ /**
731
+ * Text start event - marks beginning of a text response
732
+ */
733
+ interface TextStartEvent extends BaseEvent {
734
+ type: 'text_start';
735
+ }
736
+ /**
737
+ * Text delta event - partial text response
738
+ */
739
+ interface TextDeltaEvent extends BaseEvent {
740
+ type: 'text_delta';
741
+ delta: string;
742
+ }
743
+ /**
744
+ * Text end event - marks end of a text response
745
+ */
746
+ interface TextEndEvent extends BaseEvent {
747
+ type: 'text_end';
748
+ /** Full text content accumulated for this response */
749
+ content: string;
750
+ }
751
+ interface ToolCallStartEvent extends BaseEvent {
752
+ type: 'tool_call_start';
753
+ callId: string;
754
+ toolName?: string;
755
+ }
756
+ interface ToolCallDeltaEvent extends BaseEvent {
757
+ type: 'tool_call_delta';
758
+ callId: string;
759
+ toolName?: string;
760
+ argsTextDelta?: string;
761
+ }
762
+ interface ToolCallEndEvent extends BaseEvent {
763
+ type: 'tool_call_end';
764
+ toolCall: ToolCall;
765
+ }
766
+ /**
767
+ * Tool result event - tool execution completed
768
+ */
769
+ interface ToolResultEvent extends BaseEvent {
770
+ type: 'tool_result';
771
+ tool_call_id: string;
772
+ result: unknown;
773
+ isError?: boolean;
774
+ }
775
+ /**
776
+ * Tool approval requested event - emitted when a high-risk tool requires approval
777
+ */
778
+ interface ToolApprovalRequestedEvent extends BaseEvent {
779
+ type: 'tool_approval_requested';
780
+ /** Tool call ID */
781
+ tool_call_id: string;
782
+ /** Name of the tool */
783
+ toolName: string;
784
+ /** Risk level of the tool */
785
+ riskLevel: RiskLevel;
786
+ /** Parsed arguments */
787
+ args: Record<string, unknown>;
788
+ }
789
+ /**
790
+ * Requires action event - execution is paused awaiting external input.
791
+ *
792
+ * This is designed for "pause → user decides → resume from checkpoint" flows.
793
+ */
794
+ interface RequiresActionEvent extends BaseEvent {
795
+ type: 'requires_action';
796
+ kind: 'tool_approval';
797
+ /**
798
+ * Checkpoint to resume from.
799
+ * If a checkpoint store is configured, this may be omitted in favor of `checkpointRef`.
800
+ */
801
+ checkpoint?: AgentLoopCheckpoint;
802
+ /**
803
+ * Reference for loading checkpoint from a store.
804
+ */
805
+ checkpointRef?: {
806
+ sessionId: string;
807
+ agentId: string;
808
+ };
809
+ }
810
+ /**
811
+ * Tool skipped event - emitted when a tool execution is skipped (e.g., approval denied)
812
+ */
813
+ interface ToolSkippedEvent extends BaseEvent {
814
+ type: 'tool_skipped';
815
+ /** Tool call ID */
816
+ tool_call_id: string;
817
+ /** Name of the tool */
818
+ toolName: string;
819
+ /** Reason for skipping */
820
+ reason: string;
821
+ }
822
+ /**
823
+ * Thinking start event - marks the beginning of a thinking phase
824
+ */
825
+ interface ThinkingStartEvent extends BaseEvent {
826
+ type: 'thinking_start';
827
+ }
828
+ /**
829
+ * Thinking delta event - model's reasoning process (incremental)
830
+ */
831
+ interface ThinkingDeltaEvent extends BaseEvent {
832
+ type: 'thinking_delta';
833
+ delta: string;
834
+ }
835
+ /**
836
+ * Thinking end event - marks the end of a thinking phase
837
+ */
838
+ interface ThinkingEndEvent extends BaseEvent {
839
+ type: 'thinking_end';
840
+ /** Full reasoning content accumulated for this thinking phase */
841
+ content?: string;
842
+ }
843
+ /**
844
+ * Done event - stream completed
845
+ */
846
+ interface DoneEvent extends BaseEvent {
847
+ type: 'done';
848
+ /** Final accumulated response text */
849
+ finalResponse?: string;
850
+ /** Stop reason for the loop */
851
+ stopReason?: 'max_iterations' | 'final_response' | 'error' | 'cancelled' | 'approval_required';
852
+ /** Stop reason reported by the last model call (if available) */
853
+ modelStopReason?: ModelStopReason;
854
+ /** Cumulative token usage for the session */
855
+ usage?: Usage;
856
+ }
857
+ /**
858
+ * Iteration start event - beginning of a loop iteration
859
+ */
860
+ interface IterationStartEvent extends BaseEvent {
861
+ type: 'iteration_start';
862
+ /** Current iteration number (0-indexed) */
863
+ iteration: number;
864
+ }
865
+ /**
866
+ * Iteration end event - end of a loop iteration
867
+ */
868
+ interface IterationEndEvent extends BaseEvent {
869
+ type: 'iteration_end';
870
+ /** Current iteration number (0-indexed) */
871
+ iteration: number;
872
+ /** Whether the loop will continue to the next iteration */
873
+ willContinue: boolean;
874
+ /** Number of tool calls made in this iteration */
875
+ toolCallCount: number;
876
+ /** Cumulative token usage up to this iteration */
877
+ usage?: Usage;
878
+ }
879
+ /**
880
+ * Session created event - emitted when a new session is automatically created
881
+ */
882
+ interface SessionCreatedEvent extends BaseEvent {
883
+ type: 'session_created';
884
+ /** Agent identifier */
885
+ agentId: string;
886
+ }
887
+ /**
888
+ * Union type for all agent events
889
+ */
890
+ type AgentEvent = TextStartEvent | TextDeltaEvent | TextEndEvent | ToolCallStartEvent | ToolCallDeltaEvent | ToolCallEndEvent | ToolResultEvent | ToolApprovalRequestedEvent | RequiresActionEvent | ToolSkippedEvent | ThinkingStartEvent | ThinkingDeltaEvent | ThinkingEndEvent | DoneEvent | IterationStartEvent | IterationEndEvent | SessionCreatedEvent;
891
+ //#endregion
892
+ //#region src/model/base.d.ts
893
+ /**
894
+ * Abstract base class for LLM model providers.
895
+ *
896
+ * Implement this class to create custom model integrations
897
+ * (e.g., OpenAI, Anthropic, local models).
898
+ */
899
+ declare abstract class BaseModel {
900
+ /**
901
+ * Model identifier
902
+ */
903
+ abstract readonly modelId: string;
904
+ /**
905
+ * One-shot completion.
906
+ *
907
+ * @param messages - Conversation history
908
+ * @param options - Optional chat parameters
909
+ * @returns Complete response with message and usage
910
+ */
911
+ abstract invoke(messages: Message[], options?: ChatOptions): Promise<ChatResponse>;
912
+ /**
913
+ * Streaming completion.
914
+ *
915
+ * @param messages - Conversation history
916
+ * @param options - Optional chat parameters
917
+ * @returns Async iterable of stream events
918
+ */
919
+ abstract stream(messages: Message[], options?: ChatOptions): AsyncIterable<StreamEvent>;
920
+ }
921
+ //#endregion
922
+ //#region src/model/adapter.d.ts
923
+ interface ModelAdapter {
924
+ readonly provider: string;
925
+ readonly defaultModelId?: string;
926
+ getDefaultCapabilities?: (modelId: string) => Partial<CoreCapabilities>;
927
+ stream: (args: {
928
+ request: ModelRequest;
929
+ }) => AsyncIterable<ModelStreamEvent>;
930
+ }
931
+ //#endregion
932
+ //#region src/model/utils/retry.d.ts
933
+ /**
934
+ * Retry strategies for calculating delay between attempts.
935
+ *
936
+ * - exponential: delay = base * 2^(attempt-1) — doubles each time (most common for APIs)
937
+ * - linear: delay = base * attempt — increases linearly
938
+ * - fixed: delay = base — constant delay
939
+ */
940
+ type RetryStrategy = 'exponential' | 'linear' | 'fixed';
941
+ /**
942
+ * Jitter strategies to avoid thundering herd problem.
943
+ *
944
+ * - full: delay = random(0, calculatedDelay)
945
+ * - equal: delay = calculatedDelay/2 + random(0, calculatedDelay/2)
946
+ * - decorrelated: delay = random(base, previousDelay * 3) — AWS-style
947
+ * - none: no jitter
948
+ */
949
+ type JitterStrategy = 'full' | 'equal' | 'decorrelated' | 'none';
950
+ interface RetryPolicyOptions {
951
+ /**
952
+ * Maximum number of attempts (including the first one).
953
+ * @default 3
954
+ */
955
+ maxAttempts?: number;
956
+ /**
957
+ * Base delay in milliseconds.
958
+ * @default 500
959
+ */
960
+ baseDelayMs?: number;
961
+ /**
962
+ * Maximum delay cap in milliseconds.
963
+ * @default 30000
964
+ */
965
+ maxDelayMs?: number;
966
+ /**
967
+ * Backoff strategy.
968
+ * @default 'exponential'
969
+ */
970
+ strategy?: RetryStrategy;
971
+ /**
972
+ * Jitter strategy to randomize delays.
973
+ * @default 'equal'
974
+ */
975
+ jitter?: JitterStrategy;
976
+ /**
977
+ * Multiplier for exponential/linear backoff.
978
+ * For exponential: delay = base * multiplier^(attempt-1)
979
+ * @default 2
980
+ */
981
+ multiplier?: number;
982
+ }
983
+ /**
984
+ * Retry policy for model requests with exponential backoff and jitter.
985
+ *
986
+ * Implements industry-standard retry patterns:
987
+ * - Exponential backoff: prevents overwhelming recovering services
988
+ * - Jitter: prevents thundering herd when many clients retry simultaneously
989
+ * - Max delay cap: prevents unbounded wait times
990
+ *
991
+ * @example
992
+ * ```ts
993
+ * // Default: exponential backoff with equal jitter
994
+ * const policy = new RetryPolicy()
995
+ *
996
+ * // Custom: 5 attempts, 1s base, 60s max, full jitter
997
+ * const policy = new RetryPolicy({
998
+ * maxAttempts: 5,
999
+ * baseDelayMs: 1000,
1000
+ * maxDelayMs: 60000,
1001
+ * jitter: 'full',
1002
+ * })
1003
+ *
1004
+ * // Usage
1005
+ * for (let attempt = 1; attempt <= policy.maxAttempts; attempt++) {
1006
+ * try {
1007
+ * await makeRequest()
1008
+ * break
1009
+ * } catch (err) {
1010
+ * if (!policy.canRetry(attempt)) throw err
1011
+ * await sleep(policy.getDelay(attempt))
1012
+ * }
1013
+ * }
1014
+ * ```
1015
+ */
1016
+ declare class RetryPolicy {
1017
+ readonly maxAttempts: number;
1018
+ readonly baseDelayMs: number;
1019
+ readonly maxDelayMs: number;
1020
+ readonly strategy: RetryStrategy;
1021
+ readonly jitter: JitterStrategy;
1022
+ readonly multiplier: number;
1023
+ private _previousDelay;
1024
+ constructor(options?: RetryPolicyOptions);
1025
+ /**
1026
+ * Calculate delay for a given attempt.
1027
+ *
1028
+ * @param attempt - Current attempt number (1-indexed)
1029
+ * @returns Delay in milliseconds with jitter applied
1030
+ */
1031
+ getDelay(attempt: number): number;
1032
+ /**
1033
+ * Apply jitter to the calculated delay.
1034
+ */
1035
+ private applyJitter;
1036
+ /**
1037
+ * Check if another retry is allowed.
1038
+ *
1039
+ * @param attempt - Current attempt number (1-indexed)
1040
+ * @returns true if more retries are allowed
1041
+ */
1042
+ canRetry(attempt: number): boolean;
1043
+ /**
1044
+ * Reset internal state (useful for decorrelated jitter).
1045
+ */
1046
+ reset(): void;
1047
+ /**
1048
+ * Get a human-readable description of the policy.
1049
+ */
1050
+ toString(): string;
1051
+ /**
1052
+ * Create default retry policy for API calls.
1053
+ * - 3 attempts
1054
+ * - 500ms base delay
1055
+ * - 30s max delay
1056
+ * - Exponential backoff with equal jitter
1057
+ */
1058
+ static readonly default: RetryPolicy;
1059
+ /**
1060
+ * Create aggressive retry policy for critical operations.
1061
+ * - 5 attempts
1062
+ * - 1s base delay
1063
+ * - 60s max delay
1064
+ */
1065
+ static readonly aggressive: RetryPolicy;
1066
+ /**
1067
+ * Create gentle retry policy for rate-limited APIs.
1068
+ * - 3 attempts
1069
+ * - 2s base delay
1070
+ * - 30s max delay
1071
+ * - Full jitter for better spread
1072
+ */
1073
+ static readonly gentle: RetryPolicy;
1074
+ }
1075
+ //#endregion
1076
+ //#region src/model/health.d.ts
1077
+ /**
1078
+ * Health state for a single model.
1079
+ */
1080
+ interface ModelHealthState {
1081
+ failures: number;
1082
+ nextRetryAt: number;
1083
+ lastError?: {
1084
+ code: string;
1085
+ message: string;
1086
+ };
1087
+ }
1088
+ /**
1089
+ * Model health manager.
1090
+ * Follows SRP: only handles health state tracking.
1091
+ */
1092
+ declare class ModelHealth {
1093
+ private readonly state;
1094
+ get(ref: ModelRef): ModelHealthState;
1095
+ markSuccess(ref: ModelRef): void;
1096
+ markFailure(ref: ModelRef, options: {
1097
+ now: number;
1098
+ baseDelayMs: number;
1099
+ maxDelayMs: number;
1100
+ code: string;
1101
+ message: string;
1102
+ }): void;
1103
+ isAvailable(ref: ModelRef, now: number): boolean;
1104
+ private keyOf;
1105
+ }
1106
+ /**
1107
+ * In-memory implementation for backward compatibility.
1108
+ */
1109
+ declare class InMemoryModelHealth extends ModelHealth {}
1110
+ //#endregion
1111
+ //#region src/model/errors.d.ts
1112
+ /**
1113
+ * Model error class.
1114
+ * Follows SRP: only handles error representation.
1115
+ */
1116
+ declare class ModelError extends Error {
1117
+ readonly code: string;
1118
+ readonly retryable: boolean;
1119
+ readonly status?: number;
1120
+ constructor(message: string, options: {
1121
+ code: string;
1122
+ retryable?: boolean;
1123
+ status?: number;
1124
+ });
1125
+ }
1126
+ //#endregion
1127
+ //#region src/model/createModel.d.ts
1128
+ /**
1129
+ * Model client returned by createModel with guaranteed setModelId method
1130
+ */
1131
+ interface CreateModelResult extends Omit<ModelClient, 'setModelId'> {
1132
+ setModelId: (modelId: string) => void;
1133
+ }
1134
+ interface CreateModelOptions {
1135
+ /**
1136
+ * Provider adapters。
1137
+ *
1138
+ * 为什么是数组:
1139
+ * - 一个 `ModelClient` 通常需要同时支持多个 provider(openai/anthropic/...),因此需要"可插拔"的 adapter 列表。
1140
+ * - `createModel()` 会把它们按 `adapter.provider` 建索引,在路由/降级时根据 `ModelRef.provider` 选择对应 adapter。
1141
+ *
1142
+ * 约束:同一个 `provider` 只应出现一次(后者会覆盖前者的索引键)。
1143
+ */
1144
+ adapters: ModelAdapter[];
1145
+ /**
1146
+ * 路由与降级策略。
1147
+ *
1148
+ * 作用:当调用方没有在 `client.stream/run({ model })` 明确指定模型时,`createModel()` 会:
1149
+ * - 根据 `fallbackOrder` 给出"尝试顺序"(primary + fallback)。
1150
+ * - 结合 `health`(熔断/退避窗口)跳过当前不可用的模型。
1151
+ *
1152
+ * @remarks 如果不提供,会自动从 adapters 的 `defaultModelId` 推导。
1153
+ */
1154
+ routing?: {
1155
+ /**
1156
+ * 候选模型的尝试顺序(从前到后)。
1157
+ *
1158
+ * - 当某个模型在本次尝试中失败(或被熔断判定暂不可用)时,会继续尝试下一个。
1159
+ * - 如果所有模型都失败,`createModel()` 会抛出最后一个错误。
1160
+ */
1161
+ fallbackOrder: ModelRef[];
1162
+ };
1163
+ /**
1164
+ * 重试策略(可选)。
1165
+ *
1166
+ * 注意:这里是 "per-model 重试" —— 每个候选模型都会单独做最多 N 次重试;
1167
+ * 若该模型最终失败,会进入 `fallbackOrder` 的下一个模型。
1168
+ *
1169
+ * 支持 Exponential Backoff(指数退避)+ Jitter(随机抖动):
1170
+ * - 指数退避:防止压垮正在恢复的服务
1171
+ * - 随机抖动:防止多个客户端同时重试(雷群效应)
1172
+ */
1173
+ retry?: {
1174
+ /**
1175
+ * 单个模型的最大尝试次数(包含第一次请求)。
1176
+ *
1177
+ * - 例如 `3` 表示:首次失败且可重试时,最多再重试 2 次。
1178
+ * - 仅当错误被判定为 `retryable`(见 `ModelError.retryable` / http 408/409/429/5xx 等)才会触发重试。
1179
+ * @default 3
1180
+ */
1181
+ maxAttemptsPerModel?: number;
1182
+ /**
1183
+ * 重试基础延迟(毫秒)。
1184
+ * @default 500
1185
+ */
1186
+ baseDelayMs?: number;
1187
+ /**
1188
+ * 最大退避延迟上限(毫秒)。
1189
+ * @default 30000
1190
+ */
1191
+ maxDelayMs?: number;
1192
+ /**
1193
+ * 退避策略。
1194
+ * - exponential: delay = base * 2^(attempt-1) — 每次翻倍(最常用)
1195
+ * - linear: delay = base * attempt — 线性增长
1196
+ * - fixed: delay = base — 固定延迟
1197
+ * @default 'exponential'
1198
+ */
1199
+ strategy?: RetryStrategy;
1200
+ /**
1201
+ * 随机抖动策略,防止雷群效应。
1202
+ * - full: delay = random(0, calculatedDelay)
1203
+ * - equal: delay = calculatedDelay/2 + random(0, calculatedDelay/2)
1204
+ * - decorrelated: AWS 风格,基于上次延迟计算
1205
+ * - none: 不加抖动
1206
+ * @default 'equal'
1207
+ */
1208
+ jitter?: JitterStrategy;
1209
+ /**
1210
+ * 重试时的回调函数,用于 debug 或日志记录。
1211
+ *
1212
+ * @param info - 重试信息
1213
+ * @param info.attempt - 当前尝试次数(1-indexed)
1214
+ * @param info.maxAttempts - 最大尝试次数
1215
+ * @param info.delayMs - 即将等待的延迟时间(毫秒)
1216
+ * @param info.error - 导致重试的错误
1217
+ * @param info.model - 当前尝试的模型
1218
+ * @param info.request - 请求详细内容(用于调试)
1219
+ */
1220
+ onRetry?: (info: {
1221
+ attempt: number;
1222
+ maxAttempts: number;
1223
+ delayMs: number;
1224
+ error: {
1225
+ code: string;
1226
+ message: string;
1227
+ retryable: boolean;
1228
+ };
1229
+ model: ModelRef;
1230
+ request: ModelRequest;
1231
+ }) => void;
1232
+ };
1233
+ /**
1234
+ * 默认超时时间(毫秒)。
1235
+ *
1236
+ * - 如果单次请求未显式传 `request.timeoutMs`,就使用这里的默认值。
1237
+ * - 超时通过 `AbortController` 触发取消,adapter 应尊重 `request.signal`。
1238
+ */
1239
+ timeoutMs?: number;
1240
+ /**
1241
+ * 模型健康度/熔断状态(可选)。
1242
+ *
1243
+ * - 默认使用内置 `InMemoryModelHealth`(进程内存级别)。
1244
+ * - 当某模型失败时,会记录 failures 并计算 `nextRetryAt`,在该时间之前路由会尽量跳过它。
1245
+ * - 你可以注入自己的实例来共享健康状态(例如在同进程多处创建 client 时复用)。
1246
+ */
1247
+ health?: InMemoryModelHealth;
1248
+ }
1249
+ declare function createModel(options: CreateModelOptions): CreateModelResult;
1250
+ //#endregion
1251
+ //#region src/model/openai/createOpenAIAdapter.d.ts
1252
+ interface OpenAIAdapterOptions {
1253
+ baseUrl?: string;
1254
+ apiKey?: string;
1255
+ defaultModelId?: string;
1256
+ organization?: string;
1257
+ project?: string;
1258
+ /**
1259
+ * Compatibility flags for OpenAI-compatible gateways/providers.
1260
+ */
1261
+ compat?: {
1262
+ /**
1263
+ * When true, ensure `reasoning_content` is present on any assistant message that contains `tool_calls`.
1264
+ * When false, never add it.
1265
+ * When undefined, use heuristics (currently: DeepSeek baseUrl/modelId).
1266
+ */
1267
+ requireReasoningContentForToolCalls?: boolean;
1268
+ };
1269
+ }
1270
+ declare function createOpenAIAdapter(options?: OpenAIAdapterOptions): ModelAdapter;
1271
+ //#endregion
1272
+ //#region src/agent/middleware.d.ts
1273
+ /**
1274
+ * Next function type for immutable middleware chain.
1275
+ *
1276
+ * Accepts the (potentially modified) state and returns the resulting state
1277
+ * after all downstream middleware and core execution have completed.
1278
+ */
1279
+ type NextFunction<State> = (state: State) => Promise<State>;
1280
+ /**
1281
+ * Middleware function type (immutable pattern)
1282
+ *
1283
+ * Middleware can intercept and transform state at each iteration.
1284
+ * Unlike mutable middleware, this pattern:
1285
+ * - Receives state as input
1286
+ * - Passes (potentially modified) state to next()
1287
+ * - Returns the final state after downstream processing
1288
+ *
1289
+ * This ensures the original state is never mutated, allowing checkpoint
1290
+ * to save original state while LLM receives processed state.
1291
+ *
1292
+ * @example
1293
+ * ```ts
1294
+ * // Logging middleware (pass-through)
1295
+ * const loggingMiddleware: Middleware = async (state, next) => {
1296
+ * console.log(`Before iteration ${state.iteration}`);
1297
+ * const result = await next(state); // Pass state unchanged
1298
+ * console.log(`After iteration ${state.iteration}`);
1299
+ * return result;
1300
+ * };
1301
+ *
1302
+ * // Transforming middleware (compression)
1303
+ * const compressionMiddleware: Middleware = async (state, next) => {
1304
+ * const compressedState = { ...state, messages: compress(state.messages) };
1305
+ * return next(compressedState); // Pass modified state
1306
+ * };
1307
+ * ```
1308
+ */
1309
+ type Middleware<State = AgentLoopState> = (state: State, next: NextFunction<State>) => Promise<State>;
1310
+ /**
1311
+ * Compose multiple middleware functions into a single function.
1312
+ *
1313
+ * This implements an immutable onion model where each middleware:
1314
+ * - Receives state from the previous middleware (or initial state)
1315
+ * - Can transform state before passing to next()
1316
+ * - Returns the result from downstream processing
1317
+ *
1318
+ * Execution order for each iteration:
1319
+ * ```
1320
+ * outer:before → inner:before → exec (model.stream) → inner:after → outer:after
1321
+ * ```
1322
+ *
1323
+ * State flow:
1324
+ * ```
1325
+ * initialState → outer(transform?) → inner(transform?) → exec → result
1326
+ * ```
1327
+ *
1328
+ * @param middleware - Array of middleware functions
1329
+ * @returns Composed middleware function that can be invoked per iteration
1330
+ *
1331
+ * @example
1332
+ * ```ts
1333
+ * const composed = compose([
1334
+ * async (state, next) => {
1335
+ * console.log('outer:before');
1336
+ * const result = await next(state);
1337
+ * console.log('outer:after');
1338
+ * return result;
1339
+ * },
1340
+ * async (state, next) => {
1341
+ * console.log('inner:before');
1342
+ * // Transform state before passing down
1343
+ * const modified = { ...state, messages: compress(state.messages) };
1344
+ * const result = await next(modified);
1345
+ * console.log('inner:after');
1346
+ * return result;
1347
+ * },
1348
+ * ]);
1349
+ *
1350
+ * // Execute with core function
1351
+ * const result = await composed(initialState, async (s) => {
1352
+ * // Core execution receives transformed state
1353
+ * await model.stream(s.messages);
1354
+ * return s;
1355
+ * });
1356
+ * ```
1357
+ */
1358
+ declare function compose<State = AgentLoopState>(middleware: Middleware<State>[]): (initialState: State, exec?: NextFunction<State>) => Promise<State>;
1359
+ //#endregion
1360
+ //#region src/state/stateStore.d.ts
1361
+ /**
1362
+ * Abstract base class for state storage.
1363
+ *
1364
+ * StateStore provides a session-centric storage abstraction where all data
1365
+ * is organized by sessionId. Each session can have multiple keys storing
1366
+ * different types of data (checkpoint, compression state, session info, etc.).
1367
+ *
1368
+ * Subclasses only need to implement the low-level storage primitives:
1369
+ * - _write: Write data to a path
1370
+ * - _read: Read data from a path
1371
+ * - _delete: Delete data at a path
1372
+ * - _exists: Check if data exists at a path
1373
+ * - _list: List all paths with a given prefix
1374
+ *
1375
+ * The base class provides:
1376
+ * - High-level API for session-based storage (save, load, delete, etc.)
1377
+ * - Convenience methods for checkpoint operations
1378
+ * - JSON serialization/deserialization
1379
+ *
1380
+ * @example
1381
+ * ```typescript
1382
+ * // Using with an agent
1383
+ * const store = new FileStateStore({ dir: './state' })
1384
+ *
1385
+ * const agent = new Agent({
1386
+ * name: 'MyAgent',
1387
+ * stateStore: store,
1388
+ * // ...
1389
+ * })
1390
+ *
1391
+ * // Manual state operations
1392
+ * await store.save(sessionId, 'custom-key', { myData: 123 })
1393
+ * const data = await store.load(sessionId, 'custom-key')
1394
+ * ```
1395
+ */
1396
+ declare abstract class StateStore {
1397
+ /**
1398
+ * When to save checkpoints during agent execution.
1399
+ */
1400
+ readonly savePoint: 'before' | 'after' | 'both';
1401
+ /**
1402
+ * Whether to delete checkpoint after successful completion.
1403
+ */
1404
+ readonly deleteOnComplete: boolean;
1405
+ constructor(options?: StateStoreOptions);
1406
+ /**
1407
+ * Save data for a session under a specific key.
1408
+ *
1409
+ * @param sessionId - Session identifier
1410
+ * @param key - Data key (e.g., 'checkpoint', 'compression', or custom keys)
1411
+ * @param data - Data to save (will be JSON serialized)
1412
+ */
1413
+ save<T>(sessionId: string, key: string, data: T): Promise<void>;
1414
+ /**
1415
+ * Load data for a session by key.
1416
+ *
1417
+ * @param sessionId - Session identifier
1418
+ * @param key - Data key
1419
+ * @returns The data or undefined if not found
1420
+ */
1421
+ load<T>(sessionId: string, key: string): Promise<T | undefined>;
1422
+ /**
1423
+ * Delete data for a session by key.
1424
+ *
1425
+ * @param sessionId - Session identifier
1426
+ * @param key - Data key
1427
+ */
1428
+ delete(sessionId: string, key: string): Promise<void>;
1429
+ /**
1430
+ * Delete all data for a session.
1431
+ *
1432
+ * @param sessionId - Session identifier
1433
+ */
1434
+ deleteSession(sessionId: string): Promise<void>;
1435
+ /**
1436
+ * List all keys for a session.
1437
+ *
1438
+ * @param sessionId - Session identifier
1439
+ * @returns Array of keys
1440
+ */
1441
+ listKeys(sessionId: string): Promise<string[]>;
1442
+ /**
1443
+ * Check if data exists for a session key.
1444
+ *
1445
+ * @param sessionId - Session identifier
1446
+ * @param key - Data key
1447
+ * @returns True if data exists
1448
+ */
1449
+ exists(sessionId: string, key: string): Promise<boolean>;
1450
+ /**
1451
+ * Save an agent loop checkpoint.
1452
+ *
1453
+ * This is a convenience method that saves the checkpoint under the
1454
+ * predefined CHECKPOINT key with additional metadata.
1455
+ *
1456
+ * @param checkpoint - Checkpoint to save
1457
+ */
1458
+ saveCheckpoint(checkpoint: AgentLoopCheckpoint): Promise<void>;
1459
+ /**
1460
+ * Load an agent loop checkpoint by session ID.
1461
+ *
1462
+ * @param sessionId - Session identifier
1463
+ * @returns Checkpoint or undefined if not found
1464
+ */
1465
+ loadCheckpoint(sessionId: string): Promise<AgentLoopCheckpoint | undefined>;
1466
+ /**
1467
+ * Delete an agent loop checkpoint.
1468
+ *
1469
+ * @param sessionId - Session identifier
1470
+ */
1471
+ deleteCheckpoint(sessionId: string): Promise<void>;
1472
+ /**
1473
+ * List all checkpoints across all sessions.
1474
+ *
1475
+ * @returns Array of checkpoints
1476
+ */
1477
+ listCheckpoints(): Promise<AgentLoopCheckpoint[]>;
1478
+ /**
1479
+ * List all session IDs that have stored data.
1480
+ *
1481
+ * @returns Array of session IDs
1482
+ */
1483
+ listSessions(): Promise<string[]>;
1484
+ /**
1485
+ * Build a storage path from sessionId and key.
1486
+ * Default format: `{sessionId}/{key}`
1487
+ *
1488
+ * Subclasses can override this for different path formats.
1489
+ */
1490
+ protected buildPath(sessionId: string, key: string): string;
1491
+ /**
1492
+ * Build a prefix for listing all data under a session.
1493
+ * Default format: `{sessionId}/`
1494
+ */
1495
+ protected buildPrefix(sessionId: string): string;
1496
+ /**
1497
+ * Extract the key from a full path.
1498
+ */
1499
+ protected extractKey(sessionId: string, path: string): string;
1500
+ /**
1501
+ * Extract the sessionId from a full path.
1502
+ */
1503
+ protected extractSessionId(path: string): string | undefined;
1504
+ /**
1505
+ * Write data to a storage path.
1506
+ *
1507
+ * @param path - Storage path
1508
+ * @param data - Serialized data string
1509
+ */
1510
+ protected abstract _write(path: string, data: string): Promise<void>;
1511
+ /**
1512
+ * Read data from a storage path.
1513
+ *
1514
+ * @param path - Storage path
1515
+ * @returns Data string or undefined if not found
1516
+ */
1517
+ protected abstract _read(path: string): Promise<string | undefined>;
1518
+ /**
1519
+ * Delete data at a storage path.
1520
+ *
1521
+ * @param path - Storage path
1522
+ */
1523
+ protected abstract _delete(path: string): Promise<void>;
1524
+ /**
1525
+ * Check if data exists at a storage path.
1526
+ *
1527
+ * @param path - Storage path
1528
+ * @returns True if data exists
1529
+ */
1530
+ protected abstract _exists(path: string): Promise<boolean>;
1531
+ /**
1532
+ * List all paths with a given prefix.
1533
+ *
1534
+ * @param prefix - Path prefix (empty string for all paths)
1535
+ * @returns Array of full paths
1536
+ */
1537
+ protected abstract _list(prefix: string): Promise<string[]>;
1538
+ }
1539
+ //#endregion
1540
+ //#region src/middleware/contextCompressionMiddleware.d.ts
1541
+ /**
1542
+ * Configuration options for context compression middleware.
1543
+ */
1544
+ interface ContextCompressionOptions {
1545
+ /**
1546
+ * Maximum context token limit (e.g., 128000 for GPT-4).
1547
+ */
1548
+ contextLimit: number;
1549
+ /**
1550
+ * Reserved tokens for model output.
1551
+ * Compression triggers when used tokens > (contextLimit - outputLimit).
1552
+ */
1553
+ outputLimit: number;
1554
+ /**
1555
+ * Number of recent conversation turns to always protect (default: 2).
1556
+ * A turn is a user message + assistant response pair.
1557
+ */
1558
+ protectedTurns?: number;
1559
+ /**
1560
+ * Maximum tokens of recent tool outputs to protect (default: 40000).
1561
+ * Tool outputs within this limit won't be cleared.
1562
+ */
1563
+ protectedToolTokens?: number;
1564
+ /**
1565
+ * Threshold for trimming individual tool outputs (default: 20000).
1566
+ * Protected tool outputs exceeding this will be truncated (not cleared).
1567
+ */
1568
+ trimToolOutputThreshold?: number;
1569
+ /**
1570
+ * Whether to generate a summary of cleared content (default: false).
1571
+ * If true, requires model or getModel to be provided.
1572
+ */
1573
+ enableSummary?: boolean;
1574
+ /**
1575
+ * Model to use for generating summaries (only needed if enableSummary is true).
1576
+ */
1577
+ model?: ModelClient;
1578
+ /**
1579
+ * Function to get the model for generating summaries.
1580
+ * Useful when you want to reuse the same model client:
1581
+ * `getModel: () => model`
1582
+ */
1583
+ getModel?: () => ModelClient;
1584
+ /**
1585
+ * Custom prompt for summary generation.
1586
+ * Supports template placeholders:
1587
+ * - {{existingSummary}}: prior rolling summary (may be empty)
1588
+ * - {{toolOutputs}}: formatted cleared tool outputs
1589
+ */
1590
+ summaryPrompt?: string;
1591
+ /**
1592
+ * State store for persisting compression state.
1593
+ * If provided, compression stats, history, and summaries will be saved.
1594
+ */
1595
+ stateStore?: StateStore;
1596
+ /**
1597
+ * Function to get the state store.
1598
+ * Useful when you want to use the agent's state store: `getStateStore: () => agent.stateStore`
1599
+ */
1600
+ getStateStore?: () => StateStore | undefined;
1601
+ /**
1602
+ * Whether to persist compressed messages to state store (default: false).
1603
+ * When enabled, each compression will save a snapshot file with compressed messages.
1604
+ * This requires stateStore or getStateStore to be provided.
1605
+ *
1606
+ * Each compression saves a separate file: `compression-snapshot-${timestamp}.json`
1607
+ * Useful for debugging or auditing compressed message states.
1608
+ */
1609
+ persistClearedContent?: boolean;
1610
+ /**
1611
+ * Callback when compression is triggered.
1612
+ */
1613
+ onCompressionStart?: (stats: CompressionStats) => void;
1614
+ /**
1615
+ * Callback when compression completes.
1616
+ */
1617
+ onCompressionEnd?: (stats: CompressionStats) => void;
1618
+ }
1619
+ /**
1620
+ * Statistics about the compression operation.
1621
+ */
1622
+ interface CompressionStats {
1623
+ /** Token count before compression */
1624
+ tokensBefore: number;
1625
+ /** Token count after compression */
1626
+ tokensAfter: number;
1627
+ /** Number of tool outputs that were cleared */
1628
+ clearedToolOutputs: number;
1629
+ /** Number of tool outputs that were trimmed (but not cleared) */
1630
+ trimmedToolOutputs: number;
1631
+ /** Whether a summary was generated */
1632
+ summaryGenerated: boolean;
1633
+ /** Timestamp when this compression occurred */
1634
+ timestamp?: number;
1635
+ }
1636
+ /**
1637
+ * Create a context compression middleware.
1638
+ *
1639
+ * This middleware automatically compresses conversation history when it exceeds
1640
+ * the configured token limit. It follows an immutable pattern - original messages
1641
+ * are never modified. Instead, compressed messages are passed to the LLM while
1642
+ * the original messages remain unchanged (preserved for checkpoint).
1643
+ *
1644
+ * Compression strategy:
1645
+ * 1. Preserve message structure (all messages remain, including tool calls)
1646
+ * 2. Protect recent N turns completely
1647
+ * 3. Protect recent tool outputs up to token limit
1648
+ * 4. Clear old tool outputs with placeholder: "[Old tool result content cleared]"
1649
+ * 5. Optionally generate a summary of cleared content
1650
+ *
1651
+ * @param options - Compression configuration options
1652
+ * @returns Middleware function
1653
+ *
1654
+ * @example
1655
+ * ```ts
1656
+ * const agent = new Agent({ model, ... })
1657
+ *
1658
+ * // Basic usage - just clear old tool outputs
1659
+ * agent.use(createContextCompressionMiddleware({
1660
+ * contextLimit: 128000,
1661
+ * outputLimit: 4096,
1662
+ * }))
1663
+ *
1664
+ * // With summary generation and persistence
1665
+ * agent.use(createContextCompressionMiddleware({
1666
+ * contextLimit: 128000,
1667
+ * outputLimit: 4096,
1668
+ * enableSummary: true,
1669
+ * getModel: () => model,
1670
+ * getStateStore: () => agent.stateStore,
1671
+ * }))
1672
+ * ```
1673
+ */
1674
+ declare function createContextCompressionMiddleware(options: ContextCompressionOptions): Middleware<AgentLoopState>;
1675
+ /**
1676
+ * Options for manual compression.
1677
+ */
1678
+ interface ManualCompressionOptions {
1679
+ /**
1680
+ * Session ID for the compression.
1681
+ */
1682
+ sessionId: string;
1683
+ /**
1684
+ * Full messages from the session (including all history).
1685
+ * These should be the complete, uncompressed messages.
1686
+ */
1687
+ fullMessages: Message[];
1688
+ /**
1689
+ * Model to use for generating summary.
1690
+ */
1691
+ model: ModelClient;
1692
+ /**
1693
+ * State store for persisting compression state.
1694
+ */
1695
+ stateStore: StateStore;
1696
+ /**
1697
+ * Custom prompt for summary generation (optional).
1698
+ * If not provided, uses DEFAULT_SUMMARY_PROMPT.
1699
+ */
1700
+ summaryPrompt?: string;
1701
+ }
1702
+ /**
1703
+ * Result of manual compression.
1704
+ */
1705
+ interface ManualCompressionResult {
1706
+ /**
1707
+ * Generated summary.
1708
+ */
1709
+ summary: string;
1710
+ /**
1711
+ * Number of messages processed.
1712
+ */
1713
+ messageCount: number;
1714
+ /**
1715
+ * Number of tool outputs found.
1716
+ */
1717
+ toolOutputCount: number;
1718
+ }
1719
+ /**
1720
+ * Manually compress a session by generating a summary from full message history.
1721
+ *
1722
+ * This function extracts all tool outputs from the full messages and generates
1723
+ * a new summary based on the complete context. The summary is saved to
1724
+ * CompressionState and will be automatically loaded by the middleware on next run.
1725
+ *
1726
+ * @param options - Manual compression options
1727
+ * @returns Compression result with generated summary
1728
+ *
1729
+ * @example
1730
+ * ```ts
1731
+ * const result = await compressSessionManually({
1732
+ * sessionId: 'session-123',
1733
+ * fullMessages: allMessages,
1734
+ * model: myModel,
1735
+ * stateStore: myStore,
1736
+ * })
1737
+ * console.log(`Generated summary: ${result.summary}`)
1738
+ * ```
1739
+ */
1740
+ declare function compressSessionManually(options: ManualCompressionOptions): Promise<ManualCompressionResult>;
1741
+ //#endregion
1742
+ //#region src/state/types.d.ts
1743
+ /**
1744
+ * State store configuration options.
1745
+ */
1746
+ interface StateStoreOptions {
1747
+ /**
1748
+ * When to save checkpoints:
1749
+ * - 'before': Save before each iteration (default)
1750
+ * - 'after': Save after each iteration
1751
+ * - 'both': Save before and after
1752
+ */
1753
+ savePoint?: 'before' | 'after' | 'both';
1754
+ /**
1755
+ * Whether to delete the checkpoint after successful completion.
1756
+ * Default: true
1757
+ */
1758
+ deleteOnComplete?: boolean;
1759
+ }
1760
+ /**
1761
+ * Predefined state keys for common data types.
1762
+ */
1763
+ declare const StateKeys: {
1764
+ /** AgentLoopCheckpoint data */
1765
+ readonly CHECKPOINT: "checkpoint";
1766
+ /** CompressionState data */
1767
+ readonly COMPRESSION: "compression";
1768
+ /** SessionSnapshot data */
1769
+ readonly SESSION: "session";
1770
+ /**
1771
+ * Compressed messages snapshot key pattern.
1772
+ * Use with timestamp: `compression-snapshot-${timestamp}`
1773
+ */
1774
+ readonly COMPRESSION_SNAPSHOT: "compression-snapshot";
1775
+ };
1776
+ type StateKey = (typeof StateKeys)[keyof typeof StateKeys];
1777
+ /**
1778
+ * Compression state for context compression middleware.
1779
+ *
1780
+ * This stores all compression-related data for a session,
1781
+ * allowing the middleware to restore its state after a restart.
1782
+ */
1783
+ interface CompressionState {
1784
+ /**
1785
+ * Statistics from the last compression operation.
1786
+ */
1787
+ lastStats?: CompressionStats;
1788
+ /**
1789
+ * History of all compression operations.
1790
+ */
1791
+ history: CompressionStats[];
1792
+ /**
1793
+ * Accumulated summary content from cleared tool outputs.
1794
+ * This can be used when resuming from a checkpoint to provide context.
1795
+ */
1796
+ summary?: string;
1797
+ /**
1798
+ * Last update timestamp (ms).
1799
+ */
1800
+ updatedAt: number;
1801
+ }
1802
+ //#endregion
1803
+ //#region src/state/FileStateStore.d.ts
1804
+ /**
1805
+ * Options for creating a FileStateStore.
1806
+ */
1807
+ interface FileStateStoreOptions extends StateStoreOptions {
1808
+ /**
1809
+ * Directory path for storing state files.
1810
+ */
1811
+ dir: string;
1812
+ }
1813
+ /**
1814
+ * File-based implementation of StateStore.
1815
+ *
1816
+ * Stores state data as JSON files in a directory structure organized by session:
1817
+ *
1818
+ * ```
1819
+ * <baseDir>/
1820
+ * <sessionId>/
1821
+ * checkpoint.json
1822
+ * compression.json
1823
+ * session.json
1824
+ * custom-key.json
1825
+ * ```
1826
+ *
1827
+ * @example
1828
+ * ```typescript
1829
+ * const store = new FileStateStore({
1830
+ * dir: './state',
1831
+ * savePoint: 'before',
1832
+ * deleteOnComplete: true,
1833
+ * })
1834
+ *
1835
+ * const agent = new Agent({
1836
+ * name: 'MyAgent',
1837
+ * stateStore: store,
1838
+ * // ...
1839
+ * })
1840
+ * ```
1841
+ */
1842
+ declare class FileStateStore extends StateStore {
1843
+ private baseDir;
1844
+ constructor(options: FileStateStoreOptions);
1845
+ protected _write(storagePath: string, data: string): Promise<void>;
1846
+ protected _read(storagePath: string): Promise<string | undefined>;
1847
+ protected _delete(storagePath: string): Promise<void>;
1848
+ protected _exists(storagePath: string): Promise<boolean>;
1849
+ protected _list(prefix: string): Promise<string[]>;
1850
+ /**
1851
+ * Convert storage path to file system path.
1852
+ * Storage path: `{sessionId}/{key}`
1853
+ * File path: `{baseDir}/{sessionId}/{key}.json`
1854
+ */
1855
+ private toFilePath;
1856
+ /**
1857
+ * Ensure a directory exists.
1858
+ */
1859
+ private ensureDir;
1860
+ /**
1861
+ * List all JSON files in a directory.
1862
+ */
1863
+ private listJsonFiles;
1864
+ /**
1865
+ * Get the base directory path.
1866
+ */
1867
+ getBaseDir(): string;
1868
+ /**
1869
+ * Clear all state data from the store.
1870
+ * WARNING: This will delete all files in the base directory.
1871
+ */
1872
+ clear(): void;
1873
+ }
1874
+ //#endregion
1875
+ //#region src/state/InMemoryStateStore.d.ts
1876
+ /**
1877
+ * In-memory implementation of StateStore.
1878
+ *
1879
+ * Useful for development, testing, and short-lived applications.
1880
+ * Data is lost when the process exits.
1881
+ *
1882
+ * @example
1883
+ * ```typescript
1884
+ * const store = new InMemoryStateStore({
1885
+ * savePoint: 'before',
1886
+ * deleteOnComplete: true,
1887
+ * })
1888
+ *
1889
+ * const agent = new Agent({
1890
+ * name: 'MyAgent',
1891
+ * stateStore: store,
1892
+ * // ...
1893
+ * })
1894
+ * ```
1895
+ */
1896
+ declare class InMemoryStateStore extends StateStore {
1897
+ /**
1898
+ * Internal storage: path -> data
1899
+ */
1900
+ private store;
1901
+ constructor(options?: StateStoreOptions);
1902
+ protected _write(path: string, data: string): Promise<void>;
1903
+ protected _read(path: string): Promise<string | undefined>;
1904
+ protected _delete(path: string): Promise<void>;
1905
+ protected _exists(path: string): Promise<boolean>;
1906
+ protected _list(prefix: string): Promise<string[]>;
1907
+ /**
1908
+ * Clear all data from the store.
1909
+ * Useful for testing.
1910
+ */
1911
+ clear(): void;
1912
+ /**
1913
+ * Get statistics about the store.
1914
+ */
1915
+ stats(): {
1916
+ entryCount: number;
1917
+ sessionCount: number;
1918
+ };
1919
+ }
1920
+ //#endregion
1921
+ //#region src/tool/base.d.ts
1922
+ /**
1923
+ * Helper to create a text content block for CallToolResult
1924
+ */
1925
+ declare function textContent(text: string): CallToolResult;
1926
+ /**
1927
+ * Helper to create an error result for CallToolResult
1928
+ */
1929
+ declare function errorContent(error: string): CallToolResult;
1930
+ /**
1931
+ * Helper to create an image content block for CallToolResult
1932
+ */
1933
+ declare function imageContent(data: string, mimeType: string): CallToolResult;
1934
+ /**
1935
+ * Abstract base class for tools.
1936
+ *
1937
+ * Tools are capabilities that the agent can invoke during execution.
1938
+ * Implement this class to create custom tools.
1939
+ *
1940
+ * All tool execute() methods must return MCP SDK-compliant CallToolResult:
1941
+ * - content: array of ContentBlock (TextContent, ImageContent, etc.)
1942
+ * - isError: optional boolean to indicate error
1943
+ * - structuredContent: optional structured data object
1944
+ */
1945
+ declare abstract class BaseTool {
1946
+ /**
1947
+ * Unique name of the tool (used by LLM to invoke)
1948
+ */
1949
+ abstract readonly name: string;
1950
+ /**
1951
+ * Human-readable description of what the tool does
1952
+ */
1953
+ abstract readonly description: string;
1954
+ /**
1955
+ * JSON Schema defining the tool's input parameters
1956
+ */
1957
+ abstract readonly parameters: ToolInputSchema;
1958
+ /**
1959
+ * Risk level of the tool, used to determine if user approval is required.
1960
+ *
1961
+ * - 'safe': No risk, read-only operations (default)
1962
+ * - 'low': Low risk, minimal side effects
1963
+ * - 'medium': Medium risk, reversible changes
1964
+ * - 'high': High risk, file modifications
1965
+ * - 'critical': Critical risk, arbitrary command execution
1966
+ */
1967
+ readonly riskLevel: RiskLevel;
1968
+ /**
1969
+ * Execute the tool with given arguments
1970
+ *
1971
+ * @param args - Tool arguments matching the parameters schema
1972
+ * @param ctx - Optional runtime context provided by the Agent
1973
+ * @returns Tool execution result conforming to MCP SDK CallToolResult
1974
+ */
1975
+ abstract execute(args: Record<string, unknown>, ctx?: ToolExecutionContext): Promise<CallToolResult>;
1976
+ }
1977
+ //#endregion
1978
+ //#region src/tool/builtin/glob.d.ts
1979
+ /**
1980
+ * Result of a glob operation
1981
+ */
1982
+ interface GlobResult {
1983
+ /** List of matched file paths (sorted by modification time, newest first) */
1984
+ files: string[];
1985
+ /** Total number of matches found */
1986
+ totalMatches: number;
1987
+ /** Whether results were truncated */
1988
+ truncated: boolean;
1989
+ }
1990
+ /**
1991
+ * Arguments for the Glob tool
1992
+ */
1993
+ interface GlobArgs {
1994
+ /** The glob pattern to match files against */
1995
+ pattern: string;
1996
+ /** The directory to search in (defaults to cwd) */
1997
+ path?: string;
1998
+ }
1999
+ /**
2000
+ * Tool for finding files matching glob patterns.
2001
+ *
2002
+ * This tool provides fast file pattern matching that works with any codebase size,
2003
+ * returning matching file paths sorted by modification time.
2004
+ *
2005
+ * @example
2006
+ * ```typescript
2007
+ * const globTool = new GlobTool()
2008
+ * const result = await globTool.execute({
2009
+ * pattern: '**\/*.ts',
2010
+ * path: './src'
2011
+ * })
2012
+ * ```
2013
+ */
2014
+ declare class GlobTool extends BaseTool {
2015
+ readonly name = "Glob";
2016
+ readonly description = "Fast file pattern matching tool that works with any codebase size.\n\nUsage notes:\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted by modification time (newest first)\n- Use this tool when you need to find files by name patterns\n- You can call multiple tools in a single response for parallel searches\n\nSupported patterns:\n- `*` matches any sequence of characters except path separator\n- `**` matches any sequence of characters including path separator\n- `?` matches any single character\n- `{a,b}` matches either a or b\n- `[abc]` matches any character in brackets";
2017
+ readonly parameters: ToolInputSchema;
2018
+ /** Current working directory for search */
2019
+ private cwd;
2020
+ constructor(options?: {
2021
+ cwd?: string;
2022
+ });
2023
+ /**
2024
+ * Set the current working directory
2025
+ */
2026
+ setCwd(cwd: string): void;
2027
+ /**
2028
+ * Get the current working directory
2029
+ */
2030
+ getCwd(): string;
2031
+ /**
2032
+ * Execute glob pattern matching
2033
+ *
2034
+ * @param args - Glob arguments
2035
+ * @returns MCP-compliant CallToolResult with matching files
2036
+ */
2037
+ execute(args: Record<string, unknown>): Promise<CallToolResult>;
2038
+ /**
2039
+ * Validate and parse arguments
2040
+ */
2041
+ private validateArgs;
2042
+ /**
2043
+ * Recursively walk directory and collect matching files
2044
+ */
2045
+ private walkDirectory;
2046
+ }
2047
+ //#endregion
2048
+ //#region src/tool/builtin/grep.d.ts
2049
+ /**
2050
+ * Output modes for grep results
2051
+ */
2052
+ type GrepOutputMode = 'content' | 'files_with_matches' | 'count';
2053
+ /**
2054
+ * Result of a grep operation
2055
+ */
2056
+ interface GrepResult {
2057
+ /** Command exit code */
2058
+ exitCode: number | null;
2059
+ /** Backend used for the search */
2060
+ engine?: 'rg' | 'grep';
2061
+ /** Search output */
2062
+ output: string;
2063
+ /** Whether output was truncated */
2064
+ truncated: boolean;
2065
+ /** Whether search timed out */
2066
+ timedOut: boolean;
2067
+ /** Number of matches found (when available) */
2068
+ matchCount?: number;
2069
+ }
2070
+ /**
2071
+ * Arguments for the Grep tool
2072
+ */
2073
+ interface GrepArgs {
2074
+ /** The regular expression pattern to search for */
2075
+ pattern: string;
2076
+ /** File or directory to search in */
2077
+ path?: string;
2078
+ /** Glob pattern to filter files */
2079
+ glob?: string;
2080
+ /** Output mode */
2081
+ output_mode?: GrepOutputMode;
2082
+ /** Lines before match */
2083
+ '-B'?: number;
2084
+ /** Lines after match */
2085
+ '-A'?: number;
2086
+ /** Lines before and after match */
2087
+ '-C'?: number;
2088
+ /** Show line numbers */
2089
+ '-n'?: boolean;
2090
+ /** Case insensitive search */
2091
+ '-i'?: boolean;
2092
+ /** File type to search */
2093
+ type?: string;
2094
+ /** Limit output to first N lines/entries */
2095
+ head_limit?: number;
2096
+ /** Skip first N lines/entries */
2097
+ offset?: number;
2098
+ /** Enable multiline mode */
2099
+ multiline?: boolean;
2100
+ }
2101
+ /**
2102
+ * Tool for searching files using ripgrep.
2103
+ *
2104
+ * A powerful search tool built on ripgrep that supports regex patterns,
2105
+ * multiple output modes, and various filtering options.
2106
+ *
2107
+ * @example
2108
+ * ```typescript
2109
+ * const grepTool = new GrepTool()
2110
+ * const result = await grepTool.execute({
2111
+ * pattern: 'function\\s+\\w+',
2112
+ * path: './src',
2113
+ * type: 'ts'
2114
+ * })
2115
+ * ```
2116
+ */
2117
+ declare class GrepTool extends BaseTool {
2118
+ readonly name = "Grep";
2119
+ readonly description = "A powerful search tool built on ripgrep.\n\nUsage notes:\n- Supports full regex syntax (e.g., \"log.*Error\", \"function\\s+\\w+\")\n- Filter files with glob parameter (e.g., \"*.js\", \"**/*.tsx\") or type parameter (e.g., \"js\", \"py\", \"rust\")\n- Output modes: \"content\" shows matching lines, \"files_with_matches\" shows only file paths (default), \"count\" shows match counts\n- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n- Multiline matching: By default patterns match within single lines only. For cross-line patterns, use multiline: true";
2120
+ readonly parameters: ToolInputSchema;
2121
+ /** Current working directory for search */
2122
+ private cwd;
2123
+ /** Path to ripgrep binary */
2124
+ private rgPath;
2125
+ constructor(options?: {
2126
+ cwd?: string;
2127
+ rgPath?: string;
2128
+ });
2129
+ /**
2130
+ * Set the current working directory
2131
+ */
2132
+ setCwd(cwd: string): void;
2133
+ /**
2134
+ * Get the current working directory
2135
+ */
2136
+ getCwd(): string;
2137
+ /**
2138
+ * Execute grep search
2139
+ *
2140
+ * @param args - Grep arguments
2141
+ * @returns MCP-compliant CallToolResult with search results
2142
+ */
2143
+ execute(args: Record<string, unknown>): Promise<CallToolResult>;
2144
+ /**
2145
+ * Validate and parse arguments
2146
+ */
2147
+ private validateArgs;
2148
+ /**
2149
+ * Build ripgrep command arguments
2150
+ */
2151
+ private buildRgArgs;
2152
+ /**
2153
+ * Run ripgrep command
2154
+ */
2155
+ private runRipgrep;
2156
+ private runSystemGrep;
2157
+ }
2158
+ //#endregion
2159
+ //#region src/tool/builtin/read.d.ts
2160
+ /**
2161
+ * Result of a file read operation
2162
+ */
2163
+ interface ReadResult {
2164
+ /** File content with line numbers */
2165
+ content: string;
2166
+ /** Total number of lines in file */
2167
+ totalLines: number;
2168
+ /** Number of lines returned */
2169
+ linesReturned: number;
2170
+ /** Starting line number (1-based) */
2171
+ startLine: number;
2172
+ /** Whether any lines were truncated */
2173
+ truncated: boolean;
2174
+ /** File size in bytes */
2175
+ fileSize: number;
2176
+ /** Whether this is a binary/image file */
2177
+ isBinary: boolean;
2178
+ /** MIME type if detected */
2179
+ mimeType?: string;
2180
+ }
2181
+ /**
2182
+ * Arguments for the Read tool
2183
+ */
2184
+ interface ReadArgs {
2185
+ /** The absolute path to the file to read */
2186
+ file_path: string;
2187
+ /** The line number to start reading from (1-based) */
2188
+ offset?: number;
2189
+ /** The number of lines to read */
2190
+ limit?: number;
2191
+ }
2192
+ /**
2193
+ * Tool for reading files from the filesystem.
2194
+ *
2195
+ * This tool reads files with line number formatting, supporting
2196
+ * offset/limit for large files and detecting binary content.
2197
+ *
2198
+ * @example
2199
+ * ```typescript
2200
+ * const readTool = new ReadTool()
2201
+ * const result = await readTool.execute({
2202
+ * file_path: '/path/to/file.ts',
2203
+ * offset: 100,
2204
+ * limit: 50
2205
+ * })
2206
+ * ```
2207
+ *
2208
+ * @example Restrict reads to a specific directory
2209
+ * ```typescript
2210
+ * const readTool = new ReadTool({
2211
+ * cwd: '/app/output',
2212
+ * restrictToDirectory: true
2213
+ * })
2214
+ * // All paths will be resolved relative to /app/output
2215
+ * // Absolute paths and path traversal (../) will be blocked
2216
+ * ```
2217
+ */
2218
+ declare class ReadTool extends BaseTool {
2219
+ readonly name = "Read";
2220
+ /** Current working directory for resolving relative paths */
2221
+ private _cwd;
2222
+ /** Allowed directory for file operations (if set, restricts reads to this directory) */
2223
+ private _allowedDirectory?;
2224
+ constructor(options?: {
2225
+ cwd?: string;
2226
+ /** If set, restricts all file reads to this directory. Paths outside will be rejected. */
2227
+ allowedDirectory?: string;
2228
+ });
2229
+ /**
2230
+ * Dynamic description that includes allowed directory info if configured
2231
+ */
2232
+ get description(): string;
2233
+ /**
2234
+ * Dynamic parameters that include allowed directory info if configured
2235
+ */
2236
+ get parameters(): ToolInputSchema;
2237
+ /**
2238
+ * Set the current working directory
2239
+ */
2240
+ setCwd(cwd: string): void;
2241
+ /**
2242
+ * Get the current working directory
2243
+ */
2244
+ getCwd(): string;
2245
+ /**
2246
+ * Set the allowed directory for file operations
2247
+ */
2248
+ setAllowedDirectory(dir: string | undefined): void;
2249
+ /**
2250
+ * Get the allowed directory for file operations
2251
+ */
2252
+ getAllowedDirectory(): string | undefined;
2253
+ /**
2254
+ * Execute file read
2255
+ *
2256
+ * @param args - Read arguments
2257
+ * @returns MCP-compliant CallToolResult with file content
2258
+ */
2259
+ execute(args: Record<string, unknown>): Promise<CallToolResult>;
2260
+ /**
2261
+ * Validate and parse arguments
2262
+ */
2263
+ private validateArgs;
2264
+ /**
2265
+ * Handle binary file (images, PDFs, etc.)
2266
+ */
2267
+ private handleBinaryFile;
2268
+ /**
2269
+ * Handle Jupyter notebook file
2270
+ */
2271
+ private handleJupyterNotebook;
2272
+ /**
2273
+ * Handle text file
2274
+ */
2275
+ private handleTextFile;
2276
+ /**
2277
+ * Format output with line numbers and apply offset/limit
2278
+ */
2279
+ private formatOutput;
2280
+ /**
2281
+ * Format file size for display
2282
+ */
2283
+ private formatSize;
2284
+ }
2285
+ //#endregion
2286
+ //#region src/tool/builtin/edit.d.ts
2287
+ /**
2288
+ * Result of an edit operation
2289
+ */
2290
+ interface EditResult {
2291
+ /** Whether the edit was successful */
2292
+ success: boolean;
2293
+ /** Number of replacements made */
2294
+ replacements: number;
2295
+ /** File path that was edited */
2296
+ filePath: string;
2297
+ /** Brief description of the edit */
2298
+ message: string;
2299
+ }
2300
+ /**
2301
+ * Arguments for the Edit tool
2302
+ */
2303
+ interface EditArgs {
2304
+ /** The absolute path to the file to modify */
2305
+ file_path: string;
2306
+ /** The text to replace */
2307
+ old_string: string;
2308
+ /** The text to replace it with */
2309
+ new_string: string;
2310
+ /** Replace all occurrences (default false) */
2311
+ replace_all?: boolean;
2312
+ }
2313
+ /**
2314
+ * Tool for performing exact string replacements in files.
2315
+ *
2316
+ * This tool finds and replaces text in files with careful handling
2317
+ * of unique matches and the option to replace all occurrences.
2318
+ *
2319
+ * @example
2320
+ * ```typescript
2321
+ * const editTool = new EditTool()
2322
+ * const result = await editTool.execute({
2323
+ * file_path: '/path/to/file.ts',
2324
+ * old_string: 'const foo = 1',
2325
+ * new_string: 'const foo = 2'
2326
+ * })
2327
+ * ```
2328
+ */
2329
+ declare class EditTool extends BaseTool {
2330
+ readonly name = "Edit";
2331
+ readonly riskLevel: "high";
2332
+ readonly description = "Performs exact string replacements in files.\n\nUsage notes:\n- When editing, preserve the exact indentation (tabs/spaces) from the original file\n- The edit will FAIL if old_string is not unique in the file unless replace_all is true\n- Use replace_all for replacing/renaming strings across the entire file\n- old_string and new_string must be different\n- ALWAYS prefer editing existing files over creating new ones";
2333
+ readonly parameters: ToolInputSchema;
2334
+ /** Current working directory for resolving relative paths */
2335
+ private cwd;
2336
+ constructor(options?: {
2337
+ cwd?: string;
2338
+ });
2339
+ /**
2340
+ * Set the current working directory
2341
+ */
2342
+ setCwd(cwd: string): void;
2343
+ /**
2344
+ * Get the current working directory
2345
+ */
2346
+ getCwd(): string;
2347
+ /**
2348
+ * Execute file edit
2349
+ *
2350
+ * @param args - Edit arguments
2351
+ * @returns MCP-compliant CallToolResult with edit details
2352
+ */
2353
+ execute(args: Record<string, unknown>): Promise<CallToolResult>;
2354
+ /**
2355
+ * Validate and parse arguments
2356
+ */
2357
+ private validateArgs;
2358
+ /**
2359
+ * Count occurrences of a substring in a string
2360
+ */
2361
+ private countOccurrences;
2362
+ /**
2363
+ * Truncate string for error messages
2364
+ */
2365
+ private truncateForError;
2366
+ }
2367
+ //#endregion
2368
+ //#region src/tool/builtin/write.d.ts
2369
+ /**
2370
+ * Result of a write operation
2371
+ */
2372
+ interface WriteResult {
2373
+ /** Whether the write was successful */
2374
+ success: boolean;
2375
+ /** File path that was written */
2376
+ filePath: string;
2377
+ /** Number of bytes written */
2378
+ bytesWritten: number;
2379
+ /** Whether an existing file was overwritten */
2380
+ overwritten: boolean;
2381
+ /** Brief description of the operation */
2382
+ message: string;
2383
+ }
2384
+ /**
2385
+ * Arguments for the Write tool
2386
+ */
2387
+ interface WriteArgs {
2388
+ /** The absolute path to the file to write */
2389
+ file_path: string;
2390
+ /** The content to write to the file */
2391
+ content: string;
2392
+ }
2393
+ /**
2394
+ * Tool for writing files to the filesystem.
2395
+ *
2396
+ * This tool creates or overwrites files with the specified content,
2397
+ * automatically creating parent directories if needed.
2398
+ *
2399
+ * @example
2400
+ * ```typescript
2401
+ * const writeTool = new WriteTool()
2402
+ * const result = await writeTool.execute({
2403
+ * file_path: '/path/to/file.ts',
2404
+ * content: 'export const foo = 1'
2405
+ * })
2406
+ * ```
2407
+ *
2408
+ * @example Restrict writes to a specific directory
2409
+ * ```typescript
2410
+ * const writeTool = new WriteTool({
2411
+ * cwd: '/app/output',
2412
+ * restrictToDirectory: true
2413
+ * })
2414
+ * // All paths will be resolved relative to /app/output
2415
+ * // Absolute paths and path traversal (../) will be blocked
2416
+ * ```
2417
+ */
2418
+ declare class WriteTool extends BaseTool {
2419
+ readonly name = "Write";
2420
+ readonly riskLevel: "high";
2421
+ /** Current working directory for resolving relative paths */
2422
+ private _cwd;
2423
+ /** Allowed directory for file operations (if set, restricts writes to this directory) */
2424
+ private _allowedDirectory?;
2425
+ constructor(options?: {
2426
+ cwd?: string;
2427
+ /** If set, restricts all file writes to this directory. Paths outside will be rejected. */
2428
+ allowedDirectory?: string;
2429
+ });
2430
+ /**
2431
+ * Dynamic description that includes allowed directory info if configured
2432
+ */
2433
+ get description(): string;
2434
+ /**
2435
+ * Dynamic parameters that include allowed directory info if configured
2436
+ */
2437
+ get parameters(): ToolInputSchema;
2438
+ /**
2439
+ * Set the current working directory
2440
+ */
2441
+ setCwd(cwd: string): void;
2442
+ /**
2443
+ * Get the current working directory
2444
+ */
2445
+ getCwd(): string;
2446
+ /**
2447
+ * Set the allowed directory for file operations
2448
+ */
2449
+ setAllowedDirectory(dir: string | undefined): void;
2450
+ /**
2451
+ * Get the allowed directory for file operations
2452
+ */
2453
+ getAllowedDirectory(): string | undefined;
2454
+ /**
2455
+ * Execute file write
2456
+ *
2457
+ * @param args - Write arguments
2458
+ * @returns MCP-compliant CallToolResult with write details
2459
+ */
2460
+ execute(args: Record<string, unknown>): Promise<CallToolResult>;
2461
+ /**
2462
+ * Validate and parse arguments
2463
+ */
2464
+ private validateArgs;
2465
+ /**
2466
+ * Format file size for display
2467
+ */
2468
+ private formatSize;
2469
+ }
2470
+ //#endregion
2471
+ //#region src/tool/builtin/webSearch.d.ts
2472
+ /**
2473
+ * A single search result item
2474
+ */
2475
+ interface SearchResultItem {
2476
+ /** Result title */
2477
+ title: string;
2478
+ /** Result URL */
2479
+ link: string;
2480
+ /** Result snippet/description */
2481
+ snippet: string;
2482
+ /** Position in search results */
2483
+ position: number;
2484
+ }
2485
+ /**
2486
+ * Result of a web search operation
2487
+ */
2488
+ interface WebSearchResult {
2489
+ /** Whether the search was successful */
2490
+ success: boolean;
2491
+ /** The search query used */
2492
+ query: string;
2493
+ /** List of search results */
2494
+ results: SearchResultItem[];
2495
+ /** Total number of results found */
2496
+ totalResults: number;
2497
+ /** Formatted markdown content with sources */
2498
+ markdown: string;
2499
+ /** Error message if search failed */
2500
+ error?: string;
2501
+ }
2502
+ /**
2503
+ * Arguments for the WebSearch tool
2504
+ */
2505
+ interface WebSearchArgs {
2506
+ /** The search query to use */
2507
+ query: string;
2508
+ }
2509
+ /**
2510
+ * Tool for searching the web using Serper API.
2511
+ *
2512
+ * This tool allows the agent to search the web and use the results
2513
+ * to inform responses with up-to-date information.
2514
+ *
2515
+ * @example
2516
+ * ```typescript
2517
+ * const webSearchTool = new WebSearchTool({ apiKey: 'your-serper-api-key' })
2518
+ * const result = await webSearchTool.execute({
2519
+ * query: 'latest TypeScript features 2025'
2520
+ * })
2521
+ * ```
2522
+ */
2523
+ declare class WebSearchTool extends BaseTool {
2524
+ readonly name = "WebSearch";
2525
+ readonly description = "Allows the agent to search the web and use the results to inform responses.\n\nUsage notes:\n- Provides up-to-date information for current events and recent data\n- Returns search results with titles, links, and snippets\n- Use this tool for accessing information beyond the knowledge cutoff\n- After answering, include a \"Sources:\" section with relevant URLs as markdown hyperlinks";
2526
+ readonly parameters: ToolInputSchema;
2527
+ /** Serper API key */
2528
+ private apiKey;
2529
+ /** Serper API endpoint */
2530
+ private apiEndpoint;
2531
+ /** Number of results to return */
2532
+ private numResults;
2533
+ constructor(options?: {
2534
+ apiKey?: string;
2535
+ apiEndpoint?: string;
2536
+ numResults?: number;
2537
+ });
2538
+ /**
2539
+ * Set API key
2540
+ */
2541
+ setApiKey(apiKey: string): void;
2542
+ /**
2543
+ * Execute web search
2544
+ *
2545
+ * @param args - WebSearch arguments
2546
+ * @returns MCP-compliant CallToolResult with search results
2547
+ */
2548
+ execute(args: Record<string, unknown>): Promise<CallToolResult>;
2549
+ /**
2550
+ * Validate and parse arguments
2551
+ */
2552
+ private validateArgs;
2553
+ /**
2554
+ * Format search results as markdown
2555
+ */
2556
+ private formatMarkdown;
2557
+ }
2558
+ //#endregion
2559
+ //#region src/tool/registry.d.ts
2560
+ /**
2561
+ * Registry for managing tools.
2562
+ *
2563
+ * Provides methods to register, unregister, and look up tools,
2564
+ * as well as convert to OpenAI-compatible format.
2565
+ */
2566
+ declare class ToolRegistry {
2567
+ private tools;
2568
+ /**
2569
+ * Register a tool
2570
+ *
2571
+ * @param tool - Tool to register
2572
+ * @throws Error if tool with same name already exists
2573
+ */
2574
+ register(tool: BaseTool): void;
2575
+ /**
2576
+ * Unregister a tool by name
2577
+ *
2578
+ * @param name - Name of tool to remove
2579
+ * @returns true if tool was found and removed
2580
+ */
2581
+ unregister(name: string): boolean;
2582
+ /**
2583
+ * Get a tool by name
2584
+ *
2585
+ * @param name - Tool name
2586
+ * @returns Tool instance or undefined if not found
2587
+ */
2588
+ get(name: string): BaseTool | undefined;
2589
+ /**
2590
+ * List all registered tools
2591
+ *
2592
+ * @returns Array of all tools
2593
+ */
2594
+ list(): BaseTool[];
2595
+ /**
2596
+ * Check if a tool is registered
2597
+ *
2598
+ * @param name - Tool name
2599
+ * @returns true if tool exists
2600
+ */
2601
+ has(name: string): boolean;
2602
+ /**
2603
+ * Get count of registered tools
2604
+ */
2605
+ get size(): number;
2606
+ /**
2607
+ * Convert all tools to OpenAI-compatible format
2608
+ *
2609
+ * @returns Array of tools in OpenAI function calling format
2610
+ */
2611
+ toOpenAIFormat(): OpenAITool[];
2612
+ }
2613
+ //#endregion
2614
+ //#region src/agent/hooks/types.d.ts
2615
+ interface HookContext {
2616
+ sessionId: string;
2617
+ agentId: string;
2618
+ toolCall: ToolCall;
2619
+ toolContext: ToolExecutionContext;
2620
+ }
2621
+ interface PreToolUseResult {
2622
+ allow: boolean;
2623
+ modifiedToolCall?: ToolCall;
2624
+ }
2625
+ type PreToolUseHook = (ctx: HookContext) => Promise<PreToolUseResult>;
2626
+ type PostToolUseHook = (ctx: HookContext, result: unknown) => Promise<void>;
2627
+ type PostToolUseFailureHook = (ctx: HookContext, error: Error) => Promise<void>;
2628
+ interface ToolHooks {
2629
+ preToolUse?: PreToolUseHook[];
2630
+ postToolUse?: PostToolUseHook[];
2631
+ postToolUseFailure?: PostToolUseFailureHook[];
2632
+ }
2633
+ //#endregion
2634
+ //#region src/agent/hooks/base.d.ts
2635
+ declare abstract class BaseHook<TResult = void, TArgs extends unknown[] = []> {
2636
+ abstract execute(context: HookContext, ...args: TArgs): Promise<TResult>;
2637
+ }
2638
+ //#endregion
2639
+ //#region src/agent/hooks/manager.d.ts
2640
+ declare class HookManager {
2641
+ private readonly hooks;
2642
+ constructor(hooks?: ToolHooks);
2643
+ executePreToolUse(context: HookContext): Promise<PreToolUseResult>;
2644
+ executePostToolUse(context: HookContext, result: unknown): Promise<void>;
2645
+ executePostToolUseFailure(context: HookContext, error: Error): Promise<void>;
2646
+ }
2647
+ //#endregion
2648
+ //#region src/agent/types.d.ts
2649
+ /**
2650
+ * Tool call with execution result
2651
+ */
2652
+ interface ToolCallWithResult {
2653
+ /**
2654
+ * Original tool call from the LLM
2655
+ */
2656
+ toolCall: ToolCall;
2657
+ /**
2658
+ * Execution result (undefined if not yet executed)
2659
+ */
2660
+ result?: unknown;
2661
+ /**
2662
+ * Whether the execution resulted in an error
2663
+ */
2664
+ isError?: boolean;
2665
+ }
2666
+ /**
2667
+ * Agent Loop State - the runtime state that flows through the agent loop.
2668
+ *
2669
+ * This is the core state object that gets passed between loop iterations,
2670
+ * hooks, and middlewares. It contains everything needed to:
2671
+ * - Continue the conversation
2672
+ * - Execute pending tool calls
2673
+ * - Track progress and prevent infinite loops
2674
+ * - Accumulate the final response
2675
+ */
2676
+ interface AgentLoopState {
2677
+ /**
2678
+ * Session ID for this execution
2679
+ */
2680
+ sessionId: string;
2681
+ /**
2682
+ * Agent ID
2683
+ */
2684
+ agentId: string;
2685
+ /**
2686
+ * Full message history including system, user, assistant, and tool messages.
2687
+ * This is the primary state that gets updated each iteration.
2688
+ */
2689
+ messages: Message[];
2690
+ /**
2691
+ * Current loop iteration (0-indexed).
2692
+ * Used for max iterations check and debugging.
2693
+ */
2694
+ iteration: number;
2695
+ /**
2696
+ * Pending tool calls from the current LLM response.
2697
+ * These need to be executed before the next iteration.
2698
+ */
2699
+ pendingToolCalls: ToolCallWithResult[];
2700
+ /**
2701
+ * Text response accumulated so far in the current iteration.
2702
+ */
2703
+ currentResponse: string;
2704
+ /**
2705
+ * Thinking/reasoning content from the current iteration (if model supports it).
2706
+ */
2707
+ currentThinking?: string;
2708
+ /**
2709
+ * Whether the loop should continue.
2710
+ * Set to false when:
2711
+ * - LLM returns a final response without tool calls
2712
+ * - Max iterations reached
2713
+ * - An error occurs (depending on error handling strategy)
2714
+ * - Explicitly stopped by a hook
2715
+ */
2716
+ shouldContinue: boolean;
2717
+ /**
2718
+ * Stop reason for debugging/logging.
2719
+ */
2720
+ stopReason?: 'max_iterations' | 'final_response' | 'error' | 'cancelled' | 'approval_required';
2721
+ /**
2722
+ * The stop reason reported by the most recent model call (if available).
2723
+ *
2724
+ * Useful for debugging truncated outputs (e.g. `length`) vs normal completion (`final`).
2725
+ */
2726
+ lastModelStopReason?: ModelStopReason;
2727
+ /**
2728
+ * Cumulative token usage across all iterations.
2729
+ */
2730
+ usage: Usage;
2731
+ /**
2732
+ * Last error encountered (if any).
2733
+ */
2734
+ error?: Error;
2735
+ /**
2736
+ * Custom metadata for hooks and middlewares.
2737
+ * Use this to pass data between different stages of the loop.
2738
+ */
2739
+ metadata: Record<string, unknown>;
2740
+ }
2741
+ /**
2742
+ * Create initial AgentLoopState from AgentInput
2743
+ */
2744
+ declare function createInitialLoopState(input: AgentInput, agentId: string, systemPrompt: string): AgentLoopState;
2745
+ /**
2746
+ * Options for creating an Agent
2747
+ */
2748
+ interface AgentOptions {
2749
+ /**
2750
+ * Unique identifier for the agent (auto-generated if not provided)
2751
+ */
2752
+ id?: string;
2753
+ /**
2754
+ * Human-readable name for the agent
2755
+ */
2756
+ name: string;
2757
+ /**
2758
+ * System prompt that defines the agent's behavior
2759
+ */
2760
+ systemPrompt: string;
2761
+ /**
2762
+ * LLM model to use
2763
+ */
2764
+ model: ModelClient;
2765
+ /**
2766
+ * Tool registry (optional)
2767
+ */
2768
+ tools?: ToolRegistry;
2769
+ /**
2770
+ * State storage backend (optional).
2771
+ *
2772
+ * If not provided, an in-memory store will be created by default.
2773
+ * The agent will automatically save checkpoints during execution,
2774
+ * allowing interrupted executions to be resumed. The store can also be used
2775
+ * by middlewares (like contextCompressionMiddleware) to persist their state.
2776
+ *
2777
+ * A SessionManager is automatically created to manage sessions.
2778
+ * Sessions will be stored in the StateStore.
2779
+ *
2780
+ * The state store contains its own configuration for when to save
2781
+ * (savePoint) and whether to delete on completion (deleteOnComplete).
2782
+ */
2783
+ stateStore?: StateStore;
2784
+ }
2785
+ /**
2786
+ * Input for agent execution
2787
+ */
2788
+ interface AgentInput {
2789
+ /**
2790
+ * Session ID for this execution.
2791
+ *
2792
+ * This is optional. If not provided, a new session will be automatically
2793
+ * created and a `session_created` event will be emitted with the new sessionId.
2794
+ */
2795
+ sessionId?: string;
2796
+ /**
2797
+ * User input message
2798
+ */
2799
+ input: MessageContent;
2800
+ /**
2801
+ * Optional conversation history (caller manages this)
2802
+ */
2803
+ messages?: Message[];
2804
+ /**
2805
+ * Optional model override for this execution.
2806
+ * If provided, this model will be used instead of the agent's default model.
2807
+ *
2808
+ * @example
2809
+ * ```ts
2810
+ * const session = await agent.createSession({
2811
+ * model: { provider: 'openai', modelId: 'gpt-4' }, // Use gpt-4 for this session
2812
+ * })
2813
+ * session.send('hello')
2814
+ * for await (const event of session.receive()) {
2815
+ * console.log(event)
2816
+ * }
2817
+ * ```
2818
+ */
2819
+ model?: ModelRef;
2820
+ /**
2821
+ * AbortSignal for cancellation support.
2822
+ * When aborted, the agent loop will throw AgentAbortError.
2823
+ */
2824
+ signal?: AbortSignal;
2825
+ /**
2826
+ * Maximum number of loop iterations (default: 10).
2827
+ * Prevents infinite loops when tools keep being called.
2828
+ */
2829
+ maxIterations?: number;
2830
+ /**
2831
+ * Optional tool execution context input.
2832
+ *
2833
+ * Use this to inject capabilities (e.g. fetch/fs) and metadata.
2834
+ * Identity fields (sessionId/agentId) are filled by the Agent.
2835
+ */
2836
+ toolContext?: ToolExecutionContextInput;
2837
+ /**
2838
+ * Optional hooks for intercepting tool execution.
2839
+ */
2840
+ hooks?: ToolHooks;
2841
+ /**
2842
+ * Optional model request parameters (temperature, maxTokens, etc.).
2843
+ * These will be saved in checkpoints for resumption.
2844
+ */
2845
+ requestParams?: CheckpointRequestParams;
2846
+ }
2847
+ interface SessionHandleOptions {
2848
+ /**
2849
+ * Optional hooks for intercepting tool execution.
2850
+ */
2851
+ hooks?: ToolHooks;
2852
+ /**
2853
+ * Optional model request parameters (temperature, maxTokens, etc.)
2854
+ */
2855
+ requestParams?: CheckpointRequestParams;
2856
+ }
2857
+ interface CreateSessionOptions extends SessionHandleOptions {
2858
+ /**
2859
+ * Optional model override for this session.
2860
+ */
2861
+ model?: ModelRef;
2862
+ /**
2863
+ * Maximum number of loop iterations (default: 10).
2864
+ */
2865
+ maxIterations?: number;
2866
+ }
2867
+ interface SendOptions {
2868
+ /**
2869
+ * AbortSignal for cancellation support
2870
+ */
2871
+ signal?: AbortSignal;
2872
+ /**
2873
+ * Optional tool execution context input
2874
+ */
2875
+ toolContext?: ToolExecutionContextInput;
2876
+ }
2877
+ //#endregion
2878
+ //#region src/middleware/checkpointMiddleware.d.ts
2879
+ /**
2880
+ * Options for converting AgentLoopState to checkpoint
2881
+ */
2882
+ interface ToCheckpointOptions {
2883
+ agentName?: string;
2884
+ phase?: 'llm_call' | 'tool_execution' | 'approval_pending' | 'completed';
2885
+ status?: string;
2886
+ /**
2887
+ * Model configuration to save in checkpoint
2888
+ */
2889
+ modelConfig?: CheckpointModelConfig;
2890
+ /**
2891
+ * Model request parameters to save in checkpoint
2892
+ */
2893
+ requestParams?: CheckpointRequestParams;
2894
+ }
2895
+ /**
2896
+ * Convert AgentLoopState to AgentLoopCheckpoint
2897
+ */
2898
+ declare function toLoopCheckpoint(state: AgentLoopState, options?: ToCheckpointOptions): AgentLoopCheckpoint;
2899
+ /**
2900
+ * Restore AgentLoopState from AgentLoopCheckpoint
2901
+ *
2902
+ * Note: agentName, phase, and status are display-only fields and are not
2903
+ * part of AgentLoopState. They will be recalculated when a new checkpoint is saved.
2904
+ */
2905
+ declare function fromLoopCheckpoint(checkpoint: AgentLoopCheckpoint): AgentLoopState;
2906
+ //#endregion
2907
+ //#region src/session/base.d.ts
2908
+ /**
2909
+ * Abstract base class for a session.
2910
+ *
2911
+ * A session represents a single conversation instance with an agent.
2912
+ * One agent can have multiple concurrent sessions.
2913
+ */
2914
+ declare abstract class BaseSession {
2915
+ /**
2916
+ * Unique session identifier
2917
+ */
2918
+ abstract readonly id: string;
2919
+ /**
2920
+ * Session creation timestamp (ms)
2921
+ */
2922
+ abstract readonly createdAt: number;
2923
+ /**
2924
+ * Current session status
2925
+ */
2926
+ abstract status: SessionStatus;
2927
+ /**
2928
+ * Session title (user-defined)
2929
+ */
2930
+ abstract title?: string;
2931
+ /**
2932
+ * Last update timestamp (ms)
2933
+ */
2934
+ abstract updatedAt: number;
2935
+ /**
2936
+ * Last activity timestamp (ms)
2937
+ */
2938
+ abstract lastActiveAt: number;
2939
+ /**
2940
+ * Error message if status is 'error'
2941
+ */
2942
+ abstract errorMessage?: string;
2943
+ /**
2944
+ * Session-level configuration overrides
2945
+ */
2946
+ abstract configOverride?: SessionConfigOverride;
2947
+ /**
2948
+ * Message history
2949
+ */
2950
+ abstract messages: Message[];
2951
+ /**
2952
+ * Number of tool calls made in this session
2953
+ */
2954
+ abstract toolCallCount: number;
2955
+ /**
2956
+ * Token usage statistics
2957
+ */
2958
+ abstract usage: {
2959
+ promptTokens: number;
2960
+ completionTokens: number;
2961
+ totalTokens: number;
2962
+ };
2963
+ /**
2964
+ * Number of assistant responses
2965
+ */
2966
+ abstract responseCount: number;
2967
+ /**
2968
+ * Average response time in milliseconds
2969
+ */
2970
+ abstract avgResponseTime?: number;
2971
+ /**
2972
+ * Persist the session state.
2973
+ */
2974
+ abstract save(): Promise<void>;
2975
+ /**
2976
+ * Set model override for this session
2977
+ *
2978
+ * @param model - Model configuration to use for this session
2979
+ */
2980
+ setModelOverride(model: ModelConfig): void;
2981
+ /**
2982
+ * Clear model override (use agent's default model)
2983
+ */
2984
+ clearModelOverride(): void;
2985
+ /**
2986
+ * Set system prompt override for this session
2987
+ *
2988
+ * @param systemPrompt - System prompt to use for this session
2989
+ */
2990
+ setSystemPromptOverride(systemPrompt: string): void;
2991
+ /**
2992
+ * Clear system prompt override
2993
+ */
2994
+ clearSystemPromptOverride(): void;
2995
+ /**
2996
+ * Disable specific tools for this session
2997
+ *
2998
+ * @param toolNames - Names of tools to disable
2999
+ */
3000
+ disableTools(toolNames: string[]): void;
3001
+ /**
3002
+ * Re-enable all tools for this session
3003
+ */
3004
+ enableAllTools(): void;
3005
+ /**
3006
+ * Update session status
3007
+ *
3008
+ * @param status - New status
3009
+ * @param errorMessage - Error message (if status is 'error')
3010
+ */
3011
+ setStatus(status: SessionStatus, errorMessage?: string): void;
3012
+ /**
3013
+ * Mark session as active (update lastActiveAt)
3014
+ */
3015
+ markActive(): void;
3016
+ /**
3017
+ * Add a message to the conversation history
3018
+ *
3019
+ * @param message - Message to add
3020
+ */
3021
+ addMessage(message: Message): void;
3022
+ /**
3023
+ * Get preview of the last message (truncated for display)
3024
+ *
3025
+ * @param maxLength - Maximum length of preview
3026
+ * @returns Preview string or undefined if no messages
3027
+ */
3028
+ getLastMessagePreview(maxLength?: number): string | undefined;
3029
+ /**
3030
+ * Add usage statistics
3031
+ *
3032
+ * @param usage - Usage to add
3033
+ * @param usage.promptTokens - Number of prompt tokens
3034
+ * @param usage.completionTokens - Number of completion tokens
3035
+ * @param usage.totalTokens - Total number of tokens
3036
+ */
3037
+ addUsage(usage: {
3038
+ promptTokens: number;
3039
+ completionTokens: number;
3040
+ totalTokens: number;
3041
+ }): void;
3042
+ /**
3043
+ * Record a response with its duration
3044
+ *
3045
+ * @param durationMs - Response duration in milliseconds
3046
+ */
3047
+ recordResponse(durationMs: number): void;
3048
+ /**
3049
+ * Increment tool call count
3050
+ */
3051
+ incrementToolCallCount(): void;
3052
+ /**
3053
+ * Create a snapshot of the session for persistence
3054
+ *
3055
+ * @returns Session snapshot
3056
+ */
3057
+ toSnapshot(): SessionSnapshot;
3058
+ /**
3059
+ * Restore session state from a snapshot
3060
+ *
3061
+ * @param snapshot - Session snapshot to restore from
3062
+ */
3063
+ restoreFromSnapshot(snapshot: SessionSnapshot): void;
3064
+ }
3065
+ //#endregion
3066
+ //#region src/session/manager.d.ts
3067
+ /**
3068
+ * Abstract base class for session management.
3069
+ *
3070
+ * Handles session lifecycle: creation, retrieval, listing, and destruction.
3071
+ * Implement this class for different storage backends (e.g., Redis, SQLite, in-memory).
3072
+ */
3073
+ declare abstract class BaseSessionManager {
3074
+ /**
3075
+ * Create a new session for an agent
3076
+ *
3077
+ * @param metadata - Optional session metadata
3078
+ * @returns Newly created session
3079
+ */
3080
+ abstract create(): Promise<BaseSession>;
3081
+ /**
3082
+ * Get a session by ID
3083
+ *
3084
+ * @param sessionId - Session identifier
3085
+ * @returns Session or undefined if not found
3086
+ */
3087
+ abstract get(sessionId: string): Promise<BaseSession | undefined>;
3088
+ /**
3089
+ * List all sessions for an agent
3090
+ *
3091
+ * @returns Array of sessions belonging to the agent
3092
+ */
3093
+ abstract list(): Promise<BaseSession[]>;
3094
+ /**
3095
+ * Destroy a session
3096
+ *
3097
+ * @param sessionId - Session identifier to destroy
3098
+ */
3099
+ abstract destroy(sessionId: string): Promise<void>;
3100
+ }
3101
+ //#endregion
3102
+ //#region src/session/session.d.ts
3103
+ interface SessionRuntimeOptions extends CreateSessionOptions {
3104
+ modelClient?: ModelClient;
3105
+ systemPrompt?: string;
3106
+ agentName?: string;
3107
+ tools?: ToolRegistry;
3108
+ middlewares?: Middleware<AgentLoopState>[];
3109
+ onUsage?: (usage: {
3110
+ promptTokens: number;
3111
+ completionTokens: number;
3112
+ totalTokens: number;
3113
+ }) => void;
3114
+ hasCheckpoint?: boolean;
3115
+ }
3116
+ /**
3117
+ * Concrete Session implementation that stores data in StateStore.
3118
+ */
3119
+ declare class Session extends BaseSession {
3120
+ readonly id: string;
3121
+ readonly agentId: string;
3122
+ readonly createdAt: number;
3123
+ status: SessionStatus;
3124
+ title?: string;
3125
+ updatedAt: number;
3126
+ lastActiveAt: number;
3127
+ errorMessage?: string;
3128
+ configOverride?: SessionConfigOverride;
3129
+ messages: Message[];
3130
+ toolCallCount: number;
3131
+ usage: {
3132
+ promptTokens: number;
3133
+ completionTokens: number;
3134
+ totalTokens: number;
3135
+ };
3136
+ responseCount: number;
3137
+ avgResponseTime?: number;
3138
+ private readonly _stateStore;
3139
+ private _autoSave;
3140
+ private readonly _modelClient?;
3141
+ private readonly _tools?;
3142
+ private readonly _middlewares;
3143
+ private readonly _systemPrompt?;
3144
+ private readonly _agentName?;
3145
+ private readonly _onUsage?;
3146
+ private _hasCheckpoint;
3147
+ private _checkpointRestored;
3148
+ private _pendingInput;
3149
+ private _isReceiving;
3150
+ private readonly _hooks?;
3151
+ private _modelOverride?;
3152
+ private readonly _maxIterations?;
3153
+ private readonly _requestParams?;
3154
+ /**
3155
+ * Create a new Session or load from StateStore.
3156
+ *
3157
+ * @param stateStore - StateStore instance for persistence
3158
+ * @param sessionId - Session identifier
3159
+ * @param snapshot - Optional snapshot to restore from (if not provided, will create new session)
3160
+ */
3161
+ constructor(stateStore: StateStore, sessionId: string, snapshot?: SessionSnapshot, options?: SessionRuntimeOptions);
3162
+ get hasCheckpoint(): boolean;
3163
+ send(input: MessageContent, options?: SendOptions): void;
3164
+ receive(): AsyncIterable<AgentEvent>;
3165
+ private resolveModelRef;
3166
+ private getRuntimeModelOverride;
3167
+ private _stream;
3168
+ private _ensureRuntimeConfigured;
3169
+ private _recordUsage;
3170
+ private executeModelStream;
3171
+ private executeToolCall;
3172
+ private createToolExecutionContext;
3173
+ private mergeStateResults;
3174
+ private addToolResultToHistory;
3175
+ private addAssistantMessageWithToolCalls;
3176
+ private addFinalAssistantMessage;
3177
+ private _streamWithState;
3178
+ private static readonly APPROVAL_REQUIRED_LEVELS;
3179
+ private requiresApproval;
3180
+ private handleToolCalls;
3181
+ private handleFinalResponse;
3182
+ private _finalizeRun;
3183
+ /**
3184
+ * Save session to StateStore.
3185
+ */
3186
+ save(): Promise<void>;
3187
+ /**
3188
+ * Load session from StateStore.
3189
+ */
3190
+ load(): Promise<boolean>;
3191
+ setStatus(status: SessionStatus, errorMessage?: string): void;
3192
+ markActive(): void;
3193
+ addMessage(message: Message): void;
3194
+ addUsage(usage: {
3195
+ promptTokens: number;
3196
+ completionTokens: number;
3197
+ totalTokens: number;
3198
+ }): void;
3199
+ recordResponse(durationMs: number): void;
3200
+ incrementToolCallCount(): void;
3201
+ setModelOverride(model: ModelConfig): void;
3202
+ clearModelOverride(): void;
3203
+ setSystemPromptOverride(systemPrompt: string): void;
3204
+ clearSystemPromptOverride(): void;
3205
+ disableTools(toolNames: string[]): void;
3206
+ enableAllTools(): void;
3207
+ /**
3208
+ * Enable or disable auto-save.
3209
+ */
3210
+ setAutoSave(enabled: boolean): void;
3211
+ }
3212
+ //#endregion
3213
+ //#region src/agent/agent.d.ts
3214
+ /**
3215
+ * Agent class - the main orchestrator.
3216
+ *
3217
+ * Agent is a blueprint/configuration that can handle multiple sessions.
3218
+ * It composes model, tools, state store, and session manager.
3219
+ *
3220
+ * Supports middleware pattern for extensible hooks at each loop iteration.
3221
+ */
3222
+ declare class Agent {
3223
+ readonly id: string;
3224
+ readonly name: string;
3225
+ readonly systemPrompt: string;
3226
+ readonly createdAt: number;
3227
+ private _model;
3228
+ private _modelOverride?;
3229
+ private _tools?;
3230
+ private _stateStore?;
3231
+ private _sessionManager?;
3232
+ private _middlewares;
3233
+ constructor(options: AgentOptions);
3234
+ /**
3235
+ * Get the effective default model ID.
3236
+ */
3237
+ get modelId(): string;
3238
+ /**
3239
+ * Get the effective default model reference (provider + modelId), if available.
3240
+ *
3241
+ * - If `setModel(ModelRef)` was used, this returns that pinned model.
3242
+ * - Otherwise, returns the model client's default `modelRef` (if supported).
3243
+ */
3244
+ get modelRef(): ModelRef | undefined;
3245
+ /**
3246
+ * Get the available model references (e.g. routing fallback order), if supported by the model client.
3247
+ */
3248
+ get modelRefs(): ModelRef[];
3249
+ /**
3250
+ * Get the tool registry
3251
+ */
3252
+ get tools(): ToolRegistry | undefined;
3253
+ /**
3254
+ * Get the state store
3255
+ */
3256
+ get stateStore(): StateStore | undefined;
3257
+ /**
3258
+ * Get the session manager
3259
+ */
3260
+ get sessionManager(): BaseSessionManager | undefined;
3261
+ /**
3262
+ * Create a new session and return a Session.
3263
+ */
3264
+ createSession(options?: CreateSessionOptions): Promise<Session>;
3265
+ /**
3266
+ * Resume an existing session and return a Session.
3267
+ */
3268
+ resumeSession(sessionId: string, options?: SessionHandleOptions): Promise<Session>;
3269
+ /**
3270
+ * Add middleware to the agent.
3271
+ *
3272
+ * Middleware runs at each loop iteration and can intercept/transform the loop state.
3273
+ * Middleware follows an immutable pattern - it receives state and returns new state via next().
3274
+ *
3275
+ * @param fn - Middleware function
3276
+ * @returns this for chaining
3277
+ *
3278
+ * @example
3279
+ * ```ts
3280
+ * // Logging middleware (pass-through)
3281
+ * agent.use(async (state, next) => {
3282
+ * console.log('Before iteration', state.iteration);
3283
+ * const result = await next(state);
3284
+ * console.log('After iteration', state.iteration);
3285
+ * return result;
3286
+ * });
3287
+ *
3288
+ * // Transforming middleware (e.g., compression)
3289
+ * agent.use(async (state, next) => {
3290
+ * const compressed = { ...state, messages: compress(state.messages) };
3291
+ * return next(compressed);
3292
+ * });
3293
+ * ```
3294
+ */
3295
+ use(fn: Middleware<AgentLoopState>): this;
3296
+ /**
3297
+ * Switch to a different model
3298
+ *
3299
+ * @param model - New model client to use, or a `ModelRef` to pin the default model for subsequent requests.
3300
+ */
3301
+ setModel(model: ModelClient): void;
3302
+ setModel(model: ModelRef): void;
3303
+ }
3304
+ //#endregion
3305
+ //#region src/agent/errors.d.ts
3306
+ /**
3307
+ * Error thrown when agent execution is aborted via AbortSignal
3308
+ */
3309
+ declare class AgentAbortError extends Error {
3310
+ constructor(message?: string);
3311
+ }
3312
+ /**
3313
+ * Error thrown when agent exceeds maximum iterations
3314
+ */
3315
+ declare class AgentMaxIterationsError extends Error {
3316
+ readonly iterations: number;
3317
+ constructor(iterations: number, message?: string);
3318
+ }
3319
+ /**
3320
+ * Check if the abort signal has been triggered and throw if so.
3321
+ *
3322
+ * @param signal - AbortSignal to check
3323
+ * @param context - Optional context for error message
3324
+ * @throws AgentAbortError if signal is aborted
3325
+ */
3326
+ declare function ensureNotAborted(signal?: AbortSignal, context?: string): void;
3327
+ //#endregion
3328
+ export { Agent, AgentAbortError, type AgentEvent, type AgentEventType, type AgentInput, type AgentLoopCheckpoint, type AgentLoopState, AgentMaxIterationsError, type AgentOptions, type AssistantMessage, type BaseEvent, BaseHook, BaseModel, BaseSession, BaseSessionManager, BaseTool, type CallToolResult, type ChatOptions, type ChatResponse, type StateStore as CheckpointStore, StateStore, type StateStoreOptions as CheckpointStoreOptions, type StateStoreOptions, type CompressionState, type CompressionStats, type ContentBlock, type ContextCompressionOptions, CreateModelResult, type CreateSessionOptions, type DoneEvent, type EditArgs, type EditResult, EditTool, FileStateStore as FileCheckpointStore, FileStateStore, type FileStateStoreOptions as FileCheckpointStoreOptions, type FileStateStoreOptions, type GlobArgs, type GlobResult, GlobTool, type GrepArgs, type GrepOutputMode, type GrepResult, GrepTool, type HookContext, HookManager, type ImageContent, InMemoryStateStore as InMemoryCheckpointStore, InMemoryStateStore, InMemoryModelHealth, type IterationEndEvent, type IterationStartEvent, type JSONSchemaProperty, JitterStrategy, type ManualCompressionOptions, type ManualCompressionResult, type Message, type MessageContent, type MessageRole, type Middleware, type ModelAdapter, ModelClient, ModelDeltaChunk, ModelError, ModelId, ModelRef, ModelRequest, ModelRunResult, ModelStopReason, ModelStreamEvent, ModelStreamFn, type NextFunction, OpenAIAdapterOptions, type OpenAITool, type PostToolUseFailureHook, type PostToolUseHook, type PreToolUseHook, type PreToolUseResult, ProviderId, type ReadArgs, type ReadResult, ReadTool, RetryPolicy, RetryPolicyOptions, RetryStrategy, type RiskLevel, type SendOptions, Session, type SessionHandleOptions, type StateKey, StateKeys, type StreamEvent, type SystemMessage, type TextContent, type TextDeltaEvent, type TextEndEvent, type TextStartEvent, type ThinkingDeltaEvent, type ToCheckpointOptions, type Tool, type ToolApprovalResult, type ToolApprovalSettings, type ToolApprovalStrategy, type ToolCall, type ToolCallDeltaEvent, type ToolCallEndEvent, type ToolCallStartEvent, type ToolCallWithResult, type ToolExecutionContext, type ToolExecutionContextInput, type ToolHooks, type ToolMessage, ToolRegistry, type ToolResultEvent, type ToolRunUsage, type Usage, type UserMessage, type WebSearchArgs, type WebSearchResult, WebSearchTool, type WriteArgs, type WriteResult, WriteTool, compose, compressSessionManually, createContextCompressionMiddleware, createInitialLoopState, createModel, createOpenAIAdapter, ensureNotAborted, errorContent, fromLoopCheckpoint, imageContent, textContent, toLoopCheckpoint };