@everworker/oneringai 0.4.2 → 0.4.3

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.
@@ -1,4 +1,4 @@
1
- import { I as IConnectorRegistry, e as IProvider } from './IProvider-CNJqZItJ.cjs';
1
+ import { I as IConnectorRegistry, e as IProvider } from './IProvider-CxDUGl6n.js';
2
2
  import { EventEmitter } from 'eventemitter3';
3
3
 
4
4
  /**
@@ -367,6 +367,10 @@ interface ToolContext {
367
367
  taskId?: string;
368
368
  /** User ID — auto-populated from Agent config (userId). Also settable manually via agent.tools.setToolContext(). */
369
369
  userId?: string;
370
+ /** Account alias for multi-account OAuth — auto-populated from Agent config (accountId). Allows one user to auth multiple external accounts on the same connector (e.g., 'work', 'personal'). */
371
+ accountId?: string;
372
+ /** Auth identities this agent is scoped to (for identity-aware tool descriptions) */
373
+ identities?: AuthIdentity[];
370
374
  /** Connector registry scoped to this agent's allowed connectors and userId */
371
375
  connectorRegistry?: IConnectorRegistry;
372
376
  /** Working memory access (if agent has memory feature enabled) */
@@ -577,6 +581,857 @@ declare function defaultDescribeCall(args: Record<string, unknown>, maxLength?:
577
581
  */
578
582
  declare function getToolCallDescription<TArgs>(tool: ToolFunction<TArgs>, args: TArgs): string;
579
583
 
584
+ /**
585
+ * IContextStorage - Storage interface for AgentContext persistence
586
+ *
587
+ * Provides persistence operations for AgentContext sessions.
588
+ * Implementations can use filesystem, database, cloud storage, etc.
589
+ *
590
+ * This follows Clean Architecture - the interface is in domain layer,
591
+ * implementations are in infrastructure layer.
592
+ */
593
+
594
+ /**
595
+ * Serialized context state for persistence.
596
+ * This is the canonical definition - core layer re-exports this type.
597
+ */
598
+ interface SerializedContextState {
599
+ /** Conversation history */
600
+ conversation: InputItem[];
601
+ /** Plugin states (keyed by plugin name) */
602
+ pluginStates: Record<string, unknown>;
603
+ /** System prompt */
604
+ systemPrompt?: string;
605
+ /** Metadata */
606
+ metadata: {
607
+ savedAt: number;
608
+ agentId?: string;
609
+ userId?: string;
610
+ model: string;
611
+ };
612
+ /** Agent-specific state (for TaskAgent, UniversalAgent, etc.) */
613
+ agentState?: Record<string, unknown>;
614
+ }
615
+ /**
616
+ * Session summary for listing (lightweight, no full state)
617
+ */
618
+ interface ContextSessionSummary {
619
+ /** Session identifier */
620
+ sessionId: string;
621
+ /** When the session was created */
622
+ createdAt: Date;
623
+ /** When the session was last saved */
624
+ lastSavedAt: Date;
625
+ /** Number of messages in history */
626
+ messageCount: number;
627
+ /** Number of memory entries */
628
+ memoryEntryCount: number;
629
+ /** Optional metadata */
630
+ metadata?: ContextSessionMetadata;
631
+ }
632
+ /**
633
+ * Session metadata (stored with session)
634
+ */
635
+ interface ContextSessionMetadata {
636
+ /** Human-readable title */
637
+ title?: string;
638
+ /** Auto-generated or user-provided description */
639
+ description?: string;
640
+ /** Tags for filtering */
641
+ tags?: string[];
642
+ /** Custom key-value data */
643
+ [key: string]: unknown;
644
+ }
645
+ /**
646
+ * Full session state wrapper (includes metadata)
647
+ */
648
+ interface StoredContextSession {
649
+ /** Format version for migration support */
650
+ version: number;
651
+ /** Session identifier */
652
+ sessionId: string;
653
+ /** When the session was created */
654
+ createdAt: string;
655
+ /** When the session was last saved */
656
+ lastSavedAt: string;
657
+ /** The serialized AgentContext state */
658
+ state: SerializedContextState;
659
+ /** Session metadata */
660
+ metadata: ContextSessionMetadata;
661
+ }
662
+ /**
663
+ * Current format version for stored sessions
664
+ */
665
+ declare const CONTEXT_SESSION_FORMAT_VERSION = 1;
666
+ /**
667
+ * Storage interface for AgentContext persistence
668
+ *
669
+ * Implementations:
670
+ * - FileContextStorage: File-based storage at ~/.oneringai/agents/<agentId>/sessions/
671
+ * - (Future) RedisContextStorage, PostgresContextStorage, S3ContextStorage, etc.
672
+ */
673
+ interface IContextStorage {
674
+ /**
675
+ * Save context state to a session
676
+ *
677
+ * @param sessionId - Unique session identifier
678
+ * @param state - Serialized AgentContext state
679
+ * @param metadata - Optional session metadata
680
+ */
681
+ save(sessionId: string, state: SerializedContextState, metadata?: ContextSessionMetadata): Promise<void>;
682
+ /**
683
+ * Load context state from a session
684
+ *
685
+ * @param sessionId - Session identifier to load
686
+ * @returns The stored session, or null if not found
687
+ */
688
+ load(sessionId: string): Promise<StoredContextSession | null>;
689
+ /**
690
+ * Delete a session
691
+ *
692
+ * @param sessionId - Session identifier to delete
693
+ */
694
+ delete(sessionId: string): Promise<void>;
695
+ /**
696
+ * Check if a session exists
697
+ *
698
+ * @param sessionId - Session identifier to check
699
+ */
700
+ exists(sessionId: string): Promise<boolean>;
701
+ /**
702
+ * List all sessions (summaries only, not full state)
703
+ *
704
+ * @param options - Optional filtering and pagination
705
+ * @returns Array of session summaries, sorted by lastSavedAt descending
706
+ */
707
+ list(options?: ContextStorageListOptions): Promise<ContextSessionSummary[]>;
708
+ /**
709
+ * Update session metadata without loading full state
710
+ *
711
+ * @param sessionId - Session identifier
712
+ * @param metadata - Metadata to merge (existing keys preserved unless overwritten)
713
+ */
714
+ updateMetadata?(sessionId: string, metadata: Partial<ContextSessionMetadata>): Promise<void>;
715
+ /**
716
+ * Get the storage path (for display/debugging)
717
+ * @deprecated Use getLocation() instead - getPath() assumes filesystem storage
718
+ */
719
+ getPath(): string;
720
+ /**
721
+ * Get a human-readable storage location string (for display/debugging).
722
+ * Examples: file path, MongoDB URI, Redis key prefix, S3 bucket, etc.
723
+ * Falls back to getPath() if not implemented.
724
+ */
725
+ getLocation?(): string;
726
+ }
727
+ /**
728
+ * Options for listing sessions
729
+ */
730
+ interface ContextStorageListOptions {
731
+ /** Filter by tags (any match) */
732
+ tags?: string[];
733
+ /** Filter by creation date range */
734
+ createdAfter?: Date;
735
+ createdBefore?: Date;
736
+ /** Filter by last saved date range */
737
+ savedAfter?: Date;
738
+ savedBefore?: Date;
739
+ /** Maximum number of results */
740
+ limit?: number;
741
+ /** Offset for pagination */
742
+ offset?: number;
743
+ }
744
+
745
+ /**
746
+ * AgentContextNextGen - Type Definitions
747
+ *
748
+ * Clean, minimal type definitions for the next-generation context manager.
749
+ */
750
+
751
+ /**
752
+ * A single auth identity: connector + optional account alias.
753
+ *
754
+ * Used to scope agents to specific OAuth accounts. When `accountId` is set,
755
+ * the identity represents a specific multi-account OAuth session (e.g., 'work'
756
+ * or 'personal' Microsoft account). When omitted, uses the connector's default account.
757
+ */
758
+ interface AuthIdentity {
759
+ /** Name of the registered connector */
760
+ connector: string;
761
+ /** Optional account alias for multi-account OAuth (e.g., 'work', 'personal') */
762
+ accountId?: string;
763
+ }
764
+ /**
765
+ * Token estimator interface - used for conversation and input estimation
766
+ * Plugins handle their own token estimation internally.
767
+ */
768
+ interface ITokenEstimator {
769
+ /** Estimate tokens for a string */
770
+ estimateTokens(text: string): number;
771
+ /** Estimate tokens for arbitrary data (will be JSON stringified) */
772
+ estimateDataTokens(data: unknown): number;
773
+ /**
774
+ * Estimate tokens for an image. Provider-specific implementations can override.
775
+ *
776
+ * Default heuristic (matches OpenAI's image token pricing):
777
+ * - detail='low': 85 tokens
778
+ * - detail='high' with known dimensions: 85 + 170 * ceil(w/512) * ceil(h/512)
779
+ * - Unknown dimensions: ~1000 tokens (conservative default)
780
+ *
781
+ * @param width - Image width in pixels (if known)
782
+ * @param height - Image height in pixels (if known)
783
+ * @param detail - Image detail level: 'low', 'high', or 'auto' (default 'auto')
784
+ */
785
+ estimateImageTokens?(width?: number, height?: number, detail?: string): number;
786
+ }
787
+ /**
788
+ * Context plugin interface for NextGen context management.
789
+ *
790
+ * ## Implementing a Custom Plugin
791
+ *
792
+ * 1. **Extend BasePluginNextGen** - provides token caching helpers
793
+ * 2. **Implement getInstructions()** - return LLM usage guide (static, cached)
794
+ * 3. **Implement getContent()** - return formatted content (Markdown with `##` header)
795
+ * 4. **Call updateTokenCache()** - after any state change that affects content
796
+ * 5. **Implement getTools()** - return tools with `<plugin_prefix>_*` naming
797
+ *
798
+ * ## Plugin Contributions
799
+ *
800
+ * Plugins provide three types of content to the system message:
801
+ * 1. **Instructions** - static usage guide for the LLM (NEVER compacted)
802
+ * 2. **Content** - dynamic plugin data/state (may be compacted)
803
+ * 3. **Tools** - registered with ToolManager (NEVER compacted)
804
+ *
805
+ * ## Token Cache Lifecycle
806
+ *
807
+ * Plugins must track their own token size for budget calculation. The pattern:
808
+ *
809
+ * ```typescript
810
+ * // When state changes:
811
+ * this._entries.set(key, value);
812
+ * this.invalidateTokenCache(); // Clear cached size
813
+ *
814
+ * // In getContent():
815
+ * const content = this.formatContent();
816
+ * this.updateTokenCache(this.estimator.estimateTokens(content)); // Update cache
817
+ * return content;
818
+ * ```
819
+ *
820
+ * ## Content Format
821
+ *
822
+ * `getContent()` should return Markdown with a descriptive header:
823
+ *
824
+ * ```markdown
825
+ * ## Plugin Display Name (optional stats)
826
+ *
827
+ * Formatted content here...
828
+ * - Entry 1: value
829
+ * - Entry 2: value
830
+ * ```
831
+ *
832
+ * Built-in plugins use these headers:
833
+ * - WorkingMemory: `## Working Memory (N entries)`
834
+ * - InContextMemory: `## Live Context (N entries)`
835
+ * - PersistentInstructions: No header (user's raw instructions)
836
+ *
837
+ * ## Tool Naming Convention
838
+ *
839
+ * Use a consistent prefix based on plugin name:
840
+ * - `working_memory` plugin → `memory_store`, `memory_retrieve`, `memory_delete`, `memory_list`
841
+ * - `in_context_memory` plugin → `context_set`, `context_delete`, `context_list`
842
+ * - `persistent_instructions` plugin → `instructions_set`, `instructions_remove`, `instructions_list`, `instructions_clear`
843
+ *
844
+ * ## State Serialization
845
+ *
846
+ * `getState()` and `restoreState()` are **synchronous** for simplicity.
847
+ * If your plugin has async data, consider:
848
+ * - Storing only references/keys in state
849
+ * - Using a separate async initialization method
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * class MyPlugin extends BasePluginNextGen {
854
+ * readonly name = 'my_plugin';
855
+ * private _data = new Map<string, string>();
856
+ *
857
+ * getInstructions(): string {
858
+ * return '## My Plugin\n\nUse my_plugin_set to store data...';
859
+ * }
860
+ *
861
+ * async getContent(): Promise<string | null> {
862
+ * if (this._data.size === 0) return null;
863
+ * const lines = [...this._data].map(([k, v]) => `- ${k}: ${v}`);
864
+ * const content = `## My Plugin (${this._data.size} entries)\n\n${lines.join('\n')}`;
865
+ * this.updateTokenCache(this.estimator.estimateTokens(content));
866
+ * return content;
867
+ * }
868
+ *
869
+ * getTools(): ToolFunction[] {
870
+ * return [myPluginSetTool, myPluginGetTool];
871
+ * }
872
+ *
873
+ * getState(): unknown {
874
+ * return { data: Object.fromEntries(this._data) };
875
+ * }
876
+ *
877
+ * restoreState(state: unknown): void {
878
+ * const s = state as { data: Record<string, string> };
879
+ * this._data = new Map(Object.entries(s.data || {}));
880
+ * this.invalidateTokenCache();
881
+ * }
882
+ * }
883
+ * ```
884
+ */
885
+ interface IContextPluginNextGen {
886
+ /** Unique plugin name (used for lookup and tool prefixing) */
887
+ readonly name: string;
888
+ /**
889
+ * Get usage instructions for the LLM.
890
+ *
891
+ * Returns static text explaining how to use this plugin's tools
892
+ * and data. This is placed in the system message and is NEVER
893
+ * compacted - it persists throughout the conversation.
894
+ *
895
+ * Instructions should include:
896
+ * - What the plugin does
897
+ * - How to use available tools
898
+ * - Best practices and conventions
899
+ *
900
+ * @returns Instructions string or null if no instructions needed
901
+ *
902
+ * @example
903
+ * ```typescript
904
+ * getInstructions(): string {
905
+ * return `## Working Memory
906
+ *
907
+ * Use memory_store to save important data for later retrieval.
908
+ * Use memory_retrieve to recall previously stored data.
909
+ *
910
+ * Best practices:
911
+ * - Use descriptive keys like 'user_preferences' not 'data1'
912
+ * - Store intermediate results that may be needed later`;
913
+ * }
914
+ * ```
915
+ */
916
+ getInstructions(): string | null;
917
+ /**
918
+ * Get formatted content to include in system message.
919
+ *
920
+ * Returns the plugin's current state formatted for LLM consumption.
921
+ * Should be Markdown with a `## Header`. This content CAN be compacted
922
+ * if `isCompactable()` returns true.
923
+ *
924
+ * **IMPORTANT:** Call `updateTokenCache()` with the content's token size
925
+ * before returning to keep budget calculations accurate.
926
+ *
927
+ * @returns Formatted content string or null if empty
928
+ *
929
+ * @example
930
+ * ```typescript
931
+ * async getContent(): Promise<string | null> {
932
+ * if (this._entries.size === 0) return null;
933
+ *
934
+ * const lines = this._entries.map(e => `- ${e.key}: ${e.value}`);
935
+ * const content = `## My Plugin (${this._entries.size} entries)\n\n${lines.join('\n')}`;
936
+ *
937
+ * // IMPORTANT: Update token cache before returning
938
+ * this.updateTokenCache(this.estimator.estimateTokens(content));
939
+ * return content;
940
+ * }
941
+ * ```
942
+ */
943
+ getContent(): Promise<string | null>;
944
+ /**
945
+ * Get the full raw contents of this plugin for inspection.
946
+ *
947
+ * Used by library clients to programmatically inspect plugin state.
948
+ * Returns the actual data structure, not the formatted string.
949
+ *
950
+ * @returns Raw plugin data (entries map, array, etc.)
951
+ */
952
+ getContents(): unknown;
953
+ /**
954
+ * Get current token size of plugin content.
955
+ *
956
+ * Returns the cached token count from the last `updateTokenCache()` call.
957
+ * This is used for budget calculation in `prepare()`.
958
+ *
959
+ * The cache should be updated via `updateTokenCache()` whenever content
960
+ * changes. If cache is null, returns 0.
961
+ *
962
+ * @returns Current token count (0 if no content or cache not set)
963
+ */
964
+ getTokenSize(): number;
965
+ /**
966
+ * Get token size of instructions (cached after first call).
967
+ *
968
+ * Instructions are static, so this is computed once and cached.
969
+ * Used for budget calculation.
970
+ *
971
+ * @returns Token count for instructions (0 if no instructions)
972
+ */
973
+ getInstructionsTokenSize(): number;
974
+ /**
975
+ * Whether this plugin's content can be compacted when context is tight.
976
+ *
977
+ * Return true if the plugin can reduce its content size when requested.
978
+ * Examples: evicting low-priority entries, summarizing, removing old data.
979
+ *
980
+ * Return false if content cannot be reduced (e.g., critical state).
981
+ *
982
+ * @returns true if compact() can free tokens
983
+ */
984
+ isCompactable(): boolean;
985
+ /**
986
+ * Compact plugin content to free tokens.
987
+ *
988
+ * Called by compaction strategies when context is too full.
989
+ * Should attempt to free **approximately** `targetTokensToFree` tokens.
990
+ *
991
+ * This is a **best effort** operation:
992
+ * - May free more or less than requested
993
+ * - May return 0 if nothing can be compacted (e.g., all entries are critical)
994
+ * - Should prioritize removing lowest-priority/oldest data first
995
+ *
996
+ * Strategies may include:
997
+ * - Evicting low-priority entries
998
+ * - Summarizing verbose content
999
+ * - Removing oldest data
1000
+ * - Truncating large values
1001
+ *
1002
+ * **IMPORTANT:** Call `invalidateTokenCache()` or `updateTokenCache()`
1003
+ * after modifying content.
1004
+ *
1005
+ * @param targetTokensToFree - Approximate tokens to free (best effort)
1006
+ * @returns Actual tokens freed (may be 0 if nothing can be compacted)
1007
+ *
1008
+ * @example
1009
+ * ```typescript
1010
+ * async compact(targetTokensToFree: number): Promise<number> {
1011
+ * const before = this.getTokenSize();
1012
+ * let freed = 0;
1013
+ *
1014
+ * // Remove low-priority entries until target reached
1015
+ * const sorted = [...this._entries].sort(byPriority);
1016
+ * for (const entry of sorted) {
1017
+ * if (entry.priority === 'critical') continue; // Never remove critical
1018
+ * if (freed >= targetTokensToFree) break;
1019
+ *
1020
+ * freed += entry.tokens;
1021
+ * this._entries.delete(entry.key);
1022
+ * }
1023
+ *
1024
+ * this.invalidateTokenCache();
1025
+ * return freed;
1026
+ * }
1027
+ * ```
1028
+ */
1029
+ compact(targetTokensToFree: number): Promise<number>;
1030
+ /**
1031
+ * Get tools provided by this plugin.
1032
+ *
1033
+ * Tools are automatically registered with ToolManager when the plugin
1034
+ * is added to the context. Use a consistent naming convention:
1035
+ * `<prefix>_<action>` (e.g., `memory_store`, `context_set`).
1036
+ *
1037
+ * @returns Array of tool definitions (empty array if no tools)
1038
+ */
1039
+ getTools(): ToolFunction[];
1040
+ /**
1041
+ * Cleanup resources when context is destroyed.
1042
+ *
1043
+ * Called when AgentContextNextGen.destroy() is invoked.
1044
+ * Use for releasing resources, closing connections, etc.
1045
+ */
1046
+ destroy(): void;
1047
+ /**
1048
+ * Serialize plugin state for session persistence.
1049
+ *
1050
+ * **MUST be synchronous.** Return a JSON-serializable object representing
1051
+ * the plugin's current state. This is called when saving a session.
1052
+ *
1053
+ * For plugins with async data (e.g., external storage), return only
1054
+ * references/keys here and handle async restoration separately.
1055
+ *
1056
+ * @returns Serializable state object
1057
+ *
1058
+ * @example
1059
+ * ```typescript
1060
+ * getState(): unknown {
1061
+ * return {
1062
+ * entries: [...this._entries].map(([k, v]) => ({ key: k, ...v })),
1063
+ * version: 1, // Include version for future migrations
1064
+ * };
1065
+ * }
1066
+ * ```
1067
+ */
1068
+ getState(): unknown;
1069
+ /**
1070
+ * Restore plugin state from serialized data.
1071
+ *
1072
+ * Called when loading a saved session. The state comes from a previous
1073
+ * `getState()` call on the same plugin type.
1074
+ *
1075
+ * **IMPORTANT:** Call `invalidateTokenCache()` after restoring state
1076
+ * to ensure token counts are recalculated.
1077
+ *
1078
+ * @param state - Previously serialized state from getState()
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * restoreState(state: unknown): void {
1083
+ * const s = state as { entries: Array<{ key: string; value: unknown }> };
1084
+ * this._entries.clear();
1085
+ * for (const entry of s.entries || []) {
1086
+ * this._entries.set(entry.key, entry);
1087
+ * }
1088
+ * this.invalidateTokenCache(); // IMPORTANT: refresh token cache
1089
+ * }
1090
+ * ```
1091
+ */
1092
+ restoreState(state: unknown): void;
1093
+ }
1094
+ /**
1095
+ * Token budget breakdown - clear and simple
1096
+ */
1097
+ interface ContextBudget {
1098
+ /** Maximum context tokens for the model */
1099
+ maxTokens: number;
1100
+ /** Tokens reserved for LLM response */
1101
+ responseReserve: number;
1102
+ /** Tokens used by system message (prompt + instructions + plugin content) */
1103
+ systemMessageTokens: number;
1104
+ /** Tokens used by tool definitions (NEVER compacted) */
1105
+ toolsTokens: number;
1106
+ /** Tokens used by conversation history */
1107
+ conversationTokens: number;
1108
+ /** Tokens used by current input (user message or tool results) */
1109
+ currentInputTokens: number;
1110
+ /** Total tokens used */
1111
+ totalUsed: number;
1112
+ /** Available tokens (maxTokens - responseReserve - totalUsed) */
1113
+ available: number;
1114
+ /** Usage percentage (totalUsed / (maxTokens - responseReserve)) */
1115
+ utilizationPercent: number;
1116
+ /** Breakdown by component for debugging */
1117
+ breakdown: {
1118
+ systemPrompt: number;
1119
+ persistentInstructions: number;
1120
+ pluginInstructions: number;
1121
+ pluginContents: Record<string, number>;
1122
+ tools: number;
1123
+ conversation: number;
1124
+ currentInput: number;
1125
+ };
1126
+ }
1127
+ /**
1128
+ * Result of prepare() - ready for LLM call
1129
+ */
1130
+ interface PreparedContext {
1131
+ /** Final input items array for LLM */
1132
+ input: InputItem[];
1133
+ /** Token budget breakdown */
1134
+ budget: ContextBudget;
1135
+ /** Whether compaction was performed */
1136
+ compacted: boolean;
1137
+ /** Log of compaction actions taken */
1138
+ compactionLog: string[];
1139
+ }
1140
+ /**
1141
+ * Result of handling oversized current input
1142
+ */
1143
+ interface OversizedInputResult {
1144
+ /** Whether the input was accepted (possibly truncated) */
1145
+ accepted: boolean;
1146
+ /** Processed content (truncated if needed) */
1147
+ content: string;
1148
+ /** Error message if rejected */
1149
+ error?: string;
1150
+ /** Warning message if truncated */
1151
+ warning?: string;
1152
+ /** Original size in bytes */
1153
+ originalSize: number;
1154
+ /** Final size in bytes */
1155
+ finalSize: number;
1156
+ }
1157
+ /**
1158
+ * Feature flags for enabling/disabling plugins
1159
+ */
1160
+ interface ContextFeatures {
1161
+ /** Enable WorkingMemory plugin (default: true) */
1162
+ workingMemory?: boolean;
1163
+ /** Enable InContextMemory plugin (default: false) */
1164
+ inContextMemory?: boolean;
1165
+ /** Enable PersistentInstructions plugin (default: false) */
1166
+ persistentInstructions?: boolean;
1167
+ /** Enable UserInfo plugin (default: false) */
1168
+ userInfo?: boolean;
1169
+ }
1170
+ /**
1171
+ * Default feature configuration
1172
+ */
1173
+ declare const DEFAULT_FEATURES: Required<ContextFeatures>;
1174
+ /**
1175
+ * Plugin configurations for auto-initialization.
1176
+ * When features are enabled, plugins are created with these configs.
1177
+ * The config shapes match each plugin's constructor parameter.
1178
+ */
1179
+ interface PluginConfigs {
1180
+ /**
1181
+ * Working memory plugin config (used when features.workingMemory=true).
1182
+ * See WorkingMemoryPluginConfig for full options.
1183
+ */
1184
+ workingMemory?: Record<string, unknown>;
1185
+ /**
1186
+ * In-context memory plugin config (used when features.inContextMemory=true).
1187
+ * See InContextMemoryConfig for full options.
1188
+ */
1189
+ inContextMemory?: Record<string, unknown>;
1190
+ /**
1191
+ * Persistent instructions plugin config (used when features.persistentInstructions=true).
1192
+ * Note: agentId is auto-filled from context config if not provided.
1193
+ * See PersistentInstructionsConfig for full options.
1194
+ */
1195
+ persistentInstructions?: Record<string, unknown>;
1196
+ /**
1197
+ * User info plugin config (used when features.userInfo=true).
1198
+ * See UserInfoPluginConfig for full options.
1199
+ */
1200
+ userInfo?: Record<string, unknown>;
1201
+ }
1202
+ /**
1203
+ * AgentContextNextGen configuration
1204
+ */
1205
+ interface AgentContextNextGenConfig {
1206
+ /** Model name (used for context window lookup) */
1207
+ model: string;
1208
+ /** Maximum context tokens (auto-detected from model if not provided) */
1209
+ maxContextTokens?: number;
1210
+ /** Tokens to reserve for response (default: 4096) */
1211
+ responseReserve?: number;
1212
+ /** System prompt provided by user */
1213
+ systemPrompt?: string;
1214
+ /**
1215
+ * Compaction strategy name (default: 'default').
1216
+ * Used to create strategy from StrategyRegistry if compactionStrategy not provided.
1217
+ */
1218
+ strategy?: string;
1219
+ /**
1220
+ * Custom compaction strategy instance.
1221
+ * If provided, overrides the `strategy` option.
1222
+ */
1223
+ compactionStrategy?: ICompactionStrategy;
1224
+ /** Feature flags */
1225
+ features?: ContextFeatures;
1226
+ /** Agent ID (required for PersistentInstructions) */
1227
+ agentId?: string;
1228
+ /** User ID for multi-user scenarios. Automatically flows to ToolContext for all tool executions. */
1229
+ userId?: string;
1230
+ /**
1231
+ * Restrict this agent to specific auth identities (connector + optional account alias).
1232
+ * When set, only these identities are visible in ToolContext and tool descriptions.
1233
+ * Each identity produces its own tool set (e.g., microsoft_work_api, microsoft_personal_api).
1234
+ * When not set, all connectors visible to the current userId are available.
1235
+ */
1236
+ identities?: AuthIdentity[];
1237
+ /** Initial tools to register */
1238
+ tools?: ToolFunction[];
1239
+ /** Storage for session persistence */
1240
+ storage?: IContextStorage;
1241
+ /** Plugin-specific configurations (used with features flags) */
1242
+ plugins?: PluginConfigs;
1243
+ /**
1244
+ * Hard timeout in milliseconds for any single tool execution.
1245
+ * Acts as a safety net: if a tool's own timeout mechanism fails
1246
+ * (e.g. a child process doesn't exit), this will force-resolve with an error.
1247
+ * Default: 0 (disabled - relies on each tool's own timeout)
1248
+ */
1249
+ toolExecutionTimeout?: number;
1250
+ }
1251
+ /**
1252
+ * Default configuration values
1253
+ */
1254
+ declare const DEFAULT_CONFIG: {
1255
+ responseReserve: number;
1256
+ strategy: string;
1257
+ };
1258
+
1259
+ /**
1260
+ * Events emitted by AgentContextNextGen
1261
+ */
1262
+ interface ContextEvents {
1263
+ /** Emitted when context is prepared */
1264
+ 'context:prepared': {
1265
+ budget: ContextBudget;
1266
+ compacted: boolean;
1267
+ };
1268
+ /** Emitted when compaction is performed */
1269
+ 'context:compacted': {
1270
+ tokensFreed: number;
1271
+ log: string[];
1272
+ };
1273
+ /** Emitted right after budget is calculated in prepare() - for reactive monitoring */
1274
+ 'budget:updated': {
1275
+ budget: ContextBudget;
1276
+ timestamp: number;
1277
+ };
1278
+ /** Emitted when budget reaches warning threshold (>70%) */
1279
+ 'budget:warning': {
1280
+ budget: ContextBudget;
1281
+ };
1282
+ /** Emitted when budget reaches critical threshold (>90%) */
1283
+ 'budget:critical': {
1284
+ budget: ContextBudget;
1285
+ };
1286
+ /** Emitted when compaction is about to start */
1287
+ 'compaction:starting': {
1288
+ budget: ContextBudget;
1289
+ targetTokensToFree: number;
1290
+ timestamp: number;
1291
+ };
1292
+ /** Emitted when current input is too large */
1293
+ 'input:oversized': {
1294
+ result: OversizedInputResult;
1295
+ };
1296
+ /** Emitted when a message is added */
1297
+ 'message:added': {
1298
+ role: string;
1299
+ index: number;
1300
+ };
1301
+ /** Emitted when conversation is cleared */
1302
+ 'conversation:cleared': {
1303
+ reason?: string;
1304
+ };
1305
+ }
1306
+ /**
1307
+ * Callback type for beforeCompaction hook.
1308
+ * Called before compaction starts, allowing agents to save important data.
1309
+ */
1310
+ type BeforeCompactionCallback = (info: {
1311
+ budget: ContextBudget;
1312
+ targetTokensToFree: number;
1313
+ strategy: string;
1314
+ }) => Promise<void>;
1315
+ /**
1316
+ * Result of compact() operation.
1317
+ */
1318
+ interface CompactionResult {
1319
+ /** Tokens actually freed by compaction */
1320
+ tokensFreed: number;
1321
+ /** Number of messages removed from conversation */
1322
+ messagesRemoved: number;
1323
+ /** Names of plugins that were compacted */
1324
+ pluginsCompacted: string[];
1325
+ /** Log of actions taken during compaction */
1326
+ log: string[];
1327
+ }
1328
+ /**
1329
+ * Result of consolidate() operation.
1330
+ */
1331
+ interface ConsolidationResult {
1332
+ /** Whether any consolidation was performed */
1333
+ performed: boolean;
1334
+ /** Net token change (negative = freed, positive = added, e.g., summaries) */
1335
+ tokensChanged: number;
1336
+ /** Description of actions taken */
1337
+ actions: string[];
1338
+ }
1339
+ /**
1340
+ * Read-only context passed to compaction strategies.
1341
+ * Provides access to data needed for compaction decisions and
1342
+ * controlled methods to modify state.
1343
+ */
1344
+ interface CompactionContext {
1345
+ /** Current budget (from prepare) */
1346
+ readonly budget: ContextBudget;
1347
+ /** Current conversation history (read-only) */
1348
+ readonly conversation: ReadonlyArray<InputItem>;
1349
+ /** Current input (read-only) */
1350
+ readonly currentInput: ReadonlyArray<InputItem>;
1351
+ /** Registered plugins (for querying state) */
1352
+ readonly plugins: ReadonlyArray<IContextPluginNextGen>;
1353
+ /** Strategy name for logging */
1354
+ readonly strategyName: string;
1355
+ /**
1356
+ * Remove messages by indices.
1357
+ * Handles tool pair preservation internally.
1358
+ *
1359
+ * @param indices - Array of message indices to remove
1360
+ * @returns Tokens actually freed
1361
+ */
1362
+ removeMessages(indices: number[]): Promise<number>;
1363
+ /**
1364
+ * Compact a specific plugin.
1365
+ *
1366
+ * @param pluginName - Name of the plugin to compact
1367
+ * @param targetTokens - Approximate tokens to free
1368
+ * @returns Tokens actually freed
1369
+ */
1370
+ compactPlugin(pluginName: string, targetTokens: number): Promise<number>;
1371
+ /**
1372
+ * Estimate tokens for an item.
1373
+ *
1374
+ * @param item - Input item to estimate
1375
+ * @returns Estimated token count
1376
+ */
1377
+ estimateTokens(item: InputItem): number;
1378
+ }
1379
+ /**
1380
+ * Compaction strategy interface.
1381
+ *
1382
+ * Strategies implement two methods:
1383
+ * - `compact()`: Emergency compaction when thresholds exceeded (called from prepare())
1384
+ * - `consolidate()`: Post-cycle cleanup and optimization (called after agentic loop)
1385
+ *
1386
+ * Use `compact()` for quick, threshold-based token reduction.
1387
+ * Use `consolidate()` for more expensive operations like summarization.
1388
+ */
1389
+ interface ICompactionStrategy {
1390
+ /** Strategy name (unique identifier) for identification and logging */
1391
+ readonly name: string;
1392
+ /** Human-readable display name for UI */
1393
+ readonly displayName: string;
1394
+ /** Description explaining the strategy behavior */
1395
+ readonly description: string;
1396
+ /** Threshold percentage (0-1) at which compact() is triggered */
1397
+ readonly threshold: number;
1398
+ /**
1399
+ * Plugin names this strategy requires to function.
1400
+ * Validation is performed when strategy is assigned to context.
1401
+ * If any required plugin is missing, an error is thrown.
1402
+ *
1403
+ * @example
1404
+ * ```typescript
1405
+ * readonly requiredPlugins = ['working_memory'] as const;
1406
+ * ```
1407
+ */
1408
+ readonly requiredPlugins?: readonly string[];
1409
+ /**
1410
+ * Emergency compaction - triggered when context usage exceeds threshold.
1411
+ * Called from prepare() when utilization > threshold.
1412
+ *
1413
+ * Should be fast and focus on freeing tokens quickly.
1414
+ *
1415
+ * @param context - Compaction context with controlled access to state
1416
+ * @param targetToFree - Approximate tokens to free
1417
+ * @returns Result describing what was done
1418
+ */
1419
+ compact(context: CompactionContext, targetToFree: number): Promise<CompactionResult>;
1420
+ /**
1421
+ * Post-cycle consolidation - run after agentic cycle completes.
1422
+ * Called from Agent after run()/stream() finishes (before session save).
1423
+ *
1424
+ * Use for more expensive operations:
1425
+ * - Summarizing long conversations
1426
+ * - Memory optimization and deduplication
1427
+ * - Promoting important data to persistent storage
1428
+ *
1429
+ * @param context - Compaction context with controlled access to state
1430
+ * @returns Result describing what was done
1431
+ */
1432
+ consolidate(context: CompactionContext): Promise<ConsolidationResult>;
1433
+ }
1434
+
580
1435
  /**
581
1436
  * LLM Response entity based on OpenAI Responses API format
582
1437
  */
@@ -1394,4 +2249,4 @@ declare class HookManager {
1394
2249
  getDisabledHooks(): string[];
1395
2250
  }
1396
2251
 
1397
- export { type InputTextContent as $, type AgentEvents as A, type AgenticLoopEventName as B, type Content as C, type AgenticLoopEvents as D, ExecutionContext as E, type FunctionToolDefinition as F, type ApprovalResult as G, type HookConfig as H, type InputItem as I, type ApproveToolContext as J, type BeforeToolContext as K, type LLMResponse as L, type MemoryEntry as M, type BuiltInTool as N, type OutputItem as O, type PriorityCalculator as P, type CompactionItem as Q, ContentType as R, type StreamEvent as S, type ToolFunction as T, DEFAULT_MEMORY_CONFIG as U, type ErrorEvent as V, type WorkingMemoryConfig as W, type ExecutionConfig as X, type Hook as Y, HookManager as Z, type InputImageContent as _, type MemoryScope as a, type IterationCompleteEvent$1 as a0, type JSONSchema as a1, MEMORY_PRIORITY_VALUES as a2, type MemoryEntryInput as a3, type MemoryIndexEntry as a4, type Message as a5, type ModifyingHook as a6, type OutputTextContent as a7, type OutputTextDeltaEvent as a8, type OutputTextDoneEvent as a9, isReasoningDelta as aA, isReasoningDone as aB, isResponseComplete as aC, isSimpleScope as aD, isStreamEvent as aE, isTaskAwareScope as aF, isTerminalMemoryStatus as aG, isToolCallArgumentsDelta as aH, isToolCallArgumentsDone as aI, isToolCallStart as aJ, scopeEquals as aK, scopeMatches as aL, type ExecutionCompleteEvent as aM, type ExecutionStartEvent as aN, type LLMRequestEvent as aO, type LLMResponseEvent as aP, type ToolCompleteEvent as aQ, type ToolStartEvent as aR, type ReasoningDeltaEvent as aa, type ReasoningDoneEvent as ab, type ReasoningItem as ac, type ResponseCompleteEvent as ad, type ResponseCreatedEvent as ae, type ResponseInProgressEvent as af, type SimpleScope as ag, type TaskAwareScope as ah, type ThinkingContent as ai, type ToolCallArgumentsDeltaEvent as aj, type ToolCallArgumentsDoneEvent as ak, type ToolCallStartEvent as al, ToolCallState as am, type ToolExecutionContext as an, type ToolExecutionDoneEvent as ao, type ToolExecutionStartEvent as ap, type ToolModification as aq, type ToolResultContent as ar, type ToolUseContent as as, calculateEntrySize as at, defaultDescribeCall as au, forPlan as av, forTasks as aw, getToolCallDescription as ax, isErrorEvent as ay, isOutputTextDelta as az, type Tool as b, type ToolContext as c, type ToolPermissionConfig as d, type ToolCall as e, type MemoryPriority as f, type MemoryTier as g, type ToolResult as h, type ITextProvider as i, type HistoryMode as j, type AgentResponse as k, type ExecutionMetrics as l, type AuditEntry as m, type HookName as n, type StaleEntryInfo as o, type PriorityContext as p, type MemoryIndex as q, type TaskStatusForMemory as r, type WorkingMemoryAccess as s, type TokenUsage as t, StreamEventType as u, type TextGenerateOptions as v, type ModelCapabilities as w, MessageRole as x, type AfterToolContext as y, type AgentEventName as z };
2252
+ export { type TextGenerateOptions 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 CompactionContext as J, type CompactionResult as K, type LLMResponse as L, type MemoryEntry as M, type StaleEntryInfo as N, type OutputItem as O, type PriorityCalculator as P, type PriorityContext as Q, type MemoryIndex as R, type SerializedContextState as S, type Tool as T, type TaskStatusForMemory as U, type WorkingMemoryAccess as V, type WorkingMemoryConfig as W, type ContextStorageListOptions as X, type ContextSessionSummary as Y, type TokenUsage as Z, StreamEventType as _, type MemoryScope as a, isSimpleScope as a$, type ModelCapabilities as a0, MessageRole as a1, type AfterToolContext as a2, type AgentEventName as a3, type AgenticLoopEventName as a4, type AgenticLoopEvents as a5, type ApprovalResult as a6, type ApproveToolContext as a7, type BeforeToolContext as a8, type BuiltInTool as a9, type ReasoningItem as aA, type ResponseCompleteEvent as aB, type ResponseCreatedEvent as aC, type ResponseInProgressEvent as aD, type SimpleScope as aE, type TaskAwareScope as aF, type ThinkingContent as aG, type ToolCallArgumentsDeltaEvent as aH, type ToolCallArgumentsDoneEvent as aI, type ToolCallStartEvent as aJ, ToolCallState as aK, type ToolExecutionContext as aL, type ToolExecutionDoneEvent as aM, type ToolExecutionStartEvent as aN, type ToolModification as aO, type ToolResultContent as aP, type ToolUseContent as aQ, calculateEntrySize as aR, defaultDescribeCall as aS, forPlan as aT, forTasks as aU, getToolCallDescription as aV, isErrorEvent as aW, isOutputTextDelta as aX, isReasoningDelta as aY, isReasoningDone as aZ, isResponseComplete as a_, CONTEXT_SESSION_FORMAT_VERSION as aa, type CompactionItem as ab, ContentType as ac, DEFAULT_CONFIG as ad, DEFAULT_FEATURES as ae, DEFAULT_MEMORY_CONFIG as af, type ErrorEvent as ag, type ExecutionConfig as ah, type Hook as ai, HookManager as aj, type InputImageContent as ak, type InputTextContent as al, type IterationCompleteEvent$1 as am, type JSONSchema 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 PluginConfigs as ax, type ReasoningDeltaEvent as ay, type ReasoningDoneEvent as az, type ToolFunction as b, isStreamEvent as b0, isTaskAwareScope as b1, isTerminalMemoryStatus as b2, isToolCallArgumentsDelta as b3, isToolCallArgumentsDone as b4, isToolCallStart as b5, scopeEquals as b6, scopeMatches as b7, type ExecutionCompleteEvent as b8, type ExecutionStartEvent as b9, type LLMRequestEvent as ba, type LLMResponseEvent as bb, type ToolCompleteEvent as bc, type ToolStartEvent as bd, 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 };