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