@goodandready/dsh-ollama-cloud-provider 0.1.14 → 0.1.15

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/CHANGELOG.md CHANGED
@@ -1,5 +1,65 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.15 — 2026-11-02
4
+
5
+ - Desktop write requests are no longer accepted from a cookie name and a
6
+ Desktop user agent alone. After the loopback Host/socket checks, the plugin
7
+ verifies the `dsh-auth-*` cookie against the host's authenticated
8
+ `/api/version`; a 401/403 or a failed probe rejects the write. Forged
9
+ Desktop headers now return 403 (#42).
10
+ - Truncated streams now fail instead of reporting success: the native parser
11
+ rejects EOF before `done:true`, and the OpenAI parser rejects EOF before
12
+ `[DONE]`/`finish_reason` without emitting `block-end` or `finish`. Malformed
13
+ SSE JSON is an error instead of being skipped (#43).
14
+ - Added project-specific `AGENTS.md` and `index.md` with architecture,
15
+ constraints, compatibility, testing, security, and deployment facts (#44).
16
+ - Investigated the dev-only Zod advisory (#46). DSH core packages pin
17
+ `zod@4.4.3` exactly in rc.4, rc.5, and 0.2.2-alpha, so no in-range
18
+ dependency update exists; forced overrides are not used. The production tree
19
+ (`npm audit --omit=dev`) reports zero because the plugin has no runtime npm
20
+ dependencies. The dev-only advisory remains tracked upstream.
21
+ - Removed the local multi-version `test:engine` loop. It created its own DSH
22
+ runtime, installed a `file:` worktree package, and used forced cleanup,
23
+ contrary to the project test-server rules. Compatibility checks now follow
24
+ the approved test-server procedure in `docs/testing/test-server.md` (#47).
25
+ - SSE normalization now operates on the accumulated buffer, so CRLF split
26
+ between network chunks and split UTF-8 sequences parse correctly (#48).
27
+ - Live catalog metadata is scoped by API base, pruned when models disappear,
28
+ and invalidated together with the cache; a generation guard discards a
29
+ background refresh that finishes after a clear (#49).
30
+ - Request analytics no longer deduplicates independent requests by timestamp;
31
+ concurrent requests that start in the same millisecond and their errors are
32
+ counted (#50).
33
+ - Per-field price overrides now win over generated off-peak rates; partial
34
+ overrides apply only to the overridden field (#51).
35
+ - `/ollama test` disables reasoning, uses 64 tokens, and reports an empty or
36
+ reasoning-only reply as an error instead of `OK` (#52).
37
+ - Analytics scans the newest projection files by mtime when the directory
38
+ exceeds 5000 files and marks the report as truncated; the UI shows the
39
+ incompleteness warning (#53).
40
+ - The update card distinguishes a failed registry check from “up to date” and
41
+ offers a retry; the install button is disabled while the check has failed
42
+ (#54).
43
+ - Quota labels, window labels and credit detail are localized in English and
44
+ Chinese instead of rendering English strings directly (#55).
45
+ - Sensitive read routes (`state`, `analytics`, `usage`, `balance`) require a
46
+ host-verified session cookie; `health` and `status` remain public (#56).
47
+ - The usage reader honors its 30-second failure cache, caches a total failure,
48
+ and deduplicates concurrent reads (#57).
49
+ - Credential config patches and key writes are restricted to the plugin's
50
+ `OLLAMA_*` namespace, closing the two-step `OTHER_PLUGIN_API_KEY` mutation
51
+ path (#60).
52
+ - Saving or clearing a key refreshes server state without discarding an
53
+ unsaved settings draft (#62).
54
+ - Added an explicit `showAllModels` switch: an empty `visibleModels` list with
55
+ `showAllModels:false` now means “hide all” and survives save/reload; legacy
56
+ configs with an absent switch keep the previous empty-means-all behavior
57
+ (#63).
58
+ - Updated the design contract, README install examples and the default user
59
+ agent to the current version (#59).
60
+ - Removed the unused SSE event parser and the redundant stored image `base64`
61
+ field; transports keep using the single `dataUrl` representation (#58).
62
+
3
63
  ## 0.1.14 — 2026-10-29
4
64
 
5
65
  - Model-scoped rejections (unsupported model or per-model quota) mark only that
package/README.md CHANGED
@@ -104,17 +104,17 @@ npm pack
104
104
  Install the published package:
105
105
 
106
106
  ```bash
107
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.14
107
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.15
108
108
  # DSH Desktop:
109
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.14
109
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.15
110
110
  ```
111
111
 
112
112
  Or install the packed tarball into a profile:
113
113
 
114
114
  ```bash
115
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.14.tgz
115
+ dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.15.tgz
116
116
  # DSH Desktop:
117
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.14.tgz
117
+ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.15.tgz
118
118
  ```
119
119
 
120
120
  Restart dsh (or DSH Desktop), then pick **Ollama Cloud** in the model picker.
package/README.ru.md CHANGED
@@ -103,17 +103,17 @@ npm pack
103
103
  Установка опубликованного пакета из npm:
104
104
 
105
105
  ```bash
106
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.14
106
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.15
107
107
  # DSH Desktop:
108
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.14
108
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.15
109
109
  ```
110
110
 
111
111
  Либо установка из упакованного tarball:
112
112
 
113
113
  ```bash
114
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.14.tgz
114
+ dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.15.tgz
115
115
  # DSH Desktop:
116
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.14.tgz
116
+ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.15.tgz
117
117
  ```
118
118
 
119
119
  После установки перезапустите dsh (или DSH Desktop) и выберите **Ollama Cloud** в списке моделей.
package/README.zh.md CHANGED
@@ -102,17 +102,17 @@ npm pack
102
102
  从 npm 安装已发布版本:
103
103
 
104
104
  ```bash
105
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.14
105
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.15
106
106
  # DSH 桌面端:
107
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.14
107
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.15
108
108
  ```
109
109
 
110
110
  或通过打包文件安装:
111
111
 
112
112
  ```bash
113
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.14.tgz
113
+ dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.15.tgz
114
114
  # DSH 桌面端:
115
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.14.tgz
115
+ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.15.tgz
116
116
  ```
117
117
 
118
118
  安装完成后重启 dsh 或 DSH 桌面端,在模型列表中选择 **Ollama Cloud** 即可。
package/lib/client.js CHANGED
@@ -49,12 +49,16 @@ window.__ModuleLoader__.load({
49
49
  tokens: "Tokens",
50
50
  spend7d: "7-day spend",
51
51
  remaining: "remaining",
52
+ quotaIncludedCredits: "Included credits",
53
+ quotaFiveHour: "5-hour window",
54
+ quotaWeekly: "Weekly window",
52
55
  until: "until",
53
56
  purchased: "Purchased",
54
57
  range: "Range",
55
58
  last24h: "Last 24 hours",
56
59
  last7d: "Last 7 days",
57
60
  last30d: "Last 30 days",
61
+ last90d: "Last 90 days",
58
62
  activeAccountNow: "Active account",
59
63
  noActiveAccount: "No active account",
60
64
  accounts: "Accounts",
@@ -132,6 +136,7 @@ window.__ModuleLoader__.load({
132
136
  planLabelHint: "Optional label shown on the sidebar card, for example PRO. Ollama does not expose the plan name via API.",
133
137
  usageAnalytics: "Usage analytics",
134
138
  analyticsEmpty: "No Ollama Cloud sessions in this window.",
139
+ analyticsTruncated: "Only the newest session files were scanned; the totals are incomplete.",
135
140
  analyticsHint: "Aggregated from the local session projection cache: numeric metadata only, no prompt text.",
136
141
  days: "Days",
137
142
  sessions: "Sessions",
@@ -165,6 +170,7 @@ window.__ModuleLoader__.load({
165
170
  markTransport: "Transport error",
166
171
  pluginUpdate: "Plugin update",
167
172
  updateCheckFailed: "Could not check for updates",
173
+ retry: "Retry",
168
174
  updateFailed: "Update failed",
169
175
  updateAvailable: "Update available",
170
176
  updateUnavailable: "Automatic update is unavailable in this runtime.",
@@ -216,12 +222,16 @@ window.__ModuleLoader__.load({
216
222
  tokens: "Token",
217
223
  spend7d: "7 天费用",
218
224
  remaining: "剩余",
225
+ quotaIncludedCredits: "包含额度",
226
+ quotaFiveHour: "5 小时窗口",
227
+ quotaWeekly: "每周窗口",
219
228
  until: "至",
220
229
  purchased: "已购买",
221
230
  range: "范围",
222
231
  last24h: "最近 24 小时",
223
232
  last7d: "最近 7 天",
224
233
  last30d: "最近 30 天",
234
+ last90d: "最近 90 天",
225
235
  activeAccountNow: "当前账号",
226
236
  noActiveAccount: "没有可用账号",
227
237
  accounts: "账号",
@@ -299,6 +309,7 @@ window.__ModuleLoader__.load({
299
309
  planLabelHint: "侧边栏卡片上显示的可选标签,例如 PRO。Ollama API 不提供套餐名称。",
300
310
  usageAnalytics: "用量分析",
301
311
  analyticsEmpty: "此窗口内没有 Ollama Cloud 会话。",
312
+ analyticsTruncated: "仅扫描了最新的会话文件,合计数据不完整。",
302
313
  analyticsHint: "来自本地会话投影缓存,仅包含数值元数据,不读取提示词。",
303
314
  days: "天数",
304
315
  sessions: "会话",
@@ -332,6 +343,7 @@ window.__ModuleLoader__.load({
332
343
  markTransport: "传输错误",
333
344
  pluginUpdate: "插件更新",
334
345
  updateCheckFailed: "无法检查更新",
346
+ retry: "重试",
335
347
  updateFailed: "更新失败",
336
348
  updateAvailable: "有可用更新",
337
349
  updateUnavailable: "当前运行环境不支持自动更新。",
@@ -346,15 +358,18 @@ window.__ModuleLoader__.load({
346
358
  };
347
359
  // src/quota-model.ts
348
360
  function bar(key, label, usedPercent, extra = {}) {
361
+ const labelKey = key === "included" ? "quotaIncludedCredits" : key === "fiveHour" ? "quotaFiveHour" : key === "weekly" ? "quotaWeekly" : void 0;
349
362
  const used = Math.max(0, Math.min(100, usedPercent));
350
363
  return {
351
364
  key,
352
365
  label,
366
+ ...labelKey === void 0 ? {} : { labelKey },
353
367
  usedPercent: used,
354
368
  remainingPercent: 100 - used,
355
369
  ...extra.resetsAt === void 0 ? {} : { resetsAt: extra.resetsAt },
356
370
  ...extra.status === void 0 ? {} : { status: extra.status },
357
- ...extra.detail === void 0 ? {} : { detail: extra.detail }
371
+ ...extra.detail === void 0 ? {} : { detail: extra.detail },
372
+ ...extra.detailValues === void 0 ? {} : { detailValues: extra.detailValues }
358
373
  };
359
374
  }
360
375
  function legacyBar(key, label, window) {
@@ -371,6 +386,11 @@ window.__ModuleLoader__.load({
371
386
  const credits = report.credits;
372
387
  return [bar("included", "Included credits", credits.includedAllowance > 0 ? (credits.includedAllowance - credits.includedRemaining) / credits.includedAllowance * 100 : 0, {
373
388
  detail: `$${credits.includedRemaining.toFixed(2)} of $${credits.includedAllowance.toFixed(2)} left` + (credits.purchased > 0 ? ` · $${credits.purchased.toFixed(2)} purchased` : ""),
389
+ detailValues: {
390
+ remaining: credits.includedRemaining,
391
+ allowance: credits.includedAllowance,
392
+ purchased: credits.purchased
393
+ },
374
394
  ...credits.periodUntil === void 0 ? {} : { resetsAt: credits.periodUntil }
375
395
  })];
376
396
  }
@@ -385,16 +405,19 @@ window.__ModuleLoader__.load({
385
405
  report.windows.d24 === void 0 ? void 0 : {
386
406
  key: "24h",
387
407
  label: "24 hours",
408
+ labelKey: "last24h",
388
409
  totals: report.windows.d24
389
410
  },
390
411
  report.windows.d7 === void 0 ? void 0 : {
391
412
  key: "7d",
392
413
  label: "7 days",
414
+ labelKey: "last7d",
393
415
  totals: report.windows.d7
394
416
  },
395
417
  report.windows.d30 === void 0 ? void 0 : {
396
418
  key: "30d",
397
419
  label: "30 days",
420
+ labelKey: "last30d",
398
421
  totals: report.windows.d30
399
422
  }
400
423
  ].filter((entry) => entry !== void 0);
@@ -842,15 +865,15 @@ window.__ModuleLoader__.load({
842
865
  children: [
843
866
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
844
867
  value: "7",
845
- children: "7 days"
868
+ children: t("last7d")
846
869
  }),
847
870
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
848
871
  value: "30",
849
- children: "30 days"
872
+ children: t("last30d")
850
873
  }),
851
874
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
852
875
  value: "90",
853
- children: "90 days"
876
+ children: t("last90d")
854
877
  })
855
878
  ]
856
879
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
@@ -871,6 +894,10 @@ window.__ModuleLoader__.load({
871
894
  })]
872
895
  })]
873
896
  }),
897
+ analytics.truncated === true ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
898
+ className: "ocl-hint",
899
+ children: t("analyticsTruncated")
900
+ }) : null,
874
901
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
875
902
  className: "ocl-kpi-grid",
876
903
  children: [
@@ -963,8 +990,8 @@ window.__ModuleLoader__.load({
963
990
  className: "ocl-bar-row",
964
991
  children: [
965
992
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
966
- title: entry.label,
967
- children: entry.label
993
+ title: entry.labelKey === void 0 ? entry.label : t(entry.labelKey),
994
+ children: entry.labelKey === void 0 ? entry.label : t(entry.labelKey)
968
995
  }),
969
996
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
970
997
  className: "ocl-bar",
@@ -982,9 +1009,20 @@ window.__ModuleLoader__.load({
982
1009
  entry.resetsAt === void 0 ? "" : ` · ${reset(entry.resetsAt)}`
983
1010
  ]
984
1011
  }),
985
- entry.detail === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1012
+ entry.detailValues === void 0 ? entry.detail === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
986
1013
  className: "ocl-hint",
987
1014
  children: entry.detail
1015
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1016
+ className: "ocl-hint",
1017
+ children: [
1018
+ "$",
1019
+ entry.detailValues.remaining.toFixed(2),
1020
+ " / $",
1021
+ entry.detailValues.allowance.toFixed(2),
1022
+ " ",
1023
+ t("remaining"),
1024
+ entry.detailValues.purchased > 0 ? ` · ${t("purchased")} $${entry.detailValues.purchased.toFixed(2)}` : ""
1025
+ ]
988
1026
  })
989
1027
  ]
990
1028
  }, entry.key))
@@ -1100,7 +1138,7 @@ window.__ModuleLoader__.load({
1100
1138
  const worst = worstUsedPercent(report);
1101
1139
  const plan = state?.config.planLabel?.trim() ?? "";
1102
1140
  const name = plan === "" ? t("quotaCardName") : `${t("quotaCardName")} · ${plan}`;
1103
- const detail = bars.map((entry) => `${entry.label}: ${entry.remainingPercent.toFixed(0)}% ${t("remaining")}`).join(" · ");
1141
+ const detail = bars.map((entry) => `${entry.labelKey === void 0 ? entry.label : t(entry.labelKey)}: ${entry.remainingPercent.toFixed(0)}% ${t("remaining")}`).join(" · ");
1104
1142
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1105
1143
  type: "button",
1106
1144
  className: "ocl-foot",
@@ -1131,7 +1169,7 @@ window.__ModuleLoader__.load({
1131
1169
  className: "ocl-footHead",
1132
1170
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1133
1171
  className: "ocl-footLabel",
1134
- children: entry.label
1172
+ children: entry.labelKey === void 0 ? entry.label : t(entry.labelKey)
1135
1173
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1136
1174
  className: "ocl-footAmount",
1137
1175
  children: [
@@ -1288,7 +1326,7 @@ window.__ModuleLoader__.load({
1288
1326
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("spend") }),
1289
1327
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("tokens") })
1290
1328
  ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: rows.map((row) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
1291
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row.label }),
1329
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: t(row.labelKey) }),
1292
1330
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row.totals.requests }),
1293
1331
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("td", { children: ["$", row.totals.usd.toFixed(3)] }),
1294
1332
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row.totals.inputTokens + row.totals.outputTokens })
@@ -1467,9 +1505,9 @@ window.__ModuleLoader__.load({
1467
1505
  accounts: state.config.accounts.map((account) => ({ ...account })),
1468
1506
  modelAccountRules: state.config.modelAccountRules.map((rule) => ({ ...rule })),
1469
1507
  stickySession: state.config.stickySession,
1470
- visibleModels: state.config.visibleModels.length === 0 ? allIds : [...state.config.visibleModels],
1508
+ visibleModels: state.config.showAllModels ? allIds : [...state.config.visibleModels],
1471
1509
  filterModelsByPlan: state.config.filterModelsByPlan,
1472
- showAll: state.config.visibleModels.length === 0,
1510
+ showAll: state.config.showAllModels,
1473
1511
  modelTransports: { ...state.config.modelTransports }
1474
1512
  };
1475
1513
  }
@@ -1505,6 +1543,7 @@ window.__ModuleLoader__.load({
1505
1543
  })).filter((rule) => rule.pattern !== "" && rule.account !== ""),
1506
1544
  stickySession: draft.stickySession,
1507
1545
  visibleModels: draft.showAll ? [] : draft.visibleModels,
1546
+ showAllModels: draft.showAll,
1508
1547
  filterModelsByPlan: draft.filterModelsByPlan,
1509
1548
  modelTransports: Object.fromEntries(Object.entries(draft.modelTransports).filter(([, value]) => value !== ""))
1510
1549
  };
@@ -1519,6 +1558,18 @@ window.__ModuleLoader__.load({
1519
1558
  return false;
1520
1559
  }
1521
1560
  }
1561
+ /** Refresh may keep an unsaved draft, but a config save replaces it. */
1562
+ function mergeLoadedDraft(current, next, preserve) {
1563
+ return preserve && current !== null ? current : next;
1564
+ }
1565
+ // src/client/update-state.ts
1566
+ function updateBadge(status) {
1567
+ if (status.latestCheckFailed) return "failed";
1568
+ return status.updateAvailable ? "available" : "current";
1569
+ }
1570
+ function canInstallUpdate(status) {
1571
+ return !status.latestCheckFailed && status.updateAvailable && status.updatedVersion === void 0;
1572
+ }
1522
1573
  // src/client/update-card.tsx
1523
1574
  function PluginUpdateCard(props) {
1524
1575
  const { t } = props;
@@ -1553,7 +1604,10 @@ window.__ModuleLoader__.load({
1553
1604
  children: [
1554
1605
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("h3", {
1555
1606
  className: "ocl-card-title",
1556
- children: [t("pluginUpdate"), status === null ? null : status.updateAvailable ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1607
+ children: [t("pluginUpdate"), status === null ? null : updateBadge(status) === "failed" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1608
+ className: "ocl-badge ocl-badge-warn",
1609
+ children: t("updateCheckFailed")
1610
+ }) : updateBadge(status) === "available" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1557
1611
  className: "ocl-badge ocl-badge-warn",
1558
1612
  children: t("updateAvailable")
1559
1613
  }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
@@ -1564,33 +1618,45 @@ window.__ModuleLoader__.load({
1564
1618
  status === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1565
1619
  className: "ocl-hint",
1566
1620
  children: error ?? t("checking")
1567
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1568
- className: "ocl-row",
1569
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1570
- className: "ocl-badge",
1571
- children: [
1572
- t("currentVersion"),
1573
- ": ",
1574
- status.currentVersion
1575
- ]
1576
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1577
- className: "ocl-badge",
1578
- children: [
1579
- t("latestVersion"),
1580
- ": ",
1581
- status.latestVersion ?? "—"
1582
- ]
1583
- })]
1584
- }), status.canAutoUpdate ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1585
- type: "button",
1586
- className: "ocl-button",
1587
- disabled: busy || !status.updateAvailable || status.updatedVersion !== void 0,
1588
- onClick: update,
1589
- children: busy ? t("updating") : t("updateNow")
1590
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1591
- className: "ocl-hint",
1592
- children: t("updateUnavailable")
1593
- })] }),
1621
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
1622
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1623
+ className: "ocl-row",
1624
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1625
+ className: "ocl-badge",
1626
+ children: [
1627
+ t("currentVersion"),
1628
+ ": ",
1629
+ status.currentVersion
1630
+ ]
1631
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1632
+ className: "ocl-badge",
1633
+ children: [
1634
+ t("latestVersion"),
1635
+ ": ",
1636
+ status.latestVersion ?? "—"
1637
+ ]
1638
+ })]
1639
+ }),
1640
+ status.latestCheckFailed ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
1641
+ className: "ocl-hint",
1642
+ children: [t("updateCheckFailed"), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1643
+ type: "button",
1644
+ className: "ocl-button",
1645
+ onClick: load,
1646
+ children: t("retry")
1647
+ })]
1648
+ }) : null,
1649
+ status.canAutoUpdate ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1650
+ type: "button",
1651
+ className: "ocl-button",
1652
+ disabled: busy || !canInstallUpdate(status),
1653
+ onClick: update,
1654
+ children: busy ? t("updating") : t("updateNow")
1655
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1656
+ className: "ocl-hint",
1657
+ children: t("updateUnavailable")
1658
+ })
1659
+ ] }),
1594
1660
  notice === null ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1595
1661
  className: "ocl-notice",
1596
1662
  children: notice
@@ -1701,14 +1767,14 @@ window.__ModuleLoader__.load({
1701
1767
  const [service, setService] = (0, react.useState)(null);
1702
1768
  const [serviceBusy, setServiceBusy] = (0, react.useState)(false);
1703
1769
  const [serviceError, setServiceError] = (0, react.useState)(null);
1704
- const load = (0, react.useCallback)(async () => {
1770
+ const load = (0, react.useCallback)(async (preserveDraft = false) => {
1705
1771
  setLoading(true);
1706
1772
  try {
1707
1773
  const next = await fetchState();
1708
1774
  setState(next);
1709
1775
  const draftNext = draftOf(next);
1710
- setDraft(draftNext);
1711
- setOriginal(draftNext);
1776
+ setDraft((current) => mergeLoadedDraft(current, draftNext, preserveDraft));
1777
+ setOriginal((current) => mergeLoadedDraft(current, draftNext, preserveDraft));
1712
1778
  setError(null);
1713
1779
  } catch (caught) {
1714
1780
  setError(caught instanceof Error ? caught.message : t("failed"));
@@ -1884,7 +1950,7 @@ window.__ModuleLoader__.load({
1884
1950
  saveKey(draft.apiKeyEnv || "OLLAMA_API_KEY", keyDraft.trim()).then(() => {
1885
1951
  setKeyDraft("");
1886
1952
  setNotice(t("saved"));
1887
- return load();
1953
+ return load(true);
1888
1954
  }).catch((caught) => setError(caught instanceof Error ? caught.message : t("failed")));
1889
1955
  },
1890
1956
  children: t("saveKey")
@@ -1895,7 +1961,7 @@ window.__ModuleLoader__.load({
1895
1961
  onClick: () => {
1896
1962
  clearKey(draft.apiKeyEnv || "OLLAMA_API_KEY").then(() => {
1897
1963
  setNotice(t("saved"));
1898
- return load();
1964
+ return load(true);
1899
1965
  }).catch((caught) => setError(caught instanceof Error ? caught.message : t("failed")));
1900
1966
  },
1901
1967
  children: t("clearKey")
@@ -2160,7 +2226,7 @@ window.__ModuleLoader__.load({
2160
2226
  [account.label]: ""
2161
2227
  }));
2162
2228
  setNotice(t("saved"));
2163
- return load();
2229
+ return load(true);
2164
2230
  }).catch((caught) => setError(caught instanceof Error ? caught.message : t("failed")));
2165
2231
  },
2166
2232
  children: t("saveKey")
package/lib/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import { GenerateOptions, LlmAdapter, LlmError, LlmModelInfo, LlmProviderInfo, L
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { Context } from "@deepseek-ai/cordis";
4
4
  import { AttachmentStore } from "@deepseek-ai/dsh-attachment";
5
+ import { IncomingMessage } from "node:http";
5
6
  import { WebServer } from "@deepseek-ai/dsh-host-webserver";
6
7
  type TransportId = 'native' | 'openai-chat';
7
8
  interface AccountConfig {
@@ -43,8 +44,10 @@ interface Config {
43
44
  requestTimeoutMs?: number;
44
45
  /** Milliseconds a stream may stall; defaults to 300s. */
45
46
  streamIdleTimeoutMs?: number;
46
- /** Visible-model allowlist; empty means "show everything". */
47
+ /** Visible-model allowlist; empty with `showAllModels:false` means none. */
47
48
  visibleModels?: string[];
49
+ /** Explicit all-models switch; absent means derive from `visibleModels`. */
50
+ showAllModels?: boolean;
48
51
  /** Per-model visibility overrides; wins over `visibleModels`. */
49
52
  modelVisibility?: Record<string, boolean>;
50
53
  /** Hide models the cloud marks unsupported in the API; defaults to true. */
@@ -85,6 +88,7 @@ interface ResolvedConfig {
85
88
  requestTimeoutMs: number;
86
89
  streamIdleTimeoutMs: number;
87
90
  visibleModels: readonly string[];
91
+ showAllModels: boolean;
88
92
  modelVisibility: Readonly<Record<string, boolean>>;
89
93
  filterModelsByPlan: boolean;
90
94
  contextWindow?: number;
@@ -380,6 +384,9 @@ interface AnalyticsReport {
380
384
  summary: AnalyticsSummary;
381
385
  days: DayUsageRow[];
382
386
  sessions: SessionUsageRow[];
387
+ /** The projection directory held more files than the bounded scan. */
388
+ truncated?: boolean;
389
+ totalFiles?: number;
383
390
  }
384
391
  interface RouteDeps {
385
392
  readonly config: () => ResolvedConfig;
@@ -389,6 +396,10 @@ interface RouteDeps {
389
396
  readonly analytics?: (days: number) => Promise<AnalyticsReport>;
390
397
  readonly heatmap?: (days: number) => Promise<RequestHeatmap>;
391
398
  readonly refreshTui?: () => void;
399
+ /** Test seam; defaults to verifying the cookie against the host API. */
400
+ readonly verifyDesktop?: (req: IncomingMessage) => Promise<boolean>;
401
+ /** Same verifier for private reads; falls back to `verifyDesktop`. */
402
+ readonly verifyHost?: (req: IncomingMessage) => Promise<boolean>;
392
403
  }
393
404
  /** Register the Host HTTP surface consumed by the browser settings page. */
394
405
  declare function applyRoutes(ctx: Context, web: WebServer, deps: RouteDeps): void;
package/lib/index.js CHANGED
@@ -49,7 +49,7 @@ const DEFAULT_API_BASE = "https://ollama.com";
49
49
  const DEFAULT_OPENAI_BASE = "https://ollama.com/v1";
50
50
  const DEFAULT_USAGE_URL = "https://ollama.com/api/usage";
51
51
  const DEFAULT_BALANCE_URL = "https://ollama.com/api/balance";
52
- const DEFAULT_USER_AGENT = "dsh-ollama-cloud-provider/0.1.14";
52
+ const DEFAULT_USER_AGENT = "dsh-ollama-cloud-provider/0.1.15";
53
53
  const DEFAULT_CONTEXT_WINDOW = 131072;
54
54
  const DEFAULT_MAX_TOKENS = 32768;
55
55
  const DEFAULT_GENERATE_MAX_TOKENS = 131072;
@@ -69,6 +69,7 @@ const Config = z.object({
69
69
  requestTimeoutMs: markVolatile(z.number().min(1).max(2147483647).default(3e5)),
70
70
  streamIdleTimeoutMs: markVolatile(z.number().min(1).max(2147483647).default(3e5)),
71
71
  visibleModels: markVolatile(z.array(z.string()).default([])),
72
+ showAllModels: markVolatile(z.boolean()),
72
73
  modelVisibility: markVolatile(z.dict(z.boolean()).default({})),
73
74
  filterModelsByPlan: markVolatile(z.boolean().default(true)),
74
75
  contextWindow: markVolatile(z.number().min(1).max(1e7).step(1)),
@@ -155,6 +156,7 @@ function ruleList(value) {
155
156
  /** Normalize a raw config (possibly bypassing schemastery) into request facts. */
156
157
  function resolveConfig(config) {
157
158
  const apiKey = typeof config.apiKey === "string" && config.apiKey.trim() !== "" ? config.apiKey.trim() : void 0;
159
+ const visibleModels = Array.isArray(config.visibleModels) ? config.visibleModels.filter((id) => typeof id === "string" && id !== "") : [];
158
160
  return {
159
161
  apiKeyEnv: typeof config.apiKeyEnv === "string" && config.apiKeyEnv.trim() !== "" ? config.apiKeyEnv.trim() : DEFAULT_API_KEY_ENV,
160
162
  ...apiKey === void 0 ? {} : { apiKey },
@@ -166,7 +168,8 @@ function resolveConfig(config) {
166
168
  modelTransports: transportRecord(config.modelTransports),
167
169
  requestTimeoutMs: positiveInt(config.requestTimeoutMs, 3e5),
168
170
  streamIdleTimeoutMs: positiveInt(config.streamIdleTimeoutMs, 3e5),
169
- visibleModels: Array.isArray(config.visibleModels) ? config.visibleModels.filter((id) => typeof id === "string" && id !== "") : [],
171
+ visibleModels,
172
+ showAllModels: config.showAllModels === true ? true : config.showAllModels === false ? false : visibleModels.length === 0,
170
173
  modelVisibility: booleanRecord(config.modelVisibility),
171
174
  filterModelsByPlan: config.filterModelsByPlan !== false,
172
175
  ...typeof config.contextWindow === "number" && Number.isInteger(config.contextWindow) && config.contextWindow > 0 ? { contextWindow: config.contextWindow } : {},
@@ -726,10 +729,12 @@ function isOffPeak(at = Date.now()) {
726
729
  function estimateCost(input) {
727
730
  const price = priceFor(input.model, input.priceOverrides);
728
731
  const meta = metaForPrice(input.model);
729
- const offPeak = isOffPeak(input.at) && meta?.cost.offPeakInput !== void 0;
730
- const inputRate = offPeak ? meta?.cost.offPeakInput ?? price.input : price.input;
731
- const outputRate = offPeak ? meta?.cost.offPeakOutput ?? price.output : price.output;
732
- const cacheRate = offPeak ? meta?.cost.offPeakCacheRead ?? price.cacheRead : price.cacheRead;
732
+ const override = input.priceOverrides?.[input.model] ?? input.priceOverrides?.[baseIdOf(input.model)];
733
+ const offPeakAvailable = meta?.cost.offPeakInput !== void 0 || meta?.cost.offPeakOutput !== void 0 || meta?.cost.offPeakCacheRead !== void 0;
734
+ const offPeak = isOffPeak(input.at) && offPeakAvailable;
735
+ const inputRate = override?.input ?? (offPeak ? meta?.cost.offPeakInput ?? price.input : price.input);
736
+ const outputRate = override?.output ?? (offPeak ? meta?.cost.offPeakOutput ?? price.output : price.output);
737
+ const cacheRate = override?.cacheRead ?? (offPeak ? meta?.cost.offPeakCacheRead ?? price.cacheRead : price.cacheRead);
733
738
  const usd = (input.inputTokens * inputRate + input.outputTokens * outputRate + (input.cacheReadTokens ?? 0) * cacheRate) / 1e6;
734
739
  return {
735
740
  usd: price.priced ? usd : 0,
@@ -773,6 +778,10 @@ const CATALOG_TIMEOUT_MS = 15e3;
773
778
  const liveMeta = /* @__PURE__ */ new Map();
774
779
  const cache$1 = /* @__PURE__ */ new Map();
775
780
  const inflight = /* @__PURE__ */ new Map();
781
+ let generation = 0;
782
+ function liveKey(base, id) {
783
+ return `${base}|${id}`;
784
+ }
776
785
  const FALLBACK_META = {
777
786
  id: "",
778
787
  name: "",
@@ -846,16 +855,23 @@ function metaFromLive(entry, caps) {
846
855
  }
847
856
  };
848
857
  }
849
- /** Replace the in-memory live metadata with one successful catalog response. */
850
- function adoptLive(models, tags) {
858
+ /** Replace the in-memory live metadata for one API base with one successful response. */
859
+ function adoptLive(models, tags, base) {
851
860
  const caps = capabilitiesByModel(tags);
852
861
  const ids = [];
853
862
  for (const entry of models) {
854
863
  const meta = metaFromLive(entry, caps.get(str$1(entry.slug) ?? ""));
855
864
  if (meta.id === "") continue;
856
- liveMeta.set(meta.id, meta);
865
+ liveMeta.set(liveKey(base, meta.id), meta);
857
866
  ids.push(meta.id);
858
867
  }
868
+ const keep = new Set(ids);
869
+ const prefix = `${base}|`;
870
+ for (const key of liveMeta.keys()) {
871
+ if (!key.startsWith(prefix)) continue;
872
+ const id = key.slice(prefix.length);
873
+ if (!keep.has(id)) liveMeta.delete(key);
874
+ }
859
875
  return ids;
860
876
  }
861
877
  async function fetchJson(url, config, fetchImpl, signal) {
@@ -885,17 +901,18 @@ async function refreshCatalog(config, fetchImpl = fetch, force = false) {
885
901
  if (Date.now() - cached.at >= CATALOG_TTL_MS) refreshInBackground(config, fetchImpl, key);
886
902
  return cached.ids;
887
903
  }
888
- return refreshNow(config, fetchImpl, key, cached !== void 0);
904
+ return refreshNow(config, fetchImpl, key, cached !== void 0, generation);
889
905
  }
890
- async function refreshNow(config, fetchImpl, key, keepOnFailure) {
906
+ async function refreshNow(config, fetchImpl, key, keepOnFailure, epoch) {
891
907
  const signal = AbortSignal.timeout(CATALOG_TIMEOUT_MS);
892
908
  const [modelsResult, tagsResult] = await Promise.allSettled([fetchJson(modelsUrlFor(config), config, fetchImpl, signal), fetchJson(tagsUrlFor(config), config, fetchImpl, signal)]);
909
+ if (epoch !== generation) return Object.keys(GENERATED_MODELS);
893
910
  if (modelsResult.status === "fulfilled") {
894
911
  const payload = modelsResult.value;
895
912
  const tags = tagsResult.status === "fulfilled" ? tagsResult.value : void 0;
896
913
  const live = Array.isArray(payload.models) ? payload.models : [];
897
914
  if (live.length > 0) {
898
- const ids = adoptLive(live, tags);
915
+ const ids = adoptLive(live, tags, key);
899
916
  if (ids.length > 0) {
900
917
  cache$1.set(key, {
901
918
  at: Date.now(),
@@ -906,6 +923,7 @@ async function refreshNow(config, fetchImpl, key, keepOnFailure) {
906
923
  }
907
924
  const fromData = Array.isArray(payload.data) ? payload.data.map((entry) => str$1(entry.id)).filter((id) => id !== void 0) : [];
908
925
  if (fromData.length > 0) {
926
+ for (const liveKey of liveMeta.keys()) if (liveKey.startsWith(`${key}|`)) liveMeta.delete(liveKey);
909
927
  cache$1.set(key, {
910
928
  at: Date.now(),
911
929
  ids: fromData
@@ -918,7 +936,7 @@ async function refreshNow(config, fetchImpl, key, keepOnFailure) {
918
936
  if (stale !== void 0) return stale.ids;
919
937
  }
920
938
  const fallback = Object.keys(GENERATED_MODELS);
921
- cache$1.set(key, {
939
+ if (epoch === generation) cache$1.set(key, {
922
940
  at: Date.now(),
923
941
  ids: fallback
924
942
  });
@@ -926,17 +944,19 @@ async function refreshNow(config, fetchImpl, key, keepOnFailure) {
926
944
  }
927
945
  function refreshInBackground(config, fetchImpl, key) {
928
946
  if (inflight.has(key)) return;
929
- const task = refreshNow(config, fetchImpl, key, true).catch(() => cache$1.get(key)?.ids ?? Object.keys(GENERATED_MODELS)).finally(() => {
947
+ const task = refreshNow(config, fetchImpl, key, true, generation).catch(() => cache$1.get(key)?.ids ?? Object.keys(GENERATED_MODELS)).finally(() => {
930
948
  inflight.delete(key);
931
949
  });
932
950
  inflight.set(key, task);
933
951
  }
934
952
  function clearCatalogCache() {
953
+ generation += 1;
935
954
  cache$1.clear();
936
955
  inflight.clear();
956
+ liveMeta.clear();
937
957
  }
938
- function baseMeta(id) {
939
- const meta = liveMeta.get(id) ?? GENERATED_MODELS[id];
958
+ function baseMeta(id, base) {
959
+ const meta = liveMeta.get(liveKey(base, id)) ?? GENERATED_MODELS[id];
940
960
  return meta === void 0 ? {
941
961
  ...FALLBACK_META,
942
962
  id,
@@ -944,7 +964,7 @@ function baseMeta(id) {
944
964
  } : meta;
945
965
  }
946
966
  function effectiveModel(id, config) {
947
- const meta = baseMeta(id);
967
+ const meta = baseMeta(id, config.apiBase);
948
968
  return {
949
969
  ...meta,
950
970
  transport: config.modelTransports[id] ?? config.transport,
@@ -961,12 +981,12 @@ function effectiveMaxTokens(meta, config) {
961
981
  function modelVisible(id, config) {
962
982
  const override = config.modelVisibility[id];
963
983
  if (override !== void 0) return override;
964
- if (config.visibleModels.length === 0) return true;
984
+ if (config.showAllModels) return true;
965
985
  return config.visibleModels.includes(id);
966
986
  }
967
987
  function modelAvailable(id, config) {
968
988
  if (!config.filterModelsByPlan) return true;
969
- return baseMeta(id).available !== false;
989
+ return baseMeta(id, config.apiBase).available !== false;
970
990
  }
971
991
  function sortForPicker(ids, config, unfiltered = false) {
972
992
  return ids.filter((id) => unfiltered || modelVisible(id, config) && modelAvailable(id, config)).sort((left, right) => {
@@ -1121,7 +1141,6 @@ async function resolveImages(options, store, signal) {
1121
1141
  const base64 = Buffer.from(request.data).toString("base64");
1122
1142
  images.set(ref.attachmentId, {
1123
1143
  mediaType: request.mediaType,
1124
- base64,
1125
1144
  dataUrl: `data:${request.mediaType};base64,${base64}`,
1126
1145
  width: request.width,
1127
1146
  height: request.height
@@ -1559,7 +1578,6 @@ async function readRequestHeatmap(days, now = Date.now()) {
1559
1578
  const models = /* @__PURE__ */ new Map();
1560
1579
  const accounts = /* @__PURE__ */ new Map();
1561
1580
  const accountMetrics = /* @__PURE__ */ new Map();
1562
- const seen = /* @__PURE__ */ new Set();
1563
1581
  let total = 0;
1564
1582
  let firstAt = null;
1565
1583
  let lastAt = null;
@@ -1594,9 +1612,6 @@ async function readRequestHeatmap(days, now = Date.now()) {
1594
1612
  const provider = typeof parsed.provider === "string" ? parsed.provider : "";
1595
1613
  const model = typeof parsed.model === "string" ? parsed.model : "";
1596
1614
  const account = typeof parsed.account === "string" && parsed.account !== "" ? parsed.account : "unknown";
1597
- const key = `${at}|${provider}|${model}|${account}`;
1598
- if (seen.has(key)) continue;
1599
- seen.add(key);
1600
1615
  const date = new Date(at);
1601
1616
  const hour = date.getHours();
1602
1617
  const day = (date.getDay() + 6) % 7;
@@ -1922,6 +1937,7 @@ async function* parseNativeStream(response, idleTimeoutMs, signal) {
1922
1937
  }
1923
1938
  }
1924
1939
  if (!sawContent) throw new LlmError("Ollama Cloud returned an empty stream", "EMPTY_RESPONSE");
1940
+ throw new LlmError("Ollama Cloud stream ended before done:true", "TRANSPORT");
1925
1941
  }
1926
1942
  // src/transports/sse.ts
1927
1943
  async function readWithIdleTimeout(reader, idleTimeoutMs, signal) {
@@ -1956,7 +1972,7 @@ async function* sseData(body, idleTimeoutMs, signal) {
1956
1972
  for (;;) {
1957
1973
  const result = await readWithIdleTimeout(reader, idleTimeoutMs, signal);
1958
1974
  if (result.done) break;
1959
- buffer += decoder.decode(result.value, { stream: true }).replace(/\r\n/g, "\n");
1975
+ buffer = (buffer + decoder.decode(result.value, { stream: true })).replace(/\r\n/g, "\n");
1960
1976
  for (;;) {
1961
1977
  const boundary = buffer.indexOf("\n\n");
1962
1978
  if (boundary < 0) break;
@@ -2020,13 +2036,17 @@ async function* parseChatStream(response, idleTimeoutMs, signal) {
2020
2036
  let finishReason;
2021
2037
  let usage;
2022
2038
  let sawContent = false;
2039
+ let terminated = false;
2023
2040
  for await (const data of sseData(response.body, idleTimeoutMs, signal)) {
2024
- if (data === "[DONE]") break;
2041
+ if (data === "[DONE]") {
2042
+ terminated = true;
2043
+ break;
2044
+ }
2025
2045
  let chunk;
2026
2046
  try {
2027
2047
  chunk = JSON.parse(data);
2028
- } catch {
2029
- continue;
2048
+ } catch (error) {
2049
+ throw new LlmError("Ollama Cloud sent an invalid SSE event", "PROVIDER_HTTP_ERROR", { cause: error });
2030
2050
  }
2031
2051
  const streamError = classifyStreamError(chunk);
2032
2052
  if (streamError !== void 0) throw streamError;
@@ -2104,9 +2124,14 @@ async function* parseChatStream(response, idleTimeoutMs, signal) {
2104
2124
  argumentsDelta
2105
2125
  };
2106
2126
  }
2107
- if (choice.finish_reason !== void 0 && choice.finish_reason !== null) finishReason = choice.finish_reason;
2127
+ if (choice.finish_reason !== void 0 && choice.finish_reason !== null) {
2128
+ finishReason = choice.finish_reason;
2129
+ terminated = true;
2130
+ }
2108
2131
  }
2109
2132
  }
2133
+ if (!sawContent) throw new LlmError("Ollama Cloud completed the request without content", "EMPTY_RESPONSE");
2134
+ if (!terminated) throw new LlmError("Ollama Cloud stream ended before [DONE] or finish_reason", "TRANSPORT");
2110
2135
  if (textIndex !== void 0) yield {
2111
2136
  type: "block-end",
2112
2137
  index: textIndex,
@@ -2140,7 +2165,6 @@ async function* parseChatStream(response, idleTimeoutMs, signal) {
2140
2165
  type: "usage",
2141
2166
  usage
2142
2167
  };
2143
- if (!sawContent) throw new LlmError("Ollama Cloud completed the request without content", "EMPTY_RESPONSE");
2144
2168
  yield {
2145
2169
  type: "finish",
2146
2170
  reason: finishReasonOf(finishReason, toolCalls.size > 0)
@@ -2721,15 +2745,18 @@ function offLabel(id, meta) {
2721
2745
  }
2722
2746
  // src/quota-model.ts
2723
2747
  function bar$1(key, label, usedPercent, extra = {}) {
2748
+ const labelKey = key === "included" ? "quotaIncludedCredits" : key === "fiveHour" ? "quotaFiveHour" : key === "weekly" ? "quotaWeekly" : void 0;
2724
2749
  const used = Math.max(0, Math.min(100, usedPercent));
2725
2750
  return {
2726
2751
  key,
2727
2752
  label,
2753
+ ...labelKey === void 0 ? {} : { labelKey },
2728
2754
  usedPercent: used,
2729
2755
  remainingPercent: 100 - used,
2730
2756
  ...extra.resetsAt === void 0 ? {} : { resetsAt: extra.resetsAt },
2731
2757
  ...extra.status === void 0 ? {} : { status: extra.status },
2732
- ...extra.detail === void 0 ? {} : { detail: extra.detail }
2758
+ ...extra.detail === void 0 ? {} : { detail: extra.detail },
2759
+ ...extra.detailValues === void 0 ? {} : { detailValues: extra.detailValues }
2733
2760
  };
2734
2761
  }
2735
2762
  function legacyBar(key, label, window) {
@@ -2746,6 +2773,11 @@ function quotaBars(report) {
2746
2773
  const credits = report.credits;
2747
2774
  return [bar$1("included", "Included credits", credits.includedAllowance > 0 ? (credits.includedAllowance - credits.includedRemaining) / credits.includedAllowance * 100 : 0, {
2748
2775
  detail: `$${credits.includedRemaining.toFixed(2)} of $${credits.includedAllowance.toFixed(2)} left` + (credits.purchased > 0 ? ` · $${credits.purchased.toFixed(2)} purchased` : ""),
2776
+ detailValues: {
2777
+ remaining: credits.includedRemaining,
2778
+ allowance: credits.includedAllowance,
2779
+ purchased: credits.purchased
2780
+ },
2749
2781
  ...credits.periodUntil === void 0 ? {} : { resetsAt: credits.periodUntil }
2750
2782
  })];
2751
2783
  }
@@ -2757,16 +2789,19 @@ function windowRows(report) {
2757
2789
  report.windows.d24 === void 0 ? void 0 : {
2758
2790
  key: "24h",
2759
2791
  label: "24 hours",
2792
+ labelKey: "last24h",
2760
2793
  totals: report.windows.d24
2761
2794
  },
2762
2795
  report.windows.d7 === void 0 ? void 0 : {
2763
2796
  key: "7d",
2764
2797
  label: "7 days",
2798
+ labelKey: "last7d",
2765
2799
  totals: report.windows.d7
2766
2800
  },
2767
2801
  report.windows.d30 === void 0 ? void 0 : {
2768
2802
  key: "30d",
2769
2803
  label: "30 days",
2804
+ labelKey: "last30d",
2770
2805
  totals: report.windows.d30
2771
2806
  }
2772
2807
  ].filter((entry) => entry !== void 0);
@@ -2854,6 +2889,7 @@ async function modelsText(deps) {
2854
2889
  async function testText(deps, model) {
2855
2890
  const started = Date.now();
2856
2891
  let text = "";
2892
+ let reasoning = "";
2857
2893
  try {
2858
2894
  for await (const chunk of deps.adapter.stream({
2859
2895
  provider: PROVIDER,
@@ -2865,11 +2901,17 @@ async function testText(deps, model) {
2865
2901
  text: "Reply with exactly OK."
2866
2902
  }]
2867
2903
  }],
2868
- maxTokens: 16
2904
+ reasoningEffort: ReasoningEffortId("off"),
2905
+ maxTokens: 64
2869
2906
  })) if (chunk.type === "text-delta") text += chunk.text;
2907
+ else if (chunk.type === "reasoning-delta") reasoning += chunk.text;
2908
+ if (text === "") return {
2909
+ ok: false,
2910
+ text: `${model}: empty reply${reasoning === "" ? "" : ` (reasoning only: ${reasoning.slice(0, 80)})`}`
2911
+ };
2870
2912
  return {
2871
2913
  ok: true,
2872
- text: `${model}: OK in ${Date.now() - started} ms${text === "" ? "" : ` · ${text.slice(0, 80)}`}`
2914
+ text: `${model}: OK in ${Date.now() - started} ms · ${text.slice(0, 80)}`
2873
2915
  };
2874
2916
  } catch (error) {
2875
2917
  return {
@@ -3578,8 +3620,26 @@ async function readModelAnalytics(days = 30, priceOverrides = {}) {
3578
3620
  if (cached !== void 0 && Date.now() - cached.at < CACHE_TTL_MS) return cached.report;
3579
3621
  const dir = projectionDirectory();
3580
3622
  const sessions = [];
3623
+ let truncated = false;
3624
+ let totalFiles = 0;
3581
3625
  try {
3582
- const files = (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).slice(0, MAX_FILES);
3626
+ const candidates = (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json"));
3627
+ totalFiles = candidates.length;
3628
+ truncated = candidates.length > MAX_FILES;
3629
+ let files = candidates;
3630
+ if (truncated) files = (await Promise.all(candidates.map(async (entry) => {
3631
+ try {
3632
+ return {
3633
+ entry,
3634
+ at: (await stat(join(dir, entry.name))).mtimeMs
3635
+ };
3636
+ } catch {
3637
+ return {
3638
+ entry,
3639
+ at: 0
3640
+ };
3641
+ }
3642
+ }))).sort((left, right) => right.at - left.at).slice(0, MAX_FILES).map((item) => item.entry);
3583
3643
  let cursor = 0;
3584
3644
  const workers = Array.from({ length: Math.min(16, files.length) }, async () => {
3585
3645
  while (true) {
@@ -3602,7 +3662,11 @@ async function readModelAnalytics(days = 30, priceOverrides = {}) {
3602
3662
  } catch (error) {
3603
3663
  bestEffortFailed("projection cache is unavailable", error);
3604
3664
  }
3605
- const report = aggregateSessions(sessions, clamped, Date.now(), priceOverrides);
3665
+ const report = {
3666
+ ...aggregateSessions(sessions, clamped, Date.now(), priceOverrides),
3667
+ truncated,
3668
+ totalFiles
3669
+ };
3606
3670
  cache.set(cacheKey, {
3607
3671
  at: Date.now(),
3608
3672
  report
@@ -3622,6 +3686,7 @@ function publicConfig(config) {
3622
3686
  requestTimeoutMs: config.requestTimeoutMs,
3623
3687
  streamIdleTimeoutMs: config.streamIdleTimeoutMs,
3624
3688
  visibleModels: config.visibleModels,
3689
+ showAllModels: config.showAllModels,
3625
3690
  modelVisibility: config.modelVisibility,
3626
3691
  filterModelsByPlan: config.filterModelsByPlan,
3627
3692
  contextWindow: config.contextWindow ?? null,
@@ -3682,6 +3747,16 @@ async function probeService(config, fetchImpl = fetch) {
3682
3747
  }
3683
3748
  // src/routes-values.ts
3684
3749
  const TRANSPORTS = /* @__PURE__ */ new Set(["native", "openai-chat"]);
3750
+ const CREDENTIAL_REF_PATTERN = /^OLLAMA_[A-Z0-9_]+$/;
3751
+ /** The plugin may read and write only its own credential namespace. */
3752
+ function normalizeCredentialRef(value) {
3753
+ if (typeof value !== "string") return void 0;
3754
+ const ref = value.trim();
3755
+ return CREDENTIAL_REF_PATTERN.test(ref) ? ref : void 0;
3756
+ }
3757
+ function isCredentialRef(value) {
3758
+ return normalizeCredentialRef(value) !== void 0;
3759
+ }
3685
3760
  function cleanAccounts(value) {
3686
3761
  if (!Array.isArray(value)) return [];
3687
3762
  const out = [];
@@ -3767,14 +3842,35 @@ function sourceHost(value) {
3767
3842
  }
3768
3843
  /**
3769
3844
  * The Desktop renderer runs on `dsh-app://app`. Its host fetch has no Origin
3770
- * or Referer, but it carries the signed host auth cookie and the desktop user
3771
- * agent. Require both so a plain LAN client without either stays fail-closed.
3845
+ * or Referer, but it carries the host auth cookie and the desktop user agent.
3846
+ * The names alone are not proof: verify the cookie against the host's own
3847
+ * authenticated API, which rejects forged values with 401/403.
3772
3848
  */
3773
3849
  function desktopShellRequest(req) {
3774
3850
  const agent = req.headers["user-agent"] ?? "";
3775
3851
  const cookie = req.headers.cookie ?? "";
3776
3852
  return agent.includes("@deepseek-ai/dsh-desktop/") && cookie.includes("dsh-auth-");
3777
3853
  }
3854
+ async function defaultVerifyHost(req) {
3855
+ const host = req.headers.host;
3856
+ const cookie = req.headers.cookie;
3857
+ if (host === void 0 || host === "" || cookie === void 0 || cookie === "") return false;
3858
+ try {
3859
+ const response = await fetch(`http://${host}/api/version`, {
3860
+ headers: {
3861
+ cookie,
3862
+ accept: "application/json"
3863
+ },
3864
+ redirect: "manual",
3865
+ signal: AbortSignal.timeout(2500)
3866
+ });
3867
+ await response.body?.cancel();
3868
+ if (response.status >= 300 && response.status < 400) return false;
3869
+ return response.status < 500 && response.status !== 401 && response.status !== 403;
3870
+ } catch {
3871
+ return false;
3872
+ }
3873
+ }
3778
3874
  /**
3779
3875
  * Write routes must prove a same-origin browser context. A LAN bridge that
3780
3876
  * rewrites Host and socket to loopback would otherwise let any non-browser
@@ -3786,7 +3882,6 @@ function writeSourceError(req) {
3786
3882
  if (host === void 0 || host === "") return "request host required";
3787
3883
  const origin = req.headers.origin;
3788
3884
  if (origin !== void 0 && origin !== "") return sourceHost(origin) === host ? void 0 : "cross-origin request refused";
3789
- if (desktopShellRequest(req)) return void 0;
3790
3885
  const referer = req.headers.referer;
3791
3886
  if (referer === void 0 || referer === "") return "request origin required";
3792
3887
  return sourceHost(referer) === host ? void 0 : "cross-origin request refused";
@@ -3832,7 +3927,7 @@ async function readJson(req) {
3832
3927
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("body must be a JSON object");
3833
3928
  return parsed;
3834
3929
  }
3835
- function requirePost(req, res) {
3930
+ async function requirePost(req, res, verifyDesktop) {
3836
3931
  if (req.method !== "POST") {
3837
3932
  json(res, 405, { error: "POST required" });
3838
3933
  return false;
@@ -3841,16 +3936,23 @@ function requirePost(req, res) {
3841
3936
  json(res, 403, { error: "non-loopback Host refused" });
3842
3937
  return false;
3843
3938
  }
3844
- const sourceError = writeSourceError(req);
3845
- if (sourceError !== void 0) {
3846
- json(res, 403, { error: sourceError });
3847
- return false;
3848
- }
3849
3939
  const remote = req.socket.remoteAddress ?? "";
3850
3940
  if (!(remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1")) {
3851
3941
  json(res, 403, { error: "write endpoints are restricted to the local machine" });
3852
3942
  return false;
3853
3943
  }
3944
+ if (desktopShellRequest(req)) {
3945
+ if (!await verifyDesktop(req)) {
3946
+ json(res, 403, { error: "desktop authentication failed" });
3947
+ return false;
3948
+ }
3949
+ } else {
3950
+ const sourceError = writeSourceError(req);
3951
+ if (sourceError !== void 0) {
3952
+ json(res, 403, { error: sourceError });
3953
+ return false;
3954
+ }
3955
+ }
3854
3956
  if (!(req.headers["content-type"] ?? "").includes("application/json")) {
3855
3957
  json(res, 415, { error: "application/json required" });
3856
3958
  return false;
@@ -3876,9 +3978,10 @@ function settingsRevision(ctx) {
3876
3978
  * key in the shared credential store.
3877
3979
  */
3878
3980
  function canWriteCredentialRef(config, ref) {
3981
+ if (!isCredentialRef(ref)) return false;
3879
3982
  if (ref === config.apiKeyEnv) return true;
3880
3983
  for (const account of config.accounts) if (typeof account.apiKeyEnv === "string" && account.apiKeyEnv.trim() === ref) return true;
3881
- return /^OLLAMA_[A-Z0-9_]+$/.test(ref);
3984
+ return true;
3882
3985
  }
3883
3986
  function configOps(patch) {
3884
3987
  const ops = [];
@@ -3893,7 +3996,14 @@ function configOps(patch) {
3893
3996
  value
3894
3997
  });
3895
3998
  };
3896
- if ("apiKeyEnv" in patch) set("apiKeyEnv", patch.apiKeyEnv);
3999
+ if ("apiKeyEnv" in patch) {
4000
+ if (patch.apiKeyEnv === null || patch.apiKeyEnv === void 0) set("apiKeyEnv", void 0);
4001
+ else {
4002
+ const ref = normalizeCredentialRef(patch.apiKeyEnv);
4003
+ if (ref === void 0) throw new Error("invalid credential reference");
4004
+ set("apiKeyEnv", ref);
4005
+ }
4006
+ }
3897
4007
  if ("apiBase" in patch) set("apiBase", patch.apiBase);
3898
4008
  if ("openAiBase" in patch) set("openAiBase", patch.openAiBase);
3899
4009
  if ("usageUrl" in patch) set("usageUrl", patch.usageUrl);
@@ -3903,12 +4013,17 @@ function configOps(patch) {
3903
4013
  if ("requestTimeoutMs" in patch) set("requestTimeoutMs", patch.requestTimeoutMs);
3904
4014
  if ("streamIdleTimeoutMs" in patch) set("streamIdleTimeoutMs", patch.streamIdleTimeoutMs);
3905
4015
  if ("visibleModels" in patch) set("visibleModels", cleanStringArray(patch.visibleModels));
4016
+ if ("showAllModels" in patch) set("showAllModels", patch.showAllModels === true);
3906
4017
  if ("modelVisibility" in patch) set("modelVisibility", cleanBooleanRecord(patch.modelVisibility));
3907
4018
  if ("filterModelsByPlan" in patch) set("filterModelsByPlan", patch.filterModelsByPlan === true);
3908
4019
  if ("contextWindow" in patch) set("contextWindow", patch.contextWindow);
3909
4020
  if ("contextWindowOverrides" in patch) set("contextWindowOverrides", cleanNumberRecord(patch.contextWindowOverrides));
3910
4021
  if ("maxOutputTokens" in patch) set("maxOutputTokens", patch.maxOutputTokens);
3911
- if ("accounts" in patch) set("accounts", cleanAccounts(patch.accounts));
4022
+ if ("accounts" in patch) {
4023
+ const accounts = cleanAccounts(patch.accounts);
4024
+ for (const account of accounts) if (account.apiKeyEnv !== "" && !isCredentialRef(account.apiKeyEnv)) throw new Error("invalid credential reference");
4025
+ set("accounts", accounts);
4026
+ }
3912
4027
  if ("modelAccountRules" in patch) set("modelAccountRules", cleanModelAccountRules(patch.modelAccountRules));
3913
4028
  if ("stickySession" in patch) set("stickySession", patch.stickySession === true);
3914
4029
  if ("activeAccount" in patch) set("activeAccount", patch.activeAccount);
@@ -4034,6 +4149,7 @@ async function refreshAndState(ctx, deps, res) {
4034
4149
  /** Register the Host HTTP surface consumed by the browser settings page. */
4035
4150
  function applyRoutes(ctx, web, deps) {
4036
4151
  const disposers = [];
4152
+ const verifyHost = deps.verifyHost ?? deps.verifyDesktop ?? defaultVerifyHost;
4037
4153
  const route = (path, handler) => {
4038
4154
  disposers.push(web.register({
4039
4155
  kind: "exact",
@@ -4052,8 +4168,16 @@ function applyRoutes(ctx, web, deps) {
4052
4168
  }
4053
4169
  return true;
4054
4170
  };
4171
+ const privateRead = async (req, res) => {
4172
+ if (!readOnly(req, res)) return false;
4173
+ if (!await verifyHost(req)) {
4174
+ json(res, 403, { error: "authentication required" });
4175
+ return false;
4176
+ }
4177
+ return true;
4178
+ };
4055
4179
  route("/dsh-ollama/state", async (req, res) => {
4056
- if (!readOnly(req, res)) return;
4180
+ if (!await privateRead(req, res)) return;
4057
4181
  await refreshAndState(ctx, deps, res);
4058
4182
  });
4059
4183
  route("/dsh-ollama/health", async (req, res) => {
@@ -4086,7 +4210,7 @@ function applyRoutes(ctx, web, deps) {
4086
4210
  }
4087
4211
  });
4088
4212
  route("/dsh-ollama/analytics", async (req, res) => {
4089
- if (!readOnly(req, res)) return;
4213
+ if (!await privateRead(req, res)) return;
4090
4214
  const url = new URL(req.url ?? "/", "http://localhost");
4091
4215
  const requested = Number(url.searchParams.get("days") ?? "30");
4092
4216
  const days = Number.isFinite(requested) ? Math.max(1, Math.min(365, Math.trunc(requested))) : 30;
@@ -4102,7 +4226,7 @@ function applyRoutes(ctx, web, deps) {
4102
4226
  }
4103
4227
  });
4104
4228
  route("/dsh-ollama/usage", async (req, res) => {
4105
- if (!readOnly(req, res)) return;
4229
+ if (!await privateRead(req, res)) return;
4106
4230
  const raw = new URL(req.url ?? "/", "http://localhost").searchParams.get("range") ?? "7d";
4107
4231
  const range = raw === "24h" || raw === "30d" ? raw : "7d";
4108
4232
  try {
@@ -4115,7 +4239,7 @@ function applyRoutes(ctx, web, deps) {
4115
4239
  }
4116
4240
  });
4117
4241
  route("/dsh-ollama/balance", async (req, res) => {
4118
- if (!readOnly(req, res)) return;
4242
+ if (!await privateRead(req, res)) return;
4119
4243
  try {
4120
4244
  json(res, 200, await deps.usage.read() ?? {
4121
4245
  error: "balance unavailable",
@@ -4126,7 +4250,7 @@ function applyRoutes(ctx, web, deps) {
4126
4250
  }
4127
4251
  });
4128
4252
  route("/dsh-ollama/config", async (req, res) => {
4129
- if (!requirePost(req, res)) return;
4253
+ if (!await requirePost(req, res, verifyHost)) return;
4130
4254
  const settings = getSettings(ctx);
4131
4255
  if (settings?.mutate === void 0) {
4132
4256
  json(res, 503, { error: "settings service unavailable" });
@@ -4138,7 +4262,14 @@ function applyRoutes(ctx, web, deps) {
4138
4262
  }
4139
4263
  try {
4140
4264
  const body = await readJson(req);
4141
- const ops = configOps(typeof body.patch === "object" && body.patch !== null && !Array.isArray(body.patch) ? body.patch : body);
4265
+ const patch = typeof body.patch === "object" && body.patch !== null && !Array.isArray(body.patch) ? body.patch : body;
4266
+ let ops;
4267
+ try {
4268
+ ops = configOps(patch);
4269
+ } catch (error) {
4270
+ json(res, 400, { error: error instanceof Error ? error.message : "invalid patch" });
4271
+ return;
4272
+ }
4142
4273
  if (ops.length === 0) {
4143
4274
  json(res, 400, { error: "no known fields in patch" });
4144
4275
  return;
@@ -4152,7 +4283,7 @@ function applyRoutes(ctx, web, deps) {
4152
4283
  }
4153
4284
  });
4154
4285
  route("/dsh-ollama/key", async (req, res) => {
4155
- if (!requirePost(req, res)) return;
4286
+ if (!await requirePost(req, res, verifyHost)) return;
4156
4287
  const credentials = getCredentials(ctx);
4157
4288
  if (credentials === void 0) {
4158
4289
  json(res, 503, { error: "credentials service unavailable" });
@@ -4180,7 +4311,7 @@ function applyRoutes(ctx, web, deps) {
4180
4311
  }
4181
4312
  });
4182
4313
  route("/dsh-ollama/key/clear", async (req, res) => {
4183
- if (!requirePost(req, res)) return;
4314
+ if (!await requirePost(req, res, verifyHost)) return;
4184
4315
  const credentials = getCredentials(ctx);
4185
4316
  if (credentials === void 0) {
4186
4317
  json(res, 503, { error: "credentials service unavailable" });
@@ -4203,12 +4334,12 @@ function applyRoutes(ctx, web, deps) {
4203
4334
  }
4204
4335
  });
4205
4336
  route("/dsh-ollama/refresh", async (req, res) => {
4206
- if (!requirePost(req, res)) return;
4337
+ if (!await requirePost(req, res, verifyHost)) return;
4207
4338
  deps.usage.clear();
4208
4339
  await refreshAndState(ctx, deps, res);
4209
4340
  });
4210
4341
  route("/dsh-ollama/models/refresh", async (req, res) => {
4211
- if (!requirePost(req, res)) return;
4342
+ if (!await requirePost(req, res, verifyHost)) return;
4212
4343
  clearCatalogCache();
4213
4344
  deps.usage.clear();
4214
4345
  try {
@@ -4219,7 +4350,7 @@ function applyRoutes(ctx, web, deps) {
4219
4350
  await refreshAndState(ctx, deps, res);
4220
4351
  });
4221
4352
  route("/dsh-ollama/test", async (req, res) => {
4222
- if (!requirePost(req, res)) return;
4353
+ if (!await requirePost(req, res, verifyHost)) return;
4223
4354
  let body;
4224
4355
  try {
4225
4356
  body = await readJson(req);
@@ -4610,7 +4741,9 @@ function normalizeUsage(payload, range) {
4610
4741
  /** Cached reader for Ollama Cloud balance and usage. Fail-open by design. */
4611
4742
  function createUsageReader(config, resolveKey, fetchImpl = fetch) {
4612
4743
  const cache = /* @__PURE__ */ new Map();
4744
+ const inflight = /* @__PURE__ */ new Map();
4613
4745
  const usageCalls = [];
4746
+ let generation = 0;
4614
4747
  const keyFor = async (explicit) => {
4615
4748
  if (explicit !== void 0 && explicit !== "") return explicit;
4616
4749
  try {
@@ -4646,11 +4779,12 @@ function createUsageReader(config, resolveKey, fetchImpl = fetch) {
4646
4779
  return;
4647
4780
  }
4648
4781
  };
4649
- const readUsage = async (key, range) => {
4782
+ const readUsage = async (key, range, epoch) => {
4650
4783
  const current = config();
4651
4784
  const cacheKey = `${fingerprint(key)}:${range}`;
4652
4785
  const hit = cached(cacheKey);
4653
- if (hit?.report !== void 0) {
4786
+ if (hit !== void 0) {
4787
+ if (hit.report === void 0) return void 0;
4654
4788
  const totals = hit.report.windows[range === "24h" ? "d24" : range === "7d" ? "d7" : "d30"];
4655
4789
  return totals === void 0 ? void 0 : {
4656
4790
  totals,
@@ -4669,7 +4803,7 @@ function createUsageReader(config, resolveKey, fetchImpl = fetch) {
4669
4803
  url.searchParams.set("group_by", "model");
4670
4804
  const response = await request(url.toString(), key);
4671
4805
  if (!response.ok) {
4672
- cache.set(cacheKey, {
4806
+ if (epoch === generation) cache.set(cacheKey, {
4673
4807
  error: `usage endpoint returned HTTP ${response.status}`,
4674
4808
  checkedAt: Date.now()
4675
4809
  });
@@ -4677,19 +4811,23 @@ function createUsageReader(config, resolveKey, fetchImpl = fetch) {
4677
4811
  }
4678
4812
  return normalizeUsage(await response.json(), range);
4679
4813
  } catch (error) {
4680
- cache.set(cacheKey, {
4814
+ if (epoch === generation) cache.set(cacheKey, {
4681
4815
  error: error instanceof Error ? error.message : "usage request failed",
4682
4816
  checkedAt: Date.now()
4683
4817
  });
4684
4818
  return;
4685
4819
  }
4686
4820
  };
4687
- const compose = async (key, range) => {
4688
- const [balance, usage] = await Promise.all([readBalance(key), readUsage(key, range)]);
4689
- if (balance === void 0 && usage === void 0) return {
4690
- error: "usage and balance are unavailable",
4691
- checkedAt: Date.now()
4692
- };
4821
+ const compose = async (key, range, epoch) => {
4822
+ const [balance, usage] = await Promise.all([readBalance(key), readUsage(key, range, epoch)]);
4823
+ if (balance === void 0 && usage === void 0) {
4824
+ const result = {
4825
+ error: "usage and balance are unavailable",
4826
+ checkedAt: Date.now()
4827
+ };
4828
+ if (epoch === generation) cache.set(`${fingerprint(key)}:report:${range}`, result);
4829
+ return result;
4830
+ }
4693
4831
  const result = {
4694
4832
  report: {
4695
4833
  kind: balance?.kind ?? "credits",
@@ -4705,8 +4843,10 @@ function createUsageReader(config, resolveKey, fetchImpl = fetch) {
4705
4843
  },
4706
4844
  checkedAt: Date.now()
4707
4845
  };
4708
- cache.set(`${fingerprint(key)}:report:${range}`, result);
4709
- if (usage !== void 0) cache.set(`${fingerprint(key)}:${range}`, result);
4846
+ if (epoch === generation) {
4847
+ cache.set(`${fingerprint(key)}:report:${range}`, result);
4848
+ if (usage !== void 0) cache.set(`${fingerprint(key)}:${range}`, result);
4849
+ }
4710
4850
  return result;
4711
4851
  };
4712
4852
  const reader = async (range, explicitKey) => {
@@ -4717,13 +4857,20 @@ function createUsageReader(config, resolveKey, fetchImpl = fetch) {
4717
4857
  };
4718
4858
  const cacheKey = `${fingerprint(key)}:report:${range}`;
4719
4859
  const hit = cache.get(cacheKey);
4720
- if (hit?.report !== void 0 && Date.now() - hit.checkedAt < BALANCE_TTL_MS) return hit;
4721
- return compose(key, range);
4860
+ const ttl = hit?.report === void 0 ? FAILURE_TTL_MS : BALANCE_TTL_MS;
4861
+ if (hit !== void 0 && Date.now() - hit.checkedAt < ttl) return hit;
4862
+ const existing = inflight.get(cacheKey);
4863
+ if (existing !== void 0) return existing;
4864
+ const task = compose(key, range, generation).finally(() => inflight.delete(cacheKey));
4865
+ inflight.set(cacheKey, task);
4866
+ return task;
4722
4867
  };
4723
4868
  reader.read = (key) => reader("7d", key);
4724
4869
  reader.usage = (range, key) => reader(range, key);
4725
4870
  reader.clear = () => {
4871
+ generation += 1;
4726
4872
  cache.clear();
4873
+ inflight.clear();
4727
4874
  };
4728
4875
  return reader;
4729
4876
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-ollama-cloud-provider",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
4
4
  "description": "Ollama Cloud LLM provider plugin for DeepSeek Harness (dsh).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -70,9 +70,8 @@
70
70
  "build": "tsdown",
71
71
  "prepare": "tsdown 1>&2",
72
72
  "typecheck": "tsc --noEmit",
73
- "test": "node --import tsx --test tests/core.test.ts tests/usage.test.ts tests/adapter.test.ts tests/routes.test.ts tests/native.test.ts tests/commands.test.ts tests/tui-settings.test.ts tests/analytics.test.ts tests/apply.test.ts tests/account-rules.test.ts tests/request-log.test.ts tests/image-budget.test.ts tests/tool-schema.test.ts tests/tools.test.ts tests/plugin-updater.test.ts tests/compat.test.ts tests/status.test.ts",
73
+ "test": "node --import tsx --test tests/core.test.ts tests/usage.test.ts tests/adapter.test.ts tests/routes.test.ts tests/native.test.ts tests/openai-chat.test.ts tests/commands.test.ts tests/tui-settings.test.ts tests/analytics.test.ts tests/apply.test.ts tests/account-rules.test.ts tests/request-log.test.ts tests/image-budget.test.ts tests/tool-schema.test.ts tests/tools.test.ts tests/plugin-updater.test.ts tests/compat.test.ts tests/status.test.ts tests/settings-draft.test.ts tests/update-state.test.ts tests/ui-render.test.tsx",
74
74
  "check": "npm run typecheck && npm test && npm run build",
75
- "test:engine": "node scripts/test-engines.mjs",
76
75
  "release": "npm run check && npm pack",
77
76
  "sync:models": "node scripts/sync-models.mjs"
78
77
  },