@fgv/ts-extras 5.1.0-16 → 5.1.0-18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/index.browser.js +2 -1
  2. package/dist/packlets/ai-assist/apiClient.js +570 -58
  3. package/dist/packlets/ai-assist/chatRequestBuilders.js +180 -0
  4. package/dist/packlets/ai-assist/index.js +4 -3
  5. package/dist/packlets/ai-assist/model.js +20 -3
  6. package/dist/packlets/ai-assist/registry.js +66 -10
  7. package/dist/packlets/ai-assist/sseParser.js +122 -0
  8. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +192 -0
  9. package/dist/packlets/ai-assist/streamingAdapters/common.js +77 -0
  10. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +160 -0
  11. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +149 -0
  12. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +163 -0
  13. package/dist/packlets/ai-assist/streamingAdapters/proxy.js +157 -0
  14. package/dist/packlets/ai-assist/streamingClient.js +88 -0
  15. package/dist/packlets/conversion/converters.js +1 -1
  16. package/dist/packlets/crypto-utils/index.browser.js +2 -0
  17. package/dist/packlets/crypto-utils/index.js +2 -0
  18. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +47 -0
  19. package/dist/packlets/crypto-utils/keystore/converters.js +101 -9
  20. package/dist/packlets/crypto-utils/keystore/index.js +1 -0
  21. package/dist/packlets/crypto-utils/keystore/keyStore.js +271 -46
  22. package/dist/packlets/crypto-utils/keystore/model.js +22 -1
  23. package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js +21 -0
  24. package/dist/packlets/crypto-utils/model.js +5 -0
  25. package/dist/packlets/crypto-utils/nodeCryptoProvider.js +44 -1
  26. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  27. package/dist/test/unit/crypto/keystore/inMemoryPrivateKeyStorage.js +78 -0
  28. package/dist/ts-extras.d.ts +1089 -37
  29. package/lib/index.browser.d.ts +2 -1
  30. package/lib/index.browser.js +3 -1
  31. package/lib/packlets/ai-assist/apiClient.d.ts +103 -1
  32. package/lib/packlets/ai-assist/apiClient.js +574 -58
  33. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +89 -0
  34. package/lib/packlets/ai-assist/chatRequestBuilders.js +189 -0
  35. package/lib/packlets/ai-assist/index.d.ts +4 -3
  36. package/lib/packlets/ai-assist/index.js +10 -1
  37. package/lib/packlets/ai-assist/model.d.ts +271 -2
  38. package/lib/packlets/ai-assist/model.js +21 -3
  39. package/lib/packlets/ai-assist/registry.d.ts +10 -1
  40. package/lib/packlets/ai-assist/registry.js +67 -11
  41. package/lib/packlets/ai-assist/sseParser.d.ts +45 -0
  42. package/lib/packlets/ai-assist/sseParser.js +127 -0
  43. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +18 -0
  44. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +195 -0
  45. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +71 -0
  46. package/lib/packlets/ai-assist/streamingAdapters/common.js +81 -0
  47. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +19 -0
  48. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +163 -0
  49. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +18 -0
  50. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +152 -0
  51. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +19 -0
  52. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +166 -0
  53. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +34 -0
  54. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +160 -0
  55. package/lib/packlets/ai-assist/streamingClient.d.ts +33 -0
  56. package/lib/packlets/ai-assist/streamingClient.js +93 -0
  57. package/lib/packlets/conversion/converters.d.ts +1 -1
  58. package/lib/packlets/conversion/converters.js +1 -1
  59. package/lib/packlets/crypto-utils/index.browser.d.ts +1 -0
  60. package/lib/packlets/crypto-utils/index.browser.js +4 -1
  61. package/lib/packlets/crypto-utils/index.d.ts +1 -0
  62. package/lib/packlets/crypto-utils/index.js +4 -1
  63. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +39 -0
  64. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +50 -0
  65. package/lib/packlets/crypto-utils/keystore/converters.d.ts +68 -6
  66. package/lib/packlets/crypto-utils/keystore/converters.js +100 -8
  67. package/lib/packlets/crypto-utils/keystore/index.d.ts +1 -0
  68. package/lib/packlets/crypto-utils/keystore/index.js +1 -0
  69. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +77 -9
  70. package/lib/packlets/crypto-utils/keystore/keyStore.js +271 -46
  71. package/lib/packlets/crypto-utils/keystore/model.d.ts +238 -19
  72. package/lib/packlets/crypto-utils/keystore/model.js +24 -2
  73. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts +50 -0
  74. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js +22 -0
  75. package/lib/packlets/crypto-utils/model.d.ts +38 -0
  76. package/lib/packlets/crypto-utils/model.js +6 -1
  77. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +26 -1
  78. package/lib/packlets/crypto-utils/nodeCryptoProvider.js +43 -0
  79. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +2 -2
  80. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  81. package/package.json +7 -7
@@ -0,0 +1,163 @@
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 __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
21
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
22
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
23
+ var m = o[Symbol.asyncIterator], i;
24
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
25
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
26
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
27
+ };
28
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
29
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
30
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
31
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
32
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
33
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
34
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
35
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
36
+ function fulfill(value) { resume("next", value); }
37
+ function reject(value) { resume("throw", value); }
38
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
39
+ };
40
+ /**
41
+ * Streaming adapter for the OpenAI / xAI Responses API. This is the format
42
+ * used when server-side tools (e.g. web_search) are requested — Chat
43
+ * Completions doesn't support tool progress events, but the Responses API
44
+ * does.
45
+ *
46
+ * @packageDocumentation
47
+ */
48
+ import { succeed, Validators } from '@fgv/ts-utils';
49
+ import { buildMessages, buildOpenAiResponsesUserContent } from '../chatRequestBuilders';
50
+ import { parseSseEventJson, readSseEvents } from '../sseParser';
51
+ import { toResponsesApiTools } from '../toolFormats';
52
+ import { openSseConnection, validateEventPayload } from './common';
53
+ const responsesDeltaPayload = Validators.object({
54
+ delta: Validators.string
55
+ });
56
+ const responsesCompletedPayload = Validators.object({
57
+ response: Validators.object({ status: Validators.string.optional() }, { options: { optionalFields: ['status'] } })
58
+ });
59
+ const responsesErrorInner = Validators.object({ message: Validators.string.optional() }, { options: { optionalFields: ['message'] } });
60
+ const responsesErrorPayload = Validators.object({
61
+ error: responsesErrorInner.optional(),
62
+ message: Validators.string.optional()
63
+ }, { options: { optionalFields: ['error', 'message'] } });
64
+ // ============================================================================
65
+ // Stream translator
66
+ // ============================================================================
67
+ /**
68
+ * Translates an OpenAI Responses API SSE stream into unified events.
69
+ *
70
+ * @internal
71
+ */
72
+ function translateOpenAiResponsesStream(response) {
73
+ return __asyncGenerator(this, arguments, function* translateOpenAiResponsesStream_1() {
74
+ var _a, e_1, _b, _c;
75
+ var _d, _e, _f;
76
+ let fullText = '';
77
+ let truncated = false;
78
+ let completed = false;
79
+ try {
80
+ /* c8 ignore next - body is non-null at this point per openSseConnection */
81
+ if (!response.body)
82
+ return yield __await(void 0);
83
+ try {
84
+ for (var _g = true, _h = __asyncValues(readSseEvents(response.body)), _j; _j = yield __await(_h.next()), _a = _j.done, !_a; _g = true) {
85
+ _c = _j.value;
86
+ _g = false;
87
+ const message = _c;
88
+ const eventName = message.event;
89
+ if (eventName === 'response.output_text.delta') {
90
+ const payload = validateEventPayload(parseSseEventJson(message.data), responsesDeltaPayload);
91
+ const delta = payload === null || payload === void 0 ? void 0 : payload.delta;
92
+ if (typeof delta === 'string' && delta.length > 0) {
93
+ fullText += delta;
94
+ yield yield __await({ type: 'text-delta', delta });
95
+ }
96
+ }
97
+ else if (eventName === 'response.web_search_call.in_progress') {
98
+ yield yield __await({ type: 'tool-event', toolType: 'web_search', phase: 'started' });
99
+ }
100
+ else if (eventName === 'response.web_search_call.completed') {
101
+ yield yield __await({ type: 'tool-event', toolType: 'web_search', phase: 'completed' });
102
+ }
103
+ else if (eventName === 'response.completed') {
104
+ const payload = validateEventPayload(parseSseEventJson(message.data), responsesCompletedPayload);
105
+ truncated = (payload === null || payload === void 0 ? void 0 : payload.response.status) === 'incomplete';
106
+ completed = true;
107
+ }
108
+ else if (eventName === 'response.failed' || eventName === 'error') {
109
+ const payload = validateEventPayload(parseSseEventJson(message.data), responsesErrorPayload);
110
+ const errMsg = (_f = (_e = (_d = payload === null || payload === void 0 ? void 0 : payload.error) === null || _d === void 0 ? void 0 : _d.message) !== null && _e !== void 0 ? _e : payload === null || payload === void 0 ? void 0 : payload.message) !== null && _f !== void 0 ? _f : 'Responses API stream failed';
111
+ yield yield __await({ type: 'error', message: errMsg });
112
+ return yield __await(void 0);
113
+ }
114
+ }
115
+ }
116
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
117
+ finally {
118
+ try {
119
+ if (!_g && !_a && (_b = _h.return)) yield __await(_b.call(_h));
120
+ }
121
+ finally { if (e_1) throw e_1.error; }
122
+ }
123
+ }
124
+ catch (err) {
125
+ yield yield __await({ type: 'error', message: err instanceof Error ? err.message : String(err) });
126
+ return yield __await(void 0);
127
+ }
128
+ if (completed) {
129
+ yield yield __await({ type: 'done', truncated, fullText });
130
+ }
131
+ else {
132
+ yield yield __await({ type: 'error', message: 'Responses API stream ended without a completed event' });
133
+ }
134
+ });
135
+ }
136
+ // ============================================================================
137
+ // Per-format request caller
138
+ // ============================================================================
139
+ /**
140
+ * Issues a streaming Responses API request (with tools) and returns the
141
+ * unified-event iterable on success.
142
+ *
143
+ * @internal
144
+ */
145
+ export async function callOpenAiResponsesStream(config, prompt, tools, messagesBefore, temperature, logger, signal) {
146
+ const url = `${config.baseUrl}/responses`;
147
+ const input = buildMessages(prompt.system, buildOpenAiResponsesUserContent(prompt), {
148
+ head: messagesBefore
149
+ });
150
+ const body = {
151
+ model: config.model,
152
+ input,
153
+ tools: toResponsesApiTools(tools),
154
+ temperature,
155
+ stream: true
156
+ };
157
+ const headers = { Authorization: `Bearer ${config.apiKey}` };
158
+ /* c8 ignore next 1 - optional logger */
159
+ logger === null || logger === void 0 ? void 0 : logger.info(`OpenAI Responses streaming: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);
160
+ const conn = await openSseConnection(url, headers, body, logger, signal);
161
+ return conn.onSuccess((response) => succeed(translateOpenAiResponsesStream(response)));
162
+ }
163
+ //# sourceMappingURL=openaiResponses.js.map
@@ -0,0 +1,157 @@
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 __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
21
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
22
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
23
+ var m = o[Symbol.asyncIterator], i;
24
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
25
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
26
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
27
+ };
28
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
29
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
30
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
31
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
32
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
33
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
34
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
35
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
36
+ function fulfill(value) { resume("next", value); }
37
+ function reject(value) { resume("throw", value); }
38
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
39
+ };
40
+ /**
41
+ * Streaming adapter for a caller-provided proxy server. Unlike the
42
+ * provider-specific adapters, the proxy speaks our own unified vocabulary
43
+ * directly: each `data:` line is a JSON-serialized {@link AiAssist.IAiStreamEvent},
44
+ * so this adapter only validates the event-type discriminator and forwards.
45
+ *
46
+ * @packageDocumentation
47
+ */
48
+ import { succeed, Validators } from '@fgv/ts-utils';
49
+ import { parseSseEventJson, readSseEvents } from '../sseParser';
50
+ import { openSseConnection, validateEventPayload } from './common';
51
+ const proxyEventTypes = ['text-delta', 'tool-event', 'done', 'error'];
52
+ const proxyEventEnvelope = Validators.object({
53
+ type: Validators.enumeratedValue(proxyEventTypes)
54
+ });
55
+ // ============================================================================
56
+ // Stream translator
57
+ // ============================================================================
58
+ /**
59
+ * Translates a proxied SSE stream back into {@link AiAssist.IAiStreamEvent} objects.
60
+ * Validation is limited to the type discriminator; the proxy is contractually
61
+ * required to emit shape-correct unified events.
62
+ *
63
+ * @internal
64
+ */
65
+ function translateProxyStream(response) {
66
+ return __asyncGenerator(this, arguments, function* translateProxyStream_1() {
67
+ var _a, e_1, _b, _c;
68
+ try {
69
+ /* c8 ignore next - body is non-null at this point per openSseConnection */
70
+ if (!response.body)
71
+ return yield __await(void 0);
72
+ try {
73
+ for (var _d = true, _e = __asyncValues(readSseEvents(response.body)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
74
+ _c = _f.value;
75
+ _d = false;
76
+ const message = _c;
77
+ const json = parseSseEventJson(message.data);
78
+ if (json === undefined) {
79
+ continue;
80
+ }
81
+ const envelope = validateEventPayload(json, proxyEventEnvelope);
82
+ if (!envelope) {
83
+ continue;
84
+ }
85
+ const event = json;
86
+ yield yield __await(event);
87
+ if (envelope.type === 'done' || envelope.type === 'error') {
88
+ return yield __await(void 0);
89
+ }
90
+ }
91
+ }
92
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
93
+ finally {
94
+ try {
95
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
96
+ }
97
+ finally { if (e_1) throw e_1.error; }
98
+ }
99
+ }
100
+ catch (err) {
101
+ yield yield __await({ type: 'error', message: err instanceof Error ? err.message : String(err) });
102
+ }
103
+ });
104
+ }
105
+ // ============================================================================
106
+ // Public entry point
107
+ // ============================================================================
108
+ /**
109
+ * Calls the streaming chat endpoint on a proxy server instead of calling
110
+ * the provider directly from the browser.
111
+ *
112
+ * @remarks
113
+ * Proxy contract:
114
+ * - Endpoint: `POST ${proxyUrl}/api/ai/completion-stream`
115
+ * - Request body: same JSON as `/api/ai/completion` plus `"stream": true`
116
+ * - Response: `Content-Type: text/event-stream`; body is the unified
117
+ * {@link AiAssist.IAiStreamEvent} JSON-serialized one event per SSE `data:` line
118
+ * (no `event:` line needed since the type discriminator is in the JSON).
119
+ * - Error response (when the proxy can't even start): JSON `{error: string}`
120
+ * with a non-2xx status, surfaced as `proxy: ${error}`.
121
+ *
122
+ * The proxy server is responsible for opening the upstream SSE connection,
123
+ * translating provider-native events to the unified vocabulary, and
124
+ * forwarding events as they arrive (no buffering). The library does not
125
+ * ship a proxy implementation.
126
+ *
127
+ * @public
128
+ */
129
+ export async function callProxiedCompletionStream(proxyUrl, params) {
130
+ const { descriptor, apiKey, prompt, messagesBefore, temperature, modelOverride, logger, tools, signal } = params;
131
+ const promptBody = { system: prompt.system, user: prompt.user };
132
+ if (prompt.attachments.length > 0) {
133
+ promptBody.attachments = prompt.attachments;
134
+ }
135
+ const body = {
136
+ providerId: descriptor.id,
137
+ apiKey,
138
+ prompt: promptBody,
139
+ temperature: temperature !== null && temperature !== void 0 ? temperature : 0.7,
140
+ stream: true
141
+ };
142
+ if (messagesBefore && messagesBefore.length > 0) {
143
+ body.messagesBefore = messagesBefore;
144
+ }
145
+ if (modelOverride !== undefined) {
146
+ body.modelOverride = modelOverride;
147
+ }
148
+ if (tools && tools.length > 0) {
149
+ body.tools = tools;
150
+ }
151
+ /* c8 ignore next 1 - optional logger */
152
+ logger === null || logger === void 0 ? void 0 : logger.info(`AI streaming proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);
153
+ const url = `${proxyUrl}/api/ai/completion-stream`;
154
+ const conn = await openSseConnection(url, {}, body, logger, signal);
155
+ return conn.onSuccess((response) => succeed(translateProxyStream(response)));
156
+ }
157
+ //# sourceMappingURL=proxy.js.map
@@ -0,0 +1,88 @@
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
+ * Streaming chat completion client. Public façade over the per-format
22
+ * adapters under `streamingAdapters/`: provider dispatch and pre-flight
23
+ * validation live here; format-specific request/translation logic and the
24
+ * typed event-payload validators live with each adapter.
25
+ *
26
+ * @packageDocumentation
27
+ */
28
+ import { fail } from '@fgv/ts-utils';
29
+ import { resolveModel } from './model';
30
+ import { callAnthropicStream } from './streamingAdapters/anthropic';
31
+ import { callGeminiStream } from './streamingAdapters/gemini';
32
+ import { callOpenAiChatStream } from './streamingAdapters/openaiChat';
33
+ import { callOpenAiResponsesStream } from './streamingAdapters/openaiResponses';
34
+ export { callProxiedCompletionStream } from './streamingAdapters/proxy';
35
+ /**
36
+ * Calls the appropriate streaming chat completion API for a given provider.
37
+ *
38
+ * @remarks
39
+ * Pre-flight rejection: when `descriptor.streamingCorsRestricted === true`
40
+ * and the call isn't being routed through a proxy, this returns
41
+ * `Result.fail` before fetch is invoked. Callers should route through
42
+ * {@link AiAssist.callProxiedCompletionStream} or surface the failure to the user.
43
+ *
44
+ * Connection-time failures (auth, network, non-2xx) surface as the outer
45
+ * `Result.fail`. Once iteration begins, errors mid-stream surface as a
46
+ * terminal error event ({@link AiAssist.IAiStreamError}) followed by the iterable
47
+ * ending. The final successful event is {@link AiAssist.IAiStreamDone}.
48
+ *
49
+ * @param params - Request parameters including descriptor, API key, prompt, and optional tools
50
+ * @returns A streaming iterable of unified events, or a Result.fail
51
+ * @public
52
+ */
53
+ export async function callProviderCompletionStream(params) {
54
+ const { descriptor, apiKey, prompt, messagesBefore, temperature = 0.7, modelOverride, logger, tools, signal } = params;
55
+ if (!descriptor.baseUrl) {
56
+ return fail(`provider "${descriptor.id}" has no API endpoint configured`);
57
+ }
58
+ if (descriptor.streamingCorsRestricted) {
59
+ return fail(`provider "${descriptor.id}" requires a proxy for streaming; none is configured`);
60
+ }
61
+ if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {
62
+ return fail(`provider "${descriptor.id}" does not accept image input`);
63
+ }
64
+ const hasTools = tools !== undefined && tools.length > 0;
65
+ const modelContext = hasTools ? 'tools' : undefined;
66
+ const config = {
67
+ baseUrl: descriptor.baseUrl,
68
+ apiKey,
69
+ model: resolveModel(modelOverride !== null && modelOverride !== void 0 ? modelOverride : descriptor.defaultModel, modelContext)
70
+ };
71
+ switch (descriptor.apiFormat) {
72
+ case 'openai':
73
+ if (hasTools) {
74
+ return callOpenAiResponsesStream(config, prompt, tools, messagesBefore, temperature, logger, signal);
75
+ }
76
+ return callOpenAiChatStream(config, prompt, messagesBefore, temperature, logger, signal);
77
+ case 'anthropic':
78
+ return callAnthropicStream(config, prompt, messagesBefore, temperature, tools, logger, signal);
79
+ case 'gemini':
80
+ return callGeminiStream(config, prompt, messagesBefore, temperature, tools, logger, signal);
81
+ /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
82
+ default: {
83
+ const _exhaustive = descriptor.apiFormat;
84
+ return fail(`unsupported API format: ${String(_exhaustive)}`);
85
+ }
86
+ }
87
+ }
88
+ //# sourceMappingURL=streamingClient.js.map
@@ -101,7 +101,7 @@ export const isoDateTime = new Conversion.BaseConverter((from) => {
101
101
  * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
102
102
  * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
103
103
  * @param converter - `Converter` used to convert each item in the array
104
- * @param ignoreErrors - Specifies treatment of unconvertible elements
104
+ * @param onError - Specifies treatment of unconvertible elements
105
105
  * @beta
106
106
  */
107
107
  export function extendedArrayOf(label, converter, onError = 'failOnError') {
@@ -34,6 +34,8 @@ import * as Converters from './converters';
34
34
  export { Converters };
35
35
  // Direct encryption provider
36
36
  export { DirectEncryptionProvider } from './directEncryptionProvider';
37
+ // WebCrypto parameter table for asymmetric keypair algorithms
38
+ export { keyPairAlgorithmParams } from './keyPairAlgorithmParams';
37
39
  // Note: NodeCryptoProvider is NOT exported in browser version
38
40
  // Use BrowserCryptoProvider from @fgv/ts-web-extras instead
39
41
  // Encrypted file helpers
@@ -34,6 +34,8 @@ import * as Converters from './converters';
34
34
  export { Converters };
35
35
  // Direct encryption provider
36
36
  export { DirectEncryptionProvider } from './directEncryptionProvider';
37
+ // WebCrypto parameter table for asymmetric keypair algorithms
38
+ export { keyPairAlgorithmParams } from './keyPairAlgorithmParams';
37
39
  // Node.js crypto provider (Node.js environment only)
38
40
  export { NodeCryptoProvider, nodeCryptoProvider } from './nodeCryptoProvider';
39
41
  // Encrypted file helpers
@@ -0,0 +1,47 @@
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
+ * Lookup table from {@link CryptoUtils.KeyPairAlgorithm} to the WebCrypto
22
+ * parameters needed to drive `crypto.subtle`. Shared between every
23
+ * {@link CryptoUtils.ICryptoProvider} implementation since both Node and
24
+ * browser providers speak the same WebCrypto API. Exposed for downstream
25
+ * provider implementations (e.g. browser-side providers in `@fgv/ts-web-extras`).
26
+ * @public
27
+ */
28
+ export const keyPairAlgorithmParams = {
29
+ 'ecdsa-p256': {
30
+ generateKey: { name: 'ECDSA', namedCurve: 'P-256' },
31
+ importPublicKey: { name: 'ECDSA', namedCurve: 'P-256' },
32
+ keyPairUsages: ['sign', 'verify'],
33
+ publicKeyUsages: ['verify']
34
+ },
35
+ 'rsa-oaep-2048': {
36
+ generateKey: {
37
+ name: 'RSA-OAEP',
38
+ modulusLength: 2048,
39
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
40
+ hash: 'SHA-256'
41
+ },
42
+ importPublicKey: { name: 'RSA-OAEP', hash: 'SHA-256' },
43
+ keyPairUsages: ['encrypt', 'decrypt'],
44
+ publicKeyUsages: ['encrypt']
45
+ }
46
+ };
47
+ //# sourceMappingURL=keyPairAlgorithmParams.js.map
@@ -17,9 +17,9 @@
17
17
  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
18
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  // SOFTWARE.
20
- import { Converters } from '@fgv/ts-utils';
20
+ import { Converters, succeed, Validators } from '@fgv/ts-utils';
21
21
  import { base64String, encryptionAlgorithm, keyDerivationParams } from '../converters';
22
- import { allKeyStoreSecretTypes, KEYSTORE_FORMAT } from './model';
22
+ import { allKeyPairAlgorithms, allKeyStoreSecretTypes, allKeyStoreSymmetricSecretTypes, KEYSTORE_FORMAT, allKeyStoreAsymmetricSecretTypes } from './model';
23
23
  // ============================================================================
24
24
  // Key Store Format Converter
25
25
  // ============================================================================
@@ -31,31 +31,123 @@ export const keystoreFormat = Converters.enumeratedValue([
31
31
  KEYSTORE_FORMAT
32
32
  ]);
33
33
  // ============================================================================
34
- // Secret Type Converter
34
+ // Secret Type Converters
35
35
  // ============================================================================
36
36
  /**
37
- * Converter for {@link CryptoUtils.KeyStore.KeyStoreSecretType | key store secret type} discriminator.
37
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreSecretType | any key store secret type} discriminator.
38
+ * Accepts both symmetric and asymmetric type values.
38
39
  * @public
39
40
  */
40
41
  export const keystoreSecretType = Converters.enumeratedValue(allKeyStoreSecretTypes);
42
+ /**
43
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreSymmetricSecretType | symmetric secret type} discriminator.
44
+ * Accepts only `'encryption-key'` and `'api-key'`.
45
+ * @public
46
+ */
47
+ export const keystoreSymmetricSecretType = Converters.enumeratedValue(allKeyStoreSymmetricSecretTypes);
48
+ /**
49
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreAsymmetricSecretType | asymmetric secret type} discriminator.
50
+ * Accepts only `'asymmetric-keypair'`.
51
+ * @public
52
+ */
53
+ export const keystoreAsymmetricSecretType = Converters.enumeratedValue(allKeyStoreAsymmetricSecretTypes);
54
+ // ============================================================================
55
+ // Key Pair Algorithm Converter
56
+ // ============================================================================
57
+ /**
58
+ * Converter for {@link CryptoUtils.KeyStore.KeyPairAlgorithm | key pair algorithm}.
59
+ * @public
60
+ */
61
+ export const keyPairAlgorithm = Converters.enumeratedValue(allKeyPairAlgorithms);
41
62
  // ============================================================================
42
- // Secret Entry Converters
63
+ // JWK Shape Validator
43
64
  // ============================================================================
44
65
  /**
45
- * Converter for {@link CryptoUtils.KeyStore.IKeyStoreSecretEntryJson | key store secret entry} in JSON format.
46
- * The `type` field is optional for backwards compatibility — missing means `'encryption-key'`.
66
+ * In-place shape check for a JSON Web Key. Asserts only that the input is a
67
+ * non-array object whose `kty` discriminator is a string; every other JWK
68
+ * field passes through untouched. This is intentionally **not** a true JWK
69
+ * validator — per-algorithm correctness (RSA `n`/`e`, EC `crv`/`x`/`y`,
70
+ * key-size constraints, etc.) is delegated to `crypto.subtle.importKey` at
71
+ * first use, which is the authoritative checker. The "shape" suffix in the
72
+ * name is the warning sign for readers expecting full validation.
73
+ * @remarks
74
+ * Built with `Validators.object` (in-place, non-strict) so unknown JWK fields
75
+ * survive the round-trip; the cast to `FieldValidators<JsonWebKey>` is required
76
+ * only because TypeScript's mapped type demands an entry for every key in
77
+ * `JsonWebKey`. At runtime the `ObjectValidator` only inspects keys present in
78
+ * the field-validators map.
47
79
  * @public
48
80
  */
49
- export const keystoreSecretEntryJson = Converters.object({
81
+ export const jsonWebKeyShape = Validators.object({
82
+ kty: Validators.string
83
+ });
84
+ // ============================================================================
85
+ // Symmetric Secret Entry Converter
86
+ // ============================================================================
87
+ /**
88
+ * Converter for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson | symmetric secret entry} in JSON form.
89
+ *
90
+ * @remarks
91
+ * Backwards compatibility with vaults written before asymmetric-keypair
92
+ * support: those entries may lack the `type` discriminator on the wire. To
93
+ * keep the model type honest (`type` is required on
94
+ * {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson}, see its docs),
95
+ * we declare `type` in `optionalFields` so the inner `Converters.object` will
96
+ * accept input without it, then `.map()` injects the default
97
+ * `'encryption-key'` when missing. The output therefore always carries the
98
+ * discriminator and downstream code never sees the legacy missing-type form.
99
+ *
100
+ * @public
101
+ */
102
+ export const keystoreSymmetricEntryJson = Converters.object({
50
103
  name: Converters.string,
51
- type: keystoreSecretType,
104
+ type: keystoreSymmetricSecretType,
52
105
  key: base64String,
53
106
  description: Converters.string,
54
107
  createdAt: Converters.string
55
108
  }, {
109
+ // `type` is optional at the input layer for legacy-vault compatibility;
110
+ // the .map() below normalizes by injecting the default.
56
111
  optionalFields: ['type', 'description']
112
+ }).map((entry) => {
113
+ var _a;
114
+ return succeed(Object.assign(Object.assign({}, entry), { type: (_a = entry.type) !== null && _a !== void 0 ? _a : 'encryption-key' }));
57
115
  });
58
116
  // ============================================================================
117
+ // Asymmetric Keypair Entry Converter
118
+ // ============================================================================
119
+ /**
120
+ * Converter for {@link CryptoUtils.KeyStore.IKeyStoreAsymmetricEntryJson | asymmetric keypair entry} in JSON form.
121
+ * The `publicKeyJwk` field passes through {@link CryptoUtils.KeyStore.Converters.jsonWebKeyShape | jsonWebKeyShape}
122
+ * (shape check only — see its docs); cryptographic correctness is enforced by
123
+ * `crypto.subtle.importKey` at use.
124
+ * @public
125
+ */
126
+ export const keystoreAsymmetricEntryJson = Converters.object({
127
+ name: Converters.string,
128
+ type: keystoreAsymmetricSecretType,
129
+ id: Converters.string,
130
+ algorithm: keyPairAlgorithm,
131
+ publicKeyJwk: jsonWebKeyShape,
132
+ description: Converters.string.optional(),
133
+ createdAt: Converters.string
134
+ });
135
+ // ============================================================================
136
+ // Discriminated-Union Entry Converter
137
+ // ============================================================================
138
+ /**
139
+ * Discriminated-union converter for any {@link CryptoUtils.KeyStore.IKeyStoreEntryJson | key store entry} in JSON form.
140
+ * Routes by the `type` field: `'asymmetric-keypair'` is parsed by
141
+ * {@link CryptoUtils.KeyStore.Converters.keystoreAsymmetricEntryJson | keystoreAsymmetricEntryJson},
142
+ * anything else (including a missing `type` field for backwards compatibility) by
143
+ * {@link CryptoUtils.KeyStore.Converters.keystoreSymmetricEntryJson | keystoreSymmetricEntryJson}.
144
+ * @public
145
+ */
146
+ export const keystoreSecretEntryJson = Converters.oneOf([
147
+ keystoreAsymmetricEntryJson,
148
+ keystoreSymmetricEntryJson
149
+ ]);
150
+ // ============================================================================
59
151
  // Vault Contents Converter
60
152
  // ============================================================================
61
153
  /**
@@ -23,6 +23,7 @@
23
23
  */
24
24
  // Types and interfaces
25
25
  export * from './model';
26
+ export * from './privateKeyStorage';
26
27
  // Converters namespace
27
28
  import * as Converters from './converters';
28
29
  export { Converters };