@fgv/ts-extras 5.1.0-21 → 5.1.0-23
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/packlets/csv/csvFileHelpers.js +0 -14
- package/dist/packlets/csv/csvFileHelpers.js.map +1 -1
- package/dist/packlets/csv/csvHelpers.js +14 -0
- package/dist/packlets/csv/csvHelpers.js.map +1 -1
- package/dist/packlets/csv/index.browser.js +1 -3
- package/dist/packlets/csv/index.browser.js.map +1 -1
- package/dist/packlets/record-jar/index.browser.js +1 -3
- package/dist/packlets/record-jar/index.browser.js.map +1 -1
- package/dist/packlets/record-jar/recordJarFileHelpers.js +0 -18
- package/dist/packlets/record-jar/recordJarFileHelpers.js.map +1 -1
- package/dist/packlets/record-jar/recordJarHelpers.js +18 -0
- package/dist/packlets/record-jar/recordJarHelpers.js.map +1 -1
- package/dist/ts-extras.d.ts +239 -5
- 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/lib/packlets/csv/csvFileHelpers.d.ts +0 -10
- package/lib/packlets/csv/csvFileHelpers.d.ts.map +1 -1
- package/lib/packlets/csv/csvFileHelpers.js +0 -15
- package/lib/packlets/csv/csvFileHelpers.js.map +1 -1
- package/lib/packlets/csv/csvHelpers.d.ts +10 -0
- package/lib/packlets/csv/csvHelpers.d.ts.map +1 -1
- package/lib/packlets/csv/csvHelpers.js +15 -0
- package/lib/packlets/csv/csvHelpers.js.map +1 -1
- package/lib/packlets/csv/index.browser.d.ts +0 -1
- package/lib/packlets/csv/index.browser.d.ts.map +1 -1
- package/lib/packlets/csv/index.browser.js +1 -5
- package/lib/packlets/csv/index.browser.js.map +1 -1
- package/lib/packlets/record-jar/index.browser.d.ts +0 -1
- package/lib/packlets/record-jar/index.browser.d.ts.map +1 -1
- package/lib/packlets/record-jar/index.browser.js +1 -5
- package/lib/packlets/record-jar/index.browser.js.map +1 -1
- package/lib/packlets/record-jar/recordJarFileHelpers.d.ts +0 -11
- package/lib/packlets/record-jar/recordJarFileHelpers.d.ts.map +1 -1
- package/lib/packlets/record-jar/recordJarFileHelpers.js +0 -19
- package/lib/packlets/record-jar/recordJarFileHelpers.js.map +1 -1
- package/lib/packlets/record-jar/recordJarHelpers.d.ts +11 -0
- package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -1
- package/lib/packlets/record-jar/recordJarHelpers.js +19 -0
- package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -1
- package/package.json +7 -7
|
@@ -8,4 +8,6 @@ export { callProviderCompletion, callProxiedCompletion, callProviderImageGenerat
|
|
|
8
8
|
export { callProviderCompletionStream, callProxiedCompletionStream } 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 } from './jsonResponse';
|
|
12
|
+
export { generateJsonCompletion, SMART_JSON_PROMPT_HINT } from './jsonCompletion';
|
|
11
13
|
//# 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,OAAO,EACL,QAAQ,EAeR,iBAAiB,EAmBjB,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,EAItB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,EAE5B,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","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,OAAO,EACL,QAAQ,EAeR,iBAAiB,EAmBjB,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,EAItB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,EAE5B,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,EAItB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EAIvB,MAAM,kBAAkB,CAAC","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,95 @@
|
|
|
1
|
+
// Copyright (c) 2026 Erik Fortune
|
|
2
|
+
//
|
|
3
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
// in the Software without restriction, including without limitation the rights
|
|
6
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
// furnished to do so, subject to the following conditions:
|
|
9
|
+
//
|
|
10
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
// copies or substantial portions of the Software.
|
|
12
|
+
//
|
|
13
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
// SOFTWARE.
|
|
20
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
21
|
+
var t = {};
|
|
22
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
23
|
+
t[p] = s[p];
|
|
24
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
25
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
26
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
27
|
+
t[p[i]] = s[p[i]];
|
|
28
|
+
}
|
|
29
|
+
return t;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* `generateJsonCompletion<T>` — request a JSON-shaped completion from any
|
|
33
|
+
* provider supported by AiAssist and validate it against a caller-supplied
|
|
34
|
+
* `Converter<T>` or `Validator<T>`. Wraps fence/preamble tolerance + parsing +
|
|
35
|
+
* validation into a single call so consumers don't reinvent the pipeline.
|
|
36
|
+
*
|
|
37
|
+
* @packageDocumentation
|
|
38
|
+
*/
|
|
39
|
+
import { fail, succeed } from '@fgv/ts-utils';
|
|
40
|
+
import { callProviderCompletion } from './apiClient';
|
|
41
|
+
import { fencedStringifiedJson } from './jsonResponse';
|
|
42
|
+
import { AiPrompt } from './model';
|
|
43
|
+
/**
|
|
44
|
+
* Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}
|
|
45
|
+
* is `'smart'` (the default). Designed to discourage code fences and prose in
|
|
46
|
+
* the model's response while still tolerating them via the read-side extractor.
|
|
47
|
+
* @public
|
|
48
|
+
*/
|
|
49
|
+
export const SMART_JSON_PROMPT_HINT = 'Respond with raw JSON only — no Markdown code fences, no explanatory prose, ' +
|
|
50
|
+
'no preamble or trailing commentary. The response must parse with JSON.parse.';
|
|
51
|
+
function applyPromptHint(prompt, hint) {
|
|
52
|
+
if (hint === 'none') {
|
|
53
|
+
return prompt;
|
|
54
|
+
}
|
|
55
|
+
const suffix = hint === 'smart' ? SMART_JSON_PROMPT_HINT : hint;
|
|
56
|
+
const system = prompt.system.length > 0 ? `${prompt.system}\n\n${suffix}` : suffix;
|
|
57
|
+
return new AiPrompt(prompt.user, system, prompt.attachments);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Calls {@link AiAssist.callProviderCompletion}, then runs the response text
|
|
61
|
+
* through a tolerant JSON converter (default:
|
|
62
|
+
* {@link AiAssist.fencedStringifiedJson}) and the caller's
|
|
63
|
+
* `converter`/`validator`. Returns the validated value plus the raw text and
|
|
64
|
+
* underlying completion response for diagnostics.
|
|
65
|
+
*
|
|
66
|
+
* @remarks
|
|
67
|
+
* The default smart prompt hint asks the model to emit raw JSON. The read-side
|
|
68
|
+
* extractor still tolerates fences and prose, so models that ignore the hint
|
|
69
|
+
* are still handled.
|
|
70
|
+
*
|
|
71
|
+
* Either `converter` or `jsonConverter` must be provided; passing both lets
|
|
72
|
+
* `jsonConverter` win.
|
|
73
|
+
*
|
|
74
|
+
* @param params - Provider parameters plus JSON validation options.
|
|
75
|
+
* @returns The validated value, the raw text, and the underlying response.
|
|
76
|
+
* @public
|
|
77
|
+
*/
|
|
78
|
+
export async function generateJsonCompletion(params) {
|
|
79
|
+
const { converter, jsonConverter, promptHint = 'smart', prompt } = params, rest = __rest(params, ["converter", "jsonConverter", "promptHint", "prompt"]);
|
|
80
|
+
if (jsonConverter === undefined && converter === undefined) {
|
|
81
|
+
return fail('generateJsonCompletion: either converter or jsonConverter must be provided.');
|
|
82
|
+
}
|
|
83
|
+
const pipeline = jsonConverter !== null && jsonConverter !== void 0 ? jsonConverter : fencedStringifiedJson({ inner: converter });
|
|
84
|
+
const augmentedPrompt = applyPromptHint(prompt, promptHint);
|
|
85
|
+
const response = await callProviderCompletion(Object.assign(Object.assign({}, rest), { prompt: augmentedPrompt }));
|
|
86
|
+
if (response.isFailure()) {
|
|
87
|
+
return fail(response.message);
|
|
88
|
+
}
|
|
89
|
+
const completion = response.value;
|
|
90
|
+
return pipeline
|
|
91
|
+
.convert(completion.content)
|
|
92
|
+
.withErrorFormat((msg) => `generateJsonCompletion: ${msg}`)
|
|
93
|
+
.onSuccess((value) => succeed({ value, raw: completion.content, response: completion }));
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=jsonCompletion.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"js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BAAsB,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,IAAI,CAAC,6EAA6E,CAAC,CAAC;IAC7F,CAAC;IAED,MAAM,QAAQ,GAAiB,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,qBAAqB,CAAI,EAAE,KAAK,EAAE,SAAU,EAAE,CAAC,CAAC;IAChG,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAE5D,MAAM,QAAQ,GAAG,MAAM,sBAAsB,iCAAM,IAAI,KAAE,MAAM,EAAE,eAAe,IAAG,CAAC;IACpF,IAAI,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,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,OAAO,CAAC,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,149 @@
|
|
|
1
|
+
// Copyright (c) 2026 Erik Fortune
|
|
2
|
+
//
|
|
3
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
// in the Software without restriction, including without limitation the rights
|
|
6
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
// furnished to do so, subject to the following conditions:
|
|
9
|
+
//
|
|
10
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
// copies or substantial portions of the Software.
|
|
12
|
+
//
|
|
13
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
// SOFTWARE.
|
|
20
|
+
/**
|
|
21
|
+
* JSON-tolerant extraction and converters for LLM responses.
|
|
22
|
+
*
|
|
23
|
+
* Models commonly wrap JSON output in Markdown code fences, add a
|
|
24
|
+
* "Sure, here's the JSON:" preamble, or trail off with prose after the
|
|
25
|
+
* closing brace. These helpers normalize that quirk on the read side so every
|
|
26
|
+
* AiAssist consumer can reach a validated `T` from raw model text without
|
|
27
|
+
* reimplementing the same fence-stripping logic.
|
|
28
|
+
*
|
|
29
|
+
* Scope: strip wrappers (fences, prose, BOM, whitespace). Out of scope: repair
|
|
30
|
+
* malformed JSON (missing commas, unquoted keys, smart quotes, etc.).
|
|
31
|
+
*
|
|
32
|
+
* @packageDocumentation
|
|
33
|
+
*/
|
|
34
|
+
import { Conversion, fail, succeed } from '@fgv/ts-utils';
|
|
35
|
+
import { Converters as JsonBaseConverters } from '@fgv/ts-json-base';
|
|
36
|
+
const FENCED_BLOCK = /```[A-Za-z0-9_-]*\s*\r?\n([\s\S]*?)\r?\n?```/;
|
|
37
|
+
const BOM = /^\uFEFF/;
|
|
38
|
+
// Full RFC 8259 grammar so the extractor only succeeds when the entire
|
|
39
|
+
// candidate parses as a JSON primitive (instead of just starting like one).
|
|
40
|
+
const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
41
|
+
// eslint-disable-next-line no-control-regex
|
|
42
|
+
const JSON_STRING = /^"(?:[^"\\\u0000-\u001F]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"$/;
|
|
43
|
+
const JSON_KEYWORD = /^(?:true|false|null)$/;
|
|
44
|
+
function stripBom(text) {
|
|
45
|
+
return text.replace(BOM, '');
|
|
46
|
+
}
|
|
47
|
+
function findBalancedJsonSubstring(text) {
|
|
48
|
+
// Walk the text once tracking string state. The first '{' or '[' that is
|
|
49
|
+
// *outside* a quoted string is the candidate start; from there, count
|
|
50
|
+
// matching close characters while ignoring delimiters that appear inside
|
|
51
|
+
// strings.
|
|
52
|
+
let inString = false;
|
|
53
|
+
let escape = false;
|
|
54
|
+
let start = -1;
|
|
55
|
+
let open = '';
|
|
56
|
+
let close = '';
|
|
57
|
+
let depth = 0;
|
|
58
|
+
for (let i = 0; i < text.length; i++) {
|
|
59
|
+
const ch = text.charAt(i);
|
|
60
|
+
if (inString) {
|
|
61
|
+
if (escape) {
|
|
62
|
+
escape = false;
|
|
63
|
+
}
|
|
64
|
+
else if (ch === '\\') {
|
|
65
|
+
escape = true;
|
|
66
|
+
}
|
|
67
|
+
else if (ch === '"') {
|
|
68
|
+
inString = false;
|
|
69
|
+
}
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (ch === '"') {
|
|
73
|
+
inString = true;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (start < 0) {
|
|
77
|
+
if (ch === '{' || ch === '[') {
|
|
78
|
+
start = i;
|
|
79
|
+
open = ch;
|
|
80
|
+
close = ch === '{' ? '}' : ']';
|
|
81
|
+
depth = 1;
|
|
82
|
+
}
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (ch === open) {
|
|
86
|
+
depth++;
|
|
87
|
+
}
|
|
88
|
+
else if (ch === close) {
|
|
89
|
+
depth--;
|
|
90
|
+
if (depth === 0) {
|
|
91
|
+
return text.slice(start, i + 1);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Default {@link AiAssist.JsonTextExtractor | extractor} for LLM responses. Tolerates:
|
|
99
|
+
*
|
|
100
|
+
* - Leading/trailing whitespace and a leading byte-order mark.
|
|
101
|
+
* - Markdown code fences (with or without a language tag).
|
|
102
|
+
* - Conversational preamble before the first `{` or `[`.
|
|
103
|
+
* - Trailing prose after the matched closing `}` or `]`.
|
|
104
|
+
*
|
|
105
|
+
* Out of scope: repairing malformed JSON, handling smart quotes, etc.
|
|
106
|
+
*
|
|
107
|
+
* @param text - Raw model output.
|
|
108
|
+
* @returns A `Result<string>` containing the JSON-shaped substring, or a
|
|
109
|
+
* `Failure` if no JSON-shaped substring was found.
|
|
110
|
+
* @public
|
|
111
|
+
*/
|
|
112
|
+
export const extractJsonText = (text) => {
|
|
113
|
+
if (typeof text !== 'string') {
|
|
114
|
+
return fail('extractJsonText: input must be a string.');
|
|
115
|
+
}
|
|
116
|
+
const stripped = stripBom(text).trim();
|
|
117
|
+
if (stripped.length === 0) {
|
|
118
|
+
return fail('extractJsonText: input is empty.');
|
|
119
|
+
}
|
|
120
|
+
const fenced = FENCED_BLOCK.exec(stripped);
|
|
121
|
+
const candidate = fenced ? fenced[1].trim() : stripped;
|
|
122
|
+
if (candidate.length === 0) {
|
|
123
|
+
return fail('extractJsonText: no JSON content found.');
|
|
124
|
+
}
|
|
125
|
+
// Whole-candidate primitive check runs before the brace scan so that a
|
|
126
|
+
// valid JSON string containing braces (e.g. `"text with { }"`) is returned
|
|
127
|
+
// intact instead of being mangled into the first balanced `{ }` match.
|
|
128
|
+
if (JSON_KEYWORD.test(candidate) || JSON_NUMBER.test(candidate) || JSON_STRING.test(candidate)) {
|
|
129
|
+
return succeed(candidate);
|
|
130
|
+
}
|
|
131
|
+
const balanced = findBalancedJsonSubstring(candidate);
|
|
132
|
+
if (balanced !== undefined) {
|
|
133
|
+
return succeed(balanced);
|
|
134
|
+
}
|
|
135
|
+
return fail('extractJsonText: no JSON-shaped substring found.');
|
|
136
|
+
};
|
|
137
|
+
export function fencedStringifiedJson(options) {
|
|
138
|
+
var _a;
|
|
139
|
+
const extractor = (_a = options === null || options === void 0 ? void 0 : options.extractor) !== null && _a !== void 0 ? _a : extractJsonText;
|
|
140
|
+
const inner = options === null || options === void 0 ? void 0 : options.inner;
|
|
141
|
+
const parser = inner !== undefined ? JsonBaseConverters.stringifiedJson(inner) : JsonBaseConverters.stringifiedJson();
|
|
142
|
+
return new Conversion.BaseConverter((from) => {
|
|
143
|
+
if (typeof from !== 'string') {
|
|
144
|
+
return fail('fencedStringifiedJson: input must be a string.');
|
|
145
|
+
}
|
|
146
|
+
return extractor(from).onSuccess((extracted) => parser.convert(extracted));
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
//# sourceMappingURL=jsonResponse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonResponse.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/jsonResponse.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;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,UAAU,EAAkB,IAAI,EAAU,OAAO,EAAkB,MAAM,eAAe,CAAC;AAClG,OAAO,EAAE,UAAU,IAAI,kBAAkB,EAAkB,MAAM,mBAAmB,CAAC;AAUrF,MAAM,YAAY,GAAW,8CAA8C,CAAC;AAC5E,MAAM,GAAG,GAAW,SAAS,CAAC;AAC9B,uEAAuE;AACvE,4EAA4E;AAC5E,MAAM,WAAW,GAAW,+CAA+C,CAAC;AAC5E,4CAA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CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;QAC/F,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC;IAC5B,CAAC;IAED,MAAM,QAAQ,GAAG,yBAAyB,CAAC,SAAS,CAAC,CAAC;IACtD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO,IAAI,CAAC,kDAAkD,CAAC,CAAC;AAClE,CAAC,CAAC;AAuDF,MAAM,UAAU,qBAAqB,CACnC,OAAmF;;IAEnF,MAAM,SAAS,GAAsB,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,mCAAI,eAAe,CAAC;IAC3E,MAAM,KAAK,GAAI,OAAwD,aAAxD,OAAO,uBAAP,OAAO,CAAmD,KAAK,CAAC;IAC/E,MAAM,MAAM,GACV,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,kBAAkB,CAAC,eAAe,CAAI,KAAK,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,eAAe,EAAE,CAAC;IAE5G,OAAO,IAAI,UAAU,CAAC,aAAa,CAAgB,CAAC,IAAa,EAAyB,EAAE;QAC1F,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,OAAO,IAAI,CAAC,gDAAgD,CAAC,CAAC;QAChE,CAAC;QACD,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC;IAC7E,CAAC,CAAC,CAAC;AACL,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 * JSON-tolerant extraction and converters for LLM responses.\n *\n * Models commonly wrap JSON output in Markdown code fences, add a\n * \"Sure, here's the JSON:\" preamble, or trail off with prose after the\n * closing brace. These helpers normalize that quirk on the read side so every\n * AiAssist consumer can reach a validated `T` from raw model text without\n * reimplementing the same fence-stripping logic.\n *\n * Scope: strip wrappers (fences, prose, BOM, whitespace). Out of scope: repair\n * malformed JSON (missing commas, unquoted keys, smart quotes, etc.).\n *\n * @packageDocumentation\n */\n\nimport { Conversion, type Converter, fail, Result, succeed, type Validator } from '@fgv/ts-utils';\nimport { Converters as JsonBaseConverters, type JsonValue } from '@fgv/ts-json-base';\n\n/**\n * A function that pulls a JSON-shaped substring out of arbitrary model text.\n * Implementations strip whatever wrappers the model added (fences, preamble,\n * trailing prose) and return the JSON-shaped substring ready for `JSON.parse`.\n * @public\n */\nexport type JsonTextExtractor = (text: string) => Result<string>;\n\nconst FENCED_BLOCK: RegExp = /```[A-Za-z0-9_-]*\\s*\\r?\\n([\\s\\S]*?)\\r?\\n?```/;\nconst BOM: RegExp = /^\\uFEFF/;\n// Full RFC 8259 grammar so the extractor only succeeds when the entire\n// candidate parses as a JSON primitive (instead of just starting like one).\nconst JSON_NUMBER: RegExp = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\n// eslint-disable-next-line no-control-regex\nconst JSON_STRING: RegExp = /^\"(?:[^\"\\\\\\u0000-\\u001F]|\\\\(?:[\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"$/;\nconst JSON_KEYWORD: RegExp = /^(?:true|false|null)$/;\n\nfunction stripBom(text: string): string {\n return text.replace(BOM, '');\n}\n\nfunction findBalancedJsonSubstring(text: string): string | undefined {\n // Walk the text once tracking string state. The first '{' or '[' that is\n // *outside* a quoted string is the candidate start; from there, count\n // matching close characters while ignoring delimiters that appear inside\n // strings.\n let inString = false;\n let escape = false;\n let start = -1;\n let open = '';\n let close = '';\n let depth = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text.charAt(i);\n if (inString) {\n if (escape) {\n escape = false;\n } else if (ch === '\\\\') {\n escape = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n continue;\n }\n if (start < 0) {\n if (ch === '{' || ch === '[') {\n start = i;\n open = ch;\n close = ch === '{' ? '}' : ']';\n depth = 1;\n }\n continue;\n }\n if (ch === open) {\n depth++;\n } else if (ch === close) {\n depth--;\n if (depth === 0) {\n return text.slice(start, i + 1);\n }\n }\n }\n return undefined;\n}\n\n/**\n * Default {@link AiAssist.JsonTextExtractor | extractor} for LLM responses. Tolerates:\n *\n * - Leading/trailing whitespace and a leading byte-order mark.\n * - Markdown code fences (with or without a language tag).\n * - Conversational preamble before the first `{` or `[`.\n * - Trailing prose after the matched closing `}` or `]`.\n *\n * Out of scope: repairing malformed JSON, handling smart quotes, etc.\n *\n * @param text - Raw model output.\n * @returns A `Result<string>` containing the JSON-shaped substring, or a\n * `Failure` if no JSON-shaped substring was found.\n * @public\n */\nexport const extractJsonText: JsonTextExtractor = (text: string): Result<string> => {\n if (typeof text !== 'string') {\n return fail('extractJsonText: input must be a string.');\n }\n const stripped = stripBom(text).trim();\n if (stripped.length === 0) {\n return fail('extractJsonText: input is empty.');\n }\n\n const fenced = FENCED_BLOCK.exec(stripped);\n const candidate = fenced ? fenced[1].trim() : stripped;\n\n if (candidate.length === 0) {\n return fail('extractJsonText: no JSON content found.');\n }\n\n // Whole-candidate primitive check runs before the brace scan so that a\n // valid JSON string containing braces (e.g. `\"text with { }\"`) is returned\n // intact instead of being mangled into the first balanced `{ }` match.\n if (JSON_KEYWORD.test(candidate) || JSON_NUMBER.test(candidate) || JSON_STRING.test(candidate)) {\n return succeed(candidate);\n }\n\n const balanced = findBalancedJsonSubstring(candidate);\n if (balanced !== undefined) {\n return succeed(balanced);\n }\n\n return fail('extractJsonText: no JSON-shaped substring found.');\n};\n\n/**\n * Options shared by every {@link AiAssist.fencedStringifiedJson} call.\n * @public\n */\nexport interface IFencedStringifiedJsonExtractorOptions {\n /**\n * Optional pre-parse extractor. Defaults to {@link AiAssist.extractJsonText}.\n * Provide a custom extractor to handle response shapes the default does not\n * understand.\n */\n readonly extractor?: JsonTextExtractor;\n}\n\n/**\n * Options for the validating overload of {@link AiAssist.fencedStringifiedJson}.\n * `inner` is required so the typed `Converter<T>` return value can never lie\n * about the runtime shape.\n * @public\n */\nexport interface IFencedStringifiedJsonOptions<T> extends IFencedStringifiedJsonExtractorOptions {\n /** Inner converter or validator applied to the parsed JSON value. */\n readonly inner: Converter<T> | Validator<T>;\n}\n\n/**\n * Creates a `Converter` that accepts raw LLM response text, runs it through a\n * tolerant extractor (default: {@link AiAssist.extractJsonText}), parses the\n * extracted substring as JSON, and applies an optional inner converter or\n * validator.\n *\n * @example\n * ```ts\n * const converter = fencedStringifiedJson({ inner: myShapeConverter });\n * const result = converter.convert(llmText); // Result<MyShape>\n * ```\n *\n * @param options - Optional extractor; omit to keep the default. Without an\n * `inner` step, the converter resolves to the parsed `JsonValue`.\n * @returns A `Converter<JsonValue>`.\n * @public\n */\nexport function fencedStringifiedJson(options?: IFencedStringifiedJsonExtractorOptions): Converter<JsonValue>;\n/**\n * Creates a `Converter` that accepts raw LLM response text, runs it through a\n * tolerant extractor (default: {@link AiAssist.extractJsonText}), parses the\n * extracted substring as JSON, and applies the supplied inner converter or\n * validator.\n *\n * @param options - Required `inner` converter/validator and optional extractor.\n * @returns A `Converter<T>`.\n * @public\n */\nexport function fencedStringifiedJson<T>(options: IFencedStringifiedJsonOptions<T>): Converter<T>;\nexport function fencedStringifiedJson<T>(\n options?: IFencedStringifiedJsonExtractorOptions | IFencedStringifiedJsonOptions<T>\n): Converter<T | JsonValue> {\n const extractor: JsonTextExtractor = options?.extractor ?? extractJsonText;\n const inner = (options as IFencedStringifiedJsonOptions<T> | undefined)?.inner;\n const parser: Converter<T | JsonValue> =\n inner !== undefined ? JsonBaseConverters.stringifiedJson<T>(inner) : JsonBaseConverters.stringifiedJson();\n\n return new Conversion.BaseConverter<T | JsonValue>((from: unknown): Result<T | JsonValue> => {\n if (typeof from !== 'string') {\n return fail('fencedStringifiedJson: input must be a string.');\n }\n return extractor(from).onSuccess((extracted) => parser.convert(extracted));\n });\n}\n"]}
|
|
@@ -469,6 +469,68 @@ export class KeyStore {
|
|
|
469
469
|
}
|
|
470
470
|
});
|
|
471
471
|
}
|
|
472
|
+
/**
|
|
473
|
+
* Verifies that a candidate password derives the same key material currently
|
|
474
|
+
* stored under `name`, using the supplied
|
|
475
|
+
* {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.
|
|
476
|
+
*
|
|
477
|
+
* The keystore does not persist per-slot key derivation parameters with the
|
|
478
|
+
* entry — callers receive them from `addSecretFromPassword` and store them
|
|
479
|
+
* alongside the encrypted artifact (or wherever else makes sense). Pass
|
|
480
|
+
* those same parameters here for verification.
|
|
481
|
+
*
|
|
482
|
+
* Re-derives a key from `password` + `keyDerivation`, then compares it to
|
|
483
|
+
* the stored key material in constant time. Restricted to entries of type
|
|
484
|
+
* `'encryption-key'` — the type produced by `addSecretFromPassword`. Other
|
|
485
|
+
* symmetric types (`'api-key'`) and asymmetric entries are rejected so
|
|
486
|
+
* the boolean result reflects "this slot accepts this password" rather
|
|
487
|
+
* than an incidental byte-equality match against unrelated material.
|
|
488
|
+
*
|
|
489
|
+
* Note: the keystore does not currently flag whether an `'encryption-key'`
|
|
490
|
+
* entry was actually password-derived (vs. random via `addSecret` or raw
|
|
491
|
+
* via `importSecret`). A `true` result therefore means "the candidate
|
|
492
|
+
* password produces the same 32 bytes currently stored", which is what
|
|
493
|
+
* the equivalent consumer-side helper (`verifyGatePassword`) already
|
|
494
|
+
* implies for entries it manages.
|
|
495
|
+
*
|
|
496
|
+
* @param name - Name of the secret to verify against
|
|
497
|
+
* @param password - Candidate password to test
|
|
498
|
+
* @param keyDerivation - The key derivation parameters returned by
|
|
499
|
+
* `addSecretFromPassword` when the secret was created. Only
|
|
500
|
+
* `kdf: 'pbkdf2'` is supported.
|
|
501
|
+
* @returns Success(true) when the candidate matches the stored key,
|
|
502
|
+
* Success(false) when it does not, Failure if locked, secret missing,
|
|
503
|
+
* wrong type, unsupported `kdf`, or key derivation fails
|
|
504
|
+
* @public
|
|
505
|
+
*/
|
|
506
|
+
async verifySecretFromPassword(name, password, keyDerivation) {
|
|
507
|
+
if (!this._secrets) {
|
|
508
|
+
return fail('Key store is locked');
|
|
509
|
+
}
|
|
510
|
+
if (!password || password.length === 0) {
|
|
511
|
+
return fail('Password cannot be empty');
|
|
512
|
+
}
|
|
513
|
+
if (keyDerivation.kdf !== 'pbkdf2') {
|
|
514
|
+
return fail(`Unsupported kdf '${keyDerivation.kdf}' (expected 'pbkdf2')`);
|
|
515
|
+
}
|
|
516
|
+
const entry = this._secrets.get(name);
|
|
517
|
+
if (!entry) {
|
|
518
|
+
return fail(`Secret '${name}' not found`);
|
|
519
|
+
}
|
|
520
|
+
if (entry.type !== 'encryption-key') {
|
|
521
|
+
return fail(`Secret '${name}' is not a password-verifiable encryption key (type: ${entry.type})`);
|
|
522
|
+
}
|
|
523
|
+
const saltResult = this._cryptoProvider.fromBase64(keyDerivation.salt);
|
|
524
|
+
if (saltResult.isFailure()) {
|
|
525
|
+
return fail(`Invalid salt: ${saltResult.message}`);
|
|
526
|
+
}
|
|
527
|
+
const derivedResult = await this._cryptoProvider.deriveKey(password, saltResult.value, keyDerivation.iterations);
|
|
528
|
+
/* c8 ignore next 3 - crypto provider errors covered in nodeCryptoProvider tests */
|
|
529
|
+
if (derivedResult.isFailure()) {
|
|
530
|
+
return fail(`Key derivation failed: ${derivedResult.message}`);
|
|
531
|
+
}
|
|
532
|
+
return succeed(KeyStore._timingSafeEqual(derivedResult.value, entry.key));
|
|
533
|
+
}
|
|
472
534
|
/**
|
|
473
535
|
* Removes a secret by name. Vault-first: the in-memory vault entry is dropped
|
|
474
536
|
* before any storage cleanup runs. For asymmetric-keypair entries, best-effort
|
|
@@ -1049,6 +1111,25 @@ export class KeyStore {
|
|
|
1049
1111
|
entry.key.fill(0);
|
|
1050
1112
|
return undefined;
|
|
1051
1113
|
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Constant-time byte comparison. Returns false immediately for length
|
|
1116
|
+
* mismatch (length is not secret); for equal-length inputs, walks the full
|
|
1117
|
+
* buffer accumulating differences via XOR so the running time does not leak
|
|
1118
|
+
* the position of the first differing byte.
|
|
1119
|
+
*/
|
|
1120
|
+
static _timingSafeEqual(a, b) {
|
|
1121
|
+
/* c8 ignore next 3 - defensive: callers in this class only compare
|
|
1122
|
+
PBKDF2-derived 32-byte keys against encryption-key entries (also 32 bytes) */
|
|
1123
|
+
if (a.length !== b.length) {
|
|
1124
|
+
return false;
|
|
1125
|
+
}
|
|
1126
|
+
let diff = 0;
|
|
1127
|
+
for (let i = 0; i < a.length; i++) {
|
|
1128
|
+
// eslint-disable-next-line no-bitwise
|
|
1129
|
+
diff |= a[i] ^ b[i];
|
|
1130
|
+
}
|
|
1131
|
+
return diff === 0;
|
|
1132
|
+
}
|
|
1052
1133
|
/**
|
|
1053
1134
|
* Mints a fresh UUID v4 storage handle using the crypto provider's
|
|
1054
1135
|
* {@link CryptoUtils.ICryptoProvider.generateRandomBytes | generateRandomBytes}.
|