@xmoon76/dsh-pi-tui 0.5.3 → 0.5.5

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 (59) hide show
  1. package/README.en.md +195 -150
  2. package/README.md +137 -103
  3. package/cordis.patch.yml +54 -2
  4. package/dist/application-runtime-CbBO4bY-.mjs +6860 -0
  5. package/dist/bootstrap-DLOydLLj.mjs +108410 -0
  6. package/dist/builtins.mjs +2 -3
  7. package/dist/client-bootstrap-DwSFzcTW.mjs +872 -0
  8. package/dist/context-summary-Bz0AGXa1.mjs +12027 -0
  9. package/dist/context-summary-D9mhxPXL.mjs +10015 -0
  10. package/dist/custom-items-CKrOBCox.mjs +655 -0
  11. package/dist/disposal-BYBbEpVY.mjs +54 -0
  12. package/dist/dispose-cause-BzcXo4hu.mjs +123 -0
  13. package/dist/dispose-cause-CNFuUnjR.mjs +24 -0
  14. package/dist/dist-C7QMk0ws.mjs +15431 -0
  15. package/dist/entry-control-DnduyDiw.mjs +92 -0
  16. package/dist/extension/advanced.d.mts +1 -1
  17. package/dist/extension/unstable.d.mts +1 -1
  18. package/dist/{extensions-DzpBiiYb.d.mts → extensions-Bte3XOt5.d.mts} +1 -1
  19. package/dist/{extensions-a-rxanjw.mjs → extensions-pcFiH7Qe.mjs} +1498 -410
  20. package/dist/extensions.d.mts +2 -2
  21. package/dist/extensions.mjs +1 -1
  22. package/dist/host-bootstrap-CKdfLkNS.mjs +188 -0
  23. package/dist/host-foundation-probe-CYHsbAw6.mjs +143 -0
  24. package/dist/host-prerequisites-9JBTtVNu.mjs +36 -0
  25. package/dist/host-runtime.d.mts +26 -0
  26. package/dist/host-runtime.mjs +450 -0
  27. package/dist/index.d.mts +9 -2
  28. package/dist/index.mjs +45779 -24480
  29. package/dist/local-client.mjs +1816 -0
  30. package/dist/local-discovery-CXnLT4GF.mjs +755 -0
  31. package/dist/local-discovery-DVFFpfBG.mjs +2 -0
  32. package/dist/local-host.mjs +1025 -0
  33. package/dist/local-transport-C9aonplC.mjs +513 -0
  34. package/dist/performance-host.d.mts +2 -2
  35. package/dist/performance-host.mjs +258 -1
  36. package/dist/{performance-view-jvvd8Jn7.mjs → performance-view-CfGvLZyD.mjs} +1 -1
  37. package/dist/pi-tui-remote-contribution-DRk6Tl3J.mjs +78 -0
  38. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  39. package/dist/pi-tui-terminal-progress-contract-XTQKj-WW.mjs +905 -0
  40. package/dist/{public-types-gZi3iFNh.d.mts → public-types-Dgf1bDke.d.mts} +3 -3
  41. package/dist/{runtime-BtPH-UUb.mjs → runtime-Bh5OsftD.mjs} +1311 -1024
  42. package/dist/runtime-C5ROZqFj.mjs +2 -0
  43. package/dist/runtime-status-0lp9CM0V.mjs +1923 -0
  44. package/dist/session-4keoXjk0.mjs +10869 -0
  45. package/dist/session-B2zqv4wr.mjs +10869 -0
  46. package/dist/{startup-D5Xu8diR.mjs → startup-Ct2UUjUL.mjs} +55 -13
  47. package/dist/startup.d.mts +2 -1
  48. package/dist/startup.mjs +1 -1
  49. package/dist/terminal-progress-source-BhufrZ74.mjs +6000 -0
  50. package/dist/terminal-progress-source-CsBinCJ_.mjs +965 -0
  51. package/dist/visual-tools.d.mts +62 -0
  52. package/dist/visual-tools.mjs +556 -0
  53. package/generated/dsh-presets/README.md +1 -1
  54. package/package.json +145 -117
  55. package/dist/context-summary-CxUpNkA9.mjs +0 -2951
  56. package/dist/performance-host-BJT6scGF.mjs +0 -266
  57. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  58. package/dist/session-BZLxhrPQ.mjs +0 -5697
  59. package/dist/terminal-progress-source-BlmksrSD.mjs +0 -2200
@@ -0,0 +1,1816 @@
1
+ #!/usr/bin/env node
2
+ import { S as scopeFromInstalledProfile, _ as installedPackageRootFromEntry, g as computeBuildId, h as bindProcessSeat, m as LocalScopeError, o as ensureLocalHost, v as readInstalledDshVersion, y as readLinuxStarttime } from "./local-discovery-CXnLT4GF.mjs";
3
+ import { n as createEntryDiag, r as writeEntryRecord, t as attachEntryControl } from "./entry-control-DnduyDiw.mjs";
4
+ import { i as runDetached } from "./tasks-D_z5Yjjr.mjs";
5
+ import { t as mergeCause } from "./dispose-cause-CNFuUnjR.mjs";
6
+ import { t as runSyncDisposalSteps } from "./disposal-BYBbEpVY.mjs";
7
+ import { createRequire } from "node:module";
8
+ import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, openSync, readFileSync, realpathSync, statSync, writeSync } from "node:fs";
9
+ import { dirname, isAbsolute, join } from "node:path";
10
+ import { pathToFileURL } from "node:url";
11
+ import { spawn } from "node:child_process";
12
+ import { constants as constants$1 } from "node:os";
13
+ //#region src/app/remote-process/client-interaction-delivery.ts
14
+ /** Wrap a waterfall `next` so one official invocation delegates AT MOST once. */
15
+ function onceNext(next) {
16
+ let called = false;
17
+ let result;
18
+ return () => {
19
+ if (!called) {
20
+ called = true;
21
+ result = next();
22
+ }
23
+ return result;
24
+ };
25
+ }
26
+ /**
27
+ * Race one provider result against the official request lifetime. A presenter
28
+ * that never settles on local teardown must not keep the official Gateway's
29
+ * delivery task alive; the abandoned provider promise gets a rejection
30
+ * observer so its late settlement cannot become an unhandled rejection.
31
+ */
32
+ function raceWithAbort(promise, signal) {
33
+ if (signal === void 0) return promise;
34
+ if (signal.aborted) {
35
+ promise.catch(() => {});
36
+ return Promise.reject(abortReason(signal));
37
+ }
38
+ return new Promise((resolve, reject) => {
39
+ const onAbort = () => {
40
+ cleanup();
41
+ promise.catch(() => {});
42
+ reject(abortReason(signal));
43
+ };
44
+ const cleanup = () => {
45
+ signal.removeEventListener("abort", onAbort);
46
+ };
47
+ signal.addEventListener("abort", onAbort, { once: true });
48
+ promise.then((value) => {
49
+ cleanup();
50
+ resolve(value);
51
+ }, (error) => {
52
+ cleanup();
53
+ reject(error);
54
+ });
55
+ });
56
+ }
57
+ /** Build one abort error without inventing a Host decision. */
58
+ function abortReason(signal) {
59
+ const reason = signal?.reason;
60
+ if (reason instanceof Error) return reason;
61
+ return /* @__PURE__ */ new Error("client interaction delivery: the request lifetime ended before a surface answered");
62
+ }
63
+ /**
64
+ * Create the ONE root interaction delivery owner over the official Client
65
+ * Remote event seat. The caller must have mounted the official Session client
66
+ * (the Agent scope resolver) before the official event pump can start.
67
+ */
68
+ function createSplitClientInteractionDelivery(options) {
69
+ let current;
70
+ let disposed = false;
71
+ const surfaceWaiters = /* @__PURE__ */ new Set();
72
+ const owned = [];
73
+ const notifySurfaceWaiters = () => {
74
+ for (const waiter of [...surfaceWaiters]) {
75
+ surfaceWaiters.delete(waiter);
76
+ waiter();
77
+ }
78
+ };
79
+ /** Wait for the current surface attachment or the official request abort. */
80
+ const waitForSurface = async (signal) => {
81
+ if (current !== void 0) return current;
82
+ if (signal?.aborted === true) throw abortReason(signal);
83
+ return await new Promise((resolve, reject) => {
84
+ const cleanup = () => {
85
+ surfaceWaiters.delete(onSurface);
86
+ signal?.removeEventListener("abort", onAbort);
87
+ };
88
+ const onSurface = () => {
89
+ if (current === void 0) return;
90
+ cleanup();
91
+ resolve(current);
92
+ };
93
+ const onAbort = () => {
94
+ cleanup();
95
+ reject(abortReason(signal));
96
+ };
97
+ surfaceWaiters.add(onSurface);
98
+ signal?.addEventListener("abort", onAbort, { once: true });
99
+ });
100
+ };
101
+ const deliverQuestion = async function(request, next) {
102
+ const sessionId = options.sessions.scopeOf(this);
103
+ if (sessionId === void 0) return next();
104
+ const callId = request.wait?.callId;
105
+ const view = {
106
+ sessionId,
107
+ callId: typeof callId === "string" ? callId : void 0,
108
+ timed: request.wait?.timed === true,
109
+ questions: request.questions,
110
+ ...request.signal === void 0 ? {} : { signal: request.signal }
111
+ };
112
+ const nextOnce = onceNext(next);
113
+ for (;;) {
114
+ const attachment = await waitForSurface(request.signal);
115
+ try {
116
+ const result = await raceWithAbort(Promise.resolve().then(() => attachment.onQuestion(view, nextOnce)), request.signal);
117
+ if (current === attachment) return result;
118
+ if (request.signal?.aborted === true) return result;
119
+ } catch (error) {
120
+ if (current === attachment) throw error;
121
+ if (request.signal?.aborted === true) throw error;
122
+ }
123
+ }
124
+ };
125
+ const deliverApproval = async function(request, next) {
126
+ const sessionId = options.sessions.scopeOf(this);
127
+ if (sessionId === void 0) return next();
128
+ const view = {
129
+ toolName: request.toolName,
130
+ ...request.reason === void 0 ? {} : { reason: request.reason },
131
+ ...request.callId === void 0 ? {} : { callId: request.callId },
132
+ ...request.signal === void 0 ? {} : { signal: request.signal },
133
+ sessionId
134
+ };
135
+ const nextOnce = onceNext(next);
136
+ for (;;) {
137
+ const attachment = await waitForSurface(request.signal);
138
+ try {
139
+ const result = await raceWithAbort(Promise.resolve().then(() => attachment.onApproval(view, nextOnce)), request.signal);
140
+ if (current === attachment) return result;
141
+ if (request.signal?.aborted === true) return result;
142
+ } catch (error) {
143
+ if (current === attachment) throw error;
144
+ if (request.signal?.aborted === true) throw error;
145
+ }
146
+ }
147
+ };
148
+ owned.push(options.remote.$on("user-questions/request", deliverQuestion));
149
+ owned.push(options.remote.$on("approval/request", deliverApproval));
150
+ return {
151
+ attachSurface(revision, input) {
152
+ if (disposed) throw new Error("client interaction delivery: disposed");
153
+ const attachment = {
154
+ revision,
155
+ ...input
156
+ };
157
+ current = attachment;
158
+ notifySurfaceWaiters();
159
+ return () => {
160
+ if (current !== attachment) return;
161
+ current = void 0;
162
+ };
163
+ },
164
+ dispose() {
165
+ if (disposed) return;
166
+ disposed = true;
167
+ current = void 0;
168
+ runSyncDisposalSteps("client interaction delivery disposal", [...owned.splice(0).map((off) => () => {
169
+ off();
170
+ })]);
171
+ }
172
+ };
173
+ }
174
+ //#endregion
175
+ //#region src/app/remote-process/local-client-surface.ts
176
+ /**
177
+ * Create the bridge around the supplied process-stop owner. `stop` is invoked
178
+ * at most once, and only by the first `requestStop` caller; the promise and
179
+ * the failure latch are likewise one-shot (a late `markMounted` after a
180
+ * failure never resurrects a mounted surface).
181
+ */
182
+ function createLocalClientSurfaceBridge(stop) {
183
+ let resolveReady;
184
+ let rejectReady;
185
+ let settled = false;
186
+ const ready = new Promise((resolve, reject) => {
187
+ resolveReady = resolve;
188
+ rejectReady = reject;
189
+ });
190
+ let resolveStopped;
191
+ const stopped = new Promise((resolve) => {
192
+ resolveStopped = resolve;
193
+ });
194
+ ready.catch(() => {});
195
+ let stopRequested = false;
196
+ return {
197
+ ready,
198
+ markMounted() {
199
+ if (settled) return;
200
+ settled = true;
201
+ resolveReady?.();
202
+ },
203
+ fail(error) {
204
+ if (settled) return;
205
+ settled = true;
206
+ rejectReady?.(error);
207
+ },
208
+ requestStop(code) {
209
+ if (stopRequested) return;
210
+ stopRequested = true;
211
+ resolveStopped?.(code);
212
+ stop(code);
213
+ },
214
+ stopped
215
+ };
216
+ }
217
+ //#endregion
218
+ //#region src/app/remote-process/local-client-entry.ts
219
+ /**
220
+ * Client-only split-process entry.
221
+ *
222
+ * The Client PID owns a real Cordis root and mounts only the Client-local
223
+ * subtree plus the official Node Client transport. Its one scope is the
224
+ * canonical DSH profile: it first claims the kernel single-TUI seat, then
225
+ * discovers (or safely ensures) the Host, authenticates it through the
226
+ * official `/connect` cookie, verifies the authenticated identity, and only
227
+ * then installs the official three-layer transport on the same A0 Client
228
+ * Context.
229
+ *
230
+ * Client admission compares the required local wire protocol and the exact
231
+ * DSH runtime version, not the package bundle/build fingerprint. A different
232
+ * installed build of the same protocol may attach; a protocol or DSH mismatch
233
+ * is refused before any Host work is touched and never stops or replaces the
234
+ * live Host.
235
+ *
236
+ * The launcher supplies the DSH installation anchor and profile name through
237
+ * `SPLIT_PROCESS_DSH_ANCHOR` / `SPLIT_PROCESS_PROFILE` so this process can
238
+ * install the same official package-resolution interception the dsh launcher
239
+ * uses. The package's own `dist/` location stays the installation point — no
240
+ * repository source path or tsx loader is involved.
241
+ *
242
+ * @module app/remote-process/local-client-entry
243
+ */
244
+ /** Load the published DSH modules this entry needs, from the installation anchor. */
245
+ async function loadOfficialClientHost(anchor) {
246
+ const requireFromDsh = createRequire(realpathSync(anchor));
247
+ const importResolved = async (specifier) => import(pathToFileURL(requireFromDsh.resolve(specifier)).href);
248
+ const appBoot = await importResolved("@deepseek-ai/dsh-app-boot");
249
+ const cordis = await importResolved("@deepseek-ai/cordis");
250
+ const loaderModule = await importResolved("@deepseek-ai/cordis-plugin-loader");
251
+ const homePaths = await importResolved("@deepseek-ai/dsh-home-paths");
252
+ return {
253
+ Context: cordis.Context,
254
+ PluginPackages: appBoot.PluginPackages,
255
+ Loader: loaderModule.default,
256
+ loadProfile: appBoot.loadProfile,
257
+ createRuntimeResolution: appBoot.createRuntimeResolution,
258
+ resolveDshHome: homePaths.resolveDshHome,
259
+ resolveProfileDir: appBoot.resolveProfileDir
260
+ };
261
+ }
262
+ /** Project the authenticated record without the profile path or cookie. */
263
+ function hostRecordForTrace(host) {
264
+ const record = host.identity;
265
+ return {
266
+ scopeId: record.scopeId,
267
+ instanceId: record.instanceId,
268
+ hostPid: record.hostPid,
269
+ hostStarttime: record.hostStarttime,
270
+ origin: record.origin,
271
+ protocol: record.protocol,
272
+ bundleVersion: record.bundleVersion,
273
+ dshVersion: record.dshVersion,
274
+ buildId: record.buildId
275
+ };
276
+ }
277
+ /**
278
+ * The surface-mode telemetry sink: an owner-managed `0600` absolute JSONL file
279
+ * under the isolated qualification work root. Terminal bytes never carry JSON
280
+ * in surface mode, and the file never records a Cookie, token or private Host
281
+ * profile path. The parent directory's REAL path and ownership are validated
282
+ * before the file is opened; a symlinked target is refused.
283
+ */
284
+ function createSurfaceRecordSink() {
285
+ const target = process.env.SPLIT_PROCESS_CLIENT_RECORD_FILE;
286
+ if (target === void 0 || target === "") throw new Error("local client entry: surface mode requires SPLIT_PROCESS_CLIENT_RECORD_FILE");
287
+ if (!isAbsolute(target)) throw new Error("local client entry: the surface record file path must be absolute");
288
+ const directory = realpathSync(dirname(target));
289
+ const directoryStats = statSync(directory);
290
+ if (!directoryStats.isDirectory()) throw new Error("local client entry: the surface record directory is not a directory");
291
+ const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
292
+ if (uid !== void 0 && directoryStats.uid !== uid) throw new Error("local client entry: the surface record directory is not owned by this process user");
293
+ if (existsSync(target) && lstatSync(target).isSymbolicLink()) throw new Error("local client entry: the surface record file must not be a symlink");
294
+ const fd = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
295
+ if ((fstatSync(fd).mode & 511) !== 384) fchmodSync(fd, 384);
296
+ if ((fstatSync(fd).mode & 511) !== 384) {
297
+ closeSync(fd);
298
+ throw new Error("local client entry: the surface record file must have mode 0600");
299
+ }
300
+ return {
301
+ emit: (record) => {
302
+ writeSync(fd, `${JSON.stringify(record)}\n`);
303
+ },
304
+ close: () => {
305
+ closeSync(fd);
306
+ }
307
+ };
308
+ }
309
+ /** The surface-mode startup intent: an explicit internal input, never a
310
+ * control-channel override of published behavior. */
311
+ function surfaceStartupFacts(options) {
312
+ const sessionId = process.env.SPLIT_PROCESS_CLIENT_SESSION;
313
+ const presetId = process.env.SPLIT_PROCESS_CLIENT_PRESET;
314
+ if (options.mode !== "surface") return {};
315
+ if (sessionId !== void 0 && sessionId.trim() === "") throw new Error("local client entry: SPLIT_PROCESS_CLIENT_SESSION must be non-empty when set");
316
+ if (presetId !== void 0 && presetId.trim() === "") throw new Error("local client entry: SPLIT_PROCESS_CLIENT_PRESET must be non-empty when set");
317
+ return {
318
+ ...sessionId === void 0 || sessionId === "" ? {} : { sessionId },
319
+ ...presetId === void 0 || presetId === "" ? {} : { presetId }
320
+ };
321
+ }
322
+ /** The single internal Loader builtin name of the interaction startup gate. */
323
+ const INTERACTION_STARTUP_GATE = "pi-tui-interaction-startup-gate";
324
+ const CLIENT_PACKAGE_NAME = "@xmoon76/dsh-pi-tui";
325
+ /** The exact DSH runtime pin a candidate manifest declares (npm `devDependencies`). */
326
+ const DSH_PIN_PACKAGE = "@deepseek-ai/dsh-agent";
327
+ const INSTANCE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
328
+ /**
329
+ * Environment that belongs to the OLD Client's qualification/fault-injection
330
+ * surface only. A replacement Client must not inherit a second SIGUSR2 probe,
331
+ * a stale hold barrier or a one-shot fault injection: those are not handoff
332
+ * state and would corrupt the new process.
333
+ */
334
+ const OLD_CLIENT_ENVIRONMENT = [
335
+ "SPLIT_PROCESS_CLIENT_REEXEC_PROBE",
336
+ "SPLIT_PROCESS_CLIENT_REEXEC_TARGET_PACKAGE_ROOT",
337
+ "SPLIT_PROCESS_CLIENT_REEXEC_CHILD_FAILURE",
338
+ "SPLIT_PROCESS_CLIENT_HMR_PROBE",
339
+ "SPLIT_PROCESS_CLIENT_HMR_FAIL",
340
+ "SPLIT_PROCESS_CLIENT_HMR_HOLD",
341
+ "SPLIT_PROCESS_CLIENT_PRIVATE_RPC_PROOF",
342
+ "SPLIT_PROCESS_CLIENT_HOLD_SERIALIZE",
343
+ "SPLIT_PROCESS_CLIENT_HOLD_ASSEMBLY",
344
+ "SPLIT_PROCESS_CLIENT_HOLD_BEFORE_START",
345
+ "SPLIT_PROCESS_CLIENT_HOLD_STARTUP_GATE",
346
+ "SPLIT_PROCESS_CLIENT_FORCE_FAILURE",
347
+ "SPLIT_PROCESS_CLIENT_FORCE_STARTUP_FATAL",
348
+ "SPLIT_PROCESS_CLIENT_FORCE_REFRESH_UNRESPONSIVE_ONCE",
349
+ "SPLIT_PROCESS_CLIENT_DROP_PROMPT_ACK",
350
+ "SPLIT_PROCESS_CLIENT_OMIT_COOKIE"
351
+ ];
352
+ function failureMessage(error) {
353
+ return error instanceof Error ? error.message : String(error);
354
+ }
355
+ function isRecord(value) {
356
+ return value !== null && typeof value === "object" && !Array.isArray(value);
357
+ }
358
+ /**
359
+ * Validate one replacement Client package root and derive its production build
360
+ * fingerprint. The same checks apply to the package currently installed in the
361
+ * official profile and to the qualification-only side-by-side root override.
362
+ */
363
+ function inspectClientReexecTarget(packageRoot, dshVersion) {
364
+ if (!isAbsolute(packageRoot)) throw new Error("local client reexec: the target package root must be absolute");
365
+ let root;
366
+ try {
367
+ root = realpathSync(packageRoot);
368
+ } catch (error) {
369
+ throw new Error("local client reexec: the target package root is not readable", { cause: error });
370
+ }
371
+ const rootInfo = lstatSync(root);
372
+ const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
373
+ if (!rootInfo.isDirectory()) throw new Error("local client reexec: the target package root is not a directory");
374
+ if (uid !== void 0 && rootInfo.uid !== uid) throw new Error("local client reexec: the target package root is not owned by this process user");
375
+ let manifest;
376
+ try {
377
+ manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
378
+ } catch (error) {
379
+ throw new Error("local client reexec: the target package manifest is not readable JSON", { cause: error });
380
+ }
381
+ if (!isRecord(manifest) || manifest.name !== CLIENT_PACKAGE_NAME) throw new Error(`local client reexec: the target package is not ${CLIENT_PACKAGE_NAME}`);
382
+ if (typeof manifest.version !== "string" || manifest.version === "") throw new Error("local client reexec: the target package manifest has no version");
383
+ const devDependencies = manifest.devDependencies;
384
+ if (!isRecord(devDependencies) || devDependencies[DSH_PIN_PACKAGE] !== dshVersion) throw new Error("local client reexec: the target package is pinned to a different DSH runtime");
385
+ const entry = join(root, "dist", "local-client.mjs");
386
+ let entryInfo;
387
+ try {
388
+ entryInfo = lstatSync(entry);
389
+ } catch (error) {
390
+ throw new Error("local client reexec: the target package has no Client entry", { cause: error });
391
+ }
392
+ if (entryInfo.isSymbolicLink() || !entryInfo.isFile() || uid !== void 0 && entryInfo.uid !== uid) throw new Error("local client reexec: the target Client entry must be a regular file owned by this process user");
393
+ return {
394
+ packageRoot: root,
395
+ entry,
396
+ buildId: computeBuildId(root, dshVersion),
397
+ bundleVersion: manifest.version
398
+ };
399
+ }
400
+ /** Resolve the replacement package through the ACTIVE official profile. */
401
+ function resolveProfileInstalledClientTarget(profileDir, dshVersion) {
402
+ let manifestPath;
403
+ try {
404
+ manifestPath = createRequire(join(profileDir, "package.json")).resolve(`${CLIENT_PACKAGE_NAME}/package.json`);
405
+ } catch (error) {
406
+ throw new Error(`local client reexec: the active profile does not resolve the installed ${CLIENT_PACKAGE_NAME}`, { cause: error });
407
+ }
408
+ return inspectClientReexecTarget(dirname(manifestPath), dshVersion);
409
+ }
410
+ /**
411
+ * One typed preflight refusal. The reason is the process-owned vocabulary the
412
+ * command layer maps onto a fixed user notice; the message is the diagnostic
413
+ * detail (never surfaced verbatim by the command).
414
+ */
415
+ var ClientReexecRefusal = class extends Error {
416
+ reason;
417
+ constructor(reason, message) {
418
+ super(message);
419
+ this.name = "ClientReexecRefusal";
420
+ this.reason = reason;
421
+ }
422
+ };
423
+ function prepareClientReexec(options) {
424
+ const { status } = options;
425
+ if (status.transport !== "connected") throw new ClientReexecRefusal("not-ready", "local client reexec: the Client transport is not connected");
426
+ if (status.surfaceMounted !== true) throw new ClientReexecRefusal("not-ready", "local client reexec: the Client surface is not mounted");
427
+ const host = status.host;
428
+ if (host === void 0) throw new ClientReexecRefusal("not-ready", "local client reexec: the Client has no authenticated Host identity");
429
+ if (host.instanceId !== options.verifiedHostInstanceId) throw new ClientReexecRefusal("not-ready", "local client reexec: the live Host is not the authenticated Host instance");
430
+ let sessionId;
431
+ if (status.sessionOpen) {
432
+ const open = status.openSessionId;
433
+ if (open === void 0 || open === "") throw new ClientReexecRefusal("not-ready", "local client reexec: the open Session has no authoritative id");
434
+ sessionId = open;
435
+ }
436
+ const target = options.targetPackageRootOverride === void 0 ? resolveProfileInstalledClientTarget(options.profileDir, options.dshVersion) : inspectClientReexecTarget(options.targetPackageRootOverride, options.dshVersion);
437
+ if (target.buildId === options.currentBuildId) throw new ClientReexecRefusal("already-current", "local client reexec: the installed Client already runs this build");
438
+ return {
439
+ expectedInstanceId: host.instanceId,
440
+ ...sessionId === void 0 ? {} : { sessionId },
441
+ dshAnchor: options.dshAnchor,
442
+ profile: options.profile,
443
+ dshVersion: options.dshVersion,
444
+ targetPackageRoot: target.packageRoot,
445
+ targetEntry: target.entry,
446
+ targetBuildId: target.buildId,
447
+ targetBundleVersion: target.bundleVersion
448
+ };
449
+ }
450
+ /**
451
+ * The ONLY reexec request path. The first accepted request latches one intent
452
+ * and asks the existing stop coordinator for a normal exit; later requests are
453
+ * observable no-ops. A rejected preflight leaves the Client running and
454
+ * unlatched, so a later explicit request may retry a different target. The ONE
455
+ * latch is shared by both sources; only the target resolution differs.
456
+ */
457
+ function createClientReexecRequestHandler(options) {
458
+ let intent;
459
+ return {
460
+ request(source) {
461
+ if (intent !== void 0) {
462
+ options.emit({
463
+ m4r: "handoff-request-ignored",
464
+ processRole: "client",
465
+ pid: process.pid,
466
+ reason: "already-requested"
467
+ });
468
+ return {
469
+ kind: "refused",
470
+ reason: "stopping"
471
+ };
472
+ }
473
+ if (options.canRequest?.() === false) {
474
+ options.emit({
475
+ m4r: "handoff-request-ignored",
476
+ processRole: "client",
477
+ pid: process.pid,
478
+ reason: "stopping"
479
+ });
480
+ return {
481
+ kind: "refused",
482
+ reason: "stopping"
483
+ };
484
+ }
485
+ const status = options.status();
486
+ if (status === void 0) {
487
+ options.emit({
488
+ m4r: "handoff-request-ignored",
489
+ processRole: "client",
490
+ pid: process.pid,
491
+ reason: "not-ready"
492
+ });
493
+ return {
494
+ kind: "refused",
495
+ reason: "not-ready"
496
+ };
497
+ }
498
+ let prepared;
499
+ try {
500
+ prepared = options.prepare(status, source);
501
+ } catch (error) {
502
+ options.emit({
503
+ m4r: "handoff-request-rejected",
504
+ processRole: "client",
505
+ pid: process.pid,
506
+ error: failureMessage(error)
507
+ });
508
+ return {
509
+ kind: "refused",
510
+ reason: error instanceof ClientReexecRefusal ? error.reason : "target-invalid"
511
+ };
512
+ }
513
+ intent = prepared;
514
+ options.onAccepted?.(prepared);
515
+ options.emit({
516
+ m4r: "handoff-requested",
517
+ processRole: "client",
518
+ pid: process.pid,
519
+ source,
520
+ expectedHostInstanceId: prepared.expectedInstanceId,
521
+ ...prepared.sessionId === void 0 ? {} : { sessionId: prepared.sessionId },
522
+ targetBuildId: prepared.targetBuildId,
523
+ targetBundleVersion: prepared.targetBundleVersion
524
+ });
525
+ options.requestStop(0);
526
+ return { kind: "accepted" };
527
+ },
528
+ get intent() {
529
+ return intent;
530
+ }
531
+ };
532
+ }
533
+ /** Build the environment of the ONE replacement Client child. */
534
+ function createClientReexecChildEnvironment(intent, source = process.env) {
535
+ const env = { ...source };
536
+ const injectedFailure = source.SPLIT_PROCESS_CLIENT_REEXEC_CHILD_FAILURE;
537
+ for (const name of OLD_CLIENT_ENVIRONMENT) delete env[name];
538
+ delete env.SPLIT_PROCESS_CLIENT_PRESET;
539
+ env.SPLIT_PROCESS_CLIENT_MODE = "surface";
540
+ env.SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID = intent.expectedInstanceId;
541
+ env.SPLIT_PROCESS_DSH_ANCHOR = intent.dshAnchor;
542
+ env.SPLIT_PROCESS_PROFILE = intent.profile;
543
+ if (intent.sessionId === void 0) delete env.SPLIT_PROCESS_CLIENT_SESSION;
544
+ else env.SPLIT_PROCESS_CLIENT_SESSION = intent.sessionId;
545
+ if (injectedFailure !== void 0 && injectedFailure !== "") env.SPLIT_PROCESS_CLIENT_FORCE_FAILURE = injectedFailure;
546
+ return env;
547
+ }
548
+ /** Spawn the replacement Client on the SAME inherited terminal and await its exit. */
549
+ async function spawnClientReexecChild(entry, env, onSpawned) {
550
+ const child = spawn(process.execPath, [entry], {
551
+ cwd: process.cwd(),
552
+ env,
553
+ stdio: "inherit",
554
+ detached: false
555
+ });
556
+ onSpawned({ kill: (signal) => child.kill(signal) });
557
+ return await new Promise((resolve, reject) => {
558
+ let settled = false;
559
+ child.once("error", (error) => {
560
+ if (settled) return;
561
+ settled = true;
562
+ reject(error);
563
+ });
564
+ child.once("exit", (code, signal) => {
565
+ if (settled) return;
566
+ settled = true;
567
+ resolve({
568
+ code,
569
+ signal
570
+ });
571
+ });
572
+ });
573
+ }
574
+ function clientReexecExitCode(exit) {
575
+ if (exit.code !== null) return exit.code;
576
+ if (exit.signal === null) return 1;
577
+ const number = constants$1.signals[exit.signal];
578
+ return number === void 0 ? 1 : 128 + number;
579
+ }
580
+ /**
581
+ * Route one termination signal while a handoff is pending or already waiting.
582
+ * With no handoff, return false so the existing stop coordinator keeps owning
583
+ * the normal exit. A running replacement child receives the SAME signal; a
584
+ * handoff accepted but not yet spawned is cancelled instead of silently
585
+ * ignoring the signal. The old Client never starts a second stop.
586
+ */
587
+ function routeReexecTermination(handoffAccepted, child, signal, cancelPending) {
588
+ if (!handoffAccepted) return false;
589
+ if (child !== void 0) {
590
+ child.kill(signal);
591
+ return true;
592
+ }
593
+ cancelPending();
594
+ return true;
595
+ }
596
+ /**
597
+ * Finish the ONE Client process: close the kernel seat, and only after a fully
598
+ * successful teardown re-validate the replacement package and run the child.
599
+ * A failed teardown, seat close, target re-check or spawn never starts C1 and
600
+ * never touches the Host. Returns the replacement exit code when a handoff was
601
+ * requested, otherwise `undefined`.
602
+ */
603
+ async function finishClientEntryShutdown(options) {
604
+ let seatClosed = false;
605
+ try {
606
+ await options.seat.close();
607
+ seatClosed = true;
608
+ } catch (error) {
609
+ options.emit({
610
+ m4a0: "cleanup-failure",
611
+ processRole: "client",
612
+ phase: "shutdown",
613
+ pid: process.pid,
614
+ step: "client-seat",
615
+ error: failureMessage(error)
616
+ });
617
+ }
618
+ const reexec = options.reexec;
619
+ if (reexec === void 0) return seatClosed ? void 0 : 1;
620
+ if (reexec.cancelled?.() === true) {
621
+ const reason = /* @__PURE__ */ new Error("local client entry: the Client handoff was cancelled by a termination signal");
622
+ options.emit({
623
+ m4r: "handoff-failed",
624
+ processRole: "client",
625
+ pid: process.pid,
626
+ phase: "cancelled",
627
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
628
+ error: reason.message
629
+ });
630
+ options.stderr(handoffStartupFailureLine(reason));
631
+ return 1;
632
+ }
633
+ if (!seatClosed || !reexec.teardownSucceeded) {
634
+ const reason = /* @__PURE__ */ new Error(seatClosed ? "local client entry: the previous Client teardown did not complete" : "local client entry: the previous Client seat did not close");
635
+ options.emit({
636
+ m4r: "handoff-failed",
637
+ processRole: "client",
638
+ pid: process.pid,
639
+ phase: "teardown",
640
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
641
+ error: reason.message
642
+ });
643
+ options.stderr(handoffStartupFailureLine(reason));
644
+ return 1;
645
+ }
646
+ let target;
647
+ try {
648
+ target = inspectClientReexecTarget(reexec.intent.targetPackageRoot, reexec.intent.dshVersion);
649
+ } catch (error) {
650
+ options.emit({
651
+ m4r: "handoff-failed",
652
+ processRole: "client",
653
+ pid: process.pid,
654
+ phase: "target",
655
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
656
+ error: failureMessage(error)
657
+ });
658
+ options.stderr(handoffStartupFailureLine(error));
659
+ return 1;
660
+ }
661
+ if (target.buildId !== reexec.intent.targetBuildId || target.entry !== reexec.intent.targetEntry) {
662
+ const changed = /* @__PURE__ */ new Error("local client reexec: the replacement Client package changed between the preflight and the spawn");
663
+ options.emit({
664
+ m4r: "handoff-failed",
665
+ processRole: "client",
666
+ pid: process.pid,
667
+ phase: "target",
668
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
669
+ error: changed.message
670
+ });
671
+ options.stderr(handoffStartupFailureLine(changed));
672
+ return 1;
673
+ }
674
+ const spawnChild = options.spawnChild ?? spawnClientReexecChild;
675
+ let exit;
676
+ try {
677
+ exit = await spawnChild(target.entry, createClientReexecChildEnvironment(reexec.intent), (child) => options.onChildSpawned?.(child));
678
+ } catch (error) {
679
+ options.emit({
680
+ m4r: "handoff-failed",
681
+ processRole: "client",
682
+ pid: process.pid,
683
+ phase: "spawn",
684
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
685
+ error: failureMessage(error)
686
+ });
687
+ options.stderr(handoffStartupFailureLine(error));
688
+ return 1;
689
+ }
690
+ options.emit({
691
+ m4r: "handoff-parent-exit",
692
+ processRole: "client",
693
+ pid: process.pid,
694
+ code: exit.code,
695
+ signal: exit.signal
696
+ });
697
+ return clientReexecExitCode(exit);
698
+ }
699
+ /**
700
+ * The FINAL gate before a replacement Client publishes `handoff-restored`.
701
+ * It reads the LIVE status after the Session-open proof and refuses a Client
702
+ * whose official transport fatal, expected Host instance, connection or
703
+ * physical surface is no longer current. `status.host` is the composition's
704
+ * authenticated record (a static fact), so the meaningful currentness checks
705
+ * are the transport state/generation (the proof rejects a generation rollover)
706
+ * and this terminal-fatal gate.
707
+ */
708
+ function assertHandoffRestored(status, expectedInstanceId, terminalError) {
709
+ if (terminalError !== void 0) throw terminalError instanceof Error ? terminalError : new Error(String(terminalError));
710
+ const hostInstanceId = status.host?.instanceId;
711
+ if (hostInstanceId !== expectedInstanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local client entry: the handoff Client is no longer authenticated to the expected Host instance");
712
+ if (status.transport !== "connected") throw new Error("local client entry: the handoff Client has no connected official transport");
713
+ if (status.surfaceMounted !== true) throw new Error("local client entry: the handoff Client surface is not mounted");
714
+ return { hostInstanceId };
715
+ }
716
+ /** Read the one-shot handoff expectation; absent outside a replacement Client. */
717
+ function expectedHostInstanceFromEnvironment(mode) {
718
+ const raw = process.env.SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID;
719
+ if (raw === void 0 || raw === "") return void 0;
720
+ if (mode !== "surface") throw new Error("local client entry: SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID requires surface mode");
721
+ if (!INSTANCE_ID_PATTERN.test(raw)) throw new Error("local client entry: SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID must be a Host instance UUID");
722
+ return raw;
723
+ }
724
+ /**
725
+ * The internal reexec probe is one SIGUSR2 consumer; it may never share the
726
+ * process with the HMR, private-RPC or T34 qualification SIGUSR2 handlers, and
727
+ * a replacement Client may not also be a probe Client.
728
+ */
729
+ function assertHandoffSignalExclusivity(mode, expectedInstanceId) {
730
+ const reexecProbe = process.env.SPLIT_PROCESS_CLIENT_REEXEC_PROBE === "1";
731
+ const otherSignalMode = process.env.SPLIT_PROCESS_CLIENT_HMR_PROBE === "1" || process.env.SPLIT_PROCESS_CLIENT_PRIVATE_RPC_PROOF === "1" || (process.env.SPLIT_PROCESS_CLIENT_HOLD_SERIALIZE ?? "") !== "";
732
+ if (!reexecProbe) {
733
+ if (expectedInstanceId !== void 0 && otherSignalMode) throw new Error("local client entry: a handoff Client may not inherit another SIGUSR2 qualification mode");
734
+ return;
735
+ }
736
+ if (mode !== "surface") throw new Error("local client entry: the reexec probe requires surface mode");
737
+ if (otherSignalMode) throw new Error("local client entry: the reexec qualification signal is mutually exclusive with the HMR/private-RPC/T34 SIGUSR2 modes");
738
+ if (expectedInstanceId !== void 0) throw new Error("local client entry: the reexec probe and the handoff expectation are mutually exclusive");
739
+ }
740
+ function createInteractionStartupGate() {
741
+ let resolveBarrier;
742
+ let rejectBarrier;
743
+ let state = "pending";
744
+ const barrier = new Promise((resolve, reject) => {
745
+ resolveBarrier = resolve;
746
+ rejectBarrier = reject;
747
+ });
748
+ return {
749
+ plugin: async () => {
750
+ await barrier;
751
+ },
752
+ get pending() {
753
+ return state === "pending";
754
+ },
755
+ release() {
756
+ if (state !== "pending") return;
757
+ state = "released";
758
+ resolveBarrier?.();
759
+ },
760
+ cancel(reason) {
761
+ if (state !== "pending") return;
762
+ state = "cancelled";
763
+ rejectBarrier?.(reason);
764
+ }
765
+ };
766
+ }
767
+ /** Production fail-closed preflight for the interaction startup gate.
768
+ *
769
+ * The Gateway's event pump must not start merely because the Session plugin
770
+ * mounted: the official `typert.contexts` Agent resolver is the exact target
771
+ * every forwarded request needs. A missing resolver is a startup failure, not
772
+ * a later `next()` fallback that would irreversibly settle a Host request.
773
+ */
774
+ function assertInteractionStartupReady(gate, agentResolver) {
775
+ if (!gate.pending) throw new Error("local client entry: the interaction startup gate failed before the transport install");
776
+ if (agentResolver === void 0) throw new Error("local client entry: the official Session Agent resolver did not install");
777
+ }
778
+ const PEER_ABORTED = Symbol("peer-request-aborted");
779
+ /**
780
+ * The qualification-only non-TUI answering Peer: it registers the two official
781
+ * `$on` listeners and holds each forwarded request until the smoke sends the
782
+ * exact `peer-answer` control record. It never renders, never takes the TUI
783
+ * seat and never invents a Host decision.
784
+ */
785
+ function createPeerInteractionSeat(remote, sessions, emit) {
786
+ const pending = /* @__PURE__ */ new Map();
787
+ const owned = [];
788
+ let sequence = 0;
789
+ const KEY = (kind, key) => `${kind}:${key}`;
790
+ const waitForAnswer = async (kind, callId, signal) => {
791
+ return await new Promise((resolve) => {
792
+ let settled = false;
793
+ const settle = (value) => {
794
+ if (settled) return;
795
+ settled = true;
796
+ signal?.removeEventListener("abort", onAbort);
797
+ pending.delete(KEY(kind, callId));
798
+ resolve(value);
799
+ };
800
+ const onAbort = () => {
801
+ settle(PEER_ABORTED);
802
+ };
803
+ pending.set(KEY(kind, callId), settle);
804
+ if (signal?.aborted === true) onAbort();
805
+ else signal?.addEventListener("abort", onAbort, { once: true });
806
+ });
807
+ };
808
+ owned.push(remote.$on("user-questions/request", async function(request, next) {
809
+ const sessionId = sessions.scopeOf(this);
810
+ if (sessionId === void 0) return next();
811
+ const callId = request.wait?.callId;
812
+ const peerKey = typeof callId === "string" ? callId : `question-${++sequence}`;
813
+ emit({
814
+ m4a0: "peer-interaction",
815
+ kind: "question",
816
+ peerKey,
817
+ callId: typeof callId === "string" ? callId : void 0,
818
+ sessionId
819
+ });
820
+ const value = await waitForAnswer("question", peerKey, request.signal);
821
+ if (value === PEER_ABORTED) throw new Error("local client entry: peer question request aborted");
822
+ return value;
823
+ }));
824
+ owned.push(remote.$on("approval/request", async function(request, next) {
825
+ const sessionId = sessions.scopeOf(this);
826
+ if (sessionId === void 0) return next();
827
+ const callId = request.callId;
828
+ const peerKey = typeof callId === "string" ? callId : `approval-${++sequence}`;
829
+ emit({
830
+ m4a0: "peer-interaction",
831
+ kind: "approval",
832
+ peerKey,
833
+ callId: typeof callId === "string" ? callId : void 0,
834
+ sessionId
835
+ });
836
+ const value = await waitForAnswer("approval", peerKey, request.signal);
837
+ if (value === PEER_ABORTED) throw new Error("local client entry: peer approval request aborted");
838
+ return value;
839
+ }));
840
+ return {
841
+ answer(kind, callId, value) {
842
+ const settle = pending.get(KEY(kind, callId));
843
+ if (settle === void 0) return false;
844
+ settle(value);
845
+ return true;
846
+ },
847
+ dispose() {
848
+ for (const off of owned.splice(0)) off();
849
+ for (const settle of [...pending.values()]) settle(PEER_ABORTED);
850
+ }
851
+ };
852
+ }
853
+ /** Qualification-only read-only observer of the official transport frames.
854
+ * It records the Gateway `$events` clientId/eventId without changing any
855
+ * Gateway method or frame. */
856
+ function observeQualificationSocket(socket, emit) {
857
+ let clientId;
858
+ socket.addEventListener("message", (event) => {
859
+ const data = event.data;
860
+ const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : data instanceof ArrayBuffer ? Buffer.from(data).toString("utf8") : ArrayBuffer.isView(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8") : "";
861
+ if (text === "") return;
862
+ const client = /"clientId":"([^"]+)"/u.exec(text);
863
+ if (client !== null) clientId = client[1];
864
+ const eventId = /"eventId":"([^"]+)"/u.exec(text);
865
+ if (eventId === null) return;
866
+ emit({
867
+ m4a0: "peer-frame",
868
+ event: /"event":"([^"]+)"/u.exec(text)?.[1] ?? "unknown",
869
+ eventId: eventId[1],
870
+ ...clientId === void 0 ? {} : { clientId }
871
+ });
872
+ });
873
+ }
874
+ /**
875
+ * Run one Client-only process until its launcher requests shutdown. Exported
876
+ * for the qualification harness; `import.meta.main` is the only production
877
+ * caller.
878
+ */
879
+ async function runLocalClientEntry(options) {
880
+ const expectedHostInstanceId = expectedHostInstanceFromEnvironment(options.mode);
881
+ assertHandoffSignalExclusivity(options.mode, expectedHostInstanceId);
882
+ const hostModules = await loadOfficialClientHost(options.dshAnchor);
883
+ const dshHome = hostModules.resolveDshHome();
884
+ const packageRoot = installedPackageRootFromEntry(import.meta.url);
885
+ const profileDir = hostModules.resolveProfileDir(options.profile, dshHome);
886
+ const scope = scopeFromInstalledProfile({
887
+ dshHome,
888
+ profileDir,
889
+ packageRoot,
890
+ dshVersion: readInstalledDshVersion(options.dshAnchor)
891
+ });
892
+ const processStartIdentity = readLinuxStarttime();
893
+ const recordSink = options.mode === "surface" ? createSurfaceRecordSink() : void 0;
894
+ const emit = recordSink?.emit ?? writeEntryRecord;
895
+ emit({
896
+ m4a0: "client-started",
897
+ processRole: "client",
898
+ pid: process.pid,
899
+ phase: "startup"
900
+ });
901
+ const seat = options.mode === "peer" ? { close: async () => {} } : await bindProcessSeat(scope.clientSeatSocketName, "CLIENT_ALREADY_ACTIVE");
902
+ let context;
903
+ let loaderFiber;
904
+ let startupGate;
905
+ let installedTransport;
906
+ let transport;
907
+ let domainPrerequisites;
908
+ let mountedDomains;
909
+ let interactionDelivery;
910
+ let peerSeat;
911
+ let handle;
912
+ /** The ONE accepted one-shot handoff intent (never a second Client owner). */
913
+ let reexecIntent;
914
+ /** The reexec request latch of the qualification-only SIGUSR2 probe. */
915
+ let reexecHandler;
916
+ /** Set only when the ORIGINAL stop chain released every Client resource. */
917
+ let reexecTeardownSucceeded = false;
918
+ /** The ONE replacement child while the old PID waits as its parent. */
919
+ let reexecChild;
920
+ /** A termination signal arrived after the handoff was accepted, before spawn. */
921
+ let reexecCancelled = false;
922
+ /** The CURRENT revision's surface bridge behind the ONE root `appExit`. */
923
+ let activeBridge;
924
+ /** The ONE serial revision task slot shared by HMR and stop. */
925
+ let revisionTask = Promise.resolve();
926
+ const enqueueRevisionTask = (task) => {
927
+ const run = revisionTask.then(task, task);
928
+ revisionTask = run.then(() => {}, () => {});
929
+ return run;
930
+ };
931
+ const diag = createEntryDiag("client", recordSink?.emit);
932
+ const CLIENT_DISPOSE_DEADLINE_MS = 1e4;
933
+ const disposeWithinDeadline = async (dispose, errors) => {
934
+ let timer;
935
+ const deadline = new Promise((resolve) => {
936
+ timer = setTimeout(() => resolve(true), CLIENT_DISPOSE_DEADLINE_MS);
937
+ });
938
+ const done = dispose().then(() => false, (error) => {
939
+ errors.push(error);
940
+ return false;
941
+ });
942
+ const timedOut = await Promise.race([done, deadline]);
943
+ if (timer !== void 0) clearTimeout(timer);
944
+ if (timedOut) errors.push(/* @__PURE__ */ new Error("local client entry: client disposal deadline exceeded"));
945
+ return timedOut;
946
+ };
947
+ const forceExitAfterCleanupFailure = () => {
948
+ process.stdin.pause();
949
+ setImmediate(() => {
950
+ process.exit(1);
951
+ });
952
+ };
953
+ let stopping;
954
+ /** Resolves when the ONE startup chain has been entered/finished. A stop
955
+ * that lands before `startupPromise` exists waits here instead of disposing
956
+ * the root underneath a late `startLocalClient` call. */
957
+ let startupReadyResolve;
958
+ const startupReady = new Promise((resolve) => {
959
+ startupReadyResolve = resolve;
960
+ });
961
+ /** The ONE startup cancellation owner: a stop aborts every in-flight mount
962
+ * and readiness wait before any teardown starts. */
963
+ const startupAbort = new AbortController();
964
+ /** The in-flight ONE startup chain; `stop` awaits it before disposing. */
965
+ let startupPromise;
966
+ /** Whether the transport/root release already happened (single-root latch). */
967
+ let rootReleased = false;
968
+ let resolveStopped;
969
+ const stopped = new Promise((resolve) => {
970
+ resolveStopped = resolve;
971
+ });
972
+ let terminalError;
973
+ let compositionDone = false;
974
+ const stop = (code, failure) => {
975
+ if (stopping !== void 0) return stopping;
976
+ startupAbort.abort(failure ?? /* @__PURE__ */ new Error("local client entry: stop requested during startup"));
977
+ stopping = (async () => {
978
+ if (failure !== void 0) {
979
+ const primary = failure instanceof Error ? failure : new Error(String(failure));
980
+ emit({
981
+ m4a0: "failure",
982
+ processRole: "client",
983
+ phase: context === void 0 ? "startup" : "after-context",
984
+ pid: process.pid,
985
+ ...failure instanceof LocalScopeError ? { code: failure.code } : {},
986
+ error: primary.message,
987
+ ...primary.stack === void 0 ? {} : { stack: primary.stack }
988
+ });
989
+ }
990
+ const errors = [];
991
+ const timedOut = await disposeWithinDeadline(async () => {
992
+ if (rootReleased) return;
993
+ if (startupPromise === void 0 && context !== void 0 && !compositionDone) await startupReady;
994
+ if (startupPromise !== void 0 && handle === void 0) try {
995
+ handle = await startupPromise;
996
+ } catch {}
997
+ if (handle !== void 0) {
998
+ await revisionTask;
999
+ try {
1000
+ await handle.dispose();
1001
+ } catch (error) {
1002
+ errors.push(error);
1003
+ }
1004
+ rootReleased = true;
1005
+ return;
1006
+ }
1007
+ try {
1008
+ interactionDelivery?.dispose();
1009
+ } catch (error) {
1010
+ errors.push(error);
1011
+ }
1012
+ try {
1013
+ peerSeat?.dispose();
1014
+ } catch (error) {
1015
+ errors.push(error);
1016
+ }
1017
+ try {
1018
+ await transport?.dispose();
1019
+ } catch (error) {
1020
+ errors.push(error);
1021
+ }
1022
+ try {
1023
+ await domainPrerequisites?.dispose();
1024
+ } catch (error) {
1025
+ errors.push(error);
1026
+ }
1027
+ try {
1028
+ await mountedDomains?.dispose();
1029
+ } catch (error) {
1030
+ errors.push(error);
1031
+ }
1032
+ startupGate?.cancel(failure ?? /* @__PURE__ */ new Error("local client entry: stop requested during startup"));
1033
+ try {
1034
+ await loaderFiber?.dispose();
1035
+ } catch (error) {
1036
+ errors.push(error);
1037
+ }
1038
+ try {
1039
+ await context?.fiber.dispose();
1040
+ } catch (error) {
1041
+ errors.push(error);
1042
+ }
1043
+ rootReleased = true;
1044
+ }, errors);
1045
+ if (options.mode === "surface" && handle !== void 0) emit({
1046
+ m4b2s: "client-closed",
1047
+ ...traceStatus(handle.status)
1048
+ });
1049
+ const transportCleanupFailed = errors.some((error) => error instanceof Error && error.cleanupFailed === true);
1050
+ if (errors.length > 0 || timedOut) {
1051
+ const primary = errors[0] instanceof Error ? errors[0] : new Error(String(errors[0] ?? "client disposal failed"));
1052
+ emit({
1053
+ m4a0: "cleanup-failure",
1054
+ processRole: "client",
1055
+ phase: "shutdown",
1056
+ pid: process.pid,
1057
+ error: primary.message
1058
+ });
1059
+ process.exitCode = 1;
1060
+ } else if (failure !== void 0) {
1061
+ emit({
1062
+ m4a0: "cleanup",
1063
+ processRole: "client",
1064
+ phase: "after-context",
1065
+ pid: process.pid,
1066
+ status: "completed"
1067
+ });
1068
+ process.exitCode = 1;
1069
+ } else {
1070
+ process.exitCode = code;
1071
+ if (code === 0 && reexecIntent !== void 0) reexecTeardownSucceeded = true;
1072
+ }
1073
+ process.stdin.pause();
1074
+ resolveStopped?.();
1075
+ if (timedOut || transportCleanupFailed) forceExitAfterCleanupFailure();
1076
+ })();
1077
+ return stopping;
1078
+ };
1079
+ process.on("SIGTERM", () => {
1080
+ emit({
1081
+ m4a0: "signal",
1082
+ processRole: "client",
1083
+ pid: process.pid,
1084
+ signal: "SIGTERM"
1085
+ });
1086
+ if (routeReexecTermination(reexecIntent !== void 0, reexecChild, "SIGTERM", () => {
1087
+ reexecCancelled = true;
1088
+ })) return;
1089
+ runDetached("local client: SIGTERM shutdown", () => stop(0), { diag });
1090
+ });
1091
+ process.on("SIGINT", () => {
1092
+ emit({
1093
+ m4a0: "signal",
1094
+ processRole: "client",
1095
+ pid: process.pid,
1096
+ signal: "SIGINT"
1097
+ });
1098
+ if (routeReexecTermination(reexecIntent !== void 0, reexecChild, "SIGINT", () => {
1099
+ reexecCancelled = true;
1100
+ })) return;
1101
+ runDetached("local client: SIGINT shutdown", () => stop(130), { diag });
1102
+ });
1103
+ /**
1104
+ * The structured status of the transport for a record. Surface mode strips
1105
+ * the private Host home path; the qualification channel keeps its frozen
1106
+ * shape. Cookie/token values never enter a record on either path.
1107
+ */
1108
+ const traceTransportStatus = () => {
1109
+ if (transport === void 0) return {};
1110
+ const observed = transport.status();
1111
+ if (options.mode !== "surface") return observed;
1112
+ const { hostHome: _hostHome, ...safe } = observed;
1113
+ return safe;
1114
+ };
1115
+ /**
1116
+ * The same projection for the handle status (surface mode strips the Host
1117
+ * home path; the qualification status shape is unchanged).
1118
+ */
1119
+ const traceStatus = (status) => {
1120
+ if (options.mode !== "surface") return status;
1121
+ const { hostHome: _hostHome, ...safe } = status;
1122
+ return safe;
1123
+ };
1124
+ try {
1125
+ const host = await ensureLocalHost({
1126
+ scope,
1127
+ hostEntryPath: join(packageRoot, "dist", "local-host.mjs"),
1128
+ dshAnchor: options.dshAnchor,
1129
+ profile: options.profile,
1130
+ ...expectedHostInstanceId === void 0 ? {} : { expectedInstanceId: expectedHostInstanceId }
1131
+ });
1132
+ startupAbort.signal.throwIfAborted();
1133
+ emit({
1134
+ m4a0: "host-authenticated",
1135
+ processRole: "client",
1136
+ pid: process.pid,
1137
+ phase: "host-authenticated",
1138
+ host: hostRecordForTrace(host)
1139
+ });
1140
+ const loadedProfile = hostModules.loadProfile("split-process-client", options.profile, options.dshAnchor);
1141
+ const resolution = await hostModules.createRuntimeResolution({
1142
+ installAnchor: options.dshAnchor,
1143
+ profile: loadedProfile
1144
+ });
1145
+ context = new hostModules.Context();
1146
+ await context.plugin(hostModules.PluginPackages, { resolution });
1147
+ emit({
1148
+ m4a0: "context-ready",
1149
+ processRole: "client",
1150
+ pid: process.pid,
1151
+ phase: "context-ready"
1152
+ });
1153
+ const transportModule = await import("./local-transport-C9aonplC.mjs");
1154
+ const { mountSurfaceClientDomainPrerequisites, startLocalClient } = await import("./client-bootstrap-DwSFzcTW.mjs");
1155
+ const onTransportFatal = (error) => {
1156
+ terminalError ??= error;
1157
+ if (compositionDone) runDetached("local client: terminal transport identity failure", () => stop(1, terminalError), { diag });
1158
+ };
1159
+ if (options.mode === "surface" || options.mode === "peer") {
1160
+ const clientContext = context;
1161
+ if (clientContext === void 0) throw new Error("local client entry: the Client root Context is missing");
1162
+ loaderFiber = clientContext.plugin(hostModules.Loader, {});
1163
+ await loaderFiber;
1164
+ const loader = clientContext.get("loader");
1165
+ if (loader === void 0) throw new Error("local client entry: the official Cordis Loader did not install");
1166
+ startupGate = createInteractionStartupGate();
1167
+ loader.builtins[INTERACTION_STARTUP_GATE] = startupGate.plugin;
1168
+ await loader.create({ name: `cordis:${INTERACTION_STARTUP_GATE}` });
1169
+ startupAbort.signal.throwIfAborted();
1170
+ if (!startupGate.pending) throw new Error("local client entry: the interaction startup gate failed before the transport install");
1171
+ const gateHold = process.env.SPLIT_PROCESS_CLIENT_HOLD_STARTUP_GATE;
1172
+ if (gateHold !== void 0 && gateHold !== "") {
1173
+ emit({
1174
+ m4b2s: "qualification",
1175
+ op: "startup-gate-hold",
1176
+ stage: "loader-gate",
1177
+ barrier: gateHold
1178
+ });
1179
+ await waitForStartupHold(gateHold, startupAbort.signal);
1180
+ }
1181
+ installedTransport = await transportModule.installLocalTransport(clientContext, {
1182
+ dshAnchor: options.dshAnchor,
1183
+ host,
1184
+ scope,
1185
+ diag,
1186
+ signal: startupAbort.signal,
1187
+ onFatal: onTransportFatal,
1188
+ ...options.mode === "peer" ? { qualificationWebSocketObserver: (_url, socket) => observeQualificationSocket(socket, emit) } : {}
1189
+ });
1190
+ transport = installedTransport;
1191
+ startupAbort.signal.throwIfAborted();
1192
+ domainPrerequisites = await mountSurfaceClientDomainPrerequisites(clientContext, { dshAnchor: options.dshAnchor });
1193
+ const remote = clientContext.get("remote");
1194
+ if (remote === void 0) throw new Error("local client entry: the official Client Remote service did not install");
1195
+ const remoteService = clientContext.get("remote");
1196
+ if (options.mode === "surface") interactionDelivery = createSplitClientInteractionDelivery({
1197
+ remote,
1198
+ sessions: domainPrerequisites.sessions
1199
+ });
1200
+ else peerSeat = createPeerInteractionSeat(remote, domainPrerequisites.sessions, emit);
1201
+ const agentResolver = clientContext.get("typert")?.contexts.getClient("agent");
1202
+ assertInteractionStartupReady(startupGate, agentResolver);
1203
+ emit({
1204
+ m4b2s: "qualification",
1205
+ op: "interaction-startup-gate",
1206
+ phase: "listeners-ready",
1207
+ agentResolver: agentResolver !== void 0,
1208
+ questionListeners: 1,
1209
+ approvalListeners: 1,
1210
+ loaderTasks: loader.getTasks().length
1211
+ });
1212
+ startupGate.release();
1213
+ transport = await transportModule.awaitLocalTransportReady(installedTransport, { signal: startupAbort.signal });
1214
+ if (terminalError !== void 0) {
1215
+ await stop(1, terminalError);
1216
+ return;
1217
+ }
1218
+ emit({
1219
+ m4a0: "transport-ready",
1220
+ processRole: "client",
1221
+ pid: process.pid,
1222
+ phase: "transport-ready",
1223
+ ...traceTransportStatus()
1224
+ });
1225
+ mountedDomains = await domainPrerequisites.complete({ signal: startupAbort.signal });
1226
+ domainPrerequisites = void 0;
1227
+ startupAbort.signal.throwIfAborted();
1228
+ emit({
1229
+ m4b2s: "qualification",
1230
+ op: "startup-stage",
1231
+ stage: "domains-ready",
1232
+ pid: process.pid
1233
+ });
1234
+ if (options.mode === "peer") {
1235
+ emit({
1236
+ m4a0: "ready",
1237
+ processRole: "client",
1238
+ pid: process.pid,
1239
+ phase: "peer-ready",
1240
+ mode: "peer",
1241
+ hostPid: host.identity.hostPid,
1242
+ hostInstanceId: host.identity.instanceId,
1243
+ ...traceTransportStatus()
1244
+ });
1245
+ compositionDone = true;
1246
+ attachEntryControl(async (request) => {
1247
+ if (request.op === "status") {
1248
+ emit({
1249
+ m4a0: "status",
1250
+ pid: process.pid,
1251
+ ...traceTransportStatus()
1252
+ });
1253
+ return false;
1254
+ }
1255
+ if (request.op === "peer-answer") {
1256
+ const kind = request.kind;
1257
+ const callId = request.callId;
1258
+ const value = request.value;
1259
+ if (kind !== "question" && kind !== "approval" || typeof callId !== "string") {
1260
+ emit({
1261
+ m4a0: "control-error",
1262
+ error: "peer-answer requires kind/callId/value"
1263
+ });
1264
+ return false;
1265
+ }
1266
+ const delivered = peerSeat?.answer(kind, callId, value) === true;
1267
+ emit({
1268
+ m4a0: "peer-answer-sent",
1269
+ kind,
1270
+ callId,
1271
+ delivered
1272
+ });
1273
+ return false;
1274
+ }
1275
+ if (request.op === "peer-send-stale-result") {
1276
+ const eventId = request.eventId;
1277
+ const clientId = request.clientId;
1278
+ const outcome = request.value;
1279
+ if (typeof eventId !== "string" || typeof clientId !== "string" || outcome === void 0) {
1280
+ emit({
1281
+ m4a0: "control-error",
1282
+ error: "peer-send-stale-result requires eventId/clientId/value"
1283
+ });
1284
+ return false;
1285
+ }
1286
+ const connection = clientContext.get("connection");
1287
+ if (connection === void 0) throw new Error("local client entry: the qualification Peer has no Connection RPC");
1288
+ const response = await connection.rpc.call("/api", "$events/result", { args: {
1289
+ clientId,
1290
+ eventId,
1291
+ outcome
1292
+ } });
1293
+ emit({
1294
+ m4a0: "peer-stale-result-sent",
1295
+ eventId,
1296
+ clientId,
1297
+ ok: response.ok === true,
1298
+ ...response.error?.code === void 0 ? {} : { errorCode: response.error.code }
1299
+ });
1300
+ return false;
1301
+ }
1302
+ if (request.op === "peer-question-answer") {
1303
+ const sessionId = request.sessionId;
1304
+ const callId = request.callId;
1305
+ const value = request.value;
1306
+ if (typeof sessionId !== "string" || typeof callId !== "string" || value === void 0) {
1307
+ emit({
1308
+ m4a0: "control-error",
1309
+ error: "peer-question-answer requires sessionId/callId/value"
1310
+ });
1311
+ return false;
1312
+ }
1313
+ if (remoteService?.userQuestions === void 0) throw new Error("local client entry: the qualification Peer has no userQuestions namespace");
1314
+ const result = await remoteService.userQuestions.answer(sessionId, callId, value);
1315
+ emit({
1316
+ m4a0: "peer-question-answer",
1317
+ sessionId,
1318
+ callId,
1319
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId },
1320
+ ok: result.ok === true,
1321
+ ...result.ok ? { value: result.value === true } : {
1322
+ errorCode: result.error?.code,
1323
+ error: result.error
1324
+ }
1325
+ });
1326
+ return false;
1327
+ }
1328
+ if (request.op === "shutdown") {
1329
+ await stop(0);
1330
+ return true;
1331
+ }
1332
+ emit({
1333
+ m4a0: "control-error",
1334
+ error: `local client entry: unknown op ${JSON.stringify(request.op)}`
1335
+ });
1336
+ return false;
1337
+ });
1338
+ await stopped;
1339
+ return;
1340
+ }
1341
+ } else {
1342
+ transport = await transportModule.startLocalTransport(context, {
1343
+ dshAnchor: options.dshAnchor,
1344
+ host,
1345
+ scope,
1346
+ diag,
1347
+ onFatal: onTransportFatal
1348
+ });
1349
+ if (terminalError !== void 0) {
1350
+ await stop(1, terminalError);
1351
+ return;
1352
+ }
1353
+ emit({
1354
+ m4a0: "transport-ready",
1355
+ processRole: "client",
1356
+ pid: process.pid,
1357
+ phase: "transport-ready",
1358
+ ...traceTransportStatus()
1359
+ });
1360
+ }
1361
+ if (process.env.SPLIT_PROCESS_CLIENT_FORCE_FAILURE === "client-bootstrap") throw new Error("local client entry: qualification forced client bootstrap failure");
1362
+ const clientContext = context;
1363
+ if (clientContext === void 0) throw new Error("local client entry: the Client root Context is missing");
1364
+ const surfaceFacts = surfaceStartupFacts(options);
1365
+ /**
1366
+ * The ONE allowed process-composition edge into `app/bootstrap.ts`
1367
+ * (architecture gate: exact lazy dynamic import, this entry only). It runs
1368
+ * only AFTER `PluginPackages` installed the official runtime resolution and
1369
+ * the Client bootstrap mounted the official Domain/UI/application graph; it
1370
+ * mounts the runner as its own Cordis fiber on the SAME Client Context.
1371
+ */
1372
+ const mountRunner = async (input) => {
1373
+ const bridge = createLocalClientSurfaceBridge((code) => {
1374
+ runDetached("local client: surface exit", () => stop(code), { diag });
1375
+ });
1376
+ activeBridge = bridge;
1377
+ const { applyRunnerWithRuntime } = await import("./bootstrap-DLOydLLj.mjs");
1378
+ let runnerFiber;
1379
+ try {
1380
+ runnerFiber = clientContext.plugin((pluginContext) => {
1381
+ applyRunnerWithRuntime(pluginContext, input.config, input.override, {
1382
+ surfaceReady: () => bridge.markMounted(),
1383
+ surfaceFailed: (error) => bridge.fail(error),
1384
+ ...reexecHandler === void 0 ? {} : { requestClientReload: () => reexecHandler.request("manual") }
1385
+ });
1386
+ });
1387
+ await runnerFiber;
1388
+ } catch (error) {
1389
+ bridge.fail(error);
1390
+ throw error;
1391
+ }
1392
+ const fiber = runnerFiber;
1393
+ return {
1394
+ ready: bridge.ready,
1395
+ stopped: bridge.stopped,
1396
+ dispose: async () => {
1397
+ await fiber.dispose();
1398
+ },
1399
+ ...fiber.uid == null ? {} : { fiberUid: fiber.uid }
1400
+ };
1401
+ };
1402
+ if (options.mode === "surface") {
1403
+ clientContext.provide("appExit", (code) => {
1404
+ activeBridge?.requestStop(code);
1405
+ });
1406
+ if (process.env.SPLIT_PROCESS_CLIENT_HMR_PROBE === "1") {
1407
+ if (process.env.SPLIT_PROCESS_CLIENT_PRIVATE_RPC_PROOF === "1" || process.env.SPLIT_PROCESS_CLIENT_REEXEC_PROBE === "1" || process.env.SPLIT_PROCESS_CLIENT_HOLD_SERIALIZE !== void 0 && process.env.SPLIT_PROCESS_CLIENT_HOLD_SERIALIZE !== "") throw new Error("local client entry: the HMR qualification signal is mutually exclusive with the T34/T36/reexec SIGUSR2 modes");
1408
+ process.on("SIGUSR2", () => {
1409
+ if (handle === void 0) return;
1410
+ runDetached("local client: surface HMR", () => {
1411
+ return enqueueRevisionTask(async () => {
1412
+ await handle.replaceSurfaceForQualification();
1413
+ }).catch((error) => stop(1, error));
1414
+ }, { diag });
1415
+ });
1416
+ }
1417
+ const reexecProbe = process.env.SPLIT_PROCESS_CLIENT_REEXEC_PROBE === "1";
1418
+ const targetOverride = reexecProbe ? process.env.SPLIT_PROCESS_CLIENT_REEXEC_TARGET_PACKAGE_ROOT : void 0;
1419
+ if (targetOverride !== void 0 && targetOverride !== "" && !isAbsolute(targetOverride)) throw new Error("local client entry: SPLIT_PROCESS_CLIENT_REEXEC_TARGET_PACKAGE_ROOT must be an absolute path");
1420
+ reexecHandler = createClientReexecRequestHandler({
1421
+ status: () => handle?.status,
1422
+ prepare: (status, source) => prepareClientReexec({
1423
+ status,
1424
+ verifiedHostInstanceId: host.identity.instanceId,
1425
+ profileDir,
1426
+ dshAnchor: options.dshAnchor,
1427
+ profile: options.profile,
1428
+ dshVersion: scope.dshVersion,
1429
+ currentBuildId: scope.buildId,
1430
+ ...source === "qualification" && reexecProbe && targetOverride !== void 0 && targetOverride !== "" ? { targetPackageRootOverride: targetOverride } : {}
1431
+ }),
1432
+ requestStop: () => {
1433
+ runDetached("local client: reexec handoff", () => stop(0), { diag });
1434
+ },
1435
+ emit,
1436
+ canRequest: () => stopping === void 0,
1437
+ onAccepted: (accepted) => {
1438
+ reexecIntent = accepted;
1439
+ }
1440
+ });
1441
+ if (reexecProbe) process.on("SIGUSR2", () => {
1442
+ reexecHandler?.request("qualification");
1443
+ });
1444
+ const onTerminalEnd = () => {
1445
+ runDetached("local client: terminal EOF shutdown", () => stop(0), { diag });
1446
+ };
1447
+ process.stdin.on("end", onTerminalEnd);
1448
+ process.stdin.on("close", onTerminalEnd);
1449
+ process.on("SIGUSR1", () => {
1450
+ transport?.dropWebSocketsForQualification();
1451
+ emit({
1452
+ m4b2s: "qualification",
1453
+ op: "drop-websocket",
1454
+ processRole: "client",
1455
+ pid: process.pid
1456
+ });
1457
+ });
1458
+ }
1459
+ const composition = options.mode === "surface" ? {
1460
+ mode: "surface",
1461
+ signal: startupAbort.signal,
1462
+ transport,
1463
+ host: host.identity,
1464
+ dshAnchor: options.dshAnchor,
1465
+ authenticatedFetch: transport.authenticatedFetch,
1466
+ domains: mountedDomains,
1467
+ interactionDelivery,
1468
+ mountRunner,
1469
+ diag,
1470
+ onStatus: (status) => {
1471
+ emit({
1472
+ m4b2s: "surface-status",
1473
+ ...traceStatus(status)
1474
+ });
1475
+ },
1476
+ onQualification: (record) => {
1477
+ emit({
1478
+ m4b2s: "qualification",
1479
+ ...record
1480
+ });
1481
+ }
1482
+ } : {
1483
+ mode: "qualification",
1484
+ transport,
1485
+ host: host.identity
1486
+ };
1487
+ try {
1488
+ const holdBeforeStart = process.env.SPLIT_PROCESS_CLIENT_HOLD_BEFORE_START;
1489
+ if (holdBeforeStart !== void 0 && holdBeforeStart !== "") {
1490
+ emit({
1491
+ m4a0: "qualification",
1492
+ op: "before-start-hold",
1493
+ processRole: "client",
1494
+ pid: process.pid
1495
+ });
1496
+ await waitForStartupHold(holdBeforeStart, startupAbort.signal);
1497
+ }
1498
+ startupPromise = startLocalClient(clientContext, surfaceFacts, processStartIdentity, composition);
1499
+ handle = await startupPromise;
1500
+ } finally {
1501
+ startupReadyResolve?.();
1502
+ startupReadyResolve = void 0;
1503
+ }
1504
+ if (stopping !== void 0) {
1505
+ await stopping;
1506
+ return;
1507
+ }
1508
+ if (terminalError !== void 0) {
1509
+ await stop(1, terminalError);
1510
+ return;
1511
+ }
1512
+ if (expectedHostInstanceId !== void 0) {
1513
+ const restoredHost = handle.status.host;
1514
+ if (restoredHost === void 0 || restoredHost.instanceId !== expectedHostInstanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local client entry: the handoff Client authenticated a different Host instance");
1515
+ if (handle.status.transport !== "connected") throw new Error("local client entry: the handoff Client has no connected official transport");
1516
+ const proof = await handle.awaitHandoffOpen(surfaceFacts.sessionId, startupAbort.signal);
1517
+ if (stopping !== void 0) {
1518
+ await stopping;
1519
+ return;
1520
+ }
1521
+ const restored = handle.status;
1522
+ const restoredFacts = assertHandoffRestored(restored, expectedHostInstanceId, terminalError);
1523
+ proof.verify();
1524
+ emit({
1525
+ m4r: "handoff-restored",
1526
+ processRole: "client",
1527
+ pid: process.pid,
1528
+ expectedHostInstanceId,
1529
+ hostInstanceId: restoredFacts.hostInstanceId,
1530
+ ...surfaceFacts.sessionId === void 0 ? {} : { sessionId: surfaceFacts.sessionId },
1531
+ clientBuildId: scope.buildId,
1532
+ transport: restored.transport,
1533
+ sessionOpen: restored.sessionOpen,
1534
+ sessionHistoryOpen: surfaceFacts.sessionId !== void 0,
1535
+ surfaceMounted: restored.surfaceMounted
1536
+ });
1537
+ }
1538
+ emit({
1539
+ m4a0: "ready",
1540
+ ...traceStatus(handle.status)
1541
+ });
1542
+ compositionDone = true;
1543
+ if (options.mode === "surface") {
1544
+ await stopped;
1545
+ return;
1546
+ }
1547
+ attachEntryControl(async (request) => {
1548
+ if (request.op === "status") {
1549
+ emit({
1550
+ m4a0: "status",
1551
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId },
1552
+ ...handle.status
1553
+ });
1554
+ return false;
1555
+ }
1556
+ if (request.op === "shutdown") {
1557
+ await stop(0);
1558
+ return true;
1559
+ }
1560
+ if (request.op === "qualification-drop-websocket") {
1561
+ transport?.dropWebSocketsForQualification();
1562
+ emit({
1563
+ m4a0: "qualification",
1564
+ op: "drop-websocket",
1565
+ processRole: "client",
1566
+ pid: process.pid,
1567
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1568
+ });
1569
+ return false;
1570
+ }
1571
+ if (request.op === "qualification-host-foundation") {
1572
+ if (context === void 0) throw new Error("local client entry: the qualification probe has no Client Context");
1573
+ const { runHostFoundationProbe } = await import("./host-foundation-probe-CYHsbAw6.mjs");
1574
+ const proof = await runHostFoundationProbe(context, {
1575
+ dshAnchor: options.dshAnchor,
1576
+ host,
1577
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1578
+ });
1579
+ emit({
1580
+ ...proof,
1581
+ processRole: "client",
1582
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1583
+ });
1584
+ return false;
1585
+ }
1586
+ emit({
1587
+ m4a0: "control-error",
1588
+ error: `local client entry: unknown op ${JSON.stringify(request.op)}`
1589
+ });
1590
+ return false;
1591
+ });
1592
+ await stopped;
1593
+ } catch (error) {
1594
+ if (stopping !== void 0) {
1595
+ startupReadyResolve?.();
1596
+ await stopping;
1597
+ return;
1598
+ }
1599
+ const failure = terminalError ?? error;
1600
+ let primary = failure instanceof Error ? failure : new Error(String(failure));
1601
+ const cleanupErrors = [];
1602
+ const timedOut = await disposeWithinDeadline(async () => {
1603
+ if (rootReleased) return;
1604
+ if (handle !== void 0) {
1605
+ try {
1606
+ await handle.dispose();
1607
+ } catch (cleanupError) {
1608
+ cleanupErrors.push(cleanupError);
1609
+ }
1610
+ rootReleased = true;
1611
+ return;
1612
+ }
1613
+ try {
1614
+ interactionDelivery?.dispose();
1615
+ } catch (cleanupError) {
1616
+ cleanupErrors.push(cleanupError);
1617
+ }
1618
+ try {
1619
+ peerSeat?.dispose();
1620
+ } catch (cleanupError) {
1621
+ cleanupErrors.push(cleanupError);
1622
+ }
1623
+ try {
1624
+ await transport?.dispose();
1625
+ } catch (cleanupError) {
1626
+ cleanupErrors.push(cleanupError);
1627
+ }
1628
+ try {
1629
+ await domainPrerequisites?.dispose();
1630
+ } catch (cleanupError) {
1631
+ cleanupErrors.push(cleanupError);
1632
+ }
1633
+ try {
1634
+ await mountedDomains?.dispose();
1635
+ } catch (cleanupError) {
1636
+ cleanupErrors.push(cleanupError);
1637
+ }
1638
+ startupGate?.cancel(primary);
1639
+ try {
1640
+ await loaderFiber?.dispose();
1641
+ } catch (cleanupError) {
1642
+ cleanupErrors.push(cleanupError);
1643
+ }
1644
+ try {
1645
+ await context?.fiber.dispose();
1646
+ } catch (cleanupError) {
1647
+ cleanupErrors.push(cleanupError);
1648
+ }
1649
+ rootReleased = true;
1650
+ }, cleanupErrors);
1651
+ for (const cleanupError of cleanupErrors) primary = mergeCause(primary, cleanupError);
1652
+ const transportCleanupFailed = error instanceof Error && error.cleanupFailed === true || cleanupErrors.some((cleanupError) => cleanupError instanceof Error && cleanupError.cleanupFailed === true);
1653
+ emit({
1654
+ m4a0: "failure",
1655
+ processRole: "client",
1656
+ phase: context === void 0 ? "startup" : "after-context",
1657
+ pid: process.pid,
1658
+ ...traceTransportStatus(),
1659
+ ...failure instanceof LocalScopeError ? { code: failure.code } : {},
1660
+ error: primary.message,
1661
+ ...primary.stack === void 0 ? {} : { stack: primary.stack },
1662
+ ...primary.cause === void 0 ? {} : { cause: primary.cause instanceof Error ? primary.cause.message : String(primary.cause) }
1663
+ });
1664
+ if (options.mode === "surface" && expectedHostInstanceId !== void 0) process.stderr.write(`${handoffStartupFailureLine(failure)}\n`);
1665
+ else if (options.mode === "surface" && failure instanceof LocalScopeError && failure.code === "HOST_PROTOCOL_INCOMPATIBLE") process.stderr.write(`${surfaceStartupFailureLine(failure)}\n`);
1666
+ process.stdin.pause();
1667
+ if (cleanupErrors.length === 0 && !timedOut && !transportCleanupFailed) emit({
1668
+ m4a0: "cleanup",
1669
+ processRole: "client",
1670
+ phase: "after-context",
1671
+ pid: process.pid,
1672
+ status: "completed"
1673
+ });
1674
+ else {
1675
+ const cleanup = cleanupErrors[0] instanceof Error ? cleanupErrors[0] : new Error(String(cleanupErrors[0]));
1676
+ emit({
1677
+ m4a0: "cleanup-failure",
1678
+ processRole: "client",
1679
+ phase: "after-context",
1680
+ pid: process.pid,
1681
+ error: cleanup.message
1682
+ });
1683
+ }
1684
+ process.exitCode = 1;
1685
+ if (timedOut || transportCleanupFailed) forceExitAfterCleanupFailure();
1686
+ } finally {
1687
+ process.stdin.pause();
1688
+ const reexecExitCode = await finishClientEntryShutdown({
1689
+ seat,
1690
+ ...reexecIntent === void 0 ? {} : { reexec: {
1691
+ intent: reexecIntent,
1692
+ teardownSucceeded: reexecTeardownSucceeded,
1693
+ cancelled: () => reexecCancelled
1694
+ } },
1695
+ emit,
1696
+ stderr: (line) => {
1697
+ process.stderr.write(`${line}\n`);
1698
+ },
1699
+ onChildSpawned: (child) => {
1700
+ reexecChild = child;
1701
+ }
1702
+ });
1703
+ if (reexecExitCode !== void 0) process.exitCode = reexecExitCode;
1704
+ try {
1705
+ recordSink?.close();
1706
+ } catch (error) {
1707
+ process.exitCode = 1;
1708
+ process.stderr.write(`local client entry: closing the surface record sink failed: ${error instanceof Error ? error.message : String(error)}\n`);
1709
+ }
1710
+ }
1711
+ }
1712
+ /**
1713
+ * Dispose the Client-owned root and classify a rejecting disposer as a real
1714
+ * cleanup failure. The requested success code becomes 1; an interrupt/signal
1715
+ * code keeps its nonzero identity. Never returns the success code after a
1716
+ * failed dispose, and a second stop call is prevented by the caller's latch.
1717
+ */
1718
+ async function stopLocalClient(handle, requestedCode, emit = writeEntryRecord) {
1719
+ try {
1720
+ await handle.dispose();
1721
+ return requestedCode;
1722
+ } catch (error) {
1723
+ emit({
1724
+ m4a0: "cleanup-failure",
1725
+ processRole: "client",
1726
+ phase: "shutdown",
1727
+ pid: process.pid,
1728
+ error: error instanceof Error ? error.message : String(error),
1729
+ ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
1730
+ });
1731
+ return requestedCode === 0 ? 1 : requestedCode;
1732
+ }
1733
+ }
1734
+ /** Qualification-only hold in the pre-startup assignment window. */
1735
+ async function waitForStartupHold(path, signal) {
1736
+ const deadline = Date.now() + 6e4;
1737
+ while (!existsSync(path)) {
1738
+ signal.throwIfAborted();
1739
+ if (Date.now() > deadline) throw new Error(`local client entry: the pre-startup barrier was not released: ${path}`);
1740
+ await new Promise((resolve) => setTimeout(resolve, 20));
1741
+ }
1742
+ signal.throwIfAborted();
1743
+ }
1744
+ /**
1745
+ * The human-facing surface line for one startup failure. The live-Host
1746
+ * protocol/DSH refusal gets a dedicated, actionable line that names the code,
1747
+ * keeps the old Host untouched, requires an explicit owner-verified OS stop
1748
+ * and says that automatic in-memory migration is unsupported. It never
1749
+ * includes the registry PID, the launch URL/token or a private profile path.
1750
+ * Every other startup failure keeps the existing diagnostic.
1751
+ */
1752
+ function surfaceStartupFailureLine(error) {
1753
+ if (error instanceof LocalScopeError && error.code === "HOST_PROTOCOL_INCOMPATIBLE") return "HOST_PROTOCOL_INCOMPATIBLE: Another live local Host for this profile uses a different local protocol or DSH runtime. The Host has not been stopped or replaced. Finish or save your work in that Host, then explicitly stop that Host through its normal operating-system shutdown signal and start a compatible Host. Automatic upgrade and migration of in-memory work are not supported.";
1754
+ return `split client surface: ${error instanceof Error ? error.message : String(error)}`;
1755
+ }
1756
+ /**
1757
+ * The human-facing line for ONE replacement-Client handoff failure. It names
1758
+ * the classified reason (expected Host absent/replaced/protocol, invalid
1759
+ * replacement package, or Session history open) and says how to recover
1760
+ * manually. Only fixed entry-owned messages are surfaced: an arbitrary
1761
+ * startup/spawn error may carry a private path or PID and is replaced with a
1762
+ * generic reason. No Cookie/token/launch URL ever enters this line.
1763
+ */
1764
+ function handoffStartupFailureLine(error) {
1765
+ let reason;
1766
+ if (error instanceof LocalScopeError) {
1767
+ if (error.code === "HOST_HANDOFF_UNAVAILABLE") reason = "the expected Host is no longer available";
1768
+ else if (error.code === "HOST_IDENTITY_MISMATCH") reason = "the live local Host is not the expected instance";
1769
+ else if (error.code === "HOST_PROTOCOL_INCOMPATIBLE") reason = "the expected Host uses a different local protocol or DSH runtime";
1770
+ else reason = "the expected Host could not be authenticated";
1771
+ } else if (error instanceof Error && (error.message.startsWith("local client entry: ") || error.message.startsWith("local client reexec: "))) reason = error.message.slice(error.message.indexOf(": ") + 2);
1772
+ else reason = "the replacement Client could not restore the expected Host and Session";
1773
+ return `Client handoff failed: ${reason}. The Host was not stopped or replaced. Start a compatible Client manually to continue.`;
1774
+ }
1775
+ /**
1776
+ * Read the internal Client mode. Absent/empty keeps the frozen B1
1777
+ * `qualification` contract; `surface` is the internal real-terminal mode. Any
1778
+ * other value fails closed (never a silent default).
1779
+ */
1780
+ function clientModeFromEnvironment() {
1781
+ const raw = process.env.SPLIT_PROCESS_CLIENT_MODE;
1782
+ if (raw === void 0 || raw === "") return "qualification";
1783
+ if (raw === "qualification" || raw === "surface" || raw === "peer") return raw;
1784
+ throw new Error(`local client entry: invalid SPLIT_PROCESS_CLIENT_MODE ${JSON.stringify(raw)}; expected "qualification", "surface" or "peer"`);
1785
+ }
1786
+ /** Read the launcher environment; a missing anchor is a hard startup failure. */
1787
+ function optionsFromEnvironment() {
1788
+ const dshAnchor = process.env.SPLIT_PROCESS_DSH_ANCHOR;
1789
+ if (dshAnchor === void 0 || dshAnchor === "") throw new Error("local client entry: SPLIT_PROCESS_DSH_ANCHOR must name the installed @deepseek-ai/dsh/package.json");
1790
+ return {
1791
+ dshAnchor,
1792
+ profile: process.env.SPLIT_PROCESS_PROFILE ?? "pi-tui",
1793
+ mode: clientModeFromEnvironment()
1794
+ };
1795
+ }
1796
+ if (import.meta.main) try {
1797
+ await runLocalClientEntry(optionsFromEnvironment());
1798
+ } catch (error) {
1799
+ const record = {
1800
+ m4a0: "failure",
1801
+ processRole: "client",
1802
+ phase: "startup",
1803
+ pid: process.pid,
1804
+ ...error instanceof LocalScopeError ? { code: error.code } : {},
1805
+ error: error instanceof Error ? error.message : String(error),
1806
+ ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
1807
+ };
1808
+ if (process.env.SPLIT_PROCESS_CLIENT_MODE === "surface") {
1809
+ const handoff = process.env.SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID;
1810
+ const line = handoff === void 0 || handoff === "" ? surfaceStartupFailureLine(error) : handoffStartupFailureLine(error);
1811
+ process.stderr.write(`${line}\n`);
1812
+ } else writeEntryRecord(record);
1813
+ process.exit(1);
1814
+ }
1815
+ //#endregion
1816
+ export { ClientReexecRefusal, INTERACTION_STARTUP_GATE, assertHandoffRestored, assertHandoffSignalExclusivity, assertInteractionStartupReady, createClientReexecChildEnvironment, createClientReexecRequestHandler, createInteractionStartupGate, expectedHostInstanceFromEnvironment, finishClientEntryShutdown, handoffStartupFailureLine, inspectClientReexecTarget, prepareClientReexec, resolveProfileInstalledClientTarget, routeReexecTermination, runLocalClientEntry, stopLocalClient, surfaceStartupFailureLine };