@fgv/ts-extras-ollama 5.1.0-34

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 (65) hide show
  1. package/.rush/temp/b70e5f6b6ada97ea70c5583027ea2b58b27bef46.tar.log +54 -0
  2. package/.rush/temp/chunked-rush-logs/ts-extras-ollama.build.chunks.jsonl +9 -0
  3. package/.rush/temp/operation/build/all.log +9 -0
  4. package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
  5. package/.rush/temp/operation/build/state.json +3 -0
  6. package/.rush/temp/shrinkwrap-deps.json +681 -0
  7. package/CHANGELOG.json +4 -0
  8. package/README.md +105 -0
  9. package/config/api-extractor.json +38 -0
  10. package/config/jest.config.json +13 -0
  11. package/config/rig.json +6 -0
  12. package/dist/index.js +388 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/test/unit/chatStructured.test.js +287 -0
  15. package/dist/test/unit/chatStructured.test.js.map +1 -0
  16. package/dist/test/unit/fixtures/wireFixtures.js +90 -0
  17. package/dist/test/unit/fixtures/wireFixtures.js.map +1 -0
  18. package/dist/test/unit/modelManagement.test.js +118 -0
  19. package/dist/test/unit/modelManagement.test.js.map +1 -0
  20. package/dist/test/unit/ollamaClient.test.js +38 -0
  21. package/dist/test/unit/ollamaClient.test.js.map +1 -0
  22. package/dist/test/unit/pullModel.test.js +202 -0
  23. package/dist/test/unit/pullModel.test.js.map +1 -0
  24. package/dist/ts-extras-ollama.d.ts +365 -0
  25. package/dist/tsdoc-metadata.json +11 -0
  26. package/eslint.config.js +15 -0
  27. package/etc/ts-extras-ollama.api.md +139 -0
  28. package/lib/index.d.ts +341 -0
  29. package/lib/index.d.ts.map +1 -0
  30. package/lib/index.js +397 -0
  31. package/lib/index.js.map +1 -0
  32. package/lib/test/unit/chatStructured.test.d.ts +2 -0
  33. package/lib/test/unit/chatStructured.test.d.ts.map +1 -0
  34. package/lib/test/unit/chatStructured.test.js +289 -0
  35. package/lib/test/unit/chatStructured.test.js.map +1 -0
  36. package/lib/test/unit/fixtures/wireFixtures.d.ts +19 -0
  37. package/lib/test/unit/fixtures/wireFixtures.d.ts.map +1 -0
  38. package/lib/test/unit/fixtures/wireFixtures.js +93 -0
  39. package/lib/test/unit/fixtures/wireFixtures.js.map +1 -0
  40. package/lib/test/unit/modelManagement.test.d.ts +2 -0
  41. package/lib/test/unit/modelManagement.test.d.ts.map +1 -0
  42. package/lib/test/unit/modelManagement.test.js +120 -0
  43. package/lib/test/unit/modelManagement.test.js.map +1 -0
  44. package/lib/test/unit/ollamaClient.test.d.ts +2 -0
  45. package/lib/test/unit/ollamaClient.test.d.ts.map +1 -0
  46. package/lib/test/unit/ollamaClient.test.js +40 -0
  47. package/lib/test/unit/ollamaClient.test.js.map +1 -0
  48. package/lib/test/unit/pullModel.test.d.ts +2 -0
  49. package/lib/test/unit/pullModel.test.d.ts.map +1 -0
  50. package/lib/test/unit/pullModel.test.js +204 -0
  51. package/lib/test/unit/pullModel.test.js.map +1 -0
  52. package/package.json +83 -0
  53. package/rush-logs/ts-extras-ollama.build.cache.log +3 -0
  54. package/rush-logs/ts-extras-ollama.build.log +9 -0
  55. package/src/index.ts +655 -0
  56. package/src/test/unit/chatStructured.test.ts +330 -0
  57. package/src/test/unit/fixtures/wireFixtures.ts +95 -0
  58. package/src/test/unit/modelManagement.test.ts +128 -0
  59. package/src/test/unit/ollamaClient.test.ts +44 -0
  60. package/src/test/unit/pullModel.test.ts +220 -0
  61. package/temp/build/lint/_eslint-5eVG3S6w.json +30 -0
  62. package/temp/build/typescript/ts_8nwakTlr.json +1 -0
  63. package/temp/ts-extras-ollama.api.json +2528 -0
  64. package/temp/ts-extras-ollama.api.md +139 -0
  65. package/tsconfig.json +8 -0
package/lib/index.js ADDED
@@ -0,0 +1,397 @@
1
+ "use strict";
2
+ /**
3
+ * `@fgv/ts-extras-ollama` — Result-integration boundary over the official `ollama` JS library
4
+ * (Node-side).
5
+ *
6
+ * A thin facade that wraps the `ollama` client's native-API calls in `Result<T>` from
7
+ * `@fgv/ts-utils`, mirroring the discipline established by `@fgv/ts-extras-webauthn` and
8
+ * `@fgv/ts-extras-transformers`: one-line `captureResult` / `captureAsyncResult` wrappers around
9
+ * upstream primitives with **no opinionated orchestration** above the boundary.
10
+ *
11
+ * This package owns **exactly and only** the native-Ollama surface that the OpenAI-compatible
12
+ * `/v1` endpoint cannot express: model management (`/api/tags`, `/api/show`, `/api/ps`,
13
+ * `/api/delete`), streamed model pulls (`/api/pull`), and grammar-constrained structured output
14
+ * (`/api/chat` with a full-JSON-schema `format`). The text-completion / streaming / tool-use path
15
+ * is **not** duplicated here — `@fgv/ts-extras/ai-assist` owns it via the `/v1` compat layer
16
+ * (point a provider descriptor's `endpoint` at `http://localhost:11434/v1`).
17
+ *
18
+ * **Explicitly NOT in scope:**
19
+ * - Text completion / free-text chat / streaming chat (ai-assist owns it via `/v1`).
20
+ * - Browser / CORS path (Node-only at v0.1; a future `@fgv/ts-web-extras-ollama` is its home).
21
+ * - Model authoring / publishing (`push`, `create`, `copy`) — use the `ollama` lib directly.
22
+ * - `keep_alive` / model-lifecycle policy — pass-through only, no policy applied.
23
+ * - Pull-progress UI / rendering — `onProgress` hands raw chunks to the consumer.
24
+ * - Multi-host orchestration / connection pooling / retries / backoff — one client = one host.
25
+ *
26
+ * For any of the above, use the `ollama` library directly (with `captureAsyncResult` for your own
27
+ * Result wrapping); the opaque client handle returned by {@link createOllamaClient} is the
28
+ * upstream instance, so nothing this boundary omits is hidden from you.
29
+ *
30
+ * @packageDocumentation
31
+ */
32
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
33
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
34
+ var m = o[Symbol.asyncIterator], i;
35
+ 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);
36
+ 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); }); }; }
37
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
38
+ };
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.createOllamaClient = createOllamaClient;
41
+ exports.listModels = listModels;
42
+ exports.listRunning = listRunning;
43
+ exports.showModel = showModel;
44
+ exports.deleteModel = deleteModel;
45
+ exports.pullModel = pullModel;
46
+ exports.chatStructured = chatStructured;
47
+ const ollama_1 = require("ollama");
48
+ const ts_utils_1 = require("@fgv/ts-utils");
49
+ /**
50
+ * Constructs an Ollama client. Synchronous (the constructor performs no I/O), so returns
51
+ * `Result<IOllamaClient>` rather than a promise. A malformed `host` (which the upstream
52
+ * constructor rejects) surfaces as `Result.fail`.
53
+ *
54
+ * @param params - Optional {@link ICreateOllamaClientParams}. Omitted fields fall back to the
55
+ * `ollama` library defaults.
56
+ * @returns `Result<IOllamaClient>` wrapping the upstream `Ollama` instance.
57
+ * @public
58
+ */
59
+ function createOllamaClient(params) {
60
+ // The upstream `Ollama` constructor reads each config field with `?? <default>`, so omitted or
61
+ // `undefined` fields fall back to the library defaults — no per-field guarding needed.
62
+ return (0, ts_utils_1.captureResult)(() => new ollama_1.Ollama(params !== null && params !== void 0 ? params : {}));
63
+ }
64
+ // ─── Wire → fgv normalization (§6.3, Appendix) ──────────────────────────────────
65
+ /**
66
+ * Maps the upstream snake_case `ModelDetails` to the normalized camelCase {@link IOllamaModelDetail}.
67
+ * Upstream types every field as a required `string`, but Ollama omits fields it cannot determine,
68
+ * so individual values may be `undefined` at runtime — the normalized type reflects that by making
69
+ * every field optional.
70
+ */
71
+ function normalizeModelDetail(d) {
72
+ return {
73
+ format: d.format,
74
+ family: d.family,
75
+ families: d.families,
76
+ parameterSize: d.parameter_size,
77
+ quantizationLevel: d.quantization_level,
78
+ parentModel: d.parent_model
79
+ };
80
+ }
81
+ /**
82
+ * Maps a `/api/tags` `ModelResponse` to {@link IOllamaModel}. `modified_at` is normalized to a
83
+ * `Date` via the `Date` constructor, which accepts both the RFC3339 string the wire actually
84
+ * delivers and the `Date` the upstream type (inaccurately) claims.
85
+ */
86
+ function normalizeModel(m) {
87
+ return {
88
+ name: m.name,
89
+ model: m.model,
90
+ size: m.size,
91
+ digest: m.digest,
92
+ details: normalizeModelDetail(m.details),
93
+ modifiedAt: new Date(m.modified_at)
94
+ };
95
+ }
96
+ /**
97
+ * Maps a `/api/ps` `ModelResponse` to {@link IOllamaRunningModel}. `/api/ps` returns `expires_at`
98
+ * and `size_vram` in place of `modified_at`.
99
+ */
100
+ function normalizeRunningModel(m) {
101
+ return {
102
+ name: m.name,
103
+ model: m.model,
104
+ size: m.size,
105
+ digest: m.digest,
106
+ details: normalizeModelDetail(m.details),
107
+ expiresAt: new Date(m.expires_at),
108
+ sizeVram: m.size_vram
109
+ };
110
+ }
111
+ /**
112
+ * Normalizes the `model_info` metadata bag. The upstream type annotates it as `Map<string, any>`,
113
+ * but the lib returns `response.json()` verbatim, so the wire delivers a plain JSON object (or
114
+ * omits the field). The single `as unknown as` bridge reconciles the inaccurate upstream annotation
115
+ * with the actual JSON shape — there is no untyped input to validate here.
116
+ */
117
+ function normalizeModelInfo(raw) {
118
+ if (raw === undefined) {
119
+ return undefined;
120
+ }
121
+ return raw;
122
+ }
123
+ /**
124
+ * Maps a `/api/show` `ShowResponse` to {@link IOllamaModelInfo}. The remaining `ShowResponse`
125
+ * fields (`license`, `system`, `messages`, `modified_at`, `projector_info`) are intentionally not
126
+ * carried through — they are out of scope for the v0.1 surface.
127
+ */
128
+ function normalizeShowResponse(r) {
129
+ return {
130
+ modelfile: r.modelfile,
131
+ parameters: r.parameters,
132
+ template: r.template,
133
+ details: normalizeModelDetail(r.details),
134
+ modelInfo: normalizeModelInfo(r.model_info),
135
+ capabilities: r.capabilities
136
+ };
137
+ }
138
+ // ─── Model management primitives (§3.3) ─────────────────────────────────────────
139
+ /**
140
+ * Lists models in the local store (`GET /api/tags`). Each entry is normalized to
141
+ * {@link IOllamaModel} (camelCase, `modifiedAt` as a `Date`).
142
+ *
143
+ * @param client - A client from {@link createOllamaClient}.
144
+ * @returns `Promise<Result<ReadonlyArray<IOllamaModel>>>`; upstream / transport errors are captured
145
+ * as `Failure`.
146
+ * @public
147
+ */
148
+ async function listModels(client) {
149
+ return (0, ts_utils_1.captureAsyncResult)(async () => {
150
+ const response = await client.list();
151
+ return response.models.map(normalizeModel);
152
+ });
153
+ }
154
+ /**
155
+ * Lists models currently loaded into memory (`GET /api/ps`). Each entry is normalized to
156
+ * {@link IOllamaRunningModel} (camelCase, `expiresAt` as a `Date`, `sizeVram` in bytes).
157
+ *
158
+ * @param client - A client from {@link createOllamaClient}.
159
+ * @returns `Promise<Result<ReadonlyArray<IOllamaRunningModel>>>`; upstream / transport errors are
160
+ * captured as `Failure`.
161
+ * @public
162
+ */
163
+ async function listRunning(client) {
164
+ return (0, ts_utils_1.captureAsyncResult)(async () => {
165
+ const response = await client.ps();
166
+ return response.models.map(normalizeRunningModel);
167
+ });
168
+ }
169
+ /**
170
+ * Full model detail, capabilities, parameters, and template (`POST /api/show`), normalized to
171
+ * {@link IOllamaModelInfo}.
172
+ *
173
+ * @param client - A client from {@link createOllamaClient}.
174
+ * @param model - The model name to inspect, e.g. `'llama3.1:8b'`.
175
+ * @param options - Optional flags. `verbose: true` requests the full low-level `model_info` block.
176
+ * @returns `Promise<Result<IOllamaModelInfo>>`; upstream / transport errors (e.g. unknown model)
177
+ * are captured as `Failure`.
178
+ * @public
179
+ */
180
+ async function showModel(client, model, options) {
181
+ return (0, ts_utils_1.captureAsyncResult)(async () => {
182
+ // `verbose` is a valid `/api/show` body field that the lib forwards verbatim, but the upstream
183
+ // `ShowRequest` type omits it; building it as a non-literal object passes it through without a
184
+ // cast (and omits the key entirely when no flag was supplied).
185
+ const request = Object.assign({ model }, ((options === null || options === void 0 ? void 0 : options.verbose) !== undefined && { verbose: options.verbose }));
186
+ const response = await client.show(request);
187
+ return normalizeShowResponse(response);
188
+ });
189
+ }
190
+ /**
191
+ * Deletes a model from the local store (`DELETE /api/delete`). Returns a meaningful
192
+ * {@link IOllamaDeleteResult} rather than `Result<void>`.
193
+ *
194
+ * @param client - A client from {@link createOllamaClient}.
195
+ * @param model - The model name to delete.
196
+ * @returns `Promise<Result<IOllamaDeleteResult>>`; a missing model or transport error surfaces as
197
+ * `Failure`.
198
+ * @public
199
+ */
200
+ async function deleteModel(client, model) {
201
+ return (0, ts_utils_1.captureAsyncResult)(async () => {
202
+ await client.delete({ model });
203
+ return { model, deleted: true };
204
+ });
205
+ }
206
+ /**
207
+ * Maps an upstream `ProgressResponse` chunk to {@link IOllamaPullProgress}. The upstream type marks
208
+ * every field required, but the layer fields are omitted (and thus `undefined` at runtime) on the
209
+ * non-transfer phases — a direct structural copy preserves that, matching the optional fields.
210
+ */
211
+ function normalizePullProgress(c) {
212
+ return {
213
+ status: c.status,
214
+ digest: c.digest,
215
+ total: c.total,
216
+ completed: c.completed
217
+ };
218
+ }
219
+ /**
220
+ * Pulls a model with streamed progress (`POST /api/pull`). Drives the upstream JSON-lines stream
221
+ * internally, invoking `params.onProgress` once per chunk, and resolves the `Result` once the
222
+ * stream terminates. Any upstream error — connection drop, registry 404, abort, or a throwing
223
+ * `onProgress` — becomes a single `Failure`; success returns a meaningful {@link IOllamaPullResult}
224
+ * rather than `Result<void>`.
225
+ *
226
+ * @param client - A client from {@link createOllamaClient}.
227
+ * @param params - {@link IPullModelParams} — the model, optional `insecure` flag, optional
228
+ * `onProgress` callback, and optional `AbortSignal`.
229
+ * @returns `Promise<Result<IOllamaPullResult>>`.
230
+ * @public
231
+ */
232
+ async function pullModel(client, params) {
233
+ return (0, ts_utils_1.captureAsyncResult)(async () => {
234
+ var _a, e_1, _b, _c;
235
+ var _d, _e;
236
+ const request = Object.assign({ model: params.model, stream: true }, (params.insecure !== undefined && { insecure: params.insecure }));
237
+ const iterator = await client.pull(request);
238
+ // Wire the abort signal to the upstream iterator's abort path. An already-aborted signal
239
+ // cancels immediately; otherwise abort on first fire (and clean the listener up in `finally`).
240
+ const abortListener = () => iterator.abort();
241
+ if (params.signal !== undefined) {
242
+ if (params.signal.aborted) {
243
+ iterator.abort();
244
+ }
245
+ else {
246
+ params.signal.addEventListener('abort', abortListener, { once: true });
247
+ }
248
+ }
249
+ let chunkCount = 0;
250
+ let finalStatus = '';
251
+ try {
252
+ try {
253
+ for (var _f = true, iterator_1 = __asyncValues(iterator), iterator_1_1; iterator_1_1 = await iterator_1.next(), _a = iterator_1_1.done, !_a; _f = true) {
254
+ _c = iterator_1_1.value;
255
+ _f = false;
256
+ const chunk = _c;
257
+ (_d = params.onProgress) === null || _d === void 0 ? void 0 : _d.call(params, normalizePullProgress(chunk));
258
+ chunkCount += 1;
259
+ finalStatus = chunk.status;
260
+ }
261
+ }
262
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
263
+ finally {
264
+ try {
265
+ if (!_f && !_a && (_b = iterator_1.return)) await _b.call(iterator_1);
266
+ }
267
+ finally { if (e_1) throw e_1.error; }
268
+ }
269
+ }
270
+ finally {
271
+ (_e = params.signal) === null || _e === void 0 ? void 0 : _e.removeEventListener('abort', abortListener);
272
+ }
273
+ return { model: params.model, finalStatus, chunkCount };
274
+ });
275
+ }
276
+ /**
277
+ * Recursively removes the JSON-Schema keywords (`$schema`, `additionalProperties`) — *if present*
278
+ * — that Ollama's `format` does not need. `JsonSchema.object(...).toJson()` emits
279
+ * `additionalProperties: false` on object nodes; `$schema` is not added by default but may appear
280
+ * on a runtime-discovered schema (`JsonSchema.fromJson(raw)`). Mirrors the ai-assist Gemini
281
+ * precedent (`toGeminiParameterSchema`): the keywords are removed only where they appear as schema
282
+ * *keywords* (siblings of `type`/`properties`/…). Inside a `properties` map the keys are
283
+ * user-defined property names, not keywords, so they are preserved verbatim while each property's
284
+ * subschema value is still recursively sanitized. Stripping is infallible, so it returns a plain
285
+ * value rather than a `Result`.
286
+ */
287
+ function sanitizeFormatSchema(schema) {
288
+ if (Array.isArray(schema)) {
289
+ return schema.map(sanitizeFormatSchema);
290
+ }
291
+ if (schema !== null && typeof schema === 'object') {
292
+ const out = {};
293
+ for (const [key, value] of Object.entries(schema)) {
294
+ if (key === '$schema' || key === 'additionalProperties') {
295
+ continue;
296
+ }
297
+ if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {
298
+ const properties = {};
299
+ for (const [name, propSchema] of Object.entries(value)) {
300
+ properties[name] = sanitizeFormatSchema(propSchema);
301
+ }
302
+ out[key] = properties;
303
+ }
304
+ else {
305
+ out[key] = sanitizeFormatSchema(value);
306
+ }
307
+ }
308
+ return out;
309
+ }
310
+ return schema;
311
+ }
312
+ /**
313
+ * Maps an {@link IOllamaChatMessage} to the upstream `Message` wire shape, copying the optional
314
+ * base64 `images` array only when present.
315
+ */
316
+ function toWireMessage(message) {
317
+ return Object.assign({ role: message.role, content: message.content }, (message.images !== undefined && { images: [...message.images] }));
318
+ }
319
+ /**
320
+ * Single-turn grammar-constrained structured chat (`POST /api/chat` with `format` = full JSON
321
+ * schema). The fidelity win over ai-assist's prompt-and-parse path is **grammar-constrained
322
+ * sampling**: Ollama restricts the token sampler to the supplied schema, so the response is
323
+ * structurally guaranteed to match.
324
+ *
325
+ * The schema is the single source of truth: `schema.toJson()` (draft-07-sanitized) is sent as the
326
+ * wire `format`, and the same `schema.validate()` checks the reply — they cannot drift. `T` flows
327
+ * end-to-end from `JsonSchema.Static<typeof schema>`; no caller-supplied `T`, no cast.
328
+ *
329
+ * Runs over the streaming chat path internally, assembling the full document from the stream
330
+ * chunks and validating it whole — partial JSON has no validation value. (The design §4 sketch
331
+ * said `stream: false`, but the locked OQ-3 amendment requires an `AbortSignal`, and the `ollama`
332
+ * lib only threads a signal on the streaming path — its non-streaming request has no signal
333
+ * plumbing. The streaming `AbortableAsyncIterator.abort()` is "the mechanism that already exists
334
+ * for `pullModel`".) Any upstream error, abort, parse failure, or validation failure surfaces as a
335
+ * single `Failure` with context.
336
+ *
337
+ * @param client - A client from {@link createOllamaClient}.
338
+ * @param params - {@link IChatStructuredParams} — model, messages, the `JsonSchema` schema, and
339
+ * optional `options` / `keepAlive` / `signal`.
340
+ * @returns `Promise<Result<IOllamaChatStructuredResult<T>>>`.
341
+ * @public
342
+ */
343
+ async function chatStructured(client, params) {
344
+ const accumulated = await (0, ts_utils_1.captureAsyncResult)(async () => {
345
+ var _a, e_2, _b, _c;
346
+ var _d;
347
+ const wireFormat = sanitizeFormatSchema(params.schema.toJson());
348
+ const request = Object.assign(Object.assign({ model: params.model, messages: params.messages.map(toWireMessage),
349
+ // The wire schema accepts a plain object; the lib types `format` as `string | object`.
350
+ format: wireFormat, stream: true }, (params.options !== undefined && { options: params.options })), (params.keepAlive !== undefined && { keep_alive: params.keepAlive }));
351
+ const iterator = await client.chat(request);
352
+ const abortListener = () => iterator.abort();
353
+ if (params.signal !== undefined) {
354
+ if (params.signal.aborted) {
355
+ iterator.abort();
356
+ }
357
+ else {
358
+ params.signal.addEventListener('abort', abortListener, { once: true });
359
+ }
360
+ }
361
+ let raw = '';
362
+ let model = params.model;
363
+ let doneReason;
364
+ try {
365
+ try {
366
+ for (var _e = true, iterator_2 = __asyncValues(iterator), iterator_2_1; iterator_2_1 = await iterator_2.next(), _a = iterator_2_1.done, !_a; _e = true) {
367
+ _c = iterator_2_1.value;
368
+ _e = false;
369
+ const chunk = _c;
370
+ raw += chunk.message.content;
371
+ model = chunk.model;
372
+ if (chunk.done) {
373
+ doneReason = chunk.done_reason;
374
+ }
375
+ }
376
+ }
377
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
378
+ finally {
379
+ try {
380
+ if (!_e && !_a && (_b = iterator_2.return)) await _b.call(iterator_2);
381
+ }
382
+ finally { if (e_2) throw e_2.error; }
383
+ }
384
+ }
385
+ finally {
386
+ (_d = params.signal) === null || _d === void 0 ? void 0 : _d.removeEventListener('abort', abortListener);
387
+ }
388
+ return { raw, model, doneReason };
389
+ });
390
+ return accumulated.onSuccess(({ raw, model, doneReason }) => (0, ts_utils_1.captureResult)(() => JSON.parse(raw))
391
+ .withErrorFormat((message) => `chatStructured(${params.model}): response was not valid JSON: ${message}`)
392
+ .onSuccess((parsed) => params.schema
393
+ .validate(parsed)
394
+ .withErrorFormat((message) => `chatStructured(${params.model}): response failed schema validation: ${message}`)
395
+ .onSuccess((value) => (0, ts_utils_1.succeed)({ value, raw, model, doneReason }))));
396
+ }
397
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;;;;;;;;;AAkDH,gDAIC;AA0LD,gCAKC;AAWD,kCAOC;AAaD,8BAaC;AAYD,kCAQC;AAuFD,8BAqCC;AAqID,wCA2DC;AA/mBD,mCAUgB;AAChB,4CAAwF;AA2BxF;;;;;;;;;GASG;AACH,SAAgB,kBAAkB,CAAC,MAAkC;IACnE,+FAA+F;IAC/F,uFAAuF;IACvF,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,eAAM,CAAC,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CAAC,CAAC,CAAC;AACvD,CAAC;AA6FD,mFAAmF;AAEnF;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,CAAe;IAC3C,OAAO;QACL,MAAM,EAAE,CAAC,CAAC,MAAM;QAChB,MAAM,EAAE,CAAC,CAAC,MAAM;QAChB,QAAQ,EAAE,CAAC,CAAC,QAAQ;QACpB,aAAa,EAAE,CAAC,CAAC,cAAc;QAC/B,iBAAiB,EAAE,CAAC,CAAC,kBAAkB;QACvC,WAAW,EAAE,CAAC,CAAC,YAAY;KAC5B,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,cAAc,CAAC,CAAgB;IACtC,OAAO;QACL,IAAI,EAAE,CAAC,CAAC,IAAI;QACZ,KAAK,EA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AAI,CAAC,KAAK,CAAC,GAAG,CAAY,CAAC;SAC5C,eAAe,CACd,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,MAAM,CAAC,KAAK,mCAAmC,OAAO,EAAE,CACxF;SACA,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE,CACpB,MAAM,CAAC,MAAM;SACV,QAAQ,CAAC,MAAM,CAAC;SAChB,eAAe,CACd,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,MAAM,CAAC,KAAK,yCAAyC,OAAO,EAAE,CAC9F;SACA,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC,CACpE,CACJ,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `@fgv/ts-extras-ollama` — Result-integration boundary over the official `ollama` JS library\n * (Node-side).\n *\n * A thin facade that wraps the `ollama` client's native-API calls in `Result<T>` from\n * `@fgv/ts-utils`, mirroring the discipline established by `@fgv/ts-extras-webauthn` and\n * `@fgv/ts-extras-transformers`: one-line `captureResult` / `captureAsyncResult` wrappers around\n * upstream primitives with **no opinionated orchestration** above the boundary.\n *\n * This package owns **exactly and only** the native-Ollama surface that the OpenAI-compatible\n * `/v1` endpoint cannot express: model management (`/api/tags`, `/api/show`, `/api/ps`,\n * `/api/delete`), streamed model pulls (`/api/pull`), and grammar-constrained structured output\n * (`/api/chat` with a full-JSON-schema `format`). The text-completion / streaming / tool-use path\n * is **not** duplicated here — `@fgv/ts-extras/ai-assist` owns it via the `/v1` compat layer\n * (point a provider descriptor's `endpoint` at `http://localhost:11434/v1`).\n *\n * **Explicitly NOT in scope:**\n * - Text completion / free-text chat / streaming chat (ai-assist owns it via `/v1`).\n * - Browser / CORS path (Node-only at v0.1; a future `@fgv/ts-web-extras-ollama` is its home).\n * - Model authoring / publishing (`push`, `create`, `copy`) — use the `ollama` lib directly.\n * - `keep_alive` / model-lifecycle policy — pass-through only, no policy applied.\n * - Pull-progress UI / rendering — `onProgress` hands raw chunks to the consumer.\n * - Multi-host orchestration / connection pooling / retries / backoff — one client = one host.\n *\n * For any of the above, use the `ollama` library directly (with `captureAsyncResult` for your own\n * Result wrapping); the opaque client handle returned by {@link createOllamaClient} is the\n * upstream instance, so nothing this boundary omits is hidden from you.\n *\n * @packageDocumentation\n */\n\nimport {\n Ollama,\n type ChatRequest,\n type ListResponse,\n type Message,\n type ModelResponse,\n type ModelDetails,\n type Options,\n type ProgressResponse,\n type ShowResponse\n} from 'ollama';\nimport { captureAsyncResult, captureResult, succeed, type Result } from '@fgv/ts-utils';\nimport { type JsonObject, type JsonValue, type JsonSchema } from '@fgv/ts-json-base';\n\n/**\n * Construction parameters for an Ollama client. All optional; defaults match the `ollama` JS\n * library (host `http://127.0.0.1:11434`).\n * @public\n */\nexport interface ICreateOllamaClientParams {\n /** Server address. Defaults to `http://127.0.0.1:11434`. */\n readonly host?: string;\n /**\n * Custom `fetch` implementation. Injecting a fetch is the primary unit-test seam and the hook\n * for a future proxy / browser path.\n */\n readonly fetch?: typeof fetch;\n /** Custom headers included on every request (e.g. an auth token for a guarded sidecar). */\n readonly headers?: Record<string, string>;\n}\n\n/**\n * Opaque client handle. Re-export of the upstream `ollama` `Ollama` instance type — consumers\n * retain full access to the upstream API for anything this boundary does not wrap.\n * @public\n */\nexport type IOllamaClient = Ollama;\n\n/**\n * Constructs an Ollama client. Synchronous (the constructor performs no I/O), so returns\n * `Result<IOllamaClient>` rather than a promise. A malformed `host` (which the upstream\n * constructor rejects) surfaces as `Result.fail`.\n *\n * @param params - Optional {@link ICreateOllamaClientParams}. Omitted fields fall back to the\n * `ollama` library defaults.\n * @returns `Result<IOllamaClient>` wrapping the upstream `Ollama` instance.\n * @public\n */\nexport function createOllamaClient(params?: ICreateOllamaClientParams): Result<IOllamaClient> {\n // The upstream `Ollama` constructor reads each config field with `?? <default>`, so omitted or\n // `undefined` fields fall back to the library defaults — no per-field guarding needed.\n return captureResult(() => new Ollama(params ?? {}));\n}\n\n// ─── Shared normalized model types (§3.2) ───────────────────────────────────────\n\n/**\n * GGUF / model detail block, common to `/api/tags`, `/api/ps`, and `/api/show`. All fields\n * optional — Ollama omits any it cannot determine.\n * @public\n */\nexport interface IOllamaModelDetail {\n /** Storage format, e.g. `'gguf'`. */\n readonly format?: string;\n /** Primary architecture family, e.g. `'llama'`. */\n readonly family?: string;\n /** All architecture families this model belongs to. */\n readonly families?: ReadonlyArray<string>;\n /** Human-readable parameter count, e.g. `'8.0B'`. */\n readonly parameterSize?: string;\n /** Quantization level, e.g. `'Q4_0'`. */\n readonly quantizationLevel?: string;\n /** Parent model for fine-tunes / derived models. */\n readonly parentModel?: string;\n}\n\n/**\n * Fields common to a locally-stored model and a running model.\n * @public\n */\nexport interface IOllamaModelBase {\n /** Tagged name, e.g. `'llama3.1:8b'`. */\n readonly name: string;\n /** Underlying model id (often equal to `name`). */\n readonly model: string;\n /** On-disk size in bytes. */\n readonly size: number;\n /** SHA-256 manifest digest. */\n readonly digest: string;\n /** GGUF / architecture detail. */\n readonly details: IOllamaModelDetail;\n}\n\n/**\n * A model present in the local store (`/api/tags`).\n * @public\n */\nexport interface IOllamaModel extends IOllamaModelBase {\n /** Last-modified timestamp, parsed from the RFC3339 wire value. */\n readonly modifiedAt: Date;\n}\n\n/**\n * A model currently loaded into memory (`/api/ps`). Note `/api/ps` does NOT return\n * `modified_at`, so this does not extend {@link IOllamaModel}.\n * @public\n */\nexport interface IOllamaRunningModel extends IOllamaModelBase {\n /** When the model will be unloaded, parsed from the RFC3339 wire value. */\n readonly expiresAt: Date;\n /** Bytes resident in VRAM (0 when fully on CPU). */\n readonly sizeVram: number;\n}\n\n/**\n * Full model detail, capabilities, parameters, and template (`POST /api/show`).\n * @public\n */\nexport interface IOllamaModelInfo {\n /** The Modelfile source, when returned. */\n readonly modelfile?: string;\n /** Default parameters string. */\n readonly parameters?: string;\n /** The prompt template. */\n readonly template?: string;\n /** GGUF / architecture detail. */\n readonly details: IOllamaModelDetail;\n /** Low-level model metadata key-value map (`model_info`). */\n readonly modelInfo?: Readonly<Record<string, JsonValue>>;\n /** Declared capabilities, e.g. `['completion', 'tools', 'vision', 'thinking']`. */\n readonly capabilities?: ReadonlyArray<string>;\n}\n\n/**\n * Result of a delete. Returns a meaningful value rather than `Result<void>` (per repo standards —\n * `Result<void>` is an anti-pattern).\n * @public\n */\nexport interface IOllamaDeleteResult {\n /** The model that was deleted. */\n readonly model: string;\n /** Always `true` — a failed delete surfaces as `Result.fail`, never `deleted: false`. */\n readonly deleted: true;\n}\n\n// ─── Wire → fgv normalization (§6.3, Appendix) ──────────────────────────────────\n\n/**\n * Maps the upstream snake_case `ModelDetails` to the normalized camelCase {@link IOllamaModelDetail}.\n * Upstream types every field as a required `string`, but Ollama omits fields it cannot determine,\n * so individual values may be `undefined` at runtime — the normalized type reflects that by making\n * every field optional.\n */\nfunction normalizeModelDetail(d: ModelDetails): IOllamaModelDetail {\n return {\n format: d.format,\n family: d.family,\n families: d.families,\n parameterSize: d.parameter_size,\n quantizationLevel: d.quantization_level,\n parentModel: d.parent_model\n };\n}\n\n/**\n * Maps a `/api/tags` `ModelResponse` to {@link IOllamaModel}. `modified_at` is normalized to a\n * `Date` via the `Date` constructor, which accepts both the RFC3339 string the wire actually\n * delivers and the `Date` the upstream type (inaccurately) claims.\n */\nfunction normalizeModel(m: ModelResponse): IOllamaModel {\n return {\n name: m.name,\n model: m.model,\n size: m.size,\n digest: m.digest,\n details: normalizeModelDetail(m.details),\n modifiedAt: new Date(m.modified_at)\n };\n}\n\n/**\n * Maps a `/api/ps` `ModelResponse` to {@link IOllamaRunningModel}. `/api/ps` returns `expires_at`\n * and `size_vram` in place of `modified_at`.\n */\nfunction normalizeRunningModel(m: ModelResponse): IOllamaRunningModel {\n return {\n name: m.name,\n model: m.model,\n size: m.size,\n digest: m.digest,\n details: normalizeModelDetail(m.details),\n expiresAt: new Date(m.expires_at),\n sizeVram: m.size_vram\n };\n}\n\n/**\n * Normalizes the `model_info` metadata bag. The upstream type annotates it as `Map<string, any>`,\n * but the lib returns `response.json()` verbatim, so the wire delivers a plain JSON object (or\n * omits the field). The single `as unknown as` bridge reconciles the inaccurate upstream annotation\n * with the actual JSON shape — there is no untyped input to validate here.\n */\nfunction normalizeModelInfo(\n raw: ShowResponse['model_info']\n): Readonly<Record<string, JsonValue>> | undefined {\n if (raw === undefined) {\n return undefined;\n }\n return raw as unknown as Readonly<Record<string, JsonValue>>;\n}\n\n/**\n * Maps a `/api/show` `ShowResponse` to {@link IOllamaModelInfo}. The remaining `ShowResponse`\n * fields (`license`, `system`, `messages`, `modified_at`, `projector_info`) are intentionally not\n * carried through — they are out of scope for the v0.1 surface.\n */\nfunction normalizeShowResponse(r: ShowResponse): IOllamaModelInfo {\n return {\n modelfile: r.modelfile,\n parameters: r.parameters,\n template: r.template,\n details: normalizeModelDetail(r.details),\n modelInfo: normalizeModelInfo(r.model_info),\n capabilities: r.capabilities\n };\n}\n\n// ─── Model management primitives (§3.3) ─────────────────────────────────────────\n\n/**\n * Lists models in the local store (`GET /api/tags`). Each entry is normalized to\n * {@link IOllamaModel} (camelCase, `modifiedAt` as a `Date`).\n *\n * @param client - A client from {@link createOllamaClient}.\n * @returns `Promise<Result<ReadonlyArray<IOllamaModel>>>`; upstream / transport errors are captured\n * as `Failure`.\n * @public\n */\nexport async function listModels(client: IOllamaClient): Promise<Result<ReadonlyArray<IOllamaModel>>> {\n return captureAsyncResult(async () => {\n const response: ListResponse = await client.list();\n return response.models.map(normalizeModel);\n });\n}\n\n/**\n * Lists models currently loaded into memory (`GET /api/ps`). Each entry is normalized to\n * {@link IOllamaRunningModel} (camelCase, `expiresAt` as a `Date`, `sizeVram` in bytes).\n *\n * @param client - A client from {@link createOllamaClient}.\n * @returns `Promise<Result<ReadonlyArray<IOllamaRunningModel>>>`; upstream / transport errors are\n * captured as `Failure`.\n * @public\n */\nexport async function listRunning(\n client: IOllamaClient\n): Promise<Result<ReadonlyArray<IOllamaRunningModel>>> {\n return captureAsyncResult(async () => {\n const response: ListResponse = await client.ps();\n return response.models.map(normalizeRunningModel);\n });\n}\n\n/**\n * Full model detail, capabilities, parameters, and template (`POST /api/show`), normalized to\n * {@link IOllamaModelInfo}.\n *\n * @param client - A client from {@link createOllamaClient}.\n * @param model - The model name to inspect, e.g. `'llama3.1:8b'`.\n * @param options - Optional flags. `verbose: true` requests the full low-level `model_info` block.\n * @returns `Promise<Result<IOllamaModelInfo>>`; upstream / transport errors (e.g. unknown model)\n * are captured as `Failure`.\n * @public\n */\nexport async function showModel(\n client: IOllamaClient,\n model: string,\n options?: { readonly verbose?: boolean }\n): Promise<Result<IOllamaModelInfo>> {\n return captureAsyncResult(async () => {\n // `verbose` is a valid `/api/show` body field that the lib forwards verbatim, but the upstream\n // `ShowRequest` type omits it; building it as a non-literal object passes it through without a\n // cast (and omits the key entirely when no flag was supplied).\n const request = { model, ...(options?.verbose !== undefined && { verbose: options.verbose }) };\n const response: ShowResponse = await client.show(request);\n return normalizeShowResponse(response);\n });\n}\n\n/**\n * Deletes a model from the local store (`DELETE /api/delete`). Returns a meaningful\n * {@link IOllamaDeleteResult} rather than `Result<void>`.\n *\n * @param client - A client from {@link createOllamaClient}.\n * @param model - The model name to delete.\n * @returns `Promise<Result<IOllamaDeleteResult>>`; a missing model or transport error surfaces as\n * `Failure`.\n * @public\n */\nexport async function deleteModel(\n client: IOllamaClient,\n model: string\n): Promise<Result<IOllamaDeleteResult>> {\n return captureAsyncResult(async () => {\n await client.delete({ model });\n return { model, deleted: true };\n });\n}\n\n// ─── Pull with streamed progress (§3.4, §5) ─────────────────────────────────────\n\n/**\n * A single progress chunk from a streamed pull (`/api/pull`). Ollama emits a JSON-lines stream;\n * each line is one of these. Fields map 1:1 from the upstream `ProgressResponse`; the layer fields\n * (`digest`/`total`/`completed`) are `undefined` on the manifest / verify / write phases.\n * @public\n */\nexport interface IOllamaPullProgress {\n /**\n * Phase string, e.g. `'pulling manifest'`, `'pulling <digest>'`, `'verifying sha256 digest'`,\n * `'writing manifest'`, `'success'`.\n */\n readonly status: string;\n /** Layer digest being transferred (present during `'pulling <digest>'` phases). */\n readonly digest?: string;\n /** Total bytes for the current layer, when known. */\n readonly total?: number;\n /** Bytes transferred so far for the current layer, when known. */\n readonly completed?: number;\n}\n\n/**\n * Terminal result of a completed pull. Returns a meaningful value (not `Result<void>`): the final\n * status plus a count of progress chunks observed.\n * @public\n */\nexport interface IOllamaPullResult {\n /** The model that was pulled. */\n readonly model: string;\n /** The `status` of the final chunk, normally `'success'`. */\n readonly finalStatus: string;\n /** Number of progress chunks observed (useful for tests and diagnostics). */\n readonly chunkCount: number;\n}\n\n/**\n * Parameters for {@link pullModel}.\n * @public\n */\nexport interface IPullModelParams {\n /** Model to pull, e.g. `'llama3.1:8b'`. */\n readonly model: string;\n /** Allow pulling from insecure (non-TLS) registries. */\n readonly insecure?: boolean;\n /**\n * Progress callback, invoked once per JSON-lines chunk as it arrives. The `Result` returned by\n * {@link pullModel} resolves only after the stream terminates; progress is surfaced here in the\n * interim. A throw from this callback fails the whole pull (it runs inside the captured loop).\n */\n readonly onProgress?: (progress: IOllamaPullProgress) => void;\n /**\n * Abort signal. Cancels the in-flight pull; the upstream stream throws an `AbortError`, which\n * surfaces as `Result.fail`. An already-aborted signal cancels immediately.\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Maps an upstream `ProgressResponse` chunk to {@link IOllamaPullProgress}. The upstream type marks\n * every field required, but the layer fields are omitted (and thus `undefined` at runtime) on the\n * non-transfer phases — a direct structural copy preserves that, matching the optional fields.\n */\nfunction normalizePullProgress(c: ProgressResponse): IOllamaPullProgress {\n return {\n status: c.status,\n digest: c.digest,\n total: c.total,\n completed: c.completed\n };\n}\n\n/**\n * Pulls a model with streamed progress (`POST /api/pull`). Drives the upstream JSON-lines stream\n * internally, invoking `params.onProgress` once per chunk, and resolves the `Result` once the\n * stream terminates. Any upstream error — connection drop, registry 404, abort, or a throwing\n * `onProgress` — becomes a single `Failure`; success returns a meaningful {@link IOllamaPullResult}\n * rather than `Result<void>`.\n *\n * @param client - A client from {@link createOllamaClient}.\n * @param params - {@link IPullModelParams} — the model, optional `insecure` flag, optional\n * `onProgress` callback, and optional `AbortSignal`.\n * @returns `Promise<Result<IOllamaPullResult>>`.\n * @public\n */\nexport async function pullModel(\n client: IOllamaClient,\n params: IPullModelParams\n): Promise<Result<IOllamaPullResult>> {\n return captureAsyncResult(async () => {\n const request = {\n model: params.model,\n stream: true as const,\n ...(params.insecure !== undefined && { insecure: params.insecure })\n };\n const iterator = await client.pull(request);\n\n // Wire the abort signal to the upstream iterator's abort path. An already-aborted signal\n // cancels immediately; otherwise abort on first fire (and clean the listener up in `finally`).\n const abortListener = (): void => iterator.abort();\n if (params.signal !== undefined) {\n if (params.signal.aborted) {\n iterator.abort();\n } else {\n params.signal.addEventListener('abort', abortListener, { once: true });\n }\n }\n\n let chunkCount = 0;\n let finalStatus = '';\n try {\n for await (const chunk of iterator) {\n params.onProgress?.(normalizePullProgress(chunk));\n chunkCount += 1;\n finalStatus = chunk.status;\n }\n } finally {\n params.signal?.removeEventListener('abort', abortListener);\n }\n\n return { model: params.model, finalStatus, chunkCount };\n });\n}\n\n// ─── Grammar-constrained structured output (§3.5, §4) ───────────────────────────\n\n/**\n * A chat message in Ollama native shape.\n * @public\n */\nexport interface IOllamaChatMessage {\n /** The message role. */\n readonly role: 'system' | 'user' | 'assistant' | 'tool';\n /** The message text. */\n readonly content: string;\n /** Base64 image data for vision models (no `data:` prefix). */\n readonly images?: ReadonlyArray<string>;\n}\n\n/**\n * Result of a grammar-constrained structured chat. Carries both the validated typed value and the\n * raw JSON text the model emitted, for diagnostics.\n * @public\n */\nexport interface IOllamaChatStructuredResult<T> {\n /** The parsed-and-validated value (validated by the same schema sent on the wire). */\n readonly value: T;\n /** The raw `message.content` JSON string the model emitted (assembled across stream chunks). */\n readonly raw: string;\n /** The model that produced the response. */\n readonly model: string;\n /** Provider-reported finish reason, when present. */\n readonly doneReason?: string;\n}\n\n/**\n * Parameters for {@link chatStructured}.\n * @public\n */\nexport interface IChatStructuredParams<T> {\n /** The model to chat with, e.g. `'llama3.1:8b'`. */\n readonly model: string;\n /** The conversation so far. */\n readonly messages: ReadonlyArray<IOllamaChatMessage>;\n /**\n * The single source of truth for both the wire schema (`schema.toJson()`, sent as the native\n * `format` field) and the result validator (`schema.validate()`). Author with\n * `JsonSchema.object(...)` from `@fgv/ts-json-base`; `T` is derived via\n * `JsonSchema.Static<typeof schema>`. A runtime-discovered (MCP) schema parsed via\n * `JsonSchema.fromJson(raw)` also works — its `T` is `JsonValue`.\n */\n readonly schema: JsonSchema.ISchemaValidator<T>;\n /** Native Ollama `options` (temperature, num_ctx, seed, …). Passed verbatim. */\n readonly options?: Readonly<Record<string, JsonValue>>;\n /** Native `keep_alive` (duration string or seconds). Passed verbatim — no policy applied. */\n readonly keepAlive?: string | number;\n /**\n * Abort signal. Cancels the in-flight generation; the upstream stream throws an `AbortError`,\n * which surfaces as `Result.fail`. An already-aborted signal cancels immediately.\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Recursively removes the JSON-Schema keywords (`$schema`, `additionalProperties`) — *if present*\n * — that Ollama's `format` does not need. `JsonSchema.object(...).toJson()` emits\n * `additionalProperties: false` on object nodes; `$schema` is not added by default but may appear\n * on a runtime-discovered schema (`JsonSchema.fromJson(raw)`). Mirrors the ai-assist Gemini\n * precedent (`toGeminiParameterSchema`): the keywords are removed only where they appear as schema\n * *keywords* (siblings of `type`/`properties`/…). Inside a `properties` map the keys are\n * user-defined property names, not keywords, so they are preserved verbatim while each property's\n * subschema value is still recursively sanitized. Stripping is infallible, so it returns a plain\n * value rather than a `Result`.\n */\nfunction sanitizeFormatSchema(schema: JsonValue): JsonValue {\n if (Array.isArray(schema)) {\n return schema.map(sanitizeFormatSchema);\n }\n if (schema !== null && typeof schema === 'object') {\n const out: JsonObject = {};\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$schema' || key === 'additionalProperties') {\n continue;\n }\n if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {\n const properties: JsonObject = {};\n for (const [name, propSchema] of Object.entries(value)) {\n properties[name] = sanitizeFormatSchema(propSchema);\n }\n out[key] = properties;\n } else {\n out[key] = sanitizeFormatSchema(value);\n }\n }\n return out;\n }\n return schema;\n}\n\n/**\n * Maps an {@link IOllamaChatMessage} to the upstream `Message` wire shape, copying the optional\n * base64 `images` array only when present.\n */\nfunction toWireMessage(message: IOllamaChatMessage): Message {\n return {\n role: message.role,\n content: message.content,\n ...(message.images !== undefined && { images: [...message.images] })\n };\n}\n\n/**\n * Single-turn grammar-constrained structured chat (`POST /api/chat` with `format` = full JSON\n * schema). The fidelity win over ai-assist's prompt-and-parse path is **grammar-constrained\n * sampling**: Ollama restricts the token sampler to the supplied schema, so the response is\n * structurally guaranteed to match.\n *\n * The schema is the single source of truth: `schema.toJson()` (draft-07-sanitized) is sent as the\n * wire `format`, and the same `schema.validate()` checks the reply — they cannot drift. `T` flows\n * end-to-end from `JsonSchema.Static<typeof schema>`; no caller-supplied `T`, no cast.\n *\n * Runs over the streaming chat path internally, assembling the full document from the stream\n * chunks and validating it whole — partial JSON has no validation value. (The design §4 sketch\n * said `stream: false`, but the locked OQ-3 amendment requires an `AbortSignal`, and the `ollama`\n * lib only threads a signal on the streaming path — its non-streaming request has no signal\n * plumbing. The streaming `AbortableAsyncIterator.abort()` is \"the mechanism that already exists\n * for `pullModel`\".) Any upstream error, abort, parse failure, or validation failure surfaces as a\n * single `Failure` with context.\n *\n * @param client - A client from {@link createOllamaClient}.\n * @param params - {@link IChatStructuredParams} — model, messages, the `JsonSchema` schema, and\n * optional `options` / `keepAlive` / `signal`.\n * @returns `Promise<Result<IOllamaChatStructuredResult<T>>>`.\n * @public\n */\nexport async function chatStructured<T>(\n client: IOllamaClient,\n params: IChatStructuredParams<T>\n): Promise<Result<IOllamaChatStructuredResult<T>>> {\n const accumulated = await captureAsyncResult(async () => {\n const wireFormat = sanitizeFormatSchema(params.schema.toJson());\n const request: ChatRequest & { stream: true } = {\n model: params.model,\n messages: params.messages.map(toWireMessage),\n // The wire schema accepts a plain object; the lib types `format` as `string | object`.\n format: wireFormat as object,\n stream: true,\n // The lib types `options` narrowly as `Partial<Options>`, but the native API accepts an\n // arbitrary option bag forwarded verbatim — bridge the (overly narrow) upstream type.\n ...(params.options !== undefined && { options: params.options as unknown as Partial<Options> }),\n ...(params.keepAlive !== undefined && { keep_alive: params.keepAlive })\n };\n const iterator = await client.chat(request);\n\n const abortListener = (): void => iterator.abort();\n if (params.signal !== undefined) {\n if (params.signal.aborted) {\n iterator.abort();\n } else {\n params.signal.addEventListener('abort', abortListener, { once: true });\n }\n }\n\n let raw = '';\n let model = params.model;\n let doneReason: string | undefined;\n try {\n for await (const chunk of iterator) {\n raw += chunk.message.content;\n model = chunk.model;\n if (chunk.done) {\n doneReason = chunk.done_reason;\n }\n }\n } finally {\n params.signal?.removeEventListener('abort', abortListener);\n }\n return { raw, model, doneReason };\n });\n\n return accumulated.onSuccess(({ raw, model, doneReason }) =>\n captureResult(() => JSON.parse(raw) as unknown)\n .withErrorFormat(\n (message) => `chatStructured(${params.model}): response was not valid JSON: ${message}`\n )\n .onSuccess((parsed) =>\n params.schema\n .validate(parsed)\n .withErrorFormat(\n (message) => `chatStructured(${params.model}): response failed schema validation: ${message}`\n )\n .onSuccess((value) => succeed({ value, raw, model, doneReason }))\n )\n );\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import '@fgv/ts-utils-jest';
2
+ //# sourceMappingURL=chatStructured.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chatStructured.test.d.ts","sourceRoot":"","sources":["../../../src/test/unit/chatStructured.test.ts"],"names":[],"mappings":"AAAA,OAAO,oBAAoB,CAAC"}