@yourgpt/copilot-sdk 0.1.0 → 1.0.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.
@@ -1,212 +1,3 @@
1
- /**
2
- * Tool types for App Context Awareness
3
- */
4
- interface ScreenshotOptions {
5
- /** Target element to capture (defaults to document.body) */
6
- element?: HTMLElement;
7
- /** Image quality (0.1-1.0, default 0.8) */
8
- quality?: number;
9
- /** Image format */
10
- format?: "png" | "jpeg" | "webp";
11
- /** Max width to scale down to */
12
- maxWidth?: number;
13
- /** Max height to scale down to */
14
- maxHeight?: number;
15
- /** Whether to include cursor */
16
- includeCursor?: boolean;
17
- }
18
- interface ScreenshotResult {
19
- /** Base64-encoded image data */
20
- data: string;
21
- /** Image format */
22
- format: "png" | "jpeg" | "webp";
23
- /** Image width */
24
- width: number;
25
- /** Image height */
26
- height: number;
27
- /** Timestamp of capture */
28
- timestamp: number;
29
- }
30
- type ConsoleLogType = "log" | "info" | "warn" | "error" | "debug";
31
- interface ConsoleLogEntry {
32
- /** Type of console method */
33
- type: ConsoleLogType;
34
- /** Log message(s) */
35
- message: string;
36
- /** Additional arguments passed to console */
37
- args?: unknown[];
38
- /** Stack trace (for errors) */
39
- stack?: string;
40
- /** Timestamp */
41
- timestamp: number;
42
- }
43
- interface ConsoleLogOptions {
44
- /** Types of logs to capture */
45
- types?: ConsoleLogType[];
46
- /** Maximum number of logs to store */
47
- limit?: number;
48
- /** Filter function */
49
- filter?: (entry: ConsoleLogEntry) => boolean;
50
- }
51
- interface ConsoleLogResult {
52
- /** Captured log entries */
53
- logs: ConsoleLogEntry[];
54
- /** Total logs captured (before limit) */
55
- totalCaptured: number;
56
- }
57
- type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
58
- interface NetworkRequestEntry {
59
- /** Request URL */
60
- url: string;
61
- /** HTTP method */
62
- method: HttpMethod;
63
- /** Response status code */
64
- status: number;
65
- /** Status text */
66
- statusText: string;
67
- /** Whether request failed (non-2xx or error) */
68
- failed: boolean;
69
- /** Request headers (sanitized) */
70
- requestHeaders?: Record<string, string>;
71
- /** Response headers (sanitized) */
72
- responseHeaders?: Record<string, string>;
73
- /** Request body (if captured) */
74
- requestBody?: unknown;
75
- /** Response body (if captured and failed) */
76
- responseBody?: unknown;
77
- /** Request duration in ms */
78
- duration: number;
79
- /** Timestamp of request start */
80
- timestamp: number;
81
- /** Error message if request failed */
82
- error?: string;
83
- }
84
- interface NetworkRequestOptions {
85
- /** Maximum number of requests to store */
86
- limit?: number;
87
- /** Only capture failed requests (default: true) */
88
- failedOnly?: boolean;
89
- /** HTTP methods to capture */
90
- methods?: HttpMethod[];
91
- /** URL patterns to include (regex) */
92
- includeUrls?: RegExp[];
93
- /** URL patterns to exclude (regex) */
94
- excludeUrls?: RegExp[];
95
- /** Whether to capture request body */
96
- captureRequestBody?: boolean;
97
- /** Whether to capture response body */
98
- captureResponseBody?: boolean;
99
- /** Max body size to capture (bytes) */
100
- maxBodySize?: number;
101
- }
102
- interface NetworkRequestResult {
103
- /** Captured network requests */
104
- requests: NetworkRequestEntry[];
105
- /** Total requests captured (before limit) */
106
- totalCaptured: number;
107
- }
108
- type ToolType = "screenshot" | "console" | "network";
109
- interface IntentDetectionResult {
110
- /** Detected tools that might be helpful */
111
- suggestedTools: ToolType[];
112
- /** Confidence score (0-1) for each tool */
113
- confidence: Record<ToolType, number>;
114
- /** Keywords that triggered detection */
115
- matchedKeywords: Record<ToolType, string[]>;
116
- }
117
- interface ToolsConfig {
118
- /** Enable screenshot capture */
119
- screenshot?: boolean;
120
- /** Enable console log capture */
121
- console?: boolean;
122
- /** Enable network request capture */
123
- network?: boolean;
124
- /** Always require user consent before capturing (default: true) */
125
- requireConsent?: boolean;
126
- /** Screenshot-specific options */
127
- screenshotOptions?: ScreenshotOptions;
128
- /** Console-specific options */
129
- consoleOptions?: ConsoleLogOptions;
130
- /** Network-specific options */
131
- networkOptions?: NetworkRequestOptions;
132
- }
133
- interface ToolConsentRequest {
134
- /** Tools being requested */
135
- tools: ToolType[];
136
- /** Reason for request (from intent detection) */
137
- reason: string;
138
- /** Keywords that triggered this request */
139
- keywords: string[];
140
- }
141
- interface ToolConsentResponse {
142
- /** Tools user approved */
143
- approved: ToolType[];
144
- /** Tools user denied */
145
- denied: ToolType[];
146
- /** Remember preference for session */
147
- remember?: boolean;
148
- }
149
- interface CapturedContext {
150
- /** Screenshot data (if captured) */
151
- screenshot?: ScreenshotResult;
152
- /** Console logs (if captured) */
153
- consoleLogs?: ConsoleLogResult;
154
- /** Network requests (if captured) */
155
- networkRequests?: NetworkRequestResult;
156
- /** Timestamp of capture */
157
- timestamp: number;
158
- }
159
-
160
- /**
161
- * Intent Detector
162
- *
163
- * Detects user intent from messages to suggest relevant tools.
164
- * Framework-agnostic implementation using keyword matching.
165
- */
166
-
167
- /**
168
- * Detect user intent from a message
169
- *
170
- * @param message - User message to analyze
171
- * @returns Detection result with suggested tools
172
- *
173
- * @example
174
- * ```typescript
175
- * const result = detectIntent("I'm seeing an error on my screen");
176
- * // Returns:
177
- * // {
178
- * // suggestedTools: ['screenshot', 'console'],
179
- * // confidence: { screenshot: 0.6, console: 0.8, network: 0 },
180
- * // matchedKeywords: { screenshot: ['seeing', 'screen'], console: ['error'] }
181
- * // }
182
- * ```
183
- */
184
- declare function detectIntent(message: string): IntentDetectionResult;
185
- /**
186
- * Check if a message suggests any tools
187
- */
188
- declare function hasToolSuggestions(message: string): boolean;
189
- /**
190
- * Get the primary suggested tool (highest confidence)
191
- */
192
- declare function getPrimaryTool(message: string): ToolType | null;
193
- /**
194
- * Generate a reason string for why tools are being suggested
195
- */
196
- declare function generateSuggestionReason(result: IntentDetectionResult): string;
197
- /**
198
- * Custom keyword configuration
199
- */
200
- interface CustomKeywords {
201
- screenshot?: string[];
202
- console?: string[];
203
- network?: string[];
204
- }
205
- /**
206
- * Create a custom intent detector with additional keywords
207
- */
208
- declare function createCustomDetector(customKeywords: CustomKeywords): (message: string) => IntentDetectionResult;
209
-
210
1
  /**
211
2
  * Tool-related types for the agentic loop
212
3
  */
@@ -297,6 +88,23 @@ interface ToolContext {
297
88
  /** Request headers */
298
89
  headers?: Record<string, string>;
299
90
  };
91
+ /**
92
+ * Data passed from user's approval action.
93
+ * Only present when tool has `needsApproval: true` and user approved with extra data.
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * // In render function:
98
+ * approval.onApprove({ supervisor: selectedSupervisor });
99
+ *
100
+ * // In handler:
101
+ * handler: async (params, context) => {
102
+ * const supervisor = context?.approvalData?.supervisor;
103
+ * await assignToSupervisor(params.ticketId, supervisor);
104
+ * }
105
+ * ```
106
+ */
107
+ approvalData?: Record<string, unknown>;
300
108
  }
301
109
  /**
302
110
  * AI response behavior for tool results.
@@ -368,17 +176,79 @@ interface ToolResponse<T = unknown> {
368
176
  _aiContent?: AIContent[];
369
177
  }
370
178
  /**
371
- * Props passed to tool render function
179
+ * Approval callbacks passed to render when tool requires user action.
180
+ * Only present when status is "approval-required".
181
+ */
182
+ interface ToolApprovalCallbacks {
183
+ /**
184
+ * Approve execution and optionally pass extra data to the handler.
185
+ * The extraData is available in handler via `context.approvalData`.
186
+ *
187
+ * @example
188
+ * ```tsx
189
+ * // Simple approval
190
+ * approval.onApprove();
191
+ *
192
+ * // Approval with data (e.g., user selection)
193
+ * approval.onApprove({ supervisor: { name: "John", role: "Manager" } });
194
+ * ```
195
+ */
196
+ onApprove: (extraData?: Record<string, unknown>) => void;
197
+ /**
198
+ * Reject the tool execution with optional reason.
199
+ * This stops the tool from executing and returns an error to AI.
200
+ */
201
+ onReject: (reason?: string) => void;
202
+ /** Custom message from tool's approvalMessage config */
203
+ message?: string;
204
+ }
205
+ /**
206
+ * Props passed to tool render function.
207
+ *
208
+ * The render function is called for every status change, enabling
209
+ * full lifecycle rendering similar to Vercel AI SDK.
210
+ *
211
+ * @example
212
+ * ```tsx
213
+ * render: ({ status, args, approval, result }) => {
214
+ * if (status === "approval-required" && approval) {
215
+ * return <ApprovalCard onConfirm={() => approval.onApprove()} />;
216
+ * }
217
+ * if (status === "executing") {
218
+ * return <LoadingSkeleton />;
219
+ * }
220
+ * if (status === "completed") {
221
+ * return <ResultCard data={result.data} />;
222
+ * }
223
+ * return null;
224
+ * }
225
+ * ```
372
226
  */
373
227
  interface ToolRenderProps<TParams = Record<string, unknown>> {
374
- /** Current execution status */
375
- status: "pending" | "executing" | "completed" | "error";
228
+ /**
229
+ * Current execution status:
230
+ * - `pending`: Tool call received, waiting to start
231
+ * - `approval-required`: Waiting for user approval (when needsApproval is set)
232
+ * - `executing`: Handler is running
233
+ * - `completed`: Handler finished successfully
234
+ * - `error`: Handler failed
235
+ */
236
+ status: "pending" | "approval-required" | "executing" | "completed" | "error";
376
237
  /** Arguments passed to the tool */
377
238
  args: TParams;
378
239
  /** Result if completed */
379
240
  result?: ToolResponse;
380
241
  /** Error if failed */
381
242
  error?: string;
243
+ /** Tool call ID */
244
+ toolCallId: string;
245
+ /** Tool name */
246
+ toolName: string;
247
+ /**
248
+ * Approval callbacks - only present when status is "approval-required".
249
+ * Use these to create custom approval UIs that can pass extra data to the handler.
250
+ */
251
+ approval?: ToolApprovalCallbacks;
382
252
  }
383
253
  /**
384
254
  * Tool definition with JSON Schema
@@ -910,269 +780,6 @@ declare function hasToolCalls(message: Message): boolean;
910
780
  */
911
781
  declare function isToolResult(message: Message): boolean;
912
782
 
913
- /**
914
- * Supported LLM providers
915
- */
916
- type LLMProvider = "openai" | "anthropic" | "google" | "groq" | "ollama" | "custom";
917
- /**
918
- * LLM configuration
919
- */
920
- interface LLMConfig {
921
- /** LLM provider */
922
- provider: LLMProvider;
923
- /** Model name (e.g., 'gpt-4o', 'claude-3-5-sonnet-latest') */
924
- model?: string;
925
- /** API key for the provider */
926
- apiKey?: string;
927
- /** Base URL for custom/self-hosted models */
928
- baseUrl?: string;
929
- /** Temperature (0-2) */
930
- temperature?: number;
931
- /** Maximum tokens in response */
932
- maxTokens?: number;
933
- /** Top P sampling */
934
- topP?: number;
935
- /** Frequency penalty */
936
- frequencyPenalty?: number;
937
- /** Presence penalty */
938
- presencePenalty?: number;
939
- /** Enable streaming responses (default: true) */
940
- streaming?: boolean;
941
- }
942
- /**
943
- * Cloud configuration (for managed hosting)
944
- */
945
- interface CloudConfig {
946
- /** API key */
947
- apiKey: string;
948
- /** Bot ID */
949
- botId: string;
950
- /** Custom API endpoint (optional) */
951
- endpoint?: string;
952
- }
953
- /**
954
- * Extension configuration
955
- */
956
- interface Extension {
957
- /** Extension name */
958
- name: string;
959
- /** Extension configuration */
960
- config: Record<string, unknown>;
961
- /** Initialize the extension */
962
- init?: () => Promise<void>;
963
- }
964
- /**
965
- * Main SDK configuration
966
- */
967
- interface CopilotConfig {
968
- /** LLM configuration (for self-hosted) */
969
- config?: LLMConfig;
970
- /** Cloud configuration (for managed hosting) */
971
- cloud?: CloudConfig;
972
- /** Runtime URL for self-hosted backend */
973
- runtimeUrl?: string;
974
- /** System prompt */
975
- systemPrompt?: string;
976
- /** Extensions (like knowledge base) */
977
- extensions?: Extension[];
978
- /** Enable debug logging */
979
- debug?: boolean;
980
- }
981
- /**
982
- * Default LLM configurations per provider
983
- */
984
- declare const DEFAULT_MODELS: Record<LLMProvider, string>;
985
- /**
986
- * Get default model for a provider
987
- */
988
- declare function getDefaultModel(provider: LLMProvider): string;
989
-
990
- /**
991
- * Parameter types for actions
992
- */
993
- type ParameterType = "string" | "number" | "boolean" | "object" | "array";
994
- /**
995
- * Action parameter definition
996
- */
997
- interface ActionParameter {
998
- /** Parameter type */
999
- type: ParameterType;
1000
- /** Description of the parameter */
1001
- description?: string;
1002
- /** Whether the parameter is required */
1003
- required?: boolean;
1004
- /** Default value */
1005
- default?: unknown;
1006
- /** Enum values for string type */
1007
- enum?: string[];
1008
- /** Properties for object type */
1009
- properties?: Record<string, ActionParameter>;
1010
- /** Items schema for array type */
1011
- items?: ActionParameter;
1012
- }
1013
- /**
1014
- * Action definition
1015
- */
1016
- interface ActionDefinition<TParams = Record<string, unknown>> {
1017
- /** Unique name for the action */
1018
- name: string;
1019
- /** Description of what the action does */
1020
- description: string;
1021
- /** Parameter definitions */
1022
- parameters?: Record<string, ActionParameter>;
1023
- /** Handler function */
1024
- handler: (params: TParams) => unknown | Promise<unknown>;
1025
- /** Optional render function for UI */
1026
- render?: (props: ActionRenderProps<TParams>) => unknown;
1027
- }
1028
- /**
1029
- * Props passed to action render function
1030
- */
1031
- interface ActionRenderProps<TParams = Record<string, unknown>> {
1032
- /** Current status */
1033
- status: "pending" | "executing" | "completed" | "error";
1034
- /** Arguments passed to the action */
1035
- args: TParams;
1036
- /** Result if completed */
1037
- result?: unknown;
1038
- /** Error if failed */
1039
- error?: string;
1040
- }
1041
- /**
1042
- * Convert action definition to OpenAI tool format
1043
- */
1044
- declare function actionToTool(action: ActionDefinition): object;
1045
-
1046
- /**
1047
- * Knowledge Base Types
1048
- *
1049
- * Configuration and types for Knowledge Base (RAG) integration.
1050
- * Currently a placeholder - full implementation coming soon.
1051
- */
1052
- /**
1053
- * Supported vector database providers
1054
- */
1055
- type KnowledgeBaseProvider = "pinecone" | "qdrant" | "chroma" | "supabase" | "weaviate" | "custom";
1056
- /**
1057
- * Knowledge Base configuration
1058
- */
1059
- interface KnowledgeBaseConfig {
1060
- /** Unique identifier for this knowledge base */
1061
- id: string;
1062
- /** Display name */
1063
- name?: string;
1064
- /** Vector database provider */
1065
- provider: KnowledgeBaseProvider;
1066
- /** API key for the vector database */
1067
- apiKey?: string;
1068
- /** Index/collection name */
1069
- index?: string;
1070
- /** Namespace within the index */
1071
- namespace?: string;
1072
- /** Custom endpoint URL (for self-hosted or custom providers) */
1073
- endpoint?: string;
1074
- /** Number of results to return (default: 5) */
1075
- topK?: number;
1076
- /** Minimum similarity score threshold (0-1) */
1077
- scoreThreshold?: number;
1078
- /** Whether to include source metadata in results */
1079
- includeMetadata?: boolean;
1080
- }
1081
- /**
1082
- * Knowledge Base search result
1083
- */
1084
- interface KnowledgeBaseResult {
1085
- /** Result content/text */
1086
- content: string;
1087
- /** Similarity score (0-1) */
1088
- score: number;
1089
- /** Source metadata */
1090
- metadata?: {
1091
- /** Source document/URL */
1092
- source?: string;
1093
- /** Document title */
1094
- title?: string;
1095
- /** Page number (for PDFs) */
1096
- page?: number;
1097
- /** Chunk index */
1098
- chunk?: number;
1099
- /** Any additional metadata */
1100
- [key: string]: unknown;
1101
- };
1102
- }
1103
- /**
1104
- * Knowledge Base search request
1105
- */
1106
- interface KnowledgeBaseSearchRequest {
1107
- /** Search query */
1108
- query: string;
1109
- /** Knowledge base ID to search */
1110
- knowledgeBaseId: string;
1111
- /** Number of results (overrides config) */
1112
- limit?: number;
1113
- /** Filter by metadata */
1114
- filter?: Record<string, unknown>;
1115
- }
1116
- /**
1117
- * Knowledge Base search response
1118
- */
1119
- interface KnowledgeBaseSearchResponse {
1120
- /** Search results */
1121
- results: KnowledgeBaseResult[];
1122
- /** Knowledge base ID */
1123
- knowledgeBaseId: string;
1124
- /** Query that was searched */
1125
- query: string;
1126
- /** Search duration in ms */
1127
- durationMs?: number;
1128
- }
1129
- /**
1130
- * Internal Knowledge Base configuration
1131
- * Used for managed cloud searchIndexDocument API
1132
- */
1133
- interface InternalKnowledgeBaseConfig {
1134
- /** Project UID for the knowledge base */
1135
- projectUid: string;
1136
- /** Auth token for API calls */
1137
- token: string;
1138
- /** App ID (default: "1") */
1139
- appId?: string;
1140
- /** Results limit (default: 5) */
1141
- limit?: number;
1142
- /** Whether KB is enabled (default: true) */
1143
- enabled?: boolean;
1144
- }
1145
- /**
1146
- * Internal Knowledge Base search result
1147
- */
1148
- interface InternalKnowledgeBaseResult {
1149
- /** Document ID */
1150
- id: string;
1151
- /** Document title */
1152
- title?: string;
1153
- /** Matched content snippet */
1154
- content: string;
1155
- /** Relevance score */
1156
- score?: number;
1157
- /** Source URL if available */
1158
- url?: string;
1159
- /** Additional metadata */
1160
- metadata?: Record<string, unknown>;
1161
- }
1162
- /**
1163
- * Internal Knowledge Base search response
1164
- */
1165
- interface InternalKnowledgeBaseSearchResponse {
1166
- /** Whether the search was successful */
1167
- success: boolean;
1168
- /** Search results */
1169
- results: InternalKnowledgeBaseResult[];
1170
- /** Total number of results */
1171
- total?: number;
1172
- /** Error message if failed */
1173
- error?: string;
1174
- }
1175
-
1176
783
  /**
1177
784
  * Thread metadata (for listing threads)
1178
785
  */
@@ -1181,6 +788,10 @@ interface Thread {
1181
788
  id: string;
1182
789
  /** Thread title (auto-generated from first message or manual) */
1183
790
  title?: string;
791
+ /** Preview of the first message (for thread lists) */
792
+ preview?: string;
793
+ /** Number of messages in this thread */
794
+ messageCount?: number;
1184
795
  /** When thread was created */
1185
796
  createdAt: Date;
1186
797
  /** When thread was last updated */
@@ -1198,7 +809,7 @@ interface ThreadData extends Thread {
1198
809
  /**
1199
810
  * Persistence storage interface for custom adapters
1200
811
  */
1201
- interface ThreadStorageAdapter {
812
+ interface ThreadStorageAdapter$1 {
1202
813
  /** Save threads to storage */
1203
814
  save: (threads: ThreadData[]) => Promise<void>;
1204
815
  /** Load threads from storage */
@@ -1215,11 +826,136 @@ interface PersistenceConfig {
1215
826
  /** Storage type */
1216
827
  storage?: "localStorage" | "custom";
1217
828
  /** Custom storage adapter (required if storage is 'custom') */
1218
- customStorage?: ThreadStorageAdapter;
829
+ customStorage?: ThreadStorageAdapter$1;
1219
830
  }
1220
831
  /**
1221
832
  * Generate a thread title from message content
1222
833
  */
1223
834
  declare function generateThreadTitle(content: string): string;
1224
835
 
1225
- export { type Thread as $, type ToolCall as A, type TokenUsage as B, type ConsoleLogOptions as C, type LLMConfig as D, type CloudConfig as E, type Extension as F, type CopilotConfig as G, type HttpMethod as H, type IntentDetectionResult as I, type JSONSchemaProperty as J, type ActionParameter as K, type LLMProvider as L, type MessageAttachment as M, type NetworkRequestOptions as N, type ActionDefinition as O, type ParameterType as P, type ActionRenderProps as Q, type KnowledgeBaseProvider as R, type ScreenshotOptions as S, type ToolDefinition as T, type KnowledgeBaseConfig as U, type KnowledgeBaseResult as V, type KnowledgeBaseSearchRequest as W, type KnowledgeBaseSearchResponse as X, type InternalKnowledgeBaseConfig as Y, type InternalKnowledgeBaseResult as Z, type InternalKnowledgeBaseSearchResponse as _, type ScreenshotResult as a, type ThreadData as a0, type PersistenceConfig as a1, type ThreadStorageAdapter as a2, type AIProvider as a3, type ToolRenderProps as a4, type ToolConfig as a5, type ToolSet as a6, type UnifiedToolCall as a7, type UnifiedToolResult as a8, type ToolApprovalStatus as a9, failure as aA, type ToolExecution as aa, type AgentLoopConfig as ab, type AgentLoopState as ac, type AIResponseMode as ad, type AIContent as ae, type PermissionLevel as af, type ToolPermission as ag, type PermissionStorageConfig as ah, type PermissionStorageAdapter as ai, generateThreadTitle as aj, createMessage as ak, createUserMessage as al, createAssistantMessage as am, createToolMessage as an, createToolCall as ao, parseToolCallArgs as ap, hasToolCalls as aq, isToolResult as ar, actionToTool as as, getDefaultModel as at, DEFAULT_MODELS as au, tool as av, toolToOpenAIFormat as aw, toolToAnthropicFormat as ax, createToolResult as ay, success as az, type ConsoleLogResult as b, type ConsoleLogEntry as c, type NetworkRequestResult as d, type NetworkRequestEntry as e, type Source as f, type ToolExecutionStatus as g, type ToolResponse as h, type ToolInputSchema as i, type ToolLocation as j, type ToolContext as k, detectIntent as l, hasToolSuggestions as m, getPrimaryTool as n, generateSuggestionReason as o, createCustomDetector as p, type ConsoleLogType as q, type ToolType as r, type ToolsConfig as s, type ToolConsentRequest as t, type ToolConsentResponse as u, type CapturedContext as v, type CustomKeywords as w, type MessageRole as x, type Message as y, type MessageMetadata as z };
836
+ /**
837
+ * Thread Storage Adapter Types
838
+ *
839
+ * Interfaces for thread persistence adapters.
840
+ */
841
+
842
+ /**
843
+ * Basic thread storage adapter interface
844
+ * Used by ThreadManager for persistence
845
+ */
846
+ interface ThreadStorageAdapter {
847
+ /** Save all threads to storage */
848
+ save: (threads: ThreadData[]) => Promise<void>;
849
+ /** Load all threads from storage */
850
+ load: () => Promise<ThreadData[]>;
851
+ /** Clear all threads from storage */
852
+ clear: () => Promise<void>;
853
+ /**
854
+ * Get the last active thread ID
855
+ * Optional - used for session persistence
856
+ */
857
+ getLastActiveThreadId?: () => Promise<string | null>;
858
+ /**
859
+ * Set the last active thread ID
860
+ * Optional - used for session persistence
861
+ */
862
+ setLastActiveThreadId?: (threadId: string | null) => Promise<void>;
863
+ }
864
+ /**
865
+ * Pagination options for listing threads
866
+ */
867
+ interface ListThreadsOptions {
868
+ /** Maximum number of threads to return */
869
+ limit?: number;
870
+ /** Number of threads to skip */
871
+ offset?: number;
872
+ /** Sort order (default: updatedAt desc) */
873
+ orderBy?: "createdAt" | "updatedAt";
874
+ /** Sort direction */
875
+ orderDir?: "asc" | "desc";
876
+ }
877
+ /**
878
+ * Paginated response for thread listing
879
+ */
880
+ interface ListThreadsResult {
881
+ /** Threads for current page */
882
+ threads: Thread[];
883
+ /** Total number of threads */
884
+ total: number;
885
+ /** Whether there are more threads */
886
+ hasMore: boolean;
887
+ }
888
+ /**
889
+ * Async thread storage adapter with optimized single-thread operations
890
+ *
891
+ * Use this interface when implementing database backends (Supabase, Firebase, etc.)
892
+ * These methods are optional - if not provided, ThreadManager falls back to
893
+ * full save/load operations.
894
+ *
895
+ * @example Supabase adapter
896
+ * ```typescript
897
+ * const supabaseAdapter: AsyncThreadStorageAdapter = {
898
+ * save: async (threads) => { /* batch upsert *\/ },
899
+ * load: async () => { /* select all *\/ },
900
+ * clear: async () => { /* delete all *\/ },
901
+ *
902
+ * // Optimized operations
903
+ * getThread: async (id) => {
904
+ * const { data } = await supabase
905
+ * .from('threads')
906
+ * .select('*, messages(*)')
907
+ * .eq('id', id)
908
+ * .single();
909
+ * return data;
910
+ * },
911
+ * createThread: async (thread) => {
912
+ * const { data } = await supabase.from('threads').insert(thread).select().single();
913
+ * return data;
914
+ * },
915
+ * updateThread: async (id, updates) => {
916
+ * const { data } = await supabase.from('threads').update(updates).eq('id', id).select().single();
917
+ * return data;
918
+ * },
919
+ * deleteThread: async (id) => {
920
+ * await supabase.from('threads').delete().eq('id', id);
921
+ * },
922
+ * listThreads: async ({ limit, offset }) => {
923
+ * const { data, count } = await supabase
924
+ * .from('threads')
925
+ * .select('*', { count: 'exact' })
926
+ * .order('updatedAt', { ascending: false })
927
+ * .range(offset, offset + limit - 1);
928
+ * return { threads: data, total: count, hasMore: (offset + limit) < count };
929
+ * },
930
+ * };
931
+ * ```
932
+ */
933
+ interface AsyncThreadStorageAdapter extends ThreadStorageAdapter {
934
+ /**
935
+ * Get a single thread by ID
936
+ * If provided, used instead of loading all threads
937
+ */
938
+ getThread?: (id: string) => Promise<ThreadData | null>;
939
+ /**
940
+ * Create a new thread
941
+ * If provided, used instead of saving all threads
942
+ */
943
+ createThread?: (thread: ThreadData) => Promise<ThreadData>;
944
+ /**
945
+ * Update an existing thread
946
+ * If provided, used instead of saving all threads
947
+ */
948
+ updateThread?: (id: string, updates: Partial<ThreadData>) => Promise<ThreadData>;
949
+ /**
950
+ * Delete a thread by ID
951
+ * If provided, used instead of saving all threads
952
+ */
953
+ deleteThread?: (id: string) => Promise<void>;
954
+ /**
955
+ * List threads with pagination
956
+ * If provided, used for efficient thread listing
957
+ */
958
+ listThreads?: (options?: ListThreadsOptions) => Promise<ListThreadsResult>;
959
+ }
960
+
961
+ export { type AIProvider as A, type PermissionStorageAdapter as B, generateThreadTitle as C, createMessage as D, createUserMessage as E, createAssistantMessage as F, createToolMessage as G, createToolCall as H, parseToolCallArgs as I, type JSONSchemaProperty as J, hasToolCalls as K, isToolResult as L, type MessageAttachment as M, tool as N, toolToOpenAIFormat as O, type PersistenceConfig as P, toolToAnthropicFormat as Q, createToolResult as R, type Source as S, type ToolDefinition as T, type UnifiedToolCall as U, success as V, failure as W, type AsyncThreadStorageAdapter as X, type ListThreadsOptions as Y, type ListThreadsResult as Z, type ThreadStorageAdapter as _, type ToolExecutionStatus as a, type ToolResponse as b, type ToolInputSchema as c, type ToolLocation as d, type ToolContext as e, type MessageRole as f, type Message as g, type MessageMetadata as h, type ToolCall as i, type TokenUsage as j, type Thread as k, type ThreadData as l, type ThreadStorageAdapter$1 as m, type ToolRenderProps as n, type ToolConfig as o, type ToolSet as p, type UnifiedToolResult as q, type ToolApprovalStatus as r, type ToolExecution as s, type AgentLoopConfig as t, type AgentLoopState as u, type AIResponseMode as v, type AIContent as w, type PermissionLevel as x, type ToolPermission as y, type PermissionStorageConfig as z };