@fgv/ts-extras 5.1.0-15 → 5.1.0-17

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 (53) 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/keystore/keyStore.js +74 -42
  17. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  18. package/dist/ts-extras.d.ts +531 -5
  19. package/lib/index.browser.d.ts +2 -1
  20. package/lib/index.browser.js +3 -1
  21. package/lib/packlets/ai-assist/apiClient.d.ts +103 -1
  22. package/lib/packlets/ai-assist/apiClient.js +574 -58
  23. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +89 -0
  24. package/lib/packlets/ai-assist/chatRequestBuilders.js +189 -0
  25. package/lib/packlets/ai-assist/index.d.ts +4 -3
  26. package/lib/packlets/ai-assist/index.js +10 -1
  27. package/lib/packlets/ai-assist/model.d.ts +271 -2
  28. package/lib/packlets/ai-assist/model.js +21 -3
  29. package/lib/packlets/ai-assist/registry.d.ts +10 -1
  30. package/lib/packlets/ai-assist/registry.js +67 -11
  31. package/lib/packlets/ai-assist/sseParser.d.ts +45 -0
  32. package/lib/packlets/ai-assist/sseParser.js +127 -0
  33. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +18 -0
  34. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +195 -0
  35. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +71 -0
  36. package/lib/packlets/ai-assist/streamingAdapters/common.js +81 -0
  37. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +19 -0
  38. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +163 -0
  39. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +18 -0
  40. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +152 -0
  41. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +19 -0
  42. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +166 -0
  43. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +34 -0
  44. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +160 -0
  45. package/lib/packlets/ai-assist/streamingClient.d.ts +33 -0
  46. package/lib/packlets/ai-assist/streamingClient.js +93 -0
  47. package/lib/packlets/conversion/converters.d.ts +1 -1
  48. package/lib/packlets/conversion/converters.js +1 -1
  49. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +19 -0
  50. package/lib/packlets/crypto-utils/keystore/keyStore.js +74 -42
  51. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +2 -2
  52. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  53. 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') {
@@ -584,49 +584,29 @@ export class KeyStore {
584
584
  if (keyResult.isFailure()) {
585
585
  return fail(`Key derivation failed: ${keyResult.message}`);
586
586
  }
587
- // Build vault contents
588
- const secrets = {};
589
- for (const [name, entry] of this._secrets) {
590
- secrets[name] = {
591
- name: entry.name,
592
- type: entry.type,
593
- key: this._cryptoProvider.toBase64(entry.key),
594
- description: entry.description,
595
- createdAt: entry.createdAt
596
- };
597
- }
598
- const vaultContents = {
599
- version: KEYSTORE_FORMAT,
600
- secrets
601
- };
602
- // Serialize and encrypt
603
- const jsonResult = captureResult(() => JSON.stringify(vaultContents));
604
- /* c8 ignore next 3 - error path tested but coverage intermittently missed */
605
- if (jsonResult.isFailure()) {
606
- return fail(`Failed to serialize vault: ${jsonResult.message}`);
587
+ return this._encryptVault(keyResult.value);
588
+ }
589
+ /**
590
+ * Saves the key store using a pre-derived key, bypassing PBKDF2 key
591
+ * derivation. Use this when the derived key has been stored externally
592
+ * (e.g., in another key store) and the original password is no longer
593
+ * available.
594
+ *
595
+ * The supplied key must be the same key that was (or would be) derived
596
+ * from the master password using the key store's PBKDF2 parameters.
597
+ *
598
+ * @param derivedKey - The pre-derived master key (32 bytes for AES-256)
599
+ * @returns Success with IKeyStoreFile, Failure if locked or key invalid
600
+ * @public
601
+ */
602
+ async saveWithKey(derivedKey) {
603
+ if (!this._secrets || !this._salt) {
604
+ return fail('Key store is locked');
607
605
  }
608
- const encryptResult = await this._cryptoProvider.encrypt(jsonResult.value, keyResult.value);
609
- /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */
610
- if (encryptResult.isFailure()) {
611
- return fail(`Encryption failed: ${encryptResult.message}`);
606
+ if (derivedKey.length !== Constants.AES_256_KEY_SIZE) {
607
+ return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${derivedKey.length}`);
612
608
  }
613
- const { iv, authTag, encryptedData } = encryptResult.value;
614
- const keystoreFileData = {
615
- format: KEYSTORE_FORMAT,
616
- algorithm: Constants.DEFAULT_ALGORITHM,
617
- iv: this._cryptoProvider.toBase64(iv),
618
- authTag: this._cryptoProvider.toBase64(authTag),
619
- encryptedData: this._cryptoProvider.toBase64(encryptedData),
620
- keyDerivation: {
621
- kdf: 'pbkdf2',
622
- salt: this._cryptoProvider.toBase64(this._salt),
623
- iterations: this._iterations
624
- }
625
- };
626
- this._keystoreFile = keystoreFileData;
627
- this._dirty = false;
628
- this._isNew = false;
629
- return succeed(keystoreFileData);
609
+ return this._encryptVault(derivedKey);
630
610
  }
631
611
  /**
632
612
  * Changes the master password.
@@ -741,8 +721,60 @@ export class KeyStore {
741
721
  });
742
722
  }
743
723
  // ============================================================================
744
- // Private: Vault Decryption
724
+ // Private: Vault Encryption / Decryption
745
725
  // ============================================================================
726
+ /**
727
+ * Encrypts the vault with a derived key and returns the key store file.
728
+ * Shared by `save()` and `saveWithKey()`.
729
+ */
730
+ async _encryptVault(derivedKey) {
731
+ // _secrets and _salt are guaranteed non-undefined by callers
732
+ const secrets = this._secrets;
733
+ const salt = this._salt;
734
+ // Build vault contents
735
+ const secretEntries = {};
736
+ for (const [name, entry] of secrets) {
737
+ secretEntries[name] = {
738
+ name: entry.name,
739
+ type: entry.type,
740
+ key: this._cryptoProvider.toBase64(entry.key),
741
+ description: entry.description,
742
+ createdAt: entry.createdAt
743
+ };
744
+ }
745
+ const vaultContents = {
746
+ version: KEYSTORE_FORMAT,
747
+ secrets: secretEntries
748
+ };
749
+ // Serialize and encrypt
750
+ const jsonResult = captureResult(() => JSON.stringify(vaultContents));
751
+ /* c8 ignore next 3 - error path tested but coverage intermittently missed */
752
+ if (jsonResult.isFailure()) {
753
+ return fail(`Failed to serialize vault: ${jsonResult.message}`);
754
+ }
755
+ const encryptResult = await this._cryptoProvider.encrypt(jsonResult.value, derivedKey);
756
+ /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */
757
+ if (encryptResult.isFailure()) {
758
+ return fail(`Encryption failed: ${encryptResult.message}`);
759
+ }
760
+ const { iv, authTag, encryptedData } = encryptResult.value;
761
+ const keystoreFileData = {
762
+ format: KEYSTORE_FORMAT,
763
+ algorithm: Constants.DEFAULT_ALGORITHM,
764
+ iv: this._cryptoProvider.toBase64(iv),
765
+ authTag: this._cryptoProvider.toBase64(authTag),
766
+ encryptedData: this._cryptoProvider.toBase64(encryptedData),
767
+ keyDerivation: {
768
+ kdf: 'pbkdf2',
769
+ salt: this._cryptoProvider.toBase64(salt),
770
+ iterations: this._iterations
771
+ }
772
+ };
773
+ this._keystoreFile = keystoreFileData;
774
+ this._dirty = false;
775
+ this._isNew = false;
776
+ return succeed(keystoreFileData);
777
+ }
746
778
  /**
747
779
  * Decrypts the vault with a derived key and loads secrets into memory.
748
780
  * Shared by `unlock()` and `unlockWithKey()`.
@@ -144,8 +144,8 @@ export class ZipFileTreeAccessors {
144
144
  }
145
145
  /**
146
146
  * Default function to infer the content type of a file.
147
- * @param filePath - The path of the file.
148
- * @param provided - Optional supplied content type.
147
+ * @param __filePath - The path of the file.
148
+ * @param __provided - Optional supplied content type.
149
149
  * @returns `Success` with the content type of the file if successful, or
150
150
  * `Failure` with an error message otherwise.
151
151
  * @remarks This default implementation always returns `Success` with `undefined`.