@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8
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.
- package/LICENSE +33 -0
- package/README.en.md +103 -814
- package/README.md +102 -711
- package/cordis.patch.yml +186 -0
- package/dist/acp-preferences.d.mts +29 -0
- package/dist/acp-preferences.mjs +15 -0
- package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
- package/dist/builtins.mjs +3 -3
- package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
- package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
- package/dist/command-trust-DChWUamk.mjs +406 -0
- package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
- package/dist/daemon-launcher.d.mts +159 -0
- package/dist/daemon-launcher.mjs +2 -0
- package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
- package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
- package/dist/entry-control-DjNsE3I0.mjs +190 -0
- package/dist/extension/advanced.d.mts +1 -1
- package/dist/extension/unstable.d.mts +1 -1
- package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
- package/dist/extension-config.d.mts +29 -0
- package/dist/extension-config.mjs +22 -0
- package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
- package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
- package/dist/extensions.d.mts +2 -2
- package/dist/extensions.mjs +1 -1
- package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
- package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
- package/dist/host-runtime.d.mts +11 -5
- package/dist/host-runtime.mjs +4171 -920
- package/dist/index.d.mts +86 -174
- package/dist/index.mjs +38087 -9967
- package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
- package/dist/local-client.mjs +1158 -59
- package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
- package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
- package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
- package/dist/local-discovery-egN4_gsQ.mjs +2 -0
- package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
- package/dist/local-host.mjs +812 -89
- package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
- package/dist/local-scope-DamiMqPd.mjs +1340 -0
- package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
- package/dist/local-web-control-DMrjwCkl.mjs +454 -0
- package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
- package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
- package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
- package/dist/open-CmOBxSjN.mjs +63 -0
- package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
- package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
- package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
- package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
- package/dist/preferences.d.mts +17 -0
- package/dist/preferences.mjs +20 -0
- package/dist/preset-BcWqOtY7.mjs +46 -0
- package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
- package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
- package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
- package/dist/prompt-sections-DXmjB58H.mjs +634 -0
- package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
- package/dist/row-id-DPbyt9Nn.mjs +24 -0
- package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
- package/dist/schema-BTGYn8_X.d.mts +54 -0
- package/dist/schema-qE_P09zJ.mjs +124 -0
- package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
- package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
- package/dist/startup-CarQxWwi.d.mts +213 -0
- package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
- package/dist/startup.d.mts +2 -99
- package/dist/startup.mjs +2 -2
- package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
- package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
- package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
- package/dist/version-B9yC7bBk.mjs +83 -0
- package/dist/visual-tools.d.mts +1 -1
- package/dist/visual-tools.mjs +1 -1
- package/dist/web-preferences.d.mts +1 -1
- package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
- package/generated/dsh-presets/cordis.patch.yml +4 -2
- package/generated/dsh-presets/ptc.patch.yml +4 -0
- package/generated/dsh-presets/standard.patch.yml +7 -0
- package/generated/web-access/cordis.patch.yml +239 -0
- package/package.json +217 -170
- package/dist/entry-control-DnduyDiw.mjs +0 -92
- package/dist/local-discovery-C9VMjc0K.mjs +0 -759
- package/dist/local-discovery-CDaQHA_R.mjs +0 -2
- package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
- package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
- package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
- package/dist/version-a-eF-QER.mjs +0 -80
|
@@ -0,0 +1,1932 @@
|
|
|
1
|
+
import { n as runSyncDisposalStepsWithPrimary } from "./disposal-BYBbEpVY.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, statSync, writeSync } from "node:fs";
|
|
4
|
+
import { constants as constants$1, userInfo } from "node:os";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
import { createServer } from "node:net";
|
|
10
|
+
import { Buffer as Buffer$1 } from "node:buffer";
|
|
11
|
+
/** `<sys/proc_info.h>`: PROC_PIDTBSDINFO. */
|
|
12
|
+
const PROC_PIDTBSDINFO_FLAVOR = 3;
|
|
13
|
+
/** XNU's private flavor 17 (PROC_PIDUNIQIDENTIFIERINFO), not in the public SDK. */
|
|
14
|
+
const PROC_PIDUNIQIDENTIFIER_FLAVOR = 17;
|
|
15
|
+
const LIBPROC = "/usr/lib/libproc.dylib";
|
|
16
|
+
const LIBSYSTEM = "/usr/lib/libSystem.B.dylib";
|
|
17
|
+
const ESRCH = 3;
|
|
18
|
+
const EPERM = 1;
|
|
19
|
+
const EACCES = 13;
|
|
20
|
+
const EINVAL = 22;
|
|
21
|
+
/** `kern.bootsessionuuid` capacity — the UUID text is 36 bytes plus NUL. */
|
|
22
|
+
const BOOT_UUID_CAPACITY = 128;
|
|
23
|
+
/**
|
|
24
|
+
* Classify one libproc read outcome into this repository's observation
|
|
25
|
+
* taxonomy. `expectedBytes` is the ABI struct size this build was written for;
|
|
26
|
+
* `actualBytes` is what the kernel reported. A positive-but-different reply is
|
|
27
|
+
* an ABI mismatch even when the kernel also set an errno: the reply must never
|
|
28
|
+
* be truncated or reinterpreted.
|
|
29
|
+
*/
|
|
30
|
+
function classifyDarwinReadOutcome(expectedBytes, actualBytes, errno) {
|
|
31
|
+
if (actualBytes === expectedBytes && expectedBytes > 0) return { kind: "ok" };
|
|
32
|
+
if (actualBytes > 0) return {
|
|
33
|
+
kind: "unknown",
|
|
34
|
+
code: "ABI_UNSUPPORTED"
|
|
35
|
+
};
|
|
36
|
+
if (errno === ESRCH) return { kind: "gone" };
|
|
37
|
+
if (errno === EPERM || errno === EACCES) return {
|
|
38
|
+
kind: "unknown",
|
|
39
|
+
code: "ACCESS_DENIED"
|
|
40
|
+
};
|
|
41
|
+
if (errno === EINVAL) return {
|
|
42
|
+
kind: "unknown",
|
|
43
|
+
code: "ABI_UNSUPPORTED"
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
kind: "unknown",
|
|
47
|
+
code: "READ_FAILED"
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** A 64-bit kernel counter as an exact decimal string (Koffi yields a BigInt
|
|
51
|
+
* only when the value would lose precision as a JS number). */
|
|
52
|
+
function decimal(value) {
|
|
53
|
+
if (typeof value === "bigint") return value.toString(10);
|
|
54
|
+
if (typeof value === "number" && Number.isSafeInteger(value)) return String(value);
|
|
55
|
+
throw new Error(`expected an exact 64-bit integer, got ${String(value)}`);
|
|
56
|
+
}
|
|
57
|
+
let loaded;
|
|
58
|
+
/** One installed `@deepseek-ai/dsh` manifest, or undefined when the path is
|
|
59
|
+
* unreadable, malformed, or belongs to another package. The name check is
|
|
60
|
+
* load-bearing: `createRequire` would otherwise walk into an unrelated ancestor
|
|
61
|
+
* `node_modules` and silently borrow a Koffi copy that does not belong to the
|
|
62
|
+
* running DSH installation. */
|
|
63
|
+
function installedDshManifest(path) {
|
|
64
|
+
try {
|
|
65
|
+
const real = realpathSync(path);
|
|
66
|
+
const manifest = JSON.parse(readFileSync(real, "utf8"));
|
|
67
|
+
if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) return void 0;
|
|
68
|
+
const record = manifest;
|
|
69
|
+
return record.name === "@deepseek-ai/dsh" && typeof record.version === "string" && record.version !== "" ? real : void 0;
|
|
70
|
+
} catch {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The installed `@deepseek-ai/dsh/package.json` this process runs on.
|
|
76
|
+
*
|
|
77
|
+
* A real Direct launcher entry (`process.argv[1]`) identifies its own installed
|
|
78
|
+
* DSH package and always wins over an inherited environment anchor: a shell or
|
|
79
|
+
* tool child of a Split Host inherits SPLIT_PROCESS_DSH_ANCHOR, but a Direct
|
|
80
|
+
* `dsh` CLI started from it must use the installation executing that CLI.
|
|
81
|
+
* Only a Split Host/Client entry, whose argv[1] is the product's own
|
|
82
|
+
* local-host/local-client script, falls back to the launcher-verified
|
|
83
|
+
* SPLIT_PROCESS_DSH_ANCHOR. No NODE_PATH, profile node_modules or source tree
|
|
84
|
+
* is consulted.
|
|
85
|
+
*/
|
|
86
|
+
function installedDshAnchor() {
|
|
87
|
+
const entry = process.argv[1];
|
|
88
|
+
if (entry !== void 0) try {
|
|
89
|
+
let dir = dirname(realpathSync(entry));
|
|
90
|
+
for (let depth = 0; depth < 8; depth += 1) {
|
|
91
|
+
const anchor = installedDshManifest(join(dir, "package.json"));
|
|
92
|
+
if (anchor !== void 0) return anchor;
|
|
93
|
+
const parent = dirname(dir);
|
|
94
|
+
if (parent === dir) break;
|
|
95
|
+
dir = parent;
|
|
96
|
+
}
|
|
97
|
+
} catch {}
|
|
98
|
+
const provided = process.env.SPLIT_PROCESS_DSH_ANCHOR;
|
|
99
|
+
return provided !== void 0 && provided !== "" ? installedDshManifest(provided) : void 0;
|
|
100
|
+
}
|
|
101
|
+
/** The nearest `node_modules` directory above a package directory. */
|
|
102
|
+
function nearestModuleRoot(packageDir) {
|
|
103
|
+
for (let dir = packageDir;; dir = dirname(dir)) {
|
|
104
|
+
if (basename(dir) === "node_modules") return dir;
|
|
105
|
+
const parent = dirname(dir);
|
|
106
|
+
if (parent === dir) return void 0;
|
|
107
|
+
dir = parent;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function isInside(path, root) {
|
|
111
|
+
return path === root || path.startsWith(`${root}${sep}`);
|
|
112
|
+
}
|
|
113
|
+
/** Prove a resolved dependency belongs to its owner's installation closure.
|
|
114
|
+
*
|
|
115
|
+
* npm keeps sibling dependencies in the owner's nearest `node_modules`. pnpm
|
|
116
|
+
* keeps every package in a shared virtual store (`.mise` in the mise install
|
|
117
|
+
* and `.pnpm` in a project install), with each package in its own
|
|
118
|
+
* `<name>@<version>/node_modules` directory. Any other ancestor `node_modules`
|
|
119
|
+
* is an accidental hoist and must not supply a dependency. */
|
|
120
|
+
function assertInstallClosure(ownerDir, dependencyDir, label) {
|
|
121
|
+
const nearest = nearestModuleRoot(ownerDir);
|
|
122
|
+
if (nearest !== void 0 && isInside(dependencyDir, nearest)) return;
|
|
123
|
+
for (let dir = ownerDir;; dir = dirname(dir)) {
|
|
124
|
+
if ((basename(dir) === ".mise" || basename(dir) === ".pnpm") && isInside(dependencyDir, dir)) return;
|
|
125
|
+
const parent = dirname(dir);
|
|
126
|
+
if (parent === dir) break;
|
|
127
|
+
dir = parent;
|
|
128
|
+
}
|
|
129
|
+
throw new Error(`native process identity: ${label} resolved outside the installed DSH module tree`);
|
|
130
|
+
}
|
|
131
|
+
/** Read one JSON package manifest as an object, or undefined when unreadable. */
|
|
132
|
+
function readManifestObject(path) {
|
|
133
|
+
try {
|
|
134
|
+
const manifest = JSON.parse(readFileSync(realpathSync(path), "utf8"));
|
|
135
|
+
if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) return void 0;
|
|
136
|
+
return manifest;
|
|
137
|
+
} catch {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/** Require one dependency declaration from an owner manifest. */
|
|
142
|
+
function assertDeclaredDependency(manifest, name, label) {
|
|
143
|
+
const dependencies = manifest.dependencies;
|
|
144
|
+
const declared = dependencies !== null && typeof dependencies === "object" && !Array.isArray(dependencies) ? dependencies[name] : void 0;
|
|
145
|
+
if (typeof declared !== "string" || declared === "") throw new Error(`native process identity: ${label} does not declare ${name}`);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Resolve the Koffi entry owned by the running DSH installation:
|
|
149
|
+
* DSH anchor -> `@deepseek-ai/dsh-subprocess-local` manifest -> that package's
|
|
150
|
+
* own `koffi` dependency. The TUI never resolves Koffi from its own package, a
|
|
151
|
+
* profile, or an ambient module path.
|
|
152
|
+
*
|
|
153
|
+
* The owner's declared dependency selects the implementation; this code does
|
|
154
|
+
* not pin or compare a Koffi version, because the running DSH installation owns
|
|
155
|
+
* that choice and an upgrade must not be rejected only for a different version
|
|
156
|
+
* number. The ABI/struct-size checks in loadBridge decide actual compatibility.
|
|
157
|
+
*/
|
|
158
|
+
function resolveDshKoffi(anchor) {
|
|
159
|
+
const manifest = installedDshManifest(anchor);
|
|
160
|
+
if (manifest === void 0) throw new Error("native process identity: the DSH anchor is not an installed @deepseek-ai/dsh manifest");
|
|
161
|
+
const dshDir = dirname(manifest);
|
|
162
|
+
const subprocessManifest = realpathSync(createRequire(manifest).resolve("@deepseek-ai/dsh-subprocess-local/package.json"));
|
|
163
|
+
const subprocessDir = dirname(subprocessManifest);
|
|
164
|
+
assertInstallClosure(dshDir, subprocessDir, "@deepseek-ai/dsh-subprocess-local");
|
|
165
|
+
const subprocess = readManifestObject(subprocessManifest);
|
|
166
|
+
if (subprocess?.name !== "@deepseek-ai/dsh-subprocess-local") throw new Error("native process identity: the resolved subprocess manifest is not @deepseek-ai/dsh-subprocess-local");
|
|
167
|
+
assertDeclaredDependency(subprocess, "koffi", "@deepseek-ai/dsh-subprocess-local");
|
|
168
|
+
const koffiEntry = realpathSync(createRequire(subprocessManifest).resolve("koffi"));
|
|
169
|
+
assertInstallClosure(subprocessDir, dirname(koffiEntry), "koffi");
|
|
170
|
+
if (readManifestObject(join(dirname(koffiEntry), "package.json"))?.name !== "koffi") throw new Error("native process identity: the resolved koffi is not the koffi package");
|
|
171
|
+
return koffiEntry;
|
|
172
|
+
}
|
|
173
|
+
/** Load and ABI-check the Darwin bridge once per process. The loader itself
|
|
174
|
+
* never throws: an unavailable dylib/addon or an unexpected struct size is a
|
|
175
|
+
* classified observation, and the caller fails closed. */
|
|
176
|
+
function loadBridge() {
|
|
177
|
+
if (loaded !== void 0) return loaded;
|
|
178
|
+
let result;
|
|
179
|
+
try {
|
|
180
|
+
const anchor = installedDshAnchor();
|
|
181
|
+
if (anchor === void 0) throw new Error("native process identity: no installed DSH anchor");
|
|
182
|
+
const koffi = createRequire(import.meta.url)(resolveDshKoffi(anchor));
|
|
183
|
+
const libproc = koffi.load(LIBPROC);
|
|
184
|
+
const libsystem = koffi.load(LIBSYSTEM);
|
|
185
|
+
const bsdInfo = koffi.struct({
|
|
186
|
+
pbi_flags: "uint32",
|
|
187
|
+
pbi_status: "uint32",
|
|
188
|
+
pbi_xstatus: "uint32",
|
|
189
|
+
pbi_pid: "uint32",
|
|
190
|
+
pbi_ppid: "uint32",
|
|
191
|
+
pbi_uid: "uint32",
|
|
192
|
+
pbi_gid: "uint32",
|
|
193
|
+
pbi_ruid: "uint32",
|
|
194
|
+
pbi_rgid: "uint32",
|
|
195
|
+
pbi_svuid: "uint32",
|
|
196
|
+
pbi_svgid: "uint32",
|
|
197
|
+
rfu_1: "uint32",
|
|
198
|
+
pbi_comm: koffi.array("uint8", 16),
|
|
199
|
+
pbi_name: koffi.array("uint8", 32),
|
|
200
|
+
pbi_nfiles: "uint32",
|
|
201
|
+
pbi_pgid: "uint32",
|
|
202
|
+
pbi_pjobc: "uint32",
|
|
203
|
+
e_tdev: "uint32",
|
|
204
|
+
e_tpgid: "uint32",
|
|
205
|
+
pbi_nice: "int32",
|
|
206
|
+
pbi_start_tvsec: "uint64",
|
|
207
|
+
pbi_start_tvusec: "uint64"
|
|
208
|
+
});
|
|
209
|
+
const uniqueInfo = koffi.struct({
|
|
210
|
+
p_uuid: koffi.array("uint8", 16),
|
|
211
|
+
p_uniqueid: "uint64",
|
|
212
|
+
p_puniqueid: "uint64",
|
|
213
|
+
p_reserve: koffi.array("int32", 6)
|
|
214
|
+
});
|
|
215
|
+
if (koffi.sizeof(bsdInfo) !== 136 || koffi.sizeof(uniqueInfo) !== 56) result = {
|
|
216
|
+
ok: false,
|
|
217
|
+
code: "ABI_UNSUPPORTED"
|
|
218
|
+
};
|
|
219
|
+
else result = {
|
|
220
|
+
ok: true,
|
|
221
|
+
bridge: {
|
|
222
|
+
koffi,
|
|
223
|
+
procPidinfoBsd: libproc.func("proc_pidinfo", "int", [
|
|
224
|
+
"int",
|
|
225
|
+
"int",
|
|
226
|
+
"uint64",
|
|
227
|
+
koffi.out(koffi.pointer(bsdInfo)),
|
|
228
|
+
"int"
|
|
229
|
+
]),
|
|
230
|
+
procPidinfoUniq: libproc.func("proc_pidinfo", "int", [
|
|
231
|
+
"int",
|
|
232
|
+
"int",
|
|
233
|
+
"uint64",
|
|
234
|
+
koffi.out(koffi.pointer(uniqueInfo)),
|
|
235
|
+
"int"
|
|
236
|
+
]),
|
|
237
|
+
procListPgrpPids: libproc.func("proc_listpgrppids", "int", [
|
|
238
|
+
"int",
|
|
239
|
+
"void *",
|
|
240
|
+
"int"
|
|
241
|
+
]),
|
|
242
|
+
sysctlByName: libsystem.func("sysctlbyname", "int", [
|
|
243
|
+
"const char *",
|
|
244
|
+
"void *",
|
|
245
|
+
koffi.inout(koffi.pointer(koffi.types.size_t)),
|
|
246
|
+
"void *",
|
|
247
|
+
"size_t"
|
|
248
|
+
]),
|
|
249
|
+
getsid: libsystem.func("getsid", "int", ["int"])
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
} catch {
|
|
253
|
+
result = {
|
|
254
|
+
ok: false,
|
|
255
|
+
code: "NATIVE_UNAVAILABLE"
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
loaded = result;
|
|
259
|
+
return result;
|
|
260
|
+
}
|
|
261
|
+
/** One libproc read, classified. `read` returns the kernel byte count. */
|
|
262
|
+
function readRecord(expectedBytes, read, decode) {
|
|
263
|
+
const load = loadBridge();
|
|
264
|
+
if (!load.ok) return {
|
|
265
|
+
kind: "unknown",
|
|
266
|
+
code: load.code
|
|
267
|
+
};
|
|
268
|
+
const out = {};
|
|
269
|
+
let actual;
|
|
270
|
+
try {
|
|
271
|
+
actual = read(out, load.bridge);
|
|
272
|
+
} catch {
|
|
273
|
+
return {
|
|
274
|
+
kind: "unknown",
|
|
275
|
+
code: "READ_FAILED"
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
const classified = classifyDarwinReadOutcome(expectedBytes, actual, load.bridge.koffi.errno());
|
|
279
|
+
if (classified.kind !== "ok") return classified;
|
|
280
|
+
try {
|
|
281
|
+
return {
|
|
282
|
+
kind: "ok",
|
|
283
|
+
value: decode(out)
|
|
284
|
+
};
|
|
285
|
+
} catch {
|
|
286
|
+
return {
|
|
287
|
+
kind: "unknown",
|
|
288
|
+
code: "ABI_UNSUPPORTED"
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function integerField(out, name) {
|
|
293
|
+
const value = out[name];
|
|
294
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new Error(`${name} is not an integer`);
|
|
295
|
+
return value;
|
|
296
|
+
}
|
|
297
|
+
/** `proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, ...)` decoded. */
|
|
298
|
+
function readDarwinBsdInfo(pid) {
|
|
299
|
+
return readRecord(136, (out, bridge) => bridge.procPidinfoBsd(pid, PROC_PIDTBSDINFO_FLAVOR, 0, out, 136), (out) => {
|
|
300
|
+
const observedPid = integerField(out, "pbi_pid");
|
|
301
|
+
if (observedPid !== pid) throw new Error("proc_pidinfo returned another pid");
|
|
302
|
+
return {
|
|
303
|
+
pid: observedPid,
|
|
304
|
+
ppid: integerField(out, "pbi_ppid"),
|
|
305
|
+
pgid: integerField(out, "pbi_pgid"),
|
|
306
|
+
uid: integerField(out, "pbi_uid"),
|
|
307
|
+
status: integerField(out, "pbi_status"),
|
|
308
|
+
startSec: decimal(out["pbi_start_tvsec"]),
|
|
309
|
+
startUsec: decimal(out["pbi_start_tvusec"])
|
|
310
|
+
};
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
/** `proc_pidinfo(pid, flavor 17, 0, ...)` decoded. */
|
|
314
|
+
function readDarwinUniqueInfo(pid) {
|
|
315
|
+
return readRecord(56, (out, bridge) => bridge.procPidinfoUniq(pid, PROC_PIDUNIQIDENTIFIER_FLAVOR, 0, out, 56), (out) => {
|
|
316
|
+
const uuid = out["p_uuid"];
|
|
317
|
+
if (!(uuid instanceof Uint8Array) || uuid.length !== 16) throw new Error("p_uuid is not 16 bytes");
|
|
318
|
+
return {
|
|
319
|
+
uniqueId: decimal(out["p_uniqueid"]),
|
|
320
|
+
parentUniqueId: decimal(out["p_puniqueid"]),
|
|
321
|
+
processUuid: [...uuid].map((byte) => byte.toString(16).padStart(2, "0")).join("")
|
|
322
|
+
};
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
/** `sysctlbyname("kern.bootsessionuuid")` decoded. */
|
|
326
|
+
function readDarwinBootSessionUuid() {
|
|
327
|
+
const load = loadBridge();
|
|
328
|
+
if (!load.ok) return {
|
|
329
|
+
kind: "unknown",
|
|
330
|
+
code: load.code
|
|
331
|
+
};
|
|
332
|
+
const bytes = Buffer.alloc(BOOT_UUID_CAPACITY);
|
|
333
|
+
const length = [BOOT_UUID_CAPACITY];
|
|
334
|
+
let rc;
|
|
335
|
+
try {
|
|
336
|
+
rc = load.bridge.sysctlByName("kern.bootsessionuuid", bytes, length, null, 0);
|
|
337
|
+
} catch {
|
|
338
|
+
return {
|
|
339
|
+
kind: "unknown",
|
|
340
|
+
code: "READ_FAILED"
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
if (rc !== 0) return classifySysctlFailure(load.bridge.koffi.errno());
|
|
344
|
+
const used = length[0];
|
|
345
|
+
if (typeof used !== "number" || used < 2 || used > BOOT_UUID_CAPACITY || bytes[used - 1] !== 0) return {
|
|
346
|
+
kind: "unknown",
|
|
347
|
+
code: "READ_FAILED"
|
|
348
|
+
};
|
|
349
|
+
const value = bytes.toString("utf8", 0, used - 1);
|
|
350
|
+
if (!/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/iu.test(value)) return {
|
|
351
|
+
kind: "unknown",
|
|
352
|
+
code: "READ_FAILED"
|
|
353
|
+
};
|
|
354
|
+
return {
|
|
355
|
+
kind: "ok",
|
|
356
|
+
value
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
function classifySysctlFailure(errno) {
|
|
360
|
+
if (errno === EPERM || errno === EACCES) return {
|
|
361
|
+
kind: "unknown",
|
|
362
|
+
code: "ACCESS_DENIED"
|
|
363
|
+
};
|
|
364
|
+
if (errno === EINVAL) return {
|
|
365
|
+
kind: "unknown",
|
|
366
|
+
code: "ABI_UNSUPPORTED"
|
|
367
|
+
};
|
|
368
|
+
return {
|
|
369
|
+
kind: "unknown",
|
|
370
|
+
code: "READ_FAILED"
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** `getsid(pid)`: the kernel session id of one process. */
|
|
374
|
+
function readDarwinSessionId(pid) {
|
|
375
|
+
const load = loadBridge();
|
|
376
|
+
if (!load.ok) return {
|
|
377
|
+
kind: "unknown",
|
|
378
|
+
code: load.code
|
|
379
|
+
};
|
|
380
|
+
let sid;
|
|
381
|
+
try {
|
|
382
|
+
sid = load.bridge.getsid(pid);
|
|
383
|
+
} catch {
|
|
384
|
+
return {
|
|
385
|
+
kind: "unknown",
|
|
386
|
+
code: "READ_FAILED"
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
if (sid > 0) return {
|
|
390
|
+
kind: "ok",
|
|
391
|
+
value: sid
|
|
392
|
+
};
|
|
393
|
+
const errno = load.bridge.koffi.errno();
|
|
394
|
+
if (errno === ESRCH) return { kind: "gone" };
|
|
395
|
+
if (errno === EPERM || errno === EACCES) return {
|
|
396
|
+
kind: "unknown",
|
|
397
|
+
code: "ACCESS_DENIED"
|
|
398
|
+
};
|
|
399
|
+
return {
|
|
400
|
+
kind: "unknown",
|
|
401
|
+
code: "READ_FAILED"
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* `proc_listpgrppids(pgid)`: the pids currently in one process group. The
|
|
406
|
+
* buffer grows until the kernel reports it fits; a negative reply is a
|
|
407
|
+
* classified read failure, never an empty group.
|
|
408
|
+
*/
|
|
409
|
+
function listDarwinProcessGroupPids(pgid) {
|
|
410
|
+
const load = loadBridge();
|
|
411
|
+
if (!load.ok) return {
|
|
412
|
+
kind: "unknown",
|
|
413
|
+
code: load.code
|
|
414
|
+
};
|
|
415
|
+
let capacity = 32;
|
|
416
|
+
for (;;) {
|
|
417
|
+
const bytes = Buffer.alloc(capacity * 4);
|
|
418
|
+
let count;
|
|
419
|
+
try {
|
|
420
|
+
count = load.bridge.procListPgrpPids(pgid, bytes, bytes.length);
|
|
421
|
+
} catch {
|
|
422
|
+
return {
|
|
423
|
+
kind: "unknown",
|
|
424
|
+
code: "READ_FAILED"
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
if (count < 0) {
|
|
428
|
+
const errno = load.bridge.koffi.errno();
|
|
429
|
+
if (errno === EPERM || errno === EACCES) return {
|
|
430
|
+
kind: "unknown",
|
|
431
|
+
code: "ACCESS_DENIED"
|
|
432
|
+
};
|
|
433
|
+
if (errno === ESRCH) return { kind: "gone" };
|
|
434
|
+
return {
|
|
435
|
+
kind: "unknown",
|
|
436
|
+
code: "READ_FAILED"
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
const pids = [];
|
|
440
|
+
for (let index = 0; index < Math.min(count, capacity); index += 1) {
|
|
441
|
+
const pid = bytes.readInt32LE(index * 4);
|
|
442
|
+
if (pid > 0) pids.push(pid);
|
|
443
|
+
}
|
|
444
|
+
if (count < capacity) return {
|
|
445
|
+
kind: "ok",
|
|
446
|
+
value: pids
|
|
447
|
+
};
|
|
448
|
+
capacity *= 2;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
//#endregion
|
|
452
|
+
//#region src/runtime/native-process/identity.ts
|
|
453
|
+
/**
|
|
454
|
+
* Kernel process identity and process-group membership: the single OS seam for
|
|
455
|
+
* "is this numeric pid still the process we captured?".
|
|
456
|
+
*
|
|
457
|
+
* Every consumer that signals a process group must prove ownership first:
|
|
458
|
+
* the footer command runner's TERM->SIGKILL escalation, the owned-process-group
|
|
459
|
+
* teardown used by the test runners, and (later) the Host scope/seat layer.
|
|
460
|
+
* This module answers that one question per platform and keeps NO state: every
|
|
461
|
+
* observation is a fresh kernel read.
|
|
462
|
+
*
|
|
463
|
+
* - Linux reads `/proc/<pid>/stat` (fields 3/4/5/6/22); a real zombie is
|
|
464
|
+
* `alive` with state `Z`, and a genuinely absent entry is `gone`.
|
|
465
|
+
* - Darwin reads libproc through the lazy native bridge (`./darwin.ts`):
|
|
466
|
+
* `proc_pidinfo` flavor 3 (136-byte `proc_bsdinfo`), the private flavor 17
|
|
467
|
+
* (56-byte `proc_uniqidentifierinfo`), `kern.bootsessionuuid` and `getsid`.
|
|
468
|
+
* Each observation is bracketed BSD -> unique -> BSD with the boot UUID on
|
|
469
|
+
* both sides; an identity that changes or disagrees mid-read is `unknown`,
|
|
470
|
+
* never `alive`. A zombie is invisible to libproc and reads as `gone`.
|
|
471
|
+
*
|
|
472
|
+
* Permission failures, an unsupported native ABI and an unstable read are all
|
|
473
|
+
* `unknown` — they never mean "dead" and never authorize a signal or a
|
|
474
|
+
* takeover. 64-bit Darwin ids are returned as exact decimal strings so no JS
|
|
475
|
+
* `Number` precision is silently lost.
|
|
476
|
+
*
|
|
477
|
+
* @module runtime/native-process/identity
|
|
478
|
+
*/
|
|
479
|
+
/**
|
|
480
|
+
* Parse the fixed positional tail of one `/proc/<pid>/stat`. The comm field may
|
|
481
|
+
* contain spaces and parentheses, so everything after the LAST ')' is the
|
|
482
|
+
* fixed tail whose first entry is field 3 (`state`); `starttime` is field 22
|
|
483
|
+
* (index 19). A tail without a single-letter state, numeric starttime or
|
|
484
|
+
* numeric ppid/pgrp/session is malformed and yields `undefined`.
|
|
485
|
+
*/
|
|
486
|
+
function parseLinuxStatFields(stat) {
|
|
487
|
+
const close = stat.lastIndexOf(")");
|
|
488
|
+
if (close < 0) return void 0;
|
|
489
|
+
const fields = stat.slice(close + 2).trim().split(/\s+/u);
|
|
490
|
+
const state = fields[0];
|
|
491
|
+
const starttime = fields[19];
|
|
492
|
+
const ppid = Number.parseInt(fields[1], 10);
|
|
493
|
+
const pgid = Number.parseInt(fields[2], 10);
|
|
494
|
+
const sid = Number.parseInt(fields[3], 10);
|
|
495
|
+
if (state === void 0 || !/^[A-Za-z]$/u.test(state)) return void 0;
|
|
496
|
+
if (starttime === void 0 || !/^\d+$/u.test(starttime)) return void 0;
|
|
497
|
+
if (!Number.isSafeInteger(ppid) || !Number.isSafeInteger(pgid) || !Number.isSafeInteger(sid)) return void 0;
|
|
498
|
+
return {
|
|
499
|
+
state,
|
|
500
|
+
starttime,
|
|
501
|
+
ppid,
|
|
502
|
+
pgid,
|
|
503
|
+
sid
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
/** Parse field 3 (`state`) and field 22 (`starttime`) from one
|
|
507
|
+
* `/proc/<pid>/stat` text (external behavior preserved from local-scope). */
|
|
508
|
+
function parseProcessStat(stat) {
|
|
509
|
+
const fields = parseLinuxStatFields(stat);
|
|
510
|
+
return fields === void 0 ? void 0 : {
|
|
511
|
+
state: fields.state,
|
|
512
|
+
starttime: fields.starttime
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
/** Parse only field 22 (`starttime`) from one `/proc/<pid>/stat`. */
|
|
516
|
+
function parseProcessStatStarttime(stat) {
|
|
517
|
+
return parseProcessStat(stat)?.starttime;
|
|
518
|
+
}
|
|
519
|
+
/** Best-effort Linux `starttime` read (undefined where `/proc` is absent). */
|
|
520
|
+
function readProcessStarttime(pid = process.pid) {
|
|
521
|
+
try {
|
|
522
|
+
return parseProcessStatStarttime(readFileSync(`/proc/${String(pid)}/stat`, "utf8"));
|
|
523
|
+
} catch {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
function linuxReadFailure(error) {
|
|
528
|
+
const code = error.code;
|
|
529
|
+
if (code === "ENOENT") return { kind: "gone" };
|
|
530
|
+
if (code === "EACCES" || code === "EPERM") return {
|
|
531
|
+
kind: "unknown",
|
|
532
|
+
code: "ACCESS_DENIED"
|
|
533
|
+
};
|
|
534
|
+
return {
|
|
535
|
+
kind: "unknown",
|
|
536
|
+
code: "READ_FAILED"
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
function readLinuxKernelProcess(pid) {
|
|
540
|
+
let stat;
|
|
541
|
+
try {
|
|
542
|
+
stat = readFileSync(`/proc/${String(pid)}/stat`, "utf8");
|
|
543
|
+
} catch (error) {
|
|
544
|
+
return linuxReadFailure(error);
|
|
545
|
+
}
|
|
546
|
+
const fields = parseLinuxStatFields(stat);
|
|
547
|
+
if (fields === void 0) return {
|
|
548
|
+
kind: "unknown",
|
|
549
|
+
code: "READ_FAILED"
|
|
550
|
+
};
|
|
551
|
+
return {
|
|
552
|
+
kind: "alive",
|
|
553
|
+
identity: {
|
|
554
|
+
platform: "linux",
|
|
555
|
+
pid,
|
|
556
|
+
startTicks: fields.starttime,
|
|
557
|
+
ppid: fields.ppid,
|
|
558
|
+
pgid: fields.pgid,
|
|
559
|
+
sid: fields.sid,
|
|
560
|
+
state: fields.state
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
/** A Darwin native result mapped onto the observation taxonomy. */
|
|
565
|
+
function darwinFailure(result) {
|
|
566
|
+
return result.kind === "gone" ? { kind: "gone" } : {
|
|
567
|
+
kind: "unknown",
|
|
568
|
+
code: result.code
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function readDarwinKernelProcess(pid) {
|
|
572
|
+
const bootBefore = readDarwinBootSessionUuid();
|
|
573
|
+
if (bootBefore.kind !== "ok") return darwinFailure(bootBefore);
|
|
574
|
+
const before = readDarwinBsdInfo(pid);
|
|
575
|
+
if (before.kind !== "ok") return darwinFailure(before);
|
|
576
|
+
const unique = readDarwinUniqueInfo(pid);
|
|
577
|
+
if (unique.kind !== "ok") return darwinFailure(unique);
|
|
578
|
+
const after = readDarwinBsdInfo(pid);
|
|
579
|
+
if (after.kind !== "ok") return darwinFailure(after);
|
|
580
|
+
const session = readDarwinSessionId(pid);
|
|
581
|
+
if (session.kind !== "ok") return darwinFailure(session);
|
|
582
|
+
const bootAfter = readDarwinBootSessionUuid();
|
|
583
|
+
if (bootAfter.kind !== "ok") return darwinFailure(bootAfter);
|
|
584
|
+
if (bootBefore.value !== bootAfter.value) return {
|
|
585
|
+
kind: "unknown",
|
|
586
|
+
code: "READ_FAILED"
|
|
587
|
+
};
|
|
588
|
+
if (before.value.startSec !== after.value.startSec || before.value.startUsec !== after.value.startUsec || before.value.ppid !== after.value.ppid || before.value.pgid !== after.value.pgid || before.value.uid !== after.value.uid) return {
|
|
589
|
+
kind: "unknown",
|
|
590
|
+
code: "READ_FAILED"
|
|
591
|
+
};
|
|
592
|
+
return {
|
|
593
|
+
kind: "alive",
|
|
594
|
+
identity: {
|
|
595
|
+
platform: "darwin",
|
|
596
|
+
pid,
|
|
597
|
+
bootUUID: bootBefore.value,
|
|
598
|
+
uniqueId: unique.value.uniqueId,
|
|
599
|
+
parentUniqueId: unique.value.parentUniqueId,
|
|
600
|
+
processUUID: unique.value.processUuid,
|
|
601
|
+
startSec: before.value.startSec,
|
|
602
|
+
startUsec: before.value.startUsec,
|
|
603
|
+
ppid: before.value.ppid,
|
|
604
|
+
pgid: before.value.pgid,
|
|
605
|
+
sid: session.value,
|
|
606
|
+
uid: before.value.uid,
|
|
607
|
+
state: before.value.status
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Read the current kernel identity of one pid. Never cached: the caller decides
|
|
613
|
+
* whether an observation is still the process it captured.
|
|
614
|
+
*/
|
|
615
|
+
function readKernelProcess(pid) {
|
|
616
|
+
if (process.platform === "linux") return readLinuxKernelProcess(pid);
|
|
617
|
+
if (process.platform === "darwin") return readDarwinKernelProcess(pid);
|
|
618
|
+
return {
|
|
619
|
+
kind: "unknown",
|
|
620
|
+
code: "NATIVE_UNAVAILABLE"
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Classify one fresh observation against the identity a caller captured
|
|
625
|
+
* earlier. `gone` and `unknown` are answers about the observation itself, not
|
|
626
|
+
* about ownership; only `same` may authorize a signal or a takeover.
|
|
627
|
+
*/
|
|
628
|
+
function sameKernelProcess(expected, observed) {
|
|
629
|
+
if (observed.kind === "unknown") return "unknown";
|
|
630
|
+
if (observed.kind === "gone") return "gone";
|
|
631
|
+
const actual = observed.identity;
|
|
632
|
+
if (actual.platform !== expected.platform || actual.pid !== expected.pid) return "different";
|
|
633
|
+
if (expected.platform === "linux" && actual.platform === "linux") return actual.startTicks === expected.startTicks ? "same" : "different";
|
|
634
|
+
if (expected.platform === "darwin" && actual.platform === "darwin") return actual.bootUUID === expected.bootUUID && actual.uniqueId === expected.uniqueId && actual.processUUID === expected.processUUID && actual.startSec === expected.startSec && actual.startUsec === expected.startUsec ? "same" : "different";
|
|
635
|
+
return "different";
|
|
636
|
+
}
|
|
637
|
+
/** Whether one identity is a member of BOTH the target process group and the
|
|
638
|
+
* session the owner created for it (`setsid`: sid === pgid). A member that
|
|
639
|
+
* changed its group/session no longer proves ownership of the captured group. */
|
|
640
|
+
function isOwnedGroupMember(identity, pgid) {
|
|
641
|
+
return identity.pgid === pgid && identity.sid === pgid;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Re-read every captured member and keep only the ones that are still the SAME
|
|
645
|
+
* process and still inside the owned group+session. This second pass is what
|
|
646
|
+
* turns a snapshot into an authorization witness: a pid that exited, was
|
|
647
|
+
* reused, or left the group is dropped. Any unverifiable read makes the whole
|
|
648
|
+
* scan `unknown` — an empty result is never derived from "we could not see".
|
|
649
|
+
*/
|
|
650
|
+
function verifyCapturedMembers(captured, pgid) {
|
|
651
|
+
const verified = [];
|
|
652
|
+
for (const observation of captured) {
|
|
653
|
+
if (observation.kind !== "alive") continue;
|
|
654
|
+
const current = readKernelProcess(observation.identity.pid);
|
|
655
|
+
if (current.kind === "unknown") return current;
|
|
656
|
+
if (current.kind === "gone" || !isOwnedGroupMember(current.identity, pgid)) continue;
|
|
657
|
+
if (sameKernelProcess(observation.identity, current) === "same") verified.push(current);
|
|
658
|
+
}
|
|
659
|
+
return verified;
|
|
660
|
+
}
|
|
661
|
+
function listLinuxKernelGroupMembers(pgid) {
|
|
662
|
+
let entries;
|
|
663
|
+
try {
|
|
664
|
+
entries = readdirSync("/proc");
|
|
665
|
+
} catch (error) {
|
|
666
|
+
const code = error.code;
|
|
667
|
+
return {
|
|
668
|
+
kind: "unknown",
|
|
669
|
+
code: code === "EACCES" || code === "EPERM" ? "ACCESS_DENIED" : "READ_FAILED"
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
const captured = [];
|
|
673
|
+
for (const entry of entries) {
|
|
674
|
+
if (!/^\d+$/u.test(entry)) continue;
|
|
675
|
+
const observation = readLinuxKernelProcess(Number(entry));
|
|
676
|
+
if (observation.kind === "unknown") return observation;
|
|
677
|
+
if (observation.kind === "gone" || !isOwnedGroupMember(observation.identity, pgid)) continue;
|
|
678
|
+
captured.push(observation);
|
|
679
|
+
}
|
|
680
|
+
return verifyCapturedMembers(captured, pgid);
|
|
681
|
+
}
|
|
682
|
+
function listDarwinKernelGroupMembers(pgid) {
|
|
683
|
+
const listed = listDarwinProcessGroupPids(pgid);
|
|
684
|
+
if (listed.kind === "gone") return [];
|
|
685
|
+
if (listed.kind !== "ok") return {
|
|
686
|
+
kind: "unknown",
|
|
687
|
+
code: listed.code
|
|
688
|
+
};
|
|
689
|
+
const captured = [];
|
|
690
|
+
for (const pid of listed.value) {
|
|
691
|
+
const observation = readDarwinKernelProcess(pid);
|
|
692
|
+
if (observation.kind === "unknown") return observation;
|
|
693
|
+
if (observation.kind === "gone" || !isOwnedGroupMember(observation.identity, pgid)) continue;
|
|
694
|
+
captured.push(observation);
|
|
695
|
+
}
|
|
696
|
+
return verifyCapturedMembers(captured, pgid);
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* List the verifiable members of the process group AND session `pgid` (the
|
|
700
|
+
* owner-created `setsid` group used by every wrapper here). Only identities
|
|
701
|
+
* that are the same process in both passes and still belong to the group are
|
|
702
|
+
* returned; a suspicious read makes the WHOLE scan `unknown` so no caller can
|
|
703
|
+
* mistake "not scanned" for "no member".
|
|
704
|
+
*/
|
|
705
|
+
function listKernelGroupMembers(pgid) {
|
|
706
|
+
if (process.platform === "linux") return listLinuxKernelGroupMembers(pgid);
|
|
707
|
+
if (process.platform === "darwin") return listDarwinKernelGroupMembers(pgid);
|
|
708
|
+
return {
|
|
709
|
+
kind: "unknown",
|
|
710
|
+
code: "NATIVE_UNAVAILABLE"
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
//#endregion
|
|
714
|
+
//#region src/app/remote-process/local-scope.ts
|
|
715
|
+
/**
|
|
716
|
+
* Local Host/Client scope, process seats and installed-build identity.
|
|
717
|
+
*
|
|
718
|
+
* The ordinary DSH profile is the scope authority: this module derives a
|
|
719
|
+
* stable id from the canonical profile directory and the current UID, then
|
|
720
|
+
* owns the private run directory, the Host Singleton seat and the
|
|
721
|
+
* qualification-only Client seat. The installed-build fingerprint remains the
|
|
722
|
+
* Host's own publication/identity material; `LOCAL_PROTOCOL` below is the
|
|
723
|
+
* Host/Client compatibility contract and is independent of package builds.
|
|
724
|
+
*
|
|
725
|
+
* The abstract sockets are admission primitives only. No business traffic
|
|
726
|
+
* travels over them, and no PID file, registry record or `O_EXCL` marker can
|
|
727
|
+
* substitute for the kernel's exclusive bind.
|
|
728
|
+
*
|
|
729
|
+
* @module app/remote-process/local-scope
|
|
730
|
+
*/
|
|
731
|
+
/**
|
|
732
|
+
* The required local Host/Client wire contract, independent of package builds.
|
|
733
|
+
* Both sides must name exactly this value and the same DSH runtime version.
|
|
734
|
+
*
|
|
735
|
+
* `local/2` is the protocol baseline of the first Split-mode opening: a v2
|
|
736
|
+
* peer guarantees the v1 semantics plus the required
|
|
737
|
+
* `piTuiPromptPresence/syncView` Remote the prompt admission gate depends on.
|
|
738
|
+
* A different protocol is refused at connect (`HOST_PROTOCOL_INCOMPATIBLE`);
|
|
739
|
+
* two builds that both name `local/2` still interoperate across versions.
|
|
740
|
+
*/
|
|
741
|
+
const LOCAL_PROTOCOL = "dsh-pi-tui/local/2";
|
|
742
|
+
/** Private scope directory below the official DSH home. */
|
|
743
|
+
const RUN_ROOT_NAME = "run";
|
|
744
|
+
const SCOPE_ROOT_NAME = "dsh-pi-tui";
|
|
745
|
+
/** Linux abstract-socket prefixes; both names stay well below `sun_path`. The
|
|
746
|
+
* Host prefix is the singleton admission seat; the Client prefix is held by
|
|
747
|
+
* the frozen `qualification` mode only. */
|
|
748
|
+
const HOST_SEAT_PREFIX = "\0dsh-pi-tui-h-";
|
|
749
|
+
const CLIENT_SEAT_PREFIX = "\0dsh-pi-tui-c-";
|
|
750
|
+
/** A failure that carries one stable B1 classification code. */
|
|
751
|
+
var LocalScopeError = class extends Error {
|
|
752
|
+
/** Stable classification asserted by callers and the qualification lane. */
|
|
753
|
+
code;
|
|
754
|
+
constructor(code, message, cause) {
|
|
755
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
756
|
+
this.name = "LocalScopeError";
|
|
757
|
+
this.code = code;
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
Object.freeze({
|
|
761
|
+
assertCurrent: () => {},
|
|
762
|
+
close: async () => {}
|
|
763
|
+
});
|
|
764
|
+
/** Darwin numeric `open(2)` flags: O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK|
|
|
765
|
+
* O_NOFOLLOW|O_CLOEXEC = 16778022 on the qualified macOS ABI (Q0: the values
|
|
766
|
+
* come from the real SDK headers, not from a portable guess). */
|
|
767
|
+
const DARWIN_SEAT_FLAGS = 16778022;
|
|
768
|
+
/** A seat file is created 0600; an EXISTING file must already be exactly this. */
|
|
769
|
+
const DARWIN_SEAT_FILE_MODE = 384;
|
|
770
|
+
/** Fail before any runtime file is written on a platform the seat does not
|
|
771
|
+
* implement. */
|
|
772
|
+
function assertDarwin() {
|
|
773
|
+
if (process.platform !== "darwin" || typeof process.getuid !== "function") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "local scope: file-backed kernel seats require Darwin");
|
|
774
|
+
return process.getuid();
|
|
775
|
+
}
|
|
776
|
+
/** The ONE deterministic seat-file path per scope and purpose. */
|
|
777
|
+
function processSeatPath(scopeDir, scopeId, kind) {
|
|
778
|
+
return join(scopeDir, `seat-${kind}-${scopeId}.lock`);
|
|
779
|
+
}
|
|
780
|
+
/** Validate one already-claimed seat file: a real regular file, owned by this
|
|
781
|
+
* user, readable/writable by this user ONLY, with exactly one link. */
|
|
782
|
+
function assertSeatFileSafe(path, uid) {
|
|
783
|
+
let info;
|
|
784
|
+
try {
|
|
785
|
+
info = lstatSync(path);
|
|
786
|
+
} catch (error) {
|
|
787
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} is not accessible`, error);
|
|
788
|
+
}
|
|
789
|
+
if (info.isSymbolicLink()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must not be a symlink`);
|
|
790
|
+
if (!info.isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must be a regular file`);
|
|
791
|
+
if (info.uid !== uid || (info.mode & 511) !== DARWIN_SEAT_FILE_MODE) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must be owned by uid ${String(uid)} with mode 0600`);
|
|
792
|
+
if (info.nlink !== 1) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must have exactly one link`);
|
|
793
|
+
}
|
|
794
|
+
/** Validate the private 0700 directory the seat file lives in. */
|
|
795
|
+
function assertSeatDirectorySafe(dir, uid) {
|
|
796
|
+
let info;
|
|
797
|
+
try {
|
|
798
|
+
info = lstatSync(dir);
|
|
799
|
+
} catch (error) {
|
|
800
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat directory ${dir} is not accessible`, error);
|
|
801
|
+
}
|
|
802
|
+
if (info.isSymbolicLink() || !info.isDirectory() || info.uid !== uid || (info.mode & 63) !== 0) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat directory ${dir} must be a real uid-${String(uid)} directory without group/other access`);
|
|
803
|
+
return {
|
|
804
|
+
dev: info.dev,
|
|
805
|
+
ino: info.ino
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* One held Darwin kernel seat: the kernel's exclusive `O_EXLOCK` claim on one
|
|
810
|
+
* fixed inode, kept for the whole lifetime of the owning process. The FD is
|
|
811
|
+
* close-on-exec, so a spawned child never inherits the Host's claim.
|
|
812
|
+
*/
|
|
813
|
+
var DarwinKernelSeat = class {
|
|
814
|
+
fd;
|
|
815
|
+
path;
|
|
816
|
+
dir;
|
|
817
|
+
uid;
|
|
818
|
+
dirDev;
|
|
819
|
+
dirIno;
|
|
820
|
+
constructor(fd, path, dir, uid, dirIdentity) {
|
|
821
|
+
this.fd = fd;
|
|
822
|
+
this.path = path;
|
|
823
|
+
this.dir = dir;
|
|
824
|
+
this.uid = uid;
|
|
825
|
+
this.dirDev = dirIdentity.dev;
|
|
826
|
+
this.dirIno = dirIdentity.ino;
|
|
827
|
+
}
|
|
828
|
+
/** Re-prove the directory, the path and the held FD still name ONE inode
|
|
829
|
+
* owned by this user. Called right after the claim and before Ready. */
|
|
830
|
+
assertCurrent() {
|
|
831
|
+
if (this.fd === void 0) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local scope: seat ${this.path} was already closed`);
|
|
832
|
+
const directory = assertSeatDirectorySafe(this.dir, this.uid);
|
|
833
|
+
if (directory.dev !== this.dirDev || directory.ino !== this.dirIno) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat directory ${this.dir} was replaced`);
|
|
834
|
+
assertSeatFileSafe(this.path, this.uid);
|
|
835
|
+
const held = fstatSync(this.fd);
|
|
836
|
+
const pathInfo = lstatSync(this.path);
|
|
837
|
+
if (held.dev !== pathInfo.dev || held.ino !== pathInfo.ino || held.uid !== pathInfo.uid || (held.mode & 511) !== (pathInfo.mode & 511) || held.nlink !== pathInfo.nlink) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local scope: seat ${this.path} no longer matches the held inode`);
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Release the held descriptor synchronously. Idempotent: the FD is cleared
|
|
841
|
+
* FIRST, so a throwing close can never leave a stale descriptor for a second
|
|
842
|
+
* close, and an unpublished seat's rollback can run without a promise.
|
|
843
|
+
*/
|
|
844
|
+
releaseSync() {
|
|
845
|
+
const fd = this.fd;
|
|
846
|
+
if (fd === void 0) return;
|
|
847
|
+
this.fd = void 0;
|
|
848
|
+
closeSync(fd);
|
|
849
|
+
}
|
|
850
|
+
async close() {
|
|
851
|
+
this.releaseSync();
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
/** Claim one Darwin seat file. `EAGAIN`/`EWOULDBLOCK` means another process of
|
|
855
|
+
* this scope already holds this purpose; every other open failure is real and
|
|
856
|
+
* is reported as-is (never re-labelled "already owned"). */
|
|
857
|
+
async function bindDarwinKernelSeat(scopeDir, scopeId, kind, conflictCode) {
|
|
858
|
+
const uid = assertDarwin();
|
|
859
|
+
const dirIdentity = assertSeatDirectorySafe(scopeDir, uid);
|
|
860
|
+
const path = processSeatPath(scopeDir, scopeId, kind);
|
|
861
|
+
let existing = true;
|
|
862
|
+
try {
|
|
863
|
+
lstatSync(path);
|
|
864
|
+
} catch (error) {
|
|
865
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} is not accessible`, error);
|
|
866
|
+
existing = false;
|
|
867
|
+
}
|
|
868
|
+
if (existing) assertSeatFileSafe(path, uid);
|
|
869
|
+
let fd;
|
|
870
|
+
try {
|
|
871
|
+
fd = openSync(path, DARWIN_SEAT_FLAGS, DARWIN_SEAT_FILE_MODE);
|
|
872
|
+
} catch (error) {
|
|
873
|
+
const code = error.code;
|
|
874
|
+
if (code === "EAGAIN" || code === "EWOULDBLOCK") throw new LocalScopeError(conflictCode, `local scope: the ${kind} seat of this profile is already held by another live process`, error);
|
|
875
|
+
throw error;
|
|
876
|
+
}
|
|
877
|
+
const seat = new DarwinKernelSeat(fd, path, scopeDir, uid, dirIdentity);
|
|
878
|
+
try {
|
|
879
|
+
seat.assertCurrent();
|
|
880
|
+
} catch (error) {
|
|
881
|
+
runSyncDisposalStepsWithPrimary("release unproven Darwin seat", error, [() => seat.releaseSync()]);
|
|
882
|
+
}
|
|
883
|
+
return seat;
|
|
884
|
+
}
|
|
885
|
+
/** Fail before any runtime file is written on a platform B1 does not implement. */
|
|
886
|
+
function assertLinux() {
|
|
887
|
+
if (process.platform !== "linux" || typeof process.getuid !== "function") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "local B1 split process requires Linux abstract AF_UNIX sockets");
|
|
888
|
+
return process.getuid();
|
|
889
|
+
}
|
|
890
|
+
/** The profile scope itself is OS-neutral POSIX state: the canonical official
|
|
891
|
+
* DSH home/profile directory object plus the current UID. Linux and Darwin
|
|
892
|
+
* both derive the same hash domain and private 0700 run directory; only the
|
|
893
|
+
* kernel CLAIM below differs per platform. */
|
|
894
|
+
function assertSupportedPosixScopePlatform() {
|
|
895
|
+
if (process.platform !== "linux" && process.platform !== "darwin" || typeof process.getuid !== "function") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", `local scope: the local split backend requires Linux or macOS (this is ${process.platform})`);
|
|
896
|
+
return process.getuid();
|
|
897
|
+
}
|
|
898
|
+
/** Read a real directory and reject a non-directory or a different owner. */
|
|
899
|
+
function canonicalOwnedDirectory(path, uid, label) {
|
|
900
|
+
let real;
|
|
901
|
+
try {
|
|
902
|
+
real = realpathSync(path);
|
|
903
|
+
} catch (error) {
|
|
904
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a readable directory`, error);
|
|
905
|
+
}
|
|
906
|
+
const info = lstatSync(real);
|
|
907
|
+
if (!info.isDirectory() || info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} must be a real directory owned by uid ${String(uid)}`);
|
|
908
|
+
return real;
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* Resolve an official caller-given directory (DSH home, profile directory) and
|
|
912
|
+
* prove it is accessible and a directory. The user's install layout (owner,
|
|
913
|
+
* mode, legal directory symlink) is not judged here; the path itself comes from
|
|
914
|
+
* the official profile resolution, never from a guess.
|
|
915
|
+
*/
|
|
916
|
+
function canonicalDirectory(path, label) {
|
|
917
|
+
let real;
|
|
918
|
+
try {
|
|
919
|
+
real = realpathSync(path);
|
|
920
|
+
} catch (error) {
|
|
921
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a readable directory`, error);
|
|
922
|
+
}
|
|
923
|
+
if (!statSync(real).isDirectory()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a directory`);
|
|
924
|
+
return real;
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Create and prove one directory component WITHOUT following a pre-existing
|
|
928
|
+
* symlink. Each component is lstat-checked before its child is created. A
|
|
929
|
+
* `privateMode` component must have no group/other access at all (0700); an
|
|
930
|
+
* inherited account-level parent may be readable but never group/other
|
|
931
|
+
* writable, because only its owner may create the private chain below it.
|
|
932
|
+
*/
|
|
933
|
+
function ensureOwnedDirectory(path, uid, privateMode) {
|
|
934
|
+
let info;
|
|
935
|
+
try {
|
|
936
|
+
info = lstatSync(path);
|
|
937
|
+
} catch (error) {
|
|
938
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible`, error);
|
|
939
|
+
try {
|
|
940
|
+
mkdirSync(path, { mode: 448 });
|
|
941
|
+
} catch (mkdirError) {
|
|
942
|
+
if (mkdirError.code !== "EEXIST") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} could not be created safely`, mkdirError);
|
|
943
|
+
}
|
|
944
|
+
try {
|
|
945
|
+
info = lstatSync(path);
|
|
946
|
+
} catch (lstatError) {
|
|
947
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible after creation`, lstatError);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (info.isSymbolicLink() || !info.isDirectory() || info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} must be a real directory owned by uid ${String(uid)}`);
|
|
951
|
+
const forbiddenMode = privateMode ? 63 : 18;
|
|
952
|
+
if ((info.mode & forbiddenMode) !== 0) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", privateMode ? `local scope: ${path} must not be readable or writable by group/other` : `local scope: ${path} must not be writable by group/other`);
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Create and prove the private run chain. On Linux a component missing from the
|
|
956
|
+
* user's existing layout is created 0700 and an existing component is accepted
|
|
957
|
+
* as a real directory or a resolvable directory symlink regardless of
|
|
958
|
+
* owner/mode (D0 keeps the user's install layout); it is never chmodded. On
|
|
959
|
+
* Darwin the stricter owned chain is required. Only an inaccessible path, a
|
|
960
|
+
* non-directory, or a real filesystem failure is refused. A concurrent first
|
|
961
|
+
* start may win the mkdir with EEXIST; that normal kernel-seat race re-reads
|
|
962
|
+
* the winner.
|
|
963
|
+
*/
|
|
964
|
+
function ensureScopeDirectory(dshHome, scopeId, uid) {
|
|
965
|
+
const runRoot = join(dshHome, RUN_ROOT_NAME);
|
|
966
|
+
const scopeRoot = join(runRoot, SCOPE_ROOT_NAME);
|
|
967
|
+
const dir = join(scopeRoot, scopeId);
|
|
968
|
+
if (process.platform === "darwin") {
|
|
969
|
+
const owner = uid ?? assertDarwin();
|
|
970
|
+
for (const path of [
|
|
971
|
+
runRoot,
|
|
972
|
+
scopeRoot,
|
|
973
|
+
dir
|
|
974
|
+
]) ensureOwnedDirectory(path, owner, true);
|
|
975
|
+
return dir;
|
|
976
|
+
}
|
|
977
|
+
for (const path of [
|
|
978
|
+
runRoot,
|
|
979
|
+
scopeRoot,
|
|
980
|
+
dir
|
|
981
|
+
]) {
|
|
982
|
+
let real;
|
|
983
|
+
try {
|
|
984
|
+
real = realpathSync(path);
|
|
985
|
+
} catch (error) {
|
|
986
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible`, error);
|
|
987
|
+
try {
|
|
988
|
+
mkdirSync(path, { mode: 448 });
|
|
989
|
+
} catch (mkdirError) {
|
|
990
|
+
if (mkdirError.code !== "EEXIST") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} could not be created safely`, mkdirError);
|
|
991
|
+
}
|
|
992
|
+
try {
|
|
993
|
+
real = realpathSync(path);
|
|
994
|
+
} catch (realpathError) {
|
|
995
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible after creation`, realpathError);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (!statSync(real).isDirectory()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not a directory`);
|
|
999
|
+
}
|
|
1000
|
+
return dir;
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* The per-UID Darwin Host seat directory. The local Host singleton must not
|
|
1004
|
+
* depend on which DSH_HOME resolved the profile, so the Host seat lives under
|
|
1005
|
+
* the OS ACCOUNT home (`os.userInfo().homedir`, never `$HOME`/`DSH_HOME`/
|
|
1006
|
+
* `$TMPDIR`), keyed only by the scope id. The qualification-only Client seat
|
|
1007
|
+
* remains in the per-DSH-home scope directory.
|
|
1008
|
+
*/
|
|
1009
|
+
function darwinHostProfileSeatDir(scopeId, accountHome) {
|
|
1010
|
+
const uid = assertDarwin();
|
|
1011
|
+
const home = accountHome === void 0 ? resolveDarwinAccountHome(uid) : canonicalOwnedDirectory(accountHome, uid, "Darwin test account home");
|
|
1012
|
+
const root = join(home, ".dsh-pi-tui");
|
|
1013
|
+
ensureOwnedDirectory(root, uid, false);
|
|
1014
|
+
const run = join(root, RUN_ROOT_NAME);
|
|
1015
|
+
ensureOwnedDirectory(run, uid, true);
|
|
1016
|
+
const dir = join(run, scopeId);
|
|
1017
|
+
ensureOwnedDirectory(dir, uid, true);
|
|
1018
|
+
return dir;
|
|
1019
|
+
}
|
|
1020
|
+
/** Resolve the REAL account home for the effective UID. */
|
|
1021
|
+
function resolveDarwinAccountHome(uid) {
|
|
1022
|
+
let home;
|
|
1023
|
+
try {
|
|
1024
|
+
const info = userInfo();
|
|
1025
|
+
if (info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the OS account uid does not match this process uid");
|
|
1026
|
+
home = info.homedir;
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
if (error instanceof LocalScopeError) throw error;
|
|
1029
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the OS account home is unavailable", error);
|
|
1030
|
+
}
|
|
1031
|
+
return canonicalOwnedDirectory(home, uid, "Darwin account home");
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Resolve the installed package root from one built entry's own URL.
|
|
1035
|
+
*
|
|
1036
|
+
* The walk uses the INVOKED (lexical) entry path, never its realpath: a legal
|
|
1037
|
+
* shared-store or symlinked `dist` still has its named entry under
|
|
1038
|
+
* `<packageRoot>/dist/`, so walking the lexical parents finds the package
|
|
1039
|
+
* manifest even when the real target lives elsewhere. The nearest
|
|
1040
|
+
* `package.json` is the package boundary; it must be this product. A first
|
|
1041
|
+
* manifest of another package is a hard failure (never walk past it).
|
|
1042
|
+
*/
|
|
1043
|
+
function installedPackageRootFromEntry(entryUrl) {
|
|
1044
|
+
let current;
|
|
1045
|
+
try {
|
|
1046
|
+
current = dirname(fileURLToPath(entryUrl));
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: this entry is not a readable installed file", error);
|
|
1049
|
+
}
|
|
1050
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
1051
|
+
let text;
|
|
1052
|
+
try {
|
|
1053
|
+
text = readFileSync(join(current, "package.json"), "utf8");
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: a package manifest above this entry is not readable", error);
|
|
1056
|
+
}
|
|
1057
|
+
if (text !== void 0) {
|
|
1058
|
+
let manifest;
|
|
1059
|
+
try {
|
|
1060
|
+
manifest = JSON.parse(text);
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the nearest package manifest is not valid JSON", error);
|
|
1063
|
+
}
|
|
1064
|
+
if (manifest !== null && typeof manifest === "object" && manifest.name === "@xmoon76/dsh-pi-tui") return current;
|
|
1065
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the nearest package manifest is not @xmoon76/dsh-pi-tui");
|
|
1066
|
+
}
|
|
1067
|
+
const parent = dirname(current);
|
|
1068
|
+
if (parent === current) break;
|
|
1069
|
+
current = parent;
|
|
1070
|
+
}
|
|
1071
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: this entry is not running from an installed @xmoon76/dsh-pi-tui package");
|
|
1072
|
+
}
|
|
1073
|
+
/** Read the installed DSH version from the launcher's package anchor. */
|
|
1074
|
+
function readInstalledDshVersion(dshAnchor) {
|
|
1075
|
+
let manifest;
|
|
1076
|
+
try {
|
|
1077
|
+
manifest = JSON.parse(readFileSync(realpathSync(dshAnchor), "utf8"));
|
|
1078
|
+
} catch (error) {
|
|
1079
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed DSH manifest is unreadable", error);
|
|
1080
|
+
}
|
|
1081
|
+
const version = manifest === null || typeof manifest !== "object" ? void 0 : manifest.version;
|
|
1082
|
+
if (typeof version !== "string" || version === "") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed DSH manifest has no version");
|
|
1083
|
+
return version;
|
|
1084
|
+
}
|
|
1085
|
+
/** Read and validate the installed bundle manifest. */
|
|
1086
|
+
function readBundleVersion(packageRoot) {
|
|
1087
|
+
let manifest;
|
|
1088
|
+
try {
|
|
1089
|
+
manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
1090
|
+
} catch (error) {
|
|
1091
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed package manifest is unreadable", error);
|
|
1092
|
+
}
|
|
1093
|
+
if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed package manifest is not an object");
|
|
1094
|
+
const record = manifest;
|
|
1095
|
+
if (record.name !== "@xmoon76/dsh-pi-tui" || typeof record.version !== "string" || record.version === "") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed package manifest is not @xmoon76/dsh-pi-tui");
|
|
1096
|
+
return record.version;
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* Every `.mjs` file below `dist`, sorted by UTF-8 bytes.
|
|
1100
|
+
*
|
|
1101
|
+
* A normal npm install may materialize the package through a shared store, so a
|
|
1102
|
+
* `dist` directory or an individual `.mjs` entry may be a symlink. The walk
|
|
1103
|
+
* follows a resolvable symlink to its real regular file (or real directory),
|
|
1104
|
+
* keeps the relative path exactly as installed, and refuses a dangling target, a
|
|
1105
|
+
* non-file target or a directory cycle. It never skips a `.mjs` that a symlink
|
|
1106
|
+
* exposes, because that would produce a false build identity.
|
|
1107
|
+
*/
|
|
1108
|
+
function listInstalledDistFiles(packageRoot) {
|
|
1109
|
+
const distDir = join(packageRoot, "dist");
|
|
1110
|
+
const files = [];
|
|
1111
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
1112
|
+
const walk = (dir) => {
|
|
1113
|
+
let realDir;
|
|
1114
|
+
try {
|
|
1115
|
+
realDir = realpathSync(dir);
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload directory is not readable: ${dir}`, error);
|
|
1118
|
+
}
|
|
1119
|
+
if (!statSync(realDir).isDirectory()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a non-directory: ${dir}`);
|
|
1120
|
+
if (ancestors.has(realDir)) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a directory symlink cycle: ${dir}`);
|
|
1121
|
+
ancestors.add(realDir);
|
|
1122
|
+
try {
|
|
1123
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
1124
|
+
const path = join(dir, entry.name);
|
|
1125
|
+
if (entry.isSymbolicLink()) {
|
|
1126
|
+
let target;
|
|
1127
|
+
try {
|
|
1128
|
+
target = realpathSync(path);
|
|
1129
|
+
} catch (error) {
|
|
1130
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains an unresolvable symlink: ${path}`, error);
|
|
1131
|
+
}
|
|
1132
|
+
if (statSync(target).isDirectory()) {
|
|
1133
|
+
walk(path);
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
if (!statSync(target).isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a non-file symlink target: ${path}`);
|
|
1137
|
+
if (entry.name.endsWith(".mjs")) files.push(relative(packageRoot, path).split(sep).join("/"));
|
|
1138
|
+
continue;
|
|
1139
|
+
}
|
|
1140
|
+
if (entry.isDirectory()) {
|
|
1141
|
+
walk(path);
|
|
1142
|
+
continue;
|
|
1143
|
+
}
|
|
1144
|
+
if (!entry.isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a non-file: ${path}`);
|
|
1145
|
+
if (entry.name.endsWith(".mjs")) files.push(relative(packageRoot, path).split(sep).join("/"));
|
|
1146
|
+
}
|
|
1147
|
+
} finally {
|
|
1148
|
+
ancestors.delete(realDir);
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
walk(distDir);
|
|
1152
|
+
files.sort((left, right) => Buffer$1.compare(Buffer$1.from(left, "utf8"), Buffer$1.from(right, "utf8")));
|
|
1153
|
+
return files;
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Fingerprint the actual installed payload. Every regular `dist/**` `.mjs`
|
|
1157
|
+
* contributes `relative-posix-name NUL sha256(content) LF` in UTF-8 byte
|
|
1158
|
+
* order; the bundle and DSH versions close the stream. The value is computed
|
|
1159
|
+
* once by the Host at startup and once by each Client from its own install.
|
|
1160
|
+
*/
|
|
1161
|
+
function computeBuildId(packageRoot, dshVersion) {
|
|
1162
|
+
if (dshVersion === "") throw new Error("local scope: the installed DSH version must not be empty");
|
|
1163
|
+
const hash = createHash("sha256");
|
|
1164
|
+
for (const relativeName of listInstalledDistFiles(packageRoot)) {
|
|
1165
|
+
const content = readFileSync(join(packageRoot, ...relativeName.split("/")));
|
|
1166
|
+
hash.update(relativeName);
|
|
1167
|
+
hash.update("\0");
|
|
1168
|
+
hash.update(createHash("sha256").update(content).digest("hex"));
|
|
1169
|
+
hash.update("\n");
|
|
1170
|
+
}
|
|
1171
|
+
const manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
1172
|
+
hash.update("package.json\0");
|
|
1173
|
+
hash.update(manifest.name);
|
|
1174
|
+
hash.update("\0");
|
|
1175
|
+
hash.update(manifest.version);
|
|
1176
|
+
hash.update("\n");
|
|
1177
|
+
hash.update("@deepseek-ai/dsh\0");
|
|
1178
|
+
hash.update(dshVersion);
|
|
1179
|
+
hash.update("\n");
|
|
1180
|
+
return hash.digest("hex");
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Compute the READ-ONLY identity of one installed profile scope. The caller
|
|
1184
|
+
* supplies the official DSH home/profile resolution results; this module never
|
|
1185
|
+
* guesses a path. This function performs NO filesystem mutation: it does not
|
|
1186
|
+
* `mkdir`, does not touch the registry or a unit, and returns the scope with
|
|
1187
|
+
* `dir` as the EXPECTED private run directory path (which may not exist yet).
|
|
1188
|
+
* It is the single scope-id authority; `scopeFromInstalledProfile()` composes
|
|
1189
|
+
* the exact same computation with the one directory-creation step.
|
|
1190
|
+
*/
|
|
1191
|
+
function inspectInstalledProfileScope(facts) {
|
|
1192
|
+
const uid = assertSupportedPosixScopePlatform();
|
|
1193
|
+
const dshHome = process.platform === "darwin" ? canonicalOwnedDirectory(facts.dshHome, uid, "DSH home") : canonicalDirectory(facts.dshHome, "DSH home");
|
|
1194
|
+
const profileRealpath = process.platform === "darwin" ? canonicalOwnedDirectory(facts.profileDir, uid, "profile directory") : canonicalDirectory(facts.profileDir, "profile directory");
|
|
1195
|
+
const bundleVersion = readBundleVersion(facts.packageRoot);
|
|
1196
|
+
const scopeId = createHash("sha256").update(`dsh-pi-tui/local-scope/1\0${String(uid)}\0${profileRealpath}`).digest("hex");
|
|
1197
|
+
return Object.freeze({
|
|
1198
|
+
scopeId,
|
|
1199
|
+
dshHome,
|
|
1200
|
+
profileRealpath,
|
|
1201
|
+
dir: join(dshHome, RUN_ROOT_NAME, SCOPE_ROOT_NAME, scopeId),
|
|
1202
|
+
hostSocketName: `${HOST_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
|
|
1203
|
+
clientSeatSocketName: `${CLIENT_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
|
|
1204
|
+
buildId: computeBuildId(facts.packageRoot, facts.dshVersion),
|
|
1205
|
+
bundleVersion,
|
|
1206
|
+
dshVersion: facts.dshVersion
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Build the one scope for an installed profile AND create/prove its private
|
|
1211
|
+
* 0700 run directory, before any process seat or Host Context exists. The
|
|
1212
|
+
* scope identity comes from the same read-only computation above; only the run
|
|
1213
|
+
* directory creation is added here, so Host admission and stdout/qualification
|
|
1214
|
+
* shapes stay unchanged.
|
|
1215
|
+
*/
|
|
1216
|
+
function scopeFromInstalledProfile(facts) {
|
|
1217
|
+
const inspected = inspectInstalledProfileScope(facts);
|
|
1218
|
+
const uid = assertSupportedPosixScopePlatform();
|
|
1219
|
+
const dir = ensureScopeDirectory(inspected.dshHome, inspected.scopeId, uid);
|
|
1220
|
+
return Object.freeze({
|
|
1221
|
+
...inspected,
|
|
1222
|
+
dir
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
/**
|
|
1226
|
+
* Strict Linux process-start identity. B1 identity comparison never falls
|
|
1227
|
+
* back to a bare PID: a missing `/proc` value is a hard failure.
|
|
1228
|
+
*/
|
|
1229
|
+
function readLinuxStarttime(pid = process.pid) {
|
|
1230
|
+
assertLinux();
|
|
1231
|
+
const value = readProcessStarttime(pid);
|
|
1232
|
+
if (value === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local scope: /proc/${String(pid)}/stat does not expose a starttime`);
|
|
1233
|
+
return value;
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Claim one kernel abstract-socket seat. `EADDRINUSE` means another process
|
|
1237
|
+
* of this scope already holds the seat and is the sole winner; any other
|
|
1238
|
+
* listen error is a real failure. The Host Singleton, the frozen
|
|
1239
|
+
* `qualification` Client and the short-lived daemon-control seat are the live
|
|
1240
|
+
* users; a real `surface` Client holds no seat. The returned close is
|
|
1241
|
+
* idempotent.
|
|
1242
|
+
*/
|
|
1243
|
+
function bindLinuxAbstractSeat(name, conflictCode) {
|
|
1244
|
+
if (!name.startsWith("\0")) return Promise.reject(/* @__PURE__ */ new Error("local scope: process seats require a Linux abstract socket name"));
|
|
1245
|
+
return new Promise((resolve, reject) => {
|
|
1246
|
+
const server = createServer();
|
|
1247
|
+
let settled = false;
|
|
1248
|
+
let closed;
|
|
1249
|
+
server.once("error", (error) => {
|
|
1250
|
+
if (settled) return;
|
|
1251
|
+
settled = true;
|
|
1252
|
+
if (error.code === "EADDRINUSE") {
|
|
1253
|
+
reject(new LocalScopeError(conflictCode, `local scope: ${name.slice(1)} is already owned by another live process`, error));
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
reject(error);
|
|
1257
|
+
});
|
|
1258
|
+
server.listen(name, () => {
|
|
1259
|
+
if (settled) return;
|
|
1260
|
+
settled = true;
|
|
1261
|
+
resolve({
|
|
1262
|
+
assertCurrent() {
|
|
1263
|
+
if (!server.listening) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local scope: ${name.slice(1)} seat is no longer held`);
|
|
1264
|
+
},
|
|
1265
|
+
close() {
|
|
1266
|
+
if (closed !== void 0) return closed;
|
|
1267
|
+
closed = new Promise((resolveClose, rejectClose) => {
|
|
1268
|
+
server.close((error) => {
|
|
1269
|
+
if (error === void 0) resolveClose();
|
|
1270
|
+
else rejectClose(error);
|
|
1271
|
+
});
|
|
1272
|
+
});
|
|
1273
|
+
return closed;
|
|
1274
|
+
}
|
|
1275
|
+
});
|
|
1276
|
+
});
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
function bindKernelSeat(claim, conflictCode) {
|
|
1280
|
+
return claim.claim === "linux-abstract" ? bindLinuxAbstractSeat(claim.name, conflictCode) : bindDarwinKernelSeat(claim.dir, claim.scopeId, claim.kind, conflictCode);
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Claim one kernel abstract-socket seat. `EADDRINUSE` means another process
|
|
1284
|
+
* of this scope already holds the seat and is the sole winner; any other
|
|
1285
|
+
* listen error is a real failure. The Host Singleton, the frozen
|
|
1286
|
+
* `qualification` Client and the short-lived daemon-control seat are the live
|
|
1287
|
+
* users; a real `surface` Client holds no seat. The returned close is
|
|
1288
|
+
* idempotent.
|
|
1289
|
+
*/
|
|
1290
|
+
function bindProcessSeat(name, conflictCode) {
|
|
1291
|
+
assertLinux();
|
|
1292
|
+
return bindKernelSeat({
|
|
1293
|
+
claim: "linux-abstract",
|
|
1294
|
+
name
|
|
1295
|
+
}, conflictCode);
|
|
1296
|
+
}
|
|
1297
|
+
//#endregion
|
|
1298
|
+
//#region src/app/remote-process/entry-control.ts
|
|
1299
|
+
/** The single opt-in for the raw M4-A0 JSONL stream, frozen at process start. */
|
|
1300
|
+
const ENTRY_RECORDS_ENABLED = process.env.DSH_PI_TUI_ENTRY_RECORDS === "1";
|
|
1301
|
+
/** The longest free-text fragment the default Host production log prints. */
|
|
1302
|
+
const MAX_ENTRY_LOG_TEXT = 1024;
|
|
1303
|
+
/** One existing string field as a single bounded log line fragment. */
|
|
1304
|
+
function logText(value) {
|
|
1305
|
+
if (typeof value !== "string") return void 0;
|
|
1306
|
+
const text = value.replace(/[\r\n]+/gu, " ");
|
|
1307
|
+
return text.length <= MAX_ENTRY_LOG_TEXT ? text : text.slice(0, MAX_ENTRY_LOG_TEXT);
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* The default sink's Host production projection.
|
|
1311
|
+
*
|
|
1312
|
+
* A Host runs with its stdout/stderr redirected into the user-visible
|
|
1313
|
+
* `host.log`/journal/launchd stream, so the default sink writes a few readable
|
|
1314
|
+
* lifecycle lines instead of the qualification JSON. Only an actual Host
|
|
1315
|
+
* process owns production messages; every other record is qualification data
|
|
1316
|
+
* and stays silent unless the explicit JSONL opt-in is set.
|
|
1317
|
+
*/
|
|
1318
|
+
function hostProductionLine(record) {
|
|
1319
|
+
if (record.processRole !== "host") return void 0;
|
|
1320
|
+
switch (record.m4a0) {
|
|
1321
|
+
case "ready": return {
|
|
1322
|
+
stdout: true,
|
|
1323
|
+
text: `dsh-pi-tui host: ready (profile=${String(record.profile)}, pid=${String(record.pid)})`
|
|
1324
|
+
};
|
|
1325
|
+
case "failure": {
|
|
1326
|
+
const phase = logText(record.phase);
|
|
1327
|
+
const code = logText(record.code);
|
|
1328
|
+
const context = [phase === void 0 ? void 0 : `[phase=${phase}]`, code === void 0 ? void 0 : `[code=${code}]`].filter((part) => part !== void 0).join(" ");
|
|
1329
|
+
return {
|
|
1330
|
+
stdout: false,
|
|
1331
|
+
text: `dsh-pi-tui host: startup failed${context === "" ? "" : ` ${context}`}: ${logText(record.error) ?? ""}`
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
case "cleanup-failure": {
|
|
1335
|
+
const step = logText(record.step);
|
|
1336
|
+
return {
|
|
1337
|
+
stdout: false,
|
|
1338
|
+
text: `dsh-pi-tui host: cleanup failed${step === void 0 ? "" : ` [step=${step}]`}: ${logText(record.error) ?? ""}`
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
case "diagnostic": {
|
|
1342
|
+
const code = logText(record.code) ?? "unknown";
|
|
1343
|
+
const failure = logText(record.failure) ?? "unknown";
|
|
1344
|
+
const state = logText(record.state);
|
|
1345
|
+
return {
|
|
1346
|
+
stdout: false,
|
|
1347
|
+
text: `dsh-pi-tui host: warning ${code} (${state === void 0 ? failure : `${failure}, state=${state}`})`
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
case "diag": {
|
|
1351
|
+
if (record.level !== "warn" && record.level !== "error") return void 0;
|
|
1352
|
+
const message = logText(record.message) ?? "unknown message";
|
|
1353
|
+
return {
|
|
1354
|
+
stdout: false,
|
|
1355
|
+
text: `dsh-pi-tui host: ${record.level}: ${message}`
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
case "web-autostart": return {
|
|
1359
|
+
stdout: true,
|
|
1360
|
+
text: "dsh-pi-tui host: web autostart enabled"
|
|
1361
|
+
};
|
|
1362
|
+
case "acp-autostart": return {
|
|
1363
|
+
stdout: true,
|
|
1364
|
+
text: "dsh-pi-tui host: ACP autostart enabled"
|
|
1365
|
+
};
|
|
1366
|
+
case "cleanup": return {
|
|
1367
|
+
stdout: true,
|
|
1368
|
+
text: "dsh-pi-tui host: stopped"
|
|
1369
|
+
};
|
|
1370
|
+
default: return;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* The default sink: the qualification JSONL control channel when explicitly
|
|
1375
|
+
* enabled, otherwise the minimal readable Host production log. An explicitly
|
|
1376
|
+
* provided sink always receives every record unchanged.
|
|
1377
|
+
*/
|
|
1378
|
+
const stdoutRecordSink = (record) => {
|
|
1379
|
+
if (ENTRY_RECORDS_ENABLED) {
|
|
1380
|
+
process.stdout.write(`${JSON.stringify(record)}\n`);
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
const line = hostProductionLine(record);
|
|
1384
|
+
if (line === void 0) return;
|
|
1385
|
+
(line.stdout ? process.stdout : process.stderr).write(`${line.text}\n`);
|
|
1386
|
+
};
|
|
1387
|
+
/** One structured line emitted by a process entry. */
|
|
1388
|
+
function writeEntryRecord(record, sink = stdoutRecordSink) {
|
|
1389
|
+
sink(record);
|
|
1390
|
+
}
|
|
1391
|
+
/** A role-labelled structured diagnostics sink for the entry's detached work.
|
|
1392
|
+
* The surface entry supplies its private JSONL file sink; the qualification
|
|
1393
|
+
* entries keep the default stdout control channel. */
|
|
1394
|
+
function createEntryDiag(processRole, sink) {
|
|
1395
|
+
const emit = (level) => (message, fields) => {
|
|
1396
|
+
writeEntryRecord({
|
|
1397
|
+
m4a0: "diag",
|
|
1398
|
+
processRole,
|
|
1399
|
+
level,
|
|
1400
|
+
message,
|
|
1401
|
+
...fields
|
|
1402
|
+
}, sink);
|
|
1403
|
+
};
|
|
1404
|
+
return {
|
|
1405
|
+
debug: emit("debug"),
|
|
1406
|
+
info: emit("info"),
|
|
1407
|
+
warn: emit("warn"),
|
|
1408
|
+
error: emit("error"),
|
|
1409
|
+
dispose: () => {}
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
//#endregion
|
|
1413
|
+
//#region src/app/remote-process/daemon-launcher.ts
|
|
1414
|
+
/**
|
|
1415
|
+
* The M6-2A daemon Coordinator (`@xmoon76/dsh-pi-tui/daemon-launcher`).
|
|
1416
|
+
*
|
|
1417
|
+
* A Loader row gated on `tuiDaemonStartup`: when the daemon backend is selected,
|
|
1418
|
+
* it spawns exactly ONE foreground Client OS process (`dist/local-client.mjs`)
|
|
1419
|
+
* and waits for its real exit. It owns NO Host: the Client entry performs the
|
|
1420
|
+
* Host authentication / `ensureLocalHost` itself before it mounts the surface.
|
|
1421
|
+
* The Coordinator never calls `ensureLocalHost`, never binds a Host seat and
|
|
1422
|
+
* never creates a Session/Agent/Writer.
|
|
1423
|
+
*
|
|
1424
|
+
* Lifecycle: one idempotent child lifecycle. A terminal `SIGINT` is delivered by
|
|
1425
|
+
* the kernel to BOTH the parent and the foreground child (same process group),
|
|
1426
|
+
* so the Coordinator does NOT re-forward it; a parent-only `SIGTERM` (the child
|
|
1427
|
+
* still alive) is forwarded once. Terminal stdout/stderr belong to the real TUI
|
|
1428
|
+
* Client; the Coordinator prints no records.
|
|
1429
|
+
*
|
|
1430
|
+
* @module @xmoon76/dsh-pi-tui/app/remote-process/daemon-launcher
|
|
1431
|
+
*/
|
|
1432
|
+
/** Stable Loader row id / Cordis plugin name. */
|
|
1433
|
+
const name = "pi-tui-daemon-launcher";
|
|
1434
|
+
/** The daemon Coordinator only exists when the daemon backend published its service. */
|
|
1435
|
+
const inject = ["tuiDaemonStartup"];
|
|
1436
|
+
/** The private v1 public-launch data channel (shared shape with the Client entry). */
|
|
1437
|
+
const CLIENT_LAUNCH_ENVELOPE_ENV = "SPLIT_PROCESS_CLIENT_LAUNCH_V1";
|
|
1438
|
+
/** The one-shot public launch envelope encoded for the Client child. */
|
|
1439
|
+
function encodeLaunchEnvelope(startup) {
|
|
1440
|
+
return JSON.stringify({
|
|
1441
|
+
version: 1,
|
|
1442
|
+
...startup.sessionLaunch === void 0 ? {} : { sessionLaunch: startup.sessionLaunch },
|
|
1443
|
+
...startup.presetId === void 0 ? {} : { presetId: startup.presetId },
|
|
1444
|
+
...startup.backendSource === void 0 ? {} : { backendSource: startup.backendSource }
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* Resolve the installed Client entry from THIS package root and prove its real
|
|
1449
|
+
* target is a regular file. A shared npm package, a root-owned system install
|
|
1450
|
+
* and a legal entry symlink are normal installs; only a missing or non-regular
|
|
1451
|
+
* target is a hard failure — never a fallback to a source tree or `tsx`.
|
|
1452
|
+
*/
|
|
1453
|
+
function resolveClientEntry(packageRoot) {
|
|
1454
|
+
const entry = join(packageRoot, "dist", "local-client.mjs");
|
|
1455
|
+
let real;
|
|
1456
|
+
try {
|
|
1457
|
+
real = realpathSync(entry);
|
|
1458
|
+
} catch (error) {
|
|
1459
|
+
throw new Error(`pi-tui daemon launcher: the Client entry ${entry} is missing`, { cause: error });
|
|
1460
|
+
}
|
|
1461
|
+
if (!lstatSync(real).isFile()) throw new Error(`pi-tui daemon launcher: the Client entry ${entry} must resolve to a regular file`);
|
|
1462
|
+
let expectedRoot;
|
|
1463
|
+
try {
|
|
1464
|
+
expectedRoot = realpathSync(packageRoot);
|
|
1465
|
+
} catch (error) {
|
|
1466
|
+
throw new Error(`pi-tui daemon launcher: the package root ${packageRoot} is not readable`, { cause: error });
|
|
1467
|
+
}
|
|
1468
|
+
let entryRoot;
|
|
1469
|
+
try {
|
|
1470
|
+
entryRoot = installedPackageRootFromEntry(pathToFileURL(entry).href);
|
|
1471
|
+
} catch (error) {
|
|
1472
|
+
throw new Error(`pi-tui daemon launcher: the Client entry ${entry} cannot locate its installed package root`, { cause: error });
|
|
1473
|
+
}
|
|
1474
|
+
if (entryRoot !== expectedRoot) throw new Error(`pi-tui daemon launcher: the Client entry ${entry} resolves a different installed package root`);
|
|
1475
|
+
return entry;
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* Resolve this installed bundle's package root through the OFFICIAL profile
|
|
1479
|
+
* resolution. The launcher module itself may be reached through a symlinked
|
|
1480
|
+
* `dist`, so its own module URL is not a reliable package-root locator.
|
|
1481
|
+
* Exported for the M6 UX PR2 Direct-side admin port, which must reuse the SAME
|
|
1482
|
+
* official Profile resolution as this CLI path — never a second copy.
|
|
1483
|
+
*/
|
|
1484
|
+
function resolveProfilePackageRoot(profileDir) {
|
|
1485
|
+
let manifestPath;
|
|
1486
|
+
try {
|
|
1487
|
+
manifestPath = createRequire(join(profileDir, "package.json")).resolve("@xmoon76/dsh-pi-tui/package.json");
|
|
1488
|
+
} catch (error) {
|
|
1489
|
+
throw new Error("pi-tui daemon launcher: the official profile does not resolve the installed @xmoon76/dsh-pi-tui", { cause: error });
|
|
1490
|
+
}
|
|
1491
|
+
const root = realpathSync(dirname(manifestPath));
|
|
1492
|
+
let manifest;
|
|
1493
|
+
try {
|
|
1494
|
+
manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
throw new Error("pi-tui daemon launcher: the installed package manifest is not readable", { cause: error });
|
|
1497
|
+
}
|
|
1498
|
+
if (manifest === null || typeof manifest !== "object" || manifest.name !== "@xmoon76/dsh-pi-tui") throw new Error("pi-tui daemon launcher: the official profile resolves a different package");
|
|
1499
|
+
return root;
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Build the child environment at the ONE new-spawn boundary. Every inherited
|
|
1503
|
+
* `SPLIT_PROCESS_*` test/qualification injection is stripped first, then the
|
|
1504
|
+
* four required internal facts are set explicitly. The supervisor's own role /
|
|
1505
|
+
* Host-entry markers and the one-shot public selector are never propagated.
|
|
1506
|
+
*/
|
|
1507
|
+
function buildChildEnvironment(profileContext, launchEnvelope, source = process.env) {
|
|
1508
|
+
const env = { ...source };
|
|
1509
|
+
for (const key of Object.keys(env)) if (key.startsWith("SPLIT_PROCESS_")) delete env[key];
|
|
1510
|
+
delete env.DSH_PI_TUI_ROLE;
|
|
1511
|
+
delete env.DSH_PI_TUI_HOST_ENTRY;
|
|
1512
|
+
delete env.DSH_PI_TUI_BACKEND;
|
|
1513
|
+
env.SPLIT_PROCESS_DSH_ANCHOR = profileContext.installAnchor;
|
|
1514
|
+
env.SPLIT_PROCESS_PROFILE = profileContext.name;
|
|
1515
|
+
env.SPLIT_PROCESS_CLIENT_MODE = "surface";
|
|
1516
|
+
env[CLIENT_LAUNCH_ENVELOPE_ENV] = launchEnvelope;
|
|
1517
|
+
return env;
|
|
1518
|
+
}
|
|
1519
|
+
/** POSIX-safe single-argument quoting for the copy-paste fatal line. */
|
|
1520
|
+
function shellQuote(value) {
|
|
1521
|
+
if (/^[A-Za-z0-9_@%+=:,./-]+$/u.test(value)) return value;
|
|
1522
|
+
return `'${value.replace(/'/gu, `'\\''`)}'`;
|
|
1523
|
+
}
|
|
1524
|
+
/** The child-exit mapping: a real code, or 128+signal when the child was signalled. */
|
|
1525
|
+
function exitCodeFor(code, signal) {
|
|
1526
|
+
if (code !== null) return code;
|
|
1527
|
+
if (signal === null) return 1;
|
|
1528
|
+
const number = constants$1.signals[signal];
|
|
1529
|
+
return number === void 0 ? 1 : 128 + number;
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* The ONE child lifecycle. Idempotent start/dispose; a single settle drives the
|
|
1533
|
+
* launcher `appExit` exactly once. `dispose()` is the SINGLE stop owner: it is
|
|
1534
|
+
* driven by the row's fiber disposal (the official `runProfile` SIGTERM → shutdown
|
|
1535
|
+
* → fiber disposal path) and asks the live child to stop once. The Coordinator
|
|
1536
|
+
* installs NO second SIGTERM/SIGINT handler — a terminal SIGINT already reaches
|
|
1537
|
+
* the foreground child through the shared TTY group, and the parent's own SIGTERM
|
|
1538
|
+
* is the official shutdown's, so there is exactly one stop request.
|
|
1539
|
+
*/
|
|
1540
|
+
var DaemonCoordinator = class {
|
|
1541
|
+
spawnImpl;
|
|
1542
|
+
entry;
|
|
1543
|
+
env;
|
|
1544
|
+
appExit;
|
|
1545
|
+
diag;
|
|
1546
|
+
/** A sanitized human line for the supervisor TTY when the Client cannot be
|
|
1547
|
+
* spawned at all (never a JSON record, never a raw error/message/path). */
|
|
1548
|
+
reportFatal;
|
|
1549
|
+
shutdownBudgetMs;
|
|
1550
|
+
child;
|
|
1551
|
+
childExit;
|
|
1552
|
+
started = false;
|
|
1553
|
+
disposed = false;
|
|
1554
|
+
settled = false;
|
|
1555
|
+
disposePromise;
|
|
1556
|
+
/** Test observation: how many children were actually spawned. */
|
|
1557
|
+
spawnCount = 0;
|
|
1558
|
+
constructor(options) {
|
|
1559
|
+
this.spawnImpl = options.spawnImpl;
|
|
1560
|
+
this.entry = options.entry;
|
|
1561
|
+
this.env = options.env;
|
|
1562
|
+
this.appExit = options.appExit;
|
|
1563
|
+
this.diag = options.diag;
|
|
1564
|
+
this.reportFatal = options.reportFatal ?? (() => {});
|
|
1565
|
+
this.shutdownBudgetMs = options.shutdownBudgetMs ?? 4e3;
|
|
1566
|
+
}
|
|
1567
|
+
/** Spawn the ONE foreground Client. No-op after a prior start or dispose. */
|
|
1568
|
+
start() {
|
|
1569
|
+
if (this.started || this.disposed) return;
|
|
1570
|
+
this.started = true;
|
|
1571
|
+
let child;
|
|
1572
|
+
try {
|
|
1573
|
+
child = this.spawnImpl(process.execPath, [this.entry], {
|
|
1574
|
+
cwd: process.cwd(),
|
|
1575
|
+
stdio: "inherit",
|
|
1576
|
+
shell: false,
|
|
1577
|
+
env: this.env
|
|
1578
|
+
});
|
|
1579
|
+
} catch (error) {
|
|
1580
|
+
this.settle(1, error instanceof Error ? error : new Error(String(error)));
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
this.child = child;
|
|
1584
|
+
this.spawnCount += 1;
|
|
1585
|
+
this.childExit = new Promise((resolve) => {
|
|
1586
|
+
child.once("exit", () => resolve());
|
|
1587
|
+
child.once("error", () => resolve());
|
|
1588
|
+
});
|
|
1589
|
+
child.once("error", (error) => {
|
|
1590
|
+
this.settle(1, error);
|
|
1591
|
+
});
|
|
1592
|
+
child.once("exit", (code, signal) => {
|
|
1593
|
+
this.settle(exitCodeFor(code, signal), void 0);
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
settle(code, error) {
|
|
1597
|
+
if (this.settled) return;
|
|
1598
|
+
this.settled = true;
|
|
1599
|
+
if (error !== void 0) {
|
|
1600
|
+
this.diag.warn("pi-tui daemon: client process failed", { error: error.message });
|
|
1601
|
+
const errno = error.code;
|
|
1602
|
+
const safeErrno = typeof errno === "string" && /^[A-Z][A-Z0-9_]{1,31}$/u.test(errno) ? ` (${errno})` : "";
|
|
1603
|
+
this.reportFatal(`dsh-pi-tui: could not start the daemon Client process${safeErrno}; the Host was not started. Reinstall the profile and re-run: DSH_PI_TUI_BACKEND=daemon dsh --profile ${shellQuote(this.env.SPLIT_PROCESS_PROFILE)}`);
|
|
1604
|
+
}
|
|
1605
|
+
this.appExit(code);
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* The SINGLE stop owner, AWAITABLE. A spawn not yet started is cancelled; a
|
|
1609
|
+
* live child is asked to stop once (SIGTERM) and dispose() resolves only after
|
|
1610
|
+
* the child actually exited, so the parent Fiber disposer holds the child's
|
|
1611
|
+
* cleanup rather than the parent process exiting underneath it. The wait is
|
|
1612
|
+
* bounded to fit the official ~5s shutdown deadline; a child that does not exit
|
|
1613
|
+
* within it is escalated to SIGKILL and awaited briefly. Idempotent.
|
|
1614
|
+
*/
|
|
1615
|
+
dispose() {
|
|
1616
|
+
if (this.disposePromise !== void 0) return this.disposePromise;
|
|
1617
|
+
this.disposed = true;
|
|
1618
|
+
this.disposePromise = (async () => {
|
|
1619
|
+
const child = this.child;
|
|
1620
|
+
const exited = this.childExit;
|
|
1621
|
+
if (child === void 0 || child.exitCode !== null || child.signalCode !== null || exited === void 0) return true;
|
|
1622
|
+
const budgetEnd = Date.now() + this.shutdownBudgetMs;
|
|
1623
|
+
const killAt = budgetEnd - Math.min(1e3, Math.max(50, Math.floor(this.shutdownBudgetMs * .25)));
|
|
1624
|
+
const disposeStartedAt = performance.now();
|
|
1625
|
+
const waitExitUntil = async (absoluteDeadline) => {
|
|
1626
|
+
let timer;
|
|
1627
|
+
const deadline = new Promise((resolve) => {
|
|
1628
|
+
timer = setTimeout(() => resolve(false), Math.max(0, absoluteDeadline - Date.now()));
|
|
1629
|
+
});
|
|
1630
|
+
try {
|
|
1631
|
+
return await Promise.race([exited.then(() => true), deadline]);
|
|
1632
|
+
} finally {
|
|
1633
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1634
|
+
}
|
|
1635
|
+
};
|
|
1636
|
+
try {
|
|
1637
|
+
child.kill("SIGTERM");
|
|
1638
|
+
} catch {}
|
|
1639
|
+
const sigtermWaitAt = performance.now();
|
|
1640
|
+
if (await waitExitUntil(killAt)) {
|
|
1641
|
+
this.diag.debug("pi-tui daemon: client exited after SIGTERM", { durationMs: Math.round((performance.now() - sigtermWaitAt) * 10) / 10 });
|
|
1642
|
+
return true;
|
|
1643
|
+
}
|
|
1644
|
+
try {
|
|
1645
|
+
child.kill("SIGKILL");
|
|
1646
|
+
} catch {}
|
|
1647
|
+
if (await waitExitUntil(budgetEnd)) {
|
|
1648
|
+
this.diag.debug("pi-tui daemon: client exited after SIGKILL", { durationMs: Math.round((performance.now() - disposeStartedAt) * 10) / 10 });
|
|
1649
|
+
return true;
|
|
1650
|
+
}
|
|
1651
|
+
this.reportFatal("dsh-pi-tui: the daemon Client did not exit after SIGKILL within the shutdown budget; it may be left running");
|
|
1652
|
+
return false;
|
|
1653
|
+
})();
|
|
1654
|
+
return this.disposePromise;
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
/**
|
|
1658
|
+
* The ONE management operation lifecycle. It runs at most once, writes its
|
|
1659
|
+
* output and requests `appExit` exactly once, and a fiber disposal before the
|
|
1660
|
+
* result settles suppresses both the output and the exit so a late result can
|
|
1661
|
+
* never surface after the supervisor has gone away. The operation itself is
|
|
1662
|
+
* bounded so a shutdown never waits indefinitely on a management action.
|
|
1663
|
+
*/
|
|
1664
|
+
var DaemonControlRunner = class {
|
|
1665
|
+
run;
|
|
1666
|
+
appExit;
|
|
1667
|
+
writeStdout;
|
|
1668
|
+
writeStderr;
|
|
1669
|
+
reportFatal;
|
|
1670
|
+
shutdownBudgetMs;
|
|
1671
|
+
/** The fixed result for an unexpected local throw; the daemon manager text
|
|
1672
|
+
* stays the default so its behavior is unchanged. */
|
|
1673
|
+
fallback;
|
|
1674
|
+
started = false;
|
|
1675
|
+
disposed = false;
|
|
1676
|
+
settled = false;
|
|
1677
|
+
operation;
|
|
1678
|
+
/** Test observation: how many management operations actually started. */
|
|
1679
|
+
runCount = 0;
|
|
1680
|
+
constructor(options) {
|
|
1681
|
+
this.run = options.run;
|
|
1682
|
+
this.appExit = options.appExit;
|
|
1683
|
+
this.writeStdout = options.writeStdout ?? ((text) => {
|
|
1684
|
+
process.stdout.write(text);
|
|
1685
|
+
});
|
|
1686
|
+
this.writeStderr = options.writeStderr ?? ((text) => {
|
|
1687
|
+
process.stderr.write(text);
|
|
1688
|
+
});
|
|
1689
|
+
this.reportFatal = options.reportFatal ?? (() => {});
|
|
1690
|
+
this.shutdownBudgetMs = options.shutdownBudgetMs ?? 4e3;
|
|
1691
|
+
this.fallback = options.fallback ?? {
|
|
1692
|
+
code: 4,
|
|
1693
|
+
stdout: "",
|
|
1694
|
+
stderr: "dsh-pi-tui daemon: MANAGER_OR_OS_FAILURE: an unexpected local management failure occurred\n"
|
|
1695
|
+
};
|
|
1696
|
+
}
|
|
1697
|
+
/** Start exactly one management operation. A no-op after a prior start/dispose. */
|
|
1698
|
+
start() {
|
|
1699
|
+
if (this.started || this.disposed) return;
|
|
1700
|
+
this.started = true;
|
|
1701
|
+
this.runCount += 1;
|
|
1702
|
+
this.operation = (async () => {
|
|
1703
|
+
let result;
|
|
1704
|
+
try {
|
|
1705
|
+
result = await this.run();
|
|
1706
|
+
} catch {
|
|
1707
|
+
result = this.fallback;
|
|
1708
|
+
}
|
|
1709
|
+
if (this.disposed || this.settled) return;
|
|
1710
|
+
this.settled = true;
|
|
1711
|
+
try {
|
|
1712
|
+
if (result.stdout !== "") this.writeStdout(result.stdout);
|
|
1713
|
+
if (result.stderr !== "") this.writeStderr(result.stderr);
|
|
1714
|
+
} catch {
|
|
1715
|
+
this.reportFatal("dsh-pi-tui: the daemon management output could not be written");
|
|
1716
|
+
}
|
|
1717
|
+
try {
|
|
1718
|
+
this.appExit(result.code);
|
|
1719
|
+
} catch {}
|
|
1720
|
+
})();
|
|
1721
|
+
}
|
|
1722
|
+
/** Stop accepting a late result and bound the wait for an in-flight one. */
|
|
1723
|
+
async dispose() {
|
|
1724
|
+
this.disposed = true;
|
|
1725
|
+
if (this.operation === void 0) return true;
|
|
1726
|
+
let timer;
|
|
1727
|
+
const deadline = new Promise((resolve) => {
|
|
1728
|
+
timer = setTimeout(() => resolve(false), this.shutdownBudgetMs);
|
|
1729
|
+
});
|
|
1730
|
+
let settled;
|
|
1731
|
+
try {
|
|
1732
|
+
settled = await Promise.race([this.operation.then(() => true, () => true), deadline]);
|
|
1733
|
+
} finally {
|
|
1734
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1735
|
+
}
|
|
1736
|
+
if (!settled) this.reportFatal("dsh-pi-tui: the daemon management operation did not settle within the shutdown budget");
|
|
1737
|
+
return settled;
|
|
1738
|
+
}
|
|
1739
|
+
};
|
|
1740
|
+
/**
|
|
1741
|
+
* Write a qualification dump to a SAFE, PRIVATE target: absolute path, a real
|
|
1742
|
+
* parent directory owned by this process user, NEVER overwriting an existing
|
|
1743
|
+
* file and never following a symlink; created 0600. Throws on any unsafe target
|
|
1744
|
+
* (mirrors the qualification record-sink contract in local-client-entry).
|
|
1745
|
+
*/
|
|
1746
|
+
function writeQualificationDump(target, text) {
|
|
1747
|
+
if (!isAbsolute(target)) throw new Error("the qualification dump path must be absolute");
|
|
1748
|
+
const directory = realpathSync(dirname(target));
|
|
1749
|
+
const dirStats = statSync(directory);
|
|
1750
|
+
if (!dirStats.isDirectory()) throw new Error("the qualification dump parent is not a directory");
|
|
1751
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
|
|
1752
|
+
if (uid !== void 0 && dirStats.uid !== uid) throw new Error("the qualification dump parent is not owned by this process user");
|
|
1753
|
+
if (existsSync(target)) throw new Error("the qualification dump target already exists (refusing to overwrite)");
|
|
1754
|
+
const fd = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
1755
|
+
try {
|
|
1756
|
+
if ((fstatSync(fd).mode & 511) !== 384) fchmodSync(fd, 384);
|
|
1757
|
+
writeSync(fd, text);
|
|
1758
|
+
} finally {
|
|
1759
|
+
closeSync(fd);
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
function createLoaderDumpScheduler(produce, write) {
|
|
1763
|
+
let disposed = false;
|
|
1764
|
+
let done = false;
|
|
1765
|
+
const timers = /* @__PURE__ */ new Set();
|
|
1766
|
+
const emit = () => {
|
|
1767
|
+
if (disposed || done) return;
|
|
1768
|
+
done = true;
|
|
1769
|
+
try {
|
|
1770
|
+
write(produce());
|
|
1771
|
+
} catch {}
|
|
1772
|
+
};
|
|
1773
|
+
return {
|
|
1774
|
+
schedule(delayMs) {
|
|
1775
|
+
if (disposed) return;
|
|
1776
|
+
const timer = setTimeout(() => {
|
|
1777
|
+
timers.delete(timer);
|
|
1778
|
+
emit();
|
|
1779
|
+
}, delayMs);
|
|
1780
|
+
timers.add(timer);
|
|
1781
|
+
},
|
|
1782
|
+
flush() {
|
|
1783
|
+
emit();
|
|
1784
|
+
},
|
|
1785
|
+
dispose() {
|
|
1786
|
+
disposed = true;
|
|
1787
|
+
for (const timer of timers) clearTimeout(timer);
|
|
1788
|
+
timers.clear();
|
|
1789
|
+
}
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
/** The production Coordinator row. A `client` launch spawns the ONE foreground
|
|
1793
|
+
* Client; a `control` launch runs ONE management operation. Both settle on the
|
|
1794
|
+
* real cold-ready commit and are owned by this row's Fiber. */
|
|
1795
|
+
function apply(ctx) {
|
|
1796
|
+
const startup = ctx.get("tuiDaemonStartup");
|
|
1797
|
+
if (startup === void 0) return;
|
|
1798
|
+
const appExit = ctx.get("appExit");
|
|
1799
|
+
if (appExit === void 0) throw new Error("pi-tui daemon launcher: ctx.appExit is required");
|
|
1800
|
+
const profileContext = ctx.get("profileContext");
|
|
1801
|
+
if (profileContext === void 0) throw new Error("pi-tui daemon launcher: ctx.profileContext is required");
|
|
1802
|
+
if (startup.kind === "control") {
|
|
1803
|
+
applyManagement(ctx, startup, profileContext, appExit);
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
if (startup.kind === "web-control") {
|
|
1807
|
+
applyWebControl(ctx, startup, profileContext, appExit);
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
const entry = resolveClientEntry(resolveProfilePackageRoot(profileContext.dir));
|
|
1811
|
+
const env = buildChildEnvironment(profileContext, encodeLaunchEnvelope(startup));
|
|
1812
|
+
const diag = createEntryDiag("host", () => {});
|
|
1813
|
+
const reportFatal = (line) => {
|
|
1814
|
+
try {
|
|
1815
|
+
process.stderr.write(`${line}\n`);
|
|
1816
|
+
} catch {}
|
|
1817
|
+
};
|
|
1818
|
+
const loaderDumpPath = process.env.M62A_LOADER_DUMP;
|
|
1819
|
+
if (loaderDumpPath !== void 0 && loaderDumpPath !== "") {
|
|
1820
|
+
const produce = () => {
|
|
1821
|
+
const loader = ctx.get("loader");
|
|
1822
|
+
const rows = [];
|
|
1823
|
+
if (loader !== void 0 && typeof loader.entries === "function") for (const entry of loader.entries()) rows.push({
|
|
1824
|
+
id: entry.id,
|
|
1825
|
+
disabled: entry.disabled === true,
|
|
1826
|
+
state: entry.fiber !== void 0 ? entry.fiber.state : null
|
|
1827
|
+
});
|
|
1828
|
+
return JSON.stringify(rows);
|
|
1829
|
+
};
|
|
1830
|
+
const scheduler = createLoaderDumpScheduler(produce, (text) => writeQualificationDump(loaderDumpPath, text));
|
|
1831
|
+
const readyForDump = ctx.get("appReady");
|
|
1832
|
+
const cancelReady = readyForDump !== void 0 && typeof readyForDump.onReady === "function" ? readyForDump.onReady(() => {
|
|
1833
|
+
scheduler.schedule(800);
|
|
1834
|
+
}) : void 0;
|
|
1835
|
+
scheduler.schedule(4e3);
|
|
1836
|
+
ctx.effect(() => () => {
|
|
1837
|
+
cancelReady?.();
|
|
1838
|
+
scheduler.dispose();
|
|
1839
|
+
}, "m62a-loader-dump lifecycle");
|
|
1840
|
+
}
|
|
1841
|
+
const coordinator = new DaemonCoordinator({
|
|
1842
|
+
spawnImpl: spawn,
|
|
1843
|
+
entry,
|
|
1844
|
+
env,
|
|
1845
|
+
appExit,
|
|
1846
|
+
diag,
|
|
1847
|
+
reportFatal
|
|
1848
|
+
});
|
|
1849
|
+
startup.markCoordinatorMounted?.();
|
|
1850
|
+
const ready = ctx.get("appReady");
|
|
1851
|
+
if (ready === void 0) coordinator.start();
|
|
1852
|
+
else {
|
|
1853
|
+
let registrationReturned = false;
|
|
1854
|
+
const cancel = ready.onReady(() => {
|
|
1855
|
+
if (!registrationReturned) return;
|
|
1856
|
+
coordinator.start();
|
|
1857
|
+
});
|
|
1858
|
+
registrationReturned = true;
|
|
1859
|
+
ctx.effect(() => () => {
|
|
1860
|
+
cancel();
|
|
1861
|
+
}, "pi-tui-daemon-launcher readiness");
|
|
1862
|
+
}
|
|
1863
|
+
ctx.effect(() => () => coordinator.dispose(), "pi-tui-daemon-launcher child lifecycle");
|
|
1864
|
+
}
|
|
1865
|
+
/** The official Profile facts the one-shot management runners need. */
|
|
1866
|
+
function managementProfile(profileContext) {
|
|
1867
|
+
return {
|
|
1868
|
+
name: profileContext.name,
|
|
1869
|
+
dir: profileContext.dir,
|
|
1870
|
+
home: profileContext.home,
|
|
1871
|
+
installAnchor: profileContext.installAnchor,
|
|
1872
|
+
packageRoot: resolveProfilePackageRoot(profileContext.dir),
|
|
1873
|
+
dshVersion: readInstalledDshVersion(profileContext.installAnchor)
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
/** Mount the ONE one-shot management lifecycle: mark the launcher mounted, start
|
|
1877
|
+
* only on the real cold-ready commit, and dispose through the row fiber. */
|
|
1878
|
+
function mountManagementRunner(ctx, startup, runner, controller) {
|
|
1879
|
+
startup.markCoordinatorMounted?.();
|
|
1880
|
+
const ready = ctx.get("appReady");
|
|
1881
|
+
const lifecycleName = startup.kind === "web-control" ? "pi-tui-web-control" : "pi-tui-daemon-control";
|
|
1882
|
+
if (ready === void 0) runner.start();
|
|
1883
|
+
else {
|
|
1884
|
+
let registrationReturned = false;
|
|
1885
|
+
const cancel = ready.onReady(() => {
|
|
1886
|
+
if (!registrationReturned) return;
|
|
1887
|
+
runner.start();
|
|
1888
|
+
});
|
|
1889
|
+
registrationReturned = true;
|
|
1890
|
+
ctx.effect(() => () => {
|
|
1891
|
+
cancel();
|
|
1892
|
+
}, `${lifecycleName} readiness`);
|
|
1893
|
+
}
|
|
1894
|
+
ctx.effect(() => () => {
|
|
1895
|
+
controller.abort();
|
|
1896
|
+
return runner.dispose();
|
|
1897
|
+
}, `${lifecycleName} lifecycle`);
|
|
1898
|
+
}
|
|
1899
|
+
/** Assemble ONE daemon management operation for this official Profile. No
|
|
1900
|
+
* Client artifact is resolved, no Client is spawned and no TUI/Direct row is
|
|
1901
|
+
* opened. */
|
|
1902
|
+
function applyManagement(ctx, startup, profileContext, appExit) {
|
|
1903
|
+
const profile = managementProfile(profileContext);
|
|
1904
|
+
const controller = new AbortController();
|
|
1905
|
+
mountManagementRunner(ctx, startup, new DaemonControlRunner({
|
|
1906
|
+
run: async () => {
|
|
1907
|
+
const { runDaemonControl } = await import("./local-daemon-control-C14q9KnD.mjs");
|
|
1908
|
+
return await runDaemonControl(startup.control, profile, { signal: controller.signal });
|
|
1909
|
+
},
|
|
1910
|
+
appExit
|
|
1911
|
+
}), controller);
|
|
1912
|
+
}
|
|
1913
|
+
/** Assemble ONE headless Web CLI operation for this official Profile. It never
|
|
1914
|
+
* resolves a Client artifact, never spawns a Client and never opens the TUI. */
|
|
1915
|
+
function applyWebControl(ctx, startup, profileContext, appExit) {
|
|
1916
|
+
const profile = managementProfile(profileContext);
|
|
1917
|
+
const controller = new AbortController();
|
|
1918
|
+
mountManagementRunner(ctx, startup, new DaemonControlRunner({
|
|
1919
|
+
run: async () => {
|
|
1920
|
+
const { runLocalWebControl } = await import("./local-web-control-DMrjwCkl.mjs");
|
|
1921
|
+
return await runLocalWebControl(startup.control, profile, { signal: controller.signal });
|
|
1922
|
+
},
|
|
1923
|
+
appExit,
|
|
1924
|
+
fallback: {
|
|
1925
|
+
code: 4,
|
|
1926
|
+
stdout: "",
|
|
1927
|
+
stderr: "dsh-pi-tui web: WEB_CLI_UNAVAILABLE: an unexpected local web CLI failure occurred\n"
|
|
1928
|
+
}
|
|
1929
|
+
}), controller);
|
|
1930
|
+
}
|
|
1931
|
+
//#endregion
|
|
1932
|
+
export { listKernelGroupMembers as C, sameKernelProcess as D, readProcessStarttime as E, scopeFromInstalledProfile as S, readKernelProcess as T, darwinHostProfileSeatDir as _, createLoaderDumpScheduler as a, readInstalledDshVersion as b, name as c, writeQualificationDump as d, LOCAL_PROTOCOL as f, computeBuildId as g, bindProcessSeat as h, buildChildEnvironment as i, resolveClientEntry as l, bindDarwinKernelSeat as m, DaemonCoordinator as n, encodeLaunchEnvelope as o, LocalScopeError as p, apply as r, inject as s, DaemonControlRunner as t, resolveProfilePackageRoot as u, inspectInstalledProfileScope as v, parseProcessStat as w, readLinuxStarttime as x, installedPackageRootFromEntry as y };
|