@fgv/ts-extras 5.1.0-20 → 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/apiClient.js +30 -25
- package/dist/packlets/ai-assist/apiClient.js.map +1 -1
- package/dist/packlets/ai-assist/converters.js +2 -1
- package/dist/packlets/ai-assist/converters.js.map +1 -1
- package/dist/packlets/ai-assist/endpoint.js +78 -0
- package/dist/packlets/ai-assist/endpoint.js.map +1 -0
- 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/ai-assist/model.js.map +1 -1
- package/dist/packlets/ai-assist/registry.js +26 -0
- package/dist/packlets/ai-assist/registry.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +2 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +2 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
- package/dist/packlets/ai-assist/streamingClient.js +11 -5
- package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +6 -0
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -1
- 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 +2 -1
- package/dist/packlets/crypto-utils/model.js.map +1 -1
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js +21 -2
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
- package/dist/ts-extras.d.ts +301 -6
- package/lib/packlets/ai-assist/apiClient.d.ts +29 -0
- package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/apiClient.js +30 -25
- package/lib/packlets/ai-assist/apiClient.js.map +1 -1
- package/lib/packlets/ai-assist/converters.d.ts.map +1 -1
- package/lib/packlets/ai-assist/converters.js +2 -1
- package/lib/packlets/ai-assist/converters.js.map +1 -1
- package/lib/packlets/ai-assist/endpoint.d.ts +28 -0
- package/lib/packlets/ai-assist/endpoint.d.ts.map +1 -0
- package/lib/packlets/ai-assist/endpoint.js +82 -0
- package/lib/packlets/ai-assist/endpoint.js.map +1 -0
- 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/ai-assist/model.d.ts +9 -1
- package/lib/packlets/ai-assist/model.d.ts.map +1 -1
- package/lib/packlets/ai-assist/model.js.map +1 -1
- package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
- package/lib/packlets/ai-assist/registry.js +26 -0
- package/lib/packlets/ai-assist/registry.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +8 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.js +11 -5
- package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +14 -3
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +6 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -1
- 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 +16 -2
- package/lib/packlets/crypto-utils/model.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/model.js +2 -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 +20 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoint.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/endpoint.ts"],"names":[],"mappings":"AAoBA;;;;;GAKG;AAEH,OAAO,EAAQ,MAAM,EAAW,MAAM,eAAe,CAAC;AAEtD,OAAO,EAAE,KAAK,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAErD;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAEvE;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CACrC,UAAU,EAAE,qBAAqB,EACjC,QAAQ,CAAC,EAAE,MAAM,GAChB,MAAM,CAAC,MAAM,CAAC,CA+BhB"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Copyright (c) 2026 Erik Fortune
|
|
3
|
+
//
|
|
4
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
// in the Software without restriction, including without limitation the rights
|
|
7
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
// furnished to do so, subject to the following conditions:
|
|
10
|
+
//
|
|
11
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
// copies or substantial portions of the Software.
|
|
13
|
+
//
|
|
14
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
// SOFTWARE.
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.bearerAuthHeader = bearerAuthHeader;
|
|
23
|
+
exports.resolveEffectiveBaseUrl = resolveEffectiveBaseUrl;
|
|
24
|
+
/**
|
|
25
|
+
* Helper for resolving a request's effective base URL from a provider
|
|
26
|
+
* descriptor and an optional caller-supplied endpoint override.
|
|
27
|
+
*
|
|
28
|
+
* @packageDocumentation
|
|
29
|
+
*/
|
|
30
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
31
|
+
/**
|
|
32
|
+
* Builds an OpenAI-style `Authorization: Bearer ${key}` header, or an empty
|
|
33
|
+
* record when the key is empty. Self-hosted/local OpenAI-compatible servers
|
|
34
|
+
* (Ollama, LM Studio, llama.cpp) often reject `Authorization: Bearer ` with
|
|
35
|
+
* an empty key, so we omit the header entirely in that case.
|
|
36
|
+
*
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
function bearerAuthHeader(apiKey) {
|
|
40
|
+
return apiKey.length > 0 ? { Authorization: `Bearer ${apiKey}` } : {};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Resolves the effective base URL for a request, validating the optional
|
|
44
|
+
* `endpoint` override when present. Returns the URL with any trailing slash
|
|
45
|
+
* stripped so per-route suffix concatenation (e.g. `/chat/completions`)
|
|
46
|
+
* produces the same shape regardless of whether the caller supplied an
|
|
47
|
+
* override or the descriptor's default is used.
|
|
48
|
+
*
|
|
49
|
+
* @internal
|
|
50
|
+
*/
|
|
51
|
+
function resolveEffectiveBaseUrl(descriptor, endpoint) {
|
|
52
|
+
if (endpoint === undefined) {
|
|
53
|
+
if (!descriptor.baseUrl) {
|
|
54
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}" has no API endpoint configured`);
|
|
55
|
+
}
|
|
56
|
+
return (0, ts_utils_1.succeed)(descriptor.baseUrl.replace(/\/+$/, ''));
|
|
57
|
+
}
|
|
58
|
+
if (typeof endpoint !== 'string' || endpoint.length === 0) {
|
|
59
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}": endpoint must be a non-empty http(s) URL`);
|
|
60
|
+
}
|
|
61
|
+
let parsed;
|
|
62
|
+
try {
|
|
63
|
+
parsed = new URL(endpoint);
|
|
64
|
+
}
|
|
65
|
+
catch (_a) {
|
|
66
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}": endpoint is not a valid URL`);
|
|
67
|
+
}
|
|
68
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
69
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}": endpoint must use http or https (got ${parsed.protocol})`);
|
|
70
|
+
}
|
|
71
|
+
if (parsed.search.length > 0 || parsed.hash.length > 0) {
|
|
72
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}": endpoint must not include a query string or fragment`);
|
|
73
|
+
}
|
|
74
|
+
if (parsed.username.length > 0 || parsed.password.length > 0) {
|
|
75
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}": endpoint must not include userinfo; pass credentials via apiKey instead`);
|
|
76
|
+
}
|
|
77
|
+
// Reconstruct from origin + pathname so the returned URL is normalized
|
|
78
|
+
// (no userinfo, no query, no fragment) and the suffix concat in callers
|
|
79
|
+
// produces a well-formed request URL.
|
|
80
|
+
return (0, ts_utils_1.succeed)(`${parsed.origin}${parsed.pathname}`.replace(/\/+$/, ''));
|
|
81
|
+
}
|
|
82
|
+
//# sourceMappingURL=endpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoint.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/endpoint.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;;AAqBZ,4CAEC;AAWD,0DAkCC;AAlED;;;;;GAKG;AAEH,4CAAsD;AAItD;;;;;;;GAOG;AACH,SAAgB,gBAAgB,CAAC,MAAc;IAC7C,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,UAAU,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACxE,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,uBAAuB,CACrC,UAAiC,EACjC,QAAiB;IAEjB,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;YACxB,OAAO,IAAA,eAAI,EAAC,aAAa,UAAU,CAAC,EAAE,kCAAkC,CAAC,CAAC;QAC5E,CAAC;QACD,OAAO,IAAA,kBAAO,EAAC,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC;IACzD,CAAC;IACD,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1D,OAAO,IAAA,eAAI,EAAC,aAAa,UAAU,CAAC,EAAE,6CAA6C,CAAC,CAAC;IACvF,CAAC;IACD,IAAI,MAAW,CAAC;IAChB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC7B,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAA,eAAI,EAAC,aAAa,UAAU,CAAC,EAAE,gCAAgC,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,MAAM,CAAC,QAAQ,KAAK,OAAO,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;QAChE,OAAO,IAAA,eAAI,EAAC,aAAa,UAAU,CAAC,EAAE,2CAA2C,MAAM,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvG,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvD,OAAO,IAAA,eAAI,EAAC,aAAa,UAAU,CAAC,EAAE,yDAAyD,CAAC,CAAC;IACnG,CAAC;IACD,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC7D,OAAO,IAAA,eAAI,EACT,aAAa,UAAU,CAAC,EAAE,4EAA4E,CACvG,CAAC;IACJ,CAAC;IACD,uEAAuE;IACvE,wEAAwE;IACxE,sCAAsC;IACtC,OAAO,IAAA,kBAAO,EAAC,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["// Copyright (c) 2026 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\n/**\n * Helper for resolving a request's effective base URL from a provider\n * descriptor and an optional caller-supplied endpoint override.\n *\n * @packageDocumentation\n */\n\nimport { fail, Result, succeed } from '@fgv/ts-utils';\n\nimport { type IAiProviderDescriptor } from './model';\n\n/**\n * Builds an OpenAI-style `Authorization: Bearer ${key}` header, or an empty\n * record when the key is empty. Self-hosted/local OpenAI-compatible servers\n * (Ollama, LM Studio, llama.cpp) often reject `Authorization: Bearer ` with\n * an empty key, so we omit the header entirely in that case.\n *\n * @internal\n */\nexport function bearerAuthHeader(apiKey: string): Record<string, string> {\n return apiKey.length > 0 ? { Authorization: `Bearer ${apiKey}` } : {};\n}\n\n/**\n * Resolves the effective base URL for a request, validating the optional\n * `endpoint` override when present. Returns the URL with any trailing slash\n * stripped so per-route suffix concatenation (e.g. `/chat/completions`)\n * produces the same shape regardless of whether the caller supplied an\n * override or the descriptor's default is used.\n *\n * @internal\n */\nexport function resolveEffectiveBaseUrl(\n descriptor: IAiProviderDescriptor,\n endpoint?: string\n): Result<string> {\n if (endpoint === undefined) {\n if (!descriptor.baseUrl) {\n return fail(`provider \"${descriptor.id}\" has no API endpoint configured`);\n }\n return succeed(descriptor.baseUrl.replace(/\\/+$/, ''));\n }\n if (typeof endpoint !== 'string' || endpoint.length === 0) {\n return fail(`provider \"${descriptor.id}\": endpoint must be a non-empty http(s) URL`);\n }\n let parsed: URL;\n try {\n parsed = new URL(endpoint);\n } catch {\n return fail(`provider \"${descriptor.id}\": endpoint is not a valid URL`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return fail(`provider \"${descriptor.id}\": endpoint must use http or https (got ${parsed.protocol})`);\n }\n if (parsed.search.length > 0 || parsed.hash.length > 0) {\n return fail(`provider \"${descriptor.id}\": endpoint must not include a query string or fragment`);\n }\n if (parsed.username.length > 0 || parsed.password.length > 0) {\n return fail(\n `provider \"${descriptor.id}\": endpoint must not include userinfo; pass credentials via apiKey instead`\n );\n }\n // Reconstruct from origin + pathname so the returned URL is normalized\n // (no userinfo, no query, no fragment) and the suffix concat in callers\n // produces a well-formed request URL.\n return succeed(`${parsed.origin}${parsed.pathname}`.replace(/\\/+$/, ''));\n}\n"]}
|
|
@@ -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,sBAAsB,EAAE,MAE2C,CAAC;AAEjF;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,MAAM,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAE9D;;;;GAIG;AACH,MAAM,WAAW,6BAA6B,CAAC,CAAC,CAAE,SAAQ,yBAAyB;IACjF;;;;;OAKG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;IAEjD;;;;;OAKG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAEtC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC;CACtC;AAED;;;GAGG;AACH,MAAM,WAAW,6BAA6B,CAAC,CAAC;IAC9C,gCAAgC;IAChC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAClB,sDAAsD;IACtD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,+CAA+C;IAC/C,QAAQ,CAAC,QAAQ,EAAE,qBAAqB,CAAC;CAC1C;AAWD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,MAAM,EAAE,6BAA6B,CAAC,CAAC,CAAC,GACvC,OAAO,CAAC,MAAM,CAAC,6BAA6B,CAAC,CAAC,CAAC,CAAC,CAAC,CAoBnD"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Copyright (c) 2026 Erik Fortune
|
|
3
|
+
//
|
|
4
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
// in the Software without restriction, including without limitation the rights
|
|
7
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
// furnished to do so, subject to the following conditions:
|
|
10
|
+
//
|
|
11
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
// copies or substantial portions of the Software.
|
|
13
|
+
//
|
|
14
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
// SOFTWARE.
|
|
21
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
22
|
+
var t = {};
|
|
23
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
24
|
+
t[p] = s[p];
|
|
25
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
26
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
27
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
28
|
+
t[p[i]] = s[p[i]];
|
|
29
|
+
}
|
|
30
|
+
return t;
|
|
31
|
+
};
|
|
32
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
33
|
+
exports.SMART_JSON_PROMPT_HINT = void 0;
|
|
34
|
+
exports.generateJsonCompletion = generateJsonCompletion;
|
|
35
|
+
/**
|
|
36
|
+
* `generateJsonCompletion<T>` — request a JSON-shaped completion from any
|
|
37
|
+
* provider supported by AiAssist and validate it against a caller-supplied
|
|
38
|
+
* `Converter<T>` or `Validator<T>`. Wraps fence/preamble tolerance + parsing +
|
|
39
|
+
* validation into a single call so consumers don't reinvent the pipeline.
|
|
40
|
+
*
|
|
41
|
+
* @packageDocumentation
|
|
42
|
+
*/
|
|
43
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
44
|
+
const apiClient_1 = require("./apiClient");
|
|
45
|
+
const jsonResponse_1 = require("./jsonResponse");
|
|
46
|
+
const model_1 = require("./model");
|
|
47
|
+
/**
|
|
48
|
+
* Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}
|
|
49
|
+
* is `'smart'` (the default). Designed to discourage code fences and prose in
|
|
50
|
+
* the model's response while still tolerating them via the read-side extractor.
|
|
51
|
+
* @public
|
|
52
|
+
*/
|
|
53
|
+
exports.SMART_JSON_PROMPT_HINT = 'Respond with raw JSON only — no Markdown code fences, no explanatory prose, ' +
|
|
54
|
+
'no preamble or trailing commentary. The response must parse with JSON.parse.';
|
|
55
|
+
function applyPromptHint(prompt, hint) {
|
|
56
|
+
if (hint === 'none') {
|
|
57
|
+
return prompt;
|
|
58
|
+
}
|
|
59
|
+
const suffix = hint === 'smart' ? exports.SMART_JSON_PROMPT_HINT : hint;
|
|
60
|
+
const system = prompt.system.length > 0 ? `${prompt.system}\n\n${suffix}` : suffix;
|
|
61
|
+
return new model_1.AiPrompt(prompt.user, system, prompt.attachments);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Calls {@link AiAssist.callProviderCompletion}, then runs the response text
|
|
65
|
+
* through a tolerant JSON converter (default:
|
|
66
|
+
* {@link AiAssist.fencedStringifiedJson}) and the caller's
|
|
67
|
+
* `converter`/`validator`. Returns the validated value plus the raw text and
|
|
68
|
+
* underlying completion response for diagnostics.
|
|
69
|
+
*
|
|
70
|
+
* @remarks
|
|
71
|
+
* The default smart prompt hint asks the model to emit raw JSON. The read-side
|
|
72
|
+
* extractor still tolerates fences and prose, so models that ignore the hint
|
|
73
|
+
* are still handled.
|
|
74
|
+
*
|
|
75
|
+
* Either `converter` or `jsonConverter` must be provided; passing both lets
|
|
76
|
+
* `jsonConverter` win.
|
|
77
|
+
*
|
|
78
|
+
* @param params - Provider parameters plus JSON validation options.
|
|
79
|
+
* @returns The validated value, the raw text, and the underlying response.
|
|
80
|
+
* @public
|
|
81
|
+
*/
|
|
82
|
+
async function generateJsonCompletion(params) {
|
|
83
|
+
const { converter, jsonConverter, promptHint = 'smart', prompt } = params, rest = __rest(params, ["converter", "jsonConverter", "promptHint", "prompt"]);
|
|
84
|
+
if (jsonConverter === undefined && converter === undefined) {
|
|
85
|
+
return (0, ts_utils_1.fail)('generateJsonCompletion: either converter or jsonConverter must be provided.');
|
|
86
|
+
}
|
|
87
|
+
const pipeline = jsonConverter !== null && jsonConverter !== void 0 ? jsonConverter : (0, jsonResponse_1.fencedStringifiedJson)({ inner: converter });
|
|
88
|
+
const augmentedPrompt = applyPromptHint(prompt, promptHint);
|
|
89
|
+
const response = await (0, apiClient_1.callProviderCompletion)(Object.assign(Object.assign({}, rest), { prompt: augmentedPrompt }));
|
|
90
|
+
if (response.isFailure()) {
|
|
91
|
+
return (0, ts_utils_1.fail)(response.message);
|
|
92
|
+
}
|
|
93
|
+
const completion = response.value;
|
|
94
|
+
return pipeline
|
|
95
|
+
.convert(completion.content)
|
|
96
|
+
.withErrorFormat((msg) => `generateJsonCompletion: ${msg}`)
|
|
97
|
+
.onSuccess((value) => (0, ts_utils_1.succeed)({ value, raw: completion.content, response: completion }));
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=jsonCompletion.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonCompletion.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/jsonCompletion.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;;;;;;;;;;;;;;AAkHZ,wDAsBC;AAtID;;;;;;;GAOG;AAEH,4CAAsF;AAEtF,2CAAqF;AACrF,iDAAuD;AACvD,mCAA+D;AAE/D;;;;;GAKG;AACU,QAAA,sBAAsB,GACjC,8EAA8E;IAC9E,8EAA8E,CAAC;AA6DjF,SAAS,eAAe,CAAC,MAAgB,EAAE,IAAoB;IAC7D,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC;QACpB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,8BAAsB,CAAC,CAAC,CAAC,IAAI,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,OAAO,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;IACnF,OAAO,IAAI,gBAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;AAC/D,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACI,KAAK,UAAU,sBAAsB,CAC1C,MAAwC;IAExC,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,GAAG,OAAO,EAAE,MAAM,KAAc,MAAM,EAAf,IAAI,UAAK,MAAM,EAA5E,sDAAmE,CAAS,CAAC;IAEnF,IAAI,aAAa,KAAK,SAAS,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC3D,OAAO,IAAA,eAAI,EAAC,6EAA6E,CAAC,CAAC;IAC7F,CAAC;IAED,MAAM,QAAQ,GAAiB,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,IAAA,oCAAqB,EAAI,EAAE,KAAK,EAAE,SAAU,EAAE,CAAC,CAAC;IAChG,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAE5D,MAAM,QAAQ,GAAG,MAAM,IAAA,kCAAsB,kCAAM,IAAI,KAAE,MAAM,EAAE,eAAe,IAAG,CAAC;IACpF,IAAI,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC;QACzB,OAAO,IAAA,eAAI,EAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IACD,MAAM,UAAU,GAAG,QAAQ,CAAC,KAAK,CAAC;IAElC,OAAO,QAAQ;SACZ,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC;SAC3B,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,2BAA2B,GAAG,EAAE,CAAC;SAC1D,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,EAAE,KAAK,EAAE,GAAG,EAAE,UAAU,CAAC,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC;AAC7F,CAAC","sourcesContent":["// Copyright (c) 2026 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\n/**\n * `generateJsonCompletion<T>` — request a JSON-shaped completion from any\n * provider supported by AiAssist and validate it against a caller-supplied\n * `Converter<T>` or `Validator<T>`. Wraps fence/preamble tolerance + parsing +\n * validation into a single call so consumers don't reinvent the pipeline.\n *\n * @packageDocumentation\n */\n\nimport { type Converter, fail, Result, succeed, type Validator } from '@fgv/ts-utils';\n\nimport { callProviderCompletion, type IProviderCompletionParams } from './apiClient';\nimport { fencedStringifiedJson } from './jsonResponse';\nimport { AiPrompt, type IAiCompletionResponse } from './model';\n\n/**\n * Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}\n * is `'smart'` (the default). Designed to discourage code fences and prose in\n * the model's response while still tolerating them via the read-side extractor.\n * @public\n */\nexport const SMART_JSON_PROMPT_HINT: string =\n 'Respond with raw JSON only — no Markdown code fences, no explanatory prose, ' +\n 'no preamble or trailing commentary. The response must parse with JSON.parse.';\n\n/**\n * Controls the optional system-prompt augmentation applied by\n * {@link AiAssist.generateJsonCompletion}.\n *\n * - `'smart'` (default): append {@link AiAssist.SMART_JSON_PROMPT_HINT}.\n * - `'none'`: do not modify the prompt.\n * - A string: append the supplied text verbatim.\n *\n * @remarks\n * The `string & {}` branch is the standard TypeScript trick that prevents\n * the literal members from being widened away — callers still get\n * autocomplete for `'smart'` and `'none'` while accepting any string.\n *\n * @public\n */\nexport type JsonPromptHint = 'smart' | 'none' | (string & {});\n\n/**\n * Parameters for {@link AiAssist.generateJsonCompletion}. Extends\n * {@link AiAssist.IProviderCompletionParams} with JSON-validation knobs.\n * @public\n */\nexport interface IGenerateJsonCompletionParams<T> extends IProviderCompletionParams {\n /**\n * Caller-supplied `Converter<T>` or `Validator<T>` applied to the parsed\n * JSON value. Wrapped internally in {@link AiAssist.fencedStringifiedJson}\n * unless {@link AiAssist.IGenerateJsonCompletionParams.jsonConverter} is\n * provided.\n */\n readonly converter?: Converter<T> | Validator<T>;\n\n /**\n * Full string-to-`T` pipeline override. When supplied, takes precedence over\n * {@link AiAssist.IGenerateJsonCompletionParams.converter} and lets the\n * caller plug in a custom extractor or skip the default fence tolerance\n * entirely.\n */\n readonly jsonConverter?: Converter<T>;\n\n /**\n * Controls the optional system-prompt augmentation. Defaults to `'smart'`.\n * Pass `'none'` to disable, or a string to append custom guidance.\n */\n readonly promptHint?: JsonPromptHint;\n}\n\n/**\n * Successful result of {@link AiAssist.generateJsonCompletion}.\n * @public\n */\nexport interface IGenerateJsonCompletionResult<T> {\n /** The validated JSON value. */\n readonly value: T;\n /** The raw response text returned by the provider. */\n readonly raw: string;\n /** The full underlying completion response. */\n readonly response: IAiCompletionResponse;\n}\n\nfunction applyPromptHint(prompt: AiPrompt, hint: JsonPromptHint): AiPrompt {\n if (hint === 'none') {\n return prompt;\n }\n const suffix = hint === 'smart' ? SMART_JSON_PROMPT_HINT : hint;\n const system = prompt.system.length > 0 ? `${prompt.system}\\n\\n${suffix}` : suffix;\n return new AiPrompt(prompt.user, system, prompt.attachments);\n}\n\n/**\n * Calls {@link AiAssist.callProviderCompletion}, then runs the response text\n * through a tolerant JSON converter (default:\n * {@link AiAssist.fencedStringifiedJson}) and the caller's\n * `converter`/`validator`. Returns the validated value plus the raw text and\n * underlying completion response for diagnostics.\n *\n * @remarks\n * The default smart prompt hint asks the model to emit raw JSON. The read-side\n * extractor still tolerates fences and prose, so models that ignore the hint\n * are still handled.\n *\n * Either `converter` or `jsonConverter` must be provided; passing both lets\n * `jsonConverter` win.\n *\n * @param params - Provider parameters plus JSON validation options.\n * @returns The validated value, the raw text, and the underlying response.\n * @public\n */\nexport async function generateJsonCompletion<T>(\n params: IGenerateJsonCompletionParams<T>\n): Promise<Result<IGenerateJsonCompletionResult<T>>> {\n const { converter, jsonConverter, promptHint = 'smart', prompt, ...rest } = params;\n\n if (jsonConverter === undefined && converter === undefined) {\n return fail('generateJsonCompletion: either converter or jsonConverter must be provided.');\n }\n\n const pipeline: Converter<T> = jsonConverter ?? fencedStringifiedJson<T>({ inner: converter! });\n const augmentedPrompt = applyPromptHint(prompt, promptHint);\n\n const response = await callProviderCompletion({ ...rest, prompt: augmentedPrompt });\n if (response.isFailure()) {\n return fail(response.message);\n }\n const completion = response.value;\n\n return pipeline\n .convert(completion.content)\n .withErrorFormat((msg) => `generateJsonCompletion: ${msg}`)\n .onSuccess((value) => succeed({ value, raw: completion.content, response: completion }));\n}\n"]}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON-tolerant extraction and converters for LLM responses.
|
|
3
|
+
*
|
|
4
|
+
* Models commonly wrap JSON output in Markdown code fences, add a
|
|
5
|
+
* "Sure, here's the JSON:" preamble, or trail off with prose after the
|
|
6
|
+
* closing brace. These helpers normalize that quirk on the read side so every
|
|
7
|
+
* AiAssist consumer can reach a validated `T` from raw model text without
|
|
8
|
+
* reimplementing the same fence-stripping logic.
|
|
9
|
+
*
|
|
10
|
+
* Scope: strip wrappers (fences, prose, BOM, whitespace). Out of scope: repair
|
|
11
|
+
* malformed JSON (missing commas, unquoted keys, smart quotes, etc.).
|
|
12
|
+
*
|
|
13
|
+
* @packageDocumentation
|
|
14
|
+
*/
|
|
15
|
+
import { type Converter, Result, type Validator } from '@fgv/ts-utils';
|
|
16
|
+
import { type JsonValue } from '@fgv/ts-json-base';
|
|
17
|
+
/**
|
|
18
|
+
* A function that pulls a JSON-shaped substring out of arbitrary model text.
|
|
19
|
+
* Implementations strip whatever wrappers the model added (fences, preamble,
|
|
20
|
+
* trailing prose) and return the JSON-shaped substring ready for `JSON.parse`.
|
|
21
|
+
* @public
|
|
22
|
+
*/
|
|
23
|
+
export type JsonTextExtractor = (text: string) => Result<string>;
|
|
24
|
+
/**
|
|
25
|
+
* Default {@link AiAssist.JsonTextExtractor | extractor} for LLM responses. Tolerates:
|
|
26
|
+
*
|
|
27
|
+
* - Leading/trailing whitespace and a leading byte-order mark.
|
|
28
|
+
* - Markdown code fences (with or without a language tag).
|
|
29
|
+
* - Conversational preamble before the first `{` or `[`.
|
|
30
|
+
* - Trailing prose after the matched closing `}` or `]`.
|
|
31
|
+
*
|
|
32
|
+
* Out of scope: repairing malformed JSON, handling smart quotes, etc.
|
|
33
|
+
*
|
|
34
|
+
* @param text - Raw model output.
|
|
35
|
+
* @returns A `Result<string>` containing the JSON-shaped substring, or a
|
|
36
|
+
* `Failure` if no JSON-shaped substring was found.
|
|
37
|
+
* @public
|
|
38
|
+
*/
|
|
39
|
+
export declare const extractJsonText: JsonTextExtractor;
|
|
40
|
+
/**
|
|
41
|
+
* Options shared by every {@link AiAssist.fencedStringifiedJson} call.
|
|
42
|
+
* @public
|
|
43
|
+
*/
|
|
44
|
+
export interface IFencedStringifiedJsonExtractorOptions {
|
|
45
|
+
/**
|
|
46
|
+
* Optional pre-parse extractor. Defaults to {@link AiAssist.extractJsonText}.
|
|
47
|
+
* Provide a custom extractor to handle response shapes the default does not
|
|
48
|
+
* understand.
|
|
49
|
+
*/
|
|
50
|
+
readonly extractor?: JsonTextExtractor;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Options for the validating overload of {@link AiAssist.fencedStringifiedJson}.
|
|
54
|
+
* `inner` is required so the typed `Converter<T>` return value can never lie
|
|
55
|
+
* about the runtime shape.
|
|
56
|
+
* @public
|
|
57
|
+
*/
|
|
58
|
+
export interface IFencedStringifiedJsonOptions<T> extends IFencedStringifiedJsonExtractorOptions {
|
|
59
|
+
/** Inner converter or validator applied to the parsed JSON value. */
|
|
60
|
+
readonly inner: Converter<T> | Validator<T>;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Creates a `Converter` that accepts raw LLM response text, runs it through a
|
|
64
|
+
* tolerant extractor (default: {@link AiAssist.extractJsonText}), parses the
|
|
65
|
+
* extracted substring as JSON, and applies an optional inner converter or
|
|
66
|
+
* validator.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* const converter = fencedStringifiedJson({ inner: myShapeConverter });
|
|
71
|
+
* const result = converter.convert(llmText); // Result<MyShape>
|
|
72
|
+
* ```
|
|
73
|
+
*
|
|
74
|
+
* @param options - Optional extractor; omit to keep the default. Without an
|
|
75
|
+
* `inner` step, the converter resolves to the parsed `JsonValue`.
|
|
76
|
+
* @returns A `Converter<JsonValue>`.
|
|
77
|
+
* @public
|
|
78
|
+
*/
|
|
79
|
+
export declare function fencedStringifiedJson(options?: IFencedStringifiedJsonExtractorOptions): Converter<JsonValue>;
|
|
80
|
+
/**
|
|
81
|
+
* Creates a `Converter` that accepts raw LLM response text, runs it through a
|
|
82
|
+
* tolerant extractor (default: {@link AiAssist.extractJsonText}), parses the
|
|
83
|
+
* extracted substring as JSON, and applies the supplied inner converter or
|
|
84
|
+
* validator.
|
|
85
|
+
*
|
|
86
|
+
* @param options - Required `inner` converter/validator and optional extractor.
|
|
87
|
+
* @returns A `Converter<T>`.
|
|
88
|
+
* @public
|
|
89
|
+
*/
|
|
90
|
+
export declare function fencedStringifiedJson<T>(options: IFencedStringifiedJsonOptions<T>): Converter<T>;
|
|
91
|
+
//# sourceMappingURL=jsonResponse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonResponse.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/jsonResponse.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAc,KAAK,SAAS,EAAQ,MAAM,EAAW,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAClG,OAAO,EAAoC,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAErF;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC;AA+DjE;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,EAAE,iBA6B7B,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,sCAAsC;IACrD;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,iBAAiB,CAAC;CACxC;AAED;;;;;GAKG;AACH,MAAM,WAAW,6BAA6B,CAAC,CAAC,CAAE,SAAQ,sCAAsC;IAC9F,qEAAqE;IACrE,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;CAC7C;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE,sCAAsC,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;AAC9G;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,OAAO,EAAE,6BAA6B,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Copyright (c) 2026 Erik Fortune
|
|
3
|
+
//
|
|
4
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
// in the Software without restriction, including without limitation the rights
|
|
7
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
// furnished to do so, subject to the following conditions:
|
|
10
|
+
//
|
|
11
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
// copies or substantial portions of the Software.
|
|
13
|
+
//
|
|
14
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
// SOFTWARE.
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.extractJsonText = void 0;
|
|
23
|
+
exports.fencedStringifiedJson = fencedStringifiedJson;
|
|
24
|
+
/**
|
|
25
|
+
* JSON-tolerant extraction and converters for LLM responses.
|
|
26
|
+
*
|
|
27
|
+
* Models commonly wrap JSON output in Markdown code fences, add a
|
|
28
|
+
* "Sure, here's the JSON:" preamble, or trail off with prose after the
|
|
29
|
+
* closing brace. These helpers normalize that quirk on the read side so every
|
|
30
|
+
* AiAssist consumer can reach a validated `T` from raw model text without
|
|
31
|
+
* reimplementing the same fence-stripping logic.
|
|
32
|
+
*
|
|
33
|
+
* Scope: strip wrappers (fences, prose, BOM, whitespace). Out of scope: repair
|
|
34
|
+
* malformed JSON (missing commas, unquoted keys, smart quotes, etc.).
|
|
35
|
+
*
|
|
36
|
+
* @packageDocumentation
|
|
37
|
+
*/
|
|
38
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
39
|
+
const ts_json_base_1 = require("@fgv/ts-json-base");
|
|
40
|
+
const FENCED_BLOCK = /```[A-Za-z0-9_-]*\s*\r?\n([\s\S]*?)\r?\n?```/;
|
|
41
|
+
const BOM = /^\uFEFF/;
|
|
42
|
+
// Full RFC 8259 grammar so the extractor only succeeds when the entire
|
|
43
|
+
// candidate parses as a JSON primitive (instead of just starting like one).
|
|
44
|
+
const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
45
|
+
// eslint-disable-next-line no-control-regex
|
|
46
|
+
const JSON_STRING = /^"(?:[^"\\\u0000-\u001F]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"$/;
|
|
47
|
+
const JSON_KEYWORD = /^(?:true|false|null)$/;
|
|
48
|
+
function stripBom(text) {
|
|
49
|
+
return text.replace(BOM, '');
|
|
50
|
+
}
|
|
51
|
+
function findBalancedJsonSubstring(text) {
|
|
52
|
+
// Walk the text once tracking string state. The first '{' or '[' that is
|
|
53
|
+
// *outside* a quoted string is the candidate start; from there, count
|
|
54
|
+
// matching close characters while ignoring delimiters that appear inside
|
|
55
|
+
// strings.
|
|
56
|
+
let inString = false;
|
|
57
|
+
let escape = false;
|
|
58
|
+
let start = -1;
|
|
59
|
+
let open = '';
|
|
60
|
+
let close = '';
|
|
61
|
+
let depth = 0;
|
|
62
|
+
for (let i = 0; i < text.length; i++) {
|
|
63
|
+
const ch = text.charAt(i);
|
|
64
|
+
if (inString) {
|
|
65
|
+
if (escape) {
|
|
66
|
+
escape = false;
|
|
67
|
+
}
|
|
68
|
+
else if (ch === '\\') {
|
|
69
|
+
escape = true;
|
|
70
|
+
}
|
|
71
|
+
else if (ch === '"') {
|
|
72
|
+
inString = false;
|
|
73
|
+
}
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (ch === '"') {
|
|
77
|
+
inString = true;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (start < 0) {
|
|
81
|
+
if (ch === '{' || ch === '[') {
|
|
82
|
+
start = i;
|
|
83
|
+
open = ch;
|
|
84
|
+
close = ch === '{' ? '}' : ']';
|
|
85
|
+
depth = 1;
|
|
86
|
+
}
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (ch === open) {
|
|
90
|
+
depth++;
|
|
91
|
+
}
|
|
92
|
+
else if (ch === close) {
|
|
93
|
+
depth--;
|
|
94
|
+
if (depth === 0) {
|
|
95
|
+
return text.slice(start, i + 1);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Default {@link AiAssist.JsonTextExtractor | extractor} for LLM responses. Tolerates:
|
|
103
|
+
*
|
|
104
|
+
* - Leading/trailing whitespace and a leading byte-order mark.
|
|
105
|
+
* - Markdown code fences (with or without a language tag).
|
|
106
|
+
* - Conversational preamble before the first `{` or `[`.
|
|
107
|
+
* - Trailing prose after the matched closing `}` or `]`.
|
|
108
|
+
*
|
|
109
|
+
* Out of scope: repairing malformed JSON, handling smart quotes, etc.
|
|
110
|
+
*
|
|
111
|
+
* @param text - Raw model output.
|
|
112
|
+
* @returns A `Result<string>` containing the JSON-shaped substring, or a
|
|
113
|
+
* `Failure` if no JSON-shaped substring was found.
|
|
114
|
+
* @public
|
|
115
|
+
*/
|
|
116
|
+
const extractJsonText = (text) => {
|
|
117
|
+
if (typeof text !== 'string') {
|
|
118
|
+
return (0, ts_utils_1.fail)('extractJsonText: input must be a string.');
|
|
119
|
+
}
|
|
120
|
+
const stripped = stripBom(text).trim();
|
|
121
|
+
if (stripped.length === 0) {
|
|
122
|
+
return (0, ts_utils_1.fail)('extractJsonText: input is empty.');
|
|
123
|
+
}
|
|
124
|
+
const fenced = FENCED_BLOCK.exec(stripped);
|
|
125
|
+
const candidate = fenced ? fenced[1].trim() : stripped;
|
|
126
|
+
if (candidate.length === 0) {
|
|
127
|
+
return (0, ts_utils_1.fail)('extractJsonText: no JSON content found.');
|
|
128
|
+
}
|
|
129
|
+
// Whole-candidate primitive check runs before the brace scan so that a
|
|
130
|
+
// valid JSON string containing braces (e.g. `"text with { }"`) is returned
|
|
131
|
+
// intact instead of being mangled into the first balanced `{ }` match.
|
|
132
|
+
if (JSON_KEYWORD.test(candidate) || JSON_NUMBER.test(candidate) || JSON_STRING.test(candidate)) {
|
|
133
|
+
return (0, ts_utils_1.succeed)(candidate);
|
|
134
|
+
}
|
|
135
|
+
const balanced = findBalancedJsonSubstring(candidate);
|
|
136
|
+
if (balanced !== undefined) {
|
|
137
|
+
return (0, ts_utils_1.succeed)(balanced);
|
|
138
|
+
}
|
|
139
|
+
return (0, ts_utils_1.fail)('extractJsonText: no JSON-shaped substring found.');
|
|
140
|
+
};
|
|
141
|
+
exports.extractJsonText = extractJsonText;
|
|
142
|
+
function fencedStringifiedJson(options) {
|
|
143
|
+
var _a;
|
|
144
|
+
const extractor = (_a = options === null || options === void 0 ? void 0 : options.extractor) !== null && _a !== void 0 ? _a : exports.extractJsonText;
|
|
145
|
+
const inner = options === null || options === void 0 ? void 0 : options.inner;
|
|
146
|
+
const parser = inner !== undefined ? ts_json_base_1.Converters.stringifiedJson(inner) : ts_json_base_1.Converters.stringifiedJson();
|
|
147
|
+
return new ts_utils_1.Conversion.BaseConverter((from) => {
|
|
148
|
+
if (typeof from !== 'string') {
|
|
149
|
+
return (0, ts_utils_1.fail)('fencedStringifiedJson: input must be a string.');
|
|
150
|
+
}
|
|
151
|
+
return extractor(from).onSuccess((extracted) => parser.convert(extracted));
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
//# sourceMappingURL=jsonResponse.js.map
|