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

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/index.js CHANGED
@@ -4,7 +4,7 @@ import { clearCatalogCache, describeModel, effectiveModel, refreshCatalog } from
4
4
  import { createCatalogScheduler } from "./catalog-scheduler.js";
5
5
  import { applyCommands } from "./commands.js";
6
6
  import { Config, NS, resolveConfig, unwrapVolatileConfig } from "./config.js";
7
- import { createKeyPool, createKeyResolver } from "./credentials.js";
7
+ import { accountLabel, createKeyPool } from "./credentials.js";
8
8
  import { registerPluginUpdater } from "./plugin-updater.js";
9
9
  import { PROVIDER } from "./provider-ids.js";
10
10
  import { flushRequestLog, readRequestHeatmap } from "./request-log.js";
@@ -92,8 +92,8 @@ function apply(ctx, config) {
92
92
  id: "default",
93
93
  label: "default"
94
94
  }, ...current().accounts.map((account, index) => ({
95
- id: typeof account.label === "string" && account.label.trim() !== "" ? account.label.trim() : `account-${index + 2}`,
96
- label: typeof account.label === "string" && account.label.trim() !== "" ? account.label.trim() : `account-${index + 2}`
95
+ id: accountLabel(account.label, index),
96
+ label: accountLabel(account.label, index)
97
97
  }))],
98
98
  visibleModels: () => current().visibleModels,
99
99
  activeAccount: () => current().activeAccount,
@@ -132,6 +132,6 @@ function apply(ctx, config) {
132
132
  }), "dsh-ollama-cloud-provider: plugin updater");
133
133
  });
134
134
  }
135
- export { Config, OllamaCloudAdapter, PROVIDER, apply, applyCommands, applyRoutes, classifyResponseError, clearCatalogCache, createKeyPool, createKeyResolver, createUsageReader, describeModel, effectiveModel, inject, name, normalizeBalance, normalizeUsage, resolveConfig };
135
+ export { Config, OllamaCloudAdapter, PROVIDER, apply, applyCommands, applyRoutes, classifyResponseError, clearCatalogCache, createKeyPool, createUsageReader, describeModel, effectiveModel, inject, name, normalizeBalance, normalizeUsage, resolveConfig };
136
136
 
137
137
  //# sourceMappingURL=index.js.map
@@ -26,8 +26,7 @@ function quotaBars(report) {
26
26
  if (report === void 0) return [];
27
27
  if (report.kind === "credits" && report.credits !== void 0) {
28
28
  const credits = report.credits;
29
- return [bar("included", "Included credits", credits.includedAllowance > 0 ? (credits.includedAllowance - credits.includedRemaining) / credits.includedAllowance * 100 : 0, {
30
- detail: `$${credits.includedRemaining.toFixed(2)} of $${credits.includedAllowance.toFixed(2)} left` + (credits.purchased > 0 ? ` · $${credits.purchased.toFixed(2)} purchased` : ""),
29
+ return [bar("included", "", credits.includedAllowance > 0 ? (credits.includedAllowance - credits.includedRemaining) / credits.includedAllowance * 100 : 0, {
31
30
  detailValues: {
32
31
  remaining: credits.includedRemaining,
33
32
  allowance: credits.includedAllowance,
@@ -36,26 +35,26 @@ function quotaBars(report) {
36
35
  ...credits.periodUntil === void 0 ? {} : { resetsAt: credits.periodUntil }
37
36
  })];
38
37
  }
39
- return [legacyBar("fiveHour", "5-hour window", report.legacy?.fiveHour), legacyBar("weekly", "Weekly window", report.legacy?.weekly)].filter((entry) => entry !== void 0);
38
+ return [legacyBar("fiveHour", "", report.legacy?.fiveHour), legacyBar("weekly", "", report.legacy?.weekly)].filter((entry) => entry !== void 0);
40
39
  }
41
40
  function windowRows(report) {
42
41
  if (report === void 0) return [];
43
42
  return [
44
43
  report.windows.d24 === void 0 ? void 0 : {
45
44
  key: "24h",
46
- label: "24 hours",
45
+ label: "",
47
46
  labelKey: "last24h",
48
47
  totals: report.windows.d24
49
48
  },
50
49
  report.windows.d7 === void 0 ? void 0 : {
51
50
  key: "7d",
52
- label: "7 days",
51
+ label: "",
53
52
  labelKey: "last7d",
54
53
  totals: report.windows.d7
55
54
  },
56
55
  report.windows.d30 === void 0 ? void 0 : {
57
56
  key: "30d",
58
- label: "30 days",
57
+ label: "",
59
58
  labelKey: "last30d",
60
59
  totals: report.windows.d30
61
60
  }
@@ -1,8 +1,6 @@
1
+ import { booleanRecord, manualModelList, modelOverrideRecord, numberRecord, priceRecord, ruleList, transportRecord } from "./config.js";
2
+ import { accountLabel } from "./credentials.js";
1
3
  // src/routes-values.ts
2
- const TRANSPORTS = /* @__PURE__ */ new Set(["native", "openai-chat"]);
3
- function unsafeKey(key) {
4
- return key === "__proto__" || key === "constructor" || key === "prototype";
5
- }
6
4
  const CREDENTIAL_REF_PATTERN = /^OLLAMA_[A-Z0-9_]+$/;
7
5
  /** The plugin may read and write only its own credential namespace. */
8
6
  function normalizeCredentialRef(value) {
@@ -23,7 +21,7 @@ function cleanAccounts(value) {
23
21
  const apiKeyEnv = typeof record.apiKeyEnv === "string" ? record.apiKeyEnv.trim() : "";
24
22
  if (label === "" && apiKeyEnv === "") continue;
25
23
  out.push({
26
- label: label === "" ? `account-${out.length + 2}` : label,
24
+ label: accountLabel(label, out.length),
27
25
  apiKeyEnv
28
26
  });
29
27
  }
@@ -33,109 +31,25 @@ function cleanStringArray(value) {
33
31
  return Array.isArray(value) ? value.filter((entry) => typeof entry === "string" && entry !== "") : [];
34
32
  }
35
33
  function cleanModelAccountRules(value) {
36
- if (!Array.isArray(value)) return [];
37
- const out = [];
38
- for (const entry of value) {
39
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
40
- const record = entry;
41
- const pattern = typeof record.pattern === "string" ? record.pattern.trim() : "";
42
- const account = typeof record.account === "string" ? record.account.trim() : "";
43
- if (pattern === "" || account === "") continue;
44
- out.push({
45
- pattern,
46
- account
47
- });
48
- }
49
- return out;
34
+ return ruleList(value);
50
35
  }
51
36
  function cleanManualModels(value) {
52
- if (!Array.isArray(value)) return [];
53
- const out = [];
54
- for (const entry of value) {
55
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
56
- const record = entry;
57
- const id = typeof record.id === "string" ? record.id.trim() : "";
58
- if (id === "" || id.includes("..") || !/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/.test(id)) continue;
59
- const efforts = Array.isArray(record.reasoningEfforts) ? record.reasoningEfforts.filter((item) => typeof item === "string" && item.trim() !== "") : void 0;
60
- const thinking = typeof record.thinking === "boolean" ? record.thinking : void 0;
61
- const normalizedEfforts = thinking === true && (efforts === void 0 || efforts.length === 0) ? ["off", "high"] : thinking === false ? [] : efforts;
62
- out.push({
63
- id,
64
- enabled: record.enabled !== false,
65
- ...typeof record.name === "string" && record.name.trim() !== "" ? { name: record.name.trim() } : {},
66
- ...typeof record.contextWindow === "number" && Number.isInteger(record.contextWindow) && record.contextWindow > 0 ? { contextWindow: record.contextWindow } : {},
67
- ...typeof record.maxTokens === "number" && Number.isInteger(record.maxTokens) && record.maxTokens > 0 ? { maxTokens: record.maxTokens } : {},
68
- ...typeof record.image === "boolean" ? { image: record.image } : {},
69
- ...thinking === void 0 ? {} : { thinking },
70
- ...normalizedEfforts === void 0 ? {} : { reasoningEfforts: normalizedEfforts },
71
- ...typeof record.defaultReasoning === "string" && record.defaultReasoning.trim() !== "" ? { defaultReasoning: record.defaultReasoning.trim() } : {},
72
- ...typeof record.tools === "boolean" ? { tools: record.tools } : {}
73
- });
74
- }
75
- return out;
37
+ return manualModelList(value);
76
38
  }
77
39
  function cleanModelOverrides(value) {
78
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
79
- const out = {};
80
- for (const [id, entry] of Object.entries(value)) {
81
- if (unsafeKey(id) || id === "" || id.includes("..") || typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
82
- const record = entry;
83
- const efforts = Array.isArray(record.reasoningEfforts) ? record.reasoningEfforts.filter((item) => typeof item === "string" && item.trim() !== "") : void 0;
84
- const thinking = typeof record.thinking === "boolean" ? record.thinking : void 0;
85
- const normalizedEfforts = thinking === true && (efforts === void 0 || efforts.length === 0) ? ["off", "high"] : thinking === false ? [] : efforts;
86
- const outEntry = {
87
- ...typeof record.contextWindow === "number" && Number.isInteger(record.contextWindow) && record.contextWindow > 0 ? { contextWindow: record.contextWindow } : {},
88
- ...typeof record.image === "boolean" ? { image: record.image } : {},
89
- ...thinking === void 0 ? {} : { thinking },
90
- ...normalizedEfforts === void 0 ? {} : { reasoningEfforts: normalizedEfforts },
91
- ...typeof record.defaultEffort === "string" && record.defaultEffort.trim() !== "" ? { defaultEffort: record.defaultEffort.trim() } : {},
92
- ...typeof record.enabled === "boolean" ? { enabled: record.enabled } : {}
93
- };
94
- if (Object.keys(outEntry).length > 0) out[id] = outEntry;
95
- }
96
- return out;
40
+ return modelOverrideRecord(value);
97
41
  }
98
42
  function cleanBooleanRecord(value) {
99
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
100
- const out = {};
101
- for (const [key, entry] of Object.entries(value)) {
102
- if (unsafeKey(key)) continue;
103
- if (typeof entry === "boolean") out[key] = entry;
104
- }
105
- return out;
43
+ return booleanRecord(value);
106
44
  }
107
45
  function cleanNumberRecord(value) {
108
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
109
- const out = {};
110
- for (const [key, entry] of Object.entries(value)) {
111
- if (unsafeKey(key)) continue;
112
- if (typeof entry === "number" && Number.isInteger(entry) && entry > 0) out[key] = entry;
113
- }
114
- return out;
46
+ return numberRecord(value);
115
47
  }
116
48
  function cleanTransports(value) {
117
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
118
- const out = {};
119
- for (const [key, entry] of Object.entries(value)) {
120
- if (unsafeKey(key)) continue;
121
- if (typeof entry === "string" && TRANSPORTS.has(entry)) out[key] = entry;
122
- }
123
- return out;
49
+ return transportRecord(value);
124
50
  }
125
51
  function cleanPrices(value) {
126
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
127
- const out = {};
128
- for (const [key, entry] of Object.entries(value)) {
129
- if (unsafeKey(key)) continue;
130
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
131
- const raw = entry;
132
- const price = {};
133
- if (typeof raw.input === "number" && raw.input >= 0) price.input = raw.input;
134
- if (typeof raw.output === "number" && raw.output >= 0) price.output = raw.output;
135
- if (typeof raw.cacheRead === "number" && raw.cacheRead >= 0) price.cacheRead = raw.cacheRead;
136
- if (Object.keys(price).length > 0) out[key] = price;
137
- }
138
- return out;
52
+ return priceRecord(value);
139
53
  }
140
54
  export { cleanAccounts, cleanBooleanRecord, cleanManualModels, cleanModelAccountRules, cleanModelOverrides, cleanNumberRecord, cleanPrices, cleanStringArray, cleanTransports, isCredentialRef, normalizeCredentialRef };
141
55
 
package/lib/routes.js CHANGED
@@ -2,6 +2,7 @@ import { bestEffortFailed } from "./best-effort.js";
2
2
  import { readModelAnalytics } from "./analytics.js";
3
3
  import { clearCatalogCache, effectiveModel, modelAvailable, modelVisible, refreshCatalog } from "./catalog.js";
4
4
  import { NS } from "./config.js";
5
+ import { accountLabel } from "./credentials.js";
5
6
  import { discoverModels } from "./discovery.js";
6
7
  import { checkEndpoint } from "./endpoints.js";
7
8
  import { priceFor } from "./pricing.js";
@@ -312,7 +313,7 @@ async function buildState(ctx, deps) {
312
313
  ref: config.apiKeyEnv,
313
314
  default: true
314
315
  }, ...config.accounts.map((account, index) => ({
315
- label: typeof account.label === "string" && account.label.trim() !== "" ? account.label.trim() : `account-${index + 2}`,
316
+ label: accountLabel(account.label, index),
316
317
  ref: typeof account.apiKeyEnv === "string" ? account.apiKeyEnv.trim() : "",
317
318
  default: false
318
319
  }))];
@@ -1,31 +1,8 @@
1
1
  import { bestEffortFailed } from "../best-effort.js";
2
+ import { readWithIdleTimeout } from "./stream-reader.js";
2
3
  import { LlmError } from "@deepseek-ai/dsh-llm";
3
4
  // src/transports/ndjson.ts
4
5
  const MAX_FRAME_BYTES = 1e6;
5
- async function readWithIdleTimeout(reader, idleTimeoutMs, signal) {
6
- if (signal?.aborted === true) throw signal.reason;
7
- return await new Promise((resolve, reject) => {
8
- let settled = false;
9
- const finish = (action) => {
10
- if (settled) return;
11
- settled = true;
12
- clearTimeout(timer);
13
- signal?.removeEventListener("abort", onAbort);
14
- action();
15
- };
16
- const timer = setTimeout(() => {
17
- finish(() => reject(new LlmError(`Ollama Cloud stream went idle for ${idleTimeoutMs}ms`, "TIMEOUT")));
18
- reader.cancel().catch((err) => bestEffortFailed("ndjson:cancel", err));
19
- }, idleTimeoutMs);
20
- timer.unref?.();
21
- const onAbort = () => {
22
- finish(() => reject(signal?.reason ?? new DOMException("aborted", "AbortError")));
23
- reader.cancel().catch((err) => bestEffortFailed("ndjson:cancel", err));
24
- };
25
- signal?.addEventListener("abort", onAbort, { once: true });
26
- reader.read().then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
27
- });
28
- }
29
6
  /**
30
7
  * Yield parsed NDJSON objects from a `/api/chat` stream. Ollama uses one JSON
31
8
  * object per line, with no `data:` prefix, and a final `{done:true}` line.
@@ -36,7 +13,7 @@ async function* ndjsonObjects(body, idleTimeoutMs, signal) {
36
13
  let buffer = "";
37
14
  try {
38
15
  for (;;) {
39
- const result = await readWithIdleTimeout(reader, idleTimeoutMs, signal);
16
+ const result = await readWithIdleTimeout(reader, idleTimeoutMs, signal, "ndjson");
40
17
  if (result.done) break;
41
18
  buffer += decoder.decode(result.value, { stream: true }).replace(/\r\n/g, "\n");
42
19
  if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) throw new LlmError("Ollama Cloud sent an oversized stream frame", "PROVIDER_HTTP_ERROR");
@@ -1,31 +1,8 @@
1
1
  import { bestEffortFailed } from "../best-effort.js";
2
+ import { readWithIdleTimeout } from "./stream-reader.js";
2
3
  import { LlmError } from "@deepseek-ai/dsh-llm";
3
4
  // src/transports/sse.ts
4
5
  const MAX_FRAME_BYTES = 1e6;
5
- async function readWithIdleTimeout(reader, idleTimeoutMs, signal) {
6
- if (signal?.aborted === true) throw signal.reason;
7
- return await new Promise((resolve, reject) => {
8
- let settled = false;
9
- const finish = (action) => {
10
- if (settled) return;
11
- settled = true;
12
- clearTimeout(timer);
13
- signal?.removeEventListener("abort", onAbort);
14
- action();
15
- };
16
- const timer = setTimeout(() => {
17
- finish(() => reject(new LlmError(`Ollama Cloud stream went idle for ${idleTimeoutMs}ms`, "TIMEOUT")));
18
- reader.cancel().catch((err) => bestEffortFailed("sse:cancel", err));
19
- }, idleTimeoutMs);
20
- timer.unref?.();
21
- const onAbort = () => {
22
- finish(() => reject(signal?.reason ?? new DOMException("aborted", "AbortError")));
23
- reader.cancel().catch((err) => bestEffortFailed("sse:cancel", err));
24
- };
25
- signal?.addEventListener("abort", onAbort, { once: true });
26
- reader.read().then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
27
- });
28
- }
29
6
  /** Yield the `data:` payload of every SSE event, honoring cancellation and idle timeouts. */
30
7
  async function* sseData(body, idleTimeoutMs, signal) {
31
8
  const reader = body.getReader();
@@ -33,7 +10,7 @@ async function* sseData(body, idleTimeoutMs, signal) {
33
10
  let buffer = "";
34
11
  try {
35
12
  for (;;) {
36
- const result = await readWithIdleTimeout(reader, idleTimeoutMs, signal);
13
+ const result = await readWithIdleTimeout(reader, idleTimeoutMs, signal, "sse");
37
14
  if (result.done) break;
38
15
  buffer = (buffer + decoder.decode(result.value, { stream: true })).replace(/\r\n/g, "\n");
39
16
  if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) throw new LlmError("Ollama Cloud sent an oversized stream event", "PROVIDER_HTTP_ERROR");
@@ -0,0 +1,31 @@
1
+ import { bestEffortFailed } from "../best-effort.js";
2
+ import { LlmError } from "@deepseek-ai/dsh-llm";
3
+ // src/transports/stream-reader.ts
4
+ /** Read one stream chunk, rejecting with TIMEOUT or AbortError instead of hanging. */
5
+ async function readWithIdleTimeout(reader, idleTimeoutMs, signal, label) {
6
+ if (signal?.aborted === true) throw signal.reason;
7
+ return await new Promise((resolve, reject) => {
8
+ let settled = false;
9
+ const finish = (action) => {
10
+ if (settled) return;
11
+ settled = true;
12
+ clearTimeout(timer);
13
+ signal?.removeEventListener("abort", onAbort);
14
+ action();
15
+ };
16
+ const timer = setTimeout(() => {
17
+ finish(() => reject(new LlmError(`Ollama Cloud stream went idle for ${idleTimeoutMs}ms`, "TIMEOUT")));
18
+ reader.cancel().catch((err) => bestEffortFailed(`${label}:cancel`, err));
19
+ }, idleTimeoutMs);
20
+ timer.unref?.();
21
+ const onAbort = () => {
22
+ finish(() => reject(signal?.reason ?? new DOMException("aborted", "AbortError")));
23
+ reader.cancel().catch((err) => bestEffortFailed(`${label}:cancel`, err));
24
+ };
25
+ signal?.addEventListener("abort", onAbort, { once: true });
26
+ reader.read().then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
27
+ });
28
+ }
29
+ export { readWithIdleTimeout };
30
+
31
+ //# sourceMappingURL=stream-reader.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-ollama-cloud-provider",
3
- "version": "0.1.40",
3
+ "version": "0.1.41",
4
4
  "description": "Ollama Cloud LLM provider plugin for DeepSeek Harness (dsh).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -73,8 +73,8 @@
73
73
  "build": "tsdown",
74
74
  "prepare": "tsdown 1>&2",
75
75
  "typecheck": "tsc --noEmit",
76
- "test": "node --import tsx --test --test-concurrency=1 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 tests/update-card-view.test.tsx tests/web.test.ts tests/mock-ollama.test.ts tests/reasoning.test.ts tests/catalog-cache.test.ts tests/attempt.test.ts tests/model-groups.test.tsx tests/discovery.test.ts tests/sanitize.test.ts tests/retry.test.ts tests/provider-card.test.tsx tests/host-verification.test.ts tests/ui-actions.test.tsx tests/tool-call-id.test.ts tests/deploy-script.test.ts tests/endpoints.test.ts tests/route-guard.test.ts tests/catalog-scheduler.test.ts",
77
- "check": "npm run typecheck && npm test && npm run build && npm run pack:check",
76
+ "test": "node --import tsx --test --test-concurrency=1 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 tests/update-card-view.test.tsx tests/web.test.ts tests/mock-ollama.test.ts tests/reasoning.test.ts tests/catalog-cache.test.ts tests/attempt.test.ts tests/model-groups.test.tsx tests/discovery.test.ts tests/sanitize.test.ts tests/retry.test.ts tests/provider-card.test.tsx tests/host-verification.test.ts tests/ui-actions.test.tsx tests/tool-call-id.test.ts tests/deploy-script.test.ts tests/endpoints.test.ts tests/route-guard.test.ts tests/catalog-scheduler.test.ts tests/format.test.ts",
77
+ "check": "npm run typecheck && npm test && npm run build && node scripts/smoke-load.mjs && npm run pack:check",
78
78
  "release": "npm run check && mkdir -p dist && npm pack --pack-destination dist",
79
79
  "sync:models": "node scripts/sync-models.mjs",
80
80
  "pack:check": "node scripts/pack-check.mjs"