@nemesis-oss/ollama-sdk 1.23.0 → 1.24.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.
package/dist/index.js CHANGED
@@ -781,30 +781,311 @@ function composeMiddleware(middlewares, finalHandler) {
781
781
  }
782
782
 
783
783
  // src/vision.ts
784
+ var DEFAULT_MAX_IMAGE_BYTES = 50 * 1024 * 1024;
785
+ var DEFAULT_FETCH_TIMEOUT_MS = 3e4;
786
+ var DEFAULT_MAX_REDIRECTS = 5;
787
+ function resolveImagePolicy(policy) {
788
+ const p = policy ?? {};
789
+ const fetchImpl = p.fetchImpl ?? globalThis.fetch;
790
+ if (fetchImpl === void 0) {
791
+ throw new OllamaClientError(
792
+ "No fetch implementation available to resolve image URLs: this runtime has no global `fetch`. Pass `imageResolution.fetchImpl` (or construct the client with `fetch`).",
793
+ { code: "image_fetch_unavailable" }
794
+ );
795
+ }
796
+ return {
797
+ maxImageBytes: p.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES,
798
+ fetchTimeoutMs: p.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
799
+ maxRedirects: p.maxRedirects ?? DEFAULT_MAX_REDIRECTS,
800
+ allowedHosts: p.allowedImageHosts,
801
+ allowPrivateNetworkAccess: p.allowPrivateNetworkAccess ?? false,
802
+ allowLocalFileReads: p.allowLocalFileReads ?? true,
803
+ fetchImpl,
804
+ addressLookup: p.addressLookup ?? nodeDnsLookup
805
+ };
806
+ }
784
807
  var DATA_URI_PATTERN = /^data:image\/[a-z0-9.+-]+;base64,/i;
785
808
  var IMAGE_FILE_EXTENSION_PATTERN = /\.(png|jpe?g|webp|gif|bmp|tiff?|avif)$/i;
809
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
786
810
  function imageStringNeedsResolution(input) {
787
811
  return DATA_URI_PATTERN.test(input) || input.startsWith("http://") || input.startsWith("https://") || IMAGE_FILE_EXTENSION_PATTERN.test(input);
788
812
  }
789
- function hasNodeFs() {
813
+ function hasNodeApis() {
790
814
  return typeof process !== "undefined" && process !== null && typeof process.versions?.node === "string";
791
815
  }
792
816
  var NODE_FS_MODULE = "node:fs";
793
- async function readFileAsBase64(path) {
794
- const { promises: fs } = await import(NODE_FS_MODULE);
795
- const data = await fs.readFile(path);
796
- return data.toString("base64");
817
+ var NODE_DNS_MODULE = "node:dns/promises";
818
+ function readHeader(res, name) {
819
+ try {
820
+ return typeof res.headers?.get === "function" ? res.headers.get(name) : null;
821
+ } catch {
822
+ return null;
823
+ }
824
+ }
825
+ function toError(value) {
826
+ return value instanceof Error ? value : new Error(String(value));
827
+ }
828
+ function errorMessage(value) {
829
+ return value instanceof Error ? value.message : String(value);
830
+ }
831
+ function parseIpv4(host) {
832
+ const parts = host.split(".");
833
+ if (parts.length !== 4) return void 0;
834
+ const octets = [];
835
+ for (const part of parts) {
836
+ if (!/^\d{1,3}$/.test(part)) return void 0;
837
+ const octet = Number(part);
838
+ if (octet > 255) return void 0;
839
+ octets.push(octet);
840
+ }
841
+ const [a = -1, b = -1, c = -1, d = -1] = octets;
842
+ return [a, b, c, d];
843
+ }
844
+ function isPrivateIpv4(octets) {
845
+ const [a, b, c] = octets;
846
+ if (a === 0 || a === 10 || a === 127) return true;
847
+ if (a === 100 && b >= 64 && b <= 127) return true;
848
+ if (a === 169 && b === 254) return true;
849
+ if (a === 172 && b >= 16 && b <= 31) return true;
850
+ if (a === 192 && (b === 168 || b === 0 || b === 2)) return true;
851
+ if (a === 198 && (b === 18 || b === 19)) return true;
852
+ if (a === 198 && b === 51 && c === 100) return true;
853
+ if (a === 203 && b === 0 && c === 113) return true;
854
+ if (a >= 224) return true;
855
+ return false;
856
+ }
857
+ function parseIpv6(host) {
858
+ let text = host;
859
+ const embedded = text.match(/^(.*)(\d{1,3}(?:\.\d{1,3}){3})$/);
860
+ if (embedded !== null) {
861
+ const v4 = parseIpv4(embedded[2] ?? "");
862
+ if (v4 === void 0) return void 0;
863
+ const hi = (v4[0] ?? 0) << 8 | (v4[1] ?? 0);
864
+ const lo = (v4[2] ?? 0) << 8 | (v4[3] ?? 0);
865
+ text = `${embedded[1] ?? ""}${hi.toString(16)}:${lo.toString(16)}`;
866
+ }
867
+ const halves = text.split("::");
868
+ if (halves.length > 2) return void 0;
869
+ const head = halves[0] === "" ? [] : (halves[0] ?? "").split(":");
870
+ const tail = halves.length === 2 ? halves[1] === "" ? [] : (halves[1] ?? "").split(":") : [];
871
+ const groups = [...head, ...tail];
872
+ const missing = 8 - groups.length;
873
+ if (halves.length === 2 ? missing < 0 : groups.length !== 8) return void 0;
874
+ const full = halves.length === 2 ? [...head, ...new Array(missing).fill("0"), ...tail] : groups;
875
+ let value = 0n;
876
+ for (const group of full) {
877
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return void 0;
878
+ value = value << 16n | BigInt(parseInt(group, 16));
879
+ }
880
+ return value;
881
+ }
882
+ function isPrivateIpv6(value) {
883
+ if (value === 0n || value === 1n) return true;
884
+ const topByte = value >> 120n & 0xffn;
885
+ if (topByte >= 0xfcn && topByte <= 0xfdn) return true;
886
+ if (topByte === 0xfen) return true;
887
+ if (topByte === 0xffn) return true;
888
+ if (value >> 32n === 0xffffn) {
889
+ return isPrivateIpv4(ipv4FromBits(value & 0xffffffffn));
890
+ }
891
+ if (value >> 96n === 0x64ff9bn) {
892
+ return isPrivateIpv4(ipv4FromBits(value & 0xffffffffn));
893
+ }
894
+ if (value >> 96n === 0x20010db8n) return true;
895
+ return false;
896
+ }
897
+ function ipv4FromBits(bits) {
898
+ const a = Number(bits >> 24n & 0xffn);
899
+ const b = Number(bits >> 16n & 0xffn);
900
+ const c = Number(bits >> 8n & 0xffn);
901
+ const d = Number(bits & 0xffn);
902
+ return [a, b, c, d];
903
+ }
904
+ function hostnameIsPrivate(hostname) {
905
+ const h = hostname.toLowerCase();
906
+ if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal") || h.endsWith(".home.arpa")) {
907
+ return true;
908
+ }
909
+ const v4 = parseIpv4(h);
910
+ if (v4 !== void 0) return isPrivateIpv4(v4);
911
+ if (/^[\d.]+$/.test(h)) return true;
912
+ const v6Host = h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
913
+ const v6 = parseIpv6(v6Host);
914
+ if (v6 !== void 0) return isPrivateIpv6(v6);
915
+ return false;
916
+ }
917
+ async function nodeDnsLookup(hostname) {
918
+ if (!hasNodeApis()) return void 0;
919
+ const dns = await import(NODE_DNS_MODULE);
920
+ return dns.lookup(hostname, { all: true });
921
+ }
922
+ async function resolvesToPrivateAddress(hostname, lookup) {
923
+ if (hostnameIsPrivate(hostname)) return true;
924
+ if (lookup === void 0) return false;
925
+ try {
926
+ const addresses = await lookup(hostname);
927
+ if (addresses === void 0) return false;
928
+ return addresses.some((entry) => hostnameIsPrivate(entry.address));
929
+ } catch {
930
+ return false;
931
+ }
932
+ }
933
+ function assertHostAllowed(url, allowedHosts) {
934
+ if (allowedHosts === void 0) return;
935
+ const hostname = url.hostname.toLowerCase();
936
+ for (const allowed of allowedHosts) {
937
+ const entry = allowed.toLowerCase();
938
+ if (entry === "*" || entry === hostname) return;
939
+ if (entry.startsWith("*.")) {
940
+ const suffix = entry.slice(1);
941
+ if (hostname.endsWith(suffix) && hostname.length > suffix.length) return;
942
+ }
943
+ }
944
+ throw new OllamaClientError(
945
+ `Image host "${url.hostname}" is not in allowedImageHosts (${allowedHosts.join(", ")}). Add the host, or clear the allowlist to permit any host.`,
946
+ { code: "image_host_not_allowed" }
947
+ );
948
+ }
949
+ function privateAddressError(target, url) {
950
+ return new OllamaClientError(
951
+ `Refusing to fetch image from private/reserved network address "${target}" ("${url.toString()}"). This default blocks SSRF when image URLs come from untrusted input. If this fetch is intentional and the host is genuinely yours, set 'imageResolution.allowPrivateNetworkAccess: true'.`,
952
+ { code: "image_private_address_blocked" }
953
+ );
797
954
  }
798
- async function fetchUrlAsBase64(url, signal) {
799
- const res = await fetch(url, signal !== void 0 ? { signal } : void 0);
800
- if (!res.ok) {
955
+ async function assertFetchableUrl(url, policy) {
956
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
957
+ throw new OllamaClientError(
958
+ `Image URL protocol must be http or https, got "${url.protocol}" for "${url.toString()}".`,
959
+ { code: "image_unsupported_protocol" }
960
+ );
961
+ }
962
+ assertHostAllowed(url, policy.allowedHosts);
963
+ if (!policy.allowPrivateNetworkAccess) {
964
+ if (hostnameIsPrivate(url.hostname)) throw privateAddressError(url.hostname, url);
965
+ if (await resolvesToPrivateAddress(url.hostname, policy.addressLookup)) {
966
+ throw privateAddressError(url.hostname, url);
967
+ }
968
+ }
969
+ }
970
+ async function readBodyCapped(res, maxBytes, source) {
971
+ const body = res.body;
972
+ if (body !== null && body !== void 0 && typeof body.getReader === "function") {
973
+ const reader = body.getReader();
974
+ const chunks = [];
975
+ let total = 0;
976
+ try {
977
+ for (; ; ) {
978
+ const { done, value } = await reader.read();
979
+ if (done === true) break;
980
+ if (value === void 0 || value === null) continue;
981
+ total += value.byteLength;
982
+ if (total > maxBytes) {
983
+ throw new OllamaClientError(
984
+ `Image from "${source}" exceeds the ${maxBytes}-byte maxImageBytes limit (at least ${total} bytes received so far). Raise 'imageResolution.maxImageBytes' if images this large are expected.`,
985
+ { code: "image_too_large" }
986
+ );
987
+ }
988
+ chunks.push(value);
989
+ }
990
+ } finally {
991
+ await reader.cancel().catch(() => {
992
+ });
993
+ }
994
+ const bytes = new Uint8Array(total);
995
+ let offset = 0;
996
+ for (const chunk of chunks) {
997
+ bytes.set(chunk, offset);
998
+ offset += chunk.byteLength;
999
+ }
1000
+ return bytes;
1001
+ }
1002
+ const buffered = new Uint8Array(await res.arrayBuffer());
1003
+ if (buffered.byteLength > maxBytes) {
1004
+ throw new OllamaClientError(
1005
+ `Image from "${source}" exceeds the ${maxBytes}-byte maxImageBytes limit (${buffered.byteLength} bytes). Raise 'imageResolution.maxImageBytes' if images this large are expected.`,
1006
+ { code: "image_too_large" }
1007
+ );
1008
+ }
1009
+ return buffered;
1010
+ }
1011
+ async function fetchUrlAsBase64(urlString, callerSignal, policy) {
1012
+ const manualRedirects = hasNodeApis();
1013
+ const controller = new AbortController();
1014
+ let timedOut = false;
1015
+ const followCallerAbort = () => {
1016
+ controller.abort();
1017
+ };
1018
+ if (callerSignal !== void 0) {
1019
+ if (callerSignal.aborted) controller.abort();
1020
+ else callerSignal.addEventListener("abort", followCallerAbort, { once: true });
1021
+ }
1022
+ const timer = setTimeout(() => {
1023
+ timedOut = true;
1024
+ controller.abort();
1025
+ }, policy.fetchTimeoutMs);
1026
+ const cleanup = () => {
1027
+ clearTimeout(timer);
1028
+ if (callerSignal !== void 0) {
1029
+ callerSignal.removeEventListener("abort", followCallerAbort);
1030
+ }
1031
+ };
1032
+ try {
1033
+ let current = new URL(urlString);
1034
+ for (let redirects = 0; ; redirects++) {
1035
+ await assertFetchableUrl(current, policy);
1036
+ const res = await policy.fetchImpl(current.toString(), {
1037
+ redirect: manualRedirects ? "manual" : "follow",
1038
+ signal: controller.signal
1039
+ });
1040
+ if (manualRedirects && REDIRECT_STATUSES.has(res.status)) {
1041
+ const location = readHeader(res, "location");
1042
+ if (location === null || location === "") {
1043
+ throw new OllamaClientError(
1044
+ `Failed to fetch image from URL "${current.toString()}": HTTP ${res.status} ${res.statusText} without a Location header.`,
1045
+ { code: "image_fetch_failed", status: res.status }
1046
+ );
1047
+ }
1048
+ if (redirects >= policy.maxRedirects) {
1049
+ throw new OllamaClientError(
1050
+ `Image fetch from "${urlString}" exceeded maxRedirects (${policy.maxRedirects}).`,
1051
+ { code: "image_redirect_limit" }
1052
+ );
1053
+ }
1054
+ current = new URL(location, current);
1055
+ continue;
1056
+ }
1057
+ if (!res.ok) {
1058
+ throw new OllamaClientError(
1059
+ `Failed to fetch image from URL "${current.toString()}": HTTP ${res.status} ${res.statusText}.`,
1060
+ { code: "image_fetch_failed", status: res.status }
1061
+ );
1062
+ }
1063
+ const bytes = await readBodyCapped(res, policy.maxImageBytes, current.toString());
1064
+ return encodeBytesBase64(bytes);
1065
+ }
1066
+ } catch (err) {
1067
+ if (err instanceof OllamaClientError) throw err;
1068
+ if (controller.signal.aborted) {
1069
+ if (timedOut) {
1070
+ throw new OllamaClientError(
1071
+ `Image fetch from URL "${urlString}" timed out after ${policy.fetchTimeoutMs} ms. Raise 'imageResolution.fetchTimeoutMs' if the source is legitimately slow.`,
1072
+ { code: "image_fetch_timeout", cause: toError(err) }
1073
+ );
1074
+ }
1075
+ if (callerSignal?.aborted === true) {
1076
+ throw new OllamaAbortError(
1077
+ `Image fetch from URL "${urlString}" was aborted by the request signal.`,
1078
+ { cause: toError(err) }
1079
+ );
1080
+ }
1081
+ }
801
1082
  throw new OllamaClientError(
802
- `Failed to fetch image from URL "${url}": HTTP ${res.status} ${res.statusText}.`,
803
- { code: "image_fetch_failed" }
1083
+ `Failed to fetch image from URL "${urlString}": ${errorMessage(err)}.`,
1084
+ { code: "image_fetch_failed", cause: toError(err) }
804
1085
  );
1086
+ } finally {
1087
+ cleanup();
805
1088
  }
806
- const arrayBuffer = await res.arrayBuffer();
807
- return encodeBytesBase64(new Uint8Array(arrayBuffer));
808
1089
  }
809
1090
  function encodeBytesBase64(bytes) {
810
1091
  const bufferCtor = globalThis.Buffer;
@@ -816,37 +1097,87 @@ function encodeBytesBase64(bytes) {
816
1097
  }
817
1098
  return btoa(binary);
818
1099
  }
819
- async function resolveImageInput(input, signal) {
1100
+ function estimateBase64Bytes(payload) {
1101
+ const compact = payload.replace(/\s+/g, "");
1102
+ let padding = 0;
1103
+ if (compact.endsWith("===")) padding = 3;
1104
+ else if (compact.endsWith("==")) padding = 2;
1105
+ else if (compact.endsWith("=")) padding = 1;
1106
+ return Math.floor(compact.length * 3 / 4) - padding;
1107
+ }
1108
+ async function readFileAsBase64(path, maxBytes) {
1109
+ const { promises: fs } = await import(NODE_FS_MODULE);
1110
+ const stat = await fs.stat(path);
1111
+ if (!stat.isFile()) {
1112
+ throw new OllamaClientError(`Vision input "${path}" is not a regular file.`, {
1113
+ code: "vision_path_read_failed"
1114
+ });
1115
+ }
1116
+ if (stat.size > maxBytes) {
1117
+ throw new OllamaClientError(
1118
+ `Image file "${path}" (${stat.size} bytes) exceeds the ${maxBytes}-byte maxImageBytes limit. Raise 'imageResolution.maxImageBytes' if images this large are expected.`,
1119
+ { code: "image_too_large" }
1120
+ );
1121
+ }
1122
+ const data = await fs.readFile(path);
1123
+ if (data.byteLength > maxBytes) {
1124
+ throw new OllamaClientError(
1125
+ `Image file "${path}" (${data.byteLength} bytes) exceeds the ${maxBytes}-byte maxImageBytes limit.`,
1126
+ { code: "image_too_large" }
1127
+ );
1128
+ }
1129
+ return data.toString("base64");
1130
+ }
1131
+ async function resolveImageInput(input, signal, policy) {
820
1132
  if (typeof input !== "string") {
821
1133
  return encodeBytesBase64(input instanceof Uint8Array ? input : new Uint8Array(input));
822
1134
  }
1135
+ const resolved = resolveImagePolicy(policy);
823
1136
  if (DATA_URI_PATTERN.test(input)) {
824
- return input.replace(DATA_URI_PATTERN, "").trim();
1137
+ const payload = input.replace(DATA_URI_PATTERN, "").trim();
1138
+ const estimated = estimateBase64Bytes(payload);
1139
+ if (estimated > resolved.maxImageBytes) {
1140
+ throw new OllamaClientError(
1141
+ `Data-URI image payload (~${estimated} bytes decoded) exceeds the ${resolved.maxImageBytes}-byte maxImageBytes limit. Raise 'imageResolution.maxImageBytes' if images this large are expected.`,
1142
+ { code: "image_too_large" }
1143
+ );
1144
+ }
1145
+ return payload;
825
1146
  }
826
1147
  if (input.startsWith("http://") || input.startsWith("https://")) {
827
- return fetchUrlAsBase64(input, signal);
1148
+ return fetchUrlAsBase64(input, signal, resolved);
828
1149
  }
829
1150
  if (IMAGE_FILE_EXTENSION_PATTERN.test(input)) {
830
- if (!hasNodeFs()) {
1151
+ if (!hasNodeApis()) {
831
1152
  throw new OllamaClientError(
832
1153
  `Vision input "${input}" looks like a local file path, but this runtime has no Node.js \`fs\` module (browser/edge). Read the file into bytes yourself and pass the \`Uint8Array\`, or pass a base64 string / data URI / http(s) URL instead.`,
833
1154
  { code: "vision_path_unsupported_runtime" }
834
1155
  );
835
1156
  }
1157
+ if (!resolved.allowLocalFileReads) {
1158
+ throw new OllamaClientError(
1159
+ `Vision input "${input}" looks like a local file path, but local file reads are disabled ('imageResolution.allowLocalFileReads: false'). Pass a \`Uint8Array\`, a base64 string, a data URI, or an http(s) URL instead.`,
1160
+ { code: "vision_local_reads_disabled" }
1161
+ );
1162
+ }
836
1163
  try {
837
- return await readFileAsBase64(input);
838
- } catch {
839
- return input;
1164
+ return await readFileAsBase64(input, resolved.maxImageBytes);
1165
+ } catch (err) {
1166
+ if (err instanceof OllamaClientError) throw err;
1167
+ throw new OllamaClientError(
1168
+ `Failed to read vision input file "${input}": ${errorMessage(err)}. Pass the file's bytes as \`Uint8Array\`, a base64 string, or a data URI instead.`,
1169
+ { code: "vision_path_read_failed", cause: toError(err) }
1170
+ );
840
1171
  }
841
1172
  }
842
1173
  return input.trim();
843
1174
  }
844
- async function resolveImages(images, signal) {
1175
+ async function resolveImages(images, signal, policy) {
845
1176
  if (images === void 0) return void 0;
846
1177
  if (images.every((image) => typeof image === "string" && !imageStringNeedsResolution(image))) {
847
1178
  return images;
848
1179
  }
849
- return Promise.all(images.map((image) => resolveImageInput(image, signal)));
1180
+ return Promise.all(images.map((image) => resolveImageInput(image, signal, policy)));
850
1181
  }
851
1182
 
852
1183
  // src/utils.ts
@@ -861,22 +1192,22 @@ async function encodeImage(image) {
861
1192
  }
862
1193
  return btoa(binary);
863
1194
  }
864
- async function encodeImages(images, signal) {
865
- return resolveImages(images, signal);
1195
+ async function encodeImages(images, signal, policy) {
1196
+ return resolveImages(images, signal, policy);
866
1197
  }
867
- async function withEncodedImages(req, signal) {
1198
+ async function withEncodedImages(req, signal, policy) {
868
1199
  const needsResolution = req.images?.some(
869
1200
  (image) => typeof image !== "string" || imageStringNeedsResolution(image)
870
1201
  );
871
1202
  if (!needsResolution) return req;
872
- return { ...req, images: await encodeImages(req.images ?? [], signal) };
1203
+ return { ...req, images: await encodeImages(req.images ?? [], signal, policy) };
873
1204
  }
874
- async function withEncodedMessageImages(messages, signal) {
1205
+ async function withEncodedMessageImages(messages, signal, policy) {
875
1206
  const needsResolution = messages.some(
876
1207
  (message) => message.images?.some((image) => typeof image !== "string" || imageStringNeedsResolution(image))
877
1208
  );
878
1209
  if (!needsResolution) return messages;
879
- return Promise.all(messages.map((message) => withEncodedImages(message, signal)));
1210
+ return Promise.all(messages.map((message) => withEncodedImages(message, signal, policy)));
880
1211
  }
881
1212
  function disposableTimer(timer) {
882
1213
  return {
@@ -2457,7 +2788,13 @@ function normalizeChatStream(source, signal) {
2457
2788
  model: "",
2458
2789
  done: false
2459
2790
  };
2460
- return new OllamaStream(withStableToolCallIds(source), mapChatChunk, aggregateChat, initial, signal);
2791
+ return new OllamaStream(
2792
+ withStableToolCallIds(source),
2793
+ mapChatChunk,
2794
+ aggregateChat,
2795
+ initial,
2796
+ signal
2797
+ );
2461
2798
  }
2462
2799
  function aggregateGenerate(accumulated, chunk) {
2463
2800
  return {
@@ -3837,11 +4174,7 @@ function sanitizeAnthropicRequest(request) {
3837
4174
  };
3838
4175
  });
3839
4176
  const system = Array.isArray(request.system) ? request.system.map(sanitizeAnthropicTextBlock) : request.system;
3840
- const {
3841
- tool_choice: _toolChoice,
3842
- metadata: _metadata,
3843
- ...sanitized
3844
- } = request;
4177
+ const { tool_choice: _toolChoice, metadata: _metadata, ...sanitized } = request;
3845
4178
  return {
3846
4179
  ...sanitized,
3847
4180
  messages,
@@ -3908,7 +4241,10 @@ var AnthropicMessagesStream = class {
3908
4241
  } else if (event.type === "content_block_delta") {
3909
4242
  const current = blocks.get(event.index);
3910
4243
  if (event.delta.type === "input_json_delta") {
3911
- toolInputJson.set(event.index, (toolInputJson.get(event.index) ?? "") + event.delta.partial_json);
4244
+ toolInputJson.set(
4245
+ event.index,
4246
+ (toolInputJson.get(event.index) ?? "") + event.delta.partial_json
4247
+ );
3912
4248
  }
3913
4249
  if (current) blocks.set(event.index, mergeContentBlock(current, event.delta));
3914
4250
  } else if (event.type === "content_block_stop") {
@@ -3934,7 +4270,9 @@ var AnthropicMessagesStream = class {
3934
4270
  usage: {
3935
4271
  input_tokens: event.usage.input_tokens ?? message.usage?.input_tokens ?? 0,
3936
4272
  output_tokens: event.usage.output_tokens,
3937
- ...event.usage.cache_creation_input_tokens !== void 0 ? { cache_creation_input_tokens: event.usage.cache_creation_input_tokens } : message.usage?.cache_creation_input_tokens !== void 0 ? { cache_creation_input_tokens: message.usage.cache_creation_input_tokens } : {},
4273
+ ...event.usage.cache_creation_input_tokens !== void 0 ? { cache_creation_input_tokens: event.usage.cache_creation_input_tokens } : message.usage?.cache_creation_input_tokens !== void 0 ? {
4274
+ cache_creation_input_tokens: message.usage.cache_creation_input_tokens
4275
+ } : {},
3938
4276
  ...event.usage.cache_read_input_tokens !== void 0 ? { cache_read_input_tokens: event.usage.cache_read_input_tokens } : message.usage?.cache_read_input_tokens !== void 0 ? { cache_read_input_tokens: message.usage.cache_read_input_tokens } : {},
3939
4277
  ...event.usage.cache_creation !== void 0 ? { cache_creation: event.usage.cache_creation } : message.usage?.cache_creation !== void 0 ? { cache_creation: message.usage.cache_creation } : {}
3940
4278
  }
@@ -3980,14 +4318,11 @@ var AnthropicCompatClient = class {
3980
4318
  }
3981
4319
  request(operation, model, signal, holdUntil) {
3982
4320
  if (this.runner) {
3983
- return this.runner(
3984
- (http, runnerSignal) => operation(http, runnerSignal),
3985
- {
3986
- model,
3987
- ...signal !== void 0 ? { signal } : {},
3988
- ...holdUntil !== void 0 ? { holdUntil } : {}
3989
- }
3990
- );
4321
+ return this.runner((http, runnerSignal) => operation(http, runnerSignal), {
4322
+ model,
4323
+ ...signal !== void 0 ? { signal } : {},
4324
+ ...holdUntil !== void 0 ? { holdUntil } : {}
4325
+ });
3991
4326
  }
3992
4327
  return operation(this.http, signal);
3993
4328
  }
@@ -5873,6 +6208,13 @@ var OllamaClient = class _OllamaClient {
5873
6208
  timeoutMs;
5874
6209
  failoverCodes;
5875
6210
  fetchImpl;
6211
+ /**
6212
+ * Effective vision-resolution policy: the client's configured `fetch` by
6213
+ * default (so image fetches flow through the caller's proxy/mock), with
6214
+ * `config.imageResolution` layered on top — an explicit `fetchImpl` there
6215
+ * wins. See `ImageResolutionPolicy` and ADR 0041.
6216
+ */
6217
+ imagePolicy;
5876
6218
  logger;
5877
6219
  middleware;
5878
6220
  onLifecycleEvent;
@@ -5928,6 +6270,7 @@ var OllamaClient = class _OllamaClient {
5928
6270
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
5929
6271
  this.failoverCodes = new Set(config.failoverOn ?? DEFAULT_FAILOVER_CODES);
5930
6272
  this.fetchImpl = config.fetch ?? globalThis.fetch;
6273
+ this.imagePolicy = { fetchImpl: this.fetchImpl, ...config.imageResolution };
5931
6274
  this.logger = config.logger ?? (config.debug ? createConsoleLogger() : NOOP_LOGGER);
5932
6275
  this.middleware = config.middleware;
5933
6276
  this.onLifecycleEvent = config.onLifecycleEvent;
@@ -6225,7 +6568,11 @@ var OllamaClient = class _OllamaClient {
6225
6568
  }
6226
6569
  }
6227
6570
  async chat(req) {
6228
- const encodedMessages = await withEncodedMessageImages(req.messages, req.signal);
6571
+ const encodedMessages = await withEncodedMessageImages(
6572
+ req.messages,
6573
+ req.signal,
6574
+ this.imagePolicy
6575
+ );
6229
6576
  const messages = encodedMessages.map((message) => {
6230
6577
  if (message.role === "tool" && message.tool_call_id !== void 0) {
6231
6578
  const { tool_call_id: _toolCallId, ...nativeMessage } = message;
@@ -6304,7 +6651,7 @@ var OllamaClient = class _OllamaClient {
6304
6651
  return parseStructuredOutput(res.message.content, schema);
6305
6652
  }
6306
6653
  async generate(req) {
6307
- const encodedReq = await withEncodedImages(req, req.signal);
6654
+ const encodedReq = await withEncodedImages(req, req.signal, this.imagePolicy);
6308
6655
  this.enforceContextSafety(
6309
6656
  "generate",
6310
6657
  checkGenerateContext(req, {
@@ -7628,27 +7975,38 @@ function validate(value, schema, path) {
7628
7975
  if (Array.isArray(type) && !type.some((t) => typeof t === "string" && matchesType(value, t))) {
7629
7976
  return [{ path, message: label(path) + " must match one of: " + type.join(", ") }];
7630
7977
  }
7631
- if ("const" in s && !equalJson(value, s["const"])) issues.push({ path, message: label(path) + " must equal the schema const value" });
7978
+ if ("const" in s && !equalJson(value, s["const"]))
7979
+ issues.push({ path, message: label(path) + " must equal the schema const value" });
7632
7980
  const enumValues = s["enum"];
7633
- if (Array.isArray(enumValues) && !enumValues.some((item) => equalJson(value, item))) issues.push({ path, message: label(path) + " must be one of the allowed enum values" });
7981
+ if (Array.isArray(enumValues) && !enumValues.some((item) => equalJson(value, item)))
7982
+ issues.push({ path, message: label(path) + " must be one of the allowed enum values" });
7634
7983
  const anyOf = s["anyOf"];
7635
- if (Array.isArray(anyOf) && !anyOf.some((candidate) => validate(value, candidate, path).length === 0)) issues.push({ path, message: label(path) + " must satisfy at least one anyOf schema" });
7984
+ if (Array.isArray(anyOf) && !anyOf.some((candidate) => validate(value, candidate, path).length === 0))
7985
+ issues.push({ path, message: label(path) + " must satisfy at least one anyOf schema" });
7636
7986
  const oneOf = s["oneOf"];
7637
7987
  if (Array.isArray(oneOf)) {
7638
- const matches = oneOf.filter((candidate) => validate(value, candidate, path).length === 0).length;
7639
- if (matches !== 1) issues.push({ path, message: label(path) + " must satisfy exactly one oneOf schema" });
7988
+ const matches = oneOf.filter(
7989
+ (candidate) => validate(value, candidate, path).length === 0
7990
+ ).length;
7991
+ if (matches !== 1)
7992
+ issues.push({ path, message: label(path) + " must satisfy exactly one oneOf schema" });
7640
7993
  }
7641
7994
  const allOf = s["allOf"];
7642
- if (Array.isArray(allOf)) for (const candidate of allOf) issues.push(...validate(value, candidate, path));
7643
- if ("not" in s && validate(value, s["not"], path).length === 0) issues.push({ path, message: label(path) + " must not satisfy the not schema" });
7995
+ if (Array.isArray(allOf))
7996
+ for (const candidate of allOf) issues.push(...validate(value, candidate, path));
7997
+ if ("not" in s && validate(value, s["not"], path).length === 0)
7998
+ issues.push({ path, message: label(path) + " must not satisfy the not schema" });
7644
7999
  if (typeof value === "string") {
7645
8000
  const min = s["minLength"];
7646
8001
  const max = s["maxLength"];
7647
- if (typeof min === "number" && value.length < min) issues.push({ path, message: label(path) + " must have at least " + min + " characters" });
7648
- if (typeof max === "number" && value.length > max) issues.push({ path, message: label(path) + " must have at most " + max + " characters" });
8002
+ if (typeof min === "number" && value.length < min)
8003
+ issues.push({ path, message: label(path) + " must have at least " + min + " characters" });
8004
+ if (typeof max === "number" && value.length > max)
8005
+ issues.push({ path, message: label(path) + " must have at most " + max + " characters" });
7649
8006
  if (typeof s["pattern"] === "string") {
7650
8007
  try {
7651
- if (!new RegExp(s["pattern"]).test(value)) issues.push({ path, message: label(path) + " does not match the required pattern" });
8008
+ if (!new RegExp(s["pattern"]).test(value))
8009
+ issues.push({ path, message: label(path) + " does not match the required pattern" });
7652
8010
  } catch {
7653
8011
  }
7654
8012
  }
@@ -7662,51 +8020,65 @@ function validate(value, schema, path) {
7662
8020
  ];
7663
8021
  for (const [keyword, check2, phrase] of numericRules) {
7664
8022
  const bound = s[keyword];
7665
- if (typeof bound === "number" && !check2(value, bound)) issues.push({ path, message: label(path) + " " + phrase + " " + bound });
8023
+ if (typeof bound === "number" && !check2(value, bound))
8024
+ issues.push({ path, message: label(path) + " " + phrase + " " + bound });
7666
8025
  }
7667
8026
  const multipleOf = s["multipleOf"];
7668
8027
  if (typeof multipleOf === "number" && multipleOf > 0) {
7669
8028
  const quotient = value / multipleOf;
7670
- if (Math.abs(quotient - Math.round(quotient)) > 1e-12) issues.push({ path, message: label(path) + " must be a multiple of " + multipleOf });
8029
+ if (Math.abs(quotient - Math.round(quotient)) > 1e-12)
8030
+ issues.push({ path, message: label(path) + " must be a multiple of " + multipleOf });
7671
8031
  }
7672
8032
  }
7673
8033
  if (Array.isArray(value)) {
7674
8034
  const min = s["minItems"];
7675
8035
  const max = s["maxItems"];
7676
- if (typeof min === "number" && value.length < min) issues.push({ path, message: label(path) + " must contain at least " + min + " items" });
7677
- if (typeof max === "number" && value.length > max) issues.push({ path, message: label(path) + " must contain at most " + max + " items" });
8036
+ if (typeof min === "number" && value.length < min)
8037
+ issues.push({ path, message: label(path) + " must contain at least " + min + " items" });
8038
+ if (typeof max === "number" && value.length > max)
8039
+ issues.push({ path, message: label(path) + " must contain at most " + max + " items" });
7678
8040
  if (s["uniqueItems"] === true) {
7679
- for (let i = 0; i < value.length; i += 1) if (value.slice(0, i).some((previous) => equalJson(previous, value[i]))) {
7680
- issues.push({ path: [...path, i], message: label([...path, i]) + " must be unique" });
7681
- break;
7682
- }
8041
+ for (let i = 0; i < value.length; i += 1)
8042
+ if (value.slice(0, i).some((previous) => equalJson(previous, value[i]))) {
8043
+ issues.push({ path: [...path, i], message: label([...path, i]) + " must be unique" });
8044
+ break;
8045
+ }
7683
8046
  }
7684
- if ("items" in s) value.forEach((item, i) => issues.push(...validate(item, s["items"], [...path, i])));
7685
- if (Array.isArray(s["prefixItems"])) s["prefixItems"].forEach((itemSchema, i) => {
7686
- if (i < value.length) issues.push(...validate(value[i], itemSchema, [...path, i]));
7687
- });
8047
+ if ("items" in s)
8048
+ value.forEach((item, i) => issues.push(...validate(item, s["items"], [...path, i])));
8049
+ if (Array.isArray(s["prefixItems"]))
8050
+ s["prefixItems"].forEach((itemSchema, i) => {
8051
+ if (i < value.length) issues.push(...validate(value[i], itemSchema, [...path, i]));
8052
+ });
7688
8053
  }
7689
8054
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
7690
8055
  const object = value;
7691
8056
  const required = s["required"];
7692
8057
  if (Array.isArray(required)) {
7693
- for (const key of required) if (typeof key === "string" && !(key in object)) issues.push({ path: [...path, key], message: label([...path, key]) + " is required" });
8058
+ for (const key of required)
8059
+ if (typeof key === "string" && !(key in object))
8060
+ issues.push({ path: [...path, key], message: label([...path, key]) + " is required" });
7694
8061
  }
7695
8062
  const properties = s["properties"];
7696
8063
  if (typeof properties === "object" && properties !== null && !Array.isArray(properties)) {
7697
8064
  const propertySchemas = properties;
7698
- for (const [key, propertySchema] of Object.entries(propertySchemas)) if (key in object) issues.push(...validate(object[key], propertySchema, [...path, key]));
8065
+ for (const [key, propertySchema] of Object.entries(propertySchemas))
8066
+ if (key in object) issues.push(...validate(object[key], propertySchema, [...path, key]));
7699
8067
  const additional = s["additionalProperties"];
7700
8068
  for (const key of Object.keys(object)) {
7701
8069
  if (key in propertySchemas) continue;
7702
- if (additional === false) issues.push({ path: [...path, key], message: label([...path, key]) + " is not allowed" });
7703
- else if (additional !== true && additional !== void 0) issues.push(...validate(object[key], additional, [...path, key]));
8070
+ if (additional === false)
8071
+ issues.push({ path: [...path, key], message: label([...path, key]) + " is not allowed" });
8072
+ else if (additional !== true && additional !== void 0)
8073
+ issues.push(...validate(object[key], additional, [...path, key]));
7704
8074
  }
7705
8075
  }
7706
8076
  const min = s["minProperties"];
7707
8077
  const max = s["maxProperties"];
7708
- if (typeof min === "number" && Object.keys(object).length < min) issues.push({ path, message: label(path) + " must contain at least " + min + " properties" });
7709
- if (typeof max === "number" && Object.keys(object).length > max) issues.push({ path, message: label(path) + " must contain at most " + max + " properties" });
8078
+ if (typeof min === "number" && Object.keys(object).length < min)
8079
+ issues.push({ path, message: label(path) + " must contain at least " + min + " properties" });
8080
+ if (typeof max === "number" && Object.keys(object).length > max)
8081
+ issues.push({ path, message: label(path) + " must contain at most " + max + " properties" });
7710
8082
  }
7711
8083
  return issues;
7712
8084
  }
@@ -7734,10 +8106,10 @@ async function listAllMcpTools(mcpClient, options = {}, signal) {
7734
8106
  const pageNames = /* @__PURE__ */ new Set();
7735
8107
  for (const tool of page.tools) {
7736
8108
  if (pageNames.has(tool.name)) {
7737
- throw new OllamaMcpError(
7738
- `MCP tools/list returned duplicate tool name "${tool.name}"`,
7739
- { mcpMethod: "listTools", toolName: tool.name }
7740
- );
8109
+ throw new OllamaMcpError(`MCP tools/list returned duplicate tool name "${tool.name}"`, {
8110
+ mcpMethod: "listTools",
8111
+ toolName: tool.name
8112
+ });
7741
8113
  }
7742
8114
  pageNames.add(tool.name);
7743
8115
  if (tools.some((existing) => existing.name === tool.name)) {
@@ -7879,11 +8251,7 @@ async function loadMcpTools(mcpClient, options = {}, signal) {
7879
8251
  const tools = await listAllMcpTools(mcpClient, options, signal);
7880
8252
  const serverSupportsTasks = supportsTaskCalls(mcpClient);
7881
8253
  return tools.map((tool) => {
7882
- const taskCall = shouldCallAsTask(
7883
- tool,
7884
- options,
7885
- serverSupportsTasks
7886
- );
8254
+ const taskCall = shouldCallAsTask(tool, options, serverSupportsTasks);
7887
8255
  return convertMcpDescriptorToTool(
7888
8256
  tool,
7889
8257
  mcpClient,
@@ -7956,37 +8324,21 @@ var McpBridge = class _McpBridge {
7956
8324
  }
7957
8325
  /** Fetches one legacy MCP task's current status without starting a polling loop. */
7958
8326
  async getTaskStatus(taskId, signal) {
7959
- return this.requestTask(
7960
- "tasks/get",
7961
- taskId,
7962
- taskSchema,
7963
- signal
7964
- );
8327
+ return this.requestTask("tasks/get", taskId, taskSchema, signal);
7965
8328
  }
7966
8329
  /** Retrieves a completed legacy MCP task's result. */
7967
8330
  async getTaskResult(taskId, signal) {
7968
- return this.requestTask(
7969
- "tasks/result",
7970
- taskId,
7971
- callToolResultSchema,
7972
- signal
7973
- );
8331
+ return this.requestTask("tasks/result", taskId, callToolResultSchema, signal);
7974
8332
  }
7975
8333
  /** Cancels one legacy MCP task. */
7976
8334
  async cancelTask(taskId, signal) {
7977
- return this.requestTask(
7978
- "tasks/cancel",
7979
- taskId,
7980
- taskSchema,
7981
- signal
7982
- );
8335
+ return this.requestTask("tasks/cancel", taskId, taskSchema, signal);
7983
8336
  }
7984
8337
  requestTask(method, taskId, resultSchema, signal) {
7985
8338
  if (this.client.request === void 0) {
7986
- throw new OllamaMcpError(
7987
- `MCP client does not support ${method} requests`,
7988
- { mcpMethod: method }
7989
- );
8339
+ throw new OllamaMcpError(`MCP client does not support ${method} requests`, {
8340
+ mcpMethod: method
8341
+ });
7990
8342
  }
7991
8343
  return this.client.request(
7992
8344
  { method, params: { taskId } },