@everworker/oneringai 0.4.7 → 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 +425 -45
  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 +17 -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 +17 -0
  9. package/dist/capabilities/agents/index.js.map +1 -1
  10. package/dist/capabilities/images/index.cjs +273 -16
  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 +273 -16
  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-Blci0FEd.d.ts → index-hmTj59TM.d.ts} +543 -36
  19. package/dist/{index-D8RCwpK9.d.cts → index-t4cRhBZW.d.cts} +543 -36
  20. package/dist/index.cjs +19916 -7155
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +7807 -5065
  23. package/dist/index.d.ts +7807 -5065
  24. package/dist/index.js +19377 -6645
  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
@@ -98,6 +98,148 @@ interface ReasoningItem {
98
98
  type InputItem = Message | CompactionItem;
99
99
  type OutputItem = Message | CompactionItem | ReasoningItem;
100
100
 
101
+ /**
102
+ * IHistoryJournal - Interface for append-only conversation history logging
103
+ *
104
+ * Provides a durable, append-only log of all conversation messages,
105
+ * independent of context compaction. While the agent's working window
106
+ * (_conversation) may be compacted to fit the LLM context, the journal
107
+ * preserves the full conversation history on disk/database.
108
+ *
109
+ * The journal is a companion capability of IContextStorage — storage
110
+ * implementations that support history logging expose it via the
111
+ * `journal` property. Consumers never configure the journal separately;
112
+ * it comes for free with the storage backend.
113
+ *
114
+ * Access patterns:
115
+ * - **Write**: append-only, per-message, fire-and-forget (non-blocking)
116
+ * - **Read**: on-demand, explicit (never loaded automatically)
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * // File storage → FileHistoryJournal (JSONL files)
121
+ * const storage = new FileContextStorage({ agentId: 'my-agent' });
122
+ * storage.journal.append('session-1', [entry]);
123
+ *
124
+ * // Mongo storage → MongoHistoryJournal (collection)
125
+ * const storage = new MongoContextStorage({ agentId: 'my-agent', db });
126
+ * storage.journal.append('session-1', [entry]);
127
+ *
128
+ * // Reading history (on-demand, explicit)
129
+ * const entries = await storage.journal.read('session-1', { limit: 50 });
130
+ * const total = await storage.journal.count('session-1');
131
+ * ```
132
+ */
133
+
134
+ /**
135
+ * Type of history entry, derived from the message's role/purpose.
136
+ */
137
+ type HistoryEntryType = 'user' | 'assistant' | 'tool_result' | 'system';
138
+ /**
139
+ * A single entry in the history journal.
140
+ *
141
+ * Wraps an InputItem with metadata for ordering and filtering.
142
+ * The `item` field is the exact InputItem as it was added to the conversation,
143
+ * preserving full fidelity (including __images, tool_use_id, etc.).
144
+ */
145
+ interface HistoryEntry {
146
+ /** When this entry was recorded (epoch ms) */
147
+ timestamp: number;
148
+ /** Entry type for filtering */
149
+ type: HistoryEntryType;
150
+ /** The actual conversation item (Message or CompactionItem) */
151
+ item: InputItem;
152
+ /**
153
+ * Monotonically increasing turn counter.
154
+ * A "turn" is one user message + one assistant response (+ any tool calls in between).
155
+ * Useful for grouping related messages and pagination.
156
+ */
157
+ turnIndex: number;
158
+ }
159
+ /**
160
+ * Options for reading history entries.
161
+ */
162
+ interface HistoryReadOptions {
163
+ /** Skip this many entries from the start */
164
+ offset?: number;
165
+ /** Maximum number of entries to return */
166
+ limit?: number;
167
+ /** Filter by entry type(s) */
168
+ types?: HistoryEntryType[];
169
+ /** Only entries after this timestamp (epoch ms, inclusive) */
170
+ after?: number;
171
+ /** Only entries before this timestamp (epoch ms, inclusive) */
172
+ before?: number;
173
+ /** Only entries from this turn index onwards (inclusive) */
174
+ fromTurn?: number;
175
+ /** Only entries up to this turn index (inclusive) */
176
+ toTurn?: number;
177
+ }
178
+ /**
179
+ * Append-only history journal for conversation persistence.
180
+ *
181
+ * Implementations:
182
+ * - FileHistoryJournal: JSONL files at ~/.oneringai/agents/<agentId>/sessions/<sessionId>.history.jsonl
183
+ * - (Future) MongoHistoryJournal: MongoDB collection
184
+ * - (Future) RedisHistoryJournal: Redis Streams
185
+ */
186
+ interface IHistoryJournal {
187
+ /**
188
+ * Append entries to the journal.
189
+ *
190
+ * This is the primary write operation, called on every addUserMessage(),
191
+ * addAssistantResponse(), and addToolResults(). Should be fast (append-only).
192
+ *
193
+ * @param sessionId - Session to append to
194
+ * @param entries - One or more history entries to append
195
+ */
196
+ append(sessionId: string, entries: HistoryEntry[]): Promise<void>;
197
+ /**
198
+ * Read history entries with optional filtering and pagination.
199
+ *
200
+ * Entries are returned in chronological order (oldest first).
201
+ *
202
+ * @param sessionId - Session to read from
203
+ * @param options - Filtering and pagination options
204
+ * @returns Array of history entries
205
+ */
206
+ read(sessionId: string, options?: HistoryReadOptions): Promise<HistoryEntry[]>;
207
+ /**
208
+ * Get the total number of entries in the journal.
209
+ *
210
+ * @param sessionId - Session to count
211
+ * @returns Number of entries (0 if session has no journal)
212
+ */
213
+ count(sessionId: string): Promise<number>;
214
+ /**
215
+ * Delete all history for a session.
216
+ *
217
+ * Called when a session is deleted via IContextStorage.delete().
218
+ *
219
+ * @param sessionId - Session to clear
220
+ */
221
+ clear(sessionId: string): Promise<void>;
222
+ /**
223
+ * Stream history entries for large histories.
224
+ *
225
+ * Optional — implementations may omit this if streaming isn't practical
226
+ * (e.g., in-memory storage). Callers should fall back to read() with
227
+ * pagination if stream() is not available.
228
+ *
229
+ * @param sessionId - Session to stream
230
+ * @param options - Same filtering options as read()
231
+ * @returns AsyncIterable of history entries in chronological order
232
+ */
233
+ stream?(sessionId: string, options?: HistoryReadOptions): AsyncIterable<HistoryEntry>;
234
+ /**
235
+ * Get a human-readable location string for debugging/display.
236
+ *
237
+ * @param sessionId - Session ID
238
+ * @returns Location string (file path, MongoDB URI, etc.)
239
+ */
240
+ getLocation?(sessionId: string): string;
241
+ }
242
+
101
243
  /**
102
244
  * Memory entities for WorkingMemory
103
245
  *
@@ -373,6 +515,10 @@ interface ToolContext {
373
515
  identities?: AuthIdentity[];
374
516
  /** Connector registry scoped to this agent's allowed connectors and userId */
375
517
  connectorRegistry?: IConnectorRegistry;
518
+ /** User roles for permission policy evaluation */
519
+ roles?: string[];
520
+ /** Session ID for approval cache scoping */
521
+ sessionId?: string;
376
522
  /** Working memory access (if agent has memory feature enabled) */
377
523
  memory?: WorkingMemoryAccess;
378
524
  /** Abort signal for cancellation */
@@ -443,6 +589,47 @@ interface ToolExecutionContext {
443
589
  pendingNonBlocking: Set<string>;
444
590
  completedResults: Map<string, ToolResult>;
445
591
  }
592
+ /**
593
+ * Configuration for async (non-blocking) tool behavior
594
+ */
595
+ interface AsyncToolConfig {
596
+ /**
597
+ * If true, the agent automatically re-enters the agentic loop
598
+ * when async tool results arrive. If false, results are queued
599
+ * and the caller must call `continueWithAsyncResults()` manually.
600
+ * @default true
601
+ */
602
+ autoContinue?: boolean;
603
+ /**
604
+ * Window in ms to batch multiple async results before triggering
605
+ * a continuation. If multiple async tools complete within this window,
606
+ * their results are delivered together in a single user message.
607
+ * @default 500
608
+ */
609
+ batchWindowMs?: number;
610
+ /**
611
+ * Timeout in ms for async tool execution. If a tool doesn't complete
612
+ * within this window, it's treated as a timeout error.
613
+ * @default 300000 (5 minutes)
614
+ */
615
+ asyncTimeout?: number;
616
+ }
617
+ /**
618
+ * Status of a pending async tool execution
619
+ */
620
+ type PendingAsyncToolStatus = 'running' | 'completed' | 'failed' | 'timeout' | 'cancelled';
621
+ /**
622
+ * Tracks a single async tool execution in flight
623
+ */
624
+ interface PendingAsyncTool {
625
+ toolCallId: string;
626
+ toolName: string;
627
+ args: Record<string, unknown>;
628
+ startTime: number;
629
+ status: PendingAsyncToolStatus;
630
+ result?: ToolResult;
631
+ error?: Error;
632
+ }
446
633
  /**
447
634
  * Output handling hints for context management
448
635
  */
@@ -723,6 +910,21 @@ interface IContextStorage {
723
910
  * Falls back to getPath() if not implemented.
724
911
  */
725
912
  getLocation?(): string;
913
+ /**
914
+ * History journal companion for full conversation logging.
915
+ *
916
+ * When present, AgentContextNextGen automatically appends every message
917
+ * to the journal (append-only, fire-and-forget). The journal is never
918
+ * affected by compaction, preserving full conversation history.
919
+ *
920
+ * Storage implementations create the appropriate journal for their backend:
921
+ * - FileContextStorage → FileHistoryJournal (JSONL files)
922
+ * - MongoContextStorage → MongoHistoryJournal (collection)
923
+ *
924
+ * Consumers never configure the journal separately — it comes for free
925
+ * with the storage backend.
926
+ */
927
+ readonly journal?: IHistoryJournal;
726
928
  }
727
929
  /**
728
930
  * Options for listing sessions
@@ -1055,12 +1257,6 @@ declare class ToolCatalogRegistry {
1055
1257
  static reset(): void;
1056
1258
  }
1057
1259
 
1058
- /**
1059
- * AgentContextNextGen - Type Definitions
1060
- *
1061
- * Clean, minimal type definitions for the next-generation context manager.
1062
- */
1063
-
1064
1260
  /**
1065
1261
  * A single auth identity: connector + optional account alias.
1066
1262
  *
@@ -1404,6 +1600,140 @@ interface IContextPluginNextGen {
1404
1600
  */
1405
1601
  restoreState(state: unknown): void;
1406
1602
  }
1603
+ /**
1604
+ * Describes a store's schema for dynamic tool description generation.
1605
+ * The `descriptionFactory` on each store tool uses this to build
1606
+ * a comparison table so the LLM knows which store to use.
1607
+ */
1608
+ interface StoreEntrySchema {
1609
+ /** Short identifier used as the `store` parameter value (e.g., "memory", "context") */
1610
+ storeId: string;
1611
+ /** Human-readable store name (e.g., "Working Memory", "Live Context") */
1612
+ displayName: string;
1613
+ /** One-line description of what this store holds */
1614
+ description: string;
1615
+ /**
1616
+ * "Use for:" guidance — tells the LLM when to pick this store.
1617
+ * Should include explicit "NOT for:" guidance referencing other stores.
1618
+ */
1619
+ usageHint: string;
1620
+ /**
1621
+ * Human-readable description of the data fields accepted by storeSet.
1622
+ * Shown in the store_set tool description. One line per field.
1623
+ * Example: "description (required): Brief description of the data"
1624
+ */
1625
+ setDataFields: string;
1626
+ /**
1627
+ * Available actions for store_action, keyed by action name.
1628
+ * If undefined or empty, this store has no actions.
1629
+ */
1630
+ actions?: Record<string, {
1631
+ /** What this action does */
1632
+ description: string;
1633
+ /** Human-readable params description */
1634
+ paramsDescription?: string;
1635
+ /** If true, requires confirm: true parameter */
1636
+ destructive?: boolean;
1637
+ }>;
1638
+ }
1639
+ /**
1640
+ * Result types for store operations.
1641
+ * These are intentionally loose (Record-based) to accommodate
1642
+ * store-specific fields in responses.
1643
+ */
1644
+ interface StoreGetResult {
1645
+ found: boolean;
1646
+ key?: string;
1647
+ /** Single entry data (when key provided) */
1648
+ entry?: Record<string, unknown>;
1649
+ /** All entries (when no key provided) */
1650
+ entries?: Array<Record<string, unknown>>;
1651
+ }
1652
+ interface StoreSetResult {
1653
+ success: boolean;
1654
+ key: string;
1655
+ message?: string;
1656
+ [k: string]: unknown;
1657
+ }
1658
+ interface StoreDeleteResult {
1659
+ deleted: boolean;
1660
+ key: string;
1661
+ }
1662
+ interface StoreListResult {
1663
+ entries: Array<Record<string, unknown>>;
1664
+ total?: number;
1665
+ }
1666
+ interface StoreActionResult {
1667
+ success: boolean;
1668
+ action: string;
1669
+ [k: string]: unknown;
1670
+ }
1671
+ /**
1672
+ * Interface for plugins that provide CRUD storage.
1673
+ *
1674
+ * When a plugin implements both `IContextPluginNextGen` and `IStoreHandler`,
1675
+ * it automatically gets the 5 generic `store_*` tools — no tool creation needed.
1676
+ *
1677
+ * ## How to implement a custom CRUD plugin
1678
+ *
1679
+ * 1. Create a class that extends `BasePluginNextGen` and implements `IStoreHandler`
1680
+ * 2. Implement `getStoreSchema()` — describes your store for tool descriptions
1681
+ * 3. Implement the 5 handler methods (storeGet, storeSet, storeDelete, storeList)
1682
+ * 4. Optionally implement `storeAction()` for non-CRUD operations
1683
+ * 5. Write `getInstructions()` — explains when to use YOUR store vs others
1684
+ * 6. Register with `ctx.registerPlugin(yourPlugin)` — store tools auto-include it
1685
+ *
1686
+ * Your plugin does NOT need to define any tools via `getTools()`.
1687
+ * The `StoreToolsManager` creates the 5 `store_*` tools once and routes
1688
+ * calls to the correct handler based on the `store` parameter.
1689
+ *
1690
+ * @example
1691
+ * ```typescript
1692
+ * class NotesPlugin extends BasePluginNextGen implements IStoreHandler {
1693
+ * readonly name = 'notes';
1694
+ * private notes = new Map<string, { text: string; tag?: string }>();
1695
+ *
1696
+ * getStoreSchema(): StoreEntrySchema {
1697
+ * return {
1698
+ * storeId: 'notes',
1699
+ * displayName: 'Notes',
1700
+ * description: 'Simple text notes with optional tags',
1701
+ * usageHint: 'Use for: quick notes. NOT for structured data (use "memory").',
1702
+ * setDataFields: 'text (required): Note content\ntag?: Optional category tag',
1703
+ * };
1704
+ * }
1705
+ *
1706
+ * async storeGet(key?: string) { ... }
1707
+ * async storeSet(key: string, data: Record<string, unknown>) { ... }
1708
+ * async storeDelete(key: string) { ... }
1709
+ * async storeList(filter?: Record<string, unknown>) { ... }
1710
+ *
1711
+ * getInstructions() {
1712
+ * return 'Store name: "notes". Use store_set("notes", key, { text, tag? }).';
1713
+ * }
1714
+ * async getContent() { ... }
1715
+ * getContents() { return Object.fromEntries(this.notes); }
1716
+ * }
1717
+ * ```
1718
+ */
1719
+ interface IStoreHandler {
1720
+ /** Return the store's schema for dynamic tool descriptions */
1721
+ getStoreSchema(): StoreEntrySchema;
1722
+ /** Get one entry by key, or all entries if key is undefined */
1723
+ storeGet(key?: string, context?: ToolContext): Promise<StoreGetResult>;
1724
+ /** Create or update an entry */
1725
+ storeSet(key: string, data: Record<string, unknown>, context?: ToolContext): Promise<StoreSetResult>;
1726
+ /** Delete an entry by key */
1727
+ storeDelete(key: string, context?: ToolContext): Promise<StoreDeleteResult>;
1728
+ /** List entries with optional filter */
1729
+ storeList(filter?: Record<string, unknown>, context?: ToolContext): Promise<StoreListResult>;
1730
+ /** Execute a store-specific action (optional — only needed if store has actions) */
1731
+ storeAction?(action: string, params?: Record<string, unknown>, context?: ToolContext): Promise<StoreActionResult>;
1732
+ }
1733
+ /**
1734
+ * Type guard to check if a plugin implements IStoreHandler.
1735
+ */
1736
+ declare function isStoreHandler(plugin: IContextPluginNextGen): plugin is IContextPluginNextGen & IStoreHandler;
1407
1737
  /**
1408
1738
  * Token budget breakdown - clear and simple
1409
1739
  */
@@ -1470,7 +1800,11 @@ interface OversizedInputResult {
1470
1800
  /**
1471
1801
  * Feature flags for enabling/disabling plugins
1472
1802
  */
1473
- interface ContextFeatures {
1803
+ /**
1804
+ * Known feature flags for built-in plugins (provides autocomplete/docs).
1805
+ * External plugins register via PluginRegistry and use arbitrary string keys.
1806
+ */
1807
+ interface KnownContextFeatures {
1474
1808
  /** Enable WorkingMemory plugin (default: true) */
1475
1809
  workingMemory?: boolean;
1476
1810
  /** Enable InContextMemory plugin (default: false) */
@@ -1481,44 +1815,56 @@ interface ContextFeatures {
1481
1815
  userInfo?: boolean;
1482
1816
  /** Enable ToolCatalog plugin for dynamic tool loading/unloading (default: false) */
1483
1817
  toolCatalog?: boolean;
1818
+ /** Enable SharedWorkspace plugin for multi-agent coordination (default: false) */
1819
+ sharedWorkspace?: boolean;
1484
1820
  }
1485
1821
  /**
1486
- * Default feature configuration
1822
+ * Feature flags for enabling/disabling plugins.
1823
+ * Known keys provide autocomplete; arbitrary string keys are also accepted
1824
+ * for externally registered plugins (via PluginRegistry).
1487
1825
  */
1488
- declare const DEFAULT_FEATURES: Required<ContextFeatures>;
1826
+ type ContextFeatures = KnownContextFeatures & {
1827
+ [key: string]: boolean | undefined;
1828
+ };
1829
+ /**
1830
+ * Resolved features — all known keys guaranteed present, plus any extras.
1831
+ * Used internally after merging with DEFAULT_FEATURES.
1832
+ */
1833
+ type ResolvedContextFeatures = Required<KnownContextFeatures> & Record<string, boolean>;
1834
+ /**
1835
+ * Default feature configuration for built-in plugins.
1836
+ */
1837
+ declare const DEFAULT_FEATURES: Required<KnownContextFeatures>;
1489
1838
  /**
1490
1839
  * Plugin configurations for auto-initialization.
1491
1840
  * When features are enabled, plugins are created with these configs.
1492
1841
  * The config shapes match each plugin's constructor parameter.
1493
1842
  */
1494
- interface PluginConfigs {
1495
- /**
1496
- * Working memory plugin config (used when features.workingMemory=true).
1497
- * See WorkingMemoryPluginConfig for full options.
1498
- */
1843
+ /**
1844
+ * Known plugin configurations for built-in plugins (provides autocomplete/docs).
1845
+ */
1846
+ interface KnownPluginConfigs {
1847
+ /** Working memory plugin config. See WorkingMemoryPluginConfig. */
1499
1848
  workingMemory?: Record<string, unknown>;
1500
- /**
1501
- * In-context memory plugin config (used when features.inContextMemory=true).
1502
- * See InContextMemoryConfig for full options.
1503
- */
1849
+ /** In-context memory plugin config. See InContextMemoryConfig. */
1504
1850
  inContextMemory?: Record<string, unknown>;
1505
- /**
1506
- * Persistent instructions plugin config (used when features.persistentInstructions=true).
1507
- * Note: agentId is auto-filled from context config if not provided.
1508
- * See PersistentInstructionsConfig for full options.
1509
- */
1851
+ /** Persistent instructions plugin config. See PersistentInstructionsConfig. Note: agentId auto-filled. */
1510
1852
  persistentInstructions?: Record<string, unknown>;
1511
- /**
1512
- * User info plugin config (used when features.userInfo=true).
1513
- * See UserInfoPluginConfig for full options.
1514
- */
1853
+ /** User info plugin config. See UserInfoPluginConfig. */
1515
1854
  userInfo?: Record<string, unknown>;
1516
- /**
1517
- * Tool catalog plugin config (used when features.toolCatalog=true).
1518
- * See ToolCatalogPluginConfig for full options.
1519
- */
1855
+ /** Tool catalog plugin config. See ToolCatalogPluginConfig. */
1520
1856
  toolCatalog?: Record<string, unknown>;
1857
+ /** Shared workspace plugin config. See SharedWorkspaceConfig. */
1858
+ sharedWorkspace?: Record<string, unknown>;
1521
1859
  }
1860
+ /**
1861
+ * Plugin configurations for auto-initialization.
1862
+ * Known keys provide autocomplete; arbitrary string keys accepted
1863
+ * for externally registered plugins (via PluginRegistry).
1864
+ */
1865
+ type PluginConfigs = KnownPluginConfigs & {
1866
+ [key: string]: Record<string, unknown> | undefined;
1867
+ };
1522
1868
  /**
1523
1869
  * AgentContextNextGen configuration
1524
1870
  */
@@ -1569,6 +1915,13 @@ interface AgentContextNextGenConfig {
1569
1915
  * Default: 0 (disabled - relies on each tool's own timeout)
1570
1916
  */
1571
1917
  toolExecutionTimeout?: number;
1918
+ /**
1919
+ * Filter which message types are written to the history journal.
1920
+ * When set, only entries matching these types are appended.
1921
+ * Default: undefined (all types journaled).
1922
+ * Example: ['user', 'assistant'] to exclude tool_result entries.
1923
+ */
1924
+ journalFilter?: HistoryEntryType[];
1572
1925
  }
1573
1926
  /**
1574
1927
  * Default configuration values
@@ -1674,6 +2027,12 @@ interface CompactionContext {
1674
2027
  readonly plugins: ReadonlyArray<IContextPluginNextGen>;
1675
2028
  /** Strategy name for logging */
1676
2029
  readonly strategyName: string;
2030
+ /**
2031
+ * Describe a tool call using the tool's describeCall function.
2032
+ * Returns a human-readable summary of the tool call args (e.g., "src/core/Agent.ts [lines 100-200]").
2033
+ * Returns undefined if the tool is not found or has no describeCall.
2034
+ */
2035
+ describeToolCall?(toolName: string, toolArgs: unknown): string | undefined;
1677
2036
  /**
1678
2037
  * Remove messages by indices.
1679
2038
  * Handles tool pair preservation internally.
@@ -1755,8 +2114,50 @@ interface ICompactionStrategy {
1755
2114
  }
1756
2115
 
1757
2116
  /**
1758
- * LLM Response entity based on OpenAI Responses API format
2117
+ * Interface for objects that manage resources and need explicit cleanup.
2118
+ *
2119
+ * Implementing classes should release all resources (event listeners, timers,
2120
+ * connections, etc.) when destroy() is called. After destruction, the instance
2121
+ * should not be used.
2122
+ */
2123
+ interface IDisposable {
2124
+ /**
2125
+ * Releases all resources held by this instance.
2126
+ *
2127
+ * After calling destroy():
2128
+ * - All event listeners should be removed
2129
+ * - All timers/intervals should be cleared
2130
+ * - All internal state should be cleaned up
2131
+ * - The instance should not be reused
2132
+ *
2133
+ * Multiple calls to destroy() should be safe (idempotent).
2134
+ */
2135
+ destroy(): void;
2136
+ /**
2137
+ * Returns true if destroy() has been called.
2138
+ * Methods should check this before performing operations.
2139
+ */
2140
+ readonly isDestroyed: boolean;
2141
+ }
2142
+ /**
2143
+ * Async version of IDisposable for resources requiring async cleanup.
2144
+ */
2145
+ interface IAsyncDisposable {
2146
+ /**
2147
+ * Asynchronously releases all resources held by this instance.
2148
+ */
2149
+ destroy(): Promise<void>;
2150
+ /**
2151
+ * Returns true if destroy() has been called.
2152
+ */
2153
+ readonly isDestroyed: boolean;
2154
+ }
2155
+ /**
2156
+ * Helper to check if an object is destroyed and throw if so.
2157
+ * @param obj - The disposable object to check
2158
+ * @param operation - Name of the operation being attempted
1759
2159
  */
2160
+ declare function assertNotDestroyed(obj: IDisposable | IAsyncDisposable, operation: string): void;
1760
2161
 
1761
2162
  /**
1762
2163
  * Token usage statistics
@@ -1773,7 +2174,17 @@ interface LLMResponse {
1773
2174
  id: string;
1774
2175
  object: 'response';
1775
2176
  created_at: number;
1776
- status: 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete';
2177
+ /**
2178
+ * Response status:
2179
+ * - `completed` — Generation finished successfully
2180
+ * - `failed` — Generation failed with an error
2181
+ * - `incomplete` — Generation stopped early (e.g. max tokens reached)
2182
+ * - `cancelled` — Generation was cancelled by the caller
2183
+ * - `in_progress` — Async/streaming generation still running (used by StreamState, video generation)
2184
+ * - `queued` — Queued for processing (used by async video generation via Sora)
2185
+ * - `suspended` — Agent loop suspended waiting for external input (via SuspendSignal)
2186
+ */
2187
+ status: 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete' | 'suspended';
1777
2188
  model: string;
1778
2189
  output: OutputItem[];
1779
2190
  output_text?: string;
@@ -1784,6 +2195,28 @@ interface LLMResponse {
1784
2195
  message: string;
1785
2196
  };
1786
2197
  metadata?: Record<string, string>;
2198
+ /** Non-empty when async tools are still executing in the background */
2199
+ pendingAsyncTools?: Array<{
2200
+ toolCallId: string;
2201
+ toolName: string;
2202
+ startTime: number;
2203
+ status: PendingAsyncToolStatus;
2204
+ }>;
2205
+ /** Present when status is 'suspended' — contains info needed to resume the session */
2206
+ suspension?: {
2207
+ /** Correlation ID for routing external events back to this session */
2208
+ correlationId: string;
2209
+ /** Session ID where the agent state is persisted */
2210
+ sessionId: string;
2211
+ /** Agent ID for reconstructing the agent via Agent.hydrate() */
2212
+ agentId: string;
2213
+ /** How the external response should be injected on resume */
2214
+ resumeAs: 'user_message' | 'tool_result';
2215
+ /** ISO timestamp when this suspension expires */
2216
+ expiresAt: string;
2217
+ /** Application-specific metadata from the SuspendSignal */
2218
+ metadata?: Record<string, unknown>;
2219
+ };
1787
2220
  }
1788
2221
  type AgentResponse = LLMResponse;
1789
2222
 
@@ -1809,6 +2242,7 @@ declare enum StreamEventType {
1809
2242
  REASONING_DELTA = "response.reasoning.delta",
1810
2243
  REASONING_DONE = "response.reasoning.done",
1811
2244
  RESPONSE_COMPLETE = "response.complete",
2245
+ RETRY = "response.retry",
1812
2246
  ERROR = "response.error",
1813
2247
  AUDIO_CHUNK_READY = "response.audio_chunk.ready",
1814
2248
  AUDIO_CHUNK_ERROR = "response.audio_chunk.error",
@@ -1923,6 +2357,18 @@ interface ResponseCompleteEvent extends BaseStreamEvent {
1923
2357
  usage: TokenUsage;
1924
2358
  iterations: number;
1925
2359
  duration_ms?: number;
2360
+ /** Raw provider stop reason for diagnostics (e.g., 'end_turn', 'max_tokens', 'SAFETY') */
2361
+ stop_reason?: string;
2362
+ }
2363
+ /**
2364
+ * Retry event - emitted when agent retries an empty/incomplete LLM response
2365
+ */
2366
+ interface RetryEvent extends BaseStreamEvent {
2367
+ type: StreamEventType.RETRY;
2368
+ attempt: number;
2369
+ max_attempts: number;
2370
+ reason: string;
2371
+ delay_ms: number;
1926
2372
  }
1927
2373
  /**
1928
2374
  * Reasoning/thinking delta - incremental reasoning output
@@ -1995,7 +2441,7 @@ interface AudioStreamCompleteEvent extends BaseStreamEvent {
1995
2441
  * Union type of all stream events
1996
2442
  * Discriminated by 'type' field for type narrowing
1997
2443
  */
1998
- type StreamEvent = ResponseCreatedEvent | ResponseInProgressEvent | OutputTextDeltaEvent | OutputTextDoneEvent | ReasoningDeltaEvent | ReasoningDoneEvent | ToolCallStartEvent | ToolCallArgumentsDeltaEvent | ToolCallArgumentsDoneEvent | ToolExecutionStartEvent | ToolExecutionDoneEvent | IterationCompleteEvent$1 | ResponseCompleteEvent | ErrorEvent | AudioChunkReadyEvent | AudioChunkErrorEvent | AudioStreamCompleteEvent;
2444
+ type StreamEvent = ResponseCreatedEvent | ResponseInProgressEvent | OutputTextDeltaEvent | OutputTextDoneEvent | ReasoningDeltaEvent | ReasoningDoneEvent | ToolCallStartEvent | ToolCallArgumentsDeltaEvent | ToolCallArgumentsDoneEvent | ToolExecutionStartEvent | ToolExecutionDoneEvent | IterationCompleteEvent$1 | ResponseCompleteEvent | RetryEvent | ErrorEvent | AudioChunkReadyEvent | AudioChunkErrorEvent | AudioStreamCompleteEvent;
1999
2445
  /**
2000
2446
  * Type guard to check if event is a specific type
2001
2447
  */
@@ -2272,6 +2718,14 @@ interface ExecutionEmptyOutputEvent {
2272
2718
  duration: number;
2273
2719
  usage?: TokenUsage;
2274
2720
  }
2721
+ interface ExecutionRetryEvent {
2722
+ executionId: string;
2723
+ attempt: number;
2724
+ maxAttempts: number;
2725
+ reason: string;
2726
+ delayMs: number;
2727
+ timestamp: Date;
2728
+ }
2275
2729
  interface ExecutionMaxIterationsEvent {
2276
2730
  executionId: string;
2277
2731
  iteration: number;
@@ -2367,6 +2821,44 @@ interface CircuitClosedEvent {
2367
2821
  successCount: number;
2368
2822
  timestamp: Date;
2369
2823
  }
2824
+ interface AsyncToolStartedEvent {
2825
+ executionId: string;
2826
+ toolCallId: string;
2827
+ toolName: string;
2828
+ args: Record<string, unknown>;
2829
+ timestamp: Date;
2830
+ }
2831
+ interface AsyncToolCompleteEvent {
2832
+ executionId: string;
2833
+ toolCallId: string;
2834
+ toolName: string;
2835
+ result: ToolResult;
2836
+ duration: number;
2837
+ timestamp: Date;
2838
+ }
2839
+ interface AsyncToolErrorEvent {
2840
+ executionId: string;
2841
+ toolCallId: string;
2842
+ toolName: string;
2843
+ error: Error;
2844
+ duration: number;
2845
+ timestamp: Date;
2846
+ }
2847
+ interface AsyncToolTimeoutEvent {
2848
+ executionId: string;
2849
+ toolCallId: string;
2850
+ toolName: string;
2851
+ timeout: number;
2852
+ timestamp: Date;
2853
+ }
2854
+ interface AsyncContinuationStartEvent {
2855
+ executionId: string;
2856
+ results: Array<{
2857
+ toolCallId: string;
2858
+ toolName: string;
2859
+ }>;
2860
+ timestamp: Date;
2861
+ }
2370
2862
  /**
2371
2863
  * Map of all event names to their payload types
2372
2864
  */
@@ -2390,9 +2882,15 @@ interface AgenticLoopEvents {
2390
2882
  'tool:timeout': ToolTimeoutEvent;
2391
2883
  'hook:error': HookErrorEvent;
2392
2884
  'execution:empty_output': ExecutionEmptyOutputEvent;
2885
+ 'execution:retry': ExecutionRetryEvent;
2393
2886
  'circuit:opened': CircuitOpenedEvent;
2394
2887
  'circuit:half-open': CircuitHalfOpenEvent;
2395
2888
  'circuit:closed': CircuitClosedEvent;
2889
+ 'async:tool:started': AsyncToolStartedEvent;
2890
+ 'async:tool:complete': AsyncToolCompleteEvent;
2891
+ 'async:tool:error': AsyncToolErrorEvent;
2892
+ 'async:tool:timeout': AsyncToolTimeoutEvent;
2893
+ 'async:continuation:start': AsyncContinuationStartEvent;
2396
2894
  }
2397
2895
  type AgenticLoopEventName = keyof AgenticLoopEvents;
2398
2896
  /**
@@ -2551,7 +3049,8 @@ interface HookSignatures {
2551
3049
  * Includes error isolation, timeouts, and optional parallel execution
2552
3050
  */
2553
3051
 
2554
- declare class HookManager {
3052
+ declare class HookManager implements IDisposable {
3053
+ private _isDestroyed;
2555
3054
  private hooks;
2556
3055
  private timeout;
2557
3056
  private parallel;
@@ -2607,6 +3106,14 @@ declare class HookManager {
2607
3106
  * Clear all hooks and reset error tracking
2608
3107
  */
2609
3108
  clear(): void;
3109
+ /**
3110
+ * Check if the hook manager has been destroyed
3111
+ */
3112
+ get isDestroyed(): boolean;
3113
+ /**
3114
+ * Destroy the hook manager and release all references
3115
+ */
3116
+ destroy(): void;
2610
3117
  /**
2611
3118
  * Re-enable a disabled hook
2612
3119
  */
@@ -2617,4 +3124,4 @@ declare class HookManager {
2617
3124
  getDisabledHooks(): string[];
2618
3125
  }
2619
3126
 
2620
- export { type TokenUsage as $, type AgentContextNextGenConfig as A, type BeforeCompactionCallback as B, type ContextFeatures as C, type HookName as D, ExecutionContext as E, type FunctionToolDefinition as F, type ITokenEstimator as G, type HookConfig as H, type IContextStorage as I, type ToolCategoryScope as J, type CompactionContext as K, type LLMResponse as L, type MemoryEntry as M, type CompactionResult as N, type OutputItem as O, type PriorityCalculator as P, type AudioChunkReadyEvent as Q, type StaleEntryInfo as R, type SerializedContextState as S, type Tool as T, type PriorityContext as U, type MemoryIndex as V, type WorkingMemoryConfig as W, type TaskStatusForMemory as X, type WorkingMemoryAccess as Y, type ContextStorageListOptions as Z, type ContextSessionSummary as _, type MemoryScope as a, defaultDescribeCall as a$, StreamEventType as a0, type TextGenerateOptions as a1, type ModelCapabilities as a2, MessageRole as a3, type AfterToolContext as a4, type AgentEventName as a5, type AgenticLoopEventName as a6, type AgenticLoopEvents as a7, type ApprovalResult as a8, type ApproveToolContext as a9, type OutputTextContent as aA, type OutputTextDeltaEvent as aB, type OutputTextDoneEvent as aC, type OversizedInputResult as aD, type PluginConfigs as aE, type ReasoningDeltaEvent as aF, type ReasoningDoneEvent as aG, type ReasoningItem as aH, type ResponseCompleteEvent as aI, type ResponseCreatedEvent as aJ, type ResponseInProgressEvent as aK, type SimpleScope as aL, type TaskAwareScope as aM, type ThinkingContent as aN, type ToolCallArgumentsDeltaEvent as aO, type ToolCallArgumentsDoneEvent as aP, type ToolCallStartEvent as aQ, ToolCallState as aR, ToolCatalogRegistry as aS, type ToolCategoryDefinition as aT, type ToolExecutionContext as aU, type ToolExecutionDoneEvent as aV, type ToolExecutionStartEvent as aW, type ToolModification as aX, type ToolResultContent as aY, type ToolUseContent as aZ, calculateEntrySize as a_, type AudioChunkErrorEvent as aa, type AudioStreamCompleteEvent as ab, type BeforeToolContext as ac, type BuiltInTool as ad, CONTEXT_SESSION_FORMAT_VERSION as ae, type ToolRegistryEntry as af, type CatalogToolEntry as ag, type CompactionItem as ah, type ConnectorCategoryInfo as ai, ContentType as aj, DEFAULT_CONFIG as ak, DEFAULT_FEATURES as al, DEFAULT_MEMORY_CONFIG as am, type ErrorEvent as an, type ExecutionConfig as ao, type Hook as ap, HookManager as aq, type InputImageContent as ar, type InputTextContent as as, type IterationCompleteEvent$1 as at, type JSONSchema as au, MEMORY_PRIORITY_VALUES as av, type MemoryEntryInput as aw, type MemoryIndexEntry as ax, type Message as ay, type ModifyingHook as az, type ToolFunction as b, forPlan as b0, forTasks as b1, getToolCallDescription as b2, isAudioChunkError as b3, isAudioChunkReady as b4, isAudioStreamComplete as b5, isErrorEvent as b6, isOutputTextDelta as b7, isReasoningDelta as b8, isReasoningDone as b9, isResponseComplete as ba, isSimpleScope as bb, isStreamEvent as bc, isTaskAwareScope as bd, isTerminalMemoryStatus as be, isToolCallArgumentsDelta as bf, isToolCallArgumentsDone as bg, isToolCallStart as bh, scopeEquals as bi, scopeMatches as bj, type ExecutionCompleteEvent as bk, type ExecutionStartEvent as bl, type LLMRequestEvent as bm, type LLMResponseEvent as bn, type ToolCompleteEvent as bo, type ToolStartEvent as bp, type ToolContext as c, type ToolPermissionConfig as d, type ContextBudget as e, type ToolCall as f, type IContextPluginNextGen as g, type MemoryPriority as h, type MemoryTier as i, type ContextEvents as j, type AuthIdentity as k, type ICompactionStrategy as l, type InputItem as m, type Content as n, type PreparedContext as o, type ToolResult as p, type ConsolidationResult as q, type StoredContextSession as r, type ITextProvider as s, type ContextSessionMetadata as t, type StreamEvent as u, type HistoryMode as v, type AgentEvents as w, type AgentResponse as x, type ExecutionMetrics as y, type AuditEntry as z };
3127
+ export { type ITokenEstimator as $, type AgentContextNextGenConfig as A, type BeforeCompactionCallback as B, type ContextFeatures as C, type StoredContextSession as D, type ITextProvider as E, type ContextSessionMetadata as F, type FunctionToolDefinition as G, type StreamEvent as H, type IContextStorage as I, type HookConfig as J, type HistoryMode as K, type LLMResponse as L, type MemoryEntry as M, type AsyncToolConfig as N, type OutputItem as O, type PriorityCalculator as P, type AgentEvents as Q, type ResolvedContextFeatures as R, type StoreEntrySchema as S, type ToolCall as T, type AgentResponse as U, type PendingAsyncTool as V, type WorkingMemoryConfig as W, ExecutionContext as X, type ExecutionMetrics as Y, type AuditEntry as Z, type HookName as _, type MemoryScope as a, type ResponseCompleteEvent as a$, type ToolCategoryScope as a0, type CompactionContext as a1, type CompactionResult as a2, type PluginConfigs as a3, type AudioChunkReadyEvent as a4, type ContextStorageListOptions as a5, type ContextSessionSummary as a6, type HistoryEntry as a7, type HistoryReadOptions as a8, type StaleEntryInfo as a9, DEFAULT_FEATURES as aA, DEFAULT_MEMORY_CONFIG as aB, type ErrorEvent as aC, type ExecutionConfig as aD, type HistoryEntryType as aE, type Hook as aF, HookManager as aG, type IAsyncDisposable as aH, type InputImageContent as aI, type InputTextContent as aJ, type IterationCompleteEvent$1 as aK, type JSONSchema as aL, type KnownContextFeatures as aM, type KnownPluginConfigs as aN, MEMORY_PRIORITY_VALUES as aO, type MemoryEntryInput as aP, type MemoryIndexEntry as aQ, type Message as aR, type ModifyingHook as aS, type OutputTextContent as aT, type OutputTextDeltaEvent as aU, type OutputTextDoneEvent as aV, type OversizedInputResult as aW, type PendingAsyncToolStatus as aX, type ReasoningDeltaEvent as aY, type ReasoningDoneEvent as aZ, type ReasoningItem as a_, type PriorityContext as aa, type MemoryIndex as ab, type TaskStatusForMemory as ac, type WorkingMemoryAccess as ad, type TokenUsage as ae, StreamEventType as af, type TextGenerateOptions as ag, type ModelCapabilities as ah, MessageRole as ai, type AfterToolContext as aj, type AgentEventName as ak, type AgenticLoopEventName as al, type AgenticLoopEvents as am, type ApprovalResult as an, type ApproveToolContext as ao, type AudioChunkErrorEvent as ap, type AudioStreamCompleteEvent as aq, type BeforeToolContext as ar, type BuiltInTool as as, CONTEXT_SESSION_FORMAT_VERSION as at, type ToolRegistryEntry as au, type CatalogToolEntry as av, type CompactionItem as aw, type ConnectorCategoryInfo as ax, ContentType as ay, DEFAULT_CONFIG as az, type Tool as b, type ResponseCreatedEvent as b0, type ResponseInProgressEvent as b1, type SimpleScope as b2, type TaskAwareScope as b3, type ThinkingContent as b4, type ToolCallArgumentsDeltaEvent as b5, type ToolCallArgumentsDoneEvent as b6, type ToolCallStartEvent as b7, ToolCallState as b8, ToolCatalogRegistry as b9, isToolCallArgumentsDelta as bA, isToolCallArgumentsDone as bB, isToolCallStart as bC, scopeEquals as bD, scopeMatches as bE, type AsyncContinuationStartEvent as bF, type AsyncToolCompleteEvent as bG, type AsyncToolErrorEvent as bH, type AsyncToolStartedEvent as bI, type AsyncToolTimeoutEvent as bJ, type ExecutionCompleteEvent as bK, type ExecutionStartEvent as bL, type LLMRequestEvent as bM, type LLMResponseEvent as bN, type ToolCompleteEvent as bO, type ToolStartEvent as bP, type ToolCategoryDefinition as ba, type ToolExecutionContext as bb, type ToolExecutionDoneEvent as bc, type ToolExecutionStartEvent as bd, type ToolModification as be, type ToolResultContent as bf, type ToolUseContent as bg, assertNotDestroyed as bh, calculateEntrySize as bi, defaultDescribeCall as bj, forPlan as bk, forTasks as bl, getToolCallDescription as bm, isAudioChunkError as bn, isAudioChunkReady as bo, isAudioStreamComplete as bp, isErrorEvent as bq, isOutputTextDelta as br, isReasoningDelta as bs, isReasoningDone as bt, isResponseComplete as bu, isSimpleScope as bv, isStoreHandler as bw, isStreamEvent as bx, isTaskAwareScope as by, isTerminalMemoryStatus as bz, type ToolFunction as c, type IDisposable as d, type ToolContext as e, type ToolPermissionConfig as f, type ContextBudget as g, type IContextPluginNextGen as h, type IStoreHandler as i, type MemoryPriority as j, type StoreGetResult as k, type StoreSetResult as l, type StoreDeleteResult as m, type StoreListResult as n, type StoreActionResult as o, type MemoryTier as p, type ContextEvents as q, type AuthIdentity as r, type ICompactionStrategy as s, type InputItem as t, type Content as u, type PreparedContext as v, type ToolResult as w, type IHistoryJournal as x, type ConsolidationResult as y, type SerializedContextState as z };