@bike4mind/cli 4.0.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +184 -4
  2. package/bin/bike4mind-cli.mjs +249 -40
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/dist/{AgentHistoryStore-DgqmcVLN.mjs → AgentHistoryStore-Bvmcy2kf.mjs} +3807 -1375
  6. package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-Yp2LPlX3.mjs} +22 -3
  7. package/dist/BubblewrapRuntime-OI4qFPNB.mjs +157 -0
  8. package/dist/ConfigStore-Bo4od3Eu.mjs +2 -0
  9. package/dist/ConfigStore-CP1W86Ui.mjs +3438 -0
  10. package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-3RbeTZ9o.mjs} +34769 -22138
  11. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  12. package/dist/{RemoteSkillSource-qTvRkaNA.mjs → RemoteSkillSource-D_F99yBR.mjs} +5 -0
  13. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-lpxVEFO7.mjs} +26 -7
  14. package/dist/SandboxRuntimeAdapter-C3xICJtQ.mjs +190 -0
  15. package/dist/SandboxRuntimeAdapter-u6c_IrjP.mjs +2 -0
  16. package/dist/SeatbeltRuntime-Ccd_QbjX.mjs +194 -0
  17. package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-D4sFGL9X.mjs} +1 -1
  18. package/dist/agents/defaults/review.md +8 -1
  19. package/dist/agents/defaults/test.md +8 -1
  20. package/dist/buildToolSearch-CqHKSLtG.mjs +417 -0
  21. package/dist/commands/acpCommand.mjs +26 -20
  22. package/dist/commands/apiCommand.mjs +3 -5
  23. package/dist/commands/doctorCommand.mjs +2 -2
  24. package/dist/commands/envCommand.mjs +1 -1
  25. package/dist/commands/headlessCommand.mjs +118 -37
  26. package/dist/commands/hostCommand.mjs +2344 -0
  27. package/dist/commands/mcpCommand.mjs +45 -30
  28. package/dist/commands/mirrorCommand.mjs +279 -0
  29. package/dist/commands/modelsCommand.mjs +1117 -0
  30. package/dist/commands/pluginCommand.mjs +9 -9
  31. package/dist/commands/skillsCommand.mjs +175 -30
  32. package/dist/commands/updateCommand.mjs +2 -2
  33. package/dist/curated-build.json +1 -0
  34. package/dist/dist-BPhZ0dCz.mjs +4776 -0
  35. package/dist/dist-K7a9yOUb.mjs +7864 -0
  36. package/dist/fit-BOnDsgbk.mjs +200 -0
  37. package/dist/{grepSearch-BgoOOwGe-B388GxRD.mjs → grepSearch-CLtEqT4j-BnKPtNWr.mjs} +2 -2
  38. package/dist/index.mjs +3215 -508
  39. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  40. package/dist/modelServers-B7zI5XnO.mjs +2465 -0
  41. package/dist/{package-CQaam4Dq.mjs → package-WlxLVpUb.mjs} +1 -1
  42. package/dist/{serve-CFxUhjml.mjs → serve-DpsV0mag.mjs} +599 -26
  43. package/dist/store-Bpdo9Syo.mjs +2 -0
  44. package/dist/{store-BbvSi3KK.mjs → store-xeJRhBtO.mjs} +2 -0
  45. package/dist/types-BFIvwByC.mjs +2 -0
  46. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  47. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-Boq0RruU.mjs} +7 -29
  48. package/package.json +17 -14
  49. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  50. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  51. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  52. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  53. package/dist/buildToolSearch-D9GEK91u.mjs +0 -2351
  54. package/dist/dist-Ul2qwn5x.mjs +0 -624
  55. package/dist/store-BYeE0shc.mjs +0 -2
  56. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -0,0 +1,2344 @@
1
+ #!/usr/bin/env node
2
+ import { f as PULL_JOB_ACTIVE_STATES, g as PullJobSchema, h as PullJobRequestSchema, m as PullJobActionSchema, o as MODEL_HOST_ROLES, p as PULL_JOB_FINAL_STATES, s as ModelHostHelloSchema } from "../modelHub-BSB6qRFP.mjs";
3
+ import { A as curatedLibrary, B as isCuratedListable, E as HuggingFaceHub, F as curatedRunner, G as ollamaLibraryLayers, J as ollamaRefAliases, K as ollamaModelKey, P as curatedPins, U as loadCuratedManifest, W as lockFile, X as ModelFileBusyError, Z as ModelNotFoundError, a as checkApproval, f as licensesChanged, g as probeModelHost, i as OllamaRuntime, o as checkInstalledBlob, q as ollamaPullRef, r as DEFAULT_OLLAMA_URL, s as checkInstalledDigest, v as sameRepo } from "../dist-K7a9yOUb.mjs";
4
+ import { join } from "node:path";
5
+ import { constants } from "node:fs";
6
+ import { z as z$1 } from "zod";
7
+ import { randomBytes, randomUUID } from "node:crypto";
8
+ import { parseArgs } from "node:util";
9
+ import { homedir, hostname, userInfo } from "node:os";
10
+ import { appendFile, chmod, chown, lstat, mkdir, open, readFile, readdir, rename, rm, stat, statfs } from "node:fs/promises";
11
+ import { connect, createConnection, createServer } from "node:net";
12
+ import { createServer as createServer$1, request } from "node:http";
13
+ function connectOnce(path) {
14
+ return new Promise((resolve, reject) => {
15
+ const socket = createConnection({ path });
16
+ socket.once("connect", () => {
17
+ socket.off("error", reject);
18
+ resolve(socket);
19
+ });
20
+ socket.once("error", reject);
21
+ });
22
+ }
23
+ /** Connects to the first socket that accepts; otherwise says whether the host is down or out of reach. */
24
+ async function dialFirst(candidates) {
25
+ let refused = null;
26
+ let denied = null;
27
+ let other = null;
28
+ for (const path of candidates) try {
29
+ return {
30
+ ok: true,
31
+ socket: await connectOnce(path),
32
+ path
33
+ };
34
+ } catch (error) {
35
+ const code = error.code;
36
+ if (code === "ECONNREFUSED") refused ??= path;
37
+ else if (code === "EACCES" || code === "EPERM") denied ??= path;
38
+ else if (code !== "ENOENT" && code !== "ENOTDIR") other ??= {
39
+ path,
40
+ message: error instanceof Error ? error.message : String(error)
41
+ };
42
+ }
43
+ if (refused) return {
44
+ ok: false,
45
+ failure: "not-running",
46
+ path: refused,
47
+ message: notRunningMessage()
48
+ };
49
+ if (denied) return {
50
+ ok: false,
51
+ failure: "no-access",
52
+ path: denied,
53
+ message: noAccessMessage(denied)
54
+ };
55
+ if (other) return {
56
+ ok: false,
57
+ failure: "error",
58
+ path: other.path,
59
+ message: other.message
60
+ };
61
+ return {
62
+ ok: false,
63
+ failure: "not-running",
64
+ path: null,
65
+ message: notRunningMessage()
66
+ };
67
+ }
68
+ function login() {
69
+ try {
70
+ return userInfo().username;
71
+ } catch {
72
+ return process.env.USER ?? `uid${process.getuid?.() ?? ""}`;
73
+ }
74
+ }
75
+ function notRunningMessage() {
76
+ return "b4m-host is not running. Start it with: sudo systemctl start b4m-host (for a user install: systemctl --user start b4m-host)";
77
+ }
78
+ function noAccessMessage(path) {
79
+ return `No permission to use ${path}. Ask an administrator to run: sudo usermod -aG b4m-host ${login()} (then sign in again so the new group applies). If the b4m-host group does not exist yet, create it first with sudo groupadd b4m-host and restart b4m-host so its sockets take the group.`;
80
+ }
81
+ function exitCodeFor(failure) {
82
+ if (failure === "not-running") return 3;
83
+ if (failure === "no-access") return 4;
84
+ return 1;
85
+ }
86
+ /** Bridges stdin and stdout to the host's socket, after one preamble line naming the caller. */
87
+ async function dialStdio(options) {
88
+ const dialed = await dialFirst(options.candidates);
89
+ if (!dialed.ok) {
90
+ options.stderr.write(`b4m-host: ${dialed.message}\n`);
91
+ return exitCodeFor(dialed.failure);
92
+ }
93
+ const { socket } = dialed;
94
+ const label = login().replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 64);
95
+ socket.write(`B4M-DIAL 1 user=${label} uid=${process.getuid?.() ?? -1}\n`);
96
+ return new Promise((resolve) => {
97
+ let failed = false;
98
+ let received = false;
99
+ socket.on("error", (error) => {
100
+ failed = true;
101
+ options.stderr.write(`b4m-host: ${error.message}\n`);
102
+ socket.destroy();
103
+ });
104
+ options.stdout.on("error", () => {
105
+ failed = true;
106
+ socket.destroy();
107
+ });
108
+ socket.on("data", () => received = true);
109
+ options.stdin.pipe(socket);
110
+ socket.pipe(options.stdout, { end: false });
111
+ socket.on("end", () => {
112
+ options.stdin.unpipe(socket);
113
+ socket.end();
114
+ });
115
+ socket.on("close", () => {
116
+ options.stdin.unpipe(socket);
117
+ if (!received && !failed) {
118
+ failed = true;
119
+ options.stderr.write("b4m-host: the host closed the connection\n");
120
+ }
121
+ options.stdout.write("", () => resolve(failed ? 1 : 0));
122
+ });
123
+ });
124
+ }
125
+ /** `GET /v1/hello` on one socket. */
126
+ function fetchHello(path, timeoutMs = 1e4) {
127
+ return new Promise((resolve, reject) => {
128
+ const req = request({
129
+ socketPath: path,
130
+ path: "/v1/hello",
131
+ method: "GET",
132
+ timeout: timeoutMs
133
+ }, (res) => {
134
+ const chunks = [];
135
+ let size = 0;
136
+ res.on("data", (chunk) => {
137
+ size += chunk.length;
138
+ if (size > 65536) req.destroy(/* @__PURE__ */ new Error("hello response too large"));
139
+ else chunks.push(chunk);
140
+ });
141
+ res.on("end", () => {
142
+ try {
143
+ if (res.statusCode !== 200) throw new Error(`hello returned HTTP ${res.statusCode}`);
144
+ resolve(ModelHostHelloSchema.parse(JSON.parse(Buffer.concat(chunks).toString("utf8"))));
145
+ } catch (error) {
146
+ reject(error);
147
+ }
148
+ });
149
+ });
150
+ req.on("timeout", () => req.destroy(/* @__PURE__ */ new Error("hello timed out")));
151
+ req.on("error", reject);
152
+ req.end();
153
+ });
154
+ }
155
+ //#endregion
156
+ //#region ../model-host/src/paths.ts
157
+ const SYSTEM_SOCKET_DIR = "/run/b4m-host";
158
+ const SYSTEM_STATE_DIR = "/var/lib/b4m-host";
159
+ const MANAGE_GROUP = "b4m-host";
160
+ const ADMIN_GROUP = "b4m-host-admin";
161
+ function userRuntimeDir(env) {
162
+ if (env.XDG_RUNTIME_DIR) return env.XDG_RUNTIME_DIR;
163
+ const uid = process.getuid?.();
164
+ return uid === void 0 ? null : `/run/user/${uid}`;
165
+ }
166
+ function defaultSocketDir(mode, env = process.env) {
167
+ if (mode === "system") return SYSTEM_SOCKET_DIR;
168
+ const runtime = userRuntimeDir(env);
169
+ if (!runtime) throw new Error("XDG_RUNTIME_DIR is not set; pass --socket-dir");
170
+ return join(runtime, "b4m-host");
171
+ }
172
+ function defaultStateDir(mode, env = process.env) {
173
+ if (mode === "system") return SYSTEM_STATE_DIR;
174
+ return join(env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "b4m-host");
175
+ }
176
+ /** A system host has one socket per role, each gated by a group; a user host has one admin socket for its owner. */
177
+ function socketSpecs(mode, dir) {
178
+ if (mode === "user") return [{
179
+ role: "admin",
180
+ path: join(dir, "admin.sock"),
181
+ group: null
182
+ }];
183
+ return [{
184
+ role: "manage",
185
+ path: join(dir, "manage.sock"),
186
+ group: MANAGE_GROUP
187
+ }, {
188
+ role: "admin",
189
+ path: join(dir, "admin.sock"),
190
+ group: ADMIN_GROUP
191
+ }];
192
+ }
193
+ /** Sockets a client tries in order: the highest role first, a system host before a user one. */
194
+ function dialCandidates(socketDir, env = process.env) {
195
+ if (socketDir) return [join(socketDir, "admin.sock"), join(socketDir, "manage.sock")];
196
+ const candidates = [join(SYSTEM_SOCKET_DIR, "admin.sock"), join(SYSTEM_SOCKET_DIR, "manage.sock")];
197
+ const runtime = userRuntimeDir(env);
198
+ if (runtime) candidates.push(join(runtime, "b4m-host", "admin.sock"));
199
+ return candidates;
200
+ }
201
+ /** The gid of a group in `/etc/group`, or null when it has none there. */
202
+ async function lookupGroupId(name, groupFile = "/etc/group") {
203
+ const text = await readFile(groupFile, "utf8").catch(() => "");
204
+ for (const line of text.split("\n")) {
205
+ const [group, , gid] = line.split(":");
206
+ if (group === name && gid && /^\d+$/.test(gid)) return Number(gid);
207
+ }
208
+ return null;
209
+ }
210
+ //#endregion
211
+ //#region ../model-host/src/cached.ts
212
+ function withDeadline(promise, timeoutMs, timeoutError) {
213
+ let timer;
214
+ const deadline = new Promise((_, reject) => {
215
+ timer = setTimeout(() => reject(timeoutError()), timeoutMs);
216
+ timer.unref();
217
+ });
218
+ return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
219
+ }
220
+ /** Reuses a result for `maxAgeMs` and shares one call among concurrent callers; a failure is not kept. */
221
+ function cached(load, maxAgeMs, options = {}) {
222
+ const now = options.now ?? Date.now;
223
+ const timeoutMs = options.timeoutMs;
224
+ const timeoutError = options.timeoutError ?? (() => /* @__PURE__ */ new Error(`Timed out after ${timeoutMs} ms`));
225
+ let value = null;
226
+ let pending = null;
227
+ /** The load itself, kept until it settles even after its callers gave up on it. */
228
+ let running = null;
229
+ return () => {
230
+ if (value && now() - value.at < maxAgeMs) return Promise.resolve(value.result);
231
+ if (pending) return pending;
232
+ if (running) return Promise.reject(timeoutError());
233
+ const loading = load().then((result) => {
234
+ value = {
235
+ at: now(),
236
+ result
237
+ };
238
+ return result;
239
+ });
240
+ const settled = () => {
241
+ if (running === loading) running = null;
242
+ };
243
+ loading.then(settled, settled);
244
+ running = loading;
245
+ const attempt = (timeoutMs ? withDeadline(loading, timeoutMs, timeoutError) : loading).finally(() => {
246
+ if (pending === attempt) pending = null;
247
+ });
248
+ pending = attempt;
249
+ return attempt;
250
+ };
251
+ }
252
+ //#endregion
253
+ //#region ../model-host/src/rateLimit.ts
254
+ /** A token bucket: `capacity` requests at once, refilled at `perSecond`. */
255
+ var TokenBucket = class {
256
+ #tokens;
257
+ #last;
258
+ constructor(capacity, perSecond, now = () => performance.now()) {
259
+ this.capacity = capacity;
260
+ this.perSecond = perSecond;
261
+ this.now = now;
262
+ this.#tokens = capacity;
263
+ this.#last = now();
264
+ }
265
+ #refill() {
266
+ const now = this.now();
267
+ this.#tokens = Math.min(this.capacity, this.#tokens + Math.max(0, now - this.#last) / 1e3 * this.perSecond);
268
+ this.#last = now;
269
+ }
270
+ take() {
271
+ this.#refill();
272
+ if (this.#tokens < 1) return false;
273
+ this.#tokens -= 1;
274
+ return true;
275
+ }
276
+ /** Whole seconds until the next request would be let through. */
277
+ retryAfterSeconds() {
278
+ this.#refill();
279
+ return Math.max(1, Math.ceil((1 - this.#tokens) / this.perSecond));
280
+ }
281
+ };
282
+ //#endregion
283
+ //#region ../model-host/src/server.ts
284
+ const DEFAULT_LIMITS = {
285
+ bodyBytes: 65536,
286
+ headerBytes: 16384,
287
+ preambleBytes: 256,
288
+ firstByteTimeoutMs: 1e4,
289
+ idleTimeoutMs: 3e4,
290
+ keepAliveTimeoutMs: 5e3,
291
+ maxConnections: 64,
292
+ rateBurst: 120,
293
+ ratePerSecond: 20
294
+ };
295
+ var HttpError = class extends Error {
296
+ constructor(status, code, message, headers = {}) {
297
+ super(message);
298
+ this.status = status;
299
+ this.code = code;
300
+ this.headers = headers;
301
+ }
302
+ };
303
+ function sendJson(res, status, body, headers = {}) {
304
+ const text = JSON.stringify(body);
305
+ res.writeHead(status, {
306
+ "content-type": "application/json",
307
+ "content-length": Buffer.byteLength(text),
308
+ "cache-control": "no-store",
309
+ ...headers
310
+ });
311
+ res.end(text);
312
+ }
313
+ function sendError(res, error) {
314
+ if (res.headersSent) {
315
+ res.destroy();
316
+ return;
317
+ }
318
+ const body = {
319
+ code: error.code,
320
+ message: error.message
321
+ };
322
+ sendJson(res, error.status, body, error.headers);
323
+ }
324
+ const PREAMBLE_PREFIX = Buffer.from("B4M-DIAL ");
325
+ /** The login from `B4M-DIAL 1 user=<login> uid=<uid>`, when it is a plain account name. */
326
+ function parsePreamble(line) {
327
+ if (!/^B4M-DIAL 1(?: .*)?$/.exec(line)) return null;
328
+ return /(?:^| )user=([A-Za-z0-9._-]{1,64})(?: |$)/.exec(line)?.[1] ?? null;
329
+ }
330
+ /** Reads an optional preamble line; anything else is handed back untouched for the HTTP parser. */
331
+ function readPreamble(socket, limits) {
332
+ return new Promise((resolve) => {
333
+ let buffered = Buffer.alloc(0);
334
+ const finish = (result) => {
335
+ clearTimeout(timer);
336
+ socket.off("data", onData);
337
+ socket.off("close", onClose);
338
+ socket.pause();
339
+ resolve(result);
340
+ };
341
+ const onData = (chunk) => {
342
+ buffered = Buffer.concat([buffered, chunk]);
343
+ const n = Math.min(buffered.length, PREAMBLE_PREFIX.length);
344
+ if (!buffered.subarray(0, n).equals(PREAMBLE_PREFIX.subarray(0, n))) return finish({
345
+ login: null,
346
+ rest: buffered
347
+ });
348
+ if (buffered.length < PREAMBLE_PREFIX.length) return;
349
+ const newline = buffered.indexOf(10);
350
+ if (newline === -1 ? buffered.length > limits.preambleBytes : newline > limits.preambleBytes) return finish(null);
351
+ if (newline === -1) return;
352
+ const line = buffered.subarray(0, newline).toString("latin1").replace(/\r$/, "");
353
+ finish({
354
+ login: parsePreamble(line),
355
+ rest: buffered.subarray(newline + 1)
356
+ });
357
+ };
358
+ const onClose = () => finish(null);
359
+ const timer = setTimeout(() => finish(null), limits.firstByteTimeoutMs);
360
+ socket.on("data", onData);
361
+ socket.on("close", onClose);
362
+ socket.resume();
363
+ });
364
+ }
365
+ function readBody(req, limit) {
366
+ const tooLarge = () => new HttpError(413, "body-too-large", `Request bodies are limited to ${limit} bytes.`, { connection: "close" });
367
+ return new Promise((resolve, reject) => {
368
+ const declared = req.headers["content-length"];
369
+ if (declared !== void 0 && Number(declared) > limit) return reject(tooLarge());
370
+ const chunks = [];
371
+ let size = 0;
372
+ const cleanup = () => {
373
+ req.off("data", onData);
374
+ req.off("end", onEnd);
375
+ req.off("error", onError);
376
+ };
377
+ const onData = (chunk) => {
378
+ size += chunk.length;
379
+ if (size > limit) {
380
+ cleanup();
381
+ req.pause();
382
+ reject(tooLarge());
383
+ return;
384
+ }
385
+ chunks.push(chunk);
386
+ };
387
+ const onEnd = () => {
388
+ cleanup();
389
+ resolve(Buffer.concat(chunks));
390
+ };
391
+ const onError = (error) => {
392
+ cleanup();
393
+ reject(error);
394
+ };
395
+ req.on("data", onData);
396
+ req.on("end", onEnd);
397
+ req.on("error", onError);
398
+ });
399
+ }
400
+ /** HTTP over Unix sockets, one per role: a connection's role is the socket it came in on. */
401
+ var HostServer = class {
402
+ #http;
403
+ #listeners = [];
404
+ #connections = /* @__PURE__ */ new WeakMap();
405
+ #sockets = /* @__PURE__ */ new Set();
406
+ constructor(handler, limits = {}, log = () => {}) {
407
+ this.handler = handler;
408
+ this.log = log;
409
+ this.limits = {
410
+ ...DEFAULT_LIMITS,
411
+ ...limits
412
+ };
413
+ this.#http = createServer$1({ maxHeaderSize: this.limits.headerBytes }, (req, res) => void this.#request(req, res));
414
+ this.#http.timeout = this.limits.idleTimeoutMs;
415
+ this.#http.keepAliveTimeout = this.limits.keepAliveTimeoutMs;
416
+ Object.assign(this.#http, { httpAllowHalfOpen: true });
417
+ }
418
+ get listeners() {
419
+ return this.#listeners.map((listener) => listener.spec);
420
+ }
421
+ async #request(req, res) {
422
+ const conn = this.#connections.get(req.socket);
423
+ try {
424
+ if (!conn) throw new HttpError(500, "internal", "Unknown connection.");
425
+ if (!conn.bucket.take()) throw new HttpError(429, "rate-limited", "Too many requests; try again shortly.", { "retry-after": String(conn.bucket.retryAfterSeconds()) });
426
+ const body = await readBody(req, this.limits.bodyBytes);
427
+ await this.handler({
428
+ req,
429
+ res,
430
+ conn: {
431
+ role: conn.role,
432
+ login: conn.login
433
+ },
434
+ body
435
+ });
436
+ } catch (error) {
437
+ if (error instanceof HttpError) {
438
+ sendError(res, error);
439
+ return;
440
+ }
441
+ this.log(`request failed: ${error instanceof Error ? error.message : String(error)}`);
442
+ sendError(res, new HttpError(500, "internal", "Internal error."));
443
+ }
444
+ }
445
+ async #accept(socket, listener) {
446
+ this.#sockets.add(socket);
447
+ socket.on("close", () => this.#sockets.delete(socket));
448
+ socket.on("error", () => socket.destroy());
449
+ const preamble = await readPreamble(socket, this.limits);
450
+ if (!preamble) {
451
+ socket.destroy();
452
+ return;
453
+ }
454
+ this.#connections.set(socket, {
455
+ role: listener.spec.role,
456
+ login: preamble.login,
457
+ bucket: listener.bucket
458
+ });
459
+ if (preamble.rest.length) socket.unshift(preamble.rest);
460
+ this.#http.emit("connection", socket);
461
+ socket.resume();
462
+ }
463
+ /** Creates the socket with no access beyond its owner until its group and mode are set. */
464
+ async listen(spec) {
465
+ if (Buffer.byteLength(spec.path) > 107) throw new Error(`Socket path is longer than 107 bytes: ${spec.path}`);
466
+ const server = createServer({
467
+ allowHalfOpen: true,
468
+ pauseOnConnect: true
469
+ });
470
+ server.maxConnections = this.limits.maxConnections;
471
+ const listener = {
472
+ spec,
473
+ server,
474
+ bucket: new TokenBucket(this.limits.rateBurst, this.limits.ratePerSecond)
475
+ };
476
+ server.on("connection", (socket) => void this.#accept(socket, listener));
477
+ const previous = process.umask(127);
478
+ try {
479
+ await new Promise((resolve, reject) => {
480
+ server.once("error", reject);
481
+ server.listen(spec.path, () => {
482
+ server.off("error", reject);
483
+ resolve();
484
+ });
485
+ });
486
+ } finally {
487
+ process.umask(previous);
488
+ }
489
+ try {
490
+ if (spec.gid !== null) await chown(spec.path, -1, spec.gid);
491
+ await chmod(spec.path, spec.mode);
492
+ } catch (error) {
493
+ await new Promise((resolve) => server.close(() => resolve()));
494
+ await rm(spec.path, { force: true });
495
+ throw error;
496
+ }
497
+ server.on("error", (error) => this.log(`socket ${spec.path}: ${error.message}`));
498
+ this.#listeners.push(listener);
499
+ }
500
+ /** Closing a listener also removes its socket file. */
501
+ async close() {
502
+ const closed = this.#listeners.splice(0).map(({ server }) => new Promise((resolve) => server.close(() => resolve())));
503
+ for (const socket of this.#sockets) socket.destroy();
504
+ this.#http.closeAllConnections();
505
+ await Promise.all(closed);
506
+ }
507
+ };
508
+ //#endregion
509
+ //#region ../model-host/src/router.ts
510
+ const rank = (role) => MODEL_HOST_ROLES.indexOf(role);
511
+ function roleAllows(have, need) {
512
+ return rank(have) >= rank(need);
513
+ }
514
+ const echoed = (path) => path.length > 200 ? `${path.slice(0, 200)}...` : path;
515
+ function matchPath(pattern, path) {
516
+ const want = pattern.split("/");
517
+ const got = path.split("/");
518
+ if (want.length !== got.length) return null;
519
+ const params = {};
520
+ for (let i = 0; i < want.length; i++) {
521
+ if (!want[i].startsWith(":")) {
522
+ if (want[i] !== got[i]) return null;
523
+ continue;
524
+ }
525
+ if (!got[i]) return null;
526
+ try {
527
+ params[want[i].slice(1)] = decodeURIComponent(got[i]);
528
+ } catch {
529
+ return null;
530
+ }
531
+ }
532
+ return params;
533
+ }
534
+ function createRouter(routes) {
535
+ return async (ctx) => {
536
+ const path = new URL(ctx.req.url ?? "/", "http://b4m-host").pathname;
537
+ const matches = routes.flatMap((route) => {
538
+ const params = matchPath(route.path, path);
539
+ return params ? [{
540
+ route,
541
+ params
542
+ }] : [];
543
+ });
544
+ if (!matches.length) throw new HttpError(404, "not-found", `No route ${echoed(path)}.`);
545
+ const match = matches.find((candidate) => candidate.route.method === ctx.req.method);
546
+ if (!match) throw new HttpError(405, "method-not-allowed", `${echoed(path)} does not take ${echoed(ctx.req.method ?? "")}.`, { allow: [...new Set(matches.map((candidate) => candidate.route.method))].join(", ") });
547
+ const { route, params } = match;
548
+ if (!roleAllows(ctx.conn.role, route.role)) throw new HttpError(403, "forbidden", `${echoed(path)} needs the ${route.role} role; this connection has ${ctx.conn.role}.`);
549
+ await route.handle({
550
+ ...ctx,
551
+ params
552
+ });
553
+ };
554
+ }
555
+ //#endregion
556
+ //#region ../model-host/src/events.ts
557
+ const frame = (event) => `event: ${event.event}\ndata: ${JSON.stringify(event.data)}\n\n`;
558
+ /**
559
+ * `GET /v1/events`: server-sent `host` events, the current facts first and then whenever they change, plus whatever
560
+ * `publish` sends to streams whose role allows it.
561
+ */
562
+ var HostEvents = class {
563
+ #streams = /* @__PURE__ */ new Map();
564
+ #timer = null;
565
+ #failing = false;
566
+ constructor(options) {
567
+ this.options = options;
568
+ }
569
+ get size() {
570
+ return this.#streams.size;
571
+ }
572
+ async #read() {
573
+ try {
574
+ const data = JSON.stringify(await this.options.facts());
575
+ this.#failing = false;
576
+ return data;
577
+ } catch (error) {
578
+ if (!this.#failing) {
579
+ this.#failing = true;
580
+ this.options.log?.(`reading host facts for events failed: ${error instanceof Error ? error.message : String(error)}`);
581
+ }
582
+ return null;
583
+ }
584
+ }
585
+ #write(res, text) {
586
+ if (res.destroyed) return;
587
+ res.write(text);
588
+ if (res.writableLength > this.options.maxBufferedBytes) res.destroy();
589
+ }
590
+ #sendFacts(res, data) {
591
+ const stream = this.#streams.get(res);
592
+ if (!stream) return;
593
+ const fresh = data !== null && data !== stream.sent;
594
+ if (fresh) stream.sent = data;
595
+ this.#write(res, fresh ? `event: host\ndata: ${data}\n\n` : ": keepalive\n\n");
596
+ }
597
+ async #tick() {
598
+ const data = await this.#read();
599
+ for (const res of this.#streams.keys()) this.#sendFacts(res, data);
600
+ }
601
+ publish(event) {
602
+ const text = frame(event);
603
+ for (const [res, stream] of this.#streams) if (roleAllows(stream.role, event.role)) this.#write(res, text);
604
+ }
605
+ async subscribe(res, key, role) {
606
+ if ([...this.#streams.values()].filter((stream) => stream.key === key).length >= this.options.maxStreams) throw new HttpError(503, "too-many-streams", "Too many open event streams.");
607
+ res.writeHead(200, {
608
+ "content-type": "text/event-stream",
609
+ "cache-control": "no-store"
610
+ });
611
+ res.write("retry: 5000\n\n");
612
+ this.#streams.set(res, {
613
+ key,
614
+ role,
615
+ sent: null
616
+ });
617
+ res.on("close", () => {
618
+ this.#streams.delete(res);
619
+ if (!this.#streams.size && this.#timer) {
620
+ clearInterval(this.#timer);
621
+ this.#timer = null;
622
+ }
623
+ });
624
+ this.#timer ??= setInterval(() => void this.#tick(), this.options.intervalMs);
625
+ this.#sendFacts(res, await this.#read());
626
+ for (const event of this.options.snapshot?.() ?? []) if (roleAllows(role, event.role)) this.#write(res, frame(event));
627
+ }
628
+ close() {
629
+ if (this.#timer) clearInterval(this.#timer);
630
+ this.#timer = null;
631
+ for (const res of this.#streams.keys()) res.end();
632
+ this.#streams.clear();
633
+ }
634
+ };
635
+ //#endregion
636
+ //#region ../model-host/src/jobs.ts
637
+ const DEFAULT_FLOOR_BYTES = 2 * 1024 ** 3;
638
+ const STOP_WAIT_MS = 15e3;
639
+ const CHECK_TIMEOUT_MS = 3e4;
640
+ const L_MESSAGE = 1e3;
641
+ const ACTIVE = PULL_JOB_ACTIVE_STATES;
642
+ const FINAL = PULL_JOB_FINAL_STATES;
643
+ const isActive = (state) => ACTIVE.includes(state);
644
+ const isFinal = (state) => FINAL.includes(state);
645
+ const CONTROL = /[\u0000-\u001f\u007f]/g;
646
+ const clip = (text, max = L_MESSAGE) => {
647
+ const plain = text.replace(CONTROL, " ");
648
+ return plain.length > max ? `${plain.slice(0, max)}...` : plain;
649
+ };
650
+ const errorText = (error) => clip(error instanceof Error ? error.message : String(error));
651
+ const refuse = (code, message) => ({
652
+ ok: false,
653
+ code,
654
+ message
655
+ });
656
+ const joinNotices = (...notices) => {
657
+ const kept = [...new Set(notices.filter((notice) => !!notice))];
658
+ return kept.length ? clip(kept.join(" ")) : null;
659
+ };
660
+ /** Decimal gigabytes, as disks are sold. */
661
+ function formatGb(bytes) {
662
+ return `${(Math.max(0, bytes) / 1e9).toFixed(1)} GB`;
663
+ }
664
+ const sourceKey = (request) => request.source === "hf" ? `hf:${request.repo.toLowerCase()}:${request.buildId}` : `library:${request.ref}`;
665
+ const sourceName = (request) => request.source === "hf" ? request.repo : request.ref;
666
+ const reviewedModel = (build) => curatedLibrary(build)?.digest ?? build.weights[0]?.sha256 ?? "";
667
+ const PINNED = [
668
+ "template",
669
+ "params",
670
+ "license",
671
+ "projector",
672
+ "draft"
673
+ ];
674
+ /** True when the approved digests are exactly the build's weights and pinned layers. */
675
+ function layersMatch(approved, build) {
676
+ const pins = curatedPins(build);
677
+ if (!pins || approved.model !== reviewedModel(build)) return false;
678
+ return PINNED.every((kind) => (approved[kind] ?? null) === (pins[kind] ?? null));
679
+ }
680
+ /** Ollama reads a name without a tag as `<name>:latest`. */
681
+ const tagged = (name) => /:[^/]*$/.test(name) ? name : `${name}:latest`;
682
+ const modelKey = (name) => ollamaModelKey(tagged(name));
683
+ /** The repo part of `hf.co/<repo>:<tag>` or `huggingface.co/<repo>:<tag>`. */
684
+ const refRepo = (ref) => ref.replace(/^(?:hf\.co|huggingface\.co)\//, "").replace(/:[^/]*$/, "");
685
+ const GATED_NOTICE = "Hugging Face shows this file only to accounts with access, so b4m-host checked it after the download.";
686
+ const PRIVATE_NOTICE = "b4m-host cannot read this repo without access, so the check after the download is the only check.";
687
+ const STALE_NOTICE = "Stopped for over an hour: if Ollama restarted meanwhile, it may have dropped the partial download and start over.";
688
+ function refusalFor(failure, request, hostName) {
689
+ const name = sourceName(request);
690
+ const changed = `${name} changed since you reviewed it, so nothing was downloaded. Review it again.`;
691
+ switch (failure.reason) {
692
+ case "not-listed": return refuse(failure.reason, `${name} is not the curated build you reviewed, so nothing was downloaded.`);
693
+ case "build-missing": return refuse(failure.reason, `${request.source === "hf" ? request.buildId : name} is gone. ${changed}`);
694
+ case "changed": return refuse(failure.reason, changed);
695
+ case "abliterated": return refuse(failure.reason, `${name} is an abliterated build and is never offered as curated.`);
696
+ case "license-changed": return refuse(failure.reason, `The license of ${name} changed since you reviewed it, so nothing was downloaded.`);
697
+ case "license-required": return refuse(failure.reason, `${name} has a license you must accept before it downloads.`);
698
+ case "access-required": return refuse(failure.reason, `${name} is gated: confirm that ${hostName}'s Ollama key is added to a Hugging Face account with access.`);
699
+ case "unverified": return refuse(failure.reason, `The registry could not show which file Ollama would get for ${name}. ${changed}`);
700
+ case "blocked": return refuse(failure.reason, `Ollama cannot download ${name} as reviewed (${failure.block}).`);
701
+ case "runtime-unreachable": return refuse(failure.reason, `Ollama on ${hostName} is not reachable: ${clip(failure.error ?? "no answer")}`);
702
+ case "runtime-too-old": return refuse(failure.reason, `${failure.blocked}; Ollama on ${hostName} is ${failure.actual ?? "unknown"}.`);
703
+ case "layers-no-source":
704
+ case "layers-not-served":
705
+ case "layers-changed": return refuse(failure.reason, `The registry no longer serves ${name} as you reviewed it, so nothing was downloaded.`);
706
+ case "cancelled": return refuse(failure.reason, "Cancelled.");
707
+ }
708
+ }
709
+ /**
710
+ * Pull jobs the host runs itself, so a client that disconnects or quits changes nothing. Every job re-checks its
711
+ * approval through the shared checks in local-models before Ollama is asked, and the installed weights after.
712
+ */
713
+ var JobManager = class {
714
+ #jobs = /* @__PURE__ */ new Map();
715
+ #admission = Promise.resolve();
716
+ #closed = false;
717
+ #o;
718
+ constructor(options) {
719
+ this.#o = {
720
+ floorBytes: DEFAULT_FLOOR_BYTES,
721
+ progressEveryMs: 500,
722
+ saveEveryMs: 5e3,
723
+ maxActive: 4,
724
+ maxJobs: 32,
725
+ maxKept: 200,
726
+ inspectRetryMs: [1e3, 3e3],
727
+ verifyTimeoutMs: 4e4,
728
+ staleAfterMs: 36e5,
729
+ ...options
730
+ };
731
+ }
732
+ #now() {
733
+ return (this.#o.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
734
+ }
735
+ /**
736
+ * Reads saved jobs. One stopped while its download was being checked is checked again now, since that downloads
737
+ * nothing; any other that was running becomes `interrupted` and waits for Resume.
738
+ */
739
+ async load() {
740
+ const recheck = [];
741
+ for (const record of await this.#o.store.loadAll()) {
742
+ const { job } = record;
743
+ const entry = this.#entry({
744
+ ...job,
745
+ error: job.error && {
746
+ ...job.error,
747
+ message: clip(job.error.message)
748
+ },
749
+ notice: job.notice && clip(job.notice)
750
+ }, record.request, record.run ?? {
751
+ pulled: false,
752
+ afterOnly: false
753
+ });
754
+ if (entry.job.state === "verifying" && entry.run.pulled) recheck.push(entry);
755
+ else if (isActive(entry.job.state)) {
756
+ const was = entry.job.state;
757
+ entry.job = {
758
+ ...entry.job,
759
+ state: "interrupted",
760
+ updatedAt: this.#now()
761
+ };
762
+ this.#audit(entry, "interrupted", entry.job.startedBy, `b4m-host stopped while the job was ${was}.`);
763
+ await this.#persist(entry);
764
+ }
765
+ this.#jobs.set(entry.job.id, entry);
766
+ }
767
+ await this.#prune();
768
+ for (const entry of recheck) this.#start(entry);
769
+ }
770
+ #entry(job, request, run) {
771
+ return {
772
+ job,
773
+ request,
774
+ run,
775
+ controller: null,
776
+ stop: null,
777
+ task: null,
778
+ starting: null,
779
+ plan: null,
780
+ verifying: false,
781
+ spaceRechecked: false,
782
+ spaceRefusal: null,
783
+ lastEmit: 0,
784
+ emitTimer: null,
785
+ lastSave: 0
786
+ };
787
+ }
788
+ list() {
789
+ return [...this.#jobs.values()].map((entry) => entry.job);
790
+ }
791
+ get(id) {
792
+ return this.#find(id).job;
793
+ }
794
+ #find(id) {
795
+ const entry = this.#jobs.get(id);
796
+ if (!entry) throw new HttpError(404, "job-not-found", "No such job.");
797
+ return entry;
798
+ }
799
+ /** Whether an active job is pulling `name`, under any spelling Ollama lists it by. */
800
+ busy(name) {
801
+ const key = modelKey(name);
802
+ for (const { job } of this.#jobs.values()) if (isActive(job.state) && ollamaRefAliases(tagged(job.ref)).includes(key)) return job;
803
+ return null;
804
+ }
805
+ /** Another unfinished job that pulls into the same Ollama tag. */
806
+ #tagHolder(ref, self) {
807
+ const key = modelKey(ref);
808
+ for (const entry of this.#jobs.values()) if (entry !== self && !isFinal(entry.job.state) && modelKey(entry.job.ref) === key) return entry.job;
809
+ return null;
810
+ }
811
+ #requireTagFree(ref, self) {
812
+ const holder = this.#tagHolder(ref, self);
813
+ if (holder) {
814
+ const hint = isActive(holder.state) ? "is already downloading" : "holds";
815
+ throw new HttpError(409, "job-exists", `Job ${holder.id} ${hint} ${ref}; Ollama has one copy per tag.`);
816
+ }
817
+ }
818
+ /** Removes an installed model unless a job is pulling it. */
819
+ async removeModel(name, actor) {
820
+ const running = this.busy(name);
821
+ if (running) throw new HttpError(409, "model-busy", `Job ${running.id} is downloading ${name}; cancel it first.`);
822
+ try {
823
+ await this.#o.runtime.remove(name);
824
+ } catch (error) {
825
+ if (error instanceof ModelNotFoundError) throw new HttpError(404, "model-not-found", `Ollama has no ${name}.`);
826
+ throw error;
827
+ }
828
+ this.#o.audit({
829
+ event: "remove",
830
+ ref: name,
831
+ device: actor.device,
832
+ login: actor.user,
833
+ via: actor.via
834
+ });
835
+ }
836
+ /** Admission runs one request at a time, so a second request sees the first one's reservation. */
837
+ #admit(task) {
838
+ const next = this.#admission.then(task, task);
839
+ this.#admission = next.catch(() => void 0);
840
+ return next;
841
+ }
842
+ #claim(entry) {
843
+ let release = () => {};
844
+ entry.starting = new Promise((resolve) => release = resolve);
845
+ return () => {
846
+ entry.starting = null;
847
+ release();
848
+ };
849
+ }
850
+ /** A create or resume that a cancel, dismiss or shutdown overtook while it awaited. */
851
+ #overtaken(entry) {
852
+ return entry.stop === "cancel" || this.#jobs.get(entry.job.id) !== entry || this.#closed;
853
+ }
854
+ #audit(entry, event, actor, detail) {
855
+ const { request, job } = entry;
856
+ this.#o.audit({
857
+ event,
858
+ job: job.id,
859
+ ref: job.ref,
860
+ revision: request.source === "hf" ? request.revision : request.manifestDigest,
861
+ sha256: request.source === "hf" ? request.sha256 : request.curated.layers.model,
862
+ licensesAccepted: request.licenseAccepted ? request.licenses : [],
863
+ device: actor.device,
864
+ login: actor.user,
865
+ via: actor.via,
866
+ detail: detail ?? null
867
+ });
868
+ }
869
+ #spaceNotice() {
870
+ return `b4m-host could not read the free space on ${this.#o.hostName}, so it did not check that the model fits.`;
871
+ }
872
+ async #room(sizeBytes, partialBytes, except) {
873
+ const free = await this.#o.freeBytes().catch(() => null);
874
+ if (free === null) return {
875
+ ok: true,
876
+ unknown: true
877
+ };
878
+ const others = [...this.#jobs.values()].filter((entry) => entry.job.id !== except && isActive(entry.job.state));
879
+ const reserved = others.reduce((sum, { job }) => sum + Math.max(0, job.sizeBytes - job.progress.completedBytes), 0);
880
+ const need = Math.max(0, sizeBytes - partialBytes);
881
+ if (free - reserved - need >= this.#o.floorBytes) return {
882
+ ok: true,
883
+ unknown: false
884
+ };
885
+ const count = others.length;
886
+ const held = count ? ` and ${formatGb(reserved)} already reserved by ${count} other download${count === 1 ? "" : "s"}` : "";
887
+ return {
888
+ ok: false,
889
+ message: `Needs ${formatGb(need)} on ${this.#o.hostName}; ${formatGb(free)} free${held}, and ${formatGb(this.#o.floorBytes)} is kept free.`
890
+ };
891
+ }
892
+ #refuseSpace(message, ref, job, actor) {
893
+ this.#o.audit({
894
+ event: "admission-refused",
895
+ job,
896
+ ref,
897
+ device: actor.device,
898
+ login: actor.user,
899
+ via: actor.via,
900
+ detail: message
901
+ });
902
+ throw new HttpError(507, "insufficient-space", message);
903
+ }
904
+ #requireRoom(adding) {
905
+ if (this.#closed) throw new HttpError(503, "shutting-down", "b4m-host is stopping.");
906
+ const entries = [...this.#jobs.values()];
907
+ const active = entries.filter((entry) => isActive(entry.job.state)).length;
908
+ if (active >= this.#o.maxActive) throw new HttpError(429, "too-many-jobs", `${active} downloads are already running; wait for one to finish.`);
909
+ const open = entries.filter((entry) => !isFinal(entry.job.state)).length;
910
+ if (adding && open >= this.#o.maxJobs) throw new HttpError(429, "too-many-jobs", `${open} downloads are running, paused or interrupted; resume or cancel one first.`);
911
+ }
912
+ /** Starts a pull from what the user approved; nothing downloads until its checks pass. */
913
+ create(request, actor) {
914
+ return this.#admit(async () => {
915
+ if (this.#closed) throw new HttpError(503, "shutting-down", "b4m-host is stopping.");
916
+ const key = sourceKey(request);
917
+ const existing = [...this.#jobs.values()].find((entry) => !isFinal(entry.job.state) && sourceKey(entry.request) === key);
918
+ if (existing) {
919
+ const hint = isActive(existing.job.state) ? "is already downloading it" : "holds it; resume that job";
920
+ throw new HttpError(409, "job-exists", `Job ${existing.job.id} ${hint}.`);
921
+ }
922
+ this.#requireTagFree(request.ref, null);
923
+ this.#requireRoom(true);
924
+ const room = await this.#room(request.sizeBytes, 0, null);
925
+ if (!room.ok) this.#refuseSpace(room.message, request.ref, null, actor);
926
+ this.#requireRoom(true);
927
+ const now = this.#now();
928
+ const job = {
929
+ id: randomUUID(),
930
+ state: "queued",
931
+ source: request.source,
932
+ repo: sourceName(request),
933
+ buildId: request.source === "hf" ? request.buildId : request.curated.buildId,
934
+ ref: request.ref,
935
+ sizeBytes: request.sizeBytes,
936
+ progress: {
937
+ status: "queued",
938
+ completedBytes: 0,
939
+ totalBytes: null
940
+ },
941
+ startedBy: actor,
942
+ cancelledBy: null,
943
+ createdAt: now,
944
+ updatedAt: now,
945
+ finishedAt: null,
946
+ error: null,
947
+ notice: room.unknown ? this.#spaceNotice() : null
948
+ };
949
+ const entry = this.#entry(job, request, {
950
+ pulled: false,
951
+ afterOnly: false
952
+ });
953
+ this.#jobs.set(job.id, entry);
954
+ const release = this.#claim(entry);
955
+ try {
956
+ await this.#persist(entry);
957
+ this.#audit(entry, "create", actor);
958
+ this.#emit(entry, true);
959
+ this.#start(entry);
960
+ } finally {
961
+ release();
962
+ }
963
+ await this.#prune();
964
+ return entry.job;
965
+ });
966
+ }
967
+ /** Stops a job for good; Ollama keeps the partial blobs until its own pruning. */
968
+ async cancel(id, actor) {
969
+ const entry = this.#find(id);
970
+ const { state } = entry.job;
971
+ if (isFinal(state)) throw new HttpError(409, "job-finished", `The job already ended (${state}).`);
972
+ if (state === "verifying") throw new HttpError(409, "job-verifying", "The download finished and is being checked; it ends in a moment.");
973
+ this.#audit(entry, "cancel", actor);
974
+ entry.job = {
975
+ ...entry.job,
976
+ cancelledBy: actor
977
+ };
978
+ if (entry.starting) {
979
+ entry.stop = "cancel";
980
+ await entry.starting;
981
+ }
982
+ if (isFinal(entry.job.state) || entry.job.state === "verifying" || this.#jobs.get(id) !== entry) return entry.job;
983
+ if (!entry.task) {
984
+ await this.#finish(entry, "cancelled");
985
+ return entry.job;
986
+ }
987
+ await this.#stop(entry, "cancel");
988
+ return entry.job;
989
+ }
990
+ /** Stops holding the pull; Resume re-checks and pulls again, and Ollama reuses what it already has. */
991
+ async pause(id, actor) {
992
+ const entry = this.#find(id);
993
+ const { state } = entry.job;
994
+ if (state === "verifying") throw new HttpError(409, "job-verifying", "The download finished and is being checked; it ends in a moment.");
995
+ if (!isActive(state) || !entry.task) throw new HttpError(409, "job-not-running", `The job is ${state}.`);
996
+ this.#audit(entry, "pause", actor);
997
+ await this.#stop(entry, "pause");
998
+ return entry.job;
999
+ }
1000
+ async #stop(entry, reason) {
1001
+ entry.stop = reason;
1002
+ entry.controller?.abort();
1003
+ const task = entry.task;
1004
+ if (!task) return;
1005
+ let timer;
1006
+ await Promise.race([task, new Promise((resolve) => timer = setTimeout(resolve, STOP_WAIT_MS))]);
1007
+ clearTimeout(timer);
1008
+ }
1009
+ /** Runs every check and admission again, then pulls the same build; a finished pull only gets its check. */
1010
+ resume(id, actor) {
1011
+ return this.#admit(async () => {
1012
+ const entry = this.#find(id);
1013
+ const { state } = entry.job;
1014
+ if (state !== "paused" && state !== "interrupted" || entry.task || entry.starting) throw new HttpError(409, "job-not-resumable", `Only a paused or interrupted job resumes; this one is ${state}.`);
1015
+ this.#requireRoom(false);
1016
+ this.#requireTagFree(entry.job.ref, entry);
1017
+ const release = this.#claim(entry);
1018
+ try {
1019
+ const stale = Date.now() - Date.parse(entry.job.updatedAt) > this.#o.staleAfterMs;
1020
+ let spaceNotice = null;
1021
+ if (!entry.run.pulled) {
1022
+ const partial = stale ? 0 : entry.job.progress.completedBytes;
1023
+ const room = await this.#room(entry.job.sizeBytes, partial, entry.job.id);
1024
+ if (this.#overtaken(entry)) return entry.job;
1025
+ if (!room.ok) this.#refuseSpace(room.message, entry.job.ref, entry.job.id, actor);
1026
+ if (room.unknown) spaceNotice = this.#spaceNotice();
1027
+ }
1028
+ this.#audit(entry, "resume", actor);
1029
+ await this.#set(entry, {
1030
+ state: "queued",
1031
+ notice: joinNotices(stale && !entry.run.pulled ? STALE_NOTICE : null, spaceNotice),
1032
+ error: null,
1033
+ cancelledBy: null,
1034
+ progress: {
1035
+ ...entry.job.progress,
1036
+ status: "queued"
1037
+ }
1038
+ });
1039
+ this.#start(entry);
1040
+ return entry.job;
1041
+ } finally {
1042
+ release();
1043
+ }
1044
+ });
1045
+ }
1046
+ /** Forgets a finished job. */
1047
+ async dismiss(id, actor) {
1048
+ const entry = this.#find(id);
1049
+ if (!isFinal(entry.job.state) || entry.starting || entry.task) throw new HttpError(409, "job-not-finished", `Cancel the job first; it is ${entry.job.state}.`);
1050
+ this.#audit(entry, "dismiss", actor);
1051
+ await this.#drop(entry);
1052
+ }
1053
+ async #drop(entry) {
1054
+ if (entry.emitTimer) clearTimeout(entry.emitTimer);
1055
+ this.#jobs.delete(entry.job.id);
1056
+ await this.#o.store.remove(entry.job.id).catch((error) => this.#o.log(`removing job file: ${errorText(error)}`));
1057
+ this.#o.onDismissed(entry.job.id);
1058
+ }
1059
+ async #prune() {
1060
+ const finished = [...this.#jobs.values()].filter((entry) => isFinal(entry.job.state) && !entry.task).sort((a, b) => a.job.updatedAt.localeCompare(b.job.updatedAt));
1061
+ for (const entry of finished.slice(0, Math.max(0, finished.length - this.#o.maxKept))) await this.#drop(entry);
1062
+ }
1063
+ /**
1064
+ * Stops every running pull; each becomes `interrupted`, as after a crash. A check of finished download gets up
1065
+ * to `verifyTimeoutMs` to end; one still running stays `verifying` on disk, so the next start checks it again.
1066
+ */
1067
+ async close() {
1068
+ this.#closed = true;
1069
+ await Promise.all([...this.#jobs.values()].map((entry) => {
1070
+ if (!entry.task) return void 0;
1071
+ if (entry.verifying) return this.#wait(entry.task, this.#o.verifyTimeoutMs);
1072
+ return this.#stop(entry, "shutdown");
1073
+ }));
1074
+ for (const entry of this.#jobs.values()) if (entry.emitTimer) clearTimeout(entry.emitTimer);
1075
+ }
1076
+ async #wait(task, ms) {
1077
+ let timer;
1078
+ await Promise.race([task, new Promise((resolve) => timer = setTimeout(resolve, ms))]);
1079
+ clearTimeout(timer);
1080
+ }
1081
+ #start(entry) {
1082
+ const { state } = entry.job;
1083
+ if (!(state === "queued" || state === "verifying" && entry.run.pulled) || entry.task || entry.stop === "cancel" || this.#jobs.get(entry.job.id) !== entry) return;
1084
+ if (this.#closed && state !== "verifying") return;
1085
+ entry.stop = null;
1086
+ entry.controller = new AbortController();
1087
+ entry.task = this.#run(entry, entry.controller.signal).finally(() => {
1088
+ entry.task = null;
1089
+ entry.controller = null;
1090
+ });
1091
+ }
1092
+ async #run(entry, signal) {
1093
+ if (entry.run.pulled) {
1094
+ const plan = this.#storedPlan(entry);
1095
+ if (!plan.ok) return this.#uncheckable(entry);
1096
+ return this.#verifyStep(entry, plan);
1097
+ }
1098
+ let phase = "checking";
1099
+ try {
1100
+ await this.#set(entry, {
1101
+ state: "checking",
1102
+ progress: {
1103
+ ...entry.job.progress,
1104
+ status: "checking"
1105
+ }
1106
+ });
1107
+ const plan = await this.#check(entry.request, signal);
1108
+ if (signal.aborted) return await this.#stopped(entry);
1109
+ if (!plan.ok) {
1110
+ this.#audit(entry, "check-failed", entry.job.startedBy, plan.message);
1111
+ return await this.#fail(entry, plan.code, plan.message);
1112
+ }
1113
+ entry.plan = plan;
1114
+ entry.run = {
1115
+ ...entry.run,
1116
+ afterOnly: plan.afterOnly
1117
+ };
1118
+ if (this.#hadTag(entry, plan.ref) === void 0) entry.run = {
1119
+ ...entry.run,
1120
+ hadTag: await this.#hasTag(plan.ref),
1121
+ hadTagRef: plan.ref
1122
+ };
1123
+ if (signal.aborted) return await this.#stopped(entry);
1124
+ const holder = this.#tagHolder(plan.ref, entry);
1125
+ if (holder) {
1126
+ const message = `Job ${holder.id} is already getting ${plan.ref}.`;
1127
+ this.#audit(entry, "check-failed", entry.job.startedBy, message);
1128
+ return await this.#fail(entry, "job-exists", message);
1129
+ }
1130
+ phase = "downloading";
1131
+ await this.#set(entry, {
1132
+ state: "downloading",
1133
+ ref: plan.ref,
1134
+ notice: joinNotices(entry.job.notice, plan.notice),
1135
+ progress: {
1136
+ ...entry.job.progress,
1137
+ status: "downloading"
1138
+ }
1139
+ });
1140
+ await this.#o.runtime.pull(plan.ref, {
1141
+ signal,
1142
+ runner: plan.runner,
1143
+ idleTimeoutMs: this.#o.pullIdleTimeoutMs,
1144
+ onProgress: (progress) => this.#progress(entry, progress)
1145
+ });
1146
+ if (signal.aborted) return await this.#stopped(entry);
1147
+ entry.controller = null;
1148
+ entry.run = {
1149
+ ...entry.run,
1150
+ pulled: true
1151
+ };
1152
+ await this.#verifyStep(entry, plan);
1153
+ } catch (error) {
1154
+ if (signal.aborted) return await this.#stopped(entry);
1155
+ const message = phase === "checking" ? `Could not check ${sourceName(entry.request)} against what you reviewed: ${errorText(error)}` : `Ollama could not download ${entry.job.ref}: ${errorText(error)}`;
1156
+ this.#audit(entry, phase === "checking" ? "check-failed" : "pull-failed", entry.job.startedBy, message);
1157
+ await this.#fail(entry, phase === "checking" ? "check-error" : "pull-failed", message);
1158
+ }
1159
+ }
1160
+ async #verifyStep(entry, plan) {
1161
+ entry.verifying = true;
1162
+ try {
1163
+ await this.#set(entry, {
1164
+ state: "verifying",
1165
+ progress: {
1166
+ ...entry.job.progress,
1167
+ status: "verifying"
1168
+ }
1169
+ });
1170
+ const failure = await this.#verify(plan, this.#hadTag(entry, plan.ref) ?? null).catch((error) => ({
1171
+ code: "unverified",
1172
+ message: `b4m-host could not check ${plan.ref} after downloading it: ${errorText(error)}`
1173
+ }));
1174
+ if (failure) {
1175
+ this.#audit(entry, failure.code === "digest-mismatch" ? "digest-failed" : "check-failed", entry.job.startedBy, failure.message);
1176
+ return await this.#fail(entry, failure.code, failure.message);
1177
+ }
1178
+ this.#audit(entry, "done", entry.job.startedBy);
1179
+ await this.#finish(entry, "done");
1180
+ } finally {
1181
+ entry.verifying = false;
1182
+ }
1183
+ }
1184
+ /** The plan of a job whose pull already finished, rebuilt from what was saved. */
1185
+ #storedPlan(entry) {
1186
+ const { request } = entry;
1187
+ const base = {
1188
+ ok: true,
1189
+ ref: entry.job.ref,
1190
+ notice: null,
1191
+ afterOnly: entry.run.afterOnly,
1192
+ hidden: false
1193
+ };
1194
+ if (request.source === "hf" && !request.curated) return {
1195
+ ...base,
1196
+ verify: {
1197
+ kind: "blob",
1198
+ sha256: request.sha256
1199
+ }
1200
+ };
1201
+ if (!request.curated) return refuse("not-listed", `${request.ref} is not a curated build.`);
1202
+ const curated = this.#curated(request.curated);
1203
+ return curated.ok ? {
1204
+ ...base,
1205
+ verify: {
1206
+ kind: "curated",
1207
+ build: curated.build
1208
+ }
1209
+ } : curated;
1210
+ }
1211
+ /** `hadTag` when it was read for `ref`; files written before `hadTagRef` read it for the job's ref. */
1212
+ #hadTag(entry, ref) {
1213
+ return modelKey(entry.run.hadTagRef ?? entry.job.ref) === modelKey(ref) ? entry.run.hadTag : void 0;
1214
+ }
1215
+ /**
1216
+ * A finished pull whose approved build this host's curated list no longer pins, so nothing can check it. Like an
1217
+ * unverified download, it is removed when the job's pull created the tag and left in place otherwise.
1218
+ */
1219
+ async #uncheckable(entry) {
1220
+ const { ref } = entry.job;
1221
+ const head = `${ref} was downloaded, but this b4m-host's curated list no longer pins the build you approved, so it could not be checked`;
1222
+ const message = this.#hadTag(entry, ref) !== false ? `${head}. It is still installed; remove it unless you trust it.` : await this.#o.runtime.remove(ref).then(() => `${head}, so it was removed.`, (error) => `${head}. Removing it failed (${errorText(error)}); remove ${ref} by hand.`);
1223
+ this.#audit(entry, "check-failed", entry.job.startedBy, message);
1224
+ await this.#fail(entry, "unverified", message);
1225
+ }
1226
+ async #stopped(entry) {
1227
+ const reason = entry.stop ?? "shutdown";
1228
+ if (reason === "space") return this.#spaceStopped(entry);
1229
+ const race = reason === "shutdown" ? null : await this.#settleRace(entry);
1230
+ if (reason === "cancel") {
1231
+ if (race) this.#audit(entry, "cancelled", entry.job.cancelledBy ?? entry.job.startedBy, race);
1232
+ return this.#finish(entry, "cancelled", null, joinNotices(entry.job.notice, race));
1233
+ }
1234
+ if (reason === "shutdown") this.#audit(entry, "interrupted", entry.job.startedBy, `b4m-host stopped while the job was ${entry.job.state}.`);
1235
+ await this.#set(entry, {
1236
+ state: reason === "pause" ? "paused" : "interrupted",
1237
+ notice: joinNotices(entry.job.notice, race),
1238
+ progress: {
1239
+ ...entry.job.progress,
1240
+ status: reason === "pause" ? "paused" : "interrupted"
1241
+ }
1242
+ });
1243
+ }
1244
+ /**
1245
+ * A stop can lose the race with the end of the download. When the tag is new and Ollama now lists it, its
1246
+ * weights are checked: kept on a match, removed otherwise. Returns what the job should say about it.
1247
+ */
1248
+ async #settleRace(entry) {
1249
+ const { plan } = entry;
1250
+ if (!plan || this.#hadTag(entry, plan.ref) !== false || await this.#hasTag(plan.ref) !== true) return null;
1251
+ const failure = await this.#verify(plan, false).catch((error) => ({
1252
+ code: "unverified",
1253
+ message: `b4m-host could not check ${plan.ref}: ${errorText(error)}`
1254
+ }));
1255
+ if (failure) return `The download finished before it stopped. ${failure.message}`;
1256
+ entry.run = {
1257
+ ...entry.run,
1258
+ pulled: true
1259
+ };
1260
+ return `The download finished before it stopped; ${plan.ref} matches what you approved and is installed.`;
1261
+ }
1262
+ async #spaceStopped(entry) {
1263
+ const message = entry.spaceRefusal ?? "The model is larger than the free space on the host.";
1264
+ const { plan } = entry;
1265
+ if (plan && this.#hadTag(entry, plan.ref) === false && await this.#hasTag(plan.ref) === true) await this.#o.runtime.remove(plan.ref).catch((error) => this.#o.log(`removing ${plan.ref}: ${errorText(error)}`));
1266
+ this.#audit(entry, "admission-refused", entry.job.startedBy, message);
1267
+ await this.#fail(entry, "insufficient-space", `Ollama reported the model is ${formatGb(entry.job.sizeBytes)}, more than fits. ${message} The download stopped.`);
1268
+ }
1269
+ #fail(entry, code, message) {
1270
+ return this.#finish(entry, "failed", {
1271
+ code,
1272
+ message: clip(message)
1273
+ });
1274
+ }
1275
+ async #finish(entry, state, error = null, notice = entry.job.notice) {
1276
+ await this.#set(entry, {
1277
+ state,
1278
+ error,
1279
+ notice,
1280
+ finishedAt: this.#now(),
1281
+ progress: {
1282
+ ...entry.job.progress,
1283
+ status: state
1284
+ }
1285
+ });
1286
+ }
1287
+ async #set(entry, patch) {
1288
+ entry.job = {
1289
+ ...entry.job,
1290
+ ...patch,
1291
+ updatedAt: this.#now()
1292
+ };
1293
+ this.#emit(entry, true);
1294
+ await this.#persist(entry);
1295
+ }
1296
+ #progress(entry, progress) {
1297
+ entry.job = {
1298
+ ...entry.job,
1299
+ progress: {
1300
+ status: clip(progress.status, 253),
1301
+ completedBytes: Math.max(0, Math.round(progress.completedBytes)),
1302
+ totalBytes: progress.totalBytes === null ? null : Math.max(0, Math.round(progress.totalBytes))
1303
+ },
1304
+ updatedAt: this.#now()
1305
+ };
1306
+ if (entry.plan?.hidden && !entry.spaceRechecked && entry.job.progress.totalBytes) {
1307
+ entry.spaceRechecked = true;
1308
+ this.#recheckSpace(entry, entry.job.progress.totalBytes);
1309
+ }
1310
+ if (Date.now() - entry.lastSave >= this.#o.saveEveryMs) this.#persist(entry);
1311
+ this.#emit(entry, false);
1312
+ }
1313
+ /** A hidden repo's size was the client's word; the first size Ollama reports goes through admission again. */
1314
+ async #recheckSpace(entry, totalBytes) {
1315
+ entry.job = {
1316
+ ...entry.job,
1317
+ sizeBytes: totalBytes
1318
+ };
1319
+ const room = await this.#room(totalBytes, entry.job.progress.completedBytes, entry.job.id);
1320
+ if (room.ok || !entry.controller || entry.stop) return;
1321
+ entry.spaceRefusal = room.message;
1322
+ entry.stop = "space";
1323
+ entry.controller.abort();
1324
+ }
1325
+ #persist(entry) {
1326
+ entry.lastSave = Date.now();
1327
+ return this.#o.store.save({
1328
+ job: entry.job,
1329
+ request: entry.request,
1330
+ run: entry.run
1331
+ }).catch((error) => this.#o.log(`saving job ${entry.job.id}: ${errorText(error)}`));
1332
+ }
1333
+ /** State changes go out at once; progress at most once per `progressEveryMs`, the latest winning. */
1334
+ #emit(entry, force) {
1335
+ if (entry.emitTimer) {
1336
+ if (!force) return;
1337
+ clearTimeout(entry.emitTimer);
1338
+ entry.emitTimer = null;
1339
+ }
1340
+ const wait = this.#o.progressEveryMs - (Date.now() - entry.lastEmit);
1341
+ if (force || wait <= 0) {
1342
+ entry.lastEmit = Date.now();
1343
+ this.#o.onJob(entry.job);
1344
+ return;
1345
+ }
1346
+ entry.emitTimer = setTimeout(() => {
1347
+ entry.emitTimer = null;
1348
+ entry.lastEmit = Date.now();
1349
+ if (this.#jobs.get(entry.job.id) === entry) this.#o.onJob(entry.job);
1350
+ }, wait);
1351
+ entry.emitTimer.unref();
1352
+ }
1353
+ #approvalDeps(signal) {
1354
+ return {
1355
+ hub: () => this.#o.hub(),
1356
+ libraryLayers: this.#o.libraryLayers,
1357
+ health: () => this.#o.runtime.health(),
1358
+ signal
1359
+ };
1360
+ }
1361
+ #curated(approved) {
1362
+ const manifest = this.#o.curated();
1363
+ const entry = manifest.entries.find((candidate) => candidate.id === approved.entryId);
1364
+ const build = entry?.builds.find((candidate) => candidate.id === approved.buildId);
1365
+ if (!entry || !build) return refuse("not-listed", `${approved.entryId} (${approved.buildId}) is not in this b4m-host's curated list; upgrade b4m-host to a version that lists it.`);
1366
+ if (!isCuratedListable(entry, manifest)) return refuse("not-listed", `${entry.name} is no longer offered as curated, so nothing was downloaded.`);
1367
+ if (!layersMatch(approved.layers, build)) return refuse("layers-changed", `The layers you reviewed for ${entry.name} are not the ones this b4m-host's curated list pins, so nothing was downloaded.`);
1368
+ return {
1369
+ ok: true,
1370
+ entry,
1371
+ build
1372
+ };
1373
+ }
1374
+ async #check(request, signal) {
1375
+ const curated = request.curated ? this.#curated(request.curated) : null;
1376
+ if (curated && !curated.ok) return curated;
1377
+ const reviewed = curated && {
1378
+ entry: curated.entry,
1379
+ build: curated.build
1380
+ };
1381
+ const deps = this.#approvalDeps(signal);
1382
+ if (request.source === "library") {
1383
+ if (!reviewed) return refuse("not-listed", `${request.ref} is not a curated build.`);
1384
+ if (licensesChanged(request.licenses, [reviewed.entry.license.id])) return refuse("license-changed", `The license of ${request.ref} changed since you reviewed it.`);
1385
+ const checked = await checkApproval({
1386
+ source: "library",
1387
+ ref: request.ref,
1388
+ buildId: reviewed.build.id,
1389
+ manifestDigest: request.manifestDigest,
1390
+ sizeBytes: request.sizeBytes,
1391
+ licenseAccepted: request.licenseAccepted,
1392
+ curated: reviewed
1393
+ }, deps);
1394
+ if (!checked.ok) return refusalFor(checked, request, this.#o.hostName);
1395
+ return {
1396
+ ok: true,
1397
+ ref: checked.ref,
1398
+ runner: curatedRunner(reviewed.build),
1399
+ verify: {
1400
+ kind: "curated",
1401
+ build: reviewed.build
1402
+ },
1403
+ notice: null,
1404
+ afterOnly: false,
1405
+ hidden: false
1406
+ };
1407
+ }
1408
+ if (!sameRepo(refRepo(request.ref), request.repo)) return refuse("invalid-ref", `${request.ref} does not name ${request.repo}.`);
1409
+ if (reviewed && reviewed.build.weights[0]?.sha256 !== request.sha256) return refuse("layers-changed", `The file you reviewed is not the one the curated list pins for ${request.repo}.`);
1410
+ const seen = {
1411
+ detail: null,
1412
+ repoError: null
1413
+ };
1414
+ const base = this.#o.hub();
1415
+ const hub = {
1416
+ getModel: async (repo, options) => {
1417
+ const own = sameRepo(repo, request.repo);
1418
+ try {
1419
+ const detail = await base.getModel(repo, options);
1420
+ if (own) seen.detail = detail;
1421
+ return detail;
1422
+ } catch (error) {
1423
+ if (own) seen.repoError = error;
1424
+ throw error;
1425
+ }
1426
+ },
1427
+ verifyOllamaRef: (detail, build, options) => base.verifyOllamaRef(detail, build, options),
1428
+ ollamaLayers: (repo, tag, options) => base.ollamaLayers(repo, tag, options)
1429
+ };
1430
+ let checked;
1431
+ try {
1432
+ checked = await checkApproval({
1433
+ source: "hf",
1434
+ repo: request.repo,
1435
+ buildId: request.buildId,
1436
+ revision: request.revision,
1437
+ sizeBytes: request.sizeBytes,
1438
+ licenseAccepted: request.licenseAccepted,
1439
+ accessConfirmed: request.accessConfirmed,
1440
+ curated: reviewed
1441
+ }, {
1442
+ ...deps,
1443
+ hub: () => hub,
1444
+ checkAfterPull: true
1445
+ });
1446
+ } catch (error) {
1447
+ if (!(error === seen.repoError && error instanceof ModelNotFoundError) || !request.accessConfirmed || reviewed) throw error;
1448
+ const health = await this.#o.runtime.health();
1449
+ if (!health.ok) return refusalFor({
1450
+ ok: false,
1451
+ reason: "runtime-unreachable",
1452
+ error: health.error
1453
+ }, request, this.#o.hostName);
1454
+ return {
1455
+ ok: true,
1456
+ ref: ollamaPullRef(request.ref.replace(/^huggingface\.co\//, "hf.co/"), true),
1457
+ verify: {
1458
+ kind: "blob",
1459
+ sha256: request.sha256
1460
+ },
1461
+ notice: PRIVATE_NOTICE,
1462
+ afterOnly: true,
1463
+ hidden: true
1464
+ };
1465
+ }
1466
+ if (!checked.ok) return refusalFor(checked, request, this.#o.hostName);
1467
+ const { detail } = seen;
1468
+ const changed = refuse("changed", `${request.repo} changed since you reviewed it, so nothing was downloaded.`);
1469
+ if (detail && licensesChanged(request.licenses, detail.licenses)) return refuse("license-changed", `The license of ${request.repo} changed since you reviewed it.`);
1470
+ const sha = detail?.builds.find((build) => build.id === request.buildId)?.files[0]?.sha256 ?? null;
1471
+ if (sha !== null && sha !== request.sha256) return changed;
1472
+ const unproven = checked.verified === false;
1473
+ if (!unproven && ollamaModelKey(checked.ref) !== ollamaModelKey(request.ref)) return changed;
1474
+ return {
1475
+ ok: true,
1476
+ ref: checked.ref,
1477
+ runner: reviewed ? curatedRunner(reviewed.build) : void 0,
1478
+ verify: reviewed ? {
1479
+ kind: "curated",
1480
+ build: reviewed.build
1481
+ } : {
1482
+ kind: "blob",
1483
+ sha256: request.sha256
1484
+ },
1485
+ notice: unproven ? GATED_NOTICE : null,
1486
+ afterOnly: unproven,
1487
+ hidden: false
1488
+ };
1489
+ }
1490
+ async #hasTag(ref) {
1491
+ try {
1492
+ const aliases = ollamaRefAliases(tagged(ref));
1493
+ return (await this.#o.runtime.list()).some((model) => aliases.includes(modelKey(model.name)));
1494
+ } catch {
1495
+ return null;
1496
+ }
1497
+ }
1498
+ async #verify(plan, hadTag) {
1499
+ const { ref } = plan;
1500
+ const deadline = Date.now() + this.#o.verifyTimeoutMs;
1501
+ let inspection = null;
1502
+ for (let attempt = 0; !inspection; attempt++) try {
1503
+ const timeoutMs = Math.max(1e3, Math.min(CHECK_TIMEOUT_MS, deadline - Date.now()));
1504
+ inspection = await this.#o.runtime.inspect(ref, {
1505
+ tags: false,
1506
+ timeoutMs
1507
+ });
1508
+ } catch (error) {
1509
+ if (error instanceof ModelNotFoundError) return {
1510
+ code: "missing",
1511
+ message: `Ollama finished downloading ${ref} but does not list it.`
1512
+ };
1513
+ const pause = this.#o.inspectRetryMs[attempt];
1514
+ if (pause === void 0 || Date.now() + pause >= deadline) return this.#unverified(plan, hadTag, error);
1515
+ await new Promise((resolve) => setTimeout(resolve, pause));
1516
+ }
1517
+ const removal = {
1518
+ hadTag,
1519
+ remove: () => this.#o.runtime.remove(ref)
1520
+ };
1521
+ const { verify } = plan;
1522
+ const checked = verify.kind === "curated" ? await checkInstalledDigest(inspection, verify.build, removal) : await checkInstalledBlob(inspection, verify.sha256, removal);
1523
+ if (checked.ok) return null;
1524
+ const expected = verify.kind === "curated" ? reviewedModel(verify.build) : verify.sha256;
1525
+ const got = inspection.contents?.modelBlob ?? null;
1526
+ const head = got === expected ? `What Ollama installed for ${ref} does not match the build you approved` : `The downloaded file does not match the one you approved (expected ${expected.slice(0, 8)}, got ${got ? got.slice(0, 8) : "none"})`;
1527
+ if (checked.outcome === "removed") return {
1528
+ code: "digest-mismatch",
1529
+ message: `${head}, so it was removed.`
1530
+ };
1531
+ if (checked.outcome === "remove-failed") return {
1532
+ code: "digest-mismatch",
1533
+ message: `${head}, and removing it failed. Remove ${ref} by hand.`
1534
+ };
1535
+ return {
1536
+ code: "digest-mismatch",
1537
+ message: `${head}. ${checked.outcome === "left-in-place" && checked.hadTag ? `${ref} was installed before this download, so the previous model was replaced and is left in place` : `b4m-host could not tell whether ${ref} was installed before, so it is left in place`}; remove it unless you trust it.`
1538
+ };
1539
+ }
1540
+ /** Ollama could not describe the model. When nothing else proved the file and the tag is new, it is removed. */
1541
+ async #unverified(plan, hadTag, error) {
1542
+ const { ref } = plan;
1543
+ const head = `Ollama could not describe ${ref} after downloading it (${errorText(error)})`;
1544
+ if (!plan.afterOnly || hadTag !== false) return {
1545
+ code: "unverified",
1546
+ message: `${head}, so it was not checked against what you approved. It is still installed; remove it unless you trust it.`
1547
+ };
1548
+ try {
1549
+ await this.#o.runtime.remove(ref);
1550
+ } catch (removeError) {
1551
+ return {
1552
+ code: "unverified",
1553
+ message: `${head}, and nothing else proved it is the file you approved. Removing it failed (${errorText(removeError)}); remove ${ref} by hand.`
1554
+ };
1555
+ }
1556
+ return {
1557
+ code: "unverified",
1558
+ message: `${head}, and nothing else proved it is the file you approved, so it was removed.`
1559
+ };
1560
+ }
1561
+ };
1562
+ //#endregion
1563
+ //#region ../model-host/src/ollamaKey.ts
1564
+ const MAX_KEY_BYTES = 1024;
1565
+ /** Ollama's public key from the home it runs with; it signs pulls of gated and private Hugging Face repos. */
1566
+ async function readOllamaKey(home) {
1567
+ if (!home) return {
1568
+ path: null,
1569
+ publicKey: null,
1570
+ message: "b4m-host could not tell which home Ollama runs with, so it cannot find Ollama's key."
1571
+ };
1572
+ const path = join(home, ".ollama", "id_ed25519.pub");
1573
+ let handle;
1574
+ try {
1575
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
1576
+ const info = await handle.stat();
1577
+ if (!info.isFile() || info.size > MAX_KEY_BYTES) return {
1578
+ path,
1579
+ publicKey: null,
1580
+ message: `${path} is not an Ollama public key.`
1581
+ };
1582
+ const text = (await handle.readFile("utf8")).trim();
1583
+ if (!/^ssh-ed25519 [A-Za-z0-9+/=]+(?: [\x20-\x7e]*)?$/.test(text)) return {
1584
+ path,
1585
+ publicKey: null,
1586
+ message: `${path} is not an Ollama public key.`
1587
+ };
1588
+ return {
1589
+ path,
1590
+ publicKey: text,
1591
+ message: null
1592
+ };
1593
+ } catch (error) {
1594
+ const code = error.code;
1595
+ if (code === "ENOENT") return {
1596
+ path,
1597
+ publicKey: null,
1598
+ message: `Ollama has not created ${path} yet; it does when it first starts.`
1599
+ };
1600
+ if (code === "EACCES" || code === "EPERM") return {
1601
+ path,
1602
+ publicKey: null,
1603
+ message: `b4m-host cannot read ${path}. On the server, run: sudo cat ${path}`
1604
+ };
1605
+ return {
1606
+ path,
1607
+ publicKey: null,
1608
+ message: `Could not read ${path} (${code ?? "error"}).`
1609
+ };
1610
+ } finally {
1611
+ await handle?.close();
1612
+ }
1613
+ }
1614
+ //#endregion
1615
+ //#region ../model-host/src/app.ts
1616
+ const HOST_FEATURES = [
1617
+ "host",
1618
+ "settings",
1619
+ "events"
1620
+ ];
1621
+ const JOB_FEATURES = [
1622
+ "jobs",
1623
+ "models",
1624
+ "ollama-key"
1625
+ ];
1626
+ const MODEL_NAME = /^[A-Za-z0-9][\w.:/-]{0,399}$/;
1627
+ /** Unsent data past which an event stream is dropped; the job snapshot at the job caps must fit under it. */
1628
+ const EVENT_BUFFER_BYTES = 2097152;
1629
+ const STATFS_TIMEOUT_MS = 5e3;
1630
+ /** Free bytes on the model store right now; null when the path or the filesystem cannot say in time. */
1631
+ async function freshFreeBytes(path) {
1632
+ if (!path) return null;
1633
+ let timer;
1634
+ const late = new Promise((resolve) => timer = setTimeout(() => resolve(null), STATFS_TIMEOUT_MS));
1635
+ try {
1636
+ const info = await Promise.race([statfs(path), late]);
1637
+ return info ? info.bavail * info.bsize : null;
1638
+ } finally {
1639
+ clearTimeout(timer);
1640
+ }
1641
+ }
1642
+ function parseBody(body, schema, allowEmpty = false) {
1643
+ let value = {};
1644
+ if (body.length || !allowEmpty) try {
1645
+ value = JSON.parse(body.toString("utf8"));
1646
+ } catch {
1647
+ throw new HttpError(400, "invalid-json", "The request body is not JSON.");
1648
+ }
1649
+ const parsed = schema.safeParse(value);
1650
+ if (!parsed.success) {
1651
+ const issue = parsed.error.issues[0];
1652
+ throw new HttpError(400, "invalid-request", `${issue?.path.length ? `${issue.path.join(".").slice(0, 100)}: ` : ""}${(issue?.message ?? "invalid").slice(0, 200)}`);
1653
+ }
1654
+ return parsed.data;
1655
+ }
1656
+ function actor(conn, device) {
1657
+ return {
1658
+ device: device?.name ?? "unknown device",
1659
+ user: conn.login,
1660
+ via: conn.login ? "ssh" : "local"
1661
+ };
1662
+ }
1663
+ function createHostApp(options) {
1664
+ const probe = cached(options.probe, options.factsMaxAgeMs ?? 5e3, {
1665
+ timeoutMs: options.factsTimeoutMs ?? 15e3,
1666
+ timeoutError: () => new HttpError(503, "facts-timeout", "Reading host facts is taking too long; try again shortly.", { "retry-after": "5" })
1667
+ });
1668
+ const health = cached(options.health, 2e3);
1669
+ let jobs = null;
1670
+ const events = new HostEvents({
1671
+ facts: async () => (await probe()).host,
1672
+ snapshot: () => (jobs?.list() ?? []).map((job) => ({
1673
+ event: "job",
1674
+ data: job,
1675
+ role: "manage"
1676
+ })),
1677
+ intervalMs: options.eventsIntervalMs ?? 1e4,
1678
+ maxStreams: options.maxEventStreams ?? 32,
1679
+ maxBufferedBytes: EVENT_BUFFER_BYTES,
1680
+ log: options.log
1681
+ });
1682
+ jobs = options.jobs?.({
1683
+ onJob: (job) => events.publish({
1684
+ event: "job",
1685
+ data: job,
1686
+ role: "manage"
1687
+ }),
1688
+ onDismissed: (id) => events.publish({
1689
+ event: "job-dismissed",
1690
+ data: { id },
1691
+ role: "manage"
1692
+ }),
1693
+ freeBytes: async () => freshFreeBytes((await probe()).host.ollama.store.path)
1694
+ }) ?? null;
1695
+ const routes = [
1696
+ {
1697
+ method: "GET",
1698
+ path: "/v1/hello",
1699
+ role: "chat",
1700
+ handle: async ({ res, conn }) => {
1701
+ const ollama = await health();
1702
+ sendJson(res, 200, ModelHostHelloSchema.parse({
1703
+ protocol: 1,
1704
+ minClientProtocol: 1,
1705
+ version: options.version,
1706
+ serverId: options.serverId,
1707
+ mode: options.mode,
1708
+ role: conn.role,
1709
+ ollama: {
1710
+ url: options.ollamaUrl,
1711
+ reachable: ollama.ok,
1712
+ version: ollama.version
1713
+ },
1714
+ features: [...HOST_FEATURES, ...jobs ? JOB_FEATURES : []]
1715
+ }));
1716
+ }
1717
+ },
1718
+ {
1719
+ method: "GET",
1720
+ path: "/v1/host",
1721
+ role: "chat",
1722
+ handle: async ({ res }) => sendJson(res, 200, (await probe()).host)
1723
+ },
1724
+ {
1725
+ method: "GET",
1726
+ path: "/v1/settings",
1727
+ role: "chat",
1728
+ handle: async ({ res }) => sendJson(res, 200, (await probe()).settings)
1729
+ },
1730
+ {
1731
+ method: "GET",
1732
+ path: "/v1/events",
1733
+ role: "chat",
1734
+ handle: ({ res, conn }) => events.subscribe(res, conn.role, conn.role)
1735
+ }
1736
+ ];
1737
+ if (jobs) {
1738
+ const manager = jobs;
1739
+ const action = (run, settled = () => true) => async ({ res, conn, body, params }) => {
1740
+ const { device } = parseBody(body, PullJobActionSchema, true);
1741
+ await run(params.id, actor(conn, device));
1742
+ const job = manager.get(params.id);
1743
+ sendJson(res, settled(job) ? 200 : 202, job);
1744
+ };
1745
+ routes.push({
1746
+ method: "GET",
1747
+ path: "/v1/jobs",
1748
+ role: "manage",
1749
+ handle: ({ res }) => sendJson(res, 200, { jobs: manager.list() })
1750
+ }, {
1751
+ method: "POST",
1752
+ path: "/v1/jobs",
1753
+ role: "manage",
1754
+ handle: async ({ res, conn, body }) => {
1755
+ const request = parseBody(body, PullJobRequestSchema);
1756
+ sendJson(res, 202, await manager.create(request, actor(conn, request.device)));
1757
+ }
1758
+ }, {
1759
+ method: "GET",
1760
+ path: "/v1/jobs/:id",
1761
+ role: "manage",
1762
+ handle: ({ res, params }) => sendJson(res, 200, manager.get(params.id))
1763
+ }, {
1764
+ method: "DELETE",
1765
+ path: "/v1/jobs/:id",
1766
+ role: "manage",
1767
+ handle: async ({ res, conn, body, params }) => {
1768
+ const { device } = parseBody(body, PullJobActionSchema, true);
1769
+ await manager.dismiss(params.id, actor(conn, device));
1770
+ sendJson(res, 200, { dismissed: params.id });
1771
+ }
1772
+ }, {
1773
+ method: "POST",
1774
+ path: "/v1/jobs/:id/cancel",
1775
+ role: "manage",
1776
+ handle: action((id, who) => manager.cancel(id, who), (job) => isFinal(job.state))
1777
+ }, {
1778
+ method: "POST",
1779
+ path: "/v1/jobs/:id/pause",
1780
+ role: "manage",
1781
+ handle: action((id, who) => manager.pause(id, who), (job) => !isActive(job.state))
1782
+ }, {
1783
+ method: "POST",
1784
+ path: "/v1/jobs/:id/resume",
1785
+ role: "manage",
1786
+ handle: action((id, who) => manager.resume(id, who))
1787
+ }, {
1788
+ method: "DELETE",
1789
+ path: "/v1/models/:name",
1790
+ role: "manage",
1791
+ handle: async ({ res, conn, body, params }) => {
1792
+ if (!MODEL_NAME.test(params.name) || params.name.includes("..")) throw new HttpError(400, "invalid-model-name", "Not an Ollama model name.");
1793
+ const { device } = parseBody(body, PullJobActionSchema, true);
1794
+ await manager.removeModel(params.name, actor(conn, device));
1795
+ sendJson(res, 200, { removed: params.name });
1796
+ }
1797
+ }, {
1798
+ method: "GET",
1799
+ path: "/v1/ollama/key",
1800
+ role: "manage",
1801
+ handle: async ({ res }) => sendJson(res, 200, await readOllamaKey((await probe()).ollamaHome))
1802
+ });
1803
+ }
1804
+ return {
1805
+ routes,
1806
+ handler: createRouter(routes),
1807
+ jobs,
1808
+ close: () => events.close()
1809
+ };
1810
+ }
1811
+ //#endregion
1812
+ //#region ../model-host/src/audit.ts
1813
+ const AUDIT_MAX_BYTES = 5242880;
1814
+ /**
1815
+ * Appends one JSON line per entry to `audit.jsonl`, in order; a failed write is logged and the host carries on.
1816
+ * Past `maxBytes` the file moves to `audit.jsonl.1`, replacing the one before.
1817
+ */
1818
+ function createAuditLog(stateDir, log, now = () => /* @__PURE__ */ new Date(), maxBytes = AUDIT_MAX_BYTES) {
1819
+ const path = join(stateDir, "audit.jsonl");
1820
+ let size = null;
1821
+ let chain = Promise.resolve();
1822
+ const currentSize = () => stat(path).then((info) => info.size, () => 0);
1823
+ const write = async (line) => {
1824
+ size ??= await currentSize();
1825
+ const bytes = Buffer.byteLength(line);
1826
+ if (size > 0 && size + bytes > maxBytes) try {
1827
+ await rename(path, `${path}.1`);
1828
+ size = 0;
1829
+ } catch (error) {
1830
+ log(`audit log ${path}: rotating: ${error instanceof Error ? error.message : String(error)}`);
1831
+ size = await currentSize();
1832
+ }
1833
+ await appendFile(path, line, { mode: 416 });
1834
+ size += bytes;
1835
+ };
1836
+ const audit = (entry) => {
1837
+ const line = `${JSON.stringify({
1838
+ time: now().toISOString(),
1839
+ ...entry
1840
+ })}\n`;
1841
+ chain = chain.then(() => write(line)).catch((error) => log(`audit log ${path}: ${error instanceof Error ? error.message : String(error)}`));
1842
+ };
1843
+ return {
1844
+ audit,
1845
+ path,
1846
+ flush: () => chain
1847
+ };
1848
+ }
1849
+ //#endregion
1850
+ //#region ../model-host/src/jobStore.ts
1851
+ /** What a job learned while running that a restart must not recompute. */
1852
+ const RunStateSchema = z$1.object({
1853
+ /** Whether Ollama listed the tag before the first pull; null when it could not say, missing until known. */
1854
+ hadTag: z$1.boolean().nullable().optional(),
1855
+ /** The ref `hadTag` was read for; missing in older files, where it is the job's ref. */
1856
+ hadTagRef: z$1.string().max(1e3).optional(),
1857
+ /** The pull finished, so only the check of the installed weights is left. */
1858
+ pulled: z$1.boolean(),
1859
+ /** Nothing proved the file before the pull (a gated or private repo), so the check after it is the only one. */
1860
+ afterOnly: z$1.boolean()
1861
+ });
1862
+ const StoredJobSchema = z$1.object({
1863
+ job: PullJobSchema,
1864
+ request: PullJobRequestSchema,
1865
+ run: RunStateSchema.optional()
1866
+ });
1867
+ const FILE_NAME = /^([0-9a-f-]{36})\.json$/;
1868
+ const DRAFT_NAME = /^[0-9a-f-]{36}\.json\.[0-9a-f]{12}$/;
1869
+ const MAX_FILE_BYTES = 262144;
1870
+ /** One `jobs/<id>.json` per job, replaced by rename so a crash leaves the old copy or the new one. */
1871
+ function createJobStore(stateDir, log) {
1872
+ const dir = join(stateDir, "jobs");
1873
+ const chains = /* @__PURE__ */ new Map();
1874
+ let ready = null;
1875
+ const ensureDir = () => ready ??= (async () => {
1876
+ await mkdir(dir, {
1877
+ recursive: true,
1878
+ mode: 488
1879
+ });
1880
+ const info = await lstat(dir);
1881
+ if (!info.isDirectory()) throw new Error(`${dir} is not a directory`);
1882
+ if (info.mode & 18) await chmod(dir, 488);
1883
+ })();
1884
+ const serial = (id, task) => {
1885
+ const next = (chains.get(id) ?? Promise.resolve()).then(task, task);
1886
+ const settled = next.catch(() => void 0);
1887
+ chains.set(id, settled);
1888
+ settled.then(() => {
1889
+ if (chains.get(id) === settled) chains.delete(id);
1890
+ });
1891
+ return next;
1892
+ };
1893
+ async function readOne(name) {
1894
+ let handle;
1895
+ try {
1896
+ handle = await open(join(dir, name), constants.O_RDONLY | constants.O_NOFOLLOW);
1897
+ const info = await handle.stat();
1898
+ if (!info.isFile() || info.size > MAX_FILE_BYTES) return null;
1899
+ const parsed = StoredJobSchema.safeParse(JSON.parse(await handle.readFile("utf8")));
1900
+ return parsed.success && `${parsed.data.job.id}.json` === name ? parsed.data : null;
1901
+ } catch {
1902
+ return null;
1903
+ } finally {
1904
+ await handle?.close();
1905
+ }
1906
+ }
1907
+ return {
1908
+ async loadAll() {
1909
+ await ensureDir();
1910
+ const all = await readdir(dir);
1911
+ for (const name of all.filter((entry) => DRAFT_NAME.test(entry))) await rm(join(dir, name), { force: true });
1912
+ const names = all.filter((name) => FILE_NAME.test(name));
1913
+ const records = [];
1914
+ for (const name of names) {
1915
+ const record = await readOne(name);
1916
+ if (record) records.push(record);
1917
+ else log(`skipping unreadable job file ${join(dir, name)}`);
1918
+ }
1919
+ return records.sort((a, b) => a.job.createdAt.localeCompare(b.job.createdAt));
1920
+ },
1921
+ save(record) {
1922
+ return serial(record.job.id, async () => {
1923
+ await ensureDir();
1924
+ const path = join(dir, `${record.job.id}.json`);
1925
+ const draft = `${path}.${randomBytes(6).toString("hex")}`;
1926
+ const handle = await open(draft, "wx", 416);
1927
+ try {
1928
+ await handle.writeFile(`${JSON.stringify(record)}\n`);
1929
+ await handle.sync();
1930
+ await handle.close();
1931
+ await rename(draft, path);
1932
+ } catch (error) {
1933
+ await handle.close().catch(() => void 0);
1934
+ await rm(draft, { force: true });
1935
+ throw error;
1936
+ }
1937
+ });
1938
+ },
1939
+ remove(id) {
1940
+ return serial(id, () => rm(join(dir, `${id}.json`), { force: true }));
1941
+ }
1942
+ };
1943
+ }
1944
+ //#endregion
1945
+ //#region ../model-host/src/version.ts
1946
+ const HOST_VERSION = "0.1.0";
1947
+ //#endregion
1948
+ //#region ../model-host/src/serve.ts
1949
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
1950
+ "127.0.0.1",
1951
+ "localhost",
1952
+ "[::1]"
1953
+ ]);
1954
+ /** The host only ever talks to the Ollama on its own machine. */
1955
+ function checkOllamaUrl(url) {
1956
+ let parsed;
1957
+ try {
1958
+ parsed = new URL(url);
1959
+ } catch {
1960
+ throw new Error(`Not a URL: ${url}`);
1961
+ }
1962
+ if (parsed.protocol !== "http:" || !LOOPBACK_HOSTS.has(parsed.hostname) || parsed.username || parsed.password) throw new Error(`The Ollama URL must be http on a loopback address, such as http://127.0.0.1:11434 (got ${url})`);
1963
+ return parsed.origin;
1964
+ }
1965
+ /** What ties a server id to this machine: a state directory copied to or shared with another one gets a new id. */
1966
+ async function machineIdentity() {
1967
+ const id = (await readFile("/etc/machine-id", "utf8").catch(() => "")).trim();
1968
+ return /^[0-9a-f]{32}$/.test(id) ? id : `host:${hostname()}`;
1969
+ }
1970
+ async function readSavedServerId(path) {
1971
+ let handle;
1972
+ try {
1973
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
1974
+ } catch {
1975
+ return null;
1976
+ }
1977
+ try {
1978
+ if (!(await handle.stat()).isFile()) return null;
1979
+ const saved = JSON.parse(await handle.readFile("utf8"));
1980
+ if (typeof saved.id !== "string" || !/^[A-Za-z0-9-]{8,64}$/.test(saved.id)) return null;
1981
+ return typeof saved.machine === "string" ? {
1982
+ id: saved.id,
1983
+ machine: saved.machine
1984
+ } : null;
1985
+ } catch {
1986
+ return null;
1987
+ } finally {
1988
+ await handle.close();
1989
+ }
1990
+ }
1991
+ async function readServerId(stateDir, machine) {
1992
+ const path = join(stateDir, "server-id");
1993
+ const here = machine ?? await machineIdentity();
1994
+ const saved = await readSavedServerId(path);
1995
+ if (saved?.machine === here) return saved.id;
1996
+ const id = randomUUID();
1997
+ const draft = `${path}.${randomBytes(6).toString("hex")}`;
1998
+ const handle = await open(draft, "wx", 420);
1999
+ try {
2000
+ await handle.writeFile(`${JSON.stringify({
2001
+ id,
2002
+ machine: here
2003
+ })}\n`);
2004
+ await handle.close();
2005
+ await rename(draft, path);
2006
+ } catch (error) {
2007
+ await handle.close().catch(() => void 0);
2008
+ await rm(draft, { force: true });
2009
+ throw error;
2010
+ }
2011
+ return id;
2012
+ }
2013
+ function processAlive(pid) {
2014
+ try {
2015
+ process.kill(pid, 0);
2016
+ return true;
2017
+ } catch (error) {
2018
+ return error.code === "EPERM";
2019
+ }
2020
+ }
2021
+ async function readLockHolder(lockPath) {
2022
+ try {
2023
+ const holder = JSON.parse(await readFile(lockPath, "utf8"));
2024
+ return {
2025
+ pid: typeof holder.pid === "number" ? holder.pid : null,
2026
+ host: typeof holder.host === "string" ? holder.host : null,
2027
+ machine: typeof holder.machine === "string" ? holder.machine : null
2028
+ };
2029
+ } catch {
2030
+ return null;
2031
+ }
2032
+ }
2033
+ /**
2034
+ * One host per state directory and per socket directory (`what` names which, for the error). A holder on this machine
2035
+ * whose pid is gone crashed and is taken over at once. A holder on another machine (a shared home) is never taken
2036
+ * over, however stale its lock looks: staleness compares that machine's refreshes with this one's clock and boot time.
2037
+ * Machines are told apart by `machineIdentity()`, since two can share a default hostname.
2038
+ */
2039
+ async function takeLock(dir, what, machine) {
2040
+ const path = join(dir, "serve");
2041
+ const lockPath = `${path}.lock`;
2042
+ const busy = (holder) => {
2043
+ const remote = holder.machine ? holder.machine !== machine : holder.host !== null && holder.host !== hostname();
2044
+ const detail = [holder.pid ? `pid ${holder.pid}` : null, remote && holder.host ? `on ${holder.host}` : null].filter(Boolean).join(" ");
2045
+ const hint = remote ? `; if that machine no longer runs it, remove ${lockPath}` : "";
2046
+ return /* @__PURE__ */ new Error(`Another b4m-host is running with ${what} in ${dir}${detail ? ` (${detail})` : ""}${hint}`);
2047
+ };
2048
+ const before = await readLockHolder(lockPath);
2049
+ if (before?.machine && before.machine !== machine) throw busy(before);
2050
+ try {
2051
+ return await lockFile(path, "b4m-host", { machine });
2052
+ } catch (error) {
2053
+ if (!(error instanceof ModelFileBusyError)) throw error;
2054
+ const holder = await readLockHolder(lockPath);
2055
+ if (error.pid && holder?.machine === machine && !processAlive(error.pid)) return lockFile(path, "b4m-host", {
2056
+ force: true,
2057
+ machine
2058
+ });
2059
+ throw busy(holder ?? {
2060
+ pid: error.pid,
2061
+ host: null,
2062
+ machine: null
2063
+ });
2064
+ }
2065
+ }
2066
+ /** Removes a socket file nothing listens on; refuses one that is live, is not a socket, or cannot be probed. */
2067
+ async function clearStaleSocket(path) {
2068
+ const stat = await lstat(path).catch(() => null);
2069
+ if (!stat) return;
2070
+ if (!stat.isSocket()) throw new Error(`${path} exists and is not a socket`);
2071
+ const code = await new Promise((resolve) => {
2072
+ const socket = connect(path);
2073
+ socket.once("connect", () => {
2074
+ socket.destroy();
2075
+ resolve(null);
2076
+ });
2077
+ socket.once("error", (error) => resolve(error.code ?? "unknown"));
2078
+ });
2079
+ if (code === null) throw new Error(`Another b4m-host is already listening on ${path}`);
2080
+ if (code === "ENOENT") return;
2081
+ if (code !== "ECONNREFUSED") throw new Error(`Cannot tell whether ${path} is in use (${code}); remove it by hand`);
2082
+ await rm(path, { force: true });
2083
+ }
2084
+ /**
2085
+ * Creates `dir` with `mode` if missing, then requires a real directory owned by this user that nobody else can write.
2086
+ * Group and other bits beyond that are the caller's choice: the sockets' own modes are the authorization.
2087
+ */
2088
+ async function ensurePrivateDir(dir, mode) {
2089
+ if (await mkdir(dir, {
2090
+ recursive: true,
2091
+ mode
2092
+ }) !== void 0) await chmod(dir, mode);
2093
+ const info = await lstat(dir);
2094
+ const uid = process.getuid?.();
2095
+ if (!info.isDirectory()) throw new Error(`${dir} is not a directory`);
2096
+ if (uid !== void 0 && info.uid !== uid) throw new Error(`${dir} is owned by uid ${info.uid}, not ${uid}`);
2097
+ if (info.mode & 18) throw new Error(`${dir} is writable by group or others (mode ${(info.mode & 511).toString(8)})`);
2098
+ }
2099
+ async function listenerSpecs(options, socketDir) {
2100
+ const specs = [];
2101
+ for (const spec of socketSpecs(options.mode, socketDir)) {
2102
+ const gid = spec.group ? await lookupGroupId(spec.group, options.groupFile) : null;
2103
+ if (spec.group && gid === null) options.log(`group ${spec.group} does not exist; ${spec.path} is limited to this user`);
2104
+ specs.push({
2105
+ role: spec.role,
2106
+ path: spec.path,
2107
+ gid,
2108
+ mode: gid === null ? 384 : 432
2109
+ });
2110
+ }
2111
+ return specs;
2112
+ }
2113
+ /** Runs the host until `signal` aborts. */
2114
+ async function serve(options) {
2115
+ const ollamaUrl = checkOllamaUrl(options.ollamaUrl);
2116
+ const stateDir = options.stateDir ?? defaultStateDir(options.mode);
2117
+ const socketDir = options.socketDir ?? defaultSocketDir(options.mode);
2118
+ await ensurePrivateDir(stateDir, options.mode === "user" ? 448 : 488);
2119
+ await ensurePrivateDir(socketDir, options.mode === "user" ? 448 : 493);
2120
+ const machine = await machineIdentity();
2121
+ const locks = [{
2122
+ dir: stateDir,
2123
+ lock: await takeLock(stateDir, "state", machine)
2124
+ }];
2125
+ try {
2126
+ if (socketDir !== stateDir) locks.push({
2127
+ dir: socketDir,
2128
+ lock: await takeLock(socketDir, "sockets", machine)
2129
+ });
2130
+ } catch (error) {
2131
+ await locks[0].lock.release();
2132
+ throw error;
2133
+ }
2134
+ const stopped = new AbortController();
2135
+ const stop = () => stopped.abort();
2136
+ options.signal.addEventListener("abort", stop, { once: true });
2137
+ let lockLost = null;
2138
+ const lockCheck = setInterval(() => {
2139
+ for (const { dir, lock } of locks) lock.check().catch((error) => {
2140
+ if (!(error instanceof ModelFileBusyError)) return;
2141
+ lockLost ??= /* @__PURE__ */ new Error(`Lost the lock on ${dir}; another b4m-host took it over`);
2142
+ stop();
2143
+ });
2144
+ }, options.lockCheckMs ?? 1e4);
2145
+ const runtime = new OllamaRuntime({ baseUrl: ollamaUrl });
2146
+ const probe = options.probe ?? probeModelHost;
2147
+ let app = null;
2148
+ let server = null;
2149
+ const { audit, flush: flushAudit } = createAuditLog(stateDir, options.log);
2150
+ const hub = new HuggingFaceHub();
2151
+ let curated = null;
2152
+ try {
2153
+ app = createHostApp({
2154
+ mode: options.mode,
2155
+ serverId: await readServerId(stateDir, machine),
2156
+ version: HOST_VERSION,
2157
+ ollamaUrl,
2158
+ probe: () => probe({
2159
+ ollamaUrl,
2160
+ runtime
2161
+ }),
2162
+ health: () => runtime.health(),
2163
+ log: options.log,
2164
+ jobs: (hooks) => new JobManager({
2165
+ runtime,
2166
+ hub: () => hub,
2167
+ libraryLayers: (ref, layerOptions) => ollamaLibraryLayers(ref, layerOptions),
2168
+ curated: () => curated ??= loadCuratedManifest(options.log),
2169
+ store: createJobStore(stateDir, options.log),
2170
+ audit,
2171
+ hostName: hostname(),
2172
+ log: options.log,
2173
+ ...hooks,
2174
+ ...options.jobs
2175
+ })
2176
+ });
2177
+ await app.jobs?.load();
2178
+ server = new HostServer(app.handler, options.limits, options.log);
2179
+ for (const spec of await listenerSpecs(options, socketDir)) {
2180
+ await clearStaleSocket(spec.path);
2181
+ await server.listen(spec);
2182
+ options.log(`listening on ${spec.path} (${spec.role}, mode ${spec.mode.toString(8)})`);
2183
+ }
2184
+ options.onListening?.(server.listeners);
2185
+ if (!options.signal.aborted && !stopped.signal.aborted) await new Promise((resolve) => stopped.signal.addEventListener("abort", () => resolve(), { once: true }));
2186
+ } finally {
2187
+ clearInterval(lockCheck);
2188
+ options.signal.removeEventListener("abort", stop);
2189
+ await server?.close();
2190
+ await app?.jobs?.close();
2191
+ await flushAudit();
2192
+ app?.close();
2193
+ for (const { lock } of locks) await lock.release();
2194
+ }
2195
+ if (lockLost) throw lockLost;
2196
+ }
2197
+ //#endregion
2198
+ //#region ../model-host/src/cli.ts
2199
+ const EXIT_USAGE = 2;
2200
+ function usage(program) {
2201
+ return `Usage: ${program} <command> [options]
2202
+
2203
+ Commands:
2204
+ serve Run the host (a service manager runs this)
2205
+ dial-stdio Connect stdin and stdout to the host's socket (Bike4Mind runs this over SSH)
2206
+ status Show whether the host is running and what it reports
2207
+ version Print the version
2208
+
2209
+ Options:
2210
+ --user serve: run for this user only, with one socket only this user can open
2211
+ --socket-dir <dir> Socket directory (default /run/b4m-host; with --user, $XDG_RUNTIME_DIR/b4m-host)
2212
+ --state-dir <dir> serve: state directory (default /var/lib/b4m-host; with --user, ~/.local/state/b4m-host)
2213
+ --ollama-url <url> serve: the Ollama on this machine (default ${DEFAULT_OLLAMA_URL})
2214
+ --json status: print JSON
2215
+
2216
+ Exit codes: 3 the host is not running, 4 no permission to open its socket.
2217
+ `;
2218
+ }
2219
+ const OPTIONS = {
2220
+ serve: {
2221
+ user: { type: "boolean" },
2222
+ "socket-dir": { type: "string" },
2223
+ "state-dir": { type: "string" },
2224
+ "ollama-url": { type: "string" }
2225
+ },
2226
+ "dial-stdio": { "socket-dir": { type: "string" } },
2227
+ status: {
2228
+ "socket-dir": { type: "string" },
2229
+ json: { type: "boolean" }
2230
+ },
2231
+ version: {}
2232
+ };
2233
+ function processSignal() {
2234
+ const controller = new AbortController();
2235
+ const stop = () => controller.abort();
2236
+ process.once("SIGINT", stop);
2237
+ process.once("SIGTERM", stop);
2238
+ return controller.signal;
2239
+ }
2240
+ async function status(socketDir, json, io) {
2241
+ const dialed = await dialFirst(dialCandidates(socketDir));
2242
+ if (!dialed.ok) {
2243
+ if (json) io.stdout.write(`${JSON.stringify({
2244
+ running: false,
2245
+ reason: dialed.failure,
2246
+ socket: dialed.path
2247
+ })}\n`);
2248
+ io.stderr.write(`${dialed.message}\n`);
2249
+ return exitCodeFor(dialed.failure);
2250
+ }
2251
+ dialed.socket.destroy();
2252
+ const hello = await fetchHello(dialed.path);
2253
+ if (json) {
2254
+ io.stdout.write(`${JSON.stringify({
2255
+ running: true,
2256
+ socket: dialed.path,
2257
+ hello
2258
+ })}\n`);
2259
+ return 0;
2260
+ }
2261
+ const ollama = hello.ollama.reachable ? `${hello.ollama.url}, version ${hello.ollama.version ?? "unknown"}` : `${hello.ollama.url}, not reachable`;
2262
+ io.stdout.write([
2263
+ `b4m-host ${hello.version} is running (${hello.mode} mode)`,
2264
+ ` socket ${dialed.path} (role ${hello.role})`,
2265
+ ` server ${hello.serverId}`,
2266
+ ` ollama ${ollama}`,
2267
+ ""
2268
+ ].join("\n"));
2269
+ return 0;
2270
+ }
2271
+ /** Runs one `b4m-host` command and resolves with its exit code; `serve` resolves once it has stopped. */
2272
+ async function runHost(argv, partialIo = {}) {
2273
+ const io = {
2274
+ stdin: process.stdin,
2275
+ stdout: process.stdout,
2276
+ stderr: process.stderr,
2277
+ programName: "b4m-host",
2278
+ ...partialIo
2279
+ };
2280
+ const [command, ...rest] = argv;
2281
+ if (!command) {
2282
+ io.stderr.write(usage(io.programName));
2283
+ return EXIT_USAGE;
2284
+ }
2285
+ if (command === "help" || command === "--help" || command === "-h") {
2286
+ io.stdout.write(usage(io.programName));
2287
+ return 0;
2288
+ }
2289
+ if (command === "--version") {
2290
+ io.stdout.write(`${HOST_VERSION}\n`);
2291
+ return 0;
2292
+ }
2293
+ if (!Object.keys(OPTIONS).includes(command)) {
2294
+ io.stderr.write(`Unknown command: ${command}\n\n${usage(io.programName)}`);
2295
+ return EXIT_USAGE;
2296
+ }
2297
+ let values;
2298
+ try {
2299
+ const options = OPTIONS[command];
2300
+ ({values} = parseArgs({
2301
+ args: [...rest],
2302
+ options,
2303
+ strict: true
2304
+ }));
2305
+ } catch (error) {
2306
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n\n${usage(io.programName)}`);
2307
+ return EXIT_USAGE;
2308
+ }
2309
+ const text = (key) => typeof values[key] === "string" ? values[key] : void 0;
2310
+ const socketDir = text("socket-dir");
2311
+ try {
2312
+ switch (command) {
2313
+ case "version":
2314
+ io.stdout.write(`${HOST_VERSION}\n`);
2315
+ return 0;
2316
+ case "status": return await status(socketDir, values.json === true, io);
2317
+ case "dial-stdio": return await dialStdio({
2318
+ candidates: dialCandidates(socketDir),
2319
+ ...io
2320
+ });
2321
+ case "serve":
2322
+ await serve({
2323
+ mode: values.user ? "user" : "system",
2324
+ socketDir,
2325
+ stateDir: text("state-dir"),
2326
+ ollamaUrl: text("ollama-url") ?? "http://127.0.0.1:11434",
2327
+ signal: io.signal ?? processSignal(),
2328
+ log: (line) => io.stderr.write(`b4m-host: ${line}\n`)
2329
+ });
2330
+ return 0;
2331
+ }
2332
+ } catch (error) {
2333
+ io.stderr.write(`b4m-host: ${error instanceof Error ? error.message : String(error)}\n`);
2334
+ return 1;
2335
+ }
2336
+ }
2337
+ //#endregion
2338
+ //#region src/commands/hostCommand.ts
2339
+ /** `b4m host <args>`: the same entry as the standalone `b4m-host`, run under the CLI's Node. */
2340
+ function handleHostCommand(args) {
2341
+ return runHost(args, { programName: "b4m host" });
2342
+ }
2343
+ //#endregion
2344
+ export { handleHostCommand };