@xmoon76/dsh-pi-tui 0.5.4 → 0.5.6

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 (50) hide show
  1. package/README.en.md +46 -42
  2. package/README.md +46 -27
  3. package/cordis.patch.yml +77 -7
  4. package/dist/bootstrap-DQ4YPL-7.mjs +113583 -0
  5. package/dist/builtins.mjs +3 -9
  6. package/dist/{runtime-vc4mdr-R.mjs → client-bootstrap-Cr1JCaF5.mjs} +3670 -2277
  7. package/dist/disposal-BYBbEpVY.mjs +54 -0
  8. package/dist/dist-CIsR7cz4.mjs +15717 -0
  9. package/dist/{entry-control-DvSrndWd.mjs → entry-control-DnduyDiw.mjs} +12 -31
  10. package/dist/{extensions-CcuMY4n2.mjs → extensions-Bp0L37lP.mjs} +1239 -271
  11. package/dist/extensions.mjs +1 -1
  12. package/dist/host-bootstrap-DilsvA6f.mjs +281 -0
  13. package/dist/host-foundation-probe--5jtvHVe.mjs +413 -0
  14. package/dist/host-runtime.d.mts +30 -0
  15. package/dist/host-runtime.mjs +1317 -0
  16. package/dist/index.d.mts +19 -18
  17. package/dist/index.mjs +18410 -8836
  18. package/dist/local-client.mjs +2027 -187
  19. package/dist/local-discovery-C9VMjc0K.mjs +759 -0
  20. package/dist/local-discovery-CDaQHA_R.mjs +2 -0
  21. package/dist/local-host.mjs +1088 -87
  22. package/dist/local-transport-BVwFYq_Y.mjs +513 -0
  23. package/dist/{context-summary-DAisTA_7.mjs → pasted-path-range-CMnxuGPx.mjs} +7613 -216
  24. package/dist/pasted-path-range-r6qzV_tC.mjs +17510 -0
  25. package/dist/performance-host.d.mts +2 -2
  26. package/dist/performance-host.mjs +258 -1
  27. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +85 -0
  28. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  29. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +905 -0
  30. package/dist/pi-tui-web-access-contract-BN8Cc_Ho.mjs +118 -0
  31. package/dist/{runtime-status-0lp9CM0V.mjs → runtime-status-Cj1nFOdS.mjs} +72 -214
  32. package/dist/session-BKGXyh80.mjs +15794 -0
  33. package/dist/{session-tdJHLnJR.mjs → session-CPt_U8_f.mjs} +10707 -3657
  34. package/dist/{startup-JaVZoTIl.mjs → startup-7BYWuvBU.mjs} +124 -8
  35. package/dist/startup.d.mts +1 -1
  36. package/dist/startup.mjs +1 -1
  37. package/dist/{client-bootstrap-F5DHFI9t.mjs → terminal-progress-source-DrqQhtT8.mjs} +3653 -2969
  38. package/dist/visual-tools.d.mts +2 -2
  39. package/dist/visual-tools.mjs +26 -31
  40. package/dist/web-preferences.d.mts +29 -0
  41. package/dist/web-preferences.mjs +15 -0
  42. package/dist/web-roster-CjqnUXNk.mjs +285 -0
  43. package/generated/dsh-presets/cordis.patch.yml +5 -3
  44. package/generated/dsh-presets/ptc.patch.yml +7 -7
  45. package/generated/dsh-presets/standard.patch.yml +6 -4
  46. package/package.json +195 -172
  47. package/dist/host-bootstrap-DAgKknbY.mjs +0 -119
  48. package/dist/performance-host-CcDJjjVA.mjs +0 -266
  49. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  50. package/dist/terminal-progress-source-xor3vakJ.mjs +0 -2256
@@ -1,170 +1,400 @@
1
1
  #!/usr/bin/env node
2
- import { i as writeEntryRecord, n as createEntryDiag, r as readProcessStartIdentity, t as attachEntryControl } from "./entry-control-DvSrndWd.mjs";
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-C9VMjc0K.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";
3
5
  import { t as mergeCause } from "./dispose-cause-CNFuUnjR.mjs";
6
+ import { t as runSyncDisposalSteps } from "./disposal-BYBbEpVY.mjs";
4
7
  import { createRequire } from "node:module";
5
- import { realpathSync } from "node:fs";
8
+ import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, openSync, readFileSync, realpathSync, statSync, writeSync } from "node:fs";
9
+ import { dirname, isAbsolute, join } from "node:path";
6
10
  import { pathToFileURL } from "node:url";
7
- //#region src/runtime/process/errors.ts
8
- /**
9
- * Shared, TOTAL error-observation helpers for every async boundary in the
10
- * TUI: the owned/detached entries (`tasks.ts`), the lifecycle roots
11
- * (startup, exit, flush), the per-task callbacks and the diagnostics
12
- * formatter. One implementation, one behavior — no drift between modules.
13
- *
14
- * CONTRACT (deliberately scoped, honestly worded): the SYNC boundary is
15
- * total — observing any legal JavaScript value (a Proxy with a throwing
16
- * `getPrototypeOf` trap, a throwing `message` getter, a throwing
17
- * `toString`/`Symbol.toPrimitive`) can never make THIS code throw or
18
- * reject; every observation is protected and every fallback is a fixed
19
- * constant that never touches the value again. What is NOT guaranteed: an
20
- * observer (getter/trap/coercion) that, WHILE being observed, spawns its
21
- * OWN detached async work (e.g. `void Promise.reject(...)` inside
22
- * `toString`) — that rejection belongs to the observer, not to this
23
- * boundary, and no synchronous try/catch can intercept it. Callers must
24
- * not describe this module as a strict "any legal value, zero side
25
- * effects" guarantee.
26
- * @module @xmoon76/dsh-pi-tui/runtime/process/errors
27
- */
28
- /**
29
- * Describe an arbitrary thrown value as a string WITHOUT ever throwing:
30
- * `instanceof`, property reads and coercion are all inside the protection,
31
- * the fallbacks are FIXED constants that never touch the value again, and
32
- * a hostile Proxy/getter/`Symbol.toPrimitive` yields a stable placeholder
33
- * instead of escaping. (Best-effort beyond the sync boundary — see the
34
- * module contract.)
35
- */
36
- function safeErrorMessage(value) {
37
- try {
38
- if (value instanceof Error) try {
39
- const message = value.message;
40
- return typeof message === "string" ? message : "<error with non-string message>";
41
- } catch {
42
- return "<error with unreadable message>";
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();
43
22
  }
44
- return String(value);
45
- } catch {
46
- return "<unprintable error>";
47
- }
23
+ return result;
24
+ };
48
25
  }
49
- //#endregion
50
- //#region src/runtime/process/tasks.ts
51
26
  /**
52
- * Whether an error represents an abort/cancel rather than a real failure.
53
- * TOTAL over the whole `unknown` domain: every probe (prototype-chain
54
- * walk, `name`/`code` getters) is inside the protection, and a hostile
55
- * value that throws while being observed simply classifies as NOT a
56
- * cancellation — recognizing a cancellation must never mint a new primary
57
- * error.
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.
58
31
  */
59
- function isCancellation(error) {
60
- try {
61
- if (!(error instanceof Error)) return false;
62
- return error.name === "AbortError" || error.code === "ABORT_ERR";
63
- } catch {
64
- return false;
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));
65
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
+ });
66
56
  }
67
- /** Read the live session id for diagnostics WITHOUT ever throwing: a
68
- * throwing `sessionId()` callback degrades to `undefined` (diagnostics
69
- * must not crash classification or the final sink). */
70
- function safeSessionId(options) {
71
- try {
72
- return options.sessionId?.();
73
- } catch {
74
- return;
75
- }
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");
76
62
  }
77
- /**
78
- * Invoke the task factory SYNCHRONOUSLY (an ownership action inside the
79
- * factory — a stop, a latch, a spawn — must take effect before the helper
80
- * returns, so two calls in one input batch cannot both start), and convert
81
- * a synchronous throw into a rejected promise so it classifies exactly like
82
- * a rejection.
83
- */
84
- function invokeTask(task) {
85
- try {
86
- return Promise.resolve(task());
87
- } catch (error) {
88
- return Promise.reject(error);
89
- }
63
+ /** The root-disposal reason: no Host result is fabricated and no local cancel
64
+ * is forwarded after the owner is gone. */
65
+ function disposedReason() {
66
+ return /* @__PURE__ */ new Error("client interaction delivery: disposed before the official request settled");
90
67
  }
91
68
  /**
92
- * Attach rejection handling to a fire-and-forget task. The factory is
93
- * invoked synchronously (a synchronous throw is a rejection like any
94
- * other); every rejection is caught and classified:
95
- * - cancellation → debug diagnostics only (never a user error);
96
- * - recoverable (per the options hook) → notify + warn;
97
- * - anything else → warn.
98
- * The log line carries the task label and the live session id — never the
99
- * task payload (no API keys, prompt bodies, or shell output). A throwing
100
- * notify/diag/sessionId path cannot escape: it lands in the handler-failure
101
- * sink, which is itself total over the `unknown` domain.
69
+ * Create the ONE root interaction delivery owner over the official Client
70
+ * Remote event seat. The caller must have mounted the official Session client
71
+ * (the Agent scope resolver) before the official event pump can start.
102
72
  */
103
- function runDetached(label, task, options) {
104
- invokeTask(task).catch((error) => {
105
- if (isCancellation(error)) {
106
- options.diag.debug(label, {
107
- session: safeSessionId(options),
108
- cancelled: true
109
- });
73
+ function createSplitClientInteractionDelivery(options) {
74
+ let current;
75
+ let disposed = false;
76
+ /**
77
+ * Marks every PRESENTATION attempt made before a navigation hold / committed
78
+ * subject change as stale. This is a presentation fence only: it never
79
+ * settles or answers the official invocation, and it survives a hold release
80
+ * so a local cancellation produced by the withdrawal can never be mistaken
81
+ * for a late human answer.
82
+ */
83
+ let presentationEpoch = 0;
84
+ let navigationHold;
85
+ /** Wake-ups for a delivery wait (surface attach, subject change, hold, dispose). */
86
+ const waiters = /* @__PURE__ */ new Set();
87
+ /**
88
+ * The committed-Session authority of the CURRENT surface revision's
89
+ * application. `undefined` means "not bound yet": a forwarded request waits
90
+ * rather than presenting into a surface that has no committed subject.
91
+ */
92
+ let committedSessionId;
93
+ let bindingToken;
94
+ let bindingDisposal;
95
+ /**
96
+ * The official invocations this root currently holds. Each entry is created
97
+ * by its own callback stack and removed when that SAME invocation settles,
98
+ * aborts or the root disposes — never a Host pending copy.
99
+ */
100
+ const eligibleRequests = /* @__PURE__ */ new Set();
101
+ const eligibilityListeners = /* @__PURE__ */ new Set();
102
+ const rootLifetime = new AbortController();
103
+ const wakeWaiters = () => {
104
+ for (const waiter of [...waiters]) {
105
+ waiters.delete(waiter);
106
+ waiter();
107
+ }
108
+ };
109
+ const notifyEligibility = () => {
110
+ for (const listener of [...eligibilityListeners]) try {
111
+ listener();
112
+ } catch {}
113
+ };
114
+ const addEligible = (sessionId, kind) => {
115
+ const token = {
116
+ sessionId,
117
+ kind,
118
+ live: true
119
+ };
120
+ eligibleRequests.add(token);
121
+ notifyEligibility();
122
+ return token;
123
+ };
124
+ const removeEligible = (token) => {
125
+ if (eligibleRequests.delete(token)) notifyEligibility();
126
+ };
127
+ /** The combined official lifetime plus the root lifetime. */
128
+ const lifetimeOf = (signal) => signal === void 0 ? rootLifetime.signal : AbortSignal.any([signal, rootLifetime.signal]);
129
+ /**
130
+ * Whether the application has committed exactly the request's Session.
131
+ * An UNBOUND delivery is the legacy path (TSP split / a composition that
132
+ * never installs the PiTUI split authority): it keeps the pre-G567 forward
133
+ * behavior, and the surface's own admission still applies. The PiTUI split
134
+ * runner binds BEFORE the surface's interaction providers attach.
135
+ */
136
+ const isCommittedSubject = (sessionId) => committedSessionId === void 0 || committedSessionId() === sessionId;
137
+ /** Wake on any state change, then re-check admission. */
138
+ const waitForWake = (lifetime) => new Promise((resolve, reject) => {
139
+ if (lifetime.aborted) {
140
+ reject(abortReason(lifetime));
110
141
  return;
111
142
  }
112
- const message = safeErrorMessage(error);
113
- options.diag.warn(label, {
114
- session: safeSessionId(options),
115
- error: message
116
- });
117
- if (options.recoverable?.(error) === true) options.notify?.(`${label}: ${message}`);
118
- }).catch(handlerFailure(label, options));
119
- }
120
- /** Identity registry for the internal wrappers: `WeakSet.has` compares by
121
- * identity and never walks the argument's prototype chain, so a hostile
122
- * thrown value (a Proxy with a throwing `getPrototypeOf` trap) can be
123
- * tested safely — `instanceof HandlerFailure` on an untrusted value could
124
- * itself throw. */
125
- const handlerFailures = /* @__PURE__ */ new WeakSet();
126
- /** Whether a value is one of OUR wrapper instances (identity only; total
127
- * over the whole `unknown` domain). */
128
- function isHandlerFailure(value) {
129
- return typeof value === "object" && value !== null && handlerFailures.has(value);
143
+ const cleanup = () => {
144
+ waiters.delete(onWake);
145
+ lifetime.removeEventListener("abort", onAbort);
146
+ };
147
+ const onWake = () => {
148
+ cleanup();
149
+ resolve();
150
+ };
151
+ const onAbort = () => {
152
+ cleanup();
153
+ reject(abortReason(lifetime));
154
+ };
155
+ waiters.add(onWake);
156
+ lifetime.addEventListener("abort", onAbort, { once: true });
157
+ });
158
+ /**
159
+ * Wait until the ONE admissible presentation state holds: a surface is
160
+ * attached, no navigation hold is active, and the request's own Session is
161
+ * the committed subject. Aborts on the official request lifetime/root
162
+ * disposal; it never settles the invocation itself.
163
+ */
164
+ const waitForAdmission = async (sessionId, lifetime) => {
165
+ for (;;) {
166
+ if (disposed) throw disposedReason();
167
+ if (lifetime.aborted) throw abortReason(lifetime);
168
+ if (current !== void 0 && navigationHold === void 0 && isCommittedSubject(sessionId)) return;
169
+ await waitForWake(lifetime);
170
+ }
171
+ };
172
+ /**
173
+ * Run ONE presentation attempt of the SAME official invocation. A local
174
+ * result is accepted only while the attempt still belongs to the CURRENT
175
+ * attachment, the SAME presentation epoch, the SAME (absent) hold and the
176
+ * request's committed Session; otherwise it is dropped and the loop waits for
177
+ * the next admissible presentation. The official `next` is never called here.
178
+ */
179
+ const presentWhenAdmissible = async (sessionId, requestSignal, invoke) => {
180
+ const lifetime = lifetimeOf(requestSignal);
181
+ for (;;) {
182
+ await waitForAdmission(sessionId, lifetime);
183
+ const attachment = current;
184
+ if (attachment === void 0) continue;
185
+ const hold = navigationHold;
186
+ const epoch = presentationEpoch;
187
+ let presentation;
188
+ try {
189
+ presentation = Promise.resolve(invoke(attachment));
190
+ } catch (error) {
191
+ presentation = Promise.reject(error);
192
+ }
193
+ try {
194
+ const result = await raceWithAbort(presentation, lifetime);
195
+ if (lifetime.aborted) throw abortReason(lifetime);
196
+ if (current === attachment && navigationHold === hold && presentationEpoch === epoch && isCommittedSubject(sessionId)) return result;
197
+ } catch (error) {
198
+ if (lifetime.aborted) throw abortReason(lifetime);
199
+ if (current === attachment && navigationHold === hold && presentationEpoch === epoch && isCommittedSubject(sessionId)) throw error;
200
+ }
201
+ }
202
+ };
203
+ const deliverQuestion = async function(request, next) {
204
+ const sessionId = options.sessions.scopeOf(this);
205
+ if (sessionId === void 0) return next();
206
+ const callId = request.wait?.callId;
207
+ const view = {
208
+ sessionId,
209
+ callId: typeof callId === "string" ? callId : void 0,
210
+ timed: request.wait?.timed === true,
211
+ questions: request.questions,
212
+ ...request.signal === void 0 ? {} : { signal: request.signal }
213
+ };
214
+ const nextOnce = onceNext(next);
215
+ const eligible = addEligible(sessionId, "question");
216
+ try {
217
+ return await presentWhenAdmissible(sessionId, request.signal, (attachment) => attachment.onQuestion(view, nextOnce));
218
+ } finally {
219
+ removeEligible(eligible);
220
+ }
221
+ };
222
+ const deliverApproval = async function(request, next) {
223
+ const sessionId = options.sessions.scopeOf(this);
224
+ if (sessionId === void 0) return next();
225
+ const view = {
226
+ toolName: request.toolName,
227
+ ...request.reason === void 0 ? {} : { reason: request.reason },
228
+ ...request.callId === void 0 ? {} : { callId: request.callId },
229
+ ...request.signal === void 0 ? {} : { signal: request.signal },
230
+ sessionId
231
+ };
232
+ const nextOnce = onceNext(next);
233
+ const eligible = addEligible(sessionId, "approval");
234
+ try {
235
+ return await presentWhenAdmissible(sessionId, request.signal, (attachment) => attachment.onApproval(view, nextOnce));
236
+ } finally {
237
+ removeEligible(eligible);
238
+ }
239
+ };
240
+ const owned = [];
241
+ owned.push(options.remote.$on("user-questions/request", deliverQuestion));
242
+ owned.push(options.remote.$on("approval/request", deliverApproval));
243
+ return {
244
+ attachSurface(revision, input) {
245
+ if (disposed) throw new Error("client interaction delivery: disposed");
246
+ const attachment = {
247
+ revision,
248
+ ...input
249
+ };
250
+ current = attachment;
251
+ wakeWaiters();
252
+ return () => {
253
+ if (current !== attachment) return;
254
+ current = void 0;
255
+ wakeWaiters();
256
+ };
257
+ },
258
+ currentEligibleRequests() {
259
+ return [...eligibleRequests];
260
+ },
261
+ subscribeEligibility(listener) {
262
+ eligibilityListeners.add(listener);
263
+ return () => {
264
+ eligibilityListeners.delete(listener);
265
+ };
266
+ },
267
+ bindCommittedSession(currentSessionId, subscribeCommittedSession) {
268
+ if (disposed) throw new Error("client interaction delivery: disposed");
269
+ bindingDisposal?.();
270
+ bindingDisposal = void 0;
271
+ bindingToken = void 0;
272
+ committedSessionId = void 0;
273
+ const token = {};
274
+ const off = subscribeCommittedSession(() => {
275
+ if (bindingToken !== token) return;
276
+ presentationEpoch += 1;
277
+ wakeWaiters();
278
+ });
279
+ bindingToken = token;
280
+ committedSessionId = currentSessionId;
281
+ bindingDisposal = off;
282
+ presentationEpoch += 1;
283
+ wakeWaiters();
284
+ return () => {
285
+ if (bindingToken !== token) return;
286
+ bindingToken = void 0;
287
+ bindingDisposal = void 0;
288
+ committedSessionId = void 0;
289
+ presentationEpoch += 1;
290
+ off();
291
+ wakeWaiters();
292
+ };
293
+ },
294
+ beginNavigationHold() {
295
+ if (disposed) throw new Error("client interaction delivery: disposed");
296
+ if (navigationHold !== void 0) throw new Error("client interaction delivery: a navigation hold is already active");
297
+ presentationEpoch += 1;
298
+ let released = false;
299
+ const handle = { release: () => {
300
+ if (released) return;
301
+ released = true;
302
+ if (navigationHold !== handle) return;
303
+ navigationHold = void 0;
304
+ wakeWaiters();
305
+ } };
306
+ navigationHold = handle;
307
+ wakeWaiters();
308
+ return handle;
309
+ },
310
+ dispose() {
311
+ if (disposed) return;
312
+ disposed = true;
313
+ current = void 0;
314
+ navigationHold = void 0;
315
+ committedSessionId = void 0;
316
+ bindingToken = void 0;
317
+ const binding = bindingDisposal;
318
+ bindingDisposal = void 0;
319
+ eligibleRequests.clear();
320
+ notifyEligibility();
321
+ rootLifetime.abort(disposedReason());
322
+ wakeWaiters();
323
+ runSyncDisposalSteps("client interaction delivery disposal", [() => binding?.(), ...owned.splice(0).map((off) => () => {
324
+ off();
325
+ })]);
326
+ }
327
+ };
130
328
  }
329
+ //#endregion
330
+ //#region src/app/remote-process/local-client-surface.ts
131
331
  /**
132
- * The final sink of both helpers: a terminal side-effect handler
133
- * (onResult's own invocation aside — see {@link runOwned}), a task-local
134
- * classifier, or the diagnostics channel itself threw. The ENTIRE body is
135
- * protected — wrapper unwrapping, error description, the session read and
136
- * the diag call all live inside the try, and the fallback is a fixed
137
- * constant that never touches the hostile value again — so the sink is a
138
- * total function over the `unknown` domain: it can NEVER reject, and there
139
- * is no lower sink to leak into.
332
+ * Create the bridge around the supplied process-stop owner. `stop` is invoked
333
+ * at most once, and only by the first `requestStop` caller; the promise and
334
+ * the failure latch are likewise one-shot (a late `markMounted` after a
335
+ * failure never resurrects a mounted surface).
140
336
  */
141
- function handlerFailure(label, options) {
142
- return (error) => {
143
- try {
144
- const cause = isHandlerFailure(error) ? error.cause : error;
145
- options.diag.error(`${label} handler failed`, {
146
- session: safeSessionId(options),
147
- error: safeErrorMessage(cause)
148
- });
149
- } catch {}
337
+ function createLocalClientSurfaceBridge(stop) {
338
+ let resolveReady;
339
+ let rejectReady;
340
+ let settled = false;
341
+ const ready = new Promise((resolve, reject) => {
342
+ resolveReady = resolve;
343
+ rejectReady = reject;
344
+ });
345
+ let resolveStopped;
346
+ const stopped = new Promise((resolve) => {
347
+ resolveStopped = resolve;
348
+ });
349
+ ready.catch(() => {});
350
+ let stopRequested = false;
351
+ return {
352
+ ready,
353
+ markMounted() {
354
+ if (settled) return;
355
+ settled = true;
356
+ resolveReady?.();
357
+ },
358
+ fail(error) {
359
+ if (settled) return;
360
+ settled = true;
361
+ rejectReady?.(error);
362
+ },
363
+ requestStop(code) {
364
+ if (stopRequested) return;
365
+ stopRequested = true;
366
+ resolveStopped?.(code);
367
+ stop(code);
368
+ },
369
+ stopped
150
370
  };
151
371
  }
152
372
  //#endregion
153
373
  //#region src/app/remote-process/local-client-entry.ts
154
374
  /**
155
- * M4-A0 Client-only process entry.
375
+ * Client-only split-process entry.
156
376
  *
157
377
  * The Client PID owns a real Cordis root and mounts only the Client-local
158
- * subtree (TUI startup facts, extension host, first-party builtins). It never
159
- * imports the Host runtime, the in-process carrier, or the application
160
- * aggregate, and it reports `transport: not-connected` until M4-B1 supplies
161
- * the official authenticated Connection.
378
+ * subtree plus the official Node Client transport. Its one scope is the
379
+ * canonical DSH profile: the frozen `qualification` mode first claims the
380
+ * qualification-only kernel Client seat (the real `surface` and `peer` modes
381
+ * do not), then discovers (or safely ensures) the Host, authenticates it
382
+ * through the official `/connect` cookie, verifies the authenticated
383
+ * identity, and only then installs the official three-layer transport on the
384
+ * same A0 Client Context. The Host Singleton keeps its own separate kernel
385
+ * seat in every mode.
386
+ *
387
+ * Client admission compares the required local wire protocol and the exact
388
+ * DSH runtime version, not the package bundle/build fingerprint. A different
389
+ * installed build of the same protocol may attach; a protocol or DSH mismatch
390
+ * is refused before any Host work is touched and never stops or replaces the
391
+ * live Host.
162
392
  *
163
393
  * The launcher supplies the DSH installation anchor and profile name through
164
- * `SPLIT_PROCESS_DSH_ANCHOR` / `SPLIT_PROCESS_PROFILE` so this process can install the same official
165
- * package-resolution interception the dsh launcher uses. The package's own
166
- * `dist/` location stays the installation point — no repository source path or
167
- * tsx loader is involved.
394
+ * `SPLIT_PROCESS_DSH_ANCHOR` / `SPLIT_PROCESS_PROFILE` so this process can
395
+ * install the same official package-resolution interception the dsh launcher
396
+ * uses. The package's own `dist/` location stays the installation point — no
397
+ * repository source path or tsx loader is involved.
168
398
  *
169
399
  * @module app/remote-process/local-client-entry
170
400
  */
@@ -173,61 +403,1474 @@ async function loadOfficialClientHost(anchor) {
173
403
  const requireFromDsh = createRequire(realpathSync(anchor));
174
404
  const importResolved = async (specifier) => import(pathToFileURL(requireFromDsh.resolve(specifier)).href);
175
405
  const appBoot = await importResolved("@deepseek-ai/dsh-app-boot");
406
+ const cordis = await importResolved("@deepseek-ai/cordis");
407
+ const loaderModule = await importResolved("@deepseek-ai/cordis-plugin-loader");
408
+ const homePaths = await importResolved("@deepseek-ai/dsh-home-paths");
176
409
  return {
177
- Context: (await importResolved("@deepseek-ai/cordis")).Context,
410
+ Context: cordis.Context,
178
411
  PluginPackages: appBoot.PluginPackages,
412
+ Loader: loaderModule.default,
179
413
  loadProfile: appBoot.loadProfile,
180
- createRuntimeResolution: appBoot.createRuntimeResolution
414
+ createRuntimeResolution: appBoot.createRuntimeResolution,
415
+ resolveDshHome: homePaths.resolveDshHome,
416
+ resolveProfileDir: appBoot.resolveProfileDir
417
+ };
418
+ }
419
+ /** Project the authenticated record without the profile path or cookie. */
420
+ function hostRecordForTrace(host) {
421
+ const record = host.identity;
422
+ return {
423
+ scopeId: record.scopeId,
424
+ instanceId: record.instanceId,
425
+ hostPid: record.hostPid,
426
+ hostStarttime: record.hostStarttime,
427
+ origin: record.origin,
428
+ protocol: record.protocol,
429
+ bundleVersion: record.bundleVersion,
430
+ dshVersion: record.dshVersion,
431
+ buildId: record.buildId
432
+ };
433
+ }
434
+ /**
435
+ * The surface-mode telemetry sink: an owner-managed `0600` absolute JSONL file
436
+ * under the isolated qualification work root. Terminal bytes never carry JSON
437
+ * in surface mode, and the file never records a Cookie, token or private Host
438
+ * profile path. The parent directory's REAL path and ownership are validated
439
+ * before the file is opened; a symlinked target is refused.
440
+ */
441
+ function createSurfaceRecordSink() {
442
+ const target = process.env.SPLIT_PROCESS_CLIENT_RECORD_FILE;
443
+ if (target === void 0 || target === "") throw new Error("local client entry: surface mode requires SPLIT_PROCESS_CLIENT_RECORD_FILE");
444
+ if (!isAbsolute(target)) throw new Error("local client entry: the surface record file path must be absolute");
445
+ const directory = realpathSync(dirname(target));
446
+ const directoryStats = statSync(directory);
447
+ if (!directoryStats.isDirectory()) throw new Error("local client entry: the surface record directory is not a directory");
448
+ const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
449
+ if (uid !== void 0 && directoryStats.uid !== uid) throw new Error("local client entry: the surface record directory is not owned by this process user");
450
+ if (existsSync(target) && lstatSync(target).isSymbolicLink()) throw new Error("local client entry: the surface record file must not be a symlink");
451
+ const fd = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
452
+ if ((fstatSync(fd).mode & 511) !== 384) fchmodSync(fd, 384);
453
+ if ((fstatSync(fd).mode & 511) !== 384) {
454
+ closeSync(fd);
455
+ throw new Error("local client entry: the surface record file must have mode 0600");
456
+ }
457
+ return {
458
+ emit: (record) => {
459
+ writeSync(fd, `${JSON.stringify(record)}\n`);
460
+ },
461
+ close: () => {
462
+ closeSync(fd);
463
+ }
464
+ };
465
+ }
466
+ /** The surface-mode startup intent: an explicit internal input, never a
467
+ * control-channel override of published behavior. */
468
+ function surfaceStartupFacts(options) {
469
+ const sessionId = process.env.SPLIT_PROCESS_CLIENT_SESSION;
470
+ const presetId = process.env.SPLIT_PROCESS_CLIENT_PRESET;
471
+ if (options.mode !== "surface") return {};
472
+ if (sessionId !== void 0 && sessionId.trim() === "") throw new Error("local client entry: SPLIT_PROCESS_CLIENT_SESSION must be non-empty when set");
473
+ if (presetId !== void 0 && presetId.trim() === "") throw new Error("local client entry: SPLIT_PROCESS_CLIENT_PRESET must be non-empty when set");
474
+ return {
475
+ ...sessionId === void 0 || sessionId === "" ? {} : { sessionId },
476
+ ...presetId === void 0 || presetId === "" ? {} : { presetId }
477
+ };
478
+ }
479
+ /** The single internal Loader builtin name of the interaction startup gate. */
480
+ const INTERACTION_STARTUP_GATE = "pi-tui-interaction-startup-gate";
481
+ const CLIENT_PACKAGE_NAME = "@xmoon76/dsh-pi-tui";
482
+ /** The exact DSH runtime pin a candidate manifest declares (npm `devDependencies`). */
483
+ const DSH_PIN_PACKAGE = "@deepseek-ai/dsh-agent";
484
+ 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;
485
+ /**
486
+ * Environment that belongs to the OLD Client's qualification/fault-injection
487
+ * surface only. A replacement Client must not inherit a second SIGUSR2 probe,
488
+ * a stale hold barrier or a one-shot fault injection: those are not handoff
489
+ * state and would corrupt the new process.
490
+ */
491
+ const OLD_CLIENT_ENVIRONMENT = [
492
+ "SPLIT_PROCESS_CLIENT_REEXEC_PROBE",
493
+ "SPLIT_PROCESS_CLIENT_REEXEC_TARGET_PACKAGE_ROOT",
494
+ "SPLIT_PROCESS_CLIENT_REEXEC_CHILD_FAILURE",
495
+ "SPLIT_PROCESS_CLIENT_HMR_PROBE",
496
+ "SPLIT_PROCESS_CLIENT_HMR_FAIL",
497
+ "SPLIT_PROCESS_CLIENT_HMR_HOLD",
498
+ "SPLIT_PROCESS_CLIENT_PRIVATE_RPC_PROOF",
499
+ "SPLIT_PROCESS_CLIENT_HOLD_SERIALIZE",
500
+ "SPLIT_PROCESS_CLIENT_HOLD_ASSEMBLY",
501
+ "SPLIT_PROCESS_CLIENT_HOLD_BEFORE_START",
502
+ "SPLIT_PROCESS_CLIENT_HOLD_STARTUP_GATE",
503
+ "SPLIT_PROCESS_CLIENT_FORCE_FAILURE",
504
+ "SPLIT_PROCESS_CLIENT_FORCE_STARTUP_FATAL",
505
+ "SPLIT_PROCESS_CLIENT_FORCE_REFRESH_UNRESPONSIVE_ONCE",
506
+ "SPLIT_PROCESS_CLIENT_DROP_PROMPT_ACK",
507
+ "SPLIT_PROCESS_CLIENT_OMIT_COOKIE",
508
+ "SPLIT_PROCESS_CLIENT_WORKSPACE_INTENT_PATH"
509
+ ];
510
+ function failureMessage(error) {
511
+ return error instanceof Error ? error.message : String(error);
512
+ }
513
+ function isRecord(value) {
514
+ return value !== null && typeof value === "object" && !Array.isArray(value);
515
+ }
516
+ /**
517
+ * Validate one replacement Client package root and derive its production build
518
+ * fingerprint. The same checks apply to the package currently installed in the
519
+ * official profile and to the qualification-only side-by-side root override.
520
+ */
521
+ function inspectClientReexecTarget(packageRoot, dshVersion) {
522
+ if (!isAbsolute(packageRoot)) throw new Error("local client reexec: the target package root must be absolute");
523
+ let root;
524
+ try {
525
+ root = realpathSync(packageRoot);
526
+ } catch (error) {
527
+ throw new Error("local client reexec: the target package root is not readable", { cause: error });
528
+ }
529
+ const rootInfo = lstatSync(root);
530
+ const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
531
+ if (!rootInfo.isDirectory()) throw new Error("local client reexec: the target package root is not a directory");
532
+ if (uid !== void 0 && rootInfo.uid !== uid) throw new Error("local client reexec: the target package root is not owned by this process user");
533
+ let manifest;
534
+ try {
535
+ manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
536
+ } catch (error) {
537
+ throw new Error("local client reexec: the target package manifest is not readable JSON", { cause: error });
538
+ }
539
+ if (!isRecord(manifest) || manifest.name !== CLIENT_PACKAGE_NAME) throw new Error(`local client reexec: the target package is not ${CLIENT_PACKAGE_NAME}`);
540
+ if (typeof manifest.version !== "string" || manifest.version === "") throw new Error("local client reexec: the target package manifest has no version");
541
+ const devDependencies = manifest.devDependencies;
542
+ if (!isRecord(devDependencies) || devDependencies[DSH_PIN_PACKAGE] !== dshVersion) throw new Error("local client reexec: the target package is pinned to a different DSH runtime");
543
+ const entry = join(root, "dist", "local-client.mjs");
544
+ let entryInfo;
545
+ try {
546
+ entryInfo = lstatSync(entry);
547
+ } catch (error) {
548
+ throw new Error("local client reexec: the target package has no Client entry", { cause: error });
549
+ }
550
+ 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");
551
+ return {
552
+ packageRoot: root,
553
+ entry,
554
+ buildId: computeBuildId(root, dshVersion),
555
+ bundleVersion: manifest.version
556
+ };
557
+ }
558
+ /** Resolve the replacement package through the ACTIVE official profile. */
559
+ function resolveProfileInstalledClientTarget(profileDir, dshVersion) {
560
+ let manifestPath;
561
+ try {
562
+ manifestPath = createRequire(join(profileDir, "package.json")).resolve(`${CLIENT_PACKAGE_NAME}/package.json`);
563
+ } catch (error) {
564
+ throw new Error(`local client reexec: the active profile does not resolve the installed ${CLIENT_PACKAGE_NAME}`, { cause: error });
565
+ }
566
+ return inspectClientReexecTarget(dirname(manifestPath), dshVersion);
567
+ }
568
+ /**
569
+ * One typed preflight refusal. The reason is the process-owned vocabulary the
570
+ * command layer maps onto a fixed user notice; the message is the diagnostic
571
+ * detail (never surfaced verbatim by the command).
572
+ */
573
+ var ClientReexecRefusal = class extends Error {
574
+ reason;
575
+ constructor(reason, message) {
576
+ super(message);
577
+ this.name = "ClientReexecRefusal";
578
+ this.reason = reason;
579
+ }
580
+ };
581
+ function prepareClientReexec(options) {
582
+ const { status } = options;
583
+ if (status.transport !== "connected") throw new ClientReexecRefusal("not-ready", "local client reexec: the Client transport is not connected");
584
+ if (status.surfaceMounted !== true) throw new ClientReexecRefusal("not-ready", "local client reexec: the Client surface is not mounted");
585
+ const host = status.host;
586
+ if (host === void 0) throw new ClientReexecRefusal("not-ready", "local client reexec: the Client has no authenticated Host identity");
587
+ if (host.instanceId !== options.verifiedHostInstanceId) throw new ClientReexecRefusal("not-ready", "local client reexec: the live Host is not the authenticated Host instance");
588
+ let sessionId;
589
+ if (status.sessionOpen) {
590
+ const open = status.openSessionId;
591
+ if (open === void 0 || open === "") throw new ClientReexecRefusal("not-ready", "local client reexec: the open Session has no authoritative id");
592
+ sessionId = open;
593
+ }
594
+ const target = options.targetPackageRootOverride === void 0 ? resolveProfileInstalledClientTarget(options.profileDir, options.dshVersion) : inspectClientReexecTarget(options.targetPackageRootOverride, options.dshVersion);
595
+ if (target.buildId === options.currentBuildId) throw new ClientReexecRefusal("already-current", "local client reexec: the installed Client already runs this build");
596
+ return {
597
+ expectedInstanceId: host.instanceId,
598
+ ...sessionId === void 0 ? {} : { sessionId },
599
+ dshAnchor: options.dshAnchor,
600
+ profile: options.profile,
601
+ dshVersion: options.dshVersion,
602
+ targetPackageRoot: target.packageRoot,
603
+ targetEntry: target.entry,
604
+ targetBuildId: target.buildId,
605
+ targetBundleVersion: target.bundleVersion
606
+ };
607
+ }
608
+ /**
609
+ * The ONLY reexec request path. The first accepted request latches one intent
610
+ * and asks the existing stop coordinator for a normal exit; later requests are
611
+ * observable no-ops. A rejected preflight leaves the Client running and
612
+ * unlatched, so a later explicit request may retry a different target. The ONE
613
+ * latch is shared by both sources; only the target resolution differs.
614
+ */
615
+ function createClientReexecRequestHandler(options) {
616
+ let intent;
617
+ return {
618
+ request(source) {
619
+ if (intent !== void 0) {
620
+ options.emit({
621
+ m4r: "handoff-request-ignored",
622
+ processRole: "client",
623
+ pid: process.pid,
624
+ reason: "already-requested"
625
+ });
626
+ return {
627
+ kind: "refused",
628
+ reason: "stopping"
629
+ };
630
+ }
631
+ if (options.canRequest?.() === false) {
632
+ options.emit({
633
+ m4r: "handoff-request-ignored",
634
+ processRole: "client",
635
+ pid: process.pid,
636
+ reason: "stopping"
637
+ });
638
+ return {
639
+ kind: "refused",
640
+ reason: "stopping"
641
+ };
642
+ }
643
+ const status = options.status();
644
+ if (status === void 0) {
645
+ options.emit({
646
+ m4r: "handoff-request-ignored",
647
+ processRole: "client",
648
+ pid: process.pid,
649
+ reason: "not-ready"
650
+ });
651
+ return {
652
+ kind: "refused",
653
+ reason: "not-ready"
654
+ };
655
+ }
656
+ let prepared;
657
+ try {
658
+ prepared = options.prepare(status, source);
659
+ } catch (error) {
660
+ options.emit({
661
+ m4r: "handoff-request-rejected",
662
+ processRole: "client",
663
+ pid: process.pid,
664
+ error: failureMessage(error)
665
+ });
666
+ return {
667
+ kind: "refused",
668
+ reason: error instanceof ClientReexecRefusal ? error.reason : "target-invalid"
669
+ };
670
+ }
671
+ intent = prepared;
672
+ options.onAccepted?.(prepared);
673
+ options.emit({
674
+ m4r: "handoff-requested",
675
+ processRole: "client",
676
+ pid: process.pid,
677
+ source,
678
+ expectedHostInstanceId: prepared.expectedInstanceId,
679
+ ...prepared.sessionId === void 0 ? {} : { sessionId: prepared.sessionId },
680
+ targetBuildId: prepared.targetBuildId,
681
+ targetBundleVersion: prepared.targetBundleVersion
682
+ });
683
+ options.requestStop(0);
684
+ return { kind: "accepted" };
685
+ },
686
+ get intent() {
687
+ return intent;
688
+ }
689
+ };
690
+ }
691
+ /** Build the environment of the ONE replacement Client child. */
692
+ function createClientReexecChildEnvironment(intent, source = process.env) {
693
+ const env = { ...source };
694
+ const injectedFailure = source.SPLIT_PROCESS_CLIENT_REEXEC_CHILD_FAILURE;
695
+ for (const name of OLD_CLIENT_ENVIRONMENT) delete env[name];
696
+ delete env.SPLIT_PROCESS_CLIENT_PRESET;
697
+ env.SPLIT_PROCESS_CLIENT_MODE = "surface";
698
+ env.SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID = intent.expectedInstanceId;
699
+ env.SPLIT_PROCESS_DSH_ANCHOR = intent.dshAnchor;
700
+ env.SPLIT_PROCESS_PROFILE = intent.profile;
701
+ if (intent.sessionId === void 0) delete env.SPLIT_PROCESS_CLIENT_SESSION;
702
+ else env.SPLIT_PROCESS_CLIENT_SESSION = intent.sessionId;
703
+ if (injectedFailure !== void 0 && injectedFailure !== "") env.SPLIT_PROCESS_CLIENT_FORCE_FAILURE = injectedFailure;
704
+ return env;
705
+ }
706
+ /** Spawn the replacement Client on the SAME inherited terminal and await its exit. */
707
+ async function spawnClientReexecChild(entry, env, onSpawned) {
708
+ const child = spawn(process.execPath, [entry], {
709
+ cwd: process.cwd(),
710
+ env,
711
+ stdio: "inherit",
712
+ detached: false
713
+ });
714
+ onSpawned({ kill: (signal) => child.kill(signal) });
715
+ return await new Promise((resolve, reject) => {
716
+ let settled = false;
717
+ child.once("error", (error) => {
718
+ if (settled) return;
719
+ settled = true;
720
+ reject(error);
721
+ });
722
+ child.once("exit", (code, signal) => {
723
+ if (settled) return;
724
+ settled = true;
725
+ resolve({
726
+ code,
727
+ signal
728
+ });
729
+ });
730
+ });
731
+ }
732
+ function clientReexecExitCode(exit) {
733
+ if (exit.code !== null) return exit.code;
734
+ if (exit.signal === null) return 1;
735
+ const number = constants$1.signals[exit.signal];
736
+ return number === void 0 ? 1 : 128 + number;
737
+ }
738
+ /**
739
+ * Route one termination signal while a handoff is pending or already waiting.
740
+ * With no handoff, return false so the existing stop coordinator keeps owning
741
+ * the normal exit. A running replacement child receives the SAME signal; a
742
+ * handoff accepted but not yet spawned is cancelled instead of silently
743
+ * ignoring the signal. The old Client never starts a second stop.
744
+ */
745
+ function routeReexecTermination(handoffAccepted, child, signal, cancelPending) {
746
+ if (!handoffAccepted) return false;
747
+ if (child !== void 0) {
748
+ child.kill(signal);
749
+ return true;
750
+ }
751
+ cancelPending();
752
+ return true;
753
+ }
754
+ /**
755
+ * Finish the ONE Client process: release the process seat this mode actually
756
+ * holds (qualification) or close the no-op seat, and only after a fully
757
+ * successful teardown re-validate the replacement package and run the child.
758
+ * A failed teardown, seat close, target re-check or spawn never starts C1 and
759
+ * never touches the Host. Returns the replacement exit code when a handoff was
760
+ * requested, otherwise `undefined`.
761
+ */
762
+ async function finishClientEntryShutdown(options) {
763
+ let seatClosed = false;
764
+ try {
765
+ await options.seat.close();
766
+ seatClosed = true;
767
+ } catch (error) {
768
+ options.emit({
769
+ m4a0: "cleanup-failure",
770
+ processRole: "client",
771
+ phase: "shutdown",
772
+ pid: process.pid,
773
+ step: "client-seat",
774
+ error: failureMessage(error)
775
+ });
776
+ }
777
+ const reexec = options.reexec;
778
+ if (reexec === void 0) return seatClosed ? void 0 : 1;
779
+ if (reexec.cancelled?.() === true) {
780
+ const reason = /* @__PURE__ */ new Error("local client entry: the Client handoff was cancelled by a termination signal");
781
+ options.emit({
782
+ m4r: "handoff-failed",
783
+ processRole: "client",
784
+ pid: process.pid,
785
+ phase: "cancelled",
786
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
787
+ error: reason.message
788
+ });
789
+ options.stderr(handoffStartupFailureLine(reason));
790
+ return 1;
791
+ }
792
+ if (!seatClosed || !reexec.teardownSucceeded) {
793
+ 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");
794
+ options.emit({
795
+ m4r: "handoff-failed",
796
+ processRole: "client",
797
+ pid: process.pid,
798
+ phase: "teardown",
799
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
800
+ error: reason.message
801
+ });
802
+ options.stderr(handoffStartupFailureLine(reason));
803
+ return 1;
804
+ }
805
+ let target;
806
+ try {
807
+ target = inspectClientReexecTarget(reexec.intent.targetPackageRoot, reexec.intent.dshVersion);
808
+ } catch (error) {
809
+ options.emit({
810
+ m4r: "handoff-failed",
811
+ processRole: "client",
812
+ pid: process.pid,
813
+ phase: "target",
814
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
815
+ error: failureMessage(error)
816
+ });
817
+ options.stderr(handoffStartupFailureLine(error));
818
+ return 1;
819
+ }
820
+ if (target.buildId !== reexec.intent.targetBuildId || target.entry !== reexec.intent.targetEntry) {
821
+ const changed = /* @__PURE__ */ new Error("local client reexec: the replacement Client package changed between the preflight and the spawn");
822
+ options.emit({
823
+ m4r: "handoff-failed",
824
+ processRole: "client",
825
+ pid: process.pid,
826
+ phase: "target",
827
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
828
+ error: changed.message
829
+ });
830
+ options.stderr(handoffStartupFailureLine(changed));
831
+ return 1;
832
+ }
833
+ const spawnChild = options.spawnChild ?? spawnClientReexecChild;
834
+ let exit;
835
+ try {
836
+ exit = await spawnChild(target.entry, createClientReexecChildEnvironment(reexec.intent), (child) => options.onChildSpawned?.(child));
837
+ } catch (error) {
838
+ options.emit({
839
+ m4r: "handoff-failed",
840
+ processRole: "client",
841
+ pid: process.pid,
842
+ phase: "spawn",
843
+ expectedHostInstanceId: reexec.intent.expectedInstanceId,
844
+ error: failureMessage(error)
845
+ });
846
+ options.stderr(handoffStartupFailureLine(error));
847
+ return 1;
848
+ }
849
+ options.emit({
850
+ m4r: "handoff-parent-exit",
851
+ processRole: "client",
852
+ pid: process.pid,
853
+ code: exit.code,
854
+ signal: exit.signal
855
+ });
856
+ return clientReexecExitCode(exit);
857
+ }
858
+ /**
859
+ * The FINAL gate before a replacement Client publishes `handoff-restored`.
860
+ * It reads the LIVE status after the Session-open proof and refuses a Client
861
+ * whose official transport fatal, expected Host instance, connection or
862
+ * physical surface is no longer current. `status.host` is the composition's
863
+ * authenticated record (a static fact), so the meaningful currentness checks
864
+ * are the transport state/generation (the proof rejects a generation rollover)
865
+ * and this terminal-fatal gate.
866
+ */
867
+ function assertHandoffRestored(status, expectedInstanceId, terminalError) {
868
+ if (terminalError !== void 0) throw terminalError instanceof Error ? terminalError : new Error(String(terminalError));
869
+ const hostInstanceId = status.host?.instanceId;
870
+ if (hostInstanceId !== expectedInstanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local client entry: the handoff Client is no longer authenticated to the expected Host instance");
871
+ if (status.transport !== "connected") throw new Error("local client entry: the handoff Client has no connected official transport");
872
+ if (status.surfaceMounted !== true) throw new Error("local client entry: the handoff Client surface is not mounted");
873
+ return { hostInstanceId };
874
+ }
875
+ /** Read the one-shot handoff expectation; absent outside a replacement Client. */
876
+ function expectedHostInstanceFromEnvironment(mode) {
877
+ const raw = process.env.SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID;
878
+ if (raw === void 0 || raw === "") return void 0;
879
+ if (mode !== "surface") throw new Error("local client entry: SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID requires surface mode");
880
+ if (!INSTANCE_ID_PATTERN.test(raw)) throw new Error("local client entry: SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID must be a Host instance UUID");
881
+ return raw;
882
+ }
883
+ /**
884
+ * The internal reexec probe is one SIGUSR2 consumer; it may never share the
885
+ * process with the HMR, private-RPC or T34 qualification SIGUSR2 handlers, and
886
+ * a replacement Client may not also be a probe Client.
887
+ */
888
+ function assertHandoffSignalExclusivity(mode, expectedInstanceId) {
889
+ const reexecProbe = process.env.SPLIT_PROCESS_CLIENT_REEXEC_PROBE === "1";
890
+ 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 ?? "") !== "";
891
+ if (!reexecProbe) {
892
+ if (expectedInstanceId !== void 0 && otherSignalMode) throw new Error("local client entry: a handoff Client may not inherit another SIGUSR2 qualification mode");
893
+ return;
894
+ }
895
+ if (mode !== "surface") throw new Error("local client entry: the reexec probe requires surface mode");
896
+ if (otherSignalMode) throw new Error("local client entry: the reexec qualification signal is mutually exclusive with the HMR/private-RPC/T34 SIGUSR2 modes");
897
+ if (expectedInstanceId !== void 0) throw new Error("local client entry: the reexec probe and the handoff expectation are mutually exclusive");
898
+ }
899
+ function createInteractionStartupGate() {
900
+ let resolveBarrier;
901
+ let rejectBarrier;
902
+ let state = "pending";
903
+ const barrier = new Promise((resolve, reject) => {
904
+ resolveBarrier = resolve;
905
+ rejectBarrier = reject;
906
+ });
907
+ return {
908
+ plugin: async () => {
909
+ await barrier;
910
+ },
911
+ get pending() {
912
+ return state === "pending";
913
+ },
914
+ release() {
915
+ if (state !== "pending") return;
916
+ state = "released";
917
+ resolveBarrier?.();
918
+ },
919
+ cancel(reason) {
920
+ if (state !== "pending") return;
921
+ state = "cancelled";
922
+ rejectBarrier?.(reason);
923
+ }
924
+ };
925
+ }
926
+ /** Production fail-closed preflight for the interaction startup gate.
927
+ *
928
+ * The Gateway's event pump must not start merely because the Session plugin
929
+ * mounted: the official `typert.contexts` Agent resolver is the exact target
930
+ * every forwarded request needs. A missing resolver is a startup failure, not
931
+ * a later `next()` fallback that would irreversibly settle a Host request.
932
+ */
933
+ function assertInteractionStartupReady(gate, agentResolver) {
934
+ if (!gate.pending) throw new Error("local client entry: the interaction startup gate failed before the transport install");
935
+ if (agentResolver === void 0) throw new Error("local client entry: the official Session Agent resolver did not install");
936
+ }
937
+ const PEER_ABORTED = Symbol("peer-request-aborted");
938
+ /**
939
+ * The qualification-only non-TUI answering Peer: it registers the two official
940
+ * `$on` listeners and holds each forwarded request until the smoke sends the
941
+ * exact `peer-answer` control record. It never renders, never takes the TUI
942
+ * seat and never invents a Host decision.
943
+ */
944
+ function createPeerInteractionSeat(remote, sessions, emit) {
945
+ const pending = /* @__PURE__ */ new Map();
946
+ const owned = [];
947
+ let sequence = 0;
948
+ const KEY = (kind, key) => `${kind}:${key}`;
949
+ const waitForAnswer = async (kind, callId, signal) => {
950
+ return await new Promise((resolve) => {
951
+ let settled = false;
952
+ const settle = (value) => {
953
+ if (settled) return;
954
+ settled = true;
955
+ signal?.removeEventListener("abort", onAbort);
956
+ pending.delete(KEY(kind, callId));
957
+ resolve(value);
958
+ };
959
+ const onAbort = () => {
960
+ settle(PEER_ABORTED);
961
+ };
962
+ pending.set(KEY(kind, callId), settle);
963
+ if (signal?.aborted === true) onAbort();
964
+ else signal?.addEventListener("abort", onAbort, { once: true });
965
+ });
966
+ };
967
+ owned.push(remote.$on("user-questions/request", async function(request, next) {
968
+ const sessionId = sessions.scopeOf(this);
969
+ if (sessionId === void 0) return next();
970
+ const callId = request.wait?.callId;
971
+ const peerKey = typeof callId === "string" ? callId : `question-${++sequence}`;
972
+ emit({
973
+ m4a0: "peer-interaction",
974
+ kind: "question",
975
+ peerKey,
976
+ callId: typeof callId === "string" ? callId : void 0,
977
+ sessionId
978
+ });
979
+ const value = await waitForAnswer("question", peerKey, request.signal);
980
+ if (value === PEER_ABORTED) throw new Error("local client entry: peer question request aborted");
981
+ return value;
982
+ }));
983
+ owned.push(remote.$on("approval/request", async function(request, next) {
984
+ const sessionId = sessions.scopeOf(this);
985
+ if (sessionId === void 0) return next();
986
+ const callId = request.callId;
987
+ const peerKey = typeof callId === "string" ? callId : `approval-${++sequence}`;
988
+ emit({
989
+ m4a0: "peer-interaction",
990
+ kind: "approval",
991
+ peerKey,
992
+ callId: typeof callId === "string" ? callId : void 0,
993
+ sessionId
994
+ });
995
+ const value = await waitForAnswer("approval", peerKey, request.signal);
996
+ if (value === PEER_ABORTED) throw new Error("local client entry: peer approval request aborted");
997
+ return value;
998
+ }));
999
+ return {
1000
+ answer(kind, callId, value) {
1001
+ const settle = pending.get(KEY(kind, callId));
1002
+ if (settle === void 0) return false;
1003
+ settle(value);
1004
+ return true;
1005
+ },
1006
+ dispose() {
1007
+ for (const off of owned.splice(0)) off();
1008
+ for (const settle of [...pending.values()]) settle(PEER_ABORTED);
1009
+ }
181
1010
  };
182
1011
  }
1012
+ /** Qualification-only read-only observer of the official transport frames.
1013
+ * It records the Gateway `$events` clientId/eventId without changing any
1014
+ * Gateway method or frame. */
1015
+ function observeQualificationSocket(socket, emit) {
1016
+ let clientId;
1017
+ socket.addEventListener("message", (event) => {
1018
+ const data = event.data;
1019
+ 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") : "";
1020
+ if (text === "") return;
1021
+ const client = /"clientId":"([^"]+)"/u.exec(text);
1022
+ if (client !== null) clientId = client[1];
1023
+ const eventId = /"eventId":"([^"]+)"/u.exec(text);
1024
+ if (eventId === null) return;
1025
+ emit({
1026
+ m4a0: "peer-frame",
1027
+ event: /"event":"([^"]+)"/u.exec(text)?.[1] ?? "unknown",
1028
+ eventId: eventId[1],
1029
+ ...clientId === void 0 ? {} : { clientId }
1030
+ });
1031
+ });
1032
+ }
183
1033
  /**
184
1034
  * Run one Client-only process until its launcher requests shutdown. Exported
185
1035
  * for the qualification harness; `import.meta.main` is the only production
186
1036
  * caller.
187
1037
  */
188
1038
  async function runLocalClientEntry(options) {
189
- const host = await loadOfficialClientHost(options.dshAnchor);
190
- const loadedProfile = host.loadProfile("split-process-client", options.profile, options.dshAnchor);
191
- const resolution = await host.createRuntimeResolution({
192
- installAnchor: options.dshAnchor,
193
- profile: loadedProfile
1039
+ const expectedHostInstanceId = expectedHostInstanceFromEnvironment(options.mode);
1040
+ assertHandoffSignalExclusivity(options.mode, expectedHostInstanceId);
1041
+ const hostModules = await loadOfficialClientHost(options.dshAnchor);
1042
+ const dshHome = hostModules.resolveDshHome();
1043
+ const packageRoot = installedPackageRootFromEntry(import.meta.url);
1044
+ const profileDir = hostModules.resolveProfileDir(options.profile, dshHome);
1045
+ const scope = scopeFromInstalledProfile({
1046
+ dshHome,
1047
+ profileDir,
1048
+ packageRoot,
1049
+ dshVersion: readInstalledDshVersion(options.dshAnchor)
1050
+ });
1051
+ const processStartIdentity = readLinuxStarttime();
1052
+ const recordSink = options.mode === "surface" ? createSurfaceRecordSink() : void 0;
1053
+ const emit = recordSink?.emit ?? writeEntryRecord;
1054
+ emit({
1055
+ m4a0: "client-started",
1056
+ processRole: "client",
1057
+ pid: process.pid,
1058
+ phase: "startup"
194
1059
  });
195
- const context = new host.Context();
1060
+ const seat = options.mode === "qualification" ? await bindProcessSeat(scope.clientSeatSocketName, "CLIENT_ALREADY_ACTIVE") : { close: async () => {} };
1061
+ let context;
1062
+ let loaderFiber;
1063
+ let startupGate;
1064
+ let installedTransport;
1065
+ let transport;
1066
+ let domainPrerequisites;
1067
+ let mountedDomains;
1068
+ let interactionDelivery;
1069
+ let peerSeat;
196
1070
  let handle;
1071
+ /** The ONE accepted one-shot handoff intent (never a second Client owner). */
1072
+ let reexecIntent;
1073
+ /** The reexec request latch of the qualification-only SIGUSR2 probe. */
1074
+ let reexecHandler;
1075
+ /** Set only when the ORIGINAL stop chain released every Client resource. */
1076
+ let reexecTeardownSucceeded = false;
1077
+ /** The ONE replacement child while the old PID waits as its parent. */
1078
+ let reexecChild;
1079
+ /** A termination signal arrived after the handoff was accepted, before spawn. */
1080
+ let reexecCancelled = false;
1081
+ /** The CURRENT revision's surface bridge behind the ONE root `appExit`. */
1082
+ let activeBridge;
1083
+ /** The ONE serial revision task slot shared by HMR and stop. */
1084
+ let revisionTask = Promise.resolve();
1085
+ const enqueueRevisionTask = (task) => {
1086
+ const run = revisionTask.then(task, task);
1087
+ revisionTask = run.then(() => {}, () => {});
1088
+ return run;
1089
+ };
1090
+ const diag = createEntryDiag("client", recordSink?.emit);
1091
+ const CLIENT_DISPOSE_DEADLINE_MS = 1e4;
1092
+ const disposeWithinDeadline = async (dispose, errors) => {
1093
+ let timer;
1094
+ const deadline = new Promise((resolve) => {
1095
+ timer = setTimeout(() => resolve(true), CLIENT_DISPOSE_DEADLINE_MS);
1096
+ });
1097
+ const done = dispose().then(() => false, (error) => {
1098
+ errors.push(error);
1099
+ return false;
1100
+ });
1101
+ const timedOut = await Promise.race([done, deadline]);
1102
+ if (timer !== void 0) clearTimeout(timer);
1103
+ if (timedOut) errors.push(/* @__PURE__ */ new Error("local client entry: client disposal deadline exceeded"));
1104
+ return timedOut;
1105
+ };
1106
+ const forceExitAfterCleanupFailure = () => {
1107
+ process.stdin.pause();
1108
+ setImmediate(() => {
1109
+ process.exit(1);
1110
+ });
1111
+ };
1112
+ let stopping;
1113
+ /** Resolves when the ONE startup chain has been entered/finished. A stop
1114
+ * that lands before `startupPromise` exists waits here instead of disposing
1115
+ * the root underneath a late `startLocalClient` call. */
1116
+ let startupReadyResolve;
1117
+ const startupReady = new Promise((resolve) => {
1118
+ startupReadyResolve = resolve;
1119
+ });
1120
+ /** The ONE startup cancellation owner: a stop aborts every in-flight mount
1121
+ * and readiness wait before any teardown starts. */
1122
+ const startupAbort = new AbortController();
1123
+ /** The in-flight ONE startup chain; `stop` awaits it before disposing. */
1124
+ let startupPromise;
1125
+ /** Whether the transport/root release already happened (single-root latch). */
1126
+ let rootReleased = false;
1127
+ let resolveStopped;
1128
+ const stopped = new Promise((resolve) => {
1129
+ resolveStopped = resolve;
1130
+ });
1131
+ let terminalError;
1132
+ let compositionDone = false;
1133
+ const stop = (code, failure) => {
1134
+ if (stopping !== void 0) return stopping;
1135
+ startupAbort.abort(failure ?? /* @__PURE__ */ new Error("local client entry: stop requested during startup"));
1136
+ stopping = (async () => {
1137
+ if (failure !== void 0) {
1138
+ const primary = failure instanceof Error ? failure : new Error(String(failure));
1139
+ emit({
1140
+ m4a0: "failure",
1141
+ processRole: "client",
1142
+ phase: context === void 0 ? "startup" : "after-context",
1143
+ pid: process.pid,
1144
+ ...failure instanceof LocalScopeError ? { code: failure.code } : {},
1145
+ error: primary.message,
1146
+ ...primary.stack === void 0 ? {} : { stack: primary.stack }
1147
+ });
1148
+ }
1149
+ const errors = [];
1150
+ const timedOut = await disposeWithinDeadline(async () => {
1151
+ if (rootReleased) return;
1152
+ if (startupPromise === void 0 && context !== void 0 && !compositionDone) await startupReady;
1153
+ if (startupPromise !== void 0 && handle === void 0) try {
1154
+ handle = await startupPromise;
1155
+ } catch {}
1156
+ if (handle !== void 0) {
1157
+ await revisionTask;
1158
+ try {
1159
+ await handle.dispose();
1160
+ } catch (error) {
1161
+ errors.push(error);
1162
+ }
1163
+ rootReleased = true;
1164
+ return;
1165
+ }
1166
+ try {
1167
+ interactionDelivery?.dispose();
1168
+ } catch (error) {
1169
+ errors.push(error);
1170
+ }
1171
+ try {
1172
+ peerSeat?.dispose();
1173
+ } catch (error) {
1174
+ errors.push(error);
1175
+ }
1176
+ try {
1177
+ await transport?.dispose();
1178
+ } catch (error) {
1179
+ errors.push(error);
1180
+ }
1181
+ try {
1182
+ await domainPrerequisites?.dispose();
1183
+ } catch (error) {
1184
+ errors.push(error);
1185
+ }
1186
+ try {
1187
+ await mountedDomains?.dispose();
1188
+ } catch (error) {
1189
+ errors.push(error);
1190
+ }
1191
+ startupGate?.cancel(failure ?? /* @__PURE__ */ new Error("local client entry: stop requested during startup"));
1192
+ try {
1193
+ await loaderFiber?.dispose();
1194
+ } catch (error) {
1195
+ errors.push(error);
1196
+ }
1197
+ try {
1198
+ await context?.fiber.dispose();
1199
+ } catch (error) {
1200
+ errors.push(error);
1201
+ }
1202
+ rootReleased = true;
1203
+ }, errors);
1204
+ if (options.mode === "surface" && handle !== void 0) emit({
1205
+ m4b2s: "client-closed",
1206
+ ...traceStatus(handle.status)
1207
+ });
1208
+ const transportCleanupFailed = errors.some((error) => error instanceof Error && error.cleanupFailed === true);
1209
+ if (errors.length > 0 || timedOut) {
1210
+ const primary = errors[0] instanceof Error ? errors[0] : new Error(String(errors[0] ?? "client disposal failed"));
1211
+ emit({
1212
+ m4a0: "cleanup-failure",
1213
+ processRole: "client",
1214
+ phase: "shutdown",
1215
+ pid: process.pid,
1216
+ error: primary.message
1217
+ });
1218
+ process.exitCode = 1;
1219
+ } else if (failure !== void 0) {
1220
+ emit({
1221
+ m4a0: "cleanup",
1222
+ processRole: "client",
1223
+ phase: "after-context",
1224
+ pid: process.pid,
1225
+ status: "completed"
1226
+ });
1227
+ process.exitCode = 1;
1228
+ } else {
1229
+ process.exitCode = code;
1230
+ if (code === 0 && reexecIntent !== void 0) reexecTeardownSucceeded = true;
1231
+ }
1232
+ process.stdin.pause();
1233
+ resolveStopped?.();
1234
+ if (timedOut || transportCleanupFailed) forceExitAfterCleanupFailure();
1235
+ })();
1236
+ return stopping;
1237
+ };
1238
+ process.on("SIGTERM", () => {
1239
+ emit({
1240
+ m4a0: "signal",
1241
+ processRole: "client",
1242
+ pid: process.pid,
1243
+ signal: "SIGTERM"
1244
+ });
1245
+ if (routeReexecTermination(reexecIntent !== void 0, reexecChild, "SIGTERM", () => {
1246
+ reexecCancelled = true;
1247
+ })) return;
1248
+ runDetached("local client: SIGTERM shutdown", () => stop(0), { diag });
1249
+ });
1250
+ process.on("SIGINT", () => {
1251
+ emit({
1252
+ m4a0: "signal",
1253
+ processRole: "client",
1254
+ pid: process.pid,
1255
+ signal: "SIGINT"
1256
+ });
1257
+ if (routeReexecTermination(reexecIntent !== void 0, reexecChild, "SIGINT", () => {
1258
+ reexecCancelled = true;
1259
+ })) return;
1260
+ runDetached("local client: SIGINT shutdown", () => stop(130), { diag });
1261
+ });
1262
+ /**
1263
+ * The structured status of the transport for a record. Surface mode strips
1264
+ * the private Host home path; the qualification channel keeps its frozen
1265
+ * shape. Cookie/token values never enter a record on either path.
1266
+ */
1267
+ const traceTransportStatus = () => {
1268
+ if (transport === void 0) return {};
1269
+ const observed = transport.status();
1270
+ if (options.mode !== "surface") return observed;
1271
+ const { hostHome: _hostHome, ...safe } = observed;
1272
+ return safe;
1273
+ };
1274
+ /**
1275
+ * The same projection for the handle status (surface mode strips the Host
1276
+ * home path; the qualification status shape is unchanged).
1277
+ */
1278
+ const traceStatus = (status) => {
1279
+ if (options.mode !== "surface") return status;
1280
+ const { hostHome: _hostHome, ...safe } = status;
1281
+ return safe;
1282
+ };
197
1283
  try {
198
- await context.plugin(host.PluginPackages, { resolution });
199
- writeEntryRecord({
1284
+ const host = await ensureLocalHost({
1285
+ scope,
1286
+ hostEntryPath: join(packageRoot, "dist", "local-host.mjs"),
1287
+ dshAnchor: options.dshAnchor,
1288
+ profile: options.profile,
1289
+ ...expectedHostInstanceId === void 0 ? {} : { expectedInstanceId: expectedHostInstanceId }
1290
+ });
1291
+ startupAbort.signal.throwIfAborted();
1292
+ emit({
1293
+ m4a0: "host-authenticated",
1294
+ processRole: "client",
1295
+ pid: process.pid,
1296
+ phase: "host-authenticated",
1297
+ host: hostRecordForTrace(host)
1298
+ });
1299
+ const loadedProfile = hostModules.loadProfile("split-process-client", options.profile, options.dshAnchor);
1300
+ const resolution = await hostModules.createRuntimeResolution({
1301
+ installAnchor: options.dshAnchor,
1302
+ profile: loadedProfile
1303
+ });
1304
+ context = new hostModules.Context();
1305
+ await context.plugin(hostModules.PluginPackages, { resolution });
1306
+ emit({
200
1307
  m4a0: "context-ready",
201
1308
  processRole: "client",
202
1309
  pid: process.pid,
203
1310
  phase: "context-ready"
204
1311
  });
205
- const { startLocalClient } = await import("./client-bootstrap-F5DHFI9t.mjs");
206
- handle = await startLocalClient(context, {}, readProcessStartIdentity());
207
- writeEntryRecord({
208
- m4a0: "ready",
209
- ...handle.status
210
- });
211
- let stopping = false;
212
- const stop = async (code) => {
213
- if (stopping) return;
214
- stopping = true;
215
- if (handle === void 0) {
216
- process.exit(code);
1312
+ const transportModule = await import("./local-transport-BVwFYq_Y.mjs");
1313
+ const { mountSurfaceClientDomainPrerequisites, startLocalClient } = await import("./client-bootstrap-Cr1JCaF5.mjs");
1314
+ const onTransportFatal = (error) => {
1315
+ terminalError ??= error;
1316
+ if (compositionDone) runDetached("local client: terminal transport identity failure", () => stop(1, terminalError), { diag });
1317
+ };
1318
+ if (options.mode === "surface" || options.mode === "peer") {
1319
+ const clientContext = context;
1320
+ if (clientContext === void 0) throw new Error("local client entry: the Client root Context is missing");
1321
+ loaderFiber = clientContext.plugin(hostModules.Loader, {});
1322
+ await loaderFiber;
1323
+ const loader = clientContext.get("loader");
1324
+ if (loader === void 0) throw new Error("local client entry: the official Cordis Loader did not install");
1325
+ startupGate = createInteractionStartupGate();
1326
+ loader.builtins[INTERACTION_STARTUP_GATE] = startupGate.plugin;
1327
+ await loader.create({ name: `cordis:${INTERACTION_STARTUP_GATE}` });
1328
+ startupAbort.signal.throwIfAborted();
1329
+ if (!startupGate.pending) throw new Error("local client entry: the interaction startup gate failed before the transport install");
1330
+ const gateHold = process.env.SPLIT_PROCESS_CLIENT_HOLD_STARTUP_GATE;
1331
+ if (gateHold !== void 0 && gateHold !== "") {
1332
+ emit({
1333
+ m4b2s: "qualification",
1334
+ op: "startup-gate-hold",
1335
+ stage: "loader-gate",
1336
+ barrier: gateHold
1337
+ });
1338
+ await waitForStartupHold(gateHold, startupAbort.signal);
1339
+ }
1340
+ installedTransport = await transportModule.installLocalTransport(clientContext, {
1341
+ dshAnchor: options.dshAnchor,
1342
+ host,
1343
+ scope,
1344
+ diag,
1345
+ signal: startupAbort.signal,
1346
+ onFatal: onTransportFatal,
1347
+ ...options.mode === "peer" ? { qualificationWebSocketObserver: (_url, socket) => observeQualificationSocket(socket, emit) } : {}
1348
+ });
1349
+ transport = installedTransport;
1350
+ startupAbort.signal.throwIfAborted();
1351
+ domainPrerequisites = await mountSurfaceClientDomainPrerequisites(clientContext, { dshAnchor: options.dshAnchor });
1352
+ const remote = clientContext.get("remote");
1353
+ if (remote === void 0) throw new Error("local client entry: the official Client Remote service did not install");
1354
+ const remoteService = clientContext.get("remote");
1355
+ if (options.mode === "surface") interactionDelivery = createSplitClientInteractionDelivery({
1356
+ remote,
1357
+ sessions: domainPrerequisites.sessions
1358
+ });
1359
+ else peerSeat = createPeerInteractionSeat(remote, domainPrerequisites.sessions, emit);
1360
+ const agentResolver = clientContext.get("typert")?.contexts.getClient("agent");
1361
+ assertInteractionStartupReady(startupGate, agentResolver);
1362
+ emit({
1363
+ m4b2s: "qualification",
1364
+ op: "interaction-startup-gate",
1365
+ phase: "listeners-ready",
1366
+ agentResolver: agentResolver !== void 0,
1367
+ questionListeners: 1,
1368
+ approvalListeners: 1,
1369
+ loaderTasks: loader.getTasks().length
1370
+ });
1371
+ startupGate.release();
1372
+ transport = await transportModule.awaitLocalTransportReady(installedTransport, { signal: startupAbort.signal });
1373
+ if (terminalError !== void 0) {
1374
+ await stop(1, terminalError);
217
1375
  return;
218
1376
  }
219
- process.exit(await stopLocalClient(handle, code));
1377
+ emit({
1378
+ m4a0: "transport-ready",
1379
+ processRole: "client",
1380
+ pid: process.pid,
1381
+ phase: "transport-ready",
1382
+ ...traceTransportStatus()
1383
+ });
1384
+ mountedDomains = await domainPrerequisites.complete({ signal: startupAbort.signal });
1385
+ domainPrerequisites = void 0;
1386
+ startupAbort.signal.throwIfAborted();
1387
+ emit({
1388
+ m4b2s: "qualification",
1389
+ op: "startup-stage",
1390
+ stage: "domains-ready",
1391
+ pid: process.pid
1392
+ });
1393
+ if (options.mode === "peer") {
1394
+ emit({
1395
+ m4a0: "ready",
1396
+ processRole: "client",
1397
+ pid: process.pid,
1398
+ phase: "peer-ready",
1399
+ mode: "peer",
1400
+ hostPid: host.identity.hostPid,
1401
+ hostInstanceId: host.identity.instanceId,
1402
+ ...traceTransportStatus()
1403
+ });
1404
+ compositionDone = true;
1405
+ attachEntryControl(async (request) => {
1406
+ if (request.op === "status") {
1407
+ emit({
1408
+ m4a0: "status",
1409
+ pid: process.pid,
1410
+ ...traceTransportStatus()
1411
+ });
1412
+ return false;
1413
+ }
1414
+ if (request.op === "peer-answer") {
1415
+ const kind = request.kind;
1416
+ const callId = request.callId;
1417
+ const value = request.value;
1418
+ if (kind !== "question" && kind !== "approval" || typeof callId !== "string") {
1419
+ emit({
1420
+ m4a0: "control-error",
1421
+ error: "peer-answer requires kind/callId/value"
1422
+ });
1423
+ return false;
1424
+ }
1425
+ const delivered = peerSeat?.answer(kind, callId, value) === true;
1426
+ emit({
1427
+ m4a0: "peer-answer-sent",
1428
+ kind,
1429
+ callId,
1430
+ delivered
1431
+ });
1432
+ return false;
1433
+ }
1434
+ if (request.op === "peer-send-stale-result") {
1435
+ const eventId = request.eventId;
1436
+ const clientId = request.clientId;
1437
+ const outcome = request.value;
1438
+ if (typeof eventId !== "string" || typeof clientId !== "string" || outcome === void 0) {
1439
+ emit({
1440
+ m4a0: "control-error",
1441
+ error: "peer-send-stale-result requires eventId/clientId/value"
1442
+ });
1443
+ return false;
1444
+ }
1445
+ const connection = clientContext.get("connection");
1446
+ if (connection === void 0) throw new Error("local client entry: the qualification Peer has no Connection RPC");
1447
+ const response = await connection.rpc.call("/api", "$events/result", { args: {
1448
+ clientId,
1449
+ eventId,
1450
+ outcome
1451
+ } });
1452
+ emit({
1453
+ m4a0: "peer-stale-result-sent",
1454
+ eventId,
1455
+ clientId,
1456
+ ok: response.ok === true,
1457
+ ...response.error?.code === void 0 ? {} : { errorCode: response.error.code }
1458
+ });
1459
+ return false;
1460
+ }
1461
+ if (request.op === "peer-question-answer") {
1462
+ const sessionId = request.sessionId;
1463
+ const callId = request.callId;
1464
+ const value = request.value;
1465
+ if (typeof sessionId !== "string" || typeof callId !== "string" || value === void 0) {
1466
+ emit({
1467
+ m4a0: "control-error",
1468
+ error: "peer-question-answer requires sessionId/callId/value"
1469
+ });
1470
+ return false;
1471
+ }
1472
+ if (remoteService?.userQuestions === void 0) throw new Error("local client entry: the qualification Peer has no userQuestions namespace");
1473
+ const result = await remoteService.userQuestions.answer(sessionId, callId, value);
1474
+ emit({
1475
+ m4a0: "peer-question-answer",
1476
+ sessionId,
1477
+ callId,
1478
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId },
1479
+ ok: result.ok === true,
1480
+ ...result.ok ? { value: result.value === true } : {
1481
+ errorCode: result.error?.code,
1482
+ error: result.error
1483
+ }
1484
+ });
1485
+ return false;
1486
+ }
1487
+ if (request.op === "qualification-web-access") {
1488
+ const enabled = request.webAccessEnabled;
1489
+ const webAccess = remoteService?.piTuiWebAccess;
1490
+ if (webAccess === void 0) throw new Error("local client entry: the qualification Peer has no piTuiWebAccess namespace");
1491
+ const result = enabled === void 0 ? await webAccess.getStatus() : await webAccess.setEnabled(enabled);
1492
+ emit({
1493
+ m4a0: "qualification",
1494
+ op: "web-access",
1495
+ processRole: "client",
1496
+ pid: process.pid,
1497
+ action: enabled === void 0 ? "getStatus" : "setEnabled",
1498
+ ...enabled === void 0 ? {} : { enabled },
1499
+ ok: result.ok === true,
1500
+ ...result.ok ? { status: result.value } : {
1501
+ errorCode: result.error?.code,
1502
+ ...result.error?.message === void 0 ? {} : { error: result.error.message.slice(0, 300) }
1503
+ },
1504
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1505
+ });
1506
+ return false;
1507
+ }
1508
+ if (request.op === "qualification-workspace-create") {
1509
+ const workspace = remoteService?.workspace;
1510
+ if (workspace === void 0) throw new Error("local client entry: the qualification Peer has no workspace namespace");
1511
+ const path = request.workspacePath;
1512
+ if (typeof path !== "string" || path === "") throw new Error("local client entry: qualification-workspace-create requires an absolute workspacePath");
1513
+ const result = await workspace.create({ path });
1514
+ const value = result.ok ? result.value : void 0;
1515
+ emit({
1516
+ m4a0: "qualification",
1517
+ op: "workspace-create",
1518
+ processRole: "client",
1519
+ pid: process.pid,
1520
+ ok: result.ok === true,
1521
+ ...value === void 0 ? { errorCode: result.error?.code } : {
1522
+ created: value.created === true,
1523
+ ...typeof value.workspace?.workspaceId === "string" ? { workspaceId: value.workspace.workspaceId } : {}
1524
+ },
1525
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1526
+ });
1527
+ return false;
1528
+ }
1529
+ if (request.op === "qualification-web-autostart") {
1530
+ const settings = remoteService?.settings;
1531
+ if (settings === void 0) throw new Error("local client entry: the qualification Peer has no settings namespace");
1532
+ const preferenceOf = (value) => {
1533
+ const entry = (value?.namespaces)?.find((candidate) => candidate.ns === "pi-tui-web-preferences");
1534
+ if (entry === void 0) return void 0;
1535
+ const projected = entry.value;
1536
+ if (typeof projected?.autoStart !== "boolean" || typeof entry.revision !== "number") return void 0;
1537
+ const user = entry.user;
1538
+ return {
1539
+ autoStart: projected.autoStart,
1540
+ revision: entry.revision,
1541
+ userOverridden: user?.autoStart !== void 0
1542
+ };
1543
+ };
1544
+ const before = await settings.describe();
1545
+ const current = before.ok ? preferenceOf(before.value) : void 0;
1546
+ if (current === void 0) {
1547
+ emit({
1548
+ m4a0: "qualification",
1549
+ op: "web-autostart",
1550
+ processRole: "client",
1551
+ pid: process.pid,
1552
+ ok: false,
1553
+ errorCode: "preference/unavailable",
1554
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1555
+ });
1556
+ return false;
1557
+ }
1558
+ const requested = request.webAutoStart;
1559
+ if (requested === void 0) {
1560
+ emit({
1561
+ m4a0: "qualification",
1562
+ op: "web-autostart",
1563
+ processRole: "client",
1564
+ pid: process.pid,
1565
+ action: "read",
1566
+ ...current,
1567
+ ok: true,
1568
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1569
+ });
1570
+ return false;
1571
+ }
1572
+ if (typeof requested !== "boolean") throw new Error("local client entry: qualification-web-autostart requires a boolean webAutoStart");
1573
+ const write = await settings.mutate("pi-tui-web-preferences", [{
1574
+ op: "set",
1575
+ path: ["autoStart"],
1576
+ value: requested
1577
+ }], current.revision);
1578
+ const after = await settings.describe();
1579
+ const settled = after.ok ? preferenceOf(after.value) : void 0;
1580
+ emit({
1581
+ m4a0: "qualification",
1582
+ op: "web-autostart",
1583
+ processRole: "client",
1584
+ pid: process.pid,
1585
+ action: "write",
1586
+ requested,
1587
+ ok: write.ok && settled !== void 0,
1588
+ ...settled === void 0 ? {} : settled,
1589
+ readBack: settled?.autoStart === requested,
1590
+ ...write.ok ? {} : {
1591
+ errorCode: write.error?.code,
1592
+ ...write.error?.message === void 0 ? {} : { error: write.error.message.slice(0, 300) }
1593
+ },
1594
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1595
+ });
1596
+ return false;
1597
+ }
1598
+ if (request.op === "qualification-web-access-url") {
1599
+ const webAccess = remoteService?.piTuiWebAccess;
1600
+ if (webAccess === void 0) throw new Error("local client entry: the qualification Peer has no piTuiWebAccess namespace");
1601
+ const result = await webAccess.getAuthenticatedUrl();
1602
+ if (!result.ok) {
1603
+ emit({
1604
+ m4a0: "qualification",
1605
+ op: "web-access-url",
1606
+ processRole: "client",
1607
+ pid: process.pid,
1608
+ ok: false,
1609
+ ...result.error?.code === void 0 ? {} : { errorCode: result.error.code },
1610
+ ...result.error?.message === void 0 ? {} : { error: result.error.message.slice(0, 300) },
1611
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1612
+ });
1613
+ return false;
1614
+ }
1615
+ const url = new URL(result.value.url);
1616
+ const exchange = await fetch(url, { redirect: "manual" });
1617
+ await exchange.body?.cancel();
1618
+ const cookies = exchange.headers.getSetCookie().map((header) => header.split(";")[0] ?? "").filter((pair) => pair !== "");
1619
+ const cookieHeader = cookies.join("; ");
1620
+ let pageStatus;
1621
+ let pageBytes = 0;
1622
+ if (cookieHeader !== "") {
1623
+ const page = await fetch(`${url.origin}/`, {
1624
+ redirect: "manual",
1625
+ headers: { cookie: cookieHeader }
1626
+ });
1627
+ const body = await page.text();
1628
+ pageStatus = page.status;
1629
+ pageBytes = body.length;
1630
+ }
1631
+ emit({
1632
+ m4a0: "qualification",
1633
+ op: "web-access-url",
1634
+ processRole: "client",
1635
+ pid: process.pid,
1636
+ ok: true,
1637
+ loopback: url.hostname === "127.0.0.1",
1638
+ protocol: url.protocol,
1639
+ pathname: url.pathname,
1640
+ tokenParams: url.searchParams.getAll("token").length,
1641
+ paramNames: [...url.searchParams.keys()],
1642
+ exchangeStatus: exchange.status,
1643
+ cookieNames: cookies.map((pair) => pair.split("=")[0]),
1644
+ ...pageStatus === void 0 ? {} : {
1645
+ pageStatus,
1646
+ pageBytes
1647
+ },
1648
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1649
+ });
1650
+ return false;
1651
+ }
1652
+ if (request.op === "shutdown") {
1653
+ await stop(0);
1654
+ return true;
1655
+ }
1656
+ emit({
1657
+ m4a0: "control-error",
1658
+ error: `local client entry: unknown op ${JSON.stringify(request.op)}`
1659
+ });
1660
+ return false;
1661
+ });
1662
+ await stopped;
1663
+ return;
1664
+ }
1665
+ } else {
1666
+ transport = await transportModule.startLocalTransport(context, {
1667
+ dshAnchor: options.dshAnchor,
1668
+ host,
1669
+ scope,
1670
+ diag,
1671
+ onFatal: onTransportFatal
1672
+ });
1673
+ if (terminalError !== void 0) {
1674
+ await stop(1, terminalError);
1675
+ return;
1676
+ }
1677
+ emit({
1678
+ m4a0: "transport-ready",
1679
+ processRole: "client",
1680
+ pid: process.pid,
1681
+ phase: "transport-ready",
1682
+ ...traceTransportStatus()
1683
+ });
1684
+ }
1685
+ if (process.env.SPLIT_PROCESS_CLIENT_FORCE_FAILURE === "client-bootstrap") throw new Error("local client entry: qualification forced client bootstrap failure");
1686
+ const clientContext = context;
1687
+ if (clientContext === void 0) throw new Error("local client entry: the Client root Context is missing");
1688
+ const surfaceFacts = surfaceStartupFacts(options);
1689
+ /**
1690
+ * The ONE allowed process-composition edge into `app/bootstrap.ts`
1691
+ * (architecture gate: exact lazy dynamic import, this entry only). It runs
1692
+ * only AFTER `PluginPackages` installed the official runtime resolution and
1693
+ * the Client bootstrap mounted the official Domain/UI/application graph; it
1694
+ * mounts the runner as its own Cordis fiber on the SAME Client Context.
1695
+ */
1696
+ const mountRunner = async (input) => {
1697
+ const bridge = createLocalClientSurfaceBridge((code) => {
1698
+ runDetached("local client: surface exit", () => stop(code), { diag });
1699
+ });
1700
+ activeBridge = bridge;
1701
+ const { applyRunnerWithRuntime } = await import("./bootstrap-DQ4YPL-7.mjs");
1702
+ let runnerFiber;
1703
+ try {
1704
+ runnerFiber = clientContext.plugin((pluginContext) => {
1705
+ applyRunnerWithRuntime(pluginContext, input.config, input.override, {
1706
+ surfaceReady: () => bridge.markMounted(),
1707
+ surfaceFailed: (error) => bridge.fail(error),
1708
+ ...reexecHandler === void 0 ? {} : { requestClientReload: () => reexecHandler.request("manual") }
1709
+ });
1710
+ });
1711
+ await runnerFiber;
1712
+ } catch (error) {
1713
+ bridge.fail(error);
1714
+ throw error;
1715
+ }
1716
+ const fiber = runnerFiber;
1717
+ return {
1718
+ ready: bridge.ready,
1719
+ stopped: bridge.stopped,
1720
+ dispose: async () => {
1721
+ await fiber.dispose();
1722
+ },
1723
+ ...fiber.uid == null ? {} : { fiberUid: fiber.uid }
1724
+ };
220
1725
  };
221
- const diag = createEntryDiag("client");
222
- process.on("SIGTERM", () => {
223
- runDetached("local client: SIGTERM shutdown", () => stop(0), { diag });
224
- });
225
- process.on("SIGINT", () => {
226
- runDetached("local client: SIGINT shutdown", () => stop(130), { diag });
1726
+ if (options.mode === "surface") {
1727
+ clientContext.provide("appExit", (code) => {
1728
+ activeBridge?.requestStop(code);
1729
+ });
1730
+ if (process.env.SPLIT_PROCESS_CLIENT_HMR_PROBE === "1") {
1731
+ 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");
1732
+ process.on("SIGUSR2", () => {
1733
+ if (handle === void 0) return;
1734
+ runDetached("local client: surface HMR", () => {
1735
+ return enqueueRevisionTask(async () => {
1736
+ await handle.replaceSurfaceForQualification();
1737
+ }).catch((error) => stop(1, error));
1738
+ }, { diag });
1739
+ });
1740
+ }
1741
+ const reexecProbe = process.env.SPLIT_PROCESS_CLIENT_REEXEC_PROBE === "1";
1742
+ const targetOverride = reexecProbe ? process.env.SPLIT_PROCESS_CLIENT_REEXEC_TARGET_PACKAGE_ROOT : void 0;
1743
+ 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");
1744
+ reexecHandler = createClientReexecRequestHandler({
1745
+ status: () => handle?.status,
1746
+ prepare: (status, source) => prepareClientReexec({
1747
+ status,
1748
+ verifiedHostInstanceId: host.identity.instanceId,
1749
+ profileDir,
1750
+ dshAnchor: options.dshAnchor,
1751
+ profile: options.profile,
1752
+ dshVersion: scope.dshVersion,
1753
+ currentBuildId: scope.buildId,
1754
+ ...source === "qualification" && reexecProbe && targetOverride !== void 0 && targetOverride !== "" ? { targetPackageRootOverride: targetOverride } : {}
1755
+ }),
1756
+ requestStop: () => {
1757
+ runDetached("local client: reexec handoff", () => stop(0), { diag });
1758
+ },
1759
+ emit,
1760
+ canRequest: () => stopping === void 0,
1761
+ onAccepted: (accepted) => {
1762
+ reexecIntent = accepted;
1763
+ }
1764
+ });
1765
+ if (reexecProbe) process.on("SIGUSR2", () => {
1766
+ reexecHandler?.request("qualification");
1767
+ });
1768
+ const onTerminalEnd = () => {
1769
+ runDetached("local client: terminal EOF shutdown", () => stop(0), { diag });
1770
+ };
1771
+ process.stdin.on("end", onTerminalEnd);
1772
+ process.stdin.on("close", onTerminalEnd);
1773
+ process.on("SIGUSR1", () => {
1774
+ transport?.dropWebSocketsForQualification();
1775
+ emit({
1776
+ m4b2s: "qualification",
1777
+ op: "drop-websocket",
1778
+ processRole: "client",
1779
+ pid: process.pid
1780
+ });
1781
+ });
1782
+ }
1783
+ const composition = options.mode === "surface" ? {
1784
+ mode: "surface",
1785
+ signal: startupAbort.signal,
1786
+ transport,
1787
+ host: host.identity,
1788
+ dshAnchor: options.dshAnchor,
1789
+ authenticatedFetch: transport.authenticatedFetch,
1790
+ domains: mountedDomains,
1791
+ interactionDelivery,
1792
+ mountRunner,
1793
+ diag,
1794
+ onStatus: (status) => {
1795
+ emit({
1796
+ m4b2s: "surface-status",
1797
+ ...traceStatus(status)
1798
+ });
1799
+ },
1800
+ onQualification: (record) => {
1801
+ emit({
1802
+ m4b2s: "qualification",
1803
+ ...record
1804
+ });
1805
+ }
1806
+ } : {
1807
+ mode: "qualification",
1808
+ transport,
1809
+ host: host.identity
1810
+ };
1811
+ try {
1812
+ const holdBeforeStart = process.env.SPLIT_PROCESS_CLIENT_HOLD_BEFORE_START;
1813
+ if (holdBeforeStart !== void 0 && holdBeforeStart !== "") {
1814
+ emit({
1815
+ m4a0: "qualification",
1816
+ op: "before-start-hold",
1817
+ processRole: "client",
1818
+ pid: process.pid
1819
+ });
1820
+ await waitForStartupHold(holdBeforeStart, startupAbort.signal);
1821
+ }
1822
+ startupPromise = startLocalClient(clientContext, surfaceFacts, processStartIdentity, composition);
1823
+ handle = await startupPromise;
1824
+ } finally {
1825
+ startupReadyResolve?.();
1826
+ startupReadyResolve = void 0;
1827
+ }
1828
+ if (stopping !== void 0) {
1829
+ await stopping;
1830
+ return;
1831
+ }
1832
+ if (terminalError !== void 0) {
1833
+ await stop(1, terminalError);
1834
+ return;
1835
+ }
1836
+ if (expectedHostInstanceId !== void 0) {
1837
+ const restoredHost = handle.status.host;
1838
+ if (restoredHost === void 0 || restoredHost.instanceId !== expectedHostInstanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local client entry: the handoff Client authenticated a different Host instance");
1839
+ if (handle.status.transport !== "connected") throw new Error("local client entry: the handoff Client has no connected official transport");
1840
+ const proof = await handle.awaitHandoffOpen(surfaceFacts.sessionId, startupAbort.signal);
1841
+ if (stopping !== void 0) {
1842
+ await stopping;
1843
+ return;
1844
+ }
1845
+ const restored = handle.status;
1846
+ const restoredFacts = assertHandoffRestored(restored, expectedHostInstanceId, terminalError);
1847
+ proof.verify();
1848
+ emit({
1849
+ m4r: "handoff-restored",
1850
+ processRole: "client",
1851
+ pid: process.pid,
1852
+ expectedHostInstanceId,
1853
+ hostInstanceId: restoredFacts.hostInstanceId,
1854
+ ...surfaceFacts.sessionId === void 0 ? {} : { sessionId: surfaceFacts.sessionId },
1855
+ clientBuildId: scope.buildId,
1856
+ transport: restored.transport,
1857
+ sessionOpen: restored.sessionOpen,
1858
+ sessionHistoryOpen: surfaceFacts.sessionId !== void 0,
1859
+ surfaceMounted: restored.surfaceMounted
1860
+ });
1861
+ }
1862
+ emit({
1863
+ m4a0: "ready",
1864
+ ...traceStatus(handle.status)
227
1865
  });
1866
+ compositionDone = true;
1867
+ if (options.mode === "surface") {
1868
+ await stopped;
1869
+ return;
1870
+ }
228
1871
  attachEntryControl(async (request) => {
229
1872
  if (request.op === "status") {
230
- writeEntryRecord({
1873
+ emit({
231
1874
  m4a0: "status",
232
1875
  ...request.requestId === void 0 ? {} : { requestId: request.requestId },
233
1876
  ...handle.status
@@ -238,41 +1881,179 @@ async function runLocalClientEntry(options) {
238
1881
  await stop(0);
239
1882
  return true;
240
1883
  }
241
- writeEntryRecord({
1884
+ if (request.op === "qualification-drop-websocket") {
1885
+ transport?.dropWebSocketsForQualification();
1886
+ emit({
1887
+ m4a0: "qualification",
1888
+ op: "drop-websocket",
1889
+ processRole: "client",
1890
+ pid: process.pid,
1891
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1892
+ });
1893
+ return false;
1894
+ }
1895
+ if (request.op === "qualification-host-foundation") {
1896
+ if (context === void 0) throw new Error("local client entry: the qualification probe has no Client Context");
1897
+ const qualificationRequest = request;
1898
+ const workspacePath = qualificationRequest.workspacePath;
1899
+ if (workspacePath !== void 0 && (typeof workspacePath !== "string" || workspacePath === "")) throw new Error("local client entry: a supplied workspacePath must be a non-empty string");
1900
+ const workspaceResume = qualificationRequest.workspaceResume;
1901
+ if (workspaceResume !== void 0 && workspaceResume !== true) throw new Error("local client entry: workspaceResume must be the boolean true when supplied");
1902
+ if (workspaceResume === true && workspacePath === void 0) throw new Error("local client entry: the generation-resume control requires a workspacePath");
1903
+ const schedule = qualificationRequest.schedule;
1904
+ if (schedule !== void 0 && schedule !== true) throw new Error("local client entry: schedule must be the boolean true when supplied");
1905
+ const { runHostFoundationProbe } = await import("./host-foundation-probe--5jtvHVe.mjs");
1906
+ const proof = await runHostFoundationProbe(context, {
1907
+ dshAnchor: options.dshAnchor,
1908
+ host,
1909
+ ...workspacePath === void 0 ? {} : { workspacePath },
1910
+ ...schedule === true ? { schedule: true } : {},
1911
+ ...workspaceResume !== true ? {} : {
1912
+ readGeneration: () => transport?.status().generationId,
1913
+ dropCarrier: () => {
1914
+ transport?.dropWebSocketsForQualification();
1915
+ emit({
1916
+ m4a0: "qualification",
1917
+ op: "drop-websocket",
1918
+ label: "workspace-hold",
1919
+ processRole: "client",
1920
+ pid: process.pid
1921
+ });
1922
+ }
1923
+ },
1924
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1925
+ });
1926
+ emit({
1927
+ ...proof,
1928
+ processRole: "client",
1929
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId }
1930
+ });
1931
+ return false;
1932
+ }
1933
+ emit({
242
1934
  m4a0: "control-error",
243
1935
  error: `local client entry: unknown op ${JSON.stringify(request.op)}`
244
1936
  });
245
1937
  return false;
246
1938
  });
1939
+ await stopped;
247
1940
  } catch (error) {
248
- let primary = error instanceof Error ? error : new Error(String(error));
249
- if (handle !== void 0) try {
250
- await handle.dispose();
251
- } catch (cleanupError) {
252
- primary = mergeCause(primary, cleanupError);
253
- }
254
- try {
255
- await context.fiber.dispose();
256
- } catch (cleanupError) {
257
- primary = mergeCause(primary, cleanupError);
1941
+ if (stopping !== void 0) {
1942
+ startupReadyResolve?.();
1943
+ await stopping;
1944
+ return;
258
1945
  }
259
- writeEntryRecord({
1946
+ const failure = terminalError ?? error;
1947
+ let primary = failure instanceof Error ? failure : new Error(String(failure));
1948
+ const cleanupErrors = [];
1949
+ const timedOut = await disposeWithinDeadline(async () => {
1950
+ if (rootReleased) return;
1951
+ if (handle !== void 0) {
1952
+ try {
1953
+ await handle.dispose();
1954
+ } catch (cleanupError) {
1955
+ cleanupErrors.push(cleanupError);
1956
+ }
1957
+ rootReleased = true;
1958
+ return;
1959
+ }
1960
+ try {
1961
+ interactionDelivery?.dispose();
1962
+ } catch (cleanupError) {
1963
+ cleanupErrors.push(cleanupError);
1964
+ }
1965
+ try {
1966
+ peerSeat?.dispose();
1967
+ } catch (cleanupError) {
1968
+ cleanupErrors.push(cleanupError);
1969
+ }
1970
+ try {
1971
+ await transport?.dispose();
1972
+ } catch (cleanupError) {
1973
+ cleanupErrors.push(cleanupError);
1974
+ }
1975
+ try {
1976
+ await domainPrerequisites?.dispose();
1977
+ } catch (cleanupError) {
1978
+ cleanupErrors.push(cleanupError);
1979
+ }
1980
+ try {
1981
+ await mountedDomains?.dispose();
1982
+ } catch (cleanupError) {
1983
+ cleanupErrors.push(cleanupError);
1984
+ }
1985
+ startupGate?.cancel(primary);
1986
+ try {
1987
+ await loaderFiber?.dispose();
1988
+ } catch (cleanupError) {
1989
+ cleanupErrors.push(cleanupError);
1990
+ }
1991
+ try {
1992
+ await context?.fiber.dispose();
1993
+ } catch (cleanupError) {
1994
+ cleanupErrors.push(cleanupError);
1995
+ }
1996
+ rootReleased = true;
1997
+ }, cleanupErrors);
1998
+ for (const cleanupError of cleanupErrors) primary = mergeCause(primary, cleanupError);
1999
+ const transportCleanupFailed = error instanceof Error && error.cleanupFailed === true || cleanupErrors.some((cleanupError) => cleanupError instanceof Error && cleanupError.cleanupFailed === true);
2000
+ emit({
260
2001
  m4a0: "failure",
261
2002
  processRole: "client",
262
- phase: "after-context",
2003
+ phase: context === void 0 ? "startup" : "after-context",
263
2004
  pid: process.pid,
2005
+ ...traceTransportStatus(),
2006
+ ...failure instanceof LocalScopeError ? { code: failure.code } : {},
264
2007
  error: primary.message,
265
2008
  ...primary.stack === void 0 ? {} : { stack: primary.stack },
266
2009
  ...primary.cause === void 0 ? {} : { cause: primary.cause instanceof Error ? primary.cause.message : String(primary.cause) }
267
2010
  });
268
- writeEntryRecord({
2011
+ if (options.mode === "surface" && expectedHostInstanceId !== void 0) process.stderr.write(`${handoffStartupFailureLine(failure)}\n`);
2012
+ else if (options.mode === "surface" && failure instanceof LocalScopeError && failure.code === "HOST_PROTOCOL_INCOMPATIBLE") process.stderr.write(`${surfaceStartupFailureLine(failure)}\n`);
2013
+ process.stdin.pause();
2014
+ if (cleanupErrors.length === 0 && !timedOut && !transportCleanupFailed) emit({
269
2015
  m4a0: "cleanup",
270
2016
  processRole: "client",
271
2017
  phase: "after-context",
272
2018
  pid: process.pid,
273
2019
  status: "completed"
274
2020
  });
2021
+ else {
2022
+ const cleanup = cleanupErrors[0] instanceof Error ? cleanupErrors[0] : new Error(String(cleanupErrors[0]));
2023
+ emit({
2024
+ m4a0: "cleanup-failure",
2025
+ processRole: "client",
2026
+ phase: "after-context",
2027
+ pid: process.pid,
2028
+ error: cleanup.message
2029
+ });
2030
+ }
275
2031
  process.exitCode = 1;
2032
+ if (timedOut || transportCleanupFailed) forceExitAfterCleanupFailure();
2033
+ } finally {
2034
+ process.stdin.pause();
2035
+ const reexecExitCode = await finishClientEntryShutdown({
2036
+ seat,
2037
+ ...reexecIntent === void 0 ? {} : { reexec: {
2038
+ intent: reexecIntent,
2039
+ teardownSucceeded: reexecTeardownSucceeded,
2040
+ cancelled: () => reexecCancelled
2041
+ } },
2042
+ emit,
2043
+ stderr: (line) => {
2044
+ process.stderr.write(`${line}\n`);
2045
+ },
2046
+ onChildSpawned: (child) => {
2047
+ reexecChild = child;
2048
+ }
2049
+ });
2050
+ if (reexecExitCode !== void 0) process.exitCode = reexecExitCode;
2051
+ try {
2052
+ recordSink?.close();
2053
+ } catch (error) {
2054
+ process.exitCode = 1;
2055
+ process.stderr.write(`local client entry: closing the surface record sink failed: ${error instanceof Error ? error.message : String(error)}\n`);
2056
+ }
276
2057
  }
277
2058
  }
278
2059
  /**
@@ -297,27 +2078,86 @@ async function stopLocalClient(handle, requestedCode, emit = writeEntryRecord) {
297
2078
  return requestedCode === 0 ? 1 : requestedCode;
298
2079
  }
299
2080
  }
2081
+ /** Qualification-only hold in the pre-startup assignment window. */
2082
+ async function waitForStartupHold(path, signal) {
2083
+ const deadline = Date.now() + 6e4;
2084
+ while (!existsSync(path)) {
2085
+ signal.throwIfAborted();
2086
+ if (Date.now() > deadline) throw new Error(`local client entry: the pre-startup barrier was not released: ${path}`);
2087
+ await new Promise((resolve) => setTimeout(resolve, 20));
2088
+ }
2089
+ signal.throwIfAborted();
2090
+ }
2091
+ /**
2092
+ * The human-facing surface line for one startup failure. The live-Host
2093
+ * protocol/DSH refusal gets a dedicated, actionable line that names the code,
2094
+ * keeps the old Host untouched, requires an explicit owner-verified OS stop
2095
+ * and says that automatic in-memory migration is unsupported. It never
2096
+ * includes the registry PID, the launch URL/token or a private profile path.
2097
+ * Every other startup failure keeps the existing diagnostic.
2098
+ */
2099
+ function surfaceStartupFailureLine(error) {
2100
+ 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.";
2101
+ return `split client surface: ${error instanceof Error ? error.message : String(error)}`;
2102
+ }
2103
+ /**
2104
+ * The human-facing line for ONE replacement-Client handoff failure. It names
2105
+ * the classified reason (expected Host absent/replaced/protocol, invalid
2106
+ * replacement package, or Session history open) and says how to recover
2107
+ * manually. Only fixed entry-owned messages are surfaced: an arbitrary
2108
+ * startup/spawn error may carry a private path or PID and is replaced with a
2109
+ * generic reason. No Cookie/token/launch URL ever enters this line.
2110
+ */
2111
+ function handoffStartupFailureLine(error) {
2112
+ let reason;
2113
+ if (error instanceof LocalScopeError) {
2114
+ if (error.code === "HOST_HANDOFF_UNAVAILABLE") reason = "the expected Host is no longer available";
2115
+ else if (error.code === "HOST_IDENTITY_MISMATCH") reason = "the live local Host is not the expected instance";
2116
+ else if (error.code === "HOST_PROTOCOL_INCOMPATIBLE") reason = "the expected Host uses a different local protocol or DSH runtime";
2117
+ else reason = "the expected Host could not be authenticated";
2118
+ } 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);
2119
+ else reason = "the replacement Client could not restore the expected Host and Session";
2120
+ return `Client handoff failed: ${reason}. The Host was not stopped or replaced. Start a compatible Client manually to continue.`;
2121
+ }
2122
+ /**
2123
+ * Read the internal Client mode. Absent/empty keeps the frozen B1
2124
+ * `qualification` contract; `surface` is the internal real-terminal mode. Any
2125
+ * other value fails closed (never a silent default).
2126
+ */
2127
+ function clientModeFromEnvironment() {
2128
+ const raw = process.env.SPLIT_PROCESS_CLIENT_MODE;
2129
+ if (raw === void 0 || raw === "") return "qualification";
2130
+ if (raw === "qualification" || raw === "surface" || raw === "peer") return raw;
2131
+ throw new Error(`local client entry: invalid SPLIT_PROCESS_CLIENT_MODE ${JSON.stringify(raw)}; expected "qualification", "surface" or "peer"`);
2132
+ }
300
2133
  /** Read the launcher environment; a missing anchor is a hard startup failure. */
301
2134
  function optionsFromEnvironment() {
302
2135
  const dshAnchor = process.env.SPLIT_PROCESS_DSH_ANCHOR;
303
2136
  if (dshAnchor === void 0 || dshAnchor === "") throw new Error("local client entry: SPLIT_PROCESS_DSH_ANCHOR must name the installed @deepseek-ai/dsh/package.json");
304
2137
  return {
305
2138
  dshAnchor,
306
- profile: process.env.SPLIT_PROCESS_PROFILE ?? "pi-tui"
2139
+ profile: process.env.SPLIT_PROCESS_PROFILE ?? "pi-tui",
2140
+ mode: clientModeFromEnvironment()
307
2141
  };
308
2142
  }
309
2143
  if (import.meta.main) try {
310
2144
  await runLocalClientEntry(optionsFromEnvironment());
311
2145
  } catch (error) {
312
- writeEntryRecord({
2146
+ const record = {
313
2147
  m4a0: "failure",
314
2148
  processRole: "client",
315
2149
  phase: "startup",
316
2150
  pid: process.pid,
2151
+ ...error instanceof LocalScopeError ? { code: error.code } : {},
317
2152
  error: error instanceof Error ? error.message : String(error),
318
2153
  ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
319
- });
2154
+ };
2155
+ if (process.env.SPLIT_PROCESS_CLIENT_MODE === "surface") {
2156
+ const handoff = process.env.SPLIT_PROCESS_CLIENT_EXPECTED_INSTANCE_ID;
2157
+ const line = handoff === void 0 || handoff === "" ? surfaceStartupFailureLine(error) : handoffStartupFailureLine(error);
2158
+ process.stderr.write(`${line}\n`);
2159
+ } else writeEntryRecord(record);
320
2160
  process.exit(1);
321
2161
  }
322
2162
  //#endregion
323
- export { runLocalClientEntry, stopLocalClient };
2163
+ export { ClientReexecRefusal, INTERACTION_STARTUP_GATE, assertHandoffRestored, assertHandoffSignalExclusivity, assertInteractionStartupReady, createClientReexecChildEnvironment, createClientReexecRequestHandler, createInteractionStartupGate, expectedHostInstanceFromEnvironment, finishClientEntryShutdown, handoffStartupFailureLine, inspectClientReexecTarget, prepareClientReexec, resolveProfileInstalledClientTarget, routeReexecTermination, runLocalClientEntry, stopLocalClient, surfaceStartupFailureLine };