@eum-agent/llm-protocol-ollama 1.1.0 → 1.2.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/assets/NOTICE CHANGED
@@ -1,5 +1,7 @@
1
- Ollama mark: exact official SVG from https://github.com/ollama/ollama/blob/main/docs/logo.svg
2
- Retrieved 2026-10-17. SHA-256: cfcdccd391bdff7c16b55eb9f6e13aa8b8bfe9f6e4a75a3a39783a6a1601c45f
1
+ Ollama mark: official SVG from https://github.com/ollama/ollama/blob/main/docs/logo.svg
2
+ Retrieved 2026-10-17. Official file SHA-256: cfcdccd391bdff7c16b55eb9f6e13aa8b8bfe9f6e4a75a3a39783a6a1601c45f
3
+ assets/ollama.svg adds only <title>Ollama</title> after the opening <svg> tag.
4
+ Shipped file SHA-256: b128458c1f03cca44ca2dc642226179e030692c7104bb8e175f4ba79c03a091e
3
5
  Ollama trademarks remain the property of their respective owner.
4
6
 
5
7
  Native API references: https://docs.ollama.com/api/chat and https://docs.ollama.com/capabilities/thinking
package/dist/index.js CHANGED
@@ -1,15 +1,12 @@
1
1
  import { z } from "zod";
2
- import { randomUUID } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  //#region src/http.ts
4
- /** Bounded transport shared by read-only discovery and native model streams. */
5
- /** Validates a daemon root without credentials, query parameters or a resource suffix. */
6
4
  function daemonRoot(value) {
7
5
  if (typeof value !== "string" || value.length > 4096) throw new Error("Invalid Ollama Base URL");
8
6
  const url = new URL(value);
9
7
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || /\/(?:api(?:\/(?:chat|generate|show|tags|version))?|v1)\/?$/.test(url.pathname)) throw new Error("Ollama Base URL must identify the daemon root");
10
8
  return url.href.replace(/\/$/, "");
11
9
  }
12
- /** Reads one stream operation while observing cancellation even in transport doubles. */
13
10
  async function abortable(work, signal) {
14
11
  signal.throwIfAborted();
15
12
  let abort = () => {};
@@ -23,19 +20,31 @@ async function abortable(work, signal) {
23
20
  signal.removeEventListener("abort", abort);
24
21
  }
25
22
  }
26
- /** HTTP failure contains a status only; daemon error text is never copied into diagnostics. */
27
23
  var DaemonHttpError = class extends Error {
28
- /** Response status reported by the daemon. */
29
24
  status;
30
- /** Records a refused response without retaining its headers or body. */
31
- constructor(status) {
25
+ contextWindowExceeded;
26
+ constructor(status, contextWindowExceeded = false) {
32
27
  super("Ollama HTTP request failed");
33
28
  this.status = status;
29
+ this.contextWindowExceeded = contextWindowExceeded;
34
30
  }
35
31
  };
36
- /** Fetches one native resource without authentication, redirects or ambient provider credentials. */
37
- async function daemonFetch(fetch, root, resource, signal, body) {
38
- const response = await abortable(fetch(`${root}/api/${resource}`, {
32
+ const CONTEXT_WINDOW_REFUSALS = [
33
+ /prompt is longer than the context length/i,
34
+ /exceeds the available context size/i,
35
+ /exceeds the model's maximum context length/i
36
+ ];
37
+ async function refusedForContext(response, signal) {
38
+ try {
39
+ const message = (await readJson(response, signal, { remaining: 65536 }))?.error;
40
+ return typeof message === "string" && CONTEXT_WINDOW_REFUSALS.some((one) => one.test(message));
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+ async function daemonFetch(fetch, root, resource, signal, body, scope) {
46
+ signal.throwIfAborted();
47
+ const pending = fetch(`${root}/api/${resource}`, {
39
48
  method: body === void 0 ? "GET" : "POST",
40
49
  redirect: "error",
41
50
  signal,
@@ -43,14 +52,29 @@ async function daemonFetch(fetch, root, resource, signal, body) {
43
52
  headers: { "content-type": "application/json" },
44
53
  body: JSON.stringify(body)
45
54
  }
46
- }), signal);
55
+ });
56
+ let response;
57
+ try {
58
+ response = await abortable(pending, signal);
59
+ } catch (error) {
60
+ const closeLate = async () => {
61
+ await (await pending.catch(() => void 0))?.body?.cancel();
62
+ };
63
+ if (scope) scope.retainCleanup(closeLate).catch(() => {});
64
+ else await closeLate();
65
+ throw error;
66
+ }
47
67
  if (!response.ok) {
48
- await response.body?.cancel().catch(() => {});
49
- throw new DaemonHttpError(response.status);
68
+ const contextWindowExceeded = await refusedForContext(response, signal);
69
+ const close = async () => {
70
+ await response.body?.cancel();
71
+ };
72
+ if (scope) scope.retainCleanup(close).catch(() => {});
73
+ else await close();
74
+ throw new DaemonHttpError(response.status, contextWindowExceeded);
50
75
  }
51
76
  return response;
52
77
  }
53
- /** Decodes a JSON response under the shared raw byte allowance before allocation or parsing. */
54
78
  async function readJson(response, signal, budget) {
55
79
  const reader = response.body?.getReader();
56
80
  if (!reader) throw new Error("Ollama returned an empty body");
@@ -69,7 +93,6 @@ async function readJson(response, signal, budget) {
69
93
  reader.releaseLock();
70
94
  }
71
95
  }
72
- /** Parses finite NDJSON, rejecting invalid UTF-8, oversize frames and unterminated streams. */
73
96
  async function* readFrames(response, signal, maxBytes = 67108864, frameBytes = 8388608) {
74
97
  const reader = response.body?.getReader();
75
98
  if (!reader) throw new Error("Ollama returned an empty stream");
@@ -133,19 +156,16 @@ const evidenceSchema = z.strictObject({
133
156
  version: z.string(),
134
157
  models: z.array(evidenceRow).max(1e3)
135
158
  });
136
- /** Exact experimental native image wire verified against the official release source. */
137
159
  const IMAGE_PROFILE = "image-v1:0.15.1";
138
160
  function imageProfile(version, capabilities) {
139
161
  return version === "0.15.1" && capabilities?.includes("image") ? IMAGE_PROFILE : void 0;
140
162
  }
141
- /** Creates a compact protocol-owned profile from exact model capabilities. */
142
163
  function profileOf(capabilities, thinking) {
143
164
  if (!capabilities?.includes("completion")) return void 0;
144
165
  const flags = `${capabilities.includes("vision") ? 1 : 0}${capabilities.includes("tools") ? 1 : 0}${capabilities.includes("thinking") ? 1 : 0}`;
145
166
  const values = thinking?.values ?? [];
146
167
  return `chat-v1:${flags}:${Buffer.from(JSON.stringify(values)).toString("base64url")}`;
147
168
  }
148
- /** Validates a saved conversation profile without querying mutable discovery caches. */
149
169
  function parseChatProfile(profile) {
150
170
  const match = /^chat-v1:([01])([01])([01]):([A-Za-z0-9_-]+)$/.exec(profile);
151
171
  if (!match) return void 0;
@@ -165,12 +185,11 @@ function parseChatProfile(profile) {
165
185
  function remote(row) {
166
186
  return Boolean(row.remote_model || row.remote_host);
167
187
  }
168
- /** Discovers installed local weights with bounded show concurrency and before/after tag identity. */
169
- async function discoverModels(probe, fetch) {
188
+ async function discoverModels(probe, fetch, scope) {
170
189
  const signal = AbortSignal.any([probe.signal, AbortSignal.timeout(3e4)]);
171
190
  const budget = { remaining: Math.min(probe.maxResponseBytes ?? 8388608, 8388608) };
172
191
  const root = daemonRoot(probe.config.baseUrl);
173
- const get = async (resource, body) => readJson(await daemonFetch(fetch, root, resource, signal, body), signal, budget);
192
+ const get = async (resource, body) => readJson(await daemonFetch(fetch, root, resource, signal, body, scope), signal, budget);
174
193
  const version = z.object({ version: z.string().min(1).max(128) }).parse(await get("version")).version;
175
194
  const tags = tagsSchema.parse(await get("tags")).models;
176
195
  if (new Set(tags.map((tag) => tag.name)).size !== tags.length) throw new Error("Ollama returned duplicate model tags");
@@ -235,7 +254,6 @@ async function discoverModels(probe, fetch) {
235
254
  evidence
236
255
  };
237
256
  }
238
- /** Accepts only the exact local installed identity and capability profile from this host listing. */
239
257
  function validateExecution(input) {
240
258
  const evidence = evidenceSchema.parse(input.evidence);
241
259
  const row = evidence.models.find((model) => model.model === input.model);
@@ -247,9 +265,8 @@ function validateExecution(input) {
247
265
  sourceIdentity: row.digest
248
266
  };
249
267
  }
250
- /** Rechecks tags and details immediately before inference; cloud placeholders never execute. */
251
- async function revalidateModel(probe, fetch, selection) {
252
- const listing = await discoverModels(probe, fetch);
268
+ async function revalidateModel(probe, fetch, selection, scope) {
269
+ const listing = await discoverModels(probe, fetch, scope);
253
270
  validateExecution({
254
271
  model: probe.model ?? "",
255
272
  requested: selection,
@@ -259,14 +276,21 @@ async function revalidateModel(probe, fetch, selection) {
259
276
  }
260
277
  //#endregion
261
278
  //#region src/image.ts
262
- /** Validated square generation sizes; dimensions remain below the daemon's 4096-pixel ceiling. */
263
279
  const IMAGE_PARAMS = z.strictObject({
264
- width: z.literal(1024).default(1024),
265
- height: z.literal(1024).default(1024),
266
- steps: z.number().int().min(1).max(50).default(9),
280
+ width: z.literal(1024).default(1024).meta({ presentation: { label: {
281
+ "en-US": "Width",
282
+ "zh-CN": "\u5bbd\u5ea6"
283
+ } } }),
284
+ height: z.literal(1024).default(1024).meta({ presentation: { label: {
285
+ "en-US": "Height",
286
+ "zh-CN": "\u9ad8\u5ea6"
287
+ } } }),
288
+ steps: z.number().int().min(1).max(50).default(9).meta({ presentation: { label: {
289
+ "en-US": "Sampling steps",
290
+ "zh-CN": "\u91c7\u6837\u6b65\u6570"
291
+ } } }),
267
292
  seed: z.number().int().min(0).max(2147483647).optional()
268
293
  });
269
- /** Declares only the create operation proved by the selected image adapter. */
270
294
  function imageModel(id) {
271
295
  return {
272
296
  id,
@@ -281,15 +305,10 @@ function imageModel(id) {
281
305
  }]
282
306
  };
283
307
  }
284
- /** Normalized experimental generation failure; raw daemon text never leaves this adapter. */
285
308
  var ImageFailure = class extends Error {
286
- /** Cross-realm discriminator recognized by the host. */
287
309
  name = "GenerationFailure";
288
- /** Host failure category. */
289
310
  code;
290
- /** Whether a submission may already have executed. */
291
311
  resultState;
292
- /** Records bounded fixed failure text and submission knowledge. */
293
312
  constructor(code, message, resultState) {
294
313
  super(message);
295
314
  this.code = code;
@@ -303,7 +322,6 @@ const imageFrame = z.object({
303
322
  completed: z.number().int().nonnegative().optional(),
304
323
  total: z.number().int().positive().optional()
305
324
  });
306
- /** Submits a single experimental image request after rechecking the installed model and daemon. */
307
325
  function createImagePort(call, fetch) {
308
326
  return { async generate(request, signal) {
309
327
  const execution = call.configuredModels.find((row) => row.id === call.model)?.execution;
@@ -312,7 +330,7 @@ function createImagePort(call, fetch) {
312
330
  const params = IMAGE_PARAMS.safeParse(request.params);
313
331
  if (!params.success) throw new ImageFailure("invalid-params", "Unsupported Ollama image parameters.", "not-submitted");
314
332
  const prompt = request.prompt.trim();
315
- if (![...prompt].length || [...prompt].length > 32e3) throw new ImageFailure("invalid-input", "Image prompt must contain 1–32000 characters.", "not-submitted");
333
+ if (![...prompt].length || [...prompt].length > 32e3) throw new ImageFailure("invalid-input", "Image prompt must contain 1\u201332000 characters.", "not-submitted");
316
334
  signal.throwIfAborted();
317
335
  try {
318
336
  await revalidateModel({
@@ -325,11 +343,7 @@ function createImagePort(call, fetch) {
325
343
  throw new ImageFailure("unavailable", "The installed Ollama image model or service changed; refresh and save it again.", "not-submitted");
326
344
  }
327
345
  const timeout = new AbortController();
328
- const active = AbortSignal.any([
329
- signal,
330
- timeout.signal,
331
- AbortSignal.timeout(9e5)
332
- ]);
346
+ const active = AbortSignal.any([signal, timeout.signal]);
333
347
  let timer = setTimeout(() => timeout.abort(/* @__PURE__ */ new Error("Ollama image response timed out")), 3e5);
334
348
  let submitted = false;
335
349
  try {
@@ -390,11 +404,9 @@ function createImagePort(call, fetch) {
390
404
  }
391
405
  //#endregion
392
406
  //#region src/logo.ts
393
- /** Self-contained official Ollama mark; provenance is shipped in assets/NOTICE. */
394
407
  const OLLAMA_LOGO = "data:image/svg+xml,%3Csvg%20width%3D%2228%22%20height%3D%2228%22%20viewBox%3D%220%200%2028%2028%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M7.25558%200.114339C7.61134%200.222519%207.93252%200.400698%208.22405%200.636149C8.70993%201.0256%209.12005%201.58303%209.433%202.24356C9.74758%202.90792%209.95182%203.64354%2010.0292%204.38171C11.0662%203.9284%2012.2171%203.65235%2013.4041%203.57227L13.4881%203.56718C14.921%203.47809%2016.3375%203.6779%2017.5728%204.17044C17.7391%204.2379%2017.9022%204.31044%2018.062%204.3868C18.1443%203.66263%2018.3453%202.94355%2018.6549%202.29447C18.9678%201.63266%2019.378%201.07651%2019.8622%200.685785C20.1328%200.459579%2020.4638%200.281532%2020.8323%200.163974C21.2556%200.0367035%2021.7053%200.0137947%2022.1434%200.110521C22.8039%200.255609%2023.3704%200.578877%2023.8168%201.04851C24.2253%201.47739%2024.5316%202.0272%2024.7408%202.68646C25.1196%203.87517%2025.1855%205.43933%2024.9302%207.32549L25.0175%207.37639L25.0603%207.40058C26.3072%208.13366%2027.1752%209.17855%2027.6348%2010.3914C28.3512%2012.284%2027.9905%2014.4068%2026.7552%2015.5943L26.7255%2015.621L26.7288%2015.6248C27.4157%2016.5946%2027.8324%2017.6192%2027.9214%2018.6793L27.9246%2018.7175C28.0301%2020.0729%2027.5952%2021.4373%2026.5839%2022.7774L26.5723%2022.7902L26.5888%2022.8207C27.3663%2024.2932%2027.6101%2025.7759%2027.3103%2027.2574L27.3004%2027.307C27.254%2027.5234%2027.0983%2027.7168%2026.8677%2027.8446C26.637%2027.9724%2026.3501%2028.0246%2026.07%2027.9892C25.9312%2027.9724%2025.7982%2027.9347%2025.6783%2027.8782C25.5585%2027.8217%2025.4543%2027.7474%2025.3717%2027.6595C25.289%2027.572%2025.2296%2027.4725%2025.1968%2027.3668C25.164%2027.2614%2025.1585%2027.152%2025.1806%2027.0448C25.4556%2025.7301%2025.197%2024.4116%2024.39%2023.0702C24.3147%2022.9456%2024.2812%2022.8083%2024.2927%2022.671C24.3043%2022.5338%2024.3604%2022.401%2024.4559%2022.2849L24.4624%2022.2773C25.4573%2021.1013%2025.869%2019.9482%2025.7801%2018.8155C25.7043%2017.8241%2025.2448%2016.8504%2024.4624%2015.9226C24.3103%2015.7423%2024.2561%2015.5229%2024.3115%2015.3119C24.367%2015.1009%2024.5277%2014.9152%2024.7589%2014.795L24.7737%2014.7874C25.174%2014.585%2025.5429%2014.0683%2025.729%2013.3619C25.9344%2012.5267%2025.8808%2011.6658%2025.5726%2010.8496C25.2349%209.95872%2024.6173%209.21546%2023.7526%208.70765C22.7726%208.12984%2021.4747%207.85111%2019.8326%207.9313C19.6178%207.94209%2019.4039%207.90286%2019.2183%207.81869C19.0327%207.73451%2018.8841%207.60927%2018.7916%207.45912C18.2744%206.61277%2017.5201%206.00696%2016.5796%205.63151C15.6767%205.2833%2014.6658%205.13696%2013.661%205.20897C11.6104%205.33497%209.80194%206.22841%209.26335%207.35476C9.18715%207.51329%209.05009%207.65005%208.87052%207.74673C8.69096%207.84338%208.47747%207.89535%208.25864%207.89566C6.50122%207.8982%205.14075%208.21638%204.14592%208.79037C3.28615%209.28673%202.6998%209.98036%202.39015%2010.8114C2.10995%2011.5937%202.07158%2012.4159%202.27815%2013.2118C2.46262%2013.9219%202.82333%2014.5099%203.23674%2014.8268L3.24992%2014.8357C3.5991%2015.0992%203.67321%2015.5103%203.42945%2015.8348C2.83651%2016.6264%202.39345%2017.8062%202.32098%2018.9402C2.23862%2020.2358%202.62733%2021.3609%203.50521%2022.1678L3.53157%2022.192C3.66406%2022.3113%203.74924%2022.4576%203.77701%2022.6133C3.80475%2022.769%203.77385%2022.9276%203.68804%2023.0702C2.73933%2024.6432%202.4478%2025.9363%202.76239%2026.9545C2.81892%2027.1662%202.76631%2027.3867%202.61573%2027.5687C2.46516%2027.7509%202.22851%2027.8805%201.95615%2027.9299C1.68379%2027.9795%201.39724%2027.9446%201.15746%2027.8334C0.917644%2027.7219%200.743586%2027.5427%200.672268%2027.3337C0.272031%2026.0381%200.543797%2024.5541%201.45133%2022.8818L1.47438%2022.8373L1.46121%2022.822C1.01515%2022.3129%200.682282%2021.7498%200.476267%2021.156L0.468032%2021.1318C0.218008%2020.391%200.119645%2019.6244%200.176502%2018.86C0.248972%2017.7019%200.634385%2016.5157%201.20097%2015.5637L1.22074%2015.5306L1.21744%2015.5281C0.734856%2014.9961%200.377443%2014.3152%200.179796%2013.5618L0.17156%2013.5312C-0.100765%2012.4803%20-0.0482896%2011.3945%200.324737%2010.3622C0.756268%209.19764%201.6045%208.19729%202.85462%207.47439C2.95345%207.41712%203.05721%207.35985%203.16098%207.3064C2.89909%205.40624%202.96498%203.8319%203.34545%202.63556C3.55463%201.97629%203.86263%201.42648%204.2711%200.997598C4.71581%200.529242%205.2824%200.205974%205.94287%200.0596123C6.38099%20-0.0371136%206.83228%20-0.0142049%207.25558%200.114339ZM14.0349%2011.6832C15.5765%2011.6832%2016.9996%2012.0816%2018.0636%2012.7714C19.1013%2013.4421%2019.7189%2014.3432%2019.7189%2015.2405C19.7189%2016.3706%2019.0502%2017.2513%2017.8528%2017.8139C16.8316%2018.2911%2015.4629%2018.5228%2013.8949%2018.5228C12.233%2018.5228%2010.8132%2018.1931%209.78876%2017.5886C8.77252%2016.9904%208.20264%2016.1504%208.20264%2015.2405C8.20264%2014.3407%208.85817%2013.437%209.94194%2012.7638C11.0422%2012.0803%2012.4949%2011.6832%2014.0349%2011.6832ZM14.0349%2012.8236C12.8922%2012.8159%2011.7798%2013.1075%2010.8791%2013.6508C10.1198%2014.1217%209.68994%2014.7136%209.68994%2015.2417C9.68994%2015.7865%2010.0358%2016.2968%2010.6946%2016.685C11.4441%2017.1266%2012.5459%2017.3824%2013.8949%2017.3824C15.2109%2017.3824%2016.321%2017.1953%2017.077%2016.8403C17.8396%2016.4839%2018.23%2015.9672%2018.23%2015.2405C18.23%2014.7021%2017.8248%2014.1077%2017.105%2013.6419C16.3078%2013.1265%2015.2274%2012.8236%2014.0349%2012.8236ZM15.1252%2014.3636L15.1318%2014.3687C15.3295%2014.5608%2015.2883%2014.8396%2015.0396%2014.9923L14.5587%2015.285V15.8526C14.5578%2015.979%2014.4921%2016.0999%2014.376%2016.1889C14.2599%2016.2779%2014.1029%2016.3277%2013.9394%2016.3274C13.7758%2016.3277%2013.6188%2016.2779%2013.5027%2016.1889C13.3866%2016.0999%2013.3209%2015.979%2013.3201%2015.8526V15.2672L12.8737%2014.9897C12.8148%2014.9533%2012.7659%2014.9082%2012.7297%2014.857C12.6935%2014.8059%2012.6707%2014.7497%2012.6628%2014.6917C12.6548%2014.6337%2012.6618%2014.5751%2012.6833%2014.5192C12.7048%2014.4633%2012.7404%2014.4113%2012.7881%2014.3661C12.8853%2014.2747%2013.0253%2014.2166%2013.1776%2014.2044C13.3299%2014.1923%2013.4824%2014.2271%2013.6017%2014.3012L13.9558%2014.5201L14.3182%2014.2987C14.4371%2014.2261%2014.588%2014.1922%2014.7388%2014.2043C14.8896%2014.2165%2015.0282%2014.2736%2015.1252%2014.3636ZM6.82405%2011.9212C7.61134%2011.9212%208.25205%2012.4176%208.25205%2013.0298C8.25248%2013.3232%208.10217%2013.6048%207.83409%2013.8127C7.56602%2014.0205%207.20215%2014.1376%206.8224%2014.1383C6.44321%2014.1373%206.08%2014.0202%205.81235%2013.8127C5.54467%2013.6051%205.3944%2013.324%205.3944%2013.031C5.39351%2012.7376%205.54342%2012.4559%205.81117%2012.2478C6.07895%2012.0397%206.4443%2011.9223%206.82405%2011.9212ZM21.1634%2011.9212C21.954%2011.9212%2022.593%2012.4176%2022.593%2013.0298C22.5935%2013.3232%2022.4432%2013.6048%2022.1751%2013.8127C21.907%2014.0205%2021.5431%2014.1376%2021.1634%2014.1383C20.7842%2014.1373%2020.421%2014.0202%2020.1533%2013.8127C19.8857%2013.6051%2019.7354%2013.324%2019.7354%2013.031C19.7345%2012.7376%2019.8844%2012.4559%2020.1522%2012.2478C20.4199%2012.0397%2020.7836%2011.9223%2021.1634%2011.9212ZM6.48969%201.6543L6.48475%201.65684C6.29392%201.72096%206.131%201.82611%206.01534%201.95975L6.0071%201.96738C5.77981%202.20793%205.58216%202.56174%205.43393%203.02628C5.15392%203.90699%205.07816%205.10206%205.22969%206.56695C5.93793%206.40405%206.7104%206.30223%207.54217%206.26532L7.55864%206.26405L7.58993%206.22077C7.6657%206.11641%207.7464%206.01587%207.8337%205.9166C8.03629%204.93534%207.86993%203.76318%207.41699%202.8061C7.19628%202.34283%206.92781%201.97884%206.67087%201.77139C6.61783%201.72827%206.55871%201.68986%206.49463%201.65684L6.48969%201.6543ZM21.5999%201.70521L21.5966%201.70648C21.5325%201.73949%2021.4734%201.7779%2021.4203%201.82102C21.1634%202.02847%2020.8933%202.39374%2020.6742%202.85701C20.1966%203.86754%2020.0368%205.11734%2020.2954%206.13041L20.3909%206.25387L20.4041%206.27168H20.4535C21.2709%206.27186%2022.0841%206.36273%2022.8681%206.5415C23.0097%205.11097%2022.9307%203.94136%2022.6573%203.07719C22.509%202.61265%2022.3114%202.25883%2022.0824%202.01829L22.0759%202.01066C21.9604%201.87654%2021.7975%201.77095%2021.6064%201.70648L21.5999%201.70521Z%22%20fill%3D%22black%22%2F%3E%0A%3C%2Fsvg%3E%0A";
395
408
  //#endregion
396
409
  //#region src/port.ts
397
- /** Native Ollama conversation request rendering, measurement and streaming. */
398
410
  const settingsSchema = z.strictObject({
399
411
  maxTokens: z.number().int().positive().max(1e6).optional(),
400
412
  temperature: z.number().min(0).max(2).optional(),
@@ -428,15 +440,51 @@ const frameSchema = z.object({
428
440
  eval_count: z.number().int().nonnegative().optional(),
429
441
  prompt_eval_cached_count: z.number().int().nonnegative().optional()
430
442
  });
431
- /**
432
- * Creates a native conversation port that measures oversized candidates without IO.
433
- * Submissions enforce context capacity and recheck the saved weight identity.
434
- */
435
443
  function createOllamaPort(call, support, fetch) {
436
444
  const selection = call.configuredModels.find((row) => row.id === call.model)?.execution;
437
445
  const profile = selection?.protocolId === "ollama" ? parseChatProfile(selection.profile) : void 0;
438
446
  const root = daemonRoot(call.config.baseUrl);
447
+ function daemonFailure(error) {
448
+ if (support.failures.owns(error)) return error;
449
+ if (error instanceof DaemonHttpError && error.contextWindowExceeded) return support.failures.create({
450
+ code: "context-window-exceeded",
451
+ stage: "request",
452
+ category: "request-too-large",
453
+ source: "provider",
454
+ retryable: false,
455
+ status: error.status
456
+ });
457
+ if (error instanceof DaemonHttpError) {
458
+ const code = error.status === 429 ? "quota-exceeded" : error.status === 413 ? "request-too-large" : error.status === 401 || error.status === 403 ? "authentication-required" : error.status === 404 ? "model-unavailable" : "http-error";
459
+ return support.failures.create({
460
+ code,
461
+ stage: "transport",
462
+ category: error.status === 413 ? "request-too-large" : "provider",
463
+ source: "provider",
464
+ retryable: false,
465
+ status: error.status
466
+ });
467
+ }
468
+ return support.failures.create({
469
+ code: error instanceof TypeError ? "stream-interrupted" : "response-invalid",
470
+ stage: error instanceof TypeError ? "transport" : "stream",
471
+ category: error instanceof TypeError ? "network" : "protocol",
472
+ source: error instanceof TypeError ? "transport" : "protocol",
473
+ retryable: false
474
+ });
475
+ }
476
+ function recheckFailure(error) {
477
+ if (support.failures.owns(error) || error instanceof DaemonHttpError || error instanceof TypeError) return daemonFailure(error);
478
+ return support.failures.create({
479
+ code: "model-unavailable",
480
+ stage: "request",
481
+ category: "provider",
482
+ source: "provider",
483
+ retryable: false
484
+ });
485
+ }
439
486
  function build(request) {
487
+ const started = support.performance?.now();
440
488
  if (!selection || !profile || !selection.sourceIdentity) throw new Error("Refresh and save an installed Ollama conversation model");
441
489
  const params = settingsSchema.parse(request.params ?? {});
442
490
  const catalogue = support.catalogue(call.providerId, call.model);
@@ -451,6 +499,7 @@ function createOllamaPort(call, support, fetch) {
451
499
  images: 50
452
500
  }
453
501
  });
502
+ const renderedMedia = [];
454
503
  const messages = [];
455
504
  if (request.system?.length) messages.push({
456
505
  role: "system",
@@ -463,6 +512,7 @@ function createOllamaPort(call, support, fetch) {
463
512
  content: text
464
513
  });
465
514
  };
515
+ const renderedThinking = /* @__PURE__ */ new Set();
466
516
  const names = /* @__PURE__ */ new Map();
467
517
  request.messages.forEach((message, messageIndex) => {
468
518
  if (message.role === "assistant") {
@@ -471,6 +521,7 @@ function createOllamaPort(call, support, fetch) {
471
521
  for (const call of calls) names.set(call.id, call.name);
472
522
  const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("");
473
523
  const thinking = message.outputTruncation?.incompleteThinking ? "" : message.content.filter((part) => part.type === "thinking").map((part) => part.text).join("");
524
+ if ((text || calls.length) && thinking) renderedThinking.add(message.id);
474
525
  if (text || calls.length) messages.push({
475
526
  role: "assistant",
476
527
  content: text,
@@ -492,7 +543,10 @@ function createOllamaPort(call, support, fetch) {
492
543
  else if (part.type === "file") {
493
544
  const planned = media.at(messageIndex, partIndex);
494
545
  lines.push(planned.label);
495
- if (planned.fate === "send" && planned.data !== void 0) images.push(planned.data);
546
+ if (planned.fate === "send" && planned.data !== void 0) {
547
+ images.push(planned.data);
548
+ renderedMedia.push(planned);
549
+ }
496
550
  } else if (part.type === "tool-result") {
497
551
  const name = names.get(part.toolUseId);
498
552
  if (!name) throw new Error("Ollama tool result has no matching preceding call");
@@ -501,7 +555,10 @@ function createOllamaPort(call, support, fetch) {
501
555
  const planned = media.at(messageIndex, partIndex, fileIndex);
502
556
  if (planned.fate === "send") {
503
557
  lines.push(`${part.toolUseId} ${planned.label}`);
504
- if (planned.data !== void 0) images.push(planned.data);
558
+ if (planned.data !== void 0) {
559
+ images.push(planned.data);
560
+ renderedMedia.push(planned);
561
+ }
505
562
  } else result.push(planned.label);
506
563
  });
507
564
  messages.push({
@@ -533,7 +590,7 @@ function createOllamaPort(call, support, fetch) {
533
590
  }
534
591
  const tools = request.toolChoice === "none" ? [] : request.tools ?? [];
535
592
  if (tools.length && !profile.tools) throw new Error("This Ollama model does not support tools");
536
- const body = {
593
+ const body = support.freezePayload({
537
594
  model: call.model,
538
595
  stream: true,
539
596
  truncate: false,
@@ -552,44 +609,139 @@ function createOllamaPort(call, support, fetch) {
552
609
  num_predict: Number(maxTokens),
553
610
  ...params.temperature === void 0 ? {} : { temperature: params.temperature }
554
611
  }
555
- };
612
+ });
556
613
  if (Buffer.byteLength(JSON.stringify(body)) > 20971520) throw new Error("Ollama request exceeds 20 MiB");
614
+ support.performance?.observe({
615
+ stage: "model.project",
616
+ measurementPurpose: "request",
617
+ durationMs: support.performance.now() - started,
618
+ count: 1
619
+ });
620
+ const serialization = support.performance?.now();
557
621
  const text = JSON.stringify({
558
622
  ...body,
559
623
  messages: body.messages.map(({ images: _images, ...message }) => message)
560
624
  });
625
+ support.performance?.observe({
626
+ stage: "model.serialize",
627
+ measurementPurpose: "request",
628
+ durationMs: support.performance.now() - serialization,
629
+ count: 1
630
+ });
631
+ const inspection = support.inspect({
632
+ body,
633
+ textTokens: 0,
634
+ textBytes: Buffer.byteLength(text),
635
+ tokenizer: "utf8-bytes-quarter-v1",
636
+ request,
637
+ capacity: { context },
638
+ mediaTokens: media.tokens,
639
+ outputReserve: Number(maxTokens),
640
+ outputReserveSource: "enforced",
641
+ fingerprint: {
642
+ rendering: "ollama-chat-v1",
643
+ endpoint: call.connectionFingerprint ?? root,
644
+ model: call.model,
645
+ profile: selection.profile,
646
+ settings: body.options,
647
+ think,
648
+ media: media.sent.map((file) => ({
649
+ id: file.ref.forModel?.id ?? file.ref.id,
650
+ size: file.ref.forModel?.size ?? file.ref.size
651
+ }))
652
+ }
653
+ });
654
+ const fields = /* @__PURE__ */ new Map();
655
+ let mediaIndex = 0;
656
+ for (const message of body.messages) {
657
+ if (!message.images) continue;
658
+ const identities = message.images.map((data) => {
659
+ const file = renderedMedia[mediaIndex++];
660
+ if (!file || file.data !== data) throw new Error("prepared_media_selection_mismatch");
661
+ const hash = createHash("sha256");
662
+ for (let offset = 0; offset < data.length; offset += 65536) hash.update(data.slice(offset, offset + 65536), "base64");
663
+ return {
664
+ sha256: hash.digest("hex"),
665
+ byteLength: Buffer.byteLength(data, "base64"),
666
+ variantId: file.variantId,
667
+ mediaType: file.mediaType,
668
+ width: file.width,
669
+ height: file.height
670
+ };
671
+ });
672
+ fields.set(message, /* @__PURE__ */ new Map([["images", {
673
+ kind: "media",
674
+ value: JSON.stringify(identities)
675
+ }]]));
676
+ }
677
+ if (mediaIndex !== renderedMedia.length) throw new Error("prepared_media_selection_mismatch");
561
678
  return {
562
679
  body,
563
- inspection: support.inspect({
564
- body,
565
- textTokens: support.measureText(text),
566
- tokenizer: "o200k_base-ollama-text-v1",
567
- request,
568
- capacity: { context },
569
- mediaTokens: media.tokens,
570
- outputReserve: Number(maxTokens),
571
- outputReserveSource: "enforced",
572
- fingerprint: {
573
- rendering: "ollama-chat-v1",
574
- endpoint: call.connectionFingerprint ?? root,
575
- model: call.model,
576
- profile: selection.profile,
577
- settings: body.options,
578
- think,
579
- media: media.sent.map((file) => ({
580
- id: file.ref.forModel?.id ?? file.ref.id,
581
- size: file.ref.forModel?.size ?? file.ref.size
582
- }))
583
- }
584
- })
680
+ replaySelections: support.prepareReplaySelections(request, ({ message, part }) => {
681
+ const sent = !!part && renderedThinking.has(message.id);
682
+ return {
683
+ mode: "plain-thinking",
684
+ textIncluded: sent && part.text !== "",
685
+ group: message.id,
686
+ ...sent ? { selectedText: part.text } : { reason: "not-applicable" }
687
+ };
688
+ }),
689
+ inspection: support.freezePayload(inspection),
690
+ text,
691
+ fields,
692
+ request: {
693
+ ...request,
694
+ params: support.freezePayload(request.params ?? {})
695
+ },
696
+ mediaPlan: media,
697
+ renderedMedia: new Set(renderedMedia),
698
+ allowedTools: new Set(body.tools?.map((tool) => tool.function.name) ?? []),
699
+ toolsWithheld: request.toolChoice === "none" && (request.tools?.length ?? 0) > 0
585
700
  };
586
701
  }
587
- return {
588
- inspect(request) {
589
- return build(request).inspection;
702
+ return support.createPreparedPort({
703
+ prepare: build,
704
+ semantics(payload) {
705
+ return {
706
+ replaySelections: payload.replaySelections,
707
+ mediaSelections: () => support.mediaSelections(payload.mediaPlan, payload.renderedMedia),
708
+ format: "request-semantic-v1",
709
+ protocolId: "ollama",
710
+ adapterVersion: "1",
711
+ rendererVersion: "ollama-chat-v1",
712
+ parameters: Object.freeze(Object.fromEntries(Object.entries(payload.body).filter(([key]) => ![
713
+ "model",
714
+ "messages",
715
+ "tools",
716
+ "stream"
717
+ ].includes(key)))),
718
+ toolDefinitions: payload.body.tools ?? Object.freeze([]),
719
+ frames: () => support.semanticFrames(payload.body, {
720
+ omitRoot: ["stream"],
721
+ fields: payload.fields
722
+ })
723
+ };
590
724
  },
591
- stream(request, signal, observer) {
592
- const { body, inspection } = build(request);
725
+ async inspect(payload, signal) {
726
+ signal.throwIfAborted();
727
+ const { inspection, text, toolsWithheld } = payload;
728
+ const textTokens = await support.measureText(text, signal);
729
+ signal.throwIfAborted();
730
+ return {
731
+ ...inspection,
732
+ inputTokens: inspection.inputTokens + textTokens,
733
+ ...toolsWithheld ? { toolsWithheld: true } : {}
734
+ };
735
+ },
736
+ async *stream(payload, signal, observer, scope) {
737
+ signal.throwIfAborted();
738
+ const { body, inspection: fixed, text, allowedTools } = payload;
739
+ const textTokens = await support.measureText(text, signal);
740
+ signal.throwIfAborted();
741
+ const inspection = {
742
+ ...fixed,
743
+ inputTokens: fixed.inputTokens + textTokens
744
+ };
593
745
  if (inspection.inputTokens + inspection.outputReserve > body.options.num_ctx) throw support.failures.create({
594
746
  code: "context-limit-exceeded",
595
747
  stage: "request",
@@ -597,29 +749,74 @@ function createOllamaPort(call, support, fetch) {
597
749
  source: "protocol",
598
750
  retryable: false
599
751
  });
600
- return support.withChatAttempts({
601
- signal: AbortSignal.any([signal, AbortSignal.timeout(9e5)]),
602
- maxRetries: 0,
603
- async *attempt(attemptSignal, progress, attempt) {
604
- await revalidateModel({
605
- ...call,
606
- model: call.model,
607
- signal: attemptSignal
608
- }, fetch, selection);
609
- const response = support.observeResponseProgress(await daemonFetch(fetch, root, "chat", attemptSignal, body), progress);
752
+ yield* support.withChatAttempts({
753
+ retainCleanup: scope.retainCleanup,
754
+ accountingDispatch: call.accountingDispatch,
755
+ beforeAttempt: async (attemptSignal, ordinal) => {
756
+ await observer?.beforeAttempt?.(ordinal);
610
757
  try {
611
- observer?.dispatched({ attempt });
612
- } catch {}
758
+ await revalidateModel({
759
+ ...call,
760
+ model: call.model,
761
+ signal: attemptSignal
762
+ }, fetch, selection, scope);
763
+ } catch (error) {
764
+ if (attemptSignal.aborted) throw error;
765
+ throw recheckFailure(error);
766
+ }
767
+ },
768
+ effective: { outputLimit: body.options.num_predict },
769
+ signal,
770
+ maxRetries: 0,
771
+ async *attempt(attemptSignal, progress, attempt, usageReporter) {
772
+ const markDispatched = () => {
773
+ try {
774
+ observer?.dispatched({
775
+ attempt,
776
+ presentation: {
777
+ schema: "chat.dispatch-settings.v1",
778
+ data: {
779
+ model: {
780
+ availability: "resolved",
781
+ value: body.model,
782
+ origin: "protocol"
783
+ },
784
+ effort: body.think === void 0 ? {
785
+ availability: "resolved",
786
+ value: "default",
787
+ origin: "protocol"
788
+ } : {
789
+ availability: "resolved",
790
+ value: typeof body.think === "boolean" ? body.think ? "enabled" : "disabled" : body.think,
791
+ origin: "protocol"
792
+ }
793
+ }
794
+ }
795
+ });
796
+ } catch {}
797
+ };
798
+ const response = support.observeResponseProgress(await daemonFetch((...args) => {
799
+ const pending = fetch(...args);
800
+ markDispatched();
801
+ return pending;
802
+ }, root, "chat", attemptSignal, body, scope), progress);
613
803
  let text = "";
614
804
  let thinking = "";
615
805
  const tools = /* @__PURE__ */ new Map();
616
806
  const runId = randomUUID();
807
+ let usageSequence = 0;
617
808
  let done = false;
618
809
  let final;
619
810
  for await (const raw of readFrames(response, attemptSignal)) {
620
811
  progress();
621
812
  if (done) throw new Error("Ollama returned frames after its terminal response");
622
813
  const frame = frameSchema.parse(raw);
814
+ if (frame.prompt_eval_count !== void 0 || frame.eval_count !== void 0) usageReporter?.report({
815
+ sequence: ++usageSequence,
816
+ ...frame.prompt_eval_count === void 0 ? {} : { inputTokens: frame.prompt_eval_count },
817
+ ...frame.eval_count === void 0 ? {} : { outputTokens: frame.eval_count },
818
+ ...frame.prompt_eval_cached_count === void 0 ? {} : { cacheReadTokens: frame.prompt_eval_cached_count }
819
+ });
623
820
  if (frame.error) throw new Error("Ollama reported a stream failure");
624
821
  if (frame.message?.thinking) {
625
822
  thinking += frame.message.thinking;
@@ -629,7 +826,7 @@ function createOllamaPort(call, support, fetch) {
629
826
  };
630
827
  }
631
828
  for (const tool of frame.message?.tool_calls ?? []) {
632
- if (request.toolChoice === "none" || !request.tools?.some((definition) => definition.name === tool.function.name)) throw new Error("Ollama returned an undeclared tool call");
829
+ if (!allowedTools.has(tool.function.name)) throw new Error("Ollama returned an undeclared tool call");
633
830
  const key = tool.id ? `id:${tool.id}` : tool.function.index === void 0 ? `position:${tools.size}` : `index:${tool.function.index}`;
634
831
  const previous = tools.get(key);
635
832
  if (previous) {
@@ -696,47 +893,21 @@ function createOllamaPort(call, support, fetch) {
696
893
  if (!done || !final) throw support.interruptedFailure();
697
894
  yield final;
698
895
  },
699
- classify(error) {
700
- if (support.failures.owns(error)) return {
701
- error,
702
- retryable: false
703
- };
704
- if (error instanceof DaemonHttpError) {
705
- const code = error.status === 429 ? "quota-exceeded" : error.status === 413 ? "request-too-large" : error.status === 401 || error.status === 403 ? "authentication-required" : error.status === 404 ? "model-unavailable" : "http-error";
706
- return {
707
- error: support.failures.create({
708
- code,
709
- stage: "transport",
710
- category: error.status === 413 ? "request-too-large" : "provider",
711
- source: "provider",
712
- retryable: false,
713
- status: error.status
714
- }),
715
- retryable: false
716
- };
717
- }
718
- return {
719
- error: support.failures.create({
720
- code: error instanceof TypeError ? "stream-interrupted" : "response-invalid",
721
- stage: error instanceof TypeError ? "transport" : "stream",
722
- category: error instanceof TypeError ? "network" : "protocol",
723
- source: error instanceof TypeError ? "transport" : "protocol",
724
- retryable: false
725
- }),
726
- retryable: false
727
- };
728
- }
896
+ classify: (error) => ({
897
+ error: daemonFailure(error),
898
+ retryable: false
899
+ })
729
900
  });
730
901
  }
731
- };
902
+ });
732
903
  }
733
904
  //#endregion
734
905
  //#region src/support.ts
735
- /** Normalizes official facts without requiring an installed Chat capability. */
736
906
  function normalizeOffers(input) {
737
907
  return Object.fromEntries(input.offers.map((offer) => [offer.model, {
738
908
  id: offer.model,
739
909
  ...offer.name === void 0 ? {} : { name: offer.name },
910
+ ...offer.chat === void 0 ? {} : { chat: offer.chat },
740
911
  ...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
741
912
  ...offer.efforts?.length ? { reasoning_options: [{
742
913
  type: "effort",
@@ -756,7 +927,6 @@ function normalizeOffers(input) {
756
927
  ...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
757
928
  }]));
758
929
  }
759
- /** The owner-qualified accessor is read per operation; withdrawal never exposes an old service. */
760
930
  function lazySupport(read) {
761
931
  return new Proxy({}, { get(_target, key) {
762
932
  if (key === "normalizeListing") return normalizeOffers;
@@ -768,7 +938,6 @@ function lazySupport(read) {
768
938
  }
769
939
  //#endregion
770
940
  //#region src/protocol.ts
771
- /** Native parameter support; per-model thinking switches require explicit show metadata. */
772
941
  const facts = {
773
942
  outputLimit: {
774
943
  support: "optional",
@@ -787,7 +956,6 @@ const facts = {
787
956
  images: 50
788
957
  }
789
958
  };
790
- /** Registers no-key native discovery, conversation and conservative experimental image execution. */
791
959
  function ollamaProtocolType(support, fetch) {
792
960
  return {
793
961
  type: "ollama",
@@ -851,7 +1019,6 @@ function ollamaProtocolType(support, fetch) {
851
1019
  }
852
1020
  //#endregion
853
1021
  //#region src/index.ts
854
- /** Protocol extensions contribute no model tools. */
855
1022
  const TOOL_NAMES = [];
856
1023
  const plugin = {
857
1024
  name: "@eum-agent/llm-protocol-ollama",
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "en-US": "Ollama Model Protocol",
5
5
  "zh-CN": "模型协议 · Ollama"
6
6
  },
7
- "version": "1.1.0",
7
+ "version": "1.2.0",
8
8
  "type": "module",
9
9
  "description": "Native local Ollama model protocol",
10
10
  "license": "MIT",
@@ -18,7 +18,7 @@
18
18
  "assets"
19
19
  ],
20
20
  "devDependencies": {
21
- "@eum-agent/plugin": "1.1.0"
21
+ "@eum-agent/plugin": "1.2.0"
22
22
  },
23
23
  "dependencies": {
24
24
  "zod": "^4.4.3"
@@ -26,10 +26,10 @@
26
26
  "yaoguang": {
27
27
  "kind": "extension",
28
28
  "dependencies": {
29
- "@eum-agent/llm-management": "1.1.0"
29
+ "@eum-agent/llm-management": "1.2.0"
30
30
  },
31
31
  "foundationDependencies": {
32
- "@eum-agent/infra-local": "1.0.1"
32
+ "@eum-agent/infra-local": "1.2.0"
33
33
  },
34
34
  "description": {
35
35
  "en-US": "Native local Ollama model protocol",