@aiwayds/dsh-opentui 0.18.6 → 0.19.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,1276 @@
1
+ var __esm = (fn, res, err) => () => {
2
+ if (fn)
3
+ try {
4
+ res = fn(fn = 0);
5
+ } catch (e) {
6
+ err = [e];
7
+ }
8
+ if (err)
9
+ throw err[0];
10
+ return res;
11
+ };
12
+
13
+ // src/client/mux-frame.ts
14
+ var init_mux_frame = () => {};
15
+
16
+ // src/client/host-probe.ts
17
+ import WS from "ws";
18
+ function validAuthority(authority) {
19
+ return typeof authority === "string" && authority.length > 0 && !/[\r\n/]/.test(authority);
20
+ }
21
+ async function probeHostHttpStatus(options) {
22
+ if (!validAuthority(options.authority))
23
+ return null;
24
+ const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS;
25
+ try {
26
+ const response = await fetch(`http://${options.authority}/`, {
27
+ headers: { cookie: options.cookieHeader },
28
+ signal: AbortSignal.timeout(timeoutMs)
29
+ });
30
+ try {
31
+ await response.body?.cancel();
32
+ } catch {}
33
+ return response.status;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+ var DEFAULT_HOST_PROBE_TIMEOUT_MS = 2000;
39
+ var init_host_probe = __esm(() => {
40
+ init_mux_frame();
41
+ });
42
+
43
+ // src/client/append-system.ts
44
+ var APPEND_SYSTEM_PRESET_ID = "opentui-append-system", APPEND_SYSTEM_ROW_ID;
45
+ var init_append_system = __esm(() => {
46
+ APPEND_SYSTEM_ROW_ID = `preset-${APPEND_SYSTEM_PRESET_ID}`;
47
+ });
48
+
49
+ // src/client/safe-kill.ts
50
+ import { spawnSync } from "node:child_process";
51
+ function psStat(pid) {
52
+ try {
53
+ const result = spawnSync("ps", ["-p", String(pid), "-o", "stat="], { encoding: "utf8" });
54
+ if (result.error || result.status !== 0)
55
+ return null;
56
+ return (result.stdout ?? "").trim() || null;
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+ function statIsZombie(stat) {
62
+ return stat.startsWith("Z");
63
+ }
64
+ function defaultPidAlive(pid) {
65
+ try {
66
+ process.kill(pid, 0);
67
+ } catch (err) {
68
+ return err.code === "EPERM";
69
+ }
70
+ const stat = psStat(pid);
71
+ if (stat !== null && statIsZombie(stat))
72
+ return false;
73
+ return true;
74
+ }
75
+ function evidencesAgree(pid, registryPid, hooks) {
76
+ if (!Number.isInteger(pid) || pid <= 0)
77
+ return false;
78
+ if (registryPid !== pid)
79
+ return false;
80
+ const cmd = hooks.cmdline(pid);
81
+ if (!cmd)
82
+ return false;
83
+ const profiles = [...cmd.matchAll(/--profile[= ]+([^\s]+)/g)].map((m) => m[1]);
84
+ if (profiles.length === 0 || profiles.some((p) => p !== HOST_PROFILE))
85
+ return false;
86
+ if (hooks.hasServerEnv(pid))
87
+ return true;
88
+ if (hooks.envReadable && !hooks.envReadable(pid)) {
89
+ hooks.onEnvFallback?.(pid);
90
+ return true;
91
+ }
92
+ return false;
93
+ }
94
+ async function waitGone(pid, budgetMs, alive, sleep, now) {
95
+ if (!alive(pid))
96
+ return true;
97
+ const deadline = now() + budgetMs;
98
+ const maxIterations = Math.max(1, Math.ceil(budgetMs / DEFAULT_EXIT_POLL_MS) + 8);
99
+ for (let i = 0;i < maxIterations && now() < deadline; i++) {
100
+ await sleep(DEFAULT_EXIT_POLL_MS);
101
+ if (!alive(pid))
102
+ return true;
103
+ }
104
+ return !alive(pid);
105
+ }
106
+ async function safeStopHost(options) {
107
+ const {
108
+ pid,
109
+ registryPid,
110
+ hooks,
111
+ termGraceMs = DEFAULT_TERM_GRACE_MS,
112
+ killGraceMs = DEFAULT_KILL_GRACE_MS,
113
+ sleep = defaultSleep,
114
+ pidAlive = hooks.pidAlive ?? defaultPidAlive,
115
+ now = Date.now
116
+ } = options;
117
+ if (!evidencesAgree(pid, registryPid, hooks)) {
118
+ return { attempted: false, evidencesOk: false, signals: [], stopped: !pidAlive(pid) };
119
+ }
120
+ const signals = [];
121
+ hooks.kill(pid, "SIGTERM");
122
+ signals.push("SIGTERM");
123
+ if (await waitGone(pid, termGraceMs, pidAlive, sleep, now)) {
124
+ return { attempted: true, evidencesOk: true, signals, stopped: true };
125
+ }
126
+ hooks.kill(pid, "SIGKILL");
127
+ signals.push("SIGKILL");
128
+ const stopped = await waitGone(pid, killGraceMs, pidAlive, sleep, now);
129
+ return { attempted: true, evidencesOk: true, signals, stopped };
130
+ }
131
+ var SERVER_ENV_NAME = "DSH_OPENTUI_SERVER", SERVER_ENV_VALUE = "1", HOST_PROFILE = "opentui", DEFAULT_TERM_GRACE_MS = 5000, DEFAULT_KILL_GRACE_MS = 2000, DEFAULT_EXIT_POLL_MS = 50, psKillHooks, defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
132
+ var init_safe_kill = __esm(() => {
133
+ psKillHooks = {
134
+ cmdline(pid) {
135
+ try {
136
+ return spawnSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }).stdout?.trim() || null;
137
+ } catch {
138
+ return null;
139
+ }
140
+ },
141
+ hasServerEnv(pid) {
142
+ try {
143
+ const out = spawnSync("ps", ["eww", "-p", String(pid), "-o", "command="], { encoding: "utf8" }).stdout ?? "";
144
+ return out.includes(`${SERVER_ENV_NAME}=${SERVER_ENV_VALUE}`);
145
+ } catch {
146
+ return false;
147
+ }
148
+ },
149
+ envReadable(pid) {
150
+ try {
151
+ const result = spawnSync("ps", ["eww", "-p", String(pid), "-o", "command="], { encoding: "utf8" });
152
+ if (result.error || result.status !== null && result.status !== 0)
153
+ return false;
154
+ const out = (result.stdout ?? "").trim();
155
+ if (!out || out.includes("<defunct>"))
156
+ return false;
157
+ const stat = psStat(pid);
158
+ if (stat !== null && statIsZombie(stat))
159
+ return false;
160
+ return true;
161
+ } catch {
162
+ return false;
163
+ }
164
+ },
165
+ onEnvFallback(pid) {
166
+ console.warn(`[safe-kill] ${SERVER_ENV_NAME} env unreadable for pid ${pid}; ` + `using registry + cmdline two-evidence fallback (no "dsh" match)`);
167
+ },
168
+ kill(pid, signal) {
169
+ try {
170
+ process.kill(pid, signal);
171
+ } catch {}
172
+ }
173
+ };
174
+ });
175
+
176
+ // src/client/lifecycle.ts
177
+ import { connect as netConnect, Server } from "node:net";
178
+ function pidAlive(pid) {
179
+ return defaultPidAlive(pid);
180
+ }
181
+ function isListening(port) {
182
+ return new Promise((resolve) => {
183
+ let settled = false;
184
+ const socket = netConnect({ host: "127.0.0.1", port });
185
+ const finish = (value) => {
186
+ if (settled)
187
+ return;
188
+ settled = true;
189
+ socket.destroy();
190
+ resolve(value);
191
+ };
192
+ socket.setTimeout(LISTEN_PROBE_TIMEOUT_MS);
193
+ socket.once("connect", () => finish(true));
194
+ socket.once("error", () => finish(false));
195
+ socket.once("timeout", () => finish(false));
196
+ });
197
+ }
198
+ var DEFAULT_IDLE_EXIT_MS = 5000, DEFAULT_IDLE_EXIT_SEC, LISTEN_PROBE_TIMEOUT_MS = 750, registry, pendingBoots, respawnHistory, RETRYABLE_MINT_ERRORS;
199
+ var init_lifecycle = __esm(() => {
200
+ init_host_probe();
201
+ init_append_system();
202
+ init_safe_kill();
203
+ DEFAULT_IDLE_EXIT_SEC = DEFAULT_IDLE_EXIT_MS / 1000;
204
+ registry = new Map;
205
+ pendingBoots = new Map;
206
+ respawnHistory = new Map;
207
+ RETRYABLE_MINT_ERRORS = new Set(["CredentialsFileMissingError", "CredentialsGrantMissingError"]);
208
+ });
209
+
210
+ // src/client/host-registry.ts
211
+ import { randomUUID } from "node:crypto";
212
+ import {
213
+ existsSync,
214
+ linkSync,
215
+ mkdirSync,
216
+ readFileSync,
217
+ renameSync,
218
+ unlinkSync,
219
+ writeFileSync
220
+ } from "node:fs";
221
+ import { join } from "node:path";
222
+ function registryPath(home, profile) {
223
+ return join(home, `opentui-host.${profile}.json`);
224
+ }
225
+ function isPlainObject(value) {
226
+ return value !== null && typeof value === "object" && !Array.isArray(value);
227
+ }
228
+ function isInteger(value) {
229
+ return typeof value === "number" && Number.isInteger(value);
230
+ }
231
+ function isString(value) {
232
+ return typeof value === "string";
233
+ }
234
+ function nonEmpty(value) {
235
+ return isString(value) && value.trim() !== "";
236
+ }
237
+ function invalid(reason, raw) {
238
+ return { kind: "invalid", raw, reason };
239
+ }
240
+ function validateRegistry(raw) {
241
+ if (!isPlainObject(raw))
242
+ return invalid("registry is not an object", raw);
243
+ if (raw.version === REGISTRY_SCHEMA_VERSION) {
244
+ if (!nonEmpty(raw.profile))
245
+ return invalid("profile must be a non-empty string", raw);
246
+ if (!nonEmpty(raw.home))
247
+ return invalid("home must be a non-empty string", raw);
248
+ if (!isInteger(raw.pid) || raw.pid < 0)
249
+ return invalid("pid must be a non-negative integer", raw);
250
+ if (!isInteger(raw.port) || raw.port < 0 || raw.port > 65535)
251
+ return invalid("port must be an integer in [0, 65535]", raw);
252
+ if (!REGISTRY_PHASES.includes(raw.phase)) {
253
+ return invalid(`phase must be one of ${REGISTRY_PHASES.join("|")}`, raw);
254
+ }
255
+ if (!nonEmpty(raw.startedAt))
256
+ return invalid("startedAt must be a non-empty string", raw);
257
+ if (!nonEmpty(raw.updatedAt))
258
+ return invalid("updatedAt must be a non-empty string", raw);
259
+ if (!isString(raw.authority))
260
+ return invalid("authority must be a string", raw);
261
+ if (!Array.isArray(raw.clients))
262
+ return invalid("clients must be an array", raw);
263
+ const clients = [];
264
+ for (const [index, item] of raw.clients.entries()) {
265
+ if (!isPlainObject(item))
266
+ return invalid(`clients[${index}] must be an object`, raw);
267
+ if (!nonEmpty(item.id))
268
+ return invalid(`clients[${index}].id must be a non-empty string`, raw);
269
+ if (!isInteger(item.pid) || item.pid < 0)
270
+ return invalid(`clients[${index}].pid must be a non-negative integer`, raw);
271
+ if (!nonEmpty(item.lastSeen))
272
+ return invalid(`clients[${index}].lastSeen must be a non-empty string`, raw);
273
+ clients.push({ id: item.id, pid: item.pid, lastSeen: item.lastSeen });
274
+ }
275
+ return {
276
+ kind: "v2",
277
+ value: {
278
+ version: 2,
279
+ profile: raw.profile,
280
+ home: raw.home,
281
+ pid: raw.pid,
282
+ port: raw.port,
283
+ phase: raw.phase,
284
+ startedAt: raw.startedAt,
285
+ updatedAt: raw.updatedAt,
286
+ authority: raw.authority,
287
+ clients
288
+ }
289
+ };
290
+ }
291
+ if (raw.version !== undefined)
292
+ return invalid(`unsupported registry version ${String(raw.version)}`, raw);
293
+ if (!isInteger(raw.pid) || !isInteger(raw.port)) {
294
+ return invalid("legacy registry is missing pid/port", raw);
295
+ }
296
+ return {
297
+ kind: "legacy",
298
+ raw: {
299
+ pid: raw.pid,
300
+ port: raw.port,
301
+ ...isString(raw.authority) ? { authority: raw.authority } : {},
302
+ ...isString(raw.startedAt) ? { startedAt: raw.startedAt } : {},
303
+ ...isString(raw.profile) ? { profile: raw.profile } : {},
304
+ ...raw.booting === true ? { booting: true } : {}
305
+ }
306
+ };
307
+ }
308
+ function createClaimRegistry(home, profile, pid, nowIso) {
309
+ return {
310
+ version: 2,
311
+ profile,
312
+ home,
313
+ pid,
314
+ port: 0,
315
+ phase: "claim",
316
+ startedAt: nowIso,
317
+ updatedAt: nowIso,
318
+ authority: "",
319
+ clients: []
320
+ };
321
+ }
322
+ function withPhase(reg, phase, nowIso) {
323
+ return { ...reg, phase, updatedAt: nowIso };
324
+ }
325
+ function readRegistryAt(path, fs = nodeRegistryFs) {
326
+ let text;
327
+ try {
328
+ text = fs.readFileSync(path, "utf8");
329
+ } catch {
330
+ return { kind: "missing" };
331
+ }
332
+ let raw;
333
+ try {
334
+ raw = JSON.parse(text);
335
+ } catch {
336
+ return invalid("registry file is not valid JSON", text);
337
+ }
338
+ return validateRegistry(raw);
339
+ }
340
+ function readRegistry(home, profile, fs = nodeRegistryFs) {
341
+ return readRegistryAt(registryPath(home, profile), fs);
342
+ }
343
+ function writeRegistry(home, profile, record, fs = nodeRegistryFs) {
344
+ const checked = validateRegistry(record);
345
+ if (checked.kind !== "v2") {
346
+ throw new Error(`writeRegistry: refusing to write invalid v2 record (${checked.kind === "invalid" ? checked.reason : checked.kind})`);
347
+ }
348
+ fs.mkdirSync(home, { recursive: true });
349
+ const path = registryPath(home, profile);
350
+ const tmp = `${path}.tmp-${process.pid}-${++writeSeq}`;
351
+ fs.writeFileSync(tmp, JSON.stringify(checked.value, null, 2) + `
352
+ `);
353
+ try {
354
+ fs.renameSync(tmp, path);
355
+ } catch (error) {
356
+ try {
357
+ fs.unlinkSync(tmp);
358
+ } catch {}
359
+ throw error;
360
+ }
361
+ }
362
+ function isErrno(error, code) {
363
+ return error instanceof Error && error.code === code;
364
+ }
365
+ function claimRegistry(home, profile, options = {}) {
366
+ const fs = options.fs ?? nodeRegistryFs;
367
+ const now = options.now ?? Date.now;
368
+ const pid = options.pid ?? process.pid;
369
+ const nowIso = new Date(now()).toISOString();
370
+ fs.mkdirSync(home, { recursive: true });
371
+ const path = registryPath(home, profile);
372
+ const registry = createClaimRegistry(home, profile, pid, nowIso);
373
+ const tmp = `${path}.claim-${process.pid}-${randomUUID()}`;
374
+ fs.writeFileSync(tmp, JSON.stringify(registry, null, 2) + `
375
+ `);
376
+ try {
377
+ fs.linkSync(tmp, path);
378
+ return { ok: true, token: registry.startedAt, path, registry };
379
+ } catch (error) {
380
+ if (isErrno(error, "EEXIST"))
381
+ return { ok: false, reason: "occupied", path };
382
+ throw error;
383
+ } finally {
384
+ try {
385
+ fs.unlinkSync(tmp);
386
+ } catch {}
387
+ }
388
+ }
389
+ function looksLikeV2(value) {
390
+ const candidate = value;
391
+ return isPlainObject(candidate) && candidate.version === REGISTRY_SCHEMA_VERSION;
392
+ }
393
+ function isRegistryStale(input, deps = {}) {
394
+ const read = looksLikeV2(input) ? { kind: "v2", value: input } : input;
395
+ if (read.kind === "missing")
396
+ return { stale: false, reasons: [] };
397
+ if (read.kind === "legacy")
398
+ return { stale: true, reasons: ["legacy-schema"] };
399
+ if (read.kind === "invalid")
400
+ return { stale: true, reasons: ["invalid-schema"] };
401
+ const reasons = [];
402
+ const alive = deps.pidAlive ?? pidAlive;
403
+ if (!alive(read.value.pid))
404
+ reasons.push("dead-pid");
405
+ if (deps.registryMaxAgeMs !== undefined && (read.value.phase === "claim" || read.value.phase === "booting")) {
406
+ const now = (deps.now ?? Date.now)();
407
+ const updated = Date.parse(read.value.updatedAt);
408
+ if (!Number.isNaN(updated) && now - updated > deps.registryMaxAgeMs)
409
+ reasons.push("registry-too-old");
410
+ }
411
+ return { stale: reasons.length > 0, reasons };
412
+ }
413
+ function safeClearLegacy(home, profile, options = {}) {
414
+ const fs = options.fs ?? nodeRegistryFs;
415
+ const path = registryPath(home, profile);
416
+ const read = options.read ?? readRegistryAt(path, fs);
417
+ if (read.kind === "missing")
418
+ return { removed: false, reason: "missing" };
419
+ if (read.kind !== "legacy")
420
+ return { removed: false, reason: "not-legacy" };
421
+ const alive = options.pidAlive ?? pidAlive;
422
+ if (read.raw.pid > 0 && alive(read.raw.pid)) {
423
+ return { removed: false, reason: "legacy-host-alive" };
424
+ }
425
+ fs.unlinkSync(path);
426
+ return { removed: true, reason: "legacy-removed" };
427
+ }
428
+ var REGISTRY_SCHEMA_VERSION = 2, REGISTRY_PHASES, nodeRegistryFs, writeSeq = 0;
429
+ var init_host_registry = __esm(() => {
430
+ init_lifecycle();
431
+ REGISTRY_PHASES = ["claim", "booting", "ready", "stopping"];
432
+ nodeRegistryFs = {
433
+ existsSync: (path) => existsSync(path),
434
+ mkdirSync: (path, options) => {
435
+ mkdirSync(path, options);
436
+ },
437
+ readFileSync: (path, encoding) => readFileSync(path, encoding),
438
+ writeFileSync: (path, data, options) => {
439
+ writeFileSync(path, data, options);
440
+ },
441
+ renameSync: (from, to) => renameSync(from, to),
442
+ linkSync: (from, to) => linkSync(from, to),
443
+ unlinkSync: (path) => unlinkSync(path)
444
+ };
445
+ });
446
+
447
+ // src/client/client-lifecycle.ts
448
+ import {
449
+ existsSync as nodeExistsSync,
450
+ mkdirSync as nodeMkdirSync,
451
+ readFileSync as nodeReadFileSync,
452
+ readdirSync as nodeReaddirSync,
453
+ renameSync as nodeRenameSync,
454
+ unlinkSync as nodeUnlinkSync,
455
+ writeFileSync as nodeWriteFileSync
456
+ } from "node:fs";
457
+ import { join as join2 } from "node:path";
458
+ function clientsDir(home) {
459
+ return join2(home, CLIENTS_DIR_NAME);
460
+ }
461
+ function heartbeatPath(home, clientId) {
462
+ return join2(clientsDir(home), `${clientId}.json`);
463
+ }
464
+ function validateHeartbeat(raw) {
465
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
466
+ return null;
467
+ const r = raw;
468
+ if (typeof r.id !== "string" || r.id.trim() === "")
469
+ return null;
470
+ if (typeof r.pid !== "number" || !Number.isInteger(r.pid) || r.pid < 0)
471
+ return null;
472
+ if (typeof r.lastSeen !== "string" || r.lastSeen.trim() === "")
473
+ return null;
474
+ if (Number.isNaN(Date.parse(r.lastSeen)))
475
+ return null;
476
+ if (typeof r.workspace !== "string")
477
+ return null;
478
+ return { id: r.id, pid: r.pid, lastSeen: r.lastSeen, workspace: r.workspace };
479
+ }
480
+ function isFresh(hb, nowMs, ttlMs) {
481
+ const seen = Date.parse(hb.lastSeen);
482
+ if (Number.isNaN(seen))
483
+ return false;
484
+ const age = nowMs - seen;
485
+ return age >= 0 && age <= ttlMs;
486
+ }
487
+ function listHeartbeats(home, deps = {}) {
488
+ const fs = deps.fs ?? nodeLifecycleFs;
489
+ if (!fs.readdirSync)
490
+ return [];
491
+ let names;
492
+ try {
493
+ names = fs.readdirSync(clientsDir(home));
494
+ } catch {
495
+ return [];
496
+ }
497
+ const out = [];
498
+ for (const name of names) {
499
+ if (!name.endsWith(".json"))
500
+ continue;
501
+ try {
502
+ const raw = JSON.parse(fs.readFileSync(join2(clientsDir(home), name), "utf8"));
503
+ const hb = validateHeartbeat(raw);
504
+ if (hb)
505
+ out.push(hb);
506
+ } catch {}
507
+ }
508
+ return out;
509
+ }
510
+ function freshClients(home, deps = {}, ttlMs = DEFAULT_CLIENT_TTL_MS) {
511
+ const now = deps.now ?? Date.now;
512
+ const nowMs = now();
513
+ return listHeartbeats(home, deps).filter((hb) => isFresh(hb, nowMs, ttlMs));
514
+ }
515
+ function purgeAllHeartbeats(home, deps = {}) {
516
+ const fs = deps.fs ?? nodeLifecycleFs;
517
+ const removed = [];
518
+ for (const hb of listHeartbeats(home, deps)) {
519
+ try {
520
+ fs.unlinkSync(heartbeatPath(home, hb.id));
521
+ removed.push(hb.id);
522
+ } catch {}
523
+ }
524
+ return removed;
525
+ }
526
+ function assertLifecycleFsComplete(fs) {
527
+ const f = fs ?? nodeLifecycleFs;
528
+ const missing = ["readdirSync", "readFileSync"].filter((method) => typeof f[method] !== "function");
529
+ if (missing.length > 0)
530
+ throw new IncompleteLifecycleFsError([...missing]);
531
+ }
532
+ function assertForceAllowed(home, options) {
533
+ assertLifecycleFsComplete(options.fs);
534
+ const live = freshClients(home, options, options.ttlMs);
535
+ if (live.length > 0 && !options.yes)
536
+ throw new ForceNeedsYesError(live.length);
537
+ return { liveClients: live.length, allowed: true };
538
+ }
539
+ var CLIENTS_DIR_NAME = "opentui-clients", DEFAULT_CLIENT_TTL_MS = 15000, nodeLifecycleFs, ForceNeedsYesError, IncompleteLifecycleFsError;
540
+ var init_client_lifecycle = __esm(() => {
541
+ init_host_registry();
542
+ init_safe_kill();
543
+ nodeLifecycleFs = {
544
+ existsSync: (p) => nodeExistsSync(p),
545
+ mkdirSync: (p, o) => nodeMkdirSync(p, o),
546
+ readFileSync: (p, e) => nodeReadFileSync(p, e),
547
+ writeFileSync: (p, d, o) => nodeWriteFileSync(p, d, o),
548
+ unlinkSync: (p) => nodeUnlinkSync(p),
549
+ readdirSync: (p) => nodeReaddirSync(p),
550
+ renameSync: (from, to) => nodeRenameSync(from, to)
551
+ };
552
+ ForceNeedsYesError = class ForceNeedsYesError extends Error {
553
+ clientCount;
554
+ code = "force-needs-yes";
555
+ constructor(clientCount) {
556
+ super(`--force would disconnect ${clientCount} live client(s); re-run with --force --yes to confirm.`);
557
+ this.clientCount = clientCount;
558
+ this.name = new.target.name;
559
+ }
560
+ };
561
+ IncompleteLifecycleFsError = class IncompleteLifecycleFsError extends Error {
562
+ missing;
563
+ code = "lifecycle-fs-incomplete";
564
+ constructor(missing) {
565
+ super(`dsh-opentui: --force guard fs is missing required method(s): ${missing.join(", ")}; ` + `refusing to read an unlistable heartbeat dir as "no live clients" (that would bypass --yes).`);
566
+ this.missing = missing;
567
+ this.name = new.target.name;
568
+ }
569
+ };
570
+ });
571
+
572
+ // src/client/cookie-mint.ts
573
+ import { createHash, createHmac } from "node:crypto";
574
+ import { readFileSync as readFileSync2, statSync } from "node:fs";
575
+ import { join as join3 } from "node:path";
576
+ function ownerCookieName(authority) {
577
+ return "dsh-auth-" + base64url(createHash("sha256").update(authority).digest());
578
+ }
579
+ function mintOwnerCookie(options) {
580
+ const authority = options.authority;
581
+ if (typeof authority !== "string" || authority.length === 0 || /[\r\n/]/.test(authority)) {
582
+ throw new OwnerCookieError("authority must be a non-empty host:port without scheme or path separators");
583
+ }
584
+ const secret = readGrantSecret(options.home);
585
+ const issuedAt = Date.now();
586
+ const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
587
+ const expiresAt = issuedAt + Math.min(maxAgeMs, DEFAULT_MAX_AGE_MS);
588
+ const body = base64url(Buffer.from(JSON.stringify({ version: 1, authority, issuedAt, expiresAt }), "utf8"));
589
+ const signature = base64url(createHmac("sha256", secret).update(body).digest());
590
+ return `${ownerCookieName(authority)}=v1.${body}.${signature}`;
591
+ }
592
+ function readGrantSecret(home) {
593
+ const path = join3(home, ".credentials.yaml");
594
+ const deadline = Date.now() + RETRY_WINDOW_MS;
595
+ let sawFile = false;
596
+ while (true) {
597
+ let file = "";
598
+ try {
599
+ assertOwnerOnly(path);
600
+ file = readFileSync2(path, "utf8");
601
+ sawFile = true;
602
+ } catch (error) {
603
+ if (error instanceof CredentialsFileInsecureError)
604
+ throw error;
605
+ sawFile = false;
606
+ }
607
+ if (sawFile) {
608
+ const secret = extractSecret(file, path);
609
+ if (secret !== undefined)
610
+ return decodeSecret(secret, path);
611
+ }
612
+ if (Date.now() >= deadline) {
613
+ if (!sawFile) {
614
+ throw new CredentialsFileMissingError(`no credentials file at ${path} within ${RETRY_WINDOW_MS}ms (host first boot still pending?)`);
615
+ }
616
+ throw new CredentialsGrantMissingError(`credentials record "${RECORD_KEY}" absent in ${path} within ${RETRY_WINDOW_MS}ms (host first boot still pending?)`);
617
+ }
618
+ sleepSync(RETRY_INTERVAL_MS);
619
+ }
620
+ }
621
+ function assertOwnerOnly(path) {
622
+ let mode;
623
+ try {
624
+ mode = statSync(path).mode;
625
+ } catch {
626
+ return;
627
+ }
628
+ if ((mode & 63) !== 0) {
629
+ throw new CredentialsFileInsecureError(`credentials file ${path} is group/other accessible (mode ${mode.toString(8)}); refusing to mint — chmod 600 required`);
630
+ }
631
+ }
632
+ function extractSecret(file, path) {
633
+ const lines = file.split(`
634
+ `);
635
+ const recordsLine = findBlockLine(lines, "records", 0);
636
+ if (recordsLine === -1)
637
+ return;
638
+ const childIndent = nextChildIndent(lines, recordsLine);
639
+ if (childIndent === -1)
640
+ return;
641
+ const recordLine = findBlockLine(lines, RECORD_KEY, childIndent, recordsLine + 1);
642
+ if (recordLine === -1)
643
+ return;
644
+ const recordIndent = nextChildIndent(lines, recordLine);
645
+ if (recordIndent === -1) {
646
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} has no kind field`);
647
+ }
648
+ const kind = readScalarLine(lines, "kind", recordIndent, recordLine + 1);
649
+ if (kind !== "grant") {
650
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} has ${kind === undefined ? "no kind field" : `kind other than "grant"`}`);
651
+ }
652
+ const payloadLine = findBlockLine(lines, "payload", recordIndent, recordLine + 1);
653
+ if (payloadLine === -1) {
654
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} has no payload block`);
655
+ }
656
+ const payloadIndent = nextChildIndent(lines, payloadLine);
657
+ if (payloadIndent === -1) {
658
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} has an empty payload block`);
659
+ }
660
+ const payloadVersion = readScalarLine(lines, "version", payloadIndent, payloadLine + 1);
661
+ if (payloadVersion !== "1") {
662
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} has payload.version ${payloadVersion === undefined ? "absent" : "other than 1"} (rotated grant format)`);
663
+ }
664
+ const secret = readScalarLine(lines, "secret", payloadIndent, payloadLine + 1);
665
+ if (secret === undefined) {
666
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} has no payload.secret`);
667
+ }
668
+ return secret;
669
+ }
670
+ function findBlockLine(lines, key, atIndent, from = 0) {
671
+ const range = blockRange(lines, from, atIndent);
672
+ for (let i = range.start;i < range.end; i++) {
673
+ const entry = parseEntryLine(lines[i]);
674
+ if (entry && entry.indent === atIndent && entry.key === key && entry.value === undefined)
675
+ return i;
676
+ }
677
+ return -1;
678
+ }
679
+ function readScalarLine(lines, key, atIndent, from) {
680
+ const range = blockRange(lines, from, atIndent);
681
+ for (let i = range.start;i < range.end; i++) {
682
+ const entry = parseEntryLine(lines[i]);
683
+ if (entry && entry.indent === atIndent && entry.key === key) {
684
+ if (entry.value === undefined) {
685
+ throw new CredentialsParseError(`credentials file has a nested block where the "${key}" scalar is required`);
686
+ }
687
+ return entry.value;
688
+ }
689
+ }
690
+ return;
691
+ }
692
+ function blockRange(lines, from, atIndent) {
693
+ let start = -1;
694
+ let i = from;
695
+ for (;i < lines.length; i++) {
696
+ const line = lines[i];
697
+ if (!line.trim() || line.trimStart().startsWith("#"))
698
+ continue;
699
+ if (leadingSpaces(line) < atIndent)
700
+ break;
701
+ if (start === -1)
702
+ start = i;
703
+ }
704
+ return { start: start === -1 ? lines.length : start, end: i };
705
+ }
706
+ function nextChildIndent(lines, entryLine) {
707
+ const parentIndent = leadingSpaces(lines[entryLine]);
708
+ for (let i = entryLine + 1;i < lines.length; i++) {
709
+ const line = lines[i];
710
+ if (!line.trim() || line.trimStart().startsWith("#"))
711
+ continue;
712
+ const indent = leadingSpaces(line);
713
+ return indent > parentIndent ? indent : -1;
714
+ }
715
+ return -1;
716
+ }
717
+ function leadingSpaces(line) {
718
+ let n = 0;
719
+ while (n < line.length && line[n] === " ")
720
+ n++;
721
+ return n;
722
+ }
723
+ function parseEntryLine(line) {
724
+ const trimmed = line.trim();
725
+ if (!trimmed || trimmed.startsWith("#"))
726
+ return;
727
+ if (line.includes("\t"))
728
+ return;
729
+ const indent = leadingSpaces(line);
730
+ const rest = line.slice(indent);
731
+ const colon = rest.indexOf(":");
732
+ if (colon === -1)
733
+ return;
734
+ const key = unquote(rest.slice(0, colon).trim());
735
+ if (!key)
736
+ return;
737
+ const rawValue = rest.slice(colon + 1).trim();
738
+ if (rawValue === "" || rawValue.startsWith("#"))
739
+ return { indent, key };
740
+ return { indent, key, value: unquoteScalar(rawValue) };
741
+ }
742
+ function unquote(text) {
743
+ if (text.length >= 2) {
744
+ if (text.startsWith("'") && text.endsWith("'"))
745
+ return text.slice(1, -1).replaceAll("''", "'");
746
+ if (text.startsWith('"') && text.endsWith('"'))
747
+ return unescapeDoubleQuoted(text.slice(1, -1));
748
+ }
749
+ return text;
750
+ }
751
+ function unquoteScalar(rawValue) {
752
+ if (rawValue.startsWith("'") || rawValue.startsWith('"'))
753
+ return unquote(rawValue);
754
+ const comment = rawValue.indexOf(" #");
755
+ return (comment === -1 ? rawValue : rawValue.slice(0, comment)).trim();
756
+ }
757
+ function unescapeDoubleQuoted(text) {
758
+ return text.replaceAll("\\\"", '"').replaceAll("\\\\", "\\");
759
+ }
760
+ function decodeSecret(secret, path) {
761
+ if (!SECRET_PATTERN.test(secret)) {
762
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} has a secret that is not a 43-char base64url string (rotated grant format)`);
763
+ }
764
+ const key = Buffer.from(secret.replaceAll("-", "+").replaceAll("_", "/") + "=", "base64");
765
+ if (key.length !== 32) {
766
+ throw new CredentialsGrantInvalidError(`credentials record "${RECORD_KEY}" in ${path} decodes to ${String(key.length)} bytes, expected 32`);
767
+ }
768
+ return key;
769
+ }
770
+ function base64url(buffer) {
771
+ return buffer.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
772
+ }
773
+ function sleepSync(ms) {
774
+ const buffer = new Int32Array(new SharedArrayBuffer(4));
775
+ const parked = (() => {
776
+ try {
777
+ return Atomics.wait(buffer, 0, 0, ms) === "timed-out";
778
+ } catch {
779
+ return false;
780
+ }
781
+ })();
782
+ if (!parked) {
783
+ const until = Date.now() + ms;
784
+ while (Date.now() < until) {}
785
+ }
786
+ }
787
+ var RECORD_KEY = "client-connection/browser-session", DEFAULT_MAX_AGE_MS, RETRY_INTERVAL_MS = 100, RETRY_WINDOW_MS = 2000, SECRET_PATTERN, OwnerCookieError, CredentialsFileMissingError, CredentialsGrantMissingError, CredentialsGrantInvalidError, CredentialsFileInsecureError, CredentialsParseError;
788
+ var init_cookie_mint = __esm(() => {
789
+ DEFAULT_MAX_AGE_MS = 30 * 86400000;
790
+ SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/;
791
+ OwnerCookieError = class OwnerCookieError extends Error {
792
+ constructor(message) {
793
+ super(message);
794
+ this.name = "OwnerCookieError";
795
+ }
796
+ };
797
+ CredentialsFileMissingError = class CredentialsFileMissingError extends OwnerCookieError {
798
+ };
799
+ CredentialsGrantMissingError = class CredentialsGrantMissingError extends OwnerCookieError {
800
+ };
801
+ CredentialsGrantInvalidError = class CredentialsGrantInvalidError extends OwnerCookieError {
802
+ };
803
+ CredentialsFileInsecureError = class CredentialsFileInsecureError extends OwnerCookieError {
804
+ };
805
+ CredentialsParseError = class CredentialsParseError extends OwnerCookieError {
806
+ };
807
+ });
808
+
809
+ // src/client/host-health.ts
810
+ function authorityPort(authority) {
811
+ if (typeof authority !== "string" || authority.length === 0)
812
+ return null;
813
+ let host = authority;
814
+ if (host.startsWith("[")) {
815
+ const end = host.indexOf("]");
816
+ if (end === -1)
817
+ return null;
818
+ host = host.slice(end + 1);
819
+ if (!host.startsWith(":"))
820
+ return null;
821
+ host = host.slice(1);
822
+ } else {
823
+ const colon = host.lastIndexOf(":");
824
+ if (colon === -1)
825
+ return null;
826
+ host = host.slice(colon + 1);
827
+ }
828
+ if (!/^\d+$/.test(host))
829
+ return null;
830
+ const port = Number(host);
831
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
832
+ }
833
+ function isHealthyStatus(status) {
834
+ return status !== null && status >= HEALTH_STATUS_MIN && status < HEALTH_STATUS_MAX_EXCLUSIVE;
835
+ }
836
+ async function checkHostHealth(target, probes = defaultHealthProbes) {
837
+ let tcp = false;
838
+ try {
839
+ tcp = await probes.connectTcp(target.authority);
840
+ } catch {
841
+ tcp = false;
842
+ }
843
+ if (!tcp)
844
+ return { healthy: false, tcp: false, httpStatus: null, reason: "tcp-failed" };
845
+ let status = null;
846
+ try {
847
+ status = await probes.requestStatus(target.authority, target.cookieHeader);
848
+ } catch {
849
+ status = null;
850
+ }
851
+ if (status === null)
852
+ return { healthy: false, tcp: true, httpStatus: null, reason: "http-no-response" };
853
+ if (!isHealthyStatus(status))
854
+ return { healthy: false, tcp: true, httpStatus: status, reason: "http-unhealthy-status" };
855
+ return { healthy: true, tcp: true, httpStatus: status, reason: "ok" };
856
+ }
857
+ var HEALTH_STATUS_MIN = 200, HEALTH_STATUS_MAX_EXCLUSIVE = 400, defaultHealthProbes;
858
+ var init_host_health = __esm(() => {
859
+ init_lifecycle();
860
+ init_host_probe();
861
+ defaultHealthProbes = {
862
+ async connectTcp(authority) {
863
+ const port = authorityPort(authority);
864
+ return port === null ? false : isListening(port);
865
+ },
866
+ async requestStatus(authority, cookieHeader) {
867
+ return probeHostHttpStatus({ authority, cookieHeader });
868
+ }
869
+ };
870
+ });
871
+
872
+ // src/client/host-port.ts
873
+ import { resolve } from "node:path";
874
+ function canonicalHome(home) {
875
+ const resolved = resolve(home);
876
+ if (process.platform !== "win32")
877
+ return resolved;
878
+ return resolved.replace(/\\/g, "/").replace(/^([A-Za-z]):/, (_match, drive) => drive.toLowerCase() + ":");
879
+ }
880
+ function fnv1a32(text) {
881
+ let hash = FNV_OFFSET_BASIS;
882
+ for (let i = 0;i < text.length; i++) {
883
+ hash ^= text.charCodeAt(i);
884
+ hash = Math.imul(hash, FNV_PRIME);
885
+ }
886
+ return hash >>> 0;
887
+ }
888
+ function derivePort(home, profile, options = {}) {
889
+ const base = options.base ?? DEFAULT_PORT_BASE;
890
+ const count = options.count ?? DEFAULT_PORT_COUNT;
891
+ if (!Number.isInteger(base) || !Number.isInteger(count) || count <= 0) {
892
+ throw new RangeError("derivePort: base and count must be integers and count > 0");
893
+ }
894
+ const offset = fnv1a32(`${canonicalHome(home)}:${profile}`) % count;
895
+ return base + offset;
896
+ }
897
+ async function findFreePort(home, profile, options = {}) {
898
+ const base = options.base ?? DEFAULT_PORT_BASE;
899
+ const count = options.count ?? DEFAULT_PORT_COUNT;
900
+ if (!Number.isInteger(base) || !Number.isInteger(count) || count <= 0) {
901
+ throw new RangeError("findFreePort: base and count must be integers and count > 0");
902
+ }
903
+ const derived = derivePort(home, profile, { base, count });
904
+ const probe = options.probe ?? isListening;
905
+ for (let port = derived;port < derived + count; port++) {
906
+ if (!await probe(port))
907
+ return port;
908
+ }
909
+ throw new NoFreePortError(home, profile, derived, count);
910
+ }
911
+ var DEFAULT_PORT_BASE = 60000, DEFAULT_PORT_COUNT = 1000, FNV_OFFSET_BASIS = 2166136261, FNV_PRIME = 16777619, NoFreePortError;
912
+ var init_host_port = __esm(() => {
913
+ init_lifecycle();
914
+ NoFreePortError = class NoFreePortError extends Error {
915
+ home;
916
+ profile;
917
+ base;
918
+ count;
919
+ code = "no-free-port";
920
+ constructor(home, profile, base, count) {
921
+ super(`no free port for ${profile} in [${base}, ${base + count}) under ${home}`);
922
+ this.home = home;
923
+ this.profile = profile;
924
+ this.base = base;
925
+ this.count = count;
926
+ this.name = "NoFreePortError";
927
+ }
928
+ };
929
+ });
930
+
931
+ // src/client/host-launch.ts
932
+ import { spawn } from "node:child_process";
933
+ import { homedir } from "node:os";
934
+ import { connect as netConnect2, Server as Server2 } from "node:net";
935
+ import { dirname, join as join4 } from "node:path";
936
+ function defaultDshHome() {
937
+ return process.env.DSH_HOME || join4(homedir(), ".dsh");
938
+ }
939
+ function withFfiFlag(env) {
940
+ const existing = env.NODE_OPTIONS ?? "";
941
+ if (existing.split(/\s+/).includes(FFI_FLAG))
942
+ return env;
943
+ return { ...env, NODE_OPTIONS: `${existing} ${FFI_FLAG}`.trim() };
944
+ }
945
+ function resolveDeps(d) {
946
+ const home = d.home ?? defaultDshHome();
947
+ const profile = d.profile ?? DEFAULT_LAUNCH_PROFILE;
948
+ return {
949
+ home,
950
+ profile,
951
+ cwd: d.cwd ?? process.cwd(),
952
+ force: d.force ?? false,
953
+ yes: d.yes ?? false,
954
+ fs: d.fs ?? nodeRegistryFs,
955
+ lifecycleFs: d.lifecycleFs ?? nodeLifecycleFs,
956
+ now: d.now ?? Date.now,
957
+ sleep: d.sleep ?? defaultSleep2,
958
+ spawnHost: d.spawnHost ?? defaultSpawnHost,
959
+ pidAlive: d.pidAlive ?? defaultPidAlive,
960
+ health: d.health ?? defaultHealth,
961
+ mintCookie: d.mintCookie ?? mintOwnerCookie,
962
+ findPort: d.findPort ?? ((home, profile, probe) => findFreePort(home, profile, { probe })),
963
+ portProbe: d.portProbe ?? defaultPortProbe,
964
+ ...d.progress ? { progress: d.progress } : {},
965
+ killHooks: d.killHooks ?? psKillHooks,
966
+ timeoutMs: d.timeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS,
967
+ pollMs: d.pollMs ?? DEFAULT_POLL_MS,
968
+ registryMaxAgeMs: d.registryMaxAgeMs ?? DEFAULT_REGISTRY_MAX_AGE_MS,
969
+ logPath: d.logPath ?? ((h, p) => join4(h, `opentui-host.${p}.log`)),
970
+ baseEnv: d.baseEnv ?? process.env
971
+ };
972
+ }
973
+ function createLaunchProgress(options) {
974
+ const { isTty, write } = options;
975
+ let lastPhase = null;
976
+ return (event) => {
977
+ const seconds = (event.elapsedMs / 1000).toFixed(1);
978
+ const line = `dsh-opentui: host ${event.phase} ${seconds}s`;
979
+ if (isTty) {
980
+ write(`\r\x1B[2K${line}`);
981
+ if (event.phase === "ready")
982
+ write(`
983
+ `);
984
+ return;
985
+ }
986
+ if (event.phase === lastPhase)
987
+ return;
988
+ lastPhase = event.phase;
989
+ write(`${line}
990
+ `);
991
+ };
992
+ }
993
+ function removeStaleRecord(home, profile, stale, o) {
994
+ const current = readRegistry(home, profile, o.fs);
995
+ if (current.kind === "v2" && current.value.pid === stale.pid && current.value.startedAt === stale.startedAt) {
996
+ try {
997
+ o.fs.unlinkSync(registryPath(home, profile));
998
+ } catch {}
999
+ }
1000
+ }
1001
+ function removeInvalidRecord(home, profile, o) {
1002
+ try {
1003
+ o.fs.unlinkSync(registryPath(home, profile));
1004
+ } catch {}
1005
+ }
1006
+ function captureOutput(child, tail) {
1007
+ const push = (chunk) => {
1008
+ tail.text = (tail.text + String(chunk)).slice(-8000);
1009
+ };
1010
+ child.stdout?.on("data", push);
1011
+ child.stderr?.on("data", push);
1012
+ }
1013
+ function flushLog(o, tail) {
1014
+ const path = o.logPath(o.home, o.profile);
1015
+ try {
1016
+ o.fs.mkdirSync(dirname(path), { recursive: true });
1017
+ o.fs.writeFileSync(path, `[dsh-opentui] host output tail
1018
+ ${tail.text}
1019
+ `);
1020
+ } catch {}
1021
+ return path;
1022
+ }
1023
+ async function ensureHost(deps = {}) {
1024
+ const o = resolveDeps(deps);
1025
+ if (o.force) {
1026
+ const hbDeps = { fs: o.lifecycleFs, now: o.now };
1027
+ assertForceAllowed(o.home, { ...hbDeps, yes: o.yes });
1028
+ const current = readRegistry(o.home, o.profile, o.fs);
1029
+ const forcePid = current.kind === "v2" ? current.value.pid : current.kind === "legacy" ? current.raw.pid : 0;
1030
+ if (forcePid > 0) {
1031
+ const stop = await safeStopHost({
1032
+ pid: forcePid,
1033
+ registryPid: forcePid,
1034
+ hooks: o.killHooks,
1035
+ termGraceMs: FORCE_TERM_GRACE_MS,
1036
+ killGraceMs: FORCE_KILL_GRACE_MS,
1037
+ sleep: o.sleep,
1038
+ now: o.now,
1039
+ pidAlive: o.pidAlive
1040
+ });
1041
+ if (!stop.stopped) {
1042
+ throw new Error(`dsh-opentui: --force could not confirm the old host pid ${forcePid} is stopped ` + `(evidences ${stop.evidencesOk ? "matched but pid survived" : "refused"}); ` + `registry left intact — retry --force or stop it manually.`);
1043
+ }
1044
+ try {
1045
+ o.fs.unlinkSync(registryPath(o.home, o.profile));
1046
+ } catch {}
1047
+ }
1048
+ purgeAllHeartbeats(o.home, hbDeps);
1049
+ }
1050
+ const startedAt = o.now();
1051
+ const deadline = startedAt + o.timeoutMs;
1052
+ const emit = (phase) => o.progress?.({ phase, elapsedMs: o.now() - startedAt });
1053
+ let read = readRegistry(o.home, o.profile, o.fs);
1054
+ if (read.kind === "v2" && !o.force) {
1055
+ const reg = read.value;
1056
+ const authority = reg.authority || `127.0.0.1:${reg.port}`;
1057
+ if (reg.phase === "ready" && reg.port > 0 && o.pidAlive(reg.pid)) {
1058
+ const cookie = o.mintCookie({ home: o.home, authority });
1059
+ if ((await o.health(authority, cookie)).healthy) {
1060
+ return { port: reg.port, mode: "adopted", adopted: true, spawned: false, hostPid: reg.pid };
1061
+ }
1062
+ }
1063
+ }
1064
+ for (let attempt = 0;attempt < 4; attempt++) {
1065
+ read = readRegistry(o.home, o.profile, o.fs);
1066
+ if (read.kind === "missing")
1067
+ break;
1068
+ if (read.kind === "legacy") {
1069
+ const cleared = safeClearLegacy(o.home, o.profile, { fs: o.fs, read, pidAlive: o.pidAlive });
1070
+ if (!cleared.removed) {
1071
+ throw new Error(`dsh-opentui: legacy host pid ${read.raw.pid} is still alive; ` + `its registry record is kept — stop it manually or use --force --yes.`);
1072
+ }
1073
+ continue;
1074
+ }
1075
+ if (read.kind === "invalid") {
1076
+ removeInvalidRecord(o.home, o.profile, o);
1077
+ continue;
1078
+ }
1079
+ const verdict = isRegistryStale(read, {
1080
+ now: o.now,
1081
+ pidAlive: o.pidAlive,
1082
+ registryMaxAgeMs: o.registryMaxAgeMs
1083
+ });
1084
+ if (verdict.stale) {
1085
+ removeStaleRecord(o.home, o.profile, read.value, o);
1086
+ continue;
1087
+ }
1088
+ if (read.value.phase === "ready" && read.value.pid > 0) {
1089
+ const stop = await safeStopHost({
1090
+ pid: read.value.pid,
1091
+ registryPid: read.value.pid,
1092
+ hooks: o.killHooks,
1093
+ termGraceMs: FORCE_TERM_GRACE_MS,
1094
+ killGraceMs: FORCE_KILL_GRACE_MS,
1095
+ sleep: o.sleep,
1096
+ now: o.now,
1097
+ pidAlive: o.pidAlive
1098
+ });
1099
+ if (!stop.stopped) {
1100
+ throw new Error(`dsh-opentui: unhealthy host pid ${read.value.pid} could not be stopped ` + `(evidences ${stop.evidencesOk ? "matched but pid survived" : "refused"}); ` + `registry record kept — retry or stop it manually.`);
1101
+ }
1102
+ removeStaleRecord(o.home, o.profile, read.value, o);
1103
+ }
1104
+ break;
1105
+ }
1106
+ const claim = claimRegistry(o.home, o.profile, { fs: o.fs, now: o.now, pid: process.pid });
1107
+ if (!claim.ok) {
1108
+ while (o.now() < deadline) {
1109
+ const current = readRegistry(o.home, o.profile, o.fs);
1110
+ if (current.kind === "v2" && current.value.phase === "ready" && current.value.port > 0) {
1111
+ return {
1112
+ port: current.value.port,
1113
+ mode: "adopted",
1114
+ adopted: true,
1115
+ spawned: false,
1116
+ hostPid: current.value.pid
1117
+ };
1118
+ }
1119
+ await o.sleep(o.pollMs);
1120
+ }
1121
+ throw new HostLaunchTimeoutError(`timed out waiting for the host claimed by another launcher (${o.timeoutMs}ms)`, o.logPath(o.home, o.profile));
1122
+ }
1123
+ const port = await o.findPort(o.home, o.profile, o.portProbe);
1124
+ const booting = {
1125
+ ...claim.registry,
1126
+ pid: 0,
1127
+ port,
1128
+ phase: "booting",
1129
+ authority: `127.0.0.1:${port}`,
1130
+ updatedAt: new Date(o.now()).toISOString()
1131
+ };
1132
+ const env = withFfiFlag({
1133
+ ...o.baseEnv,
1134
+ [SERVER_ENV_NAME]: SERVER_ENV_VALUE,
1135
+ DSH_HOME: o.home
1136
+ });
1137
+ const child = o.spawnHost(["--profile", o.profile, "--no-open", "--port", String(port)], {
1138
+ cwd: o.cwd,
1139
+ env
1140
+ });
1141
+ writeRegistry(o.home, o.profile, { ...booting, pid: child.pid }, o.fs);
1142
+ const bootingRecord = { ...booting, pid: child.pid };
1143
+ emit("spawn");
1144
+ const tail = { text: "" };
1145
+ captureOutput(child, tail);
1146
+ const authority = `127.0.0.1:${port}`;
1147
+ const cookie = o.mintCookie({ home: o.home, authority });
1148
+ let ready = false;
1149
+ let died = false;
1150
+ child.on?.("exit", () => {
1151
+ died = true;
1152
+ });
1153
+ while (o.now() < deadline) {
1154
+ if (died || !o.pidAlive(child.pid))
1155
+ break;
1156
+ if ((await o.health(authority, cookie)).healthy) {
1157
+ ready = true;
1158
+ break;
1159
+ }
1160
+ emit("booting");
1161
+ await o.sleep(o.pollMs);
1162
+ }
1163
+ if (ready) {
1164
+ writeRegistry(o.home, o.profile, withPhase(bootingRecord, "ready", new Date(o.now()).toISOString()), o.fs);
1165
+ emit("ready");
1166
+ return { port, mode: "spawned", adopted: false, spawned: true, hostPid: child.pid };
1167
+ }
1168
+ const log = flushLog(o, tail);
1169
+ const current = readRegistry(o.home, o.profile, o.fs);
1170
+ const registryPid = current.kind === "v2" ? current.value.pid : -1;
1171
+ await safeStopHost({
1172
+ pid: child.pid,
1173
+ registryPid,
1174
+ hooks: o.killHooks,
1175
+ termGraceMs: FORCE_TERM_GRACE_MS,
1176
+ killGraceMs: FORCE_KILL_GRACE_MS,
1177
+ sleep: o.sleep,
1178
+ now: o.now,
1179
+ pidAlive: o.pidAlive
1180
+ });
1181
+ if (current.kind === "v2" && current.value.pid === child.pid) {
1182
+ try {
1183
+ o.fs.unlinkSync(registryPath(o.home, o.profile));
1184
+ } catch {}
1185
+ }
1186
+ throw new HostLaunchTimeoutError(`host did not become ready within ${o.timeoutMs}ms (port ${port}, pid ${child.pid})`, log);
1187
+ }
1188
+ function bindFreePort() {
1189
+ return new Promise((resolve, reject) => {
1190
+ const server = new Server2((socket) => socket.destroy());
1191
+ server.once("error", reject);
1192
+ server.listen(0, "127.0.0.1", () => {
1193
+ const { port } = server.address();
1194
+ server.close(() => resolve(port));
1195
+ });
1196
+ });
1197
+ }
1198
+ var DEFAULT_LAUNCH_PROFILE = "opentui", DEFAULT_LAUNCH_TIMEOUT_MS, DEFAULT_POLL_MS = 150, DEFAULT_REGISTRY_MAX_AGE_MS = 60000, FORCE_TERM_GRACE_MS = 2000, FORCE_KILL_GRACE_MS = 1000, LAUNCH_PHASES, HostLaunchTimeoutError, defaultSleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), defaultPortProbe = (port) => new Promise((resolve) => {
1199
+ let settled = false;
1200
+ const socket = netConnect2({ host: "127.0.0.1", port });
1201
+ const finish = (value) => {
1202
+ if (settled)
1203
+ return;
1204
+ settled = true;
1205
+ socket.destroy();
1206
+ resolve(value);
1207
+ };
1208
+ socket.setTimeout(750);
1209
+ socket.once("connect", () => finish(true));
1210
+ socket.once("error", () => finish(false));
1211
+ socket.once("timeout", () => finish(false));
1212
+ }), FFI_FLAG = "--experimental-ffi", defaultSpawnHost = (argv, options) => {
1213
+ const env = { ...options.env };
1214
+ for (const key of Object.keys(env)) {
1215
+ if (key.startsWith("npm_config_"))
1216
+ delete env[key];
1217
+ }
1218
+ const child = spawn("dsh", argv, {
1219
+ cwd: options.cwd,
1220
+ env,
1221
+ detached: true,
1222
+ stdio: ["ignore", "pipe", "pipe"]
1223
+ });
1224
+ child.unref();
1225
+ for (const pipe of [child.stdout, child.stderr]) {
1226
+ pipe.unref?.();
1227
+ }
1228
+ return child;
1229
+ }, defaultHealth = (authority, cookieHeader) => checkHostHealth({ authority, cookieHeader }, defaultHealthProbes);
1230
+ var init_host_launch = __esm(() => {
1231
+ init_client_lifecycle();
1232
+ init_cookie_mint();
1233
+ init_host_health();
1234
+ init_host_port();
1235
+ init_safe_kill();
1236
+ init_host_registry();
1237
+ init_safe_kill();
1238
+ init_client_lifecycle();
1239
+ DEFAULT_LAUNCH_TIMEOUT_MS = 5 * 60000;
1240
+ LAUNCH_PHASES = ["spawn", "booting", "ready"];
1241
+ HostLaunchTimeoutError = class HostLaunchTimeoutError extends Error {
1242
+ logPath;
1243
+ code = "host-launch-timeout";
1244
+ constructor(message, logPath) {
1245
+ super(`${message}
1246
+ --- dsh host log: ${logPath} ---`);
1247
+ this.logPath = logPath;
1248
+ this.name = new.target.name;
1249
+ }
1250
+ };
1251
+ });
1252
+ init_host_launch();
1253
+
1254
+ export {
1255
+ DEFAULT_LAUNCH_PROFILE,
1256
+ DEFAULT_LAUNCH_TIMEOUT_MS,
1257
+ DEFAULT_POLL_MS,
1258
+ DEFAULT_REGISTRY_MAX_AGE_MS,
1259
+ FORCE_KILL_GRACE_MS,
1260
+ FORCE_TERM_GRACE_MS,
1261
+ ForceNeedsYesError,
1262
+ HostLaunchTimeoutError,
1263
+ LAUNCH_PHASES,
1264
+ SERVER_ENV_NAME,
1265
+ SERVER_ENV_VALUE,
1266
+ bindFreePort,
1267
+ createLaunchProgress,
1268
+ defaultDshHome,
1269
+ defaultSpawnHost,
1270
+ ensureHost,
1271
+ psKillHooks,
1272
+ readRegistry
1273
+ };
1274
+
1275
+ //# debugId=AB30F4BAA7F0C83564756E2164756E21
1276
+ //# sourceMappingURL=host-launch.mjs.map