@bike4mind/cli 4.0.0 → 4.6.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 (51) hide show
  1. package/README.md +86 -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--J3sgO_-.mjs} +3794 -1368
  6. package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-CdO4Gamg.mjs} +22 -3
  7. package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
  8. package/dist/ConfigStore-CausUCzY.mjs +2 -0
  9. package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
  10. package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-C1Wj6xla.mjs} +32672 -21643
  11. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  12. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
  13. package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
  14. package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
  15. package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
  16. package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
  17. package/dist/agents/defaults/review.md +8 -1
  18. package/dist/agents/defaults/test.md +8 -1
  19. package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
  20. package/dist/commands/acpCommand.mjs +25 -19
  21. package/dist/commands/apiCommand.mjs +3 -5
  22. package/dist/commands/doctorCommand.mjs +2 -2
  23. package/dist/commands/envCommand.mjs +1 -1
  24. package/dist/commands/headlessCommand.mjs +117 -36
  25. package/dist/commands/hostCommand.mjs +2344 -0
  26. package/dist/commands/mcpCommand.mjs +45 -30
  27. package/dist/commands/mirrorCommand.mjs +279 -0
  28. package/dist/commands/modelsCommand.mjs +1117 -0
  29. package/dist/commands/pluginCommand.mjs +9 -9
  30. package/dist/commands/skillsCommand.mjs +174 -29
  31. package/dist/commands/updateCommand.mjs +2 -2
  32. package/dist/curated-build.json +1 -0
  33. package/dist/dist-CbViwiS9.mjs +4739 -0
  34. package/dist/dist-Citbv0y0.mjs +7864 -0
  35. package/dist/fit-CVWDiavv.mjs +200 -0
  36. package/dist/index.mjs +853 -417
  37. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  38. package/dist/modelServers-BaegigV-.mjs +2465 -0
  39. package/dist/{package-CQaam4Dq.mjs → package-C9pfAdGF.mjs} +1 -1
  40. package/dist/{serve-CFxUhjml.mjs → serve-8wyGb8of.mjs} +595 -26
  41. package/dist/types-BFIvwByC.mjs +2 -0
  42. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  43. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
  44. package/package.json +16 -13
  45. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  46. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  47. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  48. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  49. package/dist/buildToolSearch-D9GEK91u.mjs +0 -2351
  50. package/dist/dist-Ul2qwn5x.mjs +0 -624
  51. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -0,0 +1,2465 @@
1
+ #!/usr/bin/env node
2
+ import { D as sanitizeTerminalText } from "./ConfigStore-Dusy6glb.mjs";
3
+ import { C as trackChild, H as isPermissiveEntry, K as ollamaModelKey, L as findHubBuild, O as curatedBuildForRef, Q as PullIdleTimeoutError, R as hubBuildTag, S as signalTree, T as HUGGING_FACE_SSH_KEYS_URL, V as isHubRepoId, Y as HubAccessError, Z as ModelNotFoundError, b as lmStudioModelsSchema, c as checkReviewedLayers, d as detectRuntimes, et as parseBaseUrl, f as licensesChanged, i as OllamaRuntime, k as curatedEntryForRef, l as checkRuntime, p as manifestChange, s as checkInstalledDigest, x as productFromOwner, y as OpenAICompatibleRuntime, z as isAbliteratedModel } from "./dist-Citbv0y0.mjs";
4
+ import { createHash } from "crypto";
5
+ import path from "node:path";
6
+ import { z as z$1 } from "zod";
7
+ import nodeOs from "node:os";
8
+ import { chmod, mkdir, readFile, stat } from "node:fs/promises";
9
+ import { Duplex, Readable } from "node:stream";
10
+ import { spawn } from "node:child_process";
11
+ import { isIP } from "node:net";
12
+ import http from "node:http";
13
+ import dns from "node:dns";
14
+ import https from "node:https";
15
+ //#region src/utils/ollamaHost.ts
16
+ const DEFAULT_OLLAMA_PORT = 11434;
17
+ /**
18
+ * Gives a scheme-less host Ollama's default port and `http://`, so `gpu-box` means `http://gpu-box:11434`.
19
+ * Hosts with a scheme pass through unchanged.
20
+ */
21
+ function withDefaultOllamaPort(host) {
22
+ const trimmed = host.trim();
23
+ if (!trimmed || /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) return trimmed;
24
+ const slash = trimmed.indexOf("/");
25
+ const authority = slash === -1 ? trimmed : trimmed.slice(0, slash);
26
+ const path = slash === -1 ? "" : trimmed.slice(slash);
27
+ return `http://${authority}${/^\[[^\]]*\]:\d+$/.test(authority) || /^[^[\]:]+:\d+$/.test(authority) ? "" : `:${DEFAULT_OLLAMA_PORT}`}${path}`;
28
+ }
29
+ //#endregion
30
+ //#region src/commands/ollamaRegistry.ts
31
+ /**
32
+ * Reads an Ollama registry manifest before a pull: total download size and the license texts the model ships
33
+ * with, so `b4m models pull <name>` can show both and ask before anything downloads.
34
+ */
35
+ const OLLAMA_REGISTRY = "https://registry.ollama.ai";
36
+ /** Hosts a pull ref may name for Ollama's registry; `ollama.com` names resolve against the same registry. */
37
+ const OLLAMA_REGISTRY_HOSTS = /* @__PURE__ */ new Set(["registry.ollama.ai", "ollama.com"]);
38
+ const MANIFEST_ACCEPT = "application/vnd.docker.distribution.manifest.v2+json";
39
+ const LICENSE_LAYER = "application/vnd.ollama.image.license";
40
+ const MAX_LICENSE_BYTES = 262144;
41
+ const REQUEST_TIMEOUT_MS = 15e3;
42
+ const NAME_PART_RE = /^[A-Za-z0-9][\w.-]{0,127}$/;
43
+ const manifestSchema = z$1.object({ layers: z$1.array(z$1.object({
44
+ mediaType: z$1.string(),
45
+ digest: z$1.string().regex(/^sha256:[0-9a-f]{64}$/),
46
+ size: z$1.number().nonnegative()
47
+ })) });
48
+ /** `[namespace/]model[:tag]`, without a registry host. */
49
+ function parseOllamaName(name) {
50
+ const parts = name.split("/");
51
+ if (parts.length > 2) throw new Error(`Not an Ollama model name: ${name}`);
52
+ const [namespace, rest] = parts.length === 2 ? parts : ["library", parts[0]];
53
+ const colon = rest.indexOf(":");
54
+ const model = colon === -1 ? rest : rest.slice(0, colon);
55
+ const tag = colon === -1 ? "latest" : rest.slice(colon + 1);
56
+ if (![
57
+ namespace,
58
+ model,
59
+ tag
60
+ ].every((part) => NAME_PART_RE.test(part))) throw new Error(`Not an Ollama model name: ${name}`);
61
+ return {
62
+ namespace,
63
+ model,
64
+ tag,
65
+ page: namespace === "library" ? `https://ollama.com/library/${model}` : `https://ollama.com/${namespace}/${model}`
66
+ };
67
+ }
68
+ async function readOllamaManifest(name, signal, fetchImpl = fetch) {
69
+ const { namespace, model, tag } = parseOllamaName(name);
70
+ const base = `${OLLAMA_REGISTRY}/v2/${namespace}/${model}`;
71
+ const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
72
+ const response = await fetchImpl(`${base}/manifests/${tag}`, {
73
+ headers: { accept: MANIFEST_ACCEPT },
74
+ signal: requestSignal
75
+ });
76
+ if (response.status === 404) throw new Error(`The Ollama registry has no model named ${name}.`);
77
+ if (!response.ok) throw new Error(`The Ollama registry answered ${response.status} for ${name}.`);
78
+ const body = await response.text();
79
+ let json = null;
80
+ try {
81
+ json = JSON.parse(body);
82
+ } catch {}
83
+ const parsed = manifestSchema.safeParse(json);
84
+ if (!parsed.success) throw new Error(`The Ollama registry sent an unreadable manifest for ${name}.`);
85
+ const { layers } = parsed.data;
86
+ const licenseLayers = layers.filter((layer) => layer.mediaType === LICENSE_LAYER);
87
+ const licenses = await Promise.all(licenseLayers.filter((layer, index) => licenseLayers.findIndex((other) => other.digest === layer.digest) === index).map(async (layer) => {
88
+ if (layer.size > MAX_LICENSE_BYTES) return "";
89
+ const blob = await fetchImpl(`${base}/blobs/${layer.digest}`, { signal: requestSignal });
90
+ if (!blob.ok) throw new Error(`The Ollama registry answered ${blob.status} for ${name}'s license.`);
91
+ return (await blob.text()).slice(0, MAX_LICENSE_BYTES);
92
+ }));
93
+ return {
94
+ digest: `sha256:${createHash("sha256").update(body).digest("hex")}`,
95
+ layers: layers.map((layer) => layer.digest),
96
+ sizeBytes: layers.reduce((sum, layer) => sum + layer.size, 0),
97
+ licenses
98
+ };
99
+ }
100
+ /** Whitespace, markdown emphasis and quote style do not change a license's words. */
101
+ function normalize(text) {
102
+ return text.replace(/[*"\u{201c}\u{201d}]/gu, "").replace(/\s+/g, " ").trim();
103
+ }
104
+ const APACHE_END = "END OF TERMS AND CONDITIONS";
105
+ const APACHE_TERMS_SHA256 = "208c068632b160d0955a8259f36f232f5bd61792d051af42f9942706efe4ddae";
106
+ const COPYRIGHT_PLACEHOLDER = "Copyright [yyyy] [name of copyright owner]";
107
+ const APACHE_APPENDIX = `APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets [] replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same printed page as the copyright notice for easier identification within third-party archives. ${COPYRIGHT_PLACEHOLDER} Licensed under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.`;
108
+ const MIT_START = "Permission is hereby granted";
109
+ const MIT_BODY = "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.";
110
+ const COPYRIGHT_RE = /^copyright\s+(?:\(c\)\s*|\u{a9}\s*)?(?:\d{4}(?:\s*-\s*\d{4})?,?\s*)*(.{1,100})$/iu;
111
+ const NOT_A_NAME = /\b(?:may|must|shall|not|only|use[ds]?|using|commercial|prohibited|licen[cs]e[ds]?|permission|agree\w*|restrict\w*|terms?)\b|\.\s+\S/i;
112
+ function isCopyrightLine(line) {
113
+ const holder = COPYRIGHT_RE.exec(line.trim())?.[1].replace(/\s*All rights reserved\.?$/i, "");
114
+ return holder !== void 0 && /^[\x20-\x7e]+$/.test(holder) && !NOT_A_NAME.test(holder);
115
+ }
116
+ function isApache(text) {
117
+ const end = text.indexOf(APACHE_END);
118
+ if (end === -1) return false;
119
+ const terms = normalize(text.slice(0, end + 27));
120
+ if (createHash("sha256").update(terms).digest("hex") !== APACHE_TERMS_SHA256) return false;
121
+ const appendix = text.slice(end + 27);
122
+ if (normalize(appendix) === "") return true;
123
+ const copyright = /^[ \t]*(Copyright\b.*)$/im.exec(appendix);
124
+ if (!copyright || !isCopyrightLine(copyright[1])) return false;
125
+ return normalize(appendix.replace(copyright[0], COPYRIGHT_PLACEHOLDER)) === APACHE_APPENDIX;
126
+ }
127
+ /** The MIT body, preceded only by a title, copyright lines and a name that those copyright lines carry. */
128
+ function isMit(text) {
129
+ const start = text.indexOf(MIT_START);
130
+ if (start === -1 || normalize(text.slice(start)) !== MIT_BODY) return false;
131
+ const preamble = text.slice(0, start).split("\n").map((line) => line.trim()).filter(Boolean);
132
+ const words = (line) => line.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
133
+ const holderWords = new Set(preamble.filter(isCopyrightLine).flatMap(words));
134
+ return preamble.length <= 6 && preamble.every((line) => /^(?:the )?mit license(?: \(mit\))?$/i.test(line) || isCopyrightLine(line) || /^[\x20-\x7e]+$/.test(line) && words(line).length > 0 && words(line).every((word) => holderWords.has(word)));
135
+ }
136
+ function titleOf(text) {
137
+ const line = text.split("\n").map((entry) => entry.replace(/[*#]/g, "").replace(/\s+/g, " ").replace(/^[\s=_-]+|[\s=_-]+$/g, "")).find(Boolean);
138
+ return line ? line.slice(0, 80) : "license text not shown";
139
+ }
140
+ /**
141
+ * Permissive only when every license text is the Apache-2.0 or MIT template, allowing nothing beyond the copyright
142
+ * and name lines the templates have; any other text, or a template with added terms, is restricted.
143
+ */
144
+ function classifyLicenses(texts) {
145
+ const unique = [...new Set(texts)];
146
+ const matched = unique.map((text) => isApache(text) ? "Apache-2.0" : isMit(text) ? "MIT" : null);
147
+ const titles = [...new Set(unique.map((text, index) => matched[index] ?? titleOf(text)))];
148
+ return {
149
+ title: titles.length > 0 ? titles.join(" + ") : "none declared",
150
+ permissive: unique.length > 0 && matched.every(Boolean)
151
+ };
152
+ }
153
+ //#endregion
154
+ //#region src/models/localModels.ts
155
+ /**
156
+ * Local model logic shared by `b4m models` (src/commands/modelsCommand.ts) and the MCP model tools
157
+ * (src/mcp/modelTools.ts): ref parsing, runtime resolution, build and license checks, and pull planning.
158
+ * Each surface does its own output and asks the user its own way. The pull checks shared with Desktop and the
159
+ * model host live in @bike4mind/local-models (src/pulls); this file words their refusals for the terminal.
160
+ */
161
+ const NOT_RECOMMENDED_LABEL = "abliterated or uncensored build";
162
+ function hiddenAbliteratedMessage(count) {
163
+ return `${count} abliterated or uncensored ${count === 1 ? "build was" : "builds were"} left out.`;
164
+ }
165
+ /** Drops abliterated builds unless asked for; the ones kept go after every other hit and are flagged. */
166
+ function rankSearchHits(models, includeAbliterated) {
167
+ const flagged = models.filter(isAbliteratedModel);
168
+ return {
169
+ hits: [...models.filter((model) => !isAbliteratedModel(model)), ...includeAbliterated ? flagged.map((model) => ({
170
+ ...model,
171
+ notRecommended: NOT_RECOMMENDED_LABEL
172
+ })) : []],
173
+ hidden: includeAbliterated ? 0 : flagged.length
174
+ };
175
+ }
176
+ /** The licenses to accept, by name; `label` stays the source's own, which the pre-download recheck compares. */
177
+ function licenseName(license) {
178
+ const own = license.listed ?? license.label;
179
+ return license.base ? `${own} and base model ${license.base}` : own;
180
+ }
181
+ /** Ctrl-C at a prompt or while waiting on the runtime. */
182
+ var CancelledError = class extends Error {
183
+ constructor() {
184
+ super("Cancelled.");
185
+ this.name = "CancelledError";
186
+ }
187
+ };
188
+ /** Settles with `promise`, or rejects with `CancelledError` as soon as `signal` aborts. */
189
+ function abortable(promise, signal) {
190
+ if (signal.aborted) {
191
+ promise.catch(() => void 0);
192
+ return Promise.reject(new CancelledError());
193
+ }
194
+ return new Promise((resolve, reject) => {
195
+ const onAbort = () => reject(new CancelledError());
196
+ signal.addEventListener("abort", onAbort, { once: true });
197
+ promise.then((value) => {
198
+ signal.removeEventListener("abort", onAbort);
199
+ resolve(value);
200
+ }, (error) => {
201
+ signal.removeEventListener("abort", onAbort);
202
+ reject(error);
203
+ });
204
+ });
205
+ }
206
+ const DEFAULT_QUANT = "Q4_K_M";
207
+ const NO_LICENSE = "none declared";
208
+ const HF_HOSTS = /* @__PURE__ */ new Set(["hf.co", "huggingface.co"]);
209
+ const PERMISSIVE_LICENSES = /* @__PURE__ */ new Set([
210
+ "0bsd",
211
+ "apache-2.0",
212
+ "bsd",
213
+ "bsd-2-clause",
214
+ "bsd-3-clause",
215
+ "bsd-3-clause-clear",
216
+ "bsl-1.0",
217
+ "cc0-1.0",
218
+ "isc",
219
+ "mit",
220
+ "unlicense",
221
+ "zlib"
222
+ ]);
223
+ const REF_ISSUES = {
224
+ split: "split into shards, which Ollama cannot pull",
225
+ incomplete: "some shards are missing",
226
+ "no-quant-label": "the file name has no quant label",
227
+ "unsupported-quant": "Ollama cannot pull this quant from Hugging Face",
228
+ "unsupported-name": "Ollama does not accept this repo or file name",
229
+ "pinned-revision": "not on the main branch",
230
+ ambiguous: "an earlier file answers the same tag; pull asks the registry"
231
+ };
232
+ const UNPULLABLE = /* @__PURE__ */ new Set([
233
+ "split",
234
+ "incomplete",
235
+ "no-quant-label",
236
+ "unsupported-quant",
237
+ "unsupported-name",
238
+ "pinned-revision"
239
+ ]);
240
+ const clean = (text) => sanitizeTerminalText(text ?? "");
241
+ function formatBytes(bytes) {
242
+ if (bytes === null) return "-";
243
+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
244
+ if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`;
245
+ if (bytes >= 1e3) return `${Math.round(bytes / 1e3)} KB`;
246
+ return `${bytes} B`;
247
+ }
248
+ function runtimeLabel({ runtime, source, server }) {
249
+ return `${runtime.kind === "ollama" ? "Ollama" : "OpenAI-compatible server"}${server ? ` "${clean(server.name)}"` : ""} at ${runtime.baseUrl}${source === "detected" ? " (detected)" : ""}`;
250
+ }
251
+ /** Permissive only when at least one license is declared and every one is. */
252
+ function licenseFor(detail, endpoint) {
253
+ const ids = detail.licenses.map((license) => license.toLowerCase());
254
+ const names = ids.map((id) => id === "other" ? detail.licenseName ?? id : id);
255
+ const label = names.length > 0 ? names.join(", ") : NO_LICENSE;
256
+ const raw = detail.licenseLink;
257
+ const link = !raw ? `${endpoint}/${detail.id}` : /^https?:\/\//i.test(raw) ? raw : `${endpoint}/${detail.id}/blob/main/${raw.replace(/^\.?\//, "")}`;
258
+ return {
259
+ label: clean(label),
260
+ link: clean(link),
261
+ restricted: ids.length === 0 || !ids.every((id) => PERMISSIVE_LICENSES.has(id)),
262
+ plural: ids.length > 1
263
+ };
264
+ }
265
+ function gatedMessage(repo, endpoint) {
266
+ return [
267
+ `${repo} is gated: the Hugging Face account must be granted access before anything can be downloaded.`,
268
+ ` 1. Request access at ${endpoint}/${repo}`,
269
+ " 2. Set HF_TOKEN to a token of that account",
270
+ ` 3. Add your Ollama public key (~/.ollama/id_ed25519.pub) at ${HUGGING_FACE_SSH_KEYS_URL}, so Ollama's own download is allowed`
271
+ ].join("\n");
272
+ }
273
+ /** The message for a Hugging Face access refusal, or null for any other error. */
274
+ function hubAccessMessage(error, endpoint) {
275
+ if (!(error instanceof HubAccessError)) return null;
276
+ if (error.reason === "gated") return gatedMessage(clean(error.repo), endpoint());
277
+ return `Hugging Face refused ${clean(error.repo)}: check that HF_TOKEN is valid and can read it.`;
278
+ }
279
+ /** `www.`, a port and a trailing dot do not change which registry a host names. */
280
+ function registryHost(authority) {
281
+ const match = /^([^@:]+)(?::\d+)?$/.exec(authority);
282
+ if (!match) return null;
283
+ return match[1].toLowerCase().replace(/\.+$/, "").replace(/^www\./, "");
284
+ }
285
+ /**
286
+ * `owner/repo[:tag]` and Hugging Face URLs (any of its host spellings) are Hugging Face repos; `model[:tag]` and
287
+ * names on Ollama's own registry are Ollama names. Any other host is refused, so no spelling skips the checks.
288
+ */
289
+ function parsePullTarget(input) {
290
+ const trimmed = input.trim();
291
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(trimmed);
292
+ if (scheme && !/^https?$/i.test(scheme[1])) throw new Error(`Unsupported model ref: ${input}`);
293
+ const afterScheme = scheme ? trimmed.slice(scheme[0].length) : trimmed;
294
+ const slash = afterScheme.indexOf("/");
295
+ const first = slash === -1 ? afterScheme : afterScheme.slice(0, slash);
296
+ const namesHost = scheme !== null || slash !== -1 && /[.:@]/.test(first);
297
+ const host = namesHost ? registryHost(first) : null;
298
+ if (namesHost && !host) throw new Error(`Unsupported model ref: ${input}`);
299
+ const rest = host ? slash === -1 ? "" : afterScheme.slice(slash + 1) : afterScheme;
300
+ if (host && OLLAMA_REGISTRY_HOSTS.has(host)) {
301
+ const name = rest.replace(/^library\//i, "");
302
+ if (!name) throw new Error(`Not an Ollama model name: ${input}`);
303
+ return {
304
+ kind: "ollama",
305
+ name
306
+ };
307
+ }
308
+ if (host && !HF_HOSTS.has(host)) throw new Error(`Unsupported registry ${host} in ${input}. Pull from Hugging Face (owner/repo[:quant]) or Ollama (model[:tag]).`);
309
+ const colon = rest.lastIndexOf(":");
310
+ const hasTag = colon > rest.lastIndexOf("/");
311
+ const path = hasTag ? rest.slice(0, colon) : rest;
312
+ const tag = hasTag ? rest.slice(colon + 1) : null;
313
+ const segments = path.split("/");
314
+ if (!host && segments.length === 1) return {
315
+ kind: "ollama",
316
+ name: rest
317
+ };
318
+ if (!isHubRepoId(path) || tag === "") throw new Error(`Not a Hugging Face repo: ${input} (expected owner/name[:quant])`);
319
+ return {
320
+ kind: "hub",
321
+ repo: path,
322
+ tag
323
+ };
324
+ }
325
+ /** The build the tag names, as `findHubBuild` resolves it; no tag or `latest` means Q4_K_M. */
326
+ function pickBuild(builds, tag) {
327
+ return findHubBuild(builds, tag && tag.toLowerCase() !== "latest" ? tag : DEFAULT_QUANT);
328
+ }
329
+ /** The tag `pickBuild` resolves back to `build`. */
330
+ const buildTag = hubBuildTag;
331
+ async function resolveRuntimeTarget(hosts, detect = () => detectRuntimes(), createOllama = (baseUrl) => new OllamaRuntime({ baseUrl })) {
332
+ const chosen = [
333
+ ["flag", hosts.flag],
334
+ ["env", hosts.env],
335
+ ["config", hosts.config]
336
+ ].find(([, host]) => host);
337
+ if (chosen?.[1]) {
338
+ const runtime = createOllama(withDefaultOllamaPort(chosen[1]));
339
+ const health = await runtime.health();
340
+ if (!health.ok) throw new Error(`Ollama at ${runtime.baseUrl} is unreachable: ${health.error}`);
341
+ return {
342
+ runtime,
343
+ source: chosen[0]
344
+ };
345
+ }
346
+ const detected = (await detect()).filter((entry) => entry.health.ok);
347
+ const pick = detected.find((entry) => entry.runtime.kind === "ollama") ?? detected[0];
348
+ if (!pick) throw new Error("No local model runtime found. Start Ollama (https://ollama.com/download), or point the CLI at one with: b4m models ls --ollama-host http://<host>:11434");
349
+ return {
350
+ runtime: pick.runtime,
351
+ source: "detected"
352
+ };
353
+ }
354
+ async function listInstalled(runtime, defaultModel, signal) {
355
+ const [models, loaded] = await abortable(Promise.all([runtime.list(), runtime.capabilities.reportsLoaded ? runtime.loaded() : Promise.resolve([])]), signal);
356
+ const loadedNames = new Set(loaded.map((model) => model.name));
357
+ return models.map((model) => ({
358
+ ...model,
359
+ loaded: loadedNames.has(model.name),
360
+ default: !!defaultModel && sameModelName(model.name, defaultModel)
361
+ }));
362
+ }
363
+ function normalizeModelName(name) {
364
+ const withoutLibrary = name.replace(/^library\//i, "");
365
+ return withoutLibrary.lastIndexOf(":") > withoutLibrary.lastIndexOf("/") ? withoutLibrary : `${withoutLibrary}:latest`;
366
+ }
367
+ /** Whether two names are one model, counting hf.co and huggingface.co as the same Hugging Face repo. */
368
+ function sameModelName(a, b) {
369
+ return ollamaModelKey(normalizeModelName(a)) === ollamaModelKey(normalizeModelName(b));
370
+ }
371
+ function findInstalledModel(models, name) {
372
+ const wanted = name.replace(/^library\//i, "");
373
+ return models.find((model) => model.name === name || model.name === wanted) ?? models.find((model) => model.name === `${wanted}:latest`) ?? models.find((model) => sameModelName(model.name, name));
374
+ }
375
+ function requireRemovable(target) {
376
+ if (!target.runtime.capabilities.canRemove) throw new Error(`${runtimeLabel(target)} cannot remove models.`);
377
+ }
378
+ async function removeInstalled(target, name, signal) {
379
+ try {
380
+ await abortable(target.runtime.remove(name), signal);
381
+ } catch (error) {
382
+ if (error instanceof ModelNotFoundError) throw new Error(`No model named ${clean(name)} on ${runtimeLabel(target)}.`);
383
+ throw error;
384
+ }
385
+ }
386
+ async function requirePullable(deps) {
387
+ const target = await abortable(deps.resolveRuntime(), deps.signal);
388
+ if (!target.runtime.capabilities.canPull) throw new Error(`${runtimeLabel(target)} cannot download models.`);
389
+ return target;
390
+ }
391
+ async function readRegistry(name, deps) {
392
+ try {
393
+ return await abortable(deps.ollamaRegistry(name, deps.signal), deps.signal);
394
+ } catch (error) {
395
+ if (error instanceof CancelledError || deps.signal.aborted) throw new CancelledError();
396
+ const reason = error instanceof Error ? error.message : String(error);
397
+ throw new Error(`Could not read ${name} from the Ollama registry, so nothing was downloaded: ${reason}`);
398
+ }
399
+ }
400
+ /** The first 12 hex digits, the length Ollama shows digests at. */
401
+ function shortDigest(digest) {
402
+ return digest.replace(/^sha256:/, "").slice(0, 12);
403
+ }
404
+ function changedSinceReview(subject, what) {
405
+ return /* @__PURE__ */ new Error(`${subject} changed since you reviewed it (${what}), so nothing was downloaded. Pull it again to review the new version.`);
406
+ }
407
+ /**
408
+ * Re-reads the manifest after the user approved it, because Ollama then pulls by tag and a tag can move.
409
+ * Refuses when the license texts or layers differ from the ones shown.
410
+ */
411
+ async function requireUnchangedManifest(name, shown, deps) {
412
+ const now = await readRegistry(name, deps);
413
+ const change = manifestChange(shown, now);
414
+ if (change === "licenses") throw changedSinceReview(clean(name), "its license text changed");
415
+ if (change === "layers") throw changedSinceReview(clean(name), `the registry now serves ${shortDigest(now.digest)}`);
416
+ }
417
+ /** Re-reads the repo after the user approved it and refuses when its declared licenses differ from the ones shown. */
418
+ async function requireUnchangedLicenses(hub, detail, shown, signal) {
419
+ const currentDetail = await hub.getModel(detail.id, {
420
+ signal,
421
+ refresh: true
422
+ });
423
+ const now = licenseFor(currentDetail, hub.endpoint);
424
+ const reviewed = licenseFor({
425
+ ...currentDetail,
426
+ licenses: detail.licenses
427
+ }, hub.endpoint);
428
+ if (licensesChanged(detail.licenses, currentDetail.licenses) || reviewed.label !== shown.label || reviewed.link !== shown.link) throw changedSinceReview(clean(detail.id), `its license is now ${now.label}`);
429
+ }
430
+ async function planOllamaPull(name, deps) {
431
+ const { page } = parseOllamaName(name);
432
+ const target = await requirePullable(deps);
433
+ const manifest = deps.curated ? await abortable(Promise.resolve(deps.curated()), deps.signal) : void 0;
434
+ const curated = manifest ? curatedBuildForRef(manifest, name) : null;
435
+ await requireCuratedRuntime(target, curated, deps.signal);
436
+ const registry = await readRegistry(name, deps);
437
+ const license = classifyLicenses(registry.licenses);
438
+ return {
439
+ kind: "ollama",
440
+ target,
441
+ curated,
442
+ name,
443
+ manifest: registry,
444
+ license: withCuratedLicense({
445
+ label: clean(license.title),
446
+ link: page,
447
+ restricted: !license.permissive
448
+ }, name, manifest)
449
+ };
450
+ }
451
+ /** Refuses a curated build the target's Ollama is too old for, as Desktop does; nothing has downloaded yet. */
452
+ async function requireCuratedRuntime(target, curated, signal) {
453
+ if (!curated?.build.runtimeMin?.ollama) return;
454
+ const health = await abortable(target.runtime.health(), signal);
455
+ const name = clean(curated.entry.name);
456
+ const checked = checkRuntime(health, curated.build);
457
+ if (checked.ok) return;
458
+ if (checked.reason === "runtime-unreachable") throw new Error(`Could not read the version of ${runtimeLabel(target)} (${clean(checked.error ?? "no reply")}), which ${name} needs to be ${curated.build.runtimeMin.ollama} or newer, so nothing was downloaded.`);
459
+ throw new Error(`${checked.blocked} for ${name}, so nothing was downloaded. Update ${runtimeLabel(target)}, then pull it again.`);
460
+ }
461
+ /**
462
+ * A curated ref is restricted when the list records its own or its base model's license as not permissive. Every
463
+ * entry counts, so a fine-tune Curated does not offer still carries the base license the list records for it.
464
+ */
465
+ function withCuratedLicense(license, ref, manifest) {
466
+ const entry = manifest && curatedEntryForRef(manifest, ref);
467
+ if (!entry) return license;
468
+ const base = entry.license.base.class === "permissive" ? void 0 : clean(entry.license.base.id);
469
+ const listed = !license.restricted && entry.license.class !== "permissive" ? clean(entry.license.id) : void 0;
470
+ return {
471
+ ...license,
472
+ restricted: license.restricted || !isPermissiveEntry(entry),
473
+ ...base && {
474
+ base,
475
+ plural: true
476
+ },
477
+ ...listed && { listed }
478
+ };
479
+ }
480
+ /**
481
+ * Everything to show and check before a pull, read without downloading: the build, its size, every declared
482
+ * license, and the runtime it goes to. Throws for gated repos, missing or unpullable builds, and other hosts.
483
+ * `pullCommand` names how to retry with a quant in the no-such-build error.
484
+ */
485
+ async function planPull(input, deps, pullCommand = "b4m models pull") {
486
+ const parsed = parsePullTarget(input);
487
+ if (parsed.kind === "ollama") return planOllamaPull(parsed.name, deps);
488
+ const hub = deps.hub();
489
+ let detail = await hub.getModel(parsed.repo, { signal: deps.signal });
490
+ if (detail.gated && detail.canDownload !== true) detail = await hub.getModel(parsed.repo, {
491
+ signal: deps.signal,
492
+ refresh: true
493
+ });
494
+ const id = clean(detail.id);
495
+ if (detail.gated && detail.canDownload !== true) throw new Error(gatedMessage(id, hub.endpoint));
496
+ const build = pickBuild(detail.builds, parsed.tag);
497
+ if (!build) {
498
+ const tags = detail.builds.map((entry) => clean(buildTag(entry)));
499
+ throw new Error(tags.length === 0 ? `${id} has no GGUF builds.` : `${id} has no ${clean(parsed.tag ?? "Q4_K_M")} build. Pick one of: ${tags.join(", ")} (${pullCommand} ${id}:<BUILD>)`);
500
+ }
501
+ if (build.ollamaRefIssue && UNPULLABLE.has(build.ollamaRefIssue)) throw new Error(`Ollama cannot pull ${id} ${clean(build.label)}: ${REF_ISSUES[build.ollamaRefIssue]}.`);
502
+ const target = await requirePullable(deps);
503
+ const ref = `hf.co/${detail.id}:${build.quant}`;
504
+ const manifest = deps.curated ? await abortable(Promise.resolve(deps.curated()), deps.signal) : void 0;
505
+ const curated = manifest ? curatedBuildForRef(manifest, ref) : null;
506
+ await requireCuratedRuntime(target, curated, deps.signal);
507
+ return {
508
+ kind: "hub",
509
+ target,
510
+ curated,
511
+ hub,
512
+ detail,
513
+ build,
514
+ id,
515
+ license: withCuratedLicense(licenseFor(detail, hub.endpoint), ref, manifest),
516
+ projectorBytes: largestProjectorBytes(detail)
517
+ };
518
+ }
519
+ const LAYERS_CHANGED = "This model's weights, chat template, settings or license changed at its source since Bike4Mind reviewed it";
520
+ /**
521
+ * Refuses a curated build unless the registry serves its reviewed weights and exactly its pinned other layers.
522
+ * `ref` is the name Ollama pulls; for a Hugging Face build its tag names the file.
523
+ */
524
+ async function requireReviewedLayers(curated, ref, sources) {
525
+ const { signal } = sources;
526
+ const checked = await abortable(checkReviewedLayers(curated.build, ref.slice(ref.lastIndexOf(":") + 1), {
527
+ libraryLayers: (libraryRef) => sources.libraryLayers(libraryRef, signal),
528
+ hfLayers: (repo, tag) => sources.hub().ollamaLayers(repo, tag, { signal })
529
+ }, signal), signal);
530
+ if (checked.ok) return;
531
+ if (checked.reason === "layers-changed") throw new Error(`${LAYERS_CHANGED}, so nothing was downloaded.`);
532
+ throw new Error(`The registry no longer serves ${clean(ref)} as Bike4Mind reviewed it, so nothing was downloaded.`);
533
+ }
534
+ /** Cancelling after the download, during the reviewed-build check, leaves the model installed but unchecked. */
535
+ function installedUncheckedMessage(ref) {
536
+ const name = clean(ref);
537
+ return `Cancelled while checking ${name} against the reviewed build. It is still installed; remove it with \`b4m models rm ${name}\` unless you trust it.`;
538
+ }
539
+ /** Whether `ref` is installed before a pull; null when the runtime could not say. */
540
+ async function hadTagBefore(target, ref, signal) {
541
+ try {
542
+ return !!findInstalledModel(await abortable(target.runtime.list(), signal), ref);
543
+ } catch (error) {
544
+ if (signal.aborted) throw error;
545
+ return null;
546
+ }
547
+ }
548
+ const CHECK_TIMEOUT_MS = 3e4;
549
+ /**
550
+ * After a curated pull: throws unless Ollama installed the reviewed build. What it did install is removed only when
551
+ * the tag was definitely absent before (`hadTag` false), since a tag the user already had is theirs.
552
+ */
553
+ async function requireInstalledReviewed(target, curated, ref, hadTag, signal) {
554
+ const name = clean(ref);
555
+ let inspection;
556
+ try {
557
+ inspection = await abortable(target.runtime.inspect(ref, {
558
+ tags: false,
559
+ signal,
560
+ timeoutMs: CHECK_TIMEOUT_MS
561
+ }), signal);
562
+ } catch (error) {
563
+ if (signal.aborted) throw error;
564
+ const reason = clean(error instanceof Error ? error.message : String(error));
565
+ throw new Error(`Ollama could not describe ${name} after downloading it (${reason}), so it was not checked against the reviewed build. It is still installed; remove it with \`b4m models rm ${name}\` unless you trust it.`);
566
+ }
567
+ const checked = await checkInstalledDigest(inspection, curated.build, {
568
+ hadTag,
569
+ remove: () => target.runtime.remove(ref)
570
+ });
571
+ if (checked.ok) return;
572
+ if (checked.outcome === "left-in-place") throw new Error(`${LAYERS_CHANGED}. ${name} ${checked.hadTag ? "was installed before this download" : "may have been installed before this download"}, so it was left in place.`);
573
+ if (checked.outcome === "remove-failed") throw new Error(`${LAYERS_CHANGED}, and removing it failed. Remove it with \`b4m models rm ${name}\`.`);
574
+ throw new Error(`${LAYERS_CHANGED}, so what Ollama downloaded was removed.`);
575
+ }
576
+ /** The largest vision projector Ollama's Hugging Face registry may add to a pull from this repo; 0 when none. */
577
+ function largestProjectorBytes(detail) {
578
+ return Math.max(0, ...detail.projectors.map((entry) => entry.sizeBytes));
579
+ }
580
+ //#endregion
581
+ //#region ../../b4m-core/local-models/dist/fields-BNOk2VVS.mjs
582
+ /** Model ids, effort levels, sampling fields and context choices shared by Desktop and the CLI; Node-free. */
583
+ function localModelId(runtimeId, model) {
584
+ return `local:${encodeURIComponent(runtimeId)}:${model}`;
585
+ }
586
+ /** `local:<encoded runtime>:<model>`; runtime ids can contain colons so they are URL-encoded, the model stays raw. */
587
+ function parseLocalModelId(id) {
588
+ const match = /^local:([^:]+):(.+)$/s.exec(id);
589
+ if (!match) return null;
590
+ try {
591
+ return {
592
+ runtimeId: decodeURIComponent(match[1]),
593
+ model: match[2]
594
+ };
595
+ } catch {
596
+ return null;
597
+ }
598
+ }
599
+ /** Desktop's runtime id for the Ollama daemon on this computer, as in `local:ollama:<model>`. */
600
+ const LOCAL_OLLAMA_RUNTIME_ID = "ollama";
601
+ /** Ascending, which is the order the picker lists them in. */
602
+ const REASONING_EFFORT_SETTINGS = [
603
+ "default",
604
+ "none",
605
+ "minimal",
606
+ "low",
607
+ "medium",
608
+ "high",
609
+ "xhigh"
610
+ ];
611
+ /**
612
+ * The level a turn sends for a stored setting: the setting when `levels` lists it, else the listed
613
+ * level nearest it, the lower on a tie, so a level the model stops listing still moves effort the
614
+ * way it was set. Only a stored `none` maps to `none`, since that level turns thinking off.
615
+ */
616
+ function effortSent(setting, levels) {
617
+ if (setting === "default") return void 0;
618
+ if (levels.includes(setting)) return setting;
619
+ const rank = (level) => REASONING_EFFORT_SETTINGS.indexOf(level);
620
+ let nearest;
621
+ for (const level of levels) {
622
+ if (level === "default" || level === "none") continue;
623
+ if (nearest === void 0 || Math.abs(rank(level) - rank(setting)) < Math.abs(rank(nearest) - rank(setting))) nearest = level;
624
+ }
625
+ return nearest;
626
+ }
627
+ /** In the order the composer lists them. */
628
+ const GENERATION_FIELDS = [
629
+ "temperature",
630
+ "topP",
631
+ "topK",
632
+ "minP",
633
+ "repeatPenalty",
634
+ "presencePenalty",
635
+ "maxOutputTokens",
636
+ "thinkingBudgetTokens"
637
+ ];
638
+ const GENERATION_INTEGER_FIELDS = /* @__PURE__ */ new Set([
639
+ "topK",
640
+ "maxOutputTokens",
641
+ "thinkingBudgetTokens"
642
+ ]);
643
+ /**
644
+ * The widest range each field takes on any model; a model's own control narrows it, and each
645
+ * turn clamps to that. Must cover every range in Desktop's main/chat/modelControls.
646
+ */
647
+ const GENERATION_BOUNDS = {
648
+ temperature: {
649
+ min: 0,
650
+ max: 2
651
+ },
652
+ topP: {
653
+ min: 0,
654
+ max: 1
655
+ },
656
+ topK: {
657
+ min: 0,
658
+ max: 200
659
+ },
660
+ minP: {
661
+ min: 0,
662
+ max: 1
663
+ },
664
+ repeatPenalty: {
665
+ min: .5,
666
+ max: 2
667
+ },
668
+ presencePenalty: {
669
+ min: 0,
670
+ max: 2
671
+ },
672
+ maxOutputTokens: {
673
+ min: 1,
674
+ max: 2e6
675
+ },
676
+ thinkingBudgetTokens: {
677
+ min: 1024,
678
+ max: 32e3
679
+ }
680
+ };
681
+ function isRecord(raw) {
682
+ return !!raw && typeof raw === "object" && !Array.isArray(raw);
683
+ }
684
+ /** A finite number inside the field's bounds, whole where the field takes integers. */
685
+ function withinGenerationBounds(field, value) {
686
+ const bounds = GENERATION_BOUNDS[field];
687
+ return typeof value === "number" && Number.isFinite(value) && value >= bounds.min && value <= bounds.max && (!GENERATION_INTEGER_FIELDS.has(field) || Number.isInteger(value));
688
+ }
689
+ /**
690
+ * A replacement set, or null when it is not one: any known field out of bounds or not a number
691
+ * rejects the whole set, and so does a set with keys but no known field holding a value, so a
692
+ * malformed call never clears what is stored. Only `{}` clears every override.
693
+ */
694
+ function parseGenerationInput(raw) {
695
+ if (!isRecord(raw)) return null;
696
+ const settings = {};
697
+ for (const field of GENERATION_FIELDS) {
698
+ const value = raw[field];
699
+ if (value === void 0) continue;
700
+ if (!withinGenerationBounds(field, value)) return null;
701
+ settings[field] = value;
702
+ }
703
+ return Object.keys(settings).length === 0 && Object.keys(raw).length > 0 ? null : settings;
704
+ }
705
+ /** The context sizes Desktop's Settings offers for local models; Desktop's own instructions alone run past 8K. */
706
+ const LOCAL_CONTEXT_SIZES = [
707
+ 16384,
708
+ 32768,
709
+ 65536,
710
+ 131072,
711
+ 262144
712
+ ];
713
+ const MIN_MODEL_CONTEXT_TOKENS = 512;
714
+ function isContextTokens(value) {
715
+ return typeof value === "number" && Number.isInteger(value) && value >= MIN_MODEL_CONTEXT_TOKENS && value <= LOCAL_CONTEXT_SIZES[LOCAL_CONTEXT_SIZES.length - 1];
716
+ }
717
+ /** Null when `value` is not one; a cap or size outside 512 to the top offered size is not one either. */
718
+ function parseModelContextSetting(value) {
719
+ if (!isRecord(value)) return null;
720
+ const { mode, tokens, maxTokens } = value;
721
+ if (mode === "fixed") return isContextTokens(tokens) ? {
722
+ mode,
723
+ tokens
724
+ } : null;
725
+ if (mode !== "auto") return null;
726
+ if (maxTokens === void 0) return { mode };
727
+ return isContextTokens(maxTokens) ? {
728
+ mode,
729
+ maxTokens
730
+ } : null;
731
+ }
732
+ //#endregion
733
+ //#region ../../b4m-core/local-models/dist/servers.mjs
734
+ /** Most trusted first; a name that resolves to several addresses takes the least trusted one. */
735
+ const SCOPE_ORDER = [
736
+ "loopback",
737
+ "tailscale",
738
+ "private",
739
+ "public"
740
+ ];
741
+ function leastTrusted(scopes) {
742
+ return scopes.reduce((worst, scope) => SCOPE_ORDER.indexOf(scope) > SCOPE_ORDER.indexOf(worst) ? scope : worst, "loopback");
743
+ }
744
+ function ipv4Bytes(ip) {
745
+ if (isIP(ip) !== 4) return null;
746
+ return ip.split(".").map(Number);
747
+ }
748
+ /** The 8 16-bit groups of an IPv6 address, or null. Handles `::` and a trailing dotted IPv4. */
749
+ function ipv6Groups(ip) {
750
+ if (isIP(ip) !== 6) return null;
751
+ let text = ip.toLowerCase().split("%")[0];
752
+ const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
753
+ if (dotted) {
754
+ const bytes = ipv4Bytes(dotted[1]);
755
+ if (!bytes) return null;
756
+ text = `${text.slice(0, -dotted[1].length)}${(bytes[0] << 8 | bytes[1]).toString(16)}:${(bytes[2] << 8 | bytes[3]).toString(16)}`;
757
+ }
758
+ const [head, tail] = text.split("::");
759
+ const parse = (part) => part ? part.split(":").map((group) => parseInt(group, 16)) : [];
760
+ const front = parse(head);
761
+ const back = parse(tail);
762
+ const groups = tail === void 0 ? front : [
763
+ ...front,
764
+ ...new Array(8 - front.length - back.length).fill(0),
765
+ ...back
766
+ ];
767
+ return groups.length === 8 && groups.every((group) => Number.isInteger(group) && group >= 0 && group <= 65535) ? groups : null;
768
+ }
769
+ function scopeOfIpv4([a, b]) {
770
+ if (a === 127) return "loopback";
771
+ if (a === 10) return "private";
772
+ if (a === 172 && b >= 16 && b <= 31) return "private";
773
+ if (a === 192 && b === 168) return "private";
774
+ if (a === 100 && b >= 64 && b <= 127) return "private";
775
+ return "public";
776
+ }
777
+ /** Scope of an IP literal (IPv4, IPv6, or IPv4-mapped IPv6); null when `ip` is not an IP. */
778
+ function scopeOfIp(ip) {
779
+ const bare = ip.startsWith("[") && ip.endsWith("]") ? ip.slice(1, -1) : ip;
780
+ const v4 = ipv4Bytes(bare);
781
+ if (v4) return scopeOfIpv4(v4);
782
+ const groups = ipv6Groups(bare);
783
+ if (!groups) return null;
784
+ if (groups.slice(0, 7).every((group) => group === 0) && groups[7] === 1) return "loopback";
785
+ if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535) return scopeOfIpv4([
786
+ groups[6] >> 8,
787
+ groups[6] & 255,
788
+ groups[7] >> 8,
789
+ groups[7] & 255
790
+ ]);
791
+ if (groups[0] === 64890 && groups[1] === 4444 && groups[2] === 41440) return "tailscale";
792
+ if ((groups[0] & 65024) === 64512) return "private";
793
+ return "public";
794
+ }
795
+ /**
796
+ * Whether a request may go out. https is always allowed (the certificate is checked as usual). Plain
797
+ * http is refused to public addresses, and carries credentials only to loopback and Tailscale IPv6.
798
+ */
799
+ function transportVerdict(protocol, scope, hasCredentials) {
800
+ if (protocol === "https:") return {
801
+ ok: true,
802
+ unencrypted: false
803
+ };
804
+ if (protocol !== "http:") return {
805
+ ok: false,
806
+ reason: "Use an http or https address."
807
+ };
808
+ if (scope === "loopback" || scope === "tailscale") return {
809
+ ok: true,
810
+ unencrypted: false
811
+ };
812
+ if (scope === "public") return {
813
+ ok: false,
814
+ reason: "This address is on the public internet. Use https so the connection is encrypted."
815
+ };
816
+ if (hasCredentials) return {
817
+ ok: false,
818
+ reason: "Credentials are only sent over https, or over http to this computer or a Tailscale IPv6 address. Use https for this server."
819
+ };
820
+ return {
821
+ ok: true,
822
+ unencrypted: true
823
+ };
824
+ }
825
+ /** `https://host`, `http://192.168.1.5:11434` or `host:port` (http). Null for anything else, including `user:pass@`. */
826
+ function parseServerAddress(address) {
827
+ if (/[?#]/.test(address)) return null;
828
+ const baseUrl = parseBaseUrl(address);
829
+ if (!baseUrl) return null;
830
+ const url = new URL(baseUrl);
831
+ const host = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname;
832
+ return {
833
+ baseUrl,
834
+ protocol: url.protocol,
835
+ host,
836
+ origin: url.origin
837
+ };
838
+ }
839
+ /** RFC 7235 auth-scheme (a token), then whitespace, then the credential itself. */
840
+ const AUTH_SCHEME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\s+(\S.*)$/;
841
+ const REGEX_SPECIAL = /[\\^$.*+?()[\]{}|]/g;
842
+ /** Shorter values are matched only as a whole word, so a one-letter value does not mangle every reply. */
843
+ const SHORT = 8;
844
+ /** `\uXXXX` is the longest way a JSON encoder writes one character. */
845
+ const MAX_CHAR_FORM = 6;
846
+ const JSON_SHORT_ESCAPES = /* @__PURE__ */ new Map([
847
+ [8, "b"],
848
+ [9, "t"],
849
+ [10, "n"],
850
+ [12, "f"],
851
+ [13, "r"]
852
+ ]);
853
+ /**
854
+ * Replaces every credential value a server reply might quote back: the header value, the part after an
855
+ * auth scheme, and for Basic the decoded `user:pass` and the password. Each character may also appear
856
+ * backslash-escaped or as `\uXXXX`, as JSON encoders write them (Go escapes `&<>`, Python non-ASCII).
857
+ */
858
+ function credentialRedactor(credentials) {
859
+ const secrets = /* @__PURE__ */ new Set();
860
+ for (const value of Object.values(credentials ?? {})) {
861
+ secrets.add(value);
862
+ const token = AUTH_SCHEME.exec(value)?.[1];
863
+ if (!token) continue;
864
+ secrets.add(token);
865
+ if (/^basic\s/i.test(value)) {
866
+ const decoded = Buffer.from(token, "base64").toString("utf8");
867
+ const colon = decoded.indexOf(":");
868
+ if (colon >= 0) secrets.add(decoded).add(decoded.slice(colon + 1));
869
+ }
870
+ }
871
+ secrets.delete("");
872
+ if (secrets.size === 0) return null;
873
+ const ordered = [...secrets].sort((a, b) => b.length - a.length);
874
+ const pattern = new RegExp(ordered.map(secretPattern).join("|"), "g");
875
+ return {
876
+ redact: (text) => text.replace(pattern, "[redacted]"),
877
+ longest: ordered[0].length * MAX_CHAR_FORM
878
+ };
879
+ }
880
+ function secretPattern(secret) {
881
+ let body = "";
882
+ for (let index = 0; index < secret.length; index++) {
883
+ const code = secret.charCodeAt(index);
884
+ const literal = String.fromCharCode(code).replace(REGEX_SPECIAL, "\\$&");
885
+ const hex = code.toString(16).padStart(4, "0").replace(/[a-f]/g, (digit) => `[${digit}${digit.toUpperCase()}]`);
886
+ const shortEscape = JSON_SHORT_ESCAPES.get(code);
887
+ body += `(?:${literal}|\\\\${literal}|\\\\u${hex}${shortEscape ? `|\\\\${shortEscape}` : ""})`;
888
+ }
889
+ return secret.length < SHORT ? `(?<![A-Za-z0-9])${body}(?![A-Za-z0-9])` : body;
890
+ }
891
+ /** Refused before anything was sent: wrong origin, or a transport rule (see addressPolicy). */
892
+ var ServerTransportError = class extends Error {
893
+ constructor(message) {
894
+ super(message);
895
+ this.name = "ServerTransportError";
896
+ }
897
+ };
898
+ /** The server answered with a redirect. Never followed, so a credential cannot be carried anywhere else. */
899
+ var ServerRedirectError = class extends Error {
900
+ crossOrigin;
901
+ constructor(message, crossOrigin) {
902
+ super(message);
903
+ this.crossOrigin = crossOrigin;
904
+ this.name = "ServerRedirectError";
905
+ }
906
+ };
907
+ const BODY_IDLE_TIMEOUT_MS = 3e5;
908
+ const KEEPALIVE_DELAY_MS = 3e4;
909
+ const NO_IDLE_LIMIT_PATHS = /* @__PURE__ */ new Set(["/api/pull"]);
910
+ const REDIRECTS = /* @__PURE__ */ new Set([
911
+ 301,
912
+ 302,
913
+ 303,
914
+ 307,
915
+ 308
916
+ ]);
917
+ const NO_BODY = /* @__PURE__ */ new Set([
918
+ 204,
919
+ 205,
920
+ 304
921
+ ]);
922
+ const responseRedactors = /* @__PURE__ */ new WeakMap();
923
+ /** Uses the credential sent with this response's request, even after rotation or removal. */
924
+ function redactServerResponse(text, response) {
925
+ return responseRedactors.get(response)?.redact(text) ?? text;
926
+ }
927
+ /**
928
+ * Fetch for one saved server, on Node's http/https rather than Chromium's network stack: certificates
929
+ * are checked against the system and NODE_EXTRA_CA_CERTS roots, and the address a name resolves to is
930
+ * checked against the transport rules before the socket opens, so no byte of a credential leaves for a
931
+ * refused address. A CPU-only server can take minutes to prefill, and some send their headers before
932
+ * it, so neither the headers nor the first body byte have a deadline; a body that goes silent after
933
+ * that is dropped (except a pull, see NO_IDLE_LIMIT_PATHS).
934
+ *
935
+ * Credentials are added here and nowhere else, only to requests for `endpoint.origin`, and no
936
+ * redirect is followed. Connection failures reject with `TypeError('fetch failed', { cause })` like fetch.
937
+ */
938
+ function createServerFetch(endpoint, deps = {}) {
939
+ const app = endpoint.app ?? "Desktop";
940
+ const connect = endpoint.connect?.bind(endpoint);
941
+ return async (input, init = {}) => {
942
+ const url = new URL(input);
943
+ if (url.origin !== endpoint.origin) throw new ServerTransportError(`${app} only sends ${endpoint.label}'s requests to its own address.`);
944
+ const credentials = endpoint.credentialHeaders();
945
+ const headers = {
946
+ ...plainHeaders(init.headers),
947
+ ...credentials ?? {}
948
+ };
949
+ const hasCredentials = !!credentials && Object.keys(credentials).length > 0;
950
+ const protocol = url.protocol;
951
+ const host = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname;
952
+ if (isIP(host)) {
953
+ const verdict = transportVerdict(protocol, scopeOfIp(host) ?? "public", hasCredentials);
954
+ if (!verdict.ok) throw new ServerTransportError(verdict.reason);
955
+ }
956
+ const body = requestBody(init.body);
957
+ if (body !== void 0) headers["content-length"] = String(Buffer.byteLength(body));
958
+ const lookup = (hostname, options, callback) => {
959
+ (deps.lookup ?? dns.lookup)(hostname, options, (err, address, family) => {
960
+ if (err) return callback(err, address, family);
961
+ const resolved = Array.isArray(address) ? address : [{
962
+ address,
963
+ family: family ?? 4
964
+ }];
965
+ for (const entry of resolved) {
966
+ const verdict = transportVerdict(protocol, scopeOfIp(entry.address) ?? "public", hasCredentials);
967
+ if (!verdict.ok) return callback(new ServerTransportError(verdict.reason), address, family);
968
+ }
969
+ callback(null, address, family);
970
+ });
971
+ };
972
+ const response = await new Promise((resolve, reject) => {
973
+ const request = (protocol === "https:" ? https : http).request(url, {
974
+ method: init.method ?? "GET",
975
+ headers,
976
+ lookup,
977
+ ...connect ? { createConnection: () => connect() } : { agent: false },
978
+ ...init.signal ? { signal: init.signal } : {}
979
+ });
980
+ request.once("socket", (socket) => socket.setKeepAlive(true, KEEPALIVE_DELAY_MS));
981
+ request.once("response", resolve);
982
+ request.once("error", (error) => reject(wrapError(error, init.signal, endpoint.label)));
983
+ request.end(body);
984
+ });
985
+ const status = response.statusCode ?? 0;
986
+ const redactor = credentialRedactor(credentials);
987
+ const scrub = (text) => redactor?.redact(text) ?? text;
988
+ if (status < 200 || status > 599) {
989
+ response.destroy();
990
+ throw new TypeError(`${endpoint.label} answered with an invalid HTTP status (${status}).`);
991
+ }
992
+ if (REDIRECTS.has(status)) {
993
+ response.resume();
994
+ const location = response.headers.location;
995
+ const target = location && URL.canParse(location, url.href) ? new URL(location, url) : null;
996
+ const crossOrigin = !target || target.origin !== endpoint.origin;
997
+ throw new ServerRedirectError(scrub(crossOrigin ? `${endpoint.label} redirected to another address. ${app} does not follow redirects to another address, so its credentials stay with this server. Check the address.` : `${endpoint.label} answered with a redirect. Check the address, including any path.`), crossOrigin);
998
+ }
999
+ const responseHeaders = new Headers();
1000
+ for (let index = 0; index + 1 < response.rawHeaders.length; index += 2) responseHeaders.append(response.rawHeaders[index], response.rawHeaders[index + 1]);
1001
+ const empty = NO_BODY.has(status) || init.method === "HEAD";
1002
+ if (empty) response.resume();
1003
+ const encoding = (response.headers["content-encoding"] ?? "identity").trim().toLowerCase();
1004
+ const idleMs = NO_IDLE_LIMIT_PATHS.has(url.pathname) ? null : deps.bodyIdleTimeoutMs ?? BODY_IDLE_TIMEOUT_MS;
1005
+ if (status >= 300 && redactor) {
1006
+ let text = null;
1007
+ if (!empty && encoding === "identity") {
1008
+ if (idleMs !== null) response.setTimeout(idleMs, () => response.destroy());
1009
+ const read = await readCapped(response, ERROR_BODY_LIMIT);
1010
+ text = redactor.redact(read.text);
1011
+ if (read.capped) text = `${text.slice(0, Math.max(0, text.length - (redactor.longest - 1)))}[truncated]`;
1012
+ } else response.destroy();
1013
+ if (init.signal?.aborted) throw init.signal.reason;
1014
+ responseHeaders.delete("content-length");
1015
+ responseHeaders.delete("content-encoding");
1016
+ return new Response(text, {
1017
+ status,
1018
+ statusText: scrub(response.statusMessage ?? ""),
1019
+ headers: responseHeaders
1020
+ });
1021
+ }
1022
+ const armIdleLimit = () => idleMs !== null && response.setTimeout(idleMs, () => response.destroy(/* @__PURE__ */ new Error(`${endpoint.label} stopped sending its reply for ${idleText(idleMs)}. ${app} stopped waiting.`)));
1023
+ const result = new Response(empty ? null : idleLimitedBody(response, armIdleLimit), {
1024
+ status,
1025
+ statusText: scrub(response.statusMessage ?? ""),
1026
+ headers: responseHeaders
1027
+ });
1028
+ if (redactor) responseRedactors.set(result, redactor);
1029
+ return result;
1030
+ };
1031
+ }
1032
+ const ERROR_BODY_LIMIT = 1048576;
1033
+ /** Arms the idle limit on the first body chunk, so a server still prefilling is not cut off. */
1034
+ function idleLimitedBody(response, armIdleLimit) {
1035
+ let armed = false;
1036
+ return Readable.toWeb(response).pipeThrough(new TransformStream({ transform(chunk, controller) {
1037
+ if (!armed) {
1038
+ armed = true;
1039
+ armIdleLimit();
1040
+ }
1041
+ controller.enqueue(chunk);
1042
+ } }));
1043
+ }
1044
+ function idleText(ms) {
1045
+ if (ms >= 6e4 && ms % 6e4 === 0) return `${ms / 6e4} minute${ms === 6e4 ? "" : "s"}`;
1046
+ return `${ms / 1e3} s`;
1047
+ }
1048
+ async function readCapped(response, limit) {
1049
+ const chunks = [];
1050
+ let size = 0;
1051
+ try {
1052
+ for await (const chunk of response) {
1053
+ chunks.push(chunk);
1054
+ size += chunk.length;
1055
+ if (size > limit) break;
1056
+ }
1057
+ } catch {}
1058
+ response.destroy();
1059
+ return {
1060
+ text: Buffer.concat(chunks).subarray(0, limit).toString("utf8"),
1061
+ capped: size > limit
1062
+ };
1063
+ }
1064
+ function plainHeaders(headers) {
1065
+ const out = {};
1066
+ new Headers(headers).forEach((value, name) => {
1067
+ out[name] = value;
1068
+ });
1069
+ return out;
1070
+ }
1071
+ function requestBody(body) {
1072
+ if (body === void 0 || body === null) return void 0;
1073
+ if (typeof body === "string") return body;
1074
+ throw new ServerTransportError("Model server requests must have a text body.");
1075
+ }
1076
+ const TLS_CODES = /* @__PURE__ */ new Set([
1077
+ "CERT_HAS_EXPIRED",
1078
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
1079
+ "SELF_SIGNED_CERT_IN_CHAIN",
1080
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
1081
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
1082
+ "ERR_TLS_CERT_ALTNAME_INVALID",
1083
+ "CERT_NOT_YET_VALID"
1084
+ ]);
1085
+ function wrapError(error, signal, label) {
1086
+ if (signal?.aborted) return signal.reason ?? error;
1087
+ if (error instanceof ServerTransportError) return error;
1088
+ const code = error.code;
1089
+ if (code && TLS_CODES.has(code)) return new ServerTransportError(`The certificate of ${label} is not trusted (${code}). Use a certificate from a trusted authority, a local CA this computer trusts, or tailscale cert.`);
1090
+ return new TypeError("fetch failed", { cause: error });
1091
+ }
1092
+ /** The far-end port of an SSH server saved before records carried one: Ollama's. */
1093
+ const SSH_DEFAULT_PORT = 11434;
1094
+ sshServerUrl(SSH_DEFAULT_PORT);
1095
+ /** A probe over SSH waits for the connect timeout plus the server's answer. */
1096
+ const SSH_PROBE_TIMEOUT_MS = 2e4;
1097
+ /** The URL requests use for the server on the far end's loopback port `port`. */
1098
+ function sshServerUrl(port) {
1099
+ return `http://127.0.0.1:${port}`;
1100
+ }
1101
+ /** What to do when parseSshPort turns a far-end port down. */
1102
+ const SSH_PORT_PROBLEM = "Enter the port the server listens on, on that machine: a number from 1 to 65535.";
1103
+ /** A TCP port from 1 to 65535, as a number or digits only; null for anything else. */
1104
+ function parseSshPort(value) {
1105
+ const text = typeof value === "number" ? String(value) : typeof value === "string" ? value.trim() : "";
1106
+ if (!/^\d{1,5}$/.test(text)) return null;
1107
+ const port = Number(text);
1108
+ return port >= 1 && port <= 65535 ? port : null;
1109
+ }
1110
+ const DESTINATION = /^(?:[A-Za-z0-9._][A-Za-z0-9._-]{0,63}@)?[A-Za-z0-9_][A-Za-z0-9._-]{0,252}$/;
1111
+ /** Why `input` is not a usable SSH destination (`user@host` or a Host alias); null when it is. */
1112
+ function sshDestinationProblem(input) {
1113
+ const value = input.trim();
1114
+ if (!value) return "Enter an SSH destination such as user@host, or a Host alias from your ssh config.";
1115
+ if (value.startsWith("-")) return "An SSH destination cannot start with \"-\".";
1116
+ if (!DESTINATION.test(value)) return "Enter an SSH destination such as user@host, or a Host alias, using only letters, digits, dots, dashes and underscores.";
1117
+ return null;
1118
+ }
1119
+ function parseSshDestination(input) {
1120
+ return sshDestinationProblem(input) === null ? input.trim() : null;
1121
+ }
1122
+ const POSIX_ENV = /* @__PURE__ */ new Set([
1123
+ "PATH",
1124
+ "HOME",
1125
+ "USER",
1126
+ "LOGNAME",
1127
+ "SHELL",
1128
+ "LANG",
1129
+ "LC_ALL",
1130
+ "LC_CTYPE",
1131
+ "LC_MESSAGES",
1132
+ "TMPDIR",
1133
+ "XDG_RUNTIME_DIR",
1134
+ "SSH_AUTH_SOCK",
1135
+ "KRB5CCNAME"
1136
+ ]);
1137
+ const WINDOWS_ENV = /* @__PURE__ */ new Set([
1138
+ "PATH",
1139
+ "PATHEXT",
1140
+ "SYSTEMROOT",
1141
+ "WINDIR",
1142
+ "COMSPEC",
1143
+ "USERPROFILE",
1144
+ "HOMEDRIVE",
1145
+ "HOMEPATH",
1146
+ "USERNAME",
1147
+ "USERDOMAIN",
1148
+ "APPDATA",
1149
+ "LOCALAPPDATA",
1150
+ "PROGRAMDATA",
1151
+ "TEMP",
1152
+ "TMP",
1153
+ "SSH_AUTH_SOCK"
1154
+ ]);
1155
+ /** The ssh child's environment: an allowlist, never the app's own environment with its keys and tokens. */
1156
+ function sshChildEnv(env = process.env, platform = process.platform) {
1157
+ const windows = platform === "win32";
1158
+ const allowed = windows ? WINDOWS_ENV : POSIX_ENV;
1159
+ const out = {};
1160
+ for (const [key, value] of Object.entries(env)) if (value !== void 0 && allowed.has(windows ? key.toUpperCase() : key)) out[key] = value;
1161
+ return out;
1162
+ }
1163
+ /**
1164
+ * Arguments for one stdio forward to the far end's loopback `port`. Nothing in them can prompt or run a command.
1165
+ * Without our own `controlPath` the forward may reuse the user's master but never becomes one: a master
1166
+ * started here would end the user's sessions when it exits, or persist with this stripped environment.
1167
+ */
1168
+ function sshArgs(destination, controlPath = null, platform = process.platform, port = SSH_DEFAULT_PORT) {
1169
+ const target = parseSshPort(port);
1170
+ if (target === null) throw new SshRefusedError(SSH_PORT_PROBLEM);
1171
+ const option = (value) => ["-o", value];
1172
+ return [
1173
+ ...option("BatchMode=yes"),
1174
+ ...option(`ConnectTimeout=15`),
1175
+ ...option("RemoteCommand=none"),
1176
+ ...option("StrictHostKeyChecking=yes"),
1177
+ ...option("ForwardAgent=no"),
1178
+ ...option("ForwardX11=no"),
1179
+ ...option("ClearAllForwardings=yes"),
1180
+ ...option("PermitLocalCommand=no"),
1181
+ ...option("ServerAliveInterval=15"),
1182
+ ...option("ServerAliveCountMax=3"),
1183
+ ...controlPath ? [
1184
+ ...option("ControlMaster=auto"),
1185
+ ...option(`ControlPath=${controlPath}`),
1186
+ ...option("ControlPersist=120")
1187
+ ] : [...option("ControlMaster=no"), ...platform === "win32" ? option("ControlPath=none") : []],
1188
+ "-W",
1189
+ `127.0.0.1:${target}`,
1190
+ "--",
1191
+ destination
1192
+ ];
1193
+ }
1194
+ const SOCKET_PATH_LIMIT = {
1195
+ linux: 108,
1196
+ darwin: 104,
1197
+ freebsd: 104,
1198
+ openbsd: 104
1199
+ };
1200
+ const CONTROL_NAME_CHARS = 57;
1201
+ /** The shared-connection socket under `~/.ssh/b4m`, or null where it would not fit the OS limit. */
1202
+ function sharedControlPath(home, platform) {
1203
+ const limit = SOCKET_PATH_LIMIT[platform];
1204
+ if (!limit) return null;
1205
+ const dir = path.posix.join(home, ".ssh", "b4m");
1206
+ if (Buffer.byteLength(dir) + 1 + CONTROL_NAME_CHARS >= limit) return null;
1207
+ return {
1208
+ dir,
1209
+ option: "~/.ssh/b4m/%C"
1210
+ };
1211
+ }
1212
+ /** Whether `ssh -G` output shows the user's own ControlPath, which then decides sharing instead of ours. */
1213
+ function setsControlPath(effectiveConfig) {
1214
+ return effectiveConfig.split("\n").some((line) => {
1215
+ const [key, ...rest] = line.trim().split(/\s+/);
1216
+ return key?.toLowerCase() === "controlpath" && rest.join(" ").toLowerCase() !== "none";
1217
+ });
1218
+ }
1219
+ /** Needs the user to act: trust a host key, fix a login, or change the server. Shown as Refused. */
1220
+ var SshRefusedError = class extends ServerTransportError {
1221
+ constructor(message) {
1222
+ super(message);
1223
+ this.name = "SshRefusedError";
1224
+ }
1225
+ };
1226
+ /** The connection did not come up or dropped; a later check may succeed. Shown as Unreachable. */
1227
+ var SshConnectionError = class extends Error {
1228
+ constructor(message) {
1229
+ super(message);
1230
+ this.name = "SshConnectionError";
1231
+ }
1232
+ };
1233
+ /**
1234
+ * SSH logged in, but the far end refused the forward to the port: nothing listens there, or (`ambiguous`, over a
1235
+ * shared connection, which reports both the same way) its sshd does not allow forwarding.
1236
+ */
1237
+ var SshForwardRefusedError = class extends SshConnectionError {
1238
+ ambiguous;
1239
+ constructor(message, ambiguous) {
1240
+ super(message);
1241
+ this.ambiguous = ambiguous;
1242
+ this.name = "SshForwardRefusedError";
1243
+ }
1244
+ };
1245
+ const NOISE = [/^Warning: Permanently added/i, /^Pseudo-terminal will not be allocated/i];
1246
+ function lastLine(stderr) {
1247
+ const line = stderr.split(/\r?\n/).map((line) => line.replace(/[^\x20-\x7e]/g, "").trim()).filter((line) => line && !NOISE.some((pattern) => pattern.test(line))).at(-1);
1248
+ return line ? line.slice(0, 300) : null;
1249
+ }
1250
+ /** What ssh's stderr and exit code mean, in words that say what to do. */
1251
+ function describeSshFailure(stderr, code, destination, app = "Desktop", platform = process.platform, port = SSH_DEFAULT_PORT) {
1252
+ const target = `127.0.0.1:${port}`;
1253
+ const ollama = port === SSH_DEFAULT_PORT;
1254
+ const terminal = `\`ssh ${destination}\``;
1255
+ const windows = platform === "win32";
1256
+ const shell = windows ? "a Windows terminal (PowerShell or Command Prompt, not WSL)" : "a terminal";
1257
+ const connectOnce = `${shell} with ${terminal}`;
1258
+ const passphrase = windows ? ` ${app} cannot ask for a passphrase, so a key that has one must be loaded into ssh-agent.` : "";
1259
+ if (/REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(stderr)) return new SshRefusedError(`The host key of ${destination} has changed since this computer last connected. Check why, then connect once from ${connectOnce} to trust the new key.`);
1260
+ if (/Host key verification failed|host key is known|No .* host key is known/i.test(stderr)) return new SshRefusedError(`Connect once from ${connectOnce} to trust this server's host key.${passphrase}`);
1261
+ if (/open failed: connect failed/i.test(stderr)) return new SshForwardRefusedError(ollama ? `SSH to ${destination} works, but Ollama is not running on it: nothing answers at ${target} there. Start Ollama on that machine.` : `SSH to ${destination} works, but nothing answers at ${target} there. Start the model server on that machine, or check its port.`, false);
1262
+ if (/administratively prohibited/i.test(stderr)) return new SshRefusedError(`${destination} does not allow SSH port forwarding, which ${app} needs to reach ${ollama ? "Ollama" : "a model server"} there. Set AllowTcpForwarding to yes or local in its sshd_config.`);
1263
+ if (/: Permission denied \(|Too many authentication failures|no more authentication methods/i.test(stderr)) return new SshRefusedError(`${destination} refused the SSH login. Check that ${terminal} works in ${shell}. ${app} cannot ask for a password or passphrase, so load a key that has one into ssh-agent with ssh-add.`);
1264
+ if (/Session open refused by peer|stdio forwarding failed/i.test(stderr)) return new SshForwardRefusedError(`SSH to ${destination} works, but it refused the forward to ${target}. Check that ${ollama ? "Ollama" : "the model server"} is running there and that its sshd_config allows TCP forwarding (AllowTcpForwarding).`, true);
1265
+ if (/Could not resolve hostname/i.test(stderr)) return new SshConnectionError(`Could not find ${destination}. Check the name, or its HostName in your ssh config.`);
1266
+ const line = lastLine(stderr);
1267
+ if (line) return new SshConnectionError(`ssh ${destination} failed: ${line}`);
1268
+ return new SshConnectionError(`ssh ${destination} stopped (exit code ${code ?? "unknown"}).`);
1269
+ }
1270
+ const CONFIG_LIMIT = 262144;
1271
+ const CONFIG_TIMEOUT_MS = 5e3;
1272
+ const defaultSpawn = (command, args, options) => spawn(command, args, {
1273
+ ...options,
1274
+ stdio: [
1275
+ "pipe",
1276
+ "pipe",
1277
+ "pipe"
1278
+ ]
1279
+ });
1280
+ async function makePrivateDir(dir) {
1281
+ await mkdir(dir, {
1282
+ recursive: true,
1283
+ mode: 448
1284
+ });
1285
+ await chmod(dir, 448);
1286
+ }
1287
+ function accountHome() {
1288
+ try {
1289
+ return nodeOs.userInfo().homedir;
1290
+ } catch {
1291
+ return nodeOs.homedir();
1292
+ }
1293
+ }
1294
+ /** One `ssh -W` process as the socket of one HTTP request. */
1295
+ var SshForward = class extends Duplex {
1296
+ child;
1297
+ stderr = "";
1298
+ idleMs = 0;
1299
+ idleTimer;
1300
+ constructor(child, describe, spawnFailed) {
1301
+ super();
1302
+ this.child = child;
1303
+ const { stdout, stderr, stdin } = child;
1304
+ stdout?.on("data", (chunk) => {
1305
+ this.touch();
1306
+ if (!this.push(chunk)) stdout.pause();
1307
+ });
1308
+ stderr?.on("data", (chunk) => {
1309
+ this.stderr = (this.stderr + chunk.toString("utf8")).slice(-8192);
1310
+ });
1311
+ stdout?.on("error", (error) => this.destroy(error));
1312
+ stderr?.on("error", () => void 0);
1313
+ stdin?.on("error", () => void 0);
1314
+ child.once("error", (error) => this.destroy(spawnFailed(error)));
1315
+ child.once("close", (code) => {
1316
+ if (this.destroyed) return;
1317
+ if (code === 0) this.push(null);
1318
+ else this.destroy(describe(this.stderr, code));
1319
+ });
1320
+ }
1321
+ _read() {
1322
+ this.child.stdout?.resume();
1323
+ }
1324
+ _write(chunk, _encoding, callback) {
1325
+ this.touch();
1326
+ const stdin = this.child.stdin;
1327
+ if (!stdin || stdin.destroyed) return callback();
1328
+ stdin.write(chunk, () => callback());
1329
+ }
1330
+ _final(callback) {
1331
+ this.child.stdin?.end();
1332
+ callback();
1333
+ }
1334
+ _destroy(error, callback) {
1335
+ clearTimeout(this.idleTimer);
1336
+ if (this.child.exitCode === null && this.child.signalCode === null) this.child.kill();
1337
+ callback(error);
1338
+ }
1339
+ setTimeout(ms, callback) {
1340
+ this.idleMs = ms;
1341
+ if (callback) {
1342
+ if (ms === 0) this.removeListener("timeout", callback);
1343
+ else this.once("timeout", callback);
1344
+ }
1345
+ this.touch();
1346
+ return this;
1347
+ }
1348
+ setNoDelay() {
1349
+ return this;
1350
+ }
1351
+ setKeepAlive() {
1352
+ return this;
1353
+ }
1354
+ ref() {
1355
+ return this;
1356
+ }
1357
+ unref() {
1358
+ return this;
1359
+ }
1360
+ destroySoon() {
1361
+ if (this.writable) this.end();
1362
+ if (this.writableFinished) this.destroy();
1363
+ else this.once("finish", () => this.destroy());
1364
+ }
1365
+ touch() {
1366
+ clearTimeout(this.idleTimer);
1367
+ if (this.idleMs > 0 && !this.destroyed) {
1368
+ this.idleTimer = setTimeout(() => this.emit("timeout"), this.idleMs);
1369
+ this.idleTimer.unref?.();
1370
+ }
1371
+ }
1372
+ };
1373
+ /**
1374
+ * Fetch for a model server reached over SSH. Each request runs the system ssh with a stdio forward to the far
1375
+ * end's 127.0.0.1:`port`, non-interactively; when the user's ssh config sets no ControlPath, requests share
1376
+ * one connection through a short socket under ~/.ssh/b4m.
1377
+ */
1378
+ function createSshFetch(endpoint, deps = {}) {
1379
+ const destination = parseSshDestination(endpoint.destination);
1380
+ const port = parseSshPort(endpoint.port ?? 11434);
1381
+ const app = endpoint.app ?? "Desktop";
1382
+ const command = deps.command ?? "ssh";
1383
+ const spawn = deps.spawn ?? defaultSpawn;
1384
+ const platform = deps.platform ?? process.platform;
1385
+ const env = sshChildEnv(deps.env, platform);
1386
+ const usable = destination !== null && port !== null;
1387
+ let args = usable ? sshArgs(destination, null, platform, port) : [];
1388
+ let prepared = null;
1389
+ let configRead = null;
1390
+ let waiting = 0;
1391
+ const spawnFailed = (error) => error.code === "ENOENT" ? new SshRefusedError(`${app} could not find the ssh command. Install the OpenSSH client.`) : new SshConnectionError(`${app} could not start ssh (${error.code ?? error.message}).`);
1392
+ const prepare = async () => {
1393
+ if (!usable) return;
1394
+ const shared = sharedControlPath(deps.home ?? accountHome(), platform);
1395
+ if (!shared) return;
1396
+ const read = effectiveConfig(destination);
1397
+ configRead = read;
1398
+ const config = await read.done;
1399
+ if (configRead === read) configRead = null;
1400
+ if (config === null || setsControlPath(config)) return;
1401
+ try {
1402
+ await (deps.makeDir ?? makePrivateDir)(shared.dir);
1403
+ } catch {
1404
+ return;
1405
+ }
1406
+ args = sshArgs(destination, shared.option, platform, port);
1407
+ };
1408
+ const effectiveConfig = (target) => {
1409
+ let settle;
1410
+ const done = new Promise((resolve) => {
1411
+ settle = resolve;
1412
+ });
1413
+ let child;
1414
+ const group = platform !== "win32";
1415
+ try {
1416
+ child = spawn(command, [
1417
+ "-G",
1418
+ "--",
1419
+ target
1420
+ ], {
1421
+ env,
1422
+ windowsHide: true,
1423
+ detached: group
1424
+ });
1425
+ } catch {
1426
+ settle(null);
1427
+ return {
1428
+ done,
1429
+ end: () => void 0
1430
+ };
1431
+ }
1432
+ trackChild(child);
1433
+ let settled = false;
1434
+ const resolve = (value) => {
1435
+ if (settled) return;
1436
+ settled = true;
1437
+ clearTimeout(timer);
1438
+ settle(value);
1439
+ };
1440
+ const end = () => {
1441
+ if (settled) return;
1442
+ signalTree(child, "SIGKILL");
1443
+ child.stdout?.destroy();
1444
+ child.stderr?.destroy();
1445
+ resolve(null);
1446
+ };
1447
+ const timer = setTimeout(end, CONFIG_TIMEOUT_MS);
1448
+ let out = "";
1449
+ child.stdout?.on("data", (chunk) => {
1450
+ if (out.length < CONFIG_LIMIT) out += chunk.toString("utf8");
1451
+ });
1452
+ child.stderr?.resume();
1453
+ child.stdout?.on("error", () => void 0);
1454
+ child.stderr?.on("error", () => void 0);
1455
+ child.once("error", () => resolve(null));
1456
+ child.once("close", (code) => resolve(code === 0 ? out : null));
1457
+ return {
1458
+ done,
1459
+ end
1460
+ };
1461
+ };
1462
+ const inner = createServerFetch({
1463
+ origin: new URL(sshServerUrl(port ?? 11434)).origin,
1464
+ label: endpoint.label,
1465
+ app,
1466
+ credentialHeaders: () => endpoint.credentialHeaders?.() ?? null,
1467
+ connect: () => {
1468
+ let child;
1469
+ try {
1470
+ child = spawn(command, args, {
1471
+ env,
1472
+ windowsHide: true,
1473
+ detached: platform !== "win32"
1474
+ });
1475
+ } catch (error) {
1476
+ const forward = new Duplex({ read() {} });
1477
+ process.nextTick(() => forward.destroy(spawnFailed(error)));
1478
+ return forward;
1479
+ }
1480
+ return new SshForward(child, (stderr, code) => describeSshFailure(stderr, code, destination, app, platform, port), spawnFailed);
1481
+ }
1482
+ });
1483
+ return async (input, init) => {
1484
+ if (!destination) throw new SshRefusedError(sshDestinationProblem(endpoint.destination));
1485
+ if (port === null) throw new SshRefusedError(SSH_PORT_PROBLEM);
1486
+ const signal = init?.signal;
1487
+ signal?.throwIfAborted();
1488
+ const current = prepared ??= prepare().catch(() => void 0);
1489
+ waiting++;
1490
+ try {
1491
+ if (signal) {
1492
+ let onAbort;
1493
+ const aborted = new Promise((_resolve, reject) => {
1494
+ onAbort = () => reject(signal.reason);
1495
+ signal.addEventListener("abort", onAbort, { once: true });
1496
+ });
1497
+ try {
1498
+ await Promise.race([current, aborted]);
1499
+ } finally {
1500
+ signal.removeEventListener("abort", onAbort);
1501
+ }
1502
+ } else await current;
1503
+ } finally {
1504
+ waiting--;
1505
+ if (waiting === 0 && configRead && prepared === current) {
1506
+ configRead.end();
1507
+ prepared = null;
1508
+ }
1509
+ }
1510
+ signal?.throwIfAborted();
1511
+ return inner(input, init);
1512
+ };
1513
+ }
1514
+ /** OLLAMA_KV_CACHE_TYPE values besides Ollama's f16 default that a fit can price; must match shared/modelServers.ts in Desktop. */
1515
+ const QUANTIZED_KV_CACHE_TYPES = ["q8_0", "q4_0"];
1516
+ const MAX_SECRET_CHARS = 4096;
1517
+ const MAX_SPEC_MEMORY_GIB = 65536;
1518
+ const MAX_SPEC_BANDWIDTH_GBPS = 1e5;
1519
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,64}$/;
1520
+ const INVALID_HEADER_VALUE = /[^\t\x20-\x7e\x80-\xff]/;
1521
+ const RESERVED_HEADERS = /* @__PURE__ */ new Set([
1522
+ "host",
1523
+ "content-length",
1524
+ "content-type",
1525
+ "connection",
1526
+ "transfer-encoding",
1527
+ "keep-alive",
1528
+ "upgrade",
1529
+ "te",
1530
+ "trailer",
1531
+ "proxy-connection",
1532
+ "cookie"
1533
+ ]);
1534
+ /** The headers a credential adds to each request; throws with a message naming the field, never the value. */
1535
+ function credentialHeaders(credential) {
1536
+ if (credential.type === "none") return null;
1537
+ if (credential.type === "bearer") {
1538
+ const token = credential.token.trim();
1539
+ if (!token) throw new Error("Enter the token.");
1540
+ if (token.length > 4096) throw new Error(`The token is longer than ${MAX_SECRET_CHARS} characters.`);
1541
+ if (INVALID_HEADER_VALUE.test(token) || /\s/.test(token)) throw new Error("The token contains a control character, a space or a character HTTP does not allow.");
1542
+ return { authorization: `Bearer ${token}` };
1543
+ }
1544
+ const name = credential.name.trim();
1545
+ const value = credential.value.trim();
1546
+ if (!HEADER_NAME.test(name)) throw new Error("Enter a header name made of letters, digits and dashes.");
1547
+ if (RESERVED_HEADERS.has(name.toLowerCase())) throw new Error(`${name} cannot carry a credential.`);
1548
+ if (!value) throw new Error(`Enter the value for ${name}.`);
1549
+ if (value.length > 4096) throw new Error(`The value for ${name} is longer than ${MAX_SECRET_CHARS} characters.`);
1550
+ if (INVALID_HEADER_VALUE.test(value)) throw new Error(`The value for ${name} contains a control character or a character HTTP does not allow.`);
1551
+ return { [name.toLowerCase()]: value };
1552
+ }
1553
+ function isStored(value) {
1554
+ if (typeof value !== "object" || value === null) return false;
1555
+ const candidate = value;
1556
+ const transport = candidate.transport;
1557
+ const auth = candidate.auth;
1558
+ return typeof candidate.id === "string" && /^[0-9a-z]{1,32}$/.test(candidate.id) && typeof candidate.name === "string" && (candidate.kind === "ollama" || candidate.kind === "openai-compatible") && typeof transport?.type === "string" && (candidate.access === "chat" || candidate.access === "manage") && (auth?.type === "none" || auth?.type === "bearer" || auth?.type === "header" && typeof auth.name === "string");
1559
+ }
1560
+ function storedTransport(transport) {
1561
+ if (transport.type === "http" && typeof transport.baseUrl === "string") return {
1562
+ type: "http",
1563
+ baseUrl: transport.baseUrl
1564
+ };
1565
+ const destination = transport.type === "ssh" && typeof transport.destination === "string" ? parseSshDestination(transport.destination) : null;
1566
+ const port = transport.port === void 0 ? SSH_DEFAULT_PORT : parseSshPort(transport.port);
1567
+ return destination && port !== null ? {
1568
+ type: "ssh",
1569
+ destination,
1570
+ port
1571
+ } : null;
1572
+ }
1573
+ /** The unusable record for a stored SSH server that hydrate turns down; null for any other record. */
1574
+ function unusableServer(stored) {
1575
+ const { transport } = stored;
1576
+ if (transport.type !== "ssh" || storedTransport(transport)) return null;
1577
+ const saved = typeof transport.destination === "string";
1578
+ const destination = saved ? parseSshDestination(transport.destination) : null;
1579
+ return {
1580
+ ...recordFields(stored),
1581
+ transport: {
1582
+ type: "ssh",
1583
+ destination
1584
+ },
1585
+ problem: destination ? "Its saved SSH port is not a number from 1 to 65535." : saved ? "Its saved SSH destination is not one ssh can be given safely." : "It has no saved SSH destination."
1586
+ };
1587
+ }
1588
+ function recordFields(stored) {
1589
+ return {
1590
+ id: stored.id,
1591
+ name: stored.name,
1592
+ kind: stored.kind,
1593
+ access: stored.access,
1594
+ auth: stored.auth.type === "header" ? {
1595
+ type: "header",
1596
+ name: stored.auth.name
1597
+ } : { type: stored.auth.type },
1598
+ addedAt: typeof stored.addedAt === "string" ? stored.addedAt : ""
1599
+ };
1600
+ }
1601
+ /** Null for a record this version cannot use (an unknown transport, or see unusableServer); it stays on disk untouched. */
1602
+ function hydrate(stored) {
1603
+ const transport = storedTransport(stored.transport);
1604
+ if (!transport) return null;
1605
+ return {
1606
+ ...recordFields(stored),
1607
+ transport,
1608
+ models: Array.isArray(stored.models) ? stored.models.filter((name) => typeof name === "string") : [],
1609
+ specs: readSpecs(stored.specs)
1610
+ };
1611
+ }
1612
+ function readSpecsShape(value) {
1613
+ if (typeof value !== "object" || value === null) return null;
1614
+ const raw = value;
1615
+ const figure = (field) => typeof field === "number" ? field : null;
1616
+ const kv = QUANTIZED_KV_CACHE_TYPES.find((type) => type === raw.kvCacheType);
1617
+ return {
1618
+ ramGiB: figure(raw.ramGiB),
1619
+ gpuMemoryGiB: figure(raw.gpuMemoryGiB),
1620
+ bandwidthGBps: figure(raw.bandwidthGBps),
1621
+ unified: raw.unified === true,
1622
+ ...kv ? { kvCacheType: kv } : {}
1623
+ };
1624
+ }
1625
+ function specsInRange(specs) {
1626
+ const ok = (value, max) => value === null || Number.isFinite(value) && value > 0 && value <= max;
1627
+ return ok(specs.ramGiB, MAX_SPEC_MEMORY_GIB) && ok(specs.gpuMemoryGiB, MAX_SPEC_MEMORY_GIB) && ok(specs.bandwidthGBps, MAX_SPEC_BANDWIDTH_GBPS);
1628
+ }
1629
+ /** Specs as stored; a hand-edited or newer shape that does not check out is ignored, so the server stays unrated. */
1630
+ function readSpecs(value) {
1631
+ const specs = readSpecsShape(value);
1632
+ if (!specs || isBlankSpecs(specs)) return null;
1633
+ return specsInRange(specs) ? specs : null;
1634
+ }
1635
+ /** No figure and no cache type: the same as no specs at all. */
1636
+ function isBlankSpecs(specs) {
1637
+ return specs.ramGiB === null && specs.gpuMemoryGiB === null && specs.bandwidthGBps === null && !specs.kvCacheType;
1638
+ }
1639
+ function serverManagement(server) {
1640
+ if (server.local) return "allowed";
1641
+ if (server.kind !== "ollama") return "unsupported";
1642
+ return server.access === "manage" ? "allowed" : "chat-only";
1643
+ }
1644
+ function serverRuntimeId(serverId) {
1645
+ return `srv-${serverId}`;
1646
+ }
1647
+ const FILE_NAME = "model-servers.json";
1648
+ /**
1649
+ * Where Desktop keeps its userData folder: `B4M_DESKTOP_USER_DATA` when set, else the packaged name
1650
+ * (package.json `name`) then the product name under the platform's app-data folder.
1651
+ */
1652
+ function desktopUserDataDirs(opts = {}) {
1653
+ const platform = opts.platform ?? process.platform;
1654
+ const env = opts.env ?? process.env;
1655
+ const home = opts.home ?? nodeOs.homedir();
1656
+ const override = env.B4M_DESKTOP_USER_DATA?.trim();
1657
+ if (override) return [override];
1658
+ const flavor = platform === "win32" ? path.win32 : path.posix;
1659
+ let appData;
1660
+ if (platform === "darwin") appData = flavor.join(home, "Library", "Application Support");
1661
+ else if (platform === "win32") appData = env.APPDATA || flavor.join(home, "AppData", "Roaming");
1662
+ else appData = env.XDG_CONFIG_HOME || flavor.join(home, ".config");
1663
+ return [flavor.join(appData, "@bike4mind", "desktop"), flavor.join(appData, "Bike4Mind")];
1664
+ }
1665
+ async function entryAt(target) {
1666
+ try {
1667
+ return (await stat(target)).isDirectory() ? "dir" : "file";
1668
+ } catch (err) {
1669
+ const code = err.code;
1670
+ return code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unchecked";
1671
+ }
1672
+ }
1673
+ /**
1674
+ * Where to read Desktop's file `name`: in `B4M_DESKTOP_USER_DATA` when set, else in the first of
1675
+ * desktopUserDataDirs holding it, else in the first that exists. Null when none does.
1676
+ */
1677
+ async function desktopUserDataFile(name, opts = {}) {
1678
+ const flavor = (opts.platform ?? process.platform) === "win32" ? path.win32 : path.posix;
1679
+ const override = (opts.env ?? process.env).B4M_DESKTOP_USER_DATA?.trim();
1680
+ if (override) return flavor.join(override, name);
1681
+ let firstExisting = null;
1682
+ for (const dir of desktopUserDataDirs(opts)) {
1683
+ const file = flavor.join(dir, name);
1684
+ const folder = await entryAt(dir);
1685
+ if (folder === "unchecked") return file;
1686
+ if (folder !== "dir") continue;
1687
+ firstExisting ??= file;
1688
+ if (await entryAt(file) !== "missing") return file;
1689
+ }
1690
+ return firstExisting;
1691
+ }
1692
+ /** Without userinfo in the address: a credential has no place in a URL, and none is returned. */
1693
+ function withoutUserinfo(baseUrl) {
1694
+ try {
1695
+ const url = new URL(baseUrl);
1696
+ if (!url.username && !url.password) return baseUrl;
1697
+ url.username = "";
1698
+ url.password = "";
1699
+ const cleaned = url.toString();
1700
+ return !baseUrl.endsWith("/") && cleaned.endsWith("/") ? cleaned.slice(0, -1) : cleaned;
1701
+ } catch {
1702
+ return baseUrl;
1703
+ }
1704
+ }
1705
+ /**
1706
+ * Desktop's saved model servers, read once and never written. `secret` is dropped; a file from a newer
1707
+ * Desktop is read as it is. A missing file is not a problem: Desktop may not be installed.
1708
+ */
1709
+ async function readDesktopModelServers(opts = {}) {
1710
+ let files;
1711
+ if (opts.dirs) files = opts.dirs.map((dir) => path.join(dir, FILE_NAME));
1712
+ else {
1713
+ const file = await desktopUserDataFile(FILE_NAME, opts);
1714
+ files = file === null ? [] : [file];
1715
+ }
1716
+ for (const file of files) {
1717
+ let raw;
1718
+ try {
1719
+ raw = await readFile(file, "utf8");
1720
+ } catch (err) {
1721
+ const code = err.code;
1722
+ if (code === "ENOENT" || code === "ENOTDIR") continue;
1723
+ return {
1724
+ servers: [],
1725
+ path: file,
1726
+ problem: `${FILE_NAME} could not be read (${code ?? "error"}).`
1727
+ };
1728
+ }
1729
+ let parsed;
1730
+ try {
1731
+ parsed = JSON.parse(raw);
1732
+ } catch {
1733
+ return {
1734
+ servers: [],
1735
+ path: file,
1736
+ problem: `${FILE_NAME} is not valid JSON.`
1737
+ };
1738
+ }
1739
+ const all = parsed?.servers;
1740
+ if (!Array.isArray(all)) return {
1741
+ servers: [],
1742
+ path: file,
1743
+ problem: `${FILE_NAME} has no server list.`
1744
+ };
1745
+ const servers = [];
1746
+ const unusable = [];
1747
+ for (const value of all) {
1748
+ if (!isStored(value)) continue;
1749
+ const record = hydrate(value);
1750
+ if (record?.transport.type === "http") servers.push({
1751
+ ...record,
1752
+ transport: {
1753
+ type: "http",
1754
+ baseUrl: withoutUserinfo(record.transport.baseUrl)
1755
+ }
1756
+ });
1757
+ else if (record) servers.push(record);
1758
+ else {
1759
+ const turnedDown = unusableServer(value);
1760
+ if (turnedDown) unusable.push(turnedDown);
1761
+ }
1762
+ }
1763
+ return {
1764
+ servers,
1765
+ path: file,
1766
+ problem: null,
1767
+ ...unusable.length > 0 ? { unusable } : {}
1768
+ };
1769
+ }
1770
+ return {
1771
+ servers: [],
1772
+ path: null,
1773
+ problem: null
1774
+ };
1775
+ }
1776
+ /** The system error code on the error itself (Node http mid-body drops) or on its cause (fetch). */
1777
+ function errorCode(err) {
1778
+ if (!(err instanceof Error)) return void 0;
1779
+ const own = err.code;
1780
+ if (typeof own === "string") return own;
1781
+ const cause = err.cause?.code;
1782
+ return typeof cause === "string" ? cause : void 0;
1783
+ }
1784
+ const DROP_CODES = /* @__PURE__ */ new Set([
1785
+ "ECONNRESET",
1786
+ "UND_ERR_SOCKET",
1787
+ "ERR_STREAM_PREMATURE_CLOSE"
1788
+ ]);
1789
+ /** One line for a failed request; never includes a header or credential. */
1790
+ function describeFailure(err) {
1791
+ if (err instanceof ServerTransportError || err instanceof ServerRedirectError) return err.message;
1792
+ if (err instanceof SshConnectionError) return err.message;
1793
+ if (err instanceof Error && err.cause instanceof SshConnectionError) return err.cause.message;
1794
+ if (err instanceof DOMException && err.name === "TimeoutError") return "it did not answer in time";
1795
+ if (err instanceof Error && err.name === "TimeoutError") return "it did not answer in time";
1796
+ if (err instanceof PullIdleTimeoutError) return "it stopped sending data";
1797
+ const code = errorCode(err);
1798
+ if (code === "ECONNREFUSED") return "connection refused";
1799
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "host not found";
1800
+ if (code === "EHOSTUNREACH" || code === "ENETUNREACH") return "no route to the host";
1801
+ if (code === "ETIMEDOUT") return "the connection timed out";
1802
+ if (code && DROP_CODES.has(code)) return "the connection dropped";
1803
+ if (err instanceof TypeError && /terminated|aborted/i.test(err.message)) return "the connection dropped";
1804
+ if (err instanceof Error && /ended (the reply )?before/i.test(err.message)) return "the connection dropped";
1805
+ return code ?? (err instanceof Error ? err.message : String(err));
1806
+ }
1807
+ const PROBE_TIMEOUT_MS = 5e3;
1808
+ /**
1809
+ * Identifies the server by what it answers, never by port, and times the answer. `timeoutMs` applies per request;
1810
+ * null leaves each request's limit to `fetch`.
1811
+ */
1812
+ async function probeServer(fetch, baseUrl, label, now, expected, timeoutMs = PROBE_TIMEOUT_MS) {
1813
+ const get = async (path) => {
1814
+ const started = now();
1815
+ try {
1816
+ const signal = timeoutMs === null ? void 0 : AbortSignal.timeout(timeoutMs);
1817
+ const response = await fetch(`${baseUrl}${path}`, signal ? { signal } : {});
1818
+ const latencyMs = Math.round(now() - started);
1819
+ const body = response.ok ? await response.json().catch((error) => {
1820
+ if (signal?.aborted) throw error;
1821
+ return null;
1822
+ }) : (await response.body?.cancel(), null);
1823
+ return {
1824
+ status: response.status,
1825
+ body,
1826
+ latencyMs,
1827
+ error: null
1828
+ };
1829
+ } catch (error) {
1830
+ return {
1831
+ status: 0,
1832
+ body: null,
1833
+ latencyMs: null,
1834
+ error
1835
+ };
1836
+ }
1837
+ };
1838
+ const [version, models] = await Promise.all([expected === "openai-compatible" ? null : get("/api/version"), expected === "ollama" ? null : get("/v1/models")]);
1839
+ const auth = [version, models].some((result) => result?.status === 401);
1840
+ const ollamaVersion = (version?.body)?.version;
1841
+ if (version && version.status === 200 && typeof ollamaVersion === "string") {
1842
+ const listed = (await get("/api/tags")).body?.models;
1843
+ return {
1844
+ kind: "ollama",
1845
+ product: null,
1846
+ version: ollamaVersion,
1847
+ latencyMs: version.latencyMs,
1848
+ models: Array.isArray(listed) ? listed.length : null,
1849
+ auth: false,
1850
+ forbidden: false,
1851
+ error: null,
1852
+ code: null,
1853
+ refused: false
1854
+ };
1855
+ }
1856
+ const data = (models?.body)?.data;
1857
+ if (models && models.status === 200 && Array.isArray(data)) {
1858
+ const product = productFromOwner(data);
1859
+ return {
1860
+ kind: "openai-compatible",
1861
+ product,
1862
+ version: await openAIVersion(get, product),
1863
+ latencyMs: models.latencyMs,
1864
+ models: data.length,
1865
+ auth: false,
1866
+ forbidden: false,
1867
+ error: null,
1868
+ code: null,
1869
+ refused: false
1870
+ };
1871
+ }
1872
+ const failure = [version, models].find((result) => result && result.error)?.error;
1873
+ const forbidden = !auth && [version, models].some((result) => result?.status === 403);
1874
+ const refused = forbidden || failure instanceof ServerTransportError || failure instanceof ServerRedirectError;
1875
+ const status = [version, models].find((result) => result && result.status > 0)?.status;
1876
+ return {
1877
+ kind: null,
1878
+ product: null,
1879
+ version: null,
1880
+ latencyMs: null,
1881
+ models: null,
1882
+ auth,
1883
+ forbidden,
1884
+ refused,
1885
+ error: forbidden ? forbiddenMessage(label) : failure ? refused ? describeFailure(failure) : `Could not reach ${label}: ${describeFailure(failure)}` : status ? `${label} answered HTTP ${status}, not as Ollama or an OpenAI-compatible server.` : null,
1886
+ code: errorCode(failure) ?? null
1887
+ };
1888
+ }
1889
+ /** A 403 is a refusal, not a credentials prompt; Desktop's ServerForbiddenError carries the same text. */
1890
+ function forbiddenMessage(label) {
1891
+ return `${label} answered 403 Forbidden: the server or a proxy in front of it refused the request.`;
1892
+ }
1893
+ async function openAIVersion(get, product) {
1894
+ if (product === "llama-server") {
1895
+ const build = (await get("/props")).body?.build_info;
1896
+ return typeof build === "string" ? build : null;
1897
+ }
1898
+ if (product === "vllm") {
1899
+ const version = (await get("/version")).body;
1900
+ return typeof version?.version === "string" ? version.version : null;
1901
+ }
1902
+ return null;
1903
+ }
1904
+ /** Whether the server lists its models with no credential at all. */
1905
+ async function answersWithoutCredentials(fetch, baseUrl, kind) {
1906
+ try {
1907
+ const response = await fetch(`${baseUrl}${kind === "ollama" ? "/api/tags" : "/v1/models"}`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
1908
+ await response.body?.cancel();
1909
+ return response.ok;
1910
+ } catch {
1911
+ return false;
1912
+ }
1913
+ }
1914
+ /** The default ports of DEFAULT_PROBE_HOSTS in detect.ts, in the same order, with what usually listens there. */
1915
+ const SSH_DISCOVERY_PORTS = [
1916
+ {
1917
+ port: 11434,
1918
+ usual: "Ollama"
1919
+ },
1920
+ {
1921
+ port: 1234,
1922
+ usual: "LM Studio"
1923
+ },
1924
+ {
1925
+ port: 8080,
1926
+ usual: "llama-server"
1927
+ },
1928
+ {
1929
+ port: 8e3,
1930
+ usual: "vLLM"
1931
+ }
1932
+ ];
1933
+ function sshCause(error) {
1934
+ if (error instanceof SshConnectionError || error instanceof SshRefusedError) return error;
1935
+ return error instanceof Error && error.cause !== void 0 ? error.cause : error;
1936
+ }
1937
+ /** ssh itself failed (login, host key, network), so every other port would fail the same way. */
1938
+ function connectionFailure(error) {
1939
+ const cause = sshCause(error);
1940
+ return cause instanceof SshRefusedError || cause instanceof SshConnectionError && !(cause instanceof SshForwardRefusedError);
1941
+ }
1942
+ /**
1943
+ * Holds every request until the first has its answer, so ssh logs in once and, where it shares connections, the
1944
+ * rest ride that master instead of each racing to become one. After a failed login, or a first request that ran
1945
+ * out its own limit (an unanswered agent prompt or key touch), the rest fail at once instead of each prompting.
1946
+ */
1947
+ function firstRequestAlone(destination, timeoutMs, custom) {
1948
+ let first = null;
1949
+ let fatal = null;
1950
+ const advice = custom ? "restart that server" : "restart that server, or enter the port of the one you want";
1951
+ return (fetch) => async (input, init) => {
1952
+ if (!first) {
1953
+ const url = new URL(input);
1954
+ const target = `${url.hostname}:${url.port || "80"}`;
1955
+ const request = fetch(input, init);
1956
+ first = request.then(() => void 0, (error) => {
1957
+ const cause = sshCause(error);
1958
+ if (connectionFailure(error)) fatal = { error };
1959
+ else if (!init?.signal?.aborted && cause instanceof Error && cause.name === "TimeoutError") {
1960
+ const seconds = Math.ceil(timeoutMs / 1e3);
1961
+ fatal = { error: new SshConnectionError(`ssh ${destination} did not finish connecting, or ${target} there did not answer, within ${seconds} s. Run \`ssh ${destination}\` in a terminal to check that it connects. If it does, ${advice}, then test again.`) };
1962
+ }
1963
+ });
1964
+ return request;
1965
+ }
1966
+ await first;
1967
+ if (fatal) throw fatal.error;
1968
+ init?.signal?.throwIfAborted();
1969
+ return fetch(input, init);
1970
+ };
1971
+ }
1972
+ /**
1973
+ * Gives each request its own limit from when it starts, so time spent waiting behind the login is not counted.
1974
+ * `expired` runs only when a limit ends before its request has settled, body included.
1975
+ */
1976
+ function timed(fetch, timeoutMs, expired) {
1977
+ return async (input, init = {}) => {
1978
+ const timeout = AbortSignal.timeout(timeoutMs);
1979
+ let settled = false;
1980
+ const settle = () => {
1981
+ settled = true;
1982
+ };
1983
+ timeout.addEventListener("abort", () => {
1984
+ if (!settled) expired();
1985
+ }, { once: true });
1986
+ try {
1987
+ return settlesWith(await fetch(input, {
1988
+ ...init,
1989
+ signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout
1990
+ }), settle);
1991
+ } catch (error) {
1992
+ settle();
1993
+ throw error;
1994
+ }
1995
+ };
1996
+ }
1997
+ /** The same response, calling `settle` once its body has been read, failed or cancelled. */
1998
+ function settlesWith(response, settle) {
1999
+ const source = response.body;
2000
+ if (!source) {
2001
+ settle();
2002
+ return response;
2003
+ }
2004
+ const reader = source.getReader();
2005
+ const body = new ReadableStream({
2006
+ async pull(controller) {
2007
+ try {
2008
+ const { done, value } = await reader.read();
2009
+ if (done) {
2010
+ settle();
2011
+ controller.close();
2012
+ } else controller.enqueue(value);
2013
+ } catch (error) {
2014
+ settle();
2015
+ controller.error(error);
2016
+ }
2017
+ },
2018
+ cancel(reason) {
2019
+ settle();
2020
+ return reader.cancel(reason);
2021
+ }
2022
+ });
2023
+ return new Response(body, {
2024
+ status: response.status,
2025
+ statusText: response.statusText,
2026
+ headers: response.headers
2027
+ });
2028
+ }
2029
+ async function isLmStudio(fetch, baseUrl) {
2030
+ try {
2031
+ const response = await fetch(`${baseUrl}/api/v0/models`);
2032
+ if (!response.ok) {
2033
+ await response.body?.cancel();
2034
+ return false;
2035
+ }
2036
+ return lmStudioModelsSchema.safeParse(await response.json()).success;
2037
+ } catch {
2038
+ return false;
2039
+ }
2040
+ }
2041
+ /** A 401 with an API-style JSON error, not a login page that happens to sit on a usual port. */
2042
+ async function apiStyleRefusal(fetch, baseUrl) {
2043
+ try {
2044
+ const response = await fetch(`${baseUrl}/v1/models`);
2045
+ if (response.status !== 401) {
2046
+ await response.body?.cancel();
2047
+ return false;
2048
+ }
2049
+ const body = await response.json();
2050
+ return typeof body === "object" && body !== null && body.error !== void 0;
2051
+ } catch {
2052
+ return false;
2053
+ }
2054
+ }
2055
+ /** llama-server lists its models without its `--api-key` but guards `/props`, so a 401 there means it wants one. */
2056
+ async function llamaServerWantsKey(fetch, baseUrl) {
2057
+ try {
2058
+ const response = await fetch(`${baseUrl}/props`);
2059
+ await response.body?.cancel();
2060
+ return response.status === 401;
2061
+ } catch {
2062
+ return false;
2063
+ }
2064
+ }
2065
+ const requestTimeout = (options) => options.requestTimeoutMs ?? 2e4;
2066
+ const deadlineOf = (options) => options.deadlineMs ?? 3e4;
2067
+ /** `fetch` is gated and timed; `expired` says whether one of its requests ran out its own limit. */
2068
+ async function probePort(port, fetch, options, signal, expired) {
2069
+ const errors = [];
2070
+ const tracked = async (input, init = {}) => {
2071
+ try {
2072
+ if (signal.aborted) throw signal.reason;
2073
+ return await fetch(input, {
2074
+ ...init,
2075
+ signal: init.signal ? AbortSignal.any([init.signal, signal]) : signal
2076
+ });
2077
+ } catch (error) {
2078
+ errors.push(error);
2079
+ throw error;
2080
+ }
2081
+ };
2082
+ const baseUrl = sshServerUrl(port);
2083
+ const label = `127.0.0.1:${port} on ${options.destination}`;
2084
+ const outcome = await probeServer(tracked, baseUrl, label, options.now, void 0, null);
2085
+ if (outcome.kind) {
2086
+ const lmStudio = outcome.kind === "openai-compatible" && !outcome.product && await isLmStudio(tracked, baseUrl);
2087
+ return {
2088
+ state: "found",
2089
+ server: {
2090
+ port,
2091
+ kind: outcome.kind,
2092
+ product: lmStudio ? "lmstudio" : outcome.product,
2093
+ version: outcome.version,
2094
+ models: outcome.models,
2095
+ latencyMs: outcome.latencyMs,
2096
+ needsCredentials: outcome.product === "llama-server" && outcome.version === null && await llamaServerWantsKey(tracked, baseUrl)
2097
+ }
2098
+ };
2099
+ }
2100
+ if (outcome.auth && (options.port !== void 0 || await apiStyleRefusal(tracked, baseUrl))) return {
2101
+ state: "found",
2102
+ server: {
2103
+ port,
2104
+ kind: "openai-compatible",
2105
+ product: null,
2106
+ version: null,
2107
+ models: null,
2108
+ latencyMs: outcome.latencyMs,
2109
+ needsCredentials: true
2110
+ }
2111
+ };
2112
+ const causes = errors.map(sshCause);
2113
+ const fatal = errors.find(connectionFailure);
2114
+ if (fatal !== void 0) return {
2115
+ state: "failed",
2116
+ error: sshCause(fatal)
2117
+ };
2118
+ if (signal.aborted) return {
2119
+ state: "timeout",
2120
+ limitMs: deadlineOf(options)
2121
+ };
2122
+ const refused = causes.filter((cause) => cause instanceof SshForwardRefusedError);
2123
+ if (refused.length > 0) return {
2124
+ state: "closed",
2125
+ ambiguous: refused.some((cause) => cause.ambiguous)
2126
+ };
2127
+ if (causes.some((cause) => errorCode(cause) === "ECONNREFUSED")) return {
2128
+ state: "closed",
2129
+ ambiguous: false
2130
+ };
2131
+ if (expired()) return {
2132
+ state: "timeout",
2133
+ limitMs: requestTimeout(options)
2134
+ };
2135
+ if (errors.length === 0) return {
2136
+ state: "other",
2137
+ message: outcome.error ?? `${label} answered, but not as a model server.`
2138
+ };
2139
+ return {
2140
+ state: "failed",
2141
+ error: causes[0]
2142
+ };
2143
+ }
2144
+ const FORWARDING_HINT = " If a server is running there, check that its sshd_config allows TCP forwarding (AllowTcpForwarding).";
2145
+ /** The usual ports by server, e.g. "Ollama 11434, LM Studio 1234", as discovery's messages name them. */
2146
+ function usualPorts() {
2147
+ return SSH_DISCOVERY_PORTS.map(({ port, usual }) => `${usual} ${port}`).join(", ");
2148
+ }
2149
+ /** What to do when nothing was found, in order of what most likely went wrong. */
2150
+ function nothingFound(results, ports, options) {
2151
+ const { destination } = options;
2152
+ const failed = results.find((result) => result.state === "failed");
2153
+ if (failed?.state === "failed") {
2154
+ const message = describeFailure(failed.error);
2155
+ return {
2156
+ found: [],
2157
+ error: failed.error instanceof SshConnectionError || failed.error instanceof SshRefusedError ? message : `Could not reach ${destination} over SSH: ${message}`,
2158
+ refused: failed.error instanceof SshRefusedError
2159
+ };
2160
+ }
2161
+ const limits = results.flatMap((result) => result.state === "timeout" ? [result.limitMs] : []);
2162
+ if (limits.length > 0) return {
2163
+ found: [],
2164
+ error: `${destination} did not answer within ${Math.ceil(Math.max(...limits) / 1e3)} s. Check that \`ssh ${destination}\` connects from a terminal, then test again.`,
2165
+ refused: false
2166
+ };
2167
+ const others = results.flatMap((result, index) => result.state === "other" ? [ports[index]] : []);
2168
+ const ambiguous = results.some((result) => result.state === "closed" && result.ambiguous);
2169
+ if (options.port !== void 0) return {
2170
+ found: [],
2171
+ error: others.length > 0 ? `Something answers at 127.0.0.1:${options.port} on ${destination}, but not as Ollama or an OpenAI-compatible server. Check the port.` : `SSH to ${destination} works, but nothing answers at 127.0.0.1:${options.port} there. Start the model server on that machine, or check its port.${ambiguous ? FORWARDING_HINT : ""}`,
2172
+ refused: false
2173
+ };
2174
+ const answered = others.length > 0 ? ` Port ${others.join(" and ")} answered, but not as Ollama or an OpenAI-compatible server.` : "";
2175
+ return {
2176
+ found: [],
2177
+ error: `SSH to ${destination} works, but no model server answers on the usual ports there (${usualPorts()}). Start the server on that machine, or enter the port it listens on.${answered}${ambiguous ? FORWARDING_HINT : ""}`,
2178
+ refused: false
2179
+ };
2180
+ }
2181
+ /**
2182
+ * Finds the model servers on the far end's loopback: on `options.port` alone, or on every usual port at once after
2183
+ * the first request has logged in. Bounded by `deadlineMs` in all, and no request starts once it or `signal` has
2184
+ * ended. Sends only what `fetchFor` adds: callers attach a credential only with `options.port`, so a scan of the usual
2185
+ * ports carries none, and a server that wants one is reported with `needsCredentials`.
2186
+ */
2187
+ async function discoverSshServers(options) {
2188
+ const ports = options.port === void 0 ? SSH_DISCOVERY_PORTS.map(({ port }) => port) : [options.port];
2189
+ const deadline = new AbortController();
2190
+ const timer = setTimeout(() => deadline.abort(new DOMException("SSH discovery took too long", "TimeoutError")), deadlineOf(options));
2191
+ timer.unref?.();
2192
+ const signal = options.signal ? AbortSignal.any([deadline.signal, options.signal]) : deadline.signal;
2193
+ const gate = firstRequestAlone(options.destination, requestTimeout(options), options.port !== void 0);
2194
+ try {
2195
+ options.signal?.throwIfAborted();
2196
+ const results = await Promise.all(ports.map((port) => {
2197
+ let expired = false;
2198
+ return probePort(port, gate(timed(options.fetchFor(port), requestTimeout(options), () => {
2199
+ expired = true;
2200
+ })), options, signal, () => expired);
2201
+ }));
2202
+ options.signal?.throwIfAborted();
2203
+ const found = results.flatMap((result) => result.state === "found" ? [result.server] : []);
2204
+ if (found.length > 0) return {
2205
+ found,
2206
+ error: null,
2207
+ refused: false
2208
+ };
2209
+ return nothingFound(results, ports, options);
2210
+ } finally {
2211
+ clearTimeout(timer);
2212
+ }
2213
+ }
2214
+ /** Long enough for a busy server to produce the probe's one token. */
2215
+ const TOOLS_PROBE_TIMEOUT_MS = 2e4;
2216
+ const PROBE_TOOL = {
2217
+ type: "function",
2218
+ function: {
2219
+ name: "ping",
2220
+ description: "Replies pong.",
2221
+ parameters: {
2222
+ type: "object",
2223
+ properties: {}
2224
+ }
2225
+ }
2226
+ };
2227
+ /**
2228
+ * llama-server without --jinja (500), vLLM without --enable-auto-tool-choice (400, `"auto" tool choice requires
2229
+ * --enable-auto-tool-choice and --tool-call-parser to be set`), and some proxies refuse a request that declares tools.
2230
+ */
2231
+ function isToolRefusal(status, body) {
2232
+ if (status !== 400 && status !== 500) return false;
2233
+ return /\btools?\b/i.test(body);
2234
+ }
2235
+ /** isToolRefusal on a response, reading the body only for a status a refusal can have. */
2236
+ async function refusesTools(response) {
2237
+ if (response.status !== 400 && response.status !== 500) return false;
2238
+ return isToolRefusal(response.status, await response.clone().text());
2239
+ }
2240
+ /**
2241
+ * Asks with a one-token request that declares a tool; null when the answer says nothing about tool support,
2242
+ * including when `signal` aborts it.
2243
+ */
2244
+ async function probeToolSupport(fetch, baseUrl, model, timeoutMs = TOOLS_PROBE_TIMEOUT_MS, signal) {
2245
+ try {
2246
+ const timeout = AbortSignal.timeout(timeoutMs);
2247
+ const response = await fetch(`${baseUrl}/v1/chat/completions`, {
2248
+ method: "POST",
2249
+ headers: { "content-type": "application/json" },
2250
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
2251
+ body: JSON.stringify({
2252
+ model,
2253
+ messages: [{
2254
+ role: "user",
2255
+ content: "ping"
2256
+ }],
2257
+ max_tokens: 1,
2258
+ tools: [PROBE_TOOL]
2259
+ })
2260
+ });
2261
+ if (response.ok) {
2262
+ await response.body?.cancel();
2263
+ return "accepted";
2264
+ }
2265
+ if (await refusesTools(response)) return "refused";
2266
+ await response.body?.cancel();
2267
+ return null;
2268
+ } catch {
2269
+ return null;
2270
+ }
2271
+ }
2272
+ /** Why tools are off and how to turn them on, for the server's settings row and the chat it happened in. */
2273
+ function toolsOffHint(label, product, app) {
2274
+ if (product === "vllm") return `${label} was started without tool calling, so its chats run without tools. Restart vLLM with --enable-auto-tool-choice and a --tool-call-parser for the model, ${app.recheck}`;
2275
+ if (product === "llama-server") return `${label} refuses tool calls, so its chats run without tools. Restart llama-server with --jinja, ${app.recheck}`;
2276
+ return `${label} refuses tool calls, so its chats run without tools. Turn tool calling on there, ${app.recheck}`;
2277
+ }
2278
+ //#endregion
2279
+ //#region src/utils/shellWord.ts
2280
+ /** Quotes a word for a POSIX shell so a pasted command passes it as one argument. */
2281
+ const shellWord = (word) => /^[\w.:/@-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
2282
+ //#endregion
2283
+ //#region src/models/modelServers.ts
2284
+ /**
2285
+ * Model servers saved in Desktop (read-only) and the CLI's own copy of their credentials. Shared by
2286
+ * `b4m models` (src/commands/modelsCommand.ts) and the MCP model tools (src/mcp/modelTools.ts).
2287
+ */
2288
+ async function loadModelServers(read = readDesktopModelServers) {
2289
+ const { servers, problem, unusable } = await read();
2290
+ return {
2291
+ servers: servers.map((server) => ({
2292
+ ...server,
2293
+ source: "desktop"
2294
+ })),
2295
+ problem,
2296
+ ...unusable?.length ? { unusable } : {}
2297
+ };
2298
+ }
2299
+ function findModelServer(servers, name) {
2300
+ const wanted = name.trim().toLowerCase();
2301
+ return servers.find((server) => server.name === name) ?? servers.find((server) => server.name.toLowerCase() === wanted);
2302
+ }
2303
+ function unusableStatus(server) {
2304
+ return `${server.problem} Remove it in Desktop and add it again.`;
2305
+ }
2306
+ function unusableReason(server) {
2307
+ return `${clean(server.name)} cannot be used: ${unusableStatus(server)}`;
2308
+ }
2309
+ function findUnusableServer(loaded, name) {
2310
+ const wanted = name.trim().toLowerCase();
2311
+ return loaded.unusable?.find((server) => server.name.toLowerCase() === wanted);
2312
+ }
2313
+ function noSuchServer(loaded, name) {
2314
+ const unusable = findUnusableServer(loaded, name);
2315
+ if (unusable) return new Error(unusableReason(unusable));
2316
+ const known = loaded.servers.map((server) => clean(server.name)).join(", ");
2317
+ const detail = loaded.problem ?? (known ? `Saved servers: ${known}.` : "No model servers are saved in Desktop.");
2318
+ return /* @__PURE__ */ new Error(`No model server named ${clean(name)}. ${detail} See: b4m models servers`);
2319
+ }
2320
+ /** Headers for a server's credential; null when it needs none or the CLI has none yet. */
2321
+ function serverCredential(server, secret) {
2322
+ if (server.auth.type === "none" || !secret) return null;
2323
+ try {
2324
+ return server.auth.type === "bearer" ? credentialHeaders({
2325
+ type: "bearer",
2326
+ token: secret
2327
+ }) : credentialHeaders({
2328
+ type: "header",
2329
+ name: server.auth.name,
2330
+ value: secret
2331
+ });
2332
+ } catch {
2333
+ return null;
2334
+ }
2335
+ }
2336
+ /** Throws the shared rule's message (it names the field, never the value) when the secret cannot be sent. */
2337
+ function validateSecret(server, secret) {
2338
+ const trimmed = secret.trim();
2339
+ if (server.auth.type === "none") throw new Error(`${clean(server.name)} does not use credentials.`);
2340
+ if (server.auth.type === "bearer") credentialHeaders({
2341
+ type: "bearer",
2342
+ token: trimmed
2343
+ });
2344
+ else credentialHeaders({
2345
+ type: "header",
2346
+ name: server.auth.name,
2347
+ value: trimmed
2348
+ });
2349
+ return trimmed;
2350
+ }
2351
+ function needsCredential(server, secret) {
2352
+ return server.auth.type !== "none" && !serverCredential(server, secret);
2353
+ }
2354
+ function loginHint(server) {
2355
+ return `b4m models servers login ${shellWord(clean(server.name))}`;
2356
+ }
2357
+ /** The address to show; one the CLI cannot parse is not echoed, since it may carry a secret in its query. */
2358
+ function serverAddressLabel(server) {
2359
+ const { transport } = server;
2360
+ if (transport.type === "ssh") return `ssh ${transport.destination}${transport.port === 11434 ? "" : ` port ${transport.port}`}`;
2361
+ return parseServerAddress(transport.baseUrl)?.baseUrl ?? "unusable address";
2362
+ }
2363
+ /** Where requests go: the address, or for SSH the port on the far end's loopback; null when unusable. */
2364
+ function serverBaseUrl(server) {
2365
+ const { transport } = server;
2366
+ if (transport.type === "ssh") return sshServerUrl(transport.port);
2367
+ return parseServerAddress(transport.baseUrl)?.baseUrl ?? null;
2368
+ }
2369
+ /** Ends every request when `signal` aborts too, so a cancel stops an ssh already running. */
2370
+ const withSignal = (fetch, signal) => (input, init) => fetch(input, {
2371
+ ...init,
2372
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
2373
+ });
2374
+ function serverFetch(server, secret, sshFetchFor = (endpoint) => createSshFetch(endpoint)) {
2375
+ const { transport } = server;
2376
+ if (transport.type === "ssh") return sshFetchFor({
2377
+ destination: transport.destination,
2378
+ port: transport.port,
2379
+ label: server.name,
2380
+ app: "The CLI",
2381
+ credentialHeaders: () => server.kind === "ollama" ? null : serverCredential(server, secret)
2382
+ });
2383
+ const parsed = parseServerAddress(transport.baseUrl);
2384
+ if (!parsed) throw new Error(`${clean(server.name)} has an address the CLI cannot use.`);
2385
+ return createServerFetch({
2386
+ origin: parsed.origin,
2387
+ label: server.name,
2388
+ app: "The CLI",
2389
+ credentialHeaders: () => serverCredential(server, secret)
2390
+ });
2391
+ }
2392
+ function serverRedactor(server, secret) {
2393
+ return credentialRedactor(serverCredential(server, secret));
2394
+ }
2395
+ function runtimeFor(server, fetch, kind = server.kind, product = null) {
2396
+ const baseUrl = serverBaseUrl(server);
2397
+ if (!baseUrl) throw new Error(`${clean(server.name)} has an address the CLI cannot use.`);
2398
+ const id = serverRuntimeId(server.id);
2399
+ return kind === "ollama" ? new OllamaRuntime({
2400
+ baseUrl,
2401
+ id,
2402
+ fetch,
2403
+ redact: redactServerResponse
2404
+ }) : new OpenAICompatibleRuntime({
2405
+ baseUrl,
2406
+ id,
2407
+ fetch,
2408
+ product
2409
+ });
2410
+ }
2411
+ function productLabel(kind, product) {
2412
+ if (kind === "ollama") return "Ollama";
2413
+ if (product === "vllm") return "vLLM";
2414
+ if (product === "llama-server") return "llama-server";
2415
+ if (product === "lmstudio") return "LM Studio";
2416
+ if (product === "llama-swap") return "llama-swap";
2417
+ return "OpenAI-compatible";
2418
+ }
2419
+ /** Pull and remove only where Desktop lets this server be managed. */
2420
+ function requireManageable(server) {
2421
+ const management = serverManagement(server);
2422
+ if (management === "allowed") return;
2423
+ const name = clean(server.name);
2424
+ if (management === "chat-only") throw new Error(`${name} is set to Chat only in Desktop.`);
2425
+ throw new Error(`${name} is an OpenAI-compatible server; it serves the models it was started with and has no pull or remove.`);
2426
+ }
2427
+ /** The default model's name when it is one on this target's saved server, else the bare default. */
2428
+ function defaultOn(target, defaultModel) {
2429
+ if (!target.server) return defaultModel;
2430
+ const parsed = defaultModel ? parseLocalModelId(defaultModel) : null;
2431
+ return parsed?.runtimeId === serverRuntimeId(target.server.id) ? parsed.model : void 0;
2432
+ }
2433
+ const now = () => performance.now();
2434
+ /** Probes the server with the CLI's credential and returns a runtime for it; throws a plain-language reason when it is not usable. */
2435
+ async function resolveServerTarget(server, secret, fetch, probeTimeoutMs) {
2436
+ const name = clean(server.name);
2437
+ if (needsCredential(server, secret)) throw new Error(`${name} needs credentials. Run: ${loginHint(server)}`);
2438
+ const baseUrl = serverBaseUrl(server);
2439
+ if (!baseUrl) throw new Error(`${name} has an address the CLI cannot use.`);
2440
+ const timeout = probeTimeoutMs ?? (server.transport.type === "ssh" ? 2e4 : void 0);
2441
+ const outcome = await probeServer(fetch, baseUrl, server.name, now, server.kind, timeout);
2442
+ if (!outcome.kind) {
2443
+ if (outcome.auth) {
2444
+ const refused = secret ? `${name} refused the saved credentials.` : `${name} needs credentials.`;
2445
+ throw new Error(`${refused} Run: ${loginHint(server)}`);
2446
+ }
2447
+ if (outcome.forbidden) throw new Error(clean(forbiddenMessage(server.name)));
2448
+ const redactor = serverRedactor(server, secret);
2449
+ const reason = outcome.error ?? `Could not reach ${server.name}.`;
2450
+ throw new Error(clean(redactor ? redactor.redact(reason) : reason));
2451
+ }
2452
+ const redactor = serverRedactor(server, secret);
2453
+ return {
2454
+ runtime: runtimeFor(server, fetch, outcome.kind, outcome.product),
2455
+ source: "server",
2456
+ server: {
2457
+ id: server.id,
2458
+ name: server.name
2459
+ },
2460
+ product: outcome.product,
2461
+ ...redactor && { redact: (text) => redactor.redact(text) }
2462
+ };
2463
+ }
2464
+ //#endregion
2465
+ export { gatedMessage as $, serverRuntimeId as A, parseGenerationInput as B, discoverSshServers as C, withDefaultOllamaPort as Ct, probeServer as D, parseSshPort as E, GENERATION_FIELDS as F, NO_LICENSE as G, parseModelContextSetting as H, LOCAL_OLLAMA_RUNTIME_ID as I, abortable as J, REF_ISSUES as K, REASONING_EFFORT_SETTINGS as L, toolsOffHint as M, transportVerdict as N, probeToolSupport as O, usualPorts as P, formatBytes as Q, effortSent as R, desktopUserDataFile as S, DEFAULT_OLLAMA_PORT as St, parseServerAddress as T, CancelledError as U, parseLocalModelId as V, NOT_RECOMMENDED_LABEL as W, clean as X, buildTag as Y, findInstalledModel as Z, shellWord as _, resolveRuntimeTarget as _t, needsCredential as a, licenseFor as at, answersWithoutCredentials as b, shortDigest as bt, requireManageable as c, pickBuild as ct, serverBaseUrl as d, removeInstalled as dt, hadTagBefore as et, serverFetch as f, requireInstalledReviewed as ft, withSignal as g, requireUnchangedManifest as gt, validateSecret as h, requireUnchangedLicenses as ht, loginHint as i, largestProjectorBytes as it, sshDestinationProblem as j, scopeOfIp as k, resolveServerTarget as l, planPull as lt, unusableStatus as m, requireReviewedLayers as mt, findModelServer as n, hubAccessMessage as nt, noSuchServer as o, licenseName as ot, serverRedactor as p, requireRemovable as pt, UNPULLABLE as q, loadModelServers as r, installedUncheckedMessage as rt, productLabel as s, listInstalled as st, defaultOn as t, hiddenAbliteratedMessage as tt, serverAddressLabel as u, rankSearchHits as ut, SSH_PORT_PROBLEM as v, runtimeLabel as vt, leastTrusted as w, createSshFetch as x, readOllamaManifest as xt, SSH_PROBE_TIMEOUT_MS as y, sameModelName as yt, localModelId as z };