@everworker/oneringai 0.4.7 → 0.4.8

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/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { I as IConnectorRegistry, a as IConnectorAccessPolicy, C as ConnectorAccessContext, b as Connector, c as ConnectorConfig, d as ITokenStorage, e as IProvider, f as ConnectorFetchOptions, P as ProviderCapabilities, S as StoredToken$1, g as ConnectorAuth, h as ConnectorConfigResult } from './IProvider-CxDUGl6n.js';
2
2
  export { A as APIKeyConnectorAuth, D as DEFAULT_BASE_DELAY_MS, i as DEFAULT_CONNECTOR_TIMEOUT, j as DEFAULT_MAX_DELAY_MS, k as DEFAULT_MAX_RETRIES, l as DEFAULT_RETRYABLE_STATUSES, J as JWTConnectorAuth, O as OAuthConnectorAuth } from './IProvider-CxDUGl6n.js';
3
- import { C as ContextFeatures, M as MemoryEntry, a as MemoryScope, I as IContextStorage, T as Tool, b as ToolFunction, c as ToolContext, d as ToolPermissionConfig$1, e as ContextBudget$1, f as ToolCall, g as IContextPluginNextGen, W as WorkingMemoryConfig, P as PriorityCalculator, h as MemoryPriority, i as MemoryTier, j as ContextEvents, A as AgentContextNextGenConfig, k as AuthIdentity, l as ICompactionStrategy, B as BeforeCompactionCallback, m as InputItem, n as Content, o as PreparedContext, O as OutputItem, p as ToolResult, q as ConsolidationResult, S as SerializedContextState, r as StoredContextSession, s as ITextProvider, t as ContextSessionMetadata, F as FunctionToolDefinition, L as LLMResponse, u as StreamEvent, H as HookConfig, v as HistoryMode, w as AgentEvents, x as AgentResponse, E as ExecutionContext, y as ExecutionMetrics, z as AuditEntry, D as HookName, G as ITokenEstimator$1, J as ToolCategoryScope, K as CompactionContext, N as CompactionResult, Q as AudioChunkReadyEvent, R as StaleEntryInfo, U as PriorityContext, V as MemoryIndex, X as TaskStatusForMemory, Y as WorkingMemoryAccess, Z as ContextStorageListOptions, _ as ContextSessionSummary, $ as TokenUsage, a0 as StreamEventType, a1 as TextGenerateOptions, a2 as ModelCapabilities, a3 as MessageRole } from './index-Blci0FEd.js';
4
- export { a4 as AfterToolContext, a5 as AgentEventName, a6 as AgenticLoopEventName, a7 as AgenticLoopEvents, a8 as ApprovalResult, a9 as ApproveToolContext, aa as AudioChunkErrorEvent, ab as AudioStreamCompleteEvent, ac as BeforeToolContext, ad as BuiltInTool, ae as CONTEXT_SESSION_FORMAT_VERSION, af as CatalogRegistryEntry, ag as CatalogToolEntry, ah as CompactionItem, ai as ConnectorCategoryInfo, aj as ContentType, ak as DEFAULT_CONFIG, al as DEFAULT_FEATURES, am as DEFAULT_MEMORY_CONFIG, an as ErrorEvent, ao as ExecutionConfig, ap as Hook, aq as HookManager, ar as InputImageContent, as as InputTextContent, at as IterationCompleteEvent, au as JSONSchema, av as MEMORY_PRIORITY_VALUES, aw as MemoryEntryInput, ax as MemoryIndexEntry, ay as Message, az as ModifyingHook, aA as OutputTextContent, aB as OutputTextDeltaEvent, aC as OutputTextDoneEvent, aD as OversizedInputResult, aE as PluginConfigs, aF as ReasoningDeltaEvent, aG as ReasoningDoneEvent, aH as ReasoningItem, aI as ResponseCompleteEvent, aJ as ResponseCreatedEvent, aK as ResponseInProgressEvent, aL as SimpleScope, aM as TaskAwareScope, aN as ThinkingContent, aO as ToolCallArgumentsDeltaEvent, aP as ToolCallArgumentsDoneEvent, aQ as ToolCallStartEvent, aR as ToolCallState, aS as ToolCatalogRegistry, aT as ToolCategoryDefinition, aU as ToolExecutionContext, aV as ToolExecutionDoneEvent, aW as ToolExecutionStartEvent, aX as ToolModification, aY as ToolResultContent, aZ as ToolUseContent, a_ as calculateEntrySize, a$ as defaultDescribeCall, b0 as forPlan, b1 as forTasks, b2 as getToolCallDescription, b3 as isAudioChunkError, b4 as isAudioChunkReady, b5 as isAudioStreamComplete, b6 as isErrorEvent, b7 as isOutputTextDelta, b8 as isReasoningDelta, b9 as isReasoningDone, ba as isResponseComplete, bb as isSimpleScope, bc as isStreamEvent, bd as isTaskAwareScope, be as isTerminalMemoryStatus, bf as isToolCallArgumentsDelta, bg as isToolCallArgumentsDone, bh as isToolCallStart, bi as scopeEquals, bj as scopeMatches } from './index-Blci0FEd.js';
3
+ import { C as ContextFeatures, M as MemoryEntry, a as MemoryScope, I as IContextStorage, T as Tool, b as ToolFunction, c as ToolContext, d as ToolPermissionConfig$1, e as ContextBudget$1, f as ToolCall, g as IContextPluginNextGen, W as WorkingMemoryConfig, P as PriorityCalculator, h as MemoryPriority, i as MemoryTier, j as ContextEvents, A as AgentContextNextGenConfig, k as AuthIdentity, l as ICompactionStrategy, B as BeforeCompactionCallback, m as InputItem, n as Content, o as PreparedContext, O as OutputItem, p as ToolResult, q as IHistoryJournal, r as ConsolidationResult, S as SerializedContextState, s as StoredContextSession, t as ITextProvider, u as ContextSessionMetadata, F as FunctionToolDefinition, L as LLMResponse, v as StreamEvent, H as HookConfig, w as HistoryMode, x as AgentEvents, y as AgentResponse, E as ExecutionContext, z as ExecutionMetrics, D as AuditEntry, G as HookName, J as ITokenEstimator$1, K as ToolCategoryScope, N as CompactionContext, Q as CompactionResult, R as AudioChunkReadyEvent, U as ContextStorageListOptions, V as ContextSessionSummary, X as HistoryEntry, Y as HistoryReadOptions, Z as StaleEntryInfo, _ as PriorityContext, $ as MemoryIndex, a0 as TaskStatusForMemory, a1 as WorkingMemoryAccess, a2 as TokenUsage, a3 as StreamEventType, a4 as TextGenerateOptions, a5 as ModelCapabilities, a6 as MessageRole } from './index-13HQuxEB.js';
4
+ export { a7 as AfterToolContext, a8 as AgentEventName, a9 as AgenticLoopEventName, aa as AgenticLoopEvents, ab as ApprovalResult, ac as ApproveToolContext, ad as AudioChunkErrorEvent, ae as AudioStreamCompleteEvent, af as BeforeToolContext, ag as BuiltInTool, ah as CONTEXT_SESSION_FORMAT_VERSION, ai as CatalogRegistryEntry, aj as CatalogToolEntry, ak as CompactionItem, al as ConnectorCategoryInfo, am as ContentType, an as DEFAULT_CONFIG, ao as DEFAULT_FEATURES, ap as DEFAULT_MEMORY_CONFIG, aq as ErrorEvent, ar as ExecutionConfig, as as HistoryEntryType, at as Hook, au as HookManager, av as InputImageContent, aw as InputTextContent, ax as IterationCompleteEvent, ay as JSONSchema, az as MEMORY_PRIORITY_VALUES, aA as MemoryEntryInput, aB as MemoryIndexEntry, aC as Message, aD as ModifyingHook, aE as OutputTextContent, aF as OutputTextDeltaEvent, aG as OutputTextDoneEvent, aH as OversizedInputResult, aI as PluginConfigs, aJ as ReasoningDeltaEvent, aK as ReasoningDoneEvent, aL as ReasoningItem, aM as ResponseCompleteEvent, aN as ResponseCreatedEvent, aO as ResponseInProgressEvent, aP as SimpleScope, aQ as TaskAwareScope, aR as ThinkingContent, aS as ToolCallArgumentsDeltaEvent, aT as ToolCallArgumentsDoneEvent, aU as ToolCallStartEvent, aV as ToolCallState, aW as ToolCatalogRegistry, aX as ToolCategoryDefinition, aY as ToolExecutionContext, aZ as ToolExecutionDoneEvent, a_ as ToolExecutionStartEvent, a$ as ToolModification, b0 as ToolResultContent, b1 as ToolUseContent, b2 as calculateEntrySize, b3 as defaultDescribeCall, b4 as forPlan, b5 as forTasks, b6 as getToolCallDescription, b7 as isAudioChunkError, b8 as isAudioChunkReady, b9 as isAudioStreamComplete, ba as isErrorEvent, bb as isOutputTextDelta, bc as isReasoningDelta, bd as isReasoningDone, be as isResponseComplete, bf as isSimpleScope, bg as isStreamEvent, bh as isTaskAwareScope, bi as isTerminalMemoryStatus, bj as isToolCallArgumentsDelta, bk as isToolCallArgumentsDone, bl as isToolCallStart, bm as scopeEquals, bn as scopeMatches } from './index-13HQuxEB.js';
5
5
  import { EventEmitter } from 'eventemitter3';
6
6
  import { V as Vendor } from './Vendor-DYh_bzwo.js';
7
7
  export { a as VENDORS, i as isVendor } from './Vendor-DYh_bzwo.js';
@@ -1482,6 +1482,10 @@ declare class StorageRegistry {
1482
1482
  * Otherwise, calls `defaultFactory()`, caches the result, and returns it.
1483
1483
  */
1484
1484
  static resolve<K extends keyof StorageConfig>(key: K, defaultFactory: () => StorageConfig[K]): StorageConfig[K];
1485
+ /**
1486
+ * Remove a single storage backend.
1487
+ */
1488
+ static remove(key: keyof StorageConfig): boolean;
1485
1489
  /**
1486
1490
  * Check if a storage backend has been configured.
1487
1491
  */
@@ -1688,7 +1692,7 @@ declare class CircuitBreaker<T = any> extends EventEmitter<CircuitBreakerEvents>
1688
1692
  */
1689
1693
  private transitionTo;
1690
1694
  /**
1691
- * Remove failures outside the time window
1695
+ * Remove failures outside the time window and cap array size
1692
1696
  */
1693
1697
  private pruneOldFailures;
1694
1698
  /**
@@ -3107,6 +3111,20 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3107
3111
  private _cachedBudget;
3108
3112
  /** Callback for beforeCompaction hook (set by Agent) */
3109
3113
  private _beforeCompactionCallback;
3114
+ /**
3115
+ * Monotonically increasing turn counter for history journal.
3116
+ * A "turn" increments on each user message.
3117
+ */
3118
+ private _turnIndex;
3119
+ /**
3120
+ * Pre-sessionId history buffer.
3121
+ * Entries are buffered here until the first save() establishes a sessionId,
3122
+ * at which point the buffer is flushed to the journal.
3123
+ * No extra memory cost — these items are already in _conversation.
3124
+ */
3125
+ private _historyBuffer;
3126
+ /** Filter for journal entry types. When set, only matching types are journaled. */
3127
+ private readonly _journalFilter;
3110
3128
  /**
3111
3129
  * Create a new AgentContextNextGen instance.
3112
3130
  */
@@ -3261,6 +3279,14 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3261
3279
  * Get current input (read-only).
3262
3280
  */
3263
3281
  getCurrentInput(): ReadonlyArray<InputItem>;
3282
+ /**
3283
+ * Get the history journal (if storage supports it).
3284
+ *
3285
+ * The journal provides read access to full conversation history,
3286
+ * independent of context compaction. Returns null if storage is not
3287
+ * configured or doesn't support journaling.
3288
+ */
3289
+ get journal(): IHistoryJournal | null;
3264
3290
  /**
3265
3291
  * Get conversation length.
3266
3292
  */
@@ -3443,6 +3469,16 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3443
3469
  /**
3444
3470
  * Generate unique ID.
3445
3471
  */
3472
+ /**
3473
+ * Append items to the history journal.
3474
+ *
3475
+ * If a sessionId is established and storage supports journaling,
3476
+ * appends directly (fire-and-forget, non-blocking).
3477
+ * Otherwise, buffers entries until the first save().
3478
+ *
3479
+ * No extra memory cost for the buffer — items are already in _conversation.
3480
+ */
3481
+ private _journalAppend;
3446
3482
  private generateId;
3447
3483
  /**
3448
3484
  * Assert context is not destroyed.
@@ -4028,6 +4064,17 @@ interface AgentConfig$1 extends BaseAgentConfig {
4028
4064
  toolFailureMode?: 'fail' | 'continue';
4029
4065
  maxConsecutiveErrors?: number;
4030
4066
  };
4067
+ /** Configuration for retrying empty/incomplete LLM responses */
4068
+ emptyResponseRetry?: {
4069
+ /** Enable retry for empty responses (default: true) */
4070
+ enabled?: boolean;
4071
+ /** Max retry attempts (default: 2) */
4072
+ maxRetries?: number;
4073
+ /** Initial backoff delay ms (default: 1000) */
4074
+ initialDelayMs?: number;
4075
+ /** Max backoff delay ms (default: 5000) */
4076
+ maxDelayMs?: number;
4077
+ };
4031
4078
  }
4032
4079
  /**
4033
4080
  * Agent class - represents an AI assistant with tool calling capabilities
@@ -4043,6 +4090,7 @@ interface AgentConfig$1 extends BaseAgentConfig {
4043
4090
  declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDisposable {
4044
4091
  private hookManager;
4045
4092
  private executionContext;
4093
+ private _toolRegisteredListener;
4046
4094
  private _paused;
4047
4095
  private _cancelled;
4048
4096
  private _pausePromise;
@@ -8204,2099 +8252,2277 @@ declare function documentToContent(result: DocumentResult, options?: DocumentToC
8204
8252
  declare function readDocumentAsContent(source: DocumentSource | string, options?: DocumentReadOptions & DocumentToContentOptions): Promise<Content[]>;
8205
8253
 
8206
8254
  /**
8207
- * WorkingMemory class - manages indexed working memory for TaskAgent
8208
- *
8209
- * This is a GENERIC implementation that works across all agent types:
8210
- * - Basic Agent: Uses staticPriorityCalculator with simple scopes
8211
- * - TaskAgent: Uses taskAwarePriorityCalculator with task-aware scopes
8212
- * - UniversalAgent: Can switch calculators based on mode
8255
+ * Agent state entities for TaskAgent
8213
8256
  *
8214
- * The PriorityCalculator strategy pattern allows different agents to have
8215
- * different eviction behaviors without changing the core WorkingMemory logic.
8257
+ * Defines the full agent state needed for persistence and resume.
8216
8258
  */
8217
8259
 
8218
8260
  /**
8219
- * Serialized memory state for persistence
8261
+ * Agent execution status
8220
8262
  */
8221
- interface SerializedMemory {
8222
- /** Memory format version */
8223
- version: number;
8224
- /** Serialized memory entries */
8225
- entries: SerializedMemoryEntry[];
8263
+ type AgentStatus = 'idle' | 'running' | 'suspended' | 'completed' | 'failed' | 'cancelled';
8264
+ /**
8265
+ * Agent configuration (needed for resume)
8266
+ */
8267
+ interface AgentConfig {
8268
+ connectorName: string;
8269
+ model: string;
8270
+ temperature?: number;
8271
+ maxIterations?: number;
8272
+ toolNames: string[];
8226
8273
  }
8227
8274
  /**
8228
- * Serialized memory entry
8275
+ * Conversation message in history
8229
8276
  */
8230
- interface SerializedMemoryEntry {
8231
- key: string;
8232
- description: string;
8233
- value: unknown;
8234
- scope: MemoryScope;
8235
- sizeBytes: number;
8236
- basePriority?: MemoryPriority;
8237
- pinned?: boolean;
8277
+ interface ConversationMessage {
8278
+ role: 'user' | 'assistant' | 'system';
8279
+ content: string;
8280
+ timestamp: number;
8238
8281
  }
8239
8282
  /**
8240
- * Eviction strategy type
8283
+ * Agent execution metrics
8241
8284
  */
8242
- type EvictionStrategy = 'lru' | 'size';
8243
- interface WorkingMemoryEvents {
8244
- stored: {
8245
- key: string;
8246
- description: string;
8247
- scope: MemoryScope;
8248
- };
8249
- retrieved: {
8250
- key: string;
8251
- };
8252
- deleted: {
8253
- key: string;
8254
- };
8255
- evicted: {
8256
- keys: string[];
8257
- reason: 'lru' | 'size' | 'task_completed';
8258
- };
8259
- limit_warning: {
8260
- utilizationPercent: number;
8261
- };
8262
- stale_entries: {
8263
- entries: StaleEntryInfo[];
8264
- };
8285
+ interface AgentMetrics {
8286
+ totalLLMCalls: number;
8287
+ totalToolCalls: number;
8288
+ totalTokensUsed: number;
8289
+ totalCost: number;
8265
8290
  }
8266
8291
  /**
8267
- * WorkingMemory manages the agent's indexed working memory.
8268
- *
8269
- * Features:
8270
- * - Store/retrieve with descriptions for index
8271
- * - Scoped memory (simple or task-aware)
8272
- * - Priority-based eviction (respects pinned, priority, then LRU)
8273
- * - Pluggable priority calculation via PriorityCalculator strategy
8274
- * - Task completion detection and stale entry notification
8275
- * - Event emission for monitoring
8292
+ * Full agent state - everything needed to resume
8276
8293
  */
8277
- declare class WorkingMemory extends EventEmitter<WorkingMemoryEvents> implements IDisposable {
8278
- private storage;
8279
- private config;
8280
- private priorityCalculator;
8281
- private priorityContext;
8282
- private _isDestroyed;
8283
- /**
8284
- * Create a WorkingMemory instance
8285
- *
8286
- * @param storage - Storage backend for memory entries
8287
- * @param config - Memory configuration (limits, etc.)
8288
- * @param priorityCalculator - Strategy for computing effective priority (default: static)
8289
- */
8290
- constructor(storage: IMemoryStorage, config?: WorkingMemoryConfig, priorityCalculator?: PriorityCalculator);
8291
- /**
8292
- * Set the priority calculator (for switching strategies at runtime)
8293
- */
8294
- setPriorityCalculator(calculator: PriorityCalculator): void;
8295
- /**
8296
- * Update priority context (e.g., task states for TaskAgent)
8297
- */
8298
- setPriorityContext(context: PriorityContext): void;
8294
+ interface AgentState {
8295
+ id: string;
8296
+ status: AgentStatus;
8297
+ /** Configuration */
8298
+ config: AgentConfig;
8299
+ /** Current plan */
8300
+ plan: Plan;
8301
+ /** Working memory reference */
8302
+ memoryId: string;
8303
+ /** Conversation history (for context continuity) */
8304
+ conversationHistory: ConversationMessage[];
8305
+ /** Timestamps */
8306
+ createdAt: number;
8307
+ startedAt?: number;
8308
+ suspendedAt?: number;
8309
+ completedAt?: number;
8310
+ lastActivityAt: number;
8311
+ /** Metrics */
8312
+ metrics: AgentMetrics;
8313
+ }
8314
+
8315
+ /**
8316
+ * Plan storage interface for plan persistence.
8317
+ * Implement for long-running agent support.
8318
+ */
8319
+
8320
+ interface IPlanStorage {
8299
8321
  /**
8300
- * Get the current priority context
8322
+ * Save or update a plan
8301
8323
  */
8302
- getPriorityContext(): PriorityContext;
8324
+ savePlan(plan: Plan): Promise<void>;
8303
8325
  /**
8304
- * Compute effective priority for an entry using the current calculator
8326
+ * Get plan by ID
8305
8327
  */
8306
- private computeEffectivePriority;
8328
+ getPlan(planId: string): Promise<Plan | undefined>;
8307
8329
  /**
8308
- * Get all entries with their computed effective priorities
8309
- * This is a performance optimization to avoid repeated getAll() + map() calls
8330
+ * Update a specific task within a plan
8310
8331
  */
8311
- private getEntriesWithPriority;
8332
+ updateTask(planId: string, task: Task): Promise<void>;
8312
8333
  /**
8313
- * Get evictable entries sorted by eviction priority
8314
- * Filters out pinned and critical entries, sorts by priority then by strategy
8334
+ * Add a new task to a plan (for dynamic task creation)
8315
8335
  */
8316
- private getEvictableEntries;
8336
+ addTask(planId: string, task: Task): Promise<void>;
8317
8337
  /**
8318
- * Store a value in working memory
8319
- *
8320
- * @param key - Unique key for the entry
8321
- * @param description - Short description for the index (max 150 chars)
8322
- * @param value - The data to store
8323
- * @param options - Optional scope, priority, and pinned settings
8338
+ * Delete a plan
8324
8339
  */
8325
- store(key: string, description: string, value: unknown, options?: {
8326
- scope?: MemoryScope;
8327
- priority?: MemoryPriority;
8328
- pinned?: boolean;
8329
- }): Promise<void>;
8340
+ deletePlan(planId: string): Promise<void>;
8330
8341
  /**
8331
- * Enforce the maxIndexEntries limit by evicting excess entries
8332
- * Only evicts if entry count exceeds the configured limit
8342
+ * List plans by status
8333
8343
  */
8334
- private enforceEntryCountLimit;
8344
+ listPlans(filter?: {
8345
+ status?: PlanStatus[];
8346
+ }): Promise<Plan[]>;
8335
8347
  /**
8336
- * Get the configured max index entries limit
8348
+ * Find plans with tasks waiting on a specific webhook
8337
8349
  */
8338
- getMaxIndexEntries(): number | undefined;
8350
+ findByWebhookId(webhookId: string): Promise<{
8351
+ plan: Plan;
8352
+ task: Task;
8353
+ } | undefined>;
8354
+ }
8355
+
8356
+ /**
8357
+ * Agent state storage interface for full agent state persistence.
8358
+ * Required for resume capability.
8359
+ */
8360
+
8361
+ interface IAgentStateStorage {
8339
8362
  /**
8340
- * Store a value scoped to specific tasks
8341
- * Convenience method for task-aware memory
8363
+ * Save agent state
8342
8364
  */
8343
- storeForTasks(key: string, description: string, value: unknown, taskIds: string[], options?: {
8344
- priority?: MemoryPriority;
8345
- pinned?: boolean;
8346
- }): Promise<void>;
8365
+ save(state: AgentState): Promise<void>;
8347
8366
  /**
8348
- * Store a value scoped to the entire plan
8349
- * Convenience method for plan-scoped memory
8367
+ * Load agent state
8350
8368
  */
8351
- storeForPlan(key: string, description: string, value: unknown, options?: {
8352
- priority?: MemoryPriority;
8353
- pinned?: boolean;
8354
- }): Promise<void>;
8369
+ load(agentId: string): Promise<AgentState | undefined>;
8355
8370
  /**
8356
- * Retrieve a value from working memory
8357
- *
8358
- * Note: Access stats update is not strictly atomic. Under very high concurrency,
8359
- * accessCount may be slightly inaccurate. This is acceptable for memory management
8360
- * purposes where exact counts are not critical.
8371
+ * Delete agent state
8361
8372
  */
8362
- retrieve(key: string): Promise<unknown>;
8373
+ delete(agentId: string): Promise<void>;
8363
8374
  /**
8364
- * Retrieve multiple values
8375
+ * List agents by status
8365
8376
  */
8366
- retrieveMany(keys: string[]): Promise<Record<string, unknown>>;
8377
+ list(filter?: {
8378
+ status?: AgentStatus[];
8379
+ }): Promise<AgentState[]>;
8367
8380
  /**
8368
- * Delete a value from working memory
8381
+ * Update specific fields (partial update for efficiency)
8369
8382
  */
8383
+ patch(agentId: string, updates: Partial<AgentState>): Promise<void>;
8384
+ }
8385
+
8386
+ /**
8387
+ * In-memory storage implementations (default, non-persistent)
8388
+ */
8389
+
8390
+ /**
8391
+ * In-memory implementation of IMemoryStorage
8392
+ */
8393
+ declare class InMemoryStorage implements IMemoryStorage {
8394
+ private store;
8395
+ get(key: string): Promise<MemoryEntry | undefined>;
8396
+ set(key: string, entry: MemoryEntry): Promise<void>;
8370
8397
  delete(key: string): Promise<void>;
8371
- /**
8372
- * Check if key exists
8373
- */
8374
8398
  has(key: string): Promise<boolean>;
8399
+ getAll(): Promise<MemoryEntry[]>;
8400
+ getByScope(scope: MemoryScope): Promise<MemoryEntry[]>;
8401
+ clearScope(scope: MemoryScope): Promise<void>;
8402
+ clear(): Promise<void>;
8403
+ getTotalSize(): Promise<number>;
8404
+ }
8405
+ /**
8406
+ * In-memory implementation of IPlanStorage
8407
+ */
8408
+ declare class InMemoryPlanStorage implements IPlanStorage {
8409
+ private plans;
8410
+ savePlan(plan: Plan): Promise<void>;
8411
+ getPlan(planId: string): Promise<Plan | undefined>;
8412
+ updateTask(planId: string, task: Task): Promise<void>;
8413
+ addTask(planId: string, task: Task): Promise<void>;
8414
+ deletePlan(planId: string): Promise<void>;
8415
+ listPlans(filter?: {
8416
+ status?: PlanStatus[];
8417
+ }): Promise<Plan[]>;
8418
+ findByWebhookId(webhookId: string): Promise<{
8419
+ plan: Plan;
8420
+ task: Task;
8421
+ } | undefined>;
8422
+ }
8423
+ /**
8424
+ * In-memory implementation of IAgentStateStorage
8425
+ */
8426
+ declare class InMemoryAgentStateStorage implements IAgentStateStorage {
8427
+ private agents;
8428
+ save(state: AgentState): Promise<void>;
8429
+ load(agentId: string): Promise<AgentState | undefined>;
8430
+ delete(agentId: string): Promise<void>;
8431
+ list(filter?: {
8432
+ status?: AgentStatus[];
8433
+ }): Promise<AgentState[]>;
8434
+ patch(agentId: string, updates: Partial<AgentState>): Promise<void>;
8435
+ }
8436
+ /**
8437
+ * Unified agent storage interface
8438
+ */
8439
+ interface IAgentStorage {
8440
+ memory: IMemoryStorage;
8441
+ plan: IPlanStorage;
8442
+ agent: IAgentStateStorage;
8443
+ }
8444
+ /**
8445
+ * Create agent storage with defaults
8446
+ */
8447
+ declare function createAgentStorage(options?: {
8448
+ memory?: IMemoryStorage;
8449
+ plan?: IPlanStorage;
8450
+ agent?: IAgentStateStorage;
8451
+ }): IAgentStorage;
8452
+
8453
+ /**
8454
+ * FilePersistentInstructionsStorage - File-based storage for persistent instructions
8455
+ *
8456
+ * Stores custom agent instructions as a JSON file on disk.
8457
+ * Path: ~/.oneringai/agents/<agentId>/custom_instructions.json
8458
+ * Windows: %APPDATA%/oneringai/agents/<agentId>/custom_instructions.json
8459
+ *
8460
+ * Features:
8461
+ * - Cross-platform path handling
8462
+ * - Safe agent ID sanitization
8463
+ * - Atomic file operations
8464
+ * - Automatic directory creation
8465
+ * - Legacy .md file migration
8466
+ */
8467
+
8468
+ /**
8469
+ * Configuration for FilePersistentInstructionsStorage
8470
+ */
8471
+ interface FilePersistentInstructionsStorageConfig {
8472
+ /** Agent ID (used to create unique storage path) */
8473
+ agentId: string;
8474
+ /** Override the base directory (default: ~/.oneringai/agents) */
8475
+ baseDirectory?: string;
8476
+ /** Override the filename (default: custom_instructions.json) */
8477
+ filename?: string;
8478
+ }
8479
+ /**
8480
+ * File-based storage for persistent agent instructions
8481
+ */
8482
+ declare class FilePersistentInstructionsStorage implements IPersistentInstructionsStorage {
8483
+ private readonly directory;
8484
+ private readonly filePath;
8485
+ private readonly legacyFilePath;
8486
+ private readonly agentId;
8487
+ constructor(config: FilePersistentInstructionsStorageConfig);
8375
8488
  /**
8376
- * Promote an entry to persistent scope
8377
- * Works with both simple and task-aware scopes
8378
- */
8379
- persist(key: string): Promise<void>;
8380
- /**
8381
- * Pin an entry (never evicted)
8382
- */
8383
- pin(key: string): Promise<void>;
8384
- /**
8385
- * Unpin an entry
8489
+ * Load instruction entries from file.
8490
+ * Falls back to legacy .md file migration if JSON not found.
8386
8491
  */
8387
- unpin(key: string, newPriority?: MemoryPriority): Promise<void>;
8492
+ load(): Promise<InstructionEntry[] | null>;
8388
8493
  /**
8389
- * Set the base priority of an entry
8494
+ * Save instruction entries to file as JSON.
8495
+ * Creates directory if it doesn't exist.
8496
+ * Cleans up legacy .md file if present.
8390
8497
  */
8391
- setPriority(key: string, priority: MemoryPriority): Promise<void>;
8498
+ save(entries: InstructionEntry[]): Promise<void>;
8392
8499
  /**
8393
- * Update the scope of an entry without re-storing the value
8500
+ * Delete instructions file (and legacy .md if exists)
8394
8501
  */
8395
- updateScope(key: string, scope: MemoryScope): Promise<void>;
8502
+ delete(): Promise<void>;
8396
8503
  /**
8397
- * Add task IDs to an existing task-scoped entry
8398
- * If entry is not task-scoped, converts it to task-scoped
8504
+ * Check if instructions file exists (JSON or legacy .md)
8399
8505
  */
8400
- addTasksToScope(key: string, taskIds: string[]): Promise<void>;
8506
+ exists(): Promise<boolean>;
8401
8507
  /**
8402
- * Clear all entries of a specific scope
8508
+ * Get the file path (for display/debugging)
8403
8509
  */
8404
- clearScope(scope: MemoryScope): Promise<void>;
8510
+ getPath(): string;
8405
8511
  /**
8406
- * Clear all entries
8512
+ * Get the agent ID
8407
8513
  */
8408
- clear(): Promise<void>;
8514
+ getAgentId(): string;
8409
8515
  /**
8410
- * Get memory index with computed effective priorities
8411
- * Respects maxIndexEntries limit for context display
8516
+ * Ensure the directory exists
8412
8517
  */
8413
- getIndex(): Promise<MemoryIndex>;
8518
+ private ensureDirectory;
8414
8519
  /**
8415
- * Format index for context injection
8520
+ * Remove legacy .md file if it exists
8416
8521
  */
8417
- formatIndex(): Promise<string>;
8522
+ private removeLegacyFile;
8523
+ }
8524
+
8525
+ /**
8526
+ * FileContextStorage - File-based storage for AgentContext session persistence
8527
+ *
8528
+ * Stores context sessions as JSON files on disk.
8529
+ * Path: ~/.oneringai/agents/<agentId>/sessions/<sessionId>.json
8530
+ * Windows: %APPDATA%/oneringai/agents/<agentId>/sessions/<sessionId>.json
8531
+ *
8532
+ * Features:
8533
+ * - Cross-platform path handling
8534
+ * - Safe session ID sanitization
8535
+ * - Atomic file operations (write to temp, then rename)
8536
+ * - Automatic directory creation
8537
+ * - Index file for fast listing
8538
+ */
8539
+
8540
+ /**
8541
+ * Configuration for FileContextStorage
8542
+ */
8543
+ interface FileContextStorageConfig {
8544
+ /** Agent ID (used to create unique storage path) */
8545
+ agentId: string;
8546
+ /** Override the base directory (default: ~/.oneringai/agents) */
8547
+ baseDirectory?: string;
8548
+ /** Pretty-print JSON (default: true for debugging, false in production) */
8549
+ prettyPrint?: boolean;
8550
+ }
8551
+ /**
8552
+ * File-based storage for AgentContext session persistence
8553
+ */
8554
+ declare class FileContextStorage implements IContextStorage {
8555
+ private readonly agentId;
8556
+ private readonly sessionsDirectory;
8557
+ private readonly indexPath;
8558
+ private readonly prettyPrint;
8559
+ private index;
8560
+ /** History journal companion — appends full conversation history as JSONL */
8561
+ readonly journal: IHistoryJournal;
8562
+ constructor(config: FileContextStorageConfig);
8418
8563
  /**
8419
- * Evict entries using specified strategy
8420
- *
8421
- * Eviction order:
8422
- * 1. Never evict pinned entries
8423
- * 2. Evict low priority first, then normal, then high (never critical)
8424
- * 3. Within same priority, use strategy (LRU or largest size)
8425
- *
8426
- * @param count - Number of entries to evict
8427
- * @param strategy - Eviction strategy ('lru' or 'size')
8428
- * @returns Keys of evicted entries
8564
+ * Save context state to a session file
8429
8565
  */
8430
- evict(count: number, strategy?: EvictionStrategy): Promise<string[]>;
8566
+ save(sessionId: string, state: SerializedContextState, metadata?: ContextSessionMetadata): Promise<void>;
8431
8567
  /**
8432
- * Evict entries using priority-aware LRU algorithm
8433
- * @deprecated Use evict(count, 'lru') instead
8568
+ * Load context state from a session file
8434
8569
  */
8435
- evictLRU(count: number): Promise<string[]>;
8570
+ load(sessionId: string): Promise<StoredContextSession | null>;
8436
8571
  /**
8437
- * Evict largest entries first (priority-aware)
8438
- * @deprecated Use evict(count, 'size') instead
8572
+ * Delete a session
8439
8573
  */
8440
- evictBySize(count: number): Promise<string[]>;
8574
+ delete(sessionId: string): Promise<void>;
8441
8575
  /**
8442
- * Handle task completion - detect and notify about stale entries
8443
- *
8444
- * Call this when a task completes to:
8445
- * 1. Update priority context with new task state
8446
- * 2. Detect entries that became stale
8447
- * 3. Emit event to notify LLM about stale entries
8448
- *
8449
- * @param taskId - The completed task ID
8450
- * @param taskStates - Current task states map
8451
- * @returns Information about stale entries
8576
+ * Check if a session exists
8452
8577
  */
8453
- onTaskComplete(taskId: string, taskStates: Map<string, TaskStatusForMemory>): Promise<StaleEntryInfo[]>;
8578
+ exists(sessionId: string): Promise<boolean>;
8454
8579
  /**
8455
- * Evict entries for completed tasks
8456
- *
8457
- * Removes entries that were scoped only to completed tasks.
8458
- * Use after onTaskComplete() if you want automatic cleanup.
8459
- *
8460
- * @param taskStates - Current task states map
8461
- * @returns Keys of evicted entries
8580
+ * List all sessions (summaries only)
8462
8581
  */
8463
- evictCompletedTaskEntries(taskStates: Map<string, TaskStatusForMemory>): Promise<string[]>;
8582
+ list(options?: ContextStorageListOptions): Promise<ContextSessionSummary[]>;
8464
8583
  /**
8465
- * Get limited memory access for tools
8466
- *
8467
- * This provides a simplified interface for tools to interact with memory
8468
- * without exposing the full WorkingMemory API.
8584
+ * Update session metadata without loading full state
8469
8585
  */
8470
- getAccess(): WorkingMemoryAccess;
8586
+ updateMetadata(sessionId: string, metadata: Partial<ContextSessionMetadata>): Promise<void>;
8471
8587
  /**
8472
- * Store raw data (low priority, first to be evicted)
8473
- *
8474
- * Use this for original/unprocessed data that should be summarized.
8475
- * Raw data is automatically evicted first when memory pressure is high.
8476
- *
8477
- * @param key - Key without tier prefix (prefix is added automatically)
8478
- * @param description - Brief description for the index
8479
- * @param value - The raw data to store
8480
- * @param options - Optional scope and task IDs
8588
+ * Get the storage path (for display/debugging)
8589
+ * @deprecated Use getLocation() instead
8481
8590
  */
8482
- storeRaw(key: string, description: string, value: unknown, options?: {
8483
- taskIds?: string[];
8484
- scope?: MemoryScope;
8485
- }): Promise<void>;
8591
+ getPath(): string;
8486
8592
  /**
8487
- * Store a summary derived from raw data (normal priority)
8488
- *
8489
- * Use this for processed/summarized data that extracts key information.
8490
- * Links back to source data for cleanup tracking.
8491
- *
8492
- * @param key - Key without tier prefix (prefix is added automatically)
8493
- * @param description - Brief description for the index
8494
- * @param value - The summary data
8495
- * @param derivedFrom - Key(s) this summary was derived from
8496
- * @param options - Optional scope and task IDs
8593
+ * Get a human-readable storage location string (for display/debugging)
8497
8594
  */
8498
- storeSummary(key: string, description: string, value: unknown, derivedFrom: string | string[], options?: {
8499
- taskIds?: string[];
8500
- scope?: MemoryScope;
8501
- }): Promise<void>;
8595
+ getLocation(): string;
8502
8596
  /**
8503
- * Store final findings (high priority, kept longest)
8504
- *
8505
- * Use this for conclusions, insights, or final results that should be preserved.
8506
- * These are the last to be evicted and typically span the entire plan.
8507
- *
8508
- * @param key - Key without tier prefix (prefix is added automatically)
8509
- * @param description - Brief description for the index
8510
- * @param value - The findings data
8511
- * @param derivedFrom - Optional key(s) these findings were derived from
8512
- * @param options - Optional scope, task IDs, and pinned flag
8597
+ * Get the agent ID
8513
8598
  */
8514
- storeFindings(key: string, description: string, value: unknown, _derivedFrom?: string | string[], options?: {
8515
- taskIds?: string[];
8516
- scope?: MemoryScope;
8517
- pinned?: boolean;
8518
- }): Promise<void>;
8599
+ getAgentId(): string;
8519
8600
  /**
8520
- * Clean up raw data after summary/findings are created
8521
- *
8522
- * Call this after creating summaries to free up memory used by raw data.
8523
- * Only deletes entries in the 'raw' tier.
8524
- *
8525
- * @param derivedFromKeys - Keys to delete (typically from derivedFrom metadata)
8526
- * @returns Number of entries deleted
8601
+ * Rebuild the index by scanning all session files
8602
+ * Useful for recovery or migration
8527
8603
  */
8528
- cleanupRawData(derivedFromKeys: string[]): Promise<number>;
8604
+ rebuildIndex(): Promise<void>;
8605
+ private getFilePath;
8606
+ private ensureDirectory;
8607
+ private loadRaw;
8608
+ private loadIndex;
8609
+ private saveIndex;
8610
+ private updateIndex;
8611
+ private removeFromIndex;
8612
+ private storedToIndexEntry;
8613
+ }
8614
+ /**
8615
+ * Create a FileContextStorage for the given agent
8616
+ *
8617
+ * @param agentId - Agent ID
8618
+ * @param options - Optional configuration
8619
+ * @returns FileContextStorage instance
8620
+ *
8621
+ * @example
8622
+ * ```typescript
8623
+ * const storage = createFileContextStorage('my-agent');
8624
+ * const ctx = AgentContext.create({
8625
+ * model: 'gpt-4',
8626
+ * storage,
8627
+ * });
8628
+ *
8629
+ * // Save session
8630
+ * await ctx.save('session-001', { title: 'My Session' });
8631
+ *
8632
+ * // Load session
8633
+ * await ctx.load('session-001');
8634
+ * ```
8635
+ */
8636
+ declare function createFileContextStorage(agentId: string, options?: Omit<FileContextStorageConfig, 'agentId'>): FileContextStorage;
8637
+
8638
+ /**
8639
+ * FileHistoryJournal - JSONL-based append-only conversation history journal
8640
+ *
8641
+ * Stores history entries as newline-delimited JSON (JSONL) files alongside
8642
+ * session state files. Each line is a self-contained JSON object representing
8643
+ * one HistoryEntry.
8644
+ *
8645
+ * Path: <sessionsDirectory>/<sessionId>.history.jsonl
8646
+ *
8647
+ * Design:
8648
+ * - Append-only writes (fast, no rewrite of existing data)
8649
+ * - Line-based reads with filtering (no need to parse entire file for counts)
8650
+ * - Streaming support via async iteration
8651
+ * - Automatic directory creation on first write
8652
+ *
8653
+ * @example
8654
+ * ```typescript
8655
+ * const journal = new FileHistoryJournal('/path/to/sessions');
8656
+ *
8657
+ * // Append (fast, append-only)
8658
+ * await journal.append('session-1', [{ timestamp: Date.now(), type: 'user', item: msg, turnIndex: 0 }]);
8659
+ *
8660
+ * // Read with filtering
8661
+ * const entries = await journal.read('session-1', { limit: 50, types: ['user', 'assistant'] });
8662
+ *
8663
+ * // Stream large histories
8664
+ * for await (const entry of journal.stream!('session-1')) {
8665
+ * console.log(entry.type, entry.turnIndex);
8666
+ * }
8667
+ * ```
8668
+ */
8669
+
8670
+ /**
8671
+ * File-based history journal using JSONL format.
8672
+ */
8673
+ declare class FileHistoryJournal implements IHistoryJournal {
8674
+ private readonly sessionsDirectory;
8675
+ private directoryEnsured;
8676
+ constructor(sessionsDirectory: string);
8529
8677
  /**
8530
- * Get all entries by tier
8531
- *
8532
- * @param tier - The tier to filter by
8533
- * @returns Array of entries in that tier
8678
+ * Get the JSONL file path for a session's history.
8534
8679
  */
8535
- getByTier(tier: MemoryTier): Promise<MemoryEntry[]>;
8680
+ private journalPath;
8536
8681
  /**
8537
- * Promote an entry to a higher tier
8538
- *
8539
- * Changes the key prefix and updates priority.
8540
- * Use this when raw data becomes more valuable (e.g., frequently accessed).
8682
+ * Ensure the sessions directory exists (lazy, once per instance).
8683
+ */
8684
+ private ensureDirectory;
8685
+ /**
8686
+ * Append entries to the journal file.
8541
8687
  *
8542
- * @param key - Current key (with tier prefix)
8543
- * @param toTier - Target tier to promote to
8544
- * @returns New key with updated prefix
8688
+ * Uses fs.appendFile which is atomic for small writes on most filesystems.
8689
+ * Each entry is serialized as a single JSON line.
8545
8690
  */
8546
- promote(key: string, toTier: MemoryTier): Promise<string>;
8691
+ append(sessionId: string, entries: HistoryEntry[]): Promise<void>;
8547
8692
  /**
8548
- * Get tier statistics
8693
+ * Read history entries with optional filtering and pagination.
8549
8694
  *
8550
- * @returns Count and size by tier
8695
+ * For large files, prefer stream() with pagination.
8551
8696
  */
8552
- getTierStats(): Promise<Record<MemoryTier, {
8553
- count: number;
8554
- sizeBytes: number;
8555
- }>>;
8697
+ read(sessionId: string, options?: HistoryReadOptions): Promise<HistoryEntry[]>;
8556
8698
  /**
8557
- * Get statistics about memory usage
8699
+ * Count entries without fully parsing the file.
8700
+ *
8701
+ * Counts non-empty lines in the JSONL file.
8558
8702
  */
8559
- getStats(): Promise<{
8560
- totalEntries: number;
8561
- totalSizeBytes: number;
8562
- utilizationPercent: number;
8563
- byPriority: Record<MemoryPriority, number>;
8564
- pinnedCount: number;
8565
- }>;
8703
+ count(sessionId: string): Promise<number>;
8566
8704
  /**
8567
- * Get the configured memory limit
8705
+ * Delete the journal file for a session.
8568
8706
  */
8569
- getLimit(): number;
8707
+ clear(sessionId: string): Promise<void>;
8570
8708
  /**
8571
- * Check if the WorkingMemory instance has been destroyed
8709
+ * Stream history entries line-by-line using readline.
8710
+ *
8711
+ * Memory-efficient for large histories — only one entry in memory at a time.
8572
8712
  */
8573
- get isDestroyed(): boolean;
8713
+ stream(sessionId: string, options?: HistoryReadOptions): AsyncIterable<HistoryEntry>;
8574
8714
  /**
8575
- * Destroy the WorkingMemory instance
8576
- * Removes all event listeners and clears internal state
8715
+ * Get the file path for a session's journal (for debugging).
8577
8716
  */
8578
- destroy(): void;
8717
+ getLocation(sessionId: string): string;
8579
8718
  /**
8580
- * Serialize all memory entries for persistence
8581
- *
8582
- * Returns a serializable representation of all memory entries
8583
- * that can be saved to storage and restored later.
8584
- *
8585
- * @returns Serialized memory state
8719
+ * Apply non-pagination filters to an array of entries.
8586
8720
  */
8587
- serialize(): Promise<SerializedMemory>;
8721
+ private applyFilters;
8588
8722
  /**
8589
- * Restore memory entries from serialized state
8590
- *
8591
- * Clears existing memory and repopulates from the serialized state.
8592
- * Timestamps are reset to current time.
8593
- *
8594
- * @param state - Previously serialized memory state
8723
+ * Check if a single entry matches the filter criteria.
8595
8724
  */
8596
- restore(state: SerializedMemory): Promise<void>;
8725
+ private matchesFilters;
8597
8726
  }
8598
8727
 
8599
8728
  /**
8600
- * ExternalDependencyHandler - handles external dependencies
8729
+ * FileAgentDefinitionStorage - File-based storage for agent definitions
8730
+ *
8731
+ * Stores agent definitions as JSON files on disk.
8732
+ * Path: ~/.oneringai/agents/<agentId>/definition.json
8733
+ * Windows: %APPDATA%/oneringai/agents/<agentId>/definition.json
8734
+ *
8735
+ * Features:
8736
+ * - Cross-platform path handling
8737
+ * - Safe agent ID sanitization
8738
+ * - Atomic file operations
8739
+ * - Automatic directory creation
8740
+ * - Index file for fast listing
8601
8741
  */
8602
8742
 
8603
- interface ExternalDependencyEvents {
8604
- 'webhook:received': {
8605
- webhookId: string;
8606
- data: unknown;
8607
- };
8608
- 'poll:success': {
8609
- taskId: string;
8610
- data: unknown;
8611
- };
8612
- 'poll:timeout': {
8613
- taskId: string;
8614
- };
8615
- 'scheduled:triggered': {
8616
- taskId: string;
8617
- };
8618
- 'manual:completed': {
8619
- taskId: string;
8620
- data: unknown;
8621
- };
8743
+ /**
8744
+ * Configuration for FileAgentDefinitionStorage
8745
+ */
8746
+ interface FileAgentDefinitionStorageConfig {
8747
+ /** Override the base directory (default: ~/.oneringai/agents) */
8748
+ baseDirectory?: string;
8749
+ /** Pretty-print JSON (default: true) */
8750
+ prettyPrint?: boolean;
8622
8751
  }
8623
8752
  /**
8624
- * Handles external task dependencies
8753
+ * File-based storage for agent definitions
8625
8754
  */
8626
- declare class ExternalDependencyHandler extends EventEmitter<ExternalDependencyEvents> {
8627
- private activePolls;
8628
- private activeScheduled;
8629
- private cancelledPolls;
8630
- private tools;
8631
- constructor(tools?: ToolFunction[]);
8755
+ declare class FileAgentDefinitionStorage implements IAgentDefinitionStorage {
8756
+ private readonly baseDirectory;
8757
+ private readonly indexPath;
8758
+ private readonly prettyPrint;
8759
+ private index;
8760
+ constructor(config?: FileAgentDefinitionStorageConfig);
8632
8761
  /**
8633
- * Start handling a task's external dependency
8762
+ * Save an agent definition
8634
8763
  */
8635
- startWaiting(task: Task): Promise<void>;
8764
+ save(definition: StoredAgentDefinition): Promise<void>;
8636
8765
  /**
8637
- * Stop waiting on a task's external dependency
8766
+ * Load an agent definition
8638
8767
  */
8639
- stopWaiting(task: Task): void;
8768
+ load(agentId: string): Promise<StoredAgentDefinition | null>;
8640
8769
  /**
8641
- * Trigger a webhook
8770
+ * Delete an agent definition
8642
8771
  */
8643
- triggerWebhook(webhookId: string, data: unknown): Promise<void>;
8772
+ delete(agentId: string): Promise<void>;
8644
8773
  /**
8645
- * Complete a manual task
8774
+ * Check if an agent definition exists
8646
8775
  */
8647
- completeManual(taskId: string, data: unknown): Promise<void>;
8776
+ exists(agentId: string): Promise<boolean>;
8648
8777
  /**
8649
- * Start polling for a task with exponential backoff
8778
+ * List all agent definitions
8650
8779
  */
8651
- private startPolling;
8780
+ list(options?: AgentDefinitionListOptions): Promise<AgentDefinitionSummary[]>;
8652
8781
  /**
8653
- * Schedule a task to trigger at a specific time
8782
+ * Update metadata without loading full definition
8654
8783
  */
8655
- private scheduleTask;
8784
+ updateMetadata(agentId: string, metadata: Partial<AgentDefinitionMetadata>): Promise<void>;
8656
8785
  /**
8657
- * Cleanup all active dependencies
8786
+ * Get storage path
8658
8787
  */
8659
- cleanup(): void;
8788
+ getPath(): string;
8660
8789
  /**
8661
- * Update available tools
8790
+ * Rebuild the index by scanning all agent directories
8662
8791
  */
8663
- updateTools(tools: ToolFunction[]): void;
8792
+ rebuildIndex(): Promise<void>;
8793
+ private ensureDirectory;
8794
+ private loadRaw;
8795
+ private loadIndex;
8796
+ private saveIndex;
8797
+ private updateIndex;
8798
+ private removeFromIndex;
8799
+ private definitionToIndexEntry;
8664
8800
  }
8801
+ /**
8802
+ * Create a FileAgentDefinitionStorage with default configuration
8803
+ */
8804
+ declare function createFileAgentDefinitionStorage(config?: FileAgentDefinitionStorageConfig): FileAgentDefinitionStorage;
8665
8805
 
8666
8806
  /**
8667
- * Agent state entities for TaskAgent
8807
+ * FileMediaStorage - File-based media storage implementation
8668
8808
  *
8669
- * Defines the full agent state needed for persistence and resume.
8809
+ * Saves generated media to a configurable directory on the local filesystem.
8810
+ * Default output directory: `os.tmpdir()/oneringai-media/`
8670
8811
  */
8671
8812
 
8813
+ interface FileMediaStorageConfig {
8814
+ /** Directory to store media files. Defaults to `os.tmpdir()/oneringai-media/` */
8815
+ outputDir?: string;
8816
+ }
8817
+ declare class FileMediaStorage implements IMediaStorage {
8818
+ private outputDir;
8819
+ private initialized;
8820
+ constructor(config?: FileMediaStorageConfig);
8821
+ save(data: Buffer, metadata: MediaStorageMetadata): Promise<MediaStorageResult>;
8822
+ read(location: string): Promise<Buffer | null>;
8823
+ delete(location: string): Promise<void>;
8824
+ exists(location: string): Promise<boolean>;
8825
+ list(options?: MediaStorageListOptions): Promise<MediaStorageEntry[]>;
8826
+ getPath(): string;
8827
+ private generateFilename;
8828
+ private ensureDir;
8829
+ }
8672
8830
  /**
8673
- * Agent execution status
8831
+ * Factory function for creating FileMediaStorage instances
8674
8832
  */
8675
- type AgentStatus = 'idle' | 'running' | 'suspended' | 'completed' | 'failed' | 'cancelled';
8833
+ declare function createFileMediaStorage(config?: FileMediaStorageConfig): FileMediaStorage;
8834
+
8676
8835
  /**
8677
- * Agent configuration (needed for resume)
8678
- */
8679
- interface AgentConfig {
8680
- connectorName: string;
8681
- model: string;
8682
- temperature?: number;
8683
- maxIterations?: number;
8684
- toolNames: string[];
8685
- }
8686
- /**
8687
- * Conversation message in history
8688
- */
8689
- interface ConversationMessage {
8690
- role: 'user' | 'assistant' | 'system';
8691
- content: string;
8692
- timestamp: number;
8693
- }
8694
- /**
8695
- * Agent execution metrics
8836
+ * FileCustomToolStorage - File-based storage for custom tool definitions
8837
+ *
8838
+ * Stores custom tools as JSON files on disk with per-user isolation.
8839
+ * Path: ~/.oneringai/users/<userId>/custom-tools/<sanitized-name>.json
8840
+ *
8841
+ * Features:
8842
+ * - Per-user isolation (multi-tenant safe)
8843
+ * - Cross-platform path handling
8844
+ * - Safe name sanitization
8845
+ * - Atomic file operations (write to .tmp then rename)
8846
+ * - Per-user index file for fast listing
8847
+ * - Search support (case-insensitive substring on name + description)
8696
8848
  */
8697
- interface AgentMetrics {
8698
- totalLLMCalls: number;
8699
- totalToolCalls: number;
8700
- totalTokensUsed: number;
8701
- totalCost: number;
8702
- }
8849
+
8703
8850
  /**
8704
- * Full agent state - everything needed to resume
8851
+ * Configuration for FileCustomToolStorage
8705
8852
  */
8706
- interface AgentState {
8707
- id: string;
8708
- status: AgentStatus;
8709
- /** Configuration */
8710
- config: AgentConfig;
8711
- /** Current plan */
8712
- plan: Plan;
8713
- /** Working memory reference */
8714
- memoryId: string;
8715
- /** Conversation history (for context continuity) */
8716
- conversationHistory: ConversationMessage[];
8717
- /** Timestamps */
8718
- createdAt: number;
8719
- startedAt?: number;
8720
- suspendedAt?: number;
8721
- completedAt?: number;
8722
- lastActivityAt: number;
8723
- /** Metrics */
8724
- metrics: AgentMetrics;
8853
+ interface FileCustomToolStorageConfig {
8854
+ /** Override the base directory (default: ~/.oneringai/users) */
8855
+ baseDirectory?: string;
8856
+ /** Pretty-print JSON (default: true) */
8857
+ prettyPrint?: boolean;
8725
8858
  }
8726
-
8727
8859
  /**
8728
- * Plan storage interface for plan persistence.
8729
- * Implement for long-running agent support.
8860
+ * File-based storage for custom tool definitions
8861
+ *
8862
+ * Single instance handles all users. UserId is passed to each method.
8730
8863
  */
8731
-
8732
- interface IPlanStorage {
8864
+ declare class FileCustomToolStorage implements ICustomToolStorage {
8865
+ private readonly baseDirectory;
8866
+ private readonly prettyPrint;
8867
+ constructor(config?: FileCustomToolStorageConfig);
8733
8868
  /**
8734
- * Save or update a plan
8869
+ * Get the directory path for a specific user's custom tools
8735
8870
  */
8736
- savePlan(plan: Plan): Promise<void>;
8871
+ private getUserDirectory;
8737
8872
  /**
8738
- * Get plan by ID
8873
+ * Get the index file path for a specific user
8739
8874
  */
8740
- getPlan(planId: string): Promise<Plan | undefined>;
8875
+ private getUserIndexPath;
8741
8876
  /**
8742
- * Update a specific task within a plan
8877
+ * Get the tool file path for a specific user
8743
8878
  */
8744
- updateTask(planId: string, task: Task): Promise<void>;
8879
+ private getToolPath;
8745
8880
  /**
8746
- * Add a new task to a plan (for dynamic task creation)
8881
+ * Save a custom tool definition
8747
8882
  */
8748
- addTask(planId: string, task: Task): Promise<void>;
8883
+ save(userId: string | undefined, definition: CustomToolDefinition): Promise<void>;
8749
8884
  /**
8750
- * Delete a plan
8885
+ * Load a custom tool definition by name
8751
8886
  */
8752
- deletePlan(planId: string): Promise<void>;
8887
+ load(userId: string | undefined, name: string): Promise<CustomToolDefinition | null>;
8753
8888
  /**
8754
- * List plans by status
8889
+ * Delete a custom tool definition
8755
8890
  */
8756
- listPlans(filter?: {
8757
- status?: PlanStatus[];
8758
- }): Promise<Plan[]>;
8891
+ delete(userId: string | undefined, name: string): Promise<void>;
8759
8892
  /**
8760
- * Find plans with tasks waiting on a specific webhook
8893
+ * Check if a custom tool exists
8761
8894
  */
8762
- findByWebhookId(webhookId: string): Promise<{
8763
- plan: Plan;
8764
- task: Task;
8765
- } | undefined>;
8895
+ exists(userId: string | undefined, name: string): Promise<boolean>;
8896
+ /**
8897
+ * List custom tools (summaries only)
8898
+ */
8899
+ list(userId: string | undefined, options?: CustomToolListOptions): Promise<CustomToolSummary[]>;
8900
+ /**
8901
+ * Update metadata without loading full definition
8902
+ */
8903
+ updateMetadata(userId: string | undefined, name: string, metadata: Record<string, unknown>): Promise<void>;
8904
+ /**
8905
+ * Get storage path for a specific user
8906
+ */
8907
+ getPath(userId: string | undefined): string;
8908
+ private ensureDirectory;
8909
+ private loadIndex;
8910
+ private saveIndex;
8911
+ private updateIndex;
8912
+ private removeFromIndex;
8913
+ private definitionToIndexEntry;
8766
8914
  }
8915
+ /**
8916
+ * Create a FileCustomToolStorage with default configuration
8917
+ */
8918
+ declare function createFileCustomToolStorage(config?: FileCustomToolStorageConfig): FileCustomToolStorage;
8767
8919
 
8768
8920
  /**
8769
- * Agent state storage interface for full agent state persistence.
8770
- * Required for resume capability.
8921
+ * FileUserInfoStorage - File-based storage for user information
8922
+ *
8923
+ * Stores user information as a JSON file on disk.
8924
+ * Path: ~/.oneringai/users/<userId>/user_info.json
8925
+ * Windows: %APPDATA%/oneringai/users/<userId>/user_info.json
8926
+ *
8927
+ * Features:
8928
+ * - Cross-platform path handling
8929
+ * - Safe user ID sanitization
8930
+ * - Atomic file operations
8931
+ * - Automatic directory creation
8932
+ * - Multi-user support (one storage instance for all users)
8771
8933
  */
8772
8934
 
8773
- interface IAgentStateStorage {
8935
+ /**
8936
+ * Configuration for FileUserInfoStorage
8937
+ */
8938
+ interface FileUserInfoStorageConfig {
8939
+ /** Override the base directory (default: ~/.oneringai/users) */
8940
+ baseDirectory?: string;
8941
+ /** Override the filename (default: user_info.json) */
8942
+ filename?: string;
8943
+ }
8944
+ /**
8945
+ * File-based storage for user information
8946
+ *
8947
+ * Single instance handles all users. UserId is passed to each method.
8948
+ */
8949
+ declare class FileUserInfoStorage implements IUserInfoStorage {
8950
+ private readonly baseDirectory;
8951
+ private readonly filename;
8952
+ constructor(config?: FileUserInfoStorageConfig);
8774
8953
  /**
8775
- * Save agent state
8954
+ * Get the directory path for a specific user
8776
8955
  */
8777
- save(state: AgentState): Promise<void>;
8956
+ private getUserDirectory;
8778
8957
  /**
8779
- * Load agent state
8958
+ * Get the file path for a specific user
8780
8959
  */
8781
- load(agentId: string): Promise<AgentState | undefined>;
8960
+ private getUserFilePath;
8782
8961
  /**
8783
- * Delete agent state
8962
+ * Load user info entries from file for a specific user
8784
8963
  */
8785
- delete(agentId: string): Promise<void>;
8964
+ load(userId: string | undefined): Promise<UserInfoEntry[] | null>;
8786
8965
  /**
8787
- * List agents by status
8966
+ * Save user info entries to file for a specific user
8967
+ * Creates directory if it doesn't exist.
8788
8968
  */
8789
- list(filter?: {
8790
- status?: AgentStatus[];
8791
- }): Promise<AgentState[]>;
8969
+ save(userId: string | undefined, entries: UserInfoEntry[]): Promise<void>;
8792
8970
  /**
8793
- * Update specific fields (partial update for efficiency)
8971
+ * Delete user info file for a specific user
8794
8972
  */
8795
- patch(agentId: string, updates: Partial<AgentState>): Promise<void>;
8973
+ delete(userId: string | undefined): Promise<void>;
8974
+ /**
8975
+ * Check if user info file exists for a specific user
8976
+ */
8977
+ exists(userId: string | undefined): Promise<boolean>;
8978
+ /**
8979
+ * Get the file path for a specific user (for display/debugging)
8980
+ */
8981
+ getPath(userId: string | undefined): string;
8982
+ /**
8983
+ * Ensure the directory exists
8984
+ */
8985
+ private ensureDirectory;
8796
8986
  }
8797
8987
 
8798
8988
  /**
8799
- * In-memory storage implementations (default, non-persistent)
8989
+ * FileRoutineDefinitionStorage - File-based storage for routine definitions.
8990
+ *
8991
+ * Stores routines as JSON files on disk with per-user isolation.
8992
+ * Path: ~/.oneringai/users/<userId>/routines/<sanitized-id>.json
8993
+ *
8994
+ * Features:
8995
+ * - Per-user isolation (multi-tenant safe)
8996
+ * - Cross-platform path handling
8997
+ * - Safe ID sanitization
8998
+ * - Atomic file operations (write to .tmp then rename)
8999
+ * - Per-user index file for fast listing/filtering
9000
+ * - Index auto-rebuild if missing
8800
9001
  */
8801
9002
 
8802
9003
  /**
8803
- * In-memory implementation of IMemoryStorage
8804
- */
8805
- declare class InMemoryStorage implements IMemoryStorage {
8806
- private store;
8807
- get(key: string): Promise<MemoryEntry | undefined>;
8808
- set(key: string, entry: MemoryEntry): Promise<void>;
8809
- delete(key: string): Promise<void>;
8810
- has(key: string): Promise<boolean>;
8811
- getAll(): Promise<MemoryEntry[]>;
8812
- getByScope(scope: MemoryScope): Promise<MemoryEntry[]>;
8813
- clearScope(scope: MemoryScope): Promise<void>;
8814
- clear(): Promise<void>;
8815
- getTotalSize(): Promise<number>;
8816
- }
8817
- /**
8818
- * In-memory implementation of IPlanStorage
9004
+ * Configuration for FileRoutineDefinitionStorage
8819
9005
  */
8820
- declare class InMemoryPlanStorage implements IPlanStorage {
8821
- private plans;
8822
- savePlan(plan: Plan): Promise<void>;
8823
- getPlan(planId: string): Promise<Plan | undefined>;
8824
- updateTask(planId: string, task: Task): Promise<void>;
8825
- addTask(planId: string, task: Task): Promise<void>;
8826
- deletePlan(planId: string): Promise<void>;
8827
- listPlans(filter?: {
8828
- status?: PlanStatus[];
8829
- }): Promise<Plan[]>;
8830
- findByWebhookId(webhookId: string): Promise<{
8831
- plan: Plan;
8832
- task: Task;
8833
- } | undefined>;
9006
+ interface FileRoutineDefinitionStorageConfig {
9007
+ /** Override the base directory (default: ~/.oneringai/users) */
9008
+ baseDirectory?: string;
9009
+ /** Pretty-print JSON (default: true) */
9010
+ prettyPrint?: boolean;
8834
9011
  }
8835
9012
  /**
8836
- * In-memory implementation of IAgentStateStorage
9013
+ * File-based storage for routine definitions.
9014
+ *
9015
+ * Single instance handles all users. UserId is passed to each method.
8837
9016
  */
8838
- declare class InMemoryAgentStateStorage implements IAgentStateStorage {
8839
- private agents;
8840
- save(state: AgentState): Promise<void>;
8841
- load(agentId: string): Promise<AgentState | undefined>;
8842
- delete(agentId: string): Promise<void>;
8843
- list(filter?: {
8844
- status?: AgentStatus[];
8845
- }): Promise<AgentState[]>;
8846
- patch(agentId: string, updates: Partial<AgentState>): Promise<void>;
8847
- }
8848
- /**
8849
- * Unified agent storage interface
8850
- */
8851
- interface IAgentStorage {
8852
- memory: IMemoryStorage;
8853
- plan: IPlanStorage;
8854
- agent: IAgentStateStorage;
9017
+ declare class FileRoutineDefinitionStorage implements IRoutineDefinitionStorage {
9018
+ private readonly baseDirectory;
9019
+ private readonly prettyPrint;
9020
+ constructor(config?: FileRoutineDefinitionStorageConfig);
9021
+ private getUserDirectory;
9022
+ private getIndexPath;
9023
+ private getRoutinePath;
9024
+ save(userId: string | undefined, definition: RoutineDefinition): Promise<void>;
9025
+ load(userId: string | undefined, id: string): Promise<RoutineDefinition | null>;
9026
+ delete(userId: string | undefined, id: string): Promise<void>;
9027
+ exists(userId: string | undefined, id: string): Promise<boolean>;
9028
+ list(userId: string | undefined, options?: {
9029
+ tags?: string[];
9030
+ search?: string;
9031
+ limit?: number;
9032
+ offset?: number;
9033
+ }): Promise<RoutineDefinition[]>;
9034
+ getPath(userId: string | undefined): string;
9035
+ private ensureDirectory;
9036
+ private loadIndex;
9037
+ private saveIndex;
9038
+ private updateIndex;
9039
+ private removeFromIndex;
9040
+ private definitionToIndexEntry;
9041
+ /**
9042
+ * Rebuild index by scanning directory for .json files (excluding _index.json).
9043
+ * Returns empty index if directory doesn't exist.
9044
+ */
9045
+ private rebuildIndex;
8855
9046
  }
8856
9047
  /**
8857
- * Create agent storage with defaults
9048
+ * Create a FileRoutineDefinitionStorage with default configuration
8858
9049
  */
8859
- declare function createAgentStorage(options?: {
8860
- memory?: IMemoryStorage;
8861
- plan?: IPlanStorage;
8862
- agent?: IAgentStateStorage;
8863
- }): IAgentStorage;
9050
+ declare function createFileRoutineDefinitionStorage(config?: FileRoutineDefinitionStorageConfig): FileRoutineDefinitionStorage;
8864
9051
 
8865
9052
  /**
8866
- * CheckpointManager - manages agent state checkpointing
9053
+ * FileRoutineExecutionStorage - File-based storage for routine execution records.
9054
+ *
9055
+ * Stores executions as JSON files on disk with per-user isolation.
9056
+ * Path: ~/.oneringai/users/<userId>/routine-executions/<executionId>.json
9057
+ *
9058
+ * Features:
9059
+ * - Per-user isolation (multi-tenant safe)
9060
+ * - Cross-platform path handling
9061
+ * - Safe ID sanitization
9062
+ * - Atomic file operations (write to .tmp then rename)
9063
+ * - Per-user index file for fast listing/filtering
9064
+ * - Index auto-rebuild if missing
9065
+ * - Automatic pruning of old completed/failed records (maxRecords)
8867
9066
  */
8868
9067
 
8869
- interface CheckpointStrategy {
8870
- /** Checkpoint after every N tool calls */
8871
- afterToolCalls?: number;
8872
- /** Checkpoint after every N LLM calls */
8873
- afterLLMCalls?: number;
8874
- /** Checkpoint on time interval */
8875
- intervalMs?: number;
8876
- /** Always checkpoint before external wait */
8877
- beforeExternalWait: boolean;
8878
- /** Checkpoint mode */
8879
- mode: 'sync' | 'async';
9068
+ /**
9069
+ * Configuration for FileRoutineExecutionStorage
9070
+ */
9071
+ interface FileRoutineExecutionStorageConfig {
9072
+ /** Override the base directory (default: ~/.oneringai/users) */
9073
+ baseDirectory?: string;
9074
+ /** Pretty-print JSON (default: true) */
9075
+ prettyPrint?: boolean;
9076
+ /** Maximum number of execution records per user (default: 100). Oldest completed/failed are pruned on insert. */
9077
+ maxRecords?: number;
8880
9078
  }
8881
- declare const DEFAULT_CHECKPOINT_STRATEGY: CheckpointStrategy;
8882
9079
  /**
8883
- * Manages state checkpointing for persistence and recovery
9080
+ * File-based storage for routine execution records.
9081
+ *
9082
+ * Single instance handles all users. UserId is passed to each method.
8884
9083
  */
8885
- declare class CheckpointManager {
8886
- private storage;
8887
- private strategy;
8888
- private toolCallsSinceCheckpoint;
8889
- private llmCallsSinceCheckpoint;
8890
- private intervalTimer?;
8891
- private pendingCheckpoints;
8892
- private currentState;
8893
- constructor(storage: IAgentStorage, strategy?: CheckpointStrategy);
8894
- /**
8895
- * Set the current agent state (for interval checkpointing)
8896
- */
8897
- setCurrentState(state: AgentState): void;
8898
- /**
8899
- * Record a tool call (may trigger checkpoint)
8900
- */
8901
- onToolCall(state: AgentState): Promise<void>;
8902
- /**
8903
- * Record an LLM call (may trigger checkpoint)
8904
- */
8905
- onLLMCall(state: AgentState): Promise<void>;
8906
- /**
8907
- * Force a checkpoint
8908
- */
8909
- checkpoint(state: AgentState, reason: string): Promise<void>;
9084
+ declare class FileRoutineExecutionStorage implements IRoutineExecutionStorage {
9085
+ private readonly baseDirectory;
9086
+ private readonly prettyPrint;
9087
+ private readonly maxRecords;
9088
+ constructor(config?: FileRoutineExecutionStorageConfig);
9089
+ private getUserDirectory;
9090
+ private getIndexPath;
9091
+ private getExecutionPath;
9092
+ private executionUserMap;
9093
+ insert(userId: string | undefined, record: RoutineExecutionRecord): Promise<string>;
9094
+ update(id: string, updates: Partial<Pick<RoutineExecutionRecord, 'status' | 'progress' | 'error' | 'completedAt' | 'lastActivityAt'>>): Promise<void>;
9095
+ pushStep(id: string, step: RoutineExecutionStep): Promise<void>;
9096
+ updateTask(id: string, taskName: string, updates: Partial<RoutineTaskSnapshot>): Promise<void>;
9097
+ load(id: string): Promise<RoutineExecutionRecord | null>;
9098
+ list(userId: string | undefined, options?: {
9099
+ routineId?: string;
9100
+ status?: RoutineExecutionStatus;
9101
+ limit?: number;
9102
+ offset?: number;
9103
+ }): Promise<RoutineExecutionRecord[]>;
9104
+ hasRunning(userId: string | undefined, routineId: string): Promise<boolean>;
9105
+ getPath(userId: string | undefined): string;
9106
+ private ensureDirectory;
9107
+ private atomicWrite;
9108
+ private readStoredExecution;
8910
9109
  /**
8911
- * Perform the actual checkpoint
9110
+ * Load a record directly by userId + executionId (used by list()).
8912
9111
  */
8913
- private doCheckpoint;
9112
+ private loadByUserAndId;
8914
9113
  /**
8915
- * Check if interval-based checkpoint is needed
9114
+ * Resolve the file path for an execution ID.
9115
+ * Uses in-memory cache first, then falls back to scanning user directories.
8916
9116
  */
8917
- private checkIntervalCheckpoint;
9117
+ private resolveExecutionFile;
9118
+ private loadIndex;
9119
+ private saveIndex;
9120
+ private updateIndex;
9121
+ private recordToIndexEntry;
8918
9122
  /**
8919
- * Wait for all pending checkpoints to complete
9123
+ * Prune old completed/failed records if count exceeds maxRecords.
9124
+ * Running/paused/pending records are never pruned.
8920
9125
  */
8921
- flush(): Promise<void>;
9126
+ private pruneOldRecords;
8922
9127
  /**
8923
- * Cleanup resources
9128
+ * Rebuild index by scanning directory for .json files (excluding _index.json).
9129
+ * Returns empty index if directory doesn't exist.
8924
9130
  */
8925
- cleanup(): Promise<void>;
9131
+ private rebuildIndex;
8926
9132
  }
9133
+ /**
9134
+ * Create a FileRoutineExecutionStorage with default configuration
9135
+ */
9136
+ declare function createFileRoutineExecutionStorage(config?: FileRoutineExecutionStorageConfig): FileRoutineExecutionStorage;
8927
9137
 
8928
9138
  /**
8929
- * PlanningAgent - AI-driven plan generation
9139
+ * WorkingMemory class - manages indexed working memory for TaskAgent
8930
9140
  *
8931
- * Separates planning phase from execution phase.
8932
- * Analyzes goals and generates task graphs with dependencies.
9141
+ * This is a GENERIC implementation that works across all agent types:
9142
+ * - Basic Agent: Uses staticPriorityCalculator with simple scopes
9143
+ * - TaskAgent: Uses taskAwarePriorityCalculator with task-aware scopes
9144
+ * - UniversalAgent: Can switch calculators based on mode
9145
+ *
9146
+ * The PriorityCalculator strategy pattern allows different agents to have
9147
+ * different eviction behaviors without changing the core WorkingMemory logic.
8933
9148
  */
8934
9149
 
8935
9150
  /**
8936
- * PlanningAgent configuration
9151
+ * Serialized memory state for persistence
8937
9152
  */
8938
- interface PlanningAgentConfig {
8939
- /** Connector for LLM access */
8940
- connector: string | Connector;
8941
- /** Model to use for planning (can be different/cheaper than execution) */
8942
- model: string;
8943
- /** Max planning iterations */
8944
- maxPlanningIterations?: number;
8945
- /** Temperature for planning (lower = more deterministic) */
8946
- planningTemperature?: number;
8947
- /** Tools available for the plan (used to inform planning) */
8948
- availableTools?: ToolFunction[];
9153
+ interface SerializedMemory {
9154
+ /** Memory format version */
9155
+ version: number;
9156
+ /** Serialized memory entries */
9157
+ entries: SerializedMemoryEntry[];
8949
9158
  }
8950
9159
  /**
8951
- * Generated plan with metadata
9160
+ * Serialized memory entry
8952
9161
  */
8953
- interface GeneratedPlan {
8954
- plan: Plan;
8955
- reasoning: string;
8956
- estimated_duration?: string;
8957
- complexity?: 'low' | 'medium' | 'high';
9162
+ interface SerializedMemoryEntry {
9163
+ key: string;
9164
+ description: string;
9165
+ value: unknown;
9166
+ scope: MemoryScope;
9167
+ sizeBytes: number;
9168
+ basePriority?: MemoryPriority;
9169
+ pinned?: boolean;
8958
9170
  }
8959
9171
  /**
8960
- * PlanningAgent class
9172
+ * Eviction strategy type
8961
9173
  */
8962
- declare class PlanningAgent {
8963
- private agent;
9174
+ type EvictionStrategy = 'lru' | 'size';
9175
+ interface WorkingMemoryEvents {
9176
+ stored: {
9177
+ key: string;
9178
+ description: string;
9179
+ scope: MemoryScope;
9180
+ };
9181
+ retrieved: {
9182
+ key: string;
9183
+ };
9184
+ deleted: {
9185
+ key: string;
9186
+ };
9187
+ evicted: {
9188
+ keys: string[];
9189
+ reason: 'lru' | 'size' | 'task_completed';
9190
+ };
9191
+ limit_warning: {
9192
+ utilizationPercent: number;
9193
+ };
9194
+ stale_entries: {
9195
+ entries: StaleEntryInfo[];
9196
+ };
9197
+ }
9198
+ /**
9199
+ * WorkingMemory manages the agent's indexed working memory.
9200
+ *
9201
+ * Features:
9202
+ * - Store/retrieve with descriptions for index
9203
+ * - Scoped memory (simple or task-aware)
9204
+ * - Priority-based eviction (respects pinned, priority, then LRU)
9205
+ * - Pluggable priority calculation via PriorityCalculator strategy
9206
+ * - Task completion detection and stale entry notification
9207
+ * - Event emission for monitoring
9208
+ */
9209
+ declare class WorkingMemory extends EventEmitter<WorkingMemoryEvents> implements IDisposable {
9210
+ private storage;
8964
9211
  private config;
8965
- private currentTasks;
8966
- private planningComplete;
8967
- private constructor();
9212
+ private priorityCalculator;
9213
+ private priorityContext;
9214
+ private _isDestroyed;
8968
9215
  /**
8969
- * Create a new PlanningAgent
9216
+ * Create a WorkingMemory instance
9217
+ *
9218
+ * @param storage - Storage backend for memory entries
9219
+ * @param config - Memory configuration (limits, etc.)
9220
+ * @param priorityCalculator - Strategy for computing effective priority (default: static)
8970
9221
  */
8971
- static create(config: PlanningAgentConfig): PlanningAgent;
9222
+ constructor(storage: IMemoryStorage, config?: WorkingMemoryConfig, priorityCalculator?: PriorityCalculator);
8972
9223
  /**
8973
- * Create planning tools bound to this PlanningAgent instance
9224
+ * Set the priority calculator (for switching strategies at runtime)
8974
9225
  */
8975
- private createBoundPlanningTools;
9226
+ setPriorityCalculator(calculator: PriorityCalculator): void;
8976
9227
  /**
8977
- * Generate a plan from a goal
9228
+ * Update priority context (e.g., task states for TaskAgent)
8978
9229
  */
8979
- generatePlan(input: {
8980
- goal: string;
8981
- context?: string;
8982
- constraints?: string[];
8983
- }): Promise<GeneratedPlan>;
9230
+ setPriorityContext(context: PriorityContext): void;
8984
9231
  /**
8985
- * Validate and refine an existing plan
9232
+ * Get the current priority context
8986
9233
  */
8987
- refinePlan(plan: Plan, feedback: string): Promise<GeneratedPlan>;
9234
+ getPriorityContext(): PriorityContext;
8988
9235
  /**
8989
- * Build planning prompt from input
9236
+ * Compute effective priority for an entry using the current calculator
8990
9237
  */
8991
- private buildPlanningPrompt;
9238
+ private computeEffectivePriority;
8992
9239
  /**
8993
- * Estimate plan complexity
9240
+ * Get all entries with their computed effective priorities
9241
+ * This is a performance optimization to avoid repeated getAll() + map() calls
8994
9242
  */
8995
- private estimateComplexity;
9243
+ private getEntriesWithPriority;
8996
9244
  /**
8997
- * Get current tasks (for tool access)
9245
+ * Get evictable entries sorted by eviction priority
9246
+ * Filters out pinned and critical entries, sorts by priority then by strategy
8998
9247
  */
8999
- getCurrentTasks(): TaskInput[];
9248
+ private getEvictableEntries;
9000
9249
  /**
9001
- * Add task (called by planning tools)
9250
+ * Store a value in working memory
9251
+ *
9252
+ * @param key - Unique key for the entry
9253
+ * @param description - Short description for the index (max 150 chars)
9254
+ * @param value - The data to store
9255
+ * @param options - Optional scope, priority, and pinned settings
9002
9256
  */
9003
- addTask(task: TaskInput): void;
9257
+ store(key: string, description: string, value: unknown, options?: {
9258
+ scope?: MemoryScope;
9259
+ priority?: MemoryPriority;
9260
+ pinned?: boolean;
9261
+ }): Promise<void>;
9004
9262
  /**
9005
- * Update task (called by planning tools)
9263
+ * Enforce the maxIndexEntries limit by evicting excess entries
9264
+ * Only evicts if entry count exceeds the configured limit
9006
9265
  */
9007
- updateTask(name: string, updates: Partial<TaskInput>): void;
9266
+ private enforceEntryCountLimit;
9008
9267
  /**
9009
- * Remove task (called by planning tools)
9268
+ * Get the configured max index entries limit
9010
9269
  */
9011
- removeTask(name: string): void;
9270
+ getMaxIndexEntries(): number | undefined;
9012
9271
  /**
9013
- * Mark planning as complete
9272
+ * Store a value scoped to specific tasks
9273
+ * Convenience method for task-aware memory
9014
9274
  */
9015
- finalizePlanning(): void;
9016
- }
9017
- /**
9018
- * Simple plan generation without tools (fallback)
9019
- */
9020
- declare function generateSimplePlan(goal: string, context?: string): Promise<Plan>;
9021
-
9022
- /**
9023
- * ResearchAgent Types
9024
- *
9025
- * Generic interfaces for research sources that work with any data provider:
9026
- * - Web search (Serper, Brave, Tavily)
9027
- * - Vector databases (Pinecone, Weaviate, Qdrant)
9028
- * - File systems (local, S3, GCS)
9029
- * - APIs (REST, GraphQL)
9030
- * - Databases (SQL, MongoDB)
9031
- */
9032
- /**
9033
- * A single search result from any source
9034
- */
9035
- interface SourceResult {
9036
- /** Unique identifier for this result */
9037
- id: string;
9038
- /** Human-readable title */
9039
- title: string;
9040
- /** Brief description or snippet */
9041
- snippet: string;
9042
- /** Reference for fetching full content (URL, path, ID, etc.) */
9043
- reference: string;
9044
- /** Relevance score (0-1, higher is better) */
9045
- relevance?: number;
9046
- /** Source-specific metadata */
9047
- metadata?: Record<string, unknown>;
9048
- }
9049
- /**
9050
- * Response from a search operation
9051
- */
9052
- interface SearchResponse {
9053
- /** Whether the search succeeded */
9054
- success: boolean;
9055
- /** Original query */
9056
- query: string;
9057
- /** Results found */
9058
- results: SourceResult[];
9059
- /** Total results available (may be more than returned) */
9060
- totalResults?: number;
9061
- /** Error message if failed */
9062
- error?: string;
9063
- /** Source-specific metadata */
9064
- metadata?: Record<string, unknown>;
9065
- }
9066
- /**
9067
- * Fetched content from a source
9068
- */
9069
- interface FetchedContent {
9070
- /** Whether fetch succeeded */
9071
- success: boolean;
9072
- /** Reference that was fetched */
9073
- reference: string;
9074
- /** The actual content */
9075
- content: unknown;
9076
- /** Content type hint (text, html, json, binary, etc.) */
9077
- contentType?: string;
9078
- /** Size in bytes */
9079
- sizeBytes?: number;
9080
- /** Error message if failed */
9081
- error?: string;
9082
- /** Source-specific metadata */
9083
- metadata?: Record<string, unknown>;
9084
- }
9085
- /**
9086
- * Options for search operations
9087
- */
9088
- interface SearchOptions {
9089
- /** Maximum results to return */
9090
- maxResults?: number;
9091
- /** Minimum relevance score (0-1) */
9092
- minRelevance?: number;
9093
- /** Source-specific options */
9094
- sourceOptions?: Record<string, unknown>;
9095
- }
9096
- /**
9097
- * Options for fetch operations
9098
- */
9099
- interface FetchOptions {
9100
- /** Maximum content size to fetch (bytes) */
9101
- maxSize?: number;
9102
- /** Timeout in milliseconds */
9103
- timeoutMs?: number;
9104
- /** Source-specific options */
9105
- sourceOptions?: Record<string, unknown>;
9106
- }
9107
- /**
9108
- * Generic research source interface
9109
- *
9110
- * Implement this interface to add any data source to ResearchAgent:
9111
- * - Web: search queries, fetch URLs
9112
- * - Vector DB: similarity search, fetch documents
9113
- * - File system: glob patterns, read files
9114
- * - API: query endpoints, fetch resources
9115
- */
9116
- interface IResearchSource {
9117
- /** Unique name for this source */
9118
- readonly name: string;
9119
- /** Human-readable description */
9120
- readonly description: string;
9121
- /** Type of source (for categorization) */
9122
- readonly type: 'web' | 'vector' | 'file' | 'api' | 'database' | 'custom';
9275
+ storeForTasks(key: string, description: string, value: unknown, taskIds: string[], options?: {
9276
+ priority?: MemoryPriority;
9277
+ pinned?: boolean;
9278
+ }): Promise<void>;
9123
9279
  /**
9124
- * Search this source for relevant results
9280
+ * Store a value scoped to the entire plan
9281
+ * Convenience method for plan-scoped memory
9282
+ */
9283
+ storeForPlan(key: string, description: string, value: unknown, options?: {
9284
+ priority?: MemoryPriority;
9285
+ pinned?: boolean;
9286
+ }): Promise<void>;
9287
+ /**
9288
+ * Retrieve a value from working memory
9125
9289
  *
9126
- * @param query - Search query (interpreted by source)
9127
- * @param options - Search options
9128
- * @returns Search response with results
9290
+ * Note: Access stats update is not strictly atomic. Under very high concurrency,
9291
+ * accessCount may be slightly inaccurate. This is acceptable for memory management
9292
+ * purposes where exact counts are not critical.
9129
9293
  */
9130
- search(query: string, options?: SearchOptions): Promise<SearchResponse>;
9294
+ retrieve(key: string): Promise<unknown>;
9131
9295
  /**
9132
- * Fetch full content for a result
9296
+ * Retrieve multiple values
9297
+ */
9298
+ retrieveMany(keys: string[]): Promise<Record<string, unknown>>;
9299
+ /**
9300
+ * Delete a value from working memory
9301
+ */
9302
+ delete(key: string): Promise<void>;
9303
+ /**
9304
+ * Check if key exists
9305
+ */
9306
+ has(key: string): Promise<boolean>;
9307
+ /**
9308
+ * Promote an entry to persistent scope
9309
+ * Works with both simple and task-aware scopes
9310
+ */
9311
+ persist(key: string): Promise<void>;
9312
+ /**
9313
+ * Pin an entry (never evicted)
9314
+ */
9315
+ pin(key: string): Promise<void>;
9316
+ /**
9317
+ * Unpin an entry
9318
+ */
9319
+ unpin(key: string, newPriority?: MemoryPriority): Promise<void>;
9320
+ /**
9321
+ * Set the base priority of an entry
9322
+ */
9323
+ setPriority(key: string, priority: MemoryPriority): Promise<void>;
9324
+ /**
9325
+ * Update the scope of an entry without re-storing the value
9326
+ */
9327
+ updateScope(key: string, scope: MemoryScope): Promise<void>;
9328
+ /**
9329
+ * Add task IDs to an existing task-scoped entry
9330
+ * If entry is not task-scoped, converts it to task-scoped
9331
+ */
9332
+ addTasksToScope(key: string, taskIds: string[]): Promise<void>;
9333
+ /**
9334
+ * Clear all entries of a specific scope
9335
+ */
9336
+ clearScope(scope: MemoryScope): Promise<void>;
9337
+ /**
9338
+ * Clear all entries
9339
+ */
9340
+ clear(): Promise<void>;
9341
+ /**
9342
+ * Get memory index with computed effective priorities
9343
+ * Respects maxIndexEntries limit for context display
9344
+ */
9345
+ getIndex(): Promise<MemoryIndex>;
9346
+ /**
9347
+ * Format index for context injection
9348
+ */
9349
+ formatIndex(): Promise<string>;
9350
+ /**
9351
+ * Evict entries using specified strategy
9133
9352
  *
9134
- * @param reference - Reference from SourceResult
9135
- * @param options - Fetch options
9136
- * @returns Fetched content
9353
+ * Eviction order:
9354
+ * 1. Never evict pinned entries
9355
+ * 2. Evict low priority first, then normal, then high (never critical)
9356
+ * 3. Within same priority, use strategy (LRU or largest size)
9357
+ *
9358
+ * @param count - Number of entries to evict
9359
+ * @param strategy - Eviction strategy ('lru' or 'size')
9360
+ * @returns Keys of evicted entries
9137
9361
  */
9138
- fetch(reference: string, options?: FetchOptions): Promise<FetchedContent>;
9362
+ evict(count: number, strategy?: EvictionStrategy): Promise<string[]>;
9139
9363
  /**
9140
- * Optional: Check if source is available/configured
9364
+ * Evict entries using priority-aware LRU algorithm
9365
+ * @deprecated Use evict(count, 'lru') instead
9141
9366
  */
9142
- isAvailable?(): Promise<boolean>;
9367
+ evictLRU(count: number): Promise<string[]>;
9143
9368
  /**
9144
- * Optional: Get source capabilities
9369
+ * Evict largest entries first (priority-aware)
9370
+ * @deprecated Use evict(count, 'size') instead
9145
9371
  */
9146
- getCapabilities?(): SourceCapabilities;
9147
- }
9148
- /**
9149
- * Source capabilities for discovery
9150
- */
9151
- interface SourceCapabilities {
9152
- /** Whether source supports search */
9153
- canSearch: boolean;
9154
- /** Whether source supports fetch */
9155
- canFetch: boolean;
9156
- /** Whether results include relevance scores */
9157
- hasRelevanceScores: boolean;
9158
- /** Maximum results per search */
9159
- maxResultsPerSearch?: number;
9160
- /** Supported content types */
9161
- contentTypes?: string[];
9162
- }
9163
- /**
9164
- * Research finding stored in memory
9165
- */
9166
- interface ResearchFinding {
9167
- /** Source that provided this finding */
9168
- source: string;
9169
- /** Original query that found this */
9170
- query: string;
9171
- /** Key insight or summary */
9172
- summary: string;
9173
- /** Supporting details */
9174
- details?: string;
9175
- /** References used */
9176
- references: string[];
9177
- /** Confidence level (0-1) */
9178
- confidence?: number;
9179
- /** When this was found */
9180
- timestamp: number;
9181
- }
9182
- /**
9183
- * Research plan for systematic research
9184
- */
9185
- interface ResearchPlan {
9186
- /** Research goal/question */
9187
- goal: string;
9188
- /** Queries to execute */
9189
- queries: ResearchQuery[];
9190
- /** Sources to use (empty = all available) */
9191
- sources?: string[];
9192
- /** Maximum results per query */
9193
- maxResultsPerQuery?: number;
9194
- /** Maximum total findings */
9195
- maxTotalFindings?: number;
9196
- }
9197
- /**
9198
- * A query in the research plan
9199
- */
9200
- interface ResearchQuery {
9201
- /** Query string */
9202
- query: string;
9203
- /** Specific sources for this query (empty = all) */
9204
- sources?: string[];
9205
- /** Priority (higher = more important) */
9206
- priority?: number;
9207
- }
9208
- /**
9209
- * Research execution result
9210
- */
9211
- interface ResearchResult {
9212
- /** Whether research completed successfully */
9213
- success: boolean;
9214
- /** Original goal */
9215
- goal: string;
9216
- /** Queries executed */
9217
- queriesExecuted: number;
9218
- /** Results found */
9219
- resultsFound: number;
9220
- /** Results processed */
9221
- resultsProcessed: number;
9222
- /** Findings generated */
9223
- findingsCount: number;
9224
- /** Final synthesis (if generated) */
9225
- synthesis?: string;
9226
- /** Error if failed */
9227
- error?: string;
9228
- /** Execution metrics */
9229
- metrics?: {
9230
- totalDurationMs: number;
9231
- searchDurationMs: number;
9232
- processDurationMs: number;
9233
- synthesizeDurationMs: number;
9234
- };
9235
- }
9236
- /**
9237
- * Research progress event
9238
- */
9239
- interface ResearchProgress {
9240
- phase: 'searching' | 'processing' | 'synthesizing' | 'complete';
9241
- currentQuery?: string;
9242
- currentSource?: string;
9243
- queriesCompleted: number;
9244
- totalQueries: number;
9245
- resultsProcessed: number;
9246
- totalResults: number;
9247
- findingsGenerated: number;
9248
- }
9249
-
9250
- /**
9251
- * Core types for context management system
9252
- */
9253
- /**
9254
- * Context component that can be compacted
9255
- */
9256
- interface IContextComponent {
9257
- /** Unique name for this component */
9258
- name: string;
9259
- /** The actual content (string or structured data) */
9260
- content: string | unknown;
9261
- /** Priority for compaction (higher = compact first) */
9262
- priority: number;
9263
- /** Whether this component can be compacted */
9264
- compactable: boolean;
9265
- /** Additional metadata for compaction strategies */
9266
- metadata?: Record<string, unknown>;
9267
- }
9268
- /**
9269
- * Context budget information
9270
- */
9271
- interface ContextBudget {
9272
- /** Total available tokens */
9273
- total: number;
9274
- /** Reserved tokens for response */
9275
- reserved: number;
9276
- /** Currently used tokens */
9277
- used: number;
9278
- /** Available tokens remaining */
9279
- available: number;
9280
- /** Utilization percentage (used / (total - reserved)) */
9281
- utilizationPercent: number;
9282
- /** Budget status */
9283
- status: 'ok' | 'warning' | 'critical';
9284
- /** Token breakdown by component */
9285
- breakdown: Record<string, number>;
9286
- }
9287
- /**
9288
- * Context manager configuration
9289
- */
9290
- interface ContextManagerConfig {
9291
- /** Maximum context tokens for the model */
9292
- maxContextTokens: number;
9293
- /** Threshold to trigger compaction (0.0 - 1.0) */
9294
- compactionThreshold: number;
9295
- /** Hard limit - must compact before this (0.0 - 1.0) */
9296
- hardLimit: number;
9297
- /** Reserve space for response (0.0 - 1.0) */
9298
- responseReserve: number;
9299
- /** Token estimator to use */
9300
- estimator: 'approximate' | 'tiktoken' | ITokenEstimator;
9301
- /** Enable automatic compaction */
9302
- autoCompact: boolean;
9303
- /** Strategy to use */
9304
- strategy?: 'proactive' | 'aggressive' | 'lazy' | 'rolling-window' | 'adaptive' | IContextStrategy;
9305
- /** Strategy-specific options */
9306
- strategyOptions?: Record<string, unknown>;
9307
- }
9308
- /**
9309
- * Default configuration
9310
- */
9311
- declare const DEFAULT_CONTEXT_CONFIG: ContextManagerConfig;
9312
- /**
9313
- * Content type for more accurate token estimation
9314
- * Named differently from TokenContentType in Content.ts to avoid conflicts
9315
- */
9316
- type TokenContentType = 'code' | 'prose' | 'mixed';
9317
- /**
9318
- * Abstract interface for token estimation
9319
- */
9320
- interface ITokenEstimator {
9372
+ evictBySize(count: number): Promise<string[]>;
9321
9373
  /**
9322
- * Estimate token count for text
9374
+ * Handle task completion - detect and notify about stale entries
9323
9375
  *
9324
- * @param text - The text to estimate
9325
- * @param contentType - Type of content for more accurate estimation:
9326
- * - 'code': Code is typically denser (~3 chars/token)
9327
- * - 'prose': Natural language text (~4 chars/token)
9328
- * - 'mixed': Mix of code and prose (~3.5 chars/token)
9376
+ * Call this when a task completes to:
9377
+ * 1. Update priority context with new task state
9378
+ * 2. Detect entries that became stale
9379
+ * 3. Emit event to notify LLM about stale entries
9380
+ *
9381
+ * @param taskId - The completed task ID
9382
+ * @param taskStates - Current task states map
9383
+ * @returns Information about stale entries
9329
9384
  */
9330
- estimateTokens(text: string, contentType?: TokenContentType): number;
9385
+ onTaskComplete(taskId: string, taskStates: Map<string, TaskStatusForMemory>): Promise<StaleEntryInfo[]>;
9331
9386
  /**
9332
- * Estimate tokens for structured data
9387
+ * Evict entries for completed tasks
9388
+ *
9389
+ * Removes entries that were scoped only to completed tasks.
9390
+ * Use after onTaskComplete() if you want automatic cleanup.
9391
+ *
9392
+ * @param taskStates - Current task states map
9393
+ * @returns Keys of evicted entries
9333
9394
  */
9334
- estimateDataTokens(data: unknown, contentType?: TokenContentType): number;
9395
+ evictCompletedTaskEntries(taskStates: Map<string, TaskStatusForMemory>): Promise<string[]>;
9335
9396
  /**
9336
- * Estimate tokens for an image.
9337
- * @param width - Image width in pixels (if known)
9338
- * @param height - Image height in pixels (if known)
9339
- * @param detail - Image detail level: 'low', 'high', or 'auto'
9397
+ * Get limited memory access for tools
9398
+ *
9399
+ * This provides a simplified interface for tools to interact with memory
9400
+ * without exposing the full WorkingMemory API.
9340
9401
  */
9341
- estimateImageTokens?(width?: number, height?: number, detail?: string): number;
9342
- }
9343
- /**
9344
- * Abstract interface for compaction strategies
9345
- */
9346
- interface IContextCompactor {
9347
- /** Compactor name */
9348
- readonly name: string;
9349
- /** Priority order (lower = run first) */
9350
- readonly priority: number;
9402
+ getAccess(): WorkingMemoryAccess;
9351
9403
  /**
9352
- * Check if this compactor can handle the component
9404
+ * Store raw data (low priority, first to be evicted)
9405
+ *
9406
+ * Use this for original/unprocessed data that should be summarized.
9407
+ * Raw data is automatically evicted first when memory pressure is high.
9408
+ *
9409
+ * @param key - Key without tier prefix (prefix is added automatically)
9410
+ * @param description - Brief description for the index
9411
+ * @param value - The raw data to store
9412
+ * @param options - Optional scope and task IDs
9413
+ */
9414
+ storeRaw(key: string, description: string, value: unknown, options?: {
9415
+ taskIds?: string[];
9416
+ scope?: MemoryScope;
9417
+ }): Promise<void>;
9418
+ /**
9419
+ * Store a summary derived from raw data (normal priority)
9420
+ *
9421
+ * Use this for processed/summarized data that extracts key information.
9422
+ * Links back to source data for cleanup tracking.
9423
+ *
9424
+ * @param key - Key without tier prefix (prefix is added automatically)
9425
+ * @param description - Brief description for the index
9426
+ * @param value - The summary data
9427
+ * @param derivedFrom - Key(s) this summary was derived from
9428
+ * @param options - Optional scope and task IDs
9429
+ */
9430
+ storeSummary(key: string, description: string, value: unknown, derivedFrom: string | string[], options?: {
9431
+ taskIds?: string[];
9432
+ scope?: MemoryScope;
9433
+ }): Promise<void>;
9434
+ /**
9435
+ * Store final findings (high priority, kept longest)
9436
+ *
9437
+ * Use this for conclusions, insights, or final results that should be preserved.
9438
+ * These are the last to be evicted and typically span the entire plan.
9439
+ *
9440
+ * @param key - Key without tier prefix (prefix is added automatically)
9441
+ * @param description - Brief description for the index
9442
+ * @param value - The findings data
9443
+ * @param derivedFrom - Optional key(s) these findings were derived from
9444
+ * @param options - Optional scope, task IDs, and pinned flag
9445
+ */
9446
+ storeFindings(key: string, description: string, value: unknown, _derivedFrom?: string | string[], options?: {
9447
+ taskIds?: string[];
9448
+ scope?: MemoryScope;
9449
+ pinned?: boolean;
9450
+ }): Promise<void>;
9451
+ /**
9452
+ * Clean up raw data after summary/findings are created
9453
+ *
9454
+ * Call this after creating summaries to free up memory used by raw data.
9455
+ * Only deletes entries in the 'raw' tier.
9456
+ *
9457
+ * @param derivedFromKeys - Keys to delete (typically from derivedFrom metadata)
9458
+ * @returns Number of entries deleted
9459
+ */
9460
+ cleanupRawData(derivedFromKeys: string[]): Promise<number>;
9461
+ /**
9462
+ * Get all entries by tier
9463
+ *
9464
+ * @param tier - The tier to filter by
9465
+ * @returns Array of entries in that tier
9466
+ */
9467
+ getByTier(tier: MemoryTier): Promise<MemoryEntry[]>;
9468
+ /**
9469
+ * Promote an entry to a higher tier
9470
+ *
9471
+ * Changes the key prefix and updates priority.
9472
+ * Use this when raw data becomes more valuable (e.g., frequently accessed).
9473
+ *
9474
+ * @param key - Current key (with tier prefix)
9475
+ * @param toTier - Target tier to promote to
9476
+ * @returns New key with updated prefix
9353
9477
  */
9354
- canCompact(component: IContextComponent): boolean;
9478
+ promote(key: string, toTier: MemoryTier): Promise<string>;
9355
9479
  /**
9356
- * Compact the component to target size
9480
+ * Get tier statistics
9481
+ *
9482
+ * @returns Count and size by tier
9357
9483
  */
9358
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9484
+ getTierStats(): Promise<Record<MemoryTier, {
9485
+ count: number;
9486
+ sizeBytes: number;
9487
+ }>>;
9359
9488
  /**
9360
- * Estimate savings from compaction
9489
+ * Get statistics about memory usage
9361
9490
  */
9362
- estimateSavings(component: IContextComponent): number;
9363
- }
9364
- /**
9365
- * Context management strategy - defines the overall approach to managing context
9366
- */
9367
- interface IContextStrategy {
9368
- /** Strategy name */
9369
- readonly name: string;
9491
+ getStats(): Promise<{
9492
+ totalEntries: number;
9493
+ totalSizeBytes: number;
9494
+ utilizationPercent: number;
9495
+ byPriority: Record<MemoryPriority, number>;
9496
+ pinnedCount: number;
9497
+ }>;
9370
9498
  /**
9371
- * Decide if compaction is needed based on current budget
9499
+ * Get the configured memory limit
9372
9500
  */
9373
- shouldCompact(budget: ContextBudget, config: ContextManagerConfig): boolean;
9501
+ getLimit(): number;
9374
9502
  /**
9375
- * Execute compaction using available compactors
9503
+ * Check if the WorkingMemory instance has been destroyed
9376
9504
  */
9377
- compact(components: IContextComponent[], budget: ContextBudget, compactors: IContextCompactor[], estimator: ITokenEstimator): Promise<{
9378
- components: IContextComponent[];
9379
- log: string[];
9380
- tokensFreed: number;
9381
- }>;
9505
+ get isDestroyed(): boolean;
9382
9506
  /**
9383
- * Optional: Prepare components before budget calculation
9384
- * Use this for strategies that pre-process context (e.g., rolling window)
9507
+ * Destroy the WorkingMemory instance
9508
+ * Removes all event listeners and clears internal state
9385
9509
  */
9386
- prepareComponents?(components: IContextComponent[]): Promise<IContextComponent[]>;
9510
+ destroy(): void;
9387
9511
  /**
9388
- * Optional: Post-process after compaction
9389
- * Use this for strategies that need cleanup or optimization
9512
+ * Serialize all memory entries for persistence
9513
+ *
9514
+ * Returns a serializable representation of all memory entries
9515
+ * that can be saved to storage and restored later.
9516
+ *
9517
+ * @returns Serialized memory state
9390
9518
  */
9391
- postProcess?(components: IContextComponent[], budget: ContextBudget): Promise<IContextComponent[]>;
9519
+ serialize(): Promise<SerializedMemory>;
9392
9520
  /**
9393
- * Optional: Get strategy-specific metrics
9521
+ * Restore memory entries from serialized state
9522
+ *
9523
+ * Clears existing memory and repopulates from the serialized state.
9524
+ * Timestamps are reset to current time.
9525
+ *
9526
+ * @param state - Previously serialized memory state
9394
9527
  */
9395
- getMetrics?(): Record<string, unknown>;
9396
- }
9397
-
9398
- /**
9399
- * Truncate Compactor
9400
- *
9401
- * Truncates content to target size by:
9402
- * - For strings: Cut to character limit
9403
- * - For arrays: Keep most recent items
9404
- */
9405
-
9406
- declare class TruncateCompactor implements IContextCompactor {
9407
- private estimator;
9408
- readonly name = "truncate";
9409
- readonly priority = 10;
9410
- constructor(estimator: ITokenEstimator);
9411
- canCompact(component: IContextComponent): boolean;
9412
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9413
- estimateSavings(component: IContextComponent): number;
9414
- private truncateString;
9415
- private truncateArray;
9528
+ restore(state: SerializedMemory): Promise<void>;
9416
9529
  }
9417
9530
 
9418
9531
  /**
9419
- * Summarize Compactor
9420
- *
9421
- * Uses LLM to create intelligent summaries of context components before compaction.
9422
- * This preserves the semantic meaning of content while reducing token count.
9423
- *
9424
- * Supports different summarization strategies based on content type:
9425
- * - Conversation history: Preserves decisions, facts, and preferences
9426
- * - Tool outputs (search/scrape): Preserves key findings, sources, and data
9532
+ * ExternalDependencyHandler - handles external dependencies
9427
9533
  */
9428
9534
 
9429
- /**
9430
- * Configuration for the SummarizeCompactor
9431
- */
9432
- interface SummarizeCompactorConfig {
9433
- /** Text provider for LLM-based summarization */
9434
- textProvider: ITextProvider;
9435
- /** Model to use for summarization (optional - uses provider default) */
9436
- model?: string;
9437
- /** Maximum tokens for the summary (default: 500) */
9438
- maxSummaryTokens?: number;
9439
- /** Preserve markdown structure like headings and lists (default: true) */
9440
- preserveStructure?: boolean;
9441
- /** Fall back to truncation if LLM summarization fails (default: true) */
9442
- fallbackToTruncate?: boolean;
9443
- /** Temperature for summarization (default: 0.3 for deterministic output) */
9444
- temperature?: number;
9535
+ interface ExternalDependencyEvents {
9536
+ 'webhook:received': {
9537
+ webhookId: string;
9538
+ data: unknown;
9539
+ };
9540
+ 'poll:success': {
9541
+ taskId: string;
9542
+ data: unknown;
9543
+ };
9544
+ 'poll:timeout': {
9545
+ taskId: string;
9546
+ };
9547
+ 'scheduled:triggered': {
9548
+ taskId: string;
9549
+ };
9550
+ 'manual:completed': {
9551
+ taskId: string;
9552
+ data: unknown;
9553
+ };
9445
9554
  }
9446
9555
  /**
9447
- * SummarizeCompactor - LLM-based context compaction
9448
- *
9449
- * Uses AI to intelligently summarize content, preserving semantic meaning
9450
- * while significantly reducing token count.
9556
+ * Handles external task dependencies
9451
9557
  */
9452
- declare class SummarizeCompactor implements IContextCompactor {
9453
- readonly name = "summarize";
9454
- readonly priority = 5;
9455
- private config;
9456
- private estimator;
9457
- constructor(estimator: ITokenEstimator, config: SummarizeCompactorConfig);
9558
+ declare class ExternalDependencyHandler extends EventEmitter<ExternalDependencyEvents> {
9559
+ private activePolls;
9560
+ private activeScheduled;
9561
+ private cancelledPolls;
9562
+ private tools;
9563
+ constructor(tools?: ToolFunction[]);
9458
9564
  /**
9459
- * Check if this compactor can handle the component
9565
+ * Start handling a task's external dependency
9460
9566
  */
9461
- canCompact(component: IContextComponent): boolean;
9567
+ startWaiting(task: Task): Promise<void>;
9462
9568
  /**
9463
- * Compact the component by summarizing its content
9569
+ * Stop waiting on a task's external dependency
9464
9570
  */
9465
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9571
+ stopWaiting(task: Task): void;
9466
9572
  /**
9467
- * Estimate how many tokens could be saved by summarization
9573
+ * Trigger a webhook
9468
9574
  */
9469
- estimateSavings(component: IContextComponent): number;
9575
+ triggerWebhook(webhookId: string, data: unknown): Promise<void>;
9470
9576
  /**
9471
- * Perform LLM-based summarization
9577
+ * Complete a manual task
9472
9578
  */
9473
- private summarize;
9579
+ completeManual(taskId: string, data: unknown): Promise<void>;
9474
9580
  /**
9475
- * Fallback to simple truncation when LLM fails
9581
+ * Start polling for a task with exponential backoff
9476
9582
  */
9477
- private truncateFallback;
9583
+ private startPolling;
9478
9584
  /**
9479
- * Detect content type from component metadata or name
9585
+ * Schedule a task to trigger at a specific time
9480
9586
  */
9481
- private detectContentType;
9587
+ private scheduleTask;
9482
9588
  /**
9483
- * Convert content to string for processing
9589
+ * Cleanup all active dependencies
9484
9590
  */
9485
- private stringifyContent;
9591
+ cleanup(): void;
9592
+ /**
9593
+ * Update available tools
9594
+ */
9595
+ updateTools(tools: ToolFunction[]): void;
9486
9596
  }
9487
9597
 
9488
9598
  /**
9489
- * Memory Eviction Compactor
9490
- *
9491
- * Evicts LRU entries from memory index
9492
- * Works with memory components that have eviction metadata
9599
+ * CheckpointManager - manages agent state checkpointing
9493
9600
  */
9494
9601
 
9495
- declare class MemoryEvictionCompactor implements IContextCompactor {
9496
- private estimator;
9497
- readonly name = "memory-eviction";
9498
- readonly priority = 8;
9499
- constructor(estimator: ITokenEstimator);
9500
- canCompact(component: IContextComponent): boolean;
9501
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9502
- estimateSavings(component: IContextComponent): number;
9602
+ interface CheckpointStrategy {
9603
+ /** Checkpoint after every N tool calls */
9604
+ afterToolCalls?: number;
9605
+ /** Checkpoint after every N LLM calls */
9606
+ afterLLMCalls?: number;
9607
+ /** Checkpoint on time interval */
9608
+ intervalMs?: number;
9609
+ /** Always checkpoint before external wait */
9610
+ beforeExternalWait: boolean;
9611
+ /** Checkpoint mode */
9612
+ mode: 'sync' | 'async';
9503
9613
  }
9504
-
9614
+ declare const DEFAULT_CHECKPOINT_STRATEGY: CheckpointStrategy;
9505
9615
  /**
9506
- * Approximate Token Estimator
9507
- *
9508
- * Uses content-type aware heuristics:
9509
- * - Code: ~3 chars/token (more symbols, shorter words)
9510
- * - Prose: ~4 chars/token (natural language)
9511
- * - Mixed: ~3.5 chars/token
9512
- *
9513
- * Fast and good enough for most use cases.
9616
+ * Manages state checkpointing for persistence and recovery
9514
9617
  */
9515
-
9516
- declare class ApproximateTokenEstimator implements ITokenEstimator {
9618
+ declare class CheckpointManager {
9619
+ private storage;
9620
+ private strategy;
9621
+ private toolCallsSinceCheckpoint;
9622
+ private llmCallsSinceCheckpoint;
9623
+ private intervalTimer?;
9624
+ private pendingCheckpoints;
9625
+ private currentState;
9626
+ constructor(storage: IAgentStorage, strategy?: CheckpointStrategy);
9517
9627
  /**
9518
- * Estimate tokens for text with content-type awareness
9519
- *
9520
- * @param text - The text to estimate tokens for
9521
- * @param contentType - Type of content:
9522
- * - 'code': Code is typically denser (~3 chars/token)
9523
- * - 'prose': Natural language text (~4 chars/token)
9524
- * - 'mixed': Mix of code and prose (~3.5 chars/token)
9628
+ * Set the current agent state (for interval checkpointing)
9525
9629
  */
9526
- estimateTokens(text: string, contentType?: TokenContentType): number;
9630
+ setCurrentState(state: AgentState): void;
9631
+ /**
9632
+ * Record a tool call (may trigger checkpoint)
9633
+ */
9634
+ onToolCall(state: AgentState): Promise<void>;
9635
+ /**
9636
+ * Record an LLM call (may trigger checkpoint)
9637
+ */
9638
+ onLLMCall(state: AgentState): Promise<void>;
9639
+ /**
9640
+ * Force a checkpoint
9641
+ */
9642
+ checkpoint(state: AgentState, reason: string): Promise<void>;
9643
+ /**
9644
+ * Perform the actual checkpoint
9645
+ */
9646
+ private doCheckpoint;
9647
+ /**
9648
+ * Check if interval-based checkpoint is needed
9649
+ */
9650
+ private checkIntervalCheckpoint;
9527
9651
  /**
9528
- * Estimate tokens for structured data (always uses 'mixed' estimation)
9652
+ * Wait for all pending checkpoints to complete
9529
9653
  */
9530
- estimateDataTokens(data: unknown, contentType?: TokenContentType): number;
9654
+ flush(): Promise<void>;
9531
9655
  /**
9532
- * Estimate tokens for an image using tile-based model (matches OpenAI pricing).
9533
- *
9534
- * - detail='low': 85 tokens
9535
- * - detail='high' with known dimensions: 85 + 170 per 512×512 tile
9536
- * - Unknown dimensions: 1000 tokens (conservative default)
9656
+ * Cleanup resources
9537
9657
  */
9538
- estimateImageTokens(width?: number, height?: number, detail?: string): number;
9658
+ cleanup(): Promise<void>;
9539
9659
  }
9540
9660
 
9541
9661
  /**
9542
- * Token estimators
9543
- */
9544
-
9545
- /**
9546
- * Create token estimator from name
9547
- */
9548
- declare function createEstimator(name: string): ITokenEstimator;
9549
-
9550
- /**
9551
- * IHistoryManager - Interface for conversation history management
9662
+ * PlanningAgent - AI-driven plan generation
9552
9663
  *
9553
- * Follows the same pattern as IMemoryStorage for pluggable implementations.
9554
- * Users can implement this interface to use Redis, PostgreSQL, file storage, etc.
9664
+ * Separates planning phase from execution phase.
9665
+ * Analyzes goals and generates task graphs with dependencies.
9555
9666
  */
9556
9667
 
9557
9668
  /**
9558
- * A single message in conversation history
9559
- */
9560
- interface HistoryMessage {
9561
- id: string;
9562
- role: 'user' | 'assistant' | 'system';
9563
- content: string;
9564
- timestamp: number;
9565
- metadata?: Record<string, unknown>;
9566
- }
9567
- /**
9568
- * Events emitted by IHistoryManager implementations
9569
- */
9570
- interface HistoryManagerEvents {
9571
- 'message:added': {
9572
- message: HistoryMessage;
9573
- };
9574
- 'message:removed': {
9575
- messageId: string;
9576
- };
9577
- 'history:cleared': {
9578
- reason?: string;
9579
- };
9580
- 'history:compacted': {
9581
- removedCount: number;
9582
- strategy: string;
9583
- };
9584
- 'history:restored': {
9585
- messageCount: number;
9586
- };
9587
- }
9588
- /**
9589
- * Configuration for history management
9669
+ * PlanningAgent configuration
9590
9670
  */
9591
- interface IHistoryManagerConfig {
9592
- /** Maximum messages to keep (for sliding window) */
9593
- maxMessages?: number;
9594
- /** Maximum tokens to keep (estimated) */
9595
- maxTokens?: number;
9596
- /** Compaction strategy when limits are reached */
9597
- compactionStrategy?: 'truncate' | 'summarize' | 'sliding-window';
9598
- /** Number of recent messages to always preserve */
9599
- preserveRecentCount?: number;
9671
+ interface PlanningAgentConfig {
9672
+ /** Connector for LLM access */
9673
+ connector: string | Connector;
9674
+ /** Model to use for planning (can be different/cheaper than execution) */
9675
+ model: string;
9676
+ /** Max planning iterations */
9677
+ maxPlanningIterations?: number;
9678
+ /** Temperature for planning (lower = more deterministic) */
9679
+ planningTemperature?: number;
9680
+ /** Tools available for the plan (used to inform planning) */
9681
+ availableTools?: ToolFunction[];
9600
9682
  }
9601
9683
  /**
9602
- * Serialized history state for persistence
9684
+ * Generated plan with metadata
9603
9685
  */
9604
- interface SerializedHistoryState {
9605
- version: number;
9606
- messages: HistoryMessage[];
9607
- summaries?: Array<{
9608
- content: string;
9609
- coversCount: number;
9610
- timestamp: number;
9611
- }>;
9612
- metadata?: Record<string, unknown>;
9686
+ interface GeneratedPlan {
9687
+ plan: Plan;
9688
+ reasoning: string;
9689
+ estimated_duration?: string;
9690
+ complexity?: 'low' | 'medium' | 'high';
9613
9691
  }
9614
9692
  /**
9615
- * Interface for history storage backends
9616
- * Implement this to use custom storage (Redis, PostgreSQL, file, etc.)
9693
+ * PlanningAgent class
9617
9694
  */
9618
- interface IHistoryStorage {
9619
- /**
9620
- * Store a message
9621
- */
9622
- addMessage(message: HistoryMessage): Promise<void>;
9623
- /**
9624
- * Get all messages
9625
- */
9626
- getMessages(): Promise<HistoryMessage[]>;
9627
- /**
9628
- * Get recent N messages
9629
- */
9630
- getRecentMessages(count: number): Promise<HistoryMessage[]>;
9631
- /**
9632
- * Remove a message by ID
9633
- */
9634
- removeMessage(id: string): Promise<void>;
9695
+ declare class PlanningAgent {
9696
+ private agent;
9697
+ private config;
9698
+ private currentTasks;
9699
+ private planningComplete;
9700
+ private constructor();
9635
9701
  /**
9636
- * Remove messages older than timestamp
9702
+ * Create a new PlanningAgent
9637
9703
  */
9638
- removeOlderThan(timestamp: number): Promise<number>;
9704
+ static create(config: PlanningAgentConfig): PlanningAgent;
9639
9705
  /**
9640
- * Clear all messages
9706
+ * Create planning tools bound to this PlanningAgent instance
9641
9707
  */
9642
- clear(): Promise<void>;
9708
+ private createBoundPlanningTools;
9643
9709
  /**
9644
- * Get message count
9710
+ * Generate a plan from a goal
9645
9711
  */
9646
- getCount(): Promise<number>;
9712
+ generatePlan(input: {
9713
+ goal: string;
9714
+ context?: string;
9715
+ constraints?: string[];
9716
+ }): Promise<GeneratedPlan>;
9647
9717
  /**
9648
- * Get serialized state for session persistence
9718
+ * Validate and refine an existing plan
9649
9719
  */
9650
- getState(): Promise<SerializedHistoryState>;
9720
+ refinePlan(plan: Plan, feedback: string): Promise<GeneratedPlan>;
9651
9721
  /**
9652
- * Restore from serialized state
9722
+ * Build planning prompt from input
9653
9723
  */
9654
- restoreState(state: SerializedHistoryState): Promise<void>;
9655
- }
9656
- /**
9657
- * Interface for history manager
9658
- * Manages conversation history with compaction and persistence support
9659
- */
9660
- interface IHistoryManager extends EventEmitter<HistoryManagerEvents> {
9724
+ private buildPlanningPrompt;
9661
9725
  /**
9662
- * Add a message to history
9726
+ * Estimate plan complexity
9663
9727
  */
9664
- addMessage(role: 'user' | 'assistant' | 'system', content: string, metadata?: Record<string, unknown>): Promise<HistoryMessage>;
9728
+ private estimateComplexity;
9665
9729
  /**
9666
- * Get all messages (may include summaries as system messages)
9730
+ * Get current tasks (for tool access)
9667
9731
  */
9668
- getMessages(): Promise<HistoryMessage[]>;
9732
+ getCurrentTasks(): TaskInput[];
9669
9733
  /**
9670
- * Get recent messages only
9734
+ * Add task (called by planning tools)
9671
9735
  */
9672
- getRecentMessages(count?: number): Promise<HistoryMessage[]>;
9736
+ addTask(task: TaskInput): void;
9673
9737
  /**
9674
- * Get formatted history for LLM context
9738
+ * Update task (called by planning tools)
9675
9739
  */
9676
- formatForContext(options?: {
9677
- maxTokens?: number;
9678
- includeMetadata?: boolean;
9679
- }): Promise<string>;
9740
+ updateTask(name: string, updates: Partial<TaskInput>): void;
9680
9741
  /**
9681
- * Compact history (apply compaction strategy)
9742
+ * Remove task (called by planning tools)
9682
9743
  */
9683
- compact(): Promise<void>;
9744
+ removeTask(name: string): void;
9684
9745
  /**
9685
- * Clear all history
9746
+ * Mark planning as complete
9686
9747
  */
9687
- clear(): Promise<void>;
9748
+ finalizePlanning(): void;
9749
+ }
9750
+ /**
9751
+ * Simple plan generation without tools (fallback)
9752
+ */
9753
+ declare function generateSimplePlan(goal: string, context?: string): Promise<Plan>;
9754
+
9755
+ /**
9756
+ * ResearchAgent Types
9757
+ *
9758
+ * Generic interfaces for research sources that work with any data provider:
9759
+ * - Web search (Serper, Brave, Tavily)
9760
+ * - Vector databases (Pinecone, Weaviate, Qdrant)
9761
+ * - File systems (local, S3, GCS)
9762
+ * - APIs (REST, GraphQL)
9763
+ * - Databases (SQL, MongoDB)
9764
+ */
9765
+ /**
9766
+ * A single search result from any source
9767
+ */
9768
+ interface SourceResult {
9769
+ /** Unique identifier for this result */
9770
+ id: string;
9771
+ /** Human-readable title */
9772
+ title: string;
9773
+ /** Brief description or snippet */
9774
+ snippet: string;
9775
+ /** Reference for fetching full content (URL, path, ID, etc.) */
9776
+ reference: string;
9777
+ /** Relevance score (0-1, higher is better) */
9778
+ relevance?: number;
9779
+ /** Source-specific metadata */
9780
+ metadata?: Record<string, unknown>;
9781
+ }
9782
+ /**
9783
+ * Response from a search operation
9784
+ */
9785
+ interface SearchResponse {
9786
+ /** Whether the search succeeded */
9787
+ success: boolean;
9788
+ /** Original query */
9789
+ query: string;
9790
+ /** Results found */
9791
+ results: SourceResult[];
9792
+ /** Total results available (may be more than returned) */
9793
+ totalResults?: number;
9794
+ /** Error message if failed */
9795
+ error?: string;
9796
+ /** Source-specific metadata */
9797
+ metadata?: Record<string, unknown>;
9798
+ }
9799
+ /**
9800
+ * Fetched content from a source
9801
+ */
9802
+ interface FetchedContent {
9803
+ /** Whether fetch succeeded */
9804
+ success: boolean;
9805
+ /** Reference that was fetched */
9806
+ reference: string;
9807
+ /** The actual content */
9808
+ content: unknown;
9809
+ /** Content type hint (text, html, json, binary, etc.) */
9810
+ contentType?: string;
9811
+ /** Size in bytes */
9812
+ sizeBytes?: number;
9813
+ /** Error message if failed */
9814
+ error?: string;
9815
+ /** Source-specific metadata */
9816
+ metadata?: Record<string, unknown>;
9817
+ }
9818
+ /**
9819
+ * Options for search operations
9820
+ */
9821
+ interface SearchOptions {
9822
+ /** Maximum results to return */
9823
+ maxResults?: number;
9824
+ /** Minimum relevance score (0-1) */
9825
+ minRelevance?: number;
9826
+ /** Source-specific options */
9827
+ sourceOptions?: Record<string, unknown>;
9828
+ }
9829
+ /**
9830
+ * Options for fetch operations
9831
+ */
9832
+ interface FetchOptions {
9833
+ /** Maximum content size to fetch (bytes) */
9834
+ maxSize?: number;
9835
+ /** Timeout in milliseconds */
9836
+ timeoutMs?: number;
9837
+ /** Source-specific options */
9838
+ sourceOptions?: Record<string, unknown>;
9839
+ }
9840
+ /**
9841
+ * Generic research source interface
9842
+ *
9843
+ * Implement this interface to add any data source to ResearchAgent:
9844
+ * - Web: search queries, fetch URLs
9845
+ * - Vector DB: similarity search, fetch documents
9846
+ * - File system: glob patterns, read files
9847
+ * - API: query endpoints, fetch resources
9848
+ */
9849
+ interface IResearchSource {
9850
+ /** Unique name for this source */
9851
+ readonly name: string;
9852
+ /** Human-readable description */
9853
+ readonly description: string;
9854
+ /** Type of source (for categorization) */
9855
+ readonly type: 'web' | 'vector' | 'file' | 'api' | 'database' | 'custom';
9688
9856
  /**
9689
- * Get message count
9857
+ * Search this source for relevant results
9858
+ *
9859
+ * @param query - Search query (interpreted by source)
9860
+ * @param options - Search options
9861
+ * @returns Search response with results
9690
9862
  */
9691
- getMessageCount(): Promise<number>;
9863
+ search(query: string, options?: SearchOptions): Promise<SearchResponse>;
9692
9864
  /**
9693
- * Get state for session persistence
9865
+ * Fetch full content for a result
9866
+ *
9867
+ * @param reference - Reference from SourceResult
9868
+ * @param options - Fetch options
9869
+ * @returns Fetched content
9694
9870
  */
9695
- getState(): Promise<SerializedHistoryState>;
9871
+ fetch(reference: string, options?: FetchOptions): Promise<FetchedContent>;
9696
9872
  /**
9697
- * Restore from saved state
9873
+ * Optional: Check if source is available/configured
9698
9874
  */
9699
- restoreState(state: SerializedHistoryState): Promise<void>;
9875
+ isAvailable?(): Promise<boolean>;
9700
9876
  /**
9701
- * Get current configuration
9877
+ * Optional: Get source capabilities
9702
9878
  */
9703
- getConfig(): IHistoryManagerConfig;
9879
+ getCapabilities?(): SourceCapabilities;
9704
9880
  }
9705
9881
  /**
9706
- * Default configuration
9882
+ * Source capabilities for discovery
9707
9883
  */
9708
- declare const DEFAULT_HISTORY_MANAGER_CONFIG: Required<IHistoryManagerConfig>;
9709
-
9884
+ interface SourceCapabilities {
9885
+ /** Whether source supports search */
9886
+ canSearch: boolean;
9887
+ /** Whether source supports fetch */
9888
+ canFetch: boolean;
9889
+ /** Whether results include relevance scores */
9890
+ hasRelevanceScores: boolean;
9891
+ /** Maximum results per search */
9892
+ maxResultsPerSearch?: number;
9893
+ /** Supported content types */
9894
+ contentTypes?: string[];
9895
+ }
9710
9896
  /**
9711
- * InMemoryHistoryStorage - In-memory implementation of IHistoryStorage
9712
- *
9713
- * Default storage backend for conversation history.
9714
- * For production, users can implement IHistoryStorage with Redis, PostgreSQL, etc.
9897
+ * Research finding stored in memory
9715
9898
  */
9716
-
9899
+ interface ResearchFinding {
9900
+ /** Source that provided this finding */
9901
+ source: string;
9902
+ /** Original query that found this */
9903
+ query: string;
9904
+ /** Key insight or summary */
9905
+ summary: string;
9906
+ /** Supporting details */
9907
+ details?: string;
9908
+ /** References used */
9909
+ references: string[];
9910
+ /** Confidence level (0-1) */
9911
+ confidence?: number;
9912
+ /** When this was found */
9913
+ timestamp: number;
9914
+ }
9717
9915
  /**
9718
- * In-memory history storage implementation
9916
+ * Research plan for systematic research
9719
9917
  */
9720
- declare class InMemoryHistoryStorage implements IHistoryStorage {
9721
- private messages;
9722
- private summaries;
9723
- addMessage(message: HistoryMessage): Promise<void>;
9724
- getMessages(): Promise<HistoryMessage[]>;
9725
- getRecentMessages(count: number): Promise<HistoryMessage[]>;
9726
- removeMessage(id: string): Promise<void>;
9727
- removeOlderThan(timestamp: number): Promise<number>;
9728
- clear(): Promise<void>;
9729
- getCount(): Promise<number>;
9730
- getState(): Promise<SerializedHistoryState>;
9731
- restoreState(state: SerializedHistoryState): Promise<void>;
9918
+ interface ResearchPlan {
9919
+ /** Research goal/question */
9920
+ goal: string;
9921
+ /** Queries to execute */
9922
+ queries: ResearchQuery[];
9923
+ /** Sources to use (empty = all available) */
9924
+ sources?: string[];
9925
+ /** Maximum results per query */
9926
+ maxResultsPerQuery?: number;
9927
+ /** Maximum total findings */
9928
+ maxTotalFindings?: number;
9732
9929
  }
9733
-
9734
9930
  /**
9735
- * Routine Control Flow map, fold, until handlers + template resolution
9736
- *
9737
- * Control flow tasks delegate to executeRoutine() recursively with the shared agent,
9738
- * using ICM keys (__map_item, __map_index, etc.) to pass iteration state.
9931
+ * A query in the research plan
9739
9932
  */
9740
-
9741
- /** Well-known ICM/WM keys used by the routine execution framework. */
9742
- declare const ROUTINE_KEYS: {
9743
- /** Plan overview with task statuses (ICM) */
9744
- readonly PLAN: "__routine_plan";
9745
- /** Dependency results location guide (ICM) */
9746
- readonly DEPS: "__routine_deps";
9747
- /** Prefix for per-dependency result keys (ICM/WM) */
9748
- readonly DEP_RESULT_PREFIX: "__dep_result_";
9749
- /** Current map/fold item (ICM) */
9750
- readonly MAP_ITEM: "__map_item";
9751
- /** Current map/fold index, 0-based (ICM) */
9752
- readonly MAP_INDEX: "__map_index";
9753
- /** Total items in map/fold (ICM) */
9754
- readonly MAP_TOTAL: "__map_total";
9755
- /** Running fold accumulator (ICM) */
9756
- readonly FOLD_ACCUMULATOR: "__fold_accumulator";
9757
- /** Prefix for large dep results stored in WM findings tier */
9758
- readonly WM_DEP_FINDINGS_PREFIX: "findings/__dep_result_";
9759
- /** Prefix for auto-stored task outputs (set by output contracts) */
9760
- readonly TASK_OUTPUT_PREFIX: "__task_output_";
9761
- };
9762
- interface ControlFlowResult {
9763
- completed: boolean;
9764
- result?: unknown;
9765
- error?: string;
9933
+ interface ResearchQuery {
9934
+ /** Query string */
9935
+ query: string;
9936
+ /** Specific sources for this query (empty = all) */
9937
+ sources?: string[];
9938
+ /** Priority (higher = more important) */
9939
+ priority?: number;
9766
9940
  }
9767
9941
  /**
9768
- * Resolve template placeholders in text.
9769
- *
9770
- * Supported namespaces:
9771
- * - {{param.name}} → inputs[name]
9772
- * - {{map.item}} / {{map.index}} / {{map.total}} → ICM keys
9773
- * - {{fold.accumulator}} → ICM key
9774
- *
9775
- * Non-string values are JSON.stringify'd. Unresolved templates are left as-is.
9942
+ * Research execution result
9776
9943
  */
9777
- declare function resolveTemplates(text: string, inputs: Record<string, unknown>, icmPlugin: InContextMemoryPluginNextGen | null): string;
9944
+ interface ResearchResult {
9945
+ /** Whether research completed successfully */
9946
+ success: boolean;
9947
+ /** Original goal */
9948
+ goal: string;
9949
+ /** Queries executed */
9950
+ queriesExecuted: number;
9951
+ /** Results found */
9952
+ resultsFound: number;
9953
+ /** Results processed */
9954
+ resultsProcessed: number;
9955
+ /** Findings generated */
9956
+ findingsCount: number;
9957
+ /** Final synthesis (if generated) */
9958
+ synthesis?: string;
9959
+ /** Error if failed */
9960
+ error?: string;
9961
+ /** Execution metrics */
9962
+ metrics?: {
9963
+ totalDurationMs: number;
9964
+ searchDurationMs: number;
9965
+ processDurationMs: number;
9966
+ synthesizeDurationMs: number;
9967
+ };
9968
+ }
9778
9969
  /**
9779
- * Resolve the source array for a map/fold control flow using layered resolution:
9780
- * 1. Determine lookup key(s) from source config
9781
- * 2. Read from ICM/WM with fallback chain
9782
- * 3. Apply JSON path extraction if specified
9783
- * 4. Coerce to array algorithmically (JSON parse, common field names)
9784
- * 5. LLM extraction fallback if still not an array
9970
+ * Research progress event
9785
9971
  */
9786
- declare function resolveFlowSource(flow: {
9787
- source: ControlFlowSource;
9788
- maxIterations?: number;
9789
- }, flowType: string, agent: Agent, execution: RoutineExecution | undefined, icmPlugin: InContextMemoryPluginNextGen | null, wmPlugin: WorkingMemoryPluginNextGen | null): Promise<{
9790
- array: unknown[];
9791
- maxIter: number;
9792
- } | ControlFlowResult>;
9972
+ interface ResearchProgress {
9973
+ phase: 'searching' | 'processing' | 'synthesizing' | 'complete';
9974
+ currentQuery?: string;
9975
+ currentSource?: string;
9976
+ queriesCompleted: number;
9977
+ totalQueries: number;
9978
+ resultsProcessed: number;
9979
+ totalResults: number;
9980
+ findingsGenerated: number;
9981
+ }
9793
9982
 
9794
9983
  /**
9795
- * FilePersistentInstructionsStorage - File-based storage for persistent instructions
9796
- *
9797
- * Stores custom agent instructions as a JSON file on disk.
9798
- * Path: ~/.oneringai/agents/<agentId>/custom_instructions.json
9799
- * Windows: %APPDATA%/oneringai/agents/<agentId>/custom_instructions.json
9800
- *
9801
- * Features:
9802
- * - Cross-platform path handling
9803
- * - Safe agent ID sanitization
9804
- * - Atomic file operations
9805
- * - Automatic directory creation
9806
- * - Legacy .md file migration
9984
+ * Core types for context management system
9985
+ */
9986
+ /**
9987
+ * Context component that can be compacted
9988
+ */
9989
+ interface IContextComponent {
9990
+ /** Unique name for this component */
9991
+ name: string;
9992
+ /** The actual content (string or structured data) */
9993
+ content: string | unknown;
9994
+ /** Priority for compaction (higher = compact first) */
9995
+ priority: number;
9996
+ /** Whether this component can be compacted */
9997
+ compactable: boolean;
9998
+ /** Additional metadata for compaction strategies */
9999
+ metadata?: Record<string, unknown>;
10000
+ }
10001
+ /**
10002
+ * Context budget information
10003
+ */
10004
+ interface ContextBudget {
10005
+ /** Total available tokens */
10006
+ total: number;
10007
+ /** Reserved tokens for response */
10008
+ reserved: number;
10009
+ /** Currently used tokens */
10010
+ used: number;
10011
+ /** Available tokens remaining */
10012
+ available: number;
10013
+ /** Utilization percentage (used / (total - reserved)) */
10014
+ utilizationPercent: number;
10015
+ /** Budget status */
10016
+ status: 'ok' | 'warning' | 'critical';
10017
+ /** Token breakdown by component */
10018
+ breakdown: Record<string, number>;
10019
+ }
10020
+ /**
10021
+ * Context manager configuration
10022
+ */
10023
+ interface ContextManagerConfig {
10024
+ /** Maximum context tokens for the model */
10025
+ maxContextTokens: number;
10026
+ /** Threshold to trigger compaction (0.0 - 1.0) */
10027
+ compactionThreshold: number;
10028
+ /** Hard limit - must compact before this (0.0 - 1.0) */
10029
+ hardLimit: number;
10030
+ /** Reserve space for response (0.0 - 1.0) */
10031
+ responseReserve: number;
10032
+ /** Token estimator to use */
10033
+ estimator: 'approximate' | 'tiktoken' | ITokenEstimator;
10034
+ /** Enable automatic compaction */
10035
+ autoCompact: boolean;
10036
+ /** Strategy to use */
10037
+ strategy?: 'proactive' | 'aggressive' | 'lazy' | 'rolling-window' | 'adaptive' | IContextStrategy;
10038
+ /** Strategy-specific options */
10039
+ strategyOptions?: Record<string, unknown>;
10040
+ }
10041
+ /**
10042
+ * Default configuration
9807
10043
  */
9808
-
10044
+ declare const DEFAULT_CONTEXT_CONFIG: ContextManagerConfig;
9809
10045
  /**
9810
- * Configuration for FilePersistentInstructionsStorage
10046
+ * Content type for more accurate token estimation
10047
+ * Named differently from TokenContentType in Content.ts to avoid conflicts
9811
10048
  */
9812
- interface FilePersistentInstructionsStorageConfig {
9813
- /** Agent ID (used to create unique storage path) */
9814
- agentId: string;
9815
- /** Override the base directory (default: ~/.oneringai/agents) */
9816
- baseDirectory?: string;
9817
- /** Override the filename (default: custom_instructions.json) */
9818
- filename?: string;
9819
- }
10049
+ type TokenContentType = 'code' | 'prose' | 'mixed';
9820
10050
  /**
9821
- * File-based storage for persistent agent instructions
10051
+ * Abstract interface for token estimation
9822
10052
  */
9823
- declare class FilePersistentInstructionsStorage implements IPersistentInstructionsStorage {
9824
- private readonly directory;
9825
- private readonly filePath;
9826
- private readonly legacyFilePath;
9827
- private readonly agentId;
9828
- constructor(config: FilePersistentInstructionsStorageConfig);
9829
- /**
9830
- * Load instruction entries from file.
9831
- * Falls back to legacy .md file migration if JSON not found.
9832
- */
9833
- load(): Promise<InstructionEntry[] | null>;
9834
- /**
9835
- * Save instruction entries to file as JSON.
9836
- * Creates directory if it doesn't exist.
9837
- * Cleans up legacy .md file if present.
9838
- */
9839
- save(entries: InstructionEntry[]): Promise<void>;
9840
- /**
9841
- * Delete instructions file (and legacy .md if exists)
9842
- */
9843
- delete(): Promise<void>;
9844
- /**
9845
- * Check if instructions file exists (JSON or legacy .md)
9846
- */
9847
- exists(): Promise<boolean>;
9848
- /**
9849
- * Get the file path (for display/debugging)
9850
- */
9851
- getPath(): string;
10053
+ interface ITokenEstimator {
9852
10054
  /**
9853
- * Get the agent ID
10055
+ * Estimate token count for text
10056
+ *
10057
+ * @param text - The text to estimate
10058
+ * @param contentType - Type of content for more accurate estimation:
10059
+ * - 'code': Code is typically denser (~3 chars/token)
10060
+ * - 'prose': Natural language text (~4 chars/token)
10061
+ * - 'mixed': Mix of code and prose (~3.5 chars/token)
9854
10062
  */
9855
- getAgentId(): string;
10063
+ estimateTokens(text: string, contentType?: TokenContentType): number;
9856
10064
  /**
9857
- * Ensure the directory exists
10065
+ * Estimate tokens for structured data
9858
10066
  */
9859
- private ensureDirectory;
10067
+ estimateDataTokens(data: unknown, contentType?: TokenContentType): number;
9860
10068
  /**
9861
- * Remove legacy .md file if it exists
10069
+ * Estimate tokens for an image.
10070
+ * @param width - Image width in pixels (if known)
10071
+ * @param height - Image height in pixels (if known)
10072
+ * @param detail - Image detail level: 'low', 'high', or 'auto'
9862
10073
  */
9863
- private removeLegacyFile;
9864
- }
9865
-
9866
- /**
9867
- * FileContextStorage - File-based storage for AgentContext session persistence
9868
- *
9869
- * Stores context sessions as JSON files on disk.
9870
- * Path: ~/.oneringai/agents/<agentId>/sessions/<sessionId>.json
9871
- * Windows: %APPDATA%/oneringai/agents/<agentId>/sessions/<sessionId>.json
9872
- *
9873
- * Features:
9874
- * - Cross-platform path handling
9875
- * - Safe session ID sanitization
9876
- * - Atomic file operations (write to temp, then rename)
9877
- * - Automatic directory creation
9878
- * - Index file for fast listing
9879
- */
9880
-
9881
- /**
9882
- * Configuration for FileContextStorage
9883
- */
9884
- interface FileContextStorageConfig {
9885
- /** Agent ID (used to create unique storage path) */
9886
- agentId: string;
9887
- /** Override the base directory (default: ~/.oneringai/agents) */
9888
- baseDirectory?: string;
9889
- /** Pretty-print JSON (default: true for debugging, false in production) */
9890
- prettyPrint?: boolean;
10074
+ estimateImageTokens?(width?: number, height?: number, detail?: string): number;
9891
10075
  }
9892
10076
  /**
9893
- * File-based storage for AgentContext session persistence
10077
+ * Abstract interface for compaction strategies
9894
10078
  */
9895
- declare class FileContextStorage implements IContextStorage {
9896
- private readonly agentId;
9897
- private readonly sessionsDirectory;
9898
- private readonly indexPath;
9899
- private readonly prettyPrint;
9900
- private index;
9901
- constructor(config: FileContextStorageConfig);
9902
- /**
9903
- * Save context state to a session file
9904
- */
9905
- save(sessionId: string, state: SerializedContextState, metadata?: ContextSessionMetadata): Promise<void>;
9906
- /**
9907
- * Load context state from a session file
9908
- */
9909
- load(sessionId: string): Promise<StoredContextSession | null>;
10079
+ interface IContextCompactor {
10080
+ /** Compactor name */
10081
+ readonly name: string;
10082
+ /** Priority order (lower = run first) */
10083
+ readonly priority: number;
9910
10084
  /**
9911
- * Delete a session
10085
+ * Check if this compactor can handle the component
9912
10086
  */
9913
- delete(sessionId: string): Promise<void>;
10087
+ canCompact(component: IContextComponent): boolean;
9914
10088
  /**
9915
- * Check if a session exists
10089
+ * Compact the component to target size
9916
10090
  */
9917
- exists(sessionId: string): Promise<boolean>;
10091
+ compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9918
10092
  /**
9919
- * List all sessions (summaries only)
10093
+ * Estimate savings from compaction
9920
10094
  */
9921
- list(options?: ContextStorageListOptions): Promise<ContextSessionSummary[]>;
10095
+ estimateSavings(component: IContextComponent): number;
10096
+ }
10097
+ /**
10098
+ * Context management strategy - defines the overall approach to managing context
10099
+ */
10100
+ interface IContextStrategy {
10101
+ /** Strategy name */
10102
+ readonly name: string;
9922
10103
  /**
9923
- * Update session metadata without loading full state
10104
+ * Decide if compaction is needed based on current budget
9924
10105
  */
9925
- updateMetadata(sessionId: string, metadata: Partial<ContextSessionMetadata>): Promise<void>;
10106
+ shouldCompact(budget: ContextBudget, config: ContextManagerConfig): boolean;
9926
10107
  /**
9927
- * Get the storage path (for display/debugging)
9928
- * @deprecated Use getLocation() instead
10108
+ * Execute compaction using available compactors
9929
10109
  */
9930
- getPath(): string;
10110
+ compact(components: IContextComponent[], budget: ContextBudget, compactors: IContextCompactor[], estimator: ITokenEstimator): Promise<{
10111
+ components: IContextComponent[];
10112
+ log: string[];
10113
+ tokensFreed: number;
10114
+ }>;
9931
10115
  /**
9932
- * Get a human-readable storage location string (for display/debugging)
10116
+ * Optional: Prepare components before budget calculation
10117
+ * Use this for strategies that pre-process context (e.g., rolling window)
9933
10118
  */
9934
- getLocation(): string;
10119
+ prepareComponents?(components: IContextComponent[]): Promise<IContextComponent[]>;
9935
10120
  /**
9936
- * Get the agent ID
10121
+ * Optional: Post-process after compaction
10122
+ * Use this for strategies that need cleanup or optimization
9937
10123
  */
9938
- getAgentId(): string;
10124
+ postProcess?(components: IContextComponent[], budget: ContextBudget): Promise<IContextComponent[]>;
9939
10125
  /**
9940
- * Rebuild the index by scanning all session files
9941
- * Useful for recovery or migration
10126
+ * Optional: Get strategy-specific metrics
9942
10127
  */
9943
- rebuildIndex(): Promise<void>;
9944
- private getFilePath;
9945
- private ensureDirectory;
9946
- private loadRaw;
9947
- private loadIndex;
9948
- private saveIndex;
9949
- private updateIndex;
9950
- private removeFromIndex;
9951
- private storedToIndexEntry;
10128
+ getMetrics?(): Record<string, unknown>;
9952
10129
  }
10130
+
9953
10131
  /**
9954
- * Create a FileContextStorage for the given agent
9955
- *
9956
- * @param agentId - Agent ID
9957
- * @param options - Optional configuration
9958
- * @returns FileContextStorage instance
9959
- *
9960
- * @example
9961
- * ```typescript
9962
- * const storage = createFileContextStorage('my-agent');
9963
- * const ctx = AgentContext.create({
9964
- * model: 'gpt-4',
9965
- * storage,
9966
- * });
9967
- *
9968
- * // Save session
9969
- * await ctx.save('session-001', { title: 'My Session' });
10132
+ * Truncate Compactor
9970
10133
  *
9971
- * // Load session
9972
- * await ctx.load('session-001');
9973
- * ```
10134
+ * Truncates content to target size by:
10135
+ * - For strings: Cut to character limit
10136
+ * - For arrays: Keep most recent items
9974
10137
  */
9975
- declare function createFileContextStorage(agentId: string, options?: Omit<FileContextStorageConfig, 'agentId'>): FileContextStorage;
10138
+
10139
+ declare class TruncateCompactor implements IContextCompactor {
10140
+ private estimator;
10141
+ readonly name = "truncate";
10142
+ readonly priority = 10;
10143
+ constructor(estimator: ITokenEstimator);
10144
+ canCompact(component: IContextComponent): boolean;
10145
+ compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
10146
+ estimateSavings(component: IContextComponent): number;
10147
+ private truncateString;
10148
+ private truncateArray;
10149
+ }
9976
10150
 
9977
10151
  /**
9978
- * FileAgentDefinitionStorage - File-based storage for agent definitions
10152
+ * Summarize Compactor
9979
10153
  *
9980
- * Stores agent definitions as JSON files on disk.
9981
- * Path: ~/.oneringai/agents/<agentId>/definition.json
9982
- * Windows: %APPDATA%/oneringai/agents/<agentId>/definition.json
10154
+ * Uses LLM to create intelligent summaries of context components before compaction.
10155
+ * This preserves the semantic meaning of content while reducing token count.
9983
10156
  *
9984
- * Features:
9985
- * - Cross-platform path handling
9986
- * - Safe agent ID sanitization
9987
- * - Atomic file operations
9988
- * - Automatic directory creation
9989
- * - Index file for fast listing
10157
+ * Supports different summarization strategies based on content type:
10158
+ * - Conversation history: Preserves decisions, facts, and preferences
10159
+ * - Tool outputs (search/scrape): Preserves key findings, sources, and data
9990
10160
  */
9991
10161
 
9992
10162
  /**
9993
- * Configuration for FileAgentDefinitionStorage
10163
+ * Configuration for the SummarizeCompactor
9994
10164
  */
9995
- interface FileAgentDefinitionStorageConfig {
9996
- /** Override the base directory (default: ~/.oneringai/agents) */
9997
- baseDirectory?: string;
9998
- /** Pretty-print JSON (default: true) */
9999
- prettyPrint?: boolean;
10165
+ interface SummarizeCompactorConfig {
10166
+ /** Text provider for LLM-based summarization */
10167
+ textProvider: ITextProvider;
10168
+ /** Model to use for summarization (optional - uses provider default) */
10169
+ model?: string;
10170
+ /** Maximum tokens for the summary (default: 500) */
10171
+ maxSummaryTokens?: number;
10172
+ /** Preserve markdown structure like headings and lists (default: true) */
10173
+ preserveStructure?: boolean;
10174
+ /** Fall back to truncation if LLM summarization fails (default: true) */
10175
+ fallbackToTruncate?: boolean;
10176
+ /** Temperature for summarization (default: 0.3 for deterministic output) */
10177
+ temperature?: number;
10000
10178
  }
10001
10179
  /**
10002
- * File-based storage for agent definitions
10180
+ * SummarizeCompactor - LLM-based context compaction
10181
+ *
10182
+ * Uses AI to intelligently summarize content, preserving semantic meaning
10183
+ * while significantly reducing token count.
10003
10184
  */
10004
- declare class FileAgentDefinitionStorage implements IAgentDefinitionStorage {
10005
- private readonly baseDirectory;
10006
- private readonly indexPath;
10007
- private readonly prettyPrint;
10008
- private index;
10009
- constructor(config?: FileAgentDefinitionStorageConfig);
10010
- /**
10011
- * Save an agent definition
10012
- */
10013
- save(definition: StoredAgentDefinition): Promise<void>;
10185
+ declare class SummarizeCompactor implements IContextCompactor {
10186
+ readonly name = "summarize";
10187
+ readonly priority = 5;
10188
+ private config;
10189
+ private estimator;
10190
+ constructor(estimator: ITokenEstimator, config: SummarizeCompactorConfig);
10014
10191
  /**
10015
- * Load an agent definition
10192
+ * Check if this compactor can handle the component
10016
10193
  */
10017
- load(agentId: string): Promise<StoredAgentDefinition | null>;
10194
+ canCompact(component: IContextComponent): boolean;
10018
10195
  /**
10019
- * Delete an agent definition
10196
+ * Compact the component by summarizing its content
10020
10197
  */
10021
- delete(agentId: string): Promise<void>;
10198
+ compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
10022
10199
  /**
10023
- * Check if an agent definition exists
10200
+ * Estimate how many tokens could be saved by summarization
10024
10201
  */
10025
- exists(agentId: string): Promise<boolean>;
10202
+ estimateSavings(component: IContextComponent): number;
10026
10203
  /**
10027
- * List all agent definitions
10204
+ * Perform LLM-based summarization
10028
10205
  */
10029
- list(options?: AgentDefinitionListOptions): Promise<AgentDefinitionSummary[]>;
10206
+ private summarize;
10030
10207
  /**
10031
- * Update metadata without loading full definition
10208
+ * Fallback to simple truncation when LLM fails
10032
10209
  */
10033
- updateMetadata(agentId: string, metadata: Partial<AgentDefinitionMetadata>): Promise<void>;
10210
+ private truncateFallback;
10034
10211
  /**
10035
- * Get storage path
10212
+ * Detect content type from component metadata or name
10036
10213
  */
10037
- getPath(): string;
10214
+ private detectContentType;
10038
10215
  /**
10039
- * Rebuild the index by scanning all agent directories
10216
+ * Convert content to string for processing
10040
10217
  */
10041
- rebuildIndex(): Promise<void>;
10042
- private ensureDirectory;
10043
- private loadRaw;
10044
- private loadIndex;
10045
- private saveIndex;
10046
- private updateIndex;
10047
- private removeFromIndex;
10048
- private definitionToIndexEntry;
10218
+ private stringifyContent;
10049
10219
  }
10220
+
10050
10221
  /**
10051
- * Create a FileAgentDefinitionStorage with default configuration
10222
+ * Memory Eviction Compactor
10223
+ *
10224
+ * Evicts LRU entries from memory index
10225
+ * Works with memory components that have eviction metadata
10052
10226
  */
10053
- declare function createFileAgentDefinitionStorage(config?: FileAgentDefinitionStorageConfig): FileAgentDefinitionStorage;
10227
+
10228
+ declare class MemoryEvictionCompactor implements IContextCompactor {
10229
+ private estimator;
10230
+ readonly name = "memory-eviction";
10231
+ readonly priority = 8;
10232
+ constructor(estimator: ITokenEstimator);
10233
+ canCompact(component: IContextComponent): boolean;
10234
+ compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
10235
+ estimateSavings(component: IContextComponent): number;
10236
+ }
10054
10237
 
10055
10238
  /**
10056
- * FileMediaStorage - File-based media storage implementation
10239
+ * Approximate Token Estimator
10057
10240
  *
10058
- * Saves generated media to a configurable directory on the local filesystem.
10059
- * Default output directory: `os.tmpdir()/oneringai-media/`
10241
+ * Uses content-type aware heuristics:
10242
+ * - Code: ~3 chars/token (more symbols, shorter words)
10243
+ * - Prose: ~4 chars/token (natural language)
10244
+ * - Mixed: ~3.5 chars/token
10245
+ *
10246
+ * Fast and good enough for most use cases.
10060
10247
  */
10061
10248
 
10062
- interface FileMediaStorageConfig {
10063
- /** Directory to store media files. Defaults to `os.tmpdir()/oneringai-media/` */
10064
- outputDir?: string;
10065
- }
10066
- declare class FileMediaStorage implements IMediaStorage {
10067
- private outputDir;
10068
- private initialized;
10069
- constructor(config?: FileMediaStorageConfig);
10070
- save(data: Buffer, metadata: MediaStorageMetadata): Promise<MediaStorageResult>;
10071
- read(location: string): Promise<Buffer | null>;
10072
- delete(location: string): Promise<void>;
10073
- exists(location: string): Promise<boolean>;
10074
- list(options?: MediaStorageListOptions): Promise<MediaStorageEntry[]>;
10075
- getPath(): string;
10076
- private generateFilename;
10077
- private ensureDir;
10249
+ declare class ApproximateTokenEstimator implements ITokenEstimator {
10250
+ /**
10251
+ * Estimate tokens for text with content-type awareness
10252
+ *
10253
+ * @param text - The text to estimate tokens for
10254
+ * @param contentType - Type of content:
10255
+ * - 'code': Code is typically denser (~3 chars/token)
10256
+ * - 'prose': Natural language text (~4 chars/token)
10257
+ * - 'mixed': Mix of code and prose (~3.5 chars/token)
10258
+ */
10259
+ estimateTokens(text: string, contentType?: TokenContentType): number;
10260
+ /**
10261
+ * Estimate tokens for structured data (always uses 'mixed' estimation)
10262
+ */
10263
+ estimateDataTokens(data: unknown, contentType?: TokenContentType): number;
10264
+ /**
10265
+ * Estimate tokens for an image using tile-based model (matches OpenAI pricing).
10266
+ *
10267
+ * - detail='low': 85 tokens
10268
+ * - detail='high' with known dimensions: 85 + 170 per 512×512 tile
10269
+ * - Unknown dimensions: 1000 tokens (conservative default)
10270
+ */
10271
+ estimateImageTokens(width?: number, height?: number, detail?: string): number;
10078
10272
  }
10273
+
10079
10274
  /**
10080
- * Factory function for creating FileMediaStorage instances
10275
+ * Token estimators
10081
10276
  */
10082
- declare function createFileMediaStorage(config?: FileMediaStorageConfig): FileMediaStorage;
10083
10277
 
10084
10278
  /**
10085
- * FileCustomToolStorage - File-based storage for custom tool definitions
10086
- *
10087
- * Stores custom tools as JSON files on disk with per-user isolation.
10088
- * Path: ~/.oneringai/users/<userId>/custom-tools/<sanitized-name>.json
10279
+ * Create token estimator from name
10280
+ */
10281
+ declare function createEstimator(name: string): ITokenEstimator;
10282
+
10283
+ /**
10284
+ * IHistoryManager - Interface for conversation history management
10089
10285
  *
10090
- * Features:
10091
- * - Per-user isolation (multi-tenant safe)
10092
- * - Cross-platform path handling
10093
- * - Safe name sanitization
10094
- * - Atomic file operations (write to .tmp then rename)
10095
- * - Per-user index file for fast listing
10096
- * - Search support (case-insensitive substring on name + description)
10286
+ * Follows the same pattern as IMemoryStorage for pluggable implementations.
10287
+ * Users can implement this interface to use Redis, PostgreSQL, file storage, etc.
10097
10288
  */
10098
10289
 
10099
10290
  /**
10100
- * Configuration for FileCustomToolStorage
10291
+ * A single message in conversation history
10101
10292
  */
10102
- interface FileCustomToolStorageConfig {
10103
- /** Override the base directory (default: ~/.oneringai/users) */
10104
- baseDirectory?: string;
10105
- /** Pretty-print JSON (default: true) */
10106
- prettyPrint?: boolean;
10293
+ interface HistoryMessage {
10294
+ id: string;
10295
+ role: 'user' | 'assistant' | 'system';
10296
+ content: string;
10297
+ timestamp: number;
10298
+ metadata?: Record<string, unknown>;
10107
10299
  }
10108
10300
  /**
10109
- * File-based storage for custom tool definitions
10110
- *
10111
- * Single instance handles all users. UserId is passed to each method.
10301
+ * Events emitted by IHistoryManager implementations
10112
10302
  */
10113
- declare class FileCustomToolStorage implements ICustomToolStorage {
10114
- private readonly baseDirectory;
10115
- private readonly prettyPrint;
10116
- constructor(config?: FileCustomToolStorageConfig);
10117
- /**
10118
- * Get the directory path for a specific user's custom tools
10119
- */
10120
- private getUserDirectory;
10303
+ interface HistoryManagerEvents {
10304
+ 'message:added': {
10305
+ message: HistoryMessage;
10306
+ };
10307
+ 'message:removed': {
10308
+ messageId: string;
10309
+ };
10310
+ 'history:cleared': {
10311
+ reason?: string;
10312
+ };
10313
+ 'history:compacted': {
10314
+ removedCount: number;
10315
+ strategy: string;
10316
+ };
10317
+ 'history:restored': {
10318
+ messageCount: number;
10319
+ };
10320
+ }
10321
+ /**
10322
+ * Configuration for history management
10323
+ */
10324
+ interface IHistoryManagerConfig {
10325
+ /** Maximum messages to keep (for sliding window) */
10326
+ maxMessages?: number;
10327
+ /** Maximum tokens to keep (estimated) */
10328
+ maxTokens?: number;
10329
+ /** Compaction strategy when limits are reached */
10330
+ compactionStrategy?: 'truncate' | 'summarize' | 'sliding-window';
10331
+ /** Number of recent messages to always preserve */
10332
+ preserveRecentCount?: number;
10333
+ }
10334
+ /**
10335
+ * Serialized history state for persistence
10336
+ */
10337
+ interface SerializedHistoryState {
10338
+ version: number;
10339
+ messages: HistoryMessage[];
10340
+ summaries?: Array<{
10341
+ content: string;
10342
+ coversCount: number;
10343
+ timestamp: number;
10344
+ }>;
10345
+ metadata?: Record<string, unknown>;
10346
+ }
10347
+ /**
10348
+ * Interface for history storage backends
10349
+ * Implement this to use custom storage (Redis, PostgreSQL, file, etc.)
10350
+ */
10351
+ interface IHistoryStorage {
10121
10352
  /**
10122
- * Get the index file path for a specific user
10353
+ * Store a message
10123
10354
  */
10124
- private getUserIndexPath;
10355
+ addMessage(message: HistoryMessage): Promise<void>;
10125
10356
  /**
10126
- * Get the tool file path for a specific user
10357
+ * Get all messages
10127
10358
  */
10128
- private getToolPath;
10359
+ getMessages(): Promise<HistoryMessage[]>;
10129
10360
  /**
10130
- * Save a custom tool definition
10361
+ * Get recent N messages
10131
10362
  */
10132
- save(userId: string | undefined, definition: CustomToolDefinition): Promise<void>;
10363
+ getRecentMessages(count: number): Promise<HistoryMessage[]>;
10133
10364
  /**
10134
- * Load a custom tool definition by name
10365
+ * Remove a message by ID
10135
10366
  */
10136
- load(userId: string | undefined, name: string): Promise<CustomToolDefinition | null>;
10367
+ removeMessage(id: string): Promise<void>;
10137
10368
  /**
10138
- * Delete a custom tool definition
10369
+ * Remove messages older than timestamp
10139
10370
  */
10140
- delete(userId: string | undefined, name: string): Promise<void>;
10371
+ removeOlderThan(timestamp: number): Promise<number>;
10141
10372
  /**
10142
- * Check if a custom tool exists
10373
+ * Clear all messages
10143
10374
  */
10144
- exists(userId: string | undefined, name: string): Promise<boolean>;
10375
+ clear(): Promise<void>;
10145
10376
  /**
10146
- * List custom tools (summaries only)
10377
+ * Get message count
10147
10378
  */
10148
- list(userId: string | undefined, options?: CustomToolListOptions): Promise<CustomToolSummary[]>;
10379
+ getCount(): Promise<number>;
10149
10380
  /**
10150
- * Update metadata without loading full definition
10381
+ * Get serialized state for session persistence
10151
10382
  */
10152
- updateMetadata(userId: string | undefined, name: string, metadata: Record<string, unknown>): Promise<void>;
10383
+ getState(): Promise<SerializedHistoryState>;
10153
10384
  /**
10154
- * Get storage path for a specific user
10385
+ * Restore from serialized state
10155
10386
  */
10156
- getPath(userId: string | undefined): string;
10157
- private ensureDirectory;
10158
- private loadIndex;
10159
- private saveIndex;
10160
- private updateIndex;
10161
- private removeFromIndex;
10162
- private definitionToIndexEntry;
10163
- }
10164
- /**
10165
- * Create a FileCustomToolStorage with default configuration
10166
- */
10167
- declare function createFileCustomToolStorage(config?: FileCustomToolStorageConfig): FileCustomToolStorage;
10168
-
10169
- /**
10170
- * FileUserInfoStorage - File-based storage for user information
10171
- *
10172
- * Stores user information as a JSON file on disk.
10173
- * Path: ~/.oneringai/users/<userId>/user_info.json
10174
- * Windows: %APPDATA%/oneringai/users/<userId>/user_info.json
10175
- *
10176
- * Features:
10177
- * - Cross-platform path handling
10178
- * - Safe user ID sanitization
10179
- * - Atomic file operations
10180
- * - Automatic directory creation
10181
- * - Multi-user support (one storage instance for all users)
10182
- */
10183
-
10184
- /**
10185
- * Configuration for FileUserInfoStorage
10186
- */
10187
- interface FileUserInfoStorageConfig {
10188
- /** Override the base directory (default: ~/.oneringai/users) */
10189
- baseDirectory?: string;
10190
- /** Override the filename (default: user_info.json) */
10191
- filename?: string;
10387
+ restoreState(state: SerializedHistoryState): Promise<void>;
10192
10388
  }
10193
10389
  /**
10194
- * File-based storage for user information
10195
- *
10196
- * Single instance handles all users. UserId is passed to each method.
10390
+ * Interface for history manager
10391
+ * Manages conversation history with compaction and persistence support
10197
10392
  */
10198
- declare class FileUserInfoStorage implements IUserInfoStorage {
10199
- private readonly baseDirectory;
10200
- private readonly filename;
10201
- constructor(config?: FileUserInfoStorageConfig);
10393
+ interface IHistoryManager extends EventEmitter<HistoryManagerEvents> {
10202
10394
  /**
10203
- * Get the directory path for a specific user
10395
+ * Add a message to history
10204
10396
  */
10205
- private getUserDirectory;
10397
+ addMessage(role: 'user' | 'assistant' | 'system', content: string, metadata?: Record<string, unknown>): Promise<HistoryMessage>;
10206
10398
  /**
10207
- * Get the file path for a specific user
10399
+ * Get all messages (may include summaries as system messages)
10208
10400
  */
10209
- private getUserFilePath;
10401
+ getMessages(): Promise<HistoryMessage[]>;
10210
10402
  /**
10211
- * Load user info entries from file for a specific user
10403
+ * Get recent messages only
10212
10404
  */
10213
- load(userId: string | undefined): Promise<UserInfoEntry[] | null>;
10405
+ getRecentMessages(count?: number): Promise<HistoryMessage[]>;
10214
10406
  /**
10215
- * Save user info entries to file for a specific user
10216
- * Creates directory if it doesn't exist.
10407
+ * Get formatted history for LLM context
10217
10408
  */
10218
- save(userId: string | undefined, entries: UserInfoEntry[]): Promise<void>;
10409
+ formatForContext(options?: {
10410
+ maxTokens?: number;
10411
+ includeMetadata?: boolean;
10412
+ }): Promise<string>;
10219
10413
  /**
10220
- * Delete user info file for a specific user
10414
+ * Compact history (apply compaction strategy)
10221
10415
  */
10222
- delete(userId: string | undefined): Promise<void>;
10416
+ compact(): Promise<void>;
10223
10417
  /**
10224
- * Check if user info file exists for a specific user
10418
+ * Clear all history
10225
10419
  */
10226
- exists(userId: string | undefined): Promise<boolean>;
10420
+ clear(): Promise<void>;
10227
10421
  /**
10228
- * Get the file path for a specific user (for display/debugging)
10422
+ * Get message count
10229
10423
  */
10230
- getPath(userId: string | undefined): string;
10424
+ getMessageCount(): Promise<number>;
10231
10425
  /**
10232
- * Ensure the directory exists
10426
+ * Get state for session persistence
10233
10427
  */
10234
- private ensureDirectory;
10428
+ getState(): Promise<SerializedHistoryState>;
10429
+ /**
10430
+ * Restore from saved state
10431
+ */
10432
+ restoreState(state: SerializedHistoryState): Promise<void>;
10433
+ /**
10434
+ * Get current configuration
10435
+ */
10436
+ getConfig(): IHistoryManagerConfig;
10235
10437
  }
10438
+ /**
10439
+ * Default configuration
10440
+ */
10441
+ declare const DEFAULT_HISTORY_MANAGER_CONFIG: Required<IHistoryManagerConfig>;
10236
10442
 
10237
10443
  /**
10238
- * FileRoutineDefinitionStorage - File-based storage for routine definitions.
10239
- *
10240
- * Stores routines as JSON files on disk with per-user isolation.
10241
- * Path: ~/.oneringai/users/<userId>/routines/<sanitized-id>.json
10444
+ * InMemoryHistoryStorage - In-memory implementation of IHistoryStorage
10242
10445
  *
10243
- * Features:
10244
- * - Per-user isolation (multi-tenant safe)
10245
- * - Cross-platform path handling
10246
- * - Safe ID sanitization
10247
- * - Atomic file operations (write to .tmp then rename)
10248
- * - Per-user index file for fast listing/filtering
10249
- * - Index auto-rebuild if missing
10446
+ * Default storage backend for conversation history.
10447
+ * For production, users can implement IHistoryStorage with Redis, PostgreSQL, etc.
10250
10448
  */
10251
10449
 
10252
10450
  /**
10253
- * Configuration for FileRoutineDefinitionStorage
10451
+ * In-memory history storage implementation
10254
10452
  */
10255
- interface FileRoutineDefinitionStorageConfig {
10256
- /** Override the base directory (default: ~/.oneringai/users) */
10257
- baseDirectory?: string;
10258
- /** Pretty-print JSON (default: true) */
10259
- prettyPrint?: boolean;
10453
+ declare class InMemoryHistoryStorage implements IHistoryStorage {
10454
+ private messages;
10455
+ private summaries;
10456
+ addMessage(message: HistoryMessage): Promise<void>;
10457
+ getMessages(): Promise<HistoryMessage[]>;
10458
+ getRecentMessages(count: number): Promise<HistoryMessage[]>;
10459
+ removeMessage(id: string): Promise<void>;
10460
+ removeOlderThan(timestamp: number): Promise<number>;
10461
+ clear(): Promise<void>;
10462
+ getCount(): Promise<number>;
10463
+ getState(): Promise<SerializedHistoryState>;
10464
+ restoreState(state: SerializedHistoryState): Promise<void>;
10260
10465
  }
10466
+
10261
10467
  /**
10262
- * File-based storage for routine definitions.
10468
+ * Routine Control Flow map, fold, until handlers + template resolution
10263
10469
  *
10264
- * Single instance handles all users. UserId is passed to each method.
10470
+ * Control flow tasks delegate to executeRoutine() recursively with the shared agent,
10471
+ * using ICM keys (__map_item, __map_index, etc.) to pass iteration state.
10265
10472
  */
10266
- declare class FileRoutineDefinitionStorage implements IRoutineDefinitionStorage {
10267
- private readonly baseDirectory;
10268
- private readonly prettyPrint;
10269
- constructor(config?: FileRoutineDefinitionStorageConfig);
10270
- private getUserDirectory;
10271
- private getIndexPath;
10272
- private getRoutinePath;
10273
- save(userId: string | undefined, definition: RoutineDefinition): Promise<void>;
10274
- load(userId: string | undefined, id: string): Promise<RoutineDefinition | null>;
10275
- delete(userId: string | undefined, id: string): Promise<void>;
10276
- exists(userId: string | undefined, id: string): Promise<boolean>;
10277
- list(userId: string | undefined, options?: {
10278
- tags?: string[];
10279
- search?: string;
10280
- limit?: number;
10281
- offset?: number;
10282
- }): Promise<RoutineDefinition[]>;
10283
- getPath(userId: string | undefined): string;
10284
- private ensureDirectory;
10285
- private loadIndex;
10286
- private saveIndex;
10287
- private updateIndex;
10288
- private removeFromIndex;
10289
- private definitionToIndexEntry;
10290
- /**
10291
- * Rebuild index by scanning directory for .json files (excluding _index.json).
10292
- * Returns empty index if directory doesn't exist.
10293
- */
10294
- private rebuildIndex;
10473
+
10474
+ /** Well-known ICM/WM keys used by the routine execution framework. */
10475
+ declare const ROUTINE_KEYS: {
10476
+ /** Plan overview with task statuses (ICM) */
10477
+ readonly PLAN: "__routine_plan";
10478
+ /** Dependency results location guide (ICM) */
10479
+ readonly DEPS: "__routine_deps";
10480
+ /** Prefix for per-dependency result keys (ICM/WM) */
10481
+ readonly DEP_RESULT_PREFIX: "__dep_result_";
10482
+ /** Current map/fold item (ICM) */
10483
+ readonly MAP_ITEM: "__map_item";
10484
+ /** Current map/fold index, 0-based (ICM) */
10485
+ readonly MAP_INDEX: "__map_index";
10486
+ /** Total items in map/fold (ICM) */
10487
+ readonly MAP_TOTAL: "__map_total";
10488
+ /** Running fold accumulator (ICM) */
10489
+ readonly FOLD_ACCUMULATOR: "__fold_accumulator";
10490
+ /** Prefix for large dep results stored in WM findings tier */
10491
+ readonly WM_DEP_FINDINGS_PREFIX: "findings/__dep_result_";
10492
+ /** Prefix for auto-stored task outputs (set by output contracts) */
10493
+ readonly TASK_OUTPUT_PREFIX: "__task_output_";
10494
+ };
10495
+ interface ControlFlowResult {
10496
+ completed: boolean;
10497
+ result?: unknown;
10498
+ error?: string;
10295
10499
  }
10296
10500
  /**
10297
- * Create a FileRoutineDefinitionStorage with default configuration
10501
+ * Resolve template placeholders in text.
10502
+ *
10503
+ * Supported namespaces:
10504
+ * - {{param.name}} → inputs[name]
10505
+ * - {{map.item}} / {{map.index}} / {{map.total}} → ICM keys
10506
+ * - {{fold.accumulator}} → ICM key
10507
+ *
10508
+ * Non-string values are JSON.stringify'd. Unresolved templates are left as-is.
10298
10509
  */
10299
- declare function createFileRoutineDefinitionStorage(config?: FileRoutineDefinitionStorageConfig): FileRoutineDefinitionStorage;
10510
+ declare function resolveTemplates(text: string, inputs: Record<string, unknown>, icmPlugin: InContextMemoryPluginNextGen | null): string;
10511
+ /**
10512
+ * Resolve the source array for a map/fold control flow using layered resolution:
10513
+ * 1. Determine lookup key(s) from source config
10514
+ * 2. Read from ICM/WM with fallback chain
10515
+ * 3. Apply JSON path extraction if specified
10516
+ * 4. Coerce to array algorithmically (JSON parse, common field names)
10517
+ * 5. LLM extraction fallback if still not an array
10518
+ */
10519
+ declare function resolveFlowSource(flow: {
10520
+ source: ControlFlowSource;
10521
+ maxIterations?: number;
10522
+ }, flowType: string, agent: Agent, execution: RoutineExecution | undefined, icmPlugin: InContextMemoryPluginNextGen | null, wmPlugin: WorkingMemoryPluginNextGen | null): Promise<{
10523
+ array: unknown[];
10524
+ maxIter: number;
10525
+ } | ControlFlowResult>;
10300
10526
 
10301
10527
  /**
10302
10528
  * Video Model Registry
@@ -10431,6 +10657,10 @@ declare class StreamState {
10431
10657
  currentIteration: number;
10432
10658
  usage: TokenUsage;
10433
10659
  status: 'in_progress' | 'completed' | 'incomplete' | 'failed';
10660
+ /** Status reported by the provider's RESPONSE_COMPLETE event. Defaults to 'incomplete' (safe if never received). */
10661
+ providerStatus: 'completed' | 'incomplete' | 'failed';
10662
+ /** Raw stop reason from provider (e.g., 'end_turn', 'max_tokens', 'SAFETY') */
10663
+ stopReason?: string;
10434
10664
  startTime: Date;
10435
10665
  endTime?: Date;
10436
10666
  totalChunks: number;
@@ -10548,6 +10778,8 @@ declare class StreamState {
10548
10778
  reasoning_tokens: number;
10549
10779
  };
10550
10780
  };
10781
+ providerStatus: "completed" | "failed" | "incomplete";
10782
+ stopReason: string | undefined;
10551
10783
  };
10552
10784
  /**
10553
10785
  * Check if stream has any accumulated text
@@ -10583,6 +10815,8 @@ declare class StreamState {
10583
10815
  };
10584
10816
  };
10585
10817
  status: "in_progress" | "completed" | "failed" | "incomplete";
10818
+ providerStatus: "completed" | "failed" | "incomplete";
10819
+ stopReason: string | undefined;
10586
10820
  startTime: Date;
10587
10821
  endTime: Date | undefined;
10588
10822
  };
@@ -12137,6 +12371,8 @@ interface RateLimiterConfig {
12137
12371
  onLimit: 'wait' | 'throw';
12138
12372
  /** Max wait time in ms (for 'wait' mode, default: 60000) */
12139
12373
  maxWaitMs?: number;
12374
+ /** Max queued waiters (default: 500). Rejects new requests when exceeded. */
12375
+ maxQueueSize?: number;
12140
12376
  }
12141
12377
  /**
12142
12378
  * Default rate limiter configuration
@@ -13461,6 +13697,23 @@ interface GitHubPRCommentsResult {
13461
13697
  count?: number;
13462
13698
  error?: string;
13463
13699
  }
13700
+ /**
13701
+ * A branch entry
13702
+ */
13703
+ interface GitHubBranchEntry {
13704
+ name: string;
13705
+ sha: string;
13706
+ protected: boolean;
13707
+ }
13708
+ /**
13709
+ * Result from list_branches tool
13710
+ */
13711
+ interface GitHubListBranchesResult {
13712
+ success: boolean;
13713
+ branches?: GitHubBranchEntry[];
13714
+ count?: number;
13715
+ error?: string;
13716
+ }
13464
13717
  /**
13465
13718
  * Result from create_pr tool
13466
13719
  */
@@ -13506,7 +13759,9 @@ declare function createSearchFilesTool(connector: Connector, userId?: string): T
13506
13759
  * Search for code content across a GitHub repository.
13507
13760
  * Mirrors the local `grep` tool for remote GitHub repos.
13508
13761
  *
13509
- * Uses the GitHub Code Search API with text-match support.
13762
+ * Uses the GitHub Code Search API with text-match support for default branch.
13763
+ * Falls back to tree + blob scanning when a specific branch/ref is requested,
13764
+ * since GitHub's code search API only indexes the default branch.
13510
13765
  *
13511
13766
  * Note: GitHub's code search API has a rate limit of 30 requests/minute.
13512
13767
  */
@@ -13519,6 +13774,8 @@ interface SearchCodeArgs {
13519
13774
  repository?: string;
13520
13775
  /** Search query (keyword or phrase) */
13521
13776
  query: string;
13777
+ /** Branch, tag, or commit SHA. Defaults to the repository's default branch. */
13778
+ ref?: string;
13522
13779
  /** Filter by programming language (e.g., "typescript", "python") */
13523
13780
  language?: string;
13524
13781
  /** Filter by file path (e.g., "src/", "lib/utils") */
@@ -13652,6 +13909,31 @@ interface CreatePRArgs {
13652
13909
  */
13653
13910
  declare function createCreatePRTool(connector: Connector, userId?: string): ToolFunction<CreatePRArgs, GitHubCreatePRResult>;
13654
13911
 
13912
+ /**
13913
+ * GitHub List Branches Tool
13914
+ *
13915
+ * List branches in a GitHub repository.
13916
+ * Supports filtering by name pattern and pagination.
13917
+ */
13918
+
13919
+ /**
13920
+ * Arguments for the list_branches tool
13921
+ */
13922
+ interface ListBranchesArgs {
13923
+ /** Repository in "owner/repo" format or full GitHub URL */
13924
+ repository?: string;
13925
+ /** Filter branches by name prefix or substring (case-insensitive, client-side) */
13926
+ filter?: string;
13927
+ /** Include only protected branches (default: false — list all) */
13928
+ protected_only?: boolean;
13929
+ /** Maximum number of branches to return (default: 100, max: 100) */
13930
+ limit?: number;
13931
+ }
13932
+ /**
13933
+ * Create a GitHub list_branches tool
13934
+ */
13935
+ declare function createListBranchesTool(connector: Connector, userId?: string): ToolFunction<ListBranchesArgs, GitHubListBranchesResult>;
13936
+
13655
13937
  /**
13656
13938
  * Microsoft Graph Tools - Shared Types and Helpers
13657
13939
  *
@@ -14462,7 +14744,7 @@ declare const desktopTools: (ToolFunction<DesktopScreenshotArgs, DesktopScreensh
14462
14744
  * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
14463
14745
  *
14464
14746
  * Generated by: scripts/generate-tool-registry.ts
14465
- * Generated at: 2026-03-10T21:37:09.255Z
14747
+ * Generated at: 2026-03-12T18:47:09.908Z
14466
14748
  *
14467
14749
  * To regenerate: npm run generate:tools
14468
14750
  */
@@ -14902,8 +15184,10 @@ declare const index_FormatDetector: typeof FormatDetector;
14902
15184
  type index_GenericAPICallArgs = GenericAPICallArgs;
14903
15185
  type index_GenericAPICallResult = GenericAPICallResult;
14904
15186
  type index_GenericAPIToolOptions = GenericAPIToolOptions;
15187
+ type index_GitHubBranchEntry = GitHubBranchEntry;
14905
15188
  type index_GitHubCreatePRResult = GitHubCreatePRResult;
14906
15189
  type index_GitHubGetPRResult = GitHubGetPRResult;
15190
+ type index_GitHubListBranchesResult = GitHubListBranchesResult;
14907
15191
  type index_GitHubPRCommentEntry = GitHubPRCommentEntry;
14908
15192
  type index_GitHubPRCommentsResult = GitHubPRCommentsResult;
14909
15193
  type index_GitHubPRFilesResult = GitHubPRFilesResult;
@@ -14976,6 +15260,7 @@ declare const index_createGitHubReadFileTool: typeof createGitHubReadFileTool;
14976
15260
  declare const index_createGlobTool: typeof createGlobTool;
14977
15261
  declare const index_createGrepTool: typeof createGrepTool;
14978
15262
  declare const index_createImageGenerationTool: typeof createImageGenerationTool;
15263
+ declare const index_createListBranchesTool: typeof createListBranchesTool;
14979
15264
  declare const index_createListDirectoryTool: typeof createListDirectoryTool;
14980
15265
  declare const index_createMeetingTool: typeof createMeetingTool;
14981
15266
  declare const index_createMicrosoftListFilesTool: typeof createMicrosoftListFilesTool;
@@ -15061,7 +15346,7 @@ declare const index_validatePath: typeof validatePath;
15061
15346
  declare const index_webFetch: typeof webFetch;
15062
15347
  declare const index_writeFile: typeof writeFile;
15063
15348
  declare namespace index {
15064
- export { type index_BashResult as BashResult, type index_ConnectorToolEntry as ConnectorToolEntry, index_ConnectorTools as ConnectorTools, type index_CustomToolMetaToolsOptions as CustomToolMetaToolsOptions, index_DEFAULT_DESKTOP_CONFIG as DEFAULT_DESKTOP_CONFIG, index_DEFAULT_FILESYSTEM_CONFIG as DEFAULT_FILESYSTEM_CONFIG, index_DEFAULT_SHELL_CONFIG as DEFAULT_SHELL_CONFIG, index_DESKTOP_TOOL_NAMES as DESKTOP_TOOL_NAMES, type index_DesktopGetCursorResult as DesktopGetCursorResult, type index_DesktopGetScreenSizeResult as DesktopGetScreenSizeResult, type index_DesktopKeyboardKeyArgs as DesktopKeyboardKeyArgs, type index_DesktopKeyboardKeyResult as DesktopKeyboardKeyResult, type index_DesktopKeyboardTypeArgs as DesktopKeyboardTypeArgs, type index_DesktopKeyboardTypeResult as DesktopKeyboardTypeResult, type index_DesktopMouseClickArgs as DesktopMouseClickArgs, type index_DesktopMouseClickResult as DesktopMouseClickResult, type index_DesktopMouseDragArgs as DesktopMouseDragArgs, type index_DesktopMouseDragResult as DesktopMouseDragResult, type index_DesktopMouseMoveArgs as DesktopMouseMoveArgs, type index_DesktopMouseMoveResult as DesktopMouseMoveResult, type index_DesktopMouseScrollArgs as DesktopMouseScrollArgs, type index_DesktopMouseScrollResult as DesktopMouseScrollResult, type index_DesktopPoint as DesktopPoint, type index_DesktopScreenSize as DesktopScreenSize, type index_DesktopScreenshot as DesktopScreenshot, type index_DesktopScreenshotArgs as DesktopScreenshotArgs, type index_DesktopScreenshotResult as DesktopScreenshotResult, type index_DesktopToolConfig as DesktopToolConfig, type index_DesktopToolName as DesktopToolName, type index_DesktopWindow as DesktopWindow, type index_DesktopWindowFocusArgs as DesktopWindowFocusArgs, type index_DesktopWindowFocusResult as DesktopWindowFocusResult, type index_DesktopWindowListResult as DesktopWindowListResult, type index_DocumentFamily as DocumentFamily, type index_DocumentFormat as DocumentFormat, type index_DocumentImagePiece as DocumentImagePiece, type index_DocumentMetadata as DocumentMetadata, type index_DocumentPiece as DocumentPiece, type index_DocumentReadOptions as DocumentReadOptions, index_DocumentReader as DocumentReader, type index_DocumentReaderConfig as DocumentReaderConfig, type index_DocumentResult as DocumentResult, type index_DocumentSource as DocumentSource, type index_DocumentTextPiece as DocumentTextPiece, type index_DocumentToContentOptions as DocumentToContentOptions, type index_EditFileResult as EditFileResult, FileMediaStorage as FileMediaOutputHandler, type index_FilesystemToolConfig as FilesystemToolConfig, type index_FormatDetectionResult as FormatDetectionResult, index_FormatDetector as FormatDetector, type index_GenericAPICallArgs as GenericAPICallArgs, type index_GenericAPICallResult as GenericAPICallResult, type index_GenericAPIToolOptions as GenericAPIToolOptions, type index_GitHubCreatePRResult as GitHubCreatePRResult, type index_GitHubGetPRResult as GitHubGetPRResult, type index_GitHubPRCommentEntry as GitHubPRCommentEntry, type index_GitHubPRCommentsResult as GitHubPRCommentsResult, type index_GitHubPRFilesResult as GitHubPRFilesResult, type index_GitHubReadFileResult as GitHubReadFileResult, type index_GitHubRepository as GitHubRepository, type index_GitHubSearchCodeResult as GitHubSearchCodeResult, type index_GitHubSearchFilesResult as GitHubSearchFilesResult, type index_GlobResult as GlobResult, type index_GraphDriveItem as GraphDriveItem, type index_GrepMatch as GrepMatch, type index_GrepResult as GrepResult, type index_HydrateOptions as HydrateOptions, type index_IDesktopDriver as IDesktopDriver, type index_IDocumentTransformer as IDocumentTransformer, type index_IFormatHandler as IFormatHandler, type IMediaStorage as IMediaOutputHandler, type index_ImageFilterOptions as ImageFilterOptions, type MediaStorageMetadata as MediaOutputMetadata, type MediaStorageResult as MediaOutputResult, type index_MeetingSlotSuggestion as MeetingSlotSuggestion, type index_MicrosoftCreateMeetingResult as MicrosoftCreateMeetingResult, type index_MicrosoftDraftEmailResult as MicrosoftDraftEmailResult, type index_MicrosoftEditMeetingResult as MicrosoftEditMeetingResult, type index_MicrosoftFindSlotsResult as MicrosoftFindSlotsResult, type index_MicrosoftGetTranscriptResult as MicrosoftGetTranscriptResult, type index_MicrosoftListFilesResult as MicrosoftListFilesResult, type index_MicrosoftReadFileResult as MicrosoftReadFileResult, type index_MicrosoftSearchFilesResult as MicrosoftSearchFilesResult, type index_MicrosoftSendEmailResult as MicrosoftSendEmailResult, type index_MouseButton as MouseButton, index_NutTreeDriver as NutTreeDriver, type index_ReadFileResult as ReadFileResult, type index_SearchResult as SearchResult, type index_ServiceToolFactory as ServiceToolFactory, type index_ShellToolConfig as ShellToolConfig, type index_ToolCategory as ToolCategory, index_ToolRegistry as ToolRegistry, type index_ToolRegistryEntry as ToolRegistryEntry, type index_WriteFileResult as WriteFileResult, index_applyHumanDelay as applyHumanDelay, index_bash as bash, index_createBashTool as createBashTool, index_createCreatePRTool as createCreatePRTool, index_createCustomToolDelete as createCustomToolDelete, index_createCustomToolDraft as createCustomToolDraft, index_createCustomToolList as createCustomToolList, index_createCustomToolLoad as createCustomToolLoad, index_createCustomToolMetaTools as createCustomToolMetaTools, index_createCustomToolSave as createCustomToolSave, index_createCustomToolTest as createCustomToolTest, index_createDesktopGetCursorTool as createDesktopGetCursorTool, index_createDesktopGetScreenSizeTool as createDesktopGetScreenSizeTool, index_createDesktopKeyboardKeyTool as createDesktopKeyboardKeyTool, index_createDesktopKeyboardTypeTool as createDesktopKeyboardTypeTool, index_createDesktopMouseClickTool as createDesktopMouseClickTool, index_createDesktopMouseDragTool as createDesktopMouseDragTool, index_createDesktopMouseMoveTool as createDesktopMouseMoveTool, index_createDesktopMouseScrollTool as createDesktopMouseScrollTool, index_createDesktopScreenshotTool as createDesktopScreenshotTool, index_createDesktopWindowFocusTool as createDesktopWindowFocusTool, index_createDesktopWindowListTool as createDesktopWindowListTool, index_createDraftEmailTool as createDraftEmailTool, index_createEditFileTool as createEditFileTool, index_createEditMeetingTool as createEditMeetingTool, index_createExecuteJavaScriptTool as createExecuteJavaScriptTool, index_createFindMeetingSlotsTool as createFindMeetingSlotsTool, index_createGenerateRoutine as createGenerateRoutine, index_createGetMeetingTranscriptTool as createGetMeetingTranscriptTool, index_createGetPRTool as createGetPRTool, index_createGitHubReadFileTool as createGitHubReadFileTool, index_createGlobTool as createGlobTool, index_createGrepTool as createGrepTool, index_createImageGenerationTool as createImageGenerationTool, index_createListDirectoryTool as createListDirectoryTool, index_createMeetingTool as createMeetingTool, index_createMicrosoftListFilesTool as createMicrosoftListFilesTool, index_createMicrosoftReadFileTool as createMicrosoftReadFileTool, index_createMicrosoftSearchFilesTool as createMicrosoftSearchFilesTool, index_createPRCommentsTool as createPRCommentsTool, index_createPRFilesTool as createPRFilesTool, index_createReadFileTool as createReadFileTool, index_createSearchCodeTool as createSearchCodeTool, index_createSearchFilesTool as createSearchFilesTool, index_createSendEmailTool as createSendEmailTool, index_createSpeechToTextTool as createSpeechToTextTool, index_createTextToSpeechTool as createTextToSpeechTool, index_createVideoTools as createVideoTools, index_createWebScrapeTool as createWebScrapeTool, index_createWebSearchTool as createWebSearchTool, index_createWriteFileTool as createWriteFileTool, index_customToolDelete as customToolDelete, index_customToolDraft as customToolDraft, index_customToolList as customToolList, index_customToolLoad as customToolLoad, index_customToolSave as customToolSave, index_customToolTest as customToolTest, index_desktopGetCursor as desktopGetCursor, index_desktopGetScreenSize as desktopGetScreenSize, index_desktopKeyboardKey as desktopKeyboardKey, index_desktopKeyboardType as desktopKeyboardType, index_desktopMouseClick as desktopMouseClick, index_desktopMouseDrag as desktopMouseDrag, index_desktopMouseMove as desktopMouseMove, index_desktopMouseScroll as desktopMouseScroll, index_desktopScreenshot as desktopScreenshot, index_desktopTools as desktopTools, index_desktopWindowFocus as desktopWindowFocus, index_desktopWindowList as desktopWindowList, index_developerTools as developerTools, index_editFile as editFile, index_encodeSharingUrl as encodeSharingUrl, index_executeInVM as executeInVM, index_executeJavaScript as executeJavaScript, index_expandTilde as expandTilde, index_formatAttendees as formatAttendees, index_formatFileSize as formatFileSize, index_formatRecipients as formatRecipients, index_generateRoutine as generateRoutine, index_getAllBuiltInTools as getAllBuiltInTools, index_getBackgroundOutput as getBackgroundOutput, index_getDesktopDriver as getDesktopDriver, index_getDrivePrefix as getDrivePrefix, index_getMediaOutputHandler as getMediaOutputHandler, index_getMediaStorage as getMediaStorage, index_getToolByName as getToolByName, index_getToolCategories as getToolCategories, index_getToolRegistry as getToolRegistry, index_getToolsByCategory as getToolsByCategory, index_getToolsRequiringConnector as getToolsRequiringConnector, index_getUserPathPrefix as getUserPathPrefix, index_glob as glob, index_grep as grep, index_hydrateCustomTool as hydrateCustomTool, index_isBlockedCommand as isBlockedCommand, index_isExcludedExtension as isExcludedExtension, index_isMicrosoftFileUrl as isMicrosoftFileUrl, index_isTeamsMeetingUrl as isTeamsMeetingUrl, index_isWebUrl as isWebUrl, index_jsonManipulator as jsonManipulator, index_killBackgroundProcess as killBackgroundProcess, index_listDirectory as listDirectory, index_mergeTextPieces as mergeTextPieces, index_microsoftFetch as microsoftFetch, index_normalizeEmails as normalizeEmails, index_parseKeyCombo as parseKeyCombo, index_parseRepository as parseRepository, index_readFile as readFile, index_resetDefaultDriver as resetDefaultDriver, index_resolveFileEndpoints as resolveFileEndpoints, index_resolveMeetingId as resolveMeetingId, index_resolveRepository as resolveRepository, index_setMediaOutputHandler as setMediaOutputHandler, index_setMediaStorage as setMediaStorage, index_toolRegistry as toolRegistry, index_validatePath as validatePath, index_webFetch as webFetch, index_writeFile as writeFile };
15349
+ export { type index_BashResult as BashResult, type index_ConnectorToolEntry as ConnectorToolEntry, index_ConnectorTools as ConnectorTools, type index_CustomToolMetaToolsOptions as CustomToolMetaToolsOptions, index_DEFAULT_DESKTOP_CONFIG as DEFAULT_DESKTOP_CONFIG, index_DEFAULT_FILESYSTEM_CONFIG as DEFAULT_FILESYSTEM_CONFIG, index_DEFAULT_SHELL_CONFIG as DEFAULT_SHELL_CONFIG, index_DESKTOP_TOOL_NAMES as DESKTOP_TOOL_NAMES, type index_DesktopGetCursorResult as DesktopGetCursorResult, type index_DesktopGetScreenSizeResult as DesktopGetScreenSizeResult, type index_DesktopKeyboardKeyArgs as DesktopKeyboardKeyArgs, type index_DesktopKeyboardKeyResult as DesktopKeyboardKeyResult, type index_DesktopKeyboardTypeArgs as DesktopKeyboardTypeArgs, type index_DesktopKeyboardTypeResult as DesktopKeyboardTypeResult, type index_DesktopMouseClickArgs as DesktopMouseClickArgs, type index_DesktopMouseClickResult as DesktopMouseClickResult, type index_DesktopMouseDragArgs as DesktopMouseDragArgs, type index_DesktopMouseDragResult as DesktopMouseDragResult, type index_DesktopMouseMoveArgs as DesktopMouseMoveArgs, type index_DesktopMouseMoveResult as DesktopMouseMoveResult, type index_DesktopMouseScrollArgs as DesktopMouseScrollArgs, type index_DesktopMouseScrollResult as DesktopMouseScrollResult, type index_DesktopPoint as DesktopPoint, type index_DesktopScreenSize as DesktopScreenSize, type index_DesktopScreenshot as DesktopScreenshot, type index_DesktopScreenshotArgs as DesktopScreenshotArgs, type index_DesktopScreenshotResult as DesktopScreenshotResult, type index_DesktopToolConfig as DesktopToolConfig, type index_DesktopToolName as DesktopToolName, type index_DesktopWindow as DesktopWindow, type index_DesktopWindowFocusArgs as DesktopWindowFocusArgs, type index_DesktopWindowFocusResult as DesktopWindowFocusResult, type index_DesktopWindowListResult as DesktopWindowListResult, type index_DocumentFamily as DocumentFamily, type index_DocumentFormat as DocumentFormat, type index_DocumentImagePiece as DocumentImagePiece, type index_DocumentMetadata as DocumentMetadata, type index_DocumentPiece as DocumentPiece, type index_DocumentReadOptions as DocumentReadOptions, index_DocumentReader as DocumentReader, type index_DocumentReaderConfig as DocumentReaderConfig, type index_DocumentResult as DocumentResult, type index_DocumentSource as DocumentSource, type index_DocumentTextPiece as DocumentTextPiece, type index_DocumentToContentOptions as DocumentToContentOptions, type index_EditFileResult as EditFileResult, FileMediaStorage as FileMediaOutputHandler, type index_FilesystemToolConfig as FilesystemToolConfig, type index_FormatDetectionResult as FormatDetectionResult, index_FormatDetector as FormatDetector, type index_GenericAPICallArgs as GenericAPICallArgs, type index_GenericAPICallResult as GenericAPICallResult, type index_GenericAPIToolOptions as GenericAPIToolOptions, type index_GitHubBranchEntry as GitHubBranchEntry, type index_GitHubCreatePRResult as GitHubCreatePRResult, type index_GitHubGetPRResult as GitHubGetPRResult, type index_GitHubListBranchesResult as GitHubListBranchesResult, type index_GitHubPRCommentEntry as GitHubPRCommentEntry, type index_GitHubPRCommentsResult as GitHubPRCommentsResult, type index_GitHubPRFilesResult as GitHubPRFilesResult, type index_GitHubReadFileResult as GitHubReadFileResult, type index_GitHubRepository as GitHubRepository, type index_GitHubSearchCodeResult as GitHubSearchCodeResult, type index_GitHubSearchFilesResult as GitHubSearchFilesResult, type index_GlobResult as GlobResult, type index_GraphDriveItem as GraphDriveItem, type index_GrepMatch as GrepMatch, type index_GrepResult as GrepResult, type index_HydrateOptions as HydrateOptions, type index_IDesktopDriver as IDesktopDriver, type index_IDocumentTransformer as IDocumentTransformer, type index_IFormatHandler as IFormatHandler, type IMediaStorage as IMediaOutputHandler, type index_ImageFilterOptions as ImageFilterOptions, type MediaStorageMetadata as MediaOutputMetadata, type MediaStorageResult as MediaOutputResult, type index_MeetingSlotSuggestion as MeetingSlotSuggestion, type index_MicrosoftCreateMeetingResult as MicrosoftCreateMeetingResult, type index_MicrosoftDraftEmailResult as MicrosoftDraftEmailResult, type index_MicrosoftEditMeetingResult as MicrosoftEditMeetingResult, type index_MicrosoftFindSlotsResult as MicrosoftFindSlotsResult, type index_MicrosoftGetTranscriptResult as MicrosoftGetTranscriptResult, type index_MicrosoftListFilesResult as MicrosoftListFilesResult, type index_MicrosoftReadFileResult as MicrosoftReadFileResult, type index_MicrosoftSearchFilesResult as MicrosoftSearchFilesResult, type index_MicrosoftSendEmailResult as MicrosoftSendEmailResult, type index_MouseButton as MouseButton, index_NutTreeDriver as NutTreeDriver, type index_ReadFileResult as ReadFileResult, type index_SearchResult as SearchResult, type index_ServiceToolFactory as ServiceToolFactory, type index_ShellToolConfig as ShellToolConfig, type index_ToolCategory as ToolCategory, index_ToolRegistry as ToolRegistry, type index_ToolRegistryEntry as ToolRegistryEntry, type index_WriteFileResult as WriteFileResult, index_applyHumanDelay as applyHumanDelay, index_bash as bash, index_createBashTool as createBashTool, index_createCreatePRTool as createCreatePRTool, index_createCustomToolDelete as createCustomToolDelete, index_createCustomToolDraft as createCustomToolDraft, index_createCustomToolList as createCustomToolList, index_createCustomToolLoad as createCustomToolLoad, index_createCustomToolMetaTools as createCustomToolMetaTools, index_createCustomToolSave as createCustomToolSave, index_createCustomToolTest as createCustomToolTest, index_createDesktopGetCursorTool as createDesktopGetCursorTool, index_createDesktopGetScreenSizeTool as createDesktopGetScreenSizeTool, index_createDesktopKeyboardKeyTool as createDesktopKeyboardKeyTool, index_createDesktopKeyboardTypeTool as createDesktopKeyboardTypeTool, index_createDesktopMouseClickTool as createDesktopMouseClickTool, index_createDesktopMouseDragTool as createDesktopMouseDragTool, index_createDesktopMouseMoveTool as createDesktopMouseMoveTool, index_createDesktopMouseScrollTool as createDesktopMouseScrollTool, index_createDesktopScreenshotTool as createDesktopScreenshotTool, index_createDesktopWindowFocusTool as createDesktopWindowFocusTool, index_createDesktopWindowListTool as createDesktopWindowListTool, index_createDraftEmailTool as createDraftEmailTool, index_createEditFileTool as createEditFileTool, index_createEditMeetingTool as createEditMeetingTool, index_createExecuteJavaScriptTool as createExecuteJavaScriptTool, index_createFindMeetingSlotsTool as createFindMeetingSlotsTool, index_createGenerateRoutine as createGenerateRoutine, index_createGetMeetingTranscriptTool as createGetMeetingTranscriptTool, index_createGetPRTool as createGetPRTool, index_createGitHubReadFileTool as createGitHubReadFileTool, index_createGlobTool as createGlobTool, index_createGrepTool as createGrepTool, index_createImageGenerationTool as createImageGenerationTool, index_createListBranchesTool as createListBranchesTool, index_createListDirectoryTool as createListDirectoryTool, index_createMeetingTool as createMeetingTool, index_createMicrosoftListFilesTool as createMicrosoftListFilesTool, index_createMicrosoftReadFileTool as createMicrosoftReadFileTool, index_createMicrosoftSearchFilesTool as createMicrosoftSearchFilesTool, index_createPRCommentsTool as createPRCommentsTool, index_createPRFilesTool as createPRFilesTool, index_createReadFileTool as createReadFileTool, index_createSearchCodeTool as createSearchCodeTool, index_createSearchFilesTool as createSearchFilesTool, index_createSendEmailTool as createSendEmailTool, index_createSpeechToTextTool as createSpeechToTextTool, index_createTextToSpeechTool as createTextToSpeechTool, index_createVideoTools as createVideoTools, index_createWebScrapeTool as createWebScrapeTool, index_createWebSearchTool as createWebSearchTool, index_createWriteFileTool as createWriteFileTool, index_customToolDelete as customToolDelete, index_customToolDraft as customToolDraft, index_customToolList as customToolList, index_customToolLoad as customToolLoad, index_customToolSave as customToolSave, index_customToolTest as customToolTest, index_desktopGetCursor as desktopGetCursor, index_desktopGetScreenSize as desktopGetScreenSize, index_desktopKeyboardKey as desktopKeyboardKey, index_desktopKeyboardType as desktopKeyboardType, index_desktopMouseClick as desktopMouseClick, index_desktopMouseDrag as desktopMouseDrag, index_desktopMouseMove as desktopMouseMove, index_desktopMouseScroll as desktopMouseScroll, index_desktopScreenshot as desktopScreenshot, index_desktopTools as desktopTools, index_desktopWindowFocus as desktopWindowFocus, index_desktopWindowList as desktopWindowList, index_developerTools as developerTools, index_editFile as editFile, index_encodeSharingUrl as encodeSharingUrl, index_executeInVM as executeInVM, index_executeJavaScript as executeJavaScript, index_expandTilde as expandTilde, index_formatAttendees as formatAttendees, index_formatFileSize as formatFileSize, index_formatRecipients as formatRecipients, index_generateRoutine as generateRoutine, index_getAllBuiltInTools as getAllBuiltInTools, index_getBackgroundOutput as getBackgroundOutput, index_getDesktopDriver as getDesktopDriver, index_getDrivePrefix as getDrivePrefix, index_getMediaOutputHandler as getMediaOutputHandler, index_getMediaStorage as getMediaStorage, index_getToolByName as getToolByName, index_getToolCategories as getToolCategories, index_getToolRegistry as getToolRegistry, index_getToolsByCategory as getToolsByCategory, index_getToolsRequiringConnector as getToolsRequiringConnector, index_getUserPathPrefix as getUserPathPrefix, index_glob as glob, index_grep as grep, index_hydrateCustomTool as hydrateCustomTool, index_isBlockedCommand as isBlockedCommand, index_isExcludedExtension as isExcludedExtension, index_isMicrosoftFileUrl as isMicrosoftFileUrl, index_isTeamsMeetingUrl as isTeamsMeetingUrl, index_isWebUrl as isWebUrl, index_jsonManipulator as jsonManipulator, index_killBackgroundProcess as killBackgroundProcess, index_listDirectory as listDirectory, index_mergeTextPieces as mergeTextPieces, index_microsoftFetch as microsoftFetch, index_normalizeEmails as normalizeEmails, index_parseKeyCombo as parseKeyCombo, index_parseRepository as parseRepository, index_readFile as readFile, index_resetDefaultDriver as resetDefaultDriver, index_resolveFileEndpoints as resolveFileEndpoints, index_resolveMeetingId as resolveMeetingId, index_resolveRepository as resolveRepository, index_setMediaOutputHandler as setMediaOutputHandler, index_setMediaStorage as setMediaStorage, index_toolRegistry as toolRegistry, index_validatePath as validatePath, index_webFetch as webFetch, index_writeFile as writeFile };
15065
15350
  }
15066
15351
 
15067
15352
  /**
@@ -15188,4 +15473,4 @@ declare class EventEmitterTrigger implements IDisposable {
15188
15473
  get isDestroyed(): boolean;
15189
15474
  }
15190
15475
 
15191
- export { AGENT_DEFINITION_FORMAT_VERSION, AIError, APPROVAL_STATE_VERSION, Agent, type AgentConfig$1 as AgentConfig, AgentContextNextGen, AgentContextNextGenConfig, type AgentDefinitionListOptions, type AgentDefinitionMetadata, type AgentDefinitionSummary, AgentEvents, type AgentMetrics, type AgentPermissionsConfig, AgentResponse, type AgentSessionConfig, type AgentState, type AgentStatus, type ApprovalCacheEntry, type ApprovalDecision, ApproximateTokenEstimator, type AudioChunkPlaybackCallback, AudioChunkReadyEvent, AudioFormat, AudioPlaybackQueue, AuditEntry, AuthIdentity, type AuthTemplate, type AuthTemplateField, type BackoffConfig, type BackoffStrategyType, BaseMediaProvider, BasePluginNextGen, BaseProvider, type BaseProviderConfig$1 as BaseProviderConfig, type BaseProviderResponse, BaseTextProvider, type BashResult, type BeforeExecuteResult, BraveProvider, CONNECTOR_CONFIG_VERSION, CUSTOM_TOOL_DEFINITION_VERSION, CheckpointManager, type CheckpointStrategy, type ChunkingOptions, CircuitBreaker, type CircuitBreakerConfig, type CircuitBreakerEvents, type CircuitBreakerMetrics, CircuitOpenError, type CircuitState, type ClipboardImageResult, CompactionContext, CompactionResult, Connector, ConnectorAccessContext, ConnectorAuth, ConnectorConfig, ConnectorConfigResult, ConnectorConfigStore, ConnectorFetchOptions, type ConnectorToolEntry, ConnectorTools, type ConnectorToolsOptions, ConsoleMetrics, ConsolidationResult, Content, ContextBudget$1 as ContextBudget, ContextEvents, ContextFeatures, type ContextManagerConfig, type ContextOverflowBudget, ContextOverflowError, ContextSessionMetadata, ContextSessionSummary, ContextStorageListOptions, type ControlFlowResult, type ControlFlowSource, type ConversationMessage, type CreateConnectorOptions, type CustomToolDefinition, type CustomToolListOptions, type CustomToolMetaToolsOptions, type CustomToolMetadata, type CustomToolSummary, type CustomToolTestCase, DEFAULT_ALLOWLIST, DEFAULT_BACKOFF_CONFIG, DEFAULT_CHECKPOINT_STRATEGY, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_DESKTOP_CONFIG, DEFAULT_FILESYSTEM_CONFIG, DEFAULT_HISTORY_MANAGER_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_RATE_LIMITER_CONFIG, DEFAULT_SHELL_CONFIG, DESKTOP_TOOL_NAMES, type DefaultAllowlistedTool, DefaultCompactionStrategy, type DefaultCompactionStrategyConfig, DependencyCycleError, type DesktopGetCursorResult, type DesktopGetScreenSizeResult, type DesktopKeyboardKeyArgs, type DesktopKeyboardKeyResult, type DesktopKeyboardTypeArgs, type DesktopKeyboardTypeResult, type DesktopMouseClickArgs, type DesktopMouseClickResult, type DesktopMouseDragArgs, type DesktopMouseDragResult, type DesktopMouseMoveArgs, type DesktopMouseMoveResult, type DesktopMouseScrollArgs, type DesktopMouseScrollResult, type DesktopPoint, type DesktopScreenSize, type DesktopScreenshot, type DesktopScreenshotArgs, type DesktopScreenshotResult, type DesktopToolConfig, type DesktopToolName, type DesktopWindow, type DesktopWindowFocusArgs, type DesktopWindowFocusResult, type DesktopWindowListResult, type DirectCallOptions, type DocumentFamily, type DocumentFormat, type DocumentImagePiece, type DocumentMetadata, type DocumentPiece, type DocumentReadOptions, DocumentReader, type DocumentReaderConfig, type DocumentResult, type DocumentSource, type DocumentTextPiece, type DocumentToContentOptions, type EditFileResult, type ErrorContext, ErrorHandler, type ErrorHandlerConfig, type ErrorHandlerEvents, EventEmitterTrigger, type EvictionStrategy, type ExecuteRoutineOptions, ExecutionContext, ExecutionMetrics, type ExecutionRecorder, type ExecutionRecorderOptions, type ExtendedFetchOptions, type ExternalDependency, type ExternalDependencyEvents, ExternalDependencyHandler, type FetchedContent, FileAgentDefinitionStorage, type FileAgentDefinitionStorageConfig, FileConnectorStorage, type FileConnectorStorageConfig, FileContextStorage, type FileContextStorageConfig, FileCustomToolStorage, type FileCustomToolStorageConfig, FileMediaStorage as FileMediaOutputHandler, FileMediaStorage, type FileMediaStorageConfig, FilePersistentInstructionsStorage, type FilePersistentInstructionsStorageConfig, FileRoutineDefinitionStorage, type FileRoutineDefinitionStorageConfig, FileStorage, type FileStorageConfig, FileUserInfoStorage, type FileUserInfoStorageConfig, type FilesystemToolConfig, type FormatDetectionResult, FormatDetector, FrameworkLogger, FunctionToolDefinition, type GeneratedPlan, type GenericAPICallArgs, type GenericAPICallResult, type GenericAPIToolOptions, type GitHubCreatePRResult, type GitHubGetPRResult, type GitHubPRCommentEntry, type GitHubPRCommentsResult, type GitHubPRFilesResult, type GitHubReadFileResult, type GitHubRepository, type GitHubSearchCodeResult, type GitHubSearchFilesResult, type GlobResult, type GraphDriveItem, type GrepMatch, type GrepResult, type HTTPTransportConfig, type HistoryManagerEvents, type HistoryMessage, HistoryMode, HookConfig, HookName, type HydrateOptions, type IAgentDefinitionStorage, type IAgentStateStorage, type IAgentStorage, type IAsyncDisposable, IBaseModelDescription, type ICapabilityProvider, type IChunkingStrategy, ICompactionStrategy, IConnectorAccessPolicy, type IConnectorConfigStorage, IConnectorRegistry, type IContextCompactor, type IContextComponent, IContextPluginNextGen, type IContextSnapshot, IContextStorage, type IContextStrategy, type ICustomToolStorage, type IDesktopDriver, type IDisposable, type IDocumentTransformer, type IFormatHandler, type IHistoryManager, type IHistoryManagerConfig, type IHistoryStorage, IImageProvider, type IMCPClient, type IMediaStorage as IMediaOutputHandler, type IMediaStorage, type IMemoryStorage, type IPersistentInstructionsStorage, type IPlanStorage, type IPluginSnapshot, IProvider, type IResearchSource, type IRoutineDefinitionStorage, type IRoutineExecutionStorage, type ISTTModelDescription, type IScheduler, type IScrapeProvider, type ISearchProvider, type ISpeechToTextProvider, type IStreamingTextToSpeechProvider, type ITTSModelDescription, ITextProvider, type ITextToSpeechProvider, ITokenEstimator$1 as ITokenEstimator, ITokenStorage, type IToolExecutionPipeline, type IToolExecutionPlugin, type IToolExecutor, type IToolSnapshot, type IUserInfoStorage, type IVideoModelDescription, type IVideoProvider, type IViewContextComponent, type IViewContextData, type IVoiceInfo, type ImageFilterOptions, type InContextEntry, type InContextMemoryConfig, InContextMemoryPluginNextGen, type InContextPriority, InMemoryAgentStateStorage, InMemoryHistoryStorage, InMemoryMetrics, InMemoryPlanStorage, InMemoryStorage, InputItem, type InstructionEntry, InvalidConfigError, InvalidToolArgumentsError, type JSONExtractionResult, LLMResponse, type LogEntry, type LogLevel, type LoggerConfig, LoggingPlugin, type LoggingPluginOptions, MCPClient, type MCPClientConnectionState, type MCPClientState, type MCPConfiguration, MCPConnectionError, MCPError, type MCPPrompt, type MCPPromptResult, MCPProtocolError, MCPRegistry, type MCPResource, type MCPResourceContent, MCPResourceError, type MCPServerCapabilities, type MCPServerConfig, MCPTimeoutError, type MCPTool, MCPToolError, type MCPToolResult, type MCPTransportType, type MediaStorageMetadata as MediaOutputMetadata, type MediaStorageResult as MediaOutputResult, type MediaStorageEntry, type MediaStorageListOptions, type MediaStorageMetadata, type MediaStorageResult, type MeetingSlotSuggestion, MemoryConnectorStorage, MemoryEntry, MemoryEvictionCompactor, MemoryIndex, MemoryPriority, MemoryScope, MemoryStorage, MessageBuilder, MessageRole, type MetricTags, type MetricsCollector, type MetricsCollectorType, type MicrosoftCreateMeetingResult, type MicrosoftDraftEmailResult, type MicrosoftEditMeetingResult, type MicrosoftFindSlotsResult, type MicrosoftGetTranscriptResult, type MicrosoftListFilesResult, type MicrosoftReadFileResult, type MicrosoftSearchFilesResult, type MicrosoftSendEmailResult, ModelCapabilities, ModelNotSupportedError, type MouseButton, type EvictionStrategy$1 as NextGenEvictionStrategy, NoOpMetrics, NutTreeDriver, type OAuthConfig, type OAuthFlow, OAuthManager, OutputItem, ParallelTasksError, type PermissionCheckContext, type PermissionCheckResult, type PermissionManagerEvent, type PermissionScope, type PersistentInstructionsConfig, PersistentInstructionsPluginNextGen, type PieceMetadata, type Plan, type PlanConcurrency, type PlanInput, type PlanStatus, PlanningAgent, type PlanningAgentConfig, type PluginExecutionContext, PreparedContext, ProviderAuthError, ProviderCapabilities, ProviderConfigAgent, ProviderContextLengthError, ProviderError, ProviderErrorMapper, ProviderNotFoundError, ProviderRateLimitError, ROUTINE_KEYS, RapidAPIProvider, RateLimitError, type RateLimiterConfig, type RateLimiterMetrics, type ReadFileResult, type FetchOptions as ResearchFetchOptions, type ResearchFinding, type ResearchPlan, type ResearchProgress, type ResearchQuery, type ResearchResult, type SearchOptions as ResearchSearchOptions, type SearchResponse as ResearchSearchResponse, type RiskLevel, type RoutineDefinition, type RoutineDefinitionInput, type RoutineExecution, type RoutineExecutionRecord, type RoutineExecutionStatus, type RoutineExecutionStep, type RoutineParameter, type RoutineStepType, type RoutineTaskResult, type RoutineTaskSnapshot, SIMPLE_ICONS_CDN, type STTModelCapabilities, type STTOptions, type STTOutputFormat$1 as STTOutputFormat, type STTResponse, STT_MODELS, STT_MODEL_REGISTRY, type ScheduleHandle, type ScheduleSpec, ScopedConnectorRegistry, type ScrapeFeature, type ScrapeOptions, ScrapeProvider, type ScrapeProviderConfig, type ScrapeProviderFallbackConfig, type ScrapeResponse, type ScrapeResult, type SearchOptions$1 as SearchOptions, SearchProvider, type SearchProviderConfig, type SearchResponse$1 as SearchResponse, type SearchResult, type SegmentTimestamp, SentenceChunkingStrategy, type SerializedApprovalEntry, type SerializedApprovalState, SerializedContextState, type SerializedHistoryState, type SerializedInContextMemoryState, type SerializedPersistentInstructionsState, type SerializedToolState, type SerializedUserInfoState, type SerializedWorkingMemoryState, SerperProvider, ServiceCategory, type ServiceToolFactory, type ShellToolConfig, type SimpleIcon, SimpleScheduler, type SimpleVideoGenerateOptions, type SourceCapabilities, type SourceResult, SpeechToText, type SpeechToTextConfig, type StdioTransportConfig, type StorageConfig, type StorageContext, StorageRegistry, type StoredAgentDefinition, type StoredAgentType, type StoredConnectorConfig, StoredContextSession, type StoredToken, type StrategyInfo, StrategyRegistry, type StrategyRegistryEntry, StreamEvent, StreamEventType, StreamHelpers, StreamState, type SubRoutineSpec, SummarizeCompactor, TERMINAL_TASK_STATUSES, type TTSModelCapabilities, type TTSOptions, type TTSResponse, type TTSStreamChunk, TTS_MODELS, TTS_MODEL_REGISTRY, type Task, type AgentConfig as TaskAgentStateConfig, type TaskCondition, type TaskControlFlow, type TaskExecution, type TaskFailure, type TaskFoldFlow, type TaskInput, type TaskMapFlow, type TaskSourceRef, type TaskStatus, TaskStatusForMemory, TaskTimeoutError, ToolContext as TaskToolContext, type TaskUntilFlow, type TaskValidation, TaskValidationError, type TaskValidationResult, TavilyProvider, type TemplateCredentials, TextGenerateOptions, TextToSpeech, type TextToSpeechConfig, TokenBucketRateLimiter, type TokenContentType, Tool, ToolCall, type ToolCatalogPluginConfig, ToolCatalogPluginNextGen, type ToolCategory, ToolCategoryScope, type ToolCondition, ToolContext, ToolExecutionError, ToolExecutionPipeline, type ToolExecutionPipelineOptions, ToolFunction, ToolManager, type ToolManagerConfig, type ToolManagerEvent, type ToolManagerStats, type ToolMetadata, ToolNotFoundError, type ToolOptions, type ToolPermissionConfig, ToolPermissionManager, type ToolRegistration, ToolRegistry, type ToolRegistryEntry, ToolResult, type ToolSelectionContext, type ToolSource, ToolTimeoutError, type TransportConfig, TruncateCompactor, type UserInfoEntry, type UserInfoPluginConfig, UserInfoPluginNextGen, VENDOR_ICON_MAP, VIDEO_MODELS, VIDEO_MODEL_REGISTRY, type ValidationContext, Vendor, type VendorInfo, type VendorLogo, VendorOptionSchema, type VendorRegistryEntry, type VendorTemplate, type VideoExtendOptions, type VideoGenerateOptions, VideoGeneration, type VideoGenerationCreateOptions, type VideoJob, type VideoModelCapabilities, type VideoModelPricing, type VideoResponse, type VideoStatus, VoiceStream, type VoiceStreamConfig, type VoiceStreamEvents, type WordTimestamp, WorkingMemory, WorkingMemoryAccess, WorkingMemoryConfig, type WorkingMemoryEvents, type WorkingMemoryPluginConfig, WorkingMemoryPluginNextGen, type WriteFileResult, addJitter, allVendorTemplates, assertNotDestroyed, authenticatedFetch, backoffSequence, backoffWait, bash, buildAuthConfig, buildEndpointWithQuery, buildQueryString, calculateBackoff, calculateSTTCost, calculateTTSCost, calculateVideoCost, canTaskExecute, createAgentStorage, createAuthenticatedFetch, createBashTool, createConnectorFromTemplate, createCreatePRTool, createCustomToolDelete, createCustomToolDraft, createCustomToolList, createCustomToolLoad, createCustomToolMetaTools, createCustomToolSave, createCustomToolTest, createDesktopGetCursorTool, createDesktopGetScreenSizeTool, createDesktopKeyboardKeyTool, createDesktopKeyboardTypeTool, createDesktopMouseClickTool, createDesktopMouseDragTool, createDesktopMouseMoveTool, createDesktopMouseScrollTool, createDesktopScreenshotTool, createDesktopWindowFocusTool, createDesktopWindowListTool, createDraftEmailTool, createEditFileTool, createEditMeetingTool, createEstimator, createExecuteJavaScriptTool, createExecutionRecorder, createFileAgentDefinitionStorage, createFileContextStorage, createFileCustomToolStorage, createFileMediaStorage, createFileRoutineDefinitionStorage, createFindMeetingSlotsTool, createGetMeetingTranscriptTool, createGetPRTool, createGitHubReadFileTool, createGlobTool, createGrepTool, createImageGenerationTool, createImageProvider, createListDirectoryTool, createMeetingTool, createMessageWithImages, createMetricsCollector, createMicrosoftListFilesTool, createMicrosoftReadFileTool, createMicrosoftSearchFilesTool, createPRCommentsTool, createPRFilesTool, createPlan, createProvider, createReadFileTool, createRoutineDefinition, createRoutineExecution, createRoutineExecutionRecord, createSearchCodeTool, createSearchFilesTool, createSendEmailTool, createSpeechToTextTool, createTask, createTaskSnapshots, createTextMessage, createTextToSpeechTool, createVideoProvider, createVideoTools, createWriteFileTool, customToolDelete, customToolDraft, customToolList, customToolLoad, customToolSave, customToolTest, desktopGetCursor, desktopGetScreenSize, desktopKeyboardKey, desktopKeyboardType, desktopMouseClick, desktopMouseDrag, desktopMouseMove, desktopMouseScroll, desktopScreenshot, desktopTools, desktopWindowFocus, desktopWindowList, detectDependencyCycle, developerTools, documentToContent, editFile, encodeSharingUrl, evaluateCondition, executeRoutine, extractJSON, extractJSONField, extractNumber, findConnectorByServiceTypes, formatAttendees, formatFileSize, formatPluginDisplayName, formatRecipients, generateEncryptionKey, generateSimplePlan, generateWebAPITool, getActiveSTTModels, getActiveTTSModels, getActiveVideoModels, getAllBuiltInTools, getAllVendorLogos, getAllVendorTemplates, getBackgroundOutput, getConnectorTools, getCredentialsSetupURL, getDesktopDriver, getDocsURL, getDrivePrefix, getMediaOutputHandler, getMediaStorage, getNextExecutableTasks, getRegisteredScrapeProviders, getRoutineProgress, getSTTModelInfo, getSTTModelsByVendor, getSTTModelsWithFeature, getTTSModelInfo, getTTSModelsByVendor, getTTSModelsWithFeature, getTaskDependencies, getToolByName, getToolCategories, getToolRegistry, getToolsByCategory, getToolsRequiringConnector, getUserPathPrefix, getVendorAuthTemplate, getVendorColor, getVendorDefaultBaseURL, getVendorInfo, getVendorLogo, getVendorLogoCdnUrl, getVendorLogoSvg, getVendorTemplate, getVideoModelInfo, getVideoModelsByVendor, getVideoModelsWithAudio, getVideoModelsWithFeature, glob, globalErrorHandler, grep, hasClipboardImage, hasVendorLogo, hydrateCustomTool, isBlockedCommand, isExcludedExtension, isMicrosoftFileUrl, isTaskBlocked, isTeamsMeetingUrl, isTerminalStatus, isWebUrl, killBackgroundProcess, listConnectorsByServiceTypes, listDirectory, listVendorIds, listVendors, listVendorsByAuthType, listVendorsByCategory, listVendorsWithLogos, logger, mergeTextPieces, metrics, microsoftFetch, normalizeEmails, parseKeyCombo, parseRepository, readClipboardImage, readDocumentAsContent, readFile, registerScrapeProvider, resetDefaultDriver, resolveConnector, resolveDependencies, resolveFileEndpoints, resolveFlowSource, resolveMaxContextTokens, resolveMeetingId, resolveModelCapabilities, resolveRepository, resolveTemplates, retryWithBackoff, sanitizeToolName, setMediaOutputHandler, setMediaStorage, setMetricsCollector, simpleTokenEstimator, toConnectorOptions, toolRegistry, index as tools, updateTaskStatus, validatePath, writeFile };
15476
+ export { AGENT_DEFINITION_FORMAT_VERSION, AIError, APPROVAL_STATE_VERSION, Agent, type AgentConfig$1 as AgentConfig, AgentContextNextGen, AgentContextNextGenConfig, type AgentDefinitionListOptions, type AgentDefinitionMetadata, type AgentDefinitionSummary, AgentEvents, type AgentMetrics, type AgentPermissionsConfig, AgentResponse, type AgentSessionConfig, type AgentState, type AgentStatus, type ApprovalCacheEntry, type ApprovalDecision, ApproximateTokenEstimator, type AudioChunkPlaybackCallback, AudioChunkReadyEvent, AudioFormat, AudioPlaybackQueue, AuditEntry, AuthIdentity, type AuthTemplate, type AuthTemplateField, type BackoffConfig, type BackoffStrategyType, BaseMediaProvider, BasePluginNextGen, BaseProvider, type BaseProviderConfig$1 as BaseProviderConfig, type BaseProviderResponse, BaseTextProvider, type BashResult, type BeforeExecuteResult, BraveProvider, CONNECTOR_CONFIG_VERSION, CUSTOM_TOOL_DEFINITION_VERSION, CheckpointManager, type CheckpointStrategy, type ChunkingOptions, CircuitBreaker, type CircuitBreakerConfig, type CircuitBreakerEvents, type CircuitBreakerMetrics, CircuitOpenError, type CircuitState, type ClipboardImageResult, CompactionContext, CompactionResult, Connector, ConnectorAccessContext, ConnectorAuth, ConnectorConfig, ConnectorConfigResult, ConnectorConfigStore, ConnectorFetchOptions, type ConnectorToolEntry, ConnectorTools, type ConnectorToolsOptions, ConsoleMetrics, ConsolidationResult, Content, ContextBudget$1 as ContextBudget, ContextEvents, ContextFeatures, type ContextManagerConfig, type ContextOverflowBudget, ContextOverflowError, ContextSessionMetadata, ContextSessionSummary, ContextStorageListOptions, type ControlFlowResult, type ControlFlowSource, type ConversationMessage, type CreateConnectorOptions, type CustomToolDefinition, type CustomToolListOptions, type CustomToolMetaToolsOptions, type CustomToolMetadata, type CustomToolSummary, type CustomToolTestCase, DEFAULT_ALLOWLIST, DEFAULT_BACKOFF_CONFIG, DEFAULT_CHECKPOINT_STRATEGY, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_DESKTOP_CONFIG, DEFAULT_FILESYSTEM_CONFIG, DEFAULT_HISTORY_MANAGER_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_RATE_LIMITER_CONFIG, DEFAULT_SHELL_CONFIG, DESKTOP_TOOL_NAMES, type DefaultAllowlistedTool, DefaultCompactionStrategy, type DefaultCompactionStrategyConfig, DependencyCycleError, type DesktopGetCursorResult, type DesktopGetScreenSizeResult, type DesktopKeyboardKeyArgs, type DesktopKeyboardKeyResult, type DesktopKeyboardTypeArgs, type DesktopKeyboardTypeResult, type DesktopMouseClickArgs, type DesktopMouseClickResult, type DesktopMouseDragArgs, type DesktopMouseDragResult, type DesktopMouseMoveArgs, type DesktopMouseMoveResult, type DesktopMouseScrollArgs, type DesktopMouseScrollResult, type DesktopPoint, type DesktopScreenSize, type DesktopScreenshot, type DesktopScreenshotArgs, type DesktopScreenshotResult, type DesktopToolConfig, type DesktopToolName, type DesktopWindow, type DesktopWindowFocusArgs, type DesktopWindowFocusResult, type DesktopWindowListResult, type DirectCallOptions, type DocumentFamily, type DocumentFormat, type DocumentImagePiece, type DocumentMetadata, type DocumentPiece, type DocumentReadOptions, DocumentReader, type DocumentReaderConfig, type DocumentResult, type DocumentSource, type DocumentTextPiece, type DocumentToContentOptions, type EditFileResult, type ErrorContext, ErrorHandler, type ErrorHandlerConfig, type ErrorHandlerEvents, EventEmitterTrigger, type EvictionStrategy, type ExecuteRoutineOptions, ExecutionContext, ExecutionMetrics, type ExecutionRecorder, type ExecutionRecorderOptions, type ExtendedFetchOptions, type ExternalDependency, type ExternalDependencyEvents, ExternalDependencyHandler, type FetchedContent, FileAgentDefinitionStorage, type FileAgentDefinitionStorageConfig, FileConnectorStorage, type FileConnectorStorageConfig, FileContextStorage, type FileContextStorageConfig, FileCustomToolStorage, type FileCustomToolStorageConfig, FileHistoryJournal, FileMediaStorage as FileMediaOutputHandler, FileMediaStorage, type FileMediaStorageConfig, FilePersistentInstructionsStorage, type FilePersistentInstructionsStorageConfig, FileRoutineDefinitionStorage, type FileRoutineDefinitionStorageConfig, FileRoutineExecutionStorage, type FileRoutineExecutionStorageConfig, FileStorage, type FileStorageConfig, FileUserInfoStorage, type FileUserInfoStorageConfig, type FilesystemToolConfig, type FormatDetectionResult, FormatDetector, FrameworkLogger, FunctionToolDefinition, type GeneratedPlan, type GenericAPICallArgs, type GenericAPICallResult, type GenericAPIToolOptions, type GitHubBranchEntry, type GitHubCreatePRResult, type GitHubGetPRResult, type GitHubListBranchesResult, type GitHubPRCommentEntry, type GitHubPRCommentsResult, type GitHubPRFilesResult, type GitHubReadFileResult, type GitHubRepository, type GitHubSearchCodeResult, type GitHubSearchFilesResult, type GlobResult, type GraphDriveItem, type GrepMatch, type GrepResult, type HTTPTransportConfig, HistoryEntry, type HistoryManagerEvents, type HistoryMessage, HistoryMode, HistoryReadOptions, HookConfig, HookName, type HydrateOptions, type IAgentDefinitionStorage, type IAgentStateStorage, type IAgentStorage, type IAsyncDisposable, IBaseModelDescription, type ICapabilityProvider, type IChunkingStrategy, ICompactionStrategy, IConnectorAccessPolicy, type IConnectorConfigStorage, IConnectorRegistry, type IContextCompactor, type IContextComponent, IContextPluginNextGen, type IContextSnapshot, IContextStorage, type IContextStrategy, type ICustomToolStorage, type IDesktopDriver, type IDisposable, type IDocumentTransformer, type IFormatHandler, IHistoryJournal, type IHistoryManager, type IHistoryManagerConfig, type IHistoryStorage, IImageProvider, type IMCPClient, type IMediaStorage as IMediaOutputHandler, type IMediaStorage, type IMemoryStorage, type IPersistentInstructionsStorage, type IPlanStorage, type IPluginSnapshot, IProvider, type IResearchSource, type IRoutineDefinitionStorage, type IRoutineExecutionStorage, type ISTTModelDescription, type IScheduler, type IScrapeProvider, type ISearchProvider, type ISpeechToTextProvider, type IStreamingTextToSpeechProvider, type ITTSModelDescription, ITextProvider, type ITextToSpeechProvider, ITokenEstimator$1 as ITokenEstimator, ITokenStorage, type IToolExecutionPipeline, type IToolExecutionPlugin, type IToolExecutor, type IToolSnapshot, type IUserInfoStorage, type IVideoModelDescription, type IVideoProvider, type IViewContextComponent, type IViewContextData, type IVoiceInfo, type ImageFilterOptions, type InContextEntry, type InContextMemoryConfig, InContextMemoryPluginNextGen, type InContextPriority, InMemoryAgentStateStorage, InMemoryHistoryStorage, InMemoryMetrics, InMemoryPlanStorage, InMemoryStorage, InputItem, type InstructionEntry, InvalidConfigError, InvalidToolArgumentsError, type JSONExtractionResult, LLMResponse, type LogEntry, type LogLevel, type LoggerConfig, LoggingPlugin, type LoggingPluginOptions, MCPClient, type MCPClientConnectionState, type MCPClientState, type MCPConfiguration, MCPConnectionError, MCPError, type MCPPrompt, type MCPPromptResult, MCPProtocolError, MCPRegistry, type MCPResource, type MCPResourceContent, MCPResourceError, type MCPServerCapabilities, type MCPServerConfig, MCPTimeoutError, type MCPTool, MCPToolError, type MCPToolResult, type MCPTransportType, type MediaStorageMetadata as MediaOutputMetadata, type MediaStorageResult as MediaOutputResult, type MediaStorageEntry, type MediaStorageListOptions, type MediaStorageMetadata, type MediaStorageResult, type MeetingSlotSuggestion, MemoryConnectorStorage, MemoryEntry, MemoryEvictionCompactor, MemoryIndex, MemoryPriority, MemoryScope, MemoryStorage, MessageBuilder, MessageRole, type MetricTags, type MetricsCollector, type MetricsCollectorType, type MicrosoftCreateMeetingResult, type MicrosoftDraftEmailResult, type MicrosoftEditMeetingResult, type MicrosoftFindSlotsResult, type MicrosoftGetTranscriptResult, type MicrosoftListFilesResult, type MicrosoftReadFileResult, type MicrosoftSearchFilesResult, type MicrosoftSendEmailResult, ModelCapabilities, ModelNotSupportedError, type MouseButton, type EvictionStrategy$1 as NextGenEvictionStrategy, NoOpMetrics, NutTreeDriver, type OAuthConfig, type OAuthFlow, OAuthManager, OutputItem, ParallelTasksError, type PermissionCheckContext, type PermissionCheckResult, type PermissionManagerEvent, type PermissionScope, type PersistentInstructionsConfig, PersistentInstructionsPluginNextGen, type PieceMetadata, type Plan, type PlanConcurrency, type PlanInput, type PlanStatus, PlanningAgent, type PlanningAgentConfig, type PluginExecutionContext, PreparedContext, ProviderAuthError, ProviderCapabilities, ProviderConfigAgent, ProviderContextLengthError, ProviderError, ProviderErrorMapper, ProviderNotFoundError, ProviderRateLimitError, ROUTINE_KEYS, RapidAPIProvider, RateLimitError, type RateLimiterConfig, type RateLimiterMetrics, type ReadFileResult, type FetchOptions as ResearchFetchOptions, type ResearchFinding, type ResearchPlan, type ResearchProgress, type ResearchQuery, type ResearchResult, type SearchOptions as ResearchSearchOptions, type SearchResponse as ResearchSearchResponse, type RiskLevel, type RoutineDefinition, type RoutineDefinitionInput, type RoutineExecution, type RoutineExecutionRecord, type RoutineExecutionStatus, type RoutineExecutionStep, type RoutineParameter, type RoutineStepType, type RoutineTaskResult, type RoutineTaskSnapshot, SIMPLE_ICONS_CDN, type STTModelCapabilities, type STTOptions, type STTOutputFormat$1 as STTOutputFormat, type STTResponse, STT_MODELS, STT_MODEL_REGISTRY, type ScheduleHandle, type ScheduleSpec, ScopedConnectorRegistry, type ScrapeFeature, type ScrapeOptions, ScrapeProvider, type ScrapeProviderConfig, type ScrapeProviderFallbackConfig, type ScrapeResponse, type ScrapeResult, type SearchOptions$1 as SearchOptions, SearchProvider, type SearchProviderConfig, type SearchResponse$1 as SearchResponse, type SearchResult, type SegmentTimestamp, SentenceChunkingStrategy, type SerializedApprovalEntry, type SerializedApprovalState, SerializedContextState, type SerializedHistoryState, type SerializedInContextMemoryState, type SerializedPersistentInstructionsState, type SerializedToolState, type SerializedUserInfoState, type SerializedWorkingMemoryState, SerperProvider, ServiceCategory, type ServiceToolFactory, type ShellToolConfig, type SimpleIcon, SimpleScheduler, type SimpleVideoGenerateOptions, type SourceCapabilities, type SourceResult, SpeechToText, type SpeechToTextConfig, type StdioTransportConfig, type StorageConfig, type StorageContext, StorageRegistry, type StoredAgentDefinition, type StoredAgentType, type StoredConnectorConfig, StoredContextSession, type StoredToken, type StrategyInfo, StrategyRegistry, type StrategyRegistryEntry, StreamEvent, StreamEventType, StreamHelpers, StreamState, type SubRoutineSpec, SummarizeCompactor, TERMINAL_TASK_STATUSES, type TTSModelCapabilities, type TTSOptions, type TTSResponse, type TTSStreamChunk, TTS_MODELS, TTS_MODEL_REGISTRY, type Task, type AgentConfig as TaskAgentStateConfig, type TaskCondition, type TaskControlFlow, type TaskExecution, type TaskFailure, type TaskFoldFlow, type TaskInput, type TaskMapFlow, type TaskSourceRef, type TaskStatus, TaskStatusForMemory, TaskTimeoutError, ToolContext as TaskToolContext, type TaskUntilFlow, type TaskValidation, TaskValidationError, type TaskValidationResult, TavilyProvider, type TemplateCredentials, TextGenerateOptions, TextToSpeech, type TextToSpeechConfig, TokenBucketRateLimiter, type TokenContentType, Tool, ToolCall, type ToolCatalogPluginConfig, ToolCatalogPluginNextGen, type ToolCategory, ToolCategoryScope, type ToolCondition, ToolContext, ToolExecutionError, ToolExecutionPipeline, type ToolExecutionPipelineOptions, ToolFunction, ToolManager, type ToolManagerConfig, type ToolManagerEvent, type ToolManagerStats, type ToolMetadata, ToolNotFoundError, type ToolOptions, type ToolPermissionConfig, ToolPermissionManager, type ToolRegistration, ToolRegistry, type ToolRegistryEntry, ToolResult, type ToolSelectionContext, type ToolSource, ToolTimeoutError, type TransportConfig, TruncateCompactor, type UserInfoEntry, type UserInfoPluginConfig, UserInfoPluginNextGen, VENDOR_ICON_MAP, VIDEO_MODELS, VIDEO_MODEL_REGISTRY, type ValidationContext, Vendor, type VendorInfo, type VendorLogo, VendorOptionSchema, type VendorRegistryEntry, type VendorTemplate, type VideoExtendOptions, type VideoGenerateOptions, VideoGeneration, type VideoGenerationCreateOptions, type VideoJob, type VideoModelCapabilities, type VideoModelPricing, type VideoResponse, type VideoStatus, VoiceStream, type VoiceStreamConfig, type VoiceStreamEvents, type WordTimestamp, WorkingMemory, WorkingMemoryAccess, WorkingMemoryConfig, type WorkingMemoryEvents, type WorkingMemoryPluginConfig, WorkingMemoryPluginNextGen, type WriteFileResult, addJitter, allVendorTemplates, assertNotDestroyed, authenticatedFetch, backoffSequence, backoffWait, bash, buildAuthConfig, buildEndpointWithQuery, buildQueryString, calculateBackoff, calculateSTTCost, calculateTTSCost, calculateVideoCost, canTaskExecute, createAgentStorage, createAuthenticatedFetch, createBashTool, createConnectorFromTemplate, createCreatePRTool, createCustomToolDelete, createCustomToolDraft, createCustomToolList, createCustomToolLoad, createCustomToolMetaTools, createCustomToolSave, createCustomToolTest, createDesktopGetCursorTool, createDesktopGetScreenSizeTool, createDesktopKeyboardKeyTool, createDesktopKeyboardTypeTool, createDesktopMouseClickTool, createDesktopMouseDragTool, createDesktopMouseMoveTool, createDesktopMouseScrollTool, createDesktopScreenshotTool, createDesktopWindowFocusTool, createDesktopWindowListTool, createDraftEmailTool, createEditFileTool, createEditMeetingTool, createEstimator, createExecuteJavaScriptTool, createExecutionRecorder, createFileAgentDefinitionStorage, createFileContextStorage, createFileCustomToolStorage, createFileMediaStorage, createFileRoutineDefinitionStorage, createFileRoutineExecutionStorage, createFindMeetingSlotsTool, createGetMeetingTranscriptTool, createGetPRTool, createGitHubReadFileTool, createGlobTool, createGrepTool, createImageGenerationTool, createImageProvider, createListBranchesTool, createListDirectoryTool, createMeetingTool, createMessageWithImages, createMetricsCollector, createMicrosoftListFilesTool, createMicrosoftReadFileTool, createMicrosoftSearchFilesTool, createPRCommentsTool, createPRFilesTool, createPlan, createProvider, createReadFileTool, createRoutineDefinition, createRoutineExecution, createRoutineExecutionRecord, createSearchCodeTool, createSearchFilesTool, createSendEmailTool, createSpeechToTextTool, createTask, createTaskSnapshots, createTextMessage, createTextToSpeechTool, createVideoProvider, createVideoTools, createWriteFileTool, customToolDelete, customToolDraft, customToolList, customToolLoad, customToolSave, customToolTest, desktopGetCursor, desktopGetScreenSize, desktopKeyboardKey, desktopKeyboardType, desktopMouseClick, desktopMouseDrag, desktopMouseMove, desktopMouseScroll, desktopScreenshot, desktopTools, desktopWindowFocus, desktopWindowList, detectDependencyCycle, developerTools, documentToContent, editFile, encodeSharingUrl, evaluateCondition, executeRoutine, extractJSON, extractJSONField, extractNumber, findConnectorByServiceTypes, formatAttendees, formatFileSize, formatPluginDisplayName, formatRecipients, generateEncryptionKey, generateSimplePlan, generateWebAPITool, getActiveSTTModels, getActiveTTSModels, getActiveVideoModels, getAllBuiltInTools, getAllVendorLogos, getAllVendorTemplates, getBackgroundOutput, getConnectorTools, getCredentialsSetupURL, getDesktopDriver, getDocsURL, getDrivePrefix, getMediaOutputHandler, getMediaStorage, getNextExecutableTasks, getRegisteredScrapeProviders, getRoutineProgress, getSTTModelInfo, getSTTModelsByVendor, getSTTModelsWithFeature, getTTSModelInfo, getTTSModelsByVendor, getTTSModelsWithFeature, getTaskDependencies, getToolByName, getToolCategories, getToolRegistry, getToolsByCategory, getToolsRequiringConnector, getUserPathPrefix, getVendorAuthTemplate, getVendorColor, getVendorDefaultBaseURL, getVendorInfo, getVendorLogo, getVendorLogoCdnUrl, getVendorLogoSvg, getVendorTemplate, getVideoModelInfo, getVideoModelsByVendor, getVideoModelsWithAudio, getVideoModelsWithFeature, glob, globalErrorHandler, grep, hasClipboardImage, hasVendorLogo, hydrateCustomTool, isBlockedCommand, isExcludedExtension, isMicrosoftFileUrl, isTaskBlocked, isTeamsMeetingUrl, isTerminalStatus, isWebUrl, killBackgroundProcess, listConnectorsByServiceTypes, listDirectory, listVendorIds, listVendors, listVendorsByAuthType, listVendorsByCategory, listVendorsWithLogos, logger, mergeTextPieces, metrics, microsoftFetch, normalizeEmails, parseKeyCombo, parseRepository, readClipboardImage, readDocumentAsContent, readFile, registerScrapeProvider, resetDefaultDriver, resolveConnector, resolveDependencies, resolveFileEndpoints, resolveFlowSource, resolveMaxContextTokens, resolveMeetingId, resolveModelCapabilities, resolveRepository, resolveTemplates, retryWithBackoff, sanitizeToolName, setMediaOutputHandler, setMediaStorage, setMetricsCollector, simpleTokenEstimator, toConnectorOptions, toolRegistry, index as tools, updateTaskStatus, validatePath, writeFile };