@nice-code/commander 0.70.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.
@@ -0,0 +1,1954 @@
1
+ const require_cli = require("./cli.cjs");
2
+ let node_fs = require("node:fs");
3
+ let node_path = require("node:path");
4
+ let node_url = require("node:url");
5
+ let node_crypto = require("node:crypto");
6
+ let ws = require("ws");
7
+ let node_fs_promises = require("node:fs/promises");
8
+ let _nice_code_process = require("@nice-code/process");
9
+ let node_net = require("node:net");
10
+ let node_http = require("node:http");
11
+ let node_readline = require("node:readline");
12
+ //#region src/daemon/rotatingLog.ts
13
+ var RotatingLog = class {
14
+ _path;
15
+ _segmentBytes;
16
+ _keepSegments;
17
+ _fd = null;
18
+ _bytes = 0;
19
+ constructor(dir, basename, options = {}) {
20
+ (0, node_fs.mkdirSync)(dir, {
21
+ recursive: true,
22
+ mode: 448
23
+ });
24
+ this._path = (0, node_path.join)(dir, `${basename}.log`);
25
+ this._segmentBytes = options.segmentBytes ?? 1e6;
26
+ this._keepSegments = options.keepSegments ?? 5;
27
+ }
28
+ get path() {
29
+ return this._path;
30
+ }
31
+ /** Existing segments, NEWEST first (`x.log`, `x.log.1`, …) — the order a reader wants. */
32
+ segments() {
33
+ const paths = [];
34
+ for (let index = 0; index < this._keepSegments; index += 1) {
35
+ const path = index === 0 ? this._path : `${this._path}.${index}`;
36
+ if ((0, node_fs.existsSync)(path)) paths.push(path);
37
+ }
38
+ return paths;
39
+ }
40
+ write(line) {
41
+ try {
42
+ if (this._fd == null) this._open();
43
+ const data = line.endsWith("\n") ? line : `${line}\n`;
44
+ if (this._bytes + data.length > this._segmentBytes && this._bytes > 0) this._roll();
45
+ (0, node_fs.writeSync)(this._fd, data);
46
+ this._bytes += data.length;
47
+ } catch {}
48
+ }
49
+ close() {
50
+ if (this._fd == null) return;
51
+ try {
52
+ (0, node_fs.closeSync)(this._fd);
53
+ } catch {}
54
+ this._fd = null;
55
+ this._bytes = 0;
56
+ }
57
+ _open() {
58
+ this._fd = (0, node_fs.openSync)(this._path, "a", 384);
59
+ this._bytes = (0, node_fs.statSync)(this._path).size;
60
+ }
61
+ _roll() {
62
+ this.close();
63
+ for (let index = this._keepSegments - 1; index >= 1; index -= 1) {
64
+ const from = index === 1 ? this._path : `${this._path}.${index - 1}`;
65
+ const to = `${this._path}.${index}`;
66
+ if ((0, node_fs.existsSync)(from)) (0, node_fs.renameSync)(from, to);
67
+ }
68
+ this._open();
69
+ }
70
+ };
71
+ //#endregion
72
+ //#region src/daemon/aggregateSink.ts
73
+ const FLUSH_EVERY = 100;
74
+ var AggregateSink = class {
75
+ generation;
76
+ _log;
77
+ _persistPath;
78
+ _seq;
79
+ _sinceFlush = 0;
80
+ constructor(logsDir, persistPath, generation) {
81
+ this.generation = generation;
82
+ this._log = new RotatingLog(logsDir, "aggregate", {
83
+ segmentBytes: 1e7,
84
+ keepSegments: 5
85
+ });
86
+ this._persistPath = persistPath;
87
+ let highWater = 0;
88
+ try {
89
+ highWater = Number.parseInt((0, node_fs.readFileSync)(persistPath, "utf8"), 10) || 0;
90
+ } catch {}
91
+ this._seq = highWater;
92
+ }
93
+ get nextSeq() {
94
+ return this._seq + 1;
95
+ }
96
+ /** Stamps, persists, and returns the ordering key — consumers of the merged timeline need it. */
97
+ record(id, line) {
98
+ this._seq += 1;
99
+ const entry = {
100
+ g: this.generation,
101
+ s: this._seq,
102
+ id,
103
+ seq: line.seq,
104
+ ts: line.ts,
105
+ stream: line.stream,
106
+ op: line.op,
107
+ text: line.text
108
+ };
109
+ this._log.write(JSON.stringify(entry));
110
+ this._sinceFlush += 1;
111
+ if (this._sinceFlush >= FLUSH_EVERY) this.flush();
112
+ return {
113
+ g: entry.g,
114
+ s: entry.s
115
+ };
116
+ }
117
+ /** Newest-first segment paths, for the bounded history reader. */
118
+ segments() {
119
+ return this._log.segments();
120
+ }
121
+ flush() {
122
+ this._sinceFlush = 0;
123
+ try {
124
+ (0, node_fs.writeFileSync)(this._persistPath, String(this._seq), { mode: 384 });
125
+ } catch {}
126
+ }
127
+ close() {
128
+ this.flush();
129
+ this._log.close();
130
+ }
131
+ };
132
+ //#endregion
133
+ //#region src/daemon/auth.ts
134
+ const CAPABILITY_TTL_MS = 5 * 6e4;
135
+ const TICKET_TTL_MS = 3e4;
136
+ function bearerToken(authorization) {
137
+ if (authorization == null || !authorization.startsWith("Bearer ")) return null;
138
+ const token = authorization.slice(7).trim();
139
+ return token === "" ? null : token;
140
+ }
141
+ var CommanderAuth = class {
142
+ _rootToken;
143
+ /** token → expiresAt (ms). */
144
+ _capabilities = /* @__PURE__ */ new Map();
145
+ _tickets = /* @__PURE__ */ new Map();
146
+ constructor(rootToken) {
147
+ this._rootToken = rootToken;
148
+ }
149
+ /** The CLI's authority, straight from the instance record. */
150
+ isRoot(authorization) {
151
+ const presented = bearerToken(authorization);
152
+ if (presented == null) return false;
153
+ const a = Buffer.from(presented);
154
+ const b = Buffer.from(this._rootToken);
155
+ return a.length === b.length && (0, node_crypto.timingSafeEqual)(a, b);
156
+ }
157
+ /** What the browser bootstrap hands out: short-lived, JS-memory-only by design. */
158
+ mintCapability(now = Date.now()) {
159
+ this._sweep(now);
160
+ const capability = (0, node_crypto.randomBytes)(24).toString("base64url");
161
+ this._capabilities.set(capability, now + CAPABILITY_TTL_MS);
162
+ return capability;
163
+ }
164
+ hasCapability(authorization, now = Date.now()) {
165
+ const token = bearerToken(authorization);
166
+ if (token == null) return false;
167
+ this._sweep(now);
168
+ return (this._capabilities.get(token) ?? 0) > now;
169
+ }
170
+ canMintTicket(authorization, now = Date.now()) {
171
+ return this.isRoot(authorization) || this.hasCapability(authorization, now);
172
+ }
173
+ mintTicket(now = Date.now()) {
174
+ this._sweep(now);
175
+ const ticket = (0, node_crypto.randomBytes)(24).toString("base64url");
176
+ this._tickets.set(ticket, now + TICKET_TTL_MS);
177
+ return ticket;
178
+ }
179
+ /** One-use: a consumed or expired ticket never authorizes again. */
180
+ consumeTicket(ticket, now = Date.now()) {
181
+ this._sweep(now);
182
+ const expires = this._tickets.get(ticket);
183
+ if (expires == null) return false;
184
+ this._tickets.delete(ticket);
185
+ return expires > now;
186
+ }
187
+ _sweep(now) {
188
+ for (const [token, expires] of this._capabilities) if (expires <= now) this._capabilities.delete(token);
189
+ for (const [ticket, expires] of this._tickets) if (expires <= now) this._tickets.delete(ticket);
190
+ }
191
+ };
192
+ /**
193
+ * DNS-rebinding floor: the Host header must name a loopback form. Browsers send Host on every
194
+ * request (including ws upgrades); a rebound `evil.com → 127.0.0.1` arrives with `Host:
195
+ * evil.com` and dies here. `*.localhost` names also resolve loopback per RFC 6761.
196
+ */
197
+ function hostIsLoopbackForm(host) {
198
+ if (host == null || host === "") return false;
199
+ const name = host.startsWith("[") ? host.slice(1, host.indexOf("]")).toLowerCase() : host.split(":", 1)[0]?.toLowerCase() ?? "";
200
+ if (name === "::1" || name === "localhost" || name.endsWith(".localhost")) return true;
201
+ if (!name.startsWith("127.")) return false;
202
+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name);
203
+ }
204
+ /**
205
+ * Cross-site guard (devtools-cli pattern): `Sec-Fetch-Site` must be same-origin/none when
206
+ * present, and a present Origin must equal the request's own Host. Non-browser clients (curl,
207
+ * the CLI) send neither header and pass — the capability/ticket check is what authorizes them.
208
+ */
209
+ function crossSiteRequestAllowed(request) {
210
+ const fetchSite = request.headers["sec-fetch-site"];
211
+ if (fetchSite != null && fetchSite !== "same-origin" && fetchSite !== "none") return false;
212
+ const origin = request.headers.origin;
213
+ if (origin == null) return true;
214
+ return origin === `http://${request.headers.host}`;
215
+ }
216
+ //#endregion
217
+ //#region src/daemon/configWatch.ts
218
+ const DEBOUNCE_MS = 150;
219
+ const RECONCILE_MS = 5e3;
220
+ function watchCommanderConfig(options) {
221
+ let closed = false;
222
+ let timer = null;
223
+ let inFlight = null;
224
+ let queued = false;
225
+ const mtimes = /* @__PURE__ */ new Map();
226
+ const watchers = [];
227
+ const rememberMtimes = async () => {
228
+ for (const file of [options.configPath, ...options.watchFiles]) try {
229
+ mtimes.set(file, (await (0, node_fs_promises.stat)(file)).mtimeMs);
230
+ } catch {
231
+ mtimes.delete(file);
232
+ }
233
+ };
234
+ const runAttempts = async () => {
235
+ do {
236
+ queued = false;
237
+ await rememberMtimes();
238
+ try {
239
+ const file = await require_cli.loadCommanderConfigFile(options.configPath);
240
+ const { resolved, errors } = require_cli.validateCommanderConfig(file.raw, {
241
+ configPath: file.configPath,
242
+ configDir: file.configDir
243
+ });
244
+ if (resolved != null) options.onConfig(resolved);
245
+ else options.onError(errors);
246
+ } catch (error) {
247
+ options.onError([error.message]);
248
+ }
249
+ } while (queued && !closed);
250
+ };
251
+ const attempt = async () => {
252
+ if (closed) return;
253
+ if (inFlight != null) {
254
+ queued = true;
255
+ await inFlight;
256
+ return;
257
+ }
258
+ inFlight = runAttempts().finally(() => {
259
+ inFlight = null;
260
+ });
261
+ await inFlight;
262
+ };
263
+ const trigger = () => {
264
+ if (closed) return;
265
+ if (timer != null) clearTimeout(timer);
266
+ timer = setTimeout(() => {
267
+ timer = null;
268
+ attempt();
269
+ }, DEBOUNCE_MS);
270
+ timer.unref();
271
+ };
272
+ for (const file of [options.configPath, ...options.watchFiles]) try {
273
+ const watcher = (0, node_fs.watch)(file, { persistent: false }, trigger);
274
+ watcher.on("error", () => {});
275
+ watchers.push(watcher);
276
+ } catch {}
277
+ rememberMtimes();
278
+ const reconcile = setInterval(() => {
279
+ (async () => {
280
+ for (const file of [options.configPath, ...options.watchFiles]) {
281
+ let mtime = null;
282
+ try {
283
+ mtime = (await (0, node_fs_promises.stat)(file)).mtimeMs;
284
+ } catch {}
285
+ const seen = mtimes.get(file) ?? null;
286
+ if (mtime !== seen) {
287
+ mtimes.set(file, mtime ?? 0);
288
+ trigger();
289
+ return;
290
+ }
291
+ }
292
+ })();
293
+ }, RECONCILE_MS);
294
+ reconcile.unref();
295
+ return {
296
+ close() {
297
+ closed = true;
298
+ if (timer != null) clearTimeout(timer);
299
+ clearInterval(reconcile);
300
+ for (const watcher of watchers) watcher.close();
301
+ },
302
+ reloadNow: attempt
303
+ };
304
+ }
305
+ //#endregion
306
+ //#region src/daemon/controlPlane.ts
307
+ const DAEMON_COORD = require_cli.RuntimeCoordinate.env("commander_daemon");
308
+ const SLOW_CONSUMER_DROP_BYTES = 256 * 1024;
309
+ function projectExit(exit) {
310
+ return {
311
+ ...exit.code != null ? { code: exit.code } : {},
312
+ ...exit.signal != null ? { signal: exit.signal } : {},
313
+ expected: exit.expected
314
+ };
315
+ }
316
+ function projectProcess(status) {
317
+ return {
318
+ kind: status.kind,
319
+ state: status.state,
320
+ ...status.pid != null ? { pid: status.pid } : {},
321
+ ...status.startedAt != null ? { startedAt: status.startedAt } : {},
322
+ restarts: status.restarts,
323
+ ...status.lastExit != null ? { lastExit: projectExit(status.lastExit) } : {},
324
+ stale: status.stale,
325
+ removed: status.removed,
326
+ ...status.blockedBy != null ? { blockedBy: status.blockedBy } : {},
327
+ degradedBy: status.degradedBy,
328
+ ...status.unreadyReason != null ? { unreadyReason: status.unreadyReason } : {},
329
+ ...status.capability != null ? { capability: {
330
+ treeMechanism: status.capability.treeMechanism,
331
+ degraded: status.capability.degraded,
332
+ notes: status.capability.notes
333
+ } } : {},
334
+ tags: status.tags,
335
+ detail: {
336
+ command: status.detail.command,
337
+ cwd: status.detail.cwd,
338
+ dependsOn: status.detail.dependsOn,
339
+ ...status.detail.ready != null ? { ready: status.detail.ready } : {},
340
+ endpoints: status.detail.endpoints.map((endpoint) => ({
341
+ name: endpoint.name,
342
+ protocol: endpoint.protocol,
343
+ host: endpoint.host,
344
+ port: endpoint.port,
345
+ ownership: endpoint.ownership,
346
+ ...endpoint.url != null ? { url: endpoint.url } : {}
347
+ }))
348
+ }
349
+ };
350
+ }
351
+ function projectGroups(config) {
352
+ return Object.fromEntries(Object.entries(config.groups).map(([name, group]) => [name, { members: [...group.ids] }]));
353
+ }
354
+ function createControlPlane(options) {
355
+ const { supervisor, log } = options;
356
+ const runtime = new require_cli.ActionRuntime(DAEMON_COORD);
357
+ const write = (...parts) => log(parts.map(String).join(" "));
358
+ const serveSink = {
359
+ log: write,
360
+ error: write
361
+ };
362
+ /** Errors from the most recent reload attempt — empty means the new revision is live. */
363
+ let lastReloadErrors = [];
364
+ const initialState = () => ({
365
+ generation: options.generation,
366
+ configRevisionHash: supervisor.config.configRevisionHash,
367
+ configError: [],
368
+ processes: Object.fromEntries(supervisor.status().map((status) => [status.id, projectProcess(status)])),
369
+ groups: projectGroups(supervisor.config)
370
+ });
371
+ const engine = require_cli.createRealmServerEngine(require_cli.commanderStatusRealm, { initialState: initialState() });
372
+ supervisor.subscribe((id) => {
373
+ const status = supervisor.status().find((candidate) => candidate.id === id);
374
+ if (status == null) return;
375
+ engine.update((draft) => {
376
+ draft.processes[id] = projectProcess(status);
377
+ });
378
+ });
379
+ const liveSockets = /* @__PURE__ */ new Set();
380
+ const acceptorAccess = {};
381
+ const server = require_cli.serveChannel(runtime, require_cli.commanderChannel, {
382
+ storage: require_cli.createMemoryStorageAdapter_json(),
383
+ carriers: [require_cli.wsAcceptorCarrier({ send: (ws, frame) => {
384
+ if (ws.bufferedAmount > SLOW_CONSUMER_DROP_BYTES) {
385
+ log("wire: dropping a slow consumer");
386
+ liveSockets.delete(ws);
387
+ server.drop(ws);
388
+ ws.terminate();
389
+ return;
390
+ }
391
+ ws.send(frame);
392
+ } }), require_cli.httpAcceptorCarrier()],
393
+ handlers: [require_cli.commanderControlDomain.wrapAsLocalHandler({
394
+ start: async ({ ids, wait, staggerMs }) => {
395
+ const config = supervisor.config;
396
+ const ordered = require_cli.orderByDependency(config.processes, require_cli.withDependencies(config.processes, ids));
397
+ return supervisor.start(ordered, {
398
+ wait: wait ?? true,
399
+ staggerMs: staggerMs ?? 0
400
+ });
401
+ },
402
+ stop: async ({ ids }) => supervisor.stop(ids),
403
+ restart: async ({ ids, wait, staggerMs }) => {
404
+ const config = supervisor.config;
405
+ const ordered = require_cli.orderByDependency(config.processes, require_cli.withDependencies(config.processes, ids));
406
+ return supervisor.restart(ordered, {
407
+ wait: wait ?? true,
408
+ staggerMs: staggerMs ?? 0
409
+ });
410
+ },
411
+ reloadConfig: async () => {
412
+ await options.reloadConfig();
413
+ return {
414
+ ok: true,
415
+ applied: lastReloadErrors.length === 0,
416
+ configRevisionHash: supervisor.config.configRevisionHash,
417
+ errors: [...lastReloadErrors]
418
+ };
419
+ },
420
+ shutdown: async () => {
421
+ setTimeout(() => options.requestShutdown(), 25).unref();
422
+ return { ok: true };
423
+ }
424
+ })],
425
+ protocols: [require_cli.createRealmAcceptor({
426
+ realms: { commander_status: {
427
+ engine,
428
+ minSecurity: "authenticated",
429
+ resolveAvatar: (ws) => {
430
+ const client = acceptorAccess.clientFor?.(ws);
431
+ if (client?.perId == null) return void 0;
432
+ return {
433
+ type: "viewer",
434
+ persistentId: client.perId,
435
+ instanceId: client.insId ?? "default"
436
+ };
437
+ }
438
+ } },
439
+ levelFor: (ws) => acceptorAccess.levelFor?.(ws) ?? "none"
440
+ })],
441
+ logger: require_cli.createDefaultServeLogger({ sink: serveSink })
442
+ });
443
+ acceptorAccess.clientFor = (ws) => server.acceptors[0]?.wireAcceptor.clientForConnection(ws);
444
+ acceptorAccess.levelFor = (ws) => server.acceptors[0]?.wireAcceptor.levelFor(ws) ?? "none";
445
+ return {
446
+ fetch: (request) => server.fetch(request),
447
+ handleConnection: (ws) => {
448
+ liveSockets.add(ws);
449
+ ws.on("message", (data, isBinary) => {
450
+ const frame = isBinary ? Array.isArray(data) ? Buffer.concat(data) : data instanceof ArrayBuffer ? Buffer.from(data) : data : data.toString("utf8");
451
+ server.receive(ws, frame);
452
+ });
453
+ const forget = () => {
454
+ liveSockets.delete(ws);
455
+ server.drop(ws);
456
+ };
457
+ ws.on("close", forget);
458
+ ws.on("error", forget);
459
+ },
460
+ syncConfig: (next) => {
461
+ lastReloadErrors = [];
462
+ engine.update((draft) => {
463
+ draft.configRevisionHash = next.configRevisionHash;
464
+ draft.configError = [];
465
+ draft.groups = projectGroups(next);
466
+ for (const status of supervisor.status()) draft.processes[status.id] = projectProcess(status);
467
+ });
468
+ },
469
+ syncConfigError: (errors) => {
470
+ lastReloadErrors = [...errors];
471
+ engine.update((draft) => {
472
+ draft.configError = errors;
473
+ });
474
+ },
475
+ close: () => {
476
+ for (const ws of [...liveSockets]) ws.terminate();
477
+ liveSockets.clear();
478
+ }
479
+ };
480
+ }
481
+ //#endregion
482
+ //#region src/daemon/history.ts
483
+ /** Entries one read may return. A viewer renders a screenful; this is already generous. */
484
+ const MAX_HISTORY_ENTRIES = 2e3;
485
+ /** Bytes of one segment tail to consider. Segments are 10 MB; this is the recent end of one. */
486
+ const SEGMENT_TAIL_BYTES = 4e6;
487
+ /**
488
+ * Read matching entries from the newest end of the aggregate log backwards.
489
+ *
490
+ * The on-disk shape is flat (`{g,s,id,seq,ts,stream,op,text}`) while the wire shape nests the
491
+ * library's line — changing the file to match would invalidate every segment already written, so
492
+ * the mapping lives here instead.
493
+ */
494
+ async function readHistory(segments, query) {
495
+ const limit = Math.min(query.limit, MAX_HISTORY_ENTRIES);
496
+ const needle = query.query == null || query.query === "" ? null : query.query.toLowerCase();
497
+ const wanted = query.procs == null ? null : new Set(query.procs);
498
+ const found = [];
499
+ let scanned = 0;
500
+ /**
501
+ * ⚠ A segment larger than the byte window is only read from its tail, so the scan did NOT see
502
+ * the whole history even if the line budget was never touched. Reporting `complete` off the
503
+ * budget alone would answer "no matches" for a line that is sitting in the part we skipped —
504
+ * the exact thing the caller's "stopped after N lines" wording exists to prevent.
505
+ */
506
+ let windowed = false;
507
+ for (const segment of segments) {
508
+ if (found.length >= limit || scanned >= 2e5) break;
509
+ if (query.cancelled?.() === true) return {
510
+ entries: found,
511
+ complete: false,
512
+ scanned
513
+ };
514
+ if (await fileSize(segment) > SEGMENT_TAIL_BYTES) windowed = true;
515
+ const newest = [];
516
+ for await (const line of segmentLines(segment)) {
517
+ scanned += 1;
518
+ if (scanned % 5e3 === 0) {
519
+ if (query.cancelled?.() === true) return {
520
+ entries: [...newest.slice(-limit), ...found].slice(-limit),
521
+ complete: false,
522
+ scanned
523
+ };
524
+ await new Promise((resolve) => setImmediate(resolve));
525
+ }
526
+ if (scanned >= 2e5) break;
527
+ const entry = toEntry(line);
528
+ if (entry == null) continue;
529
+ if (wanted != null && !wanted.has(entry.id)) continue;
530
+ if (query.beforeS != null && entry.s > query.beforeS) continue;
531
+ if (query.afterS != null && entry.s <= query.afterS) continue;
532
+ if (needle != null && !entry.line.text.toLowerCase().includes(needle)) continue;
533
+ newest.push(entry);
534
+ if (newest.length > limit) newest.shift();
535
+ }
536
+ found.unshift(...newest);
537
+ if (found.length > limit) found.splice(0, found.length - limit);
538
+ }
539
+ return {
540
+ entries: found,
541
+ complete: scanned < 2e5 && !windowed,
542
+ scanned
543
+ };
544
+ }
545
+ /** 0 when the segment rotated away between listing it and reading it. */
546
+ async function fileSize(path) {
547
+ try {
548
+ return (await (0, node_fs_promises.stat)(path)).size;
549
+ } catch {
550
+ return 0;
551
+ }
552
+ }
553
+ /**
554
+ * Lines of one segment, reading at most its last {@link SEGMENT_TAIL_BYTES}. Starting mid-file
555
+ * can land inside a line; that first partial is dropped rather than parsed into a wrong entry.
556
+ */
557
+ async function* segmentLines(path) {
558
+ const size = await fileSize(path);
559
+ if (size === 0) return;
560
+ const start = Math.max(0, size - SEGMENT_TAIL_BYTES);
561
+ const stream = (0, node_fs.createReadStream)(path, {
562
+ start,
563
+ encoding: "utf8"
564
+ });
565
+ const reader = (0, node_readline.createInterface)({
566
+ input: stream,
567
+ crlfDelay: Number.POSITIVE_INFINITY
568
+ });
569
+ let first = true;
570
+ try {
571
+ for await (const line of reader) {
572
+ if (first) {
573
+ first = false;
574
+ if (start > 0) continue;
575
+ }
576
+ if (line !== "") yield line;
577
+ }
578
+ } finally {
579
+ reader.close();
580
+ stream.destroy();
581
+ }
582
+ }
583
+ function toEntry(text) {
584
+ let parsed;
585
+ try {
586
+ parsed = JSON.parse(text);
587
+ } catch {
588
+ return null;
589
+ }
590
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
591
+ const raw = parsed;
592
+ if (typeof raw.g !== "number" || typeof raw.s !== "number" || typeof raw.id !== "string" || typeof raw.text !== "string" || typeof raw.seq !== "number" || typeof raw.ts !== "number") return null;
593
+ const line = {
594
+ id: raw.seq,
595
+ seq: raw.seq,
596
+ ts: raw.ts,
597
+ at: 0,
598
+ stream: raw.stream === "err" ? "err" : "out",
599
+ op: "append",
600
+ text: raw.text,
601
+ truncated: false
602
+ };
603
+ return {
604
+ g: raw.g,
605
+ s: raw.s,
606
+ id: raw.id,
607
+ line
608
+ };
609
+ }
610
+ //#endregion
611
+ //#region src/daemon/logsEndpoint.ts
612
+ const FLUSH_MS = 30;
613
+ /** Per-subscription egress cap (pending queue + what the socket still owes). */
614
+ const CLIENT_CAP_BYTES = 256 * 1024;
615
+ /** Rough per-line wire estimate; the cap is a memory bound, not an accounting exercise. */
616
+ const LINE_OVERHEAD_BYTES = 96;
617
+ /**
618
+ * Concurrent subscriptions one socket may hold. Every subscription costs a supervisor listener,
619
+ * a pending queue, and a full ring backfill on arrival — so without a ceiling a single ticketed
620
+ * client could multiply the daemon's per-client memory by however many `sub` frames it cares to
621
+ * send. The byte cap above bounds each subscription; this bounds their number.
622
+ */
623
+ const MAX_SUBSCRIPTIONS = 64;
624
+ /**
625
+ * Merged-lane egress cap. Separate from the per-process one because this lane carries EVERY
626
+ * process: a viewer watching a 20-process environment can fall behind on volume no single
627
+ * process could produce.
628
+ */
629
+ const MERGED_CAP_BYTES = 512 * 1024;
630
+ /** Concurrent searches one socket may have in flight — each holds a file read. */
631
+ const MAX_SEARCHES = 4;
632
+ /**
633
+ * What a subscribe gets back. A resume cursor is an OPTIMISATION, never a promise: it is honored
634
+ * only where the ring can prove it still holds everything after it, so a reconnecting client can
635
+ * never be handed a log that looks continuous but isn't.
636
+ *
637
+ * - contiguous → an append batch (`reset` absent). Answering a cursor with `reset: true` would
638
+ * tell the client to discard everything before it, which is the opposite of resuming.
639
+ * - the ring rotated past the cursor → the exact `gap`, then a resnap.
640
+ * - the ring is entirely older than the cursor → the process was rebuilt (a config reload gives it
641
+ * a fresh ring and a fresh sequence), so the two histories are not comparable: resnap.
642
+ */
643
+ function backfillFrames(proc, ring, fromSeq) {
644
+ const resnap = {
645
+ k: "batch",
646
+ proc,
647
+ reset: true,
648
+ lines: [...ring]
649
+ };
650
+ if (fromSeq == null || ring.length === 0) return [resnap];
651
+ const oldest = ring[0]?.seq ?? 0;
652
+ if ((ring[ring.length - 1]?.seq ?? 0) < fromSeq) return [resnap];
653
+ if (oldest <= fromSeq + 1) return [{
654
+ k: "batch",
655
+ proc,
656
+ lines: ring.filter((line) => line.seq > fromSeq)
657
+ }];
658
+ return [{
659
+ k: "gap",
660
+ proc,
661
+ dropped: oldest - fromSeq - 1
662
+ }, resnap];
663
+ }
664
+ function sendFrame(ws, message) {
665
+ if (ws.readyState !== ws.OPEN) return;
666
+ ws.send(JSON.stringify(message));
667
+ }
668
+ function createLogsEndpoint(options) {
669
+ const { supervisor, segments, log } = options;
670
+ const sockets = /* @__PURE__ */ new Set();
671
+ const handleConnection = (ws) => {
672
+ sockets.add(ws);
673
+ const subs = /* @__PURE__ */ new Map();
674
+ let merged = null;
675
+ /** Ids of searches the client has abandoned (or that outlived the socket). */
676
+ const cancelledSearches = /* @__PURE__ */ new Set();
677
+ let searchesInFlight = 0;
678
+ let disposed = false;
679
+ const flush = setInterval(() => {
680
+ if (ws.readyState !== ws.OPEN) return;
681
+ const backedUp = ws.bufferedAmount > CLIENT_CAP_BYTES;
682
+ for (const [proc, sub] of subs) {
683
+ if (backedUp) {
684
+ sub.dropped += sub.pending.length;
685
+ sub.pending = [];
686
+ sub.pendingBytes = 0;
687
+ continue;
688
+ }
689
+ if (sub.dropped > 0) {
690
+ const dropped = sub.dropped + sub.pending.length;
691
+ sub.pending = [];
692
+ sub.pendingBytes = 0;
693
+ sub.dropped = 0;
694
+ sendFrame(ws, {
695
+ k: "gap",
696
+ proc,
697
+ dropped
698
+ });
699
+ sendFrame(ws, {
700
+ k: "batch",
701
+ proc,
702
+ reset: true,
703
+ lines: [...supervisor.ringFor(proc)]
704
+ });
705
+ continue;
706
+ }
707
+ if (sub.pending.length === 0) continue;
708
+ sendFrame(ws, {
709
+ k: "batch",
710
+ proc,
711
+ lines: sub.pending
712
+ });
713
+ sub.pending = [];
714
+ sub.pendingBytes = 0;
715
+ }
716
+ if (merged == null || !merged.live) return;
717
+ if (ws.bufferedAmount > MERGED_CAP_BYTES) {
718
+ merged.dropped += merged.pending.length;
719
+ merged.pending = [];
720
+ merged.pendingBytes = 0;
721
+ return;
722
+ }
723
+ if (merged.dropped > 0) {
724
+ const dropped = merged.dropped + merged.pending.length;
725
+ merged.pending = [];
726
+ merged.pendingBytes = 0;
727
+ merged.dropped = 0;
728
+ sendFrame(ws, {
729
+ k: "merged-gap",
730
+ dropped
731
+ });
732
+ return;
733
+ }
734
+ if (merged.pending.length === 0) return;
735
+ sendFrame(ws, {
736
+ k: "merged",
737
+ entries: merged.pending
738
+ });
739
+ merged.pending = [];
740
+ merged.pendingBytes = 0;
741
+ }, FLUSH_MS);
742
+ /**
743
+ * Merged backfill without a second copy of every line in memory: attach the live tap FIRST
744
+ * and buffer, then read the file for everything OLDER than the first buffered entry. The
745
+ * two halves meet exactly at `s`, so nothing is lost in the gap between them and nothing is
746
+ * delivered twice — which a read-then-attach would get wrong in both directions.
747
+ */
748
+ const subscribeMerged = async (procs, fromS) => {
749
+ merged?.off();
750
+ const sub = {
751
+ off: () => {},
752
+ pending: [],
753
+ pendingBytes: 0,
754
+ dropped: 0,
755
+ live: false
756
+ };
757
+ const wanted = procs == null ? null : new Set(procs);
758
+ sub.off = supervisor.onMergedLine((entry) => {
759
+ if (wanted != null && !wanted.has(entry.id)) return;
760
+ sub.pending.push(entry);
761
+ sub.pendingBytes += entry.line.text.length + LINE_OVERHEAD_BYTES;
762
+ if (sub.pendingBytes > MERGED_CAP_BYTES) {
763
+ sub.dropped += sub.pending.length;
764
+ sub.pending = [];
765
+ sub.pendingBytes = 0;
766
+ }
767
+ });
768
+ merged = sub;
769
+ const history = await readHistory(segments(), {
770
+ ...procs == null ? {} : { procs },
771
+ ...fromS == null ? {} : { afterS: fromS },
772
+ limit: MAX_HISTORY_ENTRIES,
773
+ cancelled: () => disposed || merged !== sub
774
+ });
775
+ if (disposed || merged !== sub) return;
776
+ const boundary = sub.pending[0]?.s;
777
+ const backfill = boundary == null ? history.entries : history.entries.filter((entry) => entry.s < boundary);
778
+ sendFrame(ws, fromS == null ? {
779
+ k: "merged",
780
+ reset: true,
781
+ entries: backfill
782
+ } : {
783
+ k: "merged",
784
+ entries: backfill
785
+ });
786
+ sub.live = true;
787
+ };
788
+ const runSearch = async (id, query, procs, limit = 200) => {
789
+ if (searchesInFlight >= MAX_SEARCHES) {
790
+ log(`logs: refusing search "${id}" — client is at ${MAX_SEARCHES} concurrent searches`);
791
+ sendFrame(ws, {
792
+ k: "search-result",
793
+ id,
794
+ entries: [],
795
+ complete: false,
796
+ scanned: 0
797
+ });
798
+ return;
799
+ }
800
+ searchesInFlight += 1;
801
+ try {
802
+ const result = await readHistory(segments(), {
803
+ ...procs == null ? {} : { procs },
804
+ query,
805
+ limit,
806
+ cancelled: () => disposed || cancelledSearches.has(id)
807
+ });
808
+ if (disposed || cancelledSearches.delete(id)) return;
809
+ sendFrame(ws, {
810
+ k: "search-result",
811
+ id,
812
+ entries: result.entries,
813
+ complete: result.complete,
814
+ scanned: result.scanned
815
+ });
816
+ } finally {
817
+ searchesInFlight -= 1;
818
+ }
819
+ };
820
+ ws.on("message", (data) => {
821
+ const message = require_cli.parseLogsClientMessage(data.toString());
822
+ if (message == null) return;
823
+ if (message.k === "unsub-merged") {
824
+ merged?.off();
825
+ merged = null;
826
+ return;
827
+ }
828
+ if (message.k === "sub-merged") {
829
+ subscribeMerged(message.procs, message.fromS);
830
+ return;
831
+ }
832
+ if (message.k === "search-cancel") {
833
+ cancelledSearches.add(message.id);
834
+ return;
835
+ }
836
+ if (message.k === "search") {
837
+ cancelledSearches.delete(message.id);
838
+ runSearch(message.id, message.query, message.procs, message.limit);
839
+ return;
840
+ }
841
+ if (message.k === "unsub") {
842
+ subs.get(message.proc)?.off();
843
+ subs.delete(message.proc);
844
+ return;
845
+ }
846
+ if (!subs.has(message.proc) && subs.size >= MAX_SUBSCRIPTIONS) {
847
+ log(`logs: refusing subscription to "${message.proc}" — client is at ${MAX_SUBSCRIPTIONS}`);
848
+ return;
849
+ }
850
+ subs.get(message.proc)?.off();
851
+ const sub = {
852
+ off: () => {},
853
+ pending: [],
854
+ pendingBytes: 0,
855
+ dropped: 0
856
+ };
857
+ sub.off = supervisor.onLine(message.proc, (line) => {
858
+ sub.pending.push(line);
859
+ sub.pendingBytes += line.text.length + LINE_OVERHEAD_BYTES;
860
+ if (sub.pendingBytes > CLIENT_CAP_BYTES) {
861
+ sub.dropped += sub.pending.length;
862
+ sub.pending = [];
863
+ sub.pendingBytes = 0;
864
+ }
865
+ });
866
+ subs.set(message.proc, sub);
867
+ for (const frame of backfillFrames(message.proc, supervisor.ringFor(message.proc), message.fromSeq)) sendFrame(ws, frame);
868
+ });
869
+ const cleanup = () => {
870
+ disposed = true;
871
+ clearInterval(flush);
872
+ for (const sub of subs.values()) sub.off();
873
+ subs.clear();
874
+ merged?.off();
875
+ merged = null;
876
+ cancelledSearches.clear();
877
+ sockets.delete(ws);
878
+ };
879
+ ws.on("close", cleanup);
880
+ ws.on("error", cleanup);
881
+ };
882
+ return {
883
+ handleConnection: (ws) => {
884
+ try {
885
+ handleConnection(ws);
886
+ } catch (error) {
887
+ log(`logs: connection dropped after setup error: ${error.message}`);
888
+ ws.terminate();
889
+ }
890
+ },
891
+ close: () => {
892
+ for (const ws of [...sockets]) ws.terminate();
893
+ sockets.clear();
894
+ }
895
+ };
896
+ }
897
+ //#endregion
898
+ //#region src/daemon/staticFiles.ts
899
+ /**
900
+ * Where the built client lives, which depends on how the daemon was loaded:
901
+ *
902
+ * - **published / built** — this module is bundled into `build/`, so `./client` is right there.
903
+ * - **from source** (the e2e shim, and `bun run` in this repo) — this file is `src/daemon/`, and
904
+ * the bundle is still at `<package>/build/client`.
905
+ *
906
+ * Resolved once, on first use rather than at import, so a daemon started before `build:client`
907
+ * ran still finds the assets once they exist.
908
+ */
909
+ let clientDir = null;
910
+ function resolveClientDir() {
911
+ if (clientDir != null) return clientDir;
912
+ const here = (0, node_url.fileURLToPath)(new URL(".", require("url").pathToFileURL(__filename).href));
913
+ for (const candidate of [(0, node_path.join)(here, "client"), (0, node_path.join)(here, "..", "..", "build", "client")]) if ((0, node_fs.existsSync)((0, node_path.join)(candidate, "index.html"))) {
914
+ clientDir = (0, node_path.normalize)(candidate);
915
+ return clientDir;
916
+ }
917
+ clientDir = (0, node_path.normalize)((0, node_path.join)(here, "client"));
918
+ return clientDir;
919
+ }
920
+ const MIME = {
921
+ ".html": "text/html; charset=utf-8",
922
+ ".js": "text/javascript; charset=utf-8",
923
+ ".css": "text/css; charset=utf-8",
924
+ ".json": "application/json; charset=utf-8",
925
+ ".map": "application/json; charset=utf-8",
926
+ ".svg": "image/svg+xml",
927
+ ".png": "image/png",
928
+ ".ico": "image/x-icon",
929
+ ".woff2": "font/woff2"
930
+ };
931
+ const CSP = [
932
+ "default-src 'none'",
933
+ "script-src 'self'",
934
+ "style-src 'self' 'unsafe-inline'",
935
+ "img-src 'self' data:",
936
+ "font-src 'self'",
937
+ "connect-src 'self' ws: wss:",
938
+ "frame-ancestors 'none'",
939
+ "base-uri 'none'",
940
+ "form-action 'none'"
941
+ ].join("; ");
942
+ function applySecurityHeaders(response) {
943
+ response.setHeader("x-content-type-options", "nosniff");
944
+ response.setHeader("referrer-policy", "no-referrer");
945
+ response.setHeader("x-frame-options", "DENY");
946
+ response.setHeader("content-security-policy", CSP);
947
+ }
948
+ /**
949
+ * Serve one file from the client bundle. `immutable` is for hashed `/assets/*` only — the
950
+ * entry document must never be cached, or a daemon upgrade keeps serving the old app shell.
951
+ */
952
+ async function serveClientFile(pathname, response, immutable) {
953
+ const root = resolveClientDir();
954
+ const file = (0, node_path.normalize)((0, node_path.join)(root, decodeURIComponent(pathname).replace(/^\/+/, "")));
955
+ if (file !== root && !file.startsWith(`${root}${node_path.sep}`)) return false;
956
+ try {
957
+ if (!(await (0, node_fs_promises.stat)(file)).isFile()) return false;
958
+ const body = await (0, node_fs_promises.readFile)(file);
959
+ response.statusCode = 200;
960
+ response.setHeader("content-type", MIME[(0, node_path.extname)(file)] ?? "application/octet-stream");
961
+ response.setHeader("cache-control", immutable ? "public, max-age=31536000, immutable" : "no-store");
962
+ applySecurityHeaders(response);
963
+ response.end(body);
964
+ return true;
965
+ } catch {
966
+ return false;
967
+ }
968
+ }
969
+ //#endregion
970
+ //#region src/daemon/supervisor.ts
971
+ const ACTIVE_STATES = new Set([
972
+ "starting",
973
+ "running",
974
+ "ready",
975
+ "unready",
976
+ "backoff",
977
+ "stopping"
978
+ ]);
979
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
980
+ const ENDPOINT_PROBE_MS = 250;
981
+ /** A just-stopped listener can linger for an instant; a restart must not trip over its own port. */
982
+ const ENDPOINT_RECHECK_MS = 150;
983
+ /** Is anything listening? A bare connect — deliberately NOT an attempt to attribute an owner. */
984
+ function tcpBound(host, port) {
985
+ return new Promise((resolve) => {
986
+ const socket = (0, node_net.connect)({
987
+ host,
988
+ port
989
+ });
990
+ const settle = (bound) => {
991
+ socket.destroy();
992
+ resolve(bound);
993
+ };
994
+ socket.setTimeout(ENDPOINT_PROBE_MS, () => settle(false));
995
+ socket.once("connect", () => settle(true));
996
+ socket.once("error", () => settle(false));
997
+ });
998
+ }
999
+ var CommanderSupervisor = class {
1000
+ _config;
1001
+ _holders = /* @__PURE__ */ new Map();
1002
+ _ledger;
1003
+ _sink;
1004
+ _depWaitMs;
1005
+ _logsDir;
1006
+ _listeners = /* @__PURE__ */ new Set();
1007
+ _lineListeners = /* @__PURE__ */ new Map();
1008
+ _mergedListeners = /* @__PURE__ */ new Set();
1009
+ _stopping = false;
1010
+ constructor(options) {
1011
+ this._config = options.config;
1012
+ this._ledger = options.ledger;
1013
+ this._sink = options.sink;
1014
+ this._depWaitMs = options.depWaitMs ?? 6e4;
1015
+ this._logsDir = options.logsDir;
1016
+ for (const definition of options.config.processes) this._holders.set(definition.id, this._newHolder(definition));
1017
+ }
1018
+ get config() {
1019
+ return this._config;
1020
+ }
1021
+ subscribe(listener) {
1022
+ this._listeners.add(listener);
1023
+ return () => this._listeners.delete(listener);
1024
+ }
1025
+ /**
1026
+ * Live line tap for the `/logs` lane. Keyed by id (not process instance) so a subscription
1027
+ * placed before the first spawn — or across a config-reload process rebuild — just works.
1028
+ */
1029
+ onLine(id, listener) {
1030
+ let set = this._lineListeners.get(id);
1031
+ if (set == null) {
1032
+ set = /* @__PURE__ */ new Set();
1033
+ this._lineListeners.set(id, set);
1034
+ }
1035
+ set.add(listener);
1036
+ return () => {
1037
+ set.delete(listener);
1038
+ if (set.size === 0) this._lineListeners.delete(id);
1039
+ };
1040
+ }
1041
+ /**
1042
+ * The merged tap: every process's lines on one stream, stamped with the daemon's `(g, s)`.
1043
+ * Distinct from `onLine` because the merged timeline's whole point is a single ordering across
1044
+ * processes — reassembling it from N per-process taps would put the ordering back in the
1045
+ * client, which is exactly where it cannot be decided.
1046
+ */
1047
+ onMergedLine(listener) {
1048
+ this._mergedListeners.add(listener);
1049
+ return () => this._mergedListeners.delete(listener);
1050
+ }
1051
+ /** The bounded ring snapshot for `/logs` backfill; empty while the process was never spawned. */
1052
+ ringFor(id) {
1053
+ return this._holders.get(id)?.proc?.ring() ?? [];
1054
+ }
1055
+ _notify(id) {
1056
+ for (const listener of this._listeners) listener(id);
1057
+ }
1058
+ _newHolder(definition) {
1059
+ return {
1060
+ definition,
1061
+ proc: null,
1062
+ startedAt: null,
1063
+ stale: false,
1064
+ removed: false,
1065
+ blockedBy: null,
1066
+ degradedBy: /* @__PURE__ */ new Set(),
1067
+ taskTimer: null,
1068
+ taskRun: null,
1069
+ chain: Promise.resolve(),
1070
+ lastTaskResult: null
1071
+ };
1072
+ }
1073
+ /** Serialize every control action per process id. */
1074
+ _enqueue(holder, action) {
1075
+ const run = holder.chain.then(action, action);
1076
+ holder.chain = run.catch(() => {});
1077
+ return run;
1078
+ }
1079
+ _ensureProc(holder) {
1080
+ if (holder.proc != null) return holder.proc;
1081
+ const definition = holder.definition;
1082
+ const proc = (0, _nice_code_process.createNiceProcess)({
1083
+ id: definition.id,
1084
+ run: definition.run,
1085
+ ...definition.shell != null ? { shell: definition.shell } : {},
1086
+ cwd: definition.cwd,
1087
+ env: definition.env,
1088
+ stdin: definition.stdin,
1089
+ kind: definition.kind,
1090
+ ...definition.ready != null ? { ready: definition.ready } : {},
1091
+ ...definition.restart != null ? { restart: definition.restart } : {},
1092
+ stop: definition.stop,
1093
+ log: {
1094
+ ...definition.log,
1095
+ file: { dir: this._logsDir }
1096
+ },
1097
+ ledger: this._ledger
1098
+ });
1099
+ proc.on("line", (line) => {
1100
+ const stamp = this._sink.record(definition.id, line);
1101
+ const tapped = this._lineListeners.get(definition.id);
1102
+ if (tapped != null) for (const listener of tapped) listener(line);
1103
+ if (this._mergedListeners.size > 0) {
1104
+ const entry = {
1105
+ ...stamp,
1106
+ id: definition.id,
1107
+ line
1108
+ };
1109
+ for (const listener of this._mergedListeners) listener(entry);
1110
+ }
1111
+ });
1112
+ proc.on("state", () => {
1113
+ this._recomputeDegraded();
1114
+ this._notify(definition.id);
1115
+ });
1116
+ holder.proc = proc;
1117
+ return proc;
1118
+ }
1119
+ /** A dependent is degraded while it is active and any dependency is not ready/succeeded. */
1120
+ _recomputeDegraded() {
1121
+ for (const holder of this._holders.values()) {
1122
+ holder.degradedBy.clear();
1123
+ if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) continue;
1124
+ for (const depId of holder.definition.dependsOn) {
1125
+ const dep = this._holders.get(depId);
1126
+ if (dep?.proc == null) {
1127
+ holder.degradedBy.add(depId);
1128
+ continue;
1129
+ }
1130
+ if (!(dep.definition.kind === "task" ? dep.proc.state === "succeeded" : dep.proc.state === "ready")) holder.degradedBy.add(depId);
1131
+ }
1132
+ }
1133
+ }
1134
+ /**
1135
+ * Edge 13 — a declared EXCLUSIVE endpoint that is already bound belongs to somebody else, and
1136
+ * spawning on top of it produces exactly the confusion the endpoint model exists to prevent:
1137
+ * the child either fails to bind with a message nobody reads, or (with a fallback binder)
1138
+ * quietly drifts to another port while readiness latches on the squatter (edge 48).
1139
+ *
1140
+ * ⚠ Reported, never cleared. Attributing a listening socket to a pid is not portable, so an
1141
+ * occupied port is surfaced and the start refused — killing an unidentified holder is the one
1142
+ * thing this must not do. Our own orphans are already gone by here (the boot scavenger reaps
1143
+ * them before anything starts) and a live foreign lease was refused earlier (C1).
1144
+ */
1145
+ async _exclusiveEndpointConflict(holder) {
1146
+ for (const endpoint of holder.definition.endpoints) {
1147
+ if (endpoint.ownership !== "exclusive") continue;
1148
+ if (!await tcpBound(endpoint.host, endpoint.port)) continue;
1149
+ await wait(ENDPOINT_RECHECK_MS);
1150
+ if (!await tcpBound(endpoint.host, endpoint.port)) continue;
1151
+ return `exclusive endpoint "${endpoint.name}" (${endpoint.host}:${endpoint.port}) is already in use — stop whatever holds it, or run \`nice-commander doctor\``;
1152
+ }
1153
+ return null;
1154
+ }
1155
+ /** Wait until `proc.state` satisfies `want`, a terminal state intervenes, or the bound lapses. */
1156
+ _waitForState(proc, want, timeoutMs) {
1157
+ if (want(proc.state)) return Promise.resolve(true);
1158
+ return new Promise((resolve) => {
1159
+ const off = proc.on("state", (next) => {
1160
+ if (want(next) || !ACTIVE_STATES.has(next)) {
1161
+ off();
1162
+ clearTimeout(timer);
1163
+ resolve(want(next));
1164
+ }
1165
+ });
1166
+ const timer = setTimeout(() => {
1167
+ off();
1168
+ resolve(want(proc.state));
1169
+ }, timeoutMs);
1170
+ timer.unref();
1171
+ });
1172
+ }
1173
+ /**
1174
+ * Start a DAG-ordered id set. Dependencies are awaited (services to ready, tasks to
1175
+ * succeeded — task deps run once per transaction); a bounded wait reports `blocked` with
1176
+ * the dependency reason instead of hanging the action.
1177
+ */
1178
+ async start(orderedIds, options = {}) {
1179
+ const waitForReady = options.wait !== false;
1180
+ const staggerMs = options.staggerMs ?? 0;
1181
+ const results = [];
1182
+ const taskRuns = /* @__PURE__ */ new Map();
1183
+ let spawned = 0;
1184
+ let leased;
1185
+ try {
1186
+ leased = new Map((await this._ledger.liveLeases()).map((record) => [record.id, record.owner?.kind ?? "another"]));
1187
+ } catch {
1188
+ leased = /* @__PURE__ */ new Map();
1189
+ }
1190
+ for (const id of orderedIds) {
1191
+ const holder = this._holders.get(id);
1192
+ if (holder == null) {
1193
+ results.push({
1194
+ id,
1195
+ outcome: "failed",
1196
+ reason: "unknown id"
1197
+ });
1198
+ continue;
1199
+ }
1200
+ if (holder.removed) {
1201
+ results.push({
1202
+ id,
1203
+ outcome: "failed",
1204
+ reason: "removed from config"
1205
+ });
1206
+ continue;
1207
+ }
1208
+ const leaseKind = leased.get(id);
1209
+ if (leaseKind != null) {
1210
+ results.push({
1211
+ id,
1212
+ outcome: "failed",
1213
+ reason: `held by a live \`${leaseKind}\` process — stop it there first`
1214
+ });
1215
+ continue;
1216
+ }
1217
+ let blocked = null;
1218
+ for (const depId of holder.definition.dependsOn) {
1219
+ const dep = this._holders.get(depId);
1220
+ if (dep == null || dep.removed) {
1221
+ blocked = `dependency "${depId}" is unavailable`;
1222
+ break;
1223
+ }
1224
+ if (dep.definition.kind === "task") {
1225
+ const taskResult = await (taskRuns.get(depId) ?? this._runTaskOnce(dep, taskRuns));
1226
+ if (!orderedIds.includes(depId)) results.push({
1227
+ ...taskResult,
1228
+ id: depId
1229
+ });
1230
+ if (taskResult.outcome !== "succeeded") {
1231
+ blocked = `task dependency "${depId}" did not succeed (${taskResult.outcome})`;
1232
+ break;
1233
+ }
1234
+ } else if (dep.proc != null && ACTIVE_STATES.has(dep.proc.state)) {
1235
+ if (!await this._waitForState(dep.proc, (state) => state === "ready", this._depWaitMs)) {
1236
+ blocked = `dependency "${depId}" did not become ready (${dep.proc.state})`;
1237
+ break;
1238
+ }
1239
+ } else if (dep.proc == null || dep.proc.state !== "ready") {
1240
+ blocked = `dependency "${depId}" is not running`;
1241
+ break;
1242
+ }
1243
+ }
1244
+ if (blocked != null) {
1245
+ holder.blockedBy = blocked;
1246
+ this._notify(id);
1247
+ results.push({
1248
+ id,
1249
+ outcome: "blocked",
1250
+ reason: blocked
1251
+ });
1252
+ continue;
1253
+ }
1254
+ holder.blockedBy = null;
1255
+ const result = holder.definition.kind === "task" ? await this._runTaskOnce(holder, taskRuns) : await this._enqueue(holder, async () => {
1256
+ const proc = this._ensureProc(holder);
1257
+ if (ACTIVE_STATES.has(proc.state)) return {
1258
+ id,
1259
+ outcome: "already-running"
1260
+ };
1261
+ if (this._stopping) return {
1262
+ id,
1263
+ outcome: "failed",
1264
+ reason: "supervisor is stopping"
1265
+ };
1266
+ const conflict = await this._exclusiveEndpointConflict(holder);
1267
+ if (conflict != null) return {
1268
+ id,
1269
+ outcome: "failed",
1270
+ reason: conflict
1271
+ };
1272
+ if (spawned > 0 && staggerMs > 0) await wait(staggerMs);
1273
+ spawned += 1;
1274
+ try {
1275
+ await proc.start();
1276
+ holder.startedAt = Date.now();
1277
+ holder.stale = false;
1278
+ this._recomputeDegraded();
1279
+ this._notify(id);
1280
+ } catch (error) {
1281
+ return {
1282
+ id,
1283
+ outcome: "failed",
1284
+ reason: error.message
1285
+ };
1286
+ }
1287
+ if (!waitForReady) return {
1288
+ id,
1289
+ outcome: "spawned"
1290
+ };
1291
+ if (await this._waitForState(proc, (state) => state === "ready", this._depWaitMs)) return {
1292
+ id,
1293
+ outcome: "ready"
1294
+ };
1295
+ return {
1296
+ id,
1297
+ outcome: "failed",
1298
+ reason: `did not become ready (state: ${proc.state})`
1299
+ };
1300
+ });
1301
+ results.push(result);
1302
+ }
1303
+ return {
1304
+ results,
1305
+ warnings: []
1306
+ };
1307
+ }
1308
+ /**
1309
+ * A task within ONE start transaction: task dependencies run once per transaction, so a
1310
+ * repeat request inside the same action joins that run rather than starting a second one.
1311
+ */
1312
+ _runTaskOnce(holder, taskRuns) {
1313
+ const existing = taskRuns.get(holder.definition.id);
1314
+ if (existing != null) return existing;
1315
+ const run = this._taskRun(holder);
1316
+ taskRuns.set(holder.definition.id, run);
1317
+ return run;
1318
+ }
1319
+ /**
1320
+ * The active run of a task, coalesced ACROSS actions on the holder (M5) — two concurrent
1321
+ * `up`s sharing a task dependency join one run instead of executing it twice back to back.
1322
+ *
1323
+ * ⚠ Only the START TRANSITION takes the holder's chain; the wait for exit deliberately sits
1324
+ * OUTSIDE it. Holding the chain for a task's full duration made `stop`/`shutdown` queue behind
1325
+ * the task's own exit — an unbounded deadlock for a task with no `timeoutMs`, and the reason a
1326
+ * wedged check could hang daemon shutdown forever (C3, edges 14/36/39).
1327
+ */
1328
+ _taskRun(holder) {
1329
+ if (holder.taskRun != null) return holder.taskRun;
1330
+ const id = holder.definition.id;
1331
+ const run = (async () => {
1332
+ const failure = await this._enqueue(holder, async () => {
1333
+ const proc = this._ensureProc(holder);
1334
+ if (ACTIVE_STATES.has(proc.state)) return null;
1335
+ if (this._stopping) return {
1336
+ id,
1337
+ outcome: "failed",
1338
+ reason: "supervisor is stopping"
1339
+ };
1340
+ const conflict = await this._exclusiveEndpointConflict(holder);
1341
+ if (conflict != null) return {
1342
+ id,
1343
+ outcome: "failed",
1344
+ reason: conflict
1345
+ };
1346
+ try {
1347
+ await proc.start();
1348
+ holder.startedAt = Date.now();
1349
+ holder.stale = false;
1350
+ this._notify(id);
1351
+ } catch (error) {
1352
+ return {
1353
+ id,
1354
+ outcome: "failed",
1355
+ reason: error.message
1356
+ };
1357
+ }
1358
+ return null;
1359
+ });
1360
+ if (failure != null) return failure;
1361
+ return this._awaitTaskExit(holder);
1362
+ })().finally(() => {
1363
+ if (holder.taskRun === run) holder.taskRun = null;
1364
+ });
1365
+ holder.taskRun = run;
1366
+ return run;
1367
+ }
1368
+ /** Await a started task's exit (outside the chain, so a stop can always get through). */
1369
+ async _awaitTaskExit(holder) {
1370
+ const id = holder.definition.id;
1371
+ const proc = holder.proc;
1372
+ if (proc == null) return {
1373
+ id,
1374
+ outcome: "failed",
1375
+ reason: "no active run"
1376
+ };
1377
+ const timeoutMs = holder.definition.timeoutMs;
1378
+ let timedOut = false;
1379
+ const exit = await new Promise((resolve) => {
1380
+ const off = proc.on("exit", (info) => {
1381
+ off();
1382
+ if (holder.taskTimer != null) {
1383
+ clearTimeout(holder.taskTimer);
1384
+ holder.taskTimer = null;
1385
+ }
1386
+ resolve(info);
1387
+ });
1388
+ if (!ACTIVE_STATES.has(proc.state) && proc.lastExit != null) {
1389
+ off();
1390
+ resolve(proc.lastExit);
1391
+ return;
1392
+ }
1393
+ if (timeoutMs != null) {
1394
+ holder.taskTimer = setTimeout(() => {
1395
+ timedOut = true;
1396
+ holder.taskTimer = null;
1397
+ proc.stop().catch(() => {});
1398
+ }, timeoutMs);
1399
+ holder.taskTimer.unref();
1400
+ }
1401
+ });
1402
+ holder.lastTaskResult = {
1403
+ definitionHash: holder.definition.definitionHash,
1404
+ exit
1405
+ };
1406
+ if (timedOut) return {
1407
+ id,
1408
+ outcome: "failed",
1409
+ reason: `timeout after ${timeoutMs} ms`
1410
+ };
1411
+ if (exit.expected) return {
1412
+ id,
1413
+ outcome: "stopped"
1414
+ };
1415
+ return exit.code === 0 ? {
1416
+ id,
1417
+ outcome: "succeeded"
1418
+ } : {
1419
+ id,
1420
+ outcome: "failed",
1421
+ reason: `exit ${exit.code ?? exit.signal ?? "unknown"}`
1422
+ };
1423
+ }
1424
+ /** Stop a set (reverse-DAG order — dependents first), warning about live reverse dependents. */
1425
+ async stop(ids) {
1426
+ const stopping = new Set(ids);
1427
+ const knownDefinitions = [...this._holders.values()].map((holder) => holder.definition);
1428
+ const warnings = [];
1429
+ for (const id of ids) {
1430
+ const live = [...this._holders.values()].filter((holder) => {
1431
+ if (stopping.has(holder.definition.id)) return false;
1432
+ if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) return false;
1433
+ return require_cli.withDependencies(knownDefinitions, [holder.definition.id]).has(id);
1434
+ });
1435
+ if (live.length > 0) warnings.push(`stopping "${id}" leaves live reverse dependents: ${live.map((h) => h.definition.id).join(", ")}`);
1436
+ }
1437
+ const order = orderForStop(knownDefinitions, ids);
1438
+ const results = [];
1439
+ for (const id of order) {
1440
+ const holder = this._holders.get(id);
1441
+ if (holder == null) {
1442
+ results.push({
1443
+ id,
1444
+ outcome: "failed",
1445
+ reason: "unknown id"
1446
+ });
1447
+ continue;
1448
+ }
1449
+ results.push(await this._enqueue(holder, async () => {
1450
+ if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) {
1451
+ holder.blockedBy = null;
1452
+ return {
1453
+ id,
1454
+ outcome: "already-stopped"
1455
+ };
1456
+ }
1457
+ if (holder.taskTimer != null) {
1458
+ clearTimeout(holder.taskTimer);
1459
+ holder.taskTimer = null;
1460
+ }
1461
+ try {
1462
+ await holder.proc.stop();
1463
+ } catch (error) {
1464
+ return {
1465
+ id,
1466
+ outcome: "failed",
1467
+ reason: error.message
1468
+ };
1469
+ }
1470
+ this._recomputeDegraded();
1471
+ this._notify(id);
1472
+ return {
1473
+ id,
1474
+ outcome: "stopped"
1475
+ };
1476
+ }));
1477
+ }
1478
+ return {
1479
+ results,
1480
+ warnings
1481
+ };
1482
+ }
1483
+ async restart(orderedIds, options = {}) {
1484
+ const stopped = await this.stop(orderedIds);
1485
+ const started = await this.start(orderedIds, options);
1486
+ return {
1487
+ results: started.results.map((result) => {
1488
+ const stopResult = stopped.results.find((candidate) => candidate.id === result.id);
1489
+ if (stopResult?.outcome !== "failed") return result;
1490
+ return result.outcome === "failed" ? {
1491
+ ...result,
1492
+ reason: `${stopResult.reason}; ${result.reason}`
1493
+ } : {
1494
+ ...result,
1495
+ reason: `restarted, but the stop reported: ${stopResult.reason}`
1496
+ };
1497
+ }),
1498
+ warnings: [...stopped.warnings, ...started.warnings]
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Config reload (last-good already validated): changed definitions of RUNNING processes mark
1503
+ * `stale` (never auto-restart); deleted definitions stay addressable as `removed`; idle
1504
+ * processes just pick up the new definition on their next start.
1505
+ */
1506
+ applyConfig(next) {
1507
+ this._config = next;
1508
+ const seen = /* @__PURE__ */ new Set();
1509
+ for (const definition of next.processes) {
1510
+ seen.add(definition.id);
1511
+ const holder = this._holders.get(definition.id);
1512
+ if (holder == null) {
1513
+ this._holders.set(definition.id, this._newHolder(definition));
1514
+ continue;
1515
+ }
1516
+ holder.removed = false;
1517
+ const active = holder.proc != null && ACTIVE_STATES.has(holder.proc.state);
1518
+ if (active && holder.definition.definitionHash !== definition.definitionHash) holder.stale = true;
1519
+ if (!active) {
1520
+ holder.proc = null;
1521
+ holder.stale = false;
1522
+ }
1523
+ holder.definition = definition;
1524
+ this._notify(definition.id);
1525
+ }
1526
+ for (const holder of this._holders.values()) if (!seen.has(holder.definition.id)) {
1527
+ holder.removed = true;
1528
+ this._notify(holder.definition.id);
1529
+ }
1530
+ }
1531
+ status() {
1532
+ return [...this._holders.values()].map((holder) => {
1533
+ const proc = holder.proc;
1534
+ const state = proc != null ? proc.state : holder.blockedBy != null ? "blocked" : "not-started";
1535
+ return {
1536
+ id: holder.definition.id,
1537
+ kind: holder.definition.kind,
1538
+ state,
1539
+ pid: proc?.pid ?? null,
1540
+ startedAt: holder.startedAt,
1541
+ restarts: proc?.restarts ?? 0,
1542
+ lastExit: proc?.lastExit ?? null,
1543
+ stale: holder.stale,
1544
+ removed: holder.removed,
1545
+ blockedBy: holder.blockedBy,
1546
+ degradedBy: [...holder.degradedBy],
1547
+ unreadyReason: proc?.unreadyReason ?? null,
1548
+ capability: proc?.capability ?? null,
1549
+ tags: holder.definition.tags,
1550
+ detail: describe(holder.definition)
1551
+ };
1552
+ });
1553
+ }
1554
+ /** The shutdown ladder (edge 39): stop everything concurrently, bounded per ladder. */
1555
+ async shutdown() {
1556
+ this._stopping = true;
1557
+ const errors = [];
1558
+ const stops = [...this._holders.values()].map((holder) => this._enqueue(holder, async () => {
1559
+ if (holder.taskTimer != null) {
1560
+ clearTimeout(holder.taskTimer);
1561
+ holder.taskTimer = null;
1562
+ }
1563
+ if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) return;
1564
+ try {
1565
+ await holder.proc.stop();
1566
+ } catch (error) {
1567
+ errors.push(`${holder.definition.id}: ${error.message}`);
1568
+ }
1569
+ }));
1570
+ await Promise.all(stops);
1571
+ this._sink.close();
1572
+ return { errors };
1573
+ }
1574
+ /**
1575
+ * Second-signal escalation (C3): skip the graceful rungs and end every owned tree NOW. An
1576
+ * impatient operator's second Ctrl+C must still mean "kill the children", never "abandon
1577
+ * them" — so this force-kills the trees and then lets each ladder verify and settle.
1578
+ */
1579
+ async forceStopAll() {
1580
+ this._stopping = true;
1581
+ await Promise.allSettled([...this._holders.values()].map(async (holder) => {
1582
+ const proc = holder.proc;
1583
+ if (proc?.pid == null) return;
1584
+ const pid = proc.pid;
1585
+ if (process.platform === "win32") await (0, _nice_code_process.taskkillTree)(pid).catch(() => {});
1586
+ else try {
1587
+ (0, _nice_code_process.signalProcessGroup)(pid, "SIGKILL");
1588
+ } catch {}
1589
+ await proc.stop().catch(() => {});
1590
+ }));
1591
+ }
1592
+ };
1593
+ /** Reverse-DAG order over the given ids (dependents stop first); definition order breaks ties. */
1594
+ /**
1595
+ * The parts of a resolved definition a viewer needs to answer "what is this, exactly?" without
1596
+ * opening the config — and nothing more. ⚠ `env` is deliberately absent: it routinely holds
1597
+ * tokens, and every attached viewer would see it.
1598
+ */
1599
+ function describe(definition) {
1600
+ const run = definition.run;
1601
+ return {
1602
+ command: typeof run === "string" ? run : run.join(" "),
1603
+ cwd: definition.cwd,
1604
+ dependsOn: [...definition.dependsOn],
1605
+ ...definition.ready == null ? {} : { ready: describeReady(definition.ready) },
1606
+ endpoints: definition.endpoints.map((endpoint) => ({
1607
+ name: endpoint.name,
1608
+ protocol: endpoint.protocol,
1609
+ host: endpoint.host,
1610
+ port: endpoint.port,
1611
+ ownership: endpoint.ownership,
1612
+ ...endpointUrl(endpoint) == null ? {} : { url: endpointUrl(endpoint) }
1613
+ }))
1614
+ };
1615
+ }
1616
+ function describeReady(ready) {
1617
+ switch (ready.kind) {
1618
+ case "logMatch": return `log matches ${String(ready.match)}`;
1619
+ case "port": return `port ${ready.port} accepts`;
1620
+ case "httpOk": return `GET ${ready.host ?? "127.0.0.1"}:${ready.port}${ready.path ?? "/"} is ok`;
1621
+ case "delay": return `${ready.ms} ms after spawn`;
1622
+ case "exit0": return "process exits successfully";
1623
+ }
1624
+ }
1625
+ /** Only http endpoints get a followable link; a tcp port is not something a browser can open. */
1626
+ function endpointUrl(endpoint) {
1627
+ if (endpoint.url != null) return endpoint.url;
1628
+ if (endpoint.protocol !== "http") return void 0;
1629
+ return `http://${endpoint.host}:${endpoint.port}`;
1630
+ }
1631
+ function orderForStop(definitions, ids) {
1632
+ const set = new Set(ids);
1633
+ const seen = /* @__PURE__ */ new Set();
1634
+ const ordered = [];
1635
+ const visit = (id) => {
1636
+ if (!set.has(id) || seen.has(id)) return;
1637
+ seen.add(id);
1638
+ for (const proc of definitions) if (set.has(proc.id) && proc.dependsOn.includes(id)) visit(proc.id);
1639
+ ordered.push(id);
1640
+ };
1641
+ for (const proc of definitions) visit(proc.id);
1642
+ for (const id of ids) visit(id);
1643
+ return ordered;
1644
+ }
1645
+ //#endregion
1646
+ //#region src/daemon/main.ts
1647
+ const PORT_SCAN_LIMIT = 100;
1648
+ const SCAVENGER_DIR_LIMIT = 32;
1649
+ /** Control inputs are small id lists — a bigger body is never legitimate. */
1650
+ const MAX_BODY_BYTES = 32 * 1024;
1651
+ function argValue(argv, flag) {
1652
+ const at = argv.indexOf(flag);
1653
+ return at >= 0 && at + 1 < argv.length ? argv[at + 1] : null;
1654
+ }
1655
+ async function packageVersion() {
1656
+ for (const candidate of [new URL("../../package.json", require("url").pathToFileURL(__filename).href), new URL("../../../package.json", require("url").pathToFileURL(__filename).href)]) try {
1657
+ const parsed = JSON.parse(await (0, node_fs_promises.readFile)(candidate, "utf8"));
1658
+ if (typeof parsed.version === "string") return parsed.version;
1659
+ } catch {}
1660
+ return "0.0.0";
1661
+ }
1662
+ /** Bounded global scavenger: dead-daemon ledgers in ANY config subdir get their orphans reaped. */
1663
+ async function scavengeDeadDaemons(dataDir, log) {
1664
+ let subdirs;
1665
+ try {
1666
+ subdirs = (0, node_fs.readdirSync)(dataDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).slice(0, SCAVENGER_DIR_LIMIT);
1667
+ } catch {
1668
+ return;
1669
+ }
1670
+ for (const configKey of subdirs) try {
1671
+ const paths = require_cli.commanderStatePaths(dataDir, configKey);
1672
+ const record = await require_cli.readInstanceRecord(paths.instanceRecordPath);
1673
+ if (record != null && await require_cli.recordDaemonAlive(record)) continue;
1674
+ const result = await (0, _nice_code_process.openProcessLedger)({
1675
+ dir: paths.stateDir,
1676
+ namespace: configKey
1677
+ }).reapOrphans();
1678
+ if (result.reaped.length > 0 || result.quarantined.length > 0) log(`scavenger[${configKey}]: reaped ${result.reaped.length} orphan record(s), quarantined ${result.quarantined.length}`);
1679
+ } catch (error) {
1680
+ log(`scavenger[${configKey}] failed: ${error.message}`);
1681
+ }
1682
+ }
1683
+ async function startCommanderDaemon(argv) {
1684
+ const configArg = argValue(argv, "--config");
1685
+ if (configArg == null) throw new Error("daemon requires --config <path>");
1686
+ const dataDir = argValue(argv, "--data-dir") ?? require_cli.resolveCommanderDataDir();
1687
+ const file = await require_cli.loadCommanderConfigFile(configArg);
1688
+ const { resolved, errors } = require_cli.validateCommanderConfig(file.raw, {
1689
+ configPath: file.configPath,
1690
+ configDir: file.configDir
1691
+ });
1692
+ if (resolved == null) throw new Error(`config validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
1693
+ const paths = require_cli.commanderStatePaths(dataDir, resolved.configKey);
1694
+ await require_cli.ensureStateDir(paths);
1695
+ const daemonLog = new RotatingLog(paths.daemonLogDir, "daemon");
1696
+ const log = (line) => daemonLog.write(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}`);
1697
+ log(`boot pid=${process.pid} runtime=${process.version} config=${file.configPath}`);
1698
+ await scavengeDeadDaemons(dataDir, log);
1699
+ const generation = ((await require_cli.readInstanceRecord(paths.instanceRecordPath))?.generation ?? 0) + 1;
1700
+ const ledger = (0, _nice_code_process.openProcessLedger)({
1701
+ dir: paths.stateDir,
1702
+ namespace: paths.ledgerNamespace,
1703
+ ownerKind: "daemon"
1704
+ });
1705
+ const sink = new AggregateSink(paths.logsDir, paths.ingestSeqPath, generation);
1706
+ const supervisor = new CommanderSupervisor({
1707
+ config: resolved,
1708
+ ledger,
1709
+ sink,
1710
+ logsDir: paths.logsDir
1711
+ });
1712
+ const token = (0, node_crypto.randomUUID)();
1713
+ const auth = new CommanderAuth(token);
1714
+ const startedAt = Date.now();
1715
+ let watcher = null;
1716
+ let shutdown = async () => {};
1717
+ const plane = createControlPlane({
1718
+ supervisor,
1719
+ generation,
1720
+ reloadConfig: () => watcher?.reloadNow() ?? Promise.resolve(),
1721
+ requestShutdown: () => void shutdown(),
1722
+ log
1723
+ });
1724
+ const logsPlane = createLogsEndpoint({
1725
+ supervisor,
1726
+ segments: () => sink.segments(),
1727
+ log
1728
+ });
1729
+ const json = (response, status, body) => {
1730
+ response.writeHead(status, {
1731
+ "content-type": "application/json; charset=utf-8",
1732
+ "cache-control": "no-store",
1733
+ "x-content-type-options": "nosniff"
1734
+ });
1735
+ response.end(JSON.stringify(body));
1736
+ };
1737
+ const readBodyBounded = async (request) => {
1738
+ const chunks = [];
1739
+ let length = 0;
1740
+ for await (const chunk of request) {
1741
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1742
+ length += buffer.length;
1743
+ if (length > MAX_BODY_BYTES) throw new Error("request body too large");
1744
+ chunks.push(buffer);
1745
+ }
1746
+ return Buffer.concat(chunks);
1747
+ };
1748
+ const route = async (request, response) => {
1749
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
1750
+ if (url.pathname === "/health") {
1751
+ if (!auth.isRoot(request.headers.authorization)) {
1752
+ json(response, 401, { error: "unauthorized" });
1753
+ return;
1754
+ }
1755
+ json(response, 200, {
1756
+ ok: true,
1757
+ configKey: resolved.configKey,
1758
+ generation,
1759
+ uptimeMs: Date.now() - startedAt
1760
+ });
1761
+ return;
1762
+ }
1763
+ if (!hostIsLoopbackForm(request.headers.host) || !crossSiteRequestAllowed(request)) {
1764
+ json(response, 403, { error: "forbidden" });
1765
+ return;
1766
+ }
1767
+ if (url.pathname === "/bootstrap" && request.method === "GET") {
1768
+ json(response, 200, { capability: auth.mintCapability() });
1769
+ return;
1770
+ }
1771
+ if (url.pathname === "/ticket" && request.method === "POST") {
1772
+ if (!auth.canMintTicket(request.headers.authorization)) {
1773
+ json(response, 401, { error: "unauthorized" });
1774
+ return;
1775
+ }
1776
+ json(response, 200, { ticket: auth.mintTicket() });
1777
+ return;
1778
+ }
1779
+ if (request.method === "GET") {
1780
+ const asset = url.pathname.startsWith("/assets/");
1781
+ if (asset || url.pathname === "/") {
1782
+ if (await serveClientFile(asset ? url.pathname : "index.html", response, asset)) return;
1783
+ json(response, 404, { error: asset ? "not found" : "web UI not built — run `bun run build` in @nice-code/commander" });
1784
+ return;
1785
+ }
1786
+ json(response, 404, { error: "not found" });
1787
+ return;
1788
+ }
1789
+ if (request.method === "POST" || request.method === "OPTIONS") {
1790
+ if (request.method === "POST" && !auth.isRoot(request.headers.authorization) && !auth.hasCapability(request.headers.authorization)) {
1791
+ json(response, 401, { error: "unauthorized" });
1792
+ return;
1793
+ }
1794
+ const headers = new Headers();
1795
+ for (let i = 0; i < request.rawHeaders.length; i += 2) headers.append(request.rawHeaders[i] ?? "", request.rawHeaders[i + 1] ?? "");
1796
+ const body = request.method === "POST" ? await readBodyBounded(request) : void 0;
1797
+ const wireResponse = await plane.fetch(new Request(url, {
1798
+ method: request.method,
1799
+ headers,
1800
+ body: body == null ? void 0 : new Uint8Array(body)
1801
+ }));
1802
+ response.writeHead(wireResponse.status, Object.fromEntries(wireResponse.headers.entries()));
1803
+ response.end(Buffer.from(await wireResponse.arrayBuffer()));
1804
+ return;
1805
+ }
1806
+ json(response, 404, { error: "not found" });
1807
+ };
1808
+ const server = (0, node_http.createServer)((request, response) => {
1809
+ route(request, response).catch((error) => {
1810
+ log(`http ${request.method} ${request.url}: ${error.message}`);
1811
+ const tooLarge = error.message.includes("too large");
1812
+ if (!response.headersSent) json(response, tooLarge ? 413 : 500, { error: "internal" });
1813
+ else response.end();
1814
+ });
1815
+ });
1816
+ const wss = new ws.WebSocketServer({
1817
+ noServer: true,
1818
+ handleProtocols: (protocols) => {
1819
+ for (const protocol of protocols) if (protocol.startsWith("commander-auth.")) return protocol;
1820
+ return false;
1821
+ }
1822
+ });
1823
+ server.on("upgrade", (request, socket, head) => {
1824
+ const reject = (status) => {
1825
+ socket.write(`HTTP/1.1 ${status}\r\n\r\n`);
1826
+ socket.destroy();
1827
+ };
1828
+ const lane = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
1829
+ if (lane !== "/wire" && lane !== "/logs" || !hostIsLoopbackForm(request.headers.host) || !crossSiteRequestAllowed(request)) {
1830
+ reject("403 Forbidden");
1831
+ return;
1832
+ }
1833
+ const ticket = String(request.headers["sec-websocket-protocol"] ?? "").split(",").map((value) => value.trim()).find((value) => value.startsWith(require_cli.COMMANDER_TICKET_PROTOCOL_PREFIX))?.slice(require_cli.COMMANDER_TICKET_PROTOCOL_PREFIX.length);
1834
+ if (ticket == null || !auth.consumeTicket(ticket)) {
1835
+ reject("401 Unauthorized");
1836
+ return;
1837
+ }
1838
+ wss.handleUpgrade(request, socket, head, (ws$1) => {
1839
+ if (lane === "/wire") plane.handleConnection(ws$1);
1840
+ else logsPlane.handleConnection(ws$1);
1841
+ });
1842
+ });
1843
+ const port = await new Promise((resolvePort, rejectPort) => {
1844
+ let candidate = resolved.daemon.port;
1845
+ const tryBind = () => {
1846
+ server.once("error", (error) => {
1847
+ if (error.code === "EADDRINUSE" && candidate < resolved.daemon.port + PORT_SCAN_LIMIT) {
1848
+ candidate += 1;
1849
+ tryBind();
1850
+ } else rejectPort(error);
1851
+ });
1852
+ server.listen(candidate, "127.0.0.1", () => resolvePort(candidate));
1853
+ };
1854
+ tryBind();
1855
+ });
1856
+ log(`listening on 127.0.0.1:${port} generation=${generation}`);
1857
+ const incumbent = await require_cli.readInstanceRecord(paths.instanceRecordPath);
1858
+ if (incumbent != null && await require_cli.recordDaemonAlive(incumbent)) throw new Error(`another nice-commander daemon (pid ${incumbent.pid}, port ${incumbent.port}) already serves this config — stop it first (\`nice-commander shutdown\`).`);
1859
+ await require_cli.writeInstanceRecord(paths.instanceRecordPath, {
1860
+ service: "nice-commander",
1861
+ instanceId: (0, node_crypto.randomUUID)(),
1862
+ generation,
1863
+ pid: process.pid,
1864
+ startStamp: await (0, _nice_code_process.readProcessStartStamp)(process.pid),
1865
+ port,
1866
+ token,
1867
+ configKey: resolved.configKey,
1868
+ configRevisionHash: resolved.configRevisionHash,
1869
+ configPath: resolved.configPath,
1870
+ protocolVersion: 1,
1871
+ packageVersion: await packageVersion()
1872
+ });
1873
+ watcher = watchCommanderConfig({
1874
+ configPath: resolved.configPath,
1875
+ watchFiles: resolved.watchFiles,
1876
+ onConfig: (next) => {
1877
+ supervisor.applyConfig(next);
1878
+ plane.syncConfig(next);
1879
+ log(`config reloaded revision=${next.configRevisionHash}`);
1880
+ require_cli.readInstanceRecord(paths.instanceRecordPath).then((current) => {
1881
+ if (current == null) return;
1882
+ return require_cli.writeInstanceRecord(paths.instanceRecordPath, {
1883
+ ...current,
1884
+ configRevisionHash: next.configRevisionHash
1885
+ });
1886
+ }).catch(() => {});
1887
+ },
1888
+ onError: (reloadErrors) => {
1889
+ plane.syncConfigError(reloadErrors);
1890
+ log(`config reload failed (last-good kept): ${reloadErrors.join("; ")}`);
1891
+ }
1892
+ });
1893
+ let shutdownInFlight = null;
1894
+ shutdown = () => {
1895
+ shutdownInFlight ??= (async () => {
1896
+ log("shutdown requested");
1897
+ watcher?.close();
1898
+ watcher = null;
1899
+ const { errors: stopErrors } = await supervisor.shutdown();
1900
+ for (const line of stopErrors) log(`stop error: ${line}`);
1901
+ await require_cli.removeInstanceRecord(paths.instanceRecordPath);
1902
+ plane.close();
1903
+ logsPlane.close();
1904
+ wss.close();
1905
+ await new Promise((resolveClose) => server.close(() => resolveClose()));
1906
+ sink.close();
1907
+ daemonLog.close();
1908
+ })();
1909
+ return shutdownInFlight;
1910
+ };
1911
+ let signalCount = 0;
1912
+ const onSignal = (signal) => {
1913
+ signalCount += 1;
1914
+ if (signalCount === 1) {
1915
+ log(`${signal}: walking the shutdown ladder`);
1916
+ shutdown().then(() => process.exit(0), (error) => {
1917
+ log(`shutdown failed: ${error.message}`);
1918
+ process.exit(1);
1919
+ });
1920
+ return;
1921
+ }
1922
+ if (signalCount === 2) {
1923
+ log(`${signal} again: escalating to force`);
1924
+ supervisor.forceStopAll().finally(() => {
1925
+ require_cli.removeInstanceRecord(paths.instanceRecordPath).finally(() => process.exit(1));
1926
+ });
1927
+ return;
1928
+ }
1929
+ log(`${signal} (${signalCount}): exiting now`);
1930
+ process.exit(1);
1931
+ };
1932
+ process.on("SIGINT", () => onSignal("SIGINT"));
1933
+ process.on("SIGTERM", () => onSignal("SIGTERM"));
1934
+ return {
1935
+ port,
1936
+ configKey: resolved.configKey,
1937
+ paths,
1938
+ shutdown
1939
+ };
1940
+ }
1941
+ /** The `nice-commander daemon` entry: boot, stay alive, exit nonzero on a boot failure. */
1942
+ async function runCommanderDaemon(argv) {
1943
+ try {
1944
+ await startCommanderDaemon(argv);
1945
+ return await new Promise(() => {});
1946
+ } catch (error) {
1947
+ process.stderr.write(`nice-commander daemon: ${error.message}\n`);
1948
+ return 2;
1949
+ }
1950
+ }
1951
+ //#endregion
1952
+ exports.runCommanderDaemon = runCommanderDaemon;
1953
+
1954
+ //# sourceMappingURL=main-Cq4RCzSk.cjs.map