@goodandready/dsh-ollama-cloud-provider 0.1.39 → 0.1.40

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/lib/client.js CHANGED
@@ -28,6 +28,7 @@ window.__ModuleLoader__.load({
28
28
  refresh: "Refresh",
29
29
  save: "Save",
30
30
  saving: "Saving…",
31
+ settingsReadOnly: "Settings are read-only in this host.",
31
32
  unsaved: "Unsaved changes",
32
33
  discard: "Discard",
33
34
  close: "Close",
@@ -275,6 +276,7 @@ window.__ModuleLoader__.load({
275
276
  refresh: "刷新",
276
277
  save: "保存",
277
278
  saving: "保存中…",
279
+ settingsReadOnly: "当前宿主机的设置为只读。",
278
280
  unsaved: "有未保存的更改",
279
281
  discard: "放弃",
280
282
  close: "关闭",
@@ -1360,6 +1362,7 @@ window.__ModuleLoader__.load({
1360
1362
  const { t, close } = props;
1361
1363
  const { state, error, load } = useHostState(6e4);
1362
1364
  const [busy, setBusy] = (0, react.useState)(false);
1365
+ const [actionError, setActionError] = (0, react.useState)(null);
1363
1366
  const [range, setRange] = (0, react.useState)("7d");
1364
1367
  const [usage, setUsage] = (0, react.useState)(null);
1365
1368
  const [analytics, setAnalytics] = (0, react.useState)(null);
@@ -1391,7 +1394,17 @@ window.__ModuleLoader__.load({
1391
1394
  const stale = usage?.stale === true || state?.usage?.stale === true;
1392
1395
  const refresh = () => {
1393
1396
  setBusy(true);
1394
- refreshState().then(() => load()).finally(() => setBusy(false));
1397
+ setActionError(null);
1398
+ (async () => {
1399
+ try {
1400
+ await refreshState();
1401
+ await load();
1402
+ } catch (caught) {
1403
+ setActionError(caught instanceof Error ? caught.message : String(caught));
1404
+ } finally {
1405
+ setBusy(false);
1406
+ }
1407
+ })();
1395
1408
  };
1396
1409
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1397
1410
  className: "ocl-panel",
@@ -1451,6 +1464,14 @@ window.__ModuleLoader__.load({
1451
1464
  error
1452
1465
  ]
1453
1466
  }),
1467
+ actionError === null ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
1468
+ className: "ocl-error",
1469
+ children: [
1470
+ t("failed"),
1471
+ ": ",
1472
+ actionError
1473
+ ]
1474
+ }),
1454
1475
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
1455
1476
  className: "ocl-card",
1456
1477
  children: [
@@ -1700,7 +1721,8 @@ window.__ModuleLoader__.load({
1700
1721
  visibleModels: state.config.showAllModels ? allIds : [...state.config.visibleModels],
1701
1722
  filterModelsByPlan: state.config.filterModelsByPlan,
1702
1723
  modelVisibility: { ...state.config.modelVisibility },
1703
- manualModels: (state.config.manualModels ?? []).map((model) => ({
1724
+ manualModels: (state.config.manualModels ?? []).map((model, index) => ({
1725
+ uid: `manual-${index}`,
1704
1726
  id: model.id,
1705
1727
  enabled: model.enabled !== false,
1706
1728
  name: model.name ?? "",
@@ -1731,105 +1753,141 @@ window.__ModuleLoader__.load({
1731
1753
  modelTransports: { ...state.config.modelTransports }
1732
1754
  };
1733
1755
  }
1734
- function numberOrNull(text) {
1756
+ /**
1757
+ * An empty field means "unset", never "substitute a default". The schema owns
1758
+ * the default, so an explicit null is the only value that cannot silently
1759
+ * replace what the user typed.
1760
+ */
1761
+ function numberOrNull(text, field = "value") {
1735
1762
  const trimmed = text.trim();
1736
1763
  if (trimmed === "") return null;
1737
1764
  const value = Number(trimmed);
1738
- if (!Number.isInteger(value) || value < 0) throw new Error(`Invalid number: ${text}`);
1765
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${field} must be a non-negative integer`);
1739
1766
  return value;
1740
1767
  }
1741
- function boundedNumber(text, min, max, integer) {
1768
+ function boundedNumber(text, min, max, integer, field = "value") {
1742
1769
  const trimmed = text.trim();
1743
1770
  if (trimmed === "") return null;
1744
1771
  const value = Number(trimmed);
1745
- if (!Number.isFinite(value) || value < min || value > max || integer && !Number.isInteger(value)) throw new Error(`Invalid number: ${text}`);
1772
+ if (!Number.isFinite(value) || value < min || value > max || integer && !Number.isInteger(value)) throw new Error(`${field} must be ${integer ? "an integer " : ""}between ${min} and ${max}`);
1746
1773
  return value;
1747
1774
  }
1748
1775
  function stopList(text) {
1749
1776
  return text.split(/[\n,]/).map((entry) => entry.trim()).filter((entry) => entry !== "");
1750
1777
  }
1751
- function patchOf(draft) {
1778
+ function draftPatch(draft) {
1779
+ const errors = {};
1780
+ const field = (name, compute) => {
1781
+ try {
1782
+ return compute();
1783
+ } catch (error) {
1784
+ errors[name] = error instanceof Error ? error.message : String(error);
1785
+ return null;
1786
+ }
1787
+ };
1788
+ const manualModels = [];
1789
+ draft.manualModels.forEach((model, index) => {
1790
+ const id = model.id.trim();
1791
+ if (id === "") return;
1792
+ const name = `manualModels[${index}]`;
1793
+ try {
1794
+ const contextWindow = numberOrNull(model.contextWindow, `${name}.contextWindow`);
1795
+ const maxTokens = numberOrNull(model.maxTokens, `${name}.maxTokens`);
1796
+ manualModels.push({
1797
+ id,
1798
+ enabled: model.enabled,
1799
+ ...model.name.trim() === "" ? {} : { name: model.name.trim() },
1800
+ ...contextWindow === null ? {} : { contextWindow },
1801
+ ...maxTokens === null ? {} : { maxTokens },
1802
+ image: model.image,
1803
+ thinking: model.thinking,
1804
+ ...stopList(model.reasoningEfforts).length === 0 ? {} : { reasoningEfforts: stopList(model.reasoningEfforts) },
1805
+ ...model.defaultReasoning.trim() === "" ? {} : { defaultReasoning: model.defaultReasoning.trim() },
1806
+ tools: model.tools
1807
+ });
1808
+ } catch (error) {
1809
+ errors[name] = error instanceof Error ? error.message : String(error);
1810
+ }
1811
+ });
1752
1812
  return {
1753
- apiKeyEnv: draft.apiKeyEnv.trim(),
1754
- apiBase: draft.apiBase.trim(),
1755
- openAiBase: draft.openAiBase.trim(),
1756
- usageUrl: draft.usageUrl.trim(),
1757
- balanceUrl: draft.balanceUrl.trim(),
1758
- transport: draft.transport,
1759
- requestTimeoutMs: numberOrNull(draft.requestTimeoutMs) ?? 3e5,
1760
- streamIdleTimeoutMs: numberOrNull(draft.streamIdleTimeoutMs) ?? 3e5,
1761
- attemptTimeoutMs: boundedNumber(draft.attemptTimeoutMs, 0, 36e5, true) ?? 0,
1762
- retryMaxRetries: boundedNumber(draft.retryMaxRetries, 0, 10, true) ?? 0,
1763
- retryBaseDelayMs: boundedNumber(draft.retryBaseDelayMs, 0, 6e4, true) ?? 250,
1764
- retryMaxDelayMs: boundedNumber(draft.retryMaxDelayMs, 0, 12e4, true) ?? 2e3,
1765
- retryJitter: boundedNumber(draft.retryJitter, 0, 1, false) ?? .2,
1766
- maxOutputTokens: numberOrNull(draft.maxOutputTokens),
1767
- contextWindow: numberOrNull(draft.contextWindow),
1768
- temperature: boundedNumber(draft.temperature, 0, 2, false),
1769
- topK: boundedNumber(draft.topK, 1, 1e6, true),
1770
- topP: boundedNumber(draft.topP, 0, 1, false),
1771
- minP: boundedNumber(draft.minP, 0, 1, false),
1772
- seed: boundedNumber(draft.seed, 0, 4294967295, true),
1773
- repeatPenalty: boundedNumber(draft.repeatPenalty, 0, 2, false),
1774
- repeatLastN: boundedNumber(draft.repeatLastN, -1, 1e6, true),
1775
- numCtx: boundedNumber(draft.numCtx, 1, 1e7, true),
1776
- keepAlive: draft.keepAlive.trim(),
1777
- stop: stopList(draft.stop),
1778
- autoRefresh: draft.autoRefresh,
1779
- refreshMinutes: boundedNumber(draft.refreshMinutes, 0, 10080, true) ?? 1440,
1780
- showSidebarQuota: draft.showSidebarQuota,
1781
- planLabel: draft.planLabel.trim(),
1782
- activeAccount: draft.activeAccount.trim(),
1783
- accounts: draft.accounts.map((account) => ({
1784
- label: account.label.trim(),
1785
- apiKeyEnv: account.apiKeyEnv.trim()
1786
- })).filter((account) => account.label !== "" || account.apiKeyEnv !== ""),
1787
- modelAccountRules: draft.modelAccountRules.map((rule) => ({
1788
- pattern: rule.pattern.trim(),
1789
- account: rule.account.trim()
1790
- })).filter((rule) => rule.pattern !== "" && rule.account !== ""),
1791
- stickySession: draft.stickySession,
1792
- visibleModels: draft.showAll ? [] : draft.visibleModels,
1793
- showAllModels: draft.showAll,
1794
- filterModelsByPlan: draft.filterModelsByPlan,
1795
- modelVisibility: draft.showAll ? draft.modelVisibility : Object.fromEntries(Object.entries(draft.modelVisibility).filter(([id, val]) => val === false || draft.visibleModels.includes(id))),
1796
- manualModels: draft.manualModels.filter((model) => model.id.trim() !== "").map((model) => ({
1797
- id: model.id.trim(),
1798
- enabled: model.enabled,
1799
- ...model.name.trim() === "" ? {} : { name: model.name.trim() },
1800
- ...numberOrNull(model.contextWindow) === null ? {} : { contextWindow: numberOrNull(model.contextWindow) },
1801
- ...numberOrNull(model.maxTokens) === null ? {} : { maxTokens: numberOrNull(model.maxTokens) },
1802
- image: model.image,
1803
- thinking: model.thinking,
1804
- ...stopList(model.reasoningEfforts).length === 0 ? {} : { reasoningEfforts: stopList(model.reasoningEfforts) },
1805
- ...model.defaultReasoning.trim() === "" ? {} : { defaultReasoning: model.defaultReasoning.trim() },
1806
- tools: model.tools
1807
- })),
1808
- modelOrder: draft.modelOrder.filter((id) => id !== ""),
1809
- contextWindowOverrides: Object.fromEntries(Object.entries(draft.contextWindowOverrides).map(([id, value]) => [id, numberOrNull(value)]).filter((entry) => entry[1] !== null && entry[1] > 0)),
1810
- priceOverrides: Object.fromEntries(Object.entries(draft.priceOverrides).map(([id, price]) => {
1811
- const out = {};
1812
- for (const [field, value] of Object.entries(price)) {
1813
- const parsed = numberOrNull(value);
1814
- if (parsed !== null) out[field] = parsed;
1815
- }
1816
- return [id, out];
1817
- }).filter((entry) => Object.keys(entry[1]).length > 0)),
1818
- modelOverrides: Object.fromEntries(Object.entries(draft.modelOverrides).map(([id, override]) => {
1819
- const contextWindow = numberOrNull(override.contextWindow);
1820
- const efforts = stopList(override.reasoningEfforts);
1821
- return [id, {
1822
- ...contextWindow === null || contextWindow <= 0 ? {} : { contextWindow },
1823
- ...override.image === "" ? {} : { image: override.image === "yes" },
1824
- ...override.thinking === "" ? {} : { thinking: override.thinking === "yes" },
1825
- ...efforts.length === 0 ? {} : { reasoningEfforts: efforts },
1826
- ...override.defaultEffort.trim() === "" ? {} : { defaultEffort: override.defaultEffort.trim() },
1827
- ...override.enabled === "" ? {} : { enabled: override.enabled === "yes" }
1828
- }];
1829
- }).filter((entry) => Object.keys(entry[1]).length > 0)),
1830
- modelTransports: Object.fromEntries(Object.entries(draft.modelTransports).filter(([, value]) => value !== ""))
1813
+ patch: {
1814
+ apiKeyEnv: draft.apiKeyEnv.trim(),
1815
+ apiBase: draft.apiBase.trim(),
1816
+ openAiBase: draft.openAiBase.trim(),
1817
+ usageUrl: draft.usageUrl.trim(),
1818
+ balanceUrl: draft.balanceUrl.trim(),
1819
+ transport: draft.transport,
1820
+ requestTimeoutMs: field("requestTimeoutMs", () => numberOrNull(draft.requestTimeoutMs, "requestTimeoutMs")),
1821
+ streamIdleTimeoutMs: field("streamIdleTimeoutMs", () => numberOrNull(draft.streamIdleTimeoutMs, "streamIdleTimeoutMs")),
1822
+ attemptTimeoutMs: field("attemptTimeoutMs", () => boundedNumber(draft.attemptTimeoutMs, 0, 36e5, true, "attemptTimeoutMs")),
1823
+ retryMaxRetries: field("retryMaxRetries", () => boundedNumber(draft.retryMaxRetries, 0, 10, true, "retryMaxRetries")),
1824
+ retryBaseDelayMs: field("retryBaseDelayMs", () => boundedNumber(draft.retryBaseDelayMs, 0, 6e4, true, "retryBaseDelayMs")),
1825
+ retryMaxDelayMs: field("retryMaxDelayMs", () => boundedNumber(draft.retryMaxDelayMs, 0, 12e4, true, "retryMaxDelayMs")),
1826
+ retryJitter: field("retryJitter", () => boundedNumber(draft.retryJitter, 0, 1, false, "retryJitter")),
1827
+ maxOutputTokens: field("maxOutputTokens", () => numberOrNull(draft.maxOutputTokens, "maxOutputTokens")),
1828
+ contextWindow: field("contextWindow", () => numberOrNull(draft.contextWindow, "contextWindow")),
1829
+ temperature: field("temperature", () => boundedNumber(draft.temperature, 0, 2, false, "temperature")),
1830
+ topK: field("topK", () => boundedNumber(draft.topK, 1, 1e6, true, "topK")),
1831
+ topP: field("topP", () => boundedNumber(draft.topP, 0, 1, false, "topP")),
1832
+ minP: field("minP", () => boundedNumber(draft.minP, 0, 1, false, "minP")),
1833
+ seed: field("seed", () => boundedNumber(draft.seed, 0, 4294967295, true, "seed")),
1834
+ repeatPenalty: field("repeatPenalty", () => boundedNumber(draft.repeatPenalty, 0, 2, false, "repeatPenalty")),
1835
+ repeatLastN: field("repeatLastN", () => boundedNumber(draft.repeatLastN, -1, 1e6, true, "repeatLastN")),
1836
+ numCtx: field("numCtx", () => boundedNumber(draft.numCtx, 1, 1e7, true, "numCtx")),
1837
+ keepAlive: draft.keepAlive.trim(),
1838
+ stop: stopList(draft.stop),
1839
+ autoRefresh: draft.autoRefresh,
1840
+ refreshMinutes: field("refreshMinutes", () => boundedNumber(draft.refreshMinutes, 0, 10080, true, "refreshMinutes")),
1841
+ showSidebarQuota: draft.showSidebarQuota,
1842
+ planLabel: draft.planLabel.trim(),
1843
+ activeAccount: draft.activeAccount.trim(),
1844
+ accounts: draft.accounts.map((account) => ({
1845
+ label: account.label.trim(),
1846
+ apiKeyEnv: account.apiKeyEnv.trim()
1847
+ })).filter((account) => account.label !== "" || account.apiKeyEnv !== ""),
1848
+ modelAccountRules: draft.modelAccountRules.map((rule) => ({
1849
+ pattern: rule.pattern.trim(),
1850
+ account: rule.account.trim()
1851
+ })).filter((rule) => rule.pattern !== "" && rule.account !== ""),
1852
+ stickySession: draft.stickySession,
1853
+ visibleModels: draft.showAll ? [] : draft.visibleModels,
1854
+ showAllModels: draft.showAll,
1855
+ filterModelsByPlan: draft.filterModelsByPlan,
1856
+ modelVisibility: draft.showAll ? draft.modelVisibility : Object.fromEntries(Object.entries(draft.modelVisibility).filter(([id, val]) => val === false || draft.visibleModels.includes(id))),
1857
+ manualModels,
1858
+ modelOrder: draft.modelOrder.filter((id) => id !== ""),
1859
+ contextWindowOverrides: field("contextWindowOverrides", () => Object.fromEntries(Object.entries(draft.contextWindowOverrides).map(([id, value]) => [id, numberOrNull(value, `contextWindowOverrides.${id}`)]).filter((entry) => entry[1] !== null && entry[1] > 0))) ?? {},
1860
+ priceOverrides: field("priceOverrides", () => Object.fromEntries(Object.entries(draft.priceOverrides).map(([id, price]) => {
1861
+ const out = {};
1862
+ for (const [name, value] of Object.entries(price)) {
1863
+ const parsed = numberOrNull(value, `priceOverrides.${id}.${name}`);
1864
+ if (parsed !== null) out[name] = parsed;
1865
+ }
1866
+ return [id, out];
1867
+ }).filter((entry) => Object.keys(entry[1]).length > 0))) ?? {},
1868
+ modelOverrides: field("modelOverrides", () => Object.fromEntries(Object.entries(draft.modelOverrides).map(([id, override]) => {
1869
+ const contextWindow = numberOrNull(override.contextWindow, `modelOverrides.${id}.contextWindow`);
1870
+ const efforts = stopList(override.reasoningEfforts);
1871
+ return [id, {
1872
+ ...contextWindow === null || contextWindow <= 0 ? {} : { contextWindow },
1873
+ ...override.image === "" ? {} : { image: override.image === "yes" },
1874
+ ...override.thinking === "" ? {} : { thinking: override.thinking === "yes" },
1875
+ ...efforts.length === 0 ? {} : { reasoningEfforts: efforts },
1876
+ ...override.defaultEffort.trim() === "" ? {} : { defaultEffort: override.defaultEffort.trim() },
1877
+ ...override.enabled === "" ? {} : { enabled: override.enabled === "yes" }
1878
+ }];
1879
+ }).filter((entry) => Object.keys(entry[1]).length > 0))) ?? {},
1880
+ modelTransports: Object.fromEntries(Object.entries(draft.modelTransports).filter(([, value]) => value !== ""))
1881
+ },
1882
+ errors
1831
1883
  };
1832
1884
  }
1885
+ function patchOf(draft) {
1886
+ const { patch, errors } = draftPatch(draft);
1887
+ const first = Object.values(errors)[0];
1888
+ if (first !== void 0) throw new Error(first);
1889
+ return patch;
1890
+ }
1833
1891
  function same(a, b) {
1834
1892
  return JSON.stringify(patchOf(a)) === JSON.stringify(patchOf(b));
1835
1893
  }
@@ -2210,8 +2268,13 @@ window.__ModuleLoader__.load({
2210
2268
  });
2211
2269
  }
2212
2270
  // src/client/settings-page.tsx
2271
+ let manualRowSeq = 0;
2272
+ function nextManualUid() {
2273
+ manualRowSeq += 1;
2274
+ return `manual-${Date.now().toString(36)}-${manualRowSeq}`;
2275
+ }
2213
2276
  function ModelEntry(props) {
2214
- const { model, visible, transport, onVisible, onTransport, onDragStart, onDrop, onEdit, dragging, t } = props;
2277
+ const { model, visible, transport, onVisible, onTransport, onDragStart, onDrop, onDragEnd, onEdit, dragging, t } = props;
2215
2278
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2216
2279
  className: `ocl-model${dragging === true ? " ocl-dragging" : ""}`,
2217
2280
  draggable: onDragStart !== void 0,
@@ -2220,6 +2283,7 @@ window.__ModuleLoader__.load({
2220
2283
  if (onDrop !== void 0) event.preventDefault();
2221
2284
  },
2222
2285
  onDrop,
2286
+ onDragEnd,
2223
2287
  children: [
2224
2288
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2225
2289
  className: "ocl-drag-handle",
@@ -2312,6 +2376,7 @@ window.__ModuleLoader__.load({
2312
2376
  function OllamaCloudSettingsPage(props) {
2313
2377
  const { t } = props;
2314
2378
  const [state, setState] = (0, react.useState)(null);
2379
+ const configWritable = state?.configWritable !== false;
2315
2380
  const [draft, setDraft] = (0, react.useState)(null);
2316
2381
  const [original, setOriginal] = (0, react.useState)(null);
2317
2382
  const [error, setError] = (0, react.useState)(null);
@@ -2362,9 +2427,15 @@ window.__ModuleLoader__.load({
2362
2427
  }, []);
2363
2428
  const save = (0, react.useCallback)(async () => {
2364
2429
  if (draft === null) return;
2430
+ const { patch, errors } = draftPatch(draft);
2431
+ const failed = Object.entries(errors);
2432
+ if (failed.length > 0) {
2433
+ setError(failed.map(([name, message]) => `${name}: ${message}`).join("; "));
2434
+ return;
2435
+ }
2365
2436
  setSaving(true);
2366
2437
  try {
2367
- await saveConfig(patchOf(draft));
2438
+ await saveConfig(patch);
2368
2439
  window.dispatchEvent(new Event(CONFIG_CHANGED_EVENT));
2369
2440
  setNotice(t("saved"));
2370
2441
  setError(null);
@@ -2473,6 +2544,7 @@ window.__ModuleLoader__.load({
2473
2544
  };
2474
2545
  const addManualModel = () => {
2475
2546
  update({ manualModels: [...draft.manualModels, {
2547
+ uid: nextManualUid(),
2476
2548
  id: "",
2477
2549
  enabled: true,
2478
2550
  name: "",
@@ -2840,25 +2912,25 @@ window.__ModuleLoader__.load({
2840
2912
  type: "password",
2841
2913
  placeholder: t("pasteKey"),
2842
2914
  "aria-label": `${t("pasteKey")} (${account.label})`,
2843
- value: accountKeys[account.label] ?? "",
2915
+ value: accountKeys[index] ?? "",
2844
2916
  onChange: (event) => {
2845
2917
  setAccountKeys((current) => ({
2846
2918
  ...current,
2847
- [account.label]: event.target.value
2919
+ [index]: event.target.value
2848
2920
  }));
2849
2921
  }
2850
2922
  }),
2851
2923
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2852
2924
  type: "button",
2853
2925
  className: "ocl-button ocl-button-primary",
2854
- disabled: (accountKeys[account.label] ?? "").trim() === "",
2926
+ disabled: (accountKeys[index] ?? "").trim() === "",
2855
2927
  onClick: () => {
2856
2928
  const ref = account.apiKeyEnv.trim();
2857
2929
  if (ref === "") return;
2858
- saveKey(ref, (accountKeys[account.label] ?? "").trim()).then(() => {
2930
+ saveKey(ref, (accountKeys[index] ?? "").trim()).then(() => {
2859
2931
  setAccountKeys((current) => ({
2860
2932
  ...current,
2861
- [account.label]: ""
2933
+ [index]: ""
2862
2934
  }));
2863
2935
  setNotice(t("saved"));
2864
2936
  return load(true);
@@ -3164,6 +3236,7 @@ window.__ModuleLoader__.load({
3164
3236
  if (dragId !== null) moveModel(dragId, model.id);
3165
3237
  setDragId(null);
3166
3238
  },
3239
+ onDragEnd: () => setDragId(null),
3167
3240
  onEdit: () => setEditingModel(model.id),
3168
3241
  onVisible: (visible) => toggleModel(model.id, visible),
3169
3242
  onTransport: (transport) => {
@@ -3284,7 +3357,7 @@ window.__ModuleLoader__.load({
3284
3357
  children: t("removeManualModel")
3285
3358
  })
3286
3359
  ]
3287
- }, `${model.id}-${index}`))
3360
+ }, model.uid))
3288
3361
  ]
3289
3362
  }),
3290
3363
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
@@ -3613,12 +3686,16 @@ window.__ModuleLoader__.load({
3613
3686
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3614
3687
  type: "button",
3615
3688
  className: "ocl-button ocl-button-primary",
3616
- disabled: !dirty || saving,
3689
+ disabled: !dirty || saving || !configWritable,
3617
3690
  onClick: () => {
3618
3691
  save();
3619
3692
  },
3620
3693
  children: saving ? t("saving") : t("save")
3621
3694
  }),
3695
+ configWritable ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3696
+ className: "ocl-badge ocl-badge-warn",
3697
+ children: t("settingsReadOnly")
3698
+ }),
3622
3699
  dirty ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3623
3700
  className: "ocl-badge ocl-badge-warn",
3624
3701
  children: t("unsaved")
package/lib/config.js CHANGED
@@ -7,7 +7,7 @@ const DEFAULT_API_BASE = "https://ollama.com";
7
7
  const DEFAULT_OPENAI_BASE = "https://ollama.com/v1";
8
8
  const DEFAULT_USAGE_URL = "https://ollama.com/api/usage";
9
9
  const DEFAULT_BALANCE_URL = "https://ollama.com/api/balance";
10
- const DEFAULT_USER_AGENT = "dsh-ollama-cloud-provider/0.1.39";
10
+ const DEFAULT_USER_AGENT = "dsh-ollama-cloud-provider/0.1.40";
11
11
  const DEFAULT_CONTEXT_WINDOW = 131072;
12
12
  const DEFAULT_MAX_TOKENS = 32768;
13
13
  const DEFAULT_GENERATE_MAX_TOKENS = 131072;
@@ -120,7 +120,7 @@ function modelOverrideRecord(value) {
120
120
  if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
121
121
  const out = {};
122
122
  for (const [id, entry] of Object.entries(value)) {
123
- if (id === "" || id.includes("..") || typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
123
+ if (unsafeKey(id) || id === "" || id.includes("..") || typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
124
124
  const record = entry;
125
125
  const contextWindow = integerInRange(record.contextWindow, 1, 1e7);
126
126
  const efforts = Array.isArray(record.reasoningEfforts) ? record.reasoningEfforts.filter((item) => typeof item === "string" && item.trim() !== "") : void 0;
@@ -172,19 +172,29 @@ function manualModelList(value) {
172
172
  function recordOf(value) {
173
173
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
174
174
  }
175
+ function unsafeKey(key) {
176
+ return key === "__proto__" || key === "constructor" || key === "prototype";
177
+ }
175
178
  function numberRecord(value) {
176
179
  const out = {};
177
- for (const [key, entry] of Object.entries(recordOf(value))) if (typeof entry === "number" && Number.isInteger(entry) && entry > 0) out[key] = entry;
180
+ for (const [key, entry] of Object.entries(recordOf(value))) {
181
+ if (unsafeKey(key)) continue;
182
+ if (typeof entry === "number" && Number.isInteger(entry) && entry > 0) out[key] = entry;
183
+ }
178
184
  return out;
179
185
  }
180
186
  function booleanRecord(value) {
181
187
  const out = {};
182
- for (const [key, entry] of Object.entries(recordOf(value))) if (typeof entry === "boolean") out[key] = entry;
188
+ for (const [key, entry] of Object.entries(recordOf(value))) {
189
+ if (unsafeKey(key)) continue;
190
+ if (typeof entry === "boolean") out[key] = entry;
191
+ }
183
192
  return out;
184
193
  }
185
194
  function priceRecord(value) {
186
195
  const out = {};
187
196
  for (const [key, entry] of Object.entries(recordOf(value))) {
197
+ if (unsafeKey(key)) continue;
188
198
  const raw = recordOf(entry);
189
199
  const price = {};
190
200
  if (typeof raw.input === "number" && raw.input >= 0) price.input = raw.input;
@@ -197,7 +207,10 @@ function priceRecord(value) {
197
207
  const TRANSPORTS = /* @__PURE__ */ new Set(["native", "openai-chat"]);
198
208
  function transportRecord(value) {
199
209
  const out = {};
200
- for (const [key, entry] of Object.entries(recordOf(value))) if (typeof entry === "string" && TRANSPORTS.has(entry)) out[key] = entry;
210
+ for (const [key, entry] of Object.entries(recordOf(value))) {
211
+ if (unsafeKey(key)) continue;
212
+ if (typeof entry === "string" && TRANSPORTS.has(entry)) out[key] = entry;
213
+ }
201
214
  return out;
202
215
  }
203
216
  function ruleList(value) {
package/lib/discovery.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { sanitizeUrl } from "./sanitize.js";
2
2
  import { isIP } from "node:net";
3
3
  import { lookup } from "node:dns/promises";
4
+ import { request } from "node:https";
4
5
  // src/discovery.ts
5
6
  const DISCOVERY_TIMEOUT_MS = 15e3;
7
+ const MAX_DISCOVERY_BYTES = 1e6;
6
8
  var DiscoveryError = class extends Error {
7
9
  status;
8
10
  constructor(message, status) {
@@ -33,10 +35,14 @@ function isPrivateAddress(address) {
33
35
  const clean = address.toLowerCase().replace(/^\[|\]$/g, "");
34
36
  if (isIP(clean) === 4) return isPrivateV4(clean);
35
37
  if (isIP(clean) !== 6) return true;
36
- return clean === "::1" || clean === "::" || clean.startsWith("fc") || clean.startsWith("fd") || /^fe[89ab]/.test(clean) || clean.startsWith("ff") || clean.startsWith("2001:db8") || clean.startsWith("::ffff:");
38
+ if (clean.startsWith("::ffff:")) {
39
+ const embedded = clean.slice(7);
40
+ return isIP(embedded) === 4 ? isPrivateV4(embedded) : true;
41
+ }
42
+ return clean === "::1" || clean === "::" || clean.startsWith("::") || clean.startsWith("fc") || clean.startsWith("fd") || /^fe[89ab]/.test(clean) || clean.startsWith("ff") || clean.startsWith("2001:db8") || clean.startsWith("64:ff9b:") || clean.startsWith("2002:");
37
43
  }
38
44
  async function assertPublicEndpoint(base, options) {
39
- if (options.allowPrivate === true) return;
45
+ if (options.allowPrivate === true) return void 0;
40
46
  const url = new URL(base);
41
47
  if (url.protocol !== "https:") throw new DiscoveryError("endpoint must use https");
42
48
  const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
@@ -52,6 +58,7 @@ async function assertPublicEndpoint(base, options) {
52
58
  throw new DiscoveryError("could not resolve endpoint");
53
59
  }
54
60
  if (addresses.length === 0 || addresses.some(isPrivateAddress)) throw new DiscoveryError("private endpoint refused");
61
+ return addresses;
55
62
  }
56
63
  function idsOf(payload) {
57
64
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return [];
@@ -69,7 +76,8 @@ function idsOf(payload) {
69
76
  return typeof id === "string" && id !== "" ? id : void 0;
70
77
  }).filter((id) => id !== void 0) : [];
71
78
  }
72
- async function get(url, key, fetchImpl, signal) {
79
+ async function get(url, key, fetchImpl, signal, pinned) {
80
+ if (pinned !== void 0 && pinned.length > 0 && fetchImpl === fetch) return pinnedJson(url, key, signal, pinned[0]);
73
81
  const response = await fetchImpl(url, {
74
82
  method: "GET",
75
83
  headers: {
@@ -83,19 +91,79 @@ async function get(url, key, fetchImpl, signal) {
83
91
  return response.json();
84
92
  }
85
93
  /**
94
+ * Connect to the already validated address instead of resolving the name again,
95
+ * so a second DNS answer cannot redirect the request to a private host.
96
+ */
97
+ function pinnedJson(url, key, signal, address) {
98
+ return new Promise((resolve, reject) => {
99
+ const target = new URL(url);
100
+ const headers = {
101
+ accept: "application/json",
102
+ host: target.host
103
+ };
104
+ if (key !== "") headers.authorization = `Bearer ${key}`;
105
+ let settled = false;
106
+ const fail = (error) => {
107
+ if (settled) return;
108
+ settled = true;
109
+ reject(error);
110
+ };
111
+ const req = request({
112
+ protocol: "https:",
113
+ host: address,
114
+ port: target.port === "" ? 443 : Number(target.port),
115
+ path: `${target.pathname}${target.search}`,
116
+ method: "GET",
117
+ headers,
118
+ servername: target.hostname.replace(/^\[|\]$/g, ""),
119
+ signal
120
+ }, (res) => {
121
+ const chunks = [];
122
+ let size = 0;
123
+ res.on("data", (chunk) => {
124
+ if (settled) return;
125
+ size += chunk.length;
126
+ if (size > MAX_DISCOVERY_BYTES) {
127
+ res.destroy(new DiscoveryError("endpoint response too large"));
128
+ return;
129
+ }
130
+ chunks.push(chunk);
131
+ });
132
+ res.on("error", fail);
133
+ res.on("end", () => {
134
+ if (settled) return;
135
+ const status = res.statusCode ?? 0;
136
+ if (status < 200 || status >= 300) {
137
+ fail(new DiscoveryError(`endpoint answered ${status}`, status));
138
+ return;
139
+ }
140
+ try {
141
+ const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
142
+ settled = true;
143
+ resolve(payload);
144
+ } catch {
145
+ fail(new DiscoveryError("endpoint returned invalid JSON"));
146
+ }
147
+ });
148
+ });
149
+ req.on("error", fail);
150
+ req.end();
151
+ });
152
+ }
153
+ /**
86
154
  * Discover a catalog for an unsaved endpoint with a one-shot key.
87
155
  * This function performs no persistence and never includes the key in errors.
88
156
  */
89
157
  async function discoverModels(rawBase, key, fetchImpl = fetch, options = {}) {
90
158
  const base = normalizeBase(rawBase);
91
- await assertPublicEndpoint(base, options);
159
+ const pinned = await assertPublicEndpoint(base, options);
92
160
  const budget = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
93
161
  let payload;
94
162
  try {
95
- payload = await get(`${base}/v1/models`, key, fetchImpl, budget);
163
+ payload = await get(`${base}/v1/models`, key, fetchImpl, budget, pinned);
96
164
  } catch (error) {
97
165
  if (error instanceof DiscoveryError && error.status === 401) throw error;
98
- if (error instanceof DiscoveryError && error.status === 404) payload = await get(`${base}/api/tags`, key, fetchImpl, budget);
166
+ if (error instanceof DiscoveryError && error.status === 404) payload = await get(`${base}/api/tags`, key, fetchImpl, budget, pinned);
99
167
  else throw error;
100
168
  }
101
169
  return {
package/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { OllamaCloudAdapter } from "./adapter.js";
2
2
  import { bestEffortFailed, setBestEffortLogger } from "./best-effort.js";
3
3
  import { clearCatalogCache, describeModel, effectiveModel, refreshCatalog } from "./catalog.js";
4
+ import { createCatalogScheduler } from "./catalog-scheduler.js";
4
5
  import { applyCommands } from "./commands.js";
5
6
  import { Config, NS, resolveConfig, unwrapVolatileConfig } from "./config.js";
6
7
  import { createKeyPool, createKeyResolver } from "./credentials.js";
@@ -49,22 +50,25 @@ function apply(ctx, config) {
49
50
  flushRequestLog();
50
51
  }, "dsh-ollama-cloud-provider: flush request log");
51
52
  ctx.effect(() => {
52
- const initial = current();
53
- const warm = initial.autoRefresh ? setTimeout(() => {
53
+ const warm = current().autoRefresh ? setTimeout(() => {
54
54
  const config = current();
55
55
  if (config.autoRefresh) refreshCatalog(config, fetch).catch((err) => bestEffortFailed("warmCatalog", err));
56
56
  }, 1e3) : void 0;
57
57
  warm?.unref?.();
58
- const intervalMs = Math.max(1, initial.refreshMinutes) * 6e4;
59
- const timer = initial.autoRefresh && initial.refreshMinutes > 0 ? setInterval(() => {
60
- const config = current();
61
- if (!config.autoRefresh || config.refreshMinutes <= 0) return;
62
- refreshCatalog(config, fetch, true).catch((err) => bestEffortFailed("refreshCatalog", err));
63
- }, intervalMs) : void 0;
64
- timer?.unref?.();
58
+ const scheduler = createCatalogScheduler({
59
+ current: () => {
60
+ const config = current();
61
+ return {
62
+ autoRefresh: config.autoRefresh,
63
+ refreshMinutes: config.refreshMinutes
64
+ };
65
+ },
66
+ refresh: () => refreshCatalog(current(), fetch, true),
67
+ onError: (error) => bestEffortFailed("refreshCatalog", error)
68
+ });
65
69
  return () => {
66
70
  if (warm !== void 0) clearTimeout(warm);
67
- if (timer !== void 0) clearInterval(timer);
71
+ scheduler.dispose();
68
72
  };
69
73
  }, "dsh-ollama-cloud-provider: catalog refresh scheduler");
70
74
  ctx.inject(["settings"], (settingsCtx) => {