@compilr-dev/agents 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +1277 -0
  2. package/dist/agent.d.ts +1272 -0
  3. package/dist/agent.js +1912 -0
  4. package/dist/anchors/builtin.d.ts +24 -0
  5. package/dist/anchors/builtin.js +61 -0
  6. package/dist/anchors/index.d.ts +6 -0
  7. package/dist/anchors/index.js +5 -0
  8. package/dist/anchors/manager.d.ts +115 -0
  9. package/dist/anchors/manager.js +412 -0
  10. package/dist/anchors/types.d.ts +168 -0
  11. package/dist/anchors/types.js +10 -0
  12. package/dist/context/index.d.ts +12 -0
  13. package/dist/context/index.js +10 -0
  14. package/dist/context/manager.d.ts +224 -0
  15. package/dist/context/manager.js +770 -0
  16. package/dist/context/types.d.ts +377 -0
  17. package/dist/context/types.js +7 -0
  18. package/dist/costs/index.d.ts +8 -0
  19. package/dist/costs/index.js +7 -0
  20. package/dist/costs/tracker.d.ts +121 -0
  21. package/dist/costs/tracker.js +295 -0
  22. package/dist/costs/types.d.ts +157 -0
  23. package/dist/costs/types.js +8 -0
  24. package/dist/errors.d.ts +178 -0
  25. package/dist/errors.js +249 -0
  26. package/dist/guardrails/builtin.d.ts +27 -0
  27. package/dist/guardrails/builtin.js +223 -0
  28. package/dist/guardrails/index.d.ts +6 -0
  29. package/dist/guardrails/index.js +5 -0
  30. package/dist/guardrails/manager.d.ts +117 -0
  31. package/dist/guardrails/manager.js +288 -0
  32. package/dist/guardrails/types.d.ts +159 -0
  33. package/dist/guardrails/types.js +7 -0
  34. package/dist/hooks/index.d.ts +31 -0
  35. package/dist/hooks/index.js +29 -0
  36. package/dist/hooks/manager.d.ts +147 -0
  37. package/dist/hooks/manager.js +600 -0
  38. package/dist/hooks/types.d.ts +368 -0
  39. package/dist/hooks/types.js +12 -0
  40. package/dist/index.d.ts +45 -0
  41. package/dist/index.js +73 -0
  42. package/dist/mcp/client.d.ts +93 -0
  43. package/dist/mcp/client.js +287 -0
  44. package/dist/mcp/errors.d.ts +60 -0
  45. package/dist/mcp/errors.js +78 -0
  46. package/dist/mcp/index.d.ts +43 -0
  47. package/dist/mcp/index.js +45 -0
  48. package/dist/mcp/manager.d.ts +120 -0
  49. package/dist/mcp/manager.js +276 -0
  50. package/dist/mcp/tools.d.ts +54 -0
  51. package/dist/mcp/tools.js +99 -0
  52. package/dist/mcp/types.d.ts +150 -0
  53. package/dist/mcp/types.js +40 -0
  54. package/dist/memory/index.d.ts +8 -0
  55. package/dist/memory/index.js +7 -0
  56. package/dist/memory/loader.d.ts +114 -0
  57. package/dist/memory/loader.js +463 -0
  58. package/dist/memory/types.d.ts +182 -0
  59. package/dist/memory/types.js +8 -0
  60. package/dist/messages/index.d.ts +82 -0
  61. package/dist/messages/index.js +155 -0
  62. package/dist/permissions/index.d.ts +5 -0
  63. package/dist/permissions/index.js +4 -0
  64. package/dist/permissions/manager.d.ts +125 -0
  65. package/dist/permissions/manager.js +379 -0
  66. package/dist/permissions/types.d.ts +162 -0
  67. package/dist/permissions/types.js +7 -0
  68. package/dist/providers/claude.d.ts +90 -0
  69. package/dist/providers/claude.js +348 -0
  70. package/dist/providers/index.d.ts +8 -0
  71. package/dist/providers/index.js +11 -0
  72. package/dist/providers/mock.d.ts +133 -0
  73. package/dist/providers/mock.js +204 -0
  74. package/dist/providers/types.d.ts +168 -0
  75. package/dist/providers/types.js +4 -0
  76. package/dist/rate-limit/index.d.ts +45 -0
  77. package/dist/rate-limit/index.js +47 -0
  78. package/dist/rate-limit/limiter.d.ts +104 -0
  79. package/dist/rate-limit/limiter.js +326 -0
  80. package/dist/rate-limit/provider-wrapper.d.ts +112 -0
  81. package/dist/rate-limit/provider-wrapper.js +201 -0
  82. package/dist/rate-limit/retry.d.ts +108 -0
  83. package/dist/rate-limit/retry.js +287 -0
  84. package/dist/rate-limit/types.d.ts +181 -0
  85. package/dist/rate-limit/types.js +22 -0
  86. package/dist/rehearsal/file-analyzer.d.ts +22 -0
  87. package/dist/rehearsal/file-analyzer.js +351 -0
  88. package/dist/rehearsal/git-analyzer.d.ts +22 -0
  89. package/dist/rehearsal/git-analyzer.js +472 -0
  90. package/dist/rehearsal/index.d.ts +35 -0
  91. package/dist/rehearsal/index.js +36 -0
  92. package/dist/rehearsal/manager.d.ts +100 -0
  93. package/dist/rehearsal/manager.js +290 -0
  94. package/dist/rehearsal/types.d.ts +235 -0
  95. package/dist/rehearsal/types.js +8 -0
  96. package/dist/skills/index.d.ts +160 -0
  97. package/dist/skills/index.js +282 -0
  98. package/dist/state/agent-state.d.ts +41 -0
  99. package/dist/state/agent-state.js +88 -0
  100. package/dist/state/checkpointer.d.ts +110 -0
  101. package/dist/state/checkpointer.js +362 -0
  102. package/dist/state/errors.d.ts +66 -0
  103. package/dist/state/errors.js +88 -0
  104. package/dist/state/index.d.ts +35 -0
  105. package/dist/state/index.js +37 -0
  106. package/dist/state/serializer.d.ts +55 -0
  107. package/dist/state/serializer.js +172 -0
  108. package/dist/state/types.d.ts +312 -0
  109. package/dist/state/types.js +14 -0
  110. package/dist/tools/builtin/bash-output.d.ts +61 -0
  111. package/dist/tools/builtin/bash-output.js +90 -0
  112. package/dist/tools/builtin/bash.d.ts +150 -0
  113. package/dist/tools/builtin/bash.js +354 -0
  114. package/dist/tools/builtin/edit.d.ts +50 -0
  115. package/dist/tools/builtin/edit.js +215 -0
  116. package/dist/tools/builtin/glob.d.ts +62 -0
  117. package/dist/tools/builtin/glob.js +244 -0
  118. package/dist/tools/builtin/grep.d.ts +74 -0
  119. package/dist/tools/builtin/grep.js +363 -0
  120. package/dist/tools/builtin/index.d.ts +44 -0
  121. package/dist/tools/builtin/index.js +69 -0
  122. package/dist/tools/builtin/kill-shell.d.ts +44 -0
  123. package/dist/tools/builtin/kill-shell.js +80 -0
  124. package/dist/tools/builtin/read-file.d.ts +57 -0
  125. package/dist/tools/builtin/read-file.js +184 -0
  126. package/dist/tools/builtin/shell-manager.d.ts +176 -0
  127. package/dist/tools/builtin/shell-manager.js +337 -0
  128. package/dist/tools/builtin/task.d.ts +202 -0
  129. package/dist/tools/builtin/task.js +350 -0
  130. package/dist/tools/builtin/todo.d.ts +207 -0
  131. package/dist/tools/builtin/todo.js +453 -0
  132. package/dist/tools/builtin/utils.d.ts +27 -0
  133. package/dist/tools/builtin/utils.js +70 -0
  134. package/dist/tools/builtin/web-fetch.d.ts +96 -0
  135. package/dist/tools/builtin/web-fetch.js +290 -0
  136. package/dist/tools/builtin/write-file.d.ts +54 -0
  137. package/dist/tools/builtin/write-file.js +147 -0
  138. package/dist/tools/define.d.ts +60 -0
  139. package/dist/tools/define.js +65 -0
  140. package/dist/tools/index.d.ts +10 -0
  141. package/dist/tools/index.js +37 -0
  142. package/dist/tools/registry.d.ts +79 -0
  143. package/dist/tools/registry.js +151 -0
  144. package/dist/tools/types.d.ts +59 -0
  145. package/dist/tools/types.js +4 -0
  146. package/dist/tracing/hooks.d.ts +58 -0
  147. package/dist/tracing/hooks.js +377 -0
  148. package/dist/tracing/index.d.ts +51 -0
  149. package/dist/tracing/index.js +55 -0
  150. package/dist/tracing/logging.d.ts +78 -0
  151. package/dist/tracing/logging.js +310 -0
  152. package/dist/tracing/manager.d.ts +160 -0
  153. package/dist/tracing/manager.js +468 -0
  154. package/dist/tracing/otel.d.ts +102 -0
  155. package/dist/tracing/otel.js +246 -0
  156. package/dist/tracing/types.d.ts +346 -0
  157. package/dist/tracing/types.js +38 -0
  158. package/dist/utils/index.d.ts +23 -0
  159. package/dist/utils/index.js +44 -0
  160. package/package.json +79 -0
@@ -0,0 +1,1272 @@
1
+ /**
2
+ * Agent - The main class for running AI agents with tool use
3
+ */
4
+ import type { LLMProvider, Message, ChatOptions, StreamChunk } from './providers/types.js';
5
+ import type { Tool, ToolDefinition, ToolRegistry, ToolExecutionResult } from './tools/types.js';
6
+ import type { ContextStats, VerbosityLevel } from './context/types.js';
7
+ import type { AgentState, Checkpointer, SessionMetadata } from './state/types.js';
8
+ import type { Anchor, AnchorInput, AnchorQueryOptions, AnchorClearOptions, AnchorManagerOptions } from './anchors/types.js';
9
+ import type { Guardrail, GuardrailInput, GuardrailResult, GuardrailManagerOptions } from './guardrails/types.js';
10
+ import type { ToolPermission, PermissionLevel, PermissionManagerOptions } from './permissions/types.js';
11
+ import type { ProjectMemoryOptions, ProjectMemory } from './memory/types.js';
12
+ import type { UsageTrackerOptions, UsageStats, BudgetStatus, TokenUsage } from './costs/types.js';
13
+ import type { HooksConfig } from './hooks/types.js';
14
+ import { PermissionManager } from './permissions/manager.js';
15
+ import { ContextManager } from './context/manager.js';
16
+ import { AnchorManager } from './anchors/manager.js';
17
+ import { GuardrailManager } from './guardrails/manager.js';
18
+ /**
19
+ * Event types emitted during agent execution
20
+ */
21
+ export type AgentEvent = {
22
+ type: 'iteration_start';
23
+ iteration: number;
24
+ } | {
25
+ type: 'llm_start';
26
+ } | {
27
+ type: 'llm_chunk';
28
+ chunk: StreamChunk;
29
+ } | {
30
+ type: 'llm_end';
31
+ text: string;
32
+ hasToolUses: boolean;
33
+ } | {
34
+ type: 'tool_start';
35
+ name: string;
36
+ input: Record<string, unknown>;
37
+ } | {
38
+ type: 'tool_end';
39
+ name: string;
40
+ result: ToolExecutionResult;
41
+ } | {
42
+ type: 'iteration_end';
43
+ iteration: number;
44
+ } | {
45
+ type: 'done';
46
+ response: string;
47
+ } | {
48
+ type: 'context_warning';
49
+ utilization: number;
50
+ threshold: number;
51
+ } | {
52
+ type: 'context_compacted';
53
+ tokensBefore: number;
54
+ tokensAfter: number;
55
+ } | {
56
+ type: 'context_summarized';
57
+ tokensBefore: number;
58
+ tokensAfter: number;
59
+ rounds: number;
60
+ } | {
61
+ type: 'context_overflow';
62
+ utilization: number;
63
+ } | {
64
+ type: 'subagent_start';
65
+ name: string;
66
+ task: string;
67
+ } | {
68
+ type: 'subagent_end';
69
+ name: string;
70
+ result: SubAgentResult;
71
+ } | {
72
+ type: 'tool_loop_warning';
73
+ toolName: string;
74
+ consecutiveCalls: number;
75
+ } | {
76
+ type: 'abort_checkpoint_saved';
77
+ sessionId: string;
78
+ reason: 'aborted' | 'error';
79
+ } | {
80
+ type: 'abort_checkpoint_failed';
81
+ error: string;
82
+ } | {
83
+ type: 'custom';
84
+ name: string;
85
+ data: unknown;
86
+ metadata?: Record<string, unknown>;
87
+ } | {
88
+ type: 'anchor_added';
89
+ anchor: Anchor;
90
+ } | {
91
+ type: 'anchor_removed';
92
+ anchorId: string;
93
+ } | {
94
+ type: 'guardrail_triggered';
95
+ result: GuardrailResult;
96
+ } | {
97
+ type: 'guardrail_blocked';
98
+ result: GuardrailResult;
99
+ message: string;
100
+ } | {
101
+ type: 'guardrail_warning';
102
+ result: GuardrailResult;
103
+ message: string;
104
+ } | {
105
+ type: 'permission_granted';
106
+ toolName: string;
107
+ level: PermissionLevel;
108
+ } | {
109
+ type: 'permission_denied';
110
+ toolName: string;
111
+ level: PermissionLevel;
112
+ reason?: string;
113
+ } | {
114
+ type: 'permission_asked';
115
+ toolName: string;
116
+ level: PermissionLevel;
117
+ } | {
118
+ type: 'usage_recorded';
119
+ tokens: TokenUsage;
120
+ model: string;
121
+ } | {
122
+ type: 'usage_budget_warning';
123
+ status: BudgetStatus;
124
+ threshold: number;
125
+ } | {
126
+ type: 'usage_budget_exceeded';
127
+ status: BudgetStatus;
128
+ };
129
+ /**
130
+ * Event handler function type
131
+ */
132
+ export type AgentEventHandler = (event: AgentEvent) => void;
133
+ /**
134
+ * Stream writer for emitting custom events during execution.
135
+ *
136
+ * Tools and middleware can use this to stream custom events to the client.
137
+ * Inspired by LangGraph's get_stream_writer() pattern.
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * // In a tool executor:
142
+ * const writer = agent.getStreamWriter();
143
+ * writer('Processing step 1...', { step: 1 });
144
+ * // ... do work ...
145
+ * writer('Processing step 2...', { step: 2 });
146
+ * ```
147
+ */
148
+ export type StreamWriter = (data: unknown, metadata?: Record<string, unknown>) => void;
149
+ /**
150
+ * Custom event configuration
151
+ */
152
+ export interface CustomEventConfig {
153
+ /**
154
+ * Event name (used for filtering/routing)
155
+ */
156
+ name: string;
157
+ /**
158
+ * Event data payload
159
+ */
160
+ data: unknown;
161
+ /**
162
+ * Optional metadata (preserved through the event pipeline)
163
+ */
164
+ metadata?: Record<string, unknown>;
165
+ }
166
+ /**
167
+ * Agent configuration options
168
+ */
169
+ export interface AgentConfig {
170
+ /**
171
+ * The LLM provider to use
172
+ */
173
+ provider: LLMProvider;
174
+ /**
175
+ * System prompt for the agent
176
+ */
177
+ systemPrompt?: string;
178
+ /**
179
+ * Maximum iterations for tool use loops (default: 10)
180
+ */
181
+ maxIterations?: number;
182
+ /**
183
+ * Maximum consecutive identical tool calls before throwing ToolLoopError (default: 3).
184
+ * Set to 0 to disable loop detection.
185
+ */
186
+ maxConsecutiveToolCalls?: number;
187
+ /**
188
+ * Behavior when max iterations is reached (default: 'error').
189
+ * - 'error': Throw MaxIterationsError immediately
190
+ * - 'summarize': Generate a final summary response before throwing
191
+ * - 'continue': Return partial result without throwing (response will be empty)
192
+ */
193
+ iterationLimitBehavior?: 'error' | 'summarize' | 'continue';
194
+ /**
195
+ * Chat options (model, temperature, etc.)
196
+ */
197
+ chatOptions?: ChatOptions;
198
+ /**
199
+ * Custom tool registry (optional, creates new one if not provided)
200
+ */
201
+ toolRegistry?: ToolRegistry;
202
+ /**
203
+ * Context manager for tracking and managing context window usage.
204
+ * If not provided, context management is disabled.
205
+ */
206
+ contextManager?: ContextManager;
207
+ /**
208
+ * Enable automatic context management (compaction, summarization).
209
+ * Requires contextManager to be set. Default: true when contextManager is provided.
210
+ */
211
+ autoContextManagement?: boolean;
212
+ /**
213
+ * Event handler for monitoring agent execution
214
+ */
215
+ onEvent?: AgentEventHandler;
216
+ /**
217
+ * Checkpointer for persisting agent state.
218
+ * If provided, enables checkpoint() and resume() functionality.
219
+ */
220
+ checkpointer?: Checkpointer;
221
+ /**
222
+ * Session ID for this agent instance.
223
+ * If not provided, a new session ID is generated automatically.
224
+ */
225
+ sessionId?: string;
226
+ /**
227
+ * Automatically save state after each run() call.
228
+ * Requires checkpointer to be set. Default: false.
229
+ */
230
+ autoCheckpoint?: boolean;
231
+ /**
232
+ * Save a partial checkpoint when run is aborted or encounters an error.
233
+ * This allows recovery from interrupted runs.
234
+ * Requires checkpointer to be set. Default: false.
235
+ *
236
+ * Inspired by LangGraph issue #5672: Cancellation causes loss of
237
+ * streamed state not yet persisted as checkpoint.
238
+ */
239
+ checkpointOnAbort?: boolean;
240
+ /**
241
+ * Anchor manager options for critical information that survives context compaction.
242
+ *
243
+ * Anchors are pieces of information that:
244
+ * - Never get compacted - Survive all context management
245
+ * - Always re-injected - Present in every LLM call
246
+ * - Scoped - Session, persistent, or temporary
247
+ *
248
+ * @example
249
+ * ```typescript
250
+ * const agent = new Agent({
251
+ * provider,
252
+ * anchors: {
253
+ * maxAnchors: 20,
254
+ * maxTokens: 2000,
255
+ * persistPath: '~/.myapp/anchors.json',
256
+ * includeDefaults: true, // Include built-in safety anchors
257
+ * }
258
+ * });
259
+ * ```
260
+ */
261
+ anchors?: AnchorManagerOptions;
262
+ /**
263
+ * Guardrail options for pattern-based safety checks.
264
+ *
265
+ * Guardrails scan tool inputs before execution and can:
266
+ * - warn: Log a warning but proceed
267
+ * - confirm: Require confirmation (via onTriggered handler)
268
+ * - block: Prevent execution entirely
269
+ *
270
+ * @example
271
+ * ```typescript
272
+ * const agent = new Agent({
273
+ * provider,
274
+ * guardrails: {
275
+ * enabled: true,
276
+ * includeDefaults: true, // Include built-in guardrails
277
+ * custom: [
278
+ * {
279
+ * id: 'no-prod',
280
+ * name: 'Production Protection',
281
+ * description: 'Block operations on production',
282
+ * patterns: [/prod/i],
283
+ * action: 'block',
284
+ * message: 'Production operations are blocked',
285
+ * }
286
+ * ],
287
+ * onTriggered: async (result, context) => {
288
+ * // Return true to proceed, false to block
289
+ * return await askUser(result.guardrail.message);
290
+ * }
291
+ * }
292
+ * });
293
+ * ```
294
+ */
295
+ guardrails?: GuardrailManagerOptions;
296
+ /**
297
+ * Permission options for tool-level access control.
298
+ *
299
+ * Permissions allow fine-grained control over which tools can execute
300
+ * and when user approval is required.
301
+ *
302
+ * @example
303
+ * ```typescript
304
+ * const agent = new Agent({
305
+ * provider,
306
+ * permissions: {
307
+ * defaultLevel: 'always', // Default: allow all tools
308
+ * rules: [
309
+ * { toolName: 'bash', level: 'once', description: 'Shell commands' },
310
+ * { toolName: 'write_file', level: 'session', description: 'File writes' },
311
+ * { toolName: 'delete_*', level: 'deny' }, // Wildcard: block all delete tools
312
+ * ],
313
+ * onPermissionRequest: async (request) => {
314
+ * // Return true to allow, false to deny
315
+ * return await showConfirmDialog(
316
+ * `Allow ${request.toolName}?`,
317
+ * request.preview
318
+ * );
319
+ * }
320
+ * }
321
+ * });
322
+ * ```
323
+ */
324
+ permissions?: PermissionManagerOptions;
325
+ /**
326
+ * Pre-loaded project memory to prepend to system prompt.
327
+ *
328
+ * Use `Agent.createWithMemory()` to automatically load from files,
329
+ * or pass a pre-loaded ProjectMemory object.
330
+ *
331
+ * @example
332
+ * ```typescript
333
+ * // Option 1: Use the factory method (recommended)
334
+ * const agent = await Agent.createWithMemory({
335
+ * provider,
336
+ * systemPrompt: 'You are a helpful assistant.',
337
+ * projectMemoryOptions: {
338
+ * providers: ['claude', 'gemini'],
339
+ * includeGeneric: true,
340
+ * },
341
+ * projectMemoryDir: '/path/to/project',
342
+ * });
343
+ *
344
+ * // Option 2: Pre-load memory manually
345
+ * const loader = new ProjectMemoryLoader({ providers: 'claude' });
346
+ * const memory = await loader.load('/path/to/project');
347
+ *
348
+ * const agent = new Agent({
349
+ * provider,
350
+ * systemPrompt: 'You are a helpful assistant.',
351
+ * projectMemory: memory, // Pre-loaded memory
352
+ * });
353
+ * ```
354
+ */
355
+ projectMemory?: ProjectMemory;
356
+ /**
357
+ * Usage tracking options for monitoring token usage.
358
+ *
359
+ * Note: We track tokens only, not dollar costs. Pricing changes frequently
360
+ * and providing potentially inaccurate cost information would be misleading.
361
+ *
362
+ * @example
363
+ * ```typescript
364
+ * const agent = new Agent({
365
+ * provider,
366
+ * usage: {
367
+ * enabled: true,
368
+ * budget: {
369
+ * maxTotalTokens: 100000, // 100k token limit
370
+ * warningThreshold: 0.8, // Warn at 80%
371
+ * },
372
+ * },
373
+ * });
374
+ *
375
+ * // After runs, check usage
376
+ * console.log(agent.getUsageStats());
377
+ * console.log(agent.getTotalTokens());
378
+ *
379
+ * // Listen for budget events
380
+ * agent.onEvent((event) => {
381
+ * if (event.type === 'usage_budget_warning') {
382
+ * console.log('Budget warning!', event.status);
383
+ * }
384
+ * });
385
+ * ```
386
+ */
387
+ usage?: UsageTrackerOptions;
388
+ /**
389
+ * Hooks for customizing agent behavior at various lifecycle points.
390
+ *
391
+ * Hooks provide extension points without subclassing for:
392
+ * - Logging and tracing
393
+ * - Input/output transformation
394
+ * - Custom validation
395
+ * - Metrics collection
396
+ * - Integration with external systems
397
+ *
398
+ * @example
399
+ * ```typescript
400
+ * const agent = new Agent({
401
+ * provider,
402
+ * hooks: {
403
+ * beforeTool: [
404
+ * async (ctx) => {
405
+ * console.log(`Tool ${ctx.toolName} starting...`);
406
+ * }
407
+ * ],
408
+ * afterTool: [
409
+ * async (ctx) => {
410
+ * console.log(`Tool ${ctx.toolName} completed in ${ctx.durationMs}ms`);
411
+ * // Optionally modify result
412
+ * return { result: ctx.result };
413
+ * }
414
+ * ],
415
+ * beforeLLM: [
416
+ * async (ctx) => {
417
+ * // Optionally inject or transform messages
418
+ * return { messages: ctx.messages };
419
+ * }
420
+ * ],
421
+ * onError: [
422
+ * async (ctx) => {
423
+ * console.error(`Error in ${ctx.phase}:`, ctx.error);
424
+ * }
425
+ * ]
426
+ * }
427
+ * });
428
+ * ```
429
+ */
430
+ hooks?: HooksConfig;
431
+ }
432
+ /**
433
+ * Options for a single run
434
+ */
435
+ export interface RunOptions {
436
+ /**
437
+ * AbortSignal for cancellation
438
+ */
439
+ signal?: AbortSignal;
440
+ /**
441
+ * Override max iterations for this run
442
+ */
443
+ maxIterations?: number;
444
+ /**
445
+ * Override chat options for this run
446
+ */
447
+ chatOptions?: ChatOptions;
448
+ /**
449
+ * Event handler for this run (in addition to config handler)
450
+ */
451
+ onEvent?: AgentEventHandler;
452
+ }
453
+ /**
454
+ * Agent run result
455
+ */
456
+ export interface AgentRunResult {
457
+ /**
458
+ * Final text response from the agent
459
+ */
460
+ response: string;
461
+ /**
462
+ * All messages in the conversation
463
+ */
464
+ messages: Message[];
465
+ /**
466
+ * Number of iterations (tool use loops) executed
467
+ */
468
+ iterations: number;
469
+ /**
470
+ * Tool calls made during execution
471
+ */
472
+ toolCalls: Array<{
473
+ name: string;
474
+ input: Record<string, unknown>;
475
+ result: ToolExecutionResult;
476
+ }>;
477
+ /**
478
+ * Whether the run was aborted
479
+ */
480
+ aborted: boolean;
481
+ /**
482
+ * Context statistics (if context manager is enabled)
483
+ */
484
+ contextStats?: ContextStats;
485
+ }
486
+ /**
487
+ * Configuration for creating a sub-agent
488
+ */
489
+ export interface SubAgentConfig {
490
+ /**
491
+ * Unique name for this sub-agent
492
+ */
493
+ name: string;
494
+ /**
495
+ * Description of what this sub-agent specializes in.
496
+ * Used for automatic delegation decisions.
497
+ */
498
+ description?: string;
499
+ /**
500
+ * System prompt for this sub-agent.
501
+ * If not provided, inherits from parent.
502
+ */
503
+ systemPrompt?: string;
504
+ /**
505
+ * Context mode for this sub-agent.
506
+ * - 'isolated': Fresh context, no parent history (default)
507
+ * - 'inherited': Receives a summary of parent context
508
+ * - 'shared': Full access to parent context (not recommended for large contexts)
509
+ */
510
+ contextMode?: 'isolated' | 'inherited' | 'shared';
511
+ /**
512
+ * Tools available to this sub-agent.
513
+ * - If not specified, inherits parent's tools
514
+ * - Can be a subset of parent's tools for safety
515
+ */
516
+ tools?: Tool[];
517
+ /**
518
+ * Maximum iterations for this sub-agent (default: 5)
519
+ */
520
+ maxIterations?: number;
521
+ /**
522
+ * Chat options override for this sub-agent
523
+ */
524
+ chatOptions?: ChatOptions;
525
+ /**
526
+ * Maximum tokens for this sub-agent's context budget.
527
+ * Default: 25% of parent's context budget.
528
+ */
529
+ contextBudget?: number;
530
+ /**
531
+ * Automatically dispose the sub-agent after each execution.
532
+ * This releases memory but requires re-creation for subsequent runs.
533
+ * Default: false (sub-agent persists for reuse)
534
+ */
535
+ autoDispose?: boolean;
536
+ /**
537
+ * Maximum size (in bytes) for tool result data returned in SubAgentResult.
538
+ * Larger results are truncated to prevent memory bloat.
539
+ * Default: 50KB
540
+ */
541
+ maxToolResultSize?: number;
542
+ /**
543
+ * Enable state isolation for this sub-agent.
544
+ *
545
+ * When true, the sub-agent uses an isolated todo store instead of the
546
+ * shared default store. This prevents state leakage between parallel
547
+ * sub-agent executions.
548
+ *
549
+ * Automatically enabled when using runParallelSubAgents().
550
+ *
551
+ * Inspired by LangGraph issue #6446: Parallel subgraphs with shared
552
+ * state keys cause InvalidUpdateError.
553
+ *
554
+ * Default: false (uses shared store)
555
+ */
556
+ stateIsolation?: boolean;
557
+ }
558
+ /**
559
+ * Result from a sub-agent execution
560
+ */
561
+ export interface SubAgentResult {
562
+ /**
563
+ * Name of the sub-agent that executed
564
+ */
565
+ name: string;
566
+ /**
567
+ * Final response from the sub-agent
568
+ */
569
+ response: string;
570
+ /**
571
+ * Whether the execution was successful
572
+ */
573
+ success: boolean;
574
+ /**
575
+ * Error message if execution failed
576
+ */
577
+ error?: string;
578
+ /**
579
+ * Number of iterations used
580
+ */
581
+ iterations: number;
582
+ /**
583
+ * Tool calls made by the sub-agent
584
+ */
585
+ toolCalls: AgentRunResult['toolCalls'];
586
+ /**
587
+ * Context stats for the sub-agent's execution
588
+ */
589
+ contextStats?: ContextStats;
590
+ }
591
+ /**
592
+ * Agent class - orchestrates LLM interactions with tool use
593
+ *
594
+ * @example
595
+ * ```typescript
596
+ * const agent = new Agent({
597
+ * provider: new ClaudeProvider({ apiKey: 'sk-...' }),
598
+ * systemPrompt: 'You are a helpful assistant.',
599
+ * });
600
+ *
601
+ * agent.registerTool(readFileTool);
602
+ * agent.registerTool(writeFileTool);
603
+ *
604
+ * const result = await agent.run('Read the contents of package.json');
605
+ * console.log(result.response);
606
+ * ```
607
+ */
608
+ export declare class Agent {
609
+ private readonly provider;
610
+ private readonly systemPrompt;
611
+ private readonly maxIterations;
612
+ private readonly maxConsecutiveToolCalls;
613
+ private readonly iterationLimitBehavior;
614
+ private readonly chatOptions;
615
+ private readonly toolRegistry;
616
+ private readonly contextManager?;
617
+ private readonly autoContextManagement;
618
+ private readonly onEvent?;
619
+ private readonly checkpointer?;
620
+ private readonly _sessionId;
621
+ private readonly autoCheckpoint;
622
+ private readonly checkpointOnAbort;
623
+ private _createdAt;
624
+ private _totalTokensUsed;
625
+ private _currentIteration;
626
+ /**
627
+ * Conversation history - persists across run() calls
628
+ */
629
+ private conversationHistory;
630
+ /**
631
+ * Registered sub-agents
632
+ */
633
+ private readonly subAgents;
634
+ /**
635
+ * Anchor manager for critical information that survives context compaction
636
+ */
637
+ private readonly anchorManager?;
638
+ /**
639
+ * Guardrail manager for pattern-based safety checks
640
+ */
641
+ private readonly guardrailManager?;
642
+ /**
643
+ * Permission manager for tool-level access control
644
+ */
645
+ private readonly permissionManager?;
646
+ /**
647
+ * Loaded project memory (instructions from CLAUDE.md, etc.)
648
+ */
649
+ private readonly projectMemory?;
650
+ /**
651
+ * Usage tracker for token usage monitoring
652
+ */
653
+ private readonly usageTracker?;
654
+ /**
655
+ * Hooks manager for lifecycle hooks
656
+ */
657
+ private readonly hooksManager?;
658
+ constructor(config: AgentConfig);
659
+ /**
660
+ * Create an agent with project memory loaded from files.
661
+ *
662
+ * This factory method automatically discovers and loads project-specific
663
+ * instructions from files like CLAUDE.md, GEMINI.md, PROJECT.md, etc.
664
+ *
665
+ * @param config - Agent configuration
666
+ * @param memoryOptions - Project memory loading options
667
+ * @param memoryDir - Directory to search for memory files (defaults to cwd)
668
+ * @returns Agent instance with loaded project memory
669
+ *
670
+ * @example
671
+ * ```typescript
672
+ * // Load Claude-specific instructions
673
+ * const agent = await Agent.createWithMemory(
674
+ * {
675
+ * provider,
676
+ * systemPrompt: 'You are a helpful assistant.',
677
+ * },
678
+ * { providers: 'claude' },
679
+ * '/path/to/project'
680
+ * );
681
+ *
682
+ * // Load instructions for multiple providers
683
+ * const agent = await Agent.createWithMemory(
684
+ * { provider },
685
+ * { providers: ['claude', 'gemini'], includeGeneric: true }
686
+ * );
687
+ *
688
+ * // Access loaded memory
689
+ * const memory = agent.getProjectMemory();
690
+ * console.log(`Loaded ${memory?.files.length} memory files`);
691
+ * ```
692
+ */
693
+ static createWithMemory(config: Omit<AgentConfig, 'projectMemory'>, memoryOptions?: ProjectMemoryOptions, memoryDir?: string): Promise<Agent>;
694
+ /**
695
+ * Get the session ID for this agent instance
696
+ */
697
+ get sessionId(): string;
698
+ /**
699
+ * Get the loaded project memory (if any).
700
+ *
701
+ * Project memory contains instructions loaded from files like
702
+ * CLAUDE.md, GEMINI.md, PROJECT.md, etc.
703
+ *
704
+ * @returns The loaded project memory, or undefined if none was loaded
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * const memory = agent.getProjectMemory();
709
+ * if (memory) {
710
+ * console.log(`Loaded ${memory.files.length} instruction files`);
711
+ * console.log(`Total tokens: ~${memory.estimatedTokens}`);
712
+ * for (const file of memory.files) {
713
+ * console.log(` - ${file.relativePath}`);
714
+ * }
715
+ * }
716
+ * ```
717
+ */
718
+ getProjectMemory(): ProjectMemory | undefined;
719
+ /**
720
+ * Check if project memory was loaded
721
+ */
722
+ hasProjectMemory(): boolean;
723
+ /**
724
+ * Get usage tracking statistics.
725
+ *
726
+ * @returns Usage statistics or undefined if usage tracking is not enabled
727
+ *
728
+ * @example
729
+ * ```typescript
730
+ * const stats = agent.getUsageStats();
731
+ * if (stats) {
732
+ * console.log(`Total calls: ${stats.totalCalls}`);
733
+ * console.log(`Total tokens: ${stats.totalTokens}`);
734
+ * console.log(`Input tokens: ${stats.totalInputTokens}`);
735
+ * console.log(`Output tokens: ${stats.totalOutputTokens}`);
736
+ * }
737
+ * ```
738
+ */
739
+ getUsageStats(): UsageStats | undefined;
740
+ /**
741
+ * Get total tokens used across all LLM calls.
742
+ */
743
+ getTotalTokens(): number;
744
+ /**
745
+ * Get total input tokens used across all LLM calls.
746
+ */
747
+ getTotalInputTokens(): number;
748
+ /**
749
+ * Get total output tokens used across all LLM calls.
750
+ */
751
+ getTotalOutputTokens(): number;
752
+ /**
753
+ * Get budget status.
754
+ */
755
+ getBudgetStatus(): BudgetStatus | undefined;
756
+ /**
757
+ * Check if budget is exceeded.
758
+ */
759
+ isBudgetExceeded(): boolean;
760
+ /**
761
+ * Get a human-readable usage summary.
762
+ */
763
+ getUsageSummary(): string | undefined;
764
+ /**
765
+ * Reset usage tracking data.
766
+ */
767
+ resetUsageTracking(): void;
768
+ /**
769
+ * Check if usage tracking is enabled.
770
+ */
771
+ hasUsageTracking(): boolean;
772
+ /**
773
+ * Record usage manually (for custom provider integrations).
774
+ *
775
+ * @internal
776
+ */
777
+ recordUsage(model: string, provider: string, tokens: TokenUsage): void;
778
+ /**
779
+ * Add an anchor (critical information that survives context compaction).
780
+ *
781
+ * Anchors are injected into every LLM call and never get compacted.
782
+ * Use them for information that must not be forgotten.
783
+ *
784
+ * @param input - Anchor input
785
+ * @returns The created anchor, or undefined if anchors are not enabled
786
+ *
787
+ * @example
788
+ * ```typescript
789
+ * // Session anchor - lives for this session only
790
+ * agent.addAnchor({
791
+ * content: 'This session we implemented: edit tool, grep tool',
792
+ * priority: 'critical',
793
+ * scope: 'session',
794
+ * });
795
+ *
796
+ * // Safety anchor - persisted across sessions
797
+ * agent.addAnchor({
798
+ * content: 'Never delete files in /important without confirmation',
799
+ * priority: 'safety',
800
+ * scope: 'persistent',
801
+ * });
802
+ *
803
+ * // Temporary anchor - expires after 1 hour
804
+ * agent.addAnchor({
805
+ * content: 'Currently working on feature X',
806
+ * priority: 'info',
807
+ * scope: 'temporary',
808
+ * expiresAt: new Date(Date.now() + 60 * 60 * 1000),
809
+ * });
810
+ * ```
811
+ */
812
+ addAnchor(input: AnchorInput): Anchor | undefined;
813
+ /**
814
+ * Get an anchor by ID
815
+ */
816
+ getAnchor(id: string): Anchor | undefined;
817
+ /**
818
+ * Get all anchors, optionally filtered
819
+ *
820
+ * @param options - Query options for filtering
821
+ * @returns Array of anchors
822
+ *
823
+ * @example
824
+ * ```typescript
825
+ * // Get all anchors
826
+ * const all = agent.getAnchors();
827
+ *
828
+ * // Get only safety anchors
829
+ * const safety = agent.getAnchors({ priority: 'safety' });
830
+ *
831
+ * // Get session anchors with specific tags
832
+ * const tagged = agent.getAnchors({ scope: 'session', tags: ['files'] });
833
+ * ```
834
+ */
835
+ getAnchors(options?: AnchorQueryOptions): Anchor[];
836
+ /**
837
+ * Check if an anchor exists
838
+ */
839
+ hasAnchor(id: string): boolean;
840
+ /**
841
+ * Remove an anchor by ID
842
+ *
843
+ * @returns true if anchor was removed, false if not found
844
+ */
845
+ removeAnchor(id: string): boolean;
846
+ /**
847
+ * Clear anchors based on criteria
848
+ *
849
+ * @param options - Clear options for filtering which anchors to remove
850
+ * @returns Number of anchors removed
851
+ *
852
+ * @example
853
+ * ```typescript
854
+ * // Clear all session anchors
855
+ * agent.clearAnchors({ scope: 'session' });
856
+ *
857
+ * // Clear expired temporary anchors
858
+ * agent.clearAnchors({ expiredOnly: true });
859
+ *
860
+ * // Clear anchors with specific tags
861
+ * agent.clearAnchors({ tags: ['auto'] });
862
+ * ```
863
+ */
864
+ clearAnchors(options?: AnchorClearOptions): number;
865
+ /**
866
+ * Get the anchor manager (if configured)
867
+ */
868
+ getAnchorManager(): AnchorManager | undefined;
869
+ /**
870
+ * Check if anchors are enabled
871
+ */
872
+ hasAnchors(): boolean;
873
+ /**
874
+ * Add a custom guardrail
875
+ *
876
+ * @param input - Guardrail definition
877
+ * @returns The created guardrail, or undefined if guardrails are not enabled
878
+ *
879
+ * @example
880
+ * ```typescript
881
+ * agent.addGuardrail({
882
+ * id: 'no-delete-important',
883
+ * name: 'Important Files Protection',
884
+ * description: 'Prevent deletion of important files',
885
+ * patterns: [/rm.*important/i, /delete.*important/i],
886
+ * action: 'block',
887
+ * message: 'Cannot delete files marked as important',
888
+ * scope: ['bash'],
889
+ * });
890
+ * ```
891
+ */
892
+ addGuardrail(input: GuardrailInput): Guardrail | undefined;
893
+ /**
894
+ * Get a guardrail by ID
895
+ */
896
+ getGuardrail(id: string): Guardrail | undefined;
897
+ /**
898
+ * Get all guardrails
899
+ */
900
+ getGuardrails(): Guardrail[];
901
+ /**
902
+ * Check if a guardrail exists
903
+ */
904
+ hasGuardrail(id: string): boolean;
905
+ /**
906
+ * Remove a guardrail by ID
907
+ */
908
+ removeGuardrail(id: string): boolean;
909
+ /**
910
+ * Enable a guardrail by ID
911
+ */
912
+ enableGuardrail(id: string): boolean;
913
+ /**
914
+ * Disable a guardrail by ID
915
+ */
916
+ disableGuardrail(id: string): boolean;
917
+ /**
918
+ * Get the guardrail manager (if configured)
919
+ */
920
+ getGuardrailManager(): GuardrailManager | undefined;
921
+ /**
922
+ * Check if guardrails are enabled
923
+ */
924
+ hasGuardrails(): boolean;
925
+ /**
926
+ * Add a permission rule for a tool
927
+ *
928
+ * @param rule - Permission rule to add
929
+ * @returns this for chaining
930
+ *
931
+ * @example
932
+ * ```typescript
933
+ * agent.addPermission({
934
+ * toolName: 'bash',
935
+ * level: 'once',
936
+ * description: 'Execute shell commands',
937
+ * });
938
+ * ```
939
+ */
940
+ addPermission(rule: ToolPermission): this;
941
+ /**
942
+ * Remove a permission rule by tool name
943
+ */
944
+ removePermission(toolName: string): boolean;
945
+ /**
946
+ * Get a permission rule by tool name
947
+ */
948
+ getPermission(toolName: string): ToolPermission | undefined;
949
+ /**
950
+ * Get all permission rules
951
+ */
952
+ getPermissions(): ToolPermission[];
953
+ /**
954
+ * Set the permission level for a tool
955
+ *
956
+ * @param toolName - Tool name or pattern
957
+ * @param level - Permission level
958
+ * @param description - Optional description
959
+ */
960
+ setPermissionLevel(toolName: string, level: PermissionLevel, description?: string): this;
961
+ /**
962
+ * Get the effective permission level for a tool
963
+ */
964
+ getPermissionLevel(toolName: string): PermissionLevel;
965
+ /**
966
+ * Grant session-level permission for a tool
967
+ */
968
+ grantSessionPermission(toolName: string): this;
969
+ /**
970
+ * Revoke session-level permission for a tool
971
+ */
972
+ revokeSessionPermission(toolName: string): boolean;
973
+ /**
974
+ * Clear all session-level permissions
975
+ */
976
+ clearSessionPermissions(): this;
977
+ /**
978
+ * Get all tools with session-level permission
979
+ */
980
+ getSessionPermissions(): string[];
981
+ /**
982
+ * Get the permission manager (if configured)
983
+ */
984
+ getPermissionManager(): PermissionManager | undefined;
985
+ /**
986
+ * Check if permissions are enabled
987
+ */
988
+ hasPermissions(): boolean;
989
+ /**
990
+ * Emit a custom event that will be streamed to event handlers.
991
+ *
992
+ * This allows tools, middleware, and user code to emit custom events
993
+ * that are streamed alongside built-in agent events.
994
+ *
995
+ * Inspired by LangGraph's get_stream_writer() pattern.
996
+ * Addresses issues like LangGraph #6330 (preserve event metadata).
997
+ *
998
+ * @param config - Custom event configuration
999
+ *
1000
+ * @example
1001
+ * ```typescript
1002
+ * agent.emitCustomEvent({
1003
+ * name: 'progress',
1004
+ * data: { step: 1, total: 5, message: 'Processing...' },
1005
+ * metadata: { toolName: 'myTool' },
1006
+ * });
1007
+ * ```
1008
+ */
1009
+ emitCustomEvent(config: CustomEventConfig): void;
1010
+ /**
1011
+ * Get a stream writer function for emitting custom events.
1012
+ *
1013
+ * This returns a simple function that can be passed to tools or
1014
+ * middleware for streaming progress updates.
1015
+ *
1016
+ * @param eventName - Name for all events emitted by this writer
1017
+ * @returns A stream writer function
1018
+ *
1019
+ * @example
1020
+ * ```typescript
1021
+ * const writer = agent.getStreamWriter('myTool');
1022
+ * writer('Starting...', { phase: 'init' });
1023
+ * writer('Processing...', { phase: 'work', progress: 50 });
1024
+ * writer('Done!', { phase: 'complete' });
1025
+ * ```
1026
+ */
1027
+ getStreamWriter(eventName?: string): StreamWriter;
1028
+ /**
1029
+ * Clear conversation history to start fresh
1030
+ */
1031
+ clearHistory(): this;
1032
+ /**
1033
+ * Get the current conversation history
1034
+ */
1035
+ getHistory(): Message[];
1036
+ /**
1037
+ * Get the context manager (if configured)
1038
+ */
1039
+ getContextManager(): ContextManager | undefined;
1040
+ /**
1041
+ * Get context statistics
1042
+ */
1043
+ getContextStats(): ContextStats | undefined;
1044
+ /**
1045
+ * Get current verbosity level based on context pressure
1046
+ */
1047
+ getVerbosityLevel(): VerbosityLevel;
1048
+ /**
1049
+ * Serialize the current agent state to an AgentState object.
1050
+ * This can be used for manual persistence or transferring state.
1051
+ *
1052
+ * @example
1053
+ * ```typescript
1054
+ * const state = agent.serialize();
1055
+ * const json = JSON.stringify(state);
1056
+ * // Store json somewhere...
1057
+ * ```
1058
+ */
1059
+ serialize(): AgentState;
1060
+ /**
1061
+ * Save the current state using the configured checkpointer.
1062
+ * Throws if no checkpointer is configured.
1063
+ *
1064
+ * @param metadata - Optional metadata overrides
1065
+ * @returns The session ID
1066
+ *
1067
+ * @example
1068
+ * ```typescript
1069
+ * const agent = new Agent({
1070
+ * provider,
1071
+ * checkpointer: new FileCheckpointer('~/.myapp/sessions/'),
1072
+ * });
1073
+ *
1074
+ * await agent.run('Hello!');
1075
+ * const sessionId = await agent.checkpoint();
1076
+ * console.log(`Saved as: ${sessionId}`);
1077
+ * ```
1078
+ */
1079
+ checkpoint(metadata?: Partial<SessionMetadata>): Promise<string>;
1080
+ /**
1081
+ * Check if a checkpointer is configured
1082
+ */
1083
+ hasCheckpointer(): boolean;
1084
+ /**
1085
+ * Save a partial checkpoint on abort or error.
1086
+ * This is called internally when checkpointOnAbort is enabled.
1087
+ *
1088
+ * @param reason - Why the checkpoint was saved ('aborted' or 'error')
1089
+ * @param emit - Event emitter function
1090
+ * @returns Promise that resolves when checkpoint is saved
1091
+ */
1092
+ private saveAbortCheckpoint;
1093
+ /**
1094
+ * Resume an agent from a saved session.
1095
+ *
1096
+ * @param sessionId - Session ID to resume
1097
+ * @param options - Resume options (provider and checkpointer required)
1098
+ *
1099
+ * @example
1100
+ * ```typescript
1101
+ * const checkpointer = new FileCheckpointer('~/.myapp/sessions/');
1102
+ *
1103
+ * // Resume a previous session
1104
+ * const agent = await Agent.resume('session_abc123', {
1105
+ * provider: new ClaudeProvider({ apiKey: '...' }),
1106
+ * checkpointer,
1107
+ * });
1108
+ *
1109
+ * // Continue the conversation
1110
+ * await agent.run('Continue where we left off...');
1111
+ * ```
1112
+ */
1113
+ static resume(sessionId: string, options: {
1114
+ provider: LLMProvider;
1115
+ checkpointer: Checkpointer;
1116
+ systemPrompt?: string;
1117
+ tools?: Tool[];
1118
+ onEvent?: AgentEventHandler;
1119
+ }): Promise<Agent>;
1120
+ /**
1121
+ * Create an agent from a serialized AgentState object.
1122
+ *
1123
+ * @param state - The serialized agent state
1124
+ * @param options - Options for the new agent
1125
+ *
1126
+ * @example
1127
+ * ```typescript
1128
+ * // Load state from somewhere
1129
+ * const json = await fs.readFile('session.json', 'utf-8');
1130
+ * const state = JSON.parse(json);
1131
+ *
1132
+ * // Create agent from state
1133
+ * const agent = Agent.fromState(state, { provider });
1134
+ * await agent.run('Continue...');
1135
+ * ```
1136
+ */
1137
+ static fromState(state: AgentState, options: {
1138
+ provider: LLMProvider;
1139
+ checkpointer?: Checkpointer;
1140
+ tools?: Tool[];
1141
+ onEvent?: AgentEventHandler;
1142
+ systemPrompt?: string;
1143
+ }): Agent;
1144
+ /**
1145
+ * Create and register a sub-agent with isolated context.
1146
+ *
1147
+ * Sub-agents are specialized agents that handle discrete tasks independently.
1148
+ * They have their own context window and can have different tools/permissions.
1149
+ *
1150
+ * @example
1151
+ * ```typescript
1152
+ * agent.createSubAgent({
1153
+ * name: 'code-reviewer',
1154
+ * description: 'Reviews code for security and quality issues',
1155
+ * systemPrompt: 'You are a code review specialist...',
1156
+ * tools: [readFileTool], // Restricted tools
1157
+ * contextMode: 'isolated',
1158
+ * });
1159
+ *
1160
+ * const result = await agent.runSubAgent('code-reviewer', 'Review src/auth.ts');
1161
+ * ```
1162
+ */
1163
+ createSubAgent(config: SubAgentConfig): this;
1164
+ /**
1165
+ * Run a sub-agent with a specific task.
1166
+ *
1167
+ * The sub-agent executes independently with its own context and returns
1168
+ * the result to the parent agent.
1169
+ *
1170
+ * @param name - Name of the registered sub-agent
1171
+ * @param task - Task description for the sub-agent
1172
+ * @param options - Optional run options
1173
+ */
1174
+ runSubAgent(name: string, task: string, options?: RunOptions): Promise<SubAgentResult>;
1175
+ /**
1176
+ * Run multiple sub-agents in parallel with proper state isolation.
1177
+ *
1178
+ * This method ensures that parallel sub-agents don't share mutable state,
1179
+ * preventing race conditions and state leakage between concurrent runs.
1180
+ *
1181
+ * Inspired by LangGraph issue #6446: Parallel subgraphs with shared
1182
+ * state keys cause InvalidUpdateError.
1183
+ *
1184
+ * @param tasks - Array of {name, task} objects to run in parallel
1185
+ * @param options - Optional run options applied to all sub-agents
1186
+ * @returns Array of results in the same order as tasks
1187
+ *
1188
+ * @example
1189
+ * ```typescript
1190
+ * // Run code review and security scan in parallel
1191
+ * const results = await agent.runParallelSubAgents([
1192
+ * { name: 'code-reviewer', task: 'Review src/auth.ts' },
1193
+ * { name: 'security-scanner', task: 'Scan src/auth.ts for vulnerabilities' },
1194
+ * ]);
1195
+ * ```
1196
+ */
1197
+ runParallelSubAgents(tasks: Array<{
1198
+ name: string;
1199
+ task: string;
1200
+ }>, options?: RunOptions): Promise<SubAgentResult[]>;
1201
+ /**
1202
+ * Get a registered sub-agent by name
1203
+ */
1204
+ getSubAgent(name: string): Agent | undefined;
1205
+ /**
1206
+ * Get all registered sub-agent names
1207
+ */
1208
+ getSubAgentNames(): string[];
1209
+ /**
1210
+ * Remove a registered sub-agent (alias for disposeSubAgent)
1211
+ */
1212
+ removeSubAgent(name: string): boolean;
1213
+ /**
1214
+ * Dispose a sub-agent and release its resources.
1215
+ *
1216
+ * This clears the sub-agent's:
1217
+ * - Conversation history
1218
+ * - Context manager state
1219
+ * - Tool registry
1220
+ *
1221
+ * After disposal, the sub-agent must be re-created to use again.
1222
+ */
1223
+ disposeSubAgent(name: string): boolean;
1224
+ /**
1225
+ * Dispose all sub-agents and release their resources.
1226
+ *
1227
+ * Useful for cleanup when the parent agent is done or
1228
+ * to free memory during long-running sessions.
1229
+ */
1230
+ disposeAllSubAgents(): void;
1231
+ /**
1232
+ * Generate a concise summary of context for inherited mode
1233
+ */
1234
+ private generateContextSummary;
1235
+ /**
1236
+ * Register a tool for the agent to use
1237
+ */
1238
+ registerTool(tool: Tool): this;
1239
+ /**
1240
+ * Register multiple tools at once
1241
+ */
1242
+ registerTools(tools: Tool[]): this;
1243
+ /**
1244
+ * Get all registered tool definitions
1245
+ */
1246
+ getToolDefinitions(): ToolDefinition[];
1247
+ /**
1248
+ * Run the agent with a user message
1249
+ */
1250
+ run(userMessage: string, options?: RunOptions): Promise<AgentRunResult>;
1251
+ /**
1252
+ * Stream the agent's response with full tool use support
1253
+ *
1254
+ * Yields AgentEvent objects as the agent executes, allowing
1255
+ * real-time monitoring of the agentic loop.
1256
+ */
1257
+ stream(userMessage: string, options?: RunOptions): AsyncIterable<AgentEvent>;
1258
+ /**
1259
+ * Process stream chunks into text, tool uses, and usage data
1260
+ */
1261
+ private processChunks;
1262
+ /**
1263
+ * Generate a summary of messages using the LLM provider.
1264
+ * Used for context summarization when approaching limits.
1265
+ */
1266
+ private generateSummary;
1267
+ /**
1268
+ * Generate a summary when the agent hits max iterations.
1269
+ * This provides a graceful fallback instead of just throwing an error.
1270
+ */
1271
+ private generateIterationLimitSummary;
1272
+ }