@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.
Files changed (90) hide show
  1. package/LICENSE +33 -0
  2. package/README.en.md +103 -814
  3. package/README.md +102 -711
  4. package/cordis.patch.yml +186 -0
  5. package/dist/acp-preferences.d.mts +29 -0
  6. package/dist/acp-preferences.mjs +15 -0
  7. package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
  8. package/dist/builtins.mjs +3 -3
  9. package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
  10. package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
  11. package/dist/command-trust-DChWUamk.mjs +406 -0
  12. package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
  13. package/dist/daemon-launcher.d.mts +159 -0
  14. package/dist/daemon-launcher.mjs +2 -0
  15. package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
  16. package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
  17. package/dist/entry-control-DjNsE3I0.mjs +190 -0
  18. package/dist/extension/advanced.d.mts +1 -1
  19. package/dist/extension/unstable.d.mts +1 -1
  20. package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
  21. package/dist/extension-config.d.mts +29 -0
  22. package/dist/extension-config.mjs +22 -0
  23. package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
  24. package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
  25. package/dist/extensions.d.mts +2 -2
  26. package/dist/extensions.mjs +1 -1
  27. package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
  28. package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
  29. package/dist/host-runtime.d.mts +11 -5
  30. package/dist/host-runtime.mjs +4171 -920
  31. package/dist/index.d.mts +86 -174
  32. package/dist/index.mjs +38087 -9967
  33. package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
  34. package/dist/local-client.mjs +1158 -59
  35. package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
  36. package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
  37. package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
  38. package/dist/local-discovery-egN4_gsQ.mjs +2 -0
  39. package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
  40. package/dist/local-host.mjs +812 -89
  41. package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
  42. package/dist/local-scope-DamiMqPd.mjs +1340 -0
  43. package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
  44. package/dist/local-web-control-DMrjwCkl.mjs +454 -0
  45. package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
  46. package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  47. package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  48. package/dist/open-CmOBxSjN.mjs +63 -0
  49. package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
  50. package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
  51. package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
  52. package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
  53. package/dist/preferences.d.mts +17 -0
  54. package/dist/preferences.mjs +20 -0
  55. package/dist/preset-BcWqOtY7.mjs +46 -0
  56. package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
  57. package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
  58. package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
  59. package/dist/prompt-sections-DXmjB58H.mjs +634 -0
  60. package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
  61. package/dist/row-id-DPbyt9Nn.mjs +24 -0
  62. package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
  63. package/dist/schema-BTGYn8_X.d.mts +54 -0
  64. package/dist/schema-qE_P09zJ.mjs +124 -0
  65. package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
  66. package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
  67. package/dist/startup-CarQxWwi.d.mts +213 -0
  68. package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
  69. package/dist/startup.d.mts +2 -99
  70. package/dist/startup.mjs +2 -2
  71. package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
  72. package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
  73. package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
  74. package/dist/version-B9yC7bBk.mjs +83 -0
  75. package/dist/visual-tools.d.mts +1 -1
  76. package/dist/visual-tools.mjs +1 -1
  77. package/dist/web-preferences.d.mts +1 -1
  78. package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
  79. package/generated/dsh-presets/cordis.patch.yml +4 -2
  80. package/generated/dsh-presets/ptc.patch.yml +4 -0
  81. package/generated/dsh-presets/standard.patch.yml +7 -0
  82. package/generated/web-access/cordis.patch.yml +239 -0
  83. package/package.json +217 -170
  84. package/dist/entry-control-DnduyDiw.mjs +0 -92
  85. package/dist/local-discovery-C9VMjc0K.mjs +0 -759
  86. package/dist/local-discovery-CDaQHA_R.mjs +0 -2
  87. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
  88. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
  89. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
  90. package/dist/version-a-eF-QER.mjs +0 -80
@@ -0,0 +1,1340 @@
1
+ import { n as runSyncDisposalStepsWithPrimary } from "./disposal-BYBbEpVY.mjs";
2
+ import { createRequire } from "node:module";
3
+ import { createHash } from "node:crypto";
4
+ import { closeSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
5
+ import { basename, dirname, join, relative, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { createServer } from "node:net";
8
+ import { userInfo } from "node:os";
9
+ import { Buffer as Buffer$1 } from "node:buffer";
10
+ /** `<sys/proc_info.h>`: PROC_PIDTBSDINFO. */
11
+ const PROC_PIDTBSDINFO_FLAVOR = 3;
12
+ /** XNU's private flavor 17 (PROC_PIDUNIQIDENTIFIERINFO), not in the public SDK. */
13
+ const PROC_PIDUNIQIDENTIFIER_FLAVOR = 17;
14
+ const LIBPROC = "/usr/lib/libproc.dylib";
15
+ const LIBSYSTEM = "/usr/lib/libSystem.B.dylib";
16
+ const ESRCH = 3;
17
+ const EPERM = 1;
18
+ const EACCES = 13;
19
+ const EINVAL = 22;
20
+ /** `kern.bootsessionuuid` capacity — the UUID text is 36 bytes plus NUL. */
21
+ const BOOT_UUID_CAPACITY = 128;
22
+ /**
23
+ * Classify one libproc read outcome into this repository's observation
24
+ * taxonomy. `expectedBytes` is the ABI struct size this build was written for;
25
+ * `actualBytes` is what the kernel reported. A positive-but-different reply is
26
+ * an ABI mismatch even when the kernel also set an errno: the reply must never
27
+ * be truncated or reinterpreted.
28
+ */
29
+ function classifyDarwinReadOutcome(expectedBytes, actualBytes, errno) {
30
+ if (actualBytes === expectedBytes && expectedBytes > 0) return { kind: "ok" };
31
+ if (actualBytes > 0) return {
32
+ kind: "unknown",
33
+ code: "ABI_UNSUPPORTED"
34
+ };
35
+ if (errno === ESRCH) return { kind: "gone" };
36
+ if (errno === EPERM || errno === EACCES) return {
37
+ kind: "unknown",
38
+ code: "ACCESS_DENIED"
39
+ };
40
+ if (errno === EINVAL) return {
41
+ kind: "unknown",
42
+ code: "ABI_UNSUPPORTED"
43
+ };
44
+ return {
45
+ kind: "unknown",
46
+ code: "READ_FAILED"
47
+ };
48
+ }
49
+ /** A 64-bit kernel counter as an exact decimal string (Koffi yields a BigInt
50
+ * only when the value would lose precision as a JS number). */
51
+ function decimal(value) {
52
+ if (typeof value === "bigint") return value.toString(10);
53
+ if (typeof value === "number" && Number.isSafeInteger(value)) return String(value);
54
+ throw new Error(`expected an exact 64-bit integer, got ${String(value)}`);
55
+ }
56
+ let loaded;
57
+ /** One installed `@deepseek-ai/dsh` manifest, or undefined when the path is
58
+ * unreadable, malformed, or belongs to another package. The name check is
59
+ * load-bearing: `createRequire` would otherwise walk into an unrelated ancestor
60
+ * `node_modules` and silently borrow a Koffi copy that does not belong to the
61
+ * running DSH installation. */
62
+ function installedDshManifest(path) {
63
+ try {
64
+ const real = realpathSync(path);
65
+ const manifest = JSON.parse(readFileSync(real, "utf8"));
66
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) return void 0;
67
+ const record = manifest;
68
+ return record.name === "@deepseek-ai/dsh" && typeof record.version === "string" && record.version !== "" ? real : void 0;
69
+ } catch {
70
+ return;
71
+ }
72
+ }
73
+ /**
74
+ * The installed `@deepseek-ai/dsh/package.json` this process runs on.
75
+ *
76
+ * A real Direct launcher entry (`process.argv[1]`) identifies its own installed
77
+ * DSH package and always wins over an inherited environment anchor: a shell or
78
+ * tool child of a Split Host inherits SPLIT_PROCESS_DSH_ANCHOR, but a Direct
79
+ * `dsh` CLI started from it must use the installation executing that CLI.
80
+ * Only a Split Host/Client entry, whose argv[1] is the product's own
81
+ * local-host/local-client script, falls back to the launcher-verified
82
+ * SPLIT_PROCESS_DSH_ANCHOR. No NODE_PATH, profile node_modules or source tree
83
+ * is consulted.
84
+ */
85
+ function installedDshAnchor() {
86
+ const entry = process.argv[1];
87
+ if (entry !== void 0) try {
88
+ let dir = dirname(realpathSync(entry));
89
+ for (let depth = 0; depth < 8; depth += 1) {
90
+ const anchor = installedDshManifest(join(dir, "package.json"));
91
+ if (anchor !== void 0) return anchor;
92
+ const parent = dirname(dir);
93
+ if (parent === dir) break;
94
+ dir = parent;
95
+ }
96
+ } catch {}
97
+ const provided = process.env.SPLIT_PROCESS_DSH_ANCHOR;
98
+ return provided !== void 0 && provided !== "" ? installedDshManifest(provided) : void 0;
99
+ }
100
+ /** The nearest `node_modules` directory above a package directory. */
101
+ function nearestModuleRoot(packageDir) {
102
+ for (let dir = packageDir;; dir = dirname(dir)) {
103
+ if (basename(dir) === "node_modules") return dir;
104
+ const parent = dirname(dir);
105
+ if (parent === dir) return void 0;
106
+ dir = parent;
107
+ }
108
+ }
109
+ function isInside(path, root) {
110
+ return path === root || path.startsWith(`${root}${sep}`);
111
+ }
112
+ /** Prove a resolved dependency belongs to its owner's installation closure.
113
+ *
114
+ * npm keeps sibling dependencies in the owner's nearest `node_modules`. pnpm
115
+ * keeps every package in a shared virtual store (`.mise` in the mise install
116
+ * and `.pnpm` in a project install), with each package in its own
117
+ * `<name>@<version>/node_modules` directory. Any other ancestor `node_modules`
118
+ * is an accidental hoist and must not supply a dependency. */
119
+ function assertInstallClosure(ownerDir, dependencyDir, label) {
120
+ const nearest = nearestModuleRoot(ownerDir);
121
+ if (nearest !== void 0 && isInside(dependencyDir, nearest)) return;
122
+ for (let dir = ownerDir;; dir = dirname(dir)) {
123
+ if ((basename(dir) === ".mise" || basename(dir) === ".pnpm") && isInside(dependencyDir, dir)) return;
124
+ const parent = dirname(dir);
125
+ if (parent === dir) break;
126
+ dir = parent;
127
+ }
128
+ throw new Error(`native process identity: ${label} resolved outside the installed DSH module tree`);
129
+ }
130
+ /** Read one JSON package manifest as an object, or undefined when unreadable. */
131
+ function readManifestObject(path) {
132
+ try {
133
+ const manifest = JSON.parse(readFileSync(realpathSync(path), "utf8"));
134
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) return void 0;
135
+ return manifest;
136
+ } catch {
137
+ return;
138
+ }
139
+ }
140
+ /** Require one dependency declaration from an owner manifest. */
141
+ function assertDeclaredDependency(manifest, name, label) {
142
+ const dependencies = manifest.dependencies;
143
+ const declared = dependencies !== null && typeof dependencies === "object" && !Array.isArray(dependencies) ? dependencies[name] : void 0;
144
+ if (typeof declared !== "string" || declared === "") throw new Error(`native process identity: ${label} does not declare ${name}`);
145
+ }
146
+ /**
147
+ * Resolve the Koffi entry owned by the running DSH installation:
148
+ * DSH anchor -> `@deepseek-ai/dsh-subprocess-local` manifest -> that package's
149
+ * own `koffi` dependency. The TUI never resolves Koffi from its own package, a
150
+ * profile, or an ambient module path.
151
+ *
152
+ * The owner's declared dependency selects the implementation; this code does
153
+ * not pin or compare a Koffi version, because the running DSH installation owns
154
+ * that choice and an upgrade must not be rejected only for a different version
155
+ * number. The ABI/struct-size checks in loadBridge decide actual compatibility.
156
+ */
157
+ function resolveDshKoffi(anchor) {
158
+ const manifest = installedDshManifest(anchor);
159
+ if (manifest === void 0) throw new Error("native process identity: the DSH anchor is not an installed @deepseek-ai/dsh manifest");
160
+ const dshDir = dirname(manifest);
161
+ const subprocessManifest = realpathSync(createRequire(manifest).resolve("@deepseek-ai/dsh-subprocess-local/package.json"));
162
+ const subprocessDir = dirname(subprocessManifest);
163
+ assertInstallClosure(dshDir, subprocessDir, "@deepseek-ai/dsh-subprocess-local");
164
+ const subprocess = readManifestObject(subprocessManifest);
165
+ 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");
166
+ assertDeclaredDependency(subprocess, "koffi", "@deepseek-ai/dsh-subprocess-local");
167
+ const koffiEntry = realpathSync(createRequire(subprocessManifest).resolve("koffi"));
168
+ assertInstallClosure(subprocessDir, dirname(koffiEntry), "koffi");
169
+ if (readManifestObject(join(dirname(koffiEntry), "package.json"))?.name !== "koffi") throw new Error("native process identity: the resolved koffi is not the koffi package");
170
+ return koffiEntry;
171
+ }
172
+ /** Load and ABI-check the Darwin bridge once per process. The loader itself
173
+ * never throws: an unavailable dylib/addon or an unexpected struct size is a
174
+ * classified observation, and the caller fails closed. */
175
+ function loadBridge() {
176
+ if (loaded !== void 0) return loaded;
177
+ let result;
178
+ try {
179
+ const anchor = installedDshAnchor();
180
+ if (anchor === void 0) throw new Error("native process identity: no installed DSH anchor");
181
+ const koffi = createRequire(import.meta.url)(resolveDshKoffi(anchor));
182
+ const libproc = koffi.load(LIBPROC);
183
+ const libsystem = koffi.load(LIBSYSTEM);
184
+ const bsdInfo = koffi.struct({
185
+ pbi_flags: "uint32",
186
+ pbi_status: "uint32",
187
+ pbi_xstatus: "uint32",
188
+ pbi_pid: "uint32",
189
+ pbi_ppid: "uint32",
190
+ pbi_uid: "uint32",
191
+ pbi_gid: "uint32",
192
+ pbi_ruid: "uint32",
193
+ pbi_rgid: "uint32",
194
+ pbi_svuid: "uint32",
195
+ pbi_svgid: "uint32",
196
+ rfu_1: "uint32",
197
+ pbi_comm: koffi.array("uint8", 16),
198
+ pbi_name: koffi.array("uint8", 32),
199
+ pbi_nfiles: "uint32",
200
+ pbi_pgid: "uint32",
201
+ pbi_pjobc: "uint32",
202
+ e_tdev: "uint32",
203
+ e_tpgid: "uint32",
204
+ pbi_nice: "int32",
205
+ pbi_start_tvsec: "uint64",
206
+ pbi_start_tvusec: "uint64"
207
+ });
208
+ const uniqueInfo = koffi.struct({
209
+ p_uuid: koffi.array("uint8", 16),
210
+ p_uniqueid: "uint64",
211
+ p_puniqueid: "uint64",
212
+ p_reserve: koffi.array("int32", 6)
213
+ });
214
+ if (koffi.sizeof(bsdInfo) !== 136 || koffi.sizeof(uniqueInfo) !== 56) result = {
215
+ ok: false,
216
+ code: "ABI_UNSUPPORTED"
217
+ };
218
+ else result = {
219
+ ok: true,
220
+ bridge: {
221
+ koffi,
222
+ procPidinfoBsd: libproc.func("proc_pidinfo", "int", [
223
+ "int",
224
+ "int",
225
+ "uint64",
226
+ koffi.out(koffi.pointer(bsdInfo)),
227
+ "int"
228
+ ]),
229
+ procPidinfoUniq: libproc.func("proc_pidinfo", "int", [
230
+ "int",
231
+ "int",
232
+ "uint64",
233
+ koffi.out(koffi.pointer(uniqueInfo)),
234
+ "int"
235
+ ]),
236
+ procListPgrpPids: libproc.func("proc_listpgrppids", "int", [
237
+ "int",
238
+ "void *",
239
+ "int"
240
+ ]),
241
+ sysctlByName: libsystem.func("sysctlbyname", "int", [
242
+ "const char *",
243
+ "void *",
244
+ koffi.inout(koffi.pointer(koffi.types.size_t)),
245
+ "void *",
246
+ "size_t"
247
+ ]),
248
+ getsid: libsystem.func("getsid", "int", ["int"])
249
+ }
250
+ };
251
+ } catch {
252
+ result = {
253
+ ok: false,
254
+ code: "NATIVE_UNAVAILABLE"
255
+ };
256
+ }
257
+ loaded = result;
258
+ return result;
259
+ }
260
+ /** One libproc read, classified. `read` returns the kernel byte count. */
261
+ function readRecord(expectedBytes, read, decode) {
262
+ const load = loadBridge();
263
+ if (!load.ok) return {
264
+ kind: "unknown",
265
+ code: load.code
266
+ };
267
+ const out = {};
268
+ let actual;
269
+ try {
270
+ actual = read(out, load.bridge);
271
+ } catch {
272
+ return {
273
+ kind: "unknown",
274
+ code: "READ_FAILED"
275
+ };
276
+ }
277
+ const classified = classifyDarwinReadOutcome(expectedBytes, actual, load.bridge.koffi.errno());
278
+ if (classified.kind !== "ok") return classified;
279
+ try {
280
+ return {
281
+ kind: "ok",
282
+ value: decode(out)
283
+ };
284
+ } catch {
285
+ return {
286
+ kind: "unknown",
287
+ code: "ABI_UNSUPPORTED"
288
+ };
289
+ }
290
+ }
291
+ function integerField(out, name) {
292
+ const value = out[name];
293
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new Error(`${name} is not an integer`);
294
+ return value;
295
+ }
296
+ /** `proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, ...)` decoded. */
297
+ function readDarwinBsdInfo(pid) {
298
+ return readRecord(136, (out, bridge) => bridge.procPidinfoBsd(pid, PROC_PIDTBSDINFO_FLAVOR, 0, out, 136), (out) => {
299
+ const observedPid = integerField(out, "pbi_pid");
300
+ if (observedPid !== pid) throw new Error("proc_pidinfo returned another pid");
301
+ return {
302
+ pid: observedPid,
303
+ ppid: integerField(out, "pbi_ppid"),
304
+ pgid: integerField(out, "pbi_pgid"),
305
+ uid: integerField(out, "pbi_uid"),
306
+ status: integerField(out, "pbi_status"),
307
+ startSec: decimal(out["pbi_start_tvsec"]),
308
+ startUsec: decimal(out["pbi_start_tvusec"])
309
+ };
310
+ });
311
+ }
312
+ /** `proc_pidinfo(pid, flavor 17, 0, ...)` decoded. */
313
+ function readDarwinUniqueInfo(pid) {
314
+ return readRecord(56, (out, bridge) => bridge.procPidinfoUniq(pid, PROC_PIDUNIQIDENTIFIER_FLAVOR, 0, out, 56), (out) => {
315
+ const uuid = out["p_uuid"];
316
+ if (!(uuid instanceof Uint8Array) || uuid.length !== 16) throw new Error("p_uuid is not 16 bytes");
317
+ return {
318
+ uniqueId: decimal(out["p_uniqueid"]),
319
+ parentUniqueId: decimal(out["p_puniqueid"]),
320
+ processUuid: [...uuid].map((byte) => byte.toString(16).padStart(2, "0")).join("")
321
+ };
322
+ });
323
+ }
324
+ /** `sysctlbyname("kern.bootsessionuuid")` decoded. */
325
+ function readDarwinBootSessionUuid() {
326
+ const load = loadBridge();
327
+ if (!load.ok) return {
328
+ kind: "unknown",
329
+ code: load.code
330
+ };
331
+ const bytes = Buffer.alloc(BOOT_UUID_CAPACITY);
332
+ const length = [BOOT_UUID_CAPACITY];
333
+ let rc;
334
+ try {
335
+ rc = load.bridge.sysctlByName("kern.bootsessionuuid", bytes, length, null, 0);
336
+ } catch {
337
+ return {
338
+ kind: "unknown",
339
+ code: "READ_FAILED"
340
+ };
341
+ }
342
+ if (rc !== 0) return classifySysctlFailure(load.bridge.koffi.errno());
343
+ const used = length[0];
344
+ if (typeof used !== "number" || used < 2 || used > BOOT_UUID_CAPACITY || bytes[used - 1] !== 0) return {
345
+ kind: "unknown",
346
+ code: "READ_FAILED"
347
+ };
348
+ const value = bytes.toString("utf8", 0, used - 1);
349
+ 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 {
350
+ kind: "unknown",
351
+ code: "READ_FAILED"
352
+ };
353
+ return {
354
+ kind: "ok",
355
+ value
356
+ };
357
+ }
358
+ function classifySysctlFailure(errno) {
359
+ if (errno === EPERM || errno === EACCES) return {
360
+ kind: "unknown",
361
+ code: "ACCESS_DENIED"
362
+ };
363
+ if (errno === EINVAL) return {
364
+ kind: "unknown",
365
+ code: "ABI_UNSUPPORTED"
366
+ };
367
+ return {
368
+ kind: "unknown",
369
+ code: "READ_FAILED"
370
+ };
371
+ }
372
+ /** `getsid(pid)`: the kernel session id of one process. */
373
+ function readDarwinSessionId(pid) {
374
+ const load = loadBridge();
375
+ if (!load.ok) return {
376
+ kind: "unknown",
377
+ code: load.code
378
+ };
379
+ let sid;
380
+ try {
381
+ sid = load.bridge.getsid(pid);
382
+ } catch {
383
+ return {
384
+ kind: "unknown",
385
+ code: "READ_FAILED"
386
+ };
387
+ }
388
+ if (sid > 0) return {
389
+ kind: "ok",
390
+ value: sid
391
+ };
392
+ const errno = load.bridge.koffi.errno();
393
+ if (errno === ESRCH) return { kind: "gone" };
394
+ if (errno === EPERM || errno === EACCES) return {
395
+ kind: "unknown",
396
+ code: "ACCESS_DENIED"
397
+ };
398
+ return {
399
+ kind: "unknown",
400
+ code: "READ_FAILED"
401
+ };
402
+ }
403
+ /**
404
+ * `proc_listpgrppids(pgid)`: the pids currently in one process group. The
405
+ * buffer grows until the kernel reports it fits; a negative reply is a
406
+ * classified read failure, never an empty group.
407
+ */
408
+ function listDarwinProcessGroupPids(pgid) {
409
+ const load = loadBridge();
410
+ if (!load.ok) return {
411
+ kind: "unknown",
412
+ code: load.code
413
+ };
414
+ let capacity = 32;
415
+ for (;;) {
416
+ const bytes = Buffer.alloc(capacity * 4);
417
+ let count;
418
+ try {
419
+ count = load.bridge.procListPgrpPids(pgid, bytes, bytes.length);
420
+ } catch {
421
+ return {
422
+ kind: "unknown",
423
+ code: "READ_FAILED"
424
+ };
425
+ }
426
+ if (count < 0) {
427
+ const errno = load.bridge.koffi.errno();
428
+ if (errno === EPERM || errno === EACCES) return {
429
+ kind: "unknown",
430
+ code: "ACCESS_DENIED"
431
+ };
432
+ if (errno === ESRCH) return { kind: "gone" };
433
+ return {
434
+ kind: "unknown",
435
+ code: "READ_FAILED"
436
+ };
437
+ }
438
+ const pids = [];
439
+ for (let index = 0; index < Math.min(count, capacity); index += 1) {
440
+ const pid = bytes.readInt32LE(index * 4);
441
+ if (pid > 0) pids.push(pid);
442
+ }
443
+ if (count < capacity) return {
444
+ kind: "ok",
445
+ value: pids
446
+ };
447
+ capacity *= 2;
448
+ }
449
+ }
450
+ //#endregion
451
+ //#region src/runtime/native-process/identity.ts
452
+ /**
453
+ * Kernel process identity and process-group membership: the single OS seam for
454
+ * "is this numeric pid still the process we captured?".
455
+ *
456
+ * Every consumer that signals a process group must prove ownership first:
457
+ * the footer command runner's TERM->SIGKILL escalation, the owned-process-group
458
+ * teardown used by the test runners, and (later) the Host scope/seat layer.
459
+ * This module answers that one question per platform and keeps NO state: every
460
+ * observation is a fresh kernel read.
461
+ *
462
+ * - Linux reads `/proc/<pid>/stat` (fields 3/4/5/6/22); a real zombie is
463
+ * `alive` with state `Z`, and a genuinely absent entry is `gone`.
464
+ * - Darwin reads libproc through the lazy native bridge (`./darwin.ts`):
465
+ * `proc_pidinfo` flavor 3 (136-byte `proc_bsdinfo`), the private flavor 17
466
+ * (56-byte `proc_uniqidentifierinfo`), `kern.bootsessionuuid` and `getsid`.
467
+ * Each observation is bracketed BSD -> unique -> BSD with the boot UUID on
468
+ * both sides; an identity that changes or disagrees mid-read is `unknown`,
469
+ * never `alive`. A zombie is invisible to libproc and reads as `gone`.
470
+ *
471
+ * Permission failures, an unsupported native ABI and an unstable read are all
472
+ * `unknown` — they never mean "dead" and never authorize a signal or a
473
+ * takeover. 64-bit Darwin ids are returned as exact decimal strings so no JS
474
+ * `Number` precision is silently lost.
475
+ *
476
+ * @module runtime/native-process/identity
477
+ */
478
+ /**
479
+ * Parse the fixed positional tail of one `/proc/<pid>/stat`. The comm field may
480
+ * contain spaces and parentheses, so everything after the LAST ')' is the
481
+ * fixed tail whose first entry is field 3 (`state`); `starttime` is field 22
482
+ * (index 19). A tail without a single-letter state, numeric starttime or
483
+ * numeric ppid/pgrp/session is malformed and yields `undefined`.
484
+ */
485
+ function parseLinuxStatFields(stat) {
486
+ const close = stat.lastIndexOf(")");
487
+ if (close < 0) return void 0;
488
+ const fields = stat.slice(close + 2).trim().split(/\s+/u);
489
+ const state = fields[0];
490
+ const starttime = fields[19];
491
+ const ppid = Number.parseInt(fields[1], 10);
492
+ const pgid = Number.parseInt(fields[2], 10);
493
+ const sid = Number.parseInt(fields[3], 10);
494
+ if (state === void 0 || !/^[A-Za-z]$/u.test(state)) return void 0;
495
+ if (starttime === void 0 || !/^\d+$/u.test(starttime)) return void 0;
496
+ if (!Number.isSafeInteger(ppid) || !Number.isSafeInteger(pgid) || !Number.isSafeInteger(sid)) return void 0;
497
+ return {
498
+ state,
499
+ starttime,
500
+ ppid,
501
+ pgid,
502
+ sid
503
+ };
504
+ }
505
+ /** Parse field 3 (`state`) and field 22 (`starttime`) from one
506
+ * `/proc/<pid>/stat` text (external behavior preserved from local-scope). */
507
+ function parseProcessStat(stat) {
508
+ const fields = parseLinuxStatFields(stat);
509
+ return fields === void 0 ? void 0 : {
510
+ state: fields.state,
511
+ starttime: fields.starttime
512
+ };
513
+ }
514
+ /** Parse only field 22 (`starttime`) from one `/proc/<pid>/stat`. */
515
+ function parseProcessStatStarttime(stat) {
516
+ return parseProcessStat(stat)?.starttime;
517
+ }
518
+ /** Best-effort Linux `starttime` read (undefined where `/proc` is absent). */
519
+ function readProcessStarttime(pid = process.pid) {
520
+ try {
521
+ return parseProcessStatStarttime(readFileSync(`/proc/${String(pid)}/stat`, "utf8"));
522
+ } catch {
523
+ return;
524
+ }
525
+ }
526
+ function linuxReadFailure(error) {
527
+ const code = error.code;
528
+ if (code === "ENOENT") return { kind: "gone" };
529
+ if (code === "EACCES" || code === "EPERM") return {
530
+ kind: "unknown",
531
+ code: "ACCESS_DENIED"
532
+ };
533
+ return {
534
+ kind: "unknown",
535
+ code: "READ_FAILED"
536
+ };
537
+ }
538
+ function readLinuxKernelProcess(pid) {
539
+ let stat;
540
+ try {
541
+ stat = readFileSync(`/proc/${String(pid)}/stat`, "utf8");
542
+ } catch (error) {
543
+ return linuxReadFailure(error);
544
+ }
545
+ const fields = parseLinuxStatFields(stat);
546
+ if (fields === void 0) return {
547
+ kind: "unknown",
548
+ code: "READ_FAILED"
549
+ };
550
+ return {
551
+ kind: "alive",
552
+ identity: {
553
+ platform: "linux",
554
+ pid,
555
+ startTicks: fields.starttime,
556
+ ppid: fields.ppid,
557
+ pgid: fields.pgid,
558
+ sid: fields.sid,
559
+ state: fields.state
560
+ }
561
+ };
562
+ }
563
+ /** A Darwin native result mapped onto the observation taxonomy. */
564
+ function darwinFailure(result) {
565
+ return result.kind === "gone" ? { kind: "gone" } : {
566
+ kind: "unknown",
567
+ code: result.code
568
+ };
569
+ }
570
+ function readDarwinKernelProcess(pid) {
571
+ const bootBefore = readDarwinBootSessionUuid();
572
+ if (bootBefore.kind !== "ok") return darwinFailure(bootBefore);
573
+ const before = readDarwinBsdInfo(pid);
574
+ if (before.kind !== "ok") return darwinFailure(before);
575
+ const unique = readDarwinUniqueInfo(pid);
576
+ if (unique.kind !== "ok") return darwinFailure(unique);
577
+ const after = readDarwinBsdInfo(pid);
578
+ if (after.kind !== "ok") return darwinFailure(after);
579
+ const session = readDarwinSessionId(pid);
580
+ if (session.kind !== "ok") return darwinFailure(session);
581
+ const bootAfter = readDarwinBootSessionUuid();
582
+ if (bootAfter.kind !== "ok") return darwinFailure(bootAfter);
583
+ if (bootBefore.value !== bootAfter.value) return {
584
+ kind: "unknown",
585
+ code: "READ_FAILED"
586
+ };
587
+ 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 {
588
+ kind: "unknown",
589
+ code: "READ_FAILED"
590
+ };
591
+ return {
592
+ kind: "alive",
593
+ identity: {
594
+ platform: "darwin",
595
+ pid,
596
+ bootUUID: bootBefore.value,
597
+ uniqueId: unique.value.uniqueId,
598
+ parentUniqueId: unique.value.parentUniqueId,
599
+ processUUID: unique.value.processUuid,
600
+ startSec: before.value.startSec,
601
+ startUsec: before.value.startUsec,
602
+ ppid: before.value.ppid,
603
+ pgid: before.value.pgid,
604
+ sid: session.value,
605
+ uid: before.value.uid,
606
+ state: before.value.status
607
+ }
608
+ };
609
+ }
610
+ /**
611
+ * Read the current kernel identity of one pid. Never cached: the caller decides
612
+ * whether an observation is still the process it captured.
613
+ */
614
+ function readKernelProcess(pid) {
615
+ if (process.platform === "linux") return readLinuxKernelProcess(pid);
616
+ if (process.platform === "darwin") return readDarwinKernelProcess(pid);
617
+ return {
618
+ kind: "unknown",
619
+ code: "NATIVE_UNAVAILABLE"
620
+ };
621
+ }
622
+ /**
623
+ * Classify one fresh observation against the identity a caller captured
624
+ * earlier. `gone` and `unknown` are answers about the observation itself, not
625
+ * about ownership; only `same` may authorize a signal or a takeover.
626
+ */
627
+ function sameKernelProcess(expected, observed) {
628
+ if (observed.kind === "unknown") return "unknown";
629
+ if (observed.kind === "gone") return "gone";
630
+ const actual = observed.identity;
631
+ if (actual.platform !== expected.platform || actual.pid !== expected.pid) return "different";
632
+ if (expected.platform === "linux" && actual.platform === "linux") return actual.startTicks === expected.startTicks ? "same" : "different";
633
+ 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";
634
+ return "different";
635
+ }
636
+ /** Whether one identity is a member of BOTH the target process group and the
637
+ * session the owner created for it (`setsid`: sid === pgid). A member that
638
+ * changed its group/session no longer proves ownership of the captured group. */
639
+ function isOwnedGroupMember(identity, pgid) {
640
+ return identity.pgid === pgid && identity.sid === pgid;
641
+ }
642
+ /**
643
+ * Re-read every captured member and keep only the ones that are still the SAME
644
+ * process and still inside the owned group+session. This second pass is what
645
+ * turns a snapshot into an authorization witness: a pid that exited, was
646
+ * reused, or left the group is dropped. Any unverifiable read makes the whole
647
+ * scan `unknown` — an empty result is never derived from "we could not see".
648
+ */
649
+ function verifyCapturedMembers(captured, pgid) {
650
+ const verified = [];
651
+ for (const observation of captured) {
652
+ if (observation.kind !== "alive") continue;
653
+ const current = readKernelProcess(observation.identity.pid);
654
+ if (current.kind === "unknown") return current;
655
+ if (current.kind === "gone" || !isOwnedGroupMember(current.identity, pgid)) continue;
656
+ if (sameKernelProcess(observation.identity, current) === "same") verified.push(current);
657
+ }
658
+ return verified;
659
+ }
660
+ function listLinuxKernelGroupMembers(pgid) {
661
+ let entries;
662
+ try {
663
+ entries = readdirSync("/proc");
664
+ } catch (error) {
665
+ const code = error.code;
666
+ return {
667
+ kind: "unknown",
668
+ code: code === "EACCES" || code === "EPERM" ? "ACCESS_DENIED" : "READ_FAILED"
669
+ };
670
+ }
671
+ const captured = [];
672
+ for (const entry of entries) {
673
+ if (!/^\d+$/u.test(entry)) continue;
674
+ const observation = readLinuxKernelProcess(Number(entry));
675
+ if (observation.kind === "unknown") return observation;
676
+ if (observation.kind === "gone" || !isOwnedGroupMember(observation.identity, pgid)) continue;
677
+ captured.push(observation);
678
+ }
679
+ return verifyCapturedMembers(captured, pgid);
680
+ }
681
+ function listDarwinKernelGroupMembers(pgid) {
682
+ const listed = listDarwinProcessGroupPids(pgid);
683
+ if (listed.kind === "gone") return [];
684
+ if (listed.kind !== "ok") return {
685
+ kind: "unknown",
686
+ code: listed.code
687
+ };
688
+ const captured = [];
689
+ for (const pid of listed.value) {
690
+ const observation = readDarwinKernelProcess(pid);
691
+ if (observation.kind === "unknown") return observation;
692
+ if (observation.kind === "gone" || !isOwnedGroupMember(observation.identity, pgid)) continue;
693
+ captured.push(observation);
694
+ }
695
+ return verifyCapturedMembers(captured, pgid);
696
+ }
697
+ /**
698
+ * List the verifiable members of the process group AND session `pgid` (the
699
+ * owner-created `setsid` group used by every wrapper here). Only identities
700
+ * that are the same process in both passes and still belong to the group are
701
+ * returned; a suspicious read makes the WHOLE scan `unknown` so no caller can
702
+ * mistake "not scanned" for "no member".
703
+ */
704
+ function listKernelGroupMembers(pgid) {
705
+ if (process.platform === "linux") return listLinuxKernelGroupMembers(pgid);
706
+ if (process.platform === "darwin") return listDarwinKernelGroupMembers(pgid);
707
+ return {
708
+ kind: "unknown",
709
+ code: "NATIVE_UNAVAILABLE"
710
+ };
711
+ }
712
+ //#endregion
713
+ //#region src/app/remote-process/local-scope.ts
714
+ /**
715
+ * Local Host/Client scope, process seats and installed-build identity.
716
+ *
717
+ * The ordinary DSH profile is the scope authority: this module derives a
718
+ * stable id from the canonical profile directory and the current UID, then
719
+ * owns the private run directory, the Host Singleton seat and the
720
+ * qualification-only Client seat. The installed-build fingerprint remains the
721
+ * Host's own publication/identity material; `LOCAL_PROTOCOL` below is the
722
+ * Host/Client compatibility contract and is independent of package builds.
723
+ *
724
+ * The abstract sockets are admission primitives only. No business traffic
725
+ * travels over them, and no PID file, registry record or `O_EXCL` marker can
726
+ * substitute for the kernel's exclusive bind.
727
+ *
728
+ * @module app/remote-process/local-scope
729
+ */
730
+ /**
731
+ * The required local Host/Client wire contract, independent of package builds.
732
+ * Both sides must name exactly this value and the same DSH runtime version.
733
+ *
734
+ * `local/2` is the protocol baseline of the first Split-mode opening: a v2
735
+ * peer guarantees the v1 semantics plus the required
736
+ * `piTuiPromptPresence/syncView` Remote the prompt admission gate depends on.
737
+ * A different protocol is refused at connect (`HOST_PROTOCOL_INCOMPATIBLE`);
738
+ * two builds that both name `local/2` still interoperate across versions.
739
+ */
740
+ const LOCAL_PROTOCOL = "dsh-pi-tui/local/2";
741
+ /** Private scope directory below the official DSH home. */
742
+ const RUN_ROOT_NAME = "run";
743
+ const SCOPE_ROOT_NAME = "dsh-pi-tui";
744
+ /** Linux abstract-socket prefixes; both names stay well below `sun_path`. The
745
+ * Host prefix is the singleton admission seat; the Client prefix is held by
746
+ * the frozen `qualification` mode only. */
747
+ const HOST_SEAT_PREFIX = "\0dsh-pi-tui-h-";
748
+ const CLIENT_SEAT_PREFIX = "\0dsh-pi-tui-c-";
749
+ /** A failure that carries one stable B1 classification code. */
750
+ var LocalScopeError = class extends Error {
751
+ /** Stable classification asserted by callers and the qualification lane. */
752
+ code;
753
+ constructor(code, message, cause) {
754
+ super(message, cause === void 0 ? void 0 : { cause });
755
+ this.name = "LocalScopeError";
756
+ this.code = code;
757
+ }
758
+ };
759
+ /** The no-op seat for a caller that holds no kernel claim (every real
760
+ * `surface` Client): nothing is held, so nothing can be lost or asserted. */
761
+ const NO_PROCESS_SEAT = Object.freeze({
762
+ assertCurrent: () => {},
763
+ close: async () => {}
764
+ });
765
+ /** Darwin numeric `open(2)` flags: O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK|
766
+ * O_NOFOLLOW|O_CLOEXEC = 16778022 on the qualified macOS ABI (Q0: the values
767
+ * come from the real SDK headers, not from a portable guess). */
768
+ const DARWIN_SEAT_FLAGS = 16778022;
769
+ /** A seat file is created 0600; an EXISTING file must already be exactly this. */
770
+ const DARWIN_SEAT_FILE_MODE = 384;
771
+ /** Fail before any runtime file is written on a platform the seat does not
772
+ * implement. */
773
+ function assertDarwin() {
774
+ if (process.platform !== "darwin" || typeof process.getuid !== "function") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "local scope: file-backed kernel seats require Darwin");
775
+ return process.getuid();
776
+ }
777
+ /** The ONE deterministic seat-file path per scope and purpose. */
778
+ function processSeatPath(scopeDir, scopeId, kind) {
779
+ return join(scopeDir, `seat-${kind}-${scopeId}.lock`);
780
+ }
781
+ /** Validate one already-claimed seat file: a real regular file, owned by this
782
+ * user, readable/writable by this user ONLY, with exactly one link. */
783
+ function assertSeatFileSafe(path, uid) {
784
+ let info;
785
+ try {
786
+ info = lstatSync(path);
787
+ } catch (error) {
788
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} is not accessible`, error);
789
+ }
790
+ if (info.isSymbolicLink()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must not be a symlink`);
791
+ if (!info.isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must be a regular file`);
792
+ 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`);
793
+ if (info.nlink !== 1) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must have exactly one link`);
794
+ }
795
+ /** Validate the private 0700 directory the seat file lives in. */
796
+ function assertSeatDirectorySafe(dir, uid) {
797
+ let info;
798
+ try {
799
+ info = lstatSync(dir);
800
+ } catch (error) {
801
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat directory ${dir} is not accessible`, error);
802
+ }
803
+ 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`);
804
+ return {
805
+ dev: info.dev,
806
+ ino: info.ino
807
+ };
808
+ }
809
+ /**
810
+ * One held Darwin kernel seat: the kernel's exclusive `O_EXLOCK` claim on one
811
+ * fixed inode, kept for the whole lifetime of the owning process. The FD is
812
+ * close-on-exec, so a spawned child never inherits the Host's claim.
813
+ */
814
+ var DarwinKernelSeat = class {
815
+ fd;
816
+ path;
817
+ dir;
818
+ uid;
819
+ dirDev;
820
+ dirIno;
821
+ constructor(fd, path, dir, uid, dirIdentity) {
822
+ this.fd = fd;
823
+ this.path = path;
824
+ this.dir = dir;
825
+ this.uid = uid;
826
+ this.dirDev = dirIdentity.dev;
827
+ this.dirIno = dirIdentity.ino;
828
+ }
829
+ /** Re-prove the directory, the path and the held FD still name ONE inode
830
+ * owned by this user. Called right after the claim and before Ready. */
831
+ assertCurrent() {
832
+ if (this.fd === void 0) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local scope: seat ${this.path} was already closed`);
833
+ const directory = assertSeatDirectorySafe(this.dir, this.uid);
834
+ if (directory.dev !== this.dirDev || directory.ino !== this.dirIno) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat directory ${this.dir} was replaced`);
835
+ assertSeatFileSafe(this.path, this.uid);
836
+ const held = fstatSync(this.fd);
837
+ const pathInfo = lstatSync(this.path);
838
+ 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`);
839
+ }
840
+ /**
841
+ * Release the held descriptor synchronously. Idempotent: the FD is cleared
842
+ * FIRST, so a throwing close can never leave a stale descriptor for a second
843
+ * close, and an unpublished seat's rollback can run without a promise.
844
+ */
845
+ releaseSync() {
846
+ const fd = this.fd;
847
+ if (fd === void 0) return;
848
+ this.fd = void 0;
849
+ closeSync(fd);
850
+ }
851
+ async close() {
852
+ this.releaseSync();
853
+ }
854
+ };
855
+ /** Claim one Darwin seat file. `EAGAIN`/`EWOULDBLOCK` means another process of
856
+ * this scope already holds this purpose; every other open failure is real and
857
+ * is reported as-is (never re-labelled "already owned"). */
858
+ async function bindDarwinKernelSeat(scopeDir, scopeId, kind, conflictCode) {
859
+ const uid = assertDarwin();
860
+ const dirIdentity = assertSeatDirectorySafe(scopeDir, uid);
861
+ const path = processSeatPath(scopeDir, scopeId, kind);
862
+ let existing = true;
863
+ try {
864
+ lstatSync(path);
865
+ } catch (error) {
866
+ if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} is not accessible`, error);
867
+ existing = false;
868
+ }
869
+ if (existing) assertSeatFileSafe(path, uid);
870
+ let fd;
871
+ try {
872
+ fd = openSync(path, DARWIN_SEAT_FLAGS, DARWIN_SEAT_FILE_MODE);
873
+ } catch (error) {
874
+ const code = error.code;
875
+ 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);
876
+ throw error;
877
+ }
878
+ const seat = new DarwinKernelSeat(fd, path, scopeDir, uid, dirIdentity);
879
+ try {
880
+ seat.assertCurrent();
881
+ } catch (error) {
882
+ runSyncDisposalStepsWithPrimary("release unproven Darwin seat", error, [() => seat.releaseSync()]);
883
+ }
884
+ return seat;
885
+ }
886
+ /** Fail before any runtime file is written on a platform B1 does not implement. */
887
+ function assertLinux() {
888
+ if (process.platform !== "linux" || typeof process.getuid !== "function") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "local B1 split process requires Linux abstract AF_UNIX sockets");
889
+ return process.getuid();
890
+ }
891
+ /** The profile scope itself is OS-neutral POSIX state: the canonical official
892
+ * DSH home/profile directory object plus the current UID. Linux and Darwin
893
+ * both derive the same hash domain and private 0700 run directory; only the
894
+ * kernel CLAIM below differs per platform. */
895
+ function assertSupportedPosixScopePlatform() {
896
+ 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})`);
897
+ return process.getuid();
898
+ }
899
+ /** Read a real directory and reject a non-directory or a different owner. */
900
+ function canonicalOwnedDirectory(path, uid, label) {
901
+ let real;
902
+ try {
903
+ real = realpathSync(path);
904
+ } catch (error) {
905
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a readable directory`, error);
906
+ }
907
+ const info = lstatSync(real);
908
+ 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)}`);
909
+ return real;
910
+ }
911
+ /**
912
+ * Resolve an official caller-given directory (DSH home, profile directory) and
913
+ * prove it is accessible and a directory. The user's install layout (owner,
914
+ * mode, legal directory symlink) is not judged here; the path itself comes from
915
+ * the official profile resolution, never from a guess.
916
+ */
917
+ function canonicalDirectory(path, label) {
918
+ let real;
919
+ try {
920
+ real = realpathSync(path);
921
+ } catch (error) {
922
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a readable directory`, error);
923
+ }
924
+ if (!statSync(real).isDirectory()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a directory`);
925
+ return real;
926
+ }
927
+ /**
928
+ * Create and prove one directory component WITHOUT following a pre-existing
929
+ * symlink. Each component is lstat-checked before its child is created. A
930
+ * `privateMode` component must have no group/other access at all (0700); an
931
+ * inherited account-level parent may be readable but never group/other
932
+ * writable, because only its owner may create the private chain below it.
933
+ */
934
+ function ensureOwnedDirectory(path, uid, privateMode) {
935
+ let info;
936
+ try {
937
+ info = lstatSync(path);
938
+ } catch (error) {
939
+ if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible`, error);
940
+ try {
941
+ mkdirSync(path, { mode: 448 });
942
+ } catch (mkdirError) {
943
+ if (mkdirError.code !== "EEXIST") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} could not be created safely`, mkdirError);
944
+ }
945
+ try {
946
+ info = lstatSync(path);
947
+ } catch (lstatError) {
948
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible after creation`, lstatError);
949
+ }
950
+ }
951
+ 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)}`);
952
+ const forbiddenMode = privateMode ? 63 : 18;
953
+ 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`);
954
+ }
955
+ /**
956
+ * Create and prove the private run chain. On Linux a component missing from the
957
+ * user's existing layout is created 0700 and an existing component is accepted
958
+ * as a real directory or a resolvable directory symlink regardless of
959
+ * owner/mode (D0 keeps the user's install layout); it is never chmodded. On
960
+ * Darwin the stricter owned chain is required. Only an inaccessible path, a
961
+ * non-directory, or a real filesystem failure is refused. A concurrent first
962
+ * start may win the mkdir with EEXIST; that normal kernel-seat race re-reads
963
+ * the winner.
964
+ */
965
+ function ensureScopeDirectory(dshHome, scopeId, uid) {
966
+ const runRoot = join(dshHome, RUN_ROOT_NAME);
967
+ const scopeRoot = join(runRoot, SCOPE_ROOT_NAME);
968
+ const dir = join(scopeRoot, scopeId);
969
+ if (process.platform === "darwin") {
970
+ const owner = uid ?? assertDarwin();
971
+ for (const path of [
972
+ runRoot,
973
+ scopeRoot,
974
+ dir
975
+ ]) ensureOwnedDirectory(path, owner, true);
976
+ return dir;
977
+ }
978
+ for (const path of [
979
+ runRoot,
980
+ scopeRoot,
981
+ dir
982
+ ]) {
983
+ let real;
984
+ try {
985
+ real = realpathSync(path);
986
+ } catch (error) {
987
+ if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible`, error);
988
+ try {
989
+ mkdirSync(path, { mode: 448 });
990
+ } catch (mkdirError) {
991
+ if (mkdirError.code !== "EEXIST") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} could not be created safely`, mkdirError);
992
+ }
993
+ try {
994
+ real = realpathSync(path);
995
+ } catch (realpathError) {
996
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible after creation`, realpathError);
997
+ }
998
+ }
999
+ if (!statSync(real).isDirectory()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not a directory`);
1000
+ }
1001
+ return dir;
1002
+ }
1003
+ /**
1004
+ * The per-UID Darwin Host seat directory. The local Host singleton must not
1005
+ * depend on which DSH_HOME resolved the profile, so the Host seat lives under
1006
+ * the OS ACCOUNT home (`os.userInfo().homedir`, never `$HOME`/`DSH_HOME`/
1007
+ * `$TMPDIR`), keyed only by the scope id. The qualification-only Client seat
1008
+ * remains in the per-DSH-home scope directory.
1009
+ */
1010
+ function darwinHostProfileSeatDir(scopeId, accountHome) {
1011
+ const uid = assertDarwin();
1012
+ const home = accountHome === void 0 ? resolveDarwinAccountHome(uid) : canonicalOwnedDirectory(accountHome, uid, "Darwin test account home");
1013
+ const root = join(home, ".dsh-pi-tui");
1014
+ ensureOwnedDirectory(root, uid, false);
1015
+ const run = join(root, RUN_ROOT_NAME);
1016
+ ensureOwnedDirectory(run, uid, true);
1017
+ const dir = join(run, scopeId);
1018
+ ensureOwnedDirectory(dir, uid, true);
1019
+ return dir;
1020
+ }
1021
+ /** Resolve the REAL account home for the effective UID. */
1022
+ function resolveDarwinAccountHome(uid) {
1023
+ let home;
1024
+ try {
1025
+ const info = userInfo();
1026
+ if (info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the OS account uid does not match this process uid");
1027
+ home = info.homedir;
1028
+ } catch (error) {
1029
+ if (error instanceof LocalScopeError) throw error;
1030
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the OS account home is unavailable", error);
1031
+ }
1032
+ return canonicalOwnedDirectory(home, uid, "Darwin account home");
1033
+ }
1034
+ /**
1035
+ * Resolve the installed package root from one built entry's own URL.
1036
+ *
1037
+ * The walk uses the INVOKED (lexical) entry path, never its realpath: a legal
1038
+ * shared-store or symlinked `dist` still has its named entry under
1039
+ * `<packageRoot>/dist/`, so walking the lexical parents finds the package
1040
+ * manifest even when the real target lives elsewhere. The nearest
1041
+ * `package.json` is the package boundary; it must be this product. A first
1042
+ * manifest of another package is a hard failure (never walk past it).
1043
+ */
1044
+ function installedPackageRootFromEntry(entryUrl) {
1045
+ let current;
1046
+ try {
1047
+ current = dirname(fileURLToPath(entryUrl));
1048
+ } catch (error) {
1049
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: this entry is not a readable installed file", error);
1050
+ }
1051
+ for (let depth = 0; depth < 64; depth += 1) {
1052
+ let text;
1053
+ try {
1054
+ text = readFileSync(join(current, "package.json"), "utf8");
1055
+ } catch (error) {
1056
+ if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: a package manifest above this entry is not readable", error);
1057
+ }
1058
+ if (text !== void 0) {
1059
+ let manifest;
1060
+ try {
1061
+ manifest = JSON.parse(text);
1062
+ } catch (error) {
1063
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the nearest package manifest is not valid JSON", error);
1064
+ }
1065
+ if (manifest !== null && typeof manifest === "object" && manifest.name === "@xmoon76/dsh-pi-tui") return current;
1066
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the nearest package manifest is not @xmoon76/dsh-pi-tui");
1067
+ }
1068
+ const parent = dirname(current);
1069
+ if (parent === current) break;
1070
+ current = parent;
1071
+ }
1072
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: this entry is not running from an installed @xmoon76/dsh-pi-tui package");
1073
+ }
1074
+ /** Read the installed DSH version from the launcher's package anchor. */
1075
+ function readInstalledDshVersion(dshAnchor) {
1076
+ let manifest;
1077
+ try {
1078
+ manifest = JSON.parse(readFileSync(realpathSync(dshAnchor), "utf8"));
1079
+ } catch (error) {
1080
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed DSH manifest is unreadable", error);
1081
+ }
1082
+ const version = manifest === null || typeof manifest !== "object" ? void 0 : manifest.version;
1083
+ if (typeof version !== "string" || version === "") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed DSH manifest has no version");
1084
+ return version;
1085
+ }
1086
+ /** Read and validate the installed bundle manifest. */
1087
+ function readBundleVersion(packageRoot) {
1088
+ let manifest;
1089
+ try {
1090
+ manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
1091
+ } catch (error) {
1092
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed package manifest is unreadable", error);
1093
+ }
1094
+ 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");
1095
+ const record = manifest;
1096
+ 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");
1097
+ return record.version;
1098
+ }
1099
+ /**
1100
+ * Every `.mjs` file below `dist`, sorted by UTF-8 bytes.
1101
+ *
1102
+ * A normal npm install may materialize the package through a shared store, so a
1103
+ * `dist` directory or an individual `.mjs` entry may be a symlink. The walk
1104
+ * follows a resolvable symlink to its real regular file (or real directory),
1105
+ * keeps the relative path exactly as installed, and refuses a dangling target, a
1106
+ * non-file target or a directory cycle. It never skips a `.mjs` that a symlink
1107
+ * exposes, because that would produce a false build identity.
1108
+ */
1109
+ function listInstalledDistFiles(packageRoot) {
1110
+ const distDir = join(packageRoot, "dist");
1111
+ const files = [];
1112
+ const ancestors = /* @__PURE__ */ new Set();
1113
+ const walk = (dir) => {
1114
+ let realDir;
1115
+ try {
1116
+ realDir = realpathSync(dir);
1117
+ } catch (error) {
1118
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload directory is not readable: ${dir}`, error);
1119
+ }
1120
+ if (!statSync(realDir).isDirectory()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a non-directory: ${dir}`);
1121
+ if (ancestors.has(realDir)) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a directory symlink cycle: ${dir}`);
1122
+ ancestors.add(realDir);
1123
+ try {
1124
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1125
+ const path = join(dir, entry.name);
1126
+ if (entry.isSymbolicLink()) {
1127
+ let target;
1128
+ try {
1129
+ target = realpathSync(path);
1130
+ } catch (error) {
1131
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains an unresolvable symlink: ${path}`, error);
1132
+ }
1133
+ if (statSync(target).isDirectory()) {
1134
+ walk(path);
1135
+ continue;
1136
+ }
1137
+ if (!statSync(target).isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a non-file symlink target: ${path}`);
1138
+ if (entry.name.endsWith(".mjs")) files.push(relative(packageRoot, path).split(sep).join("/"));
1139
+ continue;
1140
+ }
1141
+ if (entry.isDirectory()) {
1142
+ walk(path);
1143
+ continue;
1144
+ }
1145
+ if (!entry.isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a non-file: ${path}`);
1146
+ if (entry.name.endsWith(".mjs")) files.push(relative(packageRoot, path).split(sep).join("/"));
1147
+ }
1148
+ } finally {
1149
+ ancestors.delete(realDir);
1150
+ }
1151
+ };
1152
+ walk(distDir);
1153
+ files.sort((left, right) => Buffer$1.compare(Buffer$1.from(left, "utf8"), Buffer$1.from(right, "utf8")));
1154
+ return files;
1155
+ }
1156
+ /**
1157
+ * Fingerprint the actual installed payload. Every regular `dist/**` `.mjs`
1158
+ * contributes `relative-posix-name NUL sha256(content) LF` in UTF-8 byte
1159
+ * order; the bundle and DSH versions close the stream. The value is computed
1160
+ * once by the Host at startup and once by each Client from its own install.
1161
+ */
1162
+ function computeBuildId(packageRoot, dshVersion) {
1163
+ if (dshVersion === "") throw new Error("local scope: the installed DSH version must not be empty");
1164
+ const hash = createHash("sha256");
1165
+ for (const relativeName of listInstalledDistFiles(packageRoot)) {
1166
+ const content = readFileSync(join(packageRoot, ...relativeName.split("/")));
1167
+ hash.update(relativeName);
1168
+ hash.update("\0");
1169
+ hash.update(createHash("sha256").update(content).digest("hex"));
1170
+ hash.update("\n");
1171
+ }
1172
+ const manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
1173
+ hash.update("package.json\0");
1174
+ hash.update(manifest.name);
1175
+ hash.update("\0");
1176
+ hash.update(manifest.version);
1177
+ hash.update("\n");
1178
+ hash.update("@deepseek-ai/dsh\0");
1179
+ hash.update(dshVersion);
1180
+ hash.update("\n");
1181
+ return hash.digest("hex");
1182
+ }
1183
+ /**
1184
+ * Compute the READ-ONLY identity of one installed profile scope. The caller
1185
+ * supplies the official DSH home/profile resolution results; this module never
1186
+ * guesses a path. This function performs NO filesystem mutation: it does not
1187
+ * `mkdir`, does not touch the registry or a unit, and returns the scope with
1188
+ * `dir` as the EXPECTED private run directory path (which may not exist yet).
1189
+ * It is the single scope-id authority; `scopeFromInstalledProfile()` composes
1190
+ * the exact same computation with the one directory-creation step.
1191
+ */
1192
+ function inspectInstalledProfileScope(facts) {
1193
+ const uid = assertSupportedPosixScopePlatform();
1194
+ const dshHome = process.platform === "darwin" ? canonicalOwnedDirectory(facts.dshHome, uid, "DSH home") : canonicalDirectory(facts.dshHome, "DSH home");
1195
+ const profileRealpath = process.platform === "darwin" ? canonicalOwnedDirectory(facts.profileDir, uid, "profile directory") : canonicalDirectory(facts.profileDir, "profile directory");
1196
+ const bundleVersion = readBundleVersion(facts.packageRoot);
1197
+ const scopeId = createHash("sha256").update(`dsh-pi-tui/local-scope/1\0${String(uid)}\0${profileRealpath}`).digest("hex");
1198
+ return Object.freeze({
1199
+ scopeId,
1200
+ dshHome,
1201
+ profileRealpath,
1202
+ dir: join(dshHome, RUN_ROOT_NAME, SCOPE_ROOT_NAME, scopeId),
1203
+ hostSocketName: `${HOST_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
1204
+ clientSeatSocketName: `${CLIENT_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
1205
+ buildId: computeBuildId(facts.packageRoot, facts.dshVersion),
1206
+ bundleVersion,
1207
+ dshVersion: facts.dshVersion
1208
+ });
1209
+ }
1210
+ /**
1211
+ * Build the one scope for an installed profile AND create/prove its private
1212
+ * 0700 run directory, before any process seat or Host Context exists. The
1213
+ * scope identity comes from the same read-only computation above; only the run
1214
+ * directory creation is added here, so Host admission and stdout/qualification
1215
+ * shapes stay unchanged.
1216
+ */
1217
+ function scopeFromInstalledProfile(facts) {
1218
+ const inspected = inspectInstalledProfileScope(facts);
1219
+ const uid = assertSupportedPosixScopePlatform();
1220
+ const dir = ensureScopeDirectory(inspected.dshHome, inspected.scopeId, uid);
1221
+ return Object.freeze({
1222
+ ...inspected,
1223
+ dir
1224
+ });
1225
+ }
1226
+ /**
1227
+ * Strict Linux process-start identity. B1 identity comparison never falls
1228
+ * back to a bare PID: a missing `/proc` value is a hard failure.
1229
+ */
1230
+ function readLinuxStarttime(pid = process.pid) {
1231
+ assertLinux();
1232
+ const value = readProcessStarttime(pid);
1233
+ if (value === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local scope: /proc/${String(pid)}/stat does not expose a starttime`);
1234
+ return value;
1235
+ }
1236
+ /**
1237
+ * A qualification-only process-start diagnostic for the CURRENT process. It is
1238
+ * never an identity authority: Linux keeps its original `/proc` starttime
1239
+ * string, Darwin uses the exact boot-session/unique/start tuple so the value is
1240
+ * stable and ABI-safe, and an unverifiable read yields `undefined`.
1241
+ */
1242
+ function readProcessStartDiagnostic(pid = process.pid) {
1243
+ if (process.platform === "linux") return readProcessStarttime(pid);
1244
+ if (process.platform === "darwin") {
1245
+ const observed = readKernelProcess(pid);
1246
+ if (observed.kind !== "alive" || observed.identity.platform !== "darwin") return void 0;
1247
+ const identity = observed.identity;
1248
+ return `${identity.bootUUID}:${identity.uniqueId}:${identity.startSec}.${identity.startUsec}`;
1249
+ }
1250
+ }
1251
+ /**
1252
+ * Claim one kernel abstract-socket seat. `EADDRINUSE` means another process
1253
+ * of this scope already holds the seat and is the sole winner; any other
1254
+ * listen error is a real failure. The Host Singleton, the frozen
1255
+ * `qualification` Client and the short-lived daemon-control seat are the live
1256
+ * users; a real `surface` Client holds no seat. The returned close is
1257
+ * idempotent.
1258
+ */
1259
+ function bindLinuxAbstractSeat(name, conflictCode) {
1260
+ if (!name.startsWith("\0")) return Promise.reject(/* @__PURE__ */ new Error("local scope: process seats require a Linux abstract socket name"));
1261
+ return new Promise((resolve, reject) => {
1262
+ const server = createServer();
1263
+ let settled = false;
1264
+ let closed;
1265
+ server.once("error", (error) => {
1266
+ if (settled) return;
1267
+ settled = true;
1268
+ if (error.code === "EADDRINUSE") {
1269
+ reject(new LocalScopeError(conflictCode, `local scope: ${name.slice(1)} is already owned by another live process`, error));
1270
+ return;
1271
+ }
1272
+ reject(error);
1273
+ });
1274
+ server.listen(name, () => {
1275
+ if (settled) return;
1276
+ settled = true;
1277
+ resolve({
1278
+ assertCurrent() {
1279
+ if (!server.listening) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local scope: ${name.slice(1)} seat is no longer held`);
1280
+ },
1281
+ close() {
1282
+ if (closed !== void 0) return closed;
1283
+ closed = new Promise((resolveClose, rejectClose) => {
1284
+ server.close((error) => {
1285
+ if (error === void 0) resolveClose();
1286
+ else rejectClose(error);
1287
+ });
1288
+ });
1289
+ return closed;
1290
+ }
1291
+ });
1292
+ });
1293
+ });
1294
+ }
1295
+ function bindKernelSeat(claim, conflictCode) {
1296
+ return claim.claim === "linux-abstract" ? bindLinuxAbstractSeat(claim.name, conflictCode) : bindDarwinKernelSeat(claim.dir, claim.scopeId, claim.kind, conflictCode);
1297
+ }
1298
+ /**
1299
+ * Claim one kernel abstract-socket seat. `EADDRINUSE` means another process
1300
+ * of this scope already holds the seat and is the sole winner; any other
1301
+ * listen error is a real failure. The Host Singleton, the frozen
1302
+ * `qualification` Client and the short-lived daemon-control seat are the live
1303
+ * users; a real `surface` Client holds no seat. The returned close is
1304
+ * idempotent.
1305
+ */
1306
+ function bindProcessSeat(name, conflictCode) {
1307
+ assertLinux();
1308
+ return bindKernelSeat({
1309
+ claim: "linux-abstract",
1310
+ name
1311
+ }, conflictCode);
1312
+ }
1313
+ async function bindProfileKernelSeat(scope, kind, conflictCode, options = {}) {
1314
+ if (process.platform === "linux") return bindKernelSeat({
1315
+ claim: "linux-abstract",
1316
+ name: kind === "host" ? scope.hostSocketName : scope.clientSeatSocketName
1317
+ }, conflictCode);
1318
+ if (process.platform === "darwin") return bindKernelSeat({
1319
+ claim: "darwin-file",
1320
+ dir: kind === "host" ? darwinHostProfileSeatDir(scope.scopeId, options.accountHome) : scope.dir,
1321
+ scopeId: scope.scopeId,
1322
+ kind
1323
+ }, conflictCode);
1324
+ throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", `local scope: no profile kernel seat is implemented for ${process.platform}`);
1325
+ }
1326
+ /**
1327
+ * Remove one scratch directory only when it is exactly a Client-created
1328
+ * `host-scratch-*` child of this scope. A SIGKILL leaves it for deferred
1329
+ * cleanup; an active Host's scratch is never touched by a new Client.
1330
+ */
1331
+ function removeOwnedScratch(scopeDir, scratchDir) {
1332
+ if (dirname(scratchDir) !== scopeDir) return;
1333
+ if (!basename(scratchDir).startsWith("host-scratch-")) return;
1334
+ rmSync(scratchDir, {
1335
+ recursive: true,
1336
+ force: true
1337
+ });
1338
+ }
1339
+ //#endregion
1340
+ export { parseProcessStat as _, bindProcessSeat as a, readProcessStarttime as b, darwinHostProfileSeatDir as c, readInstalledDshVersion as d, readLinuxStarttime as f, listKernelGroupMembers as g, scopeFromInstalledProfile as h, bindDarwinKernelSeat as i, inspectInstalledProfileScope as l, removeOwnedScratch as m, LocalScopeError as n, bindProfileKernelSeat as o, readProcessStartDiagnostic as p, NO_PROCESS_SEAT as r, computeBuildId as s, LOCAL_PROTOCOL as t, installedPackageRootFromEntry as u, parseProcessStatStarttime as v, sameKernelProcess as x, readKernelProcess as y };