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

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +13 -6
  3. package/README.ru.md +13 -6
  4. package/README.zh.md +13 -6
  5. package/lib/account-rules.js +26 -0
  6. package/lib/adapter.d.ts +92 -0
  7. package/lib/adapter.js +566 -0
  8. package/lib/analytics.d.ts +81 -0
  9. package/lib/analytics.js +314 -0
  10. package/lib/attempt.js +29 -0
  11. package/lib/best-effort.js +20 -0
  12. package/lib/catalog-cache.js +81 -0
  13. package/lib/catalog.d.ts +10 -0
  14. package/lib/catalog.js +309 -0
  15. package/lib/commands.d.ts +14 -0
  16. package/lib/commands.js +228 -0
  17. package/lib/config.d.ts +173 -0
  18. package/lib/config.js +280 -0
  19. package/lib/context-override.js +38 -0
  20. package/lib/credentials.d.ts +23 -0
  21. package/lib/credentials.js +105 -0
  22. package/lib/discovery.js +108 -0
  23. package/lib/endpoints.js +58 -0
  24. package/lib/errors.d.ts +9 -0
  25. package/lib/errors.js +72 -0
  26. package/lib/files.js +13 -0
  27. package/lib/images.js +78 -0
  28. package/lib/index.d.ts +10 -521
  29. package/lib/index.js +20 -5921
  30. package/lib/local-host.js +47 -0
  31. package/lib/messages.js +263 -0
  32. package/lib/models.generated.d.ts +26 -0
  33. package/lib/models.generated.js +499 -0
  34. package/lib/plugin-updater.js +320 -0
  35. package/lib/pricing.js +78 -0
  36. package/lib/provider-ids.d.ts +4 -0
  37. package/lib/provider-ids.js +9 -0
  38. package/lib/quota-model.js +66 -0
  39. package/lib/reasoning.js +71 -0
  40. package/lib/request-log.d.ts +38 -0
  41. package/lib/request-log.js +203 -0
  42. package/lib/retry.js +24 -0
  43. package/lib/route-guard.js +25 -0
  44. package/lib/routes-public.js +59 -0
  45. package/lib/routes-values.js +129 -0
  46. package/lib/routes.d.ts +28 -0
  47. package/lib/routes.js +733 -0
  48. package/lib/routing.js +20 -0
  49. package/lib/sanitize.js +43 -0
  50. package/lib/status.js +60 -0
  51. package/lib/tool-schema.js +109 -0
  52. package/lib/tools.js +38 -0
  53. package/lib/transports/native.js +156 -0
  54. package/lib/transports/ndjson.js +73 -0
  55. package/lib/transports/openai-chat.js +278 -0
  56. package/lib/transports/sse.js +57 -0
  57. package/lib/transports/tool-call-id.js +17 -0
  58. package/lib/tui-settings.js +246 -0
  59. package/lib/usage.d.ts +69 -0
  60. package/lib/usage.js +277 -0
  61. package/lib/web.js +143 -0
  62. package/package.json +6 -5
package/lib/catalog.js ADDED
@@ -0,0 +1,309 @@
1
+ import { bestEffortFailed } from "./best-effort.js";
2
+ import { DEFAULT_CONTEXT_WINDOW, DEFAULT_GENERATE_MAX_TOKENS, DEFAULT_MAX_TOKENS } from "./config.js";
3
+ import { clearCatalogSnapshot, loadCatalogSnapshot, saveCatalogSnapshot } from "./catalog-cache.js";
4
+ import { createAttemptBudget } from "./attempt.js";
5
+ import { GENERATED_MODELS } from "./models.generated.js";
6
+ import { formatPrice, priceFor } from "./pricing.js";
7
+ import { normalizeThinking } from "./reasoning.js";
8
+ import { modelsUrlFor, tagsUrlFor } from "./routing.js";
9
+ // src/catalog.ts
10
+ const CATALOG_TTL_MS = 6e5;
11
+ const CATALOG_TIMEOUT_MS = 15e3;
12
+ const liveMeta = /* @__PURE__ */ new Map();
13
+ const cache = /* @__PURE__ */ new Map();
14
+ const inflight = /* @__PURE__ */ new Map();
15
+ const diskLoaded = /* @__PURE__ */ new Set();
16
+ let generation = 0;
17
+ function liveKey(base, id) {
18
+ return `${base}|${id}`;
19
+ }
20
+ const FALLBACK_META = {
21
+ id: "",
22
+ name: "",
23
+ transport: "native",
24
+ contextWindow: DEFAULT_CONTEXT_WINDOW,
25
+ maxTokens: DEFAULT_MAX_TOKENS,
26
+ input: ["text"],
27
+ reasoning: [],
28
+ reasoningToggle: false,
29
+ tools: true,
30
+ free: false,
31
+ available: true,
32
+ cost: {
33
+ input: 0,
34
+ output: 0,
35
+ cacheRead: 0
36
+ }
37
+ };
38
+ function str(value) {
39
+ return typeof value === "string" && value !== "" ? value : void 0;
40
+ }
41
+ function num(value) {
42
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : void 0;
43
+ }
44
+ function strings(value) {
45
+ if (!Array.isArray(value)) return [];
46
+ return value.filter((entry) => typeof entry === "string" && entry !== "");
47
+ }
48
+ function effortNames(value) {
49
+ if (!Array.isArray(value)) return [];
50
+ const out = [];
51
+ for (const entry of value) if (typeof entry === "object" && entry !== null && !Array.isArray(entry)) {
52
+ const effort = str(entry.effort);
53
+ if (effort !== void 0) out.push(effort);
54
+ } else if (typeof entry === "string" && entry !== "") out.push(entry);
55
+ return out;
56
+ }
57
+ function capabilitiesByModel(tags) {
58
+ const out = /* @__PURE__ */ new Map();
59
+ for (const entry of tags?.models ?? []) {
60
+ const name = str(entry.name) ?? str(entry.model);
61
+ if (name === void 0) continue;
62
+ out.set(name, new Set(strings(entry.capabilities)));
63
+ }
64
+ return out;
65
+ }
66
+ function metaFromLive(entry, caps) {
67
+ const id = str(entry.slug) ?? "";
68
+ const base = GENERATED_MODELS[id];
69
+ const levels = effortNames(entry.supported_reasoning_levels);
70
+ const toggle = (caps?.has("thinking") === true || levels.length > 0) && levels.length === 0;
71
+ const modalities = strings(entry.input_modalities);
72
+ const image = modalities.includes("image") || base?.input.includes("image") === true && modalities.length === 0;
73
+ const normalized = normalizeThinking(id, levels.length > 0 ? levels : base?.reasoning ?? [], toggle || base?.reasoningToggle === true, str(entry.default_reasoning_level) ?? base?.defaultReasoning);
74
+ return {
75
+ id,
76
+ name: str(entry.display_name) ?? id,
77
+ transport: base?.transport ?? "native",
78
+ contextWindow: num(entry.context_window) ?? num(entry.max_context_window) ?? base?.contextWindow ?? 131072,
79
+ maxTokens: base?.maxTokens ?? 32768,
80
+ input: image ? ["text", "image"] : ["text"],
81
+ reasoning: normalized.reasoning,
82
+ reasoningToggle: toggle || base?.reasoningToggle === true,
83
+ tools: caps?.has("tools") === true || base?.tools === true || base === void 0,
84
+ free: base?.free === true,
85
+ available: entry.supported_in_api !== false && entry.visibility !== "hide",
86
+ ...normalized.defaultReasoning === void 0 ? {} : { defaultReasoning: normalized.defaultReasoning },
87
+ cost: base?.cost ?? {
88
+ input: 0,
89
+ output: 0,
90
+ cacheRead: 0
91
+ }
92
+ };
93
+ }
94
+ function metaForBase(base) {
95
+ const out = {};
96
+ const prefix = `${base}|`;
97
+ for (const [key, meta] of liveMeta) if (key.startsWith(prefix)) out[key.slice(prefix.length)] = meta;
98
+ return out;
99
+ }
100
+ async function persist(base, ids) {
101
+ await saveCatalogSnapshot(base, ids, metaForBase(base));
102
+ }
103
+ /** Replace the in-memory live metadata for one API base with one successful response. */
104
+ function adoptLive(models, tags, base) {
105
+ const caps = capabilitiesByModel(tags);
106
+ const ids = [];
107
+ for (const entry of models) {
108
+ const meta = metaFromLive(entry, caps.get(str(entry.slug) ?? ""));
109
+ if (meta.id === "") continue;
110
+ liveMeta.set(liveKey(base, meta.id), meta);
111
+ ids.push(meta.id);
112
+ }
113
+ const keep = new Set(ids);
114
+ const prefix = `${base}|`;
115
+ for (const key of liveMeta.keys()) {
116
+ if (!key.startsWith(prefix)) continue;
117
+ const id = key.slice(prefix.length);
118
+ if (!keep.has(id)) liveMeta.delete(key);
119
+ }
120
+ return ids;
121
+ }
122
+ async function fetchJson(url, config, fetchImpl, signal) {
123
+ const response = await fetchImpl(url, {
124
+ headers: {
125
+ accept: "application/json",
126
+ "user-agent": config.userAgent
127
+ },
128
+ signal
129
+ });
130
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
131
+ return response.json();
132
+ }
133
+ /**
134
+ * Refresh the live catalog (public, no key required) and return its ids.
135
+ * Network failures keep the previous live metadata and fall back to the
136
+ * generated snapshot, so the picker always has something to show.
137
+ *
138
+ * A cached catalog is served immediately, even after its TTL: the network
139
+ * refresh runs in the background so the picker never blocks on a stale entry.
140
+ * Only the first load (no cache) waits for the network.
141
+ */
142
+ async function refreshCatalog(config, fetchImpl = fetch, force = false) {
143
+ const key = config.apiBase;
144
+ if (!diskLoaded.has(key)) {
145
+ diskLoaded.add(key);
146
+ const snapshot = await loadCatalogSnapshot(key);
147
+ if (snapshot !== void 0 && !cache.has(key)) {
148
+ cache.set(key, {
149
+ at: snapshot.at,
150
+ ids: snapshot.ids
151
+ });
152
+ for (const [id, meta] of Object.entries(snapshot.meta)) liveMeta.set(liveKey(key, id), meta);
153
+ }
154
+ }
155
+ const cached = cache.get(key);
156
+ if (!force && cached !== void 0) {
157
+ if (config.autoRefresh && Date.now() - cached.at >= CATALOG_TTL_MS) refreshInBackground(config, fetchImpl, key);
158
+ return cached.ids;
159
+ }
160
+ return refreshNow(config, fetchImpl, key, cached !== void 0, generation);
161
+ }
162
+ async function refreshNow(config, fetchImpl, key, keepOnFailure, epoch) {
163
+ const budget = createAttemptBudget(CATALOG_TIMEOUT_MS);
164
+ let modelsResult;
165
+ let tagsResult;
166
+ try {
167
+ [modelsResult, tagsResult] = await Promise.allSettled([fetchJson(modelsUrlFor(config), config, fetchImpl, budget.signal), fetchJson(tagsUrlFor(config), config, fetchImpl, budget.signal)]);
168
+ } finally {
169
+ budget.dispose();
170
+ }
171
+ if (epoch !== generation) return Object.keys(GENERATED_MODELS);
172
+ if (modelsResult.status === "fulfilled") {
173
+ const payload = modelsResult.value;
174
+ const tags = tagsResult.status === "fulfilled" ? tagsResult.value : void 0;
175
+ const live = Array.isArray(payload.models) ? payload.models : [];
176
+ if (live.length > 0) {
177
+ const ids = adoptLive(live, tags, key);
178
+ if (ids.length > 0) {
179
+ cache.set(key, {
180
+ at: Date.now(),
181
+ ids
182
+ });
183
+ await persist(key, ids);
184
+ return ids;
185
+ }
186
+ }
187
+ const fromData = Array.isArray(payload.data) ? payload.data.map((entry) => str(entry.id)).filter((id) => id !== void 0) : [];
188
+ const fromTags = ((tagsResult.status === "fulfilled" ? tagsResult.value : void 0)?.models ?? []).map((entry) => str(entry.name) ?? str(entry.model)).filter((id) => id !== void 0);
189
+ const discovered = fromData.length > 0 ? fromData : fromTags;
190
+ if (discovered.length > 0) {
191
+ for (const liveKey of liveMeta.keys()) if (liveKey.startsWith(`${key}|`)) liveMeta.delete(liveKey);
192
+ const ids = discovered;
193
+ cache.set(key, {
194
+ at: Date.now(),
195
+ ids
196
+ });
197
+ await persist(key, ids);
198
+ return ids;
199
+ }
200
+ }
201
+ if (keepOnFailure) {
202
+ const stale = cache.get(key);
203
+ if (stale !== void 0) return stale.ids;
204
+ }
205
+ const fallback = Object.keys(GENERATED_MODELS);
206
+ if (epoch === generation) cache.set(key, {
207
+ at: Date.now(),
208
+ ids: fallback
209
+ });
210
+ return fallback;
211
+ }
212
+ function refreshInBackground(config, fetchImpl, key) {
213
+ if (inflight.has(key)) return;
214
+ const task = refreshNow(config, fetchImpl, key, true, generation).catch((err) => {
215
+ bestEffortFailed("catalog:fetchModels", err);
216
+ return cache.get(key)?.ids ?? Object.keys(GENERATED_MODELS);
217
+ }).finally(() => {
218
+ inflight.delete(key);
219
+ });
220
+ inflight.set(key, task);
221
+ }
222
+ function clearCatalogCache() {
223
+ generation += 1;
224
+ cache.clear();
225
+ inflight.clear();
226
+ liveMeta.clear();
227
+ diskLoaded.clear();
228
+ clearCatalogSnapshot();
229
+ }
230
+ function baseMeta(id, base) {
231
+ const meta = liveMeta.get(liveKey(base, id)) ?? GENERATED_MODELS[id];
232
+ return meta === void 0 ? {
233
+ ...FALLBACK_META,
234
+ id,
235
+ name: id
236
+ } : meta;
237
+ }
238
+ function manualModelFor(id, config) {
239
+ return config.manualModels.find((entry) => entry.id === id);
240
+ }
241
+ function effectiveModel(id, config) {
242
+ const meta = baseMeta(id, config.apiBase);
243
+ const manual = manualModelFor(id, config);
244
+ const override = config.modelOverrides[id];
245
+ return {
246
+ ...meta,
247
+ name: manual?.name ?? meta.name,
248
+ transport: config.modelTransports[id] ?? config.transport,
249
+ contextWindow: config.contextWindowOverrides[id] ?? override?.contextWindow ?? manual?.contextWindow ?? config.contextWindow ?? meta.contextWindow,
250
+ maxTokens: manual?.maxTokens ?? meta.maxTokens,
251
+ input: (override?.image ?? manual?.image) === true ? ["text", "image"] : (override?.image ?? manual?.image) === false ? ["text"] : meta.input,
252
+ reasoning: override?.reasoningEfforts ?? manual?.reasoningEfforts ?? meta.reasoning,
253
+ reasoningToggle: override?.thinking ?? manual?.thinking ?? meta.reasoningToggle,
254
+ ...(override?.defaultEffort ?? manual?.defaultReasoning ?? meta.defaultReasoning) === void 0 ? {} : { defaultReasoning: override?.defaultEffort ?? manual?.defaultReasoning ?? meta.defaultReasoning },
255
+ tools: manual?.tools ?? meta.tools,
256
+ available: override?.enabled === false || manual?.enabled === false ? false : meta.available
257
+ };
258
+ }
259
+ /** Effective per-request output default; `0` means "omit the field". */
260
+ function effectiveMaxTokens(meta, config) {
261
+ const ceiling = Math.min(meta.maxTokens, DEFAULT_GENERATE_MAX_TOKENS);
262
+ if (config.maxOutputTokens === void 0) return ceiling;
263
+ if (config.maxOutputTokens === 0) return void 0;
264
+ return Math.min(ceiling, config.maxOutputTokens);
265
+ }
266
+ function modelVisible(id, config) {
267
+ const override = config.modelVisibility[id];
268
+ if (override !== void 0) return override;
269
+ if (config.showAllModels) return true;
270
+ return config.visibleModels.includes(id);
271
+ }
272
+ function modelAvailable(id, config) {
273
+ const manual = manualModelFor(id, config);
274
+ if (config.modelOverrides[id]?.enabled === false || manual?.enabled === false) return false;
275
+ if (!config.filterModelsByPlan) return true;
276
+ return effectiveModel(id, config).available !== false;
277
+ }
278
+ function sortForPicker(ids, config, unfiltered = false) {
279
+ const order = new Map([...config.modelOrder.map((id, index) => [id, index]), ...config.visibleModels.map((id, index) => [id, config.modelOrder.length + index])]);
280
+ return ids.filter((id) => unfiltered || modelVisible(id, config) && modelAvailable(id, config)).sort((left, right) => {
281
+ const leftOrder = order.get(left);
282
+ const rightOrder = order.get(right);
283
+ if (leftOrder !== void 0 || rightOrder !== void 0) {
284
+ if (leftOrder === void 0) return 1;
285
+ if (rightOrder === void 0) return -1;
286
+ if (leftOrder !== rightOrder) return leftOrder - rightOrder;
287
+ }
288
+ const a = effectiveModel(left, config);
289
+ const b = effectiveModel(right, config);
290
+ if (a.free !== b.free) return a.free ? -1 : 1;
291
+ return a.name.localeCompare(b.name);
292
+ });
293
+ }
294
+ function formatContext(value) {
295
+ if (value >= 1e6) return `${(value / 1e6).toFixed(value % 1e6 === 0 ? 0 : 1)}M`;
296
+ return `${Math.round(value / 1024)}K`;
297
+ }
298
+ function describeModel(meta, config) {
299
+ const parts = [meta.transport, `${formatContext(meta.contextWindow)} context`];
300
+ if (meta.free) parts.push("FREE");
301
+ else parts.push(formatPrice(priceFor(meta.id, config.priceOverrides)));
302
+ if (meta.input.includes("image")) parts.push("Image");
303
+ if (meta.tools) parts.push("Tools");
304
+ if (meta.reasoning.length > 0) parts.push(`reasoning: ${meta.reasoning.join("/")}`);
305
+ return parts.join(" · ");
306
+ }
307
+ export { baseMeta, clearCatalogCache, describeModel, effectiveMaxTokens, effectiveModel, formatContext, manualModelFor, modelAvailable, modelVisible, refreshCatalog, sortForPicker };
308
+
309
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1,14 @@
1
+ import { OllamaCloudAdapter } from "./adapter.js";
2
+ import { ResolvedConfig } from "./config.js";
3
+ import { KeyPool } from "./credentials.js";
4
+ import { UsageReader } from "./usage.js";
5
+ import { Context } from "@deepseek-ai/cordis";
6
+ interface CommandDeps {
7
+ readonly config: () => ResolvedConfig;
8
+ readonly pool: KeyPool;
9
+ readonly usage: UsageReader;
10
+ readonly adapter: OllamaCloudAdapter;
11
+ }
12
+ declare function applyCommands(ctx: Context, deps: CommandDeps): void;
13
+ export { CommandDeps, applyCommands };
14
+ //# sourceMappingURL=commands.d.ts.map
@@ -0,0 +1,228 @@
1
+ import { bestEffortFailed } from "./best-effort.js";
2
+ import { effectiveModel } from "./catalog.js";
3
+ import { formatUsd, priceFor } from "./pricing.js";
4
+ import { PROVIDER } from "./provider-ids.js";
5
+ import { quotaBars, windowRows } from "./quota-model.js";
6
+ import { safeErrorMessage } from "./sanitize.js";
7
+ import { clearContextOverride, describeContext, parseContextValue, setContextOverride } from "./context-override.js";
8
+ import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
9
+ // src/commands.ts
10
+ function bar(percent, width = 10) {
11
+ const clamped = Math.max(0, Math.min(100, percent));
12
+ const filled = Math.round(clamped / 100 * width);
13
+ return `[${"█".repeat(filled)}${"░".repeat(width - filled)}] ${clamped.toFixed(0)}%`;
14
+ }
15
+ function reset(iso) {
16
+ if (iso === void 0) return "";
17
+ const date = new Date(iso);
18
+ if (Number.isNaN(date.getTime())) return "";
19
+ return ` · resets ${date.toISOString().replace("T", " ").slice(0, 16)}Z`;
20
+ }
21
+ function relative(until) {
22
+ const delta = Math.max(0, until - Date.now());
23
+ if (delta >= 864e5) return `${Math.round(delta / 864e5)}d`;
24
+ if (delta >= 36e5) return `${Math.round(delta / 36e5)}h`;
25
+ return `${Math.max(1, Math.round(delta / 6e4))}m`;
26
+ }
27
+ function usageLines(result) {
28
+ if (result?.report === void 0) return [`Quota unavailable: ${result?.error ?? "no report"}`];
29
+ const lines = quotaBars(result.report).map((entry) => {
30
+ const detail = entry.detail === void 0 ? "" : ` · ${entry.detail}`;
31
+ return `${entry.label}: ${bar(entry.usedPercent)}${detail}${reset(entry.resetsAt)}`;
32
+ });
33
+ for (const row of windowRows(result.report)) lines.push(`${row.label}: ${row.totals.requests} requests · ${formatUsd(row.totals.usd)} · ${row.totals.inputTokens + row.totals.outputTokens} tokens`);
34
+ if (result.report.byModel.length > 0) {
35
+ lines.push("By model:");
36
+ for (const entry of result.report.byModel.slice(0, 10)) lines.push(` ${entry.model}: ${entry.requests} req · ${formatUsd(entry.usd)}`);
37
+ }
38
+ return lines;
39
+ }
40
+ async function accountsText(deps) {
41
+ let keys;
42
+ try {
43
+ keys = await deps.pool.resolveAll(PROVIDER);
44
+ } catch {
45
+ return "Accounts: no credential";
46
+ }
47
+ if (keys.length === 0) return "Accounts: no credential";
48
+ const active = keys.find((entry) => deps.adapter.accountHealth(entry.key) === void 0);
49
+ const lines = ["Accounts:"];
50
+ for (const [index, entry] of keys.entries()) {
51
+ const health = deps.adapter.accountHealth(entry.key);
52
+ const usage = await deps.usage.read(entry.key);
53
+ const quota = quotaBars(usage?.report).map((item) => `${item.label} ${item.usedPercent.toFixed(0)}% used`).join(" / ");
54
+ const tags = [
55
+ entry.source,
56
+ entry === active ? "active" : "",
57
+ health === void 0 ? "" : `cooling ${health.reason} ${relative(health.coolingUntil)}`,
58
+ quota === "" ? usage?.error ?? "" : quota
59
+ ].filter((tag) => tag !== "");
60
+ lines.push(` ${index + 1}. ${entry.label ?? "default"}: ${tags.join(" · ")}`);
61
+ }
62
+ return lines.join("\n");
63
+ }
64
+ function rulesText(deps) {
65
+ const rules = deps.config().modelAccountRules;
66
+ if (rules.length === 0) return "No model → account rules.";
67
+ return rules.map((rule) => `${rule.pattern} → ${rule.account}`).join("\n");
68
+ }
69
+ async function modelsText(deps) {
70
+ const config = deps.config();
71
+ try {
72
+ const models = await deps.adapter.listModels(PROVIDER, { unfiltered: true });
73
+ if (models.length === 0) return "No models.";
74
+ return models.map((model) => {
75
+ const meta = effectiveModel(model.id, config);
76
+ const price = priceFor(model.id, config.priceOverrides);
77
+ const tags = [
78
+ meta.free ? "FREE" : price.priced ? `$${price.input}/$${price.output}` : "unpriced",
79
+ `${Math.round(meta.contextWindow / 1024)}K`,
80
+ meta.input.includes("image") ? "Image" : "",
81
+ meta.reasoning.length > 0 ? `reasoning: ${meta.reasoning.join("/")}` : ""
82
+ ].filter((tag) => tag !== "");
83
+ return `- ${model.id} · ${tags.join(" · ")}`;
84
+ }).join("\n");
85
+ } catch (error) {
86
+ return `Models unavailable: ${safeErrorMessage(error)}`;
87
+ }
88
+ }
89
+ async function testText(deps, model) {
90
+ const started = Date.now();
91
+ let text = "";
92
+ let reasoning = "";
93
+ try {
94
+ for await (const chunk of deps.adapter.stream({
95
+ provider: PROVIDER,
96
+ model,
97
+ messages: [{
98
+ role: "user",
99
+ content: [{
100
+ type: "text",
101
+ text: "Reply with exactly OK."
102
+ }]
103
+ }],
104
+ reasoningEffort: ReasoningEffortId("off"),
105
+ maxTokens: 64
106
+ })) if (chunk.type === "text-delta") text += chunk.text;
107
+ else if (chunk.type === "reasoning-delta") reasoning += chunk.text;
108
+ if (text === "") return {
109
+ ok: false,
110
+ text: `${model}: empty reply${reasoning === "" ? "" : ` (reasoning only: ${reasoning.slice(0, 80)})`}`
111
+ };
112
+ return {
113
+ ok: true,
114
+ text: `${model}: OK in ${Date.now() - started} ms · ${text.slice(0, 80)}`
115
+ };
116
+ } catch (error) {
117
+ return {
118
+ ok: false,
119
+ text: `${model}: failed — ${safeErrorMessage(error)}`
120
+ };
121
+ }
122
+ }
123
+ async function statusText(deps) {
124
+ const config = deps.config();
125
+ const rules = config.modelAccountRules.length === 0 ? "none" : config.modelAccountRules.map((rule) => `${rule.pattern} → ${rule.account}`).join(", ");
126
+ const usage = await deps.usage.read();
127
+ const models = await deps.adapter.listModels(PROVIDER, { unfiltered: true }).catch((err) => {
128
+ bestEffortFailed("commands:listModels", err);
129
+ return [];
130
+ });
131
+ return [
132
+ "Ollama Cloud provider",
133
+ `Key: ${config.apiKeyEnv} · ${config.transport}`,
134
+ await accountsText(deps),
135
+ ...usageLines(usage),
136
+ `Models: ${models.length}`,
137
+ `Rules: ${rules}`
138
+ ].join("\n");
139
+ }
140
+ function applyCommands(ctx, deps) {
141
+ ctx.commands.register({
142
+ name: "ollama",
143
+ description: "Ollama Cloud status, balance, accounts, models and rules",
144
+ input: { hint: "status | usage | balance | accounts | models | rules | test [model]" },
145
+ handler: async (invocation) => {
146
+ const raw = invocation.rawInput.trim();
147
+ const parts = raw === "" ? ["status"] : raw.split(/\s+/);
148
+ const verb = parts[0] ?? "status";
149
+ const arg = parts.slice(1).join(" ").trim();
150
+ switch (verb.toLowerCase()) {
151
+ case "status": return {
152
+ kind: "success",
153
+ text: await statusText(deps)
154
+ };
155
+ case "usage": return {
156
+ kind: "success",
157
+ text: usageLines(await deps.usage.usage("7d")).join("\n")
158
+ };
159
+ case "balance": return {
160
+ kind: "success",
161
+ text: usageLines(await deps.usage.read()).join("\n")
162
+ };
163
+ case "accounts": return {
164
+ kind: "success",
165
+ text: await accountsText(deps)
166
+ };
167
+ case "models": return {
168
+ kind: "success",
169
+ text: await modelsText(deps)
170
+ };
171
+ case "rules": return {
172
+ kind: "success",
173
+ text: rulesText(deps)
174
+ };
175
+ case "test": {
176
+ const result = await testText(deps, arg === "" ? "gpt-oss:120b" : arg);
177
+ return result.ok ? {
178
+ kind: "success",
179
+ text: result.text
180
+ } : {
181
+ kind: "error",
182
+ text: result.text
183
+ };
184
+ }
185
+ default: return {
186
+ kind: "error",
187
+ text: `Unknown /ollama argument "${verb}". Use status, usage, balance, accounts, models, rules, or test [model].`
188
+ };
189
+ }
190
+ }
191
+ });
192
+ ctx.commands.register({
193
+ name: "ollama-context",
194
+ description: "Set the native Ollama context size for this session",
195
+ input: { hint: "status | 4k | 8k | 16k | 32k | 64k | 128k | <tokens> | follow | reset" },
196
+ handler: async (invocation) => {
197
+ const config = deps.config();
198
+ const sessionId = invocation.agent.id;
199
+ const raw = invocation.rawInput.trim();
200
+ const value = parseContextValue(raw);
201
+ if (raw !== "" && raw.toLowerCase() !== "status" && value === void 0) return {
202
+ kind: "error",
203
+ text: "Usage: /ollama-context status | 4k | 8k | 16k | 32k | 64k | 128k | <tokens> | follow | reset"
204
+ };
205
+ if (value === "reset") {
206
+ clearContextOverride(sessionId);
207
+ return {
208
+ kind: "success",
209
+ text: `${describeContext(config, sessionId)}\nSession override cleared.`
210
+ };
211
+ }
212
+ if (value !== void 0) {
213
+ setContextOverride(sessionId, value);
214
+ return {
215
+ kind: "success",
216
+ text: describeContext(config, sessionId)
217
+ };
218
+ }
219
+ return {
220
+ kind: "success",
221
+ text: describeContext(config, sessionId)
222
+ };
223
+ }
224
+ });
225
+ }
226
+ export { applyCommands };
227
+
228
+ //# sourceMappingURL=commands.js.map