@fgv/ts-extras 5.0.2 → 5.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.
Files changed (92) hide show
  1. package/dist/index.browser.js +6 -2
  2. package/dist/index.js +5 -1
  3. package/dist/packlets/ai-assist/apiClient.js +484 -0
  4. package/dist/packlets/ai-assist/converters.js +121 -0
  5. package/dist/packlets/ai-assist/index.js +10 -0
  6. package/dist/packlets/ai-assist/model.js +90 -0
  7. package/dist/packlets/ai-assist/registry.js +145 -0
  8. package/dist/packlets/ai-assist/toolFormats.js +160 -0
  9. package/dist/packlets/crypto-utils/constants.js +48 -0
  10. package/dist/packlets/crypto-utils/converters.js +155 -0
  11. package/dist/packlets/crypto-utils/directEncryptionProvider.js +86 -0
  12. package/dist/packlets/crypto-utils/encryptedFile.js +161 -0
  13. package/dist/packlets/crypto-utils/index.browser.js +41 -0
  14. package/dist/packlets/crypto-utils/index.js +41 -0
  15. package/dist/packlets/crypto-utils/keystore/converters.js +84 -0
  16. package/dist/packlets/crypto-utils/keystore/index.js +31 -0
  17. package/dist/packlets/crypto-utils/keystore/keyStore.js +758 -0
  18. package/dist/packlets/crypto-utils/keystore/model.js +64 -0
  19. package/dist/packlets/crypto-utils/model.js +39 -0
  20. package/dist/packlets/crypto-utils/nodeCryptoProvider.js +159 -0
  21. package/dist/packlets/experimental/formatter.js +1 -1
  22. package/dist/packlets/mustache/index.js +23 -0
  23. package/dist/packlets/mustache/interfaces.js +25 -0
  24. package/dist/packlets/mustache/mustacheTemplate.js +242 -0
  25. package/dist/packlets/record-jar/recordJarHelpers.js +1 -1
  26. package/dist/packlets/yaml/converters.js +46 -0
  27. package/dist/packlets/yaml/index.js +23 -0
  28. package/dist/packlets/zip-file-tree/index.js +1 -0
  29. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +43 -2
  30. package/dist/packlets/zip-file-tree/zipFileTreeWriter.js +40 -0
  31. package/dist/ts-extras.d.ts +1990 -112
  32. package/dist/tsdoc-metadata.json +1 -1
  33. package/lib/index.browser.d.ts +3 -1
  34. package/lib/index.browser.js +6 -1
  35. package/lib/index.d.ts +5 -1
  36. package/lib/index.js +9 -1
  37. package/lib/packlets/ai-assist/apiClient.d.ts +60 -0
  38. package/lib/packlets/ai-assist/apiClient.js +488 -0
  39. package/lib/packlets/ai-assist/converters.d.ts +55 -0
  40. package/lib/packlets/ai-assist/converters.js +124 -0
  41. package/lib/packlets/ai-assist/index.d.ts +10 -0
  42. package/lib/packlets/ai-assist/index.js +33 -0
  43. package/lib/packlets/ai-assist/model.d.ts +222 -0
  44. package/lib/packlets/ai-assist/model.js +95 -0
  45. package/lib/packlets/ai-assist/registry.d.ts +25 -0
  46. package/lib/packlets/ai-assist/registry.js +150 -0
  47. package/lib/packlets/ai-assist/toolFormats.d.ts +44 -0
  48. package/lib/packlets/ai-assist/toolFormats.js +166 -0
  49. package/lib/packlets/crypto-utils/constants.d.ts +26 -0
  50. package/lib/packlets/crypto-utils/constants.js +51 -0
  51. package/lib/packlets/crypto-utils/converters.d.ts +58 -0
  52. package/lib/packlets/crypto-utils/converters.js +192 -0
  53. package/lib/packlets/crypto-utils/directEncryptionProvider.d.ts +69 -0
  54. package/lib/packlets/crypto-utils/directEncryptionProvider.js +90 -0
  55. package/lib/packlets/crypto-utils/encryptedFile.d.ts +88 -0
  56. package/lib/packlets/crypto-utils/encryptedFile.js +201 -0
  57. package/lib/packlets/crypto-utils/index.browser.d.ts +14 -0
  58. package/lib/packlets/crypto-utils/index.browser.js +91 -0
  59. package/lib/packlets/crypto-utils/index.d.ts +15 -0
  60. package/lib/packlets/crypto-utils/index.js +88 -0
  61. package/lib/packlets/crypto-utils/keystore/converters.d.ts +29 -0
  62. package/lib/packlets/crypto-utils/keystore/converters.js +87 -0
  63. package/lib/packlets/crypto-utils/keystore/index.d.ts +9 -0
  64. package/lib/packlets/crypto-utils/keystore/index.js +71 -0
  65. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +239 -0
  66. package/lib/packlets/crypto-utils/keystore/keyStore.js +795 -0
  67. package/lib/packlets/crypto-utils/keystore/model.d.ts +245 -0
  68. package/lib/packlets/crypto-utils/keystore/model.js +68 -0
  69. package/lib/packlets/crypto-utils/model.d.ts +236 -0
  70. package/lib/packlets/crypto-utils/model.js +76 -0
  71. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +62 -0
  72. package/lib/packlets/crypto-utils/nodeCryptoProvider.js +196 -0
  73. package/lib/packlets/experimental/formatter.d.ts +1 -1
  74. package/lib/packlets/experimental/formatter.js +1 -1
  75. package/lib/packlets/mustache/index.d.ts +3 -0
  76. package/lib/packlets/mustache/index.js +27 -0
  77. package/lib/packlets/mustache/interfaces.d.ts +97 -0
  78. package/lib/packlets/mustache/interfaces.js +26 -0
  79. package/lib/packlets/mustache/mustacheTemplate.d.ts +76 -0
  80. package/lib/packlets/mustache/mustacheTemplate.js +249 -0
  81. package/lib/packlets/record-jar/recordJarHelpers.js +1 -1
  82. package/lib/packlets/yaml/converters.d.ts +9 -0
  83. package/lib/packlets/yaml/converters.js +82 -0
  84. package/lib/packlets/yaml/index.d.ts +2 -0
  85. package/lib/packlets/yaml/index.js +39 -0
  86. package/lib/packlets/zip-file-tree/index.d.ts +1 -0
  87. package/lib/packlets/zip-file-tree/index.js +15 -0
  88. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +31 -2
  89. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +42 -1
  90. package/lib/packlets/zip-file-tree/zipFileTreeWriter.d.ts +27 -0
  91. package/lib/packlets/zip-file-tree/zipFileTreeWriter.js +43 -0
  92. package/package.json +37 -18
@@ -1,11 +1,210 @@
1
1
  import { Conversion } from '@fgv/ts-utils';
2
2
  import { Converter } from '@fgv/ts-utils';
3
+ import { DetailedResult } from '@fgv/ts-utils';
3
4
  import { FileTree } from '@fgv/ts-json-base';
4
5
  import { Hash as Hash_2 } from '@fgv/ts-utils';
5
6
  import { JsonValue } from '@fgv/ts-json-base';
7
+ import { Logging } from '@fgv/ts-utils';
6
8
  import { Result } from '@fgv/ts-utils';
7
9
  import { Validator } from '@fgv/ts-utils';
8
10
 
11
+ /**
12
+ * Key size in bytes for AES-256.
13
+ * @public
14
+ */
15
+ declare const AES_256_KEY_SIZE: number;
16
+
17
+ /**
18
+ * API format categories for provider routing.
19
+ * @public
20
+ */
21
+ declare type AiApiFormat = 'openai' | 'anthropic' | 'gemini';
22
+
23
+ declare namespace AiAssist {
24
+ export {
25
+ AiPrompt,
26
+ AiProviderId,
27
+ AiServerToolType,
28
+ AiServerToolConfig,
29
+ IAiWebSearchToolConfig,
30
+ IAiToolEnablement,
31
+ IAiCompletionResponse,
32
+ IChatMessage,
33
+ AiApiFormat,
34
+ IAiProviderDescriptor,
35
+ IAiAssistProviderConfig,
36
+ IAiAssistSettings,
37
+ DEFAULT_AI_ASSIST,
38
+ IAiAssistKeyStore,
39
+ ModelSpec,
40
+ ModelSpecKey,
41
+ IModelSpecMap,
42
+ allModelSpecKeys,
43
+ MODEL_SPEC_BASE_KEY,
44
+ resolveModel,
45
+ allProviderIds,
46
+ getProviderDescriptors,
47
+ getProviderDescriptor,
48
+ callProviderCompletion,
49
+ callProxiedCompletion,
50
+ IProviderCompletionParams,
51
+ aiProviderId,
52
+ aiServerToolType,
53
+ aiWebSearchToolConfig,
54
+ aiServerToolConfig,
55
+ aiToolEnablement,
56
+ aiAssistProviderConfig,
57
+ aiAssistSettings,
58
+ modelSpecKey,
59
+ modelSpec,
60
+ resolveEffectiveTools
61
+ }
62
+ }
63
+ export { AiAssist }
64
+
65
+ /**
66
+ * Converter for {@link IAiAssistProviderConfig}.
67
+ * @public
68
+ */
69
+ declare const aiAssistProviderConfig: Converter<IAiAssistProviderConfig>;
70
+
71
+ /**
72
+ * Converter for {@link IAiAssistSettings}.
73
+ * @public
74
+ */
75
+ declare const aiAssistSettings: Converter<IAiAssistSettings>;
76
+
77
+ /**
78
+ * A structured AI prompt with system/user split for direct API calls,
79
+ * and a lazily-constructed combined version for copy/paste workflows.
80
+ * @public
81
+ */
82
+ declare class AiPrompt {
83
+ /** System instructions: schema documentation, format rules, general guidance. */
84
+ readonly system: string;
85
+ /** User request: the specific entity generation request. */
86
+ readonly user: string;
87
+ constructor(user: string, system: string);
88
+ /** Combined single-string version (user + system joined) for copy/paste. */
89
+ get combined(): string;
90
+ }
91
+
92
+ /**
93
+ * All known AI provider identifiers.
94
+ * @public
95
+ */
96
+ declare type AiProviderId = 'copy-paste' | 'xai-grok' | 'openai' | 'anthropic' | 'google-gemini' | 'groq' | 'mistral';
97
+
98
+ /**
99
+ * Converter for {@link AiProviderId}.
100
+ * @public
101
+ */
102
+ declare const aiProviderId: Converter<AiProviderId>;
103
+
104
+ /**
105
+ * Union of all server-side tool configurations. Discriminated on `type`.
106
+ * @public
107
+ */
108
+ declare type AiServerToolConfig = IAiWebSearchToolConfig;
109
+
110
+ /**
111
+ * Converter for {@link AiServerToolConfig} (discriminated union on `type`).
112
+ * @public
113
+ */
114
+ declare const aiServerToolConfig: Converter<AiServerToolConfig>;
115
+
116
+ /**
117
+ * Built-in server-side tool types supported across providers.
118
+ * @public
119
+ */
120
+ declare type AiServerToolType = 'web_search';
121
+
122
+ /**
123
+ * Converter for {@link AiServerToolType}.
124
+ * @public
125
+ */
126
+ declare const aiServerToolType: Converter<AiServerToolType>;
127
+
128
+ /**
129
+ * Converter for {@link IAiToolEnablement}.
130
+ * @public
131
+ */
132
+ declare const aiToolEnablement: Converter<IAiToolEnablement>;
133
+
134
+ /**
135
+ * Converter for {@link IAiWebSearchToolConfig}.
136
+ * @public
137
+ */
138
+ declare const aiWebSearchToolConfig: Converter<IAiWebSearchToolConfig>;
139
+
140
+ /**
141
+ * All valid key store secret types.
142
+ * @public
143
+ */
144
+ declare const allKeyStoreSecretTypes: ReadonlyArray<KeyStoreSecretType>;
145
+
146
+ /**
147
+ * All valid {@link ModelSpecKey} values.
148
+ * @public
149
+ */
150
+ declare const allModelSpecKeys: ReadonlyArray<ModelSpecKey>;
151
+
152
+ /**
153
+ * All valid provider ID values, in the same order as the registry.
154
+ * @public
155
+ */
156
+ declare const allProviderIds: ReadonlyArray<AiProviderId>;
157
+
158
+ /**
159
+ * Converter for base64 strings (validates format).
160
+ * @public
161
+ */
162
+ declare const base64String: Converter<string>;
163
+
164
+ /**
165
+ * Calls the appropriate chat completion API for a given provider.
166
+ *
167
+ * Routes based on the provider descriptor's `apiFormat` field:
168
+ * - `'openai'` for xAI, OpenAI, Groq, Mistral
169
+ * - `'anthropic'` for Anthropic Claude
170
+ * - `'gemini'` for Google Gemini
171
+ *
172
+ * When tools are provided and the provider supports them:
173
+ * - OpenAI-format providers switch to the Responses API
174
+ * - Anthropic includes tools in the Messages API request
175
+ * - Gemini includes Google Search grounding
176
+ *
177
+ * @param params - Request parameters including descriptor, API key, prompt, and optional tools
178
+ * @returns The completion response with content and truncation status, or a failure
179
+ * @public
180
+ */
181
+ declare function callProviderCompletion(params: IProviderCompletionParams): Promise<Result<IAiCompletionResponse>>;
182
+
183
+ /**
184
+ * Calls the AI completion endpoint on a proxy server instead of calling
185
+ * the provider API directly from the browser.
186
+ *
187
+ * The proxy server handles provider dispatch, CORS, and API key forwarding.
188
+ * The request shape mirrors {@link IProviderCompletionParams} but is serialized
189
+ * as JSON for the proxy endpoint.
190
+ *
191
+ * @param proxyUrl - Base URL of the proxy server (e.g. `http://localhost:3001`)
192
+ * @param params - Same parameters as {@link callProviderCompletion}
193
+ * @returns The completion response, or a failure
194
+ * @public
195
+ */
196
+ declare function callProxiedCompletion(proxyUrl: string, params: IProviderCompletionParams): Promise<Result<IAiCompletionResponse>>;
197
+
198
+ declare namespace Constants {
199
+ export {
200
+ ENCRYPTED_FILE_FORMAT,
201
+ DEFAULT_ALGORITHM,
202
+ AES_256_KEY_SIZE,
203
+ GCM_IV_SIZE,
204
+ GCM_AUTH_TAG_SIZE
205
+ }
206
+ }
207
+
9
208
  declare namespace Converters {
10
209
  export {
11
210
  templateString,
@@ -17,6 +216,87 @@ declare namespace Converters {
17
216
  }
18
217
  export { Converters }
19
218
 
219
+ declare namespace Converters_2 {
220
+ export {
221
+ keystoreFormat,
222
+ keystoreSecretType,
223
+ keystoreSecretEntryJson,
224
+ keystoreVaultContents,
225
+ keystoreFile
226
+ }
227
+ }
228
+
229
+ declare namespace Converters_3 {
230
+ export {
231
+ createEncryptedFileConverter,
232
+ encryptionAlgorithm,
233
+ encryptedFileFormat,
234
+ encryptedFileErrorMode,
235
+ keyDerivationFunction,
236
+ keyDerivationParams,
237
+ base64String,
238
+ uint8ArrayFromBase64,
239
+ namedSecret,
240
+ encryptedFile
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Creates an {@link CryptoUtils.IEncryptedFile | encrypted file} from JSON content.
246
+ * @typeParam TMetadata - Type of optional unencrypted metadata
247
+ * @param params - Encryption parameters
248
+ * @returns `Success` with encrypted file structure, or `Failure` with an error.
249
+ * @public
250
+ */
251
+ declare function createEncryptedFile<TMetadata = JsonValue>(params: ICreateEncryptedFileParams<TMetadata>): Promise<Result<IEncryptedFile<TMetadata>>>;
252
+
253
+ /**
254
+ * Creates a converter for {@link CryptoUtils.IEncryptedFile | encrypted files} with optional typed metadata.
255
+ * @typeParam TMetadata - Type of optional unencrypted metadata
256
+ * @param metadataConverter - Optional converter for validating metadata field
257
+ * @returns A converter that validates and converts encrypted file structures
258
+ * @public
259
+ */
260
+ declare function createEncryptedFileConverter<TMetadata = JsonValue>(metadataConverter?: Converter<TMetadata>): Converter<IEncryptedFile<TMetadata>>;
261
+
262
+ /**
263
+ * Creates a zip file from an array of text files.
264
+ * @public
265
+ */
266
+ declare function createZipFromTextFiles(files: ReadonlyArray<IZipTextFile>, options?: ICreateZipOptions): Result<Uint8Array>;
267
+
268
+ declare namespace CryptoUtils {
269
+ export {
270
+ Constants,
271
+ KeyStore,
272
+ Converters_3 as Converters,
273
+ DirectEncryptionProvider,
274
+ IDirectEncryptionProviderParams,
275
+ NodeCryptoProvider,
276
+ nodeCryptoProvider,
277
+ createEncryptedFile,
278
+ decryptFile,
279
+ fromBase64,
280
+ ICreateEncryptedFileParams,
281
+ toBase64,
282
+ tryDecryptFile,
283
+ isEncryptedFile,
284
+ EncryptionAlgorithm,
285
+ EncryptedFileFormat,
286
+ INamedSecret,
287
+ IEncryptionResult,
288
+ KeyDerivationFunction,
289
+ IKeyDerivationParams,
290
+ IEncryptedFile,
291
+ ICryptoProvider,
292
+ IEncryptionProvider,
293
+ EncryptedFileErrorMode,
294
+ SecretProvider,
295
+ IEncryptionConfig
296
+ }
297
+ }
298
+ export { CryptoUtils }
299
+
20
300
  declare namespace Csv {
21
301
  export {
22
302
  parseCsvString,
@@ -35,6 +315,37 @@ declare interface CsvOptions {
35
315
  delimiter?: string;
36
316
  }
37
317
 
318
+ /**
319
+ * Decrypts an {@link CryptoUtils.IEncryptedFile | encrypted file} and returns the JSON content.
320
+ * @typeParam TPayload - Expected type of decrypted content
321
+ * @param file - The encrypted file structure
322
+ * @param key - The decryption key (32 bytes for AES-256)
323
+ * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption
324
+ * @param payloadConverter - Optional converter to validate and convert decrypted content
325
+ * @returns `Success` with decrypted content, or `Failure` with an error.
326
+ * @public
327
+ */
328
+ declare function decryptFile<TPayload extends JsonValue = JsonValue>(file: IEncryptedFile<unknown>, key: Uint8Array, cryptoProvider: ICryptoProvider, payloadConverter?: Converter<TPayload>): Promise<Result<TPayload>>;
329
+
330
+ /**
331
+ * Default AI assist settings (copy-paste only).
332
+ * @public
333
+ */
334
+ declare const DEFAULT_AI_ASSIST: IAiAssistSettings;
335
+
336
+ /**
337
+ * Default encryption algorithm.
338
+ * @public
339
+ */
340
+ declare const DEFAULT_ALGORITHM: "AES-256-GCM";
341
+
342
+ /**
343
+ * Default PBKDF2 iterations for key store encryption.
344
+ * Higher than regular files since this protects the master key vault.
345
+ * @public
346
+ */
347
+ declare const DEFAULT_KEYSTORE_ITERATIONS: number;
348
+
38
349
  /**
39
350
  * Default {@link Experimental.RangeOfFormats | formats} to use for both
40
351
  * open-ended and complete {@link Experimental.RangeOf | RangeOf<T>}.
@@ -42,6 +353,107 @@ declare interface CsvOptions {
42
353
  */
43
354
  declare const DEFAULT_RANGEOF_FORMATS: RangeOfFormats;
44
355
 
356
+ /**
357
+ * Default PBKDF2 iterations for secret-level key derivation.
358
+ * Lower than keystore encryption since these are used more frequently.
359
+ * @public
360
+ */
361
+ declare const DEFAULT_SECRET_ITERATIONS: number;
362
+
363
+ /**
364
+ * An {@link IEncryptionProvider} that uses a pre-supplied key and crypto provider.
365
+ *
366
+ * This is useful when you have the raw encryption key from an external source
367
+ * (e.g. a `SecretProvider` callback, password derivation, or a one-shot
368
+ * operation) and don't want to open a full KeyStore.
369
+ *
370
+ * Optionally bound to a specific secret name for safety: if a `boundSecretName`
371
+ * is provided, calls to `encryptByName` with a different name will fail.
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * const provider = DirectEncryptionProvider.create({
376
+ * cryptoProvider: nodeCryptoProvider,
377
+ * key: myKey,
378
+ * boundSecretName: 'my-collection'
379
+ * }).orThrow();
380
+ *
381
+ * const encrypted = await provider.encryptByName('my-collection', jsonContent);
382
+ * ```
383
+ *
384
+ * @public
385
+ */
386
+ declare class DirectEncryptionProvider implements IEncryptionProvider {
387
+ private readonly _cryptoProvider;
388
+ private readonly _key;
389
+ private readonly _boundSecretName;
390
+ private constructor();
391
+ /**
392
+ * Creates a new DirectEncryptionProvider.
393
+ * @param params - Provider configuration
394
+ * @returns Success with provider, or Failure if parameters are invalid
395
+ * @public
396
+ */
397
+ static create(params: IDirectEncryptionProviderParams): Result<DirectEncryptionProvider>;
398
+ /**
399
+ * The secret name this provider is bound to, if any.
400
+ * @public
401
+ */
402
+ get boundSecretName(): string | undefined;
403
+ /**
404
+ * {@inheritDoc IEncryptionProvider.encryptByName}
405
+ */
406
+ encryptByName<TMetadata = JsonValue>(secretName: string, content: JsonValue, metadata?: TMetadata): Promise<Result<IEncryptedFile<TMetadata>>>;
407
+ }
408
+
409
+ /**
410
+ * Current format version for encrypted files.
411
+ * @public
412
+ */
413
+ declare const ENCRYPTED_FILE_FORMAT: "encrypted-collection-v1";
414
+
415
+ /**
416
+ * Default converter for encrypted files without typed metadata.
417
+ * @public
418
+ */
419
+ declare const encryptedFile: Converter<IEncryptedFile>;
420
+
421
+ /**
422
+ * Behavior when an encrypted file cannot be decrypted.
423
+ * @public
424
+ */
425
+ declare type EncryptedFileErrorMode = 'fail' | 'skip' | 'warn';
426
+
427
+ /**
428
+ * Converter for {@link CryptoUtils.EncryptedFileErrorMode | encrypted file error mode}.
429
+ * @public
430
+ */
431
+ declare const encryptedFileErrorMode: Converter<EncryptedFileErrorMode>;
432
+
433
+ /**
434
+ * Format version for encrypted files.
435
+ * @public
436
+ */
437
+ declare type EncryptedFileFormat = typeof Constants.ENCRYPTED_FILE_FORMAT;
438
+
439
+ /**
440
+ * Converter for {@link CryptoUtils.EncryptedFileFormat | encrypted file format} version.
441
+ * @public
442
+ */
443
+ declare const encryptedFileFormat: Converter<EncryptedFileFormat>;
444
+
445
+ /**
446
+ * Supported encryption algorithms.
447
+ * @public
448
+ */
449
+ declare type EncryptionAlgorithm = typeof Constants.DEFAULT_ALGORITHM;
450
+
451
+ /**
452
+ * Converter for {@link CryptoUtils.EncryptionAlgorithm | encryption algorithm} values.
453
+ * @public
454
+ */
455
+ declare const encryptionAlgorithm: Converter<EncryptionAlgorithm>;
456
+
45
457
  declare namespace Experimental {
46
458
  export {
47
459
  ExtendedArray,
@@ -68,178 +480,1523 @@ export { Experimental }
68
480
  declare class ExtendedArray<T> extends Array<T> {
69
481
  readonly itemDescription: string;
70
482
  /**
71
- * Constructs an {@link Experimental.ExtendedArray | ExtendedArray}.
72
- * @param itemDescription - Brief description of the type of each item in this array.
73
- * @param items - The initial contents of the array.
483
+ * Constructs an {@link Experimental.ExtendedArray | ExtendedArray}.
484
+ * @param itemDescription - Brief description of the type of each item in this array.
485
+ * @param items - The initial contents of the array.
486
+ */
487
+ constructor(itemDescription: string, ...items: T[]);
488
+ /**
489
+ * Type guard to determine if some arbitrary array is an
490
+ * {@link Experimental.ExtendedArray}
491
+ * @param a - The `Array` to be tested.
492
+ * @returns Returns `true` if `a` is an {@link Experimental.ExtendedArray | ExtendedArray},
493
+ * `false` otherwise.
494
+ */
495
+ static isExtendedArray<T>(a?: T[]): a is ExtendedArray<T>;
496
+ /**
497
+ * Determines if this array contains exactly one element which matches
498
+ * a supplied predicate.
499
+ * @param predicate - The predicate function to be applied.
500
+ * @returns Returns `Success<T>` with the single matching
501
+ * result if exactly one item matches `predicate`. Returns `Failure<T>`
502
+ * with an error message if there are no matches or more than one match.
503
+ */
504
+ single(predicate?: (item: T) => boolean): Result<T>;
505
+ /**
506
+ * Returns the first element of an {@link Experimental.ExtendedArray | ExtendedArray}. Fails with an
507
+ * error message if the array is empty.
508
+ * @param failMessage - Optional message to be displayed in the event of failure.
509
+ * @returns Returns `Success<T>` with the value of the first element
510
+ * in the array, or `Failure<T>` with an error message if the array is empty.
511
+ */
512
+ first(failMessage?: string): Result<T>;
513
+ /**
514
+ * Returns an array containing all elements of an {@link Experimental.ExtendedArray | ExtendedArray}.
515
+ * Fails with an error message if the array is empty.
516
+ * @param failMessage - Optional message to be displayed in the event of failure.
517
+ * @returns Returns `Success<T>` with a new (non-extended) `Array`
518
+ * containing the elements of this array, or `Failure<T>` with an error message
519
+ * if the array is empty.
520
+ */
521
+ atLeastOne(failMessage?: string): Result<T[]>;
522
+ /**
523
+ * Gets a new (non-extended) `Array` containing all of the elements from this
524
+ * {@link Experimental.ExtendedArray | ExtendedArray}.
525
+ * @returns A new (non-extended) `Array<T>`.
526
+ */
527
+ all(): T[];
528
+ }
529
+
530
+ /**
531
+ * A helper function to create a `Converter` which converts `unknown` to {@link Experimental.ExtendedArray | ExtendedArray<T>}.
532
+ * @remarks
533
+ * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
534
+ * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
535
+ * @param converter - `Converter` used to convert each item in the array
536
+ * @param ignoreErrors - Specifies treatment of unconvertible elements
537
+ * @beta
538
+ */
539
+ declare function extendedArrayOf<T, TC = undefined>(label: string, converter: Converter<T, TC>, onError?: Conversion.OnError): Converter<ExtendedArray<T>, TC>;
540
+
541
+ /**
542
+ * Formats a list of items using the supplied template and formatter, one result
543
+ * per output line.
544
+ * @param format - A mustache template used to format each item.
545
+ * @param items - The items to be formatted.
546
+ * @param itemFormatter - The {@link Experimental.Formatter | Formatter<T>} used to format each item.
547
+ * @returns The resulting string.
548
+ * @beta
549
+ */
550
+ declare function formatList<T>(format: string, items: T[], itemFormatter: Formatter<T>): Result<string>;
551
+
552
+ /**
553
+ * Interface for an object that can be formatted.
554
+ * @beta
555
+ */
556
+ declare interface Formattable {
557
+ /**
558
+ * Formats an object using the supplied mustache template.
559
+ * @param format - A mustache template used to format the object.
560
+ * @returns `Success<string>` with the resulting string, or `Failure<string>`
561
+ * with an error message if an error occurs.
562
+ */
563
+ format(format: string): Result<string>;
564
+ }
565
+
566
+ /**
567
+ * Base class which adds common formatting.
568
+ * @beta
569
+ */
570
+ declare class FormattableBase {
571
+ /**
572
+ * Helper enables derived classes to add named details to a formatted presentation.
573
+ * @param details - An array of detail description strings.
574
+ * @param label - Label to use for the new detail.
575
+ * @param value - Value to use for the new detail.
576
+ * @internal
577
+ */
578
+ protected static _tryAddDetail(details: string[], label: string, value: string | undefined): void;
579
+ /**
580
+ * {@inheritDoc Experimental.Formattable.format}
581
+ */
582
+ format(template: string): Result<string>;
583
+ }
584
+
585
+ /**
586
+ * Destination format for some formatted string.
587
+ * @beta
588
+ */
589
+ declare type FormatTargets = 'text' | 'markdown' | 'embed';
590
+
591
+ /**
592
+ * Type definition for a formatting function, which takes a `string` and an
593
+ * item and returns `Result<string>`.
594
+ * @beta
595
+ */
596
+ declare type Formatter<T> = (format: string, item: T) => Result<string>;
597
+
598
+ /**
599
+ * A collection of {@link Experimental.Formatter | formatters} indexed by target name, to enable
600
+ * different format methods per output target.
601
+ * @beta
602
+ */
603
+ declare type FormattersByExtendedTarget<TFT extends FormatTargets, T> = Record<TFT, Formatter<T>>;
604
+
605
+ /**
606
+ * A collection of {@link Experimental.Formatter | formatters} indexed by the
607
+ * {@link Experimental.FormatTargets | default supported target formats}.
608
+ * @beta
609
+ */
610
+ declare type FormattersByTarget<T> = FormattersByExtendedTarget<FormatTargets, T>;
611
+
612
+ /**
613
+ * Decodes a base64 string to a `Uint8Array`.
614
+ * @param base64 - Base64 string to decode
615
+ * @returns Decoded bytes
616
+ * @public
617
+ */
618
+ declare function fromBase64(base64: string): Uint8Array;
619
+
620
+ /**
621
+ * Auth tag size in bytes for GCM mode.
622
+ * @public
623
+ */
624
+ declare const GCM_AUTH_TAG_SIZE: number;
625
+
626
+ /**
627
+ * IV size in bytes for GCM mode.
628
+ * @public
629
+ */
630
+ declare const GCM_IV_SIZE: number;
631
+
632
+ /**
633
+ * Get a provider descriptor by id.
634
+ * @param id - The provider identifier
635
+ * @returns The descriptor, or a failure if the provider is unknown
636
+ * @public
637
+ */
638
+ declare function getProviderDescriptor(id: string): Result<IAiProviderDescriptor>;
639
+
640
+ /**
641
+ * Get all known provider descriptors. Copy-paste first, then alphabetical.
642
+ * @returns All built-in provider descriptors
643
+ * @public
644
+ */
645
+ declare function getProviderDescriptors(): ReadonlyArray<IAiProviderDescriptor>;
646
+
647
+ declare namespace Hash {
648
+ export {
649
+ Md5Normalizer
650
+ }
651
+ }
652
+ export { Hash }
653
+
654
+ /**
655
+ * Options for adding a secret derived from a password.
656
+ * @public
657
+ */
658
+ declare interface IAddSecretFromPasswordOptions extends IAddSecretOptions {
659
+ /**
660
+ * Whether to replace an existing secret with the same name.
661
+ */
662
+ readonly replace?: boolean;
663
+ /**
664
+ * PBKDF2 iterations for key derivation.
665
+ * @defaultValue DEFAULT_SECRET_ITERATIONS (350000)
666
+ */
667
+ readonly iterations?: number;
668
+ }
669
+
670
+ /**
671
+ * Result of adding a password-derived secret.
672
+ * Extends {@link IAddSecretResult} with key derivation parameters
673
+ * needed to store alongside encrypted files.
674
+ * @public
675
+ */
676
+ declare interface IAddSecretFromPasswordResult extends IAddSecretResult {
677
+ /**
678
+ * Key derivation parameters used to derive the secret key.
679
+ * Store these in encrypted file metadata so the password alone
680
+ * can re-derive the same key for decryption.
681
+ */
682
+ readonly keyDerivation: IKeyDerivationParams;
683
+ }
684
+
685
+ /**
686
+ * Options for adding a secret.
687
+ * @public
688
+ */
689
+ declare interface IAddSecretOptions {
690
+ /**
691
+ * Optional description for the secret.
692
+ */
693
+ readonly description?: string;
694
+ }
695
+
696
+ /**
697
+ * Result of adding a secret to the key store.
698
+ * @public
699
+ */
700
+ declare interface IAddSecretResult {
701
+ /**
702
+ * The secret entry that was added.
703
+ */
704
+ readonly entry: IKeyStoreSecretEntry;
705
+ /**
706
+ * Whether this replaced an existing secret.
707
+ */
708
+ readonly replaced: boolean;
709
+ }
710
+
711
+ /**
712
+ * Minimal keystore interface for AI assist API key resolution.
713
+ * Satisfied structurally by the concrete `KeyStore` class from `@fgv/ts-extras`.
714
+ * @public
715
+ */
716
+ declare interface IAiAssistKeyStore {
717
+ /** Whether the keystore is currently unlocked */
718
+ readonly isUnlocked: boolean;
719
+ /** Check if a named secret exists */
720
+ hasSecret(name: string): Result<boolean>;
721
+ /** Get an API key by secret name */
722
+ getApiKey(name: string): Result<string>;
723
+ }
724
+
725
+ /**
726
+ * Configuration for a single AI assist provider.
727
+ * @public
728
+ */
729
+ declare interface IAiAssistProviderConfig {
730
+ /** Which provider this configures */
731
+ readonly provider: AiProviderId;
732
+ /** For API-based providers: the keystore secret name holding the API key */
733
+ readonly secretName?: string;
734
+ /** Optional model override — string or context-aware map. */
735
+ readonly model?: ModelSpec;
736
+ /** Tool enablement/configuration. Tools are disabled unless explicitly enabled. */
737
+ readonly tools?: ReadonlyArray<IAiToolEnablement>;
738
+ }
739
+
740
+ /**
741
+ * AI assist settings — which providers are enabled and their configuration.
742
+ * @public
743
+ */
744
+ declare interface IAiAssistSettings {
745
+ /** Enabled providers and their configuration. */
746
+ readonly providers: ReadonlyArray<IAiAssistProviderConfig>;
747
+ /** Which enabled provider is the default for the main button. Falls back to first in list. */
748
+ readonly defaultProvider?: AiProviderId;
749
+ /** Optional proxy URL for routing API requests through a backend server (e.g. `http://localhost:3002`). */
750
+ readonly proxyUrl?: string;
751
+ /** When true, route all providers through the proxy. When false (default), only CORS-restricted providers use the proxy. */
752
+ readonly proxyAllProviders?: boolean;
753
+ }
754
+
755
+ /**
756
+ * Result of an AI provider completion call.
757
+ * @public
758
+ */
759
+ declare interface IAiCompletionResponse {
760
+ /** The generated text content */
761
+ readonly content: string;
762
+ /** Whether the response was truncated due to token limits */
763
+ readonly truncated: boolean;
764
+ }
765
+
766
+ /**
767
+ * Describes a single AI provider — single source of truth for all metadata.
768
+ * @public
769
+ */
770
+ declare interface IAiProviderDescriptor {
771
+ /** Provider identifier (e.g. 'xai-grok', 'anthropic') */
772
+ readonly id: AiProviderId;
773
+ /** Human-readable label (e.g. "xAI Grok") */
774
+ readonly label: string;
775
+ /** Button label for action buttons (e.g. "AI Assist | Grok") */
776
+ readonly buttonLabel: string;
777
+ /** Whether this provider requires an API key secret */
778
+ readonly needsSecret: boolean;
779
+ /** Which API adapter format to use */
780
+ readonly apiFormat: AiApiFormat;
781
+ /** Base URL for the API (e.g. 'https://api.x.ai/v1') */
782
+ readonly baseUrl: string;
783
+ /** Default model specification — string or context-aware map. */
784
+ readonly defaultModel: ModelSpec;
785
+ /** Which server-side tools this provider supports (empty = none). */
786
+ readonly supportedTools: ReadonlyArray<AiServerToolType>;
787
+ /** Whether this provider's API enforces CORS restrictions that prevent direct browser calls. */
788
+ readonly corsRestricted: boolean;
789
+ }
790
+
791
+ /**
792
+ * Declares a tool as enabled/disabled in provider settings.
793
+ * Tools are disabled by default — consuming apps must opt in explicitly.
794
+ * @public
795
+ */
796
+ declare interface IAiToolEnablement {
797
+ /** Which tool type. */
798
+ readonly type: AiServerToolType;
799
+ /** Whether this tool is enabled by default for this provider. */
800
+ readonly enabled: boolean;
801
+ /** Optional tool-specific configuration. */
802
+ readonly config?: AiServerToolConfig;
803
+ }
804
+
805
+ /**
806
+ * Configuration specific to web search tools.
807
+ * @public
808
+ */
809
+ declare interface IAiWebSearchToolConfig {
810
+ readonly type: 'web_search';
811
+ /** Optional: restrict search to these domains. */
812
+ readonly allowedDomains?: ReadonlyArray<string>;
813
+ /** Optional: exclude these domains from search. */
814
+ readonly blockedDomains?: ReadonlyArray<string>;
815
+ /** Optional: max number of searches per request. */
816
+ readonly maxUses?: number;
817
+ /**
818
+ * Optional: enable image understanding during web search.
819
+ * When true, the model can view and analyze images found during search.
820
+ * Currently supported by xAI only; ignored by other providers.
821
+ */
822
+ readonly enableImageUnderstanding?: boolean;
823
+ }
824
+
825
+ /**
826
+ * A single chat message in OpenAI format.
827
+ * @public
828
+ */
829
+ declare interface IChatMessage {
830
+ /** Message role */
831
+ readonly role: 'system' | 'user' | 'assistant';
832
+ /** Message content */
833
+ readonly content: string;
834
+ }
835
+
836
+ /**
837
+ * Result of context validation, containing details about missing variables.
838
+ * @public
839
+ */
840
+ declare interface IContextValidationResult {
841
+ /**
842
+ * Whether the context is valid (has all required variables)
843
+ */
844
+ readonly isValid: boolean;
845
+ /**
846
+ * Variables that are present in the context
847
+ */
848
+ readonly presentVariables: readonly string[];
849
+ /**
850
+ * Variables that are missing from the context
851
+ */
852
+ readonly missingVariables: readonly string[];
853
+ /**
854
+ * Detailed information about each missing variable
855
+ */
856
+ readonly missingDetails: readonly IMissingVariableDetail[];
857
+ }
858
+
859
+ /**
860
+ * Parameters for creating an {@link CryptoUtils.IEncryptedFile | encrypted file}.
861
+ * @typeParam TMetadata - Type of optional unencrypted metadata
862
+ * @public
863
+ */
864
+ declare interface ICreateEncryptedFileParams<TMetadata = JsonValue> {
865
+ /**
866
+ * The JSON content to encrypt.
867
+ */
868
+ readonly content: JsonValue;
869
+ /**
870
+ * Name of the secret used for encryption.
871
+ */
872
+ readonly secretName: string;
873
+ /**
874
+ * The encryption key (32 bytes for AES-256).
875
+ */
876
+ readonly key: Uint8Array;
877
+ /**
878
+ * {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for encryption.
879
+ */
880
+ readonly cryptoProvider: ICryptoProvider;
881
+ /**
882
+ * Optional metadata to include unencrypted.
883
+ */
884
+ readonly metadata?: TMetadata;
885
+ /**
886
+ * Optional converter to validate metadata before including.
887
+ * If provided, metadata will be validated before encryption.
888
+ */
889
+ readonly metadataConverter?: Converter<TMetadata>;
890
+ /**
891
+ * Optional {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.
892
+ * If provided, stores the salt and iterations used to derive the key from a password.
893
+ * This allows decryption using only a password (the salt/iterations are read from the file).
894
+ */
895
+ readonly keyDerivation?: IKeyDerivationParams;
896
+ }
897
+
898
+ /**
899
+ * Options for creating a zip file from text files.
900
+ * @public
901
+ */
902
+ declare interface ICreateZipOptions {
903
+ readonly level?: ZipCompressionLevel;
904
+ }
905
+
906
+ /**
907
+ * Crypto provider interface for cross-platform encryption.
908
+ * Implementations provided for Node.js (crypto module) and browser (Web Crypto API).
909
+ * @public
910
+ */
911
+ declare interface ICryptoProvider {
912
+ /**
913
+ * Encrypts plaintext using AES-256-GCM.
914
+ * @param plaintext - UTF-8 string to encrypt
915
+ * @param key - 32-byte encryption key
916
+ * @returns Success with encryption result, or Failure with error
917
+ */
918
+ encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>>;
919
+ /**
920
+ * Decrypts ciphertext using AES-256-GCM.
921
+ * @param encryptedData - Encrypted bytes
922
+ * @param key - 32-byte decryption key
923
+ * @param iv - Initialization vector (12 bytes)
924
+ * @param authTag - GCM authentication tag (16 bytes)
925
+ * @returns Success with decrypted UTF-8 string, or Failure with error
926
+ */
927
+ decrypt(encryptedData: Uint8Array, key: Uint8Array, iv: Uint8Array, authTag: Uint8Array): Promise<Result<string>>;
928
+ /**
929
+ * Generates a random 32-byte key suitable for AES-256.
930
+ * @returns Success with generated key, or Failure with error
931
+ */
932
+ generateKey(): Promise<Result<Uint8Array>>;
933
+ /**
934
+ * Derives a key from a password using PBKDF2.
935
+ * @param password - Password string
936
+ * @param salt - Salt bytes (should be at least 16 bytes)
937
+ * @param iterations - Number of iterations (recommend 100000+)
938
+ * @returns Success with derived 32-byte key, or Failure with error
939
+ */
940
+ deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<Result<Uint8Array>>;
941
+ /**
942
+ * Generates cryptographically secure random bytes.
943
+ * @param length - Number of bytes to generate
944
+ * @returns Success with random bytes, or Failure with error
945
+ */
946
+ generateRandomBytes(length: number): Result<Uint8Array>;
947
+ /**
948
+ * Encodes binary data to base64 string.
949
+ * @param data - Binary data to encode
950
+ * @returns Base64-encoded string
951
+ */
952
+ toBase64(data: Uint8Array): string;
953
+ /**
954
+ * Decodes base64 string to binary data.
955
+ * @param base64 - Base64-encoded string
956
+ * @returns Success with decoded bytes, or Failure if invalid base64
957
+ */
958
+ fromBase64(base64: string): Result<Uint8Array>;
959
+ }
960
+
961
+ /**
962
+ * Parameters for creating a {@link DirectEncryptionProvider}.
963
+ * @public
964
+ */
965
+ declare interface IDirectEncryptionProviderParams {
966
+ /**
967
+ * The crypto provider to use for encryption operations.
968
+ */
969
+ readonly cryptoProvider: ICryptoProvider;
970
+ /**
971
+ * The encryption key (32 bytes for AES-256).
972
+ */
973
+ readonly key: Uint8Array;
974
+ /**
975
+ * Optional bound secret name.
976
+ * When set, `encryptByName` will fail if called with a different name.
977
+ * When unset, any secret name is accepted.
978
+ */
979
+ readonly boundSecretName?: string;
980
+ }
981
+
982
+ /**
983
+ * Generic encrypted file format.
984
+ * This is the JSON structure stored in encrypted files.
985
+ * @typeParam TMetadata - Type of optional unencrypted metadata
986
+ * @public
987
+ */
988
+ declare interface IEncryptedFile<TMetadata = JsonValue> {
989
+ /**
990
+ * Format identifier for versioning.
991
+ */
992
+ readonly format: EncryptedFileFormat;
993
+ /**
994
+ * Name of the secret required to decrypt (references INamedSecret.name).
995
+ */
996
+ readonly secretName: string;
997
+ /**
998
+ * Algorithm used for encryption.
999
+ */
1000
+ readonly algorithm: EncryptionAlgorithm;
1001
+ /**
1002
+ * Base64-encoded initialization vector.
1003
+ */
1004
+ readonly iv: string;
1005
+ /**
1006
+ * Base64-encoded authentication tag (for GCM mode).
1007
+ */
1008
+ readonly authTag: string;
1009
+ /**
1010
+ * Base64-encoded encrypted data (JSON string when decrypted).
1011
+ */
1012
+ readonly encryptedData: string;
1013
+ /**
1014
+ * Optional unencrypted metadata for display/filtering.
1015
+ */
1016
+ readonly metadata?: TMetadata;
1017
+ /**
1018
+ * Optional key derivation parameters.
1019
+ * If present, allows decryption using a password with these parameters.
1020
+ * If absent, a pre-derived key must be provided.
1021
+ */
1022
+ readonly keyDerivation?: IKeyDerivationParams;
1023
+ }
1024
+
1025
+ /**
1026
+ * Configuration for encrypted file handling during loading.
1027
+ * @public
1028
+ */
1029
+ declare interface IEncryptionConfig {
1030
+ /**
1031
+ * Named secrets available for decryption.
1032
+ */
1033
+ readonly secrets?: ReadonlyArray<INamedSecret>;
1034
+ /**
1035
+ * Alternative: dynamic secret provider function.
1036
+ * Called when a secret is not found in the secrets array.
1037
+ */
1038
+ readonly secretProvider?: SecretProvider;
1039
+ /**
1040
+ * Crypto provider implementation (Node.js or browser).
1041
+ */
1042
+ readonly cryptoProvider: ICryptoProvider;
1043
+ /**
1044
+ * Behavior when decryption key is missing (default: 'fail').
1045
+ */
1046
+ readonly onMissingKey?: EncryptedFileErrorMode;
1047
+ /**
1048
+ * Behavior when decryption fails (default: 'fail').
1049
+ */
1050
+ readonly onDecryptionError?: EncryptedFileErrorMode;
1051
+ }
1052
+
1053
+ /**
1054
+ * High-level interface for encrypting JSON content by secret name.
1055
+ *
1056
+ * This abstraction unifies two common encryption workflows:
1057
+ * - **KeyStore**: looks up the named secret and crypto provider from the vault
1058
+ * - **DirectEncryptionProvider**: uses a pre-supplied key and crypto provider,
1059
+ * optionally bound to a specific secret name for safety
1060
+ *
1061
+ * Callers that need to encrypt (e.g. `EditableCollection.save()`) depend on
1062
+ * this interface rather than on `KeyStore` directly, allowing mix-and-match.
1063
+ *
1064
+ * @public
1065
+ */
1066
+ declare interface IEncryptionProvider {
1067
+ /**
1068
+ * Encrypts JSON content under a named secret.
1069
+ *
1070
+ * @param secretName - Name of the secret to encrypt with
1071
+ * @param content - JSON-safe content to encrypt
1072
+ * @param metadata - Optional unencrypted metadata to include in the encrypted file
1073
+ * @returns Success with encrypted file structure, or Failure with error context
1074
+ */
1075
+ encryptByName<TMetadata = JsonValue>(secretName: string, content: JsonValue, metadata?: TMetadata): Promise<Result<IEncryptedFile<TMetadata>>>;
1076
+ }
1077
+
1078
+ /**
1079
+ * Result of an encryption operation.
1080
+ * @public
1081
+ */
1082
+ declare interface IEncryptionResult {
1083
+ /**
1084
+ * Initialization vector used for encryption (12 bytes for GCM).
1085
+ */
1086
+ readonly iv: Uint8Array;
1087
+ /**
1088
+ * Authentication tag from GCM mode (16 bytes).
1089
+ */
1090
+ readonly authTag: Uint8Array;
1091
+ /**
1092
+ * The encrypted data.
1093
+ */
1094
+ readonly encryptedData: Uint8Array;
1095
+ }
1096
+
1097
+ /**
1098
+ * Options for importing a secret.
1099
+ * @public
1100
+ */
1101
+ declare interface IImportSecretOptions extends IAddSecretOptions {
1102
+ /**
1103
+ * Whether to replace an existing secret with the same name.
1104
+ */
1105
+ readonly replace?: boolean;
1106
+ }
1107
+
1108
+ /**
1109
+ * Key derivation parameters stored in encrypted files.
1110
+ * Allows decryption with password without needing to know the original salt/iterations.
1111
+ * @public
1112
+ */
1113
+ declare interface IKeyDerivationParams {
1114
+ /**
1115
+ * Key derivation function used.
1116
+ */
1117
+ readonly kdf: KeyDerivationFunction;
1118
+ /**
1119
+ * Base64-encoded salt used for key derivation.
1120
+ */
1121
+ readonly salt: string;
1122
+ /**
1123
+ * Number of iterations used for key derivation.
1124
+ */
1125
+ readonly iterations: number;
1126
+ }
1127
+
1128
+ /**
1129
+ * Parameters for creating a new key store.
1130
+ * @public
1131
+ */
1132
+ declare interface IKeyStoreCreateParams {
1133
+ /**
1134
+ * Crypto provider to use.
1135
+ */
1136
+ readonly cryptoProvider: ICryptoProvider;
1137
+ /**
1138
+ * PBKDF2 iterations (defaults to DEFAULT_KEYSTORE_ITERATIONS).
1139
+ */
1140
+ readonly iterations?: number;
1141
+ }
1142
+
1143
+ /**
1144
+ * The encrypted key store file format.
1145
+ * @public
1146
+ */
1147
+ declare interface IKeyStoreFile {
1148
+ /**
1149
+ * Format identifier.
1150
+ */
1151
+ readonly format: KeyStoreFormat;
1152
+ /**
1153
+ * Algorithm used for encryption.
1154
+ */
1155
+ readonly algorithm: EncryptionAlgorithm;
1156
+ /**
1157
+ * Base64-encoded initialization vector.
1158
+ */
1159
+ readonly iv: string;
1160
+ /**
1161
+ * Base64-encoded authentication tag.
1162
+ */
1163
+ readonly authTag: string;
1164
+ /**
1165
+ * Base64-encoded encrypted vault contents.
1166
+ */
1167
+ readonly encryptedData: string;
1168
+ /**
1169
+ * Key derivation parameters (required for key store - always password-derived).
1170
+ */
1171
+ readonly keyDerivation: IKeyDerivationParams;
1172
+ }
1173
+
1174
+ /**
1175
+ * Parameters for opening an existing key store.
1176
+ * @public
1177
+ */
1178
+ declare interface IKeyStoreOpenParams {
1179
+ /**
1180
+ * Crypto provider to use.
1181
+ */
1182
+ readonly cryptoProvider: ICryptoProvider;
1183
+ /**
1184
+ * The encrypted key store file content.
1185
+ */
1186
+ readonly keystoreFile: IKeyStoreFile;
1187
+ }
1188
+
1189
+ /**
1190
+ * A secret entry stored in the vault (in-memory representation).
1191
+ * @public
1192
+ */
1193
+ declare interface IKeyStoreSecretEntry {
1194
+ /**
1195
+ * Unique name for this secret (used as lookup key).
1196
+ */
1197
+ readonly name: string;
1198
+ /**
1199
+ * Secret type discriminator.
1200
+ * Defaults to `'encryption-key'` for backwards compatibility.
1201
+ */
1202
+ readonly type: KeyStoreSecretType;
1203
+ /**
1204
+ * The secret data.
1205
+ * - For `'encryption-key'`: 32-byte AES-256 key.
1206
+ * - For `'api-key'`: UTF-8 encoded API key string (arbitrary length).
1207
+ */
1208
+ readonly key: Uint8Array;
1209
+ /**
1210
+ * Optional description for this secret.
1211
+ */
1212
+ readonly description?: string;
1213
+ /**
1214
+ * When this secret was added (ISO 8601).
1215
+ */
1216
+ readonly createdAt: string;
1217
+ }
1218
+
1219
+ /**
1220
+ * JSON-serializable version of secret entry (for storage).
1221
+ * @public
1222
+ */
1223
+ declare interface IKeyStoreSecretEntryJson {
1224
+ /**
1225
+ * Unique name for this secret.
1226
+ */
1227
+ readonly name: string;
1228
+ /**
1229
+ * Secret type discriminator.
1230
+ * Optional for backwards compatibility — missing means `'encryption-key'`.
1231
+ */
1232
+ readonly type?: KeyStoreSecretType;
1233
+ /**
1234
+ * Base64-encoded secret data.
1235
+ */
1236
+ readonly key: string;
1237
+ /**
1238
+ * Optional description.
1239
+ */
1240
+ readonly description?: string;
1241
+ /**
1242
+ * When this secret was added (ISO 8601).
1243
+ */
1244
+ readonly createdAt: string;
1245
+ }
1246
+
1247
+ /**
1248
+ * The decrypted vault contents - a versioned map of secrets.
1249
+ * @public
1250
+ */
1251
+ declare interface IKeyStoreVaultContents {
1252
+ /**
1253
+ * Format version for vault contents.
1254
+ */
1255
+ readonly version: KeyStoreFormat;
1256
+ /**
1257
+ * Map of secret name to secret entry.
1258
+ */
1259
+ readonly secrets: Record<string, IKeyStoreSecretEntryJson>;
1260
+ }
1261
+
1262
+ /**
1263
+ * Details about a missing variable in context validation.
1264
+ * @public
1265
+ */
1266
+ declare interface IMissingVariableDetail {
1267
+ /**
1268
+ * The variable reference that is missing
1269
+ */
1270
+ readonly variable: IVariableRef;
1271
+ /**
1272
+ * The path segment where the lookup failed
1273
+ * (e.g., for 'user.profile.name' if 'profile' is missing, this would be 'profile')
1274
+ */
1275
+ readonly failedAtSegment?: string;
1276
+ /**
1277
+ * The parent path that exists (e.g., ['user'] if 'user' exists but 'user.profile' does not)
1278
+ */
1279
+ readonly existingPath: readonly string[];
1280
+ }
1281
+
1282
+ /**
1283
+ * A model specification: either a simple model string or a record mapping
1284
+ * context keys to nested model specs.
1285
+ *
1286
+ * @remarks
1287
+ * A bare string is equivalent to `{ base: string }`. This keeps the simple
1288
+ * case simple while allowing context-aware model selection (e.g. different
1289
+ * models for tool-augmented vs. base completions).
1290
+ *
1291
+ * @example
1292
+ * ```typescript
1293
+ * // Simple — same model for all contexts:
1294
+ * const simple: ModelSpec = 'grok-4-1-fast';
1295
+ *
1296
+ * // Context-aware — reasoning model when tools are active:
1297
+ * const split: ModelSpec = { base: 'grok-4-1-fast', tools: 'grok-4-1-fast-reasoning' };
1298
+ *
1299
+ * // Future nested — per-tool model selection:
1300
+ * const nested: ModelSpec = { base: 'grok-fast', tools: { base: 'grok-r', image: 'grok-v' } };
1301
+ * ```
1302
+ * @public
1303
+ */
1304
+ declare interface IModelSpecMap {
1305
+ readonly [key: string]: ModelSpec;
1306
+ }
1307
+
1308
+ /**
1309
+ * Options for template parsing and validation.
1310
+ * @public
1311
+ */
1312
+ declare interface IMustacheTemplateOptions {
1313
+ /**
1314
+ * Custom opening and closing tags (default: `['{{', '}}']`)
1315
+ */
1316
+ readonly tags?: readonly [string, string];
1317
+ /**
1318
+ * Whether to include comment tokens in variable extraction (default: false)
1319
+ */
1320
+ readonly includeComments?: boolean;
1321
+ /**
1322
+ * Whether to include partial references in variable extraction (default: false)
1323
+ */
1324
+ readonly includePartials?: boolean;
1325
+ }
1326
+
1327
+ /**
1328
+ * Named secret for encryption/decryption.
1329
+ * @public
1330
+ */
1331
+ declare interface INamedSecret {
1332
+ /**
1333
+ * Unique name for this secret (referenced in encrypted files).
1334
+ */
1335
+ readonly name: string;
1336
+ /**
1337
+ * The actual secret key (32 bytes for AES-256).
1338
+ */
1339
+ readonly key: Uint8Array;
1340
+ }
1341
+
1342
+ /**
1343
+ * Parameters for a provider completion request.
1344
+ * @public
1345
+ */
1346
+ declare interface IProviderCompletionParams {
1347
+ /** The provider descriptor */
1348
+ readonly descriptor: IAiProviderDescriptor;
1349
+ /** API key for authentication */
1350
+ readonly apiKey: string;
1351
+ /** The structured prompt to send */
1352
+ readonly prompt: AiPrompt;
1353
+ /**
1354
+ * Additional messages to append after system+user (e.g. for correction retries).
1355
+ * These are appended in order after the initial system and user messages.
1356
+ */
1357
+ readonly additionalMessages?: ReadonlyArray<IChatMessage>;
1358
+ /** Sampling temperature (default: 0.7) */
1359
+ readonly temperature?: number;
1360
+ /** Optional model override — string or context-aware map (uses descriptor.defaultModel otherwise) */
1361
+ readonly modelOverride?: ModelSpec;
1362
+ /** Optional logger for request/response observability. */
1363
+ readonly logger?: Logging.ILogger;
1364
+ /** Server-side tools to include in the request. Overrides settings-level tool config when provided. */
1365
+ readonly tools?: ReadonlyArray<AiServerToolConfig>;
1366
+ }
1367
+
1368
+ /**
1369
+ * Required version of options with all fields populated.
1370
+ * @internal
1371
+ */
1372
+ declare interface IRequiredMustacheTemplateOptions {
1373
+ readonly tags: [string, string];
1374
+ readonly includeComments: boolean;
1375
+ readonly includePartials: boolean;
1376
+ }
1377
+
1378
+ /**
1379
+ * Checks if a JSON object appears to be an encrypted file.
1380
+ * Uses the format field as a discriminator.
1381
+ * @param json - JSON object to check
1382
+ * @returns true if the object has the encrypted file format field
1383
+ * @public
1384
+ */
1385
+ declare function isEncryptedFile(json: unknown): boolean;
1386
+
1387
+ /**
1388
+ * Checks if a JSON object appears to be a key store file.
1389
+ * Uses the format field as a discriminator.
1390
+ * @param json - JSON object to check
1391
+ * @returns true if the object has the key store format field
1392
+ * @public
1393
+ */
1394
+ declare function isKeyStoreFile(json: unknown): boolean;
1395
+
1396
+ /**
1397
+ * A `Converter` which converts an iso formatted string, a number or a `Date` object to
1398
+ * a `Date` object.
1399
+ * @public
1400
+ */
1401
+ declare const isoDate: Converter<Date, unknown>;
1402
+
1403
+ /**
1404
+ * Represents a variable reference extracted from a Mustache template.
1405
+ * @public
1406
+ */
1407
+ declare interface IVariableRef {
1408
+ /**
1409
+ * The raw variable name as it appears in the template (e.g., 'user.name')
1410
+ */
1411
+ readonly name: string;
1412
+ /**
1413
+ * The path segments parsed from the variable name (e.g., ['user', 'name'])
1414
+ */
1415
+ readonly path: readonly string[];
1416
+ /**
1417
+ * The type of token this variable was extracted from
1418
+ */
1419
+ readonly tokenType: MustacheTokenType;
1420
+ /**
1421
+ * Whether this variable is used in a section context (# or ^)
1422
+ * Section variables may reference arrays/objects for iteration
1423
+ */
1424
+ readonly isSection: boolean;
1425
+ }
1426
+
1427
+ /**
1428
+ * Simple interface for a file to be added to a zip file.
1429
+ * @public
1430
+ */
1431
+ declare interface IZipTextFile {
1432
+ readonly path: string;
1433
+ readonly contents: string;
1434
+ }
1435
+
1436
+ /**
1437
+ * @public
1438
+ */
1439
+ declare type JarFieldPicker<T extends JarRecord = JarRecord> = (record: T) => (keyof T)[];
1440
+
1441
+ /**
1442
+ * Represents a single record in a JAR file
1443
+ * @public
1444
+ */
1445
+ declare type JarRecord = Record<string, string | string[]>;
1446
+
1447
+ /**
1448
+ * Options for a JAR record parser.
1449
+ * @public
1450
+ */
1451
+ declare interface JarRecordParserOptions {
1452
+ readonly arrayFields?: string[] | JarFieldPicker;
1453
+ readonly fixedContinuationSize?: number;
1454
+ }
1455
+
1456
+ /**
1457
+ * Supported key derivation functions.
1458
+ * @public
1459
+ */
1460
+ declare type KeyDerivationFunction = 'pbkdf2';
1461
+
1462
+ /**
1463
+ * Converter for {@link CryptoUtils.KeyDerivationFunction | key derivation function} type.
1464
+ * @public
1465
+ */
1466
+ declare const keyDerivationFunction: Converter<KeyDerivationFunction>;
1467
+
1468
+ /**
1469
+ * Converter for {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.
1470
+ * @public
1471
+ */
1472
+ declare const keyDerivationParams: Converter<IKeyDerivationParams>;
1473
+
1474
+ declare namespace KeyStore {
1475
+ export {
1476
+ Converters_2 as Converters,
1477
+ KeyStore_2 as KeyStore,
1478
+ isKeyStoreFile,
1479
+ KeyStoreFormat,
1480
+ KEYSTORE_FORMAT,
1481
+ DEFAULT_KEYSTORE_ITERATIONS,
1482
+ MIN_SALT_LENGTH,
1483
+ KeyStoreSecretType,
1484
+ allKeyStoreSecretTypes,
1485
+ IKeyStoreSecretEntry,
1486
+ IKeyStoreSecretEntryJson,
1487
+ IKeyStoreVaultContents,
1488
+ IKeyStoreFile,
1489
+ KeyStoreLockState,
1490
+ IKeyStoreCreateParams,
1491
+ IKeyStoreOpenParams,
1492
+ IAddSecretResult,
1493
+ IAddSecretOptions,
1494
+ IImportSecretOptions,
1495
+ IAddSecretFromPasswordOptions,
1496
+ DEFAULT_SECRET_ITERATIONS,
1497
+ IAddSecretFromPasswordResult
1498
+ }
1499
+ }
1500
+
1501
+ /**
1502
+ * Password-protected key store for managing encryption secrets.
1503
+ *
1504
+ * The KeyStore provides a secure vault for storing named encryption keys.
1505
+ * The vault is encrypted at rest using a master password via PBKDF2 key derivation.
1506
+ *
1507
+ * @example
1508
+ * ```typescript
1509
+ * // Create new key store
1510
+ * const keystore = KeyStore.create({ cryptoProvider: nodeCryptoProvider }).orThrow();
1511
+ * await keystore.initialize('master-password');
1512
+ *
1513
+ * // Add secrets
1514
+ * await keystore.addSecret('my-key', { description: 'Production key' });
1515
+ *
1516
+ * // Save to file
1517
+ * const fileContent = await keystore.save();
1518
+ *
1519
+ * // Later: Open existing key store
1520
+ * const keystore2 = KeyStore.open({
1521
+ * cryptoProvider: nodeCryptoProvider,
1522
+ * keystoreFile: fileContent.value
1523
+ * }).orThrow();
1524
+ * await keystore2.unlock('master-password');
1525
+ *
1526
+ * // Use as secret provider for encrypted file loading
1527
+ * const encryptionConfig = keystore2.getEncryptionConfig().orThrow();
1528
+ * ```
1529
+ *
1530
+ * @public
1531
+ */
1532
+ declare class KeyStore_2 implements IEncryptionProvider {
1533
+ private readonly _cryptoProvider;
1534
+ private readonly _iterations;
1535
+ private _keystoreFile;
1536
+ private _salt;
1537
+ private _secrets;
1538
+ private _state;
1539
+ private _dirty;
1540
+ private _isNew;
1541
+ private constructor();
1542
+ /**
1543
+ * Creates a new, empty key store.
1544
+ * Call `initialize(password)` to set the master password.
1545
+ * @param params - Creation parameters
1546
+ * @returns Success with new KeyStore instance, or Failure if parameters invalid
1547
+ * @public
1548
+ */
1549
+ static create(params: IKeyStoreCreateParams): Result<KeyStore_2>;
1550
+ /**
1551
+ * Opens an existing encrypted key store.
1552
+ * Call `unlock(password)` to decrypt and access secrets.
1553
+ * @param params - Open parameters including the encrypted file
1554
+ * @returns Success with KeyStore instance, or Failure if file format invalid
1555
+ * @public
1556
+ */
1557
+ static open(params: IKeyStoreOpenParams): Result<KeyStore_2>;
1558
+ /**
1559
+ * Initializes a new key store with the master password.
1560
+ * Generates a random salt for key derivation.
1561
+ * Only valid for newly created (not opened) key stores.
1562
+ * @param password - The master password
1563
+ * @returns Success with this instance when initialized, Failure if already initialized or opened
1564
+ * @public
1565
+ */
1566
+ initialize(password: string): Promise<Result<KeyStore_2>>;
1567
+ /**
1568
+ * Unlocks an existing key store with the master password.
1569
+ * Decrypts the vault and loads secrets into memory.
1570
+ * @param password - The master password
1571
+ * @returns Success with this instance when unlocked, Failure if password incorrect
1572
+ * @public
1573
+ */
1574
+ unlock(password: string): Promise<Result<KeyStore_2>>;
1575
+ /**
1576
+ * Locks the key store, clearing all secrets from memory.
1577
+ * @param force - If true, discards unsaved changes
1578
+ * @returns Success when locked, Failure if unsaved changes and !force
1579
+ * @public
1580
+ */
1581
+ lock(force?: boolean): Result<KeyStore_2>;
1582
+ /**
1583
+ * Checks if the key store is unlocked.
1584
+ * @public
1585
+ */
1586
+ get isUnlocked(): boolean;
1587
+ /**
1588
+ * Checks if there are unsaved changes.
1589
+ * @public
1590
+ */
1591
+ get isDirty(): boolean;
1592
+ /**
1593
+ * Whether this is a newly created key store (not opened from a file).
1594
+ * A new key store must be initialized with a password before use.
1595
+ * An opened key store must be unlocked with the existing password.
1596
+ * @public
1597
+ */
1598
+ get isNew(): boolean;
1599
+ /**
1600
+ * Gets the current lock state.
1601
+ * @public
1602
+ */
1603
+ get state(): KeyStoreLockState;
1604
+ /**
1605
+ * Gets the crypto provider used by this key store.
1606
+ * Available regardless of lock state.
1607
+ * @public
1608
+ */
1609
+ get cryptoProvider(): ICryptoProvider;
1610
+ /**
1611
+ * Lists all secret names in the key store.
1612
+ * @returns Success with array of secret names, Failure if locked
1613
+ * @public
1614
+ */
1615
+ listSecrets(): Result<readonly string[]>;
1616
+ /**
1617
+ * Gets a secret by name.
1618
+ * @param name - Name of the secret
1619
+ * @returns Success with secret entry, Failure if not found or locked
1620
+ * @public
1621
+ */
1622
+ getSecret(name: string): Result<IKeyStoreSecretEntry>;
1623
+ /**
1624
+ * Checks if a secret exists.
1625
+ * @param name - Name of the secret
1626
+ * @returns Success with boolean, Failure if locked
1627
+ * @public
1628
+ */
1629
+ hasSecret(name: string): Result<boolean>;
1630
+ /**
1631
+ * Adds a new secret with a randomly generated key.
1632
+ * @param name - Unique name for the secret
1633
+ * @param options - Optional description
1634
+ * @returns Success with the generated entry, Failure if locked or name invalid
1635
+ * @public
1636
+ */
1637
+ addSecret(name: string, options?: IAddSecretOptions): Promise<Result<IAddSecretResult>>;
1638
+ /**
1639
+ * Imports an existing secret key.
1640
+ * @param name - Unique name for the secret
1641
+ * @param key - The 32-byte AES-256 key
1642
+ * @param options - Optional description, whether to replace existing
1643
+ * @returns Success with entry, Failure if locked, key invalid, or exists and !replace
1644
+ * @public
1645
+ */
1646
+ importSecret(name: string, key: Uint8Array, options?: IImportSecretOptions): Result<IAddSecretResult>;
1647
+ /**
1648
+ * Adds a secret derived from a password using PBKDF2.
1649
+ *
1650
+ * Generates a random salt, derives a 32-byte AES-256 key from the password,
1651
+ * and stores it in the vault. Returns the key derivation parameters so they
1652
+ * can be stored alongside encrypted files, enabling decryption with just the
1653
+ * password (without unlocking the keystore).
1654
+ *
1655
+ * @param name - Unique name for the secret
1656
+ * @param password - Password to derive the key from
1657
+ * @param options - Optional description, iterations, replace flag
1658
+ * @returns Success with entry and keyDerivation params, Failure if locked or invalid
1659
+ * @public
74
1660
  */
75
- constructor(itemDescription: string, ...items: T[]);
1661
+ addSecretFromPassword(name: string, password: string, options?: IAddSecretFromPasswordOptions): Promise<Result<IAddSecretFromPasswordResult>>;
76
1662
  /**
77
- * Type guard to determine if some arbitrary array is an
78
- * {@link Experimental.ExtendedArray}
79
- * @param a - The `Array` to be tested.
80
- * @returns Returns `true` if `a` is an {@link Experimental.ExtendedArray | ExtendedArray},
81
- * `false` otherwise.
1663
+ * Removes a secret by name.
1664
+ * @param name - Name of the secret to remove
1665
+ * @returns Success with removed entry, Failure if not found or locked
1666
+ * @public
82
1667
  */
83
- static isExtendedArray<T>(a?: T[]): a is ExtendedArray<T>;
1668
+ removeSecret(name: string): Result<IKeyStoreSecretEntry>;
84
1669
  /**
85
- * Determines if this array contains exactly one element which matches
86
- * a supplied predicate.
87
- * @param predicate - The predicate function to be applied.
88
- * @returns Returns `Success<T>` with the single matching
89
- * result if exactly one item matches `predicate`. Returns `Failure<T>`
90
- * with an error message if there are no matches or more than one match.
1670
+ * Imports an API key string into the vault.
1671
+ * The string is UTF-8 encoded and stored with type `'api-key'`.
1672
+ * @param name - Unique name for the secret
1673
+ * @param apiKey - The API key string
1674
+ * @param options - Optional description, whether to replace existing
1675
+ * @returns Success with entry, Failure if locked, empty, or exists and !replace
1676
+ * @public
91
1677
  */
92
- single(predicate?: (item: T) => boolean): Result<T>;
1678
+ importApiKey(name: string, apiKey: string, options?: IImportSecretOptions): Result<IAddSecretResult>;
93
1679
  /**
94
- * Returns the first element of an {@link Experimental.ExtendedArray | ExtendedArray}. Fails with an
95
- * error message if the array is empty.
96
- * @param failMessage - Optional message to be displayed in the event of failure.
97
- * @returns Returns `Success<T>` with the value of the first element
98
- * in the array, or `Failure<T>` with an error message if the array is empty.
1680
+ * Retrieves an API key string by name.
1681
+ * Only works for secrets with type `'api-key'`.
1682
+ * @param name - Name of the secret
1683
+ * @returns Success with the API key string, Failure if not found, locked, or wrong type
1684
+ * @public
99
1685
  */
100
- first(failMessage?: string): Result<T>;
1686
+ getApiKey(name: string): Result<string>;
101
1687
  /**
102
- * Returns an array containing all elements of an {@link Experimental.ExtendedArray | ExtendedArray}.
103
- * Fails with an error message if the array is empty.
104
- * @param failMessage - Optional message to be displayed in the event of failure.
105
- * @returns Returns `Success<T>` with a new (non-extended) `Array`
106
- * containing the elements of this array, or `Failure<T>` with an error message
107
- * if the array is empty.
1688
+ * Lists secret names filtered by type.
1689
+ * @param type - The secret type to filter by
1690
+ * @returns Success with array of matching secret names, Failure if locked
1691
+ * @public
108
1692
  */
109
- atLeastOne(failMessage?: string): Result<T[]>;
1693
+ listSecretsByType(type: KeyStoreSecretType): Result<readonly string[]>;
110
1694
  /**
111
- * Gets a new (non-extended) `Array` containing all of the elements from this
112
- * {@link Experimental.ExtendedArray | ExtendedArray}.
113
- * @returns A new (non-extended) `Array<T>`.
1695
+ * Renames a secret.
1696
+ * @param oldName - Current name
1697
+ * @param newName - New name
1698
+ * @returns Success with updated entry, Failure if source not found, target exists, or locked
1699
+ * @public
114
1700
  */
115
- all(): T[];
1701
+ renameSecret(oldName: string, newName: string): Result<IKeyStoreSecretEntry>;
1702
+ /**
1703
+ * Saves the key store, returning the encrypted file content.
1704
+ * Requires the master password to encrypt.
1705
+ * @param password - The master password
1706
+ * @returns Success with IKeyStoreFile, Failure if locked
1707
+ * @public
1708
+ */
1709
+ save(password: string): Promise<Result<IKeyStoreFile>>;
1710
+ /**
1711
+ * Changes the master password.
1712
+ * Re-encrypts the vault with the new password-derived key.
1713
+ * @param currentPassword - Current master password (for verification)
1714
+ * @param newPassword - New master password
1715
+ * @returns Success when password changed, Failure if locked or current password incorrect
1716
+ * @public
1717
+ */
1718
+ changePassword(currentPassword: string, newPassword: string): Promise<Result<KeyStore_2>>;
1719
+ /** {@inheritDoc IEncryptionProvider.encryptByName} */
1720
+ encryptByName<TMetadata = JsonValue>(secretName: string, content: JsonValue, metadata?: TMetadata): Promise<Result<IEncryptedFile<TMetadata>>>;
1721
+ /**
1722
+ * Creates a SecretProvider function for use with IEncryptionConfig.
1723
+ * The returned function looks up secrets from this key store.
1724
+ * @returns Success with SecretProvider, Failure if locked
1725
+ * @public
1726
+ */
1727
+ getSecretProvider(): Result<SecretProvider>;
1728
+ /**
1729
+ * Creates a partial IEncryptionConfig using this key store as the secret source.
1730
+ * @returns Partial config that can be spread into a full IEncryptionConfig
1731
+ * @public
1732
+ */
1733
+ getEncryptionConfig(): Result<Pick<IEncryptionConfig, 'secretProvider' | 'cryptoProvider'>>;
116
1734
  }
117
1735
 
118
1736
  /**
119
- * A helper function to create a `Converter` which converts `unknown` to {@link Experimental.ExtendedArray | ExtendedArray<T>}.
120
- * @remarks
121
- * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
122
- * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
123
- * @param converter - `Converter` used to convert each item in the array
124
- * @param ignoreErrors - Specifies treatment of unconvertible elements
125
- * @beta
1737
+ * Current format version constant.
1738
+ * @public
126
1739
  */
127
- declare function extendedArrayOf<T, TC = undefined>(label: string, converter: Converter<T, TC>, onError?: Conversion.OnError): Converter<ExtendedArray<T>, TC>;
1740
+ declare const KEYSTORE_FORMAT: KeyStoreFormat;
128
1741
 
129
1742
  /**
130
- * Formats a list of items using the supplied template and formatter, one result
131
- * per output line.
132
- * @param format - A mustache template used to format each item.
133
- * @param items - The items to be formatted.
134
- * @param itemFormatter - The {@link Experimental.Formatter | Formatter<T>} used to format each item.
135
- * @returns The resulting string.
136
- * @beta
1743
+ * Converter for {@link CryptoUtils.KeyStore.IKeyStoreFile | encrypted key store file}.
1744
+ * @public
137
1745
  */
138
- declare function formatList<T>(format: string, items: T[], itemFormatter: Formatter<T>): Result<string>;
1746
+ declare const keystoreFile: Converter<IKeyStoreFile>;
139
1747
 
140
1748
  /**
141
- * Interface for an object that can be formatted.
142
- * @beta
1749
+ * Format version for key store files.
1750
+ * @public
143
1751
  */
144
- declare interface Formattable {
145
- /**
146
- * Formats an object using the supplied mustache template.
147
- * @param format - A mustache template used to format the object.
148
- * @returns `Success<string>` with the resulting string, or `Failure<string>`
149
- * with an error message if an error occurs.
150
- */
151
- format(format: string): Result<string>;
152
- }
1752
+ declare type KeyStoreFormat = 'keystore-v1';
153
1753
 
154
1754
  /**
155
- * Base class which adds common formatting.
156
- * @beta
1755
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreFormat | key store format} version.
1756
+ * @public
157
1757
  */
158
- declare class FormattableBase {
159
- /**
160
- * Helper enables derived classes to add named details to a formatted presentation.
161
- * @param details - An array of detail description strings.
162
- * @param label - Label to use for the new detail.
163
- * @param value - Value to use for the new detail.
164
- * @internal
165
- */
166
- protected static _tryAddDetail(details: string[], label: string, value: string | undefined): void;
167
- /**
168
- * {@inheritdoc Experimental.Formattable.format}
169
- */
170
- format(template: string): Result<string>;
1758
+ declare const keystoreFormat: Converter<KeyStoreFormat>;
1759
+
1760
+ /**
1761
+ * Key store lock state.
1762
+ * @public
1763
+ */
1764
+ declare type KeyStoreLockState = 'locked' | 'unlocked';
1765
+
1766
+ /**
1767
+ * Converter for {@link CryptoUtils.KeyStore.IKeyStoreSecretEntryJson | key store secret entry} in JSON format.
1768
+ * The `type` field is optional for backwards compatibility — missing means `'encryption-key'`.
1769
+ * @public
1770
+ */
1771
+ declare const keystoreSecretEntryJson: Converter<IKeyStoreSecretEntryJson>;
1772
+
1773
+ /**
1774
+ * Discriminator for secret types stored in the vault.
1775
+ * - `'encryption-key'`: A 32-byte AES-256 encryption key.
1776
+ * - `'api-key'`: An arbitrary-length API key string (UTF-8 encoded).
1777
+ * @public
1778
+ */
1779
+ declare type KeyStoreSecretType = 'encryption-key' | 'api-key';
1780
+
1781
+ /**
1782
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreSecretType | key store secret type} discriminator.
1783
+ * @public
1784
+ */
1785
+ declare const keystoreSecretType: Converter<KeyStoreSecretType>;
1786
+
1787
+ /**
1788
+ * Converter for {@link CryptoUtils.KeyStore.IKeyStoreVaultContents | key store vault contents} (decrypted state).
1789
+ * @public
1790
+ */
1791
+ declare const keystoreVaultContents: Converter<IKeyStoreVaultContents>;
1792
+
1793
+ /**
1794
+ * A hashing normalizer which computes object
1795
+ * hash using the MD5 algorithm.
1796
+ * @public
1797
+ */
1798
+ declare class Md5Normalizer extends Hash_2.HashingNormalizer {
1799
+ constructor();
1800
+ static md5Hash(parts: string[]): string;
171
1801
  }
172
1802
 
173
1803
  /**
174
- * Destination format for some formatted string.
175
- * @beta
1804
+ * Minimum salt length for key derivation.
1805
+ * @public
176
1806
  */
177
- declare type FormatTargets = 'text' | 'markdown' | 'embed';
1807
+ declare const MIN_SALT_LENGTH: number;
178
1808
 
179
1809
  /**
180
- * Type definition for a formatting function, which takes a `string` and an
181
- * item and returns `Result<string>`.
182
- * @beta
1810
+ * Default context key used as fallback when resolving a {@link ModelSpec}.
1811
+ * @public
183
1812
  */
184
- declare type Formatter<T> = (format: string, item: T) => Result<string>;
1813
+ declare const MODEL_SPEC_BASE_KEY: ModelSpecKey;
185
1814
 
186
1815
  /**
187
- * A collection of {@link Experimental.Formatter | formatters} indexed by target name, to enable
188
- * different format methods per output target.
189
- * @beta
1816
+ * @public
190
1817
  */
191
- declare type FormattersByExtendedTarget<TFT extends FormatTargets, T> = Record<TFT, Formatter<T>>;
1818
+ declare type ModelSpec = string | IModelSpecMap;
192
1819
 
193
1820
  /**
194
- * A collection of {@link Experimental.Formatter | formatters} indexed by the
195
- * {@link Experimental.FormatTargets | default supported target formats}.
196
- * @beta
1821
+ * Recursive converter for {@link ModelSpec}.
1822
+ * Accepts a string or an object whose values are themselves ModelSpec values,
1823
+ * with keys constrained to known {@link ModelSpecKey} values.
1824
+ * Uses the `self` parameter from `Converters.generic` for recursion.
1825
+ * @public
197
1826
  */
198
- declare type FormattersByTarget<T> = FormattersByExtendedTarget<FormatTargets, T>;
1827
+ declare const modelSpec: Converter<ModelSpec>;
199
1828
 
200
- declare namespace Hash {
1829
+ /**
1830
+ * Known context keys for model specification maps.
1831
+ * @public
1832
+ */
1833
+ declare type ModelSpecKey = 'base' | 'tools' | 'image';
1834
+
1835
+ /**
1836
+ * Converter for {@link ModelSpecKey}.
1837
+ * @public
1838
+ */
1839
+ declare const modelSpecKey: Converter<ModelSpecKey>;
1840
+
1841
+ declare namespace Mustache {
201
1842
  export {
202
- Md5Normalizer
1843
+ IContextValidationResult,
1844
+ IMissingVariableDetail,
1845
+ IMustacheTemplateOptions,
1846
+ IVariableRef,
1847
+ MustacheTokenType,
1848
+ MustacheTemplate
203
1849
  }
204
1850
  }
205
- export { Hash }
1851
+ export { Mustache }
206
1852
 
207
1853
  /**
208
- * A `Converter` which converts an iso formatted string, a number or a `Date` object to
209
- * a `Date` object.
1854
+ * A helper class for working with Mustache templates that provides
1855
+ * validation, variable extraction, and context validation utilities.
210
1856
  * @public
211
1857
  */
212
- declare const isoDate: Converter<Date, unknown>;
1858
+ declare class MustacheTemplate {
1859
+ /**
1860
+ * The original template string
1861
+ */
1862
+ readonly template: string;
1863
+ /**
1864
+ * The options used for parsing this template
1865
+ */
1866
+ readonly options: Readonly<IRequiredMustacheTemplateOptions>;
1867
+ private readonly _tokens;
1868
+ private _variables?;
1869
+ private constructor();
1870
+ /**
1871
+ * Creates a new MustacheTemplate instance.
1872
+ * @param template - The Mustache template string to parse
1873
+ * @param options - Optional parsing options
1874
+ * @returns Success with the template instance, or Failure if parsing fails
1875
+ */
1876
+ static create(template: string, options?: IMustacheTemplateOptions): Result<MustacheTemplate>;
1877
+ /**
1878
+ * Validates that a template string has valid Mustache syntax.
1879
+ * @param template - The template string to validate
1880
+ * @param options - Optional parsing options
1881
+ * @returns Success with true if valid, or Failure with a descriptive error message
1882
+ */
1883
+ static validate(template: string, options?: IMustacheTemplateOptions): Result<true>;
1884
+ /**
1885
+ * Checks if this template instance has valid syntax.
1886
+ * Always returns Success(true) since parsing succeeded in create().
1887
+ * @returns Success with true
1888
+ */
1889
+ validate(): Result<true>;
1890
+ /**
1891
+ * Extracts all variable references from the template.
1892
+ * @returns An array of variable references found in the template
1893
+ */
1894
+ extractVariables(): readonly IVariableRef[];
1895
+ /**
1896
+ * Extracts unique variable names from the template.
1897
+ * @returns An array of unique variable name strings (e.g., ['user.name', 'items'])
1898
+ */
1899
+ extractVariableNames(): readonly string[];
1900
+ /**
1901
+ * Validates that a context object has all required variables.
1902
+ * @param context - The context object to validate
1903
+ * @returns Success with validation result containing details about present/missing variables
1904
+ */
1905
+ validateContext(context: unknown): Result<IContextValidationResult>;
1906
+ /**
1907
+ * Renders the template with the given context.
1908
+ * Use this for pre-validated contexts where you've already checked
1909
+ * that all required variables are present.
1910
+ * @param context - The context object for template rendering
1911
+ * @returns Success with the rendered string, or Failure if rendering fails
1912
+ */
1913
+ render(context: unknown): Result<string>;
1914
+ /**
1915
+ * Validates the context and renders the template if validation passes.
1916
+ * @param context - The context object to validate and render with
1917
+ * @returns Success with the rendered string, or Failure with validation or render errors
1918
+ */
1919
+ validateAndRender(context: unknown): Result<string>;
1920
+ private static _resolveOptions;
1921
+ private static _parseTokens;
1922
+ private _extractVariablesFromTokens;
1923
+ private _parsePath;
1924
+ private _lookupPath;
1925
+ }
213
1926
 
214
1927
  /**
1928
+ * Type of a Mustache token as returned by Mustache.parse()
215
1929
  * @public
216
1930
  */
217
- declare type JarFieldPicker<T extends JarRecord = JarRecord> = (record: T) => (keyof T)[];
1931
+ declare type MustacheTokenType = 'text' | 'name' | '&' | '#' | '^' | '!' | '>' | '=';
218
1932
 
219
1933
  /**
220
- * Represents a single record in a JAR file
1934
+ * Converter for {@link CryptoUtils.INamedSecret | named secret} from JSON representation.
1935
+ * Expects key as base64 string in JSON, converts to Uint8Array.
221
1936
  * @public
222
1937
  */
223
- declare type JarRecord = Record<string, string | string[]>;
1938
+ declare const namedSecret: Converter<INamedSecret>;
224
1939
 
225
1940
  /**
226
- * Options for a JAR record parser.
1941
+ * Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.
1942
+ * Uses AES-256-GCM for authenticated encryption.
227
1943
  * @public
228
1944
  */
229
- declare interface JarRecordParserOptions {
230
- readonly arrayFields?: string[] | JarFieldPicker;
231
- readonly fixedContinuationSize?: number;
1945
+ declare class NodeCryptoProvider implements ICryptoProvider {
1946
+ /**
1947
+ * Encrypts plaintext using AES-256-GCM.
1948
+ * @param plaintext - UTF-8 string to encrypt
1949
+ * @param key - 32-byte encryption key
1950
+ * @returns `Success` with encryption result, or `Failure` with an error.
1951
+ */
1952
+ encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>>;
1953
+ /**
1954
+ * Decrypts ciphertext using AES-256-GCM.
1955
+ * @param encryptedData - Encrypted bytes
1956
+ * @param key - 32-byte decryption key
1957
+ * @param iv - Initialization vector (12 bytes)
1958
+ * @param authTag - GCM authentication tag (16 bytes)
1959
+ * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.
1960
+ */
1961
+ decrypt(encryptedData: Uint8Array, key: Uint8Array, iv: Uint8Array, authTag: Uint8Array): Promise<Result<string>>;
1962
+ /**
1963
+ * Generates a random 32-byte key suitable for AES-256.
1964
+ * @returns `Success` with generated key, or `Failure` with an error.
1965
+ */
1966
+ generateKey(): Promise<Result<Uint8Array>>;
1967
+ /**
1968
+ * Derives a key from a password using PBKDF2.
1969
+ * @param password - Password string
1970
+ * @param salt - Salt bytes (should be at least 16 bytes)
1971
+ * @param iterations - Number of iterations (recommend 100000+)
1972
+ * @returns `Success` with derived 32-byte key, or `Failure` with an error.
1973
+ */
1974
+ deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<Result<Uint8Array>>;
1975
+ /**
1976
+ * Generates cryptographically secure random bytes.
1977
+ * @param length - Number of bytes to generate
1978
+ * @returns Success with random bytes, or Failure with error
1979
+ */
1980
+ generateRandomBytes(length: number): Result<Uint8Array>;
1981
+ /**
1982
+ * Encodes binary data to base64 string.
1983
+ * @param data - Binary data to encode
1984
+ * @returns Base64-encoded string
1985
+ */
1986
+ toBase64(data: Uint8Array): string;
1987
+ /**
1988
+ * Decodes base64 string to binary data.
1989
+ * @param base64 - Base64-encoded string
1990
+ * @returns Success with decoded bytes, or Failure if invalid base64
1991
+ */
1992
+ fromBase64(base64: string): Result<Uint8Array>;
232
1993
  }
233
1994
 
234
1995
  /**
235
- * A hashing normalizer which computes object
236
- * hash using the MD5 algorithm.
1996
+ * Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.
237
1997
  * @public
238
1998
  */
239
- declare class Md5Normalizer extends Hash_2.HashingNormalizer {
240
- constructor();
241
- static md5Hash(parts: string[]): string;
242
- }
1999
+ declare const nodeCryptoProvider: NodeCryptoProvider;
243
2000
 
244
2001
  /**
245
2002
  * Parses CSV data from a string.
@@ -446,6 +2203,45 @@ declare namespace RecordJar {
446
2203
  }
447
2204
  export { RecordJar }
448
2205
 
2206
+ /**
2207
+ * Resolves the effective tools for a completion call.
2208
+ *
2209
+ * - If per-call tools are provided, they override settings-level tools entirely.
2210
+ * - Otherwise, settings-level enabled tools are used.
2211
+ * - Only tools supported by the provider are included.
2212
+ * - Returns an empty array if no tools are enabled (= no tools sent).
2213
+ *
2214
+ * @param descriptor - The provider descriptor (used to filter by supported tools)
2215
+ * @param settingsTools - Tool enablement from provider settings (optional)
2216
+ * @param perCallTools - Per-call tool override (optional)
2217
+ * @returns The resolved list of tool configs to include in the request
2218
+ * @public
2219
+ */
2220
+ declare function resolveEffectiveTools(descriptor: IAiProviderDescriptor, settingsTools?: ReadonlyArray<IAiToolEnablement>, perCallTools?: ReadonlyArray<AiServerToolConfig>): ReadonlyArray<AiServerToolConfig>;
2221
+
2222
+ /**
2223
+ * Resolves a {@link ModelSpec} to a concrete model string given an optional context key.
2224
+ *
2225
+ * @remarks
2226
+ * Resolution rules:
2227
+ * 1. If the spec is a string, return it directly (context is irrelevant).
2228
+ * 2. If the spec is an object and the context key exists, recurse into that branch.
2229
+ * 3. Otherwise, fall back to the {@link MODEL_SPEC_BASE_KEY | 'base'} key.
2230
+ * 4. If neither context nor `'base'` exists, use the first available value.
2231
+ *
2232
+ * @param spec - The model specification to resolve
2233
+ * @param context - Optional context key (e.g. `'tools'`)
2234
+ * @returns The resolved model string
2235
+ * @public
2236
+ */
2237
+ declare function resolveModel(spec: ModelSpec, context?: string): string;
2238
+
2239
+ /**
2240
+ * Function type for dynamic secret retrieval.
2241
+ * @public
2242
+ */
2243
+ declare type SecretProvider = (secretName: string) => Promise<Result<Uint8Array>>;
2244
+
449
2245
  /**
450
2246
  * Helper function to create a `StringConverter` which converts
451
2247
  * `unknown` to `string`, applying template conversions supplied at construction time or at
@@ -458,6 +2254,55 @@ export { RecordJar }
458
2254
  */
459
2255
  declare function templateString(defaultContext?: unknown): Conversion.StringConverter<string, unknown>;
460
2256
 
2257
+ /**
2258
+ * Encodes a `Uint8Array` to a base64 string.
2259
+ * @param bytes - Bytes to encode
2260
+ * @returns Base64 string
2261
+ * @public
2262
+ */
2263
+ declare function toBase64(bytes: Uint8Array): string;
2264
+
2265
+ /**
2266
+ * Attempts to parse and decrypt a JSON object as an {@link CryptoUtils.IEncryptedFile | encrypted file}.
2267
+ * @typeParam TPayload - Expected type of decrypted content
2268
+ * @typeParam TMetadata - Type of optional unencrypted metadata
2269
+ * @param json - JSON object that may be an encrypted file
2270
+ * @param key - The decryption key (32 bytes for AES-256)
2271
+ * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption
2272
+ * @param payloadConverter - Optional converter to validate and convert decrypted content
2273
+ * @param metadataConverter - Optional converter to validate metadata before decryption
2274
+ * @returns `Success` with decrypted content, or `Failure` with an error (including if not encrypted)
2275
+ * @public
2276
+ */
2277
+ declare function tryDecryptFile<TPayload extends JsonValue = JsonValue, TMetadata = JsonValue>(json: JsonValue, key: Uint8Array, cryptoProvider: ICryptoProvider, payloadConverter?: Converter<TPayload>, metadataConverter?: Converter<TMetadata>): Promise<Result<TPayload>>;
2278
+
2279
+ /**
2280
+ * Converter which converts a base64 string to a Uint8Array.
2281
+ * @public
2282
+ */
2283
+ declare const uint8ArrayFromBase64: Converter<Uint8Array>;
2284
+
2285
+ declare namespace Yaml {
2286
+ export {
2287
+ yamlConverter
2288
+ }
2289
+ }
2290
+ export { Yaml }
2291
+
2292
+ /**
2293
+ * Creates a converter that parses YAML string content and then applies the supplied converter.
2294
+ * @param converter - Converter to apply to the parsed YAML
2295
+ * @returns Converter that parses YAML then validates
2296
+ * @public
2297
+ */
2298
+ declare function yamlConverter<T>(converter: Converter<T>): Converter<T>;
2299
+
2300
+ /**
2301
+ * Supported compression levels for zip files.
2302
+ * @public
2303
+ */
2304
+ declare type ZipCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
2305
+
461
2306
  /**
462
2307
  * Implementation of `IFileTreeDirectoryItem` for directories in a ZIP archive.
463
2308
  * @public
@@ -543,6 +2388,22 @@ declare class ZipFileItem<TCT extends string = string> implements FileTree.IFile
543
2388
  * @param accessors - The ZIP file tree accessors.
544
2389
  */
545
2390
  constructor(zipFilePath: string, contents: string, accessors: ZipFileTreeAccessors<TCT>);
2391
+ /**
2392
+ * Returns a boolean indicating whether this file can be saved.
2393
+ */
2394
+ getIsMutable(): DetailedResult<boolean, FileTree.SaveDetail>;
2395
+ /**
2396
+ * Sets the contents of the file as parsed JSON.
2397
+ * @param json - The JSON to set as the contents of the file.
2398
+ * @returns A Result indicating success or failure.
2399
+ */
2400
+ setContents(json: JsonValue): Result<JsonValue>;
2401
+ /**
2402
+ * Sets the contents of the file as a string.
2403
+ * @param contents - The string to set as the contents of the file.
2404
+ * @returns A Result indicating success or failure.
2405
+ */
2406
+ setRawContents(contents: string): Result<string>;
546
2407
  /**
547
2408
  * Sets the content type of the file.
548
2409
  * @param contentType - The content type of the file.
@@ -563,7 +2424,11 @@ declare namespace ZipFileTree {
563
2424
  export {
564
2425
  ZipFileTreeAccessors,
565
2426
  ZipFileItem,
566
- ZipDirectoryItem
2427
+ ZipDirectoryItem,
2428
+ createZipFromTextFiles,
2429
+ IZipTextFile,
2430
+ ZipCompressionLevel,
2431
+ ICreateZipOptions
567
2432
  }
568
2433
  }
569
2434
  export { ZipFileTree }
@@ -572,7 +2437,7 @@ export { ZipFileTree }
572
2437
  * File tree accessors for ZIP archives.
573
2438
  * @public
574
2439
  */
575
- declare class ZipFileTreeAccessors<TCT extends string = string> implements FileTree.IFileTreeAccessors<TCT> {
2440
+ declare class ZipFileTreeAccessors<TCT extends string = string> implements FileTree.IMutableFileTreeAccessors<TCT> {
576
2441
  /**
577
2442
  * The unzipped file data.
578
2443
  */
@@ -644,6 +2509,19 @@ declare class ZipFileTreeAccessors<TCT extends string = string> implements FileT
644
2509
  * Builds the cache of all items in the ZIP archive.
645
2510
  */
646
2511
  private _buildItemCache;
2512
+ /**
2513
+ * Returns a boolean indicating whether this file can be saved.
2514
+ * @param path - The path of the file.
2515
+ * @returns A `DetailedResult` indicating success or failure.
2516
+ */
2517
+ fileIsMutable(__path: string): DetailedResult<boolean, FileTree.SaveDetail>;
2518
+ /**
2519
+ * Saves the contents of a file.
2520
+ * @param path - The path of the file.
2521
+ * @param contents - The contents of the file.
2522
+ * @returns A `Result` indicating success or failure.
2523
+ */
2524
+ saveFileContents(__path: string, __contents: string): Result<string>;
647
2525
  /**
648
2526
  * Resolves paths to an absolute path.
649
2527
  */