@everworker/oneringai 0.4.8 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +423 -43
  2. package/dist/{ImageModel-1uP-2vk7.d.ts → ImageModel-CV8OuP3Z.d.ts} +10 -4
  3. package/dist/{ImageModel-BDI37OED.d.cts → ImageModel-OjV5NvLY.d.cts} +10 -4
  4. package/dist/capabilities/agents/index.cjs +9 -0
  5. package/dist/capabilities/agents/index.cjs.map +1 -1
  6. package/dist/capabilities/agents/index.d.cts +1 -1
  7. package/dist/capabilities/agents/index.d.ts +1 -1
  8. package/dist/capabilities/agents/index.js +9 -0
  9. package/dist/capabilities/agents/index.js.map +1 -1
  10. package/dist/capabilities/images/index.cjs +262 -15
  11. package/dist/capabilities/images/index.cjs.map +1 -1
  12. package/dist/capabilities/images/index.d.cts +1 -1
  13. package/dist/capabilities/images/index.d.ts +1 -1
  14. package/dist/capabilities/images/index.js +262 -15
  15. package/dist/capabilities/images/index.js.map +1 -1
  16. package/dist/index-BlEwczd4.d.ts +320 -0
  17. package/dist/index-DrJYI_0l.d.cts +320 -0
  18. package/dist/{index-13HQuxEB.d.ts → index-hmTj59TM.d.ts} +352 -29
  19. package/dist/{index-Cbd5vY_8.d.cts → index-t4cRhBZW.d.cts} +352 -29
  20. package/dist/index.cjs +15543 -4232
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +3043 -586
  23. package/dist/index.d.ts +3043 -586
  24. package/dist/index.js +14567 -3281
  25. package/dist/index.js.map +1 -1
  26. package/dist/shared/index.cjs +596 -7
  27. package/dist/shared/index.cjs.map +1 -1
  28. package/dist/shared/index.d.cts +2 -284
  29. package/dist/shared/index.d.ts +2 -284
  30. package/dist/shared/index.js +596 -7
  31. package/dist/shared/index.js.map +1 -1
  32. package/package.json +1 -1
package/dist/index.d.cts CHANGED
@@ -1,15 +1,15 @@
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 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';
3
+ import { C as ContextFeatures, M as MemoryEntry, a as MemoryScope, T as ToolCall, I as IContextStorage, b as Tool, c as ToolFunction, d as IDisposable, e as ToolContext, f as ToolPermissionConfig$1, R as ResolvedContextFeatures, g as ContextBudget$1, h as IContextPluginNextGen, i as IStoreHandler, W as WorkingMemoryConfig, P as PriorityCalculator, j as MemoryPriority, S as StoreEntrySchema, k as StoreGetResult, l as StoreSetResult, m as StoreDeleteResult, n as StoreListResult, o as StoreActionResult, p as MemoryTier, q as ContextEvents, A as AgentContextNextGenConfig, r as AuthIdentity, s as ICompactionStrategy, B as BeforeCompactionCallback, t as InputItem, u as Content, v as PreparedContext, O as OutputItem, w as ToolResult, x as IHistoryJournal, y as ConsolidationResult, z as SerializedContextState, D as StoredContextSession, E as ITextProvider, F as ContextSessionMetadata, G as FunctionToolDefinition, L as LLMResponse, H as StreamEvent, J as HookConfig, K as HistoryMode, N as AsyncToolConfig, Q as AgentEvents, U as AgentResponse, V as PendingAsyncTool, X as ExecutionContext, Y as ExecutionMetrics, Z as AuditEntry, _ as HookName, $ as ITokenEstimator$1, a0 as ToolCategoryScope, a1 as CompactionContext, a2 as CompactionResult, a3 as PluginConfigs, a4 as AudioChunkReadyEvent, a5 as ContextStorageListOptions, a6 as ContextSessionSummary, a7 as HistoryEntry, a8 as HistoryReadOptions, a9 as StaleEntryInfo, aa as PriorityContext, ab as MemoryIndex, ac as TaskStatusForMemory, ad as WorkingMemoryAccess, ae as TokenUsage, af as StreamEventType, ag as TextGenerateOptions, ah as ModelCapabilities, ai as MessageRole } from './index-t4cRhBZW.cjs';
4
+ export { aj as AfterToolContext, ak as AgentEventName, al as AgenticLoopEventName, am as AgenticLoopEvents, an as ApprovalResult, ao as ApproveToolContext, ap as AudioChunkErrorEvent, aq as AudioStreamCompleteEvent, ar as BeforeToolContext, as as BuiltInTool, at as CONTEXT_SESSION_FORMAT_VERSION, au as CatalogRegistryEntry, av as CatalogToolEntry, aw as CompactionItem, ax as ConnectorCategoryInfo, ay as ContentType, az as DEFAULT_CONFIG, aA as DEFAULT_FEATURES, aB as DEFAULT_MEMORY_CONFIG, aC as ErrorEvent, aD as ExecutionConfig, aE as HistoryEntryType, aF as Hook, aG as HookManager, aH as IAsyncDisposable, aI as InputImageContent, aJ as InputTextContent, aK as IterationCompleteEvent, aL as JSONSchema, aM as KnownContextFeatures, aN as KnownPluginConfigs, aO as MEMORY_PRIORITY_VALUES, aP as MemoryEntryInput, aQ as MemoryIndexEntry, aR as Message, aS as ModifyingHook, aT as OutputTextContent, aU as OutputTextDeltaEvent, aV as OutputTextDoneEvent, aW as OversizedInputResult, aX as PendingAsyncToolStatus, aY as ReasoningDeltaEvent, aZ as ReasoningDoneEvent, a_ as ReasoningItem, a$ as ResponseCompleteEvent, b0 as ResponseCreatedEvent, b1 as ResponseInProgressEvent, b2 as SimpleScope, b3 as TaskAwareScope, b4 as ThinkingContent, b5 as ToolCallArgumentsDeltaEvent, b6 as ToolCallArgumentsDoneEvent, b7 as ToolCallStartEvent, b8 as ToolCallState, b9 as ToolCatalogRegistry, ba as ToolCategoryDefinition, bb as ToolExecutionContext, bc as ToolExecutionDoneEvent, bd as ToolExecutionStartEvent, be as ToolModification, bf as ToolResultContent, bg as ToolUseContent, bh as assertNotDestroyed, bi as calculateEntrySize, bj as defaultDescribeCall, bk as forPlan, bl as forTasks, bm as getToolCallDescription, bn as isAudioChunkError, bo as isAudioChunkReady, bp as isAudioStreamComplete, bq as isErrorEvent, br as isOutputTextDelta, bs as isReasoningDelta, bt as isReasoningDone, bu as isResponseComplete, bv as isSimpleScope, bw as isStoreHandler, bx as isStreamEvent, by as isTaskAwareScope, bz as isTerminalMemoryStatus, bA as isToolCallArgumentsDelta, bB as isToolCallArgumentsDone, bC as isToolCallStart, bD as scopeEquals, bE as scopeMatches } from './index-t4cRhBZW.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
- import { A as AudioFormat, I as IBaseModelDescription, V as VendorOptionSchema, a as IImageProvider } from './ImageModel-BDI37OED.cjs';
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';
8
+ import { A as AudioFormat, I as IBaseModelDescription, V as VendorOptionSchema, a as IImageProvider } from './ImageModel-OjV5NvLY.cjs';
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-OjV5NvLY.cjs';
10
+ import { I as IVoiceInfo, S as ServiceCategory } from './index-DrJYI_0l.cjs';
11
+ export { a as ILLMDescription, L as LLM_MODELS, M as MODEL_REGISTRY, b as SERVICE_DEFINITIONS, c as SERVICE_INFO, d as SERVICE_URL_PATTERNS, e as ServiceDefinition, f as ServiceInfo, g as ServiceType, h as Services, i as calculateCost, j as detectServiceFromURL, k as getActiveModels, l as getAllServiceIds, m as getModelInfo, n as getModelsByVendor, o as getServiceDefinition, p as getServiceInfo, q as getServicesByCategory, r as isKnownService } from './index-DrJYI_0l.cjs';
10
12
  import { EventEmitter as EventEmitter$1 } from 'events';
11
- import { ServiceCategory } from './shared/index.cjs';
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';
13
13
 
14
14
  /**
15
15
  * ScopedConnectorRegistry - Filtered view over the Connector registry
@@ -743,13 +743,13 @@ type PlanStatus = 'pending' | 'running' | 'suspended' | 'completed' | 'failed' |
743
743
  /**
744
744
  * Condition operators for conditional task execution
745
745
  */
746
- type ConditionOperator = 'exists' | 'not_exists' | 'equals' | 'contains' | 'truthy' | 'greater_than' | 'less_than';
746
+ type ConditionOperator$1 = 'exists' | 'not_exists' | 'equals' | 'contains' | 'truthy' | 'greater_than' | 'less_than';
747
747
  /**
748
748
  * Task condition - evaluated before execution
749
749
  */
750
750
  interface TaskCondition {
751
751
  memoryKey: string;
752
- operator: ConditionOperator;
752
+ operator: ConditionOperator$1;
753
753
  value?: unknown;
754
754
  onFalse: 'skip' | 'fail' | 'wait';
755
755
  }
@@ -1355,240 +1355,841 @@ interface IRoutineExecutionStorage {
1355
1355
  }
1356
1356
 
1357
1357
  /**
1358
- * StorageRegistry - Centralized storage backend registry
1359
- *
1360
- * Provides a single point of configuration for all storage backends
1361
- * used across the library. Subsystems resolve their storage at execution
1362
- * time (not construction time) via `resolve()`, which lazily creates
1363
- * and caches a default when nothing has been configured.
1358
+ * ICorrelationStorage - Maps external event IDs to suspended agent sessions
1364
1359
  *
1365
- * Storage types are split into two categories:
1366
- * - **Global singletons**: customTools, media, agentDefinitions, connectorConfig, oauthTokens
1367
- * - **Per-agent factories** (need agentId): sessions, persistentInstructions, workingMemory
1360
+ * When an agent suspends (via SuspendSignal), a correlation entry is saved
1361
+ * linking the external event identifier (e.g., email message ID, ticket ID)
1362
+ * to the agent session. When the external event arrives (webhook, reply, etc.),
1363
+ * the app resolves the correlation to find which session to resume.
1368
1364
  *
1369
- * For multi-user / multi-tenant environments, factories receive an optional
1370
- * `StorageContext` (opaque, like `ConnectorAccessContext`) so backends can
1371
- * partition data by userId, tenantId, or any custom field.
1365
+ * Default implementation: FileCorrelationStorage (~/.oneringai/correlations/)
1372
1366
  *
1373
1367
  * @example
1374
1368
  * ```typescript
1375
- * import { StorageRegistry } from '@everworker/oneringai';
1376
- *
1377
- * // Single-tenant (simple)
1378
- * StorageRegistry.configure({
1379
- * customTools: new MongoCustomToolStorage(),
1380
- * media: new S3MediaStorage(),
1381
- * sessions: (agentId) => new RedisContextStorage(agentId),
1369
+ * // Save correlation when agent suspends
1370
+ * await correlationStorage.save('email:msg_123', {
1371
+ * agentId: 'my-agent',
1372
+ * sessionId: 'session-456',
1373
+ * suspendedAt: new Date().toISOString(),
1374
+ * expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
1375
+ * resumeAs: 'user_message',
1382
1376
  * });
1383
1377
  *
1384
- * // Multi-tenant
1385
- * StorageRegistry.configure({
1386
- * sessions: (agentId, ctx) => new RedisContextStorage(agentId, ctx?.userId),
1387
- * customTools: new MongoCustomToolStorage(), // global singletons are unaffected
1388
- * });
1378
+ * // Resolve when external event arrives
1379
+ * const ref = await correlationStorage.resolve('email:msg_123');
1380
+ * if (ref) {
1381
+ * const agent = await Agent.hydrate(ref.sessionId, { agentId: ref.agentId });
1382
+ * await agent.run(userReply);
1383
+ * }
1389
1384
  * ```
1390
1385
  */
1391
-
1392
1386
  /**
1393
- * Opaque context passed to per-agent storage factories.
1394
- *
1395
- * The library imposes no structure — consumers define their own shape
1396
- * (e.g., `{ userId: 'alice', tenantId: 'acme' }`).
1397
- *
1398
- * Mirrors the `ConnectorAccessContext` pattern used by `Connector.scoped()`.
1387
+ * Reference to a suspended agent session
1399
1388
  */
1400
- type StorageContext = Record<string, unknown>;
1389
+ interface SessionRef {
1390
+ /** Agent identifier (used to load agent definition) */
1391
+ agentId: string;
1392
+ /** Session identifier (used to load conversation + plugin state) */
1393
+ sessionId: string;
1394
+ /** ISO timestamp when the session was suspended */
1395
+ suspendedAt: string;
1396
+ /** ISO timestamp when this correlation expires */
1397
+ expiresAt: string;
1398
+ /**
1399
+ * How the external response should be injected:
1400
+ * - `'user_message'`: as a new user message (default)
1401
+ * - `'tool_result'`: as a tool result
1402
+ */
1403
+ resumeAs: 'user_message' | 'tool_result';
1404
+ /** Application-specific metadata from the SuspendSignal */
1405
+ metadata?: Record<string, unknown>;
1406
+ }
1401
1407
  /**
1402
- * Storage configuration map.
1403
- *
1404
- * Global singletons are stored directly.
1405
- * Per-agent factories are functions that accept an agentId (and optional
1406
- * StorageContext for multi-tenant scenarios) and return a storage instance.
1408
+ * Options for listing correlations
1407
1409
  */
1408
- interface StorageConfig {
1409
- media: IMediaStorage;
1410
- agentDefinitions: IAgentDefinitionStorage;
1411
- connectorConfig: IConnectorConfigStorage;
1412
- oauthTokens: ITokenStorage;
1413
- customTools: (context?: StorageContext) => ICustomToolStorage;
1414
- sessions: (agentId: string, context?: StorageContext) => IContextStorage;
1415
- persistentInstructions: (agentId: string, context?: StorageContext) => IPersistentInstructionsStorage;
1416
- workingMemory: (context?: StorageContext) => IMemoryStorage;
1417
- userInfo: (context?: StorageContext) => IUserInfoStorage;
1418
- routineDefinitions: (context?: StorageContext) => IRoutineDefinitionStorage;
1419
- routineExecutions: (context?: StorageContext) => IRoutineExecutionStorage;
1410
+ interface CorrelationListOptions {
1411
+ /** Only return non-expired correlations */
1412
+ activeOnly?: boolean;
1413
+ /** Limit results */
1414
+ limit?: number;
1420
1415
  }
1421
- declare class StorageRegistry {
1422
- /** Internal storage map */
1423
- private static entries;
1424
- /** Default context passed to all factory calls (set via setContext) */
1425
- private static _context;
1426
- /**
1427
- * Configure multiple storage backends at once.
1428
- *
1429
- * @example
1430
- * ```typescript
1431
- * // Single-tenant
1432
- * StorageRegistry.configure({
1433
- * customTools: new MongoCustomToolStorage(),
1434
- * sessions: (agentId) => new RedisContextStorage(agentId),
1435
- * });
1436
- *
1437
- * // Multi-tenant
1438
- * StorageRegistry.configure({
1439
- * sessions: (agentId, ctx) => new TenantContextStorage(agentId, ctx?.tenantId),
1440
- * persistentInstructions: (agentId, ctx) => new TenantInstructionsStorage(agentId, ctx?.userId),
1441
- * });
1442
- * ```
1443
- */
1444
- static configure(config: Partial<StorageConfig>): void;
1416
+ /**
1417
+ * Summary of a stored correlation
1418
+ */
1419
+ interface CorrelationSummary {
1420
+ correlationId: string;
1421
+ agentId: string;
1422
+ sessionId: string;
1423
+ suspendedAt: string;
1424
+ expiresAt: string;
1425
+ isExpired: boolean;
1426
+ }
1427
+ /**
1428
+ * Storage interface for correlation mappings between external events and sessions
1429
+ */
1430
+ interface ICorrelationStorage {
1445
1431
  /**
1446
- * Set the default StorageContext.
1447
- *
1448
- * This context is automatically passed to all per-agent factory calls
1449
- * (sessions, persistentInstructions, workingMemory) when no explicit
1450
- * context is provided. Typically set once at app startup with global
1451
- * tenant/environment info, or per-request in multi-tenant servers.
1452
- *
1453
- * @example
1454
- * ```typescript
1455
- * // Single-tenant app — set once at init
1456
- * StorageRegistry.setContext({ tenantId: 'acme', environment: 'production' });
1457
- *
1458
- * // Multi-tenant server — set per-request
1459
- * app.use((req, res, next) => {
1460
- * StorageRegistry.setContext({ userId: req.user.id, tenantId: req.tenant.id });
1461
- * next();
1462
- * });
1463
- * ```
1432
+ * Save a correlation mapping.
1433
+ * If a correlation with the same ID already exists, it is overwritten.
1464
1434
  */
1465
- static setContext(context: StorageContext | undefined): void;
1435
+ save(correlationId: string, ref: SessionRef): Promise<void>;
1466
1436
  /**
1467
- * Get the current default StorageContext.
1437
+ * Resolve a correlation ID to a session reference.
1438
+ * Returns null if not found or expired.
1468
1439
  */
1469
- static getContext(): StorageContext | undefined;
1440
+ resolve(correlationId: string): Promise<SessionRef | null>;
1470
1441
  /**
1471
- * Set a single storage backend.
1442
+ * Delete a correlation mapping.
1472
1443
  */
1473
- static set<K extends keyof StorageConfig>(key: K, value: StorageConfig[K]): void;
1444
+ delete(correlationId: string): Promise<void>;
1474
1445
  /**
1475
- * Get a storage backend (or undefined if not configured).
1446
+ * Check if a correlation exists and is not expired.
1476
1447
  */
1477
- static get<K extends keyof StorageConfig>(key: K): StorageConfig[K] | undefined;
1448
+ exists(correlationId: string): Promise<boolean>;
1478
1449
  /**
1479
- * Resolve a storage backend, lazily creating and caching a default if needed.
1480
- *
1481
- * If a value has been configured via `set()` or `configure()`, returns that.
1482
- * Otherwise, calls `defaultFactory()`, caches the result, and returns it.
1450
+ * List all correlations for a given session.
1451
+ * Useful for cleanup when a session is resumed or deleted.
1483
1452
  */
1484
- static resolve<K extends keyof StorageConfig>(key: K, defaultFactory: () => StorageConfig[K]): StorageConfig[K];
1453
+ listBySession(sessionId: string): Promise<string[]>;
1485
1454
  /**
1486
- * Remove a single storage backend.
1455
+ * List all correlations for a given agent.
1487
1456
  */
1488
- static remove(key: keyof StorageConfig): boolean;
1457
+ listByAgent(agentId: string): Promise<CorrelationSummary[]>;
1489
1458
  /**
1490
- * Check if a storage backend has been configured.
1459
+ * Remove all expired correlations.
1460
+ * @returns Number of correlations pruned
1491
1461
  */
1492
- static has(key: keyof StorageConfig): boolean;
1462
+ pruneExpired(): Promise<number>;
1493
1463
  /**
1494
- * Clear all configured storage backends and context.
1495
- * Useful for testing.
1464
+ * Get the storage path (for debugging/logging).
1496
1465
  */
1497
- static reset(): void;
1466
+ getPath(): string;
1498
1467
  }
1499
1468
 
1500
1469
  /**
1501
- * Tool executor interface
1470
+ * Permission scope defines when approval is required for a tool
1471
+ *
1472
+ * - `once` - Require approval for each tool call (most restrictive)
1473
+ * - `session` - Approve once, valid for entire session
1474
+ * - `always` - Auto-approve (allowlisted, no prompts)
1475
+ * - `never` - Always blocked (blocklisted, tool cannot execute)
1502
1476
  */
1503
-
1504
- interface IToolExecutor {
1505
- /**
1506
- * Execute a tool function
1507
- * @param toolName - Name of the tool to execute
1508
- * @param args - Parsed arguments object
1509
- * @returns Tool execution result
1510
- */
1511
- execute(toolName: string, args: any): Promise<any>;
1477
+ type PermissionScope = 'once' | 'session' | 'always' | 'never';
1478
+ /**
1479
+ * Risk level classification for tools
1480
+ *
1481
+ * Used to help users understand the potential impact of approving a tool.
1482
+ * Can be used by UI to show different approval dialogs.
1483
+ */
1484
+ type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
1485
+ /**
1486
+ * Permission configuration for a tool
1487
+ *
1488
+ * Can be set on the tool definition or overridden at registration time.
1489
+ */
1490
+ interface ToolPermissionConfig {
1512
1491
  /**
1513
- * Check if tool is available
1492
+ * When approval is required.
1493
+ * @default 'once'
1514
1494
  */
1515
- hasToolFunction(toolName: string): boolean;
1495
+ scope?: PermissionScope;
1516
1496
  /**
1517
- * Get tool definition
1497
+ * Risk classification for the tool.
1498
+ * @default 'low'
1518
1499
  */
1519
- getToolDefinition(toolName: string): Tool | undefined;
1500
+ riskLevel?: RiskLevel;
1520
1501
  /**
1521
- * Register a new tool
1502
+ * Custom message shown in approval UI.
1503
+ * Should explain what the tool does and any potential risks.
1522
1504
  */
1523
- registerTool(tool: ToolFunction): void;
1505
+ approvalMessage?: string;
1524
1506
  /**
1525
- * Unregister a tool
1507
+ * Argument names that should be highlighted in approval UI.
1508
+ * E.g., ['path', 'url'] for file/network operations.
1526
1509
  */
1527
- unregisterTool(toolName: string): void;
1510
+ sensitiveArgs?: string[];
1528
1511
  /**
1529
- * List all registered tools
1512
+ * Optional expiration time for session approvals (milliseconds).
1513
+ * If set, session approvals expire after this duration.
1530
1514
  */
1531
- listTools(): string[];
1515
+ sessionTTLMs?: number;
1532
1516
  }
1533
-
1534
1517
  /**
1535
- * Interface for objects that manage resources and need explicit cleanup.
1536
- *
1537
- * Implementing classes should release all resources (event listeners, timers,
1538
- * connections, etc.) when destroy() is called. After destruction, the instance
1539
- * should not be used.
1518
+ * Context passed to approval callbacks/hooks
1540
1519
  */
1541
- interface IDisposable {
1542
- /**
1543
- * Releases all resources held by this instance.
1544
- *
1545
- * After calling destroy():
1546
- * - All event listeners should be removed
1547
- * - All timers/intervals should be cleared
1548
- * - All internal state should be cleaned up
1549
- * - The instance should not be reused
1550
- *
1551
- * Multiple calls to destroy() should be safe (idempotent).
1552
- */
1553
- destroy(): void;
1554
- /**
1555
- * Returns true if destroy() has been called.
1556
- * Methods should check this before performing operations.
1557
- */
1558
- readonly isDestroyed: boolean;
1520
+ interface PermissionCheckContext {
1521
+ /** The tool call being checked */
1522
+ toolCall: ToolCall;
1523
+ /** Parsed arguments (for display/inspection) */
1524
+ parsedArgs: Record<string, unknown>;
1525
+ /** The tool's permission config */
1526
+ config: ToolPermissionConfig;
1527
+ /** Current execution context ID */
1528
+ executionId: string;
1529
+ /** Current iteration (if in agentic loop) */
1530
+ iteration: number;
1531
+ /** Agent type (for context-specific handling) */
1532
+ agentType: 'agent' | 'task-agent' | 'universal-agent';
1533
+ /** Optional task name (for TaskAgent/UniversalAgent) */
1534
+ taskName?: string;
1559
1535
  }
1560
1536
  /**
1561
- * Async version of IDisposable for resources requiring async cleanup.
1537
+ * Entry in the approval cache representing an approved tool
1562
1538
  */
1563
- interface IAsyncDisposable {
1564
- /**
1565
- * Asynchronously releases all resources held by this instance.
1566
- */
1567
- destroy(): Promise<void>;
1568
- /**
1569
- * Returns true if destroy() has been called.
1570
- */
1571
- readonly isDestroyed: boolean;
1539
+ interface ApprovalCacheEntry {
1540
+ /** Name of the approved tool */
1541
+ toolName: string;
1542
+ /** The scope that was approved */
1543
+ scope: PermissionScope;
1544
+ /** When the approval was granted */
1545
+ approvedAt: Date;
1546
+ /** Optional identifier of who approved (for audit) */
1547
+ approvedBy?: string;
1548
+ /** When this approval expires (for session/TTL approvals) */
1549
+ expiresAt?: Date;
1550
+ /** Arguments hash if approval was for specific arguments */
1551
+ argsHash?: string;
1572
1552
  }
1573
1553
  /**
1574
- * Helper to check if an object is destroyed and throw if so.
1575
- * @param obj - The disposable object to check
1576
- * @param operation - Name of the operation being attempted
1554
+ * Serialized approval state for session persistence
1577
1555
  */
1578
- declare function assertNotDestroyed(obj: IDisposable | IAsyncDisposable, operation: string): void;
1579
-
1556
+ interface SerializedApprovalState {
1557
+ /** Version for future migrations */
1558
+ version: number;
1559
+ /** Map of tool name to approval entry */
1560
+ approvals: Record<string, SerializedApprovalEntry>;
1561
+ /** Tools that are always blocked (persisted blocklist) */
1562
+ blocklist: string[];
1563
+ /** Tools that are always allowed (persisted allowlist) */
1564
+ allowlist: string[];
1565
+ }
1580
1566
  /**
1581
- * Generic Circuit Breaker implementation
1582
- *
1583
- * Prevents cascading failures by failing fast when a system is down.
1584
- * Works for any async operation (LLM calls, tool execution, etc.)
1567
+ * Serialized version of ApprovalCacheEntry (with ISO date strings)
1585
1568
  */
1586
-
1569
+ interface SerializedApprovalEntry {
1570
+ toolName: string;
1571
+ scope: PermissionScope;
1572
+ approvedAt: string;
1573
+ approvedBy?: string;
1574
+ expiresAt?: string;
1575
+ argsHash?: string;
1576
+ }
1587
1577
  /**
1588
- * Circuit breaker states
1578
+ * Result of checking if a tool needs approval
1589
1579
  */
1590
- type CircuitState = 'closed' | 'open' | 'half-open';
1591
- /**
1580
+ interface PermissionCheckResult {
1581
+ /** Whether the tool can execute without prompting */
1582
+ allowed: boolean;
1583
+ /** Whether approval is needed (user should be prompted) */
1584
+ needsApproval: boolean;
1585
+ /** Whether the tool is blocked (cannot execute at all) */
1586
+ blocked: boolean;
1587
+ /** Reason for the decision */
1588
+ reason: string;
1589
+ /** The tool's permission config (for UI display) */
1590
+ config?: ToolPermissionConfig;
1591
+ }
1592
+ /**
1593
+ * Result from approval UI/hook
1594
+ */
1595
+ interface ApprovalDecision {
1596
+ /** Whether the tool was approved */
1597
+ approved: boolean;
1598
+ /** Scope of the approval (may differ from requested) */
1599
+ scope?: PermissionScope;
1600
+ /** Reason for denial (if not approved) */
1601
+ reason?: string;
1602
+ /** Optional identifier of who approved */
1603
+ approvedBy?: string;
1604
+ /** Whether to remember this decision for future calls */
1605
+ remember?: boolean;
1606
+ /**
1607
+ * If set, creates a persistent user permission rule from this decision.
1608
+ * The approval UI can pre-populate this based on the tool call context.
1609
+ */
1610
+ createRule?: {
1611
+ /** Rule description (shown in settings UI) */
1612
+ description?: string;
1613
+ /** Argument conditions for the rule */
1614
+ conditions?: ArgumentCondition[];
1615
+ /** ISO expiry timestamp (null = never) */
1616
+ expiresAt?: string | null;
1617
+ /** If true, rule cannot be overridden by more specific rules */
1618
+ unconditional?: boolean;
1619
+ };
1620
+ }
1621
+ /**
1622
+ * Permission configuration for any agent type.
1623
+ *
1624
+ * Used in:
1625
+ * - Agent.create({ permissions: {...} })
1626
+ * - TaskAgent.create({ permissions: {...} })
1627
+ * - UniversalAgent.create({ permissions: {...} })
1628
+ */
1629
+ interface AgentPermissionsConfig {
1630
+ /**
1631
+ * Default permission scope for tools without explicit config.
1632
+ * @default 'once'
1633
+ */
1634
+ defaultScope?: PermissionScope;
1635
+ /**
1636
+ * Default risk level for tools without explicit config.
1637
+ * @default 'low'
1638
+ */
1639
+ defaultRiskLevel?: RiskLevel;
1640
+ /**
1641
+ * Tools that are always allowed (never prompt).
1642
+ * Array of tool names.
1643
+ */
1644
+ allowlist?: string[];
1645
+ /**
1646
+ * Tools that are always blocked (cannot execute).
1647
+ * Array of tool names.
1648
+ */
1649
+ blocklist?: string[];
1650
+ /**
1651
+ * Per-tool permission overrides.
1652
+ * Keys are tool names, values are permission configs.
1653
+ */
1654
+ tools?: Record<string, ToolPermissionConfig>;
1655
+ /**
1656
+ * Callback invoked when a tool needs approval.
1657
+ * Receives full ApprovalRequestContext with tool info, risk level, args.
1658
+ * Return an ApprovalDecision to approve/deny.
1659
+ */
1660
+ onApprovalRequired?: (context: ApprovalRequestContext) => Promise<ApprovalDecision>;
1661
+ /**
1662
+ * Whether to inherit permission state from parent session.
1663
+ * Only applies when resuming from a session.
1664
+ * @default true
1665
+ */
1666
+ inheritFromSession?: boolean;
1667
+ }
1668
+ /**
1669
+ * Events emitted by ToolPermissionManager
1670
+ */
1671
+ type PermissionManagerEvent = 'tool:approved' | 'tool:denied' | 'tool:blocked' | 'tool:revoked' | 'allowlist:added' | 'allowlist:removed' | 'blocklist:added' | 'blocklist:removed' | 'session:cleared';
1672
+ /**
1673
+ * Current version of serialized approval state
1674
+ */
1675
+ declare const APPROVAL_STATE_VERSION = 1;
1676
+ /**
1677
+ * Default permission config applied when no config is specified
1678
+ */
1679
+ declare const DEFAULT_PERMISSION_CONFIG: Required<Pick<ToolPermissionConfig, 'scope' | 'riskLevel'>>;
1680
+ /**
1681
+ * Default allowlist - tools that never require user confirmation.
1682
+ *
1683
+ * These tools are safe to execute without user approval:
1684
+ * - Read-only operations (filesystem reads, searches)
1685
+ * - Internal state management (memory tools)
1686
+ * - Introspection tools (context stats)
1687
+ * - In-context memory tools
1688
+ * - Persistent instructions tools
1689
+ * - Meta-tools for agent coordination
1690
+ *
1691
+ * All other tools (write operations, shell commands, external requests)
1692
+ * require explicit user approval by default.
1693
+ */
1694
+ declare const DEFAULT_ALLOWLIST: readonly string[];
1695
+ /**
1696
+ * Type for default allowlisted tools
1697
+ */
1698
+ type DefaultAllowlistedTool = (typeof DEFAULT_ALLOWLIST)[number];
1699
+ /**
1700
+ * Policy verdict for a tool execution check.
1701
+ *
1702
+ * - `allow` - Explicitly permit execution (but later policies can still deny)
1703
+ * - `deny` - Block execution immediately (short-circuits)
1704
+ * - `abstain` - No opinion, defer to other policies
1705
+ */
1706
+ type PolicyVerdict = 'allow' | 'deny' | 'abstain';
1707
+ /**
1708
+ * Decision returned by a permission policy.
1709
+ */
1710
+ interface PolicyDecision {
1711
+ /** The verdict */
1712
+ verdict: PolicyVerdict;
1713
+ /** Human-readable reason for the decision */
1714
+ reason: string;
1715
+ /** Name of the policy that made this decision */
1716
+ policyName: string;
1717
+ /** Optional metadata for downstream processing */
1718
+ metadata?: {
1719
+ /** If true, this deny can be overridden by user approval */
1720
+ needsApproval?: boolean;
1721
+ /** Scoped cache key for argument-aware approval (e.g., "write_file:/workspace/**") */
1722
+ approvalKey?: string;
1723
+ /** How long this approval should be cached */
1724
+ approvalScope?: 'once' | 'session' | 'persistent';
1725
+ /** Additional policy-specific data */
1726
+ [key: string]: unknown;
1727
+ };
1728
+ }
1729
+ /**
1730
+ * Rich context passed to policies for evaluation.
1731
+ *
1732
+ * Contains tool identity, arguments, user identity, and tool registration metadata.
1733
+ */
1734
+ interface PolicyContext {
1735
+ /** Tool being invoked */
1736
+ toolName: string;
1737
+ /** Parsed arguments for the tool call */
1738
+ args: Record<string, unknown>;
1739
+ /** User identity (from ToolContext.userId) */
1740
+ userId?: string;
1741
+ /** User roles (from agent config userRoles) */
1742
+ roles?: string[];
1743
+ /** Agent ID */
1744
+ agentId?: string;
1745
+ /** Parent agent ID (for orchestrator workers) */
1746
+ parentAgentId?: string;
1747
+ /** Session ID */
1748
+ sessionId?: string;
1749
+ /** Execution iteration in agentic loop */
1750
+ iteration?: number;
1751
+ /** Execution ID for tracing */
1752
+ executionId?: string;
1753
+ /** Source identifier (built-in, connector:xxx, mcp, custom) */
1754
+ toolSource?: string;
1755
+ /** Category grouping (filesystem, web, shell, etc.) */
1756
+ toolCategory?: string;
1757
+ /** Registration namespace */
1758
+ toolNamespace?: string;
1759
+ /** Registration tags */
1760
+ toolTags?: string[];
1761
+ /**
1762
+ * Merged permission config from tool definition + registration override.
1763
+ * This is the tool author's declaration of risk/scope, possibly overridden
1764
+ * by the application developer at registration time.
1765
+ */
1766
+ toolPermissionConfig?: ToolPermissionConfig;
1767
+ }
1768
+ /**
1769
+ * A composable permission policy that evaluates tool execution requests.
1770
+ *
1771
+ * Policies return:
1772
+ * - `allow` to explicitly permit (does NOT short-circuit — later policies can still deny)
1773
+ * - `deny` to block immediately (short-circuits the chain)
1774
+ * - `abstain` to defer to other policies
1775
+ *
1776
+ * Tool authors declare defaults via `ToolFunction.permission`. App developers
1777
+ * can override at registration time. Policies read the merged result from
1778
+ * `PolicyContext.toolPermissionConfig`.
1779
+ */
1780
+ interface IPermissionPolicy {
1781
+ /** Unique policy name */
1782
+ readonly name: string;
1783
+ /** Priority — lower runs first. Default: 100 */
1784
+ readonly priority?: number;
1785
+ /** Human-readable description for display/audit */
1786
+ readonly description?: string;
1787
+ /**
1788
+ * Evaluate the policy for a given tool call.
1789
+ * May be sync or async.
1790
+ */
1791
+ evaluate(context: PolicyContext): Promise<PolicyDecision> | PolicyDecision;
1792
+ }
1793
+ /**
1794
+ * Configuration for the PolicyChain evaluator.
1795
+ */
1796
+ interface PolicyChainConfig {
1797
+ /**
1798
+ * What happens when all policies abstain.
1799
+ * @default 'deny'
1800
+ */
1801
+ defaultVerdict?: 'allow' | 'deny';
1802
+ }
1803
+ /**
1804
+ * Rich result from PermissionPolicyManager.check()
1805
+ */
1806
+ interface PolicyCheckResult {
1807
+ /** Whether the tool is allowed to execute */
1808
+ allowed: boolean;
1809
+ /** Whether the tool is hard-blocked (no approval possible) */
1810
+ blocked: boolean;
1811
+ /** Human-readable reason */
1812
+ reason: string;
1813
+ /** Policy that made the deciding verdict */
1814
+ policyName?: string;
1815
+ /** Whether user approval was requested (and possibly granted) */
1816
+ approvalRequired?: boolean;
1817
+ /** Argument-scoped approval key */
1818
+ approvalKey?: string;
1819
+ /** Approval scope that was applied */
1820
+ approvalScope?: 'once' | 'session' | 'persistent';
1821
+ /** ID of audit entry written (if audit storage configured) */
1822
+ auditEntryId?: string;
1823
+ /** Additional metadata from the deciding policy */
1824
+ metadata?: Record<string, unknown>;
1825
+ }
1826
+ /**
1827
+ * Context passed to the onApprovalRequired callback.
1828
+ * Extends PolicyContext with the deny decision and UI-relevant info.
1829
+ */
1830
+ interface ApprovalRequestContext extends PolicyContext {
1831
+ /** The deny decision that triggered this approval request */
1832
+ decision: PolicyDecision;
1833
+ /** Tool's risk level (from tool permission config or default) */
1834
+ riskLevel: RiskLevel;
1835
+ /** Custom approval message (from tool permission config) */
1836
+ approvalMessage?: string;
1837
+ /** Argument names to highlight as sensitive in approval UI */
1838
+ sensitiveArgs?: string[];
1839
+ /** Policy-provided approval scope key */
1840
+ approvalKey?: string;
1841
+ /** Suggested approval scope */
1842
+ approvalScope?: 'once' | 'session' | 'persistent';
1843
+ }
1844
+ /**
1845
+ * Extended agent permissions config with policy support.
1846
+ */
1847
+ interface AgentPolicyConfig extends AgentPermissionsConfig {
1848
+ /**
1849
+ * Custom policies (evaluated after legacy-derived policies).
1850
+ * Policies from tool self-declarations and registration overrides
1851
+ * are handled automatically via SessionApprovalPolicy reading
1852
+ * PolicyContext.toolPermissionConfig.
1853
+ */
1854
+ policies?: IPermissionPolicy[];
1855
+ /** Policy chain configuration */
1856
+ policyChain?: PolicyChainConfig;
1857
+ /** Per-user permission rules storage */
1858
+ userRulesStorage?: IUserPermissionRulesStorage;
1859
+ }
1860
+ /**
1861
+ * Serialized policy state for session persistence.
1862
+ */
1863
+ interface SerializedPolicyState {
1864
+ /** Version for future migrations */
1865
+ version: number;
1866
+ /** Approval cache entries keyed by approval key */
1867
+ approvals: Record<string, SerializedApprovalEntry>;
1868
+ /** Blocklisted tool names */
1869
+ blocklist: string[];
1870
+ /** Allowlisted tool names */
1871
+ allowlist: string[];
1872
+ }
1873
+ /**
1874
+ * Audit entry for permission decisions.
1875
+ */
1876
+ interface PermissionAuditEntry {
1877
+ /** Unique entry ID */
1878
+ id: string;
1879
+ /** ISO timestamp */
1880
+ timestamp: string;
1881
+ /** Tool that was checked */
1882
+ toolName: string;
1883
+ /** Policy evaluation result */
1884
+ decision: 'allow' | 'deny';
1885
+ /** Final execution outcome */
1886
+ finalOutcome: 'executed' | 'blocked' | 'approval_granted' | 'approval_denied';
1887
+ /** Human-readable reason */
1888
+ reason: string;
1889
+ /** Policy that made the deciding verdict */
1890
+ policyName?: string;
1891
+ /** User who triggered the check */
1892
+ userId?: string;
1893
+ /** Agent that triggered the check */
1894
+ agentId?: string;
1895
+ /** Redacted arguments (sensitive values replaced) */
1896
+ args?: Record<string, unknown>;
1897
+ /** Execution ID for correlation */
1898
+ executionId?: string;
1899
+ /** Whether approval was required */
1900
+ approvalRequired?: boolean;
1901
+ /** Approval key used */
1902
+ approvalKey?: string;
1903
+ /** Additional metadata */
1904
+ metadata?: Record<string, unknown>;
1905
+ }
1906
+ /**
1907
+ * Comparison operator for argument conditions.
1908
+ */
1909
+ type ConditionOperator = 'starts_with' | 'not_starts_with' | 'contains' | 'not_contains' | 'equals' | 'not_equals' | 'matches' | 'not_matches';
1910
+ /**
1911
+ * A condition that inspects a tool argument value.
1912
+ *
1913
+ * Multiple conditions on a rule use AND logic — all must match.
1914
+ *
1915
+ * Use `__toolCategory`, `__toolSource`, `__toolNamespace` as argName
1916
+ * to match against tool registration metadata instead of call arguments.
1917
+ */
1918
+ interface ArgumentCondition {
1919
+ /** Argument name to inspect (e.g., 'command', 'path', 'url') */
1920
+ argName: string;
1921
+ /** Comparison operator */
1922
+ operator: ConditionOperator;
1923
+ /** Value to compare against. For 'matches'/'not_matches', this is a regex string. */
1924
+ value: string;
1925
+ /** Case-insensitive comparison. @default true */
1926
+ ignoreCase?: boolean;
1927
+ }
1928
+ /**
1929
+ * A persistent, per-user permission rule.
1930
+ *
1931
+ * User rules have the HIGHEST priority — they override ALL built-in policies.
1932
+ * Resolution uses specificity (conditions > no conditions), not numeric priorities.
1933
+ */
1934
+ interface UserPermissionRule {
1935
+ /** Unique rule ID (UUID) */
1936
+ id: string;
1937
+ /** Tool name this rule applies to. '*' for all tools. */
1938
+ toolName: string;
1939
+ /** What to do when this rule matches */
1940
+ action: 'allow' | 'deny' | 'ask';
1941
+ /**
1942
+ * Argument conditions (optional).
1943
+ * ALL conditions must match (AND logic).
1944
+ * If empty/omitted, rule applies to ALL calls of this tool (blanket rule).
1945
+ */
1946
+ conditions?: ArgumentCondition[];
1947
+ /**
1948
+ * If true, this rule is absolute — more specific rules CANNOT override it.
1949
+ * "Allow bash unconditionally" means even a "bash + rm -rf → ask" rule is ignored.
1950
+ * @default false
1951
+ */
1952
+ unconditional?: boolean;
1953
+ /** Whether this rule is active */
1954
+ enabled: boolean;
1955
+ /** Human-readable description (shown in UI) */
1956
+ description?: string;
1957
+ /** How this rule was created */
1958
+ createdBy: 'user' | 'approval_dialog' | 'admin' | 'system';
1959
+ /** ISO timestamp */
1960
+ createdAt: string;
1961
+ /** ISO timestamp */
1962
+ updatedAt: string;
1963
+ /** Optional expiry (ISO timestamp). Null/undefined = never expires. */
1964
+ expiresAt?: string | null;
1965
+ }
1966
+ /**
1967
+ * Result from evaluating user rules against a tool call.
1968
+ */
1969
+ interface UserRuleEvalResult {
1970
+ /** What to do */
1971
+ action: 'allow' | 'deny' | 'ask';
1972
+ /** The rule that matched */
1973
+ rule: UserPermissionRule;
1974
+ /** Human-readable reason */
1975
+ reason: string;
1976
+ }
1977
+
1978
+ /**
1979
+ * IUserPermissionRulesStorage - Storage interface for per-user permission rules.
1980
+ *
1981
+ * userId is optional — defaults to 'default' in implementations.
1982
+ * Same Clean Architecture pattern as IUserInfoStorage, ICustomToolStorage, etc.
1983
+ *
1984
+ * Implementations:
1985
+ * - FileUserPermissionRulesStorage (reference, JSON)
1986
+ * - Custom: database, Redis, etc.
1987
+ */
1988
+
1989
+ interface IUserPermissionRulesStorage {
1990
+ /** Load all rules for a user. Returns null if no rules exist. */
1991
+ load(userId: string | undefined): Promise<UserPermissionRule[] | null>;
1992
+ /** Save all rules for a user (full replacement). */
1993
+ save(userId: string | undefined, rules: UserPermissionRule[]): Promise<void>;
1994
+ /** Delete all rules for a user. */
1995
+ delete(userId: string | undefined): Promise<void>;
1996
+ /** Check if rules exist for a user. */
1997
+ exists(userId: string | undefined): Promise<boolean>;
1998
+ /** Get storage path (for debugging/display). */
1999
+ getPath(userId: string | undefined): string;
2000
+ }
2001
+
2002
+ /**
2003
+ * StorageRegistry - Centralized storage backend registry
2004
+ *
2005
+ * Provides a single point of configuration for all storage backends
2006
+ * used across the library. Subsystems resolve their storage at execution
2007
+ * time (not construction time) via `resolve()`, which lazily creates
2008
+ * and caches a default when nothing has been configured.
2009
+ *
2010
+ * Storage types are split into two categories:
2011
+ * - **Global singletons**: customTools, media, agentDefinitions, connectorConfig, oauthTokens
2012
+ * - **Per-agent factories** (need agentId): sessions, persistentInstructions, workingMemory
2013
+ *
2014
+ * For multi-user / multi-tenant environments, factories receive an optional
2015
+ * `StorageContext` (opaque, like `ConnectorAccessContext`) so backends can
2016
+ * partition data by userId, tenantId, or any custom field.
2017
+ *
2018
+ * @example
2019
+ * ```typescript
2020
+ * import { StorageRegistry } from '@everworker/oneringai';
2021
+ *
2022
+ * // Single-tenant (simple)
2023
+ * StorageRegistry.configure({
2024
+ * customTools: new MongoCustomToolStorage(),
2025
+ * media: new S3MediaStorage(),
2026
+ * sessions: (agentId) => new RedisContextStorage(agentId),
2027
+ * });
2028
+ *
2029
+ * // Multi-tenant
2030
+ * StorageRegistry.configure({
2031
+ * sessions: (agentId, ctx) => new RedisContextStorage(agentId, ctx?.userId),
2032
+ * customTools: new MongoCustomToolStorage(), // global singletons are unaffected
2033
+ * });
2034
+ * ```
2035
+ */
2036
+
2037
+ /**
2038
+ * Opaque context passed to per-agent storage factories.
2039
+ *
2040
+ * The library imposes no structure — consumers define their own shape
2041
+ * (e.g., `{ userId: 'alice', tenantId: 'acme' }`).
2042
+ *
2043
+ * Mirrors the `ConnectorAccessContext` pattern used by `Connector.scoped()`.
2044
+ */
2045
+ type StorageContext = Record<string, unknown>;
2046
+ /**
2047
+ * Storage configuration map.
2048
+ *
2049
+ * Global singletons are stored directly.
2050
+ * Per-agent factories are functions that accept an agentId (and optional
2051
+ * StorageContext for multi-tenant scenarios) and return a storage instance.
2052
+ */
2053
+ interface StorageConfig {
2054
+ media: IMediaStorage;
2055
+ agentDefinitions: IAgentDefinitionStorage;
2056
+ connectorConfig: IConnectorConfigStorage;
2057
+ oauthTokens: ITokenStorage;
2058
+ customTools: (context?: StorageContext) => ICustomToolStorage;
2059
+ sessions: (agentId: string, context?: StorageContext) => IContextStorage;
2060
+ persistentInstructions: (agentId: string, context?: StorageContext) => IPersistentInstructionsStorage;
2061
+ workingMemory: (context?: StorageContext) => IMemoryStorage;
2062
+ userInfo: (context?: StorageContext) => IUserInfoStorage;
2063
+ routineDefinitions: (context?: StorageContext) => IRoutineDefinitionStorage;
2064
+ routineExecutions: (context?: StorageContext) => IRoutineExecutionStorage;
2065
+ correlations: ICorrelationStorage;
2066
+ permissionRules: IUserPermissionRulesStorage;
2067
+ }
2068
+ declare class StorageRegistry {
2069
+ /** Internal storage map */
2070
+ private static entries;
2071
+ /** Default context passed to all factory calls (set via setContext) */
2072
+ private static _context;
2073
+ /**
2074
+ * Configure multiple storage backends at once.
2075
+ *
2076
+ * @example
2077
+ * ```typescript
2078
+ * // Single-tenant
2079
+ * StorageRegistry.configure({
2080
+ * customTools: new MongoCustomToolStorage(),
2081
+ * sessions: (agentId) => new RedisContextStorage(agentId),
2082
+ * });
2083
+ *
2084
+ * // Multi-tenant
2085
+ * StorageRegistry.configure({
2086
+ * sessions: (agentId, ctx) => new TenantContextStorage(agentId, ctx?.tenantId),
2087
+ * persistentInstructions: (agentId, ctx) => new TenantInstructionsStorage(agentId, ctx?.userId),
2088
+ * });
2089
+ * ```
2090
+ */
2091
+ static configure(config: Partial<StorageConfig>): void;
2092
+ /**
2093
+ * Set the default StorageContext.
2094
+ *
2095
+ * This context is automatically passed to all per-agent factory calls
2096
+ * (sessions, persistentInstructions, workingMemory) when no explicit
2097
+ * context is provided. Typically set once at app startup with global
2098
+ * tenant/environment info, or per-request in multi-tenant servers.
2099
+ *
2100
+ * @example
2101
+ * ```typescript
2102
+ * // Single-tenant app — set once at init
2103
+ * StorageRegistry.setContext({ tenantId: 'acme', environment: 'production' });
2104
+ *
2105
+ * // Multi-tenant server — set per-request
2106
+ * app.use((req, res, next) => {
2107
+ * StorageRegistry.setContext({ userId: req.user.id, tenantId: req.tenant.id });
2108
+ * next();
2109
+ * });
2110
+ * ```
2111
+ */
2112
+ static setContext(context: StorageContext | undefined): void;
2113
+ /**
2114
+ * Get the current default StorageContext.
2115
+ */
2116
+ static getContext(): StorageContext | undefined;
2117
+ /**
2118
+ * Set a single storage backend.
2119
+ */
2120
+ static set<K extends keyof StorageConfig>(key: K, value: StorageConfig[K]): void;
2121
+ /**
2122
+ * Get a storage backend (or undefined if not configured).
2123
+ */
2124
+ static get<K extends keyof StorageConfig>(key: K): StorageConfig[K] | undefined;
2125
+ /**
2126
+ * Resolve a storage backend, lazily creating and caching a default if needed.
2127
+ *
2128
+ * If a value has been configured via `set()` or `configure()`, returns that.
2129
+ * Otherwise, calls `defaultFactory()`, caches the result, and returns it.
2130
+ */
2131
+ static resolve<K extends keyof StorageConfig>(key: K, defaultFactory: () => StorageConfig[K]): StorageConfig[K];
2132
+ /**
2133
+ * Remove a single storage backend.
2134
+ */
2135
+ static remove(key: keyof StorageConfig): boolean;
2136
+ /**
2137
+ * Check if a storage backend has been configured.
2138
+ */
2139
+ static has(key: keyof StorageConfig): boolean;
2140
+ /**
2141
+ * Clear all configured storage backends and context.
2142
+ * Useful for testing.
2143
+ */
2144
+ static reset(): void;
2145
+ }
2146
+
2147
+ /**
2148
+ * Tool executor interface
2149
+ */
2150
+
2151
+ interface IToolExecutor {
2152
+ /**
2153
+ * Execute a tool function
2154
+ * @param toolName - Name of the tool to execute
2155
+ * @param args - Parsed arguments object
2156
+ * @returns Tool execution result
2157
+ */
2158
+ execute(toolName: string, args: any): Promise<any>;
2159
+ /**
2160
+ * Check if tool is available
2161
+ */
2162
+ hasToolFunction(toolName: string): boolean;
2163
+ /**
2164
+ * Get tool definition
2165
+ */
2166
+ getToolDefinition(toolName: string): Tool | undefined;
2167
+ /**
2168
+ * Register a new tool
2169
+ */
2170
+ registerTool(tool: ToolFunction): void;
2171
+ /**
2172
+ * Unregister a tool
2173
+ */
2174
+ unregisterTool(toolName: string): void;
2175
+ /**
2176
+ * List all registered tools
2177
+ */
2178
+ listTools(): string[];
2179
+ }
2180
+
2181
+ /**
2182
+ * Generic Circuit Breaker implementation
2183
+ *
2184
+ * Prevents cascading failures by failing fast when a system is down.
2185
+ * Works for any async operation (LLM calls, tool execution, etc.)
2186
+ */
2187
+
2188
+ /**
2189
+ * Circuit breaker states
2190
+ */
2191
+ type CircuitState = 'closed' | 'open' | 'half-open';
2192
+ /**
1592
2193
  * Circuit breaker configuration
1593
2194
  */
1594
2195
  interface CircuitBreakerConfig {
@@ -1891,11 +2492,278 @@ interface IToolExecutionPipeline {
1891
2492
  */
1892
2493
  interface ToolExecutionPipelineOptions {
1893
2494
  /**
1894
- * Whether to generate unique execution IDs using crypto.randomUUID().
1895
- * If false, uses a simpler counter-based ID.
1896
- * Default: true (if crypto.randomUUID is available)
2495
+ * Whether to generate unique execution IDs using crypto.randomUUID().
2496
+ * If false, uses a simpler counter-based ID.
2497
+ * Default: true (if crypto.randomUUID is available)
2498
+ */
2499
+ useRandomUUID?: boolean;
2500
+ }
2501
+
2502
+ /**
2503
+ * UserPermissionRulesEngine - Evaluates per-user permission rules.
2504
+ *
2505
+ * User rules have the HIGHEST priority — they override ALL built-in policies.
2506
+ * Resolution uses specificity-based matching (not numeric priorities):
2507
+ *
2508
+ * 1. Unconditional rules are checked first — if matched, they are FINAL
2509
+ * (no more specific rule can override them)
2510
+ * 2. Conditional rules are evaluated by specificity — rules with MORE
2511
+ * matching conditions win over rules with fewer conditions
2512
+ * 3. Blanket rules (no conditions) are the fallback
2513
+ * 4. Ties: most recently updated rule wins
2514
+ *
2515
+ * This ensures:
2516
+ * - "bash → allow (unconditional)" means ALL bash allowed, period
2517
+ * - "bash → allow" + "bash + rm -rf → ask" means rm -rf asks, rest allowed
2518
+ * - No priority numbers needed — specificity is implicit
2519
+ */
2520
+
2521
+ declare class UserPermissionRulesEngine {
2522
+ private rules;
2523
+ private storage?;
2524
+ private _loaded;
2525
+ private _destroyed;
2526
+ /** Index: toolName → rules for O(1) lookup. Wildcard '*' rules stored under '*'. */
2527
+ private ruleIndex;
2528
+ constructor(storage?: IUserPermissionRulesStorage);
2529
+ /**
2530
+ * Evaluate user rules against a tool call.
2531
+ *
2532
+ * Returns the matching result, or null if no rule matches (fall through to chain).
2533
+ */
2534
+ evaluate(context: PolicyContext): UserRuleEvalResult | null;
2535
+ /**
2536
+ * Check if ALL conditions of a rule match the context (AND logic).
2537
+ */
2538
+ private matchesConditions;
2539
+ /**
2540
+ * Check if a single condition matches.
2541
+ */
2542
+ private matchesCondition;
2543
+ /**
2544
+ * Add a new rule. Auto-saves if storage is configured.
2545
+ */
2546
+ addRule(rule: UserPermissionRule, userId?: string): Promise<void>;
2547
+ /**
2548
+ * Update an existing rule. Auto-saves if storage is configured.
2549
+ */
2550
+ updateRule(ruleId: string, updates: Partial<UserPermissionRule>, userId?: string): Promise<boolean>;
2551
+ /**
2552
+ * Remove a rule by ID. Auto-saves if storage is configured.
2553
+ */
2554
+ removeRule(ruleId: string, userId?: string): Promise<boolean>;
2555
+ /**
2556
+ * Get a rule by ID.
2557
+ */
2558
+ getRule(ruleId: string): UserPermissionRule | null;
2559
+ /**
2560
+ * Get all rules.
2561
+ */
2562
+ getRules(): UserPermissionRule[];
2563
+ /**
2564
+ * Get all rules for a specific tool.
2565
+ */
2566
+ getRulesForTool(toolName: string): UserPermissionRule[];
2567
+ /**
2568
+ * Enable a rule.
2569
+ */
2570
+ enableRule(ruleId: string, userId?: string): Promise<boolean>;
2571
+ /**
2572
+ * Disable a rule.
2573
+ */
2574
+ disableRule(ruleId: string, userId?: string): Promise<boolean>;
2575
+ /**
2576
+ * Load rules from storage.
2577
+ */
2578
+ load(userId?: string): Promise<void>;
2579
+ /**
2580
+ * Save current rules to storage.
2581
+ */
2582
+ save(userId?: string): Promise<void>;
2583
+ /**
2584
+ * Whether rules have been loaded from storage.
2585
+ */
2586
+ get isLoaded(): boolean;
2587
+ /**
2588
+ * Set the storage backend.
2589
+ */
2590
+ setStorage(storage: IUserPermissionRulesStorage): void;
2591
+ get isDestroyed(): boolean;
2592
+ /**
2593
+ * Destroy the engine, clearing all rules and releasing storage reference.
2594
+ */
2595
+ destroy(): void;
2596
+ /**
2597
+ * Remove expired rules (lazy cleanup).
2598
+ * @returns true if any rules were removed (for save optimization).
2599
+ */
2600
+ private cleanExpired;
2601
+ /**
2602
+ * Rebuild the toolName → rules index for O(1) lookup.
2603
+ */
2604
+ private rebuildIndex;
2605
+ }
2606
+
2607
+ /**
2608
+ * PermissionPolicyManager - Top-level manager for the policy-based permission system.
2609
+ *
2610
+ * Evaluation order:
2611
+ * 1. USER RULES PRE-CHECK (highest priority, FINAL when matched)
2612
+ * 2. Parent delegation pre-check (orchestrator workers)
2613
+ * 3. Normal policy chain (built-in policies, tool self-declarations)
2614
+ *
2615
+ * Also provides:
2616
+ * - Approval flow (onApprovalRequired callback, can create persistent user rules)
2617
+ * - Argument-scoped approval cache (via SessionApprovalPolicy, in-memory only)
2618
+ * - Centralized audit via events (subscribe to 'permission:audit')
2619
+ * - Backward compatibility with legacy ToolPermissionManager
2620
+ */
2621
+
2622
+ interface PolicyManagerEvents {
2623
+ 'permission:allow': PermissionAuditEntry;
2624
+ 'permission:deny': PermissionAuditEntry;
2625
+ 'permission:approval_granted': PermissionAuditEntry;
2626
+ 'permission:approval_denied': PermissionAuditEntry;
2627
+ 'permission:audit': PermissionAuditEntry;
2628
+ 'policy:added': {
2629
+ name: string;
2630
+ };
2631
+ 'policy:removed': {
2632
+ name: string;
2633
+ };
2634
+ 'session:cleared': {};
2635
+ }
2636
+ interface PermissionPolicyManagerConfig {
2637
+ /** Policies to register at construction */
2638
+ policies?: IPermissionPolicy[];
2639
+ /** Policy chain configuration */
2640
+ chain?: PolicyChainConfig;
2641
+ /** Callback invoked when a tool needs user approval */
2642
+ onApprovalRequired?: (context: ApprovalRequestContext) => Promise<ApprovalDecision>;
2643
+ /** Per-user permission rules storage (optional) */
2644
+ userRulesStorage?: IUserPermissionRulesStorage;
2645
+ }
2646
+ declare class PermissionPolicyManager extends EventEmitter {
2647
+ private chain;
2648
+ private _isDestroyed;
2649
+ private parentEvaluator?;
2650
+ private onApprovalRequired?;
2651
+ private _userRulesEngine;
2652
+ private _allowlistPolicy?;
2653
+ private _blocklistPolicy?;
2654
+ private _sessionApprovalPolicy?;
2655
+ constructor(config?: PermissionPolicyManagerConfig);
2656
+ addPolicy(policy: IPermissionPolicy): void;
2657
+ removePolicy(name: string): boolean;
2658
+ hasPolicy(name: string): boolean;
2659
+ listPolicies(): IPermissionPolicy[];
2660
+ /**
2661
+ * Set a read-only parent evaluator for orchestrator delegation.
2662
+ *
2663
+ * - Parent deny is FINAL — worker cannot override
2664
+ * - Parent allow does NOT skip worker restrictions
2665
+ * - Parent approval callback is NOT invoked during delegation check
2666
+ */
2667
+ setParentEvaluator(parent: PermissionPolicyManager): void;
2668
+ /**
2669
+ * Get the parent evaluator (if set).
2670
+ */
2671
+ getParentEvaluator(): PermissionPolicyManager | undefined;
2672
+ /**
2673
+ * Check if a tool call is permitted.
2674
+ *
2675
+ * Evaluation order:
2676
+ * 1. USER RULES PRE-CHECK (highest priority, FINAL when matched)
2677
+ * 2. Parent delegation pre-check (orchestrator workers)
2678
+ * 3. Normal policy chain (built-in policies)
2679
+ * 4. Approval flow (if deny + needsApproval)
2680
+ * 5. Approval→rule creation (if user wants to remember)
2681
+ */
2682
+ check(context: PolicyContext): Promise<PolicyCheckResult>;
2683
+ /**
2684
+ * Handle the approval flow — called when a deny decision has needsApproval.
2685
+ * Also handles approval→rule creation when user wants to remember their decision.
2686
+ */
2687
+ private handleApprovalFlow;
2688
+ /**
2689
+ * Create a persistent user permission rule from an approval decision.
2690
+ */
2691
+ private createRuleFromApproval;
2692
+ /**
2693
+ * Evaluate chain only (no approval flow, no audit).
2694
+ * Used by parent evaluator during delegation.
2695
+ */
2696
+ private evaluateChainOnly;
2697
+ /**
2698
+ * Record an approval in the session cache.
2699
+ */
2700
+ approve(approvalKey: string, options?: {
2701
+ scope?: PermissionScope;
2702
+ approvedBy?: string;
2703
+ ttlMs?: number;
2704
+ }): void;
2705
+ /**
2706
+ * Revoke an approval from the session cache.
2707
+ */
2708
+ revoke(approvalKey: string): void;
2709
+ /**
2710
+ * Check if an approval key is cached.
2711
+ */
2712
+ isApproved(approvalKey: string): boolean;
2713
+ /**
2714
+ * Clear all session approvals.
2715
+ */
2716
+ clearSession(): void;
2717
+ allowlistAdd(toolName: string): void;
2718
+ allowlistRemove(toolName: string): void;
2719
+ blocklistAdd(toolName: string): void;
2720
+ blocklistRemove(toolName: string): void;
2721
+ /**
2722
+ * Centralized audit with redaction.
2723
+ */
2724
+ private audit;
2725
+ /**
2726
+ * Centralized argument redaction.
2727
+ *
2728
+ * Sources:
2729
+ * 1. Tool permission config sensitiveArgs
2730
+ * 2. Built-in sensitive key names (token, password, secret, etc.)
2731
+ * 3. Truncation for large values
2732
+ */
2733
+ private redactArgs;
2734
+ /**
2735
+ * Serialize approval state for session persistence.
2736
+ */
2737
+ getState(): SerializedPolicyState;
2738
+ /**
2739
+ * Load approval state from persistence.
2740
+ */
2741
+ loadState(state: SerializedPolicyState): void;
2742
+ /**
2743
+ * Create a PermissionPolicyManager from legacy AgentPermissionsConfig.
2744
+ *
2745
+ * Translates:
2746
+ * - blocklist → BlocklistPolicy
2747
+ * - allowlist → AllowlistPolicy (merged with DEFAULT_ALLOWLIST)
2748
+ * - defaultScope → SessionApprovalPolicy
2749
+ * - onApprovalRequired → passed through
2750
+ */
2751
+ static fromLegacyConfig(config: AgentPermissionsConfig): PermissionPolicyManager;
2752
+ /**
2753
+ * Create from the new AgentPolicyConfig (extends legacy config).
2754
+ */
2755
+ static fromConfig(config: AgentPolicyConfig): PermissionPolicyManager;
2756
+ /**
2757
+ * Access the user permission rules engine for CRUD operations.
2758
+ * Rules are per-user, persistent, and have the highest evaluation priority.
2759
+ */
2760
+ get userRules(): UserPermissionRulesEngine;
2761
+ get isDestroyed(): boolean;
2762
+ destroy(): void;
2763
+ /**
2764
+ * Track references to built-in policies for direct manipulation.
1897
2765
  */
1898
- useRandomUUID?: boolean;
2766
+ private trackBuiltinPolicy;
1899
2767
  }
1900
2768
 
1901
2769
  /**
@@ -2060,6 +2928,21 @@ declare class ToolManager extends EventEmitter implements IToolExecutor, IDispos
2060
2928
  * Get current tool context
2061
2929
  */
2062
2930
  getToolContext(): ToolContext | undefined;
2931
+ /**
2932
+ * Set permission policy manager for tool execution enforcement.
2933
+ *
2934
+ * Registers a PermissionEnforcementPlugin on the execution pipeline at priority 1.
2935
+ * This gates ALL tool execution through the policy chain — no bypasses.
2936
+ */
2937
+ setPermissionManager(manager: PermissionPolicyManager): void;
2938
+ /**
2939
+ * Get the permission policy manager (if enforcement is active).
2940
+ */
2941
+ getPermissionManager(): PermissionPolicyManager | undefined;
2942
+ /**
2943
+ * Check if permission enforcement is active on the execution pipeline.
2944
+ */
2945
+ hasPermissionEnforcement(): boolean;
2063
2946
  /**
2064
2947
  * Register a tool with optional configuration
2065
2948
  */
@@ -2311,7 +3194,7 @@ interface IContextSnapshot {
2311
3194
  /** Model name */
2312
3195
  model: string;
2313
3196
  /** Feature flags */
2314
- features: Required<ContextFeatures>;
3197
+ features: ResolvedContextFeatures;
2315
3198
  /** Token budget breakdown */
2316
3199
  budget: ContextBudget$1;
2317
3200
  /** Compaction strategy name */
@@ -2370,261 +3253,31 @@ interface IToolSnapshot {
2370
3253
  * Used by "View Full Context" UI panels.
2371
3254
  */
2372
3255
  interface IViewContextData {
2373
- /** Whether the data is available */
2374
- available: boolean;
2375
- /** Ordered list of context components */
2376
- components: IViewContextComponent[];
2377
- /** Total estimated tokens across all components */
2378
- totalTokens: number;
2379
- /** All components concatenated (for "Copy All" functionality) */
2380
- rawContext: string;
2381
- }
2382
- /**
2383
- * A single component of the prepared context.
2384
- */
2385
- interface IViewContextComponent {
2386
- /** Component name (e.g., 'System Message', 'User Message', 'Tool Call: search') */
2387
- name: string;
2388
- /** Human-readable text content */
2389
- content: string;
2390
- /** Estimated token count for this component */
2391
- tokenEstimate: number;
2392
- }
2393
- /**
2394
- * Convert a plugin name to a human-readable display name.
2395
- * e.g., 'working_memory' → 'Working Memory'
2396
- */
2397
- declare function formatPluginDisplayName(name: string): string;
2398
-
2399
- /**
2400
- * Tool Permission Types
2401
- *
2402
- * Defines permission scopes, risk levels, and approval state for tool execution control.
2403
- *
2404
- * Works with ALL agent types:
2405
- * - Agent (basic)
2406
- * - TaskAgent (task-based)
2407
- * - UniversalAgent (mode-fluid)
2408
- */
2409
-
2410
- /**
2411
- * Permission scope defines when approval is required for a tool
2412
- *
2413
- * - `once` - Require approval for each tool call (most restrictive)
2414
- * - `session` - Approve once, valid for entire session
2415
- * - `always` - Auto-approve (allowlisted, no prompts)
2416
- * - `never` - Always blocked (blocklisted, tool cannot execute)
2417
- */
2418
- type PermissionScope = 'once' | 'session' | 'always' | 'never';
2419
- /**
2420
- * Risk level classification for tools
2421
- *
2422
- * Used to help users understand the potential impact of approving a tool.
2423
- * Can be used by UI to show different approval dialogs.
2424
- */
2425
- type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
2426
- /**
2427
- * Permission configuration for a tool
2428
- *
2429
- * Can be set on the tool definition or overridden at registration time.
2430
- */
2431
- interface ToolPermissionConfig {
2432
- /**
2433
- * When approval is required.
2434
- * @default 'once'
2435
- */
2436
- scope?: PermissionScope;
2437
- /**
2438
- * Risk classification for the tool.
2439
- * @default 'low'
2440
- */
2441
- riskLevel?: RiskLevel;
2442
- /**
2443
- * Custom message shown in approval UI.
2444
- * Should explain what the tool does and any potential risks.
2445
- */
2446
- approvalMessage?: string;
2447
- /**
2448
- * Argument names that should be highlighted in approval UI.
2449
- * E.g., ['path', 'url'] for file/network operations.
2450
- */
2451
- sensitiveArgs?: string[];
2452
- /**
2453
- * Optional expiration time for session approvals (milliseconds).
2454
- * If set, session approvals expire after this duration.
2455
- */
2456
- sessionTTLMs?: number;
2457
- }
2458
- /**
2459
- * Context passed to approval callbacks/hooks
2460
- */
2461
- interface PermissionCheckContext {
2462
- /** The tool call being checked */
2463
- toolCall: ToolCall;
2464
- /** Parsed arguments (for display/inspection) */
2465
- parsedArgs: Record<string, unknown>;
2466
- /** The tool's permission config */
2467
- config: ToolPermissionConfig;
2468
- /** Current execution context ID */
2469
- executionId: string;
2470
- /** Current iteration (if in agentic loop) */
2471
- iteration: number;
2472
- /** Agent type (for context-specific handling) */
2473
- agentType: 'agent' | 'task-agent' | 'universal-agent';
2474
- /** Optional task name (for TaskAgent/UniversalAgent) */
2475
- taskName?: string;
2476
- }
2477
- /**
2478
- * Entry in the approval cache representing an approved tool
2479
- */
2480
- interface ApprovalCacheEntry {
2481
- /** Name of the approved tool */
2482
- toolName: string;
2483
- /** The scope that was approved */
2484
- scope: PermissionScope;
2485
- /** When the approval was granted */
2486
- approvedAt: Date;
2487
- /** Optional identifier of who approved (for audit) */
2488
- approvedBy?: string;
2489
- /** When this approval expires (for session/TTL approvals) */
2490
- expiresAt?: Date;
2491
- /** Arguments hash if approval was for specific arguments */
2492
- argsHash?: string;
2493
- }
2494
- /**
2495
- * Serialized approval state for session persistence
2496
- */
2497
- interface SerializedApprovalState {
2498
- /** Version for future migrations */
2499
- version: number;
2500
- /** Map of tool name to approval entry */
2501
- approvals: Record<string, SerializedApprovalEntry>;
2502
- /** Tools that are always blocked (persisted blocklist) */
2503
- blocklist: string[];
2504
- /** Tools that are always allowed (persisted allowlist) */
2505
- allowlist: string[];
2506
- }
2507
- /**
2508
- * Serialized version of ApprovalCacheEntry (with ISO date strings)
2509
- */
2510
- interface SerializedApprovalEntry {
2511
- toolName: string;
2512
- scope: PermissionScope;
2513
- approvedAt: string;
2514
- approvedBy?: string;
2515
- expiresAt?: string;
2516
- argsHash?: string;
2517
- }
2518
- /**
2519
- * Result of checking if a tool needs approval
2520
- */
2521
- interface PermissionCheckResult {
2522
- /** Whether the tool can execute without prompting */
2523
- allowed: boolean;
2524
- /** Whether approval is needed (user should be prompted) */
2525
- needsApproval: boolean;
2526
- /** Whether the tool is blocked (cannot execute at all) */
2527
- blocked: boolean;
2528
- /** Reason for the decision */
2529
- reason: string;
2530
- /** The tool's permission config (for UI display) */
2531
- config?: ToolPermissionConfig;
2532
- }
2533
- /**
2534
- * Result from approval UI/hook
2535
- */
2536
- interface ApprovalDecision {
2537
- /** Whether the tool was approved */
2538
- approved: boolean;
2539
- /** Scope of the approval (may differ from requested) */
2540
- scope?: PermissionScope;
2541
- /** Reason for denial (if not approved) */
2542
- reason?: string;
2543
- /** Optional identifier of who approved */
2544
- approvedBy?: string;
2545
- /** Whether to remember this decision for future calls */
2546
- remember?: boolean;
2547
- }
2548
- /**
2549
- * Permission configuration for any agent type.
2550
- *
2551
- * Used in:
2552
- * - Agent.create({ permissions: {...} })
2553
- * - TaskAgent.create({ permissions: {...} })
2554
- * - UniversalAgent.create({ permissions: {...} })
2555
- */
2556
- interface AgentPermissionsConfig {
2557
- /**
2558
- * Default permission scope for tools without explicit config.
2559
- * @default 'once'
2560
- */
2561
- defaultScope?: PermissionScope;
2562
- /**
2563
- * Default risk level for tools without explicit config.
2564
- * @default 'low'
2565
- */
2566
- defaultRiskLevel?: RiskLevel;
2567
- /**
2568
- * Tools that are always allowed (never prompt).
2569
- * Array of tool names.
2570
- */
2571
- allowlist?: string[];
2572
- /**
2573
- * Tools that are always blocked (cannot execute).
2574
- * Array of tool names.
2575
- */
2576
- blocklist?: string[];
2577
- /**
2578
- * Per-tool permission overrides.
2579
- * Keys are tool names, values are permission configs.
2580
- */
2581
- tools?: Record<string, ToolPermissionConfig>;
2582
- /**
2583
- * Callback invoked when a tool needs approval.
2584
- * Return an ApprovalDecision to approve/deny.
2585
- *
2586
- * If not provided, the existing `approve:tool` hook system is used.
2587
- * This callback runs BEFORE hooks, providing a first-pass check.
2588
- */
2589
- onApprovalRequired?: (context: PermissionCheckContext) => Promise<ApprovalDecision>;
2590
- /**
2591
- * Whether to inherit permission state from parent session.
2592
- * Only applies when resuming from a session.
2593
- * @default true
2594
- */
2595
- inheritFromSession?: boolean;
2596
- }
2597
- /**
2598
- * Events emitted by ToolPermissionManager
2599
- */
2600
- type PermissionManagerEvent = 'tool:approved' | 'tool:denied' | 'tool:blocked' | 'tool:revoked' | 'allowlist:added' | 'allowlist:removed' | 'blocklist:added' | 'blocklist:removed' | 'session:cleared';
2601
- /**
2602
- * Current version of serialized approval state
2603
- */
2604
- declare const APPROVAL_STATE_VERSION = 1;
2605
- /**
2606
- * Default permission config applied when no config is specified
2607
- */
2608
- declare const DEFAULT_PERMISSION_CONFIG: Required<Pick<ToolPermissionConfig, 'scope' | 'riskLevel'>>;
2609
- /**
2610
- * Default allowlist - tools that never require user confirmation.
2611
- *
2612
- * These tools are safe to execute without user approval:
2613
- * - Read-only operations (filesystem reads, searches)
2614
- * - Internal state management (memory tools)
2615
- * - Introspection tools (context stats)
2616
- * - In-context memory tools
2617
- * - Persistent instructions tools
2618
- * - Meta-tools for agent coordination
2619
- *
2620
- * All other tools (write operations, shell commands, external requests)
2621
- * require explicit user approval by default.
3256
+ /** Whether the data is available */
3257
+ available: boolean;
3258
+ /** Ordered list of context components */
3259
+ components: IViewContextComponent[];
3260
+ /** Total estimated tokens across all components */
3261
+ totalTokens: number;
3262
+ /** All components concatenated (for "Copy All" functionality) */
3263
+ rawContext: string;
3264
+ }
3265
+ /**
3266
+ * A single component of the prepared context.
2622
3267
  */
2623
- declare const DEFAULT_ALLOWLIST: readonly string[];
3268
+ interface IViewContextComponent {
3269
+ /** Component name (e.g., 'System Message', 'User Message', 'Tool Call: search') */
3270
+ name: string;
3271
+ /** Human-readable text content */
3272
+ content: string;
3273
+ /** Estimated token count for this component */
3274
+ tokenEstimate: number;
3275
+ }
2624
3276
  /**
2625
- * Type for default allowlisted tools
3277
+ * Convert a plugin name to a human-readable display name.
3278
+ * e.g., 'working_memory' → 'Working Memory'
2626
3279
  */
2627
- type DefaultAllowlistedTool = (typeof DEFAULT_ALLOWLIST)[number];
3280
+ declare function formatPluginDisplayName(name: string): string;
2628
3281
 
2629
3282
  /**
2630
3283
  * ToolPermissionManager - Core class for managing tool permissions
@@ -2799,6 +3452,10 @@ declare class ToolPermissionManager extends EventEmitter {
2799
3452
  * Reset to initial state
2800
3453
  */
2801
3454
  reset(): void;
3455
+ /**
3456
+ * Destroy the permission manager and release all resources
3457
+ */
3458
+ destroy(): void;
2802
3459
  }
2803
3460
 
2804
3461
  /**
@@ -2923,13 +3580,14 @@ declare const logger: FrameworkLogger;
2923
3580
  * WorkingMemoryPluginNextGen - Working memory plugin for NextGen context
2924
3581
  *
2925
3582
  * Provides external storage with an INDEX shown in context.
2926
- * LLM sees descriptions but must use memory_retrieve() to get full values.
3583
+ * LLM sees descriptions but must use store_get("memory", key) to get full values.
2927
3584
  *
2928
3585
  * Features:
2929
- * - Hierarchical tiers: raw summary findings
3586
+ * - Hierarchical tiers: raw -> summary -> findings
2930
3587
  * - Priority-based eviction
2931
3588
  * - Task-aware scoping (optional)
2932
3589
  * - Automatic tier-based priorities
3590
+ * - Implements IStoreHandler for unified store_* tools
2933
3591
  */
2934
3592
 
2935
3593
  interface SerializedWorkingMemoryState {
@@ -2953,7 +3611,7 @@ interface WorkingMemoryPluginConfig {
2953
3611
  /** Priority calculator (default: staticPriorityCalculator) */
2954
3612
  priorityCalculator?: PriorityCalculator;
2955
3613
  }
2956
- declare class WorkingMemoryPluginNextGen implements IContextPluginNextGen {
3614
+ declare class WorkingMemoryPluginNextGen implements IContextPluginNextGen, IStoreHandler {
2957
3615
  readonly name = "working_memory";
2958
3616
  private storage;
2959
3617
  private config;
@@ -2982,6 +3640,12 @@ declare class WorkingMemoryPluginNextGen implements IContextPluginNextGen {
2982
3640
  destroy(): void;
2983
3641
  getState(): SerializedWorkingMemoryState;
2984
3642
  restoreState(state: unknown): void;
3643
+ getStoreSchema(): StoreEntrySchema;
3644
+ storeGet(key?: string, _context?: ToolContext): Promise<StoreGetResult>;
3645
+ storeSet(key: string, data: Record<string, unknown>, _context?: ToolContext): Promise<StoreSetResult>;
3646
+ storeDelete(key: string, _context?: ToolContext): Promise<StoreDeleteResult>;
3647
+ storeList(filter?: Record<string, unknown>, _context?: ToolContext): Promise<StoreListResult>;
3648
+ storeAction(action: string, params?: Record<string, unknown>, _context?: ToolContext): Promise<StoreActionResult>;
2985
3649
  /**
2986
3650
  * Store a value in memory
2987
3651
  */
@@ -3044,11 +3708,6 @@ declare class WorkingMemoryPluginNextGen implements IContextPluginNextGen {
3044
3708
  private buildMemoryIndex;
3045
3709
  private ensureCapacity;
3046
3710
  private assertNotDestroyed;
3047
- private createMemoryStoreTool;
3048
- private createMemoryRetrieveTool;
3049
- private createMemoryDeleteTool;
3050
- private createMemoryQueryTool;
3051
- private createMemoryCleanupRawTool;
3052
3711
  }
3053
3712
 
3054
3713
  /**
@@ -3125,6 +3784,12 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3125
3784
  private _historyBuffer;
3126
3785
  /** Filter for journal entry types. When set, only matching types are journaled. */
3127
3786
  private readonly _journalFilter;
3787
+ /** Unified store tools manager — routes store_* tools to IStoreHandler plugins */
3788
+ private readonly _storeToolsManager;
3789
+ /** Whether the 5 generic store_* tools have been registered with ToolManager */
3790
+ private _storeToolsRegistered;
3791
+ /** Plugins that should NOT be destroyed when this context is destroyed (shared across agents) */
3792
+ private _skipDestroyPlugins;
3128
3793
  /**
3129
3794
  * Create a new AgentContextNextGen instance.
3130
3795
  */
@@ -3172,7 +3837,7 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3172
3837
  get systemPrompt(): string | undefined;
3173
3838
  set systemPrompt(value: string | undefined);
3174
3839
  /** Get feature configuration */
3175
- get features(): Required<ContextFeatures>;
3840
+ get features(): ResolvedContextFeatures;
3176
3841
  /** Check if destroyed */
3177
3842
  get isDestroyed(): boolean;
3178
3843
  /** Get current session ID */
@@ -3242,7 +3907,9 @@ declare class AgentContextNextGen extends EventEmitter<ContextEvents> {
3242
3907
  * Register a plugin.
3243
3908
  * Plugin's tools are automatically registered with ToolManager.
3244
3909
  */
3245
- registerPlugin(plugin: IContextPluginNextGen): void;
3910
+ registerPlugin(plugin: IContextPluginNextGen, options?: {
3911
+ skipDestroyOnContextDestroy?: boolean;
3912
+ }): void;
3246
3913
  /**
3247
3914
  * Get a plugin by name.
3248
3915
  */
@@ -3645,10 +4312,14 @@ interface BaseAgentConfig {
3645
4312
  toolManager?: ToolManager;
3646
4313
  /** Session configuration (uses AgentContext persistence) */
3647
4314
  session?: BaseSessionConfig;
3648
- /** Permission configuration */
3649
- permissions?: AgentPermissionsConfig;
4315
+ /** Permission configuration (legacy or policy-based) */
4316
+ permissions?: AgentPermissionsConfig | AgentPolicyConfig;
4317
+ /** User roles for permission policy evaluation */
4318
+ userRoles?: string[];
3650
4319
  /** Lifecycle hooks for customization */
3651
4320
  lifecycleHooks?: AgentLifecycleHooks;
4321
+ /** Parent agent's registryId (for tracking agent hierarchies) */
4322
+ parentAgentId?: string;
3652
4323
  /**
3653
4324
  * Hard timeout in milliseconds for any single tool execution.
3654
4325
  * Acts as a safety net at the ToolManager level: if a tool's own timeout
@@ -3706,12 +4377,15 @@ interface DirectCallOptions {
3706
4377
  * to define their own event interfaces (e.g., AgentEvents for Agent).
3707
4378
  */
3708
4379
  declare abstract class BaseAgent<TConfig extends BaseAgentConfig = BaseAgentConfig, TEvents extends Record<string, any> = BaseAgentEvents> extends EventEmitter<TEvents> {
4380
+ readonly registryId: string;
3709
4381
  readonly name: string;
3710
4382
  readonly connector: Connector;
3711
4383
  readonly model: string;
4384
+ readonly parentAgentId: string | undefined;
3712
4385
  protected _config: TConfig;
3713
4386
  protected _agentContext: AgentContextNextGen;
3714
4387
  protected _permissionManager: ToolPermissionManager;
4388
+ protected _policyManager: PermissionPolicyManager;
3715
4389
  protected _ownsContext: boolean;
3716
4390
  protected _isDestroyed: boolean;
3717
4391
  protected _cleanupCallbacks: Array<() => void | Promise<void>>;
@@ -3739,9 +4413,15 @@ declare abstract class BaseAgent<TConfig extends BaseAgentConfig = BaseAgentConf
3739
4413
  */
3740
4414
  protected initializeAgentContext(config: TConfig): AgentContextNextGen;
3741
4415
  /**
3742
- * Initialize permission manager
4416
+ * Initialize legacy permission manager (backward compat)
3743
4417
  */
3744
4418
  protected initializePermissionManager(config?: AgentPermissionsConfig, tools?: ToolFunction[]): ToolPermissionManager;
4419
+ /**
4420
+ * Initialize policy-based permission manager.
4421
+ * If config includes `policies` field, uses AgentPolicyConfig path.
4422
+ * Otherwise, translates legacy AgentPermissionsConfig to policies.
4423
+ */
4424
+ protected initializePolicyManager(config: TConfig): PermissionPolicyManager;
3745
4425
  /**
3746
4426
  * Initialize session management (call from subclass constructor after other setup)
3747
4427
  * Now uses AgentContext.save()/load() for persistence.
@@ -3827,8 +4507,15 @@ declare abstract class BaseAgent<TConfig extends BaseAgentConfig = BaseAgentConf
3827
4507
  set identities(value: AuthIdentity[] | undefined);
3828
4508
  /**
3829
4509
  * Permission management. Returns ToolPermissionManager for approval control.
4510
+ * @deprecated Use `policyManager` for the new policy-based system.
3830
4511
  */
3831
4512
  get permissions(): ToolPermissionManager;
4513
+ /**
4514
+ * Policy-based permission manager.
4515
+ * Provides composable policies, argument inspection, role-based access,
4516
+ * centralized audit, and enforcement at the ToolManager pipeline level.
4517
+ */
4518
+ get policyManager(): PermissionPolicyManager;
3832
4519
  /**
3833
4520
  * Add a tool to the agent.
3834
4521
  * Tools are registered with AgentContext (single source of truth).
@@ -4064,6 +4751,8 @@ interface AgentConfig$1 extends BaseAgentConfig {
4064
4751
  toolFailureMode?: 'fail' | 'continue';
4065
4752
  maxConsecutiveErrors?: number;
4066
4753
  };
4754
+ /** Configuration for async (non-blocking) tool execution */
4755
+ asyncTools?: AsyncToolConfig;
4067
4756
  /** Configuration for retrying empty/incomplete LLM responses */
4068
4757
  emptyResponseRetry?: {
4069
4758
  /** Enable retry for empty responses (default: true) */
@@ -4096,6 +4785,14 @@ declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDi
4096
4785
  private _pausePromise;
4097
4786
  private _resumeCallback;
4098
4787
  private _pauseResumeMutex;
4788
+ private _asyncToolTracker;
4789
+ private _asyncBatchTimer;
4790
+ private _asyncResultQueue;
4791
+ private _continuationInProgress;
4792
+ private _executionActive;
4793
+ private _pendingInjections;
4794
+ /** M3: Maximum injection queue size to prevent unbounded growth */
4795
+ private static readonly MAX_PENDING_INJECTIONS;
4099
4796
  /**
4100
4797
  * Create a new agent
4101
4798
  *
@@ -4140,6 +4837,40 @@ declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDi
4140
4837
  * @returns Agent instance, or null if not found
4141
4838
  */
4142
4839
  static fromStorage(agentId: string, storage?: IAgentDefinitionStorage, overrides?: Partial<AgentConfig$1>): Promise<Agent | null>;
4840
+ /**
4841
+ * Hydrate an agent from stored definition + saved session.
4842
+ *
4843
+ * Returns a fully reconstructed Agent with conversation history and plugin
4844
+ * states restored. The caller can customize the agent (add tools, hooks, etc.)
4845
+ * before calling `run()` to continue execution.
4846
+ *
4847
+ * This is the primary API for resuming suspended sessions.
4848
+ *
4849
+ * @param sessionId - Session ID to load
4850
+ * @param options - Agent ID and optional overrides
4851
+ * @returns Agent instance ready for customization and `run()`
4852
+ *
4853
+ * @example
4854
+ * ```typescript
4855
+ * // Reconstruct agent and load session
4856
+ * const agent = await Agent.hydrate('session-456', { agentId: 'my-agent' });
4857
+ *
4858
+ * // Customize (add hooks, tools, etc.)
4859
+ * agent.lifecycleHooks = { onError: myErrorHandler };
4860
+ * agent.tools.register(presentToUser(emailService));
4861
+ *
4862
+ * // Continue with user's reply
4863
+ * const result = await agent.run('Thanks, but also look at Q2 data');
4864
+ * ```
4865
+ */
4866
+ static hydrate(sessionId: string, options: {
4867
+ /** Agent ID to load definition for */
4868
+ agentId: string;
4869
+ /** Optional definition storage override */
4870
+ definitionStorage?: IAgentDefinitionStorage;
4871
+ /** Optional config overrides (e.g., connector, model) */
4872
+ overrides?: Partial<AgentConfig$1>;
4873
+ }): Promise<Agent>;
4143
4874
  private constructor();
4144
4875
  protected getAgentType(): 'agent' | 'task-agent' | 'universal-agent';
4145
4876
  /**
@@ -4179,6 +4910,12 @@ declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDi
4179
4910
  * Run the agent with input
4180
4911
  */
4181
4912
  run(input: string | InputItem[]): Promise<AgentResponse>;
4913
+ /**
4914
+ * Shared agentic loop used by both run() and continueWithAsyncResults().
4915
+ * Includes: iteration loop, empty response retry, context budget logging,
4916
+ * tool execution, max-iterations wrap-up, consolidation, pendingAsyncTools attachment.
4917
+ */
4918
+ private _runAgenticLoop;
4182
4919
  /**
4183
4920
  * Build tool calls array from accumulated map
4184
4921
  */
@@ -4208,7 +4945,10 @@ declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDi
4208
4945
  */
4209
4946
  private extractToolCalls;
4210
4947
  /**
4211
- * Execute tools with hooks
4948
+ * Execute tools with hooks.
4949
+ * Blocking tools (blocking !== false) are executed sequentially as before.
4950
+ * Async tools (blocking === false) return a placeholder result immediately
4951
+ * and execute in the background.
4212
4952
  */
4213
4953
  private executeToolsWithHooks;
4214
4954
  /**
@@ -4216,9 +4956,53 @@ declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDi
4216
4956
  */
4217
4957
  private executeToolWithHooks;
4218
4958
  /**
4219
- * Check tool permission before execution
4959
+ * Check tool permission before execution.
4960
+ *
4961
+ * When the PermissionEnforcementPlugin is active on the ToolManager pipeline,
4962
+ * this becomes a no-op — the pipeline handles enforcement for ALL paths.
4963
+ * This legacy path is kept for backward compatibility when pipeline enforcement
4964
+ * is not active.
4220
4965
  */
4221
4966
  private checkToolPermission;
4967
+ /**
4968
+ * Start async (non-blocking) tool execution.
4969
+ * Returns a placeholder ToolResult immediately.
4970
+ * The tool executes in the background and results are delivered
4971
+ * as a new user message when complete.
4972
+ */
4973
+ private _startAsyncExecution;
4974
+ /**
4975
+ * Called when an async tool completes (success or failure).
4976
+ * Queues the result and schedules batch delivery.
4977
+ */
4978
+ private _onAsyncComplete;
4979
+ /**
4980
+ * Flush queued async results by triggering a continuation.
4981
+ */
4982
+ private _flushAsyncResults;
4983
+ /**
4984
+ * Continue the agentic loop with async tool results.
4985
+ * Can be called automatically (autoContinue) or manually by the caller.
4986
+ *
4987
+ * Injects results as a user message and re-enters the agentic loop.
4988
+ */
4989
+ continueWithAsyncResults(results?: ToolResult[]): Promise<AgentResponse>;
4990
+ /**
4991
+ * Check if there are any pending async tools
4992
+ */
4993
+ hasPendingAsyncTools(): boolean;
4994
+ /**
4995
+ * Get info about pending async tools
4996
+ */
4997
+ getPendingAsyncTools(): PendingAsyncTool[];
4998
+ /**
4999
+ * Cancel a specific async tool by toolCallId
5000
+ */
5001
+ cancelAsyncTool(toolCallId: string): void;
5002
+ /**
5003
+ * Cancel all pending async tools
5004
+ */
5005
+ cancelAllAsyncTools(): void;
4222
5006
  /**
4223
5007
  * Pause execution
4224
5008
  */
@@ -4231,6 +5015,17 @@ declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDi
4231
5015
  * Cancel execution
4232
5016
  */
4233
5017
  cancel(reason?: string): void;
5018
+ /**
5019
+ * Inject a message into this agent's context, to be processed on the next
5020
+ * agentic loop iteration. Safe to call while the agent is running.
5021
+ *
5022
+ * Used by orchestrator tools (send_message) to communicate with workers
5023
+ * during or between turns.
5024
+ *
5025
+ * @param message - Text message to inject
5026
+ * @param role - Message role: 'user' (default) or 'developer'
5027
+ */
5028
+ inject(message: string, role?: 'user' | 'developer'): void;
4234
5029
  /**
4235
5030
  * Check if paused and wait
4236
5031
  */
@@ -4303,6 +5098,339 @@ declare class Agent extends BaseAgent<AgentConfig$1, AgentEvents> implements IDi
4303
5098
  destroy(): void;
4304
5099
  }
4305
5100
 
5101
+ /** Agent lifecycle status from the registry's perspective */
5102
+ type AgentStatus$1 = 'idle' | 'running' | 'paused' | 'cancelled' | 'destroyed';
5103
+ /** Lightweight snapshot of an agent's state */
5104
+ interface AgentInfo {
5105
+ /** Registry ID (UUID, unique) */
5106
+ id: string;
5107
+ /** Agent name (NOT unique — user-provided or auto-generated) */
5108
+ name: string;
5109
+ /** Model identifier */
5110
+ model: string;
5111
+ /** Connector name */
5112
+ connector: string;
5113
+ /** Current status */
5114
+ status: AgentStatus$1;
5115
+ /** When the agent was registered */
5116
+ createdAt: Date;
5117
+ /** Parent agent's registryId (undefined if root agent) */
5118
+ parentAgentId: string | undefined;
5119
+ /** IDs of child agents spawned by this agent (live lookup) */
5120
+ childAgentIds: string[];
5121
+ }
5122
+ /** Filter criteria for querying agents (all fields optional, AND logic) */
5123
+ interface AgentFilter {
5124
+ /** Exact match on agent name */
5125
+ name?: string;
5126
+ /** Exact match on model */
5127
+ model?: string;
5128
+ /** Exact match on connector name */
5129
+ connector?: string;
5130
+ /** Match any of these statuses */
5131
+ status?: AgentStatus$1 | AgentStatus$1[];
5132
+ /** Filter by parent agent ID */
5133
+ parentAgentId?: string;
5134
+ }
5135
+ /** Aggregate statistics across all tracked agents */
5136
+ interface AgentRegistryStats {
5137
+ total: number;
5138
+ byStatus: Record<AgentStatus$1, number>;
5139
+ byModel: Record<string, number>;
5140
+ byConnector: Record<string, number>;
5141
+ }
5142
+ /** Aggregate metrics across all tracked agents */
5143
+ interface AggregateMetrics {
5144
+ totalAgents: number;
5145
+ activeExecutions: number;
5146
+ totalTokens: number;
5147
+ totalToolCalls: number;
5148
+ totalErrors: number;
5149
+ byModel: Record<string, {
5150
+ agents: number;
5151
+ tokens: number;
5152
+ }>;
5153
+ byConnector: Record<string, {
5154
+ agents: number;
5155
+ tokens: number;
5156
+ }>;
5157
+ }
5158
+ /** Recursive tree node for parent/child visualization */
5159
+ interface AgentTreeNode {
5160
+ info: AgentInfo;
5161
+ children: AgentTreeNode[];
5162
+ }
5163
+ /** Deep inspection of a single agent */
5164
+ interface AgentInspection extends AgentInfo {
5165
+ /** Full context snapshot (plugins, tools, budget, features, systemPrompt) */
5166
+ context: IContextSnapshot;
5167
+ /** Full conversation history */
5168
+ conversation: ReadonlyArray<InputItem>;
5169
+ /** Pending input (about to go to LLM) */
5170
+ currentInput: ReadonlyArray<InputItem>;
5171
+ /** Current execution state */
5172
+ execution: {
5173
+ id: string | null;
5174
+ iteration: number;
5175
+ metrics: ExecutionMetrics | null;
5176
+ auditTrail: readonly AuditEntry[];
5177
+ };
5178
+ /** Tool manager statistics */
5179
+ toolStats: ToolManagerStats;
5180
+ /** Circuit breaker states per tool */
5181
+ circuitBreakers: Map<string, CircuitState>;
5182
+ /** Child agent info snapshots */
5183
+ children: AgentInfo[];
5184
+ }
5185
+ /** Events emitted by the registry */
5186
+ interface AgentRegistryEvents {
5187
+ 'agent:registered': {
5188
+ agent: IRegistrableAgent;
5189
+ info: AgentInfo;
5190
+ };
5191
+ 'agent:unregistered': {
5192
+ id: string;
5193
+ name: string;
5194
+ reason: 'destroyed' | 'manual';
5195
+ };
5196
+ 'agent:statusChanged': {
5197
+ id: string;
5198
+ name: string;
5199
+ previous: AgentStatus$1;
5200
+ current: AgentStatus$1;
5201
+ };
5202
+ 'registry:empty': Record<string, never>;
5203
+ }
5204
+ /** Callback type for agent event fan-in */
5205
+ type AgentEventListener = (agentId: string, agentName: string, event: string, data: unknown) => void;
5206
+ /**
5207
+ * Minimal interface an agent must satisfy to be tracked.
5208
+ * Agent already satisfies this — avoids circular import with Agent.ts.
5209
+ */
5210
+ interface IRegistrableAgent {
5211
+ readonly registryId: string;
5212
+ readonly name: string;
5213
+ readonly model: string;
5214
+ readonly connector: {
5215
+ name: string;
5216
+ };
5217
+ readonly parentAgentId: string | undefined;
5218
+ readonly isDestroyed: boolean;
5219
+ isRunning(): boolean;
5220
+ isPaused(): boolean;
5221
+ isCancelled(): boolean;
5222
+ getMetrics(): ExecutionMetrics | null;
5223
+ getExecutionContext(): ExecutionContext | null;
5224
+ getAuditTrail(): readonly AuditEntry[];
5225
+ getSnapshot(): Promise<IContextSnapshot>;
5226
+ readonly context: {
5227
+ tools: {
5228
+ getStats(): ToolManagerStats;
5229
+ getCircuitBreakerStates(): Map<string, CircuitState>;
5230
+ };
5231
+ getConversation(): ReadonlyArray<InputItem>;
5232
+ getCurrentInput(): ReadonlyArray<InputItem>;
5233
+ };
5234
+ destroy(): void;
5235
+ pause?(): void;
5236
+ resume?(): void;
5237
+ cancel?(reason?: string): void;
5238
+ inject?(message: string, role?: 'user' | 'developer'): void;
5239
+ on(event: string, listener: (...args: unknown[]) => void): this;
5240
+ off(event: string, listener: (...args: unknown[]) => void): this;
5241
+ eventNames(): (string | symbol)[];
5242
+ }
5243
+ declare class AgentRegistry {
5244
+ private static agents;
5245
+ private static childIndex;
5246
+ private static emitter;
5247
+ private static fanInListeners;
5248
+ /** Per-agent fan-in cleanup functions (only populated when fanInListeners.size > 0) */
5249
+ private static fanInCleanups;
5250
+ /**
5251
+ * Register an agent. Called automatically by Agent constructor.
5252
+ * @internal
5253
+ */
5254
+ static register(agent: IRegistrableAgent): void;
5255
+ /**
5256
+ * Unregister an agent. Called automatically by Agent.destroy().
5257
+ * @internal
5258
+ */
5259
+ static unregister(id: string, reason?: 'destroyed' | 'manual'): void;
5260
+ /** Get agent by registry ID (unique) */
5261
+ static get(id: string): IRegistrableAgent | undefined;
5262
+ /** Get all agents with a given name (names are NOT unique) */
5263
+ static getByName(name: string): IRegistrableAgent[];
5264
+ /** Check if an agent exists in the registry */
5265
+ static has(id: string): boolean;
5266
+ /** List all tracked registry IDs */
5267
+ static list(): string[];
5268
+ /** Return agents matching all provided filter criteria */
5269
+ static filter(filter: AgentFilter): IRegistrableAgent[];
5270
+ /** Number of currently tracked agents */
5271
+ static get count(): number;
5272
+ /** Lightweight info for all agents */
5273
+ static listInfo(): AgentInfo[];
5274
+ /** Lightweight info for agents matching filter */
5275
+ static filterInfo(filter: AgentFilter): AgentInfo[];
5276
+ /** Deep inspection of a single agent */
5277
+ static inspect(id: string): Promise<AgentInspection | null>;
5278
+ /** Deep inspection of all agents */
5279
+ static inspectAll(): Promise<AgentInspection[]>;
5280
+ /** Deep inspection of agents matching filter */
5281
+ static inspectMatching(filter: AgentFilter): Promise<AgentInspection[]>;
5282
+ /** Aggregate counts by status/model/connector */
5283
+ static getStats(): AgentRegistryStats;
5284
+ /** Aggregate metrics across all agents (tokens, tool calls, errors) */
5285
+ static getAggregateMetrics(): AggregateMetrics;
5286
+ /** Get child agents of a parent */
5287
+ static getChildren(parentId: string): IRegistrableAgent[];
5288
+ /** Get parent agent of a child */
5289
+ static getParent(childId: string): IRegistrableAgent | undefined;
5290
+ /** Get recursive tree starting from a root agent */
5291
+ static getTree(rootId: string): AgentTreeNode | null;
5292
+ /** Subscribe to registry lifecycle events */
5293
+ static on<K extends keyof AgentRegistryEvents>(event: K, listener: (data: AgentRegistryEvents[K]) => void): void;
5294
+ /** Unsubscribe from registry lifecycle events */
5295
+ static off<K extends keyof AgentRegistryEvents>(event: K, listener: (data: AgentRegistryEvents[K]) => void): void;
5296
+ /** Subscribe once to a registry lifecycle event */
5297
+ static once<K extends keyof AgentRegistryEvents>(event: K, listener: (data: AgentRegistryEvents[K]) => void): void;
5298
+ /** Fan-in: receive ALL events from ALL agents through one listener */
5299
+ static onAgentEvent(listener: AgentEventListener): void;
5300
+ /** Remove a fan-in listener */
5301
+ static offAgentEvent(listener: AgentEventListener): void;
5302
+ /** Pause a specific agent. Returns true if found and paused. */
5303
+ static pauseAgent(id: string): boolean;
5304
+ /** Resume a specific agent. Returns true if found and resumed. */
5305
+ static resumeAgent(id: string): boolean;
5306
+ /** Cancel a specific agent. Returns true if found and cancelled. */
5307
+ static cancelAgent(id: string, reason?: string): boolean;
5308
+ /** Destroy a specific agent. Returns true if found and destroyed. */
5309
+ static destroyAgent(id: string): boolean;
5310
+ /** Pause all agents matching filter. Returns count paused. */
5311
+ static pauseMatching(filter: AgentFilter): number;
5312
+ /** Cancel all agents matching filter. Returns count cancelled. */
5313
+ static cancelMatching(filter: AgentFilter, reason?: string): number;
5314
+ /** Destroy all agents matching filter. Returns count destroyed. */
5315
+ static destroyMatching(filter: AgentFilter): number;
5316
+ /** Pause all agents. Returns count paused. */
5317
+ static pauseAll(): number;
5318
+ /** Cancel all agents. Returns count cancelled. */
5319
+ static cancelAll(reason?: string): number;
5320
+ /** Destroy ALL tracked agents. Returns count destroyed. */
5321
+ static destroyAll(): number;
5322
+ /** Clear registry without destroying agents (for testing) */
5323
+ static clear(): void;
5324
+ /** Known agent events for fan-in forwarding */
5325
+ private static readonly KNOWN_EVENTS;
5326
+ /**
5327
+ * Wire status tracking listeners on an agent (always done on register).
5328
+ * Returns a cleanup function that removes the listeners.
5329
+ */
5330
+ private static wireStatusTracking;
5331
+ /**
5332
+ * Wire fan-in event forwarding on a single agent.
5333
+ * Only called when fanInListeners.size > 0 (lazy wiring).
5334
+ * Stores cleanup in fanInCleanups map.
5335
+ */
5336
+ private static wireFanInForAgent;
5337
+ /** Enrich AgentInfo with live childAgentIds from the index */
5338
+ private static enrichInfo;
5339
+ /** Build a deep AgentInspection from a registry entry */
5340
+ private static buildInspection;
5341
+ /** Build recursive tree from an entry (with cycle protection) */
5342
+ private static buildTree;
5343
+ /** Check if an AgentInfo matches a filter (AND logic) */
5344
+ private static matchesFilter;
5345
+ /** Bulk control helper — applies action to all matching agents */
5346
+ private static bulkControl;
5347
+ }
5348
+
5349
+ /**
5350
+ * SuspendSignal - Signal returned by tools to suspend the agent loop
5351
+ *
5352
+ * When a tool returns a SuspendSignal, the agent loop:
5353
+ * 1. Adds the `result` field as the normal tool result (visible to LLM)
5354
+ * 2. Does one final LLM call without tools for a graceful wrap-up message
5355
+ * 3. Saves the session and correlation mapping
5356
+ * 4. Returns an AgentResponse with status: 'suspended'
5357
+ *
5358
+ * Later, `Agent.hydrate()` reconstructs the agent from stored definition +
5359
+ * session, and the caller runs `agent.run(userReply)` to continue.
5360
+ *
5361
+ * @example
5362
+ * ```typescript
5363
+ * import { SuspendSignal } from '@everworker/oneringai';
5364
+ *
5365
+ * const presentToUser: ToolFunction = {
5366
+ * definition: { ... },
5367
+ * execute: async (args) => {
5368
+ * const { messageId } = await emailService.send(args.to, args.subject, args.body);
5369
+ * return SuspendSignal.create({
5370
+ * result: `Email sent to ${args.to}. Waiting for reply.`,
5371
+ * correlationId: `email:${messageId}`,
5372
+ * });
5373
+ * },
5374
+ * };
5375
+ * ```
5376
+ */
5377
+ /**
5378
+ * Options for creating a SuspendSignal
5379
+ */
5380
+ interface SuspendSignalOptions {
5381
+ /** The tool result visible to the LLM (e.g., "Email sent to user@example.com") */
5382
+ result: unknown;
5383
+ /**
5384
+ * Unique identifier for routing external events back to this session.
5385
+ * Typically prefixed by channel (e.g., "email:msg_123", "ticket:T-456")
5386
+ */
5387
+ correlationId: string;
5388
+ /**
5389
+ * How the external response should be injected when the session resumes.
5390
+ * - `'user_message'` (default): added as a new user message
5391
+ * - `'tool_result'`: added as a tool result
5392
+ */
5393
+ resumeAs?: 'user_message' | 'tool_result';
5394
+ /** Time-to-live in milliseconds before the suspended session expires. Default: 7 days */
5395
+ ttl?: number;
5396
+ /** Application-specific metadata (email ID, ticket ID, webhook URL, etc.) */
5397
+ metadata?: Record<string, unknown>;
5398
+ }
5399
+ /**
5400
+ * Signal that a tool has initiated an external operation and the agent
5401
+ * loop should suspend until an external event resumes it.
5402
+ */
5403
+ declare class SuspendSignal {
5404
+ /** The tool result visible to the LLM */
5405
+ readonly result: unknown;
5406
+ /** Correlation identifier for routing external events back */
5407
+ readonly correlationId: string;
5408
+ /** How the external response is injected on resume */
5409
+ readonly resumeAs: 'user_message' | 'tool_result';
5410
+ /** Time-to-live in milliseconds */
5411
+ readonly ttl: number;
5412
+ /** Application-specific metadata */
5413
+ readonly metadata?: Record<string, unknown>;
5414
+ private constructor();
5415
+ /**
5416
+ * Create a new SuspendSignal.
5417
+ *
5418
+ * @example
5419
+ * ```typescript
5420
+ * return SuspendSignal.create({
5421
+ * result: 'Email sent to user@example.com. Waiting for reply.',
5422
+ * correlationId: `email:${messageId}`,
5423
+ * metadata: { messageId, sentTo: email },
5424
+ * });
5425
+ * ```
5426
+ */
5427
+ static create(options: SuspendSignalOptions): SuspendSignal;
5428
+ /**
5429
+ * Type guard to check if a value is a SuspendSignal.
5430
+ */
5431
+ static is(value: unknown): value is SuspendSignal;
5432
+ }
5433
+
4306
5434
  /**
4307
5435
  * Routine Execution Runner
4308
5436
  *
@@ -4454,6 +5582,66 @@ interface ExecutionRecorder {
4454
5582
  */
4455
5583
  declare function createExecutionRecorder(options: ExecutionRecorderOptions): ExecutionRecorder;
4456
5584
 
5585
+ /**
5586
+ * StoreToolsManager - Unified CRUD tools for all IStoreHandler plugins
5587
+ *
5588
+ * Creates 5 generic tools (store_get, store_set, store_delete, store_list, store_action)
5589
+ * that route to the correct plugin handler based on the `store` parameter.
5590
+ *
5591
+ * Registered once on the first IStoreHandler plugin registration.
5592
+ * Subsequent handlers are added dynamically; `descriptionFactory` picks them up.
5593
+ */
5594
+
5595
+ declare class StoreToolsManager {
5596
+ private handlers;
5597
+ /**
5598
+ * Register a store handler. Throws on duplicate storeId.
5599
+ */
5600
+ registerHandler(handler: IStoreHandler): void;
5601
+ /**
5602
+ * Unregister a store handler by storeId.
5603
+ */
5604
+ unregisterHandler(storeId: string): boolean;
5605
+ /**
5606
+ * Get a handler by storeId.
5607
+ */
5608
+ getHandler(storeId: string): IStoreHandler | undefined;
5609
+ /**
5610
+ * Get all registered store schemas (for building tool descriptions).
5611
+ */
5612
+ getSchemas(): StoreEntrySchema[];
5613
+ /**
5614
+ * Get all registered store IDs.
5615
+ */
5616
+ getStoreIds(): string[];
5617
+ /**
5618
+ * Create the 5 generic store tools.
5619
+ * Called once when the first IStoreHandler is registered.
5620
+ */
5621
+ getTools(): ToolFunction[];
5622
+ /**
5623
+ * Cleanup.
5624
+ */
5625
+ destroy(): void;
5626
+ /**
5627
+ * Build the unified overview block for system instructions.
5628
+ * Emitted once when any IStoreHandler plugins are registered.
5629
+ * Covers: what store_* tools are, available stores, and when to use each.
5630
+ */
5631
+ buildOverview(): string;
5632
+ /**
5633
+ * Build the store comparison section for tool descriptions.
5634
+ * Called dynamically via descriptionFactory so it always reflects current handlers.
5635
+ */
5636
+ private buildStoreDescriptions;
5637
+ private createStoreGetTool;
5638
+ private createStoreSetTool;
5639
+ private createStoreDeleteTool;
5640
+ private createStoreListTool;
5641
+ private createStoreActionTool;
5642
+ private resolveHandler;
5643
+ }
5644
+
4457
5645
  /**
4458
5646
  * BasePluginNextGen - Base class for context plugins
4459
5647
  *
@@ -4822,7 +6010,7 @@ interface InContextMemoryConfig {
4822
6010
  interface SerializedInContextMemoryState {
4823
6011
  entries: InContextEntry[];
4824
6012
  }
4825
- declare class InContextMemoryPluginNextGen implements IContextPluginNextGen {
6013
+ declare class InContextMemoryPluginNextGen implements IContextPluginNextGen, IStoreHandler {
4826
6014
  readonly name = "in_context_memory";
4827
6015
  private entries;
4828
6016
  private config;
@@ -4889,9 +6077,11 @@ declare class InContextMemoryPluginNextGen implements IContextPluginNextGen {
4889
6077
  */
4890
6078
  private notifyEntriesChanged;
4891
6079
  private assertNotDestroyed;
4892
- private createContextSetTool;
4893
- private createContextDeleteTool;
4894
- private createContextListTool;
6080
+ getStoreSchema(): StoreEntrySchema;
6081
+ storeGet(key?: string, _context?: ToolContext): Promise<StoreGetResult>;
6082
+ storeSet(key: string, data: Record<string, unknown>, _context?: ToolContext): Promise<StoreSetResult>;
6083
+ storeDelete(key: string, _context?: ToolContext): Promise<StoreDeleteResult>;
6084
+ storeList(_filter?: Record<string, unknown>, _context?: ToolContext): Promise<StoreListResult>;
4895
6085
  }
4896
6086
 
4897
6087
  /**
@@ -4924,7 +6114,7 @@ interface SerializedPersistentInstructionsState {
4924
6114
  agentId: string;
4925
6115
  version: 2;
4926
6116
  }
4927
- declare class PersistentInstructionsPluginNextGen implements IContextPluginNextGen {
6117
+ declare class PersistentInstructionsPluginNextGen implements IContextPluginNextGen, IStoreHandler {
4928
6118
  readonly name = "persistent_instructions";
4929
6119
  private _entries;
4930
6120
  private _initialized;
@@ -4981,6 +6171,12 @@ declare class PersistentInstructionsPluginNextGen implements IContextPluginNextG
4981
6171
  * Check if initialized
4982
6172
  */
4983
6173
  get isInitialized(): boolean;
6174
+ getStoreSchema(): StoreEntrySchema;
6175
+ storeGet(key?: string, _context?: ToolContext): Promise<StoreGetResult>;
6176
+ storeSet(key: string, data: Record<string, unknown>, _context?: ToolContext): Promise<StoreSetResult>;
6177
+ storeDelete(key: string, _context?: ToolContext): Promise<StoreDeleteResult>;
6178
+ storeList(_filter?: Record<string, unknown>, _context?: ToolContext): Promise<StoreListResult>;
6179
+ storeAction(action: string, params?: Record<string, unknown>, _context?: ToolContext): Promise<StoreActionResult>;
4984
6180
  private ensureInitialized;
4985
6181
  private assertNotDestroyed;
4986
6182
  /**
@@ -4999,10 +6195,6 @@ declare class PersistentInstructionsPluginNextGen implements IContextPluginNextG
4999
6195
  * Render all entries as markdown for context injection
5000
6196
  */
5001
6197
  private renderContent;
5002
- private createInstructionsSetTool;
5003
- private createInstructionsRemoveTool;
5004
- private createInstructionsListTool;
5005
- private createInstructionsClearTool;
5006
6198
  }
5007
6199
 
5008
6200
  /**
@@ -5043,7 +6235,7 @@ interface SerializedUserInfoState {
5043
6235
  entries: UserInfoEntry[];
5044
6236
  userId?: string;
5045
6237
  }
5046
- declare class UserInfoPluginNextGen implements IContextPluginNextGen {
6238
+ declare class UserInfoPluginNextGen implements IContextPluginNextGen, IStoreHandler {
5047
6239
  readonly name = "user_info";
5048
6240
  private _destroyed;
5049
6241
  private _storage;
@@ -5092,10 +6284,12 @@ declare class UserInfoPluginNextGen implements IContextPluginNextGen {
5092
6284
  * Persist current entries to storage
5093
6285
  */
5094
6286
  private persistToStorage;
5095
- private createUserInfoSetTool;
5096
- private createUserInfoGetTool;
5097
- private createUserInfoRemoveTool;
5098
- private createUserInfoClearTool;
6287
+ getStoreSchema(): StoreEntrySchema;
6288
+ storeGet(key?: string, _context?: ToolContext): Promise<StoreGetResult>;
6289
+ storeSet(key: string, data: Record<string, unknown>, context?: ToolContext): Promise<StoreSetResult>;
6290
+ storeDelete(key: string, context?: ToolContext): Promise<StoreDeleteResult>;
6291
+ storeList(_filter?: Record<string, unknown>, _context?: ToolContext): Promise<StoreListResult>;
6292
+ storeAction(action: string, params?: Record<string, unknown>, context?: ToolContext): Promise<StoreActionResult>;
5099
6293
  private createTodoAddTool;
5100
6294
  private createTodoUpdateTool;
5101
6295
  private createTodoRemoveTool;
@@ -5199,6 +6393,108 @@ declare class ToolCatalogPluginNextGen extends BasePluginNextGen {
5199
6393
  private estimateToolDefinitionTokens;
5200
6394
  }
5201
6395
 
6396
+ /**
6397
+ * SharedWorkspacePluginNextGen - Shared bulletin board for multi-agent coordination
6398
+ *
6399
+ * A storage-agnostic coordination layer where agents share artifacts, status,
6400
+ * and messages. Entries can hold inline content (for collaborative documents)
6401
+ * and/or external references (file paths, DB IDs, URLs) accessed via agent tools.
6402
+ *
6403
+ * Designed to be shared across agent instances: create one instance and
6404
+ * register it on multiple AgentContextNextGen contexts.
6405
+ *
6406
+ * Use for:
6407
+ * - Shared plans, designs, reviews
6408
+ * - Task status tracking across agents
6409
+ * - Collaborative documents (inline content)
6410
+ * - References to external resources
6411
+ *
6412
+ * Do NOT use for:
6413
+ * - Private agent state (use InContextMemory / "context" store)
6414
+ * - Persistent rules (use PersistentInstructions / "instructions" store)
6415
+ */
6416
+
6417
+ interface SharedWorkspaceEntry {
6418
+ key: string;
6419
+ /** Inline content (optional — for collaborative documents) */
6420
+ content?: string;
6421
+ /** External references: file paths, DB IDs, URLs, etc. (optional) */
6422
+ references?: string[];
6423
+ /** Required brief summary — always cheap to show in context */
6424
+ summary: string;
6425
+ /** Free-form status */
6426
+ status: string;
6427
+ /** Agent name or ID that last updated this entry */
6428
+ author: string;
6429
+ /** Auto-incremented on each update */
6430
+ version: number;
6431
+ /** Optional tags for filtering */
6432
+ tags?: string[];
6433
+ createdAt: number;
6434
+ updatedAt: number;
6435
+ }
6436
+ interface WorkspaceLogEntry {
6437
+ author: string;
6438
+ message: string;
6439
+ timestamp: number;
6440
+ }
6441
+ interface SharedWorkspaceConfig {
6442
+ /** Maximum number of entries (default: 50) */
6443
+ maxEntries?: number;
6444
+ /** Maximum total tokens for context rendering (default: 8000) */
6445
+ maxTotalTokens?: number;
6446
+ /** Maximum log entries to keep (default: 100) */
6447
+ maxLogEntries?: number;
6448
+ /** Callback when entries change */
6449
+ onEntriesChanged?: (entries: SharedWorkspaceEntry[]) => void;
6450
+ }
6451
+ interface SerializedSharedWorkspaceState {
6452
+ entries: SharedWorkspaceEntry[];
6453
+ log: WorkspaceLogEntry[];
6454
+ }
6455
+ declare class SharedWorkspacePluginNextGen implements IContextPluginNextGen, IStoreHandler {
6456
+ readonly name = "shared_workspace";
6457
+ private entries;
6458
+ private log;
6459
+ private config;
6460
+ private estimator;
6461
+ private _destroyed;
6462
+ private _tokenCache;
6463
+ private _instructionsTokenCache;
6464
+ constructor(config?: Partial<SharedWorkspaceConfig>);
6465
+ getInstructions(): string;
6466
+ getContent(): Promise<string | null>;
6467
+ getContents(): {
6468
+ entries: SharedWorkspaceEntry[];
6469
+ log: WorkspaceLogEntry[];
6470
+ };
6471
+ getTokenSize(): number;
6472
+ getInstructionsTokenSize(): number;
6473
+ isCompactable(): boolean;
6474
+ compact(targetTokensToFree: number): Promise<number>;
6475
+ getTools(): ToolFunction[];
6476
+ destroy(): void;
6477
+ getState(): SerializedSharedWorkspaceState;
6478
+ restoreState(state: unknown): void;
6479
+ getStoreSchema(): StoreEntrySchema;
6480
+ storeGet(key?: string, _context?: ToolContext): Promise<StoreGetResult>;
6481
+ storeSet(key: string, data: Record<string, unknown>, _context?: ToolContext): Promise<StoreSetResult>;
6482
+ storeDelete(key: string, _context?: ToolContext): Promise<StoreDeleteResult>;
6483
+ storeList(filter?: Record<string, unknown>, _context?: ToolContext): Promise<StoreListResult>;
6484
+ storeAction(action: string, params?: Record<string, unknown>, _context?: ToolContext): Promise<StoreActionResult>;
6485
+ /** Get an entry by key */
6486
+ getEntry(key: string): SharedWorkspaceEntry | undefined;
6487
+ /** Get all entries */
6488
+ getAllEntries(): SharedWorkspaceEntry[];
6489
+ /** Get the conversation log */
6490
+ getLog(): WorkspaceLogEntry[];
6491
+ /** Append to the conversation log */
6492
+ appendLog(author: string, message: string): void;
6493
+ private formatContent;
6494
+ private formatEntry;
6495
+ private enforceMaxEntries;
6496
+ }
6497
+
5202
6498
  /**
5203
6499
  * DefaultCompactionStrategy - Standard compaction behavior
5204
6500
  *
@@ -5406,14 +6702,116 @@ declare class StrategyRegistry {
5406
6702
  */
5407
6703
  static remove(name: string): boolean;
5408
6704
  /**
5409
- * Get a strategy entry without throwing.
5410
- * Returns undefined if not found.
6705
+ * Get a strategy entry without throwing.
6706
+ * Returns undefined if not found.
6707
+ */
6708
+ static getIfExists(name: string): StrategyRegistryEntry | undefined;
6709
+ /**
6710
+ * Reset the registry to initial state (for testing).
6711
+ * @internal
6712
+ */
6713
+ static _reset(): void;
6714
+ }
6715
+
6716
+ /**
6717
+ * PluginRegistry — Global registry for external plugin factories.
6718
+ *
6719
+ * Allows external packages to register plugin factories that auto-initialize
6720
+ * when the corresponding feature flag is enabled in ContextFeatures.
6721
+ *
6722
+ * Built-in plugins (workingMemory, inContextMemory, etc.) are NOT registered
6723
+ * here — they remain hardcoded in AgentContextNextGen.initializePlugins().
6724
+ * This registry is exclusively for EXTERNAL plugins.
6725
+ *
6726
+ * Follows the StrategyRegistry pattern: static class, private Map, lazy init.
6727
+ *
6728
+ * @example
6729
+ * ```typescript
6730
+ * // In an external package (e.g., @everworker/react-ui/plugins.ts)
6731
+ * import { PluginRegistry } from '@everworker/oneringai';
6732
+ * import { DynamicUIPlugin } from './DynamicUIPlugin';
6733
+ *
6734
+ * PluginRegistry.register('dynamic_ui', (config) => new DynamicUIPlugin(config), {
6735
+ * description: 'Rich side-panel content via InContextMemory showInUI',
6736
+ * dependencies: ['inContextMemory'],
6737
+ * });
6738
+ *
6739
+ * // In app code
6740
+ * import '@everworker/react-ui/plugins'; // side-effect registers factory
6741
+ *
6742
+ * const agent = Agent.create({
6743
+ * connector: 'openai', model: 'gpt-4',
6744
+ * context: { features: { dynamicUI: true } }, // auto-initializes!
6745
+ * });
6746
+ * ```
6747
+ */
6748
+
6749
+ /** Context passed to plugin factories during auto-initialization */
6750
+ interface PluginFactoryContext {
6751
+ agentId: string;
6752
+ userId?: string;
6753
+ features: Record<string, boolean | undefined>;
6754
+ }
6755
+ /** Plugin factory function — creates a plugin instance from optional config */
6756
+ type PluginFactory = (config?: Record<string, unknown>, context?: PluginFactoryContext) => IContextPluginNextGen;
6757
+ /** Options for registering a plugin */
6758
+ interface PluginRegisterOptions {
6759
+ /**
6760
+ * Feature flag key in camelCase (e.g., 'dynamicUI').
6761
+ * If omitted, derived from pluginName via snake_case → camelCase conversion.
5411
6762
  */
5412
- static getIfExists(name: string): StrategyRegistryEntry | undefined;
6763
+ featureKey?: string;
6764
+ /** Human-readable description */
6765
+ description?: string;
6766
+ /** Feature keys (camelCase) that must also be enabled for this plugin to work */
6767
+ dependencies?: string[];
6768
+ }
6769
+ /** Registry entry for an external plugin */
6770
+ interface PluginRegistryEntry {
6771
+ /** Feature flag key in ContextFeatures (camelCase, e.g., 'dynamicUI') */
6772
+ featureKey: string;
6773
+ /** Plugin name (snake_case, e.g., 'dynamic_ui') — must match plugin.name */
6774
+ pluginName: string;
6775
+ /** Factory to create plugin instances */
6776
+ factory: PluginFactory;
6777
+ /** Human-readable description */
6778
+ description?: string;
6779
+ /** Feature keys that must be enabled for this plugin to work */
6780
+ dependencies?: string[];
6781
+ }
6782
+ /** Serializable plugin info (no factory reference) */
6783
+ interface PluginRegistryInfo {
6784
+ featureKey: string;
6785
+ pluginName: string;
6786
+ description?: string;
6787
+ dependencies?: string[];
6788
+ }
6789
+ declare class PluginRegistry {
6790
+ private static registry;
5413
6791
  /**
5414
- * Reset the registry to initial state (for testing).
5415
- * @internal
5416
- */
6792
+ * Register an external plugin factory.
6793
+ *
6794
+ * @param pluginName - Plugin name in snake_case (must match plugin.name)
6795
+ * @param factory - Factory function to create plugin instances
6796
+ * @param options - Registration options (featureKey, description, dependencies)
6797
+ *
6798
+ * @throws If featureKey collides with a built-in plugin
6799
+ * @throws If featureKey is already registered
6800
+ */
6801
+ static register(pluginName: string, factory: PluginFactory, options?: PluginRegisterOptions): void;
6802
+ /** Check if a feature key has a registered factory */
6803
+ static has(featureKey: string): boolean;
6804
+ /** Get a registry entry by feature key */
6805
+ static get(featureKey: string): PluginRegistryEntry | undefined;
6806
+ /** List all registered feature keys */
6807
+ static list(): string[];
6808
+ /** Get serializable info for all registered plugins (no factory references) */
6809
+ static getInfo(): PluginRegistryInfo[];
6810
+ /** Remove a registered plugin by feature key */
6811
+ static remove(featureKey: string): boolean;
6812
+ /** Get all entries as ReadonlyMap (internal use by AgentContextNextGen) */
6813
+ static getAll(): ReadonlyMap<string, PluginRegistryEntry>;
6814
+ /** Reset registry — for testing only */
5417
6815
  static _reset(): void;
5418
6816
  }
5419
6817
 
@@ -5435,6 +6833,122 @@ declare function getVendorDefaultBaseURL(vendor: string): string | undefined;
5435
6833
  */
5436
6834
  declare function createProvider(connector: Connector): ITextProvider;
5437
6835
 
6836
+ /**
6837
+ * createOrchestrator - Factory for creating an orchestrator Agent
6838
+ *
6839
+ * The orchestrator is a regular Agent with:
6840
+ * - A SharedWorkspacePlugin (shared with all workers)
6841
+ * - 7 orchestration tools for managing worker agents
6842
+ * - A system prompt that describes available agent types and coordination patterns
6843
+ * - Async tool support for non-blocking turn assignment
6844
+ *
6845
+ * Workers are persistent Agent instances that remember reasoning across turns.
6846
+ * All agents share the same workspace for artifact coordination.
6847
+ */
6848
+
6849
+ /**
6850
+ * Configuration for an agent type that the orchestrator can spawn.
6851
+ */
6852
+ interface AgentTypeConfig {
6853
+ /** System prompt defining this agent's role and behavior */
6854
+ systemPrompt: string;
6855
+ /** Additional tools specific to this agent type */
6856
+ tools?: ToolFunction[];
6857
+ /** Model override (defaults to orchestrator's model) */
6858
+ model?: string;
6859
+ /** Connector override (defaults to orchestrator's connector) */
6860
+ connector?: string;
6861
+ /** Context features for this agent type */
6862
+ features?: Partial<ContextFeatures>;
6863
+ /** Plugin configurations for this agent type */
6864
+ plugins?: PluginConfigs;
6865
+ }
6866
+ /**
6867
+ * Configuration for the orchestrator.
6868
+ */
6869
+ interface OrchestratorConfig {
6870
+ /** Connector name for LLM access */
6871
+ connector: string;
6872
+ /** Model to use for the orchestrator (also default for workers) */
6873
+ model: string;
6874
+ /** Custom system prompt (overrides the auto-generated one) */
6875
+ systemPrompt?: string;
6876
+ /** Available agent types that can be spawned */
6877
+ agentTypes: Record<string, AgentTypeConfig>;
6878
+ /** SharedWorkspace configuration */
6879
+ workspace?: Partial<SharedWorkspaceConfig>;
6880
+ /** Additional context features for the orchestrator */
6881
+ features?: Partial<ContextFeatures>;
6882
+ /** Plugin configurations for the orchestrator */
6883
+ pluginConfigs?: PluginConfigs;
6884
+ /** Agent name for the orchestrator (default: 'orchestrator') */
6885
+ name?: string;
6886
+ /** Agent ID for session persistence */
6887
+ agentId?: string;
6888
+ /** Max iterations for the orchestrator's agentic loop (default: 100) */
6889
+ maxIterations?: number;
6890
+ /** Maximum number of worker agents (default: 20) */
6891
+ maxAgents?: number;
6892
+ }
6893
+ /**
6894
+ * Create an orchestrator Agent that can coordinate a team of worker agents.
6895
+ *
6896
+ * @example
6897
+ * ```typescript
6898
+ * const orchestrator = createOrchestrator({
6899
+ * connector: 'openai',
6900
+ * model: 'gpt-4',
6901
+ * agentTypes: {
6902
+ * architect: {
6903
+ * systemPrompt: 'You are a senior software architect...',
6904
+ * tools: [readFile, writeFile],
6905
+ * },
6906
+ * critic: {
6907
+ * systemPrompt: 'You are a thorough code reviewer...',
6908
+ * tools: [readFile, grep],
6909
+ * },
6910
+ * developer: {
6911
+ * systemPrompt: 'You are a senior developer...',
6912
+ * tools: [readFile, writeFile, editFile, bash],
6913
+ * },
6914
+ * },
6915
+ * });
6916
+ *
6917
+ * const result = await orchestrator.run('Build an auth module with JWT support');
6918
+ * ```
6919
+ */
6920
+ declare function createOrchestrator(config: OrchestratorConfig): Agent;
6921
+
6922
+ /**
6923
+ * Orchestration Tools - Tools given to the orchestrator Agent for managing worker agents.
6924
+ *
6925
+ * 7 tools:
6926
+ * - create_agent: Spawn a worker agent from predefined types
6927
+ * - list_agents: See team status
6928
+ * - destroy_agent: Remove a worker
6929
+ * - assign_turn: Assign a turn and wait for result (blocking)
6930
+ * - assign_turn_async: Assign a turn without waiting (non-blocking, result delivered via async continuation)
6931
+ * - assign_parallel: Fan-out to multiple agents, wait for all
6932
+ * - send_message: Inject a message into an agent's context
6933
+ */
6934
+
6935
+ interface OrchestrationToolsContext {
6936
+ /** Shared workspace plugin instance */
6937
+ workspace: SharedWorkspacePluginNextGen;
6938
+ /** Live worker agent instances (name → Agent) */
6939
+ agents: Map<string, Agent>;
6940
+ /** Registered agent type configurations */
6941
+ agentTypes: Map<string, AgentTypeConfig>;
6942
+ /** Timestamp of each agent's last completed turn (for workspace deltas) */
6943
+ lastTurnTimestamps: Map<string, number>;
6944
+ /** Factory function to create a worker agent */
6945
+ createWorkerAgent: (name: string, type: string) => Agent;
6946
+ /** Maximum number of worker agents (M2, default: 20) */
6947
+ maxAgents?: number;
6948
+ }
6949
+ declare function buildWorkspaceDelta(agentName: string, workspace: SharedWorkspacePluginNextGen, lastSeen: Map<string, number>): string;
6950
+ declare function buildOrchestrationTools(ctx: OrchestrationToolsContext): ToolFunction[];
6951
+
5438
6952
  /**
5439
6953
  * MCP Configuration Types
5440
6954
  *
@@ -5845,6 +7359,10 @@ declare class MCPClient extends EventEmitter implements IMCPClient, IDisposable
5845
7359
  */
5846
7360
  get isDestroyed(): boolean;
5847
7361
  destroy(): void;
7362
+ /**
7363
+ * Create a standardized MCPError for this server
7364
+ */
7365
+ private createMCPError;
5848
7366
  private createTransport;
5849
7367
  private ensureConnected;
5850
7368
  private refreshTools;
@@ -5984,26 +7502,6 @@ declare class MCPResourceError extends MCPError {
5984
7502
  constructor(message: string, resourceUri: string, serverName?: string, cause?: Error);
5985
7503
  }
5986
7504
 
5987
- /**
5988
- * Shared voice definitions and language constants
5989
- * Eliminates duplication across TTS model registries
5990
- */
5991
- /**
5992
- * Voice information structure
5993
- * Used consistently across all TTS providers
5994
- */
5995
- interface IVoiceInfo {
5996
- id: string;
5997
- name: string;
5998
- language: string;
5999
- gender: 'male' | 'female' | 'neutral';
6000
- style?: string;
6001
- previewUrl?: string;
6002
- isDefault?: boolean;
6003
- accent?: string;
6004
- age?: 'child' | 'young' | 'adult' | 'senior';
6005
- }
6006
-
6007
7505
  /**
6008
7506
  * Audio provider interfaces for Text-to-Speech and Speech-to-Text
6009
7507
  */
@@ -7355,138 +8853,994 @@ declare class VoiceStream extends EventEmitter$1 implements IDisposable {
7355
8853
  */
7356
8854
  private executeTTS;
7357
8855
  /**
7358
- * Drain the audio event buffer, yielding all ready events.
8856
+ * Drain the audio event buffer, yielding all ready events.
8857
+ */
8858
+ private drainAudioBuffer;
8859
+ /** Next chunk_index we're allowed to emit (ordering gate) */
8860
+ private nextEmitChunkIndex;
8861
+ /** Events from future chunks held back until their turn */
8862
+ private holdBackBuffer;
8863
+ /**
8864
+ * Push an audio event, respecting chunk_index ordering.
8865
+ * Events for the current chunk_index go directly to the consumer buffer.
8866
+ * Events from later chunks are held back until earlier chunks complete.
8867
+ */
8868
+ private pushAudioEvent;
8869
+ /**
8870
+ * Called when a TTS chunk_index finishes (all sub-chunks emitted).
8871
+ * Advances the gate and releases any held-back events for the next chunk.
8872
+ */
8873
+ private advanceChunkGate;
8874
+ /**
8875
+ * Wait until a new event is pushed to the audio buffer
8876
+ */
8877
+ private waitForBufferNotify;
8878
+ private waitForTTSSlot;
8879
+ private releaseTTSSlot;
8880
+ private waitForQueueSlot;
8881
+ private releaseQueueWaiter;
8882
+ private releaseAllWaiters;
8883
+ private cleanup;
8884
+ }
8885
+
8886
+ /**
8887
+ * Sentence boundary detection for voice pseudo-streaming.
8888
+ * Splits streaming text deltas into speakable chunks.
8889
+ */
8890
+
8891
+ /**
8892
+ * Default chunking strategy that splits text at sentence boundaries.
8893
+ *
8894
+ * Handles:
8895
+ * - Sentence terminators (. ? !) followed by whitespace
8896
+ * - Abbreviation exclusion (Dr., Mr., U.S., e.g., etc.)
8897
+ * - Numeric decimals (3.14, $1.50)
8898
+ * - Paragraph breaks (\n\n)
8899
+ * - Fenced code block tracking (``` ... ```)
8900
+ * - Markdown stripping
8901
+ * - Min/max chunk length enforcement
8902
+ */
8903
+ declare class SentenceChunkingStrategy implements IChunkingStrategy {
8904
+ private buffer;
8905
+ private inCodeBlock;
8906
+ private codeBlockBuffer;
8907
+ private options;
8908
+ private abbreviations;
8909
+ constructor(options?: ChunkingOptions);
8910
+ feed(delta: string): string[];
8911
+ flush(): string | null;
8912
+ reset(): void;
8913
+ private extractChunks;
8914
+ /**
8915
+ * Track and remove fenced code blocks from the buffer.
8916
+ * Text inside code blocks is discarded (not spoken).
8917
+ */
8918
+ private processCodeBlocks;
8919
+ /**
8920
+ * Find the position right after the next sentence boundary.
8921
+ * Returns -1 if no complete sentence boundary found.
8922
+ */
8923
+ private findSentenceBoundary;
8924
+ /**
8925
+ * Check if the period at position `pos` is part of a known abbreviation.
8926
+ */
8927
+ private isAbbreviation;
8928
+ /**
8929
+ * Check if the period at position `pos` is a decimal point.
8930
+ * e.g., 3.14, $1.50
8931
+ */
8932
+ private isDecimalNumber;
8933
+ /**
8934
+ * Check if the period at position `pos` is part of an ellipsis (...).
8935
+ */
8936
+ private isEllipsis;
8937
+ /**
8938
+ * Split text that exceeds maxChunkLength at clause boundaries.
8939
+ */
8940
+ private splitLongText;
8941
+ /**
8942
+ * Merge chunks that are shorter than minChunkLength with the next chunk.
8943
+ */
8944
+ private mergeSmallChunks;
8945
+ /**
8946
+ * Strip markdown formatting from text for natural speech.
8947
+ */
8948
+ private cleanForSpeech;
8949
+ }
8950
+
8951
+ /**
8952
+ * AudioPlaybackQueue - Consumer-side helper for ordered audio playback
8953
+ *
8954
+ * TTS chunks may complete out of order (chunk 2 finishes before chunk 1).
8955
+ * This queue buffers audio events and delivers them to the callback
8956
+ * in sequential order by chunk_index.
8957
+ *
8958
+ * @example
8959
+ * ```typescript
8960
+ * const queue = new AudioPlaybackQueue((event) => {
8961
+ * // Play audio chunk — guaranteed to be in order
8962
+ * playAudio(Buffer.from(event.audio_base64, 'base64'));
8963
+ * });
8964
+ *
8965
+ * for await (const event of voiceStream.wrap(agent.stream('Hello'))) {
8966
+ * if (isAudioChunkReady(event)) {
8967
+ * queue.enqueue(event);
8968
+ * }
8969
+ * }
8970
+ * ```
8971
+ */
8972
+
8973
+ declare class AudioPlaybackQueue {
8974
+ private buffer;
8975
+ private nextPlayIndex;
8976
+ private onReady;
8977
+ constructor(onReady: AudioChunkPlaybackCallback);
8978
+ /**
8979
+ * Enqueue an audio chunk event. If it's the next expected chunk,
8980
+ * it (and any subsequent buffered chunks) are immediately delivered
8981
+ * to the callback in order.
8982
+ */
8983
+ enqueue(event: AudioChunkReadyEvent): void;
8984
+ /**
8985
+ * Reset the queue (e.g., on interruption or new stream).
8986
+ */
8987
+ reset(): void;
8988
+ /**
8989
+ * Number of chunks currently buffered waiting for earlier chunks.
8990
+ */
8991
+ get pendingCount(): number;
8992
+ /**
8993
+ * The next chunk index expected for playback.
8994
+ */
8995
+ get nextExpectedIndex(): number;
8996
+ private drain;
8997
+ }
8998
+
8999
+ /**
9000
+ * Voice capability types
9001
+ *
9002
+ * Defines the interfaces for voice calling integration:
9003
+ * - VoiceBridge: multi-session manager connecting telephony to agents
9004
+ * - VoiceSession: per-call state machine
9005
+ * - IVoicePipeline: strategy pattern for audio ↔ agent routing
9006
+ * - ITelephonyAdapter: abstraction over Twilio, Vonage, etc.
9007
+ */
9008
+
9009
+ /**
9010
+ * Audio encoding formats used in voice pipelines.
9011
+ * - pcm_s16le: 16-bit signed little-endian PCM (standard for STT/TTS)
9012
+ * - mulaw: μ-law companded 8-bit (Twilio telephony)
9013
+ * - alaw: A-law companded 8-bit (European telephony)
9014
+ */
9015
+ type AudioEncoding = 'pcm_s16le' | 'mulaw' | 'alaw';
9016
+ /**
9017
+ * A single frame of audio data exchanged between adapter and pipeline.
9018
+ * All voice processing operates on these frames.
9019
+ */
9020
+ interface AudioFrame {
9021
+ /** Raw audio bytes */
9022
+ audio: Buffer;
9023
+ /** Sample rate in Hz (e.g., 8000 for Twilio, 16000/24000 for STT/TTS) */
9024
+ sampleRate: number;
9025
+ /** Encoding format */
9026
+ encoding: AudioEncoding;
9027
+ /** Always mono */
9028
+ channels: 1;
9029
+ /** Milliseconds from call start */
9030
+ timestamp: number;
9031
+ }
9032
+ /** Result of VAD processing a single audio frame */
9033
+ type VADEvent = 'speech_start' | 'speech_end' | null;
9034
+ /**
9035
+ * Voice Activity Detector interface.
9036
+ * Implementations detect when the caller starts and stops speaking.
9037
+ */
9038
+ interface IVoiceActivityDetector {
9039
+ /** Feed an audio frame, returns speech state change (if any) */
9040
+ process(frame: AudioFrame): VADEvent;
9041
+ /** Reset internal state (e.g., between utterances) */
9042
+ reset(): void;
9043
+ }
9044
+ /**
9045
+ * Configuration for the default energy-based VAD
9046
+ */
9047
+ interface EnergyVADConfig {
9048
+ /** RMS energy threshold to consider as speech (0-1 scale). Default: 0.01 */
9049
+ energyThreshold?: number;
9050
+ /** Consecutive speech frames needed to trigger speech_start. Default: 3 */
9051
+ speechFramesThreshold?: number;
9052
+ /** Silence duration in ms to trigger speech_end. Default: 1500 */
9053
+ silenceTimeout?: number;
9054
+ /** Minimum speech duration in ms to be considered valid. Default: 250 */
9055
+ minSpeechDuration?: number;
9056
+ }
9057
+ type CallDirection = 'inbound' | 'outbound';
9058
+ type SessionState = 'idle' | 'ringing' | 'connected' | 'listening' | 'processing' | 'speaking' | 'ending' | 'ended';
9059
+ /**
9060
+ * Read-only snapshot of a voice session's state.
9061
+ * Exposed to lifecycle hooks and event handlers.
9062
+ */
9063
+ interface VoiceSessionInfo {
9064
+ /** Unique session identifier */
9065
+ sessionId: string;
9066
+ /** Adapter-specific call identifier (e.g., Twilio CallSid) */
9067
+ callId: string;
9068
+ /** Whether this is an inbound or outbound call */
9069
+ direction: CallDirection;
9070
+ /** Caller identifier (phone number, SIP URI, etc.) */
9071
+ from: string;
9072
+ /** Called identifier */
9073
+ to: string;
9074
+ /** Current session state */
9075
+ state: SessionState;
9076
+ /** When the call was initiated */
9077
+ startedAt: Date;
9078
+ /** When the call ended (undefined if still active) */
9079
+ endedAt?: Date;
9080
+ /** Number of conversation turns completed */
9081
+ turns: number;
9082
+ /** Adapter-specific metadata (e.g., Twilio AccountSid, geographic info) */
9083
+ metadata: Record<string, unknown>;
9084
+ }
9085
+ type CallEndReason = 'caller_hangup' | 'agent_hangup' | 'timeout' | 'error' | 'rejected';
9086
+ interface CallSummary {
9087
+ /** Call duration in seconds */
9088
+ duration: number;
9089
+ /** Number of conversation turns */
9090
+ turns: number;
9091
+ /** Why the call ended */
9092
+ endReason: CallEndReason;
9093
+ /** Total STT processing time in ms */
9094
+ totalSttMs: number;
9095
+ /** Total TTS processing time in ms */
9096
+ totalTtsMs: number;
9097
+ /** Total agent processing time in ms */
9098
+ totalAgentMs: number;
9099
+ }
9100
+ /**
9101
+ * Lifecycle hooks for voice sessions.
9102
+ * All hooks are async and called in order. Errors in hooks are logged
9103
+ * but do not terminate the call (except onCallStart returning false).
9104
+ */
9105
+ interface VoiceHooks {
9106
+ /**
9107
+ * Called when a new call connects (inbound or outbound).
9108
+ * Return `false` to reject the call. Return void or true to accept.
9109
+ */
9110
+ onCallStart?: (session: VoiceSessionInfo) => Promise<boolean | void>;
9111
+ /**
9112
+ * Called after STT produces text, before sending to agent.
9113
+ * Return modified text to alter what the agent sees.
9114
+ */
9115
+ beforeAgentResponse?: (text: string, session: VoiceSessionInfo) => Promise<string>;
9116
+ /**
9117
+ * Called after agent produces text, before TTS.
9118
+ * Return modified text to alter what the caller hears.
9119
+ */
9120
+ afterAgentResponse?: (text: string, session: VoiceSessionInfo) => Promise<string>;
9121
+ /**
9122
+ * Called when the caller interrupts agent speech.
9123
+ */
9124
+ onInterrupt?: (session: VoiceSessionInfo) => Promise<void>;
9125
+ /**
9126
+ * Called when any error occurs during the call.
9127
+ */
9128
+ onError?: (error: Error, session: VoiceSessionInfo) => Promise<void>;
9129
+ /**
9130
+ * Called when the call ends for any reason.
9131
+ */
9132
+ onCallEnd?: (session: VoiceSessionInfo, summary: CallSummary) => Promise<void>;
9133
+ }
9134
+ /**
9135
+ * Text pipeline configuration — STT → Agent → TTS
9136
+ */
9137
+ interface TextPipelineConfig {
9138
+ pipeline: 'text';
9139
+ /** STT configuration */
9140
+ stt: {
9141
+ /** Connector name for the STT provider */
9142
+ connector: string;
9143
+ /** STT model (e.g., 'whisper-1'). Default: provider's default */
9144
+ model?: string;
9145
+ /** BCP-47 language hint (e.g., 'en'). Default: auto-detect */
9146
+ language?: string;
9147
+ };
9148
+ /** TTS configuration */
9149
+ tts: {
9150
+ /** Connector name for the TTS provider */
9151
+ connector: string;
9152
+ /** TTS model (e.g., 'tts-1', 'tts-1-hd'). Default: 'tts-1' */
9153
+ model?: string;
9154
+ /** Voice ID (e.g., 'nova', 'alloy'). Default: 'nova' */
9155
+ voice?: string;
9156
+ /** Speech speed (0.25 to 4.0). Default: 1.0 */
9157
+ speed?: number;
9158
+ };
9159
+ }
9160
+ /**
9161
+ * Realtime pipeline configuration — direct voice-to-voice via OpenAI Realtime API.
9162
+ * No separate STT/TTS needed — the model handles audio natively.
9163
+ */
9164
+ interface RealtimePipelineConfig {
9165
+ pipeline: 'realtime';
9166
+ /** Voice for the realtime model (e.g., 'alloy', 'echo', 'shimmer'). Default: 'alloy' */
9167
+ voice?: string;
9168
+ /**
9169
+ * Turn detection mode:
9170
+ * - 'server_vad': OpenAI handles VAD (default, recommended)
9171
+ * - 'none': Manual turn management
9172
+ */
9173
+ turnDetection?: 'server_vad' | 'none';
9174
+ /** VAD threshold (0.0-1.0) for server_vad mode. Default: 0.5 */
9175
+ vadThreshold?: number;
9176
+ /** Silence duration in ms before end-of-turn. Default: 500 */
9177
+ silenceDurationMs?: number;
9178
+ /** Enable input audio transcription for hooks/logging. Default: true */
9179
+ inputTranscription?: boolean;
9180
+ /** Transcription model for input audio. Default: 'gpt-4o-transcribe' */
9181
+ transcriptionModel?: string;
9182
+ }
9183
+ type PipelineConfig = TextPipelineConfig | RealtimePipelineConfig;
9184
+ /**
9185
+ * A single entry in the voice call transcript.
9186
+ * Emitted by pipelines for UI display and logging.
9187
+ */
9188
+ interface TranscriptMessage {
9189
+ /** Who produced this message */
9190
+ role: 'caller' | 'agent' | 'tool_use' | 'tool_result';
9191
+ /** Text content (transcript, tool args JSON, or tool result) */
9192
+ text: string;
9193
+ /** Unix timestamp in ms */
9194
+ timestamp: number;
9195
+ /** Tool name (for tool_use / tool_result) */
9196
+ toolName?: string;
9197
+ /** Tool call ID for correlating use/result pairs */
9198
+ toolCallId?: string;
9199
+ }
9200
+ /**
9201
+ * Common fields shared by all VoiceBridge configurations.
9202
+ */
9203
+ interface VoiceBridgeBaseConfig {
9204
+ /** Agent configuration — connector, model, instructions, tools */
9205
+ agent: AgentConfig$1;
9206
+ /** Silence duration (ms) to consider end-of-utterance. Default: 1500 */
9207
+ silenceTimeout?: number;
9208
+ /** Allow caller to interrupt agent mid-speech. Default: true */
9209
+ interruptible?: boolean;
9210
+ /** First thing agent says when an inbound call connects. */
9211
+ greeting?: string;
9212
+ /** First thing agent says when an outbound call connects. If omitted, no greeting on outbound. */
9213
+ greetingOutbound?: string;
9214
+ /** Max concurrent calls. 0 = unlimited. Default: 10 */
9215
+ maxConcurrentCalls?: number;
9216
+ /** Max call duration in seconds. 0 = unlimited. Default: 3600 */
9217
+ maxCallDuration?: number;
9218
+ /** VAD configuration (for energy-based detector, text pipeline only) */
9219
+ vad?: EnergyVADConfig;
9220
+ /** Lifecycle hooks */
9221
+ hooks?: VoiceHooks;
9222
+ }
9223
+ /**
9224
+ * VoiceBridge configuration — discriminated union by pipeline type.
9225
+ */
9226
+ type VoiceBridgeConfig = (VoiceBridgeBaseConfig & TextPipelineConfig) | (VoiceBridgeBaseConfig & RealtimePipelineConfig);
9227
+ /**
9228
+ * Events emitted by a voice pipeline
9229
+ */
9230
+ interface VoicePipelinePlaybackAck {
9231
+ /** Telephony/provider specific acknowledgement token */
9232
+ name: string;
9233
+ /** Milliseconds of assistant audio acknowledged as played */
9234
+ playedMs: number;
9235
+ }
9236
+ interface VoicePipelineEvents {
9237
+ /** Audio ready to send to the caller */
9238
+ 'audio:out': (frame: AudioFrame) => void;
9239
+ /** Session state changed */
9240
+ 'state:change': (state: SessionState) => void;
9241
+ /** Caller interrupted agent speech (barge-in) */
9242
+ 'interrupt': () => void;
9243
+ /** Telephony playback progress acknowledgement */
9244
+ 'playback:ack': (ack: VoicePipelinePlaybackAck) => void;
9245
+ /** Transcript entry for UI display (caller text, agent text, tool calls) */
9246
+ 'transcript': (entry: TranscriptMessage) => void;
9247
+ /** Error during processing */
9248
+ 'error': (error: Error) => void;
9249
+ }
9250
+ /**
9251
+ * Voice pipeline strategy interface.
9252
+ * TextPipeline and RealtimePipeline both implement this.
9253
+ */
9254
+ interface IVoicePipeline {
9255
+ /** Initialize pipeline for a new call session */
9256
+ init(sessionInfo: VoiceSessionInfo): Promise<void>;
9257
+ /** Process an incoming audio frame from the caller */
9258
+ processAudio(frame: AudioFrame): void;
9259
+ /** Signal that the caller stopped speaking (silence detected by VAD) */
9260
+ onSpeechEnd(): Promise<void>;
9261
+ /** Signal that the caller started speaking (interrupt if agent is speaking) */
9262
+ onSpeechStart(): void;
9263
+ /** Interrupt current agent response (e.g., caller spoke during TTS) */
9264
+ interrupt(): void;
9265
+ /** Notify pipeline of telephony playback progress */
9266
+ onPlaybackAck?(ack: VoicePipelinePlaybackAck): void;
9267
+ /** Get current pipeline state */
9268
+ getState(): SessionState;
9269
+ /** Subscribe to pipeline events */
9270
+ on<K extends keyof VoicePipelineEvents>(event: K, handler: VoicePipelineEvents[K]): void;
9271
+ off<K extends keyof VoicePipelineEvents>(event: K, handler: VoicePipelineEvents[K]): void;
9272
+ /** Clean up all resources (agent, TTS, STT) */
9273
+ destroy(): Promise<void>;
9274
+ }
9275
+ /**
9276
+ * Metadata for an incoming call from the telephony provider.
9277
+ * The adapter maps provider-specific data to this structure.
9278
+ */
9279
+ interface IncomingCallInfo {
9280
+ /** Provider-specific call ID (e.g., Twilio CallSid) */
9281
+ callId: string;
9282
+ /** Caller identifier (phone number, SIP URI) */
9283
+ from: string;
9284
+ /** Called identifier */
9285
+ to: string;
9286
+ /** Adapter-specific metadata */
9287
+ metadata: Record<string, unknown>;
9288
+ }
9289
+ /**
9290
+ * Telephony adapter events
9291
+ */
9292
+ interface TelephonyMediaTimestamp {
9293
+ /** Twilio media timestamp in ms from stream start */
9294
+ timestamp: number;
9295
+ }
9296
+ interface TelephonyAdapterEvents {
9297
+ /** A new call has been established and audio is flowing */
9298
+ 'call:connected': (callId: string, info: IncomingCallInfo) => void;
9299
+ /** Audio frame received from caller */
9300
+ 'call:audio': (callId: string, frame: AudioFrame) => void;
9301
+ /** Latest inbound media timestamp from telephony */
9302
+ 'call:media_timestamp': (callId: string, info: TelephonyMediaTimestamp) => void;
9303
+ /** Call has ended */
9304
+ 'call:ended': (callId: string, reason: string) => void;
9305
+ /** Adapter-level error */
9306
+ 'error': (error: Error, callId?: string) => void;
9307
+ }
9308
+ /**
9309
+ * Abstraction over telephony providers (Twilio, Vonage, etc.).
9310
+ * The adapter handles the provider-specific protocol and exposes
9311
+ * a uniform audio frame interface to the VoiceBridge.
9312
+ */
9313
+ interface ITelephonyAdapter {
9314
+ /** Send an audio frame to the caller */
9315
+ sendAudio(callId: string, frame: AudioFrame): void;
9316
+ /** Clear all buffered outbound audio for a call (barge-in/interrupt) */
9317
+ clearAudio?(callId: string): void;
9318
+ /** End a specific call */
9319
+ hangup(callId: string): Promise<void>;
9320
+ /** Initiate an outbound call. Returns the provider-specific call ID. */
9321
+ makeCall?(config: OutboundCallConfig): Promise<string>;
9322
+ /** Get all active call IDs */
9323
+ getActiveCalls(): string[];
9324
+ /** Subscribe to adapter events */
9325
+ on<K extends keyof TelephonyAdapterEvents>(event: K, handler: TelephonyAdapterEvents[K]): void;
9326
+ off<K extends keyof TelephonyAdapterEvents>(event: K, handler: TelephonyAdapterEvents[K]): void;
9327
+ /** Clean up all connections */
9328
+ destroy(): Promise<void>;
9329
+ }
9330
+ /**
9331
+ * Configuration for initiating an outbound call.
9332
+ */
9333
+ interface OutboundCallConfig {
9334
+ /** Destination phone number (E.164 format, e.g., '+15558675310') */
9335
+ to: string;
9336
+ /** Caller ID / from phone number (must be a verified Twilio number) */
9337
+ from: string;
9338
+ /** Ring timeout in seconds before giving up. Default: 30 */
9339
+ timeout?: number;
9340
+ /** Enable answering machine detection. Default: false */
9341
+ machineDetection?: boolean;
9342
+ }
9343
+ interface TwilioAdapterConfig {
9344
+ /** Twilio connector name (for REST API auth) */
9345
+ connector: string;
9346
+ /**
9347
+ * Twilio Account SID. Required for outbound calls.
9348
+ * For inbound-only, this is extracted from the media stream event.
7359
9349
  */
7360
- private drainAudioBuffer;
9350
+ accountSid?: string;
7361
9351
  /**
7362
- * Push an audio event and wake up the consumer in wrap()
9352
+ * WebSocket server mode:
9353
+ * - 'standalone': adapter creates its own HTTP/WS server
9354
+ * - 'external': you provide handlers for your existing server
7363
9355
  */
7364
- private pushAudioEvent;
9356
+ mode?: 'standalone' | 'external';
9357
+ /** Port for standalone mode. Default: 3000 */
9358
+ port?: number;
9359
+ /** Path for voice webhook. Default: '/voice' */
9360
+ webhookPath?: string;
9361
+ /** Path for media stream WebSocket. Default: '/media-stream' */
9362
+ mediaStreamPath?: string;
7365
9363
  /**
7366
- * Wait until a new event is pushed to the audio buffer
9364
+ * Public URL where Twilio can reach this server.
9365
+ * Required for standalone mode and outbound calls.
9366
+ * Example: 'https://myserver.com' or 'https://abc123.ngrok.io'
7367
9367
  */
7368
- private waitForBufferNotify;
7369
- private waitForTTSSlot;
7370
- private releaseTTSSlot;
7371
- private waitForQueueSlot;
7372
- private releaseQueueWaiter;
7373
- private releaseAllWaiters;
7374
- private cleanup;
9368
+ publicUrl?: string;
7375
9369
  }
7376
9370
 
7377
9371
  /**
7378
- * Sentence boundary detection for voice pseudo-streaming.
7379
- * Splits streaming text deltas into speakable chunks.
9372
+ * VoiceBridge - Multi-session voice call manager
9373
+ *
9374
+ * Connects a telephony adapter to agents via voice pipelines.
9375
+ * Creates a fresh Agent and pipeline per call, manages concurrent sessions,
9376
+ * and fires lifecycle hooks.
9377
+ *
9378
+ * @example
9379
+ * ```typescript
9380
+ * const bridge = VoiceBridge.create({
9381
+ * agent: { connector: 'anthropic', model: 'claude-sonnet-4-6', tools: [...] },
9382
+ * pipeline: 'text',
9383
+ * stt: { connector: 'openai', model: 'whisper-1' },
9384
+ * tts: { connector: 'openai', model: 'tts-1', voice: 'nova' },
9385
+ * greeting: 'Hello! How can I help you today?',
9386
+ * hooks: {
9387
+ * onCallStart: async (session) => { console.log('Call from', session.from); },
9388
+ * onCallEnd: async (session, summary) => { console.log('Duration:', summary.duration); },
9389
+ * },
9390
+ * });
9391
+ *
9392
+ * // Attach to a telephony adapter
9393
+ * bridge.attach(twilioAdapter);
9394
+ * ```
7380
9395
  */
7381
9396
 
9397
+ interface VoiceBridgeEvents {
9398
+ 'session:created': (info: VoiceSessionInfo) => void;
9399
+ 'session:ended': (info: VoiceSessionInfo, summary: CallSummary) => void;
9400
+ 'transcript': (info: VoiceSessionInfo, entry: TranscriptMessage) => void;
9401
+ 'error': (error: Error, sessionId?: string) => void;
9402
+ }
9403
+ declare class VoiceBridge extends EventEmitter$1 {
9404
+ private config;
9405
+ private sessions;
9406
+ private callToSession;
9407
+ private pendingOutbound;
9408
+ private cleanupTimers;
9409
+ private endingSessions;
9410
+ private adapter;
9411
+ private destroyed;
9412
+ static create(config: VoiceBridgeConfig): VoiceBridge;
9413
+ private constructor();
9414
+ attach(adapter: ITelephonyAdapter): void;
9415
+ detach(): void;
9416
+ getActiveSessions(): VoiceSessionInfo[];
9417
+ getSession(sessionId: string): VoiceSessionInfo | null;
9418
+ get activeSessionCount(): number;
9419
+ hangup(sessionId: string): Promise<void>;
9420
+ /**
9421
+ * Initiate an outbound call.
9422
+ * The adapter places the call via the telephony provider. When the callee
9423
+ * answers and the media stream connects, the normal session lifecycle
9424
+ * (agent creation, pipeline, hooks) kicks in automatically.
9425
+ *
9426
+ * @returns callId from the telephony provider
9427
+ */
9428
+ makeCall(to: string, from: string): Promise<string>;
9429
+ private handleCallConnected;
9430
+ private handleCallAudio;
9431
+ private handleCallEnded;
9432
+ private handleMediaTimestamp;
9433
+ private handleAdapterError;
9434
+ private onCallConnected;
9435
+ private endSession;
9436
+ private createPipeline;
9437
+ private fireHook;
9438
+ destroy(): Promise<void>;
9439
+ }
9440
+
7382
9441
  /**
7383
- * Default chunking strategy that splits text at sentence boundaries.
9442
+ * VoiceSession - Per-call state machine
7384
9443
  *
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
9444
+ * Manages the lifecycle of a single voice call:
9445
+ * - State transitions (idle ringing connected → ... → ended)
9446
+ * - Turn counting
9447
+ * - Timing metrics
9448
+ * - Owns one Agent instance and one IVoicePipeline instance
7393
9449
  */
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;
9450
+
9451
+ interface VoiceSessionEvents {
9452
+ 'state:change': (prev: SessionState, next: SessionState, info: VoiceSessionInfo) => void;
9453
+ 'ended': (summary: CallSummary) => void;
9454
+ 'error': (error: Error) => void;
9455
+ }
9456
+ declare class VoiceSession extends EventEmitter$1 {
9457
+ readonly sessionId: string;
9458
+ readonly direction: CallDirection;
9459
+ readonly callId: string;
9460
+ readonly from: string;
9461
+ readonly to: string;
9462
+ readonly startedAt: Date;
9463
+ readonly metadata: Record<string, unknown>;
9464
+ private _state;
9465
+ private _endedAt?;
9466
+ private _turns;
9467
+ private _endReason;
9468
+ private _totalSttMs;
9469
+ private _totalTtsMs;
9470
+ private _totalAgentMs;
9471
+ private _agent;
9472
+ private _pipeline;
9473
+ private _maxDurationTimer;
9474
+ constructor(callInfo: IncomingCallInfo, direction?: CallDirection);
9475
+ get state(): SessionState;
9476
+ get turns(): number;
9477
+ get agent(): Agent | null;
9478
+ get pipeline(): IVoicePipeline | null;
7405
9479
  /**
7406
- * Track and remove fenced code blocks from the buffer.
7407
- * Text inside code blocks is discarded (not spoken).
9480
+ * Transition to a new state. Throws if the transition is invalid.
7408
9481
  */
7409
- private processCodeBlocks;
9482
+ transition(newState: SessionState): void;
7410
9483
  /**
7411
- * Find the position right after the next sentence boundary.
7412
- * Returns -1 if no complete sentence boundary found.
9484
+ * Increment the turn counter (called after each agent response completes)
7413
9485
  */
7414
- private findSentenceBoundary;
9486
+ incrementTurns(): void;
9487
+ addSttTime(ms: number): void;
9488
+ addTtsTime(ms: number): void;
9489
+ addAgentTime(ms: number): void;
7415
9490
  /**
7416
- * Check if the period at position `pos` is part of a known abbreviation.
9491
+ * Create and assign the agent for this call session.
7417
9492
  */
7418
- private isAbbreviation;
9493
+ createAgent(config: AgentConfig$1): Agent;
7419
9494
  /**
7420
- * Check if the period at position `pos` is a decimal point.
7421
- * e.g., 3.14, $1.50
9495
+ * Assign the voice pipeline for this call session.
7422
9496
  */
7423
- private isDecimalNumber;
9497
+ setPipeline(pipeline: IVoicePipeline): void;
7424
9498
  /**
7425
- * Check if the period at position `pos` is part of an ellipsis (...).
9499
+ * Set a maximum call duration timer.
9500
+ * When it fires, the session transitions to 'ending'.
7426
9501
  */
7427
- private isEllipsis;
9502
+ setMaxDuration(seconds: number): void;
7428
9503
  /**
7429
- * Split text that exceeds maxChunkLength at clause boundaries.
9504
+ * Get a read-only snapshot of the session state.
7430
9505
  */
7431
- private splitLongText;
9506
+ getInfo(): VoiceSessionInfo;
7432
9507
  /**
7433
- * Merge chunks that are shorter than minChunkLength with the next chunk.
9508
+ * Set the reason the call ended (before calling end()).
7434
9509
  */
7435
- private mergeSmallChunks;
9510
+ setEndReason(reason: CallEndReason): void;
7436
9511
  /**
7437
- * Strip markdown formatting from text for natural speech.
9512
+ * Get the call summary. Only meaningful after the session has ended.
7438
9513
  */
7439
- private cleanForSpeech;
9514
+ getSummary(): CallSummary;
9515
+ /**
9516
+ * End the session and clean up all resources.
9517
+ */
9518
+ end(reason?: CallEndReason): Promise<CallSummary>;
7440
9519
  }
7441
9520
 
7442
9521
  /**
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.
9522
+ * TextPipeline - STT Agent TTS voice pipeline
7448
9523
  *
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
- * });
9524
+ * Processes a voice call using the text-based approach:
9525
+ * 1. Accumulate audio frames from caller
9526
+ * 2. VAD detects end of speech
9527
+ * 3. STT transcribes accumulated audio to text
9528
+ * 4. Agent processes text (may call tools)
9529
+ * 5. Agent response streamed through VoiceStream (TTS)
9530
+ * 6. Audio frames sent back to caller
7455
9531
  *
7456
- * for await (const event of voiceStream.wrap(agent.stream('Hello'))) {
7457
- * if (isAudioChunkReady(event)) {
7458
- * queue.enqueue(event);
7459
- * }
7460
- * }
7461
- * ```
9532
+ * This pipeline works with ANY LLM - the agent handles text in/out,
9533
+ * and we handle the audio conversion on both sides.
7462
9534
  */
7463
9535
 
7464
- declare class AudioPlaybackQueue {
7465
- private buffer;
7466
- private nextPlayIndex;
7467
- private onReady;
7468
- constructor(onReady: AudioChunkPlaybackCallback);
9536
+ interface TextPipelineInitConfig {
9537
+ agent: Agent;
9538
+ session: VoiceSession;
9539
+ stt: TextPipelineConfig['stt'];
9540
+ tts: TextPipelineConfig['tts'];
9541
+ vad: IVoiceActivityDetector;
9542
+ interruptible: boolean;
9543
+ greeting?: string;
9544
+ hooks?: VoiceHooks;
9545
+ }
9546
+ declare class TextPipeline extends EventEmitter$1 implements IVoicePipeline {
9547
+ private agent;
9548
+ private session;
9549
+ private stt;
9550
+ private tts;
9551
+ private voiceStream;
9552
+ private vad;
9553
+ private hooks;
9554
+ private interruptible;
9555
+ private greeting?;
9556
+ private ttsVoice;
9557
+ private _state;
9558
+ private destroyed;
9559
+ private isProcessingUtterance;
9560
+ private utteranceBuffer;
9561
+ private utteranceStartTime;
9562
+ private currentStreamAbort;
9563
+ private audioChunkCount;
9564
+ constructor(config: TextPipelineInitConfig);
9565
+ init(_sessionInfo: VoiceSessionInfo): Promise<void>;
9566
+ /** Consecutive high-energy frames during speaking state (for barge-in) */
9567
+ private bargeInFrames;
9568
+ private bargeInDiagCounter;
9569
+ /** Energy threshold for barge-in during speaking (higher than normal to reject echo) */
9570
+ private static readonly BARGE_IN_ENERGY_THRESHOLD;
9571
+ /** Consecutive frames needed to confirm barge-in (not just a brief noise spike) */
9572
+ private static readonly BARGE_IN_FRAMES_REQUIRED;
9573
+ processAudio(frame: AudioFrame): void;
9574
+ /**
9575
+ * Calculate RMS energy of a single audio frame (for barge-in detection).
9576
+ */
9577
+ private calculateFrameEnergy;
9578
+ onSpeechStart(): void;
9579
+ onSpeechEnd(): Promise<void>;
9580
+ interrupt(): void;
9581
+ getState(): SessionState;
9582
+ on<K extends keyof VoicePipelineEvents>(event: K, handler: VoicePipelineEvents[K]): this;
9583
+ off<K extends keyof VoicePipelineEvents>(event: K, handler: VoicePipelineEvents[K]): this;
9584
+ destroy(): Promise<void>;
9585
+ private setState;
7469
9586
  /**
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.
9587
+ * Synthesize text to speech and emit audio frames.
9588
+ * Used for greeting and other non-agent audio.
7473
9589
  */
7474
- enqueue(event: AudioChunkReadyEvent): void;
9590
+ private synthesizeAndSend;
9591
+ }
9592
+
9593
+ /**
9594
+ * RealtimePipeline - OpenAI Realtime WebSocket voice-to-voice pipeline
9595
+ *
9596
+ * Connects directly to OpenAI's Realtime API for native audio-to-audio streaming.
9597
+ * Instead of STT → Agent → TTS, audio goes directly to/from the model over WebSocket.
9598
+ *
9599
+ * Features:
9600
+ * - Native voice-to-voice with <200ms latency
9601
+ * - Built-in server-side VAD (no EnergyVAD needed)
9602
+ * - Function calling via the same WebSocket
9603
+ * - Conversation transcript maintained for UI display
9604
+ * - G.711 μ-law 8kHz audio format (matches Twilio native)
9605
+ */
9606
+
9607
+ interface RealtimePipelineInitConfig {
9608
+ agentConfig: AgentConfig$1;
9609
+ session: VoiceSession;
9610
+ voice?: string;
9611
+ turnDetection?: 'server_vad' | 'none';
9612
+ vadThreshold?: number;
9613
+ silenceDurationMs?: number;
9614
+ inputTranscription?: boolean;
9615
+ transcriptionModel?: string;
9616
+ greeting?: string;
9617
+ interruptible?: boolean;
9618
+ hooks?: VoiceHooks;
9619
+ }
9620
+ declare class RealtimePipeline extends EventEmitter$1 implements IVoicePipeline {
9621
+ private config;
9622
+ private session;
9623
+ private toolManager;
9624
+ private tools;
9625
+ private ws;
9626
+ private state;
9627
+ private destroyed;
9628
+ private ignoringEvents;
9629
+ private sessionInfo;
9630
+ private transcript;
9631
+ private agentTranscriptBuffer;
9632
+ private pendingToolCalls;
9633
+ private isResponseActive;
9634
+ private currentResponseId;
9635
+ private currentAssistantItemId;
9636
+ private currentAssistantContentIndex;
9637
+ private responseStartTimestamp;
9638
+ private latestMediaTimestamp;
9639
+ private hasStartedAudioForCurrentResponse;
9640
+ private interruptingResponseId;
9641
+ private tailResponseId;
9642
+ private tailAssistantItemId;
9643
+ private tailAssistantContentIndex;
9644
+ private tailResponseStartTimestamp;
9645
+ private tailExpiresAt;
9646
+ constructor(config: RealtimePipelineInitConfig);
9647
+ init(sessionInfo: VoiceSessionInfo): Promise<void>;
9648
+ processAudio(frame: AudioFrame): void;
9649
+ onSpeechEnd(): Promise<void>;
9650
+ onSpeechStart(): void;
9651
+ interrupt(): void;
9652
+ onPlaybackAck(_ack: {
9653
+ name: string;
9654
+ playedMs: number;
9655
+ }): void;
9656
+ onTelephonyTimestamp(timestamp: number): void;
9657
+ getState(): SessionState;
9658
+ on<K extends keyof VoicePipelineEvents>(event: K, handler: VoicePipelineEvents[K]): this;
9659
+ off<K extends keyof VoicePipelineEvents>(event: K, handler: VoicePipelineEvents[K]): this;
7475
9660
  /**
7476
- * Reset the queue (e.g., on interruption or new stream).
9661
+ * Get the full conversation transcript for this session.
7477
9662
  */
9663
+ getTranscript(): TranscriptMessage[];
9664
+ destroy(): Promise<void>;
9665
+ private sendSessionUpdate;
9666
+ private handleServerEvent;
9667
+ private executeToolCall;
9668
+ private sendEvent;
9669
+ private setState;
9670
+ private getElapsedPlaybackMs;
9671
+ private getTailElapsedPlaybackMs;
9672
+ private clearPlaybackTailContext;
9673
+ private handleBargeIn;
9674
+ private isAssistantPlaybackActive;
9675
+ private isPlaybackTailActive;
9676
+ private truncateAssistantAudio;
9677
+ private emitError;
9678
+ private addTranscript;
9679
+ private fireHookSafe;
9680
+ }
9681
+
9682
+ /**
9683
+ * EnergyVAD - Simple energy-based Voice Activity Detection
9684
+ *
9685
+ * Detects speech start/end based on RMS energy threshold and timing.
9686
+ * Suitable for telephony audio where background noise is relatively low.
9687
+ *
9688
+ * Can be replaced with more sophisticated VAD (WebRTC VAD, Silero, etc.)
9689
+ * by implementing IVoiceActivityDetector.
9690
+ */
9691
+
9692
+ declare class EnergyVAD implements IVoiceActivityDetector {
9693
+ private config;
9694
+ private isSpeaking;
9695
+ private consecutiveSpeechFrames;
9696
+ private speechStartTime;
9697
+ private lastSpeechTime;
9698
+ private nonPcmWarned;
9699
+ constructor(config?: EnergyVADConfig);
9700
+ process(frame: AudioFrame): VADEvent;
7478
9701
  reset(): void;
7479
9702
  /**
7480
- * Number of chunks currently buffered waiting for earlier chunks.
9703
+ * Calculate RMS (Root Mean Square) energy of an audio frame.
9704
+ * Expects PCM 16-bit signed little-endian. Non-PCM formats produce
9705
+ * inaccurate results — the adapter should transcode to PCM first.
7481
9706
  */
7482
- get pendingCount(): number;
9707
+ private calculateRMS;
9708
+ }
9709
+
9710
+ /**
9711
+ * TwilioAdapter - Telephony adapter for Twilio Voice
9712
+ *
9713
+ * Handles:
9714
+ * - Inbound call webhooks (returns TwiML to connect Media Stream)
9715
+ * - Twilio Media Stream WebSocket protocol
9716
+ * - μ-law ↔ PCM transcoding
9717
+ * - Maps Twilio protocol to ITelephonyAdapter interface
9718
+ *
9719
+ * Usage modes:
9720
+ * 1. Standalone: adapter creates its own HTTP/WS server
9721
+ * 2. External: you get webhook/media handlers for your existing server
9722
+ *
9723
+ * @example Standalone
9724
+ * ```typescript
9725
+ * const adapter = TwilioAdapter.createStandalone({
9726
+ * connector: 'twilio',
9727
+ * port: 3000,
9728
+ * publicUrl: 'https://abc123.ngrok.io',
9729
+ * });
9730
+ * await adapter.start();
9731
+ * ```
9732
+ *
9733
+ * @example External (Express + ws)
9734
+ * ```typescript
9735
+ * const adapter = TwilioAdapter.create({ connector: 'twilio' });
9736
+ * app.post('/voice', adapter.webhookHandler());
9737
+ * wss.on('connection', (ws, req) => {
9738
+ * if (req.url === '/media-stream') adapter.handleMediaSocket(ws);
9739
+ * });
9740
+ * ```
9741
+ */
9742
+
9743
+ declare class TwilioAdapter extends EventEmitter$1 implements ITelephonyAdapter {
9744
+ private config;
9745
+ private connector;
9746
+ private streams;
9747
+ private streamSidToCallId;
9748
+ private pendingOutbound;
9749
+ private destroyed;
9750
+ private server;
9751
+ static create(config: TwilioAdapterConfig): TwilioAdapter;
9752
+ static createStandalone(config: TwilioAdapterConfig & {
9753
+ publicUrl: string;
9754
+ port?: number;
9755
+ }): TwilioAdapter;
9756
+ private constructor();
7483
9757
  /**
7484
- * The next chunk index expected for playback.
9758
+ * Make a Twilio REST API call with proper Basic Auth.
9759
+ *
9760
+ * Twilio requires HTTP Basic Auth = base64(AccountSid:AuthToken).
9761
+ * The Connector.fetch() doesn't support two-part Basic Auth natively,
9762
+ * so we construct it manually here.
9763
+ */
9764
+ private twilioFetch;
9765
+ start(): Promise<void>;
9766
+ stop(): Promise<void>;
9767
+ webhookHandler(): (req: any, res: any) => void;
9768
+ handleMediaSocket(ws: any): void;
9769
+ /** Counter for diagnostic logging (first few frames only) */
9770
+ private sendDiagCount;
9771
+ sendAudio(callId: string, frame: AudioFrame): void;
9772
+ clearAudio(callId: string): void;
9773
+ hangup(callId: string): Promise<void>;
9774
+ getActiveCalls(): string[];
9775
+ on<K extends keyof TelephonyAdapterEvents>(event: K, handler: TelephonyAdapterEvents[K]): this;
9776
+ off<K extends keyof TelephonyAdapterEvents>(event: K, handler: TelephonyAdapterEvents[K]): this;
9777
+ destroy(): Promise<void>;
9778
+ /**
9779
+ * Initiate an outbound call via Twilio REST API.
9780
+ * When the callee answers, Twilio hits /voice-outbound which returns
9781
+ * TwiML to connect a media stream (same pipeline as inbound).
9782
+ *
9783
+ * @returns The Twilio CallSid
7485
9784
  */
7486
- get nextExpectedIndex(): number;
7487
- private drain;
9785
+ makeCall(config: OutboundCallConfig): Promise<string>;
9786
+ /**
9787
+ * Returns a webhook handler for outbound calls (external mode).
9788
+ * When callee answers, Twilio POSTs to this endpoint.
9789
+ */
9790
+ outboundWebhookHandler(): (req: any, res: any) => void;
9791
+ private handleOutboundWebhookRequest;
9792
+ private handleWebhookRequest;
9793
+ private handleStreamStart;
9794
+ private handleStreamMedia;
9795
+ private handlePlaybackMark;
9796
+ private handleStreamStop;
9797
+ private cleanupStream;
7488
9798
  }
7489
9799
 
9800
+ /**
9801
+ * Audio codec utilities for Twilio integration
9802
+ *
9803
+ * Twilio Media Streams send/receive μ-law encoded audio at 8kHz mono.
9804
+ * OpenAI TTS outputs PCM 16-bit signed LE at 24kHz.
9805
+ *
9806
+ * μ-law encoder and decoder are line-by-line translations of the
9807
+ * Sun Microsystems / ITU-T G.711 reference C implementation.
9808
+ * Source: CCITT Rec. G.711 (1988), also used in FFmpeg, sox, libsndfile.
9809
+ */
9810
+ /**
9811
+ * Decode μ-law audio buffer to PCM 16-bit signed little-endian.
9812
+ *
9813
+ * @param mulaw - Buffer of μ-law encoded bytes (8kHz mono)
9814
+ * @returns Buffer of PCM 16-bit signed LE samples (2x the input length)
9815
+ */
9816
+ declare function mulawToPcm(mulaw: Buffer): Buffer;
9817
+ /**
9818
+ * Encode PCM 16-bit signed little-endian to μ-law.
9819
+ *
9820
+ * @param pcm - Buffer of PCM 16-bit signed LE samples
9821
+ * @returns Buffer of μ-law encoded bytes (half the input length)
9822
+ */
9823
+ declare function pcmToMulaw(pcm: Buffer): Buffer;
9824
+ /**
9825
+ * Resample PCM 16-bit audio.
9826
+ * Downsampling uses box filter (averaging) for anti-aliasing.
9827
+ * Upsampling uses linear interpolation.
9828
+ *
9829
+ * @param pcm - Input PCM 16-bit signed LE buffer
9830
+ * @param fromRate - Source sample rate (e.g., 24000)
9831
+ * @param toRate - Target sample rate (e.g., 8000)
9832
+ * @returns Resampled PCM 16-bit signed LE buffer
9833
+ */
9834
+ declare function resamplePcm(pcm: Buffer, fromRate: number, toRate: number): Buffer;
9835
+ /**
9836
+ * Convert Twilio μ-law 8kHz audio to PCM 16-bit at target sample rate.
9837
+ */
9838
+ declare function twilioToStt(mulaw: Buffer, targetRate?: number): Buffer;
9839
+ /**
9840
+ * Convert PCM 16-bit audio to Twilio μ-law 8kHz format.
9841
+ */
9842
+ declare function sttToTwilio(pcm: Buffer, sourceRate?: number): Buffer;
9843
+
7490
9844
  /**
7491
9845
  * SearchProvider - Unified search interface with connector support
7492
9846
  *
@@ -8251,6 +10605,35 @@ declare function documentToContent(result: DocumentResult, options?: DocumentToC
8251
10605
  */
8252
10606
  declare function readDocumentAsContent(source: DocumentSource | string, options?: DocumentReadOptions & DocumentToContentOptions): Promise<Content[]>;
8253
10607
 
10608
+ /**
10609
+ * FileUserPermissionRulesStorage - File-based storage for per-user permission rules.
10610
+ *
10611
+ * Path: ~/.oneringai/users/<userId>/permission_rules.json
10612
+ * Windows: %APPDATA%/oneringai/users/<userId>/permission_rules.json
10613
+ *
10614
+ * Same pattern as FileUserInfoStorage — atomic writes, userId sanitization.
10615
+ */
10616
+
10617
+ interface FileUserPermissionRulesStorageConfig {
10618
+ /** Override the base directory (default: ~/.oneringai/users) */
10619
+ baseDirectory?: string;
10620
+ /** Override the filename (default: permission_rules.json) */
10621
+ filename?: string;
10622
+ }
10623
+ declare class FileUserPermissionRulesStorage implements IUserPermissionRulesStorage {
10624
+ private readonly baseDirectory;
10625
+ private readonly filename;
10626
+ constructor(config?: FileUserPermissionRulesStorageConfig);
10627
+ private getUserDirectory;
10628
+ private getUserFilePath;
10629
+ load(userId: string | undefined): Promise<UserPermissionRule[] | null>;
10630
+ save(userId: string | undefined, rules: UserPermissionRule[]): Promise<void>;
10631
+ delete(userId: string | undefined): Promise<void>;
10632
+ exists(userId: string | undefined): Promise<boolean>;
10633
+ getPath(userId: string | undefined): string;
10634
+ private ensureDirectory;
10635
+ }
10636
+
8254
10637
  /**
8255
10638
  * Agent state entities for TaskAgent
8256
10639
  *
@@ -8557,6 +10940,8 @@ declare class FileContextStorage implements IContextStorage {
8557
10940
  private readonly indexPath;
8558
10941
  private readonly prettyPrint;
8559
10942
  private index;
10943
+ /** Async mutex to prevent concurrent read-modify-write corruption of the index */
10944
+ private _indexLock;
8560
10945
  /** History journal companion — appends full conversation history as JSONL */
8561
10946
  readonly journal: IHistoryJournal;
8562
10947
  constructor(config: FileContextStorageConfig);
@@ -8607,6 +10992,11 @@ declare class FileContextStorage implements IContextStorage {
8607
10992
  private loadRaw;
8608
10993
  private loadIndex;
8609
10994
  private saveIndex;
10995
+ /**
10996
+ * Acquire the index lock, run fn, then release.
10997
+ * Serializes all index mutations to prevent concurrent read-modify-write corruption.
10998
+ */
10999
+ private withIndexLock;
8610
11000
  private updateIndex;
8611
11001
  private removeFromIndex;
8612
11002
  private storedToIndexEntry;
@@ -8667,6 +11057,10 @@ declare function createFileContextStorage(agentId: string, options?: Omit<FileCo
8667
11057
  * ```
8668
11058
  */
8669
11059
 
11060
+ /**
11061
+ * Sanitize ID for use as a filename.
11062
+ * Same logic as FileContextStorage to ensure matching paths.
11063
+ */
8670
11064
  /**
8671
11065
  * File-based history journal using JSONL format.
8672
11066
  */
@@ -8941,6 +11335,10 @@ interface FileUserInfoStorageConfig {
8941
11335
  /** Override the filename (default: user_info.json) */
8942
11336
  filename?: string;
8943
11337
  }
11338
+ /**
11339
+ * Sanitize user ID for use as a directory name
11340
+ * Removes or replaces characters that are not safe for filenames
11341
+ */
8944
11342
  /**
8945
11343
  * File-based storage for user information
8946
11344
  *
@@ -9135,6 +11533,53 @@ declare class FileRoutineExecutionStorage implements IRoutineExecutionStorage {
9135
11533
  */
9136
11534
  declare function createFileRoutineExecutionStorage(config?: FileRoutineExecutionStorageConfig): FileRoutineExecutionStorage;
9137
11535
 
11536
+ /**
11537
+ * FileCorrelationStorage - File-based storage for correlation mappings
11538
+ *
11539
+ * Stores correlation entries as individual JSON files on disk.
11540
+ * Path: ~/.oneringai/correlations/<correlationId-hash>.json
11541
+ *
11542
+ * Features:
11543
+ * - Safe filename hashing for arbitrary correlation IDs
11544
+ * - Reverse index by sessionId for cleanup on resume
11545
+ * - Automatic expiry checking on resolve
11546
+ * - Atomic file operations (write to temp, then rename)
11547
+ */
11548
+
11549
+ /**
11550
+ * Configuration for FileCorrelationStorage
11551
+ */
11552
+ interface FileCorrelationStorageConfig {
11553
+ /** Override the base directory (default: ~/.oneringai/correlations) */
11554
+ baseDirectory?: string;
11555
+ }
11556
+ /**
11557
+ * File-based implementation of ICorrelationStorage
11558
+ */
11559
+ declare class FileCorrelationStorage implements ICorrelationStorage {
11560
+ private readonly baseDir;
11561
+ private _initialized;
11562
+ constructor(config?: FileCorrelationStorageConfig);
11563
+ private ensureDir;
11564
+ private getFilePath;
11565
+ save(correlationId: string, ref: SessionRef): Promise<void>;
11566
+ resolve(correlationId: string): Promise<SessionRef | null>;
11567
+ delete(correlationId: string): Promise<void>;
11568
+ exists(correlationId: string): Promise<boolean>;
11569
+ listBySession(sessionId: string): Promise<string[]>;
11570
+ listByAgent(agentId: string): Promise<CorrelationSummary[]>;
11571
+ pruneExpired(): Promise<number>;
11572
+ getPath(): string;
11573
+ /**
11574
+ * Read all stored correlation entries
11575
+ */
11576
+ private _readAll;
11577
+ }
11578
+ /**
11579
+ * Create a FileCorrelationStorage with default settings
11580
+ */
11581
+ declare function createFileCorrelationStorage(config?: FileCorrelationStorageConfig): FileCorrelationStorage;
11582
+
9138
11583
  /**
9139
11584
  * WorkingMemory class - manages indexed working memory for TaskAgent
9140
11585
  *
@@ -11128,10 +13573,11 @@ declare abstract class BaseProvider implements IProvider {
11128
13573
  protected getMaxRetries(): number;
11129
13574
  }
11130
13575
 
11131
- declare abstract class BaseTextProvider extends BaseProvider implements ITextProvider {
13576
+ declare abstract class BaseTextProvider extends BaseProvider implements ITextProvider, IDisposable {
11132
13577
  protected circuitBreaker?: CircuitBreaker;
11133
13578
  protected logger: FrameworkLogger;
11134
13579
  private _isObservabilityInitialized;
13580
+ private _isDestroyed;
11135
13581
  constructor(config: any);
11136
13582
  /**
11137
13583
  * Auto-initialize observability on first use (lazy initialization)
@@ -11160,11 +13606,20 @@ declare abstract class BaseTextProvider extends BaseProvider implements ITextPro
11160
13606
  * Normalize input to string (helper for providers that don't support complex input)
11161
13607
  */
11162
13608
  protected normalizeInputToString(input: string | any[]): string;
13609
+ /**
13610
+ * Map common HTTP error codes to typed provider errors.
13611
+ * Subclasses can override for vendor-specific error mapping and call super.mapError() as fallback.
13612
+ */
13613
+ protected mapError(error: unknown, providerName?: string): Error;
11163
13614
  /**
11164
13615
  * List available models from the provider's API.
11165
13616
  * Default returns empty array; providers override when they have SDK support.
11166
13617
  */
11167
13618
  listModels(): Promise<string[]>;
13619
+ /**
13620
+ * Check if the provider has been destroyed
13621
+ */
13622
+ get isDestroyed(): boolean;
11168
13623
  /**
11169
13624
  * Clean up provider resources (circuit breaker listeners, etc.)
11170
13625
  * Should be called when the provider is no longer needed.
@@ -12802,7 +15257,7 @@ declare function isBlockedCommand(command: string, config?: ShellToolConfig): {
12802
15257
  * Features:
12803
15258
  * - Configurable timeouts
12804
15259
  * - Output truncation for large outputs
12805
- * - Background execution support
15260
+ * - Background execution via BackgroundProcessManager
12806
15261
  * - Blocked command patterns for safety
12807
15262
  * - Working directory persistence
12808
15263
  */
@@ -12826,6 +15281,7 @@ interface BashArgs {
12826
15281
  declare function createBashTool(config?: ShellToolConfig): ToolFunction<BashArgs, BashResult>;
12827
15282
  /**
12828
15283
  * Get output from a background process
15284
+ * @deprecated Use BackgroundProcessManager.readOutput() or bg_process_output tool instead
12829
15285
  */
12830
15286
  declare function getBackgroundOutput(bgId: string): {
12831
15287
  found: boolean;
@@ -12834,6 +15290,7 @@ declare function getBackgroundOutput(bgId: string): {
12834
15290
  };
12835
15291
  /**
12836
15292
  * Kill a background process
15293
+ * @deprecated Use BackgroundProcessManager.kill() or bg_process_kill tool instead
12837
15294
  */
12838
15295
  declare function killBackgroundProcess(bgId: string): boolean;
12839
15296
  /**
@@ -14744,7 +17201,7 @@ declare const desktopTools: (ToolFunction<DesktopScreenshotArgs, DesktopScreensh
14744
17201
  * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
14745
17202
  *
14746
17203
  * Generated by: scripts/generate-tool-registry.ts
14747
- * Generated at: 2026-03-12T18:47:09.908Z
17204
+ * Generated at: 2026-03-17T09:34:42.832Z
14748
17205
  *
14749
17206
  * To regenerate: npm run generate:tools
14750
17207
  */
@@ -15473,4 +17930,4 @@ declare class EventEmitterTrigger implements IDisposable {
15473
17930
  get isDestroyed(): boolean;
15474
17931
  }
15475
17932
 
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 };
17933
+ export { AGENT_DEFINITION_FORMAT_VERSION, AIError, APPROVAL_STATE_VERSION, Agent, type AgentConfig$1 as AgentConfig, AgentContextNextGen, AgentContextNextGenConfig, type AgentDefinitionListOptions, type AgentDefinitionMetadata, type AgentDefinitionSummary, type AgentEventListener, AgentEvents, type AgentFilter, type AgentInfo, type AgentInspection, type AgentMetrics, type AgentPermissionsConfig, type AgentPolicyConfig, AgentRegistry, type AgentRegistryEvents, type AgentRegistryStats, AgentResponse, type AgentSessionConfig, type AgentState, type AgentStatus, type AgentTypeConfig, type ApprovalCacheEntry, type ApprovalDecision, type ApprovalRequestContext, ApproximateTokenEstimator, AsyncToolConfig, type AudioChunkPlaybackCallback, AudioChunkReadyEvent, type AudioEncoding, AudioFormat, type AudioFrame, 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, type CallDirection, type CallEndReason, type CallSummary, 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 CorrelationListOptions, type CorrelationSummary, 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, EnergyVAD, type EnergyVADConfig, 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, FileCorrelationStorage, type FileCorrelationStorageConfig, 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, FileUserPermissionRulesStorage, 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, IBaseModelDescription, type ICapabilityProvider, type IChunkingStrategy, ICompactionStrategy, IConnectorAccessPolicy, type IConnectorConfigStorage, IConnectorRegistry, type IContextCompactor, type IContextComponent, IContextPluginNextGen, type IContextSnapshot, IContextStorage, type IContextStrategy, type ICorrelationStorage, type ICustomToolStorage, type IDesktopDriver, IDisposable, type IDocumentTransformer, type IFormatHandler, IHistoryJournal, type IHistoryManager, type IHistoryManagerConfig, type IHistoryStorage, IImageProvider, type IMCPClient, type IMediaStorage as IMediaOutputHandler, type IMediaStorage, type IMemoryStorage, type IPermissionPolicy, type IPersistentInstructionsStorage, type IPlanStorage, type IPluginSnapshot, IProvider, type IResearchSource, type IRoutineDefinitionStorage, type IRoutineExecutionStorage, type ISTTModelDescription, type IScheduler, type IScrapeProvider, type ISearchProvider, type ISpeechToTextProvider, IStoreHandler, type IStreamingTextToSpeechProvider, type ITTSModelDescription, type ITelephonyAdapter, ITextProvider, type ITextToSpeechProvider, ITokenEstimator$1 as ITokenEstimator, ITokenStorage, type IToolExecutionPipeline, type IToolExecutionPlugin, type IToolExecutor, type IToolSnapshot, type IUserInfoStorage, type IUserPermissionRulesStorage, type IVideoModelDescription, type IVideoProvider, type IViewContextComponent, type IViewContextData, type IVoiceActivityDetector, IVoiceInfo, type IVoicePipeline, type ImageFilterOptions, type InContextEntry, type InContextMemoryConfig, InContextMemoryPluginNextGen, type InContextPriority, InMemoryAgentStateStorage, InMemoryHistoryStorage, InMemoryMetrics, InMemoryPlanStorage, InMemoryStorage, type IncomingCallInfo, 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, type OrchestrationToolsContext, type OrchestratorConfig, type OutboundCallConfig, OutputItem, ParallelTasksError, PendingAsyncTool, type PermissionAuditEntry, type PermissionCheckContext, type PermissionCheckResult, type PermissionManagerEvent, PermissionPolicyManager, type PermissionPolicyManagerConfig, type PermissionScope, type PersistentInstructionsConfig, PersistentInstructionsPluginNextGen, type PieceMetadata, type PipelineConfig, type Plan, type PlanConcurrency, type PlanInput, type PlanStatus, PlanningAgent, type PlanningAgentConfig, PluginConfigs, type PluginExecutionContext, type PluginFactory, type PluginFactoryContext, type PluginRegisterOptions, PluginRegistry, type PluginRegistryEntry, type PluginRegistryInfo, type PolicyChainConfig, type PolicyCheckResult, type PolicyContext, type PolicyDecision, type PolicyManagerEvents, PreparedContext, ProviderAuthError, ProviderCapabilities, ProviderConfigAgent, ProviderContextLengthError, ProviderError, ProviderErrorMapper, ProviderNotFoundError, ProviderRateLimitError, ROUTINE_KEYS, RapidAPIProvider, RateLimitError, type RateLimiterConfig, type RateLimiterMetrics, type ReadFileResult, RealtimePipeline, type RealtimePipelineConfig, type AgentStatus$1 as RegistryAgentStatus, type FetchOptions as ResearchFetchOptions, type ResearchFinding, type ResearchPlan, type ResearchProgress, type ResearchQuery, type ResearchResult, type SearchOptions as ResearchSearchOptions, type SearchResponse as ResearchSearchResponse, ResolvedContextFeatures, 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 SerializedSharedWorkspaceState, type SerializedToolState, type SerializedUserInfoState, type SerializedWorkingMemoryState, SerperProvider, ServiceCategory, type ServiceToolFactory, type SessionRef, type SessionState, type SharedWorkspaceConfig, type SharedWorkspaceEntry, SharedWorkspacePluginNextGen, type ShellToolConfig, type SimpleIcon, SimpleScheduler, type SimpleVideoGenerateOptions, type SourceCapabilities, type SourceResult, SpeechToText, type SpeechToTextConfig, type StdioTransportConfig, type StorageConfig, type StorageContext, StorageRegistry, StoreActionResult, StoreDeleteResult, StoreEntrySchema, StoreGetResult, StoreListResult, StoreSetResult, StoreToolsManager, type StoredAgentDefinition, type StoredAgentType, type StoredConnectorConfig, StoredContextSession, type StoredToken, type StrategyInfo, StrategyRegistry, type StrategyRegistryEntry, StreamEvent, StreamEventType, StreamHelpers, StreamState, type SubRoutineSpec, SummarizeCompactor, SuspendSignal, type SuspendSignalOptions, 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 TelephonyAdapterEvents, type TemplateCredentials, TextGenerateOptions, TextPipeline, type TextPipelineConfig, 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 TranscriptMessage, type TransportConfig, TruncateCompactor, TwilioAdapter, type TwilioAdapterConfig, type UserInfoEntry, type UserInfoPluginConfig, UserInfoPluginNextGen, type UserPermissionRule, UserPermissionRulesEngine, type VADEvent, 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, VoiceBridge, type VoiceBridgeConfig, type VoiceBridgeEvents, type VoiceHooks, type VoicePipelineEvents, VoiceSession, type VoiceSessionEvents, type VoiceSessionInfo, VoiceStream, type VoiceStreamConfig, type VoiceStreamEvents, type WordTimestamp, WorkingMemory, WorkingMemoryAccess, WorkingMemoryConfig, type WorkingMemoryEvents, type WorkingMemoryPluginConfig, WorkingMemoryPluginNextGen, type WorkspaceLogEntry, type WriteFileResult, addJitter, allVendorTemplates, authenticatedFetch, backoffSequence, backoffWait, bash, buildAuthConfig, buildEndpointWithQuery, buildOrchestrationTools, buildQueryString, buildWorkspaceDelta, 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, createFileCorrelationStorage, createFileCustomToolStorage, createFileMediaStorage, createFileRoutineDefinitionStorage, createFileRoutineExecutionStorage, createFindMeetingSlotsTool, createGetMeetingTranscriptTool, createGetPRTool, createGitHubReadFileTool, createGlobTool, createGrepTool, createImageGenerationTool, createImageProvider, createListBranchesTool, createListDirectoryTool, createMeetingTool, createMessageWithImages, createMetricsCollector, createMicrosoftListFilesTool, createMicrosoftReadFileTool, createMicrosoftSearchFilesTool, createOrchestrator, 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, mulawToPcm, normalizeEmails, parseKeyCombo, parseRepository, pcmToMulaw, readClipboardImage, readDocumentAsContent, readFile, registerScrapeProvider, resamplePcm, resetDefaultDriver, resolveConnector, resolveDependencies, resolveFileEndpoints, resolveFlowSource, resolveMaxContextTokens, resolveMeetingId, resolveModelCapabilities, resolveRepository, resolveTemplates, retryWithBackoff, sanitizeToolName, setMediaOutputHandler, setMediaStorage, setMetricsCollector, simpleTokenEstimator, sttToTwilio, toConnectorOptions, toolRegistry, index as tools, twilioToStt, updateTaskStatus, validatePath, writeFile };