@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.
@@ -0,0 +1,863 @@
1
+ import { k as Thread, l as ThreadData, _ as ThreadStorageAdapter, X as AsyncThreadStorageAdapter, g as Message } from './types-BtAaOV07.cjs';
2
+
3
+ /**
4
+ * Tool types for App Context Awareness
5
+ */
6
+ interface ScreenshotOptions {
7
+ /** Target element to capture (defaults to document.body) */
8
+ element?: HTMLElement;
9
+ /** Image quality (0.1-1.0, default 0.8) */
10
+ quality?: number;
11
+ /** Image format */
12
+ format?: "png" | "jpeg" | "webp";
13
+ /** Max width to scale down to */
14
+ maxWidth?: number;
15
+ /** Max height to scale down to */
16
+ maxHeight?: number;
17
+ /** Whether to include cursor */
18
+ includeCursor?: boolean;
19
+ }
20
+ interface ScreenshotResult {
21
+ /** Base64-encoded image data */
22
+ data: string;
23
+ /** Image format */
24
+ format: "png" | "jpeg" | "webp";
25
+ /** Image width */
26
+ width: number;
27
+ /** Image height */
28
+ height: number;
29
+ /** Timestamp of capture */
30
+ timestamp: number;
31
+ }
32
+ type ConsoleLogType = "log" | "info" | "warn" | "error" | "debug";
33
+ interface ConsoleLogEntry {
34
+ /** Type of console method */
35
+ type: ConsoleLogType;
36
+ /** Log message(s) */
37
+ message: string;
38
+ /** Additional arguments passed to console */
39
+ args?: unknown[];
40
+ /** Stack trace (for errors) */
41
+ stack?: string;
42
+ /** Timestamp */
43
+ timestamp: number;
44
+ }
45
+ interface ConsoleLogOptions {
46
+ /** Types of logs to capture */
47
+ types?: ConsoleLogType[];
48
+ /** Maximum number of logs to store */
49
+ limit?: number;
50
+ /** Filter function */
51
+ filter?: (entry: ConsoleLogEntry) => boolean;
52
+ }
53
+ interface ConsoleLogResult {
54
+ /** Captured log entries */
55
+ logs: ConsoleLogEntry[];
56
+ /** Total logs captured (before limit) */
57
+ totalCaptured: number;
58
+ }
59
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
60
+ interface NetworkRequestEntry {
61
+ /** Request URL */
62
+ url: string;
63
+ /** HTTP method */
64
+ method: HttpMethod;
65
+ /** Response status code */
66
+ status: number;
67
+ /** Status text */
68
+ statusText: string;
69
+ /** Whether request failed (non-2xx or error) */
70
+ failed: boolean;
71
+ /** Request headers (sanitized) */
72
+ requestHeaders?: Record<string, string>;
73
+ /** Response headers (sanitized) */
74
+ responseHeaders?: Record<string, string>;
75
+ /** Request body (if captured) */
76
+ requestBody?: unknown;
77
+ /** Response body (if captured and failed) */
78
+ responseBody?: unknown;
79
+ /** Request duration in ms */
80
+ duration: number;
81
+ /** Timestamp of request start */
82
+ timestamp: number;
83
+ /** Error message if request failed */
84
+ error?: string;
85
+ }
86
+ interface NetworkRequestOptions {
87
+ /** Maximum number of requests to store */
88
+ limit?: number;
89
+ /** Only capture failed requests (default: true) */
90
+ failedOnly?: boolean;
91
+ /** HTTP methods to capture */
92
+ methods?: HttpMethod[];
93
+ /** URL patterns to include (regex) */
94
+ includeUrls?: RegExp[];
95
+ /** URL patterns to exclude (regex) */
96
+ excludeUrls?: RegExp[];
97
+ /** Whether to capture request body */
98
+ captureRequestBody?: boolean;
99
+ /** Whether to capture response body */
100
+ captureResponseBody?: boolean;
101
+ /** Max body size to capture (bytes) */
102
+ maxBodySize?: number;
103
+ }
104
+ interface NetworkRequestResult {
105
+ /** Captured network requests */
106
+ requests: NetworkRequestEntry[];
107
+ /** Total requests captured (before limit) */
108
+ totalCaptured: number;
109
+ }
110
+ type ToolType = "screenshot" | "console" | "network";
111
+ interface IntentDetectionResult {
112
+ /** Detected tools that might be helpful */
113
+ suggestedTools: ToolType[];
114
+ /** Confidence score (0-1) for each tool */
115
+ confidence: Record<ToolType, number>;
116
+ /** Keywords that triggered detection */
117
+ matchedKeywords: Record<ToolType, string[]>;
118
+ }
119
+ interface ToolsConfig {
120
+ /** Enable screenshot capture */
121
+ screenshot?: boolean;
122
+ /** Enable console log capture */
123
+ console?: boolean;
124
+ /** Enable network request capture */
125
+ network?: boolean;
126
+ /** Always require user consent before capturing (default: true) */
127
+ requireConsent?: boolean;
128
+ /** Screenshot-specific options */
129
+ screenshotOptions?: ScreenshotOptions;
130
+ /** Console-specific options */
131
+ consoleOptions?: ConsoleLogOptions;
132
+ /** Network-specific options */
133
+ networkOptions?: NetworkRequestOptions;
134
+ }
135
+ interface ToolConsentRequest {
136
+ /** Tools being requested */
137
+ tools: ToolType[];
138
+ /** Reason for request (from intent detection) */
139
+ reason: string;
140
+ /** Keywords that triggered this request */
141
+ keywords: string[];
142
+ }
143
+ interface ToolConsentResponse {
144
+ /** Tools user approved */
145
+ approved: ToolType[];
146
+ /** Tools user denied */
147
+ denied: ToolType[];
148
+ /** Remember preference for session */
149
+ remember?: boolean;
150
+ }
151
+ interface CapturedContext {
152
+ /** Screenshot data (if captured) */
153
+ screenshot?: ScreenshotResult;
154
+ /** Console logs (if captured) */
155
+ consoleLogs?: ConsoleLogResult;
156
+ /** Network requests (if captured) */
157
+ networkRequests?: NetworkRequestResult;
158
+ /** Timestamp of capture */
159
+ timestamp: number;
160
+ }
161
+
162
+ /**
163
+ * Intent Detector
164
+ *
165
+ * Detects user intent from messages to suggest relevant tools.
166
+ * Framework-agnostic implementation using keyword matching.
167
+ */
168
+
169
+ /**
170
+ * Detect user intent from a message
171
+ *
172
+ * @param message - User message to analyze
173
+ * @returns Detection result with suggested tools
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * const result = detectIntent("I'm seeing an error on my screen");
178
+ * // Returns:
179
+ * // {
180
+ * // suggestedTools: ['screenshot', 'console'],
181
+ * // confidence: { screenshot: 0.6, console: 0.8, network: 0 },
182
+ * // matchedKeywords: { screenshot: ['seeing', 'screen'], console: ['error'] }
183
+ * // }
184
+ * ```
185
+ */
186
+ declare function detectIntent(message: string): IntentDetectionResult;
187
+ /**
188
+ * Check if a message suggests any tools
189
+ */
190
+ declare function hasToolSuggestions(message: string): boolean;
191
+ /**
192
+ * Get the primary suggested tool (highest confidence)
193
+ */
194
+ declare function getPrimaryTool(message: string): ToolType | null;
195
+ /**
196
+ * Generate a reason string for why tools are being suggested
197
+ */
198
+ declare function generateSuggestionReason(result: IntentDetectionResult): string;
199
+ /**
200
+ * Custom keyword configuration
201
+ */
202
+ interface CustomKeywords {
203
+ screenshot?: string[];
204
+ console?: string[];
205
+ network?: string[];
206
+ }
207
+ /**
208
+ * Create a custom intent detector with additional keywords
209
+ */
210
+ declare function createCustomDetector(customKeywords: CustomKeywords): (message: string) => IntentDetectionResult;
211
+
212
+ /**
213
+ * Supported LLM providers
214
+ */
215
+ type LLMProvider = "openai" | "anthropic" | "google" | "groq" | "ollama" | "custom";
216
+ /**
217
+ * LLM configuration
218
+ */
219
+ interface LLMConfig {
220
+ /** LLM provider */
221
+ provider: LLMProvider;
222
+ /** Model name (e.g., 'gpt-4o', 'claude-3-5-sonnet-latest') */
223
+ model?: string;
224
+ /** API key for the provider */
225
+ apiKey?: string;
226
+ /** Base URL for custom/self-hosted models */
227
+ baseUrl?: string;
228
+ /** Temperature (0-2) */
229
+ temperature?: number;
230
+ /** Maximum tokens in response */
231
+ maxTokens?: number;
232
+ /** Top P sampling */
233
+ topP?: number;
234
+ /** Frequency penalty */
235
+ frequencyPenalty?: number;
236
+ /** Presence penalty */
237
+ presencePenalty?: number;
238
+ /** Enable streaming responses (default: true) */
239
+ streaming?: boolean;
240
+ }
241
+ /**
242
+ * Cloud configuration (for managed hosting)
243
+ */
244
+ interface CloudConfig {
245
+ /** API key */
246
+ apiKey: string;
247
+ /** Bot ID */
248
+ botId: string;
249
+ /** Custom API endpoint (optional) */
250
+ endpoint?: string;
251
+ }
252
+ /**
253
+ * Extension configuration
254
+ */
255
+ interface Extension {
256
+ /** Extension name */
257
+ name: string;
258
+ /** Extension configuration */
259
+ config: Record<string, unknown>;
260
+ /** Initialize the extension */
261
+ init?: () => Promise<void>;
262
+ }
263
+ /**
264
+ * Main SDK configuration
265
+ */
266
+ interface CopilotConfig {
267
+ /** LLM configuration (for self-hosted) */
268
+ config?: LLMConfig;
269
+ /** Cloud configuration (for managed hosting) */
270
+ cloud?: CloudConfig;
271
+ /** Runtime URL for self-hosted backend */
272
+ runtimeUrl?: string;
273
+ /** System prompt */
274
+ systemPrompt?: string;
275
+ /** Extensions (like knowledge base) */
276
+ extensions?: Extension[];
277
+ /** Enable debug logging */
278
+ debug?: boolean;
279
+ }
280
+ /**
281
+ * Default LLM configurations per provider
282
+ */
283
+ declare const DEFAULT_MODELS: Record<LLMProvider, string>;
284
+ /**
285
+ * Get default model for a provider
286
+ */
287
+ declare function getDefaultModel(provider: LLMProvider): string;
288
+
289
+ /**
290
+ * Parameter types for actions
291
+ */
292
+ type ParameterType = "string" | "number" | "boolean" | "object" | "array";
293
+ /**
294
+ * Action parameter definition
295
+ */
296
+ interface ActionParameter {
297
+ /** Parameter type */
298
+ type: ParameterType;
299
+ /** Description of the parameter */
300
+ description?: string;
301
+ /** Whether the parameter is required */
302
+ required?: boolean;
303
+ /** Default value */
304
+ default?: unknown;
305
+ /** Enum values for string type */
306
+ enum?: string[];
307
+ /** Properties for object type */
308
+ properties?: Record<string, ActionParameter>;
309
+ /** Items schema for array type */
310
+ items?: ActionParameter;
311
+ }
312
+ /**
313
+ * Action definition
314
+ */
315
+ interface ActionDefinition<TParams = Record<string, unknown>> {
316
+ /** Unique name for the action */
317
+ name: string;
318
+ /** Description of what the action does */
319
+ description: string;
320
+ /** Parameter definitions */
321
+ parameters?: Record<string, ActionParameter>;
322
+ /** Handler function */
323
+ handler: (params: TParams) => unknown | Promise<unknown>;
324
+ /** Optional render function for UI */
325
+ render?: (props: ActionRenderProps<TParams>) => unknown;
326
+ }
327
+ /**
328
+ * Props passed to action render function
329
+ */
330
+ interface ActionRenderProps<TParams = Record<string, unknown>> {
331
+ /** Current status */
332
+ status: "pending" | "executing" | "completed" | "error";
333
+ /** Arguments passed to the action */
334
+ args: TParams;
335
+ /** Result if completed */
336
+ result?: unknown;
337
+ /** Error if failed */
338
+ error?: string;
339
+ }
340
+ /**
341
+ * Convert action definition to OpenAI tool format
342
+ */
343
+ declare function actionToTool(action: ActionDefinition): object;
344
+
345
+ /**
346
+ * Knowledge Base Types
347
+ *
348
+ * Configuration and types for Knowledge Base (RAG) integration.
349
+ * Currently a placeholder - full implementation coming soon.
350
+ */
351
+ /**
352
+ * Supported vector database providers
353
+ */
354
+ type KnowledgeBaseProvider = "pinecone" | "qdrant" | "chroma" | "supabase" | "weaviate" | "custom";
355
+ /**
356
+ * Knowledge Base configuration
357
+ */
358
+ interface KnowledgeBaseConfig {
359
+ /** Unique identifier for this knowledge base */
360
+ id: string;
361
+ /** Display name */
362
+ name?: string;
363
+ /** Vector database provider */
364
+ provider: KnowledgeBaseProvider;
365
+ /** API key for the vector database */
366
+ apiKey?: string;
367
+ /** Index/collection name */
368
+ index?: string;
369
+ /** Namespace within the index */
370
+ namespace?: string;
371
+ /** Custom endpoint URL (for self-hosted or custom providers) */
372
+ endpoint?: string;
373
+ /** Number of results to return (default: 5) */
374
+ topK?: number;
375
+ /** Minimum similarity score threshold (0-1) */
376
+ scoreThreshold?: number;
377
+ /** Whether to include source metadata in results */
378
+ includeMetadata?: boolean;
379
+ }
380
+ /**
381
+ * Knowledge Base search result
382
+ */
383
+ interface KnowledgeBaseResult {
384
+ /** Result content/text */
385
+ content: string;
386
+ /** Similarity score (0-1) */
387
+ score: number;
388
+ /** Source metadata */
389
+ metadata?: {
390
+ /** Source document/URL */
391
+ source?: string;
392
+ /** Document title */
393
+ title?: string;
394
+ /** Page number (for PDFs) */
395
+ page?: number;
396
+ /** Chunk index */
397
+ chunk?: number;
398
+ /** Any additional metadata */
399
+ [key: string]: unknown;
400
+ };
401
+ }
402
+ /**
403
+ * Knowledge Base search request
404
+ */
405
+ interface KnowledgeBaseSearchRequest {
406
+ /** Search query */
407
+ query: string;
408
+ /** Knowledge base ID to search */
409
+ knowledgeBaseId: string;
410
+ /** Number of results (overrides config) */
411
+ limit?: number;
412
+ /** Filter by metadata */
413
+ filter?: Record<string, unknown>;
414
+ }
415
+ /**
416
+ * Knowledge Base search response
417
+ */
418
+ interface KnowledgeBaseSearchResponse {
419
+ /** Search results */
420
+ results: KnowledgeBaseResult[];
421
+ /** Knowledge base ID */
422
+ knowledgeBaseId: string;
423
+ /** Query that was searched */
424
+ query: string;
425
+ /** Search duration in ms */
426
+ durationMs?: number;
427
+ }
428
+ /**
429
+ * Internal Knowledge Base configuration
430
+ * Used for managed cloud searchIndexDocument API
431
+ */
432
+ interface InternalKnowledgeBaseConfig {
433
+ /** Project UID for the knowledge base */
434
+ projectUid: string;
435
+ /** Auth token for API calls */
436
+ token: string;
437
+ /** App ID (default: "1") */
438
+ appId?: string;
439
+ /** Results limit (default: 5) */
440
+ limit?: number;
441
+ /** Whether KB is enabled (default: true) */
442
+ enabled?: boolean;
443
+ }
444
+ /**
445
+ * Internal Knowledge Base search result
446
+ */
447
+ interface InternalKnowledgeBaseResult {
448
+ /** Document ID */
449
+ id: string;
450
+ /** Document title */
451
+ title?: string;
452
+ /** Matched content snippet */
453
+ content: string;
454
+ /** Relevance score */
455
+ score?: number;
456
+ /** Source URL if available */
457
+ url?: string;
458
+ /** Additional metadata */
459
+ metadata?: Record<string, unknown>;
460
+ }
461
+ /**
462
+ * Internal Knowledge Base search response
463
+ */
464
+ interface InternalKnowledgeBaseSearchResponse {
465
+ /** Whether the search was successful */
466
+ success: boolean;
467
+ /** Search results */
468
+ results: InternalKnowledgeBaseResult[];
469
+ /** Total number of results */
470
+ total?: number;
471
+ /** Error message if failed */
472
+ error?: string;
473
+ }
474
+
475
+ /**
476
+ * ThreadManagerState Interface
477
+ *
478
+ * Contract for framework-specific state implementations.
479
+ * Following the same pattern as ChatState for framework agnosticism.
480
+ */
481
+
482
+ /**
483
+ * Load status for async operations
484
+ */
485
+ type LoadStatus = "idle" | "loading" | "loaded" | "error";
486
+ /**
487
+ * ThreadManagerState interface - Framework adapters implement this
488
+ *
489
+ * This is the key abstraction that enables framework-agnostic code.
490
+ * The ThreadManager class uses this interface, and each framework
491
+ * provides its own implementation.
492
+ *
493
+ * @example React implementation
494
+ * ```typescript
495
+ * class ReactThreadManagerState implements ThreadManagerState {
496
+ * #threads: Thread[] = [];
497
+ * #callbacks = new Set<() => void>();
498
+ *
499
+ * get threads() { return this.#threads; }
500
+ * set threads(t) {
501
+ * this.#threads = t;
502
+ * this.#callbacks.forEach(cb => cb()); // Trigger re-render
503
+ * }
504
+ *
505
+ * subscribe(cb: () => void) {
506
+ * this.#callbacks.add(cb);
507
+ * return () => this.#callbacks.delete(cb);
508
+ * }
509
+ * }
510
+ * ```
511
+ */
512
+ interface ThreadManagerState {
513
+ /** All threads (metadata only) */
514
+ threads: Thread[];
515
+ /** Currently selected thread ID */
516
+ currentThreadId: string | null;
517
+ /** Currently loaded thread data (with messages) */
518
+ currentThread: ThreadData | null;
519
+ /** Current loading status */
520
+ loadStatus: LoadStatus;
521
+ /** Current error if any */
522
+ error: Error | undefined;
523
+ /**
524
+ * Set all threads
525
+ */
526
+ setThreads(threads: Thread[]): void;
527
+ /**
528
+ * Set the current thread
529
+ */
530
+ setCurrentThread(thread: ThreadData | null): void;
531
+ /**
532
+ * Set the current thread ID
533
+ */
534
+ setCurrentThreadId(id: string | null): void;
535
+ /**
536
+ * Add a new thread to the list
537
+ */
538
+ addThread(thread: Thread): void;
539
+ /**
540
+ * Update a thread's metadata
541
+ */
542
+ updateThread(id: string, updates: Partial<Thread>): void;
543
+ /**
544
+ * Remove a thread from the list
545
+ */
546
+ removeThread(id: string): void;
547
+ /**
548
+ * Set loading status
549
+ */
550
+ setLoadStatus(status: LoadStatus): void;
551
+ /**
552
+ * Set error
553
+ */
554
+ setError(error: Error | undefined): void;
555
+ /**
556
+ * Subscribe to state changes
557
+ * Returns unsubscribe function
558
+ *
559
+ * This is used by React's useSyncExternalStore.
560
+ * Vue/Svelte may not need this (they use refs/stores).
561
+ */
562
+ subscribe?(callback: () => void): () => void;
563
+ /**
564
+ * Get immutable snapshot of threads
565
+ */
566
+ getThreadsSnapshot?(): Thread[];
567
+ /**
568
+ * Get current thread snapshot
569
+ */
570
+ getCurrentThreadSnapshot?(): ThreadData | null;
571
+ /**
572
+ * Get load status snapshot
573
+ */
574
+ getLoadStatusSnapshot?(): LoadStatus;
575
+ /**
576
+ * Get error snapshot
577
+ */
578
+ getErrorSnapshot?(): Error | undefined;
579
+ }
580
+ /**
581
+ * Default in-memory state implementation (for testing/vanilla JS)
582
+ */
583
+ declare class SimpleThreadManagerState implements ThreadManagerState {
584
+ private _threads;
585
+ private _currentThreadId;
586
+ private _currentThread;
587
+ private _loadStatus;
588
+ private _error;
589
+ private callbacks;
590
+ get threads(): Thread[];
591
+ get currentThreadId(): string | null;
592
+ get currentThread(): ThreadData | null;
593
+ get loadStatus(): LoadStatus;
594
+ get error(): Error | undefined;
595
+ set threads(value: Thread[]);
596
+ setThreads(threads: Thread[]): void;
597
+ setCurrentThread(thread: ThreadData | null): void;
598
+ setCurrentThreadId(id: string | null): void;
599
+ addThread(thread: Thread): void;
600
+ updateThread(id: string, updates: Partial<Thread>): void;
601
+ removeThread(id: string): void;
602
+ setLoadStatus(status: LoadStatus): void;
603
+ setError(error: Error | undefined): void;
604
+ subscribe(callback: () => void): () => void;
605
+ getThreadsSnapshot(): Thread[];
606
+ getCurrentThreadSnapshot(): ThreadData | null;
607
+ getLoadStatusSnapshot(): LoadStatus;
608
+ getErrorSnapshot(): Error | undefined;
609
+ private notify;
610
+ }
611
+
612
+ /**
613
+ * localStorage Thread Storage Adapter
614
+ *
615
+ * Default adapter for thread persistence using browser localStorage.
616
+ * Stores all data in a single key for cleaner storage management.
617
+ */
618
+
619
+ /**
620
+ * Configuration for localStorage adapter
621
+ */
622
+ interface LocalStorageAdapterConfig {
623
+ /**
624
+ * Storage key to use
625
+ * @default "copilot-sdk-store"
626
+ */
627
+ storageKey?: string;
628
+ }
629
+ /**
630
+ * Create a localStorage adapter for thread storage
631
+ *
632
+ * All data is stored in a single key for cleaner storage management.
633
+ *
634
+ * @example Default usage
635
+ * ```typescript
636
+ * const adapter = createLocalStorageAdapter();
637
+ * const threadManager = new ThreadManager({ adapter });
638
+ * ```
639
+ *
640
+ * @example With custom key
641
+ * ```typescript
642
+ * const adapter = createLocalStorageAdapter({
643
+ * storageKey: "my-app-copilot-store"
644
+ * });
645
+ * ```
646
+ */
647
+ declare function createLocalStorageAdapter(config?: LocalStorageAdapterConfig): ThreadStorageAdapter;
648
+ /**
649
+ * Default localStorage adapter instance
650
+ */
651
+ declare const localStorageAdapter: ThreadStorageAdapter;
652
+
653
+ /**
654
+ * In-Memory Thread Storage Adapter
655
+ *
656
+ * Non-persistent adapter useful for testing or ephemeral sessions.
657
+ */
658
+
659
+ /**
660
+ * Create an in-memory adapter for thread storage
661
+ *
662
+ * This adapter stores threads in memory only - data is lost on page refresh.
663
+ * Useful for:
664
+ * - Testing
665
+ * - Server-side rendering (where localStorage is unavailable)
666
+ * - Ephemeral sessions where persistence isn't needed
667
+ *
668
+ * @example
669
+ * ```typescript
670
+ * const adapter = createMemoryAdapter();
671
+ * const threadManager = new ThreadManager({ adapter });
672
+ * ```
673
+ *
674
+ * @example Pre-populate with threads
675
+ * ```typescript
676
+ * const adapter = createMemoryAdapter([
677
+ * { id: "1", title: "Test", messages: [], sources: [], createdAt: new Date(), updatedAt: new Date() }
678
+ * ]);
679
+ * ```
680
+ */
681
+ declare function createMemoryAdapter(initialThreads?: ThreadData[]): ThreadStorageAdapter;
682
+ /**
683
+ * No-op adapter that never saves or loads
684
+ * Useful when you want to completely disable persistence
685
+ */
686
+ declare const noopAdapter: ThreadStorageAdapter;
687
+
688
+ /**
689
+ * ThreadManager - Framework-agnostic Thread Management
690
+ *
691
+ * Manages thread state and persistence with pluggable storage adapters.
692
+ * Similar pattern to AbstractChat for framework agnosticism.
693
+ */
694
+
695
+ /**
696
+ * Configuration for ThreadManager
697
+ */
698
+ interface ThreadManagerConfig {
699
+ /**
700
+ * Storage adapter for persistence
701
+ * @default localStorage adapter
702
+ */
703
+ adapter?: ThreadStorageAdapter | AsyncThreadStorageAdapter;
704
+ /**
705
+ * Debounce delay for auto-save (ms)
706
+ * @default 1000
707
+ */
708
+ saveDebounce?: number;
709
+ /**
710
+ * Whether to auto-load threads on initialization
711
+ * @default true
712
+ */
713
+ autoLoad?: boolean;
714
+ /**
715
+ * Whether to auto-restore the last active thread on load
716
+ * Requires adapter to support getLastActiveThreadId/setLastActiveThreadId
717
+ * @default true
718
+ */
719
+ autoRestoreLastThread?: boolean;
720
+ /**
721
+ * Custom state implementation (for framework adapters)
722
+ * @default SimpleThreadManagerState
723
+ */
724
+ state?: ThreadManagerState;
725
+ }
726
+ /**
727
+ * Callbacks for ThreadManager events
728
+ */
729
+ interface ThreadManagerCallbacks {
730
+ /** Called when threads are loaded */
731
+ onThreadsLoaded?: (threads: Thread[]) => void;
732
+ /** Called when a thread is created */
733
+ onThreadCreated?: (thread: ThreadData) => void;
734
+ /** Called when a thread is switched */
735
+ onThreadSwitched?: (thread: ThreadData | null) => void;
736
+ /** Called when a thread is updated */
737
+ onThreadUpdated?: (thread: ThreadData) => void;
738
+ /** Called when a thread is deleted */
739
+ onThreadDeleted?: (threadId: string) => void;
740
+ /** Called when an error occurs */
741
+ onError?: (error: Error) => void;
742
+ }
743
+ /**
744
+ * Options for creating a new thread
745
+ */
746
+ interface CreateThreadOptions {
747
+ /** Custom thread ID (auto-generated if not provided) */
748
+ id?: string;
749
+ /** Thread title */
750
+ title?: string;
751
+ /** Initial messages */
752
+ messages?: Message[];
753
+ }
754
+ /**
755
+ * Options for updating a thread
756
+ */
757
+ interface UpdateThreadOptions {
758
+ /** Update title */
759
+ title?: string;
760
+ /** Update messages */
761
+ messages?: Message[];
762
+ /** Custom metadata updates */
763
+ [key: string]: unknown;
764
+ }
765
+ /**
766
+ * ThreadManager - Manages thread state and persistence
767
+ *
768
+ * @example Basic usage with localStorage (default)
769
+ * ```typescript
770
+ * const manager = new ThreadManager();
771
+ * await manager.loadThreads();
772
+ *
773
+ * const thread = await manager.createThread();
774
+ * console.log(manager.threads);
775
+ * ```
776
+ *
777
+ * @example With custom adapter
778
+ * ```typescript
779
+ * const manager = new ThreadManager({
780
+ * adapter: myDatabaseAdapter,
781
+ * });
782
+ * ```
783
+ */
784
+ declare class ThreadManager {
785
+ protected state: ThreadManagerState;
786
+ protected adapter: ThreadStorageAdapter | AsyncThreadStorageAdapter;
787
+ protected callbacks: ThreadManagerCallbacks;
788
+ protected saveDebounce: number;
789
+ protected autoLoad: boolean;
790
+ protected autoRestoreLastThread: boolean;
791
+ private saveTimer;
792
+ private threadsData;
793
+ private initPromise;
794
+ constructor(config?: ThreadManagerConfig, callbacks?: ThreadManagerCallbacks);
795
+ /** All threads (metadata) */
796
+ get threads(): Thread[];
797
+ /** Currently selected thread ID */
798
+ get currentThreadId(): string | null;
799
+ /** Currently loaded thread (with messages) */
800
+ get currentThread(): ThreadData | null;
801
+ /** Whether threads are currently loading */
802
+ get isLoading(): boolean;
803
+ /** Current load status */
804
+ get loadStatus(): LoadStatus;
805
+ /** Current error */
806
+ get error(): Error | undefined;
807
+ /** Whether there are pending changes waiting to be saved */
808
+ get hasPendingChanges(): boolean;
809
+ /**
810
+ * Load all threads from storage
811
+ */
812
+ loadThreads(): Promise<void>;
813
+ /**
814
+ * Wait for initialization to complete
815
+ */
816
+ waitForInit(): Promise<void>;
817
+ /**
818
+ * Create a new thread
819
+ */
820
+ createThread(options?: CreateThreadOptions): Promise<ThreadData>;
821
+ /**
822
+ * Switch to a different thread
823
+ */
824
+ switchThread(id: string): Promise<ThreadData | null>;
825
+ /**
826
+ * Update the current thread
827
+ */
828
+ updateCurrentThread(updates: UpdateThreadOptions): Promise<void>;
829
+ /**
830
+ * Delete a thread
831
+ */
832
+ deleteThread(id: string): Promise<void>;
833
+ /**
834
+ * Clear the current thread selection
835
+ */
836
+ clearCurrentThread(): void;
837
+ /**
838
+ * Clear all threads
839
+ */
840
+ clearAllThreads(): Promise<void>;
841
+ /**
842
+ * Save changes immediately (bypass debounce)
843
+ */
844
+ saveNow(): Promise<void>;
845
+ /**
846
+ * Dispose of the manager and save pending changes
847
+ */
848
+ dispose(): Promise<void>;
849
+ /**
850
+ * Schedule a debounced save
851
+ */
852
+ protected scheduleSave(): void;
853
+ /**
854
+ * Save the last active thread ID (for session persistence)
855
+ */
856
+ protected saveLastActiveThread(threadId: string | null): void;
857
+ }
858
+ /**
859
+ * Create a ThreadManager instance
860
+ */
861
+ declare function createThreadManager(config?: ThreadManagerConfig, callbacks?: ThreadManagerCallbacks): ThreadManager;
862
+
863
+ export { type ThreadManagerState as $, type ActionParameter as A, type InternalKnowledgeBaseResult as B, type ConsoleLogOptions as C, type InternalKnowledgeBaseSearchResponse as D, type Extension as E, actionToTool as F, getDefaultModel as G, type HttpMethod as H, type IntentDetectionResult as I, DEFAULT_MODELS as J, type KnowledgeBaseProvider as K, type LLMProvider as L, ThreadManager as M, type NetworkRequestOptions as N, createThreadManager as O, type ParameterType as P, createLocalStorageAdapter as Q, localStorageAdapter as R, type ScreenshotOptions as S, type ToolType as T, createMemoryAdapter as U, noopAdapter as V, SimpleThreadManagerState as W, type ThreadManagerConfig as X, type ThreadManagerCallbacks as Y, type CreateThreadOptions as Z, type UpdateThreadOptions as _, type ScreenshotResult as a, type LoadStatus as a0, type LocalStorageAdapterConfig as a1, type ConsoleLogResult as b, type ConsoleLogEntry as c, type NetworkRequestResult as d, type NetworkRequestEntry as e, detectIntent as f, getPrimaryTool as g, hasToolSuggestions as h, generateSuggestionReason as i, createCustomDetector as j, type ConsoleLogType as k, type ToolsConfig as l, type ToolConsentRequest as m, type ToolConsentResponse as n, type CapturedContext as o, type CustomKeywords as p, type LLMConfig as q, type CloudConfig as r, type CopilotConfig as s, type ActionDefinition as t, type ActionRenderProps as u, type KnowledgeBaseConfig as v, type KnowledgeBaseResult as w, type KnowledgeBaseSearchRequest as x, type KnowledgeBaseSearchResponse as y, type InternalKnowledgeBaseConfig as z };