@bike4mind/cli 4.0.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +184 -4
  2. package/bin/bike4mind-cli.mjs +249 -40
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/dist/{AgentHistoryStore-DgqmcVLN.mjs → AgentHistoryStore-Bvmcy2kf.mjs} +3807 -1375
  6. package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-Yp2LPlX3.mjs} +22 -3
  7. package/dist/BubblewrapRuntime-OI4qFPNB.mjs +157 -0
  8. package/dist/ConfigStore-Bo4od3Eu.mjs +2 -0
  9. package/dist/ConfigStore-CP1W86Ui.mjs +3438 -0
  10. package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-3RbeTZ9o.mjs} +34769 -22138
  11. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  12. package/dist/{RemoteSkillSource-qTvRkaNA.mjs → RemoteSkillSource-D_F99yBR.mjs} +5 -0
  13. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-lpxVEFO7.mjs} +26 -7
  14. package/dist/SandboxRuntimeAdapter-C3xICJtQ.mjs +190 -0
  15. package/dist/SandboxRuntimeAdapter-u6c_IrjP.mjs +2 -0
  16. package/dist/SeatbeltRuntime-Ccd_QbjX.mjs +194 -0
  17. package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-D4sFGL9X.mjs} +1 -1
  18. package/dist/agents/defaults/review.md +8 -1
  19. package/dist/agents/defaults/test.md +8 -1
  20. package/dist/buildToolSearch-CqHKSLtG.mjs +417 -0
  21. package/dist/commands/acpCommand.mjs +26 -20
  22. package/dist/commands/apiCommand.mjs +3 -5
  23. package/dist/commands/doctorCommand.mjs +2 -2
  24. package/dist/commands/envCommand.mjs +1 -1
  25. package/dist/commands/headlessCommand.mjs +118 -37
  26. package/dist/commands/hostCommand.mjs +2344 -0
  27. package/dist/commands/mcpCommand.mjs +45 -30
  28. package/dist/commands/mirrorCommand.mjs +279 -0
  29. package/dist/commands/modelsCommand.mjs +1117 -0
  30. package/dist/commands/pluginCommand.mjs +9 -9
  31. package/dist/commands/skillsCommand.mjs +175 -30
  32. package/dist/commands/updateCommand.mjs +2 -2
  33. package/dist/curated-build.json +1 -0
  34. package/dist/dist-BPhZ0dCz.mjs +4776 -0
  35. package/dist/dist-K7a9yOUb.mjs +7864 -0
  36. package/dist/fit-BOnDsgbk.mjs +200 -0
  37. package/dist/{grepSearch-BgoOOwGe-B388GxRD.mjs → grepSearch-CLtEqT4j-BnKPtNWr.mjs} +2 -2
  38. package/dist/index.mjs +3215 -508
  39. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  40. package/dist/modelServers-B7zI5XnO.mjs +2465 -0
  41. package/dist/{package-CQaam4Dq.mjs → package-WlxLVpUb.mjs} +1 -1
  42. package/dist/{serve-CFxUhjml.mjs → serve-DpsV0mag.mjs} +599 -26
  43. package/dist/store-Bpdo9Syo.mjs +2 -0
  44. package/dist/{store-BbvSi3KK.mjs → store-xeJRhBtO.mjs} +2 -0
  45. package/dist/types-BFIvwByC.mjs +2 -0
  46. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  47. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-Boq0RruU.mjs} +7 -29
  48. package/package.json +17 -14
  49. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  50. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  51. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  52. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  53. package/dist/buildToolSearch-D9GEK91u.mjs +0 -2351
  54. package/dist/dist-Ul2qwn5x.mjs +0 -624
  55. package/dist/store-BYeE0shc.mjs +0 -2
  56. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -0,0 +1,1117 @@
1
+ #!/usr/bin/env node
2
+ import { t as ConfigStore } from "../ConfigStore-CP1W86Ui.mjs";
3
+ import "../Logger-3RbeTZ9o.mjs";
4
+ import { S as vramNeedsLlamaServer, l as OLLAMA_SKIPS_INTEL_IGPU } from "../modelHub-BSB6qRFP.mjs";
5
+ import { $ as RuntimeHttpError, E as HuggingFaceHub, F as curatedRunner, G as ollamaLibraryLayers, H as isPermissiveEntry, I as curatedSource, M as curatedParamsLabel, N as curatedPicks, T as HUGGING_FACE_SSH_KEYS_URL, V as isHubRepoId, h as probeHardware, j as curatedListing, z as isAbliteratedModel } from "../dist-K7a9yOUb.mjs";
6
+ import { $ as gatedMessage, A as serverRuntimeId, C as discoverSshServers, Ct as withDefaultOllamaPort, D as probeServer, E as parseSshPort, J as abortable, K as REF_ISSUES, M as toolsOffHint, N as transportVerdict, O as probeToolSupport, P as usualPorts, Q as formatBytes, T as parseServerAddress, U as CancelledError, W as NOT_RECOMMENDED_LABEL, X as clean, Y as buildTag, Z as findInstalledModel, _t as resolveRuntimeTarget, a as needsCredential, at as licenseFor, b as answersWithoutCredentials, bt as shortDigest, c as requireManageable, ct as pickBuild, d as serverBaseUrl, dt as removeInstalled, et as hadTagBefore, f as serverFetch, ft as requireInstalledReviewed, g as withSignal, gt as requireUnchangedManifest, h as validateSecret, ht as requireUnchangedLicenses, i as loginHint, j as sshDestinationProblem, k as scopeOfIp, l as resolveServerTarget, lt as planPull, m as unusableStatus, mt as requireReviewedLayers, n as findModelServer, nt as hubAccessMessage, o as noSuchServer, ot as licenseName, p as serverRedactor, pt as requireRemovable, q as UNPULLABLE, r as loadModelServers, rt as installedUncheckedMessage, s as productLabel, st as listInstalled, t as defaultOn, tt as hiddenAbliteratedMessage, u as serverAddressLabel, ut as rankSearchHits, v as SSH_PORT_PROBLEM, vt as runtimeLabel, w as leastTrusted, x as createSshFetch, xt as readOllamaManifest, y as SSH_PROBE_TIMEOUT_MS, yt as sameModelName, z as localModelId } from "../modelServers-B7zI5XnO.mjs";
7
+ import { a as machineLabel, i as fitForPlan, n as LLAMA_SERVER_VRAM_HELP, o as machineReader, r as fitForHubBuild, s as createCliCuratedList, t as FIT_LABELS } from "../fit-BOnDsgbk.mjs";
8
+ import { createInterface } from "readline";
9
+ import { lookup } from "dns/promises";
10
+ import { Writable } from "stream";
11
+ //#region src/commands/modelsCommand.ts
12
+ /**
13
+ * External models command (b4m models ls|search|show|curated|servers|pull|rm|use).
14
+ * Finds, downloads and selects local models on the configured Ollama runtime or a server saved in Desktop, with Hugging Face GGUF
15
+ * repos resolved through @bike4mind/local-models. Runs outside the interactive CLI session.
16
+ */
17
+ /** Exit code for a run stopped by Ctrl-C (128 + SIGINT). */
18
+ const EXIT_CANCELLED = 130;
19
+ const SEARCH_LIMIT = 20;
20
+ const PROGRESS_INTERVAL_MS = 100;
21
+ function formatCount(count) {
22
+ if (count === null) return "-";
23
+ if (count >= 1e9) return `${(count / 1e9).toFixed(1)}B`;
24
+ if (count >= 1e6) return `${(count / 1e6).toFixed(1)}M`;
25
+ if (count >= 1e3) return `${(count / 1e3).toFixed(1)}k`;
26
+ return String(count);
27
+ }
28
+ function formatGated(gated) {
29
+ return gated === false ? "no" : `yes (${gated === "manual" ? "manual approval" : "automatic approval"})`;
30
+ }
31
+ /** Left-aligned columns; the last column is not padded. */
32
+ function table(rows) {
33
+ const widths = rows[0].map((_, col) => Math.max(...rows.map((row) => row[col]?.length ?? 0)));
34
+ return rows.map((row) => row.map((cell, col) => col === row.length - 1 ? cell : cell.padEnd(widths[col])).join(" ").trimEnd());
35
+ }
36
+ async function listModels(deps, opts) {
37
+ const target = await abortable(deps.resolveRuntime(), deps.signal);
38
+ const { runtime } = target;
39
+ const rows = await listInstalled(runtime, defaultOn(target, deps.config.defaultModel), deps.signal);
40
+ if (opts.json) {
41
+ deps.log(JSON.stringify({
42
+ runtime: {
43
+ kind: runtime.kind,
44
+ baseUrl: runtime.baseUrl,
45
+ source: target.source,
46
+ ...target.server && { server: target.server.name }
47
+ },
48
+ models: rows
49
+ }, null, 2));
50
+ return 0;
51
+ }
52
+ deps.log(runtimeLabel(target));
53
+ if (rows.length === 0) {
54
+ deps.log(target.server ? `No models are served by ${clean(target.server.name)}.` : "No models installed. Find one with: b4m models search <query>");
55
+ return 0;
56
+ }
57
+ if (target.server && runtime.kind === "openai-compatible") {
58
+ const lines = table([[
59
+ "NAME",
60
+ "CONTEXT",
61
+ "NOTE"
62
+ ], ...rows.map((model) => [
63
+ clean(model.name),
64
+ model.contextLength ? String(model.contextLength) : "-",
65
+ [
66
+ model.baseModel && `LoRA on ${clean(model.baseModel)}`,
67
+ model.aliases && model.aliases.length > 0 && `also: ${model.aliases.map(clean).join(", ")}`,
68
+ model.default && "default"
69
+ ].filter(Boolean).join("; ")
70
+ ])]);
71
+ for (const line of lines) deps.log(line);
72
+ return 0;
73
+ }
74
+ const lines = table([[
75
+ "NAME",
76
+ "SIZE",
77
+ "QUANT",
78
+ "CAPABILITIES",
79
+ ""
80
+ ], ...rows.map((model) => [
81
+ clean(model.name),
82
+ formatBytes(model.sizeBytes),
83
+ clean(model.quantization) || "-",
84
+ Object.entries(model.capabilities).filter(([, has]) => has).map(([name]) => name).join(", ") || "-",
85
+ [model.loaded && "loaded", model.default && "default"].filter(Boolean).join(", ")
86
+ ])]);
87
+ for (const line of lines) deps.log(line);
88
+ return 0;
89
+ }
90
+ async function searchModels(query, deps, opts) {
91
+ const page = await deps.hub().search({
92
+ query,
93
+ limit: SEARCH_LIMIT,
94
+ signal: deps.signal
95
+ });
96
+ const { hits, hidden } = rankSearchHits(page.models, opts.includeAbliterated);
97
+ if (opts.json) {
98
+ deps.log(JSON.stringify({
99
+ ...page,
100
+ models: hits,
101
+ ...hidden > 0 && { hidden: hiddenAbliteratedMessage(hidden) }
102
+ }, null, 2));
103
+ return 0;
104
+ }
105
+ if (hits.length === 0) deps.log(`No GGUF models on Hugging Face match "${clean(query)}".`);
106
+ else {
107
+ const labelled = hits.some((model) => model.notRecommended);
108
+ const lines = table([[
109
+ "REPO",
110
+ "DOWNLOADS",
111
+ "LIKES",
112
+ "LICENSE",
113
+ "GATED",
114
+ ...labelled ? ["NOTE"] : []
115
+ ], ...hits.map((model) => [
116
+ clean(model.id),
117
+ formatCount(model.downloads),
118
+ formatCount(model.likes),
119
+ model.licenses.map(clean).join(", ") || "-",
120
+ formatGated(model.gated),
121
+ ...labelled ? [model.notRecommended ? `not recommended: ${NOT_RECOMMENDED_LABEL}` : ""] : []
122
+ ])]);
123
+ for (const line of lines) deps.log(line);
124
+ }
125
+ if (hidden > 0) {
126
+ deps.log("");
127
+ deps.log(`${hiddenAbliteratedMessage(hidden)} Show them with --include-abliterated.`);
128
+ }
129
+ if (hits.length === 0) return 0;
130
+ deps.log("");
131
+ deps.log("Builds and sizes: b4m models show <repo>");
132
+ return 0;
133
+ }
134
+ async function showModel(repo, deps, opts) {
135
+ if (!isHubRepoId(repo)) throw new Error(`Not a Hugging Face repo: ${repo} (expected owner/name)`);
136
+ const hub = deps.hub();
137
+ const detail = await hub.getModel(repo, { signal: deps.signal });
138
+ const reading = await abortable(deps.machine(deps.runtimeHost()), deps.signal);
139
+ const fitOf = (build) => fitForHubBuild(build, detail, reading);
140
+ if (opts.json) {
141
+ const rated = {
142
+ ...detail,
143
+ builds: detail.builds.map((build) => ({
144
+ ...build,
145
+ fit: fitOf(build)
146
+ }))
147
+ };
148
+ deps.log(JSON.stringify(isAbliteratedModel(detail) ? {
149
+ ...rated,
150
+ notRecommended: NOT_RECOMMENDED_LABEL
151
+ } : rated, null, 2));
152
+ return 0;
153
+ }
154
+ const license = licenseFor(detail, hub.endpoint);
155
+ const id = clean(detail.id);
156
+ deps.log(id);
157
+ deps.log(` License: ${license.label}${license.restricted ? ` (${license.link})` : ""}`);
158
+ deps.log(` Gated: ${formatGated(detail.gated)}${detail.gated && detail.canDownload === true ? ", access granted" : ""}`);
159
+ deps.log(` Revision: ${clean(detail.revision)}`);
160
+ if (detail.baseModels.length > 0) deps.log(` Based on: ${detail.baseModels.map(clean).join(", ")}`);
161
+ if (isAbliteratedModel(detail)) deps.log(` Caution: not recommended: ${NOT_RECOMMENDED_LABEL}`);
162
+ if (detail.gguf) {
163
+ const facts = [
164
+ detail.gguf.architecture && clean(detail.gguf.architecture),
165
+ detail.gguf.parameterCount !== null && `${formatCount(detail.gguf.parameterCount)} params`,
166
+ detail.gguf.contextLength !== null && `${detail.gguf.contextLength} context`
167
+ ].filter(Boolean);
168
+ if (facts.length > 0) deps.log(` Model: ${facts.join(", ")}`);
169
+ }
170
+ if (detail.gated && detail.canDownload !== true) {
171
+ deps.log("");
172
+ deps.log(gatedMessage(id, hub.endpoint));
173
+ }
174
+ deps.log("");
175
+ if (detail.builds.length === 0) {
176
+ deps.log("No GGUF builds in this repo.");
177
+ return 0;
178
+ }
179
+ deps.log("Builds (smallest first):");
180
+ const lines = table([[
181
+ "BUILD",
182
+ "SIZE",
183
+ "FIT",
184
+ "OLLAMA REF"
185
+ ], ...detail.builds.map((build) => [
186
+ clean(build.label),
187
+ formatBytes(build.sizeBytes),
188
+ FIT_LABELS[fitOf(build).verdict],
189
+ build.ollamaRef ? clean(build.ollamaRef) : `none: ${REF_ISSUES[build.ollamaRefIssue ?? "unsupported-name"]}`
190
+ ])]);
191
+ for (const line of lines) deps.log(` ${line}`);
192
+ deps.log("unknown" in reading ? ` Fit is unknown. ${reading.unknown}.` : ` Fit is a rough estimate from each file's size for this machine (${machineLabel(reading)}); pull explains it.`);
193
+ if (detail.projectors.length > 0) {
194
+ deps.log("");
195
+ deps.log("Vision projectors (Ollama's Hugging Face registry adds one to each pull):");
196
+ for (const projector of detail.projectors) deps.log(` ${clean(projector.path)} ${clean(projector.quant) || "-"} ${formatBytes(projector.sizeBytes)}`);
197
+ }
198
+ const pullable = detail.builds.filter((build) => !build.ollamaRefIssue || !UNPULLABLE.has(build.ollamaRefIssue));
199
+ const suggested = pickBuild(pullable, null) ?? pullable.find((build) => build.ollamaRef);
200
+ if (suggested?.quant) {
201
+ deps.log("");
202
+ deps.log(`Pull one with: b4m models pull ${id}:${clean(buildTag(suggested))}`);
203
+ }
204
+ return 0;
205
+ }
206
+ const SLOT_LABELS = {
207
+ best: "Best",
208
+ fast: "Fast",
209
+ "long-context": "Long context",
210
+ light: "Light"
211
+ };
212
+ const TOOL_RATINGS = {
213
+ weak: "weak",
214
+ ok: "good",
215
+ strong: "strong"
216
+ };
217
+ const formatGiB = (bytes) => {
218
+ const gib = bytes / 1024 ** 3;
219
+ return `${gib >= 100 ? Math.round(gib) : Number(gib.toFixed(1))} GiB`;
220
+ };
221
+ /** "an Intel GPU (NAME)", or the name alone when it already starts with "Intel", as the probe's names on Linux do. */
222
+ function anIntelGpu(name) {
223
+ if (!name) return "an Intel GPU";
224
+ return /^Intel\b/.test(name) ? `an ${clean(name)}` : `an Intel GPU (${clean(name)})`;
225
+ }
226
+ function machineText(hw) {
227
+ const memory = formatGiB(hw.totalMemoryBytes);
228
+ if (hw.memoryKind === "unified") {
229
+ const shared = `This computer has ${memory} of memory, shared with its GPU${hw.gpuName ? ` (${clean(hw.gpuName)})` : ""}.`;
230
+ return hw.gpuVendor === "intel" ? `${shared} ${OLLAMA_SKIPS_INTEL_IGPU}` : shared;
231
+ }
232
+ if (hw.memoryKind === "discrete" && hw.gpuMemoryBytes) return `This computer has ${memory} of RAM and ${formatGiB(hw.gpuMemoryBytes)} of GPU memory${hw.gpuName ? ` (${clean(hw.gpuName)})` : ""}.`;
233
+ if (vramNeedsLlamaServer(hw)) return `This computer has ${memory} of RAM and ${anIntelGpu(hw.gpuName)} of unknown memory, so its picks assume the CPU. ${LLAMA_SERVER_VRAM_HELP}`;
234
+ return `This computer has ${memory} of RAM and no GPU memory was detected, so its picks assume the CPU.`;
235
+ }
236
+ function tierText(tier) {
237
+ if (tier.memoryKind === "cpu") return "CPU only";
238
+ return `${tier.minGiB} GiB+ ${tier.memoryKind === "discrete" ? "GPU memory" : "unified memory"}`;
239
+ }
240
+ function curatedTags(entry, build) {
241
+ const { rating } = entry.toolUse;
242
+ const tools = !entry.capabilities.tools ? "no tools" : rating === "unrated" ? "tools" : `tools: ${TOOL_RATINGS[rating]}`;
243
+ const minimum = build.runtimeMin?.ollama;
244
+ return [
245
+ entry.capabilities.vision && "vision",
246
+ entry.capabilities.thinking && "thinking",
247
+ entry.roles.includes("code") && "code",
248
+ tools,
249
+ minimum && `needs Ollama >= ${clean(minimum)}`
250
+ ].filter((tag) => Boolean(tag)).join(", ");
251
+ }
252
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
253
+ "localhost",
254
+ "::1",
255
+ "[::1]"
256
+ ]);
257
+ function isLoopbackHost(host) {
258
+ try {
259
+ const { hostname } = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(host) ? host : `http://${host}`);
260
+ return LOOPBACK_HOSTS.has(hostname.toLowerCase()) || /^127\./.test(hostname);
261
+ } catch {
262
+ return false;
263
+ }
264
+ }
265
+ function curatedBuildJson(build) {
266
+ const { ollamaRef, sizeBytes } = curatedSource(build);
267
+ return {
268
+ id: build.id,
269
+ quant: build.quant.label,
270
+ ref: ollamaRef,
271
+ sizeBytes,
272
+ ollamaMin: build.runtimeMin?.ollama ?? null
273
+ };
274
+ }
275
+ function curatedEntryJson(entry) {
276
+ return {
277
+ id: entry.id,
278
+ name: entry.name,
279
+ params: curatedParamsLabel(entry),
280
+ why: entry.why,
281
+ license: {
282
+ id: entry.license.id,
283
+ kind: isPermissiveEntry(entry) ? "permissive" : "restricted",
284
+ url: entry.license.source,
285
+ base: {
286
+ id: entry.license.base.id,
287
+ permissive: entry.license.base.class === "permissive"
288
+ }
289
+ },
290
+ vision: entry.capabilities.vision,
291
+ thinking: entry.capabilities.thinking,
292
+ code: entry.roles.includes("code"),
293
+ tools: entry.capabilities.tools,
294
+ toolUse: {
295
+ rating: entry.toolUse.rating,
296
+ note: entry.toolUse.note ?? null
297
+ }
298
+ };
299
+ }
300
+ function licenseCell(entry) {
301
+ const id = clean(entry.license.id);
302
+ if (isPermissiveEntry(entry)) return id;
303
+ const { base } = entry.license;
304
+ return `restricted: ${id}${base.class === "permissive" ? "" : ` (base: ${clean(base.id)})`}`;
305
+ }
306
+ const sizeOfBuild = (build) => curatedSource(build).sizeBytes;
307
+ /** Lists the Curated models without contacting any runtime; downloading one is always a separate `pull`. */
308
+ async function listCurated(deps, opts) {
309
+ if (opts.refresh) await abortable(deps.curatedSource?.refresh() ?? Promise.resolve(), deps.signal);
310
+ const manifest = await abortable(Promise.resolve(deps.curated()), deps.signal);
311
+ const origin = deps.curatedSource?.origin() ?? null;
312
+ const hardware = await abortable(deps.hardware(), deps.signal);
313
+ const listing = curatedListing(manifest).map(({ entry, builds }) => ({
314
+ entry,
315
+ builds: [...builds].sort((a, b) => sizeOfBuild(a) - sizeOfBuild(b))
316
+ }));
317
+ const { tier, picks } = curatedPicks(manifest, hardware);
318
+ if (opts.json) {
319
+ deps.log(JSON.stringify({
320
+ updatedAt: manifest.updatedAt,
321
+ ...origin && { source: {
322
+ origin: origin.origin,
323
+ sequence: origin.sequence,
324
+ check: origin.check,
325
+ stale: origin.stale,
326
+ checkedAt: origin.checkedAt
327
+ } },
328
+ machine: {
329
+ memoryKind: hardware.memoryKind,
330
+ totalMemoryBytes: hardware.totalMemoryBytes,
331
+ gpuMemoryBytes: hardware.gpuMemoryBytes,
332
+ gpuName: hardware.gpuName
333
+ },
334
+ tier: tier && {
335
+ memoryKind: tier.memoryKind,
336
+ minGiB: tier.minGiB
337
+ },
338
+ picks: picks.map(({ pick, entry, build }) => ({
339
+ slot: pick.slot,
340
+ entryId: entry.id,
341
+ name: entry.name,
342
+ build: curatedBuildJson(build)
343
+ })),
344
+ entries: listing.map(({ entry, builds }) => ({
345
+ ...curatedEntryJson(entry),
346
+ builds: builds.map(curatedBuildJson)
347
+ }))
348
+ }, null, 2));
349
+ return 0;
350
+ }
351
+ deps.log(`Curated list from ${clean(manifest.updatedAt.slice(0, 10))}. ${machineText(hardware)}`);
352
+ if (origin) deps.log(origin.text);
353
+ else if (opts.refresh) deps.log("This CLI has no online curated list; showing the bundled one.");
354
+ if (listing.length === 0) {
355
+ deps.log("The Curated list has no models. Search Hugging Face with: b4m models search <query>");
356
+ return 0;
357
+ }
358
+ const refOf = (build) => clean(curatedSource(build).ollamaRef);
359
+ const sizeOf = (build) => formatBytes(sizeOfBuild(build));
360
+ const host = deps.config.ollamaHost;
361
+ if (host && !isLoopbackHost(host)) deps.log(`The picks are for this computer, not the Ollama host at ${clean(host)}.`);
362
+ deps.log("");
363
+ if (!tier || picks.length === 0) deps.log("For this computer: the list has no picks for this computer's memory yet.");
364
+ else {
365
+ deps.log(`For this computer (${tierText(tier)}):`);
366
+ const lines = table([[
367
+ "SLOT",
368
+ "MODEL",
369
+ "REF",
370
+ "SIZE",
371
+ "LICENSE",
372
+ "TAGS"
373
+ ], ...picks.map(({ pick, entry, build }) => [
374
+ SLOT_LABELS[pick.slot],
375
+ clean(entry.name),
376
+ refOf(build),
377
+ sizeOf(build),
378
+ licenseCell(entry),
379
+ curatedTags(entry, build)
380
+ ])]);
381
+ for (const line of lines) deps.log(` ${line}`);
382
+ }
383
+ deps.log("");
384
+ deps.log("All curated models, smallest first:");
385
+ const lines = table([[
386
+ "MODEL",
387
+ "PARAMS",
388
+ "REF",
389
+ "SIZE",
390
+ "LICENSE",
391
+ "TAGS"
392
+ ], ...listing.flatMap(({ entry, builds }) => builds.map((build) => [
393
+ clean(entry.name),
394
+ clean(curatedParamsLabel(entry)),
395
+ refOf(build),
396
+ sizeOf(build),
397
+ licenseCell(entry),
398
+ curatedTags(entry, build)
399
+ ]))]);
400
+ for (const line of lines) deps.log(` ${line}`);
401
+ if (listing.some(({ entry }) => !isPermissiveEntry(entry))) {
402
+ deps.log("");
403
+ deps.log("A restricted license is not a permissive open-source license; pull asks you to accept it first.");
404
+ }
405
+ deps.log("");
406
+ deps.log(`Pull one with: b4m models pull ${refOf(picks[0]?.build ?? listing[0].builds[0])}`);
407
+ return 0;
408
+ }
409
+ /** Asks unless `--yes`; without a terminal to ask on, a missing `--yes` is an error. */
410
+ async function confirmDownload(question, deps, opts) {
411
+ if (opts.yes) return true;
412
+ if (!deps.isTTY) throw new Error("Re-run with --yes to download without a prompt.");
413
+ return deps.confirm(question);
414
+ }
415
+ /** `runner` and `verify` come from a curated build: the runner Ollama must use, and the post-install check. */
416
+ async function pullWithProgress(target, ref, deps, { runner, verify } = {}) {
417
+ let lastStatus = "";
418
+ let lastDraw = 0;
419
+ let sawBytes = false;
420
+ try {
421
+ await target.runtime.pull(ref, {
422
+ runner,
423
+ signal: deps.signal,
424
+ onProgress: ({ status, completedBytes, totalBytes }) => {
425
+ if (!sawBytes && totalBytes && completedBytes < totalBytes) {
426
+ sawBytes = true;
427
+ if (completedBytes > 0) {
428
+ if (deps.isTTY) deps.progress.end();
429
+ deps.log(`Already downloaded: ${formatBytes(completedBytes)}; pulling the rest.`);
430
+ }
431
+ }
432
+ const text = clean(target.redact ? target.redact(status) : status);
433
+ if (!deps.isTTY) {
434
+ if (text !== lastStatus) deps.log(text);
435
+ lastStatus = text;
436
+ return;
437
+ }
438
+ const now = Date.now();
439
+ if (text === lastStatus && now - lastDraw < PROGRESS_INTERVAL_MS) return;
440
+ lastStatus = text;
441
+ lastDraw = now;
442
+ const amount = text.startsWith("pulling ") && totalBytes && totalBytes > 0 ? ` ${Math.floor(completedBytes / totalBytes * 100)}% ${formatBytes(completedBytes)} / ${formatBytes(totalBytes)}` : "";
443
+ deps.progress.update(`${text}${amount}`);
444
+ }
445
+ });
446
+ } catch (error) {
447
+ if (deps.isTTY) deps.progress.end();
448
+ if (deps.signal.aborted) {
449
+ deps.log("Pull cancelled. Nothing was installed; Ollama keeps the partial download, so pulling again resumes it.");
450
+ return "cancelled";
451
+ }
452
+ throw error;
453
+ }
454
+ if (deps.isTTY) deps.progress.end();
455
+ if (verify) {
456
+ deps.log("Checking the installed model against the reviewed build.");
457
+ try {
458
+ await verify();
459
+ } catch (error) {
460
+ if (!deps.signal.aborted) throw error;
461
+ deps.log(installedUncheckedMessage(ref));
462
+ return "cancelled";
463
+ }
464
+ }
465
+ deps.log(`Pulled ${clean(ref)}. Chat with it by default: b4m models use ${clean(ref)}`);
466
+ return "pulled";
467
+ }
468
+ /** Restricted or undeclared licenses need a yes at the prompt or `--accept-license`. */
469
+ async function acceptLicense(license, deps, opts) {
470
+ if (!license.restricted) return true;
471
+ const declared = license.label !== "none declared" || license.base !== void 0;
472
+ const noun = license.plural ? "licenses" : "license";
473
+ const named = licenseName(license);
474
+ deps.log("");
475
+ deps.log(declared ? `This model is under the ${named} ${noun}, ${license.plural ? "which are not all permissive open-source licenses" : "which is not a permissive open-source license"}.` : "This model does not declare a license.");
476
+ deps.log(`Read ${declared ? license.plural ? "them" : "it" : "its page"} before downloading: ${license.link}`);
477
+ if (opts.acceptLicense) return true;
478
+ if (!deps.isTTY) throw new Error("Re-run with --accept-license once you have read and accepted the license.");
479
+ return deps.confirm(declared ? `Do you accept the ${named} ${noun}? [y/N] ` : "Download it anyway? [y/N] ");
480
+ }
481
+ /** Prints the fit verdict; a too-large one stops the pull unless `--force`. Unknown never does. */
482
+ async function requireFit(plan, deps, opts) {
483
+ const fit = await abortable(fitForPlan(plan, deps.machine), deps.signal);
484
+ deps.log(`Fit: ${FIT_LABELS[fit.verdict]}. ${fit.detail}`);
485
+ if (fit.verdict !== "too-large" || opts.force) return;
486
+ if (fit.gpuUnread) throw new Error("Nothing was downloaded: this build is rated too large from system RAM alone, since the GPU could not be read. If this machine has a GPU that can hold it, re-run with --force to download it anyway.");
487
+ const smaller = plan.kind === "ollama" ? "Pick a smaller tag" : `Pick a smaller quant from: b4m models show ${plan.id}`;
488
+ throw new Error(`Nothing was downloaded: this build is rated too large for this machine. ${smaller}, or re-run with --force to download it anyway.`);
489
+ }
490
+ async function pullModel(input, deps, opts) {
491
+ const plan = await planPull(input, deps);
492
+ if (plan.kind === "ollama") {
493
+ const { name, manifest, license, target } = plan;
494
+ deps.log(`Model: ${clean(name)} (Ollama registry)`);
495
+ deps.log(`Digest: ${shortDigest(manifest.digest)}`);
496
+ deps.log(`Size: ${formatBytes(manifest.sizeBytes)}`);
497
+ deps.log(`License: ${license.label}${license.base ? ` (base: ${license.base})` : ""}`);
498
+ deps.log(`Runtime: ${runtimeLabel(target)}`);
499
+ await requireFit(plan, deps, opts);
500
+ if (!await acceptLicense(license, deps, opts)) return "declined";
501
+ if (!await confirmDownload(`Download ${formatBytes(manifest.sizeBytes)}? [y/N] `, deps, opts)) return "declined";
502
+ await requireUnchangedManifest(name, manifest, deps);
503
+ return pullReviewed(plan, name, deps);
504
+ }
505
+ const { hub, detail, build, id, target, license, projectorBytes: projector } = plan;
506
+ deps.log(`Model: ${id} (${clean(build.label)})`);
507
+ deps.log(`File: ${build.files.map((file) => clean(file.path)).join(", ")}`);
508
+ deps.log(`Size: ${formatBytes(build.sizeBytes)}${projector > 0 ? ` plus a vision projector of up to ${formatBytes(projector)}` : ""}`);
509
+ deps.log(`License: ${license.label}${license.base ? ` (base: ${license.base})` : ""}`);
510
+ deps.log(`Runtime: ${runtimeLabel(target)}`);
511
+ await requireFit(plan, deps, opts);
512
+ if (detail.ollamaNeedsSshKey) {
513
+ deps.log("");
514
+ deps.log(`Ollama downloads ${detail.private ? "private" : "gated"} repos with its own key: add ~/.ollama/id_ed25519.pub of the Ollama host at ${HUGGING_FACE_SSH_KEYS_URL} if you have not.`);
515
+ }
516
+ if (!await acceptLicense(license, deps, opts)) return "declined";
517
+ if (!await confirmDownload(`Download ${formatBytes(build.sizeBytes)}? [y/N] `, deps, opts)) return "declined";
518
+ let ref;
519
+ try {
520
+ await requireUnchangedLicenses(hub, detail, license, deps.signal);
521
+ ref = await hub.verifyOllamaRef(detail, build, { signal: deps.signal });
522
+ } catch (error) {
523
+ if (deps.signal.aborted) {
524
+ deps.log("Pull cancelled before the download started.");
525
+ return "cancelled";
526
+ }
527
+ throw error;
528
+ }
529
+ if (!ref) throw new Error(`Hugging Face's registry does not serve this exact ${clean(build.label)} file to Ollama, so nothing was downloaded. Pick another build from: b4m models show ${id}`);
530
+ return pullReviewed(plan, ref, deps);
531
+ }
532
+ /** Pulls `ref`; a curated build is checked against its reviewed pins first and once Ollama has installed it. */
533
+ async function pullReviewed(plan, ref, deps) {
534
+ const { curated, target } = plan;
535
+ if (!curated) return pullWithProgress(target, ref, deps);
536
+ let hadTag;
537
+ try {
538
+ await requireReviewedLayers(curated, ref, deps);
539
+ hadTag = await hadTagBefore(target, ref, deps.signal);
540
+ } catch (error) {
541
+ if (deps.signal.aborted) {
542
+ deps.log("Pull cancelled before the download started.");
543
+ return "cancelled";
544
+ }
545
+ throw error;
546
+ }
547
+ return pullWithProgress(target, ref, deps, {
548
+ runner: curatedRunner(curated.build),
549
+ verify: () => requireInstalledReviewed(target, curated, ref, hadTag, deps.signal)
550
+ });
551
+ }
552
+ async function removeModel(name, deps, opts) {
553
+ const target = await abortable(deps.resolveRuntime(), deps.signal);
554
+ requireRemovable(target);
555
+ if (!opts.yes) {
556
+ if (!deps.isTTY) throw new Error("Re-run with --yes to remove without a prompt.");
557
+ if (!await deps.confirm(`Remove ${clean(name)} from ${runtimeLabel(target)}? [y/N] `)) {
558
+ deps.log("Aborted");
559
+ return 0;
560
+ }
561
+ }
562
+ const installed = findInstalledModel(await abortable(target.runtime.list(), deps.signal), name);
563
+ await removeInstalled(target, installed?.name ?? name, deps.signal);
564
+ deps.log(`Removed ${clean(name)}.`);
565
+ const currentDefault = defaultOn(target, deps.config.defaultModel);
566
+ if (currentDefault && sameModelName(currentDefault, name)) deps.log("It was your default model; pick another with: b4m models use <name>");
567
+ return 0;
568
+ }
569
+ async function useModel(name, deps) {
570
+ const target = await abortable(deps.resolveRuntime(), deps.signal);
571
+ if (target.server) return useServerModel(name, {
572
+ ...target,
573
+ server: target.server
574
+ }, deps);
575
+ const { runtime } = target;
576
+ if (runtime.kind !== "ollama") throw new Error(`The CLI chats with local models through Ollama; ${runtimeLabel(target)} is not Ollama.`);
577
+ const models = await abortable(runtime.list(), deps.signal);
578
+ const model = findInstalledModel(models, name);
579
+ if (!model) throw new Error(`No model named ${clean(name)} on ${runtimeLabel(target)}. See: b4m models ls`);
580
+ await deps.config.save({
581
+ defaultModel: model.name,
582
+ localDefaultModel: model.name,
583
+ ...deps.config.ollamaHost !== runtime.baseUrl && { ollamaHost: runtime.baseUrl }
584
+ });
585
+ deps.log(`Default model: ${clean(model.name)} on Ollama at ${runtime.baseUrl}`);
586
+ deps.log("Start chatting with: b4m");
587
+ return 0;
588
+ }
589
+ /** Saves the server's id with the model, so chat goes to that server and never to a same-named model elsewhere. */
590
+ async function useServerModel(name, target, deps) {
591
+ const server = clean(target.server.name);
592
+ const models = await abortable(target.runtime.list(), deps.signal);
593
+ const model = findInstalledModel(models, name) ?? models.find((listed) => listed.aliases?.includes(name));
594
+ if (!model) throw new Error(`No model named ${clean(name)} on ${server}. See: b4m models ls --server ${server}`);
595
+ if (model.name !== name && model.aliases?.includes(name)) deps.log(`${clean(name)} is another name for ${clean(model.name)} on ${server}; saving ${clean(model.name)}.`);
596
+ const id = localModelId(serverRuntimeId(target.server.id), model.name);
597
+ await deps.config.save({
598
+ defaultModel: id,
599
+ localDefaultModel: id
600
+ });
601
+ deps.log(`Default model: ${clean(model.name)} on ${server}`);
602
+ deps.log("Start chatting with: b4m");
603
+ return 0;
604
+ }
605
+ /** The servers, with every ssh request also ended by Ctrl-C, so a running ssh stops too. */
606
+ function requireServers(deps) {
607
+ if (!deps.servers) throw new Error("Model servers are not available here.");
608
+ const sshFetchFor = deps.servers.sshFetchFor ?? ((endpoint) => createSshFetch(endpoint));
609
+ return {
610
+ ...deps.servers,
611
+ sshFetchFor: (endpoint) => withSignal(sshFetchFor(endpoint), deps.signal)
612
+ };
613
+ }
614
+ async function scopeOfHost(host, resolve) {
615
+ const literal = scopeOfIp(host);
616
+ if (literal) return literal;
617
+ try {
618
+ const scopes = (await Promise.race([resolve ? resolve(host) : lookup(host, { all: true }).then((found) => found.map((entry) => entry.address)), new Promise((done) => setTimeout(() => done(null), 1500).unref())]) ?? []).flatMap((address) => scopeOfIp(address) ?? []);
619
+ return scopes.length > 0 ? leastTrusted(scopes) : null;
620
+ } catch {
621
+ return null;
622
+ }
623
+ }
624
+ const SERVER_APP = {
625
+ name: "the CLI",
626
+ recheck: "then check again with: b4m models servers --check-tools"
627
+ };
628
+ async function describeServer(server, ctx, checkTools) {
629
+ const secret = ctx.secret(server.id);
630
+ const credentials = server.auth.type === "none" ? "none" : needsCredential(server, secret) ? "needed" : "set";
631
+ const base = {
632
+ server,
633
+ credentials
634
+ };
635
+ const baseUrl = serverBaseUrl(server);
636
+ if (!baseUrl) return {
637
+ ...base,
638
+ product: productLabel(server.kind, null),
639
+ status: {
640
+ state: "offline",
641
+ latencyMs: null,
642
+ text: "unusable address"
643
+ },
644
+ notes: []
645
+ };
646
+ const ssh = server.transport.type === "ssh";
647
+ const redactor = serverRedactor(server, secret);
648
+ const fetch = serverFetch(server, secret, ctx.sshFetchFor);
649
+ const outcome = await probeServer(fetch, baseUrl, server.name, () => performance.now(), server.kind, ssh ? SSH_PROBE_TIMEOUT_MS : void 0);
650
+ const notes = [];
651
+ const parsed = ssh ? null : parseServerAddress(baseUrl);
652
+ const scope = parsed ? await scopeOfHost(parsed.host, ctx.resolveHost) : null;
653
+ if (parsed && scope) {
654
+ const verdict = transportVerdict(parsed.protocol, scope, credentials === "set");
655
+ if (!verdict.ok) notes.push(verdict.reason);
656
+ else if (verdict.unencrypted) notes.push("Unencrypted");
657
+ }
658
+ if (outcome.kind && scope === "public") {
659
+ if (await answersWithoutCredentials(serverFetch(server, void 0), baseUrl, outcome.kind)) notes.push("Open to anyone");
660
+ }
661
+ const model = server.models[0];
662
+ if (checkTools && outcome.kind === "openai-compatible" && model) {
663
+ if (await probeToolSupport(fetch, baseUrl, model) === "refused") notes.push(toolsOffHint(server.name, outcome.product, SERVER_APP));
664
+ }
665
+ const text = (value) => clean(redactor ? redactor.redact(value) : value);
666
+ let status;
667
+ if (outcome.kind) status = {
668
+ state: "online",
669
+ latencyMs: outcome.latencyMs,
670
+ text: `online (${outcome.latencyMs ?? "?"} ms)`
671
+ };
672
+ else if (outcome.auth) status = {
673
+ state: "credentials",
674
+ latencyMs: null,
675
+ text: credentials === "set" ? "refused the saved credentials" : "needs credentials"
676
+ };
677
+ else status = {
678
+ state: outcome.refused || outcome.forbidden ? "refused" : "offline",
679
+ latencyMs: null,
680
+ text: text(outcome.error ?? "offline")
681
+ };
682
+ return {
683
+ ...base,
684
+ product: productLabel(outcome.kind ?? server.kind, outcome.product),
685
+ status,
686
+ notes
687
+ };
688
+ }
689
+ async function listServers(deps, opts) {
690
+ const ctx = requireServers(deps);
691
+ const loaded = await abortable(ctx.load(), deps.signal);
692
+ const rows = await abortable(Promise.all(loaded.servers.map((server) => describeServer(server, ctx, Boolean(opts.checkTools)))), deps.signal);
693
+ const unusable = (loaded.unusable ?? []).map((server) => ({
694
+ server,
695
+ product: productLabel(server.kind, null),
696
+ address: server.transport.destination ? `ssh ${server.transport.destination}` : "unusable address",
697
+ credentials: server.auth.type === "none" ? "none" : ctx.secret(server.id) ? "set" : "needed",
698
+ status: {
699
+ state: "refused",
700
+ latencyMs: null,
701
+ text: clean(unusableStatus(server))
702
+ }
703
+ }));
704
+ if (opts.json) {
705
+ deps.log(JSON.stringify({
706
+ problem: loaded.problem,
707
+ toolsChecked: Boolean(opts.checkTools),
708
+ servers: [...rows.map(({ server, product, credentials, status, notes }) => ({
709
+ id: server.id,
710
+ name: server.name,
711
+ kind: server.kind,
712
+ product,
713
+ transport: server.transport.type,
714
+ address: serverAddressLabel(server),
715
+ access: server.access,
716
+ source: server.source,
717
+ credentials,
718
+ status,
719
+ notes
720
+ })), ...unusable.map(({ server, product, address, credentials, status }) => ({
721
+ id: server.id,
722
+ name: server.name,
723
+ kind: server.kind,
724
+ product,
725
+ transport: server.transport.type,
726
+ address,
727
+ access: server.access,
728
+ source: "desktop",
729
+ credentials,
730
+ status,
731
+ notes: []
732
+ }))]
733
+ }, null, 2));
734
+ return 0;
735
+ }
736
+ if (rows.length === 0 && unusable.length === 0) {
737
+ deps.log(loaded.problem ?? "No model servers are saved in Desktop. Add one in Desktop under Settings.");
738
+ return 0;
739
+ }
740
+ if (loaded.problem) deps.log(loaded.problem);
741
+ const access = (server) => server.access === "manage" ? "Manage" : "Chat only";
742
+ const lines = table([
743
+ [
744
+ "NAME",
745
+ "KIND",
746
+ "ADDRESS",
747
+ "ACCESS",
748
+ "CREDENTIALS",
749
+ "STATUS",
750
+ "NOTE"
751
+ ],
752
+ ...rows.map(({ server, product, credentials, status, notes }) => [
753
+ clean(server.name),
754
+ product,
755
+ clean(serverAddressLabel(server)),
756
+ access(server),
757
+ credentials === "needed" ? `needed: ${loginHint(server)}` : credentials,
758
+ status.text,
759
+ notes.map(clean).join(" ")
760
+ ]),
761
+ ...unusable.map(({ server, product, address, credentials, status }) => [
762
+ clean(server.name),
763
+ product,
764
+ clean(address),
765
+ access(server),
766
+ credentials,
767
+ status.text,
768
+ ""
769
+ ])
770
+ ]);
771
+ for (const line of lines) deps.log(line);
772
+ if (!opts.checkTools && rows.some((row) => row.server.kind === "openai-compatible" && row.status.state === "online")) {
773
+ deps.log("");
774
+ deps.log("Tool support: not checked. Add --check-tools to send each OpenAI-compatible server a one-token request.");
775
+ }
776
+ return 0;
777
+ }
778
+ async function chosenServer(name, ctx, signal) {
779
+ const loaded = await abortable(ctx.load(), signal);
780
+ const server = findModelServer(loaded.servers, name);
781
+ if (!server) throw noSuchServer(loaded, name);
782
+ return server;
783
+ }
784
+ async function loginServer(name, deps, opts) {
785
+ const ctx = requireServers(deps);
786
+ const server = await chosenServer(name, ctx, deps.signal);
787
+ const label = clean(server.name);
788
+ if (server.auth.type === "none") throw new Error(`${label} does not use credentials.`);
789
+ let entered;
790
+ if (opts.tokenStdin) entered = await abortable(ctx.readStdin(), deps.signal);
791
+ else if (ctx.stdinIsTTY ?? deps.isTTY) {
792
+ const what = server.auth.type === "bearer" ? "Token" : `Value for the ${clean(server.auth.name)} header`;
793
+ entered = await ctx.readSecret(`${what} for ${label}: `);
794
+ } else throw new Error("Re-run with --token-stdin to give the credential without a prompt.");
795
+ const secret = validateSecret(server, entered);
796
+ const refused = () => /* @__PURE__ */ new Error(`${label} refused these credentials. Nothing was saved.`);
797
+ const fetch = withSignal(serverFetch(server, secret, ctx.sshFetchFor), deps.signal);
798
+ const target = await abortable(resolveServerTarget(server, secret, fetch), deps.signal).catch((error) => {
799
+ const message = error instanceof Error ? error.message : String(error);
800
+ if (/refused the saved credentials|needs credentials/.test(message)) throw refused();
801
+ throw error;
802
+ });
803
+ try {
804
+ await abortable(target.runtime.list(), deps.signal);
805
+ } catch (error) {
806
+ if (error instanceof RuntimeHttpError && (error.status === 401 || error.status === 403)) throw refused();
807
+ throw error;
808
+ }
809
+ await ctx.saveSecret(server.id, secret);
810
+ deps.log(`Saved the credentials for ${label}; ${runtimeLabel(target)} answered.`);
811
+ return 0;
812
+ }
813
+ async function logoutServer(name, deps) {
814
+ const ctx = requireServers(deps);
815
+ const loaded = await abortable(ctx.load(), deps.signal);
816
+ const known = findModelServer(loaded.servers, name) ?? findModelServer(loaded.unusable ?? [], name);
817
+ const id = known?.id ?? (ctx.secret(name) !== void 0 ? name : null);
818
+ if (id === null) throw noSuchServer(loaded, name);
819
+ const label = clean(known?.name ?? name);
820
+ if (ctx.secret(id) === void 0) {
821
+ deps.log(`The CLI has no saved credentials for ${label}.`);
822
+ return 0;
823
+ }
824
+ await ctx.clearSecret(id);
825
+ deps.log(`Removed the CLI's saved credentials for ${label}. Desktop's copy is untouched.`);
826
+ return 0;
827
+ }
828
+ /** `--server`: the same command, run against one of Desktop's saved servers. */
829
+ async function onServer(name, subcommand, deps) {
830
+ const ctx = requireServers(deps);
831
+ const server = await chosenServer(name, ctx, deps.signal);
832
+ if (subcommand === "pull" || subcommand === "rm" || subcommand === "remove") requireManageable(server);
833
+ const secret = ctx.secret(server.id);
834
+ return {
835
+ ...deps,
836
+ resolveRuntime: () => abortable(resolveServerTarget(server, secret, serverFetch(server, secret, ctx.sshFetchFor)), deps.signal)
837
+ };
838
+ }
839
+ /**
840
+ * `servers discover <destination>`: the model servers on another machine's loopback, found over SSH. Saving one is
841
+ * Desktop's, since the CLI only reads Desktop's list.
842
+ */
843
+ async function discoverServers(destination, deps, opts) {
844
+ const problem = sshDestinationProblem(destination);
845
+ if (problem) throw new Error(problem);
846
+ const port = opts.port === void 0 ? void 0 : parseSshPort(opts.port);
847
+ if (port === null) throw new Error(SSH_PORT_PROBLEM);
848
+ const target = destination.trim();
849
+ const sshFetchFor = deps.servers?.sshFetchFor ?? createSshFetch;
850
+ if (!opts.json) deps.log(`Looking for model servers on ${clean(target)} (${port !== void 0 ? `port ${port}` : usualPorts()})`);
851
+ const result = await abortable(discoverSshServers({
852
+ destination: target,
853
+ ...port !== void 0 ? { port } : {},
854
+ now: () => performance.now(),
855
+ signal: deps.signal,
856
+ fetchFor: (farPort) => sshFetchFor({
857
+ destination: target,
858
+ port: farPort,
859
+ label: target,
860
+ app: "The CLI"
861
+ })
862
+ }), deps.signal);
863
+ if (opts.json) {
864
+ deps.log(JSON.stringify({
865
+ destination: target,
866
+ found: result.found,
867
+ error: result.error
868
+ }, null, 2));
869
+ return result.found.length > 0 ? 0 : 1;
870
+ }
871
+ if (result.found.length === 0) throw new Error(result.error ?? `Found no model server on ${target}.`);
872
+ const lines = table([[
873
+ "PORT",
874
+ "KIND",
875
+ "VERSION",
876
+ "MODELS",
877
+ "NOTE"
878
+ ], ...result.found.map((server) => [
879
+ String(server.port),
880
+ productLabel(server.kind, server.product),
881
+ clean(server.version ?? ""),
882
+ server.models === null ? "" : String(server.models),
883
+ server.needsCredentials ? "asks for an API key" : ""
884
+ ])]);
885
+ for (const line of lines) deps.log(line);
886
+ deps.log("");
887
+ deps.log(`To use one, add it in Desktop under Settings, Model servers: choose SSH and enter ${clean(target)}. The CLI then lists it in: b4m models servers`);
888
+ return 0;
889
+ }
890
+ function positional(value, usage) {
891
+ const text = (Array.isArray(value) ? value.join(" ") : value ?? "").trim();
892
+ if (!text) throw new Error(`Usage: ${usage}`);
893
+ return text;
894
+ }
895
+ async function runModelsCommand(subcommand, argv, deps) {
896
+ const opts = {
897
+ json: argv["output-format"] === "json",
898
+ yes: Boolean(argv.yes),
899
+ force: Boolean(argv.force),
900
+ acceptLicense: Boolean(argv["accept-license"]),
901
+ includeAbliterated: Boolean(argv["include-abliterated"]),
902
+ checkTools: Boolean(argv["check-tools"]),
903
+ refresh: Boolean(argv.refresh)
904
+ };
905
+ try {
906
+ if (argv.server !== void 0) {
907
+ const serverName = String(argv.server).trim();
908
+ if (!serverName) throw new Error("--server needs a server name (see: b4m models servers)");
909
+ if (![
910
+ "ls",
911
+ "list",
912
+ "use",
913
+ "pull",
914
+ "rm",
915
+ "remove"
916
+ ].includes(subcommand ?? "")) throw new Error("--server works with ls, use, pull and rm.");
917
+ deps = await onServer(serverName, subcommand ?? "", deps);
918
+ }
919
+ switch (subcommand) {
920
+ case "servers": {
921
+ if (argv.action === "discover") return await discoverServers(positional(argv.name, "b4m models servers discover <user@host> [--port N]"), deps, {
922
+ ...opts,
923
+ ...argv.port !== void 0 ? { port: argv.port } : {}
924
+ });
925
+ if (argv.port !== void 0) throw new Error("--port works only with: b4m models servers discover");
926
+ const name = () => positional(argv.name, `b4m models servers ${argv.action} <name>`);
927
+ if (argv.action === void 0) return await listServers(deps, opts);
928
+ if (argv.action === "login") return await loginServer(name(), deps, { tokenStdin: Boolean(argv["token-stdin"]) });
929
+ if (argv.action === "logout") return await logoutServer(name(), deps);
930
+ throw new Error(`Unknown servers action: ${clean(String(argv.action))}. Use discover, login or logout.`);
931
+ }
932
+ case "ls":
933
+ case "list": return await listModels(deps, opts);
934
+ case "search": return await searchModels(positional(argv.query, "b4m models search <query>"), deps, opts);
935
+ case "show": return await showModel(positional(argv.repo, "b4m models show <owner/repo>"), deps, opts);
936
+ case "curated": return await listCurated(deps, opts);
937
+ case "pull": {
938
+ const result = await pullModel(positional(argv.ref, "b4m models pull <ref | owner/repo[:quant]>"), deps, opts);
939
+ if (result === "declined") deps.log("Aborted");
940
+ return result === "cancelled" ? 130 : 0;
941
+ }
942
+ case "rm":
943
+ case "remove": return await removeModel(positional(argv.name, "b4m models rm <name>"), deps, opts);
944
+ case "use": return await useModel(positional(argv.name, "b4m models use <name>"), deps);
945
+ default: throw new Error(`Unknown models subcommand: ${subcommand ?? "(none)"}`);
946
+ }
947
+ } catch (error) {
948
+ if (error instanceof CancelledError || deps.signal.aborted) {
949
+ deps.log("Cancelled.");
950
+ return 130;
951
+ }
952
+ const refused = hubAccessMessage(error, () => deps.hub().endpoint);
953
+ if (refused) throw new Error(refused);
954
+ throw new Error(clean(error instanceof Error ? error.message : String(error)));
955
+ }
956
+ }
957
+ /** Resolves the answer; rejects with `CancelledError` on Ctrl-C at the prompt or when `signal` aborts. */
958
+ function confirmOnTerminal(question, signal, streams = {
959
+ input: process.stdin,
960
+ output: process.stdout
961
+ }) {
962
+ if (signal.aborted) return Promise.reject(new CancelledError());
963
+ const rl = createInterface({
964
+ input: streams.input,
965
+ output: streams.output
966
+ });
967
+ return new Promise((resolve, reject) => {
968
+ const cancel = () => {
969
+ streams.output.write("\n");
970
+ rl.close();
971
+ reject(new CancelledError());
972
+ };
973
+ const finish = (answer) => {
974
+ signal.removeEventListener("abort", cancel);
975
+ rl.close();
976
+ resolve(/^y(es)?$/i.test(answer.trim()));
977
+ };
978
+ rl.on("SIGINT", () => {
979
+ signal.removeEventListener("abort", cancel);
980
+ cancel();
981
+ });
982
+ signal.addEventListener("abort", cancel, { once: true });
983
+ rl.question(question, finish);
984
+ });
985
+ }
986
+ /** Reads one line without echoing it; the prompt goes to stderr so a piped stdout stays clean. */
987
+ function readSecretOnTerminal(prompt, signal, streams = {
988
+ input: process.stdin,
989
+ output: process.stderr
990
+ }) {
991
+ if (signal.aborted) return Promise.reject(new CancelledError());
992
+ let echo = true;
993
+ const muted = new Writable({ write(chunk, encoding, done) {
994
+ if (echo) streams.output.write(chunk, encoding);
995
+ done();
996
+ } });
997
+ const rl = createInterface({
998
+ input: streams.input,
999
+ output: muted,
1000
+ terminal: true
1001
+ });
1002
+ return new Promise((resolve, reject) => {
1003
+ const cancel = () => {
1004
+ streams.output.write("\n");
1005
+ rl.close();
1006
+ reject(new CancelledError());
1007
+ };
1008
+ rl.on("SIGINT", () => {
1009
+ signal.removeEventListener("abort", cancel);
1010
+ cancel();
1011
+ });
1012
+ signal.addEventListener("abort", cancel, { once: true });
1013
+ const onClose = () => {
1014
+ signal.removeEventListener("abort", cancel);
1015
+ reject(new CancelledError());
1016
+ };
1017
+ rl.once("close", onClose);
1018
+ rl.question(prompt, (answer) => {
1019
+ rl.off("close", onClose);
1020
+ signal.removeEventListener("abort", cancel);
1021
+ rl.close();
1022
+ streams.output.write("\n");
1023
+ resolve(answer);
1024
+ });
1025
+ echo = false;
1026
+ });
1027
+ }
1028
+ async function readAllStdin() {
1029
+ const chunks = [];
1030
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
1031
+ return Buffer.concat(chunks).toString("utf8");
1032
+ }
1033
+ async function handleModelsCommand(subcommand, argv) {
1034
+ const configStore = new ConfigStore();
1035
+ const config = await configStore.load();
1036
+ let credentials = { ...config.modelServerCredentials };
1037
+ const models = {
1038
+ defaultModel: config.defaultModel,
1039
+ ollamaHost: config.ollamaHost,
1040
+ save: async (patch) => {
1041
+ await configStore.update(patch);
1042
+ Object.assign(models, patch);
1043
+ }
1044
+ };
1045
+ const flagHost = argv["ollama-host"];
1046
+ if (flagHost === "" && models.ollamaHost) {
1047
+ await models.save({ ollamaHost: void 0 });
1048
+ console.error("Cleared the saved Ollama host.");
1049
+ }
1050
+ const controller = new AbortController();
1051
+ const onSigint = () => {
1052
+ if (controller.signal.aborted) process.exit(130);
1053
+ controller.abort();
1054
+ };
1055
+ process.on("SIGINT", onSigint);
1056
+ let hub;
1057
+ const curatedList = createCliCuratedList({ offline: Boolean(argv.offline) });
1058
+ try {
1059
+ return await runModelsCommand(subcommand, argv, {
1060
+ hub: () => hub ??= new HuggingFaceHub({ token: process.env.HF_TOKEN }),
1061
+ ollamaRegistry: (name, signal) => readOllamaManifest(name, signal),
1062
+ libraryLayers: (ref, signal) => ollamaLibraryLayers(ref, { signal }),
1063
+ resolveRuntime: async () => {
1064
+ const target = await resolveRuntimeTarget({
1065
+ flag: flagHost || void 0,
1066
+ env: process.env.B4M_OLLAMA_HOST,
1067
+ config: models.ollamaHost
1068
+ });
1069
+ if (target.source === "flag" && target.runtime.baseUrl !== models.ollamaHost) {
1070
+ await models.save({ ollamaHost: target.runtime.baseUrl });
1071
+ console.error(`Saved Ollama host ${target.runtime.baseUrl}`);
1072
+ }
1073
+ return target;
1074
+ },
1075
+ config: models,
1076
+ confirm: (question) => confirmOnTerminal(question, controller.signal),
1077
+ isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY),
1078
+ log: (line) => console.log(line),
1079
+ progress: {
1080
+ update: (line) => process.stdout.write(`\r\x1b[2K${line}`),
1081
+ end: () => process.stdout.write("\n")
1082
+ },
1083
+ machine: machineReader(),
1084
+ runtimeHost: () => {
1085
+ const host = flagHost || process.env.B4M_OLLAMA_HOST || models.ollamaHost;
1086
+ return host ? withDefaultOllamaPort(host) : null;
1087
+ },
1088
+ curated: () => curatedList.manifest(),
1089
+ curatedSource: curatedList,
1090
+ hardware: () => probeHardware(),
1091
+ servers: {
1092
+ load: () => loadModelServers(),
1093
+ secret: (id) => credentials[id]?.secret,
1094
+ saveSecret: async (id, secret) => {
1095
+ await configStore.setModelServerCredential(id, secret);
1096
+ credentials = {
1097
+ ...credentials,
1098
+ [id]: { secret }
1099
+ };
1100
+ },
1101
+ clearSecret: async (id) => {
1102
+ await configStore.clearModelServerCredential(id);
1103
+ const { [id]: removed, ...rest } = credentials;
1104
+ credentials = rest;
1105
+ },
1106
+ readSecret: (prompt) => readSecretOnTerminal(prompt, controller.signal),
1107
+ readStdin: readAllStdin,
1108
+ stdinIsTTY: Boolean(process.stdin.isTTY)
1109
+ },
1110
+ signal: controller.signal
1111
+ });
1112
+ } finally {
1113
+ process.off("SIGINT", onSigint);
1114
+ }
1115
+ }
1116
+ //#endregion
1117
+ export { EXIT_CANCELLED, confirmOnTerminal, discoverServers, handleModelsCommand, listCurated, listModels, listServers, loginServer, logoutServer, pullModel, readSecretOnTerminal, removeModel, runModelsCommand, searchModels, showModel, useModel };