@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +33 -0
  2. package/README.en.md +103 -814
  3. package/README.md +102 -711
  4. package/cordis.patch.yml +186 -0
  5. package/dist/acp-preferences.d.mts +29 -0
  6. package/dist/acp-preferences.mjs +15 -0
  7. package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
  8. package/dist/builtins.mjs +3 -3
  9. package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
  10. package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
  11. package/dist/command-trust-DChWUamk.mjs +406 -0
  12. package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
  13. package/dist/daemon-launcher.d.mts +159 -0
  14. package/dist/daemon-launcher.mjs +2 -0
  15. package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
  16. package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
  17. package/dist/entry-control-DjNsE3I0.mjs +190 -0
  18. package/dist/extension/advanced.d.mts +1 -1
  19. package/dist/extension/unstable.d.mts +1 -1
  20. package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
  21. package/dist/extension-config.d.mts +29 -0
  22. package/dist/extension-config.mjs +22 -0
  23. package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
  24. package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
  25. package/dist/extensions.d.mts +2 -2
  26. package/dist/extensions.mjs +1 -1
  27. package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
  28. package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
  29. package/dist/host-runtime.d.mts +11 -5
  30. package/dist/host-runtime.mjs +4171 -920
  31. package/dist/index.d.mts +86 -174
  32. package/dist/index.mjs +38087 -9967
  33. package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
  34. package/dist/local-client.mjs +1158 -59
  35. package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
  36. package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
  37. package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
  38. package/dist/local-discovery-egN4_gsQ.mjs +2 -0
  39. package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
  40. package/dist/local-host.mjs +812 -89
  41. package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
  42. package/dist/local-scope-DamiMqPd.mjs +1340 -0
  43. package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
  44. package/dist/local-web-control-DMrjwCkl.mjs +454 -0
  45. package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
  46. package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  47. package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  48. package/dist/open-CmOBxSjN.mjs +63 -0
  49. package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
  50. package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
  51. package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
  52. package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
  53. package/dist/preferences.d.mts +17 -0
  54. package/dist/preferences.mjs +20 -0
  55. package/dist/preset-BcWqOtY7.mjs +46 -0
  56. package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
  57. package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
  58. package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
  59. package/dist/prompt-sections-DXmjB58H.mjs +634 -0
  60. package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
  61. package/dist/row-id-DPbyt9Nn.mjs +24 -0
  62. package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
  63. package/dist/schema-BTGYn8_X.d.mts +54 -0
  64. package/dist/schema-qE_P09zJ.mjs +124 -0
  65. package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
  66. package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
  67. package/dist/startup-CarQxWwi.d.mts +213 -0
  68. package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
  69. package/dist/startup.d.mts +2 -99
  70. package/dist/startup.mjs +2 -2
  71. package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
  72. package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
  73. package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
  74. package/dist/version-B9yC7bBk.mjs +83 -0
  75. package/dist/visual-tools.d.mts +1 -1
  76. package/dist/visual-tools.mjs +1 -1
  77. package/dist/web-preferences.d.mts +1 -1
  78. package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
  79. package/generated/dsh-presets/cordis.patch.yml +4 -2
  80. package/generated/dsh-presets/ptc.patch.yml +4 -0
  81. package/generated/dsh-presets/standard.patch.yml +7 -0
  82. package/generated/web-access/cordis.patch.yml +239 -0
  83. package/package.json +217 -170
  84. package/dist/entry-control-DnduyDiw.mjs +0 -92
  85. package/dist/local-discovery-C9VMjc0K.mjs +0 -759
  86. package/dist/local-discovery-CDaQHA_R.mjs +0 -2
  87. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
  88. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
  89. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
  90. package/dist/version-a-eF-QER.mjs +0 -80
@@ -1,5 +1,6 @@
1
- import { a as connectForCookie, b as readProcessStarttime, l as readLaunchMaterial, m as LocalScopeError, u as readLocalRecord } from "./local-discovery-C9VMjc0K.mjs";
1
+ import { n as LocalScopeError } from "./local-scope-DamiMqPd.mjs";
2
2
  import { i as runDetached } from "./tasks-D_z5Yjjr.mjs";
3
+ import { f as readLaunchMaterial, m as sameLocalInstanceRecord, p as readLocalRecord, r as assertRecordedHostKernelIdentityCurrent, s as connectForCookie } from "./local-discovery-DOSsCh9q.mjs";
3
4
  import { t as mergeCause } from "./dispose-cause-CNFuUnjR.mjs";
4
5
  import { createRequire } from "node:module";
5
6
  import { realpathSync } from "node:fs";
@@ -25,6 +26,15 @@ const NODE_CLIENT_MODULES = [
25
26
  ];
26
27
  /** Bound on the first real Gateway generation after HTTP authentication. */
27
28
  const GENERATION_READY_TIMEOUT_MS = 3e4;
29
+ /** Bounded wait for the re-admitted generation after an expired operator. */
30
+ const OPERATOR_RECOVERY_TIMEOUT_MS = 3e4;
31
+ /** Whether one wire frame carries the settings-document invalidation event. */
32
+ function isSettingsDocumentUpdatedFrame(event) {
33
+ const data = event.data;
34
+ if (typeof data === "string") return data.includes("settings/document-updated");
35
+ if (data instanceof Uint8Array) return Buffer.from(data).toString("utf8").includes("settings/document-updated");
36
+ return false;
37
+ }
28
38
  /** Resolve and import the three Node Client halves from the installed DSH anchor. */
29
39
  async function loadLocalTransportModules(dshAnchor) {
30
40
  const requireFromDsh = createRequire(realpathSync(dshAnchor));
@@ -48,14 +58,32 @@ async function loadLocalTransportModules(dshAnchor) {
48
58
  };
49
59
  }
50
60
  /** Resolve a relative logical route and require the authenticated Host origin. */
51
- function cookieFetch(origin, currentCookie, includeCookie) {
61
+ function cookieFetch(origin, currentCookie, includeCookie, qualificationPromptAckDropped) {
52
62
  const dropPromptAck = process.env.SPLIT_PROCESS_CLIENT_DROP_PROMPT_ACK === "1";
53
63
  let promptAckDropped = false;
64
+ const dropModelAck = process.env.SPLIT_PROCESS_CLIENT_DROP_MODEL_ACK === "1";
65
+ let modelAckDropped = false;
66
+ const expireOperatorOnce = process.env.SPLIT_PROCESS_CLIENT_EXPIRE_OPERATOR_ONCE;
67
+ /**
68
+ * Qualification-only delay before the forged operator expires: a real TTL
69
+ * can only elapse while the Client is already live, so the injected 401 must
70
+ * land mid-session instead of inside the startup request chain.
71
+ */
72
+ const expireOperatorAfterMs = Number(process.env.SPLIT_PROCESS_CLIENT_EXPIRE_OPERATOR_AFTER_MS ?? "0");
73
+ const installedAt = Date.now();
74
+ let expiredOperatorInjected = false;
54
75
  return async (input, init = {}) => {
55
76
  const url = new URL(typeof input === "string" ? input : input.href, `${origin}/`);
56
77
  if (url.origin !== origin) throw new Error(`local transport: refusing a cross-origin request to ${url.origin}`);
57
78
  const headers = new Headers(init.headers);
58
79
  if (includeCookie) headers.set("cookie", currentCookie());
80
+ const forgeThis = expireOperatorOnce !== void 0 && Date.now() - installedAt >= expireOperatorAfterMs && (expireOperatorOnce === "1" || url.pathname.includes(expireOperatorOnce));
81
+ if (!expiredOperatorInjected && forgeThis && typeof init.body === "string" && !url.pathname.includes("$events/")) {
82
+ expiredOperatorInjected = true;
83
+ const pair = currentCookie();
84
+ const separator = pair.indexOf("=");
85
+ headers.set("cookie", `${separator > 0 ? pair.slice(0, separator) : "dsh-auth"}=qualification-forged-operator`);
86
+ }
59
87
  const request = {
60
88
  ...init,
61
89
  headers,
@@ -72,9 +100,15 @@ function cookieFetch(origin, currentCookie, includeCookie) {
72
100
  if (method === "session/prompt") {
73
101
  promptAckDropped = true;
74
102
  await (await fetch(url, request)).body?.cancel();
103
+ qualificationPromptAckDropped?.();
75
104
  throw new Error("local transport: qualification dropped the session/prompt ACK after Host receipt");
76
105
  }
77
106
  }
107
+ if (dropModelAck && !modelAckDropped && typeof init.body === "string" && init.body.includes("piTuiDefaultModel/saveSelection")) {
108
+ modelAckDropped = true;
109
+ await (await fetch(url, request)).body?.cancel();
110
+ throw new Error("local transport: qualification dropped the piTuiDefaultModel/saveSelection ACK after Host receipt");
111
+ }
78
112
  return await fetch(url, request);
79
113
  };
80
114
  }
@@ -107,6 +141,7 @@ function lazyWebSocket(open, adopt, diag, release) {
107
141
  notify("close", {});
108
142
  release();
109
143
  };
144
+ const suppressSettingsEvent = process.env.SPLIT_PROCESS_CLIENT_SUPPRESS_SETTINGS_EVENT === "1";
110
145
  const start = async () => {
111
146
  try {
112
147
  const socket = await open();
@@ -125,6 +160,7 @@ function lazyWebSocket(open, adopt, diag, release) {
125
160
  notify("error", event);
126
161
  });
127
162
  socket.addEventListener("message", (event) => {
163
+ if (suppressSettingsEvent && isSettingsDocumentUpdatedFrame(event)) return;
128
164
  notify("message", event);
129
165
  });
130
166
  socket.addEventListener("close", (event) => {
@@ -198,6 +234,174 @@ function cookieWebSocketFactory(origin, currentCookie, refreshCookie, sockets, w
198
234
  };
199
235
  }
200
236
  /**
237
+ * Wait until the official Connection publishes a generation OTHER than the one
238
+ * an expired operator belonged to. The recovery below must never retry a
239
+ * request before the re-admitted generation exists: the retried request has to
240
+ * arrive as the operator that owns the NEW stream, and the old generation must
241
+ * already be unable to commit further event results.
242
+ */
243
+ function waitForReplacementGeneration(connection, previousId, signal, timeoutMs) {
244
+ return new Promise((resolveWait, rejectWait) => {
245
+ let settled = false;
246
+ let unsubscribe;
247
+ const current = () => connection.generation.getSnapshot();
248
+ const cleanup = () => {
249
+ settled = true;
250
+ unsubscribe?.();
251
+ clearTimeout(timer);
252
+ signal?.removeEventListener("abort", onAbort);
253
+ };
254
+ const finish = (error) => {
255
+ if (settled) return;
256
+ cleanup();
257
+ if (error === void 0) resolveWait();
258
+ else rejectWait(error);
259
+ };
260
+ const onAbort = () => finish(signal?.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("local transport: operator recovery aborted"));
261
+ const timer = setTimeout(() => finish(new LocalScopeError("HOST_UNRESPONSIVE", `local transport: no replacement Connection generation within ${String(timeoutMs / 1e3)}s`)), timeoutMs);
262
+ if (signal?.aborted === true) {
263
+ onAbort();
264
+ return;
265
+ }
266
+ unsubscribe = connection.generation.subscribe(() => {
267
+ const generation = current();
268
+ if (generation !== void 0 && generation.id !== previousId) finish();
269
+ });
270
+ signal?.addEventListener("abort", onAbort, { once: true });
271
+ const afterSubscribe = current();
272
+ if (afterSubscribe !== void 0 && afterSubscribe.id !== previousId) finish();
273
+ });
274
+ }
275
+ /**
276
+ * Await one shared operation but let THIS caller stop waiting when its own
277
+ * request is cancelled. The shared operation itself keeps running for the other
278
+ * waiters; only this caller's await is released.
279
+ */
280
+ function settleWithOwnSignal(operation, signal) {
281
+ if (signal === void 0) return operation;
282
+ return new Promise((resolveWait, rejectWait) => {
283
+ if (signal.aborted) {
284
+ operation.catch(() => {});
285
+ rejectWait(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("local transport: request aborted"));
286
+ return;
287
+ }
288
+ const onAbort = () => {
289
+ operation.catch(() => {});
290
+ rejectWait(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("local transport: request aborted"));
291
+ };
292
+ signal.addEventListener("abort", onAbort, { once: true });
293
+ operation.then(() => {
294
+ signal.removeEventListener("abort", onAbort);
295
+ resolveWait();
296
+ }, (error) => {
297
+ signal.removeEventListener("abort", onAbort);
298
+ rejectWait(error);
299
+ });
300
+ });
301
+ }
302
+ /**
303
+ * Whether this request signal is aborted right now. A function call keeps the
304
+ * check honest across an `await`: narrowing a property read would make the
305
+ * compiler treat a later abort as unreachable.
306
+ */
307
+ function isSignalAborted(signal) {
308
+ return signal?.aborted === true;
309
+ }
310
+ /** The truthful cancellation reason of one request signal. */
311
+ function abortReasonOf(signal, fallback) {
312
+ if (signal?.reason instanceof Error) return signal.reason;
313
+ if (fallback instanceof Error) return fallback;
314
+ return /* @__PURE__ */ new Error("local transport: request aborted");
315
+ }
316
+ /**
317
+ * The ONE auth-recovery wrapper for the official unary carrier and every
318
+ * borrowed authenticated route.
319
+ *
320
+ * Two DIFFERENT questions are kept apart:
321
+ *
322
+ * 1. Must the connection be rebuilt? YES for every 401 except a forwarded event
323
+ * RESULT, whose payload belongs to the stream and Peer that received the
324
+ * invocation — there the Gateway's own generation abort + Host re-delivery
325
+ * is the only correct recovery. A dead operator affects EVERY route, so a
326
+ * non-replayable request (a stream/FormData upload) still triggers the
327
+ * rebuild even though it cannot be re-sent; otherwise that upload would
328
+ * leave every later request on the expired operator.
329
+ * 2. May THIS payload be re-sent? Only a replayable body, only once, and only
330
+ * after the re-admitted generation is ready. A 401 is rejected before Host
331
+ * dispatch, so this retry cannot duplicate a write.
332
+ *
333
+ * A caller cancellation is ALWAYS reported as cancellation, never as an HTTP
334
+ * auth failure: the official rpc caller throws on `!response.ok` before it
335
+ * re-checks the abort signal, so a 401 returned to a cancelled caller would
336
+ * surface as an authentication error. A genuine re-admit failure still returns
337
+ * the original 401.
338
+ */
339
+ async function sendWithOperatorRecovery(deps, input, init) {
340
+ const signal = init?.signal ?? void 0;
341
+ const response = await deps.send(input, init);
342
+ if (response.status !== 401) return response;
343
+ if (isSignalAborted(signal)) throw abortReasonOf(signal, void 0);
344
+ const { rebuild, retry } = operatorRecoveryDecision(input, init, deps.origin);
345
+ if (!rebuild) return response;
346
+ try {
347
+ await settleWithOwnSignal(deps.recoverOperator(signal), signal);
348
+ } catch (error) {
349
+ if (isSignalAborted(signal)) throw abortReasonOf(signal, error);
350
+ return response;
351
+ }
352
+ if (isSignalAborted(signal)) throw abortReasonOf(signal, void 0);
353
+ if (!retry) return response;
354
+ return await deps.send(input, init);
355
+ }
356
+ /**
357
+ * Decide what one 401 requires. Rebuilding and re-sending are separate facts:
358
+ * a forwarded event RESULT is owned by the Gateway's generation abort + Host
359
+ * re-delivery (neither), while a non-replayable upload must still rebuild the
360
+ * connection (otherwise every later request keeps using the expired operator)
361
+ * even though the upload itself cannot be re-sent.
362
+ */
363
+ function operatorRecoveryDecision(input, init, origin) {
364
+ if (new URL(typeof input === "string" ? input : input.href, `${origin}/`).pathname.includes("$events/result")) return {
365
+ rebuild: false,
366
+ retry: false
367
+ };
368
+ if (init?.signal?.aborted === true) return {
369
+ rebuild: false,
370
+ retry: false
371
+ };
372
+ return {
373
+ rebuild: true,
374
+ retry: init?.body === void 0 || typeof init.body === "string"
375
+ };
376
+ }
377
+ /**
378
+ * The ONE production recovery for an expired/invalidated operator Cookie.
379
+ *
380
+ * The official Connection is told to replace its attempt; that closes the
381
+ * current mux socket (its generation's tasks stop committing) BEFORE the socket
382
+ * factory mints the replacement operator for the RE-open. The caller then waits
383
+ * for the replacement generation so a retried request can only arrive on the new
384
+ * operator that owns the new stream. A request whose invocation was already
385
+ * dispatched to the old stream (`$events/result`) is NEVER retried: its clientId
386
+ * belongs to the old Peer and the official generation abort + Host re-delivery
387
+ * is the only correct recovery.
388
+ */
389
+ function createOperatorRecovery(current, lifetime) {
390
+ let inflight;
391
+ return async (signal) => {
392
+ inflight ??= (async () => {
393
+ const connection = current();
394
+ if (connection === void 0) throw new LocalScopeError("HOST_UNRESPONSIVE", "local transport: no Connection to re-admit");
395
+ const previousId = connection.generation.getSnapshot()?.id;
396
+ connection.reconnect();
397
+ await waitForReplacementGeneration(connection, previousId, lifetime, OPERATOR_RECOVERY_TIMEOUT_MS);
398
+ })().finally(() => {
399
+ inflight = void 0;
400
+ });
401
+ await inflight;
402
+ };
403
+ }
404
+ /**
201
405
  * Wait for the first real `$events` generation, bounded so a Client without a
202
406
  * serving Host fails instead of spinning forever. Generation identity comes
203
407
  * only from the official Connection handle.
@@ -254,24 +458,16 @@ function waitForFirstGeneration(connection, signal) {
254
458
  function assertIdentityStillCurrent(scope, expected) {
255
459
  const current = readLocalRecord(scope);
256
460
  if (current === void 0) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local transport: the Host registry disappeared before connected");
257
- for (const key of [
258
- "scopeId",
259
- "profileRealpath",
260
- "instanceId",
261
- "hostPid",
262
- "hostStarttime",
263
- "origin",
264
- "protocol",
265
- "bundleVersion",
266
- "dshVersion",
267
- "buildId"
268
- ]) if (current[key] !== expected[key]) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local transport: the Host identity changed at ${key} before connected`);
269
- const liveStarttime = readProcessStarttime(expected.hostPid);
270
- if (liveStarttime === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local transport: the Host process starttime is unavailable");
271
- if (liveStarttime !== expected.hostStarttime) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local transport: the Host PID is no longer the authenticated process");
461
+ if (!sameLocalInstanceRecord(current, expected)) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local transport: the Host identity changed before connected");
462
+ assertRecordedHostKernelIdentityCurrent(expected);
272
463
  }
273
- /** Wait for a set of sockets to close, bounded so disposal cannot park forever. */
274
- async function closeRemainingSockets(sockets) {
464
+ /**
465
+ * Wait for a set of sockets to close, bounded so disposal cannot park forever.
466
+ * The timeout is a HANG PROTECTION, not a second socket owner: the losing timer
467
+ * is cancelled on every path so a normally closed socket leaves no referenced
468
+ * Node handle behind disposal.
469
+ */
470
+ async function closeRemainingSockets(sockets, diag, timeoutMs = 2e3) {
275
471
  if (sockets.size === 0) return;
276
472
  const closures = [];
277
473
  for (const socket of sockets) {
@@ -282,7 +478,47 @@ async function closeRemainingSockets(sockets) {
282
478
  }));
283
479
  }
284
480
  if (closures.length === 0) return;
285
- await Promise.race([Promise.all(closures), new Promise((resolve) => setTimeout(resolve, 2e3))]);
481
+ const startedAt = performance.now();
482
+ let timer;
483
+ const deadline = new Promise((resolve) => {
484
+ timer = setTimeout(resolve, timeoutMs);
485
+ });
486
+ try {
487
+ await Promise.race([Promise.all(closures), deadline]);
488
+ } finally {
489
+ if (timer !== void 0) clearTimeout(timer);
490
+ }
491
+ diag.debug("local transport: remaining sockets settled", {
492
+ sockets: sockets.size,
493
+ durationMs: Math.round((performance.now() - startedAt) * 10) / 10
494
+ });
495
+ }
496
+ /**
497
+ * Dispose ONE official Fiber under its ORIGINAL hang budget. This is a fault
498
+ * bound, never a second completion path: the timer is cancelled when the Fiber
499
+ * settles or rejects so a normal disposal cannot leave a referenced 5s handle
500
+ * keeping the Client process alive.
501
+ */
502
+ async function disposeFiberWithinDeadline(fiber, label, diag, timeoutMs = 5e3) {
503
+ const startedAt = performance.now();
504
+ let timedOut = false;
505
+ let timer;
506
+ const deadline = new Promise((_, reject) => {
507
+ timer = setTimeout(() => {
508
+ timedOut = true;
509
+ reject(/* @__PURE__ */ new Error(`local transport: ${label} disposal timed out`));
510
+ }, timeoutMs);
511
+ });
512
+ try {
513
+ await Promise.race([fiber.dispose(), deadline]);
514
+ } finally {
515
+ if (timer !== void 0) clearTimeout(timer);
516
+ diag.debug("local transport: fiber disposal settled", {
517
+ fiber: label,
518
+ timedOut,
519
+ durationMs: Math.round((performance.now() - startedAt) * 10) / 10
520
+ });
521
+ }
286
522
  }
287
523
  /**
288
524
  * Install the official three-layer Client transport on the caller's Client
@@ -292,9 +528,17 @@ async function closeRemainingSockets(sockets) {
292
528
  */
293
529
  async function installLocalTransport(context, options) {
294
530
  const { dshAnchor, host, scope, diag } = options;
295
- const modules = await loadLocalTransportModules(dshAnchor);
531
+ const modules = options.modulesOverride ?? await loadLocalTransportModules(dshAnchor);
296
532
  const origin = host.record.origin;
297
533
  let disposed = false;
534
+ /**
535
+ * The ONE in-flight/completed disposal. Every caller of `dispose()` — the
536
+ * exit root's early release, the surface handle teardown, the startup
537
+ * failure unwind — awaits the SAME settlement and observes the SAME failure:
538
+ * a later call must never return success over an unwind that already failed
539
+ * (the release's `cleanupFailed` would otherwise be silently lost).
540
+ */
541
+ let disposalPromise;
298
542
  const disposal = new AbortController();
299
543
  let fatalReported = false;
300
544
  let live = false;
@@ -318,7 +562,7 @@ async function installLocalTransport(context, options) {
318
562
  rejectFatal?.(error);
319
563
  };
320
564
  const isTerminalRefreshFailure = (error) => !(error instanceof LocalScopeError && error.code === "HOST_UNRESPONSIVE");
321
- const refreshCookie = async () => {
565
+ const refreshCookie = async (signal) => {
322
566
  if (process.env.SPLIT_PROCESS_CLIENT_FORCE_REFRESH_UNRESPONSIVE_ONCE === "1" && !forcedRetryableRefresh) {
323
567
  forcedRetryableRefresh = true;
324
568
  throw new LocalScopeError("HOST_UNRESPONSIVE", "local transport: qualification forced retryable refresh failure");
@@ -326,7 +570,7 @@ async function installLocalTransport(context, options) {
326
570
  if (refreshPromise === void 0) refreshPromise = (async () => {
327
571
  try {
328
572
  const launch = readLaunchMaterial(scope, host.identity);
329
- cookie = await connectForCookie(host.identity, launch);
573
+ cookie = await connectForCookie(host.identity, launch, signal);
330
574
  } catch (error) {
331
575
  if (isTerminalRefreshFailure(error)) reportFatal(error);
332
576
  throw error;
@@ -339,10 +583,14 @@ async function installLocalTransport(context, options) {
339
583
  const sockets = /* @__PURE__ */ new Set();
340
584
  const wrappers = /* @__PURE__ */ new Set();
341
585
  const includeCookie = process.env.SPLIT_PROCESS_CLIENT_OMIT_COOKIE !== "1";
342
- const fetchAuthenticated = cookieFetch(origin, () => cookie, includeCookie);
586
+ const fetchAuthenticated = cookieFetch(origin, () => cookie, includeCookie, options.qualificationPromptAckDropped);
587
+ const fetchOfficial = cookieFetch(origin, () => cookie, includeCookie, options.qualificationPromptAckDropped);
588
+ /** Borrowed-route send; re-assigned below once the Connection exists. */
589
+ let sendAuthenticated = fetchAuthenticated;
343
590
  let typertFiber;
344
591
  let connectionFiber;
345
592
  let gatewayFiber;
593
+ let connection;
346
594
  const unwind = async () => {
347
595
  disposed = true;
348
596
  disposal.abort(/* @__PURE__ */ new Error("local transport: disposed"));
@@ -353,7 +601,7 @@ async function installLocalTransport(context, options) {
353
601
  errors.push(error);
354
602
  }
355
603
  try {
356
- await closeRemainingSockets(sockets);
604
+ await closeRemainingSockets(sockets, diag);
357
605
  } catch (error) {
358
606
  errors.push(error);
359
607
  }
@@ -364,9 +612,7 @@ async function installLocalTransport(context, options) {
364
612
  ]) {
365
613
  if (fiber === void 0) continue;
366
614
  try {
367
- await Promise.race([fiber.dispose(), new Promise((_, reject) => {
368
- setTimeout(() => reject(/* @__PURE__ */ new Error(`local transport: ${label} disposal timed out`)), 5e3);
369
- })]);
615
+ await disposeFiberWithinDeadline(fiber, label, diag);
370
616
  } catch (error) {
371
617
  errors.push(error);
372
618
  }
@@ -379,11 +625,36 @@ async function installLocalTransport(context, options) {
379
625
  await typertFiber;
380
626
  options.signal?.throwIfAborted();
381
627
  const createWebSocket = cookieWebSocketFactory(origin, () => cookie, refreshCookie, sockets, wrappers, diag, includeCookie);
628
+ const recoverOperator = createOperatorRecovery(() => connection, disposal.signal);
629
+ /**
630
+ * The ONE auth-recovery wrapper for the official unary carrier and every
631
+ * borrowed authenticated route. Two DIFFERENT questions are kept apart:
632
+ *
633
+ * 1. Must the connection be rebuilt? YES for every 401 except a forwarded
634
+ * event RESULT, whose payload belongs to the stream and Peer that
635
+ * received the invocation — there the Gateway's own generation abort +
636
+ * Host re-delivery is the only correct recovery. A dead operator affects
637
+ * EVERY route, so a non-replayable request (a stream/FormData upload)
638
+ * still triggers the rebuild even though it cannot be re-sent; otherwise
639
+ * that upload would leave every later request on the expired operator.
640
+ * 2. May THIS payload be re-sent? Only a replayable body, only once, and
641
+ * only after the re-admitted generation is ready. A 401 is rejected
642
+ * before Host dispatch, so this retry cannot duplicate a write.
643
+ */
644
+ sendAuthenticated = (input, init) => sendWithOperatorRecovery({
645
+ send: fetchAuthenticated,
646
+ recoverOperator,
647
+ origin
648
+ }, input, init);
382
649
  connectionFiber = context.plugin((connectionContext) => {
383
650
  modules.connection.installConnection(connectionContext, {
384
651
  interactions: "answer",
385
652
  transport: {
386
- fetch: cookieFetch(origin, () => cookie, includeCookie),
653
+ fetch: (input, init) => sendWithOperatorRecovery({
654
+ send: fetchOfficial,
655
+ recoverOperator,
656
+ origin
657
+ }, input, init),
387
658
  createWebSocket: (url) => {
388
659
  const socket = createWebSocket(url);
389
660
  options.qualificationWebSocketObserver?.(url, socket);
@@ -400,6 +671,7 @@ async function installLocalTransport(context, options) {
400
671
  options.signal?.throwIfAborted();
401
672
  const installed = context.get("connection");
402
673
  if (installed === void 0) throw new Error("local transport: the official Connection service did not install");
674
+ connection = installed;
403
675
  if (process.env.SPLIT_PROCESS_CLIENT_FORCE_STARTUP_FATAL === "1") reportFatal(new LocalScopeError("HOST_IDENTITY_MISMATCH", "local transport: qualification forced startup identity failure"));
404
676
  let readyPromise;
405
677
  const handle = {
@@ -450,23 +722,26 @@ async function installLocalTransport(context, options) {
450
722
  if (disposed || !live) throw new Error("local transport: the authenticated fetch is unavailable before connection or after disposal");
451
723
  if (fatalError !== void 0) throw fatalError;
452
724
  if (installed.generation.getSnapshot() === void 0) throw new LocalScopeError("HOST_UNRESPONSIVE", "local transport: no current authenticated Host generation");
453
- await refreshCookie();
454
725
  if (disposed) throw new Error("local transport: the authenticated fetch is unavailable after disposal");
455
726
  if (fatalError !== void 0) throw fatalError;
456
- return await fetchAuthenticated(input, init);
727
+ return await sendAuthenticated(input, init);
457
728
  },
458
729
  dropWebSocketsForQualification() {
459
730
  for (const socket of [...sockets]) if (socket.readyState < WebSocket.CLOSED) socket.terminate();
460
731
  },
461
732
  async dispose() {
462
- if (disposed) return;
733
+ if (disposalPromise !== void 0) return await disposalPromise;
463
734
  disposed = true;
464
- const errors = await unwind();
465
- if (errors.length === 0) return;
466
- const primary = errors[0] instanceof Error ? errors[0] : new Error(String(errors[0]));
467
- for (const secondary of errors.slice(1)) mergeCause(primary, secondary);
468
- primary.cleanupFailed = true;
469
- throw primary;
735
+ disposalPromise = (async () => {
736
+ const errors = await unwind();
737
+ if (errors.length === 0) return;
738
+ const primary = errors[0] instanceof Error ? errors[0] : new Error(String(errors[0]));
739
+ for (const secondary of errors.slice(1)) mergeCause(primary, secondary);
740
+ primary.cleanupFailed = true;
741
+ throw primary;
742
+ })();
743
+ disposalPromise.catch(() => {});
744
+ return await disposalPromise;
470
745
  }
471
746
  };
472
747
  return handle;