@fgv/ts-extras 5.1.0-21 → 5.1.0-22
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/packlets/ai-assist/index.js +2 -0
- package/dist/packlets/ai-assist/index.js.map +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js +95 -0
- package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -0
- package/dist/packlets/ai-assist/jsonResponse.js +149 -0
- package/dist/packlets/ai-assist/jsonResponse.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/keyStore.js +81 -0
- package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -1
- package/dist/packlets/crypto-utils/model.js.map +1 -1
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js +9 -1
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
- package/dist/ts-extras.d.ts +235 -1
- package/lib/packlets/ai-assist/index.d.ts +2 -0
- package/lib/packlets/ai-assist/index.d.ts.map +1 -1
- package/lib/packlets/ai-assist/index.js +7 -1
- package/lib/packlets/ai-assist/index.js.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts +93 -0
- package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -0
- package/lib/packlets/ai-assist/jsonCompletion.js +99 -0
- package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -0
- package/lib/packlets/ai-assist/jsonResponse.d.ts +91 -0
- package/lib/packlets/ai-assist/jsonResponse.d.ts.map +1 -0
- package/lib/packlets/ai-assist/jsonResponse.js +154 -0
- package/lib/packlets/ai-assist/jsonResponse.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +43 -1
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/keystore/keyStore.js +81 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -1
- package/lib/packlets/crypto-utils/model.d.ts +10 -1
- package/lib/packlets/crypto-utils/model.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/model.js.map +1 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +7 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js +8 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodeCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAU,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC3G,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AASlE;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAC7B;;;;;OAKG;IACI,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAe;QACrD,OAAO,aAAa,CAAC,GAAG,EAAE;YACxB,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,gBAAgB,EAAE,CAAC;gBAC9C,MAAM,IAAI,KAAK,CAAC,eAAe,SAAS,CAAC,gBAAgB,eAAe,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACxF,CAAC;YAED,qBAAq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,KAAK,MAAM,EAAE,CAAC;QAClC,OAAO,IAAI,CAAC,GAAG,KAAK,uCAAuC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,CAAC;IACrF,CAAC;IACD,MAAM,UAAU,GAAI,GAAG,CAAC,SAA4B,CAAC,UAAU,CAAC;IAChE,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC,GAAG,KAAK,mCAAmC,UAAU,IAAI,CAAC,CAAC;IACzE,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAuB,IAAI,kBAAkB,EAAE,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport * as crypto from 'crypto';\nimport { captureAsyncResult, captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { keyPairAlgorithmParams } from './keyPairAlgorithmParams';\nimport {\n ICryptoProvider,\n IEncryptionResult,\n IWrapBytesOptions,\n IWrappedBytes,\n KeyPairAlgorithm\n} from './model';\n\n/**\n * Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.\n * Uses AES-256-GCM for authenticated encryption.\n * @public\n */\nexport class NodeCryptoProvider implements ICryptoProvider {\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>> {\n return captureResult(() => {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n throw new Error(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n // Generate random IV\n const iv = crypto.randomBytes(Constants.GCM_IV_SIZE);\n\n // Create cipher\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n // Encrypt\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n\n // Get auth tag\n const authTag = cipher.getAuthTag();\n\n return {\n iv: new Uint8Array(iv),\n authTag: new Uint8Array(authTag),\n encryptedData: new Uint8Array(encrypted)\n };\n });\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== Constants.GCM_IV_SIZE) {\n return fail(`IV must be ${Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== Constants.GCM_AUTH_TAG_SIZE) {\n return fail(`Auth tag must be ${Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);\n }\n\n return captureResult(() => {\n // Create decipher\n const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(iv));\n\n // Set auth tag\n decipher.setAuthTag(Buffer.from(authTag));\n\n // Decrypt\n const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedData)), decipher.final()]);\n\n return decrypted.toString('utf8');\n }).withErrorFormat((e) => `Decryption failed: ${e}`);\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns `Success` with generated key, or `Failure` with an error.\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n return captureResult(() => {\n const key = crypto.randomBytes(Constants.AES_256_KEY_SIZE);\n return new Uint8Array(key);\n });\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns `Success` with derived 32-byte key, or `Failure` with an error.\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return fail('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return fail('Salt should be at least 8 bytes');\n }\n\n return new Promise((resolve) => {\n crypto.pbkdf2(\n password,\n Buffer.from(salt),\n iterations,\n Constants.AES_256_KEY_SIZE,\n 'sha256',\n (err, derivedKey) => {\n /* c8 ignore next 3 - PBKDF2 internal errors are hard to trigger with valid parameters */\n if (err) {\n resolve(fail(`Key derivation failed: ${err.message}`));\n } else {\n resolve(succeed(new Uint8Array(derivedKey)));\n }\n }\n );\n });\n }\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns `Success` with hex-encoded hash string, or `Failure` with an error.\n */\n public async sha256(data: string): Promise<Result<string>> {\n return captureResult(() => {\n const hash = crypto.createHash('sha256');\n hash.update(data, 'utf8');\n return hash.digest('hex');\n });\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n return captureResult(() => new Uint8Array(crypto.randomBytes(length)));\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n return Buffer.from(data).toString('base64');\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n // Check for obviously invalid characters\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) {\n return Failure.with('Invalid base64 string');\n }\n return Success.with(new Uint8Array(Buffer.from(base64, 'base64')));\n }\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair using Node's WebCrypto.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.\n * @param extractable - Whether the resulting keys may be exported.\n * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.\n */\n public async generateKeyPair(\n algorithm: KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = keyPairAlgorithmParams[algorithm];\n // Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's\n // broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and\n // returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`\n // is a runtime check via the `in` operator, not a type assertion.\n const result = await captureAsyncResult(async () => {\n const generated = await crypto.webcrypto.subtle.generateKey(\n params.generateKey as AlgorithmIdentifier,\n extractable,\n [...params.keyPairUsages]\n );\n if ('privateKey' in generated && 'publicKey' in generated) {\n return generated;\n }\n /* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */\n throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);\n });\n return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);\n }\n\n /**\n * Exports a public `CryptoKey` as a JSON Web Key.\n * @remarks\n * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`\n * does not enforce public-vs-private; without this guard a caller that\n * passed an extractable private key would receive its private fields\n * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.\n * @param publicKey - Extractable public key to export.\n * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.\n */\n public async exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>> {\n if (publicKey.type !== 'public') {\n return fail(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => crypto.webcrypto.subtle.exportKey('jwk', publicKey));\n return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);\n }\n\n /**\n * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.\n * @param jwk - The JSON Web Key produced by a prior export.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.\n */\n public async importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>> {\n const params = keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n crypto.webcrypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages)\n );\n return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);\n }\n\n /**\n * Wraps `plaintext` for the holder of `recipientPublicKey` using\n * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.\n * @param plaintext - The bytes to wrap.\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with an error.\n */\n public async wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return fail(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = crypto.webcrypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveKey'\n ])) as CryptoKeyPair;\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: recipientPublicKey },\n ephemeral.privateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = crypto.randomBytes(Constants.GCM_IV_SIZE);\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, plaintext);\n const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);\n return {\n ephemeralPublicKey,\n nonce: this.toBase64(nonce),\n ciphertext: this.toBase64(new Uint8Array(ctBuf))\n };\n });\n return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);\n }\n\n /**\n * Unwraps a payload produced by `wrapBytes` using the recipient's private\n * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.\n * @param wrapped - The wrapped payload.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.\n * @param options - HKDF salt and info matching the wrap call.\n * @returns `Success` with the original `plaintext`, or `Failure` with an error.\n */\n public async unwrapBytes(\n wrapped: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return fail(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return fail(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== Constants.GCM_IV_SIZE) {\n return fail(\n `unwrapBytes failed: nonce must be ${Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return fail(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < Constants.GCM_AUTH_TAG_SIZE) {\n return fail(\n `unwrapBytes failed: ciphertext must be at least ${Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = crypto.webcrypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeralPub = await subtle.importKey(\n 'jwk',\n wrapped.ephemeralPublicKey,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: ephemeralPub },\n recipientPrivateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n const ptBuf = await subtle.decrypt(\n { name: 'AES-GCM', iv: nonceResult.value },\n wrapKey,\n ciphertextResult.value\n );\n return new Uint8Array(ptBuf);\n });\n return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);\n }\n}\n\n/**\n * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`\n * (public or private). Used by the wrap/unwrap methods to surface a clean\n * `Failure` instead of letting the WebCrypto deriveKey call throw a less\n * informative error later in the pipeline. Key usages are intentionally not\n * checked here: WebCrypto already produces a specific error if `deriveKey` is\n * not in `usages`, and `deriveBits` is an equally valid alternative usage that\n * an explicit check would have to track.\n * @param key - The CryptoKey to validate.\n * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).\n * @param label - Human-readable role label included in the failure message.\n * @returns `Success` with the key (unchanged) when the algorithm, curve, and\n * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.\n */\nfunction checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {\n if (key.algorithm.name !== 'ECDH') {\n return fail(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);\n }\n const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;\n if (namedCurve !== 'P-256') {\n return fail(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return fail(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/**\n * Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.\n * @public\n */\nexport const nodeCryptoProvider: NodeCryptoProvider = new NodeCryptoProvider();\n"]}
|
|
1
|
+
{"version":3,"file":"nodeCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;A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,GAAG,CAAC,CAAC;AACtB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAuB,IAAI,kBAAkB,EAAE,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport * as crypto from 'crypto';\nimport {\n captureAsyncResult,\n captureResult,\n fail,\n Failure,\n generateUuid,\n Result,\n succeed,\n Success,\n Uuid\n} from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { keyPairAlgorithmParams } from './keyPairAlgorithmParams';\nimport {\n ICryptoProvider,\n IEncryptionResult,\n IWrapBytesOptions,\n IWrappedBytes,\n KeyPairAlgorithm\n} from './model';\n\n/**\n * Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.\n * Uses AES-256-GCM for authenticated encryption.\n * @public\n */\nexport class NodeCryptoProvider implements ICryptoProvider {\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>> {\n return captureResult(() => {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n throw new Error(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n // Generate random IV\n const iv = crypto.randomBytes(Constants.GCM_IV_SIZE);\n\n // Create cipher\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n // Encrypt\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n\n // Get auth tag\n const authTag = cipher.getAuthTag();\n\n return {\n iv: new Uint8Array(iv),\n authTag: new Uint8Array(authTag),\n encryptedData: new Uint8Array(encrypted)\n };\n });\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== Constants.GCM_IV_SIZE) {\n return fail(`IV must be ${Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== Constants.GCM_AUTH_TAG_SIZE) {\n return fail(`Auth tag must be ${Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);\n }\n\n return captureResult(() => {\n // Create decipher\n const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(iv));\n\n // Set auth tag\n decipher.setAuthTag(Buffer.from(authTag));\n\n // Decrypt\n const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedData)), decipher.final()]);\n\n return decrypted.toString('utf8');\n }).withErrorFormat((e) => `Decryption failed: ${e}`);\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns `Success` with generated key, or `Failure` with an error.\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n return captureResult(() => {\n const key = crypto.randomBytes(Constants.AES_256_KEY_SIZE);\n return new Uint8Array(key);\n });\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns `Success` with derived 32-byte key, or `Failure` with an error.\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return fail('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return fail('Salt should be at least 8 bytes');\n }\n\n return new Promise((resolve) => {\n crypto.pbkdf2(\n password,\n Buffer.from(salt),\n iterations,\n Constants.AES_256_KEY_SIZE,\n 'sha256',\n (err, derivedKey) => {\n /* c8 ignore next 3 - PBKDF2 internal errors are hard to trigger with valid parameters */\n if (err) {\n resolve(fail(`Key derivation failed: ${err.message}`));\n } else {\n resolve(succeed(new Uint8Array(derivedKey)));\n }\n }\n );\n });\n }\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns `Success` with hex-encoded hash string, or `Failure` with an error.\n */\n public async sha256(data: string): Promise<Result<string>> {\n return captureResult(() => {\n const hash = crypto.createHash('sha256');\n hash.update(data, 'utf8');\n return hash.digest('hex');\n });\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n return captureResult(() => new Uint8Array(crypto.randomBytes(length)));\n }\n\n /**\n * Generates a cryptographically random UUIDv4 via the platform Web Crypto API.\n * @returns `Success` with the generated UUID, or `Failure` if the runtime\n * does not expose `globalThis.crypto.randomUUID`.\n */\n public generateUuid(): Result<Uuid> {\n return captureResult(() => generateUuid());\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n return Buffer.from(data).toString('base64');\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n // Check for obviously invalid characters\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) {\n return Failure.with('Invalid base64 string');\n }\n return Success.with(new Uint8Array(Buffer.from(base64, 'base64')));\n }\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair using Node's WebCrypto.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.\n * @param extractable - Whether the resulting keys may be exported.\n * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.\n */\n public async generateKeyPair(\n algorithm: KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = keyPairAlgorithmParams[algorithm];\n // Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's\n // broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and\n // returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`\n // is a runtime check via the `in` operator, not a type assertion.\n const result = await captureAsyncResult(async () => {\n const generated = await crypto.webcrypto.subtle.generateKey(\n params.generateKey as AlgorithmIdentifier,\n extractable,\n [...params.keyPairUsages]\n );\n if ('privateKey' in generated && 'publicKey' in generated) {\n return generated;\n }\n /* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */\n throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);\n });\n return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);\n }\n\n /**\n * Exports a public `CryptoKey` as a JSON Web Key.\n * @remarks\n * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`\n * does not enforce public-vs-private; without this guard a caller that\n * passed an extractable private key would receive its private fields\n * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.\n * @param publicKey - Extractable public key to export.\n * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.\n */\n public async exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>> {\n if (publicKey.type !== 'public') {\n return fail(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => crypto.webcrypto.subtle.exportKey('jwk', publicKey));\n return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);\n }\n\n /**\n * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.\n * @param jwk - The JSON Web Key produced by a prior export.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.\n */\n public async importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>> {\n const params = keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n crypto.webcrypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages)\n );\n return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);\n }\n\n /**\n * Wraps `plaintext` for the holder of `recipientPublicKey` using\n * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.\n * @param plaintext - The bytes to wrap.\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with an error.\n */\n public async wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return fail(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = crypto.webcrypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveKey'\n ])) as CryptoKeyPair;\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: recipientPublicKey },\n ephemeral.privateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = crypto.randomBytes(Constants.GCM_IV_SIZE);\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, plaintext);\n const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);\n return {\n ephemeralPublicKey,\n nonce: this.toBase64(nonce),\n ciphertext: this.toBase64(new Uint8Array(ctBuf))\n };\n });\n return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);\n }\n\n /**\n * Unwraps a payload produced by `wrapBytes` using the recipient's private\n * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.\n * @param wrapped - The wrapped payload.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.\n * @param options - HKDF salt and info matching the wrap call.\n * @returns `Success` with the original `plaintext`, or `Failure` with an error.\n */\n public async unwrapBytes(\n wrapped: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return fail(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return fail(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== Constants.GCM_IV_SIZE) {\n return fail(\n `unwrapBytes failed: nonce must be ${Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return fail(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < Constants.GCM_AUTH_TAG_SIZE) {\n return fail(\n `unwrapBytes failed: ciphertext must be at least ${Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = crypto.webcrypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeralPub = await subtle.importKey(\n 'jwk',\n wrapped.ephemeralPublicKey,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: ephemeralPub },\n recipientPrivateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n const ptBuf = await subtle.decrypt(\n { name: 'AES-GCM', iv: nonceResult.value },\n wrapKey,\n ciphertextResult.value\n );\n return new Uint8Array(ptBuf);\n });\n return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);\n }\n}\n\n/**\n * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`\n * (public or private). Used by the wrap/unwrap methods to surface a clean\n * `Failure` instead of letting the WebCrypto deriveKey call throw a less\n * informative error later in the pipeline. Key usages are intentionally not\n * checked here: WebCrypto already produces a specific error if `deriveKey` is\n * not in `usages`, and `deriveBits` is an equally valid alternative usage that\n * an explicit check would have to track.\n * @param key - The CryptoKey to validate.\n * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).\n * @param label - Human-readable role label included in the failure message.\n * @returns `Success` with the key (unchanged) when the algorithm, curve, and\n * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.\n */\nfunction checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {\n if (key.algorithm.name !== 'ECDH') {\n return fail(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);\n }\n const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;\n if (namedCurve !== 'P-256') {\n return fail(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return fail(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/**\n * Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.\n * @public\n */\nexport const nodeCryptoProvider: NodeCryptoProvider = new NodeCryptoProvider();\n"]}
|
package/dist/ts-extras.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { Hash as Hash_2 } from '@fgv/ts-utils';
|
|
|
6
6
|
import { JsonValue } from '@fgv/ts-json-base';
|
|
7
7
|
import { Logging } from '@fgv/ts-utils';
|
|
8
8
|
import { Result } from '@fgv/ts-utils';
|
|
9
|
+
import { Uuid } from '@fgv/ts-utils';
|
|
9
10
|
import { Validator } from '@fgv/ts-utils';
|
|
10
11
|
|
|
11
12
|
/**
|
|
@@ -87,7 +88,17 @@ declare namespace AiAssist {
|
|
|
87
88
|
aiAssistSettings,
|
|
88
89
|
modelSpecKey,
|
|
89
90
|
modelSpec,
|
|
90
|
-
resolveEffectiveTools
|
|
91
|
+
resolveEffectiveTools,
|
|
92
|
+
extractJsonText,
|
|
93
|
+
fencedStringifiedJson,
|
|
94
|
+
IFencedStringifiedJsonExtractorOptions,
|
|
95
|
+
IFencedStringifiedJsonOptions,
|
|
96
|
+
JsonTextExtractor,
|
|
97
|
+
generateJsonCompletion,
|
|
98
|
+
SMART_JSON_PROMPT_HINT,
|
|
99
|
+
IGenerateJsonCompletionParams,
|
|
100
|
+
IGenerateJsonCompletionResult,
|
|
101
|
+
JsonPromptHint
|
|
91
102
|
}
|
|
92
103
|
}
|
|
93
104
|
export { AiAssist }
|
|
@@ -768,6 +779,54 @@ declare class ExtendedArray<T> extends Array<T> {
|
|
|
768
779
|
*/
|
|
769
780
|
declare function extendedArrayOf<T, TC = undefined>(label: string, converter: Converter<T, TC>, onError?: Conversion.OnError): Converter<ExtendedArray<T>, TC>;
|
|
770
781
|
|
|
782
|
+
/**
|
|
783
|
+
* Default {@link AiAssist.JsonTextExtractor | extractor} for LLM responses. Tolerates:
|
|
784
|
+
*
|
|
785
|
+
* - Leading/trailing whitespace and a leading byte-order mark.
|
|
786
|
+
* - Markdown code fences (with or without a language tag).
|
|
787
|
+
* - Conversational preamble before the first `{` or `[`.
|
|
788
|
+
* - Trailing prose after the matched closing `}` or `]`.
|
|
789
|
+
*
|
|
790
|
+
* Out of scope: repairing malformed JSON, handling smart quotes, etc.
|
|
791
|
+
*
|
|
792
|
+
* @param text - Raw model output.
|
|
793
|
+
* @returns A `Result<string>` containing the JSON-shaped substring, or a
|
|
794
|
+
* `Failure` if no JSON-shaped substring was found.
|
|
795
|
+
* @public
|
|
796
|
+
*/
|
|
797
|
+
declare const extractJsonText: JsonTextExtractor;
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Creates a `Converter` that accepts raw LLM response text, runs it through a
|
|
801
|
+
* tolerant extractor (default: {@link AiAssist.extractJsonText}), parses the
|
|
802
|
+
* extracted substring as JSON, and applies an optional inner converter or
|
|
803
|
+
* validator.
|
|
804
|
+
*
|
|
805
|
+
* @example
|
|
806
|
+
* ```ts
|
|
807
|
+
* const converter = fencedStringifiedJson({ inner: myShapeConverter });
|
|
808
|
+
* const result = converter.convert(llmText); // Result<MyShape>
|
|
809
|
+
* ```
|
|
810
|
+
*
|
|
811
|
+
* @param options - Optional extractor; omit to keep the default. Without an
|
|
812
|
+
* `inner` step, the converter resolves to the parsed `JsonValue`.
|
|
813
|
+
* @returns A `Converter<JsonValue>`.
|
|
814
|
+
* @public
|
|
815
|
+
*/
|
|
816
|
+
declare function fencedStringifiedJson(options?: IFencedStringifiedJsonExtractorOptions): Converter<JsonValue>;
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Creates a `Converter` that accepts raw LLM response text, runs it through a
|
|
820
|
+
* tolerant extractor (default: {@link AiAssist.extractJsonText}), parses the
|
|
821
|
+
* extracted substring as JSON, and applies the supplied inner converter or
|
|
822
|
+
* validator.
|
|
823
|
+
*
|
|
824
|
+
* @param options - Required `inner` converter/validator and optional extractor.
|
|
825
|
+
* @returns A `Converter<T>`.
|
|
826
|
+
* @public
|
|
827
|
+
*/
|
|
828
|
+
declare function fencedStringifiedJson<T>(options: IFencedStringifiedJsonOptions<T>): Converter<T>;
|
|
829
|
+
|
|
771
830
|
/**
|
|
772
831
|
* Formats a list of items using the supplied template and formatter, one result
|
|
773
832
|
* per output line.
|
|
@@ -859,6 +918,27 @@ declare const GCM_AUTH_TAG_SIZE: number;
|
|
|
859
918
|
*/
|
|
860
919
|
declare const GCM_IV_SIZE: number;
|
|
861
920
|
|
|
921
|
+
/**
|
|
922
|
+
* Calls {@link AiAssist.callProviderCompletion}, then runs the response text
|
|
923
|
+
* through a tolerant JSON converter (default:
|
|
924
|
+
* {@link AiAssist.fencedStringifiedJson}) and the caller's
|
|
925
|
+
* `converter`/`validator`. Returns the validated value plus the raw text and
|
|
926
|
+
* underlying completion response for diagnostics.
|
|
927
|
+
*
|
|
928
|
+
* @remarks
|
|
929
|
+
* The default smart prompt hint asks the model to emit raw JSON. The read-side
|
|
930
|
+
* extractor still tolerates fences and prose, so models that ignore the hint
|
|
931
|
+
* are still handled.
|
|
932
|
+
*
|
|
933
|
+
* Either `converter` or `jsonConverter` must be provided; passing both lets
|
|
934
|
+
* `jsonConverter` win.
|
|
935
|
+
*
|
|
936
|
+
* @param params - Provider parameters plus JSON validation options.
|
|
937
|
+
* @returns The validated value, the raw text, and the underlying response.
|
|
938
|
+
* @public
|
|
939
|
+
*/
|
|
940
|
+
declare function generateJsonCompletion<T>(params: IGenerateJsonCompletionParams<T>): Promise<Result<IGenerateJsonCompletionResult<T>>>;
|
|
941
|
+
|
|
862
942
|
/**
|
|
863
943
|
* Get a provider descriptor by id.
|
|
864
944
|
* @param id - The provider identifier
|
|
@@ -1540,6 +1620,15 @@ declare interface ICryptoProvider {
|
|
|
1540
1620
|
* @returns Success with random bytes, or Failure with error
|
|
1541
1621
|
*/
|
|
1542
1622
|
generateRandomBytes(length: number): Result<Uint8Array>;
|
|
1623
|
+
/**
|
|
1624
|
+
* Generates a cryptographically random UUIDv4 using the provider's
|
|
1625
|
+
* underlying source of randomness. The default Node and browser
|
|
1626
|
+
* implementations delegate to `globalThis.crypto.randomUUID`;
|
|
1627
|
+
* deterministic providers (e.g. test stubs) may override to produce
|
|
1628
|
+
* reproducible values.
|
|
1629
|
+
* @returns Success with a canonical UUID, or Failure with error.
|
|
1630
|
+
*/
|
|
1631
|
+
generateUuid(): Result<Uuid>;
|
|
1543
1632
|
/**
|
|
1544
1633
|
* Encodes binary data to base64 string.
|
|
1545
1634
|
* @param data - Binary data to encode
|
|
@@ -1757,6 +1846,70 @@ declare interface IEncryptionResult {
|
|
|
1757
1846
|
readonly encryptedData: Uint8Array;
|
|
1758
1847
|
}
|
|
1759
1848
|
|
|
1849
|
+
/**
|
|
1850
|
+
* Options shared by every {@link AiAssist.fencedStringifiedJson} call.
|
|
1851
|
+
* @public
|
|
1852
|
+
*/
|
|
1853
|
+
declare interface IFencedStringifiedJsonExtractorOptions {
|
|
1854
|
+
/**
|
|
1855
|
+
* Optional pre-parse extractor. Defaults to {@link AiAssist.extractJsonText}.
|
|
1856
|
+
* Provide a custom extractor to handle response shapes the default does not
|
|
1857
|
+
* understand.
|
|
1858
|
+
*/
|
|
1859
|
+
readonly extractor?: JsonTextExtractor;
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
/**
|
|
1863
|
+
* Options for the validating overload of {@link AiAssist.fencedStringifiedJson}.
|
|
1864
|
+
* `inner` is required so the typed `Converter<T>` return value can never lie
|
|
1865
|
+
* about the runtime shape.
|
|
1866
|
+
* @public
|
|
1867
|
+
*/
|
|
1868
|
+
declare interface IFencedStringifiedJsonOptions<T> extends IFencedStringifiedJsonExtractorOptions {
|
|
1869
|
+
/** Inner converter or validator applied to the parsed JSON value. */
|
|
1870
|
+
readonly inner: Converter<T> | Validator<T>;
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
/**
|
|
1874
|
+
* Parameters for {@link AiAssist.generateJsonCompletion}. Extends
|
|
1875
|
+
* {@link AiAssist.IProviderCompletionParams} with JSON-validation knobs.
|
|
1876
|
+
* @public
|
|
1877
|
+
*/
|
|
1878
|
+
declare interface IGenerateJsonCompletionParams<T> extends IProviderCompletionParams {
|
|
1879
|
+
/**
|
|
1880
|
+
* Caller-supplied `Converter<T>` or `Validator<T>` applied to the parsed
|
|
1881
|
+
* JSON value. Wrapped internally in {@link AiAssist.fencedStringifiedJson}
|
|
1882
|
+
* unless {@link AiAssist.IGenerateJsonCompletionParams.jsonConverter} is
|
|
1883
|
+
* provided.
|
|
1884
|
+
*/
|
|
1885
|
+
readonly converter?: Converter<T> | Validator<T>;
|
|
1886
|
+
/**
|
|
1887
|
+
* Full string-to-`T` pipeline override. When supplied, takes precedence over
|
|
1888
|
+
* {@link AiAssist.IGenerateJsonCompletionParams.converter} and lets the
|
|
1889
|
+
* caller plug in a custom extractor or skip the default fence tolerance
|
|
1890
|
+
* entirely.
|
|
1891
|
+
*/
|
|
1892
|
+
readonly jsonConverter?: Converter<T>;
|
|
1893
|
+
/**
|
|
1894
|
+
* Controls the optional system-prompt augmentation. Defaults to `'smart'`.
|
|
1895
|
+
* Pass `'none'` to disable, or a string to append custom guidance.
|
|
1896
|
+
*/
|
|
1897
|
+
readonly promptHint?: JsonPromptHint;
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
/**
|
|
1901
|
+
* Successful result of {@link AiAssist.generateJsonCompletion}.
|
|
1902
|
+
* @public
|
|
1903
|
+
*/
|
|
1904
|
+
declare interface IGenerateJsonCompletionResult<T> {
|
|
1905
|
+
/** The validated JSON value. */
|
|
1906
|
+
readonly value: T;
|
|
1907
|
+
/** The raw response text returned by the provider. */
|
|
1908
|
+
readonly raw: string;
|
|
1909
|
+
/** The full underlying completion response. */
|
|
1910
|
+
readonly response: IAiCompletionResponse;
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1760
1913
|
/**
|
|
1761
1914
|
* Options for importing raw key material via {@link KeyStore.importSecret}.
|
|
1762
1915
|
* Extends {@link IImportSecretOptions} with a type classification.
|
|
@@ -2575,6 +2728,31 @@ declare interface JarRecordParserOptions {
|
|
|
2575
2728
|
readonly fixedContinuationSize?: number;
|
|
2576
2729
|
}
|
|
2577
2730
|
|
|
2731
|
+
/**
|
|
2732
|
+
* Controls the optional system-prompt augmentation applied by
|
|
2733
|
+
* {@link AiAssist.generateJsonCompletion}.
|
|
2734
|
+
*
|
|
2735
|
+
* - `'smart'` (default): append {@link AiAssist.SMART_JSON_PROMPT_HINT}.
|
|
2736
|
+
* - `'none'`: do not modify the prompt.
|
|
2737
|
+
* - A string: append the supplied text verbatim.
|
|
2738
|
+
*
|
|
2739
|
+
* @remarks
|
|
2740
|
+
* The `string & {}` branch is the standard TypeScript trick that prevents
|
|
2741
|
+
* the literal members from being widened away — callers still get
|
|
2742
|
+
* autocomplete for `'smart'` and `'none'` while accepting any string.
|
|
2743
|
+
*
|
|
2744
|
+
* @public
|
|
2745
|
+
*/
|
|
2746
|
+
declare type JsonPromptHint = 'smart' | 'none' | (string & {});
|
|
2747
|
+
|
|
2748
|
+
/**
|
|
2749
|
+
* A function that pulls a JSON-shaped substring out of arbitrary model text.
|
|
2750
|
+
* Implementations strip whatever wrappers the model added (fences, preamble,
|
|
2751
|
+
* trailing prose) and return the JSON-shaped substring ready for `JSON.parse`.
|
|
2752
|
+
* @public
|
|
2753
|
+
*/
|
|
2754
|
+
declare type JsonTextExtractor = (text: string) => Result<string>;
|
|
2755
|
+
|
|
2578
2756
|
/**
|
|
2579
2757
|
* In-place shape check for a JSON Web Key. Asserts only that the input is a
|
|
2580
2758
|
* non-array object whose `kty` discriminator is a string; every other JWK
|
|
@@ -2882,6 +3060,41 @@ declare class KeyStore_2 implements IEncryptionProvider {
|
|
|
2882
3060
|
* @public
|
|
2883
3061
|
*/
|
|
2884
3062
|
addSecretFromPassword(name: string, password: string, options?: IAddSecretFromPasswordOptions): Promise<Result<IAddSecretFromPasswordResult>>;
|
|
3063
|
+
/**
|
|
3064
|
+
* Verifies that a candidate password derives the same key material currently
|
|
3065
|
+
* stored under `name`, using the supplied
|
|
3066
|
+
* {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.
|
|
3067
|
+
*
|
|
3068
|
+
* The keystore does not persist per-slot key derivation parameters with the
|
|
3069
|
+
* entry — callers receive them from `addSecretFromPassword` and store them
|
|
3070
|
+
* alongside the encrypted artifact (or wherever else makes sense). Pass
|
|
3071
|
+
* those same parameters here for verification.
|
|
3072
|
+
*
|
|
3073
|
+
* Re-derives a key from `password` + `keyDerivation`, then compares it to
|
|
3074
|
+
* the stored key material in constant time. Restricted to entries of type
|
|
3075
|
+
* `'encryption-key'` — the type produced by `addSecretFromPassword`. Other
|
|
3076
|
+
* symmetric types (`'api-key'`) and asymmetric entries are rejected so
|
|
3077
|
+
* the boolean result reflects "this slot accepts this password" rather
|
|
3078
|
+
* than an incidental byte-equality match against unrelated material.
|
|
3079
|
+
*
|
|
3080
|
+
* Note: the keystore does not currently flag whether an `'encryption-key'`
|
|
3081
|
+
* entry was actually password-derived (vs. random via `addSecret` or raw
|
|
3082
|
+
* via `importSecret`). A `true` result therefore means "the candidate
|
|
3083
|
+
* password produces the same 32 bytes currently stored", which is what
|
|
3084
|
+
* the equivalent consumer-side helper (`verifyGatePassword`) already
|
|
3085
|
+
* implies for entries it manages.
|
|
3086
|
+
*
|
|
3087
|
+
* @param name - Name of the secret to verify against
|
|
3088
|
+
* @param password - Candidate password to test
|
|
3089
|
+
* @param keyDerivation - The key derivation parameters returned by
|
|
3090
|
+
* `addSecretFromPassword` when the secret was created. Only
|
|
3091
|
+
* `kdf: 'pbkdf2'` is supported.
|
|
3092
|
+
* @returns Success(true) when the candidate matches the stored key,
|
|
3093
|
+
* Success(false) when it does not, Failure if locked, secret missing,
|
|
3094
|
+
* wrong type, unsupported `kdf`, or key derivation fails
|
|
3095
|
+
* @public
|
|
3096
|
+
*/
|
|
3097
|
+
verifySecretFromPassword(name: string, password: string, keyDerivation: IKeyDerivationParams): Promise<Result<boolean>>;
|
|
2885
3098
|
/**
|
|
2886
3099
|
* Removes a secret by name. Vault-first: the in-memory vault entry is dropped
|
|
2887
3100
|
* before any storage cleanup runs. For asymmetric-keypair entries, best-effort
|
|
@@ -3028,6 +3241,13 @@ declare class KeyStore_2 implements IEncryptionProvider {
|
|
|
3028
3241
|
* @returns A warning string if storage cleanup failed, otherwise undefined.
|
|
3029
3242
|
*/
|
|
3030
3243
|
private _releaseEntryResources;
|
|
3244
|
+
/**
|
|
3245
|
+
* Constant-time byte comparison. Returns false immediately for length
|
|
3246
|
+
* mismatch (length is not secret); for equal-length inputs, walks the full
|
|
3247
|
+
* buffer accumulating differences via XOR so the running time does not leak
|
|
3248
|
+
* the position of the first differing byte.
|
|
3249
|
+
*/
|
|
3250
|
+
private static _timingSafeEqual;
|
|
3031
3251
|
/**
|
|
3032
3252
|
* Mints a fresh UUID v4 storage handle using the crypto provider's
|
|
3033
3253
|
* {@link CryptoUtils.ICryptoProvider.generateRandomBytes | generateRandomBytes}.
|
|
@@ -3346,6 +3566,12 @@ declare class NodeCryptoProvider implements ICryptoProvider {
|
|
|
3346
3566
|
* @returns Success with random bytes, or Failure with error
|
|
3347
3567
|
*/
|
|
3348
3568
|
generateRandomBytes(length: number): Result<Uint8Array>;
|
|
3569
|
+
/**
|
|
3570
|
+
* Generates a cryptographically random UUIDv4 via the platform Web Crypto API.
|
|
3571
|
+
* @returns `Success` with the generated UUID, or `Failure` if the runtime
|
|
3572
|
+
* does not expose `globalThis.crypto.randomUUID`.
|
|
3573
|
+
*/
|
|
3574
|
+
generateUuid(): Result<Uuid>;
|
|
3349
3575
|
/**
|
|
3350
3576
|
* Encodes binary data to base64 string.
|
|
3351
3577
|
* @param data - Binary data to encode
|
|
@@ -3670,6 +3896,14 @@ declare function resolveModel(spec: ModelSpec, context?: string): string;
|
|
|
3670
3896
|
*/
|
|
3671
3897
|
declare type SecretProvider = (secretName: string) => Promise<Result<Uint8Array>>;
|
|
3672
3898
|
|
|
3899
|
+
/**
|
|
3900
|
+
* Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}
|
|
3901
|
+
* is `'smart'` (the default). Designed to discourage code fences and prose in
|
|
3902
|
+
* the model's response while still tolerating them via the read-side extractor.
|
|
3903
|
+
* @public
|
|
3904
|
+
*/
|
|
3905
|
+
declare const SMART_JSON_PROMPT_HINT: string;
|
|
3906
|
+
|
|
3673
3907
|
/**
|
|
3674
3908
|
* Whether a provider declares any image-generation capability at all.
|
|
3675
3909
|
*
|
|
@@ -8,4 +8,6 @@ export { callProviderCompletion, callProxiedCompletion, callProviderImageGenerat
|
|
|
8
8
|
export { callProviderCompletionStream, callProxiedCompletionStream, type IProviderCompletionStreamParams } from './streamingClient';
|
|
9
9
|
export { aiProviderId, aiServerToolType, aiWebSearchToolConfig, aiServerToolConfig, aiToolEnablement, aiAssistProviderConfig, aiAssistSettings, modelSpecKey, modelSpec } from './converters';
|
|
10
10
|
export { resolveEffectiveTools } from './toolFormats';
|
|
11
|
+
export { extractJsonText, fencedStringifiedJson, type IFencedStringifiedJsonExtractorOptions, type IFencedStringifiedJsonOptions, type JsonTextExtractor } from './jsonResponse';
|
|
12
|
+
export { generateJsonCompletion, SMART_JSON_PROMPT_HINT, type IGenerateJsonCompletionParams, type IGenerateJsonCompletionResult, type JsonPromptHint } from './jsonCompletion';
|
|
11
13
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,QAAQ,EACR,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,iBAAiB,EACtB,iBAAiB,EACjB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,YAAY,EACjB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,iBAAiB,EACtB,KAAK,0BAA0B,EAC/B,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,YAAY,EACZ,SAAS,EACV,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,+BAA+B,EAChC,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,sBAAsB,EACtB,qBAAqB,EACrB,KAAK,yBAAyB,EAC9B,KAAK,8BAA8B,EACnC,KAAK,yBAAyB,EAC/B,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,EAC3B,KAAK,+BAA+B,EACrC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,EAClB,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,SAAS,EACV,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,QAAQ,EACR,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,iBAAiB,EACtB,iBAAiB,EACjB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,YAAY,EACjB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,iBAAiB,EACtB,KAAK,0BAA0B,EAC/B,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,YAAY,EACZ,SAAS,EACV,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,+BAA+B,EAChC,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,sBAAsB,EACtB,qBAAqB,EACrB,KAAK,yBAAyB,EAC9B,KAAK,8BAA8B,EACnC,KAAK,yBAAyB,EAC/B,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,EAC3B,KAAK,+BAA+B,EACrC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,EAClB,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,SAAS,EACV,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,KAAK,sCAAsC,EAC3C,KAAK,6BAA6B,EAClC,KAAK,iBAAiB,EACvB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,KAAK,6BAA6B,EAClC,KAAK,6BAA6B,EAClC,KAAK,cAAc,EACpB,MAAM,kBAAkB,CAAC"}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
-
exports.resolveEffectiveTools = exports.modelSpec = exports.modelSpecKey = exports.aiAssistSettings = exports.aiAssistProviderConfig = exports.aiToolEnablement = exports.aiServerToolConfig = exports.aiWebSearchToolConfig = exports.aiServerToolType = exports.aiProviderId = exports.callProxiedCompletionStream = exports.callProviderCompletionStream = exports.callProxiedListModels = exports.callProviderListModels = exports.callProxiedImageGeneration = exports.callProviderImageGeneration = exports.callProxiedCompletion = exports.callProviderCompletion = exports.DEFAULT_MODEL_CAPABILITY_CONFIG = exports.supportsImageGeneration = exports.resolveImageCapability = exports.getProviderDescriptor = exports.getProviderDescriptors = exports.allProviderIds = exports.toDataUrl = exports.resolveModel = exports.MODEL_SPEC_BASE_KEY = exports.allModelSpecKeys = exports.DEFAULT_AI_ASSIST = exports.AiPrompt = void 0;
|
|
7
|
+
exports.SMART_JSON_PROMPT_HINT = exports.generateJsonCompletion = exports.fencedStringifiedJson = exports.extractJsonText = exports.resolveEffectiveTools = exports.modelSpec = exports.modelSpecKey = exports.aiAssistSettings = exports.aiAssistProviderConfig = exports.aiToolEnablement = exports.aiServerToolConfig = exports.aiWebSearchToolConfig = exports.aiServerToolType = exports.aiProviderId = exports.callProxiedCompletionStream = exports.callProviderCompletionStream = exports.callProxiedListModels = exports.callProviderListModels = exports.callProxiedImageGeneration = exports.callProviderImageGeneration = exports.callProxiedCompletion = exports.callProviderCompletion = exports.DEFAULT_MODEL_CAPABILITY_CONFIG = exports.supportsImageGeneration = exports.resolveImageCapability = exports.getProviderDescriptor = exports.getProviderDescriptors = exports.allProviderIds = exports.toDataUrl = exports.resolveModel = exports.MODEL_SPEC_BASE_KEY = exports.allModelSpecKeys = exports.DEFAULT_AI_ASSIST = exports.AiPrompt = void 0;
|
|
8
8
|
var model_1 = require("./model");
|
|
9
9
|
Object.defineProperty(exports, "AiPrompt", { enumerable: true, get: function () { return model_1.AiPrompt; } });
|
|
10
10
|
Object.defineProperty(exports, "DEFAULT_AI_ASSIST", { enumerable: true, get: function () { return model_1.DEFAULT_AI_ASSIST; } });
|
|
@@ -41,4 +41,10 @@ Object.defineProperty(exports, "modelSpecKey", { enumerable: true, get: function
|
|
|
41
41
|
Object.defineProperty(exports, "modelSpec", { enumerable: true, get: function () { return converters_1.modelSpec; } });
|
|
42
42
|
var toolFormats_1 = require("./toolFormats");
|
|
43
43
|
Object.defineProperty(exports, "resolveEffectiveTools", { enumerable: true, get: function () { return toolFormats_1.resolveEffectiveTools; } });
|
|
44
|
+
var jsonResponse_1 = require("./jsonResponse");
|
|
45
|
+
Object.defineProperty(exports, "extractJsonText", { enumerable: true, get: function () { return jsonResponse_1.extractJsonText; } });
|
|
46
|
+
Object.defineProperty(exports, "fencedStringifiedJson", { enumerable: true, get: function () { return jsonResponse_1.fencedStringifiedJson; } });
|
|
47
|
+
var jsonCompletion_1 = require("./jsonCompletion");
|
|
48
|
+
Object.defineProperty(exports, "generateJsonCompletion", { enumerable: true, get: function () { return jsonCompletion_1.generateJsonCompletion; } });
|
|
49
|
+
Object.defineProperty(exports, "SMART_JSON_PROMPT_HINT", { enumerable: true, get: function () { return jsonCompletion_1.SMART_JSON_PROMPT_HINT; } });
|
|
44
50
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,iCAuCiB;AAtCf,iGAAA,QAAQ,OAAA;AAeR,0GAAA,iBAAiB,OAAA;AAmBjB,yGAAA,gBAAgB,OAAA;AAChB,4GAAA,mBAAmB,OAAA;AACnB,qGAAA,YAAY,OAAA;AACZ,kGAAA,SAAS,OAAA;AAGX,uCAOoB;AANlB,0GAAA,cAAc,OAAA;AACd,kHAAA,sBAAsB,OAAA;AACtB,iHAAA,qBAAqB,OAAA;AACrB,kHAAA,sBAAsB,OAAA;AACtB,mHAAA,uBAAuB,OAAA;AACvB,2HAAA,+BAA+B,OAAA;AAGjC,yCAUqB;AATnB,mHAAA,sBAAsB,OAAA;AACtB,kHAAA,qBAAqB,OAAA;AACrB,wHAAA,2BAA2B,OAAA;AAC3B,uHAAA,0BAA0B,OAAA;AAC1B,mHAAA,sBAAsB,OAAA;AACtB,kHAAA,qBAAqB,OAAA;AAMvB,qDAI2B;AAHzB,+HAAA,4BAA4B,OAAA;AAC5B,8HAAA,2BAA2B,OAAA;AAI7B,2CAUsB;AATpB,0GAAA,YAAY,OAAA;AACZ,8GAAA,gBAAgB,OAAA;AAChB,mHAAA,qBAAqB,OAAA;AACrB,gHAAA,kBAAkB,OAAA;AAClB,8GAAA,gBAAgB,OAAA;AAChB,oHAAA,sBAAsB,OAAA;AACtB,8GAAA,gBAAgB,OAAA;AAChB,0GAAA,YAAY,OAAA;AACZ,uGAAA,SAAS,OAAA;AAGX,6CAAsD;AAA7C,oHAAA,qBAAqB,OAAA","sourcesContent":["/**\n * AI assist packlet - provider registry, prompt class, settings, and API client.\n * @packageDocumentation\n */\n\nexport {\n AiPrompt,\n type AiModelCapability,\n type AiProviderId,\n type AiServerToolType,\n type AiServerToolConfig,\n type IAiWebSearchToolConfig,\n type IAiToolEnablement,\n type IAiCompletionResponse,\n type IChatMessage,\n type AiApiFormat,\n type AiImageApiFormat,\n type IAiImageModelCapability,\n type IAiProviderDescriptor,\n type IAiAssistProviderConfig,\n type IAiAssistSettings,\n DEFAULT_AI_ASSIST,\n type IAiAssistKeyStore,\n type IAiImageAttachment,\n type IAiImageData,\n type IAiImageGenerationOptions,\n type IAiImageGenerationParams,\n type IAiGeneratedImage,\n type IAiImageGenerationResponse,\n type IAiModelCapabilityRule,\n type IAiModelCapabilityConfig,\n type IAiModelInfo,\n type IAiStreamEvent,\n type IAiStreamTextDelta,\n type IAiStreamToolEvent,\n type IAiStreamDone,\n type IAiStreamError,\n type ModelSpec,\n type ModelSpecKey,\n type IModelSpecMap,\n allModelSpecKeys,\n MODEL_SPEC_BASE_KEY,\n resolveModel,\n toDataUrl\n} from './model';\n\nexport {\n allProviderIds,\n getProviderDescriptors,\n getProviderDescriptor,\n resolveImageCapability,\n supportsImageGeneration,\n DEFAULT_MODEL_CAPABILITY_CONFIG\n} from './registry';\n\nexport {\n callProviderCompletion,\n callProxiedCompletion,\n callProviderImageGeneration,\n callProxiedImageGeneration,\n callProviderListModels,\n callProxiedListModels,\n type IProviderCompletionParams,\n type IProviderImageGenerationParams,\n type IProviderListModelsParams\n} from './apiClient';\n\nexport {\n callProviderCompletionStream,\n callProxiedCompletionStream,\n type IProviderCompletionStreamParams\n} from './streamingClient';\n\nexport {\n aiProviderId,\n aiServerToolType,\n aiWebSearchToolConfig,\n aiServerToolConfig,\n aiToolEnablement,\n aiAssistProviderConfig,\n aiAssistSettings,\n modelSpecKey,\n modelSpec\n} from './converters';\n\nexport { resolveEffectiveTools } from './toolFormats';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,iCAuCiB;AAtCf,iGAAA,QAAQ,OAAA;AAeR,0GAAA,iBAAiB,OAAA;AAmBjB,yGAAA,gBAAgB,OAAA;AAChB,4GAAA,mBAAmB,OAAA;AACnB,qGAAA,YAAY,OAAA;AACZ,kGAAA,SAAS,OAAA;AAGX,uCAOoB;AANlB,0GAAA,cAAc,OAAA;AACd,kHAAA,sBAAsB,OAAA;AACtB,iHAAA,qBAAqB,OAAA;AACrB,kHAAA,sBAAsB,OAAA;AACtB,mHAAA,uBAAuB,OAAA;AACvB,2HAAA,+BAA+B,OAAA;AAGjC,yCAUqB;AATnB,mHAAA,sBAAsB,OAAA;AACtB,kHAAA,qBAAqB,OAAA;AACrB,wHAAA,2BAA2B,OAAA;AAC3B,uHAAA,0BAA0B,OAAA;AAC1B,mHAAA,sBAAsB,OAAA;AACtB,kHAAA,qBAAqB,OAAA;AAMvB,qDAI2B;AAHzB,+HAAA,4BAA4B,OAAA;AAC5B,8HAAA,2BAA2B,OAAA;AAI7B,2CAUsB;AATpB,0GAAA,YAAY,OAAA;AACZ,8GAAA,gBAAgB,OAAA;AAChB,mHAAA,qBAAqB,OAAA;AACrB,gHAAA,kBAAkB,OAAA;AAClB,8GAAA,gBAAgB,OAAA;AAChB,oHAAA,sBAAsB,OAAA;AACtB,8GAAA,gBAAgB,OAAA;AAChB,0GAAA,YAAY,OAAA;AACZ,uGAAA,SAAS,OAAA;AAGX,6CAAsD;AAA7C,oHAAA,qBAAqB,OAAA;AAE9B,+CAMwB;AALtB,+GAAA,eAAe,OAAA;AACf,qHAAA,qBAAqB,OAAA;AAMvB,mDAM0B;AALxB,wHAAA,sBAAsB,OAAA;AACtB,wHAAA,sBAAsB,OAAA","sourcesContent":["/**\n * AI assist packlet - provider registry, prompt class, settings, and API client.\n * @packageDocumentation\n */\n\nexport {\n AiPrompt,\n type AiModelCapability,\n type AiProviderId,\n type AiServerToolType,\n type AiServerToolConfig,\n type IAiWebSearchToolConfig,\n type IAiToolEnablement,\n type IAiCompletionResponse,\n type IChatMessage,\n type AiApiFormat,\n type AiImageApiFormat,\n type IAiImageModelCapability,\n type IAiProviderDescriptor,\n type IAiAssistProviderConfig,\n type IAiAssistSettings,\n DEFAULT_AI_ASSIST,\n type IAiAssistKeyStore,\n type IAiImageAttachment,\n type IAiImageData,\n type IAiImageGenerationOptions,\n type IAiImageGenerationParams,\n type IAiGeneratedImage,\n type IAiImageGenerationResponse,\n type IAiModelCapabilityRule,\n type IAiModelCapabilityConfig,\n type IAiModelInfo,\n type IAiStreamEvent,\n type IAiStreamTextDelta,\n type IAiStreamToolEvent,\n type IAiStreamDone,\n type IAiStreamError,\n type ModelSpec,\n type ModelSpecKey,\n type IModelSpecMap,\n allModelSpecKeys,\n MODEL_SPEC_BASE_KEY,\n resolveModel,\n toDataUrl\n} from './model';\n\nexport {\n allProviderIds,\n getProviderDescriptors,\n getProviderDescriptor,\n resolveImageCapability,\n supportsImageGeneration,\n DEFAULT_MODEL_CAPABILITY_CONFIG\n} from './registry';\n\nexport {\n callProviderCompletion,\n callProxiedCompletion,\n callProviderImageGeneration,\n callProxiedImageGeneration,\n callProviderListModels,\n callProxiedListModels,\n type IProviderCompletionParams,\n type IProviderImageGenerationParams,\n type IProviderListModelsParams\n} from './apiClient';\n\nexport {\n callProviderCompletionStream,\n callProxiedCompletionStream,\n type IProviderCompletionStreamParams\n} from './streamingClient';\n\nexport {\n aiProviderId,\n aiServerToolType,\n aiWebSearchToolConfig,\n aiServerToolConfig,\n aiToolEnablement,\n aiAssistProviderConfig,\n aiAssistSettings,\n modelSpecKey,\n modelSpec\n} from './converters';\n\nexport { resolveEffectiveTools } from './toolFormats';\n\nexport {\n extractJsonText,\n fencedStringifiedJson,\n type IFencedStringifiedJsonExtractorOptions,\n type IFencedStringifiedJsonOptions,\n type JsonTextExtractor\n} from './jsonResponse';\n\nexport {\n generateJsonCompletion,\n SMART_JSON_PROMPT_HINT,\n type IGenerateJsonCompletionParams,\n type IGenerateJsonCompletionResult,\n type JsonPromptHint\n} from './jsonCompletion';\n"]}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `generateJsonCompletion<T>` — request a JSON-shaped completion from any
|
|
3
|
+
* provider supported by AiAssist and validate it against a caller-supplied
|
|
4
|
+
* `Converter<T>` or `Validator<T>`. Wraps fence/preamble tolerance + parsing +
|
|
5
|
+
* validation into a single call so consumers don't reinvent the pipeline.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
import { type Converter, Result, type Validator } from '@fgv/ts-utils';
|
|
10
|
+
import { type IProviderCompletionParams } from './apiClient';
|
|
11
|
+
import { type IAiCompletionResponse } from './model';
|
|
12
|
+
/**
|
|
13
|
+
* Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}
|
|
14
|
+
* is `'smart'` (the default). Designed to discourage code fences and prose in
|
|
15
|
+
* the model's response while still tolerating them via the read-side extractor.
|
|
16
|
+
* @public
|
|
17
|
+
*/
|
|
18
|
+
export declare const SMART_JSON_PROMPT_HINT: string;
|
|
19
|
+
/**
|
|
20
|
+
* Controls the optional system-prompt augmentation applied by
|
|
21
|
+
* {@link AiAssist.generateJsonCompletion}.
|
|
22
|
+
*
|
|
23
|
+
* - `'smart'` (default): append {@link AiAssist.SMART_JSON_PROMPT_HINT}.
|
|
24
|
+
* - `'none'`: do not modify the prompt.
|
|
25
|
+
* - A string: append the supplied text verbatim.
|
|
26
|
+
*
|
|
27
|
+
* @remarks
|
|
28
|
+
* The `string & {}` branch is the standard TypeScript trick that prevents
|
|
29
|
+
* the literal members from being widened away — callers still get
|
|
30
|
+
* autocomplete for `'smart'` and `'none'` while accepting any string.
|
|
31
|
+
*
|
|
32
|
+
* @public
|
|
33
|
+
*/
|
|
34
|
+
export type JsonPromptHint = 'smart' | 'none' | (string & {});
|
|
35
|
+
/**
|
|
36
|
+
* Parameters for {@link AiAssist.generateJsonCompletion}. Extends
|
|
37
|
+
* {@link AiAssist.IProviderCompletionParams} with JSON-validation knobs.
|
|
38
|
+
* @public
|
|
39
|
+
*/
|
|
40
|
+
export interface IGenerateJsonCompletionParams<T> extends IProviderCompletionParams {
|
|
41
|
+
/**
|
|
42
|
+
* Caller-supplied `Converter<T>` or `Validator<T>` applied to the parsed
|
|
43
|
+
* JSON value. Wrapped internally in {@link AiAssist.fencedStringifiedJson}
|
|
44
|
+
* unless {@link AiAssist.IGenerateJsonCompletionParams.jsonConverter} is
|
|
45
|
+
* provided.
|
|
46
|
+
*/
|
|
47
|
+
readonly converter?: Converter<T> | Validator<T>;
|
|
48
|
+
/**
|
|
49
|
+
* Full string-to-`T` pipeline override. When supplied, takes precedence over
|
|
50
|
+
* {@link AiAssist.IGenerateJsonCompletionParams.converter} and lets the
|
|
51
|
+
* caller plug in a custom extractor or skip the default fence tolerance
|
|
52
|
+
* entirely.
|
|
53
|
+
*/
|
|
54
|
+
readonly jsonConverter?: Converter<T>;
|
|
55
|
+
/**
|
|
56
|
+
* Controls the optional system-prompt augmentation. Defaults to `'smart'`.
|
|
57
|
+
* Pass `'none'` to disable, or a string to append custom guidance.
|
|
58
|
+
*/
|
|
59
|
+
readonly promptHint?: JsonPromptHint;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Successful result of {@link AiAssist.generateJsonCompletion}.
|
|
63
|
+
* @public
|
|
64
|
+
*/
|
|
65
|
+
export interface IGenerateJsonCompletionResult<T> {
|
|
66
|
+
/** The validated JSON value. */
|
|
67
|
+
readonly value: T;
|
|
68
|
+
/** The raw response text returned by the provider. */
|
|
69
|
+
readonly raw: string;
|
|
70
|
+
/** The full underlying completion response. */
|
|
71
|
+
readonly response: IAiCompletionResponse;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Calls {@link AiAssist.callProviderCompletion}, then runs the response text
|
|
75
|
+
* through a tolerant JSON converter (default:
|
|
76
|
+
* {@link AiAssist.fencedStringifiedJson}) and the caller's
|
|
77
|
+
* `converter`/`validator`. Returns the validated value plus the raw text and
|
|
78
|
+
* underlying completion response for diagnostics.
|
|
79
|
+
*
|
|
80
|
+
* @remarks
|
|
81
|
+
* The default smart prompt hint asks the model to emit raw JSON. The read-side
|
|
82
|
+
* extractor still tolerates fences and prose, so models that ignore the hint
|
|
83
|
+
* are still handled.
|
|
84
|
+
*
|
|
85
|
+
* Either `converter` or `jsonConverter` must be provided; passing both lets
|
|
86
|
+
* `jsonConverter` win.
|
|
87
|
+
*
|
|
88
|
+
* @param params - Provider parameters plus JSON validation options.
|
|
89
|
+
* @returns The validated value, the raw text, and the underlying response.
|
|
90
|
+
* @public
|
|
91
|
+
*/
|
|
92
|
+
export declare function generateJsonCompletion<T>(params: IGenerateJsonCompletionParams<T>): Promise<Result<IGenerateJsonCompletionResult<T>>>;
|
|
93
|
+
//# sourceMappingURL=jsonCompletion.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonCompletion.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/jsonCompletion.ts"],"names":[],"mappings":"AAoBA;;;;;;;GAOG;AAEH,OAAO,EAAE,KAAK,SAAS,EAAQ,MAAM,EAAW,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAEtF,OAAO,EAA0B,KAAK,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAErF,OAAO,EAAY,KAAK,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAE/D;;;;;GAKG;AACH,eAAO,MAAM,sBAA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