@nemesis-oss/ollama-sdk 1.7.0 → 1.8.0

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 (39) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/dist/anthropic-B_UXplNF.d.ts +1647 -0
  3. package/dist/anthropic-CVDFy_a0.d.cts +1647 -0
  4. package/dist/generated-api.cjs +74 -6
  5. package/dist/generated-api.cjs.map +1 -1
  6. package/dist/generated-api.d.cts +230 -629
  7. package/dist/generated-api.d.ts +230 -629
  8. package/dist/generated-api.js +72 -7
  9. package/dist/generated-api.js.map +1 -1
  10. package/dist/generated-models-schemas.cjs +89 -1
  11. package/dist/generated-models-schemas.cjs.map +1 -1
  12. package/dist/generated-models-schemas.d.cts +121 -1
  13. package/dist/generated-models-schemas.d.ts +121 -1
  14. package/dist/generated-models-schemas.js +79 -2
  15. package/dist/generated-models-schemas.js.map +1 -1
  16. package/dist/generated-runtime.cjs +576 -57
  17. package/dist/generated-runtime.cjs.map +1 -1
  18. package/dist/generated-runtime.d.cts +21 -23
  19. package/dist/generated-runtime.d.ts +21 -23
  20. package/dist/generated-runtime.js +575 -58
  21. package/dist/generated-runtime.js.map +1 -1
  22. package/dist/index.cjs +1078 -75
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +378 -874
  25. package/dist/index.d.ts +378 -874
  26. package/dist/index.js +1075 -76
  27. package/dist/index.js.map +1 -1
  28. package/dist/mcp/tools.json +287 -73
  29. package/dist/mcp-generated.cjs +96 -7
  30. package/dist/mcp-generated.cjs.map +1 -1
  31. package/dist/mcp-generated.d.cts +1 -1
  32. package/dist/mcp-generated.d.ts +1 -1
  33. package/dist/mcp-generated.js +96 -7
  34. package/dist/mcp-generated.js.map +1 -1
  35. package/dist/{runtime-qwD72cpn.d.ts → runtime-C6UYtBRB.d.ts} +218 -4
  36. package/dist/{runtime-bQ48I-RC.d.cts → runtime-DTmUeU6K.d.cts} +218 -4
  37. package/dist/skills.cjs.map +1 -1
  38. package/dist/skills.js.map +1 -1
  39. package/package.json +3 -2
@@ -72,6 +72,35 @@ var OllamaRequestValidationError = class extends OllamaClientError {
72
72
  this.issues = options.issues;
73
73
  }
74
74
  };
75
+ var OllamaRequestTooLargeError = class extends OllamaClientError {
76
+ operationId;
77
+ actualBytes;
78
+ maxBytes;
79
+ constructor(message, options) {
80
+ super(message, { ...options, code: "request_too_large", retryable: false, status: 413 });
81
+ this.operationId = options.operationId;
82
+ this.actualBytes = options.actualBytes;
83
+ this.maxBytes = options.maxBytes;
84
+ }
85
+ };
86
+ var OllamaResponseValidationError = class extends OllamaClientError {
87
+ operationId;
88
+ issues;
89
+ constructor(message, options) {
90
+ super(message, { ...options, code: "response_validation_error", retryable: false });
91
+ this.operationId = options.operationId;
92
+ this.issues = options.issues;
93
+ }
94
+ };
95
+ var OllamaServerVersionUnknownError = class extends OllamaClientError {
96
+ operationId;
97
+ minRequiredVersion;
98
+ constructor(message, options) {
99
+ super(message, { ...options, code: "server_version_unknown", retryable: false });
100
+ this.operationId = options.operationId;
101
+ this.minRequiredVersion = options.minRequiredVersion;
102
+ }
103
+ };
75
104
  var OllamaGenericClientError = class extends OllamaClientError {
76
105
  constructor(message, options) {
77
106
  super(message, { ...options, code: "client_error" });
@@ -127,6 +156,98 @@ async function* parseNdjsonStream(stream) {
127
156
  _promise && await _promise;
128
157
  }
129
158
  }
159
+
160
+ // src/streaming/sse.ts
161
+ function dispatch(event, data, id, retry) {
162
+ if (data.length === 0) return void 0;
163
+ const joined = data.join("\n");
164
+ return {
165
+ ...event !== void 0 ? { event } : {},
166
+ data: joined.endsWith("\n") ? joined.slice(0, -1) : joined,
167
+ ...id !== void 0 ? { id } : {},
168
+ ...retry !== void 0 ? { retry } : {}
169
+ };
170
+ }
171
+ async function* parseSseStream(stream) {
172
+ var _stack = [];
173
+ try {
174
+ const reader = stream.getReader();
175
+ const decoder = new TextDecoder();
176
+ let buffer = "";
177
+ let eventType;
178
+ let data = [];
179
+ let lastEventId;
180
+ let retry;
181
+ const processLine = (line) => {
182
+ if (line.length === 0) {
183
+ const event = dispatch(eventType, data, lastEventId, retry);
184
+ eventType = void 0;
185
+ data = [];
186
+ retry = void 0;
187
+ return event;
188
+ }
189
+ if (line.startsWith(":")) return void 0;
190
+ const separator = line.indexOf(":");
191
+ const field = separator === -1 ? line : line.slice(0, separator);
192
+ let value = separator === -1 ? "" : line.slice(separator + 1);
193
+ if (value.startsWith(" ")) value = value.slice(1);
194
+ switch (field) {
195
+ case "event":
196
+ eventType = value;
197
+ break;
198
+ case "data":
199
+ data.push(value);
200
+ break;
201
+ case "id":
202
+ if (!value.includes("\0")) lastEventId = value;
203
+ break;
204
+ case "retry": {
205
+ if (/^\d+$/.test(value)) {
206
+ const parsed = Number(value);
207
+ if (Number.isSafeInteger(parsed)) retry = parsed;
208
+ }
209
+ break;
210
+ }
211
+ default:
212
+ break;
213
+ }
214
+ return void 0;
215
+ };
216
+ const _reader = __using(_stack, disposableReader(reader), true);
217
+ while (true) {
218
+ const { done, value } = await reader.read();
219
+ if (done) break;
220
+ buffer += decoder.decode(value, { stream: true });
221
+ while (true) {
222
+ const lf = buffer.indexOf("\n");
223
+ const cr = buffer.indexOf("\r");
224
+ if (lf === -1 && cr === -1) break;
225
+ if (cr !== -1 && lf === -1 && cr === buffer.length - 1) break;
226
+ const lineEnd = lf === -1 ? cr : cr === -1 ? lf : Math.min(lf, cr);
227
+ let separatorLength = 1;
228
+ if (buffer[lineEnd] === "\r" && buffer[lineEnd + 1] === "\n") {
229
+ separatorLength = 2;
230
+ }
231
+ const line = buffer.slice(0, lineEnd);
232
+ buffer = buffer.slice(lineEnd + separatorLength);
233
+ const event = processLine(line);
234
+ if (event) yield event;
235
+ }
236
+ }
237
+ buffer += decoder.decode();
238
+ if (buffer.length > 0) {
239
+ const event = processLine(buffer);
240
+ if (event) yield event;
241
+ }
242
+ const terminal = dispatch(eventType, data, lastEventId, retry);
243
+ if (terminal) yield terminal;
244
+ } catch (_) {
245
+ var _error = _, _hasError = true;
246
+ } finally {
247
+ var _promise = __callDispose(_stack, _error, _hasError);
248
+ _promise && await _promise;
249
+ }
250
+ }
130
251
  var ToolCallSchema = z.object({
131
252
  function: z.object({
132
253
  name: z.string(),
@@ -175,28 +296,45 @@ var ChatRequestSchema = z.object({
175
296
  logprobs: z.boolean().optional(),
176
297
  top_logprobs: z.number().optional()
177
298
  });
178
- var GenerateRequestSchema = z.object({
179
- model: z.string(),
180
- prompt: z.string().optional(),
181
- suffix: z.string().optional(),
182
- images: z.array(z.string()).optional(),
183
- format: z.union([z.string(), z.object({})]).optional(),
184
- system: z.string().optional(),
185
- stream: z.boolean().optional(),
186
- think: ThinkValueSchema.optional(),
187
- raw: z.boolean().optional(),
188
- keep_alive: z.union([z.string(), z.number()]).optional(),
189
- options: ModelOptionsSchema.optional(),
190
- logprobs: z.boolean().optional(),
191
- top_logprobs: z.number().optional()
299
+ var TokenLogprobSchema = z.object({
300
+ token: z.string().optional(),
301
+ logprob: z.number().optional(),
302
+ bytes: z.array(z.number()).optional()
192
303
  });
193
- var EmbedRequestSchema = z.object({
194
- model: z.string(),
195
- input: z.union([z.string(), z.array(z.string())]),
196
- truncate: z.boolean().optional(),
197
- dimensions: z.number().optional(),
198
- keep_alive: z.string().optional(),
199
- options: ModelOptionsSchema.optional()
304
+
305
+ // src/generated/models/Logprob.schema.ts
306
+ var LogprobSchema = z.object({
307
+ token: z.string().optional(),
308
+ logprob: z.number().optional(),
309
+ bytes: z.array(z.number()).optional(),
310
+ top_logprobs: z.array(TokenLogprobSchema).optional()
311
+ });
312
+
313
+ // src/generated/models/ChatResponse.schema.ts
314
+ var ChatResponseSchema = z.object({
315
+ model: z.string().optional(),
316
+ created_at: z.string().optional(),
317
+ message: z.object({
318
+ role: z.enum(["assistant"]).optional(),
319
+ content: z.string().optional(),
320
+ thinking: z.string().optional(),
321
+ tool_calls: z.array(ToolCallSchema).optional(),
322
+ images: z.array(z.string()).optional()
323
+ }).optional(),
324
+ done: z.boolean().optional(),
325
+ done_reason: z.string().optional(),
326
+ total_duration: z.number().optional(),
327
+ load_duration: z.number().optional(),
328
+ prompt_eval_count: z.number().optional(),
329
+ prompt_eval_cached_count: z.number().optional(),
330
+ prompt_eval_duration: z.number().optional(),
331
+ eval_count: z.number().optional(),
332
+ eval_duration: z.number().optional(),
333
+ logprobs: z.array(LogprobSchema).optional()
334
+ });
335
+ var CopyRequestSchema = z.object({
336
+ source: z.string(),
337
+ destination: z.string()
200
338
  });
201
339
  var CreateRequestSchema = z.object({
202
340
  model: z.string(),
@@ -215,13 +353,91 @@ var CreateRequestSchema = z.object({
215
353
  requires: z.string().optional(),
216
354
  stream: z.boolean().optional()
217
355
  });
218
- var CopyRequestSchema = z.object({
219
- source: z.string(),
220
- destination: z.string()
221
- });
222
356
  var DeleteRequestSchema = z.object({
223
357
  model: z.string()
224
358
  });
359
+ var EmbedRequestSchema = z.object({
360
+ model: z.string(),
361
+ input: z.union([z.string(), z.array(z.string())]),
362
+ truncate: z.boolean().optional(),
363
+ dimensions: z.number().optional(),
364
+ keep_alive: z.string().optional(),
365
+ options: ModelOptionsSchema.optional()
366
+ });
367
+ var EmbedResponseSchema = z.object({
368
+ model: z.string().optional(),
369
+ embeddings: z.array(z.array(z.number())).optional(),
370
+ total_duration: z.number().optional(),
371
+ load_duration: z.number().optional(),
372
+ prompt_eval_count: z.number().optional()
373
+ });
374
+ var GenerateRequestSchema = z.object({
375
+ model: z.string(),
376
+ prompt: z.string().optional(),
377
+ suffix: z.string().optional(),
378
+ images: z.array(z.string()).optional(),
379
+ format: z.union([z.string(), z.object({})]).optional(),
380
+ system: z.string().optional(),
381
+ stream: z.boolean().optional(),
382
+ think: ThinkValueSchema.optional(),
383
+ raw: z.boolean().optional(),
384
+ keep_alive: z.union([z.string(), z.number()]).optional(),
385
+ options: ModelOptionsSchema.optional(),
386
+ logprobs: z.boolean().optional(),
387
+ top_logprobs: z.number().optional()
388
+ });
389
+ var GenerateResponseSchema = z.object({
390
+ model: z.string().optional(),
391
+ created_at: z.string().optional(),
392
+ response: z.string().optional(),
393
+ thinking: z.string().optional(),
394
+ done: z.boolean().optional(),
395
+ done_reason: z.string().optional(),
396
+ total_duration: z.number().optional(),
397
+ load_duration: z.number().optional(),
398
+ prompt_eval_count: z.number().optional(),
399
+ prompt_eval_cached_count: z.number().optional(),
400
+ prompt_eval_duration: z.number().optional(),
401
+ eval_count: z.number().optional(),
402
+ eval_duration: z.number().optional(),
403
+ logprobs: z.array(LogprobSchema).optional()
404
+ });
405
+ var ModelSummarySchema = z.object({
406
+ name: z.string().optional(),
407
+ model: z.string().optional(),
408
+ remote_model: z.string().optional(),
409
+ remote_host: z.string().optional(),
410
+ modified_at: z.string().optional(),
411
+ size: z.number().optional(),
412
+ digest: z.string().optional(),
413
+ details: z.object({
414
+ format: z.string().optional(),
415
+ family: z.string().optional(),
416
+ families: z.array(z.string()).optional(),
417
+ parameter_size: z.string().optional(),
418
+ quantization_level: z.string().optional()
419
+ }).optional()
420
+ });
421
+
422
+ // src/generated/models/ListResponse.schema.ts
423
+ var ListResponseSchema = z.object({
424
+ models: z.array(ModelSummarySchema).optional()
425
+ });
426
+ var PsSchema = z.object({
427
+ name: z.string().optional(),
428
+ model: z.string().optional(),
429
+ size: z.number().optional(),
430
+ digest: z.string().optional(),
431
+ details: z.object({}).optional(),
432
+ expires_at: z.string().optional(),
433
+ size_vram: z.number().optional(),
434
+ context_length: z.number().optional()
435
+ });
436
+
437
+ // src/generated/models/PsResponse.schema.ts
438
+ var PsResponseSchema = z.object({
439
+ models: z.array(PsSchema).optional()
440
+ });
225
441
  var PullRequestSchema = z.object({
226
442
  model: z.string(),
227
443
  insecure: z.boolean().optional(),
@@ -236,27 +452,164 @@ var ShowRequestSchema = z.object({
236
452
  model: z.string(),
237
453
  verbose: z.boolean().optional()
238
454
  });
455
+ var ThinkingSchema = z.object({
456
+ values: z.array(z.union([z.boolean(), z.string()])),
457
+ default: z.union([z.boolean(), z.string()])
458
+ });
459
+
460
+ // src/generated/models/ShowResponse.schema.ts
461
+ var ShowResponseSchema = z.object({
462
+ thinking: ThinkingSchema.optional(),
463
+ parameters: z.string().optional(),
464
+ license: z.string().optional(),
465
+ modified_at: z.string().optional(),
466
+ details: z.object({}).optional(),
467
+ template: z.string().optional(),
468
+ capabilities: z.array(z.string()).optional(),
469
+ model_info: z.object({}).optional()
470
+ });
471
+ var StatusResponseSchema = z.object({
472
+ status: z.string().optional()
473
+ });
474
+ var SystemOneContentSchema = z.union([
475
+ z.string().regex(new RegExp("\\S")),
476
+ z.object({}).catchall(z.unknown()),
477
+ z.array(z.unknown())
478
+ ]);
479
+
480
+ // src/generated/models/SystemOneChoiceQuestion.schema.ts
481
+ var SystemOneChoiceQuestionSchema = z.object({
482
+ type: z.enum(["choice"]),
483
+ instructions: SystemOneContentSchema,
484
+ criteria: z.object({}).catchall(z.union([z.string(), z.null()])).refine((v) => Object.keys(v).length >= 2, { message: "must have at least 2 properties" }).refine((v) => Object.keys(v).length <= 26, { message: "must have at most 26 properties" }).refine((v) => Object.keys(v).every((k) => new RegExp("\\S").test(k)), {
485
+ message: 'property names must match pattern "\\S"'
486
+ })
487
+ });
488
+ var SystemOneNoulQuestionSchema = z.object({
489
+ type: z.enum(["noul"]),
490
+ instructions: SystemOneContentSchema,
491
+ criteria: z.object({
492
+ false: z.string().optional(),
493
+ true: z.string().optional()
494
+ }).optional()
495
+ });
496
+ var SystemOneScoreQuestionSchema = z.object({
497
+ type: z.enum(["score"]),
498
+ instructions: SystemOneContentSchema,
499
+ criteria: z.array(z.string()).min(2).max(26)
500
+ });
501
+
502
+ // src/generated/models/SystemOneRequest.schema.ts
503
+ var SystemOneRequestSchema = z.object({
504
+ model: z.string().regex(new RegExp("\\S")),
505
+ state: SystemOneContentSchema,
506
+ images: z.array(z.string()).optional(),
507
+ questions: z.object({}).catchall(
508
+ z.union([
509
+ SystemOneChoiceQuestionSchema,
510
+ SystemOneNoulQuestionSchema,
511
+ SystemOneScoreQuestionSchema
512
+ ])
513
+ ).refine((v) => Object.keys(v).length >= 1, { message: "must have at least 1 properties" }).refine((v) => Object.keys(v).length <= 64, { message: "must have at most 64 properties" }).refine((v) => Object.keys(v).every((k) => new RegExp("\\S").test(k)), {
514
+ message: 'property names must match pattern "\\S"'
515
+ }),
516
+ keep_alive: z.union([z.string(), z.number()]).optional()
517
+ });
518
+ var SystemOneConfidenceSchema = z.number().min(0).max(1);
519
+ var SystemOneProbabilitiesSchema = z.object({}).catchall(z.number().min(0).max(1));
520
+
521
+ // src/generated/models/SystemOneChoiceAnswer.schema.ts
522
+ var SystemOneChoiceAnswerSchema = z.object({
523
+ type: z.enum(["choice"]),
524
+ choice: z.string(),
525
+ probabilities: SystemOneProbabilitiesSchema,
526
+ confidence: SystemOneConfidenceSchema
527
+ });
528
+ var SystemOneNoulAnswerSchema = z.object({
529
+ type: z.enum(["noul"]),
530
+ noul: z.number().min(0).max(1)
531
+ });
532
+ var SystemOneScoreAnswerSchema = z.object({
533
+ type: z.enum(["score"]),
534
+ score: z.number().min(0).max(25),
535
+ legend: z.object({}).catchall(z.string()),
536
+ probabilities: SystemOneProbabilitiesSchema,
537
+ confidence: SystemOneConfidenceSchema
538
+ });
539
+
540
+ // src/generated/models/SystemOneResponse.schema.ts
541
+ var SystemOneResponseSchema = z.object({
542
+ model: z.string(),
543
+ answers: z.object({}).catchall(
544
+ z.union([SystemOneChoiceAnswerSchema, SystemOneNoulAnswerSchema, SystemOneScoreAnswerSchema])
545
+ ),
546
+ usage: z.object({
547
+ input_tokens: z.number().min(0),
548
+ output_tokens: z.number().min(0)
549
+ })
550
+ });
551
+ var VersionResponseSchema = z.object({
552
+ version: z.string().optional()
553
+ });
554
+ var WebFetchRequestSchema = z.object({
555
+ url: z.string()
556
+ });
557
+ var WebFetchResponseSchema = z.object({
558
+ title: z.string().optional(),
559
+ content: z.string().optional(),
560
+ links: z.array(z.string()).optional()
561
+ });
562
+ var WebSearchRequestSchema = z.object({
563
+ query: z.string(),
564
+ max_results: z.number().min(1).max(10).optional()
565
+ });
566
+ var WebSearchResultSchema = z.object({
567
+ title: z.string().optional(),
568
+ url: z.string().optional(),
569
+ content: z.string().optional()
570
+ });
571
+
572
+ // src/generated/models/WebSearchResponse.schema.ts
573
+ var WebSearchResponseSchema = z.object({
574
+ results: z.array(WebSearchResultSchema).optional()
575
+ });
239
576
 
240
577
  // src/generated/runtime/schema-registry.ts
241
578
  var requestSchemas = {
242
579
  chat: ChatRequestSchema,
243
- generate: GenerateRequestSchema,
244
- embed: EmbedRequestSchema,
245
- create: CreateRequestSchema,
246
580
  copy: CopyRequestSchema,
581
+ create: CreateRequestSchema,
247
582
  delete: DeleteRequestSchema,
583
+ embed: EmbedRequestSchema,
584
+ generate: GenerateRequestSchema,
248
585
  pull: PullRequestSchema,
249
586
  push: PushRequestSchema,
250
- show: ShowRequestSchema
251
- // Operations without a registered request schema (blobs, ps, tags,
252
- // version, systemOne, openai*, anthropic*) skip validation. This is
253
- // deliberate — the OpenAPI spec doesn't define request bodies for
254
- // GET/HEAD operations, and the compat-surface request schemas (OpenAI,
255
- // Anthropic) are richer than what the IR currently models.
587
+ show: ShowRequestSchema,
588
+ systemOne: SystemOneRequestSchema,
589
+ webFetch: WebFetchRequestSchema,
590
+ webSearch: WebSearchRequestSchema
591
+ };
592
+ var responseSchemas = {
593
+ chat: ChatResponseSchema,
594
+ create: StatusResponseSchema,
595
+ embed: EmbedResponseSchema,
596
+ generate: GenerateResponseSchema,
597
+ ps: PsResponseSchema,
598
+ pull: StatusResponseSchema,
599
+ push: StatusResponseSchema,
600
+ show: ShowResponseSchema,
601
+ systemOne: SystemOneResponseSchema,
602
+ tags: ListResponseSchema,
603
+ version: VersionResponseSchema,
604
+ webFetch: WebFetchResponseSchema,
605
+ webSearch: WebSearchResponseSchema
256
606
  };
257
607
  function getRequestSchema(operationId) {
258
608
  return requestSchemas[operationId];
259
609
  }
610
+ function getResponseSchema(operationId) {
611
+ return responseSchemas[operationId];
612
+ }
260
613
 
261
614
  // src/generated/runtime/runtime.ts
262
615
  function compareVersions(a, b) {
@@ -269,18 +622,13 @@ function compareVersions(a, b) {
269
622
  }
270
623
  return 0;
271
624
  }
272
- function assertOperationAllowed(operation, options) {
273
- const localMode = options.localMode ?? true;
274
- if (!localMode && !operation.environment.cloud) {
275
- throw new OllamaGenericClientError(
276
- `Operation ${operation.operationId} (${operation.method} ${operation.path}) is local-only and not supported in cloud mode.`
277
- );
278
- }
279
- if (operation.constraints?.minOllamaVersion && options.serverVersion && compareVersions(options.serverVersion, operation.constraints.minOllamaVersion) < 0) {
280
- throw new OllamaGenericClientError(
281
- `Operation ${operation.operationId} (${operation.method} ${operation.path}) requires Ollama >= ${operation.constraints.minOllamaVersion} (server reports ${options.serverVersion}).`
282
- );
283
- }
625
+ async function fetchServerVersion(http) {
626
+ const result = await http.request({
627
+ path: "/api/version",
628
+ method: "GET"
629
+ });
630
+ if (result && typeof result.version === "string") return result.version;
631
+ return void 0;
284
632
  }
285
633
  function shouldStream(req) {
286
634
  if (req.body && typeof req.body === "object" && "stream" in req.body) {
@@ -303,6 +651,35 @@ var OllamaRuntime = class {
303
651
  this.options = options;
304
652
  }
305
653
  options;
654
+ /**
655
+ * Cached promise of the Ollama server version, populated lazily the first
656
+ * time a version-gated operation is invoked. `undefined` until then.
657
+ *
658
+ * Wave 12 (P0 #5): see {@link OllamaRuntimeOptions.enforceVersion}.
659
+ */
660
+ serverVersionCache;
661
+ /**
662
+ * Wave 15 (P0): resolve the HTTP backend for a given operation.
663
+ *
664
+ * Operations with a declared `host` (e.g. web search/fetch at
665
+ * https://ollama.com) must route to a HttpClient pointed at that host,
666
+ * not the default one. The runtime accepts an optional `cloudHttp`
667
+ * backend for this purpose — if the operation declares a host and no
668
+ * cloud backend is configured, the runtime throws rather than silently
669
+ * sending the request to the wrong server.
670
+ */
671
+ resolveHttpBackend(operation) {
672
+ if (operation.host) {
673
+ const cloudHttp = this.options.cloudHttp;
674
+ if (!cloudHttp) {
675
+ throw new OllamaGenericClientError(
676
+ `Operation ${operation.operationId} (${operation.method} ${operation.path}) targets host "${operation.host}" but the runtime has no cloudHttp backend configured. Use OllamaClient.webSearch() / OllamaClient.webFetch() for cloud-hosted operations, or construct OllamaRuntime with a cloudHttp option.`
677
+ );
678
+ }
679
+ return cloudHttp;
680
+ }
681
+ return this.options.http;
682
+ }
306
683
  /**
307
684
  * Invoke an operation. Called by every generated API method.
308
685
  *
@@ -311,7 +688,7 @@ var OllamaRuntime = class {
311
688
  * class's overloads pick the right return type at compile time.
312
689
  */
313
690
  async invoke(req) {
314
- assertOperationAllowed(req.operation, this.options);
691
+ await this.assertOperationAllowed(req.operation);
315
692
  let body = buildBody(req);
316
693
  if (this.options.validateRequests === true && body !== void 0) {
317
694
  const schema = getRequestSchema(req.operation.operationId);
@@ -330,32 +707,172 @@ var OllamaRuntime = class {
330
707
  body = result.data;
331
708
  }
332
709
  }
710
+ if (body !== void 0) {
711
+ const serialized = serializeForByteCount(body);
712
+ const hasImages = bodyHasImages(body);
713
+ const maxBytesWithImages = req.operation.constraints?.maxRequestBytesWithImages;
714
+ const maxBytesBase = req.operation.constraints?.maxRequestBytes;
715
+ const applicableLimit = hasImages && maxBytesWithImages !== void 0 ? maxBytesWithImages : maxBytesBase;
716
+ if (applicableLimit !== void 0 && serialized.byteLength > applicableLimit) {
717
+ throw new OllamaRequestTooLargeError(
718
+ `Operation ${req.operation.operationId} (${req.operation.method} ${req.operation.path}) request body is ${serialized.byteLength} bytes, exceeding the contract limit of ${applicableLimit} bytes` + (hasImages ? " (images limit)." : "."),
719
+ {
720
+ operationId: req.operation.operationId,
721
+ actualBytes: serialized.byteLength,
722
+ maxBytes: applicableLimit,
723
+ request: { method: req.operation.method, url: req.operation.path }
724
+ }
725
+ );
726
+ }
727
+ }
333
728
  const streaming = shouldStream(req);
729
+ const resolvedPath = resolvePathParams(req.operation.path, req.pathParams);
730
+ const model = req.model ?? extractModelFromBody(body);
334
731
  const httpReq = {
335
- path: req.operation.path,
732
+ path: resolvedPath,
336
733
  method: req.operation.method,
337
734
  ...body !== void 0 ? { body } : {},
338
735
  ...req.signal !== void 0 ? { signal: req.signal } : {},
339
- // For streaming calls, request the raw Response so we can pipe it
340
- // through parseNdjsonStream directly. This inherits middleware,
341
- // retry, telemetry, and error-mapping from HttpClient — the
342
- // previous Wave 3 implementation bypassed them with a direct
343
- // `fetch()` call.
344
- ...streaming ? { raw: true } : {}
736
+ ...streaming ? { raw: true } : {},
737
+ ...model !== void 0 ? { model } : {}
345
738
  };
346
739
  if (!streaming) {
347
- return await this.options.http.request(httpReq);
740
+ const result = await this.resolveHttpBackend(req.operation).request(httpReq);
741
+ if (this.options.validateResponses === true) {
742
+ const responseSchema = getResponseSchema(req.operation.operationId);
743
+ if (responseSchema) {
744
+ const result2 = responseSchema.safeParse(result);
745
+ if (!result2.success) {
746
+ throw new OllamaResponseValidationError(
747
+ `Response validation failed for operation "${req.operation.operationId}" (${req.operation.method} ${req.operation.path}): ` + result2.error.issues.map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`).join("; "),
748
+ {
749
+ operationId: req.operation.operationId,
750
+ issues: result2.error.issues,
751
+ request: { method: req.operation.method, url: req.operation.path }
752
+ }
753
+ );
754
+ }
755
+ }
756
+ }
757
+ return result;
348
758
  }
349
- const response = await this.options.http.request(httpReq);
759
+ const response = await this.resolveHttpBackend(req.operation).request(httpReq);
350
760
  if (!response.body) {
351
761
  throw new OllamaGenericClientError(
352
762
  `Operation ${req.operation.operationId}: streaming response had no body.`
353
763
  );
354
764
  }
355
- return parseNdjsonStream(response.body);
765
+ return parseStreamByMode(req.operation.transport.mode, response.body);
766
+ }
767
+ /**
768
+ * Apply environment + version guards before delegating to HttpClient.
769
+ *
770
+ * Throws {@link OllamaGenericClientError} when:
771
+ * - The operation is local-only and the runtime is in cloud mode.
772
+ * - The operation has `constraints.minOllamaVersion` and the server is older.
773
+ *
774
+ * Wave 12 (P0 #5): when `minOllamaVersion` is declared but the runtime's
775
+ * `serverVersion` is unknown AND `enforceVersion` is `'auto'` or
776
+ * `'strict'`, the runtime lazily fetches `/api/version` (cached on the
777
+ * runtime instance) so the constraint is actually enforced even when the
778
+ * caller didn't supply it. Previously the constraint was only enforced
779
+ * when `serverVersion` was manually supplied — meaning in practice it was
780
+ * almost never enforced.
781
+ */
782
+ async assertOperationAllowed(operation) {
783
+ const localMode = this.options.localMode ?? true;
784
+ if (!localMode && !operation.environment.cloud) {
785
+ throw new OllamaGenericClientError(
786
+ `Operation ${operation.operationId} (${operation.method} ${operation.path}) is local-only and not supported in cloud mode.`
787
+ );
788
+ }
789
+ const minVersion = operation.constraints?.minOllamaVersion;
790
+ if (!minVersion) return;
791
+ let serverVersion = this.options.serverVersion;
792
+ const policy = this.options.enforceVersion ?? "auto";
793
+ if (!serverVersion && policy !== "off") {
794
+ if (!this.serverVersionCache) {
795
+ const p = fetchServerVersion(this.options.http).catch((err) => {
796
+ if (policy === "strict") {
797
+ throw new OllamaServerVersionUnknownError(
798
+ `Operation ${operation.operationId} requires Ollama >= ${minVersion} but the runtime could not determine the server version (enforceVersion: 'strict').`,
799
+ {
800
+ operationId: operation.operationId,
801
+ minRequiredVersion: minVersion,
802
+ cause: err
803
+ }
804
+ );
805
+ }
806
+ return void 0;
807
+ });
808
+ this.serverVersionCache = p;
809
+ }
810
+ serverVersion = await this.serverVersionCache ?? void 0;
811
+ }
812
+ if (serverVersion && compareVersions(serverVersion, minVersion) < 0) {
813
+ throw new OllamaGenericClientError(
814
+ `Operation ${operation.operationId} (${operation.method} ${operation.path}) requires Ollama >= ${minVersion} (server reports ${serverVersion}).`
815
+ );
816
+ }
356
817
  }
357
818
  };
819
+ function parseStreamByMode(mode, body) {
820
+ if (mode === "ndjson") {
821
+ return parseNdjsonStream(body);
822
+ }
823
+ if (mode === "sse") {
824
+ return parseSseStreamAsJson(body);
825
+ }
826
+ throw new OllamaGenericClientError(
827
+ `Transport mode "${mode}" is not a streaming mode; cannot parse a stream for it.`
828
+ );
829
+ }
830
+ async function* parseSseStreamAsJson(body) {
831
+ for await (const event of parseSseStream(body)) {
832
+ const data = event.data;
833
+ if (!data) continue;
834
+ if (data === "[DONE]") return;
835
+ try {
836
+ yield JSON.parse(data);
837
+ } catch (err) {
838
+ throw new OllamaGenericClientError(`Failed to parse SSE event data as JSON: ${data}`, {
839
+ cause: err
840
+ });
841
+ }
842
+ }
843
+ }
844
+ function serializeForByteCount(body) {
845
+ if (body instanceof Uint8Array) return body;
846
+ if (typeof body === "string") return new TextEncoder().encode(body);
847
+ const json = JSON.stringify(body);
848
+ return new TextEncoder().encode(json);
849
+ }
850
+ function bodyHasImages(body) {
851
+ if (typeof body !== "object" || body === null) return false;
852
+ const obj = body;
853
+ const images = obj.images;
854
+ return Array.isArray(images) && images.length > 0;
855
+ }
856
+ function resolvePathParams(pathTemplate, pathParams) {
857
+ if (!pathTemplate.includes("{")) return pathTemplate;
858
+ const params = pathParams ?? {};
859
+ return pathTemplate.replace(/\{([^}]+)\}/g, (_match, name) => {
860
+ const value = params[name];
861
+ if (value === void 0) {
862
+ throw new OllamaGenericClientError(
863
+ `Missing path parameter "${name}" for path template "${pathTemplate}". Provide it via the pathParams field on the invoke() request.`
864
+ );
865
+ }
866
+ return encodeURIComponent(value);
867
+ });
868
+ }
869
+ function extractModelFromBody(body) {
870
+ if (typeof body !== "object" || body === null) return void 0;
871
+ const obj = body;
872
+ const model = obj.model;
873
+ return typeof model === "string" ? model : void 0;
874
+ }
358
875
 
359
- export { OllamaRuntime, getRequestSchema, requestSchemas };
876
+ export { OllamaRuntime, getRequestSchema, getResponseSchema, requestSchemas, responseSchemas };
360
877
  //# sourceMappingURL=generated-runtime.js.map
361
878
  //# sourceMappingURL=generated-runtime.js.map