@everworker/oneringai 0.4.2 → 0.4.4
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.
- package/README.md +132 -13
- package/dist/{IProvider-CNJqZItJ.d.cts → IProvider-B8sqUzJG.d.cts} +36 -6
- package/dist/{IProvider-B6hqVVq8.d.ts → IProvider-CxDUGl6n.d.ts} +36 -6
- package/dist/{ImageModel-B64HX3lN.d.cts → ImageModel-Ds5_6sf7.d.cts} +1 -1
- package/dist/{ImageModel-DU-y_WOb.d.ts → ImageModel-OWbA277F.d.ts} +1 -1
- package/dist/capabilities/agents/index.d.cts +2 -2
- package/dist/capabilities/agents/index.d.ts +2 -2
- package/dist/capabilities/images/index.cjs +251 -106
- package/dist/capabilities/images/index.cjs.map +1 -1
- package/dist/capabilities/images/index.d.cts +2 -2
- package/dist/capabilities/images/index.d.ts +2 -2
- package/dist/capabilities/images/index.js +251 -106
- package/dist/capabilities/images/index.js.map +1 -1
- package/dist/index-DmYrHH7d.d.cts +2556 -0
- package/dist/index-Dyl6pHfq.d.ts +2556 -0
- package/dist/index.cjs +4141 -444
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +825 -945
- package/dist/index.d.ts +825 -945
- package/dist/index.js +4107 -429
- package/dist/index.js.map +1 -1
- package/dist/shared/index.cjs +9 -0
- package/dist/shared/index.cjs.map +1 -1
- package/dist/shared/index.js +9 -0
- package/dist/shared/index.js.map +1 -1
- package/package.json +2 -1
- package/dist/index-9VOnAX17.d.ts +0 -1397
- package/dist/index-BMjyFNJQ.d.cts +0 -1397
|
@@ -0,0 +1,2556 @@
|
|
|
1
|
+
import { I as IConnectorRegistry, e as IProvider } from './IProvider-CxDUGl6n.js';
|
|
2
|
+
import { EventEmitter } from 'eventemitter3';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Content types based on OpenAI Responses API format
|
|
6
|
+
*/
|
|
7
|
+
declare enum ContentType {
|
|
8
|
+
INPUT_TEXT = "input_text",
|
|
9
|
+
INPUT_IMAGE_URL = "input_image_url",
|
|
10
|
+
INPUT_FILE = "input_file",
|
|
11
|
+
OUTPUT_TEXT = "output_text",
|
|
12
|
+
TOOL_USE = "tool_use",
|
|
13
|
+
TOOL_RESULT = "tool_result",
|
|
14
|
+
THINKING = "thinking"
|
|
15
|
+
}
|
|
16
|
+
interface BaseContent {
|
|
17
|
+
type: ContentType;
|
|
18
|
+
}
|
|
19
|
+
interface InputTextContent extends BaseContent {
|
|
20
|
+
type: ContentType.INPUT_TEXT;
|
|
21
|
+
text: string;
|
|
22
|
+
}
|
|
23
|
+
interface InputImageContent extends BaseContent {
|
|
24
|
+
type: ContentType.INPUT_IMAGE_URL;
|
|
25
|
+
image_url: {
|
|
26
|
+
url: string;
|
|
27
|
+
detail?: 'auto' | 'low' | 'high';
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
interface InputFileContent extends BaseContent {
|
|
31
|
+
type: ContentType.INPUT_FILE;
|
|
32
|
+
file_id: string;
|
|
33
|
+
}
|
|
34
|
+
interface OutputTextContent extends BaseContent {
|
|
35
|
+
type: ContentType.OUTPUT_TEXT;
|
|
36
|
+
text: string;
|
|
37
|
+
annotations?: any[];
|
|
38
|
+
}
|
|
39
|
+
interface ToolUseContent extends BaseContent {
|
|
40
|
+
type: ContentType.TOOL_USE;
|
|
41
|
+
id: string;
|
|
42
|
+
name: string;
|
|
43
|
+
arguments: string;
|
|
44
|
+
}
|
|
45
|
+
interface ToolResultContent extends BaseContent {
|
|
46
|
+
type: ContentType.TOOL_RESULT;
|
|
47
|
+
tool_use_id: string;
|
|
48
|
+
content: string | any;
|
|
49
|
+
error?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Images extracted from tool results via the __images convention.
|
|
52
|
+
* Stored separately from `content` so they don't inflate text-based token counts.
|
|
53
|
+
* Provider converters read this field to inject native multimodal image blocks.
|
|
54
|
+
*/
|
|
55
|
+
__images?: Array<{
|
|
56
|
+
base64: string;
|
|
57
|
+
mediaType: string;
|
|
58
|
+
}>;
|
|
59
|
+
}
|
|
60
|
+
interface ThinkingContent extends BaseContent {
|
|
61
|
+
type: ContentType.THINKING;
|
|
62
|
+
thinking: string;
|
|
63
|
+
/** Anthropic's opaque signature for round-tripping thinking blocks */
|
|
64
|
+
signature?: string;
|
|
65
|
+
/** Whether this thinking block should be persisted in conversation history.
|
|
66
|
+
* Anthropic requires it (true), OpenAI/Google do not (false). */
|
|
67
|
+
persistInHistory: boolean;
|
|
68
|
+
}
|
|
69
|
+
type Content = InputTextContent | InputImageContent | InputFileContent | OutputTextContent | ToolUseContent | ToolResultContent | ThinkingContent;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Message entity based on OpenAI Responses API format
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
declare enum MessageRole {
|
|
76
|
+
USER = "user",
|
|
77
|
+
ASSISTANT = "assistant",
|
|
78
|
+
DEVELOPER = "developer"
|
|
79
|
+
}
|
|
80
|
+
interface Message {
|
|
81
|
+
type: 'message';
|
|
82
|
+
id?: string;
|
|
83
|
+
role: MessageRole;
|
|
84
|
+
content: Content[];
|
|
85
|
+
}
|
|
86
|
+
interface CompactionItem {
|
|
87
|
+
type: 'compaction';
|
|
88
|
+
id: string;
|
|
89
|
+
encrypted_content: string;
|
|
90
|
+
}
|
|
91
|
+
interface ReasoningItem {
|
|
92
|
+
type: 'reasoning';
|
|
93
|
+
id: string;
|
|
94
|
+
effort?: 'low' | 'medium' | 'high';
|
|
95
|
+
summary?: string;
|
|
96
|
+
encrypted_content?: string;
|
|
97
|
+
}
|
|
98
|
+
type InputItem = Message | CompactionItem;
|
|
99
|
+
type OutputItem = Message | CompactionItem | ReasoningItem;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Memory entities for WorkingMemory
|
|
103
|
+
*
|
|
104
|
+
* This module provides a GENERIC memory system that works across all agent types:
|
|
105
|
+
* - Basic Agent: Simple session/persistent scoping with static priority
|
|
106
|
+
* - TaskAgent: Task-aware scoping with dynamic priority based on task states
|
|
107
|
+
* - UniversalAgent: Mode-aware, switches strategy based on current mode
|
|
108
|
+
*
|
|
109
|
+
* The key abstraction is PriorityCalculator - a pluggable strategy that
|
|
110
|
+
* determines entry priority for eviction decisions.
|
|
111
|
+
*/
|
|
112
|
+
/**
|
|
113
|
+
* Simple scope for basic agents - just a lifecycle label
|
|
114
|
+
*/
|
|
115
|
+
type SimpleScope = 'session' | 'persistent';
|
|
116
|
+
/**
|
|
117
|
+
* Task-aware scope for TaskAgent/UniversalAgent
|
|
118
|
+
*/
|
|
119
|
+
type TaskAwareScope = {
|
|
120
|
+
type: 'task';
|
|
121
|
+
taskIds: string[];
|
|
122
|
+
} | {
|
|
123
|
+
type: 'plan';
|
|
124
|
+
} | {
|
|
125
|
+
type: 'persistent';
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Union type - memory system accepts both
|
|
129
|
+
*/
|
|
130
|
+
type MemoryScope = SimpleScope | TaskAwareScope;
|
|
131
|
+
/**
|
|
132
|
+
* Type guard: is this a task-aware scope?
|
|
133
|
+
*/
|
|
134
|
+
declare function isTaskAwareScope(scope: MemoryScope): scope is TaskAwareScope;
|
|
135
|
+
/**
|
|
136
|
+
* Type guard: is this a simple scope?
|
|
137
|
+
*/
|
|
138
|
+
declare function isSimpleScope(scope: MemoryScope): scope is SimpleScope;
|
|
139
|
+
/**
|
|
140
|
+
* Compare two scopes for equality
|
|
141
|
+
* Handles both simple scopes (string comparison) and task-aware scopes (deep comparison)
|
|
142
|
+
*/
|
|
143
|
+
declare function scopeEquals(a: MemoryScope, b: MemoryScope): boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Check if a scope matches a filter scope
|
|
146
|
+
* More flexible than scopeEquals - supports partial matching for task scopes
|
|
147
|
+
*/
|
|
148
|
+
declare function scopeMatches(entryScope: MemoryScope, filterScope: MemoryScope): boolean;
|
|
149
|
+
/**
|
|
150
|
+
* Priority determines eviction order (lower priority evicted first)
|
|
151
|
+
*
|
|
152
|
+
* - critical: Never evicted (pinned, or actively in use)
|
|
153
|
+
* - high: Important data, evicted only when necessary
|
|
154
|
+
* - normal: Default priority
|
|
155
|
+
* - low: Candidate for eviction (stale data, completed task data)
|
|
156
|
+
*/
|
|
157
|
+
type MemoryPriority = 'critical' | 'high' | 'normal' | 'low';
|
|
158
|
+
/**
|
|
159
|
+
* Priority values for comparison (higher = more important, less likely to evict)
|
|
160
|
+
*/
|
|
161
|
+
declare const MEMORY_PRIORITY_VALUES: Record<MemoryPriority, number>;
|
|
162
|
+
/**
|
|
163
|
+
* Memory tier for hierarchical data management
|
|
164
|
+
*
|
|
165
|
+
* The tier system provides a structured approach to managing research/analysis data:
|
|
166
|
+
* - raw: Original data, low priority, first to be evicted
|
|
167
|
+
* - summary: Processed summaries, normal priority
|
|
168
|
+
* - findings: Final conclusions/insights, high priority, kept longest
|
|
169
|
+
*
|
|
170
|
+
* Workflow: raw → summary → findings (data gets more refined, priority increases)
|
|
171
|
+
*/
|
|
172
|
+
type MemoryTier = 'raw' | 'summary' | 'findings';
|
|
173
|
+
/**
|
|
174
|
+
* Context passed to priority calculator - varies by agent type
|
|
175
|
+
*/
|
|
176
|
+
interface PriorityContext {
|
|
177
|
+
/** For TaskAgent: map of taskId → current status */
|
|
178
|
+
taskStates?: Map<string, TaskStatusForMemory>;
|
|
179
|
+
/** For UniversalAgent: current mode */
|
|
180
|
+
mode?: 'interactive' | 'planning' | 'executing';
|
|
181
|
+
/** Custom context for extensions */
|
|
182
|
+
[key: string]: unknown;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Task status values for priority calculation
|
|
186
|
+
*/
|
|
187
|
+
type TaskStatusForMemory = 'pending' | 'in_progress' | 'completed' | 'failed' | 'skipped' | 'cancelled';
|
|
188
|
+
/**
|
|
189
|
+
* Check if a task status is terminal (task will not progress further)
|
|
190
|
+
*/
|
|
191
|
+
declare function isTerminalMemoryStatus(status: TaskStatusForMemory): boolean;
|
|
192
|
+
/**
|
|
193
|
+
* Priority calculator function type.
|
|
194
|
+
* Given an entry and optional context, returns the effective priority.
|
|
195
|
+
*/
|
|
196
|
+
type PriorityCalculator = (entry: MemoryEntry, context?: PriorityContext) => MemoryPriority;
|
|
197
|
+
/**
|
|
198
|
+
* Reason why an entry became stale
|
|
199
|
+
*/
|
|
200
|
+
type StaleReason = 'task_completed' | 'task_failed' | 'unused' | 'scope_cleared';
|
|
201
|
+
/**
|
|
202
|
+
* Information about a stale entry for LLM notification
|
|
203
|
+
*/
|
|
204
|
+
interface StaleEntryInfo {
|
|
205
|
+
key: string;
|
|
206
|
+
description: string;
|
|
207
|
+
reason: StaleReason;
|
|
208
|
+
previousPriority: MemoryPriority;
|
|
209
|
+
newPriority: MemoryPriority;
|
|
210
|
+
taskIds?: string[];
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Single memory entry stored in working memory
|
|
214
|
+
*/
|
|
215
|
+
interface MemoryEntry {
|
|
216
|
+
key: string;
|
|
217
|
+
description: string;
|
|
218
|
+
value: unknown;
|
|
219
|
+
sizeBytes: number;
|
|
220
|
+
scope: MemoryScope;
|
|
221
|
+
basePriority: MemoryPriority;
|
|
222
|
+
pinned: boolean;
|
|
223
|
+
createdAt: number;
|
|
224
|
+
lastAccessedAt: number;
|
|
225
|
+
accessCount: number;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Index entry (lightweight, always in context)
|
|
229
|
+
*/
|
|
230
|
+
interface MemoryIndexEntry {
|
|
231
|
+
key: string;
|
|
232
|
+
description: string;
|
|
233
|
+
size: string;
|
|
234
|
+
scope: MemoryScope;
|
|
235
|
+
effectivePriority: MemoryPriority;
|
|
236
|
+
pinned: boolean;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Full memory index with metadata
|
|
240
|
+
*/
|
|
241
|
+
interface MemoryIndex {
|
|
242
|
+
entries: MemoryIndexEntry[];
|
|
243
|
+
totalSizeBytes: number;
|
|
244
|
+
totalSizeHuman: string;
|
|
245
|
+
limitBytes: number;
|
|
246
|
+
limitHuman: string;
|
|
247
|
+
utilizationPercent: number;
|
|
248
|
+
/** Total entry count (before any truncation for display) */
|
|
249
|
+
totalEntryCount: number;
|
|
250
|
+
/** Number of entries omitted from display due to maxIndexEntries limit */
|
|
251
|
+
omittedCount: number;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Configuration for working memory
|
|
255
|
+
*/
|
|
256
|
+
interface WorkingMemoryConfig {
|
|
257
|
+
/** Max memory size in bytes. If not set, calculated from model context */
|
|
258
|
+
maxSizeBytes?: number;
|
|
259
|
+
/** Max number of entries in the memory index. Excess entries are auto-evicted via LRU. Default: 30 */
|
|
260
|
+
maxIndexEntries?: number;
|
|
261
|
+
/** Max description length */
|
|
262
|
+
descriptionMaxLength: number;
|
|
263
|
+
/** Percentage at which to warn agent */
|
|
264
|
+
softLimitPercent: number;
|
|
265
|
+
/** Percentage of model context to allocate to memory */
|
|
266
|
+
contextAllocationPercent: number;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Input for creating a memory entry
|
|
270
|
+
*/
|
|
271
|
+
interface MemoryEntryInput {
|
|
272
|
+
key: string;
|
|
273
|
+
description: string;
|
|
274
|
+
value: unknown;
|
|
275
|
+
/** Scope - defaults to 'session' for basic agents */
|
|
276
|
+
scope?: MemoryScope;
|
|
277
|
+
/** Base priority - may be overridden by dynamic calculation */
|
|
278
|
+
priority?: MemoryPriority;
|
|
279
|
+
/** If true, entry is never evicted */
|
|
280
|
+
pinned?: boolean;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Create a task-scoped memory entry input
|
|
284
|
+
*/
|
|
285
|
+
declare function forTasks(key: string, description: string, value: unknown, taskIds: string[], options?: {
|
|
286
|
+
priority?: MemoryPriority;
|
|
287
|
+
pinned?: boolean;
|
|
288
|
+
}): MemoryEntryInput;
|
|
289
|
+
/**
|
|
290
|
+
* Create a plan-scoped memory entry input
|
|
291
|
+
*/
|
|
292
|
+
declare function forPlan(key: string, description: string, value: unknown, options?: {
|
|
293
|
+
priority?: MemoryPriority;
|
|
294
|
+
pinned?: boolean;
|
|
295
|
+
}): MemoryEntryInput;
|
|
296
|
+
/**
|
|
297
|
+
* Default configuration values
|
|
298
|
+
*/
|
|
299
|
+
declare const DEFAULT_MEMORY_CONFIG: WorkingMemoryConfig;
|
|
300
|
+
/**
|
|
301
|
+
* Calculate the size of a value in bytes (JSON serialization)
|
|
302
|
+
* Uses Buffer.byteLength for accurate UTF-8 byte count
|
|
303
|
+
*/
|
|
304
|
+
declare function calculateEntrySize(value: unknown): number;
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Tool context interface - passed to tools during execution
|
|
308
|
+
*
|
|
309
|
+
* This is a SIMPLE interface. Tools receive only what they need:
|
|
310
|
+
* - agentId: For logging/tracing
|
|
311
|
+
* - taskId: For task-aware operations
|
|
312
|
+
* - memory: For storing/retrieving data
|
|
313
|
+
* - signal: For cancellation
|
|
314
|
+
*
|
|
315
|
+
* Plugins and context management are NOT exposed to tools.
|
|
316
|
+
* Tools should be self-contained and not depend on framework internals.
|
|
317
|
+
*/
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Limited memory access for tools
|
|
321
|
+
*
|
|
322
|
+
* This interface is designed to work with all agent types:
|
|
323
|
+
* - Basic agents: Use simple scopes ('session', 'persistent')
|
|
324
|
+
* - TaskAgent: Use task-aware scopes ({ type: 'task', taskIds: [...] })
|
|
325
|
+
* - UniversalAgent: Switches between simple and task-aware based on mode
|
|
326
|
+
*/
|
|
327
|
+
interface WorkingMemoryAccess {
|
|
328
|
+
get(key: string): Promise<unknown>;
|
|
329
|
+
/**
|
|
330
|
+
* Store a value in memory
|
|
331
|
+
*
|
|
332
|
+
* @param key - Unique key for the entry
|
|
333
|
+
* @param description - Short description (max 150 chars)
|
|
334
|
+
* @param value - Data to store
|
|
335
|
+
* @param options - Optional scope, priority, and pinning
|
|
336
|
+
*/
|
|
337
|
+
set(key: string, description: string, value: unknown, options?: {
|
|
338
|
+
/** Scope determines lifecycle - defaults to 'session' */
|
|
339
|
+
scope?: MemoryScope;
|
|
340
|
+
/** Base priority for eviction ordering */
|
|
341
|
+
priority?: MemoryPriority;
|
|
342
|
+
/** If true, entry is never evicted */
|
|
343
|
+
pinned?: boolean;
|
|
344
|
+
}): Promise<void>;
|
|
345
|
+
delete(key: string): Promise<void>;
|
|
346
|
+
has(key: string): Promise<boolean>;
|
|
347
|
+
/**
|
|
348
|
+
* List all memory entries
|
|
349
|
+
* Returns key, description, and computed priority info
|
|
350
|
+
*/
|
|
351
|
+
list(): Promise<Array<{
|
|
352
|
+
key: string;
|
|
353
|
+
description: string;
|
|
354
|
+
effectivePriority?: MemoryPriority;
|
|
355
|
+
pinned?: boolean;
|
|
356
|
+
}>>;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Context passed to tool execute function
|
|
360
|
+
*
|
|
361
|
+
* Simple and clean - only what tools actually need.
|
|
362
|
+
*/
|
|
363
|
+
interface ToolContext {
|
|
364
|
+
/** Agent ID (for logging/tracing) */
|
|
365
|
+
agentId?: string;
|
|
366
|
+
/** Task ID (if running in TaskAgent) */
|
|
367
|
+
taskId?: string;
|
|
368
|
+
/** User ID — auto-populated from Agent config (userId). Also settable manually via agent.tools.setToolContext(). */
|
|
369
|
+
userId?: string;
|
|
370
|
+
/** Account alias for multi-account OAuth — auto-populated from Agent config (accountId). Allows one user to auth multiple external accounts on the same connector (e.g., 'work', 'personal'). */
|
|
371
|
+
accountId?: string;
|
|
372
|
+
/** Auth identities this agent is scoped to (for identity-aware tool descriptions) */
|
|
373
|
+
identities?: AuthIdentity[];
|
|
374
|
+
/** Connector registry scoped to this agent's allowed connectors and userId */
|
|
375
|
+
connectorRegistry?: IConnectorRegistry;
|
|
376
|
+
/** Working memory access (if agent has memory feature enabled) */
|
|
377
|
+
memory?: WorkingMemoryAccess;
|
|
378
|
+
/** Abort signal for cancellation */
|
|
379
|
+
signal?: AbortSignal;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Tool entities with blocking/non-blocking execution support
|
|
384
|
+
*/
|
|
385
|
+
|
|
386
|
+
interface JSONSchema {
|
|
387
|
+
type: string;
|
|
388
|
+
properties?: Record<string, any>;
|
|
389
|
+
required?: string[];
|
|
390
|
+
[key: string]: any;
|
|
391
|
+
}
|
|
392
|
+
interface FunctionToolDefinition {
|
|
393
|
+
type: 'function';
|
|
394
|
+
function: {
|
|
395
|
+
name: string;
|
|
396
|
+
description?: string;
|
|
397
|
+
parameters?: JSONSchema;
|
|
398
|
+
strict?: boolean;
|
|
399
|
+
};
|
|
400
|
+
blocking?: boolean;
|
|
401
|
+
timeout?: number;
|
|
402
|
+
}
|
|
403
|
+
interface BuiltInTool {
|
|
404
|
+
type: 'web_search' | 'file_search' | 'computer_use' | 'code_interpreter';
|
|
405
|
+
blocking?: boolean;
|
|
406
|
+
}
|
|
407
|
+
type Tool = FunctionToolDefinition | BuiltInTool;
|
|
408
|
+
declare enum ToolCallState {
|
|
409
|
+
PENDING = "pending",// Tool call identified, not yet executed
|
|
410
|
+
EXECUTING = "executing",// Currently executing
|
|
411
|
+
COMPLETED = "completed",// Successfully completed
|
|
412
|
+
FAILED = "failed",// Execution failed
|
|
413
|
+
TIMEOUT = "timeout"
|
|
414
|
+
}
|
|
415
|
+
interface ToolCall {
|
|
416
|
+
id: string;
|
|
417
|
+
type: 'function';
|
|
418
|
+
function: {
|
|
419
|
+
name: string;
|
|
420
|
+
arguments: string;
|
|
421
|
+
};
|
|
422
|
+
blocking: boolean;
|
|
423
|
+
state: ToolCallState;
|
|
424
|
+
startTime?: Date;
|
|
425
|
+
endTime?: Date;
|
|
426
|
+
error?: string;
|
|
427
|
+
}
|
|
428
|
+
interface ToolResult {
|
|
429
|
+
tool_use_id: string;
|
|
430
|
+
tool_name?: string;
|
|
431
|
+
tool_args?: Record<string, unknown>;
|
|
432
|
+
content: any;
|
|
433
|
+
error?: string;
|
|
434
|
+
executionTime?: number;
|
|
435
|
+
state: ToolCallState;
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Tool execution context - tracks all tool calls in a generation
|
|
439
|
+
*/
|
|
440
|
+
interface ToolExecutionContext {
|
|
441
|
+
executionId: string;
|
|
442
|
+
toolCalls: Map<string, ToolCall>;
|
|
443
|
+
pendingNonBlocking: Set<string>;
|
|
444
|
+
completedResults: Map<string, ToolResult>;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Output handling hints for context management
|
|
448
|
+
*/
|
|
449
|
+
interface ToolOutputHints {
|
|
450
|
+
expectedSize?: 'small' | 'medium' | 'large' | 'variable';
|
|
451
|
+
summarize?: (output: unknown) => string;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Idempotency configuration for tool caching
|
|
455
|
+
*/
|
|
456
|
+
interface ToolIdempotency {
|
|
457
|
+
/**
|
|
458
|
+
* @deprecated Use 'cacheable' instead. Will be removed in a future version.
|
|
459
|
+
* If true, tool is naturally idempotent (e.g., read-only) and doesn't need caching.
|
|
460
|
+
* If false, tool results should be cached based on arguments.
|
|
461
|
+
*/
|
|
462
|
+
safe?: boolean;
|
|
463
|
+
/**
|
|
464
|
+
* If true, tool results can be cached based on arguments.
|
|
465
|
+
* Use this for tools that return deterministic results for the same inputs.
|
|
466
|
+
* Takes precedence over the deprecated 'safe' field.
|
|
467
|
+
* @default false
|
|
468
|
+
*/
|
|
469
|
+
cacheable?: boolean;
|
|
470
|
+
keyFn?: (args: Record<string, unknown>) => string;
|
|
471
|
+
ttlMs?: number;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Permission configuration for a tool
|
|
475
|
+
*
|
|
476
|
+
* Controls when approval is required for tool execution.
|
|
477
|
+
* Used by the ToolPermissionManager.
|
|
478
|
+
*/
|
|
479
|
+
interface ToolPermissionConfig {
|
|
480
|
+
/**
|
|
481
|
+
* When approval is required.
|
|
482
|
+
* - 'once' - Require approval for each call
|
|
483
|
+
* - 'session' - Approve once per session
|
|
484
|
+
* - 'always' - Auto-approve (no prompts)
|
|
485
|
+
* - 'never' - Always blocked
|
|
486
|
+
* @default 'once'
|
|
487
|
+
*/
|
|
488
|
+
scope?: 'once' | 'session' | 'always' | 'never';
|
|
489
|
+
/**
|
|
490
|
+
* Risk level classification.
|
|
491
|
+
* @default 'low'
|
|
492
|
+
*/
|
|
493
|
+
riskLevel?: 'low' | 'medium' | 'high' | 'critical';
|
|
494
|
+
/**
|
|
495
|
+
* Custom message shown in approval UI.
|
|
496
|
+
*/
|
|
497
|
+
approvalMessage?: string;
|
|
498
|
+
/**
|
|
499
|
+
* Argument names that should be highlighted as sensitive.
|
|
500
|
+
*/
|
|
501
|
+
sensitiveArgs?: string[];
|
|
502
|
+
/**
|
|
503
|
+
* TTL for session approvals (milliseconds).
|
|
504
|
+
*/
|
|
505
|
+
sessionTTLMs?: number;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* User-provided tool function
|
|
509
|
+
*/
|
|
510
|
+
interface ToolFunction<TArgs = any, TResult = any> {
|
|
511
|
+
definition: FunctionToolDefinition;
|
|
512
|
+
execute: (args: TArgs, context?: ToolContext) => Promise<TResult>;
|
|
513
|
+
idempotency?: ToolIdempotency;
|
|
514
|
+
output?: ToolOutputHints;
|
|
515
|
+
/** Permission settings for this tool. If not set, defaults are used. */
|
|
516
|
+
permission?: ToolPermissionConfig;
|
|
517
|
+
/**
|
|
518
|
+
* Dynamic description generator for the tool.
|
|
519
|
+
* If provided, this function is called when tool definitions are serialized for the LLM,
|
|
520
|
+
* allowing the description to reflect current state (e.g., available connectors).
|
|
521
|
+
*
|
|
522
|
+
* The returned string replaces definition.function.description when sending to LLM.
|
|
523
|
+
* The static description in definition.function.description serves as a fallback.
|
|
524
|
+
*
|
|
525
|
+
* @param context - Current ToolContext (includes userId, agentId, etc.)
|
|
526
|
+
* @returns The current tool description
|
|
527
|
+
*
|
|
528
|
+
* @example
|
|
529
|
+
* // Tool with dynamic connector list scoped to current user:
|
|
530
|
+
* descriptionFactory: (context) => {
|
|
531
|
+
* const connectors = getConnectorsForUser(context?.userId);
|
|
532
|
+
* return `Execute API calls. Available connectors: ${connectors.map(c => c.name).join(', ')}`;
|
|
533
|
+
* }
|
|
534
|
+
*/
|
|
535
|
+
descriptionFactory?: (context?: ToolContext) => string;
|
|
536
|
+
/**
|
|
537
|
+
* Returns a human-readable description of a tool call.
|
|
538
|
+
* Used for logging, UI display, and debugging.
|
|
539
|
+
*
|
|
540
|
+
* @param args - The arguments passed to the tool
|
|
541
|
+
* @returns A concise description (e.g., "reading /path/to/file.ts")
|
|
542
|
+
*
|
|
543
|
+
* If not implemented, use `defaultDescribeCall()` as a fallback.
|
|
544
|
+
*
|
|
545
|
+
* @example
|
|
546
|
+
* // For read_file tool:
|
|
547
|
+
* describeCall: (args) => args.file_path
|
|
548
|
+
*
|
|
549
|
+
* @example
|
|
550
|
+
* // For bash tool:
|
|
551
|
+
* describeCall: (args) => args.command.length > 50
|
|
552
|
+
* ? args.command.slice(0, 47) + '...'
|
|
553
|
+
* : args.command
|
|
554
|
+
*/
|
|
555
|
+
describeCall?: (args: TArgs) => string;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Default implementation for describeCall.
|
|
559
|
+
* Shows the first meaningful argument value.
|
|
560
|
+
*
|
|
561
|
+
* @param args - Tool arguments object
|
|
562
|
+
* @param maxLength - Maximum length before truncation (default: 60)
|
|
563
|
+
* @returns Human-readable description
|
|
564
|
+
*
|
|
565
|
+
* @example
|
|
566
|
+
* defaultDescribeCall({ file_path: '/path/to/file.ts' })
|
|
567
|
+
* // Returns: '/path/to/file.ts'
|
|
568
|
+
*
|
|
569
|
+
* @example
|
|
570
|
+
* defaultDescribeCall({ query: 'search term', limit: 10 })
|
|
571
|
+
* // Returns: 'search term'
|
|
572
|
+
*/
|
|
573
|
+
declare function defaultDescribeCall(args: Record<string, unknown>, maxLength?: number): string;
|
|
574
|
+
/**
|
|
575
|
+
* Get a human-readable description of a tool call.
|
|
576
|
+
* Uses the tool's describeCall method if available, otherwise falls back to default.
|
|
577
|
+
*
|
|
578
|
+
* @param tool - The tool function
|
|
579
|
+
* @param args - The arguments passed to the tool
|
|
580
|
+
* @returns Human-readable description
|
|
581
|
+
*/
|
|
582
|
+
declare function getToolCallDescription<TArgs>(tool: ToolFunction<TArgs>, args: TArgs): string;
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* IContextStorage - Storage interface for AgentContext persistence
|
|
586
|
+
*
|
|
587
|
+
* Provides persistence operations for AgentContext sessions.
|
|
588
|
+
* Implementations can use filesystem, database, cloud storage, etc.
|
|
589
|
+
*
|
|
590
|
+
* This follows Clean Architecture - the interface is in domain layer,
|
|
591
|
+
* implementations are in infrastructure layer.
|
|
592
|
+
*/
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Serialized context state for persistence.
|
|
596
|
+
* This is the canonical definition - core layer re-exports this type.
|
|
597
|
+
*/
|
|
598
|
+
interface SerializedContextState {
|
|
599
|
+
/** Conversation history */
|
|
600
|
+
conversation: InputItem[];
|
|
601
|
+
/** Plugin states (keyed by plugin name) */
|
|
602
|
+
pluginStates: Record<string, unknown>;
|
|
603
|
+
/** System prompt */
|
|
604
|
+
systemPrompt?: string;
|
|
605
|
+
/** Metadata */
|
|
606
|
+
metadata: {
|
|
607
|
+
savedAt: number;
|
|
608
|
+
agentId?: string;
|
|
609
|
+
userId?: string;
|
|
610
|
+
model: string;
|
|
611
|
+
};
|
|
612
|
+
/** Agent-specific state (for TaskAgent, UniversalAgent, etc.) */
|
|
613
|
+
agentState?: Record<string, unknown>;
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Session summary for listing (lightweight, no full state)
|
|
617
|
+
*/
|
|
618
|
+
interface ContextSessionSummary {
|
|
619
|
+
/** Session identifier */
|
|
620
|
+
sessionId: string;
|
|
621
|
+
/** When the session was created */
|
|
622
|
+
createdAt: Date;
|
|
623
|
+
/** When the session was last saved */
|
|
624
|
+
lastSavedAt: Date;
|
|
625
|
+
/** Number of messages in history */
|
|
626
|
+
messageCount: number;
|
|
627
|
+
/** Number of memory entries */
|
|
628
|
+
memoryEntryCount: number;
|
|
629
|
+
/** Optional metadata */
|
|
630
|
+
metadata?: ContextSessionMetadata;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Session metadata (stored with session)
|
|
634
|
+
*/
|
|
635
|
+
interface ContextSessionMetadata {
|
|
636
|
+
/** Human-readable title */
|
|
637
|
+
title?: string;
|
|
638
|
+
/** Auto-generated or user-provided description */
|
|
639
|
+
description?: string;
|
|
640
|
+
/** Tags for filtering */
|
|
641
|
+
tags?: string[];
|
|
642
|
+
/** Custom key-value data */
|
|
643
|
+
[key: string]: unknown;
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Full session state wrapper (includes metadata)
|
|
647
|
+
*/
|
|
648
|
+
interface StoredContextSession {
|
|
649
|
+
/** Format version for migration support */
|
|
650
|
+
version: number;
|
|
651
|
+
/** Session identifier */
|
|
652
|
+
sessionId: string;
|
|
653
|
+
/** When the session was created */
|
|
654
|
+
createdAt: string;
|
|
655
|
+
/** When the session was last saved */
|
|
656
|
+
lastSavedAt: string;
|
|
657
|
+
/** The serialized AgentContext state */
|
|
658
|
+
state: SerializedContextState;
|
|
659
|
+
/** Session metadata */
|
|
660
|
+
metadata: ContextSessionMetadata;
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Current format version for stored sessions
|
|
664
|
+
*/
|
|
665
|
+
declare const CONTEXT_SESSION_FORMAT_VERSION = 1;
|
|
666
|
+
/**
|
|
667
|
+
* Storage interface for AgentContext persistence
|
|
668
|
+
*
|
|
669
|
+
* Implementations:
|
|
670
|
+
* - FileContextStorage: File-based storage at ~/.oneringai/agents/<agentId>/sessions/
|
|
671
|
+
* - (Future) RedisContextStorage, PostgresContextStorage, S3ContextStorage, etc.
|
|
672
|
+
*/
|
|
673
|
+
interface IContextStorage {
|
|
674
|
+
/**
|
|
675
|
+
* Save context state to a session
|
|
676
|
+
*
|
|
677
|
+
* @param sessionId - Unique session identifier
|
|
678
|
+
* @param state - Serialized AgentContext state
|
|
679
|
+
* @param metadata - Optional session metadata
|
|
680
|
+
*/
|
|
681
|
+
save(sessionId: string, state: SerializedContextState, metadata?: ContextSessionMetadata): Promise<void>;
|
|
682
|
+
/**
|
|
683
|
+
* Load context state from a session
|
|
684
|
+
*
|
|
685
|
+
* @param sessionId - Session identifier to load
|
|
686
|
+
* @returns The stored session, or null if not found
|
|
687
|
+
*/
|
|
688
|
+
load(sessionId: string): Promise<StoredContextSession | null>;
|
|
689
|
+
/**
|
|
690
|
+
* Delete a session
|
|
691
|
+
*
|
|
692
|
+
* @param sessionId - Session identifier to delete
|
|
693
|
+
*/
|
|
694
|
+
delete(sessionId: string): Promise<void>;
|
|
695
|
+
/**
|
|
696
|
+
* Check if a session exists
|
|
697
|
+
*
|
|
698
|
+
* @param sessionId - Session identifier to check
|
|
699
|
+
*/
|
|
700
|
+
exists(sessionId: string): Promise<boolean>;
|
|
701
|
+
/**
|
|
702
|
+
* List all sessions (summaries only, not full state)
|
|
703
|
+
*
|
|
704
|
+
* @param options - Optional filtering and pagination
|
|
705
|
+
* @returns Array of session summaries, sorted by lastSavedAt descending
|
|
706
|
+
*/
|
|
707
|
+
list(options?: ContextStorageListOptions): Promise<ContextSessionSummary[]>;
|
|
708
|
+
/**
|
|
709
|
+
* Update session metadata without loading full state
|
|
710
|
+
*
|
|
711
|
+
* @param sessionId - Session identifier
|
|
712
|
+
* @param metadata - Metadata to merge (existing keys preserved unless overwritten)
|
|
713
|
+
*/
|
|
714
|
+
updateMetadata?(sessionId: string, metadata: Partial<ContextSessionMetadata>): Promise<void>;
|
|
715
|
+
/**
|
|
716
|
+
* Get the storage path (for display/debugging)
|
|
717
|
+
* @deprecated Use getLocation() instead - getPath() assumes filesystem storage
|
|
718
|
+
*/
|
|
719
|
+
getPath(): string;
|
|
720
|
+
/**
|
|
721
|
+
* Get a human-readable storage location string (for display/debugging).
|
|
722
|
+
* Examples: file path, MongoDB URI, Redis key prefix, S3 bucket, etc.
|
|
723
|
+
* Falls back to getPath() if not implemented.
|
|
724
|
+
*/
|
|
725
|
+
getLocation?(): string;
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Options for listing sessions
|
|
729
|
+
*/
|
|
730
|
+
interface ContextStorageListOptions {
|
|
731
|
+
/** Filter by tags (any match) */
|
|
732
|
+
tags?: string[];
|
|
733
|
+
/** Filter by creation date range */
|
|
734
|
+
createdAfter?: Date;
|
|
735
|
+
createdBefore?: Date;
|
|
736
|
+
/** Filter by last saved date range */
|
|
737
|
+
savedAfter?: Date;
|
|
738
|
+
savedBefore?: Date;
|
|
739
|
+
/** Maximum number of results */
|
|
740
|
+
limit?: number;
|
|
741
|
+
/** Offset for pagination */
|
|
742
|
+
offset?: number;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* ToolCatalogRegistry - Static Global Registry for Tool Categories
|
|
747
|
+
*
|
|
748
|
+
* The single source of truth for all tool categories and their tools.
|
|
749
|
+
* Library users register their own categories and tools at app startup.
|
|
750
|
+
*
|
|
751
|
+
* Built-in tools are auto-registered from registry.generated.ts on first access.
|
|
752
|
+
*
|
|
753
|
+
* @example
|
|
754
|
+
* ```typescript
|
|
755
|
+
* // Register custom category
|
|
756
|
+
* ToolCatalogRegistry.registerCategory({
|
|
757
|
+
* name: 'knowledge',
|
|
758
|
+
* displayName: 'Knowledge Graph',
|
|
759
|
+
* description: 'Search entities, get facts, manage references',
|
|
760
|
+
* });
|
|
761
|
+
*
|
|
762
|
+
* // Register tools in category
|
|
763
|
+
* ToolCatalogRegistry.registerTools('knowledge', [
|
|
764
|
+
* { name: 'entity_search', displayName: 'Entity Search', description: 'Search people/orgs', tool: entitySearch, safeByDefault: true },
|
|
765
|
+
* ]);
|
|
766
|
+
*
|
|
767
|
+
* // Query
|
|
768
|
+
* const categories = ToolCatalogRegistry.getCategories();
|
|
769
|
+
* const tools = ToolCatalogRegistry.getToolsInCategory('knowledge');
|
|
770
|
+
* const found = ToolCatalogRegistry.findTool('entity_search');
|
|
771
|
+
* ```
|
|
772
|
+
*/
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Definition of a tool category in the catalog.
|
|
776
|
+
*/
|
|
777
|
+
interface ToolCategoryDefinition {
|
|
778
|
+
/** Unique category name (e.g., 'filesystem', 'knowledge', 'connector:github') */
|
|
779
|
+
name: string;
|
|
780
|
+
/** Human-readable display name (e.g., 'File System') */
|
|
781
|
+
displayName: string;
|
|
782
|
+
/** Description shown in catalog metatool display */
|
|
783
|
+
description: string;
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* A single tool entry in the catalog.
|
|
787
|
+
*/
|
|
788
|
+
interface CatalogToolEntry {
|
|
789
|
+
/** The actual tool function (optional when createTool factory is provided) */
|
|
790
|
+
tool?: ToolFunction;
|
|
791
|
+
/** Tool name (matches definition.function.name) */
|
|
792
|
+
name: string;
|
|
793
|
+
/** Human-readable display name */
|
|
794
|
+
displayName: string;
|
|
795
|
+
/** Brief description */
|
|
796
|
+
description: string;
|
|
797
|
+
/** Whether this tool is safe to execute without user approval */
|
|
798
|
+
safeByDefault: boolean;
|
|
799
|
+
/** Whether this tool requires a connector to function */
|
|
800
|
+
requiresConnector?: boolean;
|
|
801
|
+
/** Factory for runtime tool creation (e.g., browser tools needing context) */
|
|
802
|
+
createTool?: (ctx: Record<string, unknown>) => ToolFunction;
|
|
803
|
+
/** Source identifier (e.g., 'oneringai', 'hosea', 'custom') */
|
|
804
|
+
source?: string;
|
|
805
|
+
/** Connector name (for connector-originated tools) */
|
|
806
|
+
connectorName?: string;
|
|
807
|
+
/** Service type (e.g., 'github', 'slack') */
|
|
808
|
+
serviceType?: string;
|
|
809
|
+
/** Supported connector service types */
|
|
810
|
+
connectorServiceTypes?: string[];
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Entry format from the generated tool registry (registry.generated.ts).
|
|
814
|
+
* Used by initializeFromRegistry() and registerFromToolRegistry().
|
|
815
|
+
*/
|
|
816
|
+
interface ToolRegistryEntry {
|
|
817
|
+
name: string;
|
|
818
|
+
displayName: string;
|
|
819
|
+
category: string;
|
|
820
|
+
description: string;
|
|
821
|
+
tool: ToolFunction;
|
|
822
|
+
safeByDefault: boolean;
|
|
823
|
+
requiresConnector?: boolean;
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Scope for filtering which categories are visible/allowed.
|
|
827
|
+
*
|
|
828
|
+
* - `string[]` — shorthand allowlist (only these categories)
|
|
829
|
+
* - `{ include: string[] }` — explicit allowlist
|
|
830
|
+
* - `{ exclude: string[] }` — blocklist (all except these)
|
|
831
|
+
* - `undefined` — all categories allowed
|
|
832
|
+
*/
|
|
833
|
+
type ToolCategoryScope = string[] | {
|
|
834
|
+
include: string[];
|
|
835
|
+
} | {
|
|
836
|
+
exclude: string[];
|
|
837
|
+
};
|
|
838
|
+
/**
|
|
839
|
+
* Connector category metadata returned by discoverConnectorCategories().
|
|
840
|
+
*/
|
|
841
|
+
interface ConnectorCategoryInfo {
|
|
842
|
+
/** Category name in 'connector:<name>' format */
|
|
843
|
+
name: string;
|
|
844
|
+
/** Human-readable display name */
|
|
845
|
+
displayName: string;
|
|
846
|
+
/** Description */
|
|
847
|
+
description: string;
|
|
848
|
+
/** Number of tools */
|
|
849
|
+
toolCount: number;
|
|
850
|
+
/** Resolved tools */
|
|
851
|
+
tools: ToolFunction[];
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Static global registry for tool categories and their tools.
|
|
855
|
+
*
|
|
856
|
+
* Like Connector and StorageRegistry, this is a static class that acts
|
|
857
|
+
* as a single source of truth. App code registers categories at startup,
|
|
858
|
+
* and plugins/agents query them at runtime.
|
|
859
|
+
*/
|
|
860
|
+
declare class ToolCatalogRegistry {
|
|
861
|
+
/** Category definitions: name → definition */
|
|
862
|
+
private static _categories;
|
|
863
|
+
/** Tools per category: category name → tool entries */
|
|
864
|
+
private static _tools;
|
|
865
|
+
/** Whether built-in tools have been registered */
|
|
866
|
+
private static _initialized;
|
|
867
|
+
/** Lazy-loaded ConnectorTools module. null = not attempted, false = failed */
|
|
868
|
+
private static _connectorToolsModule;
|
|
869
|
+
private static readonly BUILTIN_DESCRIPTIONS;
|
|
870
|
+
/**
|
|
871
|
+
* Convert a hyphenated or plain name to a display name.
|
|
872
|
+
* E.g., 'custom-tools' → 'Custom Tools', 'filesystem' → 'Filesystem'
|
|
873
|
+
*/
|
|
874
|
+
static toDisplayName(name: string): string;
|
|
875
|
+
/**
|
|
876
|
+
* Parse a connector category name, returning the connector name or null.
|
|
877
|
+
* E.g., 'connector:github' → 'github', 'filesystem' → null
|
|
878
|
+
*/
|
|
879
|
+
static parseConnectorCategory(category: string): string | null;
|
|
880
|
+
/**
|
|
881
|
+
* Get the ConnectorTools module (lazy-loaded, cached).
|
|
882
|
+
* Returns null if ConnectorTools is not available.
|
|
883
|
+
* Uses false sentinel to prevent retrying after first failure.
|
|
884
|
+
*/
|
|
885
|
+
static getConnectorToolsModule(): {
|
|
886
|
+
ConnectorTools: any;
|
|
887
|
+
} | null;
|
|
888
|
+
/**
|
|
889
|
+
* Register a tool category.
|
|
890
|
+
* If the category already exists, updates its metadata.
|
|
891
|
+
* @throws Error if name is empty or whitespace
|
|
892
|
+
*/
|
|
893
|
+
static registerCategory(def: ToolCategoryDefinition): void;
|
|
894
|
+
/**
|
|
895
|
+
* Register multiple tools in a category.
|
|
896
|
+
* The category is auto-created if it doesn't exist (with a generic description).
|
|
897
|
+
* @throws Error if category name is empty or whitespace
|
|
898
|
+
*/
|
|
899
|
+
static registerTools(category: string, tools: CatalogToolEntry[]): void;
|
|
900
|
+
/**
|
|
901
|
+
* Register a single tool in a category.
|
|
902
|
+
*/
|
|
903
|
+
static registerTool(category: string, tool: CatalogToolEntry): void;
|
|
904
|
+
/**
|
|
905
|
+
* Unregister a category and all its tools.
|
|
906
|
+
*/
|
|
907
|
+
static unregisterCategory(category: string): boolean;
|
|
908
|
+
/**
|
|
909
|
+
* Unregister a single tool from a category.
|
|
910
|
+
*/
|
|
911
|
+
static unregisterTool(category: string, toolName: string): boolean;
|
|
912
|
+
/**
|
|
913
|
+
* Get all registered categories.
|
|
914
|
+
*/
|
|
915
|
+
static getCategories(): ToolCategoryDefinition[];
|
|
916
|
+
/**
|
|
917
|
+
* Get a single category by name.
|
|
918
|
+
*/
|
|
919
|
+
static getCategory(name: string): ToolCategoryDefinition | undefined;
|
|
920
|
+
/**
|
|
921
|
+
* Check if a category exists.
|
|
922
|
+
*/
|
|
923
|
+
static hasCategory(name: string): boolean;
|
|
924
|
+
/**
|
|
925
|
+
* Get all tools in a category.
|
|
926
|
+
*/
|
|
927
|
+
static getToolsInCategory(category: string): CatalogToolEntry[];
|
|
928
|
+
/**
|
|
929
|
+
* Get all catalog tools across all categories.
|
|
930
|
+
*/
|
|
931
|
+
static getAllCatalogTools(): CatalogToolEntry[];
|
|
932
|
+
/**
|
|
933
|
+
* Find a tool by name across all categories.
|
|
934
|
+
*/
|
|
935
|
+
static findTool(name: string): {
|
|
936
|
+
category: string;
|
|
937
|
+
entry: CatalogToolEntry;
|
|
938
|
+
} | undefined;
|
|
939
|
+
/**
|
|
940
|
+
* Filter categories by scope.
|
|
941
|
+
*/
|
|
942
|
+
static filterCategories(scope?: ToolCategoryScope): ToolCategoryDefinition[];
|
|
943
|
+
/**
|
|
944
|
+
* Check if a category is allowed by a scope.
|
|
945
|
+
*/
|
|
946
|
+
static isCategoryAllowed(name: string, scope?: ToolCategoryScope): boolean;
|
|
947
|
+
/**
|
|
948
|
+
* Discover all connector categories with their tools.
|
|
949
|
+
* Calls ConnectorTools.discoverAll() and filters by scope/identities.
|
|
950
|
+
*
|
|
951
|
+
* @param options - Optional filtering
|
|
952
|
+
* @returns Array of connector category info
|
|
953
|
+
*/
|
|
954
|
+
static discoverConnectorCategories(options?: {
|
|
955
|
+
scope?: ToolCategoryScope;
|
|
956
|
+
identities?: Array<{
|
|
957
|
+
connector: string;
|
|
958
|
+
}>;
|
|
959
|
+
}): ConnectorCategoryInfo[];
|
|
960
|
+
/**
|
|
961
|
+
* Resolve tools for a specific connector category.
|
|
962
|
+
*
|
|
963
|
+
* @param category - Category name in 'connector:<name>' format
|
|
964
|
+
* @returns Array of resolved tools with names
|
|
965
|
+
*/
|
|
966
|
+
static resolveConnectorCategoryTools(category: string): Array<{
|
|
967
|
+
tool: ToolFunction;
|
|
968
|
+
name: string;
|
|
969
|
+
}>;
|
|
970
|
+
/**
|
|
971
|
+
* Resolve tool names to ToolFunction[].
|
|
972
|
+
*
|
|
973
|
+
* Searches registered categories and (optionally) connector tools.
|
|
974
|
+
* Used by app-level executors (e.g., V25's OneRingAgentExecutor).
|
|
975
|
+
*
|
|
976
|
+
* @param toolNames - Array of tool names to resolve
|
|
977
|
+
* @param options - Resolution options
|
|
978
|
+
* @returns Resolved tool functions (skips unresolvable names with warning)
|
|
979
|
+
*/
|
|
980
|
+
static resolveTools(toolNames: string[], options?: {
|
|
981
|
+
includeConnectors?: boolean;
|
|
982
|
+
userId?: string;
|
|
983
|
+
context?: Record<string, unknown>;
|
|
984
|
+
}): ToolFunction[];
|
|
985
|
+
/**
|
|
986
|
+
* Resolve tools grouped by connector name.
|
|
987
|
+
*
|
|
988
|
+
* Tools with a `connectorName` go into `byConnector`; all others go into `plain`.
|
|
989
|
+
* Supports factory-based tool creation via `createTool` when context is provided.
|
|
990
|
+
*
|
|
991
|
+
* @param toolNames - Array of tool names to resolve
|
|
992
|
+
* @param context - Optional context passed to createTool factories
|
|
993
|
+
* @param options - Resolution options
|
|
994
|
+
* @returns Grouped tools: plain + byConnector map
|
|
995
|
+
*/
|
|
996
|
+
static resolveToolsGrouped(toolNames: string[], context?: Record<string, unknown>, options?: {
|
|
997
|
+
includeConnectors?: boolean;
|
|
998
|
+
}): {
|
|
999
|
+
plain: ToolFunction[];
|
|
1000
|
+
byConnector: Map<string, ToolFunction[]>;
|
|
1001
|
+
};
|
|
1002
|
+
/**
|
|
1003
|
+
* Resolve a tool from a CatalogToolEntry, using factory if available.
|
|
1004
|
+
* Returns null if neither tool nor createTool is available.
|
|
1005
|
+
*/
|
|
1006
|
+
private static resolveEntryTool;
|
|
1007
|
+
/**
|
|
1008
|
+
* Search connector tools by name (uses lazy accessor).
|
|
1009
|
+
*/
|
|
1010
|
+
private static findConnectorTool;
|
|
1011
|
+
/**
|
|
1012
|
+
* Ensure built-in tools from registry.generated.ts are registered.
|
|
1013
|
+
* Called lazily on first query.
|
|
1014
|
+
*
|
|
1015
|
+
* In ESM environments, call `initializeFromRegistry(toolRegistry)` explicitly
|
|
1016
|
+
* from your app startup instead of relying on auto-initialization.
|
|
1017
|
+
*/
|
|
1018
|
+
static ensureInitialized(): void;
|
|
1019
|
+
/**
|
|
1020
|
+
* Explicitly initialize from the generated tool registry.
|
|
1021
|
+
* Call this at app startup in ESM environments where lazy require() doesn't work.
|
|
1022
|
+
*
|
|
1023
|
+
* @example
|
|
1024
|
+
* ```typescript
|
|
1025
|
+
* import { toolRegistry } from './tools/registry.generated.js';
|
|
1026
|
+
* ToolCatalogRegistry.initializeFromRegistry(toolRegistry);
|
|
1027
|
+
* ```
|
|
1028
|
+
*/
|
|
1029
|
+
static initializeFromRegistry(registry: ToolRegistryEntry[]): void;
|
|
1030
|
+
/**
|
|
1031
|
+
* Internal: register tools from a tool registry array.
|
|
1032
|
+
*/
|
|
1033
|
+
private static registerFromToolRegistry;
|
|
1034
|
+
/**
|
|
1035
|
+
* Reset the registry. Primarily for testing.
|
|
1036
|
+
*/
|
|
1037
|
+
static reset(): void;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* AgentContextNextGen - Type Definitions
|
|
1042
|
+
*
|
|
1043
|
+
* Clean, minimal type definitions for the next-generation context manager.
|
|
1044
|
+
*/
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* A single auth identity: connector + optional account alias.
|
|
1048
|
+
*
|
|
1049
|
+
* Used to scope agents to specific OAuth accounts. When `accountId` is set,
|
|
1050
|
+
* the identity represents a specific multi-account OAuth session (e.g., 'work'
|
|
1051
|
+
* or 'personal' Microsoft account). When omitted, uses the connector's default account.
|
|
1052
|
+
*/
|
|
1053
|
+
interface AuthIdentity {
|
|
1054
|
+
/** Name of the registered connector */
|
|
1055
|
+
connector: string;
|
|
1056
|
+
/** Optional account alias for multi-account OAuth (e.g., 'work', 'personal') */
|
|
1057
|
+
accountId?: string;
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Token estimator interface - used for conversation and input estimation
|
|
1061
|
+
* Plugins handle their own token estimation internally.
|
|
1062
|
+
*/
|
|
1063
|
+
interface ITokenEstimator {
|
|
1064
|
+
/** Estimate tokens for a string */
|
|
1065
|
+
estimateTokens(text: string): number;
|
|
1066
|
+
/** Estimate tokens for arbitrary data (will be JSON stringified) */
|
|
1067
|
+
estimateDataTokens(data: unknown): number;
|
|
1068
|
+
/**
|
|
1069
|
+
* Estimate tokens for an image. Provider-specific implementations can override.
|
|
1070
|
+
*
|
|
1071
|
+
* Default heuristic (matches OpenAI's image token pricing):
|
|
1072
|
+
* - detail='low': 85 tokens
|
|
1073
|
+
* - detail='high' with known dimensions: 85 + 170 * ceil(w/512) * ceil(h/512)
|
|
1074
|
+
* - Unknown dimensions: ~1000 tokens (conservative default)
|
|
1075
|
+
*
|
|
1076
|
+
* @param width - Image width in pixels (if known)
|
|
1077
|
+
* @param height - Image height in pixels (if known)
|
|
1078
|
+
* @param detail - Image detail level: 'low', 'high', or 'auto' (default 'auto')
|
|
1079
|
+
*/
|
|
1080
|
+
estimateImageTokens?(width?: number, height?: number, detail?: string): number;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Context plugin interface for NextGen context management.
|
|
1084
|
+
*
|
|
1085
|
+
* ## Implementing a Custom Plugin
|
|
1086
|
+
*
|
|
1087
|
+
* 1. **Extend BasePluginNextGen** - provides token caching helpers
|
|
1088
|
+
* 2. **Implement getInstructions()** - return LLM usage guide (static, cached)
|
|
1089
|
+
* 3. **Implement getContent()** - return formatted content (Markdown with `##` header)
|
|
1090
|
+
* 4. **Call updateTokenCache()** - after any state change that affects content
|
|
1091
|
+
* 5. **Implement getTools()** - return tools with `<plugin_prefix>_*` naming
|
|
1092
|
+
*
|
|
1093
|
+
* ## Plugin Contributions
|
|
1094
|
+
*
|
|
1095
|
+
* Plugins provide three types of content to the system message:
|
|
1096
|
+
* 1. **Instructions** - static usage guide for the LLM (NEVER compacted)
|
|
1097
|
+
* 2. **Content** - dynamic plugin data/state (may be compacted)
|
|
1098
|
+
* 3. **Tools** - registered with ToolManager (NEVER compacted)
|
|
1099
|
+
*
|
|
1100
|
+
* ## Token Cache Lifecycle
|
|
1101
|
+
*
|
|
1102
|
+
* Plugins must track their own token size for budget calculation. The pattern:
|
|
1103
|
+
*
|
|
1104
|
+
* ```typescript
|
|
1105
|
+
* // When state changes:
|
|
1106
|
+
* this._entries.set(key, value);
|
|
1107
|
+
* this.invalidateTokenCache(); // Clear cached size
|
|
1108
|
+
*
|
|
1109
|
+
* // In getContent():
|
|
1110
|
+
* const content = this.formatContent();
|
|
1111
|
+
* this.updateTokenCache(this.estimator.estimateTokens(content)); // Update cache
|
|
1112
|
+
* return content;
|
|
1113
|
+
* ```
|
|
1114
|
+
*
|
|
1115
|
+
* ## Content Format
|
|
1116
|
+
*
|
|
1117
|
+
* `getContent()` should return Markdown with a descriptive header:
|
|
1118
|
+
*
|
|
1119
|
+
* ```markdown
|
|
1120
|
+
* ## Plugin Display Name (optional stats)
|
|
1121
|
+
*
|
|
1122
|
+
* Formatted content here...
|
|
1123
|
+
* - Entry 1: value
|
|
1124
|
+
* - Entry 2: value
|
|
1125
|
+
* ```
|
|
1126
|
+
*
|
|
1127
|
+
* Built-in plugins use these headers:
|
|
1128
|
+
* - WorkingMemory: `## Working Memory (N entries)`
|
|
1129
|
+
* - InContextMemory: `## Live Context (N entries)`
|
|
1130
|
+
* - PersistentInstructions: No header (user's raw instructions)
|
|
1131
|
+
*
|
|
1132
|
+
* ## Tool Naming Convention
|
|
1133
|
+
*
|
|
1134
|
+
* Use a consistent prefix based on plugin name:
|
|
1135
|
+
* - `working_memory` plugin → `memory_store`, `memory_retrieve`, `memory_delete`, `memory_list`
|
|
1136
|
+
* - `in_context_memory` plugin → `context_set`, `context_delete`, `context_list`
|
|
1137
|
+
* - `persistent_instructions` plugin → `instructions_set`, `instructions_remove`, `instructions_list`, `instructions_clear`
|
|
1138
|
+
*
|
|
1139
|
+
* ## State Serialization
|
|
1140
|
+
*
|
|
1141
|
+
* `getState()` and `restoreState()` are **synchronous** for simplicity.
|
|
1142
|
+
* If your plugin has async data, consider:
|
|
1143
|
+
* - Storing only references/keys in state
|
|
1144
|
+
* - Using a separate async initialization method
|
|
1145
|
+
*
|
|
1146
|
+
* @example
|
|
1147
|
+
* ```typescript
|
|
1148
|
+
* class MyPlugin extends BasePluginNextGen {
|
|
1149
|
+
* readonly name = 'my_plugin';
|
|
1150
|
+
* private _data = new Map<string, string>();
|
|
1151
|
+
*
|
|
1152
|
+
* getInstructions(): string {
|
|
1153
|
+
* return '## My Plugin\n\nUse my_plugin_set to store data...';
|
|
1154
|
+
* }
|
|
1155
|
+
*
|
|
1156
|
+
* async getContent(): Promise<string | null> {
|
|
1157
|
+
* if (this._data.size === 0) return null;
|
|
1158
|
+
* const lines = [...this._data].map(([k, v]) => `- ${k}: ${v}`);
|
|
1159
|
+
* const content = `## My Plugin (${this._data.size} entries)\n\n${lines.join('\n')}`;
|
|
1160
|
+
* this.updateTokenCache(this.estimator.estimateTokens(content));
|
|
1161
|
+
* return content;
|
|
1162
|
+
* }
|
|
1163
|
+
*
|
|
1164
|
+
* getTools(): ToolFunction[] {
|
|
1165
|
+
* return [myPluginSetTool, myPluginGetTool];
|
|
1166
|
+
* }
|
|
1167
|
+
*
|
|
1168
|
+
* getState(): unknown {
|
|
1169
|
+
* return { data: Object.fromEntries(this._data) };
|
|
1170
|
+
* }
|
|
1171
|
+
*
|
|
1172
|
+
* restoreState(state: unknown): void {
|
|
1173
|
+
* const s = state as { data: Record<string, string> };
|
|
1174
|
+
* this._data = new Map(Object.entries(s.data || {}));
|
|
1175
|
+
* this.invalidateTokenCache();
|
|
1176
|
+
* }
|
|
1177
|
+
* }
|
|
1178
|
+
* ```
|
|
1179
|
+
*/
|
|
1180
|
+
interface IContextPluginNextGen {
|
|
1181
|
+
/** Unique plugin name (used for lookup and tool prefixing) */
|
|
1182
|
+
readonly name: string;
|
|
1183
|
+
/**
|
|
1184
|
+
* Get usage instructions for the LLM.
|
|
1185
|
+
*
|
|
1186
|
+
* Returns static text explaining how to use this plugin's tools
|
|
1187
|
+
* and data. This is placed in the system message and is NEVER
|
|
1188
|
+
* compacted - it persists throughout the conversation.
|
|
1189
|
+
*
|
|
1190
|
+
* Instructions should include:
|
|
1191
|
+
* - What the plugin does
|
|
1192
|
+
* - How to use available tools
|
|
1193
|
+
* - Best practices and conventions
|
|
1194
|
+
*
|
|
1195
|
+
* @returns Instructions string or null if no instructions needed
|
|
1196
|
+
*
|
|
1197
|
+
* @example
|
|
1198
|
+
* ```typescript
|
|
1199
|
+
* getInstructions(): string {
|
|
1200
|
+
* return `## Working Memory
|
|
1201
|
+
*
|
|
1202
|
+
* Use memory_store to save important data for later retrieval.
|
|
1203
|
+
* Use memory_retrieve to recall previously stored data.
|
|
1204
|
+
*
|
|
1205
|
+
* Best practices:
|
|
1206
|
+
* - Use descriptive keys like 'user_preferences' not 'data1'
|
|
1207
|
+
* - Store intermediate results that may be needed later`;
|
|
1208
|
+
* }
|
|
1209
|
+
* ```
|
|
1210
|
+
*/
|
|
1211
|
+
getInstructions(): string | null;
|
|
1212
|
+
/**
|
|
1213
|
+
* Get formatted content to include in system message.
|
|
1214
|
+
*
|
|
1215
|
+
* Returns the plugin's current state formatted for LLM consumption.
|
|
1216
|
+
* Should be Markdown with a `## Header`. This content CAN be compacted
|
|
1217
|
+
* if `isCompactable()` returns true.
|
|
1218
|
+
*
|
|
1219
|
+
* **IMPORTANT:** Call `updateTokenCache()` with the content's token size
|
|
1220
|
+
* before returning to keep budget calculations accurate.
|
|
1221
|
+
*
|
|
1222
|
+
* @returns Formatted content string or null if empty
|
|
1223
|
+
*
|
|
1224
|
+
* @example
|
|
1225
|
+
* ```typescript
|
|
1226
|
+
* async getContent(): Promise<string | null> {
|
|
1227
|
+
* if (this._entries.size === 0) return null;
|
|
1228
|
+
*
|
|
1229
|
+
* const lines = this._entries.map(e => `- ${e.key}: ${e.value}`);
|
|
1230
|
+
* const content = `## My Plugin (${this._entries.size} entries)\n\n${lines.join('\n')}`;
|
|
1231
|
+
*
|
|
1232
|
+
* // IMPORTANT: Update token cache before returning
|
|
1233
|
+
* this.updateTokenCache(this.estimator.estimateTokens(content));
|
|
1234
|
+
* return content;
|
|
1235
|
+
* }
|
|
1236
|
+
* ```
|
|
1237
|
+
*/
|
|
1238
|
+
getContent(): Promise<string | null>;
|
|
1239
|
+
/**
|
|
1240
|
+
* Get the full raw contents of this plugin for inspection.
|
|
1241
|
+
*
|
|
1242
|
+
* Used by library clients to programmatically inspect plugin state.
|
|
1243
|
+
* Returns the actual data structure, not the formatted string.
|
|
1244
|
+
*
|
|
1245
|
+
* @returns Raw plugin data (entries map, array, etc.)
|
|
1246
|
+
*/
|
|
1247
|
+
getContents(): unknown;
|
|
1248
|
+
/**
|
|
1249
|
+
* Get current token size of plugin content.
|
|
1250
|
+
*
|
|
1251
|
+
* Returns the cached token count from the last `updateTokenCache()` call.
|
|
1252
|
+
* This is used for budget calculation in `prepare()`.
|
|
1253
|
+
*
|
|
1254
|
+
* The cache should be updated via `updateTokenCache()` whenever content
|
|
1255
|
+
* changes. If cache is null, returns 0.
|
|
1256
|
+
*
|
|
1257
|
+
* @returns Current token count (0 if no content or cache not set)
|
|
1258
|
+
*/
|
|
1259
|
+
getTokenSize(): number;
|
|
1260
|
+
/**
|
|
1261
|
+
* Get token size of instructions (cached after first call).
|
|
1262
|
+
*
|
|
1263
|
+
* Instructions are static, so this is computed once and cached.
|
|
1264
|
+
* Used for budget calculation.
|
|
1265
|
+
*
|
|
1266
|
+
* @returns Token count for instructions (0 if no instructions)
|
|
1267
|
+
*/
|
|
1268
|
+
getInstructionsTokenSize(): number;
|
|
1269
|
+
/**
|
|
1270
|
+
* Whether this plugin's content can be compacted when context is tight.
|
|
1271
|
+
*
|
|
1272
|
+
* Return true if the plugin can reduce its content size when requested.
|
|
1273
|
+
* Examples: evicting low-priority entries, summarizing, removing old data.
|
|
1274
|
+
*
|
|
1275
|
+
* Return false if content cannot be reduced (e.g., critical state).
|
|
1276
|
+
*
|
|
1277
|
+
* @returns true if compact() can free tokens
|
|
1278
|
+
*/
|
|
1279
|
+
isCompactable(): boolean;
|
|
1280
|
+
/**
|
|
1281
|
+
* Compact plugin content to free tokens.
|
|
1282
|
+
*
|
|
1283
|
+
* Called by compaction strategies when context is too full.
|
|
1284
|
+
* Should attempt to free **approximately** `targetTokensToFree` tokens.
|
|
1285
|
+
*
|
|
1286
|
+
* This is a **best effort** operation:
|
|
1287
|
+
* - May free more or less than requested
|
|
1288
|
+
* - May return 0 if nothing can be compacted (e.g., all entries are critical)
|
|
1289
|
+
* - Should prioritize removing lowest-priority/oldest data first
|
|
1290
|
+
*
|
|
1291
|
+
* Strategies may include:
|
|
1292
|
+
* - Evicting low-priority entries
|
|
1293
|
+
* - Summarizing verbose content
|
|
1294
|
+
* - Removing oldest data
|
|
1295
|
+
* - Truncating large values
|
|
1296
|
+
*
|
|
1297
|
+
* **IMPORTANT:** Call `invalidateTokenCache()` or `updateTokenCache()`
|
|
1298
|
+
* after modifying content.
|
|
1299
|
+
*
|
|
1300
|
+
* @param targetTokensToFree - Approximate tokens to free (best effort)
|
|
1301
|
+
* @returns Actual tokens freed (may be 0 if nothing can be compacted)
|
|
1302
|
+
*
|
|
1303
|
+
* @example
|
|
1304
|
+
* ```typescript
|
|
1305
|
+
* async compact(targetTokensToFree: number): Promise<number> {
|
|
1306
|
+
* const before = this.getTokenSize();
|
|
1307
|
+
* let freed = 0;
|
|
1308
|
+
*
|
|
1309
|
+
* // Remove low-priority entries until target reached
|
|
1310
|
+
* const sorted = [...this._entries].sort(byPriority);
|
|
1311
|
+
* for (const entry of sorted) {
|
|
1312
|
+
* if (entry.priority === 'critical') continue; // Never remove critical
|
|
1313
|
+
* if (freed >= targetTokensToFree) break;
|
|
1314
|
+
*
|
|
1315
|
+
* freed += entry.tokens;
|
|
1316
|
+
* this._entries.delete(entry.key);
|
|
1317
|
+
* }
|
|
1318
|
+
*
|
|
1319
|
+
* this.invalidateTokenCache();
|
|
1320
|
+
* return freed;
|
|
1321
|
+
* }
|
|
1322
|
+
* ```
|
|
1323
|
+
*/
|
|
1324
|
+
compact(targetTokensToFree: number): Promise<number>;
|
|
1325
|
+
/**
|
|
1326
|
+
* Get tools provided by this plugin.
|
|
1327
|
+
*
|
|
1328
|
+
* Tools are automatically registered with ToolManager when the plugin
|
|
1329
|
+
* is added to the context. Use a consistent naming convention:
|
|
1330
|
+
* `<prefix>_<action>` (e.g., `memory_store`, `context_set`).
|
|
1331
|
+
*
|
|
1332
|
+
* @returns Array of tool definitions (empty array if no tools)
|
|
1333
|
+
*/
|
|
1334
|
+
getTools(): ToolFunction[];
|
|
1335
|
+
/**
|
|
1336
|
+
* Cleanup resources when context is destroyed.
|
|
1337
|
+
*
|
|
1338
|
+
* Called when AgentContextNextGen.destroy() is invoked.
|
|
1339
|
+
* Use for releasing resources, closing connections, etc.
|
|
1340
|
+
*/
|
|
1341
|
+
destroy(): void;
|
|
1342
|
+
/**
|
|
1343
|
+
* Serialize plugin state for session persistence.
|
|
1344
|
+
*
|
|
1345
|
+
* **MUST be synchronous.** Return a JSON-serializable object representing
|
|
1346
|
+
* the plugin's current state. This is called when saving a session.
|
|
1347
|
+
*
|
|
1348
|
+
* For plugins with async data (e.g., external storage), return only
|
|
1349
|
+
* references/keys here and handle async restoration separately.
|
|
1350
|
+
*
|
|
1351
|
+
* @returns Serializable state object
|
|
1352
|
+
*
|
|
1353
|
+
* @example
|
|
1354
|
+
* ```typescript
|
|
1355
|
+
* getState(): unknown {
|
|
1356
|
+
* return {
|
|
1357
|
+
* entries: [...this._entries].map(([k, v]) => ({ key: k, ...v })),
|
|
1358
|
+
* version: 1, // Include version for future migrations
|
|
1359
|
+
* };
|
|
1360
|
+
* }
|
|
1361
|
+
* ```
|
|
1362
|
+
*/
|
|
1363
|
+
getState(): unknown;
|
|
1364
|
+
/**
|
|
1365
|
+
* Restore plugin state from serialized data.
|
|
1366
|
+
*
|
|
1367
|
+
* Called when loading a saved session. The state comes from a previous
|
|
1368
|
+
* `getState()` call on the same plugin type.
|
|
1369
|
+
*
|
|
1370
|
+
* **IMPORTANT:** Call `invalidateTokenCache()` after restoring state
|
|
1371
|
+
* to ensure token counts are recalculated.
|
|
1372
|
+
*
|
|
1373
|
+
* @param state - Previously serialized state from getState()
|
|
1374
|
+
*
|
|
1375
|
+
* @example
|
|
1376
|
+
* ```typescript
|
|
1377
|
+
* restoreState(state: unknown): void {
|
|
1378
|
+
* const s = state as { entries: Array<{ key: string; value: unknown }> };
|
|
1379
|
+
* this._entries.clear();
|
|
1380
|
+
* for (const entry of s.entries || []) {
|
|
1381
|
+
* this._entries.set(entry.key, entry);
|
|
1382
|
+
* }
|
|
1383
|
+
* this.invalidateTokenCache(); // IMPORTANT: refresh token cache
|
|
1384
|
+
* }
|
|
1385
|
+
* ```
|
|
1386
|
+
*/
|
|
1387
|
+
restoreState(state: unknown): void;
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Token budget breakdown - clear and simple
|
|
1391
|
+
*/
|
|
1392
|
+
interface ContextBudget {
|
|
1393
|
+
/** Maximum context tokens for the model */
|
|
1394
|
+
maxTokens: number;
|
|
1395
|
+
/** Tokens reserved for LLM response */
|
|
1396
|
+
responseReserve: number;
|
|
1397
|
+
/** Tokens used by system message (prompt + instructions + plugin content) */
|
|
1398
|
+
systemMessageTokens: number;
|
|
1399
|
+
/** Tokens used by tool definitions (NEVER compacted) */
|
|
1400
|
+
toolsTokens: number;
|
|
1401
|
+
/** Tokens used by conversation history */
|
|
1402
|
+
conversationTokens: number;
|
|
1403
|
+
/** Tokens used by current input (user message or tool results) */
|
|
1404
|
+
currentInputTokens: number;
|
|
1405
|
+
/** Total tokens used */
|
|
1406
|
+
totalUsed: number;
|
|
1407
|
+
/** Available tokens (maxTokens - responseReserve - totalUsed) */
|
|
1408
|
+
available: number;
|
|
1409
|
+
/** Usage percentage (totalUsed / (maxTokens - responseReserve)) */
|
|
1410
|
+
utilizationPercent: number;
|
|
1411
|
+
/** Breakdown by component for debugging */
|
|
1412
|
+
breakdown: {
|
|
1413
|
+
systemPrompt: number;
|
|
1414
|
+
persistentInstructions: number;
|
|
1415
|
+
pluginInstructions: number;
|
|
1416
|
+
pluginContents: Record<string, number>;
|
|
1417
|
+
tools: number;
|
|
1418
|
+
conversation: number;
|
|
1419
|
+
currentInput: number;
|
|
1420
|
+
};
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Result of prepare() - ready for LLM call
|
|
1424
|
+
*/
|
|
1425
|
+
interface PreparedContext {
|
|
1426
|
+
/** Final input items array for LLM */
|
|
1427
|
+
input: InputItem[];
|
|
1428
|
+
/** Token budget breakdown */
|
|
1429
|
+
budget: ContextBudget;
|
|
1430
|
+
/** Whether compaction was performed */
|
|
1431
|
+
compacted: boolean;
|
|
1432
|
+
/** Log of compaction actions taken */
|
|
1433
|
+
compactionLog: string[];
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* Result of handling oversized current input
|
|
1437
|
+
*/
|
|
1438
|
+
interface OversizedInputResult {
|
|
1439
|
+
/** Whether the input was accepted (possibly truncated) */
|
|
1440
|
+
accepted: boolean;
|
|
1441
|
+
/** Processed content (truncated if needed) */
|
|
1442
|
+
content: string;
|
|
1443
|
+
/** Error message if rejected */
|
|
1444
|
+
error?: string;
|
|
1445
|
+
/** Warning message if truncated */
|
|
1446
|
+
warning?: string;
|
|
1447
|
+
/** Original size in bytes */
|
|
1448
|
+
originalSize: number;
|
|
1449
|
+
/** Final size in bytes */
|
|
1450
|
+
finalSize: number;
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Feature flags for enabling/disabling plugins
|
|
1454
|
+
*/
|
|
1455
|
+
interface ContextFeatures {
|
|
1456
|
+
/** Enable WorkingMemory plugin (default: true) */
|
|
1457
|
+
workingMemory?: boolean;
|
|
1458
|
+
/** Enable InContextMemory plugin (default: false) */
|
|
1459
|
+
inContextMemory?: boolean;
|
|
1460
|
+
/** Enable PersistentInstructions plugin (default: false) */
|
|
1461
|
+
persistentInstructions?: boolean;
|
|
1462
|
+
/** Enable UserInfo plugin (default: false) */
|
|
1463
|
+
userInfo?: boolean;
|
|
1464
|
+
/** Enable ToolCatalog plugin for dynamic tool loading/unloading (default: false) */
|
|
1465
|
+
toolCatalog?: boolean;
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Default feature configuration
|
|
1469
|
+
*/
|
|
1470
|
+
declare const DEFAULT_FEATURES: Required<ContextFeatures>;
|
|
1471
|
+
/**
|
|
1472
|
+
* Plugin configurations for auto-initialization.
|
|
1473
|
+
* When features are enabled, plugins are created with these configs.
|
|
1474
|
+
* The config shapes match each plugin's constructor parameter.
|
|
1475
|
+
*/
|
|
1476
|
+
interface PluginConfigs {
|
|
1477
|
+
/**
|
|
1478
|
+
* Working memory plugin config (used when features.workingMemory=true).
|
|
1479
|
+
* See WorkingMemoryPluginConfig for full options.
|
|
1480
|
+
*/
|
|
1481
|
+
workingMemory?: Record<string, unknown>;
|
|
1482
|
+
/**
|
|
1483
|
+
* In-context memory plugin config (used when features.inContextMemory=true).
|
|
1484
|
+
* See InContextMemoryConfig for full options.
|
|
1485
|
+
*/
|
|
1486
|
+
inContextMemory?: Record<string, unknown>;
|
|
1487
|
+
/**
|
|
1488
|
+
* Persistent instructions plugin config (used when features.persistentInstructions=true).
|
|
1489
|
+
* Note: agentId is auto-filled from context config if not provided.
|
|
1490
|
+
* See PersistentInstructionsConfig for full options.
|
|
1491
|
+
*/
|
|
1492
|
+
persistentInstructions?: Record<string, unknown>;
|
|
1493
|
+
/**
|
|
1494
|
+
* User info plugin config (used when features.userInfo=true).
|
|
1495
|
+
* See UserInfoPluginConfig for full options.
|
|
1496
|
+
*/
|
|
1497
|
+
userInfo?: Record<string, unknown>;
|
|
1498
|
+
/**
|
|
1499
|
+
* Tool catalog plugin config (used when features.toolCatalog=true).
|
|
1500
|
+
* See ToolCatalogPluginConfig for full options.
|
|
1501
|
+
*/
|
|
1502
|
+
toolCatalog?: Record<string, unknown>;
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* AgentContextNextGen configuration
|
|
1506
|
+
*/
|
|
1507
|
+
interface AgentContextNextGenConfig {
|
|
1508
|
+
/** Model name (used for context window lookup) */
|
|
1509
|
+
model: string;
|
|
1510
|
+
/** Maximum context tokens (auto-detected from model if not provided) */
|
|
1511
|
+
maxContextTokens?: number;
|
|
1512
|
+
/** Tokens to reserve for response (default: 4096) */
|
|
1513
|
+
responseReserve?: number;
|
|
1514
|
+
/** System prompt provided by user */
|
|
1515
|
+
systemPrompt?: string;
|
|
1516
|
+
/**
|
|
1517
|
+
* Compaction strategy name (default: 'default').
|
|
1518
|
+
* Used to create strategy from StrategyRegistry if compactionStrategy not provided.
|
|
1519
|
+
*/
|
|
1520
|
+
strategy?: string;
|
|
1521
|
+
/**
|
|
1522
|
+
* Custom compaction strategy instance.
|
|
1523
|
+
* If provided, overrides the `strategy` option.
|
|
1524
|
+
*/
|
|
1525
|
+
compactionStrategy?: ICompactionStrategy;
|
|
1526
|
+
/** Feature flags */
|
|
1527
|
+
features?: ContextFeatures;
|
|
1528
|
+
/** Agent ID (required for PersistentInstructions) */
|
|
1529
|
+
agentId?: string;
|
|
1530
|
+
/** User ID for multi-user scenarios. Automatically flows to ToolContext for all tool executions. */
|
|
1531
|
+
userId?: string;
|
|
1532
|
+
/**
|
|
1533
|
+
* Restrict this agent to specific auth identities (connector + optional account alias).
|
|
1534
|
+
* When set, only these identities are visible in ToolContext and tool descriptions.
|
|
1535
|
+
* Each identity produces its own tool set (e.g., microsoft_work_api, microsoft_personal_api).
|
|
1536
|
+
* When not set, all connectors visible to the current userId are available.
|
|
1537
|
+
*/
|
|
1538
|
+
identities?: AuthIdentity[];
|
|
1539
|
+
/** Initial tools to register */
|
|
1540
|
+
tools?: ToolFunction[];
|
|
1541
|
+
/** Storage for session persistence */
|
|
1542
|
+
storage?: IContextStorage;
|
|
1543
|
+
/** Restrict tool catalog to specific categories */
|
|
1544
|
+
toolCategories?: ToolCategoryScope;
|
|
1545
|
+
/** Plugin-specific configurations (used with features flags) */
|
|
1546
|
+
plugins?: PluginConfigs;
|
|
1547
|
+
/**
|
|
1548
|
+
* Hard timeout in milliseconds for any single tool execution.
|
|
1549
|
+
* Acts as a safety net: if a tool's own timeout mechanism fails
|
|
1550
|
+
* (e.g. a child process doesn't exit), this will force-resolve with an error.
|
|
1551
|
+
* Default: 0 (disabled - relies on each tool's own timeout)
|
|
1552
|
+
*/
|
|
1553
|
+
toolExecutionTimeout?: number;
|
|
1554
|
+
}
|
|
1555
|
+
/**
|
|
1556
|
+
* Default configuration values
|
|
1557
|
+
*/
|
|
1558
|
+
declare const DEFAULT_CONFIG: {
|
|
1559
|
+
responseReserve: number;
|
|
1560
|
+
strategy: string;
|
|
1561
|
+
};
|
|
1562
|
+
|
|
1563
|
+
/**
|
|
1564
|
+
* Events emitted by AgentContextNextGen
|
|
1565
|
+
*/
|
|
1566
|
+
interface ContextEvents {
|
|
1567
|
+
/** Emitted when context is prepared */
|
|
1568
|
+
'context:prepared': {
|
|
1569
|
+
budget: ContextBudget;
|
|
1570
|
+
compacted: boolean;
|
|
1571
|
+
};
|
|
1572
|
+
/** Emitted when compaction is performed */
|
|
1573
|
+
'context:compacted': {
|
|
1574
|
+
tokensFreed: number;
|
|
1575
|
+
log: string[];
|
|
1576
|
+
};
|
|
1577
|
+
/** Emitted right after budget is calculated in prepare() - for reactive monitoring */
|
|
1578
|
+
'budget:updated': {
|
|
1579
|
+
budget: ContextBudget;
|
|
1580
|
+
timestamp: number;
|
|
1581
|
+
};
|
|
1582
|
+
/** Emitted when budget reaches warning threshold (>70%) */
|
|
1583
|
+
'budget:warning': {
|
|
1584
|
+
budget: ContextBudget;
|
|
1585
|
+
};
|
|
1586
|
+
/** Emitted when budget reaches critical threshold (>90%) */
|
|
1587
|
+
'budget:critical': {
|
|
1588
|
+
budget: ContextBudget;
|
|
1589
|
+
};
|
|
1590
|
+
/** Emitted when compaction is about to start */
|
|
1591
|
+
'compaction:starting': {
|
|
1592
|
+
budget: ContextBudget;
|
|
1593
|
+
targetTokensToFree: number;
|
|
1594
|
+
timestamp: number;
|
|
1595
|
+
};
|
|
1596
|
+
/** Emitted when current input is too large */
|
|
1597
|
+
'input:oversized': {
|
|
1598
|
+
result: OversizedInputResult;
|
|
1599
|
+
};
|
|
1600
|
+
/** Emitted when a message is added */
|
|
1601
|
+
'message:added': {
|
|
1602
|
+
role: string;
|
|
1603
|
+
index: number;
|
|
1604
|
+
};
|
|
1605
|
+
/** Emitted when conversation is cleared */
|
|
1606
|
+
'conversation:cleared': {
|
|
1607
|
+
reason?: string;
|
|
1608
|
+
};
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Callback type for beforeCompaction hook.
|
|
1612
|
+
* Called before compaction starts, allowing agents to save important data.
|
|
1613
|
+
*/
|
|
1614
|
+
type BeforeCompactionCallback = (info: {
|
|
1615
|
+
budget: ContextBudget;
|
|
1616
|
+
targetTokensToFree: number;
|
|
1617
|
+
strategy: string;
|
|
1618
|
+
}) => Promise<void>;
|
|
1619
|
+
/**
|
|
1620
|
+
* Result of compact() operation.
|
|
1621
|
+
*/
|
|
1622
|
+
interface CompactionResult {
|
|
1623
|
+
/** Tokens actually freed by compaction */
|
|
1624
|
+
tokensFreed: number;
|
|
1625
|
+
/** Number of messages removed from conversation */
|
|
1626
|
+
messagesRemoved: number;
|
|
1627
|
+
/** Names of plugins that were compacted */
|
|
1628
|
+
pluginsCompacted: string[];
|
|
1629
|
+
/** Log of actions taken during compaction */
|
|
1630
|
+
log: string[];
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* Result of consolidate() operation.
|
|
1634
|
+
*/
|
|
1635
|
+
interface ConsolidationResult {
|
|
1636
|
+
/** Whether any consolidation was performed */
|
|
1637
|
+
performed: boolean;
|
|
1638
|
+
/** Net token change (negative = freed, positive = added, e.g., summaries) */
|
|
1639
|
+
tokensChanged: number;
|
|
1640
|
+
/** Description of actions taken */
|
|
1641
|
+
actions: string[];
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Read-only context passed to compaction strategies.
|
|
1645
|
+
* Provides access to data needed for compaction decisions and
|
|
1646
|
+
* controlled methods to modify state.
|
|
1647
|
+
*/
|
|
1648
|
+
interface CompactionContext {
|
|
1649
|
+
/** Current budget (from prepare) */
|
|
1650
|
+
readonly budget: ContextBudget;
|
|
1651
|
+
/** Current conversation history (read-only) */
|
|
1652
|
+
readonly conversation: ReadonlyArray<InputItem>;
|
|
1653
|
+
/** Current input (read-only) */
|
|
1654
|
+
readonly currentInput: ReadonlyArray<InputItem>;
|
|
1655
|
+
/** Registered plugins (for querying state) */
|
|
1656
|
+
readonly plugins: ReadonlyArray<IContextPluginNextGen>;
|
|
1657
|
+
/** Strategy name for logging */
|
|
1658
|
+
readonly strategyName: string;
|
|
1659
|
+
/**
|
|
1660
|
+
* Remove messages by indices.
|
|
1661
|
+
* Handles tool pair preservation internally.
|
|
1662
|
+
*
|
|
1663
|
+
* @param indices - Array of message indices to remove
|
|
1664
|
+
* @returns Tokens actually freed
|
|
1665
|
+
*/
|
|
1666
|
+
removeMessages(indices: number[]): Promise<number>;
|
|
1667
|
+
/**
|
|
1668
|
+
* Compact a specific plugin.
|
|
1669
|
+
*
|
|
1670
|
+
* @param pluginName - Name of the plugin to compact
|
|
1671
|
+
* @param targetTokens - Approximate tokens to free
|
|
1672
|
+
* @returns Tokens actually freed
|
|
1673
|
+
*/
|
|
1674
|
+
compactPlugin(pluginName: string, targetTokens: number): Promise<number>;
|
|
1675
|
+
/**
|
|
1676
|
+
* Estimate tokens for an item.
|
|
1677
|
+
*
|
|
1678
|
+
* @param item - Input item to estimate
|
|
1679
|
+
* @returns Estimated token count
|
|
1680
|
+
*/
|
|
1681
|
+
estimateTokens(item: InputItem): number;
|
|
1682
|
+
}
|
|
1683
|
+
/**
|
|
1684
|
+
* Compaction strategy interface.
|
|
1685
|
+
*
|
|
1686
|
+
* Strategies implement two methods:
|
|
1687
|
+
* - `compact()`: Emergency compaction when thresholds exceeded (called from prepare())
|
|
1688
|
+
* - `consolidate()`: Post-cycle cleanup and optimization (called after agentic loop)
|
|
1689
|
+
*
|
|
1690
|
+
* Use `compact()` for quick, threshold-based token reduction.
|
|
1691
|
+
* Use `consolidate()` for more expensive operations like summarization.
|
|
1692
|
+
*/
|
|
1693
|
+
interface ICompactionStrategy {
|
|
1694
|
+
/** Strategy name (unique identifier) for identification and logging */
|
|
1695
|
+
readonly name: string;
|
|
1696
|
+
/** Human-readable display name for UI */
|
|
1697
|
+
readonly displayName: string;
|
|
1698
|
+
/** Description explaining the strategy behavior */
|
|
1699
|
+
readonly description: string;
|
|
1700
|
+
/** Threshold percentage (0-1) at which compact() is triggered */
|
|
1701
|
+
readonly threshold: number;
|
|
1702
|
+
/**
|
|
1703
|
+
* Plugin names this strategy requires to function.
|
|
1704
|
+
* Validation is performed when strategy is assigned to context.
|
|
1705
|
+
* If any required plugin is missing, an error is thrown.
|
|
1706
|
+
*
|
|
1707
|
+
* @example
|
|
1708
|
+
* ```typescript
|
|
1709
|
+
* readonly requiredPlugins = ['working_memory'] as const;
|
|
1710
|
+
* ```
|
|
1711
|
+
*/
|
|
1712
|
+
readonly requiredPlugins?: readonly string[];
|
|
1713
|
+
/**
|
|
1714
|
+
* Emergency compaction - triggered when context usage exceeds threshold.
|
|
1715
|
+
* Called from prepare() when utilization > threshold.
|
|
1716
|
+
*
|
|
1717
|
+
* Should be fast and focus on freeing tokens quickly.
|
|
1718
|
+
*
|
|
1719
|
+
* @param context - Compaction context with controlled access to state
|
|
1720
|
+
* @param targetToFree - Approximate tokens to free
|
|
1721
|
+
* @returns Result describing what was done
|
|
1722
|
+
*/
|
|
1723
|
+
compact(context: CompactionContext, targetToFree: number): Promise<CompactionResult>;
|
|
1724
|
+
/**
|
|
1725
|
+
* Post-cycle consolidation - run after agentic cycle completes.
|
|
1726
|
+
* Called from Agent after run()/stream() finishes (before session save).
|
|
1727
|
+
*
|
|
1728
|
+
* Use for more expensive operations:
|
|
1729
|
+
* - Summarizing long conversations
|
|
1730
|
+
* - Memory optimization and deduplication
|
|
1731
|
+
* - Promoting important data to persistent storage
|
|
1732
|
+
*
|
|
1733
|
+
* @param context - Compaction context with controlled access to state
|
|
1734
|
+
* @returns Result describing what was done
|
|
1735
|
+
*/
|
|
1736
|
+
consolidate(context: CompactionContext): Promise<ConsolidationResult>;
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
/**
|
|
1740
|
+
* LLM Response entity based on OpenAI Responses API format
|
|
1741
|
+
*/
|
|
1742
|
+
|
|
1743
|
+
/**
|
|
1744
|
+
* Token usage statistics
|
|
1745
|
+
*/
|
|
1746
|
+
interface TokenUsage {
|
|
1747
|
+
input_tokens: number;
|
|
1748
|
+
output_tokens: number;
|
|
1749
|
+
total_tokens: number;
|
|
1750
|
+
output_tokens_details?: {
|
|
1751
|
+
reasoning_tokens: number;
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
interface LLMResponse {
|
|
1755
|
+
id: string;
|
|
1756
|
+
object: 'response';
|
|
1757
|
+
created_at: number;
|
|
1758
|
+
status: 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete';
|
|
1759
|
+
model: string;
|
|
1760
|
+
output: OutputItem[];
|
|
1761
|
+
output_text?: string;
|
|
1762
|
+
thinking?: string;
|
|
1763
|
+
usage: TokenUsage;
|
|
1764
|
+
error?: {
|
|
1765
|
+
type: string;
|
|
1766
|
+
message: string;
|
|
1767
|
+
};
|
|
1768
|
+
metadata?: Record<string, string>;
|
|
1769
|
+
}
|
|
1770
|
+
type AgentResponse = LLMResponse;
|
|
1771
|
+
|
|
1772
|
+
/**
|
|
1773
|
+
* Streaming event types for real-time LLM responses
|
|
1774
|
+
* Based on OpenAI Responses API event format as the internal standard
|
|
1775
|
+
*/
|
|
1776
|
+
|
|
1777
|
+
/**
|
|
1778
|
+
* Stream event type enum
|
|
1779
|
+
*/
|
|
1780
|
+
declare enum StreamEventType {
|
|
1781
|
+
RESPONSE_CREATED = "response.created",
|
|
1782
|
+
RESPONSE_IN_PROGRESS = "response.in_progress",
|
|
1783
|
+
OUTPUT_TEXT_DELTA = "response.output_text.delta",
|
|
1784
|
+
OUTPUT_TEXT_DONE = "response.output_text.done",
|
|
1785
|
+
TOOL_CALL_START = "response.tool_call.start",
|
|
1786
|
+
TOOL_CALL_ARGUMENTS_DELTA = "response.tool_call_arguments.delta",
|
|
1787
|
+
TOOL_CALL_ARGUMENTS_DONE = "response.tool_call_arguments.done",
|
|
1788
|
+
TOOL_EXECUTION_START = "response.tool_execution.start",
|
|
1789
|
+
TOOL_EXECUTION_DONE = "response.tool_execution.done",
|
|
1790
|
+
ITERATION_COMPLETE = "response.iteration.complete",
|
|
1791
|
+
REASONING_DELTA = "response.reasoning.delta",
|
|
1792
|
+
REASONING_DONE = "response.reasoning.done",
|
|
1793
|
+
RESPONSE_COMPLETE = "response.complete",
|
|
1794
|
+
ERROR = "response.error"
|
|
1795
|
+
}
|
|
1796
|
+
/**
|
|
1797
|
+
* Base interface for all stream events
|
|
1798
|
+
*/
|
|
1799
|
+
interface BaseStreamEvent {
|
|
1800
|
+
type: StreamEventType;
|
|
1801
|
+
response_id: string;
|
|
1802
|
+
}
|
|
1803
|
+
/**
|
|
1804
|
+
* Response created - first event in stream
|
|
1805
|
+
*/
|
|
1806
|
+
interface ResponseCreatedEvent extends BaseStreamEvent {
|
|
1807
|
+
type: StreamEventType.RESPONSE_CREATED;
|
|
1808
|
+
model: string;
|
|
1809
|
+
created_at: number;
|
|
1810
|
+
}
|
|
1811
|
+
/**
|
|
1812
|
+
* Response in progress
|
|
1813
|
+
*/
|
|
1814
|
+
interface ResponseInProgressEvent extends BaseStreamEvent {
|
|
1815
|
+
type: StreamEventType.RESPONSE_IN_PROGRESS;
|
|
1816
|
+
}
|
|
1817
|
+
/**
|
|
1818
|
+
* Text delta - incremental text output
|
|
1819
|
+
*/
|
|
1820
|
+
interface OutputTextDeltaEvent extends BaseStreamEvent {
|
|
1821
|
+
type: StreamEventType.OUTPUT_TEXT_DELTA;
|
|
1822
|
+
item_id: string;
|
|
1823
|
+
output_index: number;
|
|
1824
|
+
content_index: number;
|
|
1825
|
+
delta: string;
|
|
1826
|
+
sequence_number: number;
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
1829
|
+
* Text output complete for this item
|
|
1830
|
+
*/
|
|
1831
|
+
interface OutputTextDoneEvent extends BaseStreamEvent {
|
|
1832
|
+
type: StreamEventType.OUTPUT_TEXT_DONE;
|
|
1833
|
+
item_id: string;
|
|
1834
|
+
output_index: number;
|
|
1835
|
+
text: string;
|
|
1836
|
+
}
|
|
1837
|
+
/**
|
|
1838
|
+
* Tool call detected and starting
|
|
1839
|
+
*/
|
|
1840
|
+
interface ToolCallStartEvent extends BaseStreamEvent {
|
|
1841
|
+
type: StreamEventType.TOOL_CALL_START;
|
|
1842
|
+
item_id: string;
|
|
1843
|
+
tool_call_id: string;
|
|
1844
|
+
tool_name: string;
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* Tool call arguments delta - incremental JSON
|
|
1848
|
+
*/
|
|
1849
|
+
interface ToolCallArgumentsDeltaEvent extends BaseStreamEvent {
|
|
1850
|
+
type: StreamEventType.TOOL_CALL_ARGUMENTS_DELTA;
|
|
1851
|
+
item_id: string;
|
|
1852
|
+
tool_call_id: string;
|
|
1853
|
+
tool_name: string;
|
|
1854
|
+
delta: string;
|
|
1855
|
+
sequence_number: number;
|
|
1856
|
+
}
|
|
1857
|
+
/**
|
|
1858
|
+
* Tool call arguments complete
|
|
1859
|
+
*/
|
|
1860
|
+
interface ToolCallArgumentsDoneEvent extends BaseStreamEvent {
|
|
1861
|
+
type: StreamEventType.TOOL_CALL_ARGUMENTS_DONE;
|
|
1862
|
+
tool_call_id: string;
|
|
1863
|
+
tool_name: string;
|
|
1864
|
+
arguments: string;
|
|
1865
|
+
incomplete?: boolean;
|
|
1866
|
+
}
|
|
1867
|
+
/**
|
|
1868
|
+
* Tool execution starting
|
|
1869
|
+
*/
|
|
1870
|
+
interface ToolExecutionStartEvent extends BaseStreamEvent {
|
|
1871
|
+
type: StreamEventType.TOOL_EXECUTION_START;
|
|
1872
|
+
tool_call_id: string;
|
|
1873
|
+
tool_name: string;
|
|
1874
|
+
arguments: any;
|
|
1875
|
+
}
|
|
1876
|
+
/**
|
|
1877
|
+
* Tool execution complete
|
|
1878
|
+
*/
|
|
1879
|
+
interface ToolExecutionDoneEvent extends BaseStreamEvent {
|
|
1880
|
+
type: StreamEventType.TOOL_EXECUTION_DONE;
|
|
1881
|
+
tool_call_id: string;
|
|
1882
|
+
tool_name: string;
|
|
1883
|
+
result: any;
|
|
1884
|
+
execution_time_ms: number;
|
|
1885
|
+
error?: string;
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* Iteration complete - end of agentic loop iteration
|
|
1889
|
+
*/
|
|
1890
|
+
interface IterationCompleteEvent$1 extends BaseStreamEvent {
|
|
1891
|
+
type: StreamEventType.ITERATION_COMPLETE;
|
|
1892
|
+
iteration: number;
|
|
1893
|
+
tool_calls_count: number;
|
|
1894
|
+
has_more_iterations: boolean;
|
|
1895
|
+
}
|
|
1896
|
+
/**
|
|
1897
|
+
* Response complete - final event
|
|
1898
|
+
*/
|
|
1899
|
+
interface ResponseCompleteEvent extends BaseStreamEvent {
|
|
1900
|
+
type: StreamEventType.RESPONSE_COMPLETE;
|
|
1901
|
+
status: 'completed' | 'incomplete' | 'failed';
|
|
1902
|
+
usage: TokenUsage;
|
|
1903
|
+
iterations: number;
|
|
1904
|
+
duration_ms?: number;
|
|
1905
|
+
}
|
|
1906
|
+
/**
|
|
1907
|
+
* Reasoning/thinking delta - incremental reasoning output
|
|
1908
|
+
*/
|
|
1909
|
+
interface ReasoningDeltaEvent extends BaseStreamEvent {
|
|
1910
|
+
type: StreamEventType.REASONING_DELTA;
|
|
1911
|
+
item_id: string;
|
|
1912
|
+
delta: string;
|
|
1913
|
+
sequence_number: number;
|
|
1914
|
+
}
|
|
1915
|
+
/**
|
|
1916
|
+
* Reasoning/thinking complete for this item
|
|
1917
|
+
*/
|
|
1918
|
+
interface ReasoningDoneEvent extends BaseStreamEvent {
|
|
1919
|
+
type: StreamEventType.REASONING_DONE;
|
|
1920
|
+
item_id: string;
|
|
1921
|
+
thinking: string;
|
|
1922
|
+
}
|
|
1923
|
+
/**
|
|
1924
|
+
* Error event
|
|
1925
|
+
*/
|
|
1926
|
+
interface ErrorEvent extends BaseStreamEvent {
|
|
1927
|
+
type: StreamEventType.ERROR;
|
|
1928
|
+
error: {
|
|
1929
|
+
type: string;
|
|
1930
|
+
message: string;
|
|
1931
|
+
code?: string;
|
|
1932
|
+
};
|
|
1933
|
+
recoverable: boolean;
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* Union type of all stream events
|
|
1937
|
+
* Discriminated by 'type' field for type narrowing
|
|
1938
|
+
*/
|
|
1939
|
+
type StreamEvent = ResponseCreatedEvent | ResponseInProgressEvent | OutputTextDeltaEvent | OutputTextDoneEvent | ReasoningDeltaEvent | ReasoningDoneEvent | ToolCallStartEvent | ToolCallArgumentsDeltaEvent | ToolCallArgumentsDoneEvent | ToolExecutionStartEvent | ToolExecutionDoneEvent | IterationCompleteEvent$1 | ResponseCompleteEvent | ErrorEvent;
|
|
1940
|
+
/**
|
|
1941
|
+
* Type guard to check if event is a specific type
|
|
1942
|
+
*/
|
|
1943
|
+
declare function isStreamEvent<T extends StreamEvent>(event: StreamEvent, type: StreamEventType): event is T;
|
|
1944
|
+
/**
|
|
1945
|
+
* Type guards for specific events
|
|
1946
|
+
*/
|
|
1947
|
+
declare function isOutputTextDelta(event: StreamEvent): event is OutputTextDeltaEvent;
|
|
1948
|
+
declare function isToolCallStart(event: StreamEvent): event is ToolCallStartEvent;
|
|
1949
|
+
declare function isToolCallArgumentsDelta(event: StreamEvent): event is ToolCallArgumentsDeltaEvent;
|
|
1950
|
+
declare function isToolCallArgumentsDone(event: StreamEvent): event is ToolCallArgumentsDoneEvent;
|
|
1951
|
+
declare function isReasoningDelta(event: StreamEvent): event is ReasoningDeltaEvent;
|
|
1952
|
+
declare function isReasoningDone(event: StreamEvent): event is ReasoningDoneEvent;
|
|
1953
|
+
declare function isResponseComplete(event: StreamEvent): event is ResponseCompleteEvent;
|
|
1954
|
+
declare function isErrorEvent(event: StreamEvent): event is ErrorEvent;
|
|
1955
|
+
|
|
1956
|
+
/**
|
|
1957
|
+
* Text generation provider interface
|
|
1958
|
+
*/
|
|
1959
|
+
|
|
1960
|
+
interface TextGenerateOptions {
|
|
1961
|
+
model: string;
|
|
1962
|
+
input: string | InputItem[];
|
|
1963
|
+
instructions?: string;
|
|
1964
|
+
tools?: Tool[];
|
|
1965
|
+
tool_choice?: 'auto' | 'required' | {
|
|
1966
|
+
type: 'function';
|
|
1967
|
+
function: {
|
|
1968
|
+
name: string;
|
|
1969
|
+
};
|
|
1970
|
+
};
|
|
1971
|
+
temperature?: number;
|
|
1972
|
+
max_output_tokens?: number;
|
|
1973
|
+
response_format?: {
|
|
1974
|
+
type: 'text' | 'json_object' | 'json_schema';
|
|
1975
|
+
json_schema?: any;
|
|
1976
|
+
};
|
|
1977
|
+
parallel_tool_calls?: boolean;
|
|
1978
|
+
previous_response_id?: string;
|
|
1979
|
+
metadata?: Record<string, string>;
|
|
1980
|
+
/** Vendor-agnostic thinking/reasoning configuration */
|
|
1981
|
+
thinking?: {
|
|
1982
|
+
enabled: boolean;
|
|
1983
|
+
/** Budget in tokens for thinking (Anthropic & Google) */
|
|
1984
|
+
budgetTokens?: number;
|
|
1985
|
+
/** Reasoning effort level (OpenAI) */
|
|
1986
|
+
effort?: 'low' | 'medium' | 'high';
|
|
1987
|
+
};
|
|
1988
|
+
/** Vendor-specific options (e.g., Google's thinkingLevel, OpenAI's reasoning_effort) */
|
|
1989
|
+
vendorOptions?: Record<string, any>;
|
|
1990
|
+
}
|
|
1991
|
+
interface ModelCapabilities {
|
|
1992
|
+
supportsTools: boolean;
|
|
1993
|
+
supportsVision: boolean;
|
|
1994
|
+
supportsJSON: boolean;
|
|
1995
|
+
supportsJSONSchema: boolean;
|
|
1996
|
+
maxTokens: number;
|
|
1997
|
+
maxInputTokens?: number;
|
|
1998
|
+
maxOutputTokens?: number;
|
|
1999
|
+
}
|
|
2000
|
+
interface ITextProvider extends IProvider {
|
|
2001
|
+
/**
|
|
2002
|
+
* Generate text response
|
|
2003
|
+
*/
|
|
2004
|
+
generate(options: TextGenerateOptions): Promise<LLMResponse>;
|
|
2005
|
+
/**
|
|
2006
|
+
* Stream text response with real-time events
|
|
2007
|
+
* Returns an async iterator of streaming events
|
|
2008
|
+
*/
|
|
2009
|
+
streamGenerate(options: TextGenerateOptions): AsyncIterableIterator<StreamEvent>;
|
|
2010
|
+
/**
|
|
2011
|
+
* Get model capabilities
|
|
2012
|
+
*/
|
|
2013
|
+
getModelCapabilities(model: string): ModelCapabilities;
|
|
2014
|
+
/**
|
|
2015
|
+
* List available models from the provider's API
|
|
2016
|
+
*/
|
|
2017
|
+
listModels(): Promise<string[]>;
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
/**
|
|
2021
|
+
* Execution context - tracks state, metrics, and history for agent execution
|
|
2022
|
+
* Includes memory safety (circular buffers) and resource limits
|
|
2023
|
+
*/
|
|
2024
|
+
|
|
2025
|
+
type HistoryMode = 'none' | 'summary' | 'full';
|
|
2026
|
+
interface ExecutionContextConfig {
|
|
2027
|
+
maxHistorySize?: number;
|
|
2028
|
+
historyMode?: HistoryMode;
|
|
2029
|
+
maxAuditTrailSize?: number;
|
|
2030
|
+
}
|
|
2031
|
+
interface IterationRecord {
|
|
2032
|
+
iteration: number;
|
|
2033
|
+
request: TextGenerateOptions;
|
|
2034
|
+
response: AgentResponse;
|
|
2035
|
+
toolCalls: ToolCall[];
|
|
2036
|
+
toolResults: ToolResult[];
|
|
2037
|
+
startTime: Date;
|
|
2038
|
+
endTime: Date;
|
|
2039
|
+
}
|
|
2040
|
+
interface IterationSummary {
|
|
2041
|
+
iteration: number;
|
|
2042
|
+
tokens: number;
|
|
2043
|
+
toolCount: number;
|
|
2044
|
+
duration: number;
|
|
2045
|
+
timestamp: Date;
|
|
2046
|
+
}
|
|
2047
|
+
interface ExecutionMetrics {
|
|
2048
|
+
totalDuration: number;
|
|
2049
|
+
llmDuration: number;
|
|
2050
|
+
toolDuration: number;
|
|
2051
|
+
hookDuration: number;
|
|
2052
|
+
iterationCount: number;
|
|
2053
|
+
toolCallCount: number;
|
|
2054
|
+
toolSuccessCount: number;
|
|
2055
|
+
toolFailureCount: number;
|
|
2056
|
+
toolTimeoutCount: number;
|
|
2057
|
+
inputTokens: number;
|
|
2058
|
+
outputTokens: number;
|
|
2059
|
+
totalTokens: number;
|
|
2060
|
+
errors: Array<{
|
|
2061
|
+
type: string;
|
|
2062
|
+
message: string;
|
|
2063
|
+
timestamp: Date;
|
|
2064
|
+
}>;
|
|
2065
|
+
}
|
|
2066
|
+
interface AuditEntry {
|
|
2067
|
+
timestamp: Date;
|
|
2068
|
+
type: 'hook_executed' | 'tool_modified' | 'tool_skipped' | 'execution_paused' | 'execution_resumed' | 'tool_approved' | 'tool_rejected' | 'tool_blocked' | 'tool_permission_approved';
|
|
2069
|
+
hookName?: string;
|
|
2070
|
+
toolName?: string;
|
|
2071
|
+
details: any;
|
|
2072
|
+
}
|
|
2073
|
+
declare class ExecutionContext {
|
|
2074
|
+
readonly executionId: string;
|
|
2075
|
+
readonly startTime: Date;
|
|
2076
|
+
iteration: number;
|
|
2077
|
+
readonly toolCalls: Map<string, ToolCall>;
|
|
2078
|
+
readonly toolResults: Map<string, ToolResult>;
|
|
2079
|
+
paused: boolean;
|
|
2080
|
+
pauseReason?: string;
|
|
2081
|
+
cancelled: boolean;
|
|
2082
|
+
cancelReason?: string;
|
|
2083
|
+
readonly metadata: Map<string, any>;
|
|
2084
|
+
private readonly config;
|
|
2085
|
+
private readonly iterations;
|
|
2086
|
+
private readonly iterationSummaries;
|
|
2087
|
+
readonly metrics: ExecutionMetrics;
|
|
2088
|
+
private readonly auditTrail;
|
|
2089
|
+
constructor(executionId: string, config?: ExecutionContextConfig);
|
|
2090
|
+
/**
|
|
2091
|
+
* Add iteration to history (memory-safe)
|
|
2092
|
+
*/
|
|
2093
|
+
addIteration(record: IterationRecord): void;
|
|
2094
|
+
/**
|
|
2095
|
+
* Get iteration history
|
|
2096
|
+
*/
|
|
2097
|
+
getHistory(): IterationRecord[] | IterationSummary[];
|
|
2098
|
+
/**
|
|
2099
|
+
* Add audit entry
|
|
2100
|
+
*/
|
|
2101
|
+
audit(type: AuditEntry['type'], details: any, hookName?: string, toolName?: string): void;
|
|
2102
|
+
/**
|
|
2103
|
+
* Get audit trail
|
|
2104
|
+
*/
|
|
2105
|
+
getAuditTrail(): readonly AuditEntry[];
|
|
2106
|
+
/**
|
|
2107
|
+
* Update metrics
|
|
2108
|
+
*/
|
|
2109
|
+
updateMetrics(update: Partial<ExecutionMetrics>): void;
|
|
2110
|
+
/**
|
|
2111
|
+
* Add tool call to tracking
|
|
2112
|
+
*/
|
|
2113
|
+
addToolCall(toolCall: ToolCall): void;
|
|
2114
|
+
/**
|
|
2115
|
+
* Add tool result to tracking
|
|
2116
|
+
*/
|
|
2117
|
+
addToolResult(result: ToolResult): void;
|
|
2118
|
+
/**
|
|
2119
|
+
* Check resource limits
|
|
2120
|
+
*/
|
|
2121
|
+
checkLimits(limits?: {
|
|
2122
|
+
maxExecutionTime?: number;
|
|
2123
|
+
maxToolCalls?: number;
|
|
2124
|
+
maxContextSize?: number;
|
|
2125
|
+
}): void;
|
|
2126
|
+
/**
|
|
2127
|
+
* Estimate memory usage (rough approximation)
|
|
2128
|
+
*/
|
|
2129
|
+
private estimateSize;
|
|
2130
|
+
/**
|
|
2131
|
+
* Cleanup resources and release memory
|
|
2132
|
+
* Clears all internal arrays and maps to allow garbage collection
|
|
2133
|
+
*/
|
|
2134
|
+
cleanup(): void;
|
|
2135
|
+
/**
|
|
2136
|
+
* Get execution summary
|
|
2137
|
+
*/
|
|
2138
|
+
getSummary(): {
|
|
2139
|
+
executionId: string;
|
|
2140
|
+
startTime: Date;
|
|
2141
|
+
currentIteration: number;
|
|
2142
|
+
paused: boolean;
|
|
2143
|
+
cancelled: boolean;
|
|
2144
|
+
metrics: {
|
|
2145
|
+
totalDuration: number;
|
|
2146
|
+
llmDuration: number;
|
|
2147
|
+
toolDuration: number;
|
|
2148
|
+
hookDuration: number;
|
|
2149
|
+
iterationCount: number;
|
|
2150
|
+
toolCallCount: number;
|
|
2151
|
+
toolSuccessCount: number;
|
|
2152
|
+
toolFailureCount: number;
|
|
2153
|
+
toolTimeoutCount: number;
|
|
2154
|
+
inputTokens: number;
|
|
2155
|
+
outputTokens: number;
|
|
2156
|
+
totalTokens: number;
|
|
2157
|
+
errors: Array<{
|
|
2158
|
+
type: string;
|
|
2159
|
+
message: string;
|
|
2160
|
+
timestamp: Date;
|
|
2161
|
+
}>;
|
|
2162
|
+
};
|
|
2163
|
+
totalDuration: number;
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
/**
|
|
2168
|
+
* Event types for agent execution
|
|
2169
|
+
* These events are emitted asynchronously for notifications (UI updates, logging, etc.)
|
|
2170
|
+
*/
|
|
2171
|
+
|
|
2172
|
+
/**
|
|
2173
|
+
* Minimal config type for execution start events.
|
|
2174
|
+
* This captures the essential info without importing full AgentConfig.
|
|
2175
|
+
*/
|
|
2176
|
+
interface ExecutionConfig {
|
|
2177
|
+
model: string;
|
|
2178
|
+
instructions?: string;
|
|
2179
|
+
temperature?: number;
|
|
2180
|
+
maxIterations?: number;
|
|
2181
|
+
}
|
|
2182
|
+
interface ExecutionStartEvent {
|
|
2183
|
+
executionId: string;
|
|
2184
|
+
config: ExecutionConfig;
|
|
2185
|
+
timestamp: Date;
|
|
2186
|
+
}
|
|
2187
|
+
interface ExecutionCompleteEvent {
|
|
2188
|
+
executionId: string;
|
|
2189
|
+
response: AgentResponse;
|
|
2190
|
+
timestamp: Date;
|
|
2191
|
+
duration: number;
|
|
2192
|
+
}
|
|
2193
|
+
interface ExecutionErrorEvent {
|
|
2194
|
+
executionId: string;
|
|
2195
|
+
error: Error;
|
|
2196
|
+
timestamp: Date;
|
|
2197
|
+
}
|
|
2198
|
+
interface ExecutionPausedEvent {
|
|
2199
|
+
executionId: string;
|
|
2200
|
+
reason?: string;
|
|
2201
|
+
timestamp: Date;
|
|
2202
|
+
}
|
|
2203
|
+
interface ExecutionResumedEvent {
|
|
2204
|
+
executionId: string;
|
|
2205
|
+
timestamp: Date;
|
|
2206
|
+
}
|
|
2207
|
+
interface ExecutionCancelledEvent {
|
|
2208
|
+
executionId: string;
|
|
2209
|
+
reason?: string;
|
|
2210
|
+
timestamp: Date;
|
|
2211
|
+
}
|
|
2212
|
+
interface ExecutionMaxIterationsEvent {
|
|
2213
|
+
executionId: string;
|
|
2214
|
+
iteration: number;
|
|
2215
|
+
maxIterations: number;
|
|
2216
|
+
timestamp: Date;
|
|
2217
|
+
}
|
|
2218
|
+
interface IterationStartEvent {
|
|
2219
|
+
executionId: string;
|
|
2220
|
+
iteration: number;
|
|
2221
|
+
timestamp: Date;
|
|
2222
|
+
}
|
|
2223
|
+
interface IterationCompleteEvent {
|
|
2224
|
+
executionId: string;
|
|
2225
|
+
iteration: number;
|
|
2226
|
+
response: AgentResponse;
|
|
2227
|
+
timestamp: Date;
|
|
2228
|
+
duration: number;
|
|
2229
|
+
}
|
|
2230
|
+
interface LLMRequestEvent {
|
|
2231
|
+
executionId: string;
|
|
2232
|
+
iteration: number;
|
|
2233
|
+
options: TextGenerateOptions;
|
|
2234
|
+
timestamp: Date;
|
|
2235
|
+
}
|
|
2236
|
+
interface LLMResponseEvent {
|
|
2237
|
+
executionId: string;
|
|
2238
|
+
iteration: number;
|
|
2239
|
+
response: AgentResponse;
|
|
2240
|
+
timestamp: Date;
|
|
2241
|
+
duration: number;
|
|
2242
|
+
}
|
|
2243
|
+
interface LLMErrorEvent {
|
|
2244
|
+
executionId: string;
|
|
2245
|
+
iteration: number;
|
|
2246
|
+
error: Error;
|
|
2247
|
+
timestamp: Date;
|
|
2248
|
+
}
|
|
2249
|
+
interface ToolDetectedEvent {
|
|
2250
|
+
executionId: string;
|
|
2251
|
+
iteration: number;
|
|
2252
|
+
toolCalls: ToolCall[];
|
|
2253
|
+
timestamp: Date;
|
|
2254
|
+
}
|
|
2255
|
+
interface ToolStartEvent {
|
|
2256
|
+
executionId: string;
|
|
2257
|
+
iteration: number;
|
|
2258
|
+
toolCall: ToolCall;
|
|
2259
|
+
timestamp: Date;
|
|
2260
|
+
}
|
|
2261
|
+
interface ToolCompleteEvent {
|
|
2262
|
+
executionId: string;
|
|
2263
|
+
iteration: number;
|
|
2264
|
+
toolCall: ToolCall;
|
|
2265
|
+
result: ToolResult;
|
|
2266
|
+
timestamp: Date;
|
|
2267
|
+
}
|
|
2268
|
+
interface ToolErrorEvent {
|
|
2269
|
+
executionId: string;
|
|
2270
|
+
iteration: number;
|
|
2271
|
+
toolCall: ToolCall;
|
|
2272
|
+
error: Error;
|
|
2273
|
+
timestamp: Date;
|
|
2274
|
+
}
|
|
2275
|
+
interface ToolTimeoutEvent {
|
|
2276
|
+
executionId: string;
|
|
2277
|
+
iteration: number;
|
|
2278
|
+
toolCall: ToolCall;
|
|
2279
|
+
timeout: number;
|
|
2280
|
+
timestamp: Date;
|
|
2281
|
+
}
|
|
2282
|
+
interface HookErrorEvent {
|
|
2283
|
+
executionId: string;
|
|
2284
|
+
hookName: string;
|
|
2285
|
+
error: Error;
|
|
2286
|
+
timestamp: Date;
|
|
2287
|
+
}
|
|
2288
|
+
interface CircuitOpenedEvent {
|
|
2289
|
+
executionId: string;
|
|
2290
|
+
breakerName: string;
|
|
2291
|
+
failureCount: number;
|
|
2292
|
+
lastError: string;
|
|
2293
|
+
nextRetryTime: number;
|
|
2294
|
+
timestamp: Date;
|
|
2295
|
+
}
|
|
2296
|
+
interface CircuitHalfOpenEvent {
|
|
2297
|
+
executionId: string;
|
|
2298
|
+
breakerName: string;
|
|
2299
|
+
timestamp: Date;
|
|
2300
|
+
}
|
|
2301
|
+
interface CircuitClosedEvent {
|
|
2302
|
+
executionId: string;
|
|
2303
|
+
breakerName: string;
|
|
2304
|
+
successCount: number;
|
|
2305
|
+
timestamp: Date;
|
|
2306
|
+
}
|
|
2307
|
+
/**
|
|
2308
|
+
* Map of all event names to their payload types
|
|
2309
|
+
*/
|
|
2310
|
+
interface AgenticLoopEvents {
|
|
2311
|
+
'execution:start': ExecutionStartEvent;
|
|
2312
|
+
'execution:complete': ExecutionCompleteEvent;
|
|
2313
|
+
'execution:error': ExecutionErrorEvent;
|
|
2314
|
+
'execution:paused': ExecutionPausedEvent;
|
|
2315
|
+
'execution:resumed': ExecutionResumedEvent;
|
|
2316
|
+
'execution:cancelled': ExecutionCancelledEvent;
|
|
2317
|
+
'execution:maxIterations': ExecutionMaxIterationsEvent;
|
|
2318
|
+
'iteration:start': IterationStartEvent;
|
|
2319
|
+
'iteration:complete': IterationCompleteEvent;
|
|
2320
|
+
'llm:request': LLMRequestEvent;
|
|
2321
|
+
'llm:response': LLMResponseEvent;
|
|
2322
|
+
'llm:error': LLMErrorEvent;
|
|
2323
|
+
'tool:detected': ToolDetectedEvent;
|
|
2324
|
+
'tool:start': ToolStartEvent;
|
|
2325
|
+
'tool:complete': ToolCompleteEvent;
|
|
2326
|
+
'tool:error': ToolErrorEvent;
|
|
2327
|
+
'tool:timeout': ToolTimeoutEvent;
|
|
2328
|
+
'hook:error': HookErrorEvent;
|
|
2329
|
+
'circuit:opened': CircuitOpenedEvent;
|
|
2330
|
+
'circuit:half-open': CircuitHalfOpenEvent;
|
|
2331
|
+
'circuit:closed': CircuitClosedEvent;
|
|
2332
|
+
}
|
|
2333
|
+
type AgenticLoopEventName = keyof AgenticLoopEvents;
|
|
2334
|
+
/**
|
|
2335
|
+
* Agent events - alias for AgenticLoopEvents for cleaner API
|
|
2336
|
+
* This is the preferred export name going forward.
|
|
2337
|
+
*/
|
|
2338
|
+
type AgentEvents = AgenticLoopEvents;
|
|
2339
|
+
type AgentEventName = AgenticLoopEventName;
|
|
2340
|
+
|
|
2341
|
+
/**
|
|
2342
|
+
* Hook types for agent execution
|
|
2343
|
+
* Hooks can modify execution flow synchronously or asynchronously
|
|
2344
|
+
*/
|
|
2345
|
+
|
|
2346
|
+
/**
|
|
2347
|
+
* Base hook function type
|
|
2348
|
+
*/
|
|
2349
|
+
type Hook<TContext, TResult = any> = (context: TContext) => TResult | Promise<TResult>;
|
|
2350
|
+
/**
|
|
2351
|
+
* Hook that can modify data
|
|
2352
|
+
*/
|
|
2353
|
+
type ModifyingHook<TContext, TModification> = Hook<TContext, TModification>;
|
|
2354
|
+
interface BeforeExecutionContext {
|
|
2355
|
+
executionId: string;
|
|
2356
|
+
config: ExecutionConfig;
|
|
2357
|
+
timestamp: Date;
|
|
2358
|
+
}
|
|
2359
|
+
interface AfterExecutionContext {
|
|
2360
|
+
executionId: string;
|
|
2361
|
+
response: AgentResponse;
|
|
2362
|
+
context: ExecutionContext;
|
|
2363
|
+
timestamp: Date;
|
|
2364
|
+
duration: number;
|
|
2365
|
+
}
|
|
2366
|
+
interface BeforeLLMContext {
|
|
2367
|
+
executionId: string;
|
|
2368
|
+
iteration: number;
|
|
2369
|
+
options: TextGenerateOptions;
|
|
2370
|
+
context: ExecutionContext;
|
|
2371
|
+
timestamp: Date;
|
|
2372
|
+
}
|
|
2373
|
+
interface AfterLLMContext {
|
|
2374
|
+
executionId: string;
|
|
2375
|
+
iteration: number;
|
|
2376
|
+
response: AgentResponse;
|
|
2377
|
+
context: ExecutionContext;
|
|
2378
|
+
timestamp: Date;
|
|
2379
|
+
duration: number;
|
|
2380
|
+
}
|
|
2381
|
+
interface BeforeToolContext {
|
|
2382
|
+
executionId: string;
|
|
2383
|
+
iteration: number;
|
|
2384
|
+
toolCall: ToolCall;
|
|
2385
|
+
context: ExecutionContext;
|
|
2386
|
+
timestamp: Date;
|
|
2387
|
+
}
|
|
2388
|
+
interface AfterToolContext {
|
|
2389
|
+
executionId: string;
|
|
2390
|
+
iteration: number;
|
|
2391
|
+
toolCall: ToolCall;
|
|
2392
|
+
result: ToolResult;
|
|
2393
|
+
context: ExecutionContext;
|
|
2394
|
+
timestamp: Date;
|
|
2395
|
+
}
|
|
2396
|
+
interface ApproveToolContext {
|
|
2397
|
+
executionId: string;
|
|
2398
|
+
iteration: number;
|
|
2399
|
+
toolCall: ToolCall;
|
|
2400
|
+
context: ExecutionContext;
|
|
2401
|
+
timestamp: Date;
|
|
2402
|
+
}
|
|
2403
|
+
interface PauseCheckContext {
|
|
2404
|
+
executionId: string;
|
|
2405
|
+
iteration: number;
|
|
2406
|
+
context: ExecutionContext;
|
|
2407
|
+
timestamp: Date;
|
|
2408
|
+
}
|
|
2409
|
+
interface LLMModification {
|
|
2410
|
+
modified?: Partial<TextGenerateOptions>;
|
|
2411
|
+
skip?: boolean;
|
|
2412
|
+
reason?: string;
|
|
2413
|
+
}
|
|
2414
|
+
interface ToolModification {
|
|
2415
|
+
modified?: Partial<ToolCall>;
|
|
2416
|
+
skip?: boolean;
|
|
2417
|
+
mockResult?: any;
|
|
2418
|
+
reason?: string;
|
|
2419
|
+
}
|
|
2420
|
+
interface ToolResultModification {
|
|
2421
|
+
modified?: Partial<ToolResult>;
|
|
2422
|
+
retry?: boolean;
|
|
2423
|
+
reason?: string;
|
|
2424
|
+
}
|
|
2425
|
+
interface ApprovalResult {
|
|
2426
|
+
approved: boolean;
|
|
2427
|
+
reason?: string;
|
|
2428
|
+
modifiedArgs?: any;
|
|
2429
|
+
}
|
|
2430
|
+
interface PauseDecision {
|
|
2431
|
+
shouldPause: boolean;
|
|
2432
|
+
reason?: string;
|
|
2433
|
+
}
|
|
2434
|
+
interface HookConfig {
|
|
2435
|
+
'before:execution'?: Hook<BeforeExecutionContext, void>;
|
|
2436
|
+
'after:execution'?: Hook<AfterExecutionContext, void>;
|
|
2437
|
+
'before:llm'?: ModifyingHook<BeforeLLMContext, LLMModification>;
|
|
2438
|
+
'after:llm'?: ModifyingHook<AfterLLMContext, {}>;
|
|
2439
|
+
'before:tool'?: ModifyingHook<BeforeToolContext, ToolModification>;
|
|
2440
|
+
'after:tool'?: ModifyingHook<AfterToolContext, ToolResultModification>;
|
|
2441
|
+
'approve:tool'?: Hook<ApproveToolContext, ApprovalResult>;
|
|
2442
|
+
'pause:check'?: Hook<PauseCheckContext, PauseDecision>;
|
|
2443
|
+
hookTimeout?: number;
|
|
2444
|
+
parallelHooks?: boolean;
|
|
2445
|
+
}
|
|
2446
|
+
type HookName = keyof Omit<HookConfig, 'hookTimeout' | 'parallelHooks'>;
|
|
2447
|
+
/**
|
|
2448
|
+
* Map of hook names to their context and result types
|
|
2449
|
+
*/
|
|
2450
|
+
interface HookSignatures {
|
|
2451
|
+
'before:execution': {
|
|
2452
|
+
context: BeforeExecutionContext;
|
|
2453
|
+
result: void;
|
|
2454
|
+
};
|
|
2455
|
+
'after:execution': {
|
|
2456
|
+
context: AfterExecutionContext;
|
|
2457
|
+
result: void;
|
|
2458
|
+
};
|
|
2459
|
+
'before:llm': {
|
|
2460
|
+
context: BeforeLLMContext;
|
|
2461
|
+
result: LLMModification;
|
|
2462
|
+
};
|
|
2463
|
+
'after:llm': {
|
|
2464
|
+
context: AfterLLMContext;
|
|
2465
|
+
result: {};
|
|
2466
|
+
};
|
|
2467
|
+
'before:tool': {
|
|
2468
|
+
context: BeforeToolContext;
|
|
2469
|
+
result: ToolModification;
|
|
2470
|
+
};
|
|
2471
|
+
'after:tool': {
|
|
2472
|
+
context: AfterToolContext;
|
|
2473
|
+
result: ToolResultModification;
|
|
2474
|
+
};
|
|
2475
|
+
'approve:tool': {
|
|
2476
|
+
context: ApproveToolContext;
|
|
2477
|
+
result: ApprovalResult;
|
|
2478
|
+
};
|
|
2479
|
+
'pause:check': {
|
|
2480
|
+
context: PauseCheckContext;
|
|
2481
|
+
result: PauseDecision;
|
|
2482
|
+
};
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
/**
|
|
2486
|
+
* Hook manager - handles hook registration and execution
|
|
2487
|
+
* Includes error isolation, timeouts, and optional parallel execution
|
|
2488
|
+
*/
|
|
2489
|
+
|
|
2490
|
+
declare class HookManager {
|
|
2491
|
+
private hooks;
|
|
2492
|
+
private timeout;
|
|
2493
|
+
private parallel;
|
|
2494
|
+
private hookErrorCounts;
|
|
2495
|
+
private disabledHooks;
|
|
2496
|
+
private maxConsecutiveErrors;
|
|
2497
|
+
private emitter;
|
|
2498
|
+
constructor(config: HookConfig | undefined, emitter: EventEmitter, errorHandling?: {
|
|
2499
|
+
maxConsecutiveErrors?: number;
|
|
2500
|
+
});
|
|
2501
|
+
/**
|
|
2502
|
+
* Register hooks from configuration
|
|
2503
|
+
*/
|
|
2504
|
+
private registerFromConfig;
|
|
2505
|
+
/**
|
|
2506
|
+
* Register a hook
|
|
2507
|
+
*/
|
|
2508
|
+
register(name: HookName, hook: Hook<any, any>): void;
|
|
2509
|
+
/**
|
|
2510
|
+
* Unregister a specific hook function by reference.
|
|
2511
|
+
* Returns true if the hook was found and removed.
|
|
2512
|
+
*/
|
|
2513
|
+
unregister(name: HookName, hook: Hook<any, any>): boolean;
|
|
2514
|
+
/**
|
|
2515
|
+
* Execute hooks for a given name
|
|
2516
|
+
*/
|
|
2517
|
+
executeHooks<K extends HookName>(name: K, context: HookSignatures[K]['context'], defaultResult: HookSignatures[K]['result']): Promise<HookSignatures[K]['result']>;
|
|
2518
|
+
/**
|
|
2519
|
+
* Execute hooks sequentially
|
|
2520
|
+
*/
|
|
2521
|
+
private executeHooksSequential;
|
|
2522
|
+
/**
|
|
2523
|
+
* Execute hooks in parallel
|
|
2524
|
+
*/
|
|
2525
|
+
private executeHooksParallel;
|
|
2526
|
+
/**
|
|
2527
|
+
* Generate unique key for a hook
|
|
2528
|
+
*/
|
|
2529
|
+
private getHookKey;
|
|
2530
|
+
/**
|
|
2531
|
+
* Execute single hook with error isolation and timeout (with per-hook error tracking)
|
|
2532
|
+
*/
|
|
2533
|
+
private executeHookSafely;
|
|
2534
|
+
/**
|
|
2535
|
+
* Check if there are any hooks registered
|
|
2536
|
+
*/
|
|
2537
|
+
hasHooks(name: HookName): boolean;
|
|
2538
|
+
/**
|
|
2539
|
+
* Get hook count
|
|
2540
|
+
*/
|
|
2541
|
+
getHookCount(name?: HookName): number;
|
|
2542
|
+
/**
|
|
2543
|
+
* Clear all hooks and reset error tracking
|
|
2544
|
+
*/
|
|
2545
|
+
clear(): void;
|
|
2546
|
+
/**
|
|
2547
|
+
* Re-enable a disabled hook
|
|
2548
|
+
*/
|
|
2549
|
+
enableHook(hookKey: string): void;
|
|
2550
|
+
/**
|
|
2551
|
+
* Get list of disabled hooks
|
|
2552
|
+
*/
|
|
2553
|
+
getDisabledHooks(): string[];
|
|
2554
|
+
}
|
|
2555
|
+
|
|
2556
|
+
export { StreamEventType as $, type AgentContextNextGenConfig as A, type BeforeCompactionCallback as B, type ContextFeatures as C, type HookName as D, ExecutionContext as E, type FunctionToolDefinition as F, type ITokenEstimator as G, type HookConfig as H, type IContextStorage as I, type ToolCategoryScope as J, type CompactionContext as K, type LLMResponse as L, type MemoryEntry as M, type CompactionResult as N, type OutputItem as O, type PriorityCalculator as P, type StaleEntryInfo as Q, type PriorityContext as R, type SerializedContextState as S, type Tool as T, type MemoryIndex as U, type TaskStatusForMemory as V, type WorkingMemoryConfig as W, type WorkingMemoryAccess as X, type ContextStorageListOptions as Y, type ContextSessionSummary as Z, type TokenUsage as _, type MemoryScope as a, getToolCallDescription as a$, type TextGenerateOptions as a0, type ModelCapabilities as a1, MessageRole as a2, type AfterToolContext as a3, type AgentEventName as a4, type AgenticLoopEventName as a5, type AgenticLoopEvents as a6, type ApprovalResult as a7, type ApproveToolContext as a8, type BeforeToolContext as a9, type OversizedInputResult as aA, type PluginConfigs as aB, type ReasoningDeltaEvent as aC, type ReasoningDoneEvent as aD, type ReasoningItem as aE, type ResponseCompleteEvent as aF, type ResponseCreatedEvent as aG, type ResponseInProgressEvent as aH, type SimpleScope as aI, type TaskAwareScope as aJ, type ThinkingContent as aK, type ToolCallArgumentsDeltaEvent as aL, type ToolCallArgumentsDoneEvent as aM, type ToolCallStartEvent as aN, ToolCallState as aO, ToolCatalogRegistry as aP, type ToolCategoryDefinition as aQ, type ToolExecutionContext as aR, type ToolExecutionDoneEvent as aS, type ToolExecutionStartEvent as aT, type ToolModification as aU, type ToolResultContent as aV, type ToolUseContent as aW, calculateEntrySize as aX, defaultDescribeCall as aY, forPlan as aZ, forTasks as a_, type BuiltInTool as aa, CONTEXT_SESSION_FORMAT_VERSION as ab, type ToolRegistryEntry as ac, type CatalogToolEntry as ad, type CompactionItem as ae, type ConnectorCategoryInfo as af, ContentType as ag, DEFAULT_CONFIG as ah, DEFAULT_FEATURES as ai, DEFAULT_MEMORY_CONFIG as aj, type ErrorEvent as ak, type ExecutionConfig as al, type Hook as am, HookManager as an, type InputImageContent as ao, type InputTextContent as ap, type IterationCompleteEvent$1 as aq, type JSONSchema as ar, MEMORY_PRIORITY_VALUES as as, type MemoryEntryInput as at, type MemoryIndexEntry as au, type Message as av, type ModifyingHook as aw, type OutputTextContent as ax, type OutputTextDeltaEvent as ay, type OutputTextDoneEvent as az, type ToolFunction as b, isErrorEvent as b0, isOutputTextDelta as b1, isReasoningDelta as b2, isReasoningDone as b3, isResponseComplete as b4, isSimpleScope as b5, isStreamEvent as b6, isTaskAwareScope as b7, isTerminalMemoryStatus as b8, isToolCallArgumentsDelta as b9, isToolCallArgumentsDone as ba, isToolCallStart as bb, scopeEquals as bc, scopeMatches as bd, type ExecutionCompleteEvent as be, type ExecutionStartEvent as bf, type LLMRequestEvent as bg, type LLMResponseEvent as bh, type ToolCompleteEvent as bi, type ToolStartEvent as bj, type ToolContext as c, type ToolPermissionConfig as d, type ContextBudget as e, type ToolCall as f, type IContextPluginNextGen as g, type MemoryPriority as h, type MemoryTier as i, type ContextEvents as j, type AuthIdentity as k, type ICompactionStrategy as l, type InputItem as m, type Content as n, type PreparedContext as o, type ToolResult as p, type ConsolidationResult as q, type StoredContextSession as r, type ITextProvider as s, type ContextSessionMetadata as t, type StreamEvent as u, type HistoryMode as v, type AgentEvents as w, type AgentResponse as x, type ExecutionMetrics as y, type AuditEntry as z };
|