@everworker/oneringai 0.4.6 → 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.cts CHANGED
@@ -1,12 +1,13 @@
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-B8sqUzJG.cjs';
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-B8sqUzJG.cjs';
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 StaleEntryInfo, R as PriorityContext, U as MemoryIndex, V as TaskStatusForMemory, X as WorkingMemoryAccess, Y as ContextStorageListOptions, Z as ContextSessionSummary, _ as TokenUsage, $ as StreamEventType, a0 as TextGenerateOptions, a1 as ModelCapabilities, a2 as MessageRole } from './index-DJ-qAK15.cjs';
4
- export { a3 as AfterToolContext, a4 as AgentEventName, a5 as AgenticLoopEventName, a6 as AgenticLoopEvents, a7 as ApprovalResult, a8 as ApproveToolContext, a9 as BeforeToolContext, aa as BuiltInTool, ab as CONTEXT_SESSION_FORMAT_VERSION, ac as CatalogRegistryEntry, ad as CatalogToolEntry, ae as CompactionItem, af as ConnectorCategoryInfo, ag as ContentType, ah as DEFAULT_CONFIG, ai as DEFAULT_FEATURES, aj as DEFAULT_MEMORY_CONFIG, ak as ErrorEvent, al as ExecutionConfig, am as Hook, an as HookManager, ao as InputImageContent, ap as InputTextContent, aq as IterationCompleteEvent, ar as JSONSchema, as as MEMORY_PRIORITY_VALUES, at as MemoryEntryInput, au as MemoryIndexEntry, av as Message, aw as ModifyingHook, ax as OutputTextContent, ay as OutputTextDeltaEvent, az as OutputTextDoneEvent, aA as OversizedInputResult, aB as PluginConfigs, aC as ReasoningDeltaEvent, aD as ReasoningDoneEvent, aE as ReasoningItem, aF as ResponseCompleteEvent, aG as ResponseCreatedEvent, aH as ResponseInProgressEvent, aI as SimpleScope, aJ as TaskAwareScope, aK as ThinkingContent, aL as ToolCallArgumentsDeltaEvent, aM as ToolCallArgumentsDoneEvent, aN as ToolCallStartEvent, aO as ToolCallState, aP as ToolCatalogRegistry, aQ as ToolCategoryDefinition, aR as ToolExecutionContext, aS as ToolExecutionDoneEvent, aT as ToolExecutionStartEvent, aU as ToolModification, aV as ToolResultContent, aW as ToolUseContent, aX as calculateEntrySize, aY as defaultDescribeCall, aZ as forPlan, a_ as forTasks, a$ as getToolCallDescription, b0 as isErrorEvent, b1 as isOutputTextDelta, b2 as isReasoningDelta, b3 as isReasoningDone, b4 as isResponseComplete, b5 as isSimpleScope, b6 as isStreamEvent, b7 as isTaskAwareScope, b8 as isTerminalMemoryStatus, b9 as isToolCallArgumentsDelta, ba as isToolCallArgumentsDone, bb as isToolCallStart, bc as scopeEquals, bd as scopeMatches } from './index-DJ-qAK15.cjs';
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-Cbd5vY_8.cjs';
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-Cbd5vY_8.cjs';
5
5
  import { EventEmitter } from 'eventemitter3';
6
6
  import { V as Vendor } from './Vendor-DYh_bzwo.cjs';
7
7
  export { a as VENDORS, i as isVendor } from './Vendor-DYh_bzwo.cjs';
8
8
  import { A as AudioFormat, I as IBaseModelDescription, V as VendorOptionSchema, a as IImageProvider } from './ImageModel-BDI37OED.cjs';
9
9
  export { b as AspectRatio, c as IImageModelDescription, d as IMAGE_MODELS, e as IMAGE_MODEL_REGISTRY, f as ISourceLinks, g as ImageEditOptions, h as ImageGenerateOptions, i as ImageGeneration, j as ImageGenerationCreateOptions, k as ImageModelCapabilities, l as ImageModelPricing, m as ImageResponse, n as ImageVariationOptions, O as OutputFormat, Q as QualityLevel, S as SimpleGenerateOptions, o as calculateImageCost, p as getActiveImageModels, q as getImageModelInfo, r as getImageModelsByVendor, s as getImageModelsWithFeature } from './ImageModel-BDI37OED.cjs';
10
+ import { EventEmitter as EventEmitter$1 } from 'events';
10
11
  import { ServiceCategory } from './shared/index.cjs';
11
12
  export { ILLMDescription, LLM_MODELS, MODEL_REGISTRY, SERVICE_DEFINITIONS, SERVICE_INFO, SERVICE_URL_PATTERNS, ServiceDefinition, ServiceInfo, ServiceType, Services, calculateCost, detectServiceFromURL, getActiveModels, getAllServiceIds, getModelInfo, getModelsByVendor, getServiceDefinition, getServiceInfo, getServicesByCategory, isKnownService } from './shared/index.cjs';
12
13
 
@@ -1481,6 +1482,10 @@ declare class StorageRegistry {
1481
1482
  * Otherwise, calls `defaultFactory()`, caches the result, and returns it.
1482
1483
  */
1483
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;
1484
1489
  /**
1485
1490
  * Check if a storage backend has been configured.
1486
1491
  */
@@ -1687,7 +1692,7 @@ declare class CircuitBreaker<T = any> extends EventEmitter<CircuitBreakerEvents>
1687
1692
  */
1688
1693
  private transitionTo;
1689
1694
  /**
1690
- * Remove failures outside the time window
1695
+ * Remove failures outside the time window and cap array size
1691
1696
  */
1692
1697
  private pruneOldFailures;
1693
1698
  /**
@@ -3106,6 +3111,20 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3106
3111
  private _cachedBudget;
3107
3112
  /** Callback for beforeCompaction hook (set by Agent) */
3108
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;
3109
3128
  /**
3110
3129
  * Create a new AgentContextNextGen instance.
3111
3130
  */
@@ -3260,6 +3279,14 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3260
3279
  * Get current input (read-only).
3261
3280
  */
3262
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;
3263
3290
  /**
3264
3291
  * Get conversation length.
3265
3292
  */
@@ -3442,6 +3469,16 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3442
3469
  /**
3443
3470
  * Generate unique ID.
3444
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;
3445
3482
  private generateId;
3446
3483
  /**
3447
3484
  * Assert context is not destroyed.
@@ -4027,6 +4064,17 @@ interface AgentConfig$1 extends BaseAgentConfig {
4027
4064
  toolFailureMode?: 'fail' | 'continue';
4028
4065
  maxConsecutiveErrors?: number;
4029
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
+ };
4030
4078
  }
4031
4079
  /**
4032
4080
  * Agent class - represents an AI assistant with tool calling capabilities
@@ -4042,6 +4090,7 @@ interface AgentConfig$1 extends BaseAgentConfig {
4042
4090
  declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDisposable {
4043
4091
  private hookManager;
4044
4092
  private executionContext;
4093
+ private _toolRegisteredListener;
4045
4094
  private _paused;
4046
4095
  private _cancelled;
4047
4096
  private _pausePromise;
@@ -6002,6 +6051,29 @@ interface ITextToSpeechProvider extends IProvider {
6002
6051
  */
6003
6052
  listVoices?(): Promise<IVoiceInfo[]>;
6004
6053
  }
6054
+ /**
6055
+ * A single chunk of streamed TTS audio
6056
+ */
6057
+ interface TTSStreamChunk {
6058
+ /** Audio data for this chunk */
6059
+ audio: Buffer;
6060
+ /** True when this is the last chunk */
6061
+ isFinal: boolean;
6062
+ }
6063
+ /**
6064
+ * Streaming Text-to-Speech provider interface (opt-in extension)
6065
+ * Providers that support chunked transfer implement this alongside ITextToSpeechProvider.
6066
+ */
6067
+ interface IStreamingTextToSpeechProvider extends ITextToSpeechProvider {
6068
+ /**
6069
+ * Check if streaming is supported for the given format
6070
+ */
6071
+ supportsStreaming(format?: AudioFormat): boolean;
6072
+ /**
6073
+ * Stream TTS audio chunks as they arrive from the API
6074
+ */
6075
+ synthesizeStream(options: TTSOptions): AsyncIterableIterator<TTSStreamChunk>;
6076
+ }
6005
6077
  /**
6006
6078
  * STT output format types
6007
6079
  */
@@ -6234,6 +6306,15 @@ declare class TextToSpeech {
6234
6306
  * @param options - Optional synthesis parameters
6235
6307
  */
6236
6308
  toFile(text: string, filePath: string, options?: Partial<Omit<TTSOptions, 'model' | 'input'>>): Promise<void>;
6309
+ /**
6310
+ * Check if the underlying provider supports streaming TTS
6311
+ */
6312
+ supportsStreaming(format?: AudioFormat): boolean;
6313
+ /**
6314
+ * Stream TTS audio chunks as they arrive from the API.
6315
+ * Falls back to buffered synthesis yielding a single chunk if provider doesn't support streaming.
6316
+ */
6317
+ synthesizeStream(text: string, options?: Partial<Omit<TTSOptions, 'model' | 'input'>>): AsyncIterableIterator<TTSStreamChunk>;
6237
6318
  /**
6238
6319
  * Get model information for current or specified model
6239
6320
  */
@@ -7088,6 +7169,324 @@ declare class VideoGeneration {
7088
7169
  */
7089
7170
  declare function createVideoProvider(connector: Connector): IVideoProvider;
7090
7171
 
7172
+ /**
7173
+ * Types for voice pseudo-streaming capability
7174
+ */
7175
+
7176
+ /**
7177
+ * Interface for text chunking strategies used by VoiceStream.
7178
+ * Implementations accumulate streaming text deltas and emit complete
7179
+ * chunks suitable for TTS synthesis.
7180
+ */
7181
+ interface IChunkingStrategy {
7182
+ /**
7183
+ * Feed a text delta from the stream.
7184
+ * Returns any completed chunks (sentences/phrases).
7185
+ * Keeps partial text in an internal buffer.
7186
+ */
7187
+ feed(delta: string): string[];
7188
+ /**
7189
+ * Flush remaining buffered text as a final chunk.
7190
+ * Called when the text stream ends.
7191
+ */
7192
+ flush(): string | null;
7193
+ /** Reset internal state for reuse */
7194
+ reset(): void;
7195
+ }
7196
+ /**
7197
+ * Options for the default SentenceChunkingStrategy
7198
+ */
7199
+ interface ChunkingOptions {
7200
+ /** Minimum characters before emitting a chunk. Default: 20 */
7201
+ minChunkLength?: number;
7202
+ /** Maximum characters per chunk. Forces split at clause boundary. Default: 500 */
7203
+ maxChunkLength?: number;
7204
+ /** Skip text inside fenced code blocks. Default: true */
7205
+ skipCodeBlocks?: boolean;
7206
+ /** Strip markdown formatting (bold, italic, links, headings). Default: true */
7207
+ stripMarkdown?: boolean;
7208
+ /** Additional abbreviations to recognize (e.g., ['Corp.', 'Ltd.']) */
7209
+ additionalAbbreviations?: string[];
7210
+ }
7211
+ /**
7212
+ * Configuration for VoiceStream
7213
+ */
7214
+ interface VoiceStreamConfig {
7215
+ /** TTS connector name or instance */
7216
+ ttsConnector: string | Connector;
7217
+ /** TTS model (e.g., 'tts-1-hd', 'gpt-4o-mini-tts') */
7218
+ ttsModel?: string;
7219
+ /** Voice ID (e.g., 'nova', 'alloy') */
7220
+ voice?: string;
7221
+ /** Audio output format. Default: 'mp3' */
7222
+ format?: AudioFormat;
7223
+ /** Speech speed (0.25 to 4.0). Default: 1.0 */
7224
+ speed?: number;
7225
+ /** Custom chunking strategy. Default: SentenceChunkingStrategy */
7226
+ chunkingStrategy?: IChunkingStrategy;
7227
+ /** Options for default chunking strategy (ignored if chunkingStrategy provided) */
7228
+ chunkingOptions?: ChunkingOptions;
7229
+ /** Maximum concurrent TTS synthesis requests. Default: 2 */
7230
+ maxConcurrentTTS?: number;
7231
+ /**
7232
+ * Maximum queued chunks waiting for TTS.
7233
+ * When full, wrap() awaits a free slot (lossless backpressure).
7234
+ * Default: 5
7235
+ */
7236
+ maxQueuedChunks?: number;
7237
+ /** Vendor-specific TTS options passthrough */
7238
+ vendorOptions?: Record<string, unknown>;
7239
+ /**
7240
+ * Enable streaming TTS. When true, audio chunks are yielded as they arrive
7241
+ * from the API instead of buffering the entire response. Best with format 'pcm'.
7242
+ * Default: false
7243
+ */
7244
+ streaming?: boolean;
7245
+ }
7246
+ /**
7247
+ * Events emitted by VoiceStream via EventEmitter
7248
+ */
7249
+ interface VoiceStreamEvents {
7250
+ 'audio:ready': (data: {
7251
+ chunkIndex: number;
7252
+ text: string;
7253
+ durationSeconds?: number;
7254
+ }) => void;
7255
+ 'audio:error': (data: {
7256
+ chunkIndex: number;
7257
+ text: string;
7258
+ error: Error;
7259
+ }) => void;
7260
+ 'audio:complete': (data: {
7261
+ totalChunks: number;
7262
+ totalDurationSeconds?: number;
7263
+ }) => void;
7264
+ 'audio:interrupted': (data: {
7265
+ pendingChunks: number;
7266
+ }) => void;
7267
+ }
7268
+ /**
7269
+ * Callback invoked when the next in-order audio chunk is ready for playback
7270
+ */
7271
+ type AudioChunkPlaybackCallback = (event: AudioChunkReadyEvent) => void;
7272
+
7273
+ /**
7274
+ * VoiceStream - Voice pseudo-streaming capability
7275
+ *
7276
+ * Wraps an agent's text stream and interleaves audio events by chunking text
7277
+ * into sentences and synthesizing them via TTS in parallel. Produces the
7278
+ * illusion of real-time speech streaming.
7279
+ *
7280
+ * @example
7281
+ * ```typescript
7282
+ * const voice = VoiceStream.create({
7283
+ * ttsConnector: 'openai',
7284
+ * ttsModel: 'tts-1-hd',
7285
+ * voice: 'nova',
7286
+ * });
7287
+ *
7288
+ * for await (const event of voice.wrap(agent.stream('Tell me a story'))) {
7289
+ * if (event.type === StreamEventType.OUTPUT_TEXT_DELTA) {
7290
+ * process.stdout.write(event.delta);
7291
+ * } else if (event.type === StreamEventType.AUDIO_CHUNK_READY) {
7292
+ * playbackQueue.enqueue(event);
7293
+ * }
7294
+ * }
7295
+ * ```
7296
+ */
7297
+
7298
+ declare class VoiceStream extends EventEmitter$1 implements IDisposable {
7299
+ private tts;
7300
+ private chunker;
7301
+ private format;
7302
+ private speed;
7303
+ private maxConcurrentTTS;
7304
+ private maxQueuedChunks;
7305
+ private vendorOptions?;
7306
+ private streaming;
7307
+ private chunkIndex;
7308
+ private totalCharacters;
7309
+ private totalDuration;
7310
+ private activeJobs;
7311
+ private activeTTSCount;
7312
+ private interrupted;
7313
+ private lastResponseId;
7314
+ private _isDestroyed;
7315
+ private slotWaiters;
7316
+ private audioEventBuffer;
7317
+ private bufferNotify;
7318
+ private queueWaiters;
7319
+ /**
7320
+ * Create a new VoiceStream instance
7321
+ */
7322
+ static create(config: VoiceStreamConfig): VoiceStream;
7323
+ private constructor();
7324
+ /**
7325
+ * Transform an agent text stream into an augmented stream with audio events.
7326
+ * Original text events pass through unchanged; audio events are interleaved.
7327
+ *
7328
+ * The generator yields events in this order:
7329
+ * 1. All original StreamEvents (pass-through)
7330
+ * 2. AudioChunkReady/AudioChunkError events as TTS completes
7331
+ * 3. AudioStreamComplete as the final audio event
7332
+ */
7333
+ wrap(textStream: AsyncIterableIterator<StreamEvent>): AsyncIterableIterator<StreamEvent>;
7334
+ /**
7335
+ * Interrupt audio generation. Cancels pending TTS and flushes queue.
7336
+ * Call this when the user sends a new message mid-speech.
7337
+ * Active HTTP requests cannot be cancelled but their results will be discarded.
7338
+ */
7339
+ interrupt(): void;
7340
+ /**
7341
+ * Reset state for a new stream. Called automatically by wrap().
7342
+ */
7343
+ reset(): void;
7344
+ destroy(): void;
7345
+ get isDestroyed(): boolean;
7346
+ /**
7347
+ * Schedule a text chunk for TTS synthesis.
7348
+ * Awaits a free queue slot if backpressure is active (lossless).
7349
+ */
7350
+ private scheduleTTS;
7351
+ /**
7352
+ * Execute TTS for a single text chunk.
7353
+ * Respects concurrency semaphore.
7354
+ * Branches on streaming mode: yields sub-chunks or a single buffered chunk.
7355
+ */
7356
+ private executeTTS;
7357
+ /**
7358
+ * Drain the audio event buffer, yielding all ready events.
7359
+ */
7360
+ private drainAudioBuffer;
7361
+ /**
7362
+ * Push an audio event and wake up the consumer in wrap()
7363
+ */
7364
+ private pushAudioEvent;
7365
+ /**
7366
+ * Wait until a new event is pushed to the audio buffer
7367
+ */
7368
+ private waitForBufferNotify;
7369
+ private waitForTTSSlot;
7370
+ private releaseTTSSlot;
7371
+ private waitForQueueSlot;
7372
+ private releaseQueueWaiter;
7373
+ private releaseAllWaiters;
7374
+ private cleanup;
7375
+ }
7376
+
7377
+ /**
7378
+ * Sentence boundary detection for voice pseudo-streaming.
7379
+ * Splits streaming text deltas into speakable chunks.
7380
+ */
7381
+
7382
+ /**
7383
+ * Default chunking strategy that splits text at sentence boundaries.
7384
+ *
7385
+ * Handles:
7386
+ * - Sentence terminators (. ? !) followed by whitespace
7387
+ * - Abbreviation exclusion (Dr., Mr., U.S., e.g., etc.)
7388
+ * - Numeric decimals (3.14, $1.50)
7389
+ * - Paragraph breaks (\n\n)
7390
+ * - Fenced code block tracking (``` ... ```)
7391
+ * - Markdown stripping
7392
+ * - Min/max chunk length enforcement
7393
+ */
7394
+ declare class SentenceChunkingStrategy implements IChunkingStrategy {
7395
+ private buffer;
7396
+ private inCodeBlock;
7397
+ private codeBlockBuffer;
7398
+ private options;
7399
+ private abbreviations;
7400
+ constructor(options?: ChunkingOptions);
7401
+ feed(delta: string): string[];
7402
+ flush(): string | null;
7403
+ reset(): void;
7404
+ private extractChunks;
7405
+ /**
7406
+ * Track and remove fenced code blocks from the buffer.
7407
+ * Text inside code blocks is discarded (not spoken).
7408
+ */
7409
+ private processCodeBlocks;
7410
+ /**
7411
+ * Find the position right after the next sentence boundary.
7412
+ * Returns -1 if no complete sentence boundary found.
7413
+ */
7414
+ private findSentenceBoundary;
7415
+ /**
7416
+ * Check if the period at position `pos` is part of a known abbreviation.
7417
+ */
7418
+ private isAbbreviation;
7419
+ /**
7420
+ * Check if the period at position `pos` is a decimal point.
7421
+ * e.g., 3.14, $1.50
7422
+ */
7423
+ private isDecimalNumber;
7424
+ /**
7425
+ * Check if the period at position `pos` is part of an ellipsis (...).
7426
+ */
7427
+ private isEllipsis;
7428
+ /**
7429
+ * Split text that exceeds maxChunkLength at clause boundaries.
7430
+ */
7431
+ private splitLongText;
7432
+ /**
7433
+ * Merge chunks that are shorter than minChunkLength with the next chunk.
7434
+ */
7435
+ private mergeSmallChunks;
7436
+ /**
7437
+ * Strip markdown formatting from text for natural speech.
7438
+ */
7439
+ private cleanForSpeech;
7440
+ }
7441
+
7442
+ /**
7443
+ * AudioPlaybackQueue - Consumer-side helper for ordered audio playback
7444
+ *
7445
+ * TTS chunks may complete out of order (chunk 2 finishes before chunk 1).
7446
+ * This queue buffers audio events and delivers them to the callback
7447
+ * in sequential order by chunk_index.
7448
+ *
7449
+ * @example
7450
+ * ```typescript
7451
+ * const queue = new AudioPlaybackQueue((event) => {
7452
+ * // Play audio chunk — guaranteed to be in order
7453
+ * playAudio(Buffer.from(event.audio_base64, 'base64'));
7454
+ * });
7455
+ *
7456
+ * for await (const event of voiceStream.wrap(agent.stream('Hello'))) {
7457
+ * if (isAudioChunkReady(event)) {
7458
+ * queue.enqueue(event);
7459
+ * }
7460
+ * }
7461
+ * ```
7462
+ */
7463
+
7464
+ declare class AudioPlaybackQueue {
7465
+ private buffer;
7466
+ private nextPlayIndex;
7467
+ private onReady;
7468
+ constructor(onReady: AudioChunkPlaybackCallback);
7469
+ /**
7470
+ * Enqueue an audio chunk event. If it's the next expected chunk,
7471
+ * it (and any subsequent buffered chunks) are immediately delivered
7472
+ * to the callback in order.
7473
+ */
7474
+ enqueue(event: AudioChunkReadyEvent): void;
7475
+ /**
7476
+ * Reset the queue (e.g., on interruption or new stream).
7477
+ */
7478
+ reset(): void;
7479
+ /**
7480
+ * Number of chunks currently buffered waiting for earlier chunks.
7481
+ */
7482
+ get pendingCount(): number;
7483
+ /**
7484
+ * The next chunk index expected for playback.
7485
+ */
7486
+ get nextExpectedIndex(): number;
7487
+ private drain;
7488
+ }
7489
+
7091
7490
  /**
7092
7491
  * SearchProvider - Unified search interface with connector support
7093
7492
  *
@@ -7853,2099 +8252,2277 @@ declare function documentToContent(result: DocumentResult, options?: DocumentToC
7853
8252
  declare function readDocumentAsContent(source: DocumentSource | string, options?: DocumentReadOptions & DocumentToContentOptions): Promise<Content[]>;
7854
8253
 
7855
8254
  /**
7856
- * WorkingMemory class - manages indexed working memory for TaskAgent
7857
- *
7858
- * This is a GENERIC implementation that works across all agent types:
7859
- * - Basic Agent: Uses staticPriorityCalculator with simple scopes
7860
- * - TaskAgent: Uses taskAwarePriorityCalculator with task-aware scopes
7861
- * - UniversalAgent: Can switch calculators based on mode
8255
+ * Agent state entities for TaskAgent
7862
8256
  *
7863
- * The PriorityCalculator strategy pattern allows different agents to have
7864
- * different eviction behaviors without changing the core WorkingMemory logic.
8257
+ * Defines the full agent state needed for persistence and resume.
7865
8258
  */
7866
8259
 
7867
8260
  /**
7868
- * Serialized memory state for persistence
8261
+ * Agent execution status
7869
8262
  */
7870
- interface SerializedMemory {
7871
- /** Memory format version */
7872
- version: number;
7873
- /** Serialized memory entries */
7874
- 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[];
7875
8273
  }
7876
8274
  /**
7877
- * Serialized memory entry
8275
+ * Conversation message in history
7878
8276
  */
7879
- interface SerializedMemoryEntry {
7880
- key: string;
7881
- description: string;
7882
- value: unknown;
7883
- scope: MemoryScope;
7884
- sizeBytes: number;
7885
- basePriority?: MemoryPriority;
7886
- pinned?: boolean;
8277
+ interface ConversationMessage {
8278
+ role: 'user' | 'assistant' | 'system';
8279
+ content: string;
8280
+ timestamp: number;
7887
8281
  }
7888
8282
  /**
7889
- * Eviction strategy type
8283
+ * Agent execution metrics
7890
8284
  */
7891
- type EvictionStrategy = 'lru' | 'size';
7892
- interface WorkingMemoryEvents {
7893
- stored: {
7894
- key: string;
7895
- description: string;
7896
- scope: MemoryScope;
7897
- };
7898
- retrieved: {
7899
- key: string;
7900
- };
7901
- deleted: {
7902
- key: string;
7903
- };
7904
- evicted: {
7905
- keys: string[];
7906
- reason: 'lru' | 'size' | 'task_completed';
7907
- };
7908
- limit_warning: {
7909
- utilizationPercent: number;
7910
- };
7911
- stale_entries: {
7912
- entries: StaleEntryInfo[];
7913
- };
8285
+ interface AgentMetrics {
8286
+ totalLLMCalls: number;
8287
+ totalToolCalls: number;
8288
+ totalTokensUsed: number;
8289
+ totalCost: number;
7914
8290
  }
7915
8291
  /**
7916
- * WorkingMemory manages the agent's indexed working memory.
7917
- *
7918
- * Features:
7919
- * - Store/retrieve with descriptions for index
7920
- * - Scoped memory (simple or task-aware)
7921
- * - Priority-based eviction (respects pinned, priority, then LRU)
7922
- * - Pluggable priority calculation via PriorityCalculator strategy
7923
- * - Task completion detection and stale entry notification
7924
- * - Event emission for monitoring
8292
+ * Full agent state - everything needed to resume
7925
8293
  */
7926
- declare class WorkingMemory extends EventEmitter<WorkingMemoryEvents> implements IDisposable {
7927
- private storage;
7928
- private config;
7929
- private priorityCalculator;
7930
- private priorityContext;
7931
- private _isDestroyed;
7932
- /**
7933
- * Create a WorkingMemory instance
7934
- *
7935
- * @param storage - Storage backend for memory entries
7936
- * @param config - Memory configuration (limits, etc.)
7937
- * @param priorityCalculator - Strategy for computing effective priority (default: static)
7938
- */
7939
- constructor(storage: IMemoryStorage, config?: WorkingMemoryConfig, priorityCalculator?: PriorityCalculator);
7940
- /**
7941
- * Set the priority calculator (for switching strategies at runtime)
7942
- */
7943
- setPriorityCalculator(calculator: PriorityCalculator): void;
7944
- /**
7945
- * Update priority context (e.g., task states for TaskAgent)
7946
- */
7947
- setPriorityContext(context: PriorityContext): void;
7948
- /**
7949
- * Get the current priority context
7950
- */
7951
- getPriorityContext(): PriorityContext;
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 {
7952
8321
  /**
7953
- * Compute effective priority for an entry using the current calculator
8322
+ * Save or update a plan
7954
8323
  */
7955
- private computeEffectivePriority;
8324
+ savePlan(plan: Plan): Promise<void>;
7956
8325
  /**
7957
- * Get all entries with their computed effective priorities
7958
- * This is a performance optimization to avoid repeated getAll() + map() calls
8326
+ * Get plan by ID
7959
8327
  */
7960
- private getEntriesWithPriority;
8328
+ getPlan(planId: string): Promise<Plan | undefined>;
7961
8329
  /**
7962
- * Get evictable entries sorted by eviction priority
7963
- * Filters out pinned and critical entries, sorts by priority then by strategy
8330
+ * Update a specific task within a plan
7964
8331
  */
7965
- private getEvictableEntries;
8332
+ updateTask(planId: string, task: Task): Promise<void>;
7966
8333
  /**
7967
- * Store a value in working memory
7968
- *
7969
- * @param key - Unique key for the entry
7970
- * @param description - Short description for the index (max 150 chars)
7971
- * @param value - The data to store
7972
- * @param options - Optional scope, priority, and pinned settings
8334
+ * Add a new task to a plan (for dynamic task creation)
7973
8335
  */
7974
- store(key: string, description: string, value: unknown, options?: {
7975
- scope?: MemoryScope;
7976
- priority?: MemoryPriority;
7977
- pinned?: boolean;
7978
- }): Promise<void>;
8336
+ addTask(planId: string, task: Task): Promise<void>;
7979
8337
  /**
7980
- * Enforce the maxIndexEntries limit by evicting excess entries
7981
- * Only evicts if entry count exceeds the configured limit
8338
+ * Delete a plan
7982
8339
  */
7983
- private enforceEntryCountLimit;
8340
+ deletePlan(planId: string): Promise<void>;
7984
8341
  /**
7985
- * Get the configured max index entries limit
8342
+ * List plans by status
7986
8343
  */
7987
- getMaxIndexEntries(): number | undefined;
8344
+ listPlans(filter?: {
8345
+ status?: PlanStatus[];
8346
+ }): Promise<Plan[]>;
7988
8347
  /**
7989
- * Store a value scoped to specific tasks
7990
- * Convenience method for task-aware memory
8348
+ * Find plans with tasks waiting on a specific webhook
7991
8349
  */
7992
- storeForTasks(key: string, description: string, value: unknown, taskIds: string[], options?: {
7993
- priority?: MemoryPriority;
7994
- pinned?: boolean;
7995
- }): Promise<void>;
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 {
7996
8362
  /**
7997
- * Store a value scoped to the entire plan
7998
- * Convenience method for plan-scoped memory
8363
+ * Save agent state
7999
8364
  */
8000
- storeForPlan(key: string, description: string, value: unknown, options?: {
8001
- priority?: MemoryPriority;
8002
- pinned?: boolean;
8003
- }): Promise<void>;
8365
+ save(state: AgentState): Promise<void>;
8004
8366
  /**
8005
- * Retrieve a value from working memory
8006
- *
8007
- * Note: Access stats update is not strictly atomic. Under very high concurrency,
8008
- * accessCount may be slightly inaccurate. This is acceptable for memory management
8009
- * purposes where exact counts are not critical.
8367
+ * Load agent state
8010
8368
  */
8011
- retrieve(key: string): Promise<unknown>;
8369
+ load(agentId: string): Promise<AgentState | undefined>;
8012
8370
  /**
8013
- * Retrieve multiple values
8371
+ * Delete agent state
8014
8372
  */
8015
- retrieveMany(keys: string[]): Promise<Record<string, unknown>>;
8373
+ delete(agentId: string): Promise<void>;
8016
8374
  /**
8017
- * Delete a value from working memory
8375
+ * List agents by status
8018
8376
  */
8019
- delete(key: string): Promise<void>;
8377
+ list(filter?: {
8378
+ status?: AgentStatus[];
8379
+ }): Promise<AgentState[]>;
8020
8380
  /**
8021
- * Check if key exists
8381
+ * Update specific fields (partial update for efficiency)
8022
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>;
8397
+ delete(key: string): Promise<void>;
8023
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);
8024
8488
  /**
8025
- * Promote an entry to persistent scope
8026
- * Works with both simple and task-aware scopes
8489
+ * Load instruction entries from file.
8490
+ * Falls back to legacy .md file migration if JSON not found.
8027
8491
  */
8028
- persist(key: string): Promise<void>;
8492
+ load(): Promise<InstructionEntry[] | null>;
8029
8493
  /**
8030
- * Pin an entry (never evicted)
8494
+ * Save instruction entries to file as JSON.
8495
+ * Creates directory if it doesn't exist.
8496
+ * Cleans up legacy .md file if present.
8031
8497
  */
8032
- pin(key: string): Promise<void>;
8498
+ save(entries: InstructionEntry[]): Promise<void>;
8033
8499
  /**
8034
- * Unpin an entry
8500
+ * Delete instructions file (and legacy .md if exists)
8035
8501
  */
8036
- unpin(key: string, newPriority?: MemoryPriority): Promise<void>;
8502
+ delete(): Promise<void>;
8037
8503
  /**
8038
- * Set the base priority of an entry
8504
+ * Check if instructions file exists (JSON or legacy .md)
8039
8505
  */
8040
- setPriority(key: string, priority: MemoryPriority): Promise<void>;
8506
+ exists(): Promise<boolean>;
8041
8507
  /**
8042
- * Update the scope of an entry without re-storing the value
8508
+ * Get the file path (for display/debugging)
8043
8509
  */
8044
- updateScope(key: string, scope: MemoryScope): Promise<void>;
8510
+ getPath(): string;
8045
8511
  /**
8046
- * Add task IDs to an existing task-scoped entry
8047
- * If entry is not task-scoped, converts it to task-scoped
8512
+ * Get the agent ID
8048
8513
  */
8049
- addTasksToScope(key: string, taskIds: string[]): Promise<void>;
8514
+ getAgentId(): string;
8050
8515
  /**
8051
- * Clear all entries of a specific scope
8516
+ * Ensure the directory exists
8052
8517
  */
8053
- clearScope(scope: MemoryScope): Promise<void>;
8518
+ private ensureDirectory;
8054
8519
  /**
8055
- * Clear all entries
8520
+ * Remove legacy .md file if it exists
8056
8521
  */
8057
- clear(): Promise<void>;
8058
- /**
8059
- * Get memory index with computed effective priorities
8060
- * Respects maxIndexEntries limit for context display
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);
8563
+ /**
8564
+ * Save context state to a session file
8061
8565
  */
8062
- getIndex(): Promise<MemoryIndex>;
8566
+ save(sessionId: string, state: SerializedContextState, metadata?: ContextSessionMetadata): Promise<void>;
8063
8567
  /**
8064
- * Format index for context injection
8568
+ * Load context state from a session file
8065
8569
  */
8066
- formatIndex(): Promise<string>;
8570
+ load(sessionId: string): Promise<StoredContextSession | null>;
8067
8571
  /**
8068
- * Evict entries using specified strategy
8069
- *
8070
- * Eviction order:
8071
- * 1. Never evict pinned entries
8072
- * 2. Evict low priority first, then normal, then high (never critical)
8073
- * 3. Within same priority, use strategy (LRU or largest size)
8074
- *
8075
- * @param count - Number of entries to evict
8076
- * @param strategy - Eviction strategy ('lru' or 'size')
8077
- * @returns Keys of evicted entries
8572
+ * Delete a session
8078
8573
  */
8079
- evict(count: number, strategy?: EvictionStrategy): Promise<string[]>;
8574
+ delete(sessionId: string): Promise<void>;
8080
8575
  /**
8081
- * Evict entries using priority-aware LRU algorithm
8082
- * @deprecated Use evict(count, 'lru') instead
8576
+ * Check if a session exists
8083
8577
  */
8084
- evictLRU(count: number): Promise<string[]>;
8578
+ exists(sessionId: string): Promise<boolean>;
8085
8579
  /**
8086
- * Evict largest entries first (priority-aware)
8087
- * @deprecated Use evict(count, 'size') instead
8580
+ * List all sessions (summaries only)
8088
8581
  */
8089
- evictBySize(count: number): Promise<string[]>;
8582
+ list(options?: ContextStorageListOptions): Promise<ContextSessionSummary[]>;
8090
8583
  /**
8091
- * Handle task completion - detect and notify about stale entries
8092
- *
8093
- * Call this when a task completes to:
8094
- * 1. Update priority context with new task state
8095
- * 2. Detect entries that became stale
8096
- * 3. Emit event to notify LLM about stale entries
8097
- *
8098
- * @param taskId - The completed task ID
8099
- * @param taskStates - Current task states map
8100
- * @returns Information about stale entries
8584
+ * Update session metadata without loading full state
8101
8585
  */
8102
- onTaskComplete(taskId: string, taskStates: Map<string, TaskStatusForMemory>): Promise<StaleEntryInfo[]>;
8586
+ updateMetadata(sessionId: string, metadata: Partial<ContextSessionMetadata>): Promise<void>;
8103
8587
  /**
8104
- * Evict entries for completed tasks
8105
- *
8106
- * Removes entries that were scoped only to completed tasks.
8107
- * Use after onTaskComplete() if you want automatic cleanup.
8108
- *
8109
- * @param taskStates - Current task states map
8110
- * @returns Keys of evicted entries
8588
+ * Get the storage path (for display/debugging)
8589
+ * @deprecated Use getLocation() instead
8111
8590
  */
8112
- evictCompletedTaskEntries(taskStates: Map<string, TaskStatusForMemory>): Promise<string[]>;
8591
+ getPath(): string;
8113
8592
  /**
8114
- * Get limited memory access for tools
8115
- *
8116
- * This provides a simplified interface for tools to interact with memory
8117
- * without exposing the full WorkingMemory API.
8593
+ * Get a human-readable storage location string (for display/debugging)
8118
8594
  */
8119
- getAccess(): WorkingMemoryAccess;
8595
+ getLocation(): string;
8120
8596
  /**
8121
- * Store raw data (low priority, first to be evicted)
8122
- *
8123
- * Use this for original/unprocessed data that should be summarized.
8124
- * Raw data is automatically evicted first when memory pressure is high.
8125
- *
8126
- * @param key - Key without tier prefix (prefix is added automatically)
8127
- * @param description - Brief description for the index
8128
- * @param value - The raw data to store
8129
- * @param options - Optional scope and task IDs
8597
+ * Get the agent ID
8130
8598
  */
8131
- storeRaw(key: string, description: string, value: unknown, options?: {
8132
- taskIds?: string[];
8133
- scope?: MemoryScope;
8134
- }): Promise<void>;
8599
+ getAgentId(): string;
8135
8600
  /**
8136
- * Store a summary derived from raw data (normal priority)
8137
- *
8138
- * Use this for processed/summarized data that extracts key information.
8139
- * Links back to source data for cleanup tracking.
8140
- *
8141
- * @param key - Key without tier prefix (prefix is added automatically)
8142
- * @param description - Brief description for the index
8143
- * @param value - The summary data
8144
- * @param derivedFrom - Key(s) this summary was derived from
8145
- * @param options - Optional scope and task IDs
8601
+ * Rebuild the index by scanning all session files
8602
+ * Useful for recovery or migration
8146
8603
  */
8147
- storeSummary(key: string, description: string, value: unknown, derivedFrom: string | string[], options?: {
8148
- taskIds?: string[];
8149
- scope?: MemoryScope;
8150
- }): Promise<void>;
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);
8151
8677
  /**
8152
- * Store final findings (high priority, kept longest)
8153
- *
8154
- * Use this for conclusions, insights, or final results that should be preserved.
8155
- * These are the last to be evicted and typically span the entire plan.
8156
- *
8157
- * @param key - Key without tier prefix (prefix is added automatically)
8158
- * @param description - Brief description for the index
8159
- * @param value - The findings data
8160
- * @param derivedFrom - Optional key(s) these findings were derived from
8161
- * @param options - Optional scope, task IDs, and pinned flag
8678
+ * Get the JSONL file path for a session's history.
8162
8679
  */
8163
- storeFindings(key: string, description: string, value: unknown, _derivedFrom?: string | string[], options?: {
8164
- taskIds?: string[];
8165
- scope?: MemoryScope;
8166
- pinned?: boolean;
8167
- }): Promise<void>;
8680
+ private journalPath;
8168
8681
  /**
8169
- * Clean up raw data after summary/findings are created
8170
- *
8171
- * Call this after creating summaries to free up memory used by raw data.
8172
- * Only deletes entries in the 'raw' tier.
8173
- *
8174
- * @param derivedFromKeys - Keys to delete (typically from derivedFrom metadata)
8175
- * @returns Number of entries deleted
8682
+ * Ensure the sessions directory exists (lazy, once per instance).
8176
8683
  */
8177
- cleanupRawData(derivedFromKeys: string[]): Promise<number>;
8684
+ private ensureDirectory;
8178
8685
  /**
8179
- * Get all entries by tier
8686
+ * Append entries to the journal file.
8180
8687
  *
8181
- * @param tier - The tier to filter by
8182
- * @returns Array of entries in that tier
8688
+ * Uses fs.appendFile which is atomic for small writes on most filesystems.
8689
+ * Each entry is serialized as a single JSON line.
8183
8690
  */
8184
- getByTier(tier: MemoryTier): Promise<MemoryEntry[]>;
8691
+ append(sessionId: string, entries: HistoryEntry[]): Promise<void>;
8185
8692
  /**
8186
- * Promote an entry to a higher tier
8187
- *
8188
- * Changes the key prefix and updates priority.
8189
- * Use this when raw data becomes more valuable (e.g., frequently accessed).
8693
+ * Read history entries with optional filtering and pagination.
8190
8694
  *
8191
- * @param key - Current key (with tier prefix)
8192
- * @param toTier - Target tier to promote to
8193
- * @returns New key with updated prefix
8695
+ * For large files, prefer stream() with pagination.
8194
8696
  */
8195
- promote(key: string, toTier: MemoryTier): Promise<string>;
8697
+ read(sessionId: string, options?: HistoryReadOptions): Promise<HistoryEntry[]>;
8196
8698
  /**
8197
- * Get tier statistics
8699
+ * Count entries without fully parsing the file.
8198
8700
  *
8199
- * @returns Count and size by tier
8701
+ * Counts non-empty lines in the JSONL file.
8200
8702
  */
8201
- getTierStats(): Promise<Record<MemoryTier, {
8202
- count: number;
8203
- sizeBytes: number;
8204
- }>>;
8703
+ count(sessionId: string): Promise<number>;
8205
8704
  /**
8206
- * Get statistics about memory usage
8705
+ * Delete the journal file for a session.
8207
8706
  */
8208
- getStats(): Promise<{
8209
- totalEntries: number;
8210
- totalSizeBytes: number;
8211
- utilizationPercent: number;
8212
- byPriority: Record<MemoryPriority, number>;
8213
- pinnedCount: number;
8214
- }>;
8707
+ clear(sessionId: string): Promise<void>;
8215
8708
  /**
8216
- * Get the configured memory limit
8709
+ * Stream history entries line-by-line using readline.
8710
+ *
8711
+ * Memory-efficient for large histories — only one entry in memory at a time.
8217
8712
  */
8218
- getLimit(): number;
8713
+ stream(sessionId: string, options?: HistoryReadOptions): AsyncIterable<HistoryEntry>;
8219
8714
  /**
8220
- * Check if the WorkingMemory instance has been destroyed
8715
+ * Get the file path for a session's journal (for debugging).
8221
8716
  */
8222
- get isDestroyed(): boolean;
8717
+ getLocation(sessionId: string): string;
8223
8718
  /**
8224
- * Destroy the WorkingMemory instance
8225
- * Removes all event listeners and clears internal state
8719
+ * Apply non-pagination filters to an array of entries.
8226
8720
  */
8227
- destroy(): void;
8721
+ private applyFilters;
8228
8722
  /**
8229
- * Serialize all memory entries for persistence
8230
- *
8231
- * Returns a serializable representation of all memory entries
8232
- * that can be saved to storage and restored later.
8233
- *
8234
- * @returns Serialized memory state
8723
+ * Check if a single entry matches the filter criteria.
8235
8724
  */
8236
- serialize(): Promise<SerializedMemory>;
8237
- /**
8238
- * Restore memory entries from serialized state
8239
- *
8240
- * Clears existing memory and repopulates from the serialized state.
8241
- * Timestamps are reset to current time.
8242
- *
8243
- * @param state - Previously serialized memory state
8244
- */
8245
- restore(state: SerializedMemory): Promise<void>;
8725
+ private matchesFilters;
8246
8726
  }
8247
8727
 
8248
8728
  /**
8249
- * 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
8250
8741
  */
8251
8742
 
8252
- interface ExternalDependencyEvents {
8253
- 'webhook:received': {
8254
- webhookId: string;
8255
- data: unknown;
8256
- };
8257
- 'poll:success': {
8258
- taskId: string;
8259
- data: unknown;
8260
- };
8261
- 'poll:timeout': {
8262
- taskId: string;
8263
- };
8264
- 'scheduled:triggered': {
8265
- taskId: string;
8266
- };
8267
- 'manual:completed': {
8268
- taskId: string;
8269
- data: unknown;
8270
- };
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;
8271
8751
  }
8272
8752
  /**
8273
- * Handles external task dependencies
8753
+ * File-based storage for agent definitions
8274
8754
  */
8275
- declare class ExternalDependencyHandler extends EventEmitter<ExternalDependencyEvents> {
8276
- private activePolls;
8277
- private activeScheduled;
8278
- private cancelledPolls;
8279
- private tools;
8280
- 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);
8281
8761
  /**
8282
- * Start handling a task's external dependency
8762
+ * Save an agent definition
8283
8763
  */
8284
- startWaiting(task: Task): Promise<void>;
8764
+ save(definition: StoredAgentDefinition): Promise<void>;
8285
8765
  /**
8286
- * Stop waiting on a task's external dependency
8766
+ * Load an agent definition
8287
8767
  */
8288
- stopWaiting(task: Task): void;
8768
+ load(agentId: string): Promise<StoredAgentDefinition | null>;
8289
8769
  /**
8290
- * Trigger a webhook
8770
+ * Delete an agent definition
8291
8771
  */
8292
- triggerWebhook(webhookId: string, data: unknown): Promise<void>;
8772
+ delete(agentId: string): Promise<void>;
8293
8773
  /**
8294
- * Complete a manual task
8774
+ * Check if an agent definition exists
8295
8775
  */
8296
- completeManual(taskId: string, data: unknown): Promise<void>;
8776
+ exists(agentId: string): Promise<boolean>;
8297
8777
  /**
8298
- * Start polling for a task with exponential backoff
8778
+ * List all agent definitions
8299
8779
  */
8300
- private startPolling;
8780
+ list(options?: AgentDefinitionListOptions): Promise<AgentDefinitionSummary[]>;
8301
8781
  /**
8302
- * Schedule a task to trigger at a specific time
8782
+ * Update metadata without loading full definition
8303
8783
  */
8304
- private scheduleTask;
8784
+ updateMetadata(agentId: string, metadata: Partial<AgentDefinitionMetadata>): Promise<void>;
8305
8785
  /**
8306
- * Cleanup all active dependencies
8786
+ * Get storage path
8307
8787
  */
8308
- cleanup(): void;
8788
+ getPath(): string;
8309
8789
  /**
8310
- * Update available tools
8790
+ * Rebuild the index by scanning all agent directories
8311
8791
  */
8312
- 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;
8313
8800
  }
8314
-
8315
8801
  /**
8316
- * Agent state entities for TaskAgent
8317
- *
8318
- * Defines the full agent state needed for persistence and resume.
8802
+ * Create a FileAgentDefinitionStorage with default configuration
8319
8803
  */
8804
+ declare function createFileAgentDefinitionStorage(config?: FileAgentDefinitionStorageConfig): FileAgentDefinitionStorage;
8320
8805
 
8321
8806
  /**
8322
- * Agent execution status
8323
- */
8324
- type AgentStatus = 'idle' | 'running' | 'suspended' | 'completed' | 'failed' | 'cancelled';
8325
- /**
8326
- * Agent configuration (needed for resume)
8807
+ * FileMediaStorage - File-based media storage implementation
8808
+ *
8809
+ * Saves generated media to a configurable directory on the local filesystem.
8810
+ * Default output directory: `os.tmpdir()/oneringai-media/`
8327
8811
  */
8328
- interface AgentConfig {
8329
- connectorName: string;
8330
- model: string;
8331
- temperature?: number;
8332
- maxIterations?: number;
8333
- toolNames: string[];
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;
8334
8829
  }
8335
8830
  /**
8336
- * Conversation message in history
8831
+ * Factory function for creating FileMediaStorage instances
8337
8832
  */
8338
- interface ConversationMessage {
8339
- role: 'user' | 'assistant' | 'system';
8340
- content: string;
8341
- timestamp: number;
8342
- }
8833
+ declare function createFileMediaStorage(config?: FileMediaStorageConfig): FileMediaStorage;
8834
+
8343
8835
  /**
8344
- * 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)
8345
8848
  */
8346
- interface AgentMetrics {
8347
- totalLLMCalls: number;
8348
- totalToolCalls: number;
8349
- totalTokensUsed: number;
8350
- totalCost: number;
8351
- }
8849
+
8352
8850
  /**
8353
- * Full agent state - everything needed to resume
8851
+ * Configuration for FileCustomToolStorage
8354
8852
  */
8355
- interface AgentState {
8356
- id: string;
8357
- status: AgentStatus;
8358
- /** Configuration */
8359
- config: AgentConfig;
8360
- /** Current plan */
8361
- plan: Plan;
8362
- /** Working memory reference */
8363
- memoryId: string;
8364
- /** Conversation history (for context continuity) */
8365
- conversationHistory: ConversationMessage[];
8366
- /** Timestamps */
8367
- createdAt: number;
8368
- startedAt?: number;
8369
- suspendedAt?: number;
8370
- completedAt?: number;
8371
- lastActivityAt: number;
8372
- /** Metrics */
8373
- 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;
8374
8858
  }
8375
-
8376
8859
  /**
8377
- * Plan storage interface for plan persistence.
8378
- * 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.
8379
8863
  */
8380
-
8381
- interface IPlanStorage {
8864
+ declare class FileCustomToolStorage implements ICustomToolStorage {
8865
+ private readonly baseDirectory;
8866
+ private readonly prettyPrint;
8867
+ constructor(config?: FileCustomToolStorageConfig);
8382
8868
  /**
8383
- * Save or update a plan
8869
+ * Get the directory path for a specific user's custom tools
8384
8870
  */
8385
- savePlan(plan: Plan): Promise<void>;
8871
+ private getUserDirectory;
8386
8872
  /**
8387
- * Get plan by ID
8873
+ * Get the index file path for a specific user
8388
8874
  */
8389
- getPlan(planId: string): Promise<Plan | undefined>;
8875
+ private getUserIndexPath;
8390
8876
  /**
8391
- * Update a specific task within a plan
8877
+ * Get the tool file path for a specific user
8392
8878
  */
8393
- updateTask(planId: string, task: Task): Promise<void>;
8879
+ private getToolPath;
8394
8880
  /**
8395
- * Add a new task to a plan (for dynamic task creation)
8881
+ * Save a custom tool definition
8396
8882
  */
8397
- addTask(planId: string, task: Task): Promise<void>;
8883
+ save(userId: string | undefined, definition: CustomToolDefinition): Promise<void>;
8398
8884
  /**
8399
- * Delete a plan
8885
+ * Load a custom tool definition by name
8400
8886
  */
8401
- deletePlan(planId: string): Promise<void>;
8887
+ load(userId: string | undefined, name: string): Promise<CustomToolDefinition | null>;
8402
8888
  /**
8403
- * List plans by status
8889
+ * Delete a custom tool definition
8404
8890
  */
8405
- listPlans(filter?: {
8406
- status?: PlanStatus[];
8407
- }): Promise<Plan[]>;
8891
+ delete(userId: string | undefined, name: string): Promise<void>;
8408
8892
  /**
8409
- * Find plans with tasks waiting on a specific webhook
8893
+ * Check if a custom tool exists
8410
8894
  */
8411
- findByWebhookId(webhookId: string): Promise<{
8412
- plan: Plan;
8413
- task: Task;
8414
- } | undefined>;
8415
- }
8416
-
8417
- /**
8418
- * Agent state storage interface for full agent state persistence.
8419
- * Required for resume capability.
8420
- */
8421
-
8422
- interface IAgentStateStorage {
8895
+ exists(userId: string | undefined, name: string): Promise<boolean>;
8423
8896
  /**
8424
- * Save agent state
8897
+ * List custom tools (summaries only)
8425
8898
  */
8426
- save(state: AgentState): Promise<void>;
8899
+ list(userId: string | undefined, options?: CustomToolListOptions): Promise<CustomToolSummary[]>;
8427
8900
  /**
8428
- * Load agent state
8901
+ * Update metadata without loading full definition
8429
8902
  */
8430
- load(agentId: string): Promise<AgentState | undefined>;
8903
+ updateMetadata(userId: string | undefined, name: string, metadata: Record<string, unknown>): Promise<void>;
8431
8904
  /**
8432
- * Delete agent state
8905
+ * Get storage path for a specific user
8433
8906
  */
8434
- delete(agentId: string): Promise<void>;
8435
- /**
8436
- * List agents by status
8437
- */
8438
- list(filter?: {
8439
- status?: AgentStatus[];
8440
- }): Promise<AgentState[]>;
8441
- /**
8442
- * Update specific fields (partial update for efficiency)
8443
- */
8444
- patch(agentId: string, updates: Partial<AgentState>): Promise<void>;
8907
+ getPath(userId: string | undefined): string;
8908
+ private ensureDirectory;
8909
+ private loadIndex;
8910
+ private saveIndex;
8911
+ private updateIndex;
8912
+ private removeFromIndex;
8913
+ private definitionToIndexEntry;
8445
8914
  }
8446
-
8447
8915
  /**
8448
- * In-memory storage implementations (default, non-persistent)
8916
+ * Create a FileCustomToolStorage with default configuration
8449
8917
  */
8918
+ declare function createFileCustomToolStorage(config?: FileCustomToolStorageConfig): FileCustomToolStorage;
8450
8919
 
8451
8920
  /**
8452
- * In-memory implementation of IMemoryStorage
8453
- */
8454
- declare class InMemoryStorage implements IMemoryStorage {
8455
- private store;
8456
- get(key: string): Promise<MemoryEntry | undefined>;
8457
- set(key: string, entry: MemoryEntry): Promise<void>;
8458
- delete(key: string): Promise<void>;
8459
- has(key: string): Promise<boolean>;
8460
- getAll(): Promise<MemoryEntry[]>;
8461
- getByScope(scope: MemoryScope): Promise<MemoryEntry[]>;
8462
- clearScope(scope: MemoryScope): Promise<void>;
8463
- clear(): Promise<void>;
8464
- getTotalSize(): Promise<number>;
8465
- }
8466
- /**
8467
- * In-memory implementation of IPlanStorage
8468
- */
8469
- declare class InMemoryPlanStorage implements IPlanStorage {
8470
- private plans;
8471
- savePlan(plan: Plan): Promise<void>;
8472
- getPlan(planId: string): Promise<Plan | undefined>;
8473
- updateTask(planId: string, task: Task): Promise<void>;
8474
- addTask(planId: string, task: Task): Promise<void>;
8475
- deletePlan(planId: string): Promise<void>;
8476
- listPlans(filter?: {
8477
- status?: PlanStatus[];
8478
- }): Promise<Plan[]>;
8479
- findByWebhookId(webhookId: string): Promise<{
8480
- plan: Plan;
8481
- task: Task;
8482
- } | undefined>;
8483
- }
8484
- /**
8485
- * In-memory implementation of IAgentStateStorage
8486
- */
8487
- declare class InMemoryAgentStateStorage implements IAgentStateStorage {
8488
- private agents;
8489
- save(state: AgentState): Promise<void>;
8490
- load(agentId: string): Promise<AgentState | undefined>;
8491
- delete(agentId: string): Promise<void>;
8492
- list(filter?: {
8493
- status?: AgentStatus[];
8494
- }): Promise<AgentState[]>;
8495
- patch(agentId: string, updates: Partial<AgentState>): Promise<void>;
8496
- }
8497
- /**
8498
- * Unified agent storage interface
8499
- */
8500
- interface IAgentStorage {
8501
- memory: IMemoryStorage;
8502
- plan: IPlanStorage;
8503
- agent: IAgentStateStorage;
8504
- }
8505
- /**
8506
- * Create agent storage with defaults
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)
8507
8933
  */
8508
- declare function createAgentStorage(options?: {
8509
- memory?: IMemoryStorage;
8510
- plan?: IPlanStorage;
8511
- agent?: IAgentStateStorage;
8512
- }): IAgentStorage;
8513
8934
 
8514
8935
  /**
8515
- * CheckpointManager - manages agent state checkpointing
8936
+ * Configuration for FileUserInfoStorage
8516
8937
  */
8517
-
8518
- interface CheckpointStrategy {
8519
- /** Checkpoint after every N tool calls */
8520
- afterToolCalls?: number;
8521
- /** Checkpoint after every N LLM calls */
8522
- afterLLMCalls?: number;
8523
- /** Checkpoint on time interval */
8524
- intervalMs?: number;
8525
- /** Always checkpoint before external wait */
8526
- beforeExternalWait: boolean;
8527
- /** Checkpoint mode */
8528
- mode: 'sync' | 'async';
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;
8529
8943
  }
8530
- declare const DEFAULT_CHECKPOINT_STRATEGY: CheckpointStrategy;
8531
8944
  /**
8532
- * Manages state checkpointing for persistence and recovery
8945
+ * File-based storage for user information
8946
+ *
8947
+ * Single instance handles all users. UserId is passed to each method.
8533
8948
  */
8534
- declare class CheckpointManager {
8535
- private storage;
8536
- private strategy;
8537
- private toolCallsSinceCheckpoint;
8538
- private llmCallsSinceCheckpoint;
8539
- private intervalTimer?;
8540
- private pendingCheckpoints;
8541
- private currentState;
8542
- constructor(storage: IAgentStorage, strategy?: CheckpointStrategy);
8949
+ declare class FileUserInfoStorage implements IUserInfoStorage {
8950
+ private readonly baseDirectory;
8951
+ private readonly filename;
8952
+ constructor(config?: FileUserInfoStorageConfig);
8543
8953
  /**
8544
- * Set the current agent state (for interval checkpointing)
8954
+ * Get the directory path for a specific user
8545
8955
  */
8546
- setCurrentState(state: AgentState): void;
8956
+ private getUserDirectory;
8547
8957
  /**
8548
- * Record a tool call (may trigger checkpoint)
8958
+ * Get the file path for a specific user
8549
8959
  */
8550
- onToolCall(state: AgentState): Promise<void>;
8960
+ private getUserFilePath;
8551
8961
  /**
8552
- * Record an LLM call (may trigger checkpoint)
8962
+ * Load user info entries from file for a specific user
8553
8963
  */
8554
- onLLMCall(state: AgentState): Promise<void>;
8964
+ load(userId: string | undefined): Promise<UserInfoEntry[] | null>;
8555
8965
  /**
8556
- * Force a checkpoint
8966
+ * Save user info entries to file for a specific user
8967
+ * Creates directory if it doesn't exist.
8557
8968
  */
8558
- checkpoint(state: AgentState, reason: string): Promise<void>;
8969
+ save(userId: string | undefined, entries: UserInfoEntry[]): Promise<void>;
8559
8970
  /**
8560
- * Perform the actual checkpoint
8971
+ * Delete user info file for a specific user
8561
8972
  */
8562
- private doCheckpoint;
8973
+ delete(userId: string | undefined): Promise<void>;
8563
8974
  /**
8564
- * Check if interval-based checkpoint is needed
8975
+ * Check if user info file exists for a specific user
8565
8976
  */
8566
- private checkIntervalCheckpoint;
8977
+ exists(userId: string | undefined): Promise<boolean>;
8567
8978
  /**
8568
- * Wait for all pending checkpoints to complete
8979
+ * Get the file path for a specific user (for display/debugging)
8569
8980
  */
8570
- flush(): Promise<void>;
8981
+ getPath(userId: string | undefined): string;
8571
8982
  /**
8572
- * Cleanup resources
8983
+ * Ensure the directory exists
8573
8984
  */
8574
- cleanup(): Promise<void>;
8985
+ private ensureDirectory;
8575
8986
  }
8576
8987
 
8577
8988
  /**
8578
- * PlanningAgent - AI-driven plan generation
8989
+ * FileRoutineDefinitionStorage - File-based storage for routine definitions.
8579
8990
  *
8580
- * Separates planning phase from execution phase.
8581
- * Analyzes goals and generates task graphs with dependencies.
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
8582
9001
  */
8583
9002
 
8584
9003
  /**
8585
- * PlanningAgent configuration
9004
+ * Configuration for FileRoutineDefinitionStorage
8586
9005
  */
8587
- interface PlanningAgentConfig {
8588
- /** Connector for LLM access */
8589
- connector: string | Connector;
8590
- /** Model to use for planning (can be different/cheaper than execution) */
8591
- model: string;
8592
- /** Max planning iterations */
8593
- maxPlanningIterations?: number;
8594
- /** Temperature for planning (lower = more deterministic) */
8595
- planningTemperature?: number;
8596
- /** Tools available for the plan (used to inform planning) */
8597
- availableTools?: ToolFunction[];
9006
+ interface FileRoutineDefinitionStorageConfig {
9007
+ /** Override the base directory (default: ~/.oneringai/users) */
9008
+ baseDirectory?: string;
9009
+ /** Pretty-print JSON (default: true) */
9010
+ prettyPrint?: boolean;
8598
9011
  }
8599
9012
  /**
8600
- * Generated plan with metadata
9013
+ * File-based storage for routine definitions.
9014
+ *
9015
+ * Single instance handles all users. UserId is passed to each method.
8601
9016
  */
8602
- interface GeneratedPlan {
8603
- plan: Plan;
8604
- reasoning: string;
8605
- estimated_duration?: string;
8606
- complexity?: 'low' | 'medium' | 'high';
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;
8607
9046
  }
8608
9047
  /**
8609
- * PlanningAgent class
9048
+ * Create a FileRoutineDefinitionStorage with default configuration
8610
9049
  */
8611
- declare class PlanningAgent {
8612
- private agent;
8613
- private config;
8614
- private currentTasks;
8615
- private planningComplete;
8616
- private constructor();
8617
- /**
8618
- * Create a new PlanningAgent
8619
- */
8620
- static create(config: PlanningAgentConfig): PlanningAgent;
8621
- /**
8622
- * Create planning tools bound to this PlanningAgent instance
8623
- */
8624
- private createBoundPlanningTools;
8625
- /**
8626
- * Generate a plan from a goal
8627
- */
8628
- generatePlan(input: {
8629
- goal: string;
8630
- context?: string;
8631
- constraints?: string[];
8632
- }): Promise<GeneratedPlan>;
8633
- /**
8634
- * Validate and refine an existing plan
8635
- */
8636
- refinePlan(plan: Plan, feedback: string): Promise<GeneratedPlan>;
8637
- /**
8638
- * Build planning prompt from input
8639
- */
8640
- private buildPlanningPrompt;
8641
- /**
8642
- * Estimate plan complexity
8643
- */
8644
- private estimateComplexity;
8645
- /**
8646
- * Get current tasks (for tool access)
8647
- */
8648
- getCurrentTasks(): TaskInput[];
9050
+ declare function createFileRoutineDefinitionStorage(config?: FileRoutineDefinitionStorageConfig): FileRoutineDefinitionStorage;
9051
+
9052
+ /**
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)
9066
+ */
9067
+
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;
9078
+ }
9079
+ /**
9080
+ * File-based storage for routine execution records.
9081
+ *
9082
+ * Single instance handles all users. UserId is passed to each method.
9083
+ */
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;
8649
9109
  /**
8650
- * Add task (called by planning tools)
9110
+ * Load a record directly by userId + executionId (used by list()).
8651
9111
  */
8652
- addTask(task: TaskInput): void;
9112
+ private loadByUserAndId;
8653
9113
  /**
8654
- * Update task (called by planning tools)
9114
+ * Resolve the file path for an execution ID.
9115
+ * Uses in-memory cache first, then falls back to scanning user directories.
8655
9116
  */
8656
- updateTask(name: string, updates: Partial<TaskInput>): void;
9117
+ private resolveExecutionFile;
9118
+ private loadIndex;
9119
+ private saveIndex;
9120
+ private updateIndex;
9121
+ private recordToIndexEntry;
8657
9122
  /**
8658
- * Remove task (called by planning tools)
9123
+ * Prune old completed/failed records if count exceeds maxRecords.
9124
+ * Running/paused/pending records are never pruned.
8659
9125
  */
8660
- removeTask(name: string): void;
9126
+ private pruneOldRecords;
8661
9127
  /**
8662
- * Mark planning as complete
9128
+ * Rebuild index by scanning directory for .json files (excluding _index.json).
9129
+ * Returns empty index if directory doesn't exist.
8663
9130
  */
8664
- finalizePlanning(): void;
9131
+ private rebuildIndex;
8665
9132
  }
8666
9133
  /**
8667
- * Simple plan generation without tools (fallback)
9134
+ * Create a FileRoutineExecutionStorage with default configuration
8668
9135
  */
8669
- declare function generateSimplePlan(goal: string, context?: string): Promise<Plan>;
9136
+ declare function createFileRoutineExecutionStorage(config?: FileRoutineExecutionStorageConfig): FileRoutineExecutionStorage;
8670
9137
 
8671
9138
  /**
8672
- * ResearchAgent Types
9139
+ * WorkingMemory class - manages indexed working memory for TaskAgent
8673
9140
  *
8674
- * Generic interfaces for research sources that work with any data provider:
8675
- * - Web search (Serper, Brave, Tavily)
8676
- * - Vector databases (Pinecone, Weaviate, Qdrant)
8677
- * - File systems (local, S3, GCS)
8678
- * - APIs (REST, GraphQL)
8679
- * - Databases (SQL, MongoDB)
8680
- */
8681
- /**
8682
- * A single search result from any source
8683
- */
8684
- interface SourceResult {
8685
- /** Unique identifier for this result */
8686
- id: string;
8687
- /** Human-readable title */
8688
- title: string;
8689
- /** Brief description or snippet */
8690
- snippet: string;
8691
- /** Reference for fetching full content (URL, path, ID, etc.) */
8692
- reference: string;
8693
- /** Relevance score (0-1, higher is better) */
8694
- relevance?: number;
8695
- /** Source-specific metadata */
8696
- metadata?: Record<string, unknown>;
8697
- }
8698
- /**
8699
- * Response from a search operation
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.
8700
9148
  */
8701
- interface SearchResponse {
8702
- /** Whether the search succeeded */
8703
- success: boolean;
8704
- /** Original query */
8705
- query: string;
8706
- /** Results found */
8707
- results: SourceResult[];
8708
- /** Total results available (may be more than returned) */
8709
- totalResults?: number;
8710
- /** Error message if failed */
8711
- error?: string;
8712
- /** Source-specific metadata */
8713
- metadata?: Record<string, unknown>;
8714
- }
9149
+
8715
9150
  /**
8716
- * Fetched content from a source
9151
+ * Serialized memory state for persistence
8717
9152
  */
8718
- interface FetchedContent {
8719
- /** Whether fetch succeeded */
8720
- success: boolean;
8721
- /** Reference that was fetched */
8722
- reference: string;
8723
- /** The actual content */
8724
- content: unknown;
8725
- /** Content type hint (text, html, json, binary, etc.) */
8726
- contentType?: string;
8727
- /** Size in bytes */
8728
- sizeBytes?: number;
8729
- /** Error message if failed */
8730
- error?: string;
8731
- /** Source-specific metadata */
8732
- metadata?: Record<string, unknown>;
9153
+ interface SerializedMemory {
9154
+ /** Memory format version */
9155
+ version: number;
9156
+ /** Serialized memory entries */
9157
+ entries: SerializedMemoryEntry[];
8733
9158
  }
8734
9159
  /**
8735
- * Options for search operations
9160
+ * Serialized memory entry
8736
9161
  */
8737
- interface SearchOptions {
8738
- /** Maximum results to return */
8739
- maxResults?: number;
8740
- /** Minimum relevance score (0-1) */
8741
- minRelevance?: number;
8742
- /** Source-specific options */
8743
- sourceOptions?: Record<string, unknown>;
9162
+ interface SerializedMemoryEntry {
9163
+ key: string;
9164
+ description: string;
9165
+ value: unknown;
9166
+ scope: MemoryScope;
9167
+ sizeBytes: number;
9168
+ basePriority?: MemoryPriority;
9169
+ pinned?: boolean;
8744
9170
  }
8745
9171
  /**
8746
- * Options for fetch operations
9172
+ * Eviction strategy type
8747
9173
  */
8748
- interface FetchOptions {
8749
- /** Maximum content size to fetch (bytes) */
8750
- maxSize?: number;
8751
- /** Timeout in milliseconds */
8752
- timeoutMs?: number;
8753
- /** Source-specific options */
8754
- sourceOptions?: Record<string, unknown>;
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
+ };
8755
9197
  }
8756
9198
  /**
8757
- * Generic research source interface
9199
+ * WorkingMemory manages the agent's indexed working memory.
8758
9200
  *
8759
- * Implement this interface to add any data source to ResearchAgent:
8760
- * - Web: search queries, fetch URLs
8761
- * - Vector DB: similarity search, fetch documents
8762
- * - File system: glob patterns, read files
8763
- * - API: query endpoints, fetch resources
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
8764
9208
  */
8765
- interface IResearchSource {
8766
- /** Unique name for this source */
8767
- readonly name: string;
8768
- /** Human-readable description */
8769
- readonly description: string;
8770
- /** Type of source (for categorization) */
8771
- readonly type: 'web' | 'vector' | 'file' | 'api' | 'database' | 'custom';
9209
+ declare class WorkingMemory extends EventEmitter<WorkingMemoryEvents> implements IDisposable {
9210
+ private storage;
9211
+ private config;
9212
+ private priorityCalculator;
9213
+ private priorityContext;
9214
+ private _isDestroyed;
8772
9215
  /**
8773
- * Search this source for relevant results
9216
+ * Create a WorkingMemory instance
8774
9217
  *
8775
- * @param query - Search query (interpreted by source)
8776
- * @param options - Search options
8777
- * @returns Search response with results
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)
8778
9221
  */
8779
- search(query: string, options?: SearchOptions): Promise<SearchResponse>;
9222
+ constructor(storage: IMemoryStorage, config?: WorkingMemoryConfig, priorityCalculator?: PriorityCalculator);
8780
9223
  /**
8781
- * Fetch full content for a result
8782
- *
8783
- * @param reference - Reference from SourceResult
8784
- * @param options - Fetch options
8785
- * @returns Fetched content
9224
+ * Set the priority calculator (for switching strategies at runtime)
8786
9225
  */
8787
- fetch(reference: string, options?: FetchOptions): Promise<FetchedContent>;
9226
+ setPriorityCalculator(calculator: PriorityCalculator): void;
8788
9227
  /**
8789
- * Optional: Check if source is available/configured
9228
+ * Update priority context (e.g., task states for TaskAgent)
8790
9229
  */
8791
- isAvailable?(): Promise<boolean>;
9230
+ setPriorityContext(context: PriorityContext): void;
8792
9231
  /**
8793
- * Optional: Get source capabilities
9232
+ * Get the current priority context
8794
9233
  */
8795
- getCapabilities?(): SourceCapabilities;
8796
- }
8797
- /**
8798
- * Source capabilities for discovery
8799
- */
8800
- interface SourceCapabilities {
8801
- /** Whether source supports search */
8802
- canSearch: boolean;
8803
- /** Whether source supports fetch */
8804
- canFetch: boolean;
8805
- /** Whether results include relevance scores */
8806
- hasRelevanceScores: boolean;
8807
- /** Maximum results per search */
8808
- maxResultsPerSearch?: number;
8809
- /** Supported content types */
8810
- contentTypes?: string[];
8811
- }
8812
- /**
8813
- * Research finding stored in memory
8814
- */
8815
- interface ResearchFinding {
8816
- /** Source that provided this finding */
8817
- source: string;
8818
- /** Original query that found this */
8819
- query: string;
8820
- /** Key insight or summary */
8821
- summary: string;
8822
- /** Supporting details */
8823
- details?: string;
8824
- /** References used */
8825
- references: string[];
8826
- /** Confidence level (0-1) */
8827
- confidence?: number;
8828
- /** When this was found */
8829
- timestamp: number;
8830
- }
8831
- /**
8832
- * Research plan for systematic research
8833
- */
8834
- interface ResearchPlan {
8835
- /** Research goal/question */
8836
- goal: string;
8837
- /** Queries to execute */
8838
- queries: ResearchQuery[];
8839
- /** Sources to use (empty = all available) */
8840
- sources?: string[];
8841
- /** Maximum results per query */
8842
- maxResultsPerQuery?: number;
8843
- /** Maximum total findings */
8844
- maxTotalFindings?: number;
8845
- }
8846
- /**
8847
- * A query in the research plan
8848
- */
8849
- interface ResearchQuery {
8850
- /** Query string */
8851
- query: string;
8852
- /** Specific sources for this query (empty = all) */
8853
- sources?: string[];
8854
- /** Priority (higher = more important) */
8855
- priority?: number;
8856
- }
8857
- /**
8858
- * Research execution result
8859
- */
8860
- interface ResearchResult {
8861
- /** Whether research completed successfully */
8862
- success: boolean;
8863
- /** Original goal */
8864
- goal: string;
8865
- /** Queries executed */
8866
- queriesExecuted: number;
8867
- /** Results found */
8868
- resultsFound: number;
8869
- /** Results processed */
8870
- resultsProcessed: number;
8871
- /** Findings generated */
8872
- findingsCount: number;
8873
- /** Final synthesis (if generated) */
8874
- synthesis?: string;
8875
- /** Error if failed */
8876
- error?: string;
8877
- /** Execution metrics */
8878
- metrics?: {
8879
- totalDurationMs: number;
8880
- searchDurationMs: number;
8881
- processDurationMs: number;
8882
- synthesizeDurationMs: number;
8883
- };
8884
- }
8885
- /**
8886
- * Research progress event
8887
- */
8888
- interface ResearchProgress {
8889
- phase: 'searching' | 'processing' | 'synthesizing' | 'complete';
8890
- currentQuery?: string;
8891
- currentSource?: string;
8892
- queriesCompleted: number;
8893
- totalQueries: number;
8894
- resultsProcessed: number;
8895
- totalResults: number;
8896
- findingsGenerated: number;
8897
- }
8898
-
8899
- /**
8900
- * Core types for context management system
8901
- */
8902
- /**
8903
- * Context component that can be compacted
8904
- */
8905
- interface IContextComponent {
8906
- /** Unique name for this component */
8907
- name: string;
8908
- /** The actual content (string or structured data) */
8909
- content: string | unknown;
8910
- /** Priority for compaction (higher = compact first) */
8911
- priority: number;
8912
- /** Whether this component can be compacted */
8913
- compactable: boolean;
8914
- /** Additional metadata for compaction strategies */
8915
- metadata?: Record<string, unknown>;
8916
- }
8917
- /**
8918
- * Context budget information
8919
- */
8920
- interface ContextBudget {
8921
- /** Total available tokens */
8922
- total: number;
8923
- /** Reserved tokens for response */
8924
- reserved: number;
8925
- /** Currently used tokens */
8926
- used: number;
8927
- /** Available tokens remaining */
8928
- available: number;
8929
- /** Utilization percentage (used / (total - reserved)) */
8930
- utilizationPercent: number;
8931
- /** Budget status */
8932
- status: 'ok' | 'warning' | 'critical';
8933
- /** Token breakdown by component */
8934
- breakdown: Record<string, number>;
8935
- }
8936
- /**
8937
- * Context manager configuration
8938
- */
8939
- interface ContextManagerConfig {
8940
- /** Maximum context tokens for the model */
8941
- maxContextTokens: number;
8942
- /** Threshold to trigger compaction (0.0 - 1.0) */
8943
- compactionThreshold: number;
8944
- /** Hard limit - must compact before this (0.0 - 1.0) */
8945
- hardLimit: number;
8946
- /** Reserve space for response (0.0 - 1.0) */
8947
- responseReserve: number;
8948
- /** Token estimator to use */
8949
- estimator: 'approximate' | 'tiktoken' | ITokenEstimator;
8950
- /** Enable automatic compaction */
8951
- autoCompact: boolean;
8952
- /** Strategy to use */
8953
- strategy?: 'proactive' | 'aggressive' | 'lazy' | 'rolling-window' | 'adaptive' | IContextStrategy;
8954
- /** Strategy-specific options */
8955
- strategyOptions?: Record<string, unknown>;
8956
- }
8957
- /**
8958
- * Default configuration
8959
- */
8960
- declare const DEFAULT_CONTEXT_CONFIG: ContextManagerConfig;
8961
- /**
8962
- * Content type for more accurate token estimation
8963
- * Named differently from TokenContentType in Content.ts to avoid conflicts
8964
- */
8965
- type TokenContentType = 'code' | 'prose' | 'mixed';
8966
- /**
8967
- * Abstract interface for token estimation
8968
- */
8969
- interface ITokenEstimator {
9234
+ getPriorityContext(): PriorityContext;
8970
9235
  /**
8971
- * Estimate token count for text
9236
+ * Compute effective priority for an entry using the current calculator
9237
+ */
9238
+ private computeEffectivePriority;
9239
+ /**
9240
+ * Get all entries with their computed effective priorities
9241
+ * This is a performance optimization to avoid repeated getAll() + map() calls
9242
+ */
9243
+ private getEntriesWithPriority;
9244
+ /**
9245
+ * Get evictable entries sorted by eviction priority
9246
+ * Filters out pinned and critical entries, sorts by priority then by strategy
9247
+ */
9248
+ private getEvictableEntries;
9249
+ /**
9250
+ * Store a value in working memory
8972
9251
  *
8973
- * @param text - The text to estimate
8974
- * @param contentType - Type of content for more accurate estimation:
8975
- * - 'code': Code is typically denser (~3 chars/token)
8976
- * - 'prose': Natural language text (~4 chars/token)
8977
- * - 'mixed': Mix of code and prose (~3.5 chars/token)
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
8978
9256
  */
8979
- estimateTokens(text: string, contentType?: TokenContentType): number;
9257
+ store(key: string, description: string, value: unknown, options?: {
9258
+ scope?: MemoryScope;
9259
+ priority?: MemoryPriority;
9260
+ pinned?: boolean;
9261
+ }): Promise<void>;
8980
9262
  /**
8981
- * Estimate tokens for structured data
9263
+ * Enforce the maxIndexEntries limit by evicting excess entries
9264
+ * Only evicts if entry count exceeds the configured limit
8982
9265
  */
8983
- estimateDataTokens(data: unknown, contentType?: TokenContentType): number;
9266
+ private enforceEntryCountLimit;
8984
9267
  /**
8985
- * Estimate tokens for an image.
8986
- * @param width - Image width in pixels (if known)
8987
- * @param height - Image height in pixels (if known)
8988
- * @param detail - Image detail level: 'low', 'high', or 'auto'
9268
+ * Get the configured max index entries limit
8989
9269
  */
8990
- estimateImageTokens?(width?: number, height?: number, detail?: string): number;
8991
- }
8992
- /**
8993
- * Abstract interface for compaction strategies
8994
- */
8995
- interface IContextCompactor {
8996
- /** Compactor name */
8997
- readonly name: string;
8998
- /** Priority order (lower = run first) */
8999
- readonly priority: number;
9270
+ getMaxIndexEntries(): number | undefined;
9000
9271
  /**
9001
- * Check if this compactor can handle the component
9272
+ * Store a value scoped to specific tasks
9273
+ * Convenience method for task-aware memory
9274
+ */
9275
+ storeForTasks(key: string, description: string, value: unknown, taskIds: string[], options?: {
9276
+ priority?: MemoryPriority;
9277
+ pinned?: boolean;
9278
+ }): Promise<void>;
9279
+ /**
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
9289
+ *
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.
9293
+ */
9294
+ retrieve(key: string): Promise<unknown>;
9295
+ /**
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
9352
+ *
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
9361
+ */
9362
+ evict(count: number, strategy?: EvictionStrategy): Promise<string[]>;
9363
+ /**
9364
+ * Evict entries using priority-aware LRU algorithm
9365
+ * @deprecated Use evict(count, 'lru') instead
9366
+ */
9367
+ evictLRU(count: number): Promise<string[]>;
9368
+ /**
9369
+ * Evict largest entries first (priority-aware)
9370
+ * @deprecated Use evict(count, 'size') instead
9371
+ */
9372
+ evictBySize(count: number): Promise<string[]>;
9373
+ /**
9374
+ * Handle task completion - detect and notify about stale entries
9375
+ *
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
9384
+ */
9385
+ onTaskComplete(taskId: string, taskStates: Map<string, TaskStatusForMemory>): Promise<StaleEntryInfo[]>;
9386
+ /**
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
9394
+ */
9395
+ evictCompletedTaskEntries(taskStates: Map<string, TaskStatusForMemory>): Promise<string[]>;
9396
+ /**
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.
9401
+ */
9402
+ getAccess(): WorkingMemoryAccess;
9403
+ /**
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
9002
9477
  */
9003
- canCompact(component: IContextComponent): boolean;
9478
+ promote(key: string, toTier: MemoryTier): Promise<string>;
9004
9479
  /**
9005
- * Compact the component to target size
9480
+ * Get tier statistics
9481
+ *
9482
+ * @returns Count and size by tier
9006
9483
  */
9007
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9484
+ getTierStats(): Promise<Record<MemoryTier, {
9485
+ count: number;
9486
+ sizeBytes: number;
9487
+ }>>;
9008
9488
  /**
9009
- * Estimate savings from compaction
9489
+ * Get statistics about memory usage
9010
9490
  */
9011
- estimateSavings(component: IContextComponent): number;
9012
- }
9013
- /**
9014
- * Context management strategy - defines the overall approach to managing context
9015
- */
9016
- interface IContextStrategy {
9017
- /** Strategy name */
9018
- readonly name: string;
9491
+ getStats(): Promise<{
9492
+ totalEntries: number;
9493
+ totalSizeBytes: number;
9494
+ utilizationPercent: number;
9495
+ byPriority: Record<MemoryPriority, number>;
9496
+ pinnedCount: number;
9497
+ }>;
9019
9498
  /**
9020
- * Decide if compaction is needed based on current budget
9499
+ * Get the configured memory limit
9021
9500
  */
9022
- shouldCompact(budget: ContextBudget, config: ContextManagerConfig): boolean;
9501
+ getLimit(): number;
9023
9502
  /**
9024
- * Execute compaction using available compactors
9503
+ * Check if the WorkingMemory instance has been destroyed
9025
9504
  */
9026
- compact(components: IContextComponent[], budget: ContextBudget, compactors: IContextCompactor[], estimator: ITokenEstimator): Promise<{
9027
- components: IContextComponent[];
9028
- log: string[];
9029
- tokensFreed: number;
9030
- }>;
9505
+ get isDestroyed(): boolean;
9031
9506
  /**
9032
- * Optional: Prepare components before budget calculation
9033
- * 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
9034
9509
  */
9035
- prepareComponents?(components: IContextComponent[]): Promise<IContextComponent[]>;
9510
+ destroy(): void;
9036
9511
  /**
9037
- * Optional: Post-process after compaction
9038
- * 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
9039
9518
  */
9040
- postProcess?(components: IContextComponent[], budget: ContextBudget): Promise<IContextComponent[]>;
9519
+ serialize(): Promise<SerializedMemory>;
9041
9520
  /**
9042
- * 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
9043
9527
  */
9044
- getMetrics?(): Record<string, unknown>;
9045
- }
9046
-
9047
- /**
9048
- * Truncate Compactor
9049
- *
9050
- * Truncates content to target size by:
9051
- * - For strings: Cut to character limit
9052
- * - For arrays: Keep most recent items
9053
- */
9054
-
9055
- declare class TruncateCompactor implements IContextCompactor {
9056
- private estimator;
9057
- readonly name = "truncate";
9058
- readonly priority = 10;
9059
- constructor(estimator: ITokenEstimator);
9060
- canCompact(component: IContextComponent): boolean;
9061
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9062
- estimateSavings(component: IContextComponent): number;
9063
- private truncateString;
9064
- private truncateArray;
9528
+ restore(state: SerializedMemory): Promise<void>;
9065
9529
  }
9066
9530
 
9067
9531
  /**
9068
- * Summarize Compactor
9069
- *
9070
- * Uses LLM to create intelligent summaries of context components before compaction.
9071
- * This preserves the semantic meaning of content while reducing token count.
9072
- *
9073
- * Supports different summarization strategies based on content type:
9074
- * - Conversation history: Preserves decisions, facts, and preferences
9075
- * - Tool outputs (search/scrape): Preserves key findings, sources, and data
9532
+ * ExternalDependencyHandler - handles external dependencies
9076
9533
  */
9077
9534
 
9078
- /**
9079
- * Configuration for the SummarizeCompactor
9080
- */
9081
- interface SummarizeCompactorConfig {
9082
- /** Text provider for LLM-based summarization */
9083
- textProvider: ITextProvider;
9084
- /** Model to use for summarization (optional - uses provider default) */
9085
- model?: string;
9086
- /** Maximum tokens for the summary (default: 500) */
9087
- maxSummaryTokens?: number;
9088
- /** Preserve markdown structure like headings and lists (default: true) */
9089
- preserveStructure?: boolean;
9090
- /** Fall back to truncation if LLM summarization fails (default: true) */
9091
- fallbackToTruncate?: boolean;
9092
- /** Temperature for summarization (default: 0.3 for deterministic output) */
9093
- 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
+ };
9094
9554
  }
9095
9555
  /**
9096
- * SummarizeCompactor - LLM-based context compaction
9097
- *
9098
- * Uses AI to intelligently summarize content, preserving semantic meaning
9099
- * while significantly reducing token count.
9556
+ * Handles external task dependencies
9100
9557
  */
9101
- declare class SummarizeCompactor implements IContextCompactor {
9102
- readonly name = "summarize";
9103
- readonly priority = 5;
9104
- private config;
9105
- private estimator;
9106
- 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[]);
9107
9564
  /**
9108
- * Check if this compactor can handle the component
9565
+ * Start handling a task's external dependency
9109
9566
  */
9110
- canCompact(component: IContextComponent): boolean;
9567
+ startWaiting(task: Task): Promise<void>;
9111
9568
  /**
9112
- * Compact the component by summarizing its content
9569
+ * Stop waiting on a task's external dependency
9113
9570
  */
9114
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9571
+ stopWaiting(task: Task): void;
9115
9572
  /**
9116
- * Estimate how many tokens could be saved by summarization
9573
+ * Trigger a webhook
9117
9574
  */
9118
- estimateSavings(component: IContextComponent): number;
9575
+ triggerWebhook(webhookId: string, data: unknown): Promise<void>;
9119
9576
  /**
9120
- * Perform LLM-based summarization
9577
+ * Complete a manual task
9121
9578
  */
9122
- private summarize;
9579
+ completeManual(taskId: string, data: unknown): Promise<void>;
9123
9580
  /**
9124
- * Fallback to simple truncation when LLM fails
9581
+ * Start polling for a task with exponential backoff
9125
9582
  */
9126
- private truncateFallback;
9583
+ private startPolling;
9127
9584
  /**
9128
- * Detect content type from component metadata or name
9585
+ * Schedule a task to trigger at a specific time
9129
9586
  */
9130
- private detectContentType;
9587
+ private scheduleTask;
9131
9588
  /**
9132
- * Convert content to string for processing
9589
+ * Cleanup all active dependencies
9133
9590
  */
9134
- private stringifyContent;
9591
+ cleanup(): void;
9592
+ /**
9593
+ * Update available tools
9594
+ */
9595
+ updateTools(tools: ToolFunction[]): void;
9135
9596
  }
9136
9597
 
9137
9598
  /**
9138
- * Memory Eviction Compactor
9139
- *
9140
- * Evicts LRU entries from memory index
9141
- * Works with memory components that have eviction metadata
9599
+ * CheckpointManager - manages agent state checkpointing
9142
9600
  */
9143
9601
 
9144
- declare class MemoryEvictionCompactor implements IContextCompactor {
9145
- private estimator;
9146
- readonly name = "memory-eviction";
9147
- readonly priority = 8;
9148
- constructor(estimator: ITokenEstimator);
9149
- canCompact(component: IContextComponent): boolean;
9150
- compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9151
- 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';
9152
9613
  }
9153
-
9614
+ declare const DEFAULT_CHECKPOINT_STRATEGY: CheckpointStrategy;
9154
9615
  /**
9155
- * Approximate Token Estimator
9156
- *
9157
- * Uses content-type aware heuristics:
9158
- * - Code: ~3 chars/token (more symbols, shorter words)
9159
- * - Prose: ~4 chars/token (natural language)
9160
- * - Mixed: ~3.5 chars/token
9161
- *
9162
- * Fast and good enough for most use cases.
9616
+ * Manages state checkpointing for persistence and recovery
9163
9617
  */
9164
-
9165
- 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);
9166
9627
  /**
9167
- * Estimate tokens for text with content-type awareness
9168
- *
9169
- * @param text - The text to estimate tokens for
9170
- * @param contentType - Type of content:
9171
- * - 'code': Code is typically denser (~3 chars/token)
9172
- * - 'prose': Natural language text (~4 chars/token)
9173
- * - 'mixed': Mix of code and prose (~3.5 chars/token)
9628
+ * Set the current agent state (for interval checkpointing)
9174
9629
  */
9175
- 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;
9176
9651
  /**
9177
- * Estimate tokens for structured data (always uses 'mixed' estimation)
9652
+ * Wait for all pending checkpoints to complete
9178
9653
  */
9179
- estimateDataTokens(data: unknown, contentType?: TokenContentType): number;
9654
+ flush(): Promise<void>;
9180
9655
  /**
9181
- * Estimate tokens for an image using tile-based model (matches OpenAI pricing).
9182
- *
9183
- * - detail='low': 85 tokens
9184
- * - detail='high' with known dimensions: 85 + 170 per 512×512 tile
9185
- * - Unknown dimensions: 1000 tokens (conservative default)
9656
+ * Cleanup resources
9186
9657
  */
9187
- estimateImageTokens(width?: number, height?: number, detail?: string): number;
9658
+ cleanup(): Promise<void>;
9188
9659
  }
9189
9660
 
9190
9661
  /**
9191
- * Token estimators
9192
- */
9193
-
9194
- /**
9195
- * Create token estimator from name
9196
- */
9197
- declare function createEstimator(name: string): ITokenEstimator;
9198
-
9199
- /**
9200
- * IHistoryManager - Interface for conversation history management
9662
+ * PlanningAgent - AI-driven plan generation
9201
9663
  *
9202
- * Follows the same pattern as IMemoryStorage for pluggable implementations.
9203
- * 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.
9204
9666
  */
9205
9667
 
9206
9668
  /**
9207
- * A single message in conversation history
9208
- */
9209
- interface HistoryMessage {
9210
- id: string;
9211
- role: 'user' | 'assistant' | 'system';
9212
- content: string;
9213
- timestamp: number;
9214
- metadata?: Record<string, unknown>;
9215
- }
9216
- /**
9217
- * Events emitted by IHistoryManager implementations
9218
- */
9219
- interface HistoryManagerEvents {
9220
- 'message:added': {
9221
- message: HistoryMessage;
9222
- };
9223
- 'message:removed': {
9224
- messageId: string;
9225
- };
9226
- 'history:cleared': {
9227
- reason?: string;
9228
- };
9229
- 'history:compacted': {
9230
- removedCount: number;
9231
- strategy: string;
9232
- };
9233
- 'history:restored': {
9234
- messageCount: number;
9235
- };
9236
- }
9237
- /**
9238
- * Configuration for history management
9669
+ * PlanningAgent configuration
9239
9670
  */
9240
- interface IHistoryManagerConfig {
9241
- /** Maximum messages to keep (for sliding window) */
9242
- maxMessages?: number;
9243
- /** Maximum tokens to keep (estimated) */
9244
- maxTokens?: number;
9245
- /** Compaction strategy when limits are reached */
9246
- compactionStrategy?: 'truncate' | 'summarize' | 'sliding-window';
9247
- /** Number of recent messages to always preserve */
9248
- 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[];
9249
9682
  }
9250
9683
  /**
9251
- * Serialized history state for persistence
9684
+ * Generated plan with metadata
9252
9685
  */
9253
- interface SerializedHistoryState {
9254
- version: number;
9255
- messages: HistoryMessage[];
9256
- summaries?: Array<{
9257
- content: string;
9258
- coversCount: number;
9259
- timestamp: number;
9260
- }>;
9261
- metadata?: Record<string, unknown>;
9686
+ interface GeneratedPlan {
9687
+ plan: Plan;
9688
+ reasoning: string;
9689
+ estimated_duration?: string;
9690
+ complexity?: 'low' | 'medium' | 'high';
9262
9691
  }
9263
9692
  /**
9264
- * Interface for history storage backends
9265
- * Implement this to use custom storage (Redis, PostgreSQL, file, etc.)
9693
+ * PlanningAgent class
9266
9694
  */
9267
- interface IHistoryStorage {
9268
- /**
9269
- * Store a message
9270
- */
9271
- addMessage(message: HistoryMessage): Promise<void>;
9272
- /**
9273
- * Get all messages
9274
- */
9275
- getMessages(): Promise<HistoryMessage[]>;
9276
- /**
9277
- * Get recent N messages
9278
- */
9279
- getRecentMessages(count: number): Promise<HistoryMessage[]>;
9280
- /**
9281
- * Remove a message by ID
9282
- */
9283
- removeMessage(id: string): Promise<void>;
9695
+ declare class PlanningAgent {
9696
+ private agent;
9697
+ private config;
9698
+ private currentTasks;
9699
+ private planningComplete;
9700
+ private constructor();
9284
9701
  /**
9285
- * Remove messages older than timestamp
9702
+ * Create a new PlanningAgent
9286
9703
  */
9287
- removeOlderThan(timestamp: number): Promise<number>;
9704
+ static create(config: PlanningAgentConfig): PlanningAgent;
9288
9705
  /**
9289
- * Clear all messages
9706
+ * Create planning tools bound to this PlanningAgent instance
9290
9707
  */
9291
- clear(): Promise<void>;
9708
+ private createBoundPlanningTools;
9292
9709
  /**
9293
- * Get message count
9710
+ * Generate a plan from a goal
9294
9711
  */
9295
- getCount(): Promise<number>;
9712
+ generatePlan(input: {
9713
+ goal: string;
9714
+ context?: string;
9715
+ constraints?: string[];
9716
+ }): Promise<GeneratedPlan>;
9296
9717
  /**
9297
- * Get serialized state for session persistence
9718
+ * Validate and refine an existing plan
9298
9719
  */
9299
- getState(): Promise<SerializedHistoryState>;
9720
+ refinePlan(plan: Plan, feedback: string): Promise<GeneratedPlan>;
9300
9721
  /**
9301
- * Restore from serialized state
9722
+ * Build planning prompt from input
9302
9723
  */
9303
- restoreState(state: SerializedHistoryState): Promise<void>;
9304
- }
9305
- /**
9306
- * Interface for history manager
9307
- * Manages conversation history with compaction and persistence support
9308
- */
9309
- interface IHistoryManager extends EventEmitter<HistoryManagerEvents> {
9724
+ private buildPlanningPrompt;
9310
9725
  /**
9311
- * Add a message to history
9726
+ * Estimate plan complexity
9312
9727
  */
9313
- addMessage(role: 'user' | 'assistant' | 'system', content: string, metadata?: Record<string, unknown>): Promise<HistoryMessage>;
9728
+ private estimateComplexity;
9314
9729
  /**
9315
- * Get all messages (may include summaries as system messages)
9730
+ * Get current tasks (for tool access)
9316
9731
  */
9317
- getMessages(): Promise<HistoryMessage[]>;
9732
+ getCurrentTasks(): TaskInput[];
9318
9733
  /**
9319
- * Get recent messages only
9734
+ * Add task (called by planning tools)
9320
9735
  */
9321
- getRecentMessages(count?: number): Promise<HistoryMessage[]>;
9736
+ addTask(task: TaskInput): void;
9322
9737
  /**
9323
- * Get formatted history for LLM context
9738
+ * Update task (called by planning tools)
9324
9739
  */
9325
- formatForContext(options?: {
9326
- maxTokens?: number;
9327
- includeMetadata?: boolean;
9328
- }): Promise<string>;
9740
+ updateTask(name: string, updates: Partial<TaskInput>): void;
9329
9741
  /**
9330
- * Compact history (apply compaction strategy)
9742
+ * Remove task (called by planning tools)
9331
9743
  */
9332
- compact(): Promise<void>;
9744
+ removeTask(name: string): void;
9333
9745
  /**
9334
- * Clear all history
9746
+ * Mark planning as complete
9335
9747
  */
9336
- 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';
9337
9856
  /**
9338
- * 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
9339
9862
  */
9340
- getMessageCount(): Promise<number>;
9863
+ search(query: string, options?: SearchOptions): Promise<SearchResponse>;
9341
9864
  /**
9342
- * 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
9343
9870
  */
9344
- getState(): Promise<SerializedHistoryState>;
9871
+ fetch(reference: string, options?: FetchOptions): Promise<FetchedContent>;
9345
9872
  /**
9346
- * Restore from saved state
9873
+ * Optional: Check if source is available/configured
9347
9874
  */
9348
- restoreState(state: SerializedHistoryState): Promise<void>;
9875
+ isAvailable?(): Promise<boolean>;
9349
9876
  /**
9350
- * Get current configuration
9877
+ * Optional: Get source capabilities
9351
9878
  */
9352
- getConfig(): IHistoryManagerConfig;
9879
+ getCapabilities?(): SourceCapabilities;
9353
9880
  }
9354
9881
  /**
9355
- * Default configuration
9882
+ * Source capabilities for discovery
9356
9883
  */
9357
- declare const DEFAULT_HISTORY_MANAGER_CONFIG: Required<IHistoryManagerConfig>;
9358
-
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
+ }
9359
9896
  /**
9360
- * InMemoryHistoryStorage - In-memory implementation of IHistoryStorage
9361
- *
9362
- * Default storage backend for conversation history.
9363
- * For production, users can implement IHistoryStorage with Redis, PostgreSQL, etc.
9897
+ * Research finding stored in memory
9364
9898
  */
9365
-
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
+ }
9366
9915
  /**
9367
- * In-memory history storage implementation
9916
+ * Research plan for systematic research
9368
9917
  */
9369
- declare class InMemoryHistoryStorage implements IHistoryStorage {
9370
- private messages;
9371
- private summaries;
9372
- addMessage(message: HistoryMessage): Promise<void>;
9373
- getMessages(): Promise<HistoryMessage[]>;
9374
- getRecentMessages(count: number): Promise<HistoryMessage[]>;
9375
- removeMessage(id: string): Promise<void>;
9376
- removeOlderThan(timestamp: number): Promise<number>;
9377
- clear(): Promise<void>;
9378
- getCount(): Promise<number>;
9379
- getState(): Promise<SerializedHistoryState>;
9380
- 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;
9381
9929
  }
9382
-
9383
9930
  /**
9384
- * Routine Control Flow map, fold, until handlers + template resolution
9385
- *
9386
- * Control flow tasks delegate to executeRoutine() recursively with the shared agent,
9387
- * using ICM keys (__map_item, __map_index, etc.) to pass iteration state.
9931
+ * A query in the research plan
9388
9932
  */
9389
-
9390
- /** Well-known ICM/WM keys used by the routine execution framework. */
9391
- declare const ROUTINE_KEYS: {
9392
- /** Plan overview with task statuses (ICM) */
9393
- readonly PLAN: "__routine_plan";
9394
- /** Dependency results location guide (ICM) */
9395
- readonly DEPS: "__routine_deps";
9396
- /** Prefix for per-dependency result keys (ICM/WM) */
9397
- readonly DEP_RESULT_PREFIX: "__dep_result_";
9398
- /** Current map/fold item (ICM) */
9399
- readonly MAP_ITEM: "__map_item";
9400
- /** Current map/fold index, 0-based (ICM) */
9401
- readonly MAP_INDEX: "__map_index";
9402
- /** Total items in map/fold (ICM) */
9403
- readonly MAP_TOTAL: "__map_total";
9404
- /** Running fold accumulator (ICM) */
9405
- readonly FOLD_ACCUMULATOR: "__fold_accumulator";
9406
- /** Prefix for large dep results stored in WM findings tier */
9407
- readonly WM_DEP_FINDINGS_PREFIX: "findings/__dep_result_";
9408
- /** Prefix for auto-stored task outputs (set by output contracts) */
9409
- readonly TASK_OUTPUT_PREFIX: "__task_output_";
9410
- };
9411
- interface ControlFlowResult {
9412
- completed: boolean;
9413
- result?: unknown;
9414
- 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;
9415
9940
  }
9416
9941
  /**
9417
- * Resolve template placeholders in text.
9418
- *
9419
- * Supported namespaces:
9420
- * - {{param.name}} → inputs[name]
9421
- * - {{map.item}} / {{map.index}} / {{map.total}} → ICM keys
9422
- * - {{fold.accumulator}} → ICM key
9423
- *
9424
- * Non-string values are JSON.stringify'd. Unresolved templates are left as-is.
9942
+ * Research execution result
9425
9943
  */
9426
- 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
+ }
9427
9969
  /**
9428
- * Resolve the source array for a map/fold control flow using layered resolution:
9429
- * 1. Determine lookup key(s) from source config
9430
- * 2. Read from ICM/WM with fallback chain
9431
- * 3. Apply JSON path extraction if specified
9432
- * 4. Coerce to array algorithmically (JSON parse, common field names)
9433
- * 5. LLM extraction fallback if still not an array
9970
+ * Research progress event
9434
9971
  */
9435
- declare function resolveFlowSource(flow: {
9436
- source: ControlFlowSource;
9437
- maxIterations?: number;
9438
- }, flowType: string, agent: Agent, execution: RoutineExecution | undefined, icmPlugin: InContextMemoryPluginNextGen | null, wmPlugin: WorkingMemoryPluginNextGen | null): Promise<{
9439
- array: unknown[];
9440
- maxIter: number;
9441
- } | 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
+ }
9442
9982
 
9443
9983
  /**
9444
- * FilePersistentInstructionsStorage - File-based storage for persistent instructions
9445
- *
9446
- * Stores custom agent instructions as a JSON file on disk.
9447
- * Path: ~/.oneringai/agents/<agentId>/custom_instructions.json
9448
- * Windows: %APPDATA%/oneringai/agents/<agentId>/custom_instructions.json
9449
- *
9450
- * Features:
9451
- * - Cross-platform path handling
9452
- * - Safe agent ID sanitization
9453
- * - Atomic file operations
9454
- * - Automatic directory creation
9455
- * - 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
9456
10043
  */
9457
-
10044
+ declare const DEFAULT_CONTEXT_CONFIG: ContextManagerConfig;
9458
10045
  /**
9459
- * Configuration for FilePersistentInstructionsStorage
10046
+ * Content type for more accurate token estimation
10047
+ * Named differently from TokenContentType in Content.ts to avoid conflicts
9460
10048
  */
9461
- interface FilePersistentInstructionsStorageConfig {
9462
- /** Agent ID (used to create unique storage path) */
9463
- agentId: string;
9464
- /** Override the base directory (default: ~/.oneringai/agents) */
9465
- baseDirectory?: string;
9466
- /** Override the filename (default: custom_instructions.json) */
9467
- filename?: string;
9468
- }
10049
+ type TokenContentType = 'code' | 'prose' | 'mixed';
9469
10050
  /**
9470
- * File-based storage for persistent agent instructions
10051
+ * Abstract interface for token estimation
9471
10052
  */
9472
- declare class FilePersistentInstructionsStorage implements IPersistentInstructionsStorage {
9473
- private readonly directory;
9474
- private readonly filePath;
9475
- private readonly legacyFilePath;
9476
- private readonly agentId;
9477
- constructor(config: FilePersistentInstructionsStorageConfig);
9478
- /**
9479
- * Load instruction entries from file.
9480
- * Falls back to legacy .md file migration if JSON not found.
9481
- */
9482
- load(): Promise<InstructionEntry[] | null>;
9483
- /**
9484
- * Save instruction entries to file as JSON.
9485
- * Creates directory if it doesn't exist.
9486
- * Cleans up legacy .md file if present.
9487
- */
9488
- save(entries: InstructionEntry[]): Promise<void>;
9489
- /**
9490
- * Delete instructions file (and legacy .md if exists)
9491
- */
9492
- delete(): Promise<void>;
9493
- /**
9494
- * Check if instructions file exists (JSON or legacy .md)
9495
- */
9496
- exists(): Promise<boolean>;
9497
- /**
9498
- * Get the file path (for display/debugging)
9499
- */
9500
- getPath(): string;
10053
+ interface ITokenEstimator {
9501
10054
  /**
9502
- * 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)
9503
10062
  */
9504
- getAgentId(): string;
10063
+ estimateTokens(text: string, contentType?: TokenContentType): number;
9505
10064
  /**
9506
- * Ensure the directory exists
10065
+ * Estimate tokens for structured data
9507
10066
  */
9508
- private ensureDirectory;
10067
+ estimateDataTokens(data: unknown, contentType?: TokenContentType): number;
9509
10068
  /**
9510
- * 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'
9511
10073
  */
9512
- private removeLegacyFile;
9513
- }
9514
-
9515
- /**
9516
- * FileContextStorage - File-based storage for AgentContext session persistence
9517
- *
9518
- * Stores context sessions as JSON files on disk.
9519
- * Path: ~/.oneringai/agents/<agentId>/sessions/<sessionId>.json
9520
- * Windows: %APPDATA%/oneringai/agents/<agentId>/sessions/<sessionId>.json
9521
- *
9522
- * Features:
9523
- * - Cross-platform path handling
9524
- * - Safe session ID sanitization
9525
- * - Atomic file operations (write to temp, then rename)
9526
- * - Automatic directory creation
9527
- * - Index file for fast listing
9528
- */
9529
-
9530
- /**
9531
- * Configuration for FileContextStorage
9532
- */
9533
- interface FileContextStorageConfig {
9534
- /** Agent ID (used to create unique storage path) */
9535
- agentId: string;
9536
- /** Override the base directory (default: ~/.oneringai/agents) */
9537
- baseDirectory?: string;
9538
- /** Pretty-print JSON (default: true for debugging, false in production) */
9539
- prettyPrint?: boolean;
10074
+ estimateImageTokens?(width?: number, height?: number, detail?: string): number;
9540
10075
  }
9541
10076
  /**
9542
- * File-based storage for AgentContext session persistence
10077
+ * Abstract interface for compaction strategies
9543
10078
  */
9544
- declare class FileContextStorage implements IContextStorage {
9545
- private readonly agentId;
9546
- private readonly sessionsDirectory;
9547
- private readonly indexPath;
9548
- private readonly prettyPrint;
9549
- private index;
9550
- constructor(config: FileContextStorageConfig);
9551
- /**
9552
- * Save context state to a session file
9553
- */
9554
- save(sessionId: string, state: SerializedContextState, metadata?: ContextSessionMetadata): Promise<void>;
9555
- /**
9556
- * Load context state from a session file
9557
- */
9558
- 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;
9559
10084
  /**
9560
- * Delete a session
10085
+ * Check if this compactor can handle the component
9561
10086
  */
9562
- delete(sessionId: string): Promise<void>;
10087
+ canCompact(component: IContextComponent): boolean;
9563
10088
  /**
9564
- * Check if a session exists
10089
+ * Compact the component to target size
9565
10090
  */
9566
- exists(sessionId: string): Promise<boolean>;
10091
+ compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9567
10092
  /**
9568
- * List all sessions (summaries only)
10093
+ * Estimate savings from compaction
9569
10094
  */
9570
- 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;
9571
10103
  /**
9572
- * Update session metadata without loading full state
10104
+ * Decide if compaction is needed based on current budget
9573
10105
  */
9574
- updateMetadata(sessionId: string, metadata: Partial<ContextSessionMetadata>): Promise<void>;
10106
+ shouldCompact(budget: ContextBudget, config: ContextManagerConfig): boolean;
9575
10107
  /**
9576
- * Get the storage path (for display/debugging)
9577
- * @deprecated Use getLocation() instead
10108
+ * Execute compaction using available compactors
9578
10109
  */
9579
- getPath(): string;
10110
+ compact(components: IContextComponent[], budget: ContextBudget, compactors: IContextCompactor[], estimator: ITokenEstimator): Promise<{
10111
+ components: IContextComponent[];
10112
+ log: string[];
10113
+ tokensFreed: number;
10114
+ }>;
9580
10115
  /**
9581
- * 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)
9582
10118
  */
9583
- getLocation(): string;
10119
+ prepareComponents?(components: IContextComponent[]): Promise<IContextComponent[]>;
9584
10120
  /**
9585
- * Get the agent ID
10121
+ * Optional: Post-process after compaction
10122
+ * Use this for strategies that need cleanup or optimization
9586
10123
  */
9587
- getAgentId(): string;
10124
+ postProcess?(components: IContextComponent[], budget: ContextBudget): Promise<IContextComponent[]>;
9588
10125
  /**
9589
- * Rebuild the index by scanning all session files
9590
- * Useful for recovery or migration
10126
+ * Optional: Get strategy-specific metrics
9591
10127
  */
9592
- rebuildIndex(): Promise<void>;
9593
- private getFilePath;
9594
- private ensureDirectory;
9595
- private loadRaw;
9596
- private loadIndex;
9597
- private saveIndex;
9598
- private updateIndex;
9599
- private removeFromIndex;
9600
- private storedToIndexEntry;
10128
+ getMetrics?(): Record<string, unknown>;
9601
10129
  }
10130
+
9602
10131
  /**
9603
- * Create a FileContextStorage for the given agent
9604
- *
9605
- * @param agentId - Agent ID
9606
- * @param options - Optional configuration
9607
- * @returns FileContextStorage instance
9608
- *
9609
- * @example
9610
- * ```typescript
9611
- * const storage = createFileContextStorage('my-agent');
9612
- * const ctx = AgentContext.create({
9613
- * model: 'gpt-4',
9614
- * storage,
9615
- * });
9616
- *
9617
- * // Save session
9618
- * await ctx.save('session-001', { title: 'My Session' });
10132
+ * Truncate Compactor
9619
10133
  *
9620
- * // Load session
9621
- * await ctx.load('session-001');
9622
- * ```
10134
+ * Truncates content to target size by:
10135
+ * - For strings: Cut to character limit
10136
+ * - For arrays: Keep most recent items
9623
10137
  */
9624
- 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
+ }
9625
10150
 
9626
10151
  /**
9627
- * FileAgentDefinitionStorage - File-based storage for agent definitions
10152
+ * Summarize Compactor
9628
10153
  *
9629
- * Stores agent definitions as JSON files on disk.
9630
- * Path: ~/.oneringai/agents/<agentId>/definition.json
9631
- * 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.
9632
10156
  *
9633
- * Features:
9634
- * - Cross-platform path handling
9635
- * - Safe agent ID sanitization
9636
- * - Atomic file operations
9637
- * - Automatic directory creation
9638
- * - 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
9639
10160
  */
9640
10161
 
9641
10162
  /**
9642
- * Configuration for FileAgentDefinitionStorage
10163
+ * Configuration for the SummarizeCompactor
9643
10164
  */
9644
- interface FileAgentDefinitionStorageConfig {
9645
- /** Override the base directory (default: ~/.oneringai/agents) */
9646
- baseDirectory?: string;
9647
- /** Pretty-print JSON (default: true) */
9648
- 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;
9649
10178
  }
9650
10179
  /**
9651
- * 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.
9652
10184
  */
9653
- declare class FileAgentDefinitionStorage implements IAgentDefinitionStorage {
9654
- private readonly baseDirectory;
9655
- private readonly indexPath;
9656
- private readonly prettyPrint;
9657
- private index;
9658
- constructor(config?: FileAgentDefinitionStorageConfig);
9659
- /**
9660
- * Save an agent definition
9661
- */
9662
- 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);
9663
10191
  /**
9664
- * Load an agent definition
10192
+ * Check if this compactor can handle the component
9665
10193
  */
9666
- load(agentId: string): Promise<StoredAgentDefinition | null>;
10194
+ canCompact(component: IContextComponent): boolean;
9667
10195
  /**
9668
- * Delete an agent definition
10196
+ * Compact the component by summarizing its content
9669
10197
  */
9670
- delete(agentId: string): Promise<void>;
10198
+ compact(component: IContextComponent, targetTokens: number): Promise<IContextComponent>;
9671
10199
  /**
9672
- * Check if an agent definition exists
10200
+ * Estimate how many tokens could be saved by summarization
9673
10201
  */
9674
- exists(agentId: string): Promise<boolean>;
10202
+ estimateSavings(component: IContextComponent): number;
9675
10203
  /**
9676
- * List all agent definitions
10204
+ * Perform LLM-based summarization
9677
10205
  */
9678
- list(options?: AgentDefinitionListOptions): Promise<AgentDefinitionSummary[]>;
10206
+ private summarize;
9679
10207
  /**
9680
- * Update metadata without loading full definition
10208
+ * Fallback to simple truncation when LLM fails
9681
10209
  */
9682
- updateMetadata(agentId: string, metadata: Partial<AgentDefinitionMetadata>): Promise<void>;
10210
+ private truncateFallback;
9683
10211
  /**
9684
- * Get storage path
10212
+ * Detect content type from component metadata or name
9685
10213
  */
9686
- getPath(): string;
10214
+ private detectContentType;
9687
10215
  /**
9688
- * Rebuild the index by scanning all agent directories
10216
+ * Convert content to string for processing
9689
10217
  */
9690
- rebuildIndex(): Promise<void>;
9691
- private ensureDirectory;
9692
- private loadRaw;
9693
- private loadIndex;
9694
- private saveIndex;
9695
- private updateIndex;
9696
- private removeFromIndex;
9697
- private definitionToIndexEntry;
10218
+ private stringifyContent;
9698
10219
  }
10220
+
9699
10221
  /**
9700
- * 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
9701
10226
  */
9702
- 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
+ }
9703
10237
 
9704
10238
  /**
9705
- * FileMediaStorage - File-based media storage implementation
10239
+ * Approximate Token Estimator
9706
10240
  *
9707
- * Saves generated media to a configurable directory on the local filesystem.
9708
- * 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.
9709
10247
  */
9710
10248
 
9711
- interface FileMediaStorageConfig {
9712
- /** Directory to store media files. Defaults to `os.tmpdir()/oneringai-media/` */
9713
- outputDir?: string;
9714
- }
9715
- declare class FileMediaStorage implements IMediaStorage {
9716
- private outputDir;
9717
- private initialized;
9718
- constructor(config?: FileMediaStorageConfig);
9719
- save(data: Buffer, metadata: MediaStorageMetadata): Promise<MediaStorageResult>;
9720
- read(location: string): Promise<Buffer | null>;
9721
- delete(location: string): Promise<void>;
9722
- exists(location: string): Promise<boolean>;
9723
- list(options?: MediaStorageListOptions): Promise<MediaStorageEntry[]>;
9724
- getPath(): string;
9725
- private generateFilename;
9726
- 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;
9727
10272
  }
10273
+
9728
10274
  /**
9729
- * Factory function for creating FileMediaStorage instances
10275
+ * Token estimators
9730
10276
  */
9731
- declare function createFileMediaStorage(config?: FileMediaStorageConfig): FileMediaStorage;
9732
10277
 
9733
10278
  /**
9734
- * FileCustomToolStorage - File-based storage for custom tool definitions
9735
- *
9736
- * Stores custom tools as JSON files on disk with per-user isolation.
9737
- * 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
9738
10285
  *
9739
- * Features:
9740
- * - Per-user isolation (multi-tenant safe)
9741
- * - Cross-platform path handling
9742
- * - Safe name sanitization
9743
- * - Atomic file operations (write to .tmp then rename)
9744
- * - Per-user index file for fast listing
9745
- * - 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.
9746
10288
  */
9747
10289
 
9748
10290
  /**
9749
- * Configuration for FileCustomToolStorage
10291
+ * A single message in conversation history
9750
10292
  */
9751
- interface FileCustomToolStorageConfig {
9752
- /** Override the base directory (default: ~/.oneringai/users) */
9753
- baseDirectory?: string;
9754
- /** Pretty-print JSON (default: true) */
9755
- prettyPrint?: boolean;
10293
+ interface HistoryMessage {
10294
+ id: string;
10295
+ role: 'user' | 'assistant' | 'system';
10296
+ content: string;
10297
+ timestamp: number;
10298
+ metadata?: Record<string, unknown>;
9756
10299
  }
9757
10300
  /**
9758
- * File-based storage for custom tool definitions
9759
- *
9760
- * Single instance handles all users. UserId is passed to each method.
10301
+ * Events emitted by IHistoryManager implementations
9761
10302
  */
9762
- declare class FileCustomToolStorage implements ICustomToolStorage {
9763
- private readonly baseDirectory;
9764
- private readonly prettyPrint;
9765
- constructor(config?: FileCustomToolStorageConfig);
9766
- /**
9767
- * Get the directory path for a specific user's custom tools
9768
- */
9769
- 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 {
9770
10352
  /**
9771
- * Get the index file path for a specific user
10353
+ * Store a message
9772
10354
  */
9773
- private getUserIndexPath;
10355
+ addMessage(message: HistoryMessage): Promise<void>;
9774
10356
  /**
9775
- * Get the tool file path for a specific user
10357
+ * Get all messages
9776
10358
  */
9777
- private getToolPath;
10359
+ getMessages(): Promise<HistoryMessage[]>;
9778
10360
  /**
9779
- * Save a custom tool definition
10361
+ * Get recent N messages
9780
10362
  */
9781
- save(userId: string | undefined, definition: CustomToolDefinition): Promise<void>;
10363
+ getRecentMessages(count: number): Promise<HistoryMessage[]>;
9782
10364
  /**
9783
- * Load a custom tool definition by name
10365
+ * Remove a message by ID
9784
10366
  */
9785
- load(userId: string | undefined, name: string): Promise<CustomToolDefinition | null>;
10367
+ removeMessage(id: string): Promise<void>;
9786
10368
  /**
9787
- * Delete a custom tool definition
10369
+ * Remove messages older than timestamp
9788
10370
  */
9789
- delete(userId: string | undefined, name: string): Promise<void>;
10371
+ removeOlderThan(timestamp: number): Promise<number>;
9790
10372
  /**
9791
- * Check if a custom tool exists
10373
+ * Clear all messages
9792
10374
  */
9793
- exists(userId: string | undefined, name: string): Promise<boolean>;
10375
+ clear(): Promise<void>;
9794
10376
  /**
9795
- * List custom tools (summaries only)
10377
+ * Get message count
9796
10378
  */
9797
- list(userId: string | undefined, options?: CustomToolListOptions): Promise<CustomToolSummary[]>;
10379
+ getCount(): Promise<number>;
9798
10380
  /**
9799
- * Update metadata without loading full definition
10381
+ * Get serialized state for session persistence
9800
10382
  */
9801
- updateMetadata(userId: string | undefined, name: string, metadata: Record<string, unknown>): Promise<void>;
10383
+ getState(): Promise<SerializedHistoryState>;
9802
10384
  /**
9803
- * Get storage path for a specific user
10385
+ * Restore from serialized state
9804
10386
  */
9805
- getPath(userId: string | undefined): string;
9806
- private ensureDirectory;
9807
- private loadIndex;
9808
- private saveIndex;
9809
- private updateIndex;
9810
- private removeFromIndex;
9811
- private definitionToIndexEntry;
9812
- }
9813
- /**
9814
- * Create a FileCustomToolStorage with default configuration
9815
- */
9816
- declare function createFileCustomToolStorage(config?: FileCustomToolStorageConfig): FileCustomToolStorage;
9817
-
9818
- /**
9819
- * FileUserInfoStorage - File-based storage for user information
9820
- *
9821
- * Stores user information as a JSON file on disk.
9822
- * Path: ~/.oneringai/users/<userId>/user_info.json
9823
- * Windows: %APPDATA%/oneringai/users/<userId>/user_info.json
9824
- *
9825
- * Features:
9826
- * - Cross-platform path handling
9827
- * - Safe user ID sanitization
9828
- * - Atomic file operations
9829
- * - Automatic directory creation
9830
- * - Multi-user support (one storage instance for all users)
9831
- */
9832
-
9833
- /**
9834
- * Configuration for FileUserInfoStorage
9835
- */
9836
- interface FileUserInfoStorageConfig {
9837
- /** Override the base directory (default: ~/.oneringai/users) */
9838
- baseDirectory?: string;
9839
- /** Override the filename (default: user_info.json) */
9840
- filename?: string;
10387
+ restoreState(state: SerializedHistoryState): Promise<void>;
9841
10388
  }
9842
10389
  /**
9843
- * File-based storage for user information
9844
- *
9845
- * 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
9846
10392
  */
9847
- declare class FileUserInfoStorage implements IUserInfoStorage {
9848
- private readonly baseDirectory;
9849
- private readonly filename;
9850
- constructor(config?: FileUserInfoStorageConfig);
10393
+ interface IHistoryManager extends EventEmitter<HistoryManagerEvents> {
9851
10394
  /**
9852
- * Get the directory path for a specific user
10395
+ * Add a message to history
9853
10396
  */
9854
- private getUserDirectory;
10397
+ addMessage(role: 'user' | 'assistant' | 'system', content: string, metadata?: Record<string, unknown>): Promise<HistoryMessage>;
9855
10398
  /**
9856
- * Get the file path for a specific user
10399
+ * Get all messages (may include summaries as system messages)
9857
10400
  */
9858
- private getUserFilePath;
10401
+ getMessages(): Promise<HistoryMessage[]>;
9859
10402
  /**
9860
- * Load user info entries from file for a specific user
10403
+ * Get recent messages only
9861
10404
  */
9862
- load(userId: string | undefined): Promise<UserInfoEntry[] | null>;
10405
+ getRecentMessages(count?: number): Promise<HistoryMessage[]>;
9863
10406
  /**
9864
- * Save user info entries to file for a specific user
9865
- * Creates directory if it doesn't exist.
10407
+ * Get formatted history for LLM context
9866
10408
  */
9867
- save(userId: string | undefined, entries: UserInfoEntry[]): Promise<void>;
10409
+ formatForContext(options?: {
10410
+ maxTokens?: number;
10411
+ includeMetadata?: boolean;
10412
+ }): Promise<string>;
9868
10413
  /**
9869
- * Delete user info file for a specific user
10414
+ * Compact history (apply compaction strategy)
9870
10415
  */
9871
- delete(userId: string | undefined): Promise<void>;
10416
+ compact(): Promise<void>;
9872
10417
  /**
9873
- * Check if user info file exists for a specific user
10418
+ * Clear all history
9874
10419
  */
9875
- exists(userId: string | undefined): Promise<boolean>;
10420
+ clear(): Promise<void>;
9876
10421
  /**
9877
- * Get the file path for a specific user (for display/debugging)
10422
+ * Get message count
9878
10423
  */
9879
- getPath(userId: string | undefined): string;
10424
+ getMessageCount(): Promise<number>;
9880
10425
  /**
9881
- * Ensure the directory exists
10426
+ * Get state for session persistence
9882
10427
  */
9883
- 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;
9884
10437
  }
10438
+ /**
10439
+ * Default configuration
10440
+ */
10441
+ declare const DEFAULT_HISTORY_MANAGER_CONFIG: Required<IHistoryManagerConfig>;
9885
10442
 
9886
10443
  /**
9887
- * FileRoutineDefinitionStorage - File-based storage for routine definitions.
9888
- *
9889
- * Stores routines as JSON files on disk with per-user isolation.
9890
- * Path: ~/.oneringai/users/<userId>/routines/<sanitized-id>.json
10444
+ * InMemoryHistoryStorage - In-memory implementation of IHistoryStorage
9891
10445
  *
9892
- * Features:
9893
- * - Per-user isolation (multi-tenant safe)
9894
- * - Cross-platform path handling
9895
- * - Safe ID sanitization
9896
- * - Atomic file operations (write to .tmp then rename)
9897
- * - Per-user index file for fast listing/filtering
9898
- * - Index auto-rebuild if missing
10446
+ * Default storage backend for conversation history.
10447
+ * For production, users can implement IHistoryStorage with Redis, PostgreSQL, etc.
9899
10448
  */
9900
10449
 
9901
10450
  /**
9902
- * Configuration for FileRoutineDefinitionStorage
10451
+ * In-memory history storage implementation
9903
10452
  */
9904
- interface FileRoutineDefinitionStorageConfig {
9905
- /** Override the base directory (default: ~/.oneringai/users) */
9906
- baseDirectory?: string;
9907
- /** Pretty-print JSON (default: true) */
9908
- 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>;
9909
10465
  }
10466
+
9910
10467
  /**
9911
- * File-based storage for routine definitions.
10468
+ * Routine Control Flow map, fold, until handlers + template resolution
9912
10469
  *
9913
- * 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.
9914
10472
  */
9915
- declare class FileRoutineDefinitionStorage implements IRoutineDefinitionStorage {
9916
- private readonly baseDirectory;
9917
- private readonly prettyPrint;
9918
- constructor(config?: FileRoutineDefinitionStorageConfig);
9919
- private getUserDirectory;
9920
- private getIndexPath;
9921
- private getRoutinePath;
9922
- save(userId: string | undefined, definition: RoutineDefinition): Promise<void>;
9923
- load(userId: string | undefined, id: string): Promise<RoutineDefinition | null>;
9924
- delete(userId: string | undefined, id: string): Promise<void>;
9925
- exists(userId: string | undefined, id: string): Promise<boolean>;
9926
- list(userId: string | undefined, options?: {
9927
- tags?: string[];
9928
- search?: string;
9929
- limit?: number;
9930
- offset?: number;
9931
- }): Promise<RoutineDefinition[]>;
9932
- getPath(userId: string | undefined): string;
9933
- private ensureDirectory;
9934
- private loadIndex;
9935
- private saveIndex;
9936
- private updateIndex;
9937
- private removeFromIndex;
9938
- private definitionToIndexEntry;
9939
- /**
9940
- * Rebuild index by scanning directory for .json files (excluding _index.json).
9941
- * Returns empty index if directory doesn't exist.
9942
- */
9943
- 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;
9944
10499
  }
9945
10500
  /**
9946
- * 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.
9947
10509
  */
9948
- 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>;
9949
10526
 
9950
10527
  /**
9951
10528
  * Video Model Registry
@@ -10080,6 +10657,10 @@ declare class StreamState {
10080
10657
  currentIteration: number;
10081
10658
  usage: TokenUsage;
10082
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;
10083
10664
  startTime: Date;
10084
10665
  endTime?: Date;
10085
10666
  totalChunks: number;
@@ -10197,6 +10778,8 @@ declare class StreamState {
10197
10778
  reasoning_tokens: number;
10198
10779
  };
10199
10780
  };
10781
+ providerStatus: "completed" | "failed" | "incomplete";
10782
+ stopReason: string | undefined;
10200
10783
  };
10201
10784
  /**
10202
10785
  * Check if stream has any accumulated text
@@ -10232,6 +10815,8 @@ declare class StreamState {
10232
10815
  };
10233
10816
  };
10234
10817
  status: "in_progress" | "completed" | "failed" | "incomplete";
10818
+ providerStatus: "completed" | "failed" | "incomplete";
10819
+ stopReason: string | undefined;
10235
10820
  startTime: Date;
10236
10821
  endTime: Date | undefined;
10237
10822
  };
@@ -11786,6 +12371,8 @@ interface RateLimiterConfig {
11786
12371
  onLimit: 'wait' | 'throw';
11787
12372
  /** Max wait time in ms (for 'wait' mode, default: 60000) */
11788
12373
  maxWaitMs?: number;
12374
+ /** Max queued waiters (default: 500). Rejects new requests when exceeded. */
12375
+ maxQueueSize?: number;
11789
12376
  }
11790
12377
  /**
11791
12378
  * Default rate limiter configuration
@@ -13110,6 +13697,23 @@ interface GitHubPRCommentsResult {
13110
13697
  count?: number;
13111
13698
  error?: string;
13112
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
+ }
13113
13717
  /**
13114
13718
  * Result from create_pr tool
13115
13719
  */
@@ -13155,7 +13759,9 @@ declare function createSearchFilesTool(connector: Connector, userId?: string): T
13155
13759
  * Search for code content across a GitHub repository.
13156
13760
  * Mirrors the local `grep` tool for remote GitHub repos.
13157
13761
  *
13158
- * 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.
13159
13765
  *
13160
13766
  * Note: GitHub's code search API has a rate limit of 30 requests/minute.
13161
13767
  */
@@ -13168,6 +13774,8 @@ interface SearchCodeArgs {
13168
13774
  repository?: string;
13169
13775
  /** Search query (keyword or phrase) */
13170
13776
  query: string;
13777
+ /** Branch, tag, or commit SHA. Defaults to the repository's default branch. */
13778
+ ref?: string;
13171
13779
  /** Filter by programming language (e.g., "typescript", "python") */
13172
13780
  language?: string;
13173
13781
  /** Filter by file path (e.g., "src/", "lib/utils") */
@@ -13301,6 +13909,31 @@ interface CreatePRArgs {
13301
13909
  */
13302
13910
  declare function createCreatePRTool(connector: Connector, userId?: string): ToolFunction<CreatePRArgs, GitHubCreatePRResult>;
13303
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
+
13304
13937
  /**
13305
13938
  * Microsoft Graph Tools - Shared Types and Helpers
13306
13939
  *
@@ -14111,7 +14744,7 @@ declare const desktopTools: (ToolFunction<DesktopScreenshotArgs, DesktopScreensh
14111
14744
  * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
14112
14745
  *
14113
14746
  * Generated by: scripts/generate-tool-registry.ts
14114
- * Generated at: 2026-03-04T17:26:21.729Z
14747
+ * Generated at: 2026-03-12T18:47:09.908Z
14115
14748
  *
14116
14749
  * To regenerate: npm run generate:tools
14117
14750
  */
@@ -14551,8 +15184,10 @@ declare const index_FormatDetector: typeof FormatDetector;
14551
15184
  type index_GenericAPICallArgs = GenericAPICallArgs;
14552
15185
  type index_GenericAPICallResult = GenericAPICallResult;
14553
15186
  type index_GenericAPIToolOptions = GenericAPIToolOptions;
15187
+ type index_GitHubBranchEntry = GitHubBranchEntry;
14554
15188
  type index_GitHubCreatePRResult = GitHubCreatePRResult;
14555
15189
  type index_GitHubGetPRResult = GitHubGetPRResult;
15190
+ type index_GitHubListBranchesResult = GitHubListBranchesResult;
14556
15191
  type index_GitHubPRCommentEntry = GitHubPRCommentEntry;
14557
15192
  type index_GitHubPRCommentsResult = GitHubPRCommentsResult;
14558
15193
  type index_GitHubPRFilesResult = GitHubPRFilesResult;
@@ -14625,6 +15260,7 @@ declare const index_createGitHubReadFileTool: typeof createGitHubReadFileTool;
14625
15260
  declare const index_createGlobTool: typeof createGlobTool;
14626
15261
  declare const index_createGrepTool: typeof createGrepTool;
14627
15262
  declare const index_createImageGenerationTool: typeof createImageGenerationTool;
15263
+ declare const index_createListBranchesTool: typeof createListBranchesTool;
14628
15264
  declare const index_createListDirectoryTool: typeof createListDirectoryTool;
14629
15265
  declare const index_createMeetingTool: typeof createMeetingTool;
14630
15266
  declare const index_createMicrosoftListFilesTool: typeof createMicrosoftListFilesTool;
@@ -14710,7 +15346,7 @@ declare const index_validatePath: typeof validatePath;
14710
15346
  declare const index_webFetch: typeof webFetch;
14711
15347
  declare const index_writeFile: typeof writeFile;
14712
15348
  declare namespace index {
14713
- 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 };
14714
15350
  }
14715
15351
 
14716
15352
  /**
@@ -14837,4 +15473,4 @@ declare class EventEmitterTrigger implements IDisposable {
14837
15473
  get isDestroyed(): boolean;
14838
15474
  }
14839
15475
 
14840
- 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, AudioFormat, 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, 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, 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 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, 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, 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, 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 };