@mikesaintsg/core 0.0.2 → 0.0.4

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.
package/dist/index.d.ts CHANGED
@@ -3,13 +3,17 @@ export declare interface AbortableOptions {
3
3
  readonly signal?: AbortSignal;
4
4
  }
5
5
 
6
- /** Batched embedding adapter interface - extends base with batching */
7
- export declare interface BatchedEmbeddingAdapterInterface extends EmbeddingAdapterInterface {
8
- queue(text: string, options?: AbortableOptions): Promise<Embedding>;
9
- queueBatch(texts: readonly string[], options?: AbortableOptions): Promise<readonly Embedding[]>;
10
- flush(): Promise<void>;
11
- getPendingCount(): number;
12
- getCache(): EmbeddingCacheInterface | undefined;
6
+ /**
7
+ * Batch adapter interface.
8
+ * Controls batching behavior for bulk operations.
9
+ */
10
+ export declare interface BatchAdapterInterface {
11
+ /** Maximum items per batch */
12
+ getBatchSize(): number;
13
+ /** Delay between batches (ms) */
14
+ getDelayMs(): number;
15
+ /** Whether to deduplicate items within a batch */
16
+ shouldDeduplicate(): boolean;
13
17
  }
14
18
 
15
19
  /** Default timeout for bridge operations in milliseconds */
@@ -26,6 +30,14 @@ export declare interface BuiltContext {
26
30
  readonly timestamp: number;
27
31
  }
28
32
 
33
+ /** Cache statistics */
34
+ export declare interface CacheStats {
35
+ readonly hits: number;
36
+ readonly misses: number;
37
+ readonly size: number;
38
+ readonly maxSize?: number;
39
+ }
40
+
29
41
  /**
30
42
  * Chain results (flatMap). Apply a function that returns a Result to a success value.
31
43
  *
@@ -76,26 +88,6 @@ export declare interface ContextFrame {
76
88
  readonly metadata?: FrameMetadata;
77
89
  }
78
90
 
79
- /**
80
- * Core package error.
81
- *
82
- * @example
83
- * ```ts
84
- * throw new CoreError('ADAPTER_ERROR', 'Failed to connect to OpenAI')
85
- * ```
86
- */
87
- export declare class CoreError extends Error {
88
- readonly code: CoreErrorCode;
89
- readonly cause: Error | undefined;
90
- constructor(code: CoreErrorCode, message: string, cause?: Error);
91
- }
92
-
93
- /** Core package error codes */
94
- export declare type CoreErrorCode = 'ADAPTER_ERROR' | 'BRIDGE_ERROR' | 'VALIDATION_ERROR' | 'NOT_FOUND' | 'TIMEOUT' | 'ABORTED';
95
-
96
- /** Factory function for creating embedding cache */
97
- export declare type CreateEmbeddingCache = (options?: EmbeddingCacheOptions) => EmbeddingCacheInterface;
98
-
99
91
  /**
100
92
  * Create a navigation guard that prevents leaving when form is dirty.
101
93
  *
@@ -148,7 +140,7 @@ export declare function createFormDirtyGuard<TFormData = unknown, TPage extends
148
140
  * registry.register({ ...schema, execute: handler })
149
141
  * ```
150
142
  */
151
- export declare function createRetrievalTool<TMetadata = unknown>(options: RetrievalToolOptions<TMetadata>): RetrievalToolCreated;
143
+ export declare function createRetrievalTool<TMetadata = unknown>(options: RetrievalToolOptions<TMetadata>): RetrievalToolInterface;
152
144
 
153
145
  /**
154
146
  * Create a session persistence adapter for storing inference sessions.
@@ -198,11 +190,23 @@ export declare function createSessionPersistence(options: SessionPersistenceOpti
198
190
  * })
199
191
  *
200
192
  * // Execute tool calls from LLM response
201
- * const results = await bridge.executeAll(response.toolCalls)
193
+ * const results = await bridge.execute(response.toolCalls)
202
194
  * ```
203
195
  */
204
196
  export declare function createToolCallBridge(options: ToolCallBridgeOptions): ToolCallBridgeInterface;
205
197
 
198
+ /**
199
+ * Deduplication adapter interface.
200
+ * Determines how to handle duplicate frames based on content hash.
201
+ * Implemented in @mikesaintsg/adapters.
202
+ */
203
+ export declare interface DeduplicationAdapterInterface {
204
+ /** Select which frame to keep from duplicates with the same content hash */
205
+ select(frames: readonly ContextFrame[]): ContextFrame;
206
+ /** Check if a frame should be preserved regardless of deduplication */
207
+ shouldPreserve(frame: ContextFrame): boolean;
208
+ }
209
+
206
210
  /** Deduplication result summary */
207
211
  export declare interface DeduplicationResult {
208
212
  readonly originalCount: number;
@@ -212,73 +216,87 @@ export declare interface DeduplicationResult {
212
216
  readonly tokensSaved: number;
213
217
  }
214
218
 
219
+ /** Deduplication strategy for default adapter */
220
+ export declare type DeduplicationStrategy = 'keep_latest' | 'keep_first' | 'keep_highest_priority' | 'merge';
221
+
222
+ /** Resource that must be explicitly destroyed */
223
+ export declare interface Destroyable {
224
+ /** Release all resources held by this instance. After calling, the instance is unusable. */
225
+ destroy(): void;
226
+ }
227
+
228
+ /**
229
+ * @mikesaintsg/core
230
+ *
231
+ * Base error class and utilities for the ecosystem.
232
+ */
215
233
  /**
216
234
  * Base error class for all ecosystem errors.
217
235
  * All package-specific errors should extend this class.
236
+ *
237
+ * @example
238
+ * ```ts
239
+ * class StorageError extends EcosystemError {
240
+ * readonly code: StorageErrorCode
241
+ *
242
+ * constructor(code: StorageErrorCode, message: string, cause?: Error) {
243
+ * super(message, cause)
244
+ * this.code = code
245
+ * }
246
+ * }
247
+ * ```
218
248
  */
219
249
  export declare abstract class EcosystemError extends Error {
250
+ /** Error code for programmatic handling */
220
251
  abstract readonly code: string;
252
+ /** Original error that caused this one */
221
253
  readonly cause: Error | undefined;
222
254
  constructor(message: string, cause?: Error);
223
255
  }
224
256
 
225
- /** Embedding vector */
257
+ /** A single embedding vector. Float32Array for memory efficiency and typed array operations. */
226
258
  export declare type Embedding = Float32Array;
227
259
 
228
- /** Embedding generation contract */
260
+ /**
261
+ * Contract for embedding generation.
262
+ * Implemented by adapters, consumed by vectorstore.
263
+ */
229
264
  export declare interface EmbeddingAdapterInterface {
265
+ /**
266
+ * Generate embeddings for one or more texts.
267
+ * @param texts - Texts to embed
268
+ * @param options - Optional abort signal
269
+ * @returns Embeddings in same order as input texts
270
+ */
230
271
  embed(texts: readonly string[], options?: AbortableOptions): Promise<readonly Embedding[]>;
272
+ /** Get metadata about the embedding model. Used for compatibility checking. */
231
273
  getModelMetadata(): EmbeddingModelMetadata;
232
274
  }
233
275
 
234
- /** Embedding batch options */
235
- export declare interface EmbeddingBatchOptions {
236
- readonly maxBatchSize?: number;
237
- readonly flushDelayMs?: number;
238
- readonly deduplicate?: boolean;
239
- readonly cache?: EmbeddingCacheInterface;
240
- }
241
-
242
- /** Embedding cache entry */
243
- export declare interface EmbeddingCacheEntry {
244
- readonly embedding: Embedding;
245
- readonly contentHash: ContentHash;
246
- readonly modelId: string;
247
- readonly createdAt: number;
248
- readonly hitCount: number;
249
- }
250
-
251
- /** Embedding cache interface */
252
- export declare interface EmbeddingCacheInterface {
253
- get(contentHash: ContentHash): Embedding | undefined;
254
- set(contentHash: ContentHash, embedding: Embedding): void;
255
- has(contentHash: ContentHash): boolean;
256
- remove(contentHash: ContentHash): boolean;
276
+ /**
277
+ * Embedding cache adapter interface.
278
+ * Provides caching for embedding operations.
279
+ */
280
+ export declare interface EmbeddingCacheAdapterInterface {
281
+ /** Get cached embedding for text */
282
+ get(text: string): Embedding | undefined;
283
+ /** Store embedding in cache */
284
+ set(text: string, embedding: Embedding): void;
285
+ /** Check if text is cached */
286
+ has(text: string): boolean;
287
+ /** Clear all cached embeddings */
257
288
  clear(): void;
258
- getStats(): EmbeddingCacheStats;
259
- }
260
-
261
- /** LRU cache eviction options */
262
- export declare interface EmbeddingCacheOptions {
263
- readonly maxEntries?: number;
264
- readonly maxBytes?: number;
265
- readonly ttlMs?: number;
266
- readonly onEvict?: (contentHash: ContentHash, embedding: Embedding) => void;
267
- }
268
-
269
- /** Embedding cache statistics */
270
- export declare interface EmbeddingCacheStats {
271
- readonly entries: number;
272
- readonly hits: number;
273
- readonly misses: number;
274
- readonly hitRate: number;
275
- readonly estimatedBytes: number;
289
+ /** Optional: Get cache statistics */
290
+ getStats?(): CacheStats;
276
291
  }
277
292
 
278
- /** Embedding model info */
293
+ /** Metadata identifying an embedding model. Used to ensure vector compatibility. */
279
294
  export declare interface EmbeddingModelMetadata {
295
+ /** Provider name (e.g., 'openai', 'anthropic') */
280
296
  readonly provider: string;
297
+ /** Model identifier (e.g., 'text-embedding-3-small') */
281
298
  readonly model: string;
299
+ /** Vector dimensions produced by this model */
282
300
  readonly dimensions: number;
283
301
  }
284
302
 
@@ -303,12 +321,26 @@ export declare interface Err<E> {
303
321
  */
304
322
  export declare function err<E>(error: E): Err<E>;
305
323
 
306
- /** Extract error code type */
307
- export declare type ErrorCode<T extends EcosystemError> = T['code'];
324
+ /** Extract error code type from an error class */
325
+ export declare type ErrorCode<T extends {
326
+ readonly code: string;
327
+ }> = T['code'];
328
+
329
+ /** Generation finish reason */
330
+ export declare type FinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'error';
308
331
 
309
332
  /** Default form dirty guard message */
310
333
  export declare const FORM_DIRTY_DEFAULT_MESSAGE = "You have unsaved changes. Are you sure you want to leave?";
311
334
 
335
+ /**
336
+ * Default result formatter for retrieval tools.
337
+ * Returns content, score, and metadata.
338
+ *
339
+ * @param result - Scored result to format
340
+ * @returns Formatted result object
341
+ */
342
+ export declare function formatScoredResult(result: ScoredResult): unknown;
343
+
312
344
  /** Form dirty guard options */
313
345
  export declare interface FormDirtyGuardOptions<TFormData = unknown, TPage extends string = string> {
314
346
  readonly form: FormMinimal<TFormData>;
@@ -361,45 +393,29 @@ export declare interface GenerationDefaults {
361
393
  readonly stop?: readonly string[];
362
394
  }
363
395
 
364
- /** HTTP persistence options */
365
- export declare interface HTTPPersistenceOptions {
366
- readonly baseURL: string;
367
- readonly headers?: Readonly<Record<string, string>>;
368
- readonly timeout?: number;
369
- }
370
-
371
- /** IndexedDB VectorStore persistence options */
372
- export declare interface IndexedDBVectorStorePersistenceOptions {
373
- readonly database: MinimalDatabaseAccess;
374
- readonly documentsStore?: string;
375
- readonly metadataStore?: string;
396
+ /** Generation options */
397
+ export declare interface GenerationOptions extends AbortableOptions {
398
+ readonly model?: string;
399
+ readonly temperature?: number;
400
+ readonly maxTokens?: number;
401
+ readonly topP?: number;
402
+ readonly tools?: readonly ToolSchema[];
403
+ readonly toolChoice?: 'auto' | 'none' | 'required' | {
404
+ readonly name: string;
405
+ };
406
+ readonly stop?: readonly string[];
407
+ readonly timeout?: TimeoutOptions;
376
408
  }
377
409
 
378
- /** In-memory embedding cache options */
379
- export declare interface InMemoryEmbeddingCacheOptions {
380
- readonly maxEntries?: number;
381
- readonly ttlMs?: number;
410
+ /** Generation result */
411
+ export declare interface GenerationResult {
412
+ readonly text: string;
413
+ readonly toolCalls: readonly ToolCall[];
414
+ readonly finishReason: FinishReason;
415
+ readonly usage?: UsageStats;
416
+ readonly aborted: boolean;
382
417
  }
383
418
 
384
- /**
385
- * Type guard to check if an error is a CoreError.
386
- *
387
- * @param error - The value to check
388
- * @returns True if the error is a CoreError
389
- *
390
- * @example
391
- * ```ts
392
- * try {
393
- * await adapter.embed(['text'])
394
- * } catch (error) {
395
- * if (isCoreError(error)) {
396
- * console.log('Code:', error.code)
397
- * }
398
- * }
399
- * ```
400
- */
401
- export declare function isCoreError(error: unknown): error is CoreError;
402
-
403
419
  /**
404
420
  * Type guard for ecosystem errors.
405
421
  *
@@ -451,6 +467,18 @@ export declare function isErr<T, E>(result: Result<T, E>): result is Err<E>;
451
467
  */
452
468
  export declare function isOk<T, E>(result: Result<T, E>): result is Ok<T>;
453
469
 
470
+ /**
471
+ * Check if a value is a single ToolCall (not an array).
472
+ *
473
+ * @param value - Value to check
474
+ * @returns True if the value is a single ToolCall
475
+ */
476
+ export declare function isToolCall(value: unknown): value is {
477
+ id: string;
478
+ name: string;
479
+ arguments: unknown;
480
+ };
481
+
454
482
  /** JSON Schema 7 subset for tool parameters */
455
483
  export declare interface JSONSchema7 {
456
484
  readonly type?: string | readonly string[];
@@ -505,9 +533,31 @@ export declare function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U):
505
533
  */
506
534
  export declare function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;
507
535
 
536
+ /** Message object */
537
+ export declare interface Message {
538
+ readonly id: string;
539
+ readonly role: MessageRole;
540
+ readonly content: MessageContent;
541
+ readonly createdAt: number;
542
+ readonly metadata?: MessageMetadata;
543
+ }
544
+
545
+ /** Message content types */
546
+ export declare type MessageContent = string | ToolCallContent | ToolResultContent;
547
+
548
+ /** Message metadata */
549
+ export declare interface MessageMetadata {
550
+ readonly model?: string;
551
+ readonly tokenCount?: number;
552
+ readonly finishReason?: FinishReason;
553
+ }
554
+
555
+ /** Message role */
556
+ export declare type MessageRole = 'system' | 'user' | 'assistant' | 'tool';
557
+
508
558
  /**
509
559
  * Minimal database access interface for cross-package adapters.
510
- * Used by vectorstore persistence adapters to access IndexedDB without
560
+ * Used by persistence adapters to access IndexedDB without
511
561
  * creating a hard dependency on the indexeddb package.
512
562
  */
513
563
  export declare interface MinimalDatabaseAccess<T = unknown> {
@@ -516,7 +566,7 @@ export declare interface MinimalDatabaseAccess<T = unknown> {
516
566
 
517
567
  /**
518
568
  * Minimal directory access interface for cross-package adapters.
519
- * Used by vectorstore OPFS persistence adapters without creating
569
+ * Used by OPFS persistence adapters without creating
520
570
  * a hard dependency on the filesystem package.
521
571
  */
522
572
  export declare interface MinimalDirectoryAccess {
@@ -576,15 +626,9 @@ export declare interface Ok<T> {
576
626
  */
577
627
  export declare function ok<T>(value: T): Ok<T>;
578
628
 
579
- /** OPFS VectorStore persistence options */
580
- export declare interface OPFSVectorStorePersistenceOptions {
581
- readonly directory: MinimalDirectoryAccess;
582
- readonly chunkSize?: number;
583
- }
584
-
585
629
  /**
586
630
  * Generic error data interface for package-specific errors.
587
- * Use this as a base for error data interfaces in packages.
631
+ * Packages extend this to define their error structure.
588
632
  *
589
633
  * @example
590
634
  * ```ts
@@ -599,6 +643,39 @@ export declare interface PackageErrorData<TCode extends string> {
599
643
  readonly cause?: Error;
600
644
  }
601
645
 
646
+ /**
647
+ * Priority adapter interface.
648
+ * Provides priority weights and comparison logic.
649
+ * Implemented in @mikesaintsg/adapters.
650
+ */
651
+ export declare interface PriorityAdapterInterface {
652
+ /** Get numeric weight for a priority level. Higher values = more important. */
653
+ getWeight(priority: FramePriority): number;
654
+ /** Compare two frames by priority */
655
+ compare(a: ContextFrame, b: ContextFrame): number;
656
+ }
657
+
658
+ /**
659
+ * Provider adapter interface - LLM provider integration.
660
+ * Implemented for each supported provider (OpenAI, Anthropic, etc.).
661
+ */
662
+ export declare interface ProviderAdapterInterface {
663
+ /** Get adapter identifier */
664
+ getId(): string;
665
+ /**
666
+ * Generate completion.
667
+ * @param messages - Messages to send
668
+ * @param options - Generation options
669
+ */
670
+ generate(messages: readonly Message[], options: GenerationOptions): StreamHandleInterface;
671
+ /** Check if provider supports tools */
672
+ supportsTools(): boolean;
673
+ /** Check if provider supports streaming */
674
+ supportsStreaming(): boolean;
675
+ /** Get all capabilities */
676
+ getCapabilities(): ProviderCapabilities;
677
+ }
678
+
602
679
  /** Provider capabilities information */
603
680
  export declare interface ProviderCapabilities {
604
681
  readonly supportsTools: boolean;
@@ -614,7 +691,42 @@ export declare interface PruneResult {
614
691
  readonly remainingCount: number;
615
692
  }
616
693
 
617
- /** Result union */
694
+ /**
695
+ * Rate limit adapter interface.
696
+ * Controls request rate to external services.
697
+ */
698
+ export declare interface RateLimitAdapterInterface {
699
+ /** Acquire a request slot, waits if none available */
700
+ acquire(): Promise<void>;
701
+ /** Release a request slot */
702
+ release(): void;
703
+ /** Get current rate limit state */
704
+ getState(): RateLimitState;
705
+ /** Dynamically adjust rate limit (e.g., from Retry-After header) */
706
+ setLimit(requestsPerMinute: number): void;
707
+ }
708
+
709
+ /** Rate limit state */
710
+ export declare interface RateLimitState {
711
+ readonly activeRequests: number;
712
+ readonly maxConcurrent: number;
713
+ readonly requestsInWindow: number;
714
+ readonly requestsPerMinute: number;
715
+ readonly windowResetIn: number;
716
+ }
717
+
718
+ /**
719
+ * Reranker adapter interface.
720
+ * Reranks search results using a cross-encoder or similar model.
721
+ */
722
+ export declare interface RerankerAdapterInterface {
723
+ /** Rerank documents for a given query */
724
+ rerank(query: string, docs: readonly ScoredResult[]): Promise<readonly ScoredResult[]>;
725
+ /** Get the model ID used for reranking */
726
+ getModelId(): string;
727
+ }
728
+
729
+ /** Result union - discriminated union for operation results */
618
730
  export declare type Result<T, E> = Ok<T> | Err<E>;
619
731
 
620
732
  /** Default retrieval limit for retrieval tool */
@@ -624,7 +736,7 @@ export declare const RETRIEVAL_DEFAULT_LIMIT = 10;
624
736
  export declare const RETRIEVAL_MAX_LIMIT = 100;
625
737
 
626
738
  /** Retrieval tool created by factory */
627
- export declare interface RetrievalToolCreated {
739
+ export declare interface RetrievalToolInterface {
628
740
  readonly schema: ToolSchema;
629
741
  readonly handler: (args: Readonly<Record<string, unknown>>) => Promise<readonly unknown[]>;
630
742
  }
@@ -642,6 +754,21 @@ export declare interface RetrievalToolOptions<TMetadata = unknown> {
642
754
  readonly buildFilter?: (params: Readonly<Record<string, unknown>>) => TMetadata | undefined;
643
755
  }
644
756
 
757
+ /**
758
+ * Retry adapter interface.
759
+ * Determines retry behavior for failed operations.
760
+ */
761
+ export declare interface RetryAdapterInterface {
762
+ /** Determine if an error should trigger a retry */
763
+ shouldRetry(error: unknown, attempt: number): boolean;
764
+ /** Get delay before next retry attempt (ms) */
765
+ getDelay(attempt: number): number;
766
+ /** Maximum number of retry attempts */
767
+ getMaxAttempts(): number;
768
+ /** Optional callback before each retry */
769
+ onRetry?(error: unknown, attempt: number, delayMs: number): void;
770
+ }
771
+
645
772
  /** Scored result from similarity search or retrieval */
646
773
  export declare interface ScoredResult {
647
774
  readonly id: string;
@@ -704,6 +831,28 @@ export declare interface SessionPersistenceOptions {
704
831
  readonly onSaveError?: (error: unknown, sessionId: string) => void;
705
832
  }
706
833
 
834
+ /**
835
+ * Determine if form dirty guard should be skipped for a navigation.
836
+ *
837
+ * @param to - Target page
838
+ * @param from - Source page
839
+ * @param excludePages - Pages to exclude from guard
840
+ * @param onlyFromPages - Only guard from these pages (if specified)
841
+ * @returns True if guard should be skipped
842
+ */
843
+ export declare function shouldSkipFormGuard<TPage extends string>(to: TPage, from: TPage, excludePages: readonly TPage[], onlyFromPages: readonly TPage[] | undefined): boolean;
844
+
845
+ /**
846
+ * Similarity adapter interface.
847
+ * Computes similarity between embedding vectors.
848
+ */
849
+ export declare interface SimilarityAdapterInterface {
850
+ /** Compute similarity score between two embeddings */
851
+ compute(a: Embedding, b: Embedding): number;
852
+ /** Name of the similarity function */
853
+ readonly name: string;
854
+ }
855
+
707
856
  /** Storage information (quota and usage) */
708
857
  export declare interface StorageInfo {
709
858
  readonly usage: number;
@@ -723,11 +872,39 @@ export declare interface StoredDocument {
723
872
  readonly updatedAt?: number;
724
873
  }
725
874
 
875
+ /**
876
+ * Stream handle interface - async iteration over tokens.
877
+ * Provides streaming access to generation with abort control.
878
+ */
879
+ export declare interface StreamHandleInterface {
880
+ /** Request identifier */
881
+ readonly requestId: string;
882
+ /** Async iteration */
883
+ [Symbol.asyncIterator](): AsyncIterator<string>;
884
+ /** Get final result */
885
+ result(): Promise<GenerationResult>;
886
+ /** Abort generation */
887
+ abort(): void;
888
+ /** Subscribe to tokens */
889
+ onToken(callback: (token: string) => void): Unsubscribe;
890
+ /** Subscribe to completion */
891
+ onComplete(callback: (result: GenerationResult) => void): Unsubscribe;
892
+ /** Subscribe to errors */
893
+ onError(callback: (error: Error) => void): Unsubscribe;
894
+ }
895
+
726
896
  /** Converts subscription methods to hook callbacks for options */
727
897
  export declare type SubscriptionToHook<T> = {
728
898
  [K in keyof T]?: T[K] extends (callback: infer CB) => Unsubscribe ? CB : never;
729
899
  };
730
900
 
901
+ /** Timeout options for generation */
902
+ export declare interface TimeoutOptions {
903
+ readonly requestMs?: number;
904
+ readonly streamMs?: number;
905
+ readonly tokenMs?: number;
906
+ }
907
+
731
908
  /** Token budget level */
732
909
  export declare type TokenBudgetLevel = 'ok' | 'warning' | 'critical' | 'exceeded';
733
910
 
@@ -741,11 +918,43 @@ export declare interface TokenBudgetState {
741
918
  readonly level: TokenBudgetLevel;
742
919
  }
743
920
 
921
+ /**
922
+ * Token counter interface for model-specific token counting.
923
+ * Provides estimation of token counts for context window management,
924
+ * cost estimation, and truncation decisions.
925
+ */
926
+ export declare interface TokenCounterInterface {
927
+ /**
928
+ * Count tokens in text for specific model.
929
+ * @param text - Text to count tokens in
930
+ * @param model - Model to use for counting
931
+ */
932
+ countTokens(text: string, model: string): number;
933
+ /**
934
+ * Count tokens in messages array.
935
+ * @param messages - Messages to count
936
+ * @param model - Model to use for counting
937
+ */
938
+ countMessages(messages: readonly Message[], model: string): number;
939
+ /**
940
+ * Estimate if content fits in context window.
941
+ * @param content - Content to check
942
+ * @param model - Model to check against
943
+ * @param maxTokens - Maximum tokens allowed
944
+ */
945
+ fitsInContext(content: string, model: string, maxTokens: number): boolean;
946
+ /**
947
+ * Get model's context window size.
948
+ * @param model - Model name
949
+ */
950
+ getContextWindowSize(model: string): number | undefined;
951
+ }
952
+
744
953
  /** Tool call from LLM response */
745
954
  export declare interface ToolCall {
746
955
  readonly id: string;
747
956
  readonly name: string;
748
- readonly arguments: Record<string, unknown>;
957
+ readonly arguments: Readonly<Record<string, unknown>>;
749
958
  }
750
959
 
751
960
  /**
@@ -753,8 +962,15 @@ export declare interface ToolCall {
753
962
  * Connects inference tool calls to contextprotocol tool registry.
754
963
  */
755
964
  export declare interface ToolCallBridgeInterface {
756
- execute(toolCall: ToolCall): Promise<ToolResult>;
757
- executeAll(toolCalls: readonly ToolCall[]): Promise<readonly ToolResult[]>;
965
+ /**
966
+ * Execute tool call(s).
967
+ * Accepts single call or array of calls.
968
+ * @param toolCalls - Single tool call or array of calls
969
+ * @returns Single result or array of results
970
+ */
971
+ execute(toolCalls: ToolCall): Promise<ToolResult>;
972
+ execute(toolCalls: readonly ToolCall[]): Promise<readonly ToolResult[]>;
973
+ /** Check if tool exists */
758
974
  hasTool(name: string): boolean;
759
975
  }
760
976
 
@@ -767,14 +983,23 @@ export declare interface ToolCallBridgeOptions {
767
983
  readonly onAfterExecute?: (toolCall: ToolCall, result: unknown) => void;
768
984
  }
769
985
 
986
+ /** Tool call content */
987
+ export declare interface ToolCallContent {
988
+ readonly type: 'tool_calls';
989
+ readonly toolCalls: readonly ToolCall[];
990
+ }
991
+
770
992
  /**
771
993
  * Tool format adapter interface.
772
994
  * Converts between internal tool representations and provider-specific formats.
773
995
  * Implemented in @mikesaintsg/adapters.
774
996
  */
775
997
  export declare interface ToolFormatAdapterInterface {
998
+ /** Convert tool schemas to provider-specific format */
776
999
  formatSchemas(schemas: readonly ToolSchema[]): unknown;
1000
+ /** Parse tool calls from provider response */
777
1001
  parseToolCalls(response: unknown): readonly ToolCall[];
1002
+ /** Format tool result for provider */
778
1003
  formatResult(result: ToolResult): unknown;
779
1004
  }
780
1005
 
@@ -796,6 +1021,14 @@ export declare interface ToolResult {
796
1021
  readonly error?: string;
797
1022
  }
798
1023
 
1024
+ /** Tool result content */
1025
+ export declare interface ToolResultContent {
1026
+ readonly type: 'tool_result';
1027
+ readonly callId: string;
1028
+ readonly name: string;
1029
+ readonly result: unknown;
1030
+ }
1031
+
799
1032
  /** Tool schema definition */
800
1033
  export declare interface ToolSchema {
801
1034
  readonly name: string;
@@ -804,6 +1037,18 @@ export declare interface ToolSchema {
804
1037
  readonly returns?: JSONSchema7;
805
1038
  }
806
1039
 
1040
+ /**
1041
+ * Truncation adapter interface.
1042
+ * Determines which frames to remove when budget is exceeded.
1043
+ * Implemented in @mikesaintsg/adapters.
1044
+ */
1045
+ export declare interface TruncationAdapterInterface {
1046
+ /** Sort frames for truncation order. Frames at the end are removed first. */
1047
+ sort(frames: readonly ContextFrame[]): readonly ContextFrame[];
1048
+ /** Check if a frame should be preserved regardless of truncation */
1049
+ shouldPreserve(frame: ContextFrame): boolean;
1050
+ }
1051
+
807
1052
  /** Truncation information */
808
1053
  export declare interface TruncationInfo {
809
1054
  readonly originalFrameCount: number;
@@ -818,6 +1063,13 @@ export declare type TruncationReason = 'budget_exceeded' | 'priority_too_low' |
818
1063
  /** Truncation strategy */
819
1064
  export declare type TruncationStrategy = 'priority' | 'fifo' | 'lifo' | 'score' | 'custom';
820
1065
 
1066
+ /**
1067
+ * @mikesaintsg/core
1068
+ *
1069
+ * Shared type definitions for the @mikesaintsg ecosystem.
1070
+ * Contains ONLY types and interfaces — no implementations.
1071
+ * All public types and interfaces are defined here as the SOURCE OF TRUTH.
1072
+ */
821
1073
  /** Cleanup function returned by event subscriptions */
822
1074
  export declare type Unsubscribe = () => void;
823
1075
 
@@ -851,6 +1103,13 @@ export declare function unwrap<T, E>(result: Result<T, E>, defaultValue: T): T;
851
1103
  */
852
1104
  export declare function unwrapOrThrow<T, E>(result: Result<T, E>): T;
853
1105
 
1106
+ /** Token usage statistics */
1107
+ export declare interface UsageStats {
1108
+ readonly promptTokens: number;
1109
+ readonly completionTokens: number;
1110
+ readonly totalTokens: number;
1111
+ }
1112
+
854
1113
  /** VectorStore metadata for persistence */
855
1114
  export declare interface VectorStoreMetadata {
856
1115
  readonly dimensions: number;