@xmoon76/dsh-pi-tui 0.5.2-rc.1 → 0.5.3

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.
@@ -1,7 +1,7 @@
1
- import { n as TUI_STARTUP_SERVICE } from "./startup-CWQl0-0n.mjs";
1
+ import { n as TUI_STARTUP_SERVICE } from "./startup-D5Xu8diR.mjs";
2
2
  import { n as isCancellation, o as safeErrorMessage, t as cancellationError } from "./tasks-D_z5Yjjr.mjs";
3
- import { B as SupersededReadError, D as REMOTE_IMPLEMENTED_CAPABILITIES, I as credentialOptionsFor, R as providerOptionsFor, S as classifySubagentPromptSettlement, T as isRemoteBusinessRefusalCode, a as createTerminalProgressInterval, at as resolveTrustedFooterCommand, b as detachedSessionStatus, c as detachLog, ct as resolveUserLayerFooterMode, d as pluginInstallRequestId, f as listPiTuiHostFileReferences, i as PI_TUI_TERMINAL_PROGRESS_WATCH, k as clientOwnerOf, l as detachPhase, m as hostPathQueryEnvironment, n as createRemoteTerminalProgressSource, o as detachChange, ot as resolveUserCommandItemActivationIds, p as DirectHostDiscoveryDriver, r as PI_TUI_TERMINAL_PROGRESS_NAMESPACE, rt as parseFooterCustomItems, s as detachInspection, st as resolveUserCommandItemFallbackActivationIds, u as detachPluginManagerSnapshot, ut as contextPressureOccupancy, v as QuestionAnswerError, w as GATEWAY_PRE_INVOCATION_CODES, x as detachedTurnOutline } from "./terminal-progress-source-Dpwz3csm.mjs";
4
- import { a as PI_TUI_EXTENSIONS_SERVICE, n as extensions_exports } from "./extensions-VuoIE_Jc.mjs";
3
+ import { A as clientOwnerOf, C as classifySubagentPromptSettlement, E as isRemoteBusinessRefusalCode, L as credentialOptionsFor, O as REMOTE_IMPLEMENTED_CAPABILITIES, S as detachedTurnOutline, T as GATEWAY_PRE_INVOCATION_CODES, V as SupersededReadError, a as PluginManagerStaleResultError, c as detachInspection, ct as resolveUserCommandItemFallbackActivationIds, d as detachPluginManagerSnapshot, dt as contextPressureOccupancy, f as pluginInstallRequestId, h as hostPathQueryEnvironment, i as PI_TUI_TERMINAL_PROGRESS_WATCH, it as parseFooterCustomItems, l as detachLog, lt as resolveUserLayerFooterMode, m as DirectHostDiscoveryDriver, n as createRemoteTerminalProgressSource, o as createTerminalProgressInterval, ot as resolveTrustedFooterCommand, p as listPiTuiHostFileReferences, r as PI_TUI_TERMINAL_PROGRESS_NAMESPACE, s as detachChange, st as resolveUserCommandItemActivationIds, u as detachPhase, x as detachedSessionStatus, y as QuestionAnswerError, z as providerOptionsFor } from "./terminal-progress-source-BlmksrSD.mjs";
4
+ import { a as PI_TUI_EXTENSIONS_SERVICE, n as extensions_exports } from "./extensions-a-rxanjw.mjs";
5
5
  import { t as builtins_exports } from "./builtins.mjs";
6
6
  import { a as performance_host_exports } from "./performance-host-BJT6scGF.mjs";
7
7
  import { createRequire } from "node:module";
@@ -1124,6 +1124,7 @@ var RemoteConfigPort = class {
1124
1124
  permissions;
1125
1125
  presetDefault;
1126
1126
  subagentModelSelection;
1127
+ web;
1127
1128
  /** `undefined` while the `tui-app` namespace is absent from the mirror
1128
1129
  * (the port's documented absence contract). */
1129
1130
  get tuiSettings() {
@@ -1146,6 +1147,7 @@ var RemoteConfigPort = class {
1146
1147
  this.permissions = new RemotePermissionConfig(this.mirror, source.remote.commands);
1147
1148
  this.presetDefault = new RemotePresetDefaultConfig(this.mirror);
1148
1149
  this.subagentModelSelection = new RemoteSubagentModelSelectionConfig(this.mirror);
1150
+ this.web = new RemoteUnsupportedWebProviderConfig();
1149
1151
  }
1150
1152
  /** Commit one fresh mirror snapshot (or leave the last-known value). A
1151
1153
  * failure is RECORDED as well as thrown, so `readiness()` stays truthful
@@ -1185,6 +1187,39 @@ var RemoteConfigPort = class {
1185
1187
  this.credentialConfig.dispose();
1186
1188
  }
1187
1189
  };
1190
+ /**
1191
+ * The Remote backend's Web provider sub-domain: INTENTIONALLY unsupported in
1192
+ * S2. The wire carries no web-provider selection read (the `settings` mirror
1193
+ * exposes plugin forms for the CLIENT-owned surfaces only) and no write RPC for
1194
+ * a Host namespace, so the section is presented as unsupported on this backend
1195
+ * and every write fails closed instead of naming a Host settings namespace or
1196
+ * reporting a success it cannot observe. Remote web-provider support is owned
1197
+ * by a later stage (S3/S4) together with the Host generated-settings parity.
1198
+ */
1199
+ var RemoteUnsupportedWebProviderConfig = class {
1200
+ available() {
1201
+ return false;
1202
+ }
1203
+ async read() {}
1204
+ refuse() {
1205
+ throw new Error("web provider settings are not supported on this backend");
1206
+ }
1207
+ async setSearchProvider() {
1208
+ this.refuse();
1209
+ }
1210
+ async setFetchProvider() {
1211
+ this.refuse();
1212
+ }
1213
+ async setSearchApiCount() {
1214
+ this.refuse();
1215
+ }
1216
+ async setSendOriginalQuestion() {
1217
+ this.refuse();
1218
+ }
1219
+ async setSearchApiBaseURL() {
1220
+ this.refuse();
1221
+ }
1222
+ };
1188
1223
  //#endregion
1189
1224
  //#region src/runtime/remote/session-archive-remote.ts
1190
1225
  /** The official absolute export path (`dsh-session-log-export` routes). */
@@ -1385,7 +1420,8 @@ function createPiTuiHostFileReferenceRuntime(deps) {
1385
1420
  return await listPiTuiHostFileReferences(agent, query, signal, {
1386
1421
  official: deps.official(),
1387
1422
  driver,
1388
- environment
1423
+ environment,
1424
+ workingDirectory: deps.workingDirectory?.()
1389
1425
  });
1390
1426
  } };
1391
1427
  }
@@ -1405,7 +1441,10 @@ var PiTuiFileReferenceHostService = class extends TypertRemoteService {
1405
1441
  */
1406
1442
  constructor(ctx, deps) {
1407
1443
  super(ctx, PI_TUI_FILE_REFERENCES_NAMESPACE);
1408
- this.runtime = createPiTuiHostFileReferenceRuntime(deps);
1444
+ this.runtime = createPiTuiHostFileReferenceRuntime({
1445
+ ...deps,
1446
+ workingDirectory: () => ctx.get("workingDirectory")
1447
+ });
1409
1448
  }
1410
1449
  /**
1411
1450
  * The private Remote method (`piTuiFileReferences/list`, see
@@ -1714,6 +1753,7 @@ const HOST_PREREQUISITE_SERVICES = [
1714
1753
  "commands",
1715
1754
  "fileReferences",
1716
1755
  "fs",
1756
+ "workingDirectory",
1717
1757
  "llm",
1718
1758
  "sessions",
1719
1759
  "sessionProjections",
@@ -1749,19 +1789,29 @@ function mergeCause(failure, secondary) {
1749
1789
  function assertHostPrerequisites(hostContext) {
1750
1790
  for (const service of HOST_PREREQUISITE_SERVICES) if (hostContext.reflect.get(service) === void 0) throw new Error(`remote host runtime: the Host Context is missing the required "${service}" service`);
1751
1791
  }
1752
- /** Build the in-process carrier over the Host connection + gateway seams. */
1792
+ /** Build the in-process carrier over the Host connection + gateway seams.
1793
+ *
1794
+ * The carrier speaks for the Host Connection's OWN owner Peer
1795
+ * (`HostConnectionService.browserPeer`, created inside the service constructor
1796
+ * with `principal: { kind: 'owner' }` and disposed by the Connection plugin
1797
+ * fiber). The SAME reference is passed to the shared Fetch handler and to
1798
+ * `wireStream.open`, so one identity — and one lifetime — covers both the
1799
+ * unary and the streaming path; the carrier never creates, caches, or disposes
1800
+ * a Peer of its own. */
1753
1801
  function createInProcessCarrier(hostContext) {
1754
- const shared = hostContext.connection.createSharedFetchHandler("/api");
1802
+ const connection = hostContext.connection;
1803
+ const peer = connection.browserPeer;
1804
+ const shared = connection.createSharedFetchHandler("/api");
1755
1805
  const gateway = hostContext.typertGateway;
1756
1806
  return {
1757
1807
  ownsHost: true,
1758
1808
  fetch(input, init) {
1759
1809
  const request = input instanceof Request ? new Request(input, init) : new Request(new URL(String(input), IN_PROCESS_BASE_URL), init);
1760
- return shared.fetch(request);
1810
+ return shared.fetch(request, peer);
1761
1811
  },
1762
1812
  openStream(endpoint, payload, signal, uplink) {
1763
1813
  return (async function* () {
1764
- yield* await gateway.wireStream.open(endpoint, payload, uplink ?? emptyUplink(), void 0, signal);
1814
+ yield* await gateway.wireStream.open(endpoint, payload, uplink ?? emptyUplink(), peer, signal);
1765
1815
  })();
1766
1816
  }
1767
1817
  };
@@ -1954,6 +2004,13 @@ let officialClientModulesPromise;
1954
2004
  * Load the six official Client bundles once per process and freeze their
1955
2005
  * captured module exports. Concurrent callers share the same promise.
1956
2006
  *
2007
+ * DSH 0.2.1-rc.1 and later select the `./client` entry by condition: `@deepseek-ai/dsh-typert-registry`,
2008
+ * `@deepseek-ai/dsh-client-connection` and `@deepseek-ai/dsh-api-gateway` publish
2009
+ * a standalone Node ESM variant (which never touches `window.__ModuleLoader__`),
2010
+ * while the remaining three publish the browser loader factory. Both channels
2011
+ * feed one table, so the registration order below still holds for every
2012
+ * `/client` dependency.
2013
+ *
1957
2014
  * Failure semantics: a rejected capture stays cached (fail fast, no silent
1958
2015
  * retry). ESM evaluates each bundle at most once per process, so bundles
1959
2016
  * already imported during a failed capture can never re-register — a retry
@@ -1965,15 +2022,18 @@ function loadOfficialClientModulesOnce() {
1965
2022
  }
1966
2023
  /**
1967
2024
  * Exact scoped loader capture: install a temporary `window.__ModuleLoader__`,
1968
- * dynamic-import the six bundles in dependency order, validate and evaluate
1969
- * every registration, freeze the module-export table, and restore the
1970
- * previous process state in `finally` — before any Client Context exists.
2025
+ * dynamic-import the six bundles in dependency order, admit each bundle from
2026
+ * exactly the channel the published `./client` entry selected (loader
2027
+ * registration or standalone Node module — see {@link captureOfficialClientModules}),
2028
+ * freeze the module-export table, and restore the previous process state in
2029
+ * `finally` — before any Client Context exists.
1971
2030
  */
1972
2031
  /**
1973
2032
  * The exact scoped loader admission rules (module-internal seam, exercised by
1974
2033
  * the L5 loader-exactness test): reject an unknown registration id, a
1975
2034
  * duplicate id, a non-function factory, and a `/client` dependency requested
1976
- * before its dependency-order capture; report missing expected ids.
2035
+ * before its dependency-order capture; admit a directly imported Node bundle
2036
+ * for an id the loader did not register; report missing expected ids.
1977
2037
  */
1978
2038
  function createScopedClientModuleLoader(expectedIds) {
1979
2039
  const nodeRequire = createRequire(import.meta.url);
@@ -1995,12 +2055,30 @@ function createScopedClientModuleLoader(expectedIds) {
1995
2055
  registrations.set(id, factory);
1996
2056
  captured.set(id, factory(requireModule));
1997
2057
  };
2058
+ /**
2059
+ * Admit one directly imported bundle whose `./client` entry did not register
2060
+ * through the loader shim (the standalone Node variant). The module joins the
2061
+ * SAME table {@link requireModule} resolves `/client` dependencies from, so a
2062
+ * registering bundle can still depend on a Node-variant one. A bundle that did
2063
+ * register is left to its own registration: the browser factory result is the
2064
+ * authoritative module for that id.
2065
+ * @param id - the bundle's registration id.
2066
+ * @param module - the imported module namespace.
2067
+ * @throws when the id is unexpected or already admitted by a direct import.
2068
+ */
2069
+ const acceptImported = (id, module) => {
2070
+ if (!expectedIds.includes(id)) throw new Error(`official Client bundle import produced an unexpected id: ${String(id)}`);
2071
+ if (registrations.has(id)) return;
2072
+ if (captured.has(id)) throw new Error(`official Client bundle ${id} was imported as a Node module twice`);
2073
+ captured.set(id, module);
2074
+ };
1998
2075
  return {
1999
2076
  load,
2000
2077
  requireModule,
2001
2078
  registeredIds: () => [...registrations.keys()],
2079
+ acceptImported,
2002
2080
  assertComplete() {
2003
- for (const id of expectedIds) if (!registrations.has(id)) throw new Error(`official Client bundle ${id} never registered through __ModuleLoader__`);
2081
+ for (const id of expectedIds) if (!captured.has(id)) throw new Error(`official Client bundle ${id} was neither registered through __ModuleLoader__ nor imported as a Node module`);
2004
2082
  }
2005
2083
  };
2006
2084
  }
@@ -2052,13 +2130,13 @@ async function captureOfficialClientModules() {
2052
2130
  const loader = createScopedClientModuleLoader(EXPECTED_REGISTRATION_IDS);
2053
2131
  const restoreShim = installScopedModuleLoaderShim(loader.load);
2054
2132
  try {
2055
- for (const bundle of OFFICIAL_CLIENT_BUNDLES) await import(bundle.specifier);
2133
+ for (const bundle of OFFICIAL_CLIENT_BUNDLES) loader.acceptImported(bundle.id, await import(bundle.specifier));
2056
2134
  loader.assertComplete();
2057
2135
  } finally {
2058
2136
  restoreShim();
2059
2137
  }
2060
2138
  const captured = /* @__PURE__ */ new Map();
2061
- for (const id of loader.registeredIds()) captured.set(id, loader.requireModule(`${id}/client`));
2139
+ for (const id of EXPECTED_REGISTRATION_IDS) captured.set(id, loader.requireModule(`${id}/client`));
2062
2140
  return freezeOfficialClientModules(captured);
2063
2141
  }
2064
2142
  function freezeOfficialClientModules(captured) {
@@ -2165,11 +2243,14 @@ async function createRemoteClientRuntime(options) {
2165
2243
  typertFiber = context.plugin(modules.typert);
2166
2244
  await typertFiber;
2167
2245
  connectionFiber = context.plugin((connectionContext) => {
2168
- modules.connection.installConnection(connectionContext, { transport: {
2169
- ownsHost: true,
2170
- fetch: carrier.fetch,
2171
- openStream: carrier.openStream
2172
- } });
2246
+ modules.connection.installConnection(connectionContext, {
2247
+ interactions: "answer",
2248
+ transport: {
2249
+ ownsHost: true,
2250
+ fetch: carrier.fetch,
2251
+ openStream: carrier.openStream
2252
+ }
2253
+ });
2173
2254
  });
2174
2255
  await connectionFiber;
2175
2256
  gatewayFiber = context.plugin(modules.gateway);
@@ -2697,32 +2778,55 @@ var RemotePluginManagerPort = class {
2697
2778
  });
2698
2779
  }
2699
2780
  async inspect(spec, registry, signal) {
2700
- const result = await this.remote.pluginManager.inspect(spec, registry === void 0 ? void 0 : { registry }, signal);
2701
- return detachInspection(unwrapRemote$1(result, "inspect"));
2781
+ return detachInspection(await this.currentness("inspect", () => this.remote.pluginManager.inspect(spec, registry === void 0 ? void 0 : { registry }, signal)));
2782
+ }
2783
+ /**
2784
+ * One Remote result (a read or a settlement) fenced to the Connection
2785
+ * generation captured BEFORE dispatch. The fence covers success, an official
2786
+ * refusal result and a transport rejection alike: a reply carried by a
2787
+ * superseded generation is never presented as the new generation's definite
2788
+ * outcome. The Host may already have applied a write (or advanced an
2789
+ * install), so the caller's authoritative inventory reread / request-id
2790
+ * reconcile decides the visible outcome. An unchanged generation preserves
2791
+ * the original error and its real refusal taxonomy.
2792
+ */
2793
+ async currentness(operation, call) {
2794
+ const captured = this.generation.getSnapshot();
2795
+ const stillCurrent = () => Object.is(captured, this.generation.getSnapshot());
2796
+ let value;
2797
+ try {
2798
+ value = unwrapRemote$1(await call(), operation);
2799
+ } catch (error) {
2800
+ if (!stillCurrent()) throw new PluginManagerStaleResultError(operation);
2801
+ throw error;
2802
+ }
2803
+ if (!stillCurrent()) throw new PluginManagerStaleResultError(operation);
2804
+ return value;
2702
2805
  }
2703
2806
  async setBundleEnabled(name, enabled) {
2704
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.setBundleEnabled(name, enabled), "setBundleEnabled"));
2807
+ return detachChange(await this.currentness("setBundleEnabled", () => this.remote.pluginManager.setBundleEnabled(name, enabled)));
2705
2808
  }
2706
2809
  async setPluginEnabled(id, enabled) {
2707
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.setPluginEnabled(id, enabled), "setPluginEnabled"));
2810
+ return detachChange(await this.currentness("setPluginEnabled", () => this.remote.pluginManager.setPluginEnabled(id, enabled)));
2708
2811
  }
2709
2812
  async removeBundle(name) {
2710
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.removeBundle(name), "removeBundle"));
2813
+ return detachChange(await this.currentness("removeBundle", () => this.remote.pluginManager.removeBundle(name)));
2711
2814
  }
2712
2815
  async startInstall(request) {
2713
2816
  const options = {
2714
2817
  requestId: pluginInstallRequestId(request.requestId),
2715
2818
  registry: request.registry,
2716
- ...request.enabled === void 0 ? {} : { enabled: request.enabled }
2819
+ ...request.enabled === void 0 ? {} : { enabled: request.enabled },
2820
+ ...request.approvedBuilds === void 0 ? {} : { approvedBuilds: [...request.approvedBuilds] }
2717
2821
  };
2718
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.installBundle(request.spec, options), "installBundle"));
2822
+ return detachChange(await this.currentness("installBundle", () => this.remote.pluginManager.installBundle(request.spec, options)));
2719
2823
  }
2720
2824
  async waitForInstall(requestId) {
2721
- const result = unwrapRemote$1(await this.remote.pluginManager.waitForInstall(pluginInstallRequestId(requestId)), "waitForInstall");
2825
+ const result = await this.currentness("waitForInstall", () => this.remote.pluginManager.waitForInstall(pluginInstallRequestId(requestId)));
2722
2826
  return result === null ? null : detachChange(result);
2723
2827
  }
2724
2828
  async cancelInstall(requestId) {
2725
- const result = unwrapRemote$1(await this.remote.pluginManager.cancelInstall(pluginInstallRequestId(requestId)), "cancelInstall");
2829
+ const result = await this.currentness("cancelInstall", () => this.remote.pluginManager.cancelInstall(pluginInstallRequestId(requestId)));
2726
2830
  return Object.freeze({ status: result.status });
2727
2831
  }
2728
2832
  subscribeInstall(listener) {
@@ -2976,6 +3080,7 @@ var RemoteSessionReader = class {
2976
3080
  cwd: row.cwd,
2977
3081
  ...row.parentId === void 0 ? {} : { parentSession: row.parentId },
2978
3082
  ...row.origin === void 0 ? {} : { origin: row.origin },
3083
+ ...row.formatStatus === void 0 ? {} : { formatStatus: row.formatStatus },
2979
3084
  live: false
2980
3085
  };
2981
3086
  });
@@ -3222,9 +3327,15 @@ function acquireMainSurfaceReference(sessions, sessionId, signal) {
3222
3327
  source: "tuiMainView",
3223
3328
  ...signal === void 0 ? {} : { signal }
3224
3329
  });
3330
+ const binding = reference.binding;
3225
3331
  return {
3226
3332
  sessionId,
3227
- bindingIdentity: reference.binding,
3333
+ bindingIdentity: binding,
3334
+ ready: reference.ready,
3335
+ openState: () => {
3336
+ const session = binding.session;
3337
+ return session !== void 0 && typeof session.getSnapshot === "function" ? session.getSnapshot() : {};
3338
+ },
3228
3339
  release: () => {
3229
3340
  reference.release();
3230
3341
  }
@@ -3350,10 +3461,12 @@ var RemoteSessionWriter = class {
3350
3461
  sessions;
3351
3462
  generation;
3352
3463
  serializer;
3353
- constructor(sessions, generation, serializer) {
3464
+ admission;
3465
+ constructor(sessions, generation, serializer, admission) {
3354
3466
  this.sessions = sessions;
3355
3467
  this.generation = generation;
3356
3468
  this.serializer = serializer;
3469
+ this.admission = admission;
3357
3470
  }
3358
3471
  /**
3359
3472
  * Resolve and PIN the exact generation for one addressed session after
@@ -3424,6 +3537,10 @@ var RemoteSessionWriter = class {
3424
3537
  handle.abandon();
3425
3538
  return remoteNotDispatched();
3426
3539
  }
3540
+ if (this.admission?.isDispatchAllowed() === false) {
3541
+ handle.abandon();
3542
+ return remoteNotDispatched();
3543
+ }
3427
3544
  const result = await binding.session.prompt(serialized.content, mode, void 0, handle.requestId);
3428
3545
  if (result.ok) return {
3429
3546
  kind: "committed",
@@ -3568,7 +3685,8 @@ function classifyCreateFailure(error, requestedSessionId) {
3568
3685
  const FORK_REFUSAL_CODES = /* @__PURE__ */ new Set([
3569
3686
  "gateway/bad-request",
3570
3687
  "session/not-found",
3571
- "session/fork-unavailable"
3688
+ "session/fork-unavailable",
3689
+ "session/migration-required"
3572
3690
  ]);
3573
3691
  function classifyForkFailure(error) {
3574
3692
  const code = errorCode$1(error);
@@ -3599,11 +3717,9 @@ function classifyForkFailure(error) {
3599
3717
  /** The experimental Remote session lifecycle. */
3600
3718
  var RemoteSessionLifecycle = class {
3601
3719
  sessions;
3602
- session;
3603
3720
  generation;
3604
- constructor(sessions, session, generation) {
3721
+ constructor(sessions, generation) {
3605
3722
  this.sessions = sessions;
3606
- this.session = session;
3607
3723
  this.generation = generation;
3608
3724
  }
3609
3725
  async create(request) {
@@ -3618,51 +3734,20 @@ var RemoteSessionLifecycle = class {
3618
3734
  outcome: { kind: "cancelled" }
3619
3735
  };
3620
3736
  const ownership = () => !Object.is(captured, this.generation.getSnapshot()) || isAborted(request.signal) ? "superseded" : "current";
3621
- if (request.agentPreset !== void 0) return this.createWithPreset(request, cwd, ownership);
3622
3737
  let id;
3623
3738
  try {
3624
- id = String(await this.sessions.create({
3739
+ id = await this.sessions.create({
3740
+ ...cwd === void 0 ? {} : { cwd },
3625
3741
  sessionId: request.sessionId,
3626
- ...cwd === void 0 ? {} : { cwd }
3627
- }));
3742
+ ...request.agentPreset === void 0 ? {} : { agentPreset: request.agentPreset }
3743
+ });
3628
3744
  } catch (error) {
3629
3745
  return {
3630
3746
  ownership: ownership(),
3631
3747
  outcome: classifyCreateFailure(error, request.sessionId)
3632
3748
  };
3633
3749
  }
3634
- const handle = { session: { id } };
3635
- if (ownership() === "superseded") return {
3636
- ownership: "superseded",
3637
- outcome: {
3638
- kind: "created",
3639
- handle
3640
- }
3641
- };
3642
- return this.ownPublishedSession(id, ownership, request.signal);
3643
- }
3644
- /**
3645
- * Guaranteed-fresh TUI create with an explicit preset: one Host mutation
3646
- * (`session.create` with the preset) preserves creation-time atomicity. The
3647
- * official generated Remote THROWS on transport/envelope failure; normalize
3648
- * it so a post-dispatch failure is `indeterminate` with the requested id as
3649
- * correlation (v2 §0.7.3), never a rejected Promise.
3650
- */
3651
- async createWithPreset(request, cwd, ownership) {
3652
- const result = await this.session.create({
3653
- sessionId: request.sessionId,
3654
- ...cwd === void 0 ? {} : { cwd },
3655
- ...request.agentPreset === void 0 ? {} : { agentPreset: request.agentPreset }
3656
- }).catch((error) => ({
3657
- ok: false,
3658
- error
3659
- }));
3660
- if (!result.ok) return {
3661
- ownership: ownership(),
3662
- outcome: classifyCreateFailure(result.error, request.sessionId)
3663
- };
3664
- const publishedId = result.value.sessionId;
3665
- if (typeof publishedId !== "string" || publishedId === "") return {
3750
+ if (typeof id !== "string" || id === "") return {
3666
3751
  ownership: ownership(),
3667
3752
  outcome: {
3668
3753
  kind: "indeterminate",
@@ -3673,29 +3758,7 @@ var RemoteSessionLifecycle = class {
3673
3758
  requestedSessionId: request.sessionId
3674
3759
  }
3675
3760
  };
3676
- const handle = { session: { id: publishedId } };
3677
- if (ownership() === "superseded") return {
3678
- ownership: "superseded",
3679
- outcome: {
3680
- kind: "created",
3681
- handle
3682
- }
3683
- };
3684
- try {
3685
- await this.sessions.refresh();
3686
- } catch (error) {
3687
- return {
3688
- ownership: ownership(),
3689
- outcome: {
3690
- kind: "published-with-error",
3691
- sessionId: publishedId,
3692
- error: {
3693
- code: "session/reconcile-failed",
3694
- message: `the created Session could not be reconciled into Client state: ${remoteFailureMessage(error)}`
3695
- }
3696
- }
3697
- };
3698
- }
3761
+ const handle = { session: { id } };
3699
3762
  if (ownership() === "superseded") return {
3700
3763
  ownership: "superseded",
3701
3764
  outcome: {
@@ -3703,7 +3766,7 @@ var RemoteSessionLifecycle = class {
3703
3766
  handle
3704
3767
  }
3705
3768
  };
3706
- return this.ownPublishedSession(publishedId, ownership, request.signal);
3769
+ return this.ownPublishedSession(id, ownership, request.signal);
3707
3770
  }
3708
3771
  /**
3709
3772
  * Take Client generation ownership of a just-published Session.
@@ -3793,6 +3856,45 @@ var RemoteSessionLifecycle = class {
3793
3856
  outcome: { kind: "cancelled" }
3794
3857
  };
3795
3858
  }
3859
+ try {
3860
+ await owner.ready;
3861
+ } catch (error) {
3862
+ owner.release();
3863
+ if (!Object.is(captured, this.generation.getSnapshot())) return {
3864
+ ownership: "superseded",
3865
+ outcome: { kind: "cancelled" }
3866
+ };
3867
+ if (isAborted(request.signal)) return {
3868
+ ownership: "superseded",
3869
+ outcome: { kind: "cancelled" }
3870
+ };
3871
+ return {
3872
+ ownership: "current",
3873
+ outcome: {
3874
+ kind: "unavailable",
3875
+ message: `session "${request.sessionId}" failed to open: ${remoteFailureMessage(error)}`
3876
+ }
3877
+ };
3878
+ }
3879
+ if (!Object.is(captured, this.generation.getSnapshot()) || isAborted(request.signal)) {
3880
+ owner.release();
3881
+ return {
3882
+ ownership: "superseded",
3883
+ outcome: { kind: "cancelled" }
3884
+ };
3885
+ }
3886
+ const opened = owner.openState();
3887
+ if (opened.openState !== "open") {
3888
+ owner.release();
3889
+ const reason = opened.openState === "error" ? opened.openError === void 0 || opened.openError === null ? "the official initial history open failed" : remoteFailureMessage(opened.openError) : opened.openState === void 0 ? "the official open state is unavailable" : `the official history open is not settled (state: ${opened.openState})`;
3890
+ return {
3891
+ ownership: "current",
3892
+ outcome: {
3893
+ kind: "unavailable",
3894
+ message: `session "${request.sessionId}" failed to open: ${reason}`
3895
+ }
3896
+ };
3897
+ }
3796
3898
  return {
3797
3899
  ownership: "current",
3798
3900
  outcome: {
@@ -3828,7 +3930,8 @@ var RemoteSessionLifecycle = class {
3828
3930
  try {
3829
3931
  childId = String(await this.sessions.fork({
3830
3932
  sessionId: request.sourceSessionId,
3831
- ...request.atSeq === void 0 ? {} : { atSeq: request.atSeq }
3933
+ ...request.atSeq === void 0 ? {} : { atSeq: request.atSeq },
3934
+ allowMigration: false
3832
3935
  }));
3833
3936
  } catch (error) {
3834
3937
  return {
@@ -3952,6 +4055,7 @@ var RemoteSubagentPort = class {
3952
4055
  let signal;
3953
4056
  let canonical;
3954
4057
  let requestId;
4058
+ let timeZone;
3955
4059
  try {
3956
4060
  signal = context.makeSignal();
3957
4061
  canonical = [];
@@ -3964,6 +4068,7 @@ var RemoteSubagentPort = class {
3964
4068
  kind: "rejected",
3965
4069
  reason: { kind: "cancelled" }
3966
4070
  };
4071
+ timeZone = context.clientTimeZone();
3967
4072
  requestId = randomUUID();
3968
4073
  } catch (error) {
3969
4074
  return {
@@ -3980,7 +4085,8 @@ var RemoteSubagentPort = class {
3980
4085
  childSessionId: request.childSessionId,
3981
4086
  mode: "continuable",
3982
4087
  delivery: request.delivery,
3983
- content: canonical
4088
+ content: canonical,
4089
+ clientTimeZone: timeZone
3984
4090
  }, signal);
3985
4091
  if (result.ok) return {
3986
4092
  kind: "ok",
@@ -4858,8 +4964,8 @@ function createRemoteM3ASemantics(runtime, options) {
4858
4964
  return {
4859
4965
  sessionReader: new RemoteSessionReader(sessions, generation),
4860
4966
  pendingInputReader: new RemotePendingInputReader(sessions, generation),
4861
- sessionWriter: new RemoteSessionWriter(sessions, generation, options.promptSerializer),
4862
- sessionLifecycle: new RemoteSessionLifecycle(sessions, remote.session, generation),
4967
+ sessionWriter: new RemoteSessionWriter(sessions, generation, options.promptSerializer, options.isDispatchAllowed === void 0 ? void 0 : { isDispatchAllowed: options.isDispatchAllowed }),
4968
+ sessionLifecycle: new RemoteSessionLifecycle(sessions, generation),
4863
4969
  subagent: new RemoteSubagentPort(remote.subagents),
4864
4970
  catalog: {
4865
4971
  models: modelCatalog,
@@ -5175,6 +5281,11 @@ var RemoteTaskReader = class {
5175
5281
  * re-enters it ONCE before giving up — otherwise one transient failure would
5176
5282
  * turn every later read (including the Task Center's own retry) into a
5177
5283
  * permanent failure;
5284
+ * - `state === 'migration-required'` (0.2.1-rc.1): the Session needs an official
5285
+ * migration before its projections can be read. Settled and NOT an
5286
+ * authoritative catalog, so this read fails closed with a named error
5287
+ * rather than reporting an empty membership (the fuller migration UX
5288
+ * belongs to the Session-migration stage);
5178
5289
  * - `state === 'ready'` WITHOUT `subagentCatalog`: the official Client clears
5179
5290
  * the projection store and still settles `ready` when `session.projections`
5180
5291
  * answers a null/missing Session, so this is a REAL read failure — exactly
@@ -5214,6 +5325,7 @@ var RemoteTaskReader = class {
5214
5325
  }
5215
5326
  continue;
5216
5327
  }
5328
+ if (state === "migration-required") throw new Error(`the subagentCatalog projection requires an official migration for Session ${sessionId}`);
5217
5329
  const entries = projection.values.subagentCatalog;
5218
5330
  if (entries === void 0) throw new Error(`the subagentCatalog projection is unavailable for Session ${sessionId}`);
5219
5331
  return entries;
@@ -5283,174 +5395,325 @@ var RemoteTaskReader = class {
5283
5395
  //#endregion
5284
5396
  //#region src/app/remote/live-ingress.ts
5285
5397
  /**
5286
- * Create the ingress factory. The factory holds no subscription state until
5287
- * `subscribe` runs; each handle owns exactly one eventSource subscription plus
5288
- * the current-fact projection faces, and detaches on an exact BINDING
5289
- * replacement or an explicit dispose — never on a Connection generation
5290
- * rollover, which it adopts (see the module contract above).
5398
+ * Create the ingress factory.
5399
+ *
5400
+ * LIFETIME CONTRACT: the factory installs exactly ONE process-lifetime watch —
5401
+ * a listener on the official Connection generation source, used to remember that
5402
+ * a rollover happened even while no handle exists (a surface rebuild must then
5403
+ * treat its cold attach as verify-first). That watch is NOT owned by a handle
5404
+ * and is never explicitly released: its lifetime is the owning presentation
5405
+ * bundle / Client runtime — the official generation source belongs to the same
5406
+ * Client context and stops delivering when that context is disposed, and the
5407
+ * presentation source (`src/app/remote/presentation-source.ts`) is created once
5408
+ * per aggregate with no separate disposer. Each `subscribe` handle additionally
5409
+ * owns exactly one eventSource subscription plus the current-fact projection
5410
+ * faces, and detaches on an exact BINDING replacement or an explicit `dispose` —
5411
+ * never on a Connection generation rollover, which it adopts (see the module
5412
+ * contract above).
5291
5413
  */
5292
5414
  function createRemoteLiveIngress(sessions, generation, projectionKeys = []) {
5293
- return { subscribe(sessionId, sinks, hydrateRevision) {
5294
- const capturedGeneration = generation.getSnapshot();
5295
- if (capturedGeneration === void 0) return void 0;
5296
- const binding = sessions.binding(sessionId);
5297
- if (binding === void 0) return void 0;
5298
- /** The transient tuples whose `start` input is ALREADY reflected in the
5299
- * presentation (the read-side partition rule: ONE start per
5300
- * attemptId+turn+step, then chunks). Seeded from the CURRENT window's
5301
- * transient baseline (the cold hydrate synthesized those starts), so a
5302
- * chunk arriving for an ALREADY-STARTED attempt never re-starts it
5303
- * (a re-start would reset its live blocks and drop painted transient
5304
- * output). Retired on settle-assistant (the attempt is durable now)
5305
- * and re-seeded on a window replace. */
5306
- const startedTuples = /* @__PURE__ */ new Set();
5415
+ /**
5416
+ * Whether this process observed a Connection rollover. A COLD attach that
5417
+ * happens after one may be hydrating the retained PREVIOUS-generation window
5418
+ * (the upstream journal stream keeps it until the opening page is republished)
5419
+ * and the official faces carry no window-generation marker, so such a handle
5420
+ * starts in verify-first mode: the first publication reconciles the window
5421
+ * instead of being trusted as an incremental delta.
5422
+ */
5423
+ let observedRollover = false;
5424
+ let lastSeenGeneration = generation.getSnapshot();
5425
+ const trackRollover = () => {
5426
+ const current = generation.getSnapshot();
5427
+ if (current !== void 0 && current !== lastSeenGeneration) observedRollover = true;
5428
+ lastSeenGeneration = current;
5429
+ };
5430
+ generation.subscribe(trackRollover);
5431
+ return { subscribe(sessionId, sinks, hydrate) {
5432
+ let disposed = false;
5433
+ let attached;
5434
+ let startedTuples = /* @__PURE__ */ new Set();
5435
+ /** The revision of the last increment DELIVERED — or the revision one
5436
+ * acknowledged recovery committed. Delivery bookkeeping only. */
5437
+ let lastDeliveredRevision = -1;
5438
+ /** `recovering` = the incremental sequence is untrustworthy; the owner
5439
+ * must re-fold the official window and acknowledge the revision. */
5440
+ let mode = "incremental";
5441
+ /** The FULL identity the last wakeup was issued for: a NEW generation,
5442
+ * binding, revision or open state re-arms it. Comparing revisions alone
5443
+ * would swallow a mid-re-fold rollover whose read is already doomed by
5444
+ * the transport fence — the handle would stay recovering with no future
5445
+ * wakeup. */
5446
+ let notified;
5447
+ let notifyQueued = false;
5448
+ /** The Connection generation the delivered sequence belongs to. */
5449
+ let fencedGeneration = generation.getSnapshot();
5450
+ /**
5451
+ * The window revision the OLD generation had published when a rollover was
5452
+ * detected. The upstream RemoteJournalStream KEEPS the old published
5453
+ * window after a reconnect until the new generation's opening page
5454
+ * arrives (`packages/api/gateway/src/client/journal-stream.ts`), so a
5455
+ * re-fold performed in that gap reads a window that is still the DEAD
5456
+ * generation's — its revision and open state look perfectly current. Until
5457
+ * the new generation republishes (a new revision / `replace`), no
5458
+ * acknowledgement may claim that window, otherwise the opening page then
5459
+ * arrives as an ordinary append and the original missing rows return.
5460
+ */
5461
+ let rolloverBaselineRevision;
5307
5462
  const seedTuplesFromWindow = (entries) => {
5308
5463
  for (const entry of entries) {
5309
5464
  if (entry.type !== "transient") continue;
5310
5465
  startedTuples.add(`${entry.event.data.attemptId}:${entry.event.data.turn}:${entry.event.data.step}`);
5311
5466
  }
5312
5467
  };
5313
- seedTuplesFromWindow(binding.eventSource.getSnapshot().entries);
5314
- /** Transient chunks retained for a late subscriber baseline — NOT a
5315
- * second tracker: this mirrors the read-side `liveInputs` partition
5316
- * so a `replace` change can replay the new window's baseline through
5317
- * the SAME sinks. */
5318
- let disposed = false;
5319
- let unsubscribe;
5320
- const subscriptionRevision = binding.eventSource.getSnapshot().revision;
5321
- let lastRevision = subscriptionRevision;
5322
- const missedHydrationEvents = hydrateRevision !== void 0 && subscriptionRevision > hydrateRevision;
5323
- /** The exact retained binding is the ONLY retirement condition: a
5324
- * same-id rollover replaces the binding object, so its subscription
5325
- * must detach. */
5326
- const isBindingReplaced = () => disposed || sessions.binding(sessionId) !== binding;
5327
- /** Adopt the current Connection generation. A generation ROLLOVER
5328
- * (reconnect, network loss) does NOT retire the retained binding — it
5329
- * invalidates the OLD generation's async results and must drive the
5330
- * authoritative re-hydrate. Detaching here instead would leave the
5331
- * Remote surface permanently dead after any reconnect, because nothing
5332
- * re-establishes this subscription for an unchanged subject. */
5333
- let fencedGeneration = capturedGeneration;
5334
- const adoptGeneration = () => {
5335
- const current = generation.getSnapshot();
5336
- if (Object.is(fencedGeneration, current)) return "same";
5337
- fencedGeneration = current;
5338
- return "replaced";
5468
+ const detach = () => {
5469
+ const current = attached;
5470
+ if (current === void 0) return;
5471
+ attached = void 0;
5472
+ current.detach();
5339
5473
  };
5340
- /** Partition the CHANGE entries into durable events + live inputs
5341
- * (same tuple/start rule as the reader). */
5342
- const partitionChange = (entries) => {
5343
- const durable = [];
5344
- const live = [];
5345
- for (const entry of entries) {
5346
- if (entry.type === "event") {
5347
- durable.push(entry.event);
5348
- continue;
5349
- }
5350
- const { attemptId, turn, step, chunk } = entry.event.data;
5351
- const key = `${attemptId}:${turn}:${step}`;
5352
- if (!startedTuples.has(key)) {
5353
- startedTuples.add(key);
5474
+ const dispose = () => {
5475
+ if (disposed) return;
5476
+ disposed = true;
5477
+ unsubscribeGeneration();
5478
+ detach();
5479
+ };
5480
+ /** Ask the fold OWNER to reconcile the CURRENT official window. Intent
5481
+ * only, coalesced, deferred by exactly one microtask so the caller's
5482
+ * `handle = subscribe(...)` assignment always completes first. Every
5483
+ * later revision, the loading→open transition and any change of the
5484
+ * generation/binding identity re-arm it. */
5485
+ /** The reason of the pending (coalesced) wakeup: a recovery anywhere in the
5486
+ * window escalates a paging wakeup, never the other way round. */
5487
+ let pendingRefoldReason = "recovery";
5488
+ const requireRefold = (reason = "recovery") => {
5489
+ if (disposed) return;
5490
+ const current = attached;
5491
+ if (current === void 0) return;
5492
+ if (reason === "recovery") pendingRefoldReason = "recovery";
5493
+ else if (!notifyQueued && notified === void 0) pendingRefoldReason = "paging";
5494
+ mode = "recovering";
5495
+ const window = current.binding.eventSource.getSnapshot();
5496
+ const open = current.binding.session.getSnapshot().openState === "open";
5497
+ if (notified !== void 0 && Object.is(notified.generation, fencedGeneration) && Object.is(notified.binding, current.binding) && notified.revision === window.revision && notified.open === open) return;
5498
+ notified = {
5499
+ generation: fencedGeneration,
5500
+ binding: current.binding,
5501
+ revision: window.revision,
5502
+ open
5503
+ };
5504
+ if (notifyQueued) return;
5505
+ notifyQueued = true;
5506
+ queueMicrotask(() => {
5507
+ notifyQueued = false;
5508
+ if (disposed || mode !== "recovering") return;
5509
+ const still = attached;
5510
+ if (still === void 0 || sessions.binding(sessionId) !== still.binding) return;
5511
+ sinks.onWindowRefoldRequired(sessionId, pendingRefoldReason);
5512
+ pendingRefoldReason = "recovery";
5513
+ });
5514
+ };
5515
+ /** Acknowledge one committed re-fold (see the interface contract). The
5516
+ * proof is re-validated against the LIVE official state here. */
5517
+ const acknowledgeWindowRefold = (proof) => {
5518
+ if (disposed) return false;
5519
+ const current = attached;
5520
+ if (current === void 0) return false;
5521
+ if (!Object.is(proof.binding, current.binding)) return false;
5522
+ const liveGeneration = generation.getSnapshot();
5523
+ if (!Object.is(proof.generation, liveGeneration)) return false;
5524
+ const window = current.binding.eventSource.getSnapshot();
5525
+ if (window.revision !== proof.revision) return false;
5526
+ if (current.binding.session.getSnapshot().openState !== "open") return false;
5527
+ if (!refoldEligible(proof.revision)) return false;
5528
+ fencedGeneration = liveGeneration;
5529
+ startedTuples = /* @__PURE__ */ new Set();
5530
+ seedTuplesFromWindow(window.entries);
5531
+ lastDeliveredRevision = proof.revision;
5532
+ rolloverBaselineRevision = void 0;
5533
+ mode = "incremental";
5534
+ notified = void 0;
5535
+ return true;
5536
+ };
5537
+ /** One attachment: the receiver over this EXACT binding's official
5538
+ * channels. A replaced same-id binding retires it (the owner's commit
5539
+ * path installs the next one). */
5540
+ const attach = (capturedGeneration, binding) => {
5541
+ startedTuples = /* @__PURE__ */ new Set();
5542
+ seedTuplesFromWindow(binding.eventSource.getSnapshot().entries);
5543
+ const subscriptionRevision = binding.eventSource.getSnapshot().revision;
5544
+ lastDeliveredRevision = subscriptionRevision;
5545
+ mode = "incremental";
5546
+ notified = void 0;
5547
+ let lastSnapshotChange = 0;
5548
+ const isBindingReplaced = () => disposed || sessions.binding(sessionId) !== binding;
5549
+ const partitionChange = (entries) => {
5550
+ const durable = [];
5551
+ const live = [];
5552
+ for (const entry of entries) {
5553
+ if (entry.type === "event") {
5554
+ durable.push(entry.event);
5555
+ continue;
5556
+ }
5557
+ const { attemptId, turn, step, chunk } = entry.event.data;
5558
+ const key = `${attemptId}:${turn}:${step}`;
5559
+ if (!startedTuples.has(key)) {
5560
+ startedTuples.add(key);
5561
+ live.push({
5562
+ kind: "start",
5563
+ sessionId,
5564
+ attemptId,
5565
+ turn,
5566
+ step
5567
+ });
5568
+ }
5354
5569
  live.push({
5355
- kind: "start",
5570
+ kind: "chunk",
5356
5571
  sessionId,
5357
5572
  attemptId,
5358
5573
  turn,
5359
- step
5574
+ step,
5575
+ time: entry.event.time,
5576
+ chunk
5360
5577
  });
5361
5578
  }
5362
- live.push({
5363
- kind: "chunk",
5364
- sessionId,
5365
- attemptId,
5366
- turn,
5367
- step,
5368
- time: entry.event.time,
5369
- chunk
5370
- });
5371
- }
5372
- return {
5373
- durable,
5374
- live
5579
+ return {
5580
+ durable,
5581
+ live
5582
+ };
5375
5583
  };
5376
- };
5377
- const publish = () => {
5378
- if (isBindingReplaced()) {
5379
- dispose();
5380
- return;
5381
- }
5382
- if (adoptGeneration() === "replaced") lastRevision = -1;
5383
- const window = binding.eventSource.getSnapshot();
5384
- if (window.revision === lastRevision) return;
5385
- lastRevision = window.revision;
5386
- const change = window.change;
5387
- if (change === void 0) {
5388
- sinks.onWindowReplaced(sessionId);
5389
- return;
5390
- }
5391
- switch (change.kind) {
5392
- case "append": {
5393
- const { durable, live } = partitionChange(change.entries);
5394
- for (const input of live) sinks.onLiveInput(input);
5395
- for (const event of durable) sinks.onDurableEvent(sessionId, event);
5584
+ const publish = () => {
5585
+ if (isBindingReplaced()) {
5586
+ dispose();
5587
+ return;
5588
+ }
5589
+ const liveGeneration = generation.getSnapshot();
5590
+ if (!Object.is(fencedGeneration, liveGeneration)) {
5591
+ fencedGeneration = liveGeneration;
5592
+ rolloverBaselineRevision = binding.eventSource.getSnapshot().revision;
5593
+ requireRefold();
5594
+ }
5595
+ if (mode === "recovering") {
5596
+ requireRefold();
5396
5597
  return;
5397
5598
  }
5398
- case "prepend":
5399
- sinks.onWindowPrepended(sessionId);
5599
+ const window = binding.eventSource.getSnapshot();
5600
+ if (window.revision === lastDeliveredRevision) return;
5601
+ const change = window.change;
5602
+ if (change !== void 0 && change.kind === "prepend") {
5603
+ requireRefold("paging");
5400
5604
  return;
5401
- case "replace":
5402
- startedTuples.clear();
5403
- seedTuplesFromWindow(binding.eventSource.getSnapshot().entries);
5404
- sinks.onWindowReplaced(sessionId);
5605
+ }
5606
+ if (change === void 0 || change.kind === "replace") {
5607
+ requireRefold();
5405
5608
  return;
5406
- case "settle-assistant":
5407
- if (change.entry !== void 0) sinks.onDurableEvent(sessionId, change.entry.event);
5408
- for (const key of startedTuples) if (key.startsWith(`${change.attemptId}:`)) startedTuples.delete(key);
5609
+ }
5610
+ if (window.revision !== lastDeliveredRevision + 1) {
5611
+ requireRefold();
5409
5612
  return;
5410
- }
5411
- };
5412
- const dispose = () => {
5413
- if (disposed) return;
5414
- disposed = true;
5415
- unsubscribe?.();
5416
- unsubscribe = void 0;
5417
- unsubscribeSnapshot();
5418
- unsubscribeProjections();
5613
+ }
5614
+ switch (change.kind) {
5615
+ case "append": {
5616
+ const { durable, live } = partitionChange(change.entries);
5617
+ for (const input of live) sinks.onLiveInput(input);
5618
+ for (const event of durable) sinks.onDurableEvent(sessionId, event);
5619
+ lastDeliveredRevision = window.revision;
5620
+ return;
5621
+ }
5622
+ case "settle-assistant":
5623
+ if (change.entry !== void 0) sinks.onDurableEvent(sessionId, change.entry.event);
5624
+ for (const key of startedTuples) if (key.startsWith(`${change.attemptId}:`)) startedTuples.delete(key);
5625
+ lastDeliveredRevision = window.revision;
5626
+ return;
5627
+ }
5628
+ };
5629
+ const onSnapshot = () => {
5630
+ if (isBindingReplaced()) {
5631
+ dispose();
5632
+ return;
5633
+ }
5634
+ lastSnapshotChange += 1;
5635
+ sinks.onSessionSnapshotChanged(sessionId);
5636
+ if (mode === "recovering") requireRefold();
5637
+ };
5638
+ let projectionRefreshQueued = false;
5639
+ const onProjections = () => {
5640
+ if (isBindingReplaced()) {
5641
+ dispose();
5642
+ return;
5643
+ }
5644
+ if (projectionRefreshQueued) return;
5645
+ projectionRefreshQueued = true;
5646
+ queueMicrotask(() => {
5647
+ projectionRefreshQueued = false;
5648
+ if (disposed || isBindingReplaced()) return;
5649
+ sinks.onProjectionsChanged(sessionId);
5650
+ });
5651
+ };
5652
+ const unsubscribeSnapshot = binding.session.subscribe(onSnapshot);
5653
+ const offs = projectionKeys.map((key) => binding.session.projections.faceOf(key).subscribe(onProjections));
5654
+ const unsubscribeEvent = binding.eventSource.subscribe(publish);
5655
+ attached = {
5656
+ binding,
5657
+ detach: () => {
5658
+ unsubscribeEvent();
5659
+ unsubscribeSnapshot();
5660
+ for (const off of offs) off();
5661
+ }
5662
+ };
5663
+ const hydrateToken = hydrate?.transportToken;
5664
+ if (!(hydrate === void 0 || Object.is(hydrateToken?.binding, binding) && Object.is(hydrateToken?.generation, capturedGeneration))) {
5665
+ rolloverBaselineRevision = subscriptionRevision;
5666
+ requireRefold();
5667
+ } else if (hydrate !== void 0 && hydrate.revision !== subscriptionRevision) requireRefold();
5668
+ publish();
5419
5669
  };
5420
- let lastSnapshotChange = 0;
5421
- const onSnapshot = () => {
5422
- if (isBindingReplaced()) {
5423
- dispose();
5424
- return;
5425
- }
5426
- lastSnapshotChange += 1;
5427
- sinks.onSessionSnapshotChanged(sessionId);
5670
+ /** Attach as soon as BOTH official inputs exist. Driven only by the
5671
+ * official generation channel (the bootstrap/viewer calls this once on
5672
+ * entry); never a timer. */
5673
+ const tryAttach = () => {
5674
+ if (disposed || attached !== void 0) return;
5675
+ const liveGeneration = generation.getSnapshot();
5676
+ if (liveGeneration === void 0) return;
5677
+ const binding = sessions.binding(sessionId);
5678
+ if (binding === void 0) return;
5679
+ fencedGeneration = liveGeneration;
5680
+ attach(liveGeneration, binding);
5428
5681
  };
5429
- const unsubscribeSnapshot = binding.session.subscribe(onSnapshot);
5430
- let projectionRefreshQueued = false;
5431
- const onProjections = () => {
5432
- if (isBindingReplaced()) {
5433
- dispose();
5682
+ const onGeneration = () => {
5683
+ if (disposed) return;
5684
+ if (attached === void 0) {
5685
+ tryAttach();
5434
5686
  return;
5435
5687
  }
5436
- if (projectionRefreshQueued) return;
5437
- projectionRefreshQueued = true;
5438
- queueMicrotask(() => {
5439
- projectionRefreshQueued = false;
5440
- if (disposed || isBindingReplaced()) return;
5441
- sinks.onProjectionsChanged(sessionId);
5442
- });
5688
+ const liveGeneration = generation.getSnapshot();
5689
+ if (Object.is(fencedGeneration, liveGeneration)) return;
5690
+ const current = attached;
5691
+ fencedGeneration = liveGeneration;
5692
+ rolloverBaselineRevision = current === void 0 ? void 0 : current.binding.eventSource.getSnapshot().revision;
5693
+ requireRefold();
5443
5694
  };
5444
- const unsubscribeProjections = (() => {
5445
- const offs = projectionKeys.map((key) => binding.session.projections.faceOf(key).subscribe(onProjections));
5446
- return () => {
5447
- for (const off of offs) off();
5695
+ const refoldEligible = (revision) => !(rolloverBaselineRevision !== void 0 && revision === rolloverBaselineRevision);
5696
+ const unsubscribeGeneration = generation.subscribe(() => {
5697
+ trackRollover();
5698
+ onGeneration();
5699
+ });
5700
+ const verifyFirst = observedRollover;
5701
+ tryAttach();
5702
+ if (verifyFirst && attached !== void 0) {
5703
+ mode = "recovering";
5704
+ const window = attached.binding.eventSource.getSnapshot();
5705
+ notified = {
5706
+ generation: fencedGeneration,
5707
+ binding: attached.binding,
5708
+ revision: window.revision,
5709
+ open: attached.binding.session.getSnapshot().openState === "open"
5448
5710
  };
5449
- })();
5450
- unsubscribe = binding.eventSource.subscribe(publish);
5451
- publish();
5452
- if (!disposed && missedHydrationEvents && lastRevision === subscriptionRevision) sinks.onWindowReplaced(sessionId);
5453
- return { dispose };
5711
+ }
5712
+ return {
5713
+ dispose,
5714
+ acknowledgeWindowRefold,
5715
+ refoldEligible
5716
+ };
5454
5717
  } };
5455
5718
  }
5456
5719
  //#endregion
@@ -5501,6 +5764,7 @@ function createRemoteChildViewSource(options) {
5501
5764
  return;
5502
5765
  }
5503
5766
  let read;
5767
+ const openFenceGeneration = options.generation.getSnapshot();
5504
5768
  try {
5505
5769
  read = await reader.read(childId, target.signal);
5506
5770
  } catch (error) {
@@ -5523,6 +5787,10 @@ function createRemoteChildViewSource(options) {
5523
5787
  reference.release();
5524
5788
  throw childOpenFailure(childId, opened.openState, opened.openError);
5525
5789
  }
5790
+ if (!Object.is(openFenceGeneration, options.generation.getSnapshot()) || binding.eventSource?.getSnapshot().revision !== read.revision) {
5791
+ reference.release();
5792
+ return;
5793
+ }
5526
5794
  const hydrated = (snapshot, current) => ({
5527
5795
  durableEvents: snapshot.durableEvents,
5528
5796
  liveInputs: snapshot.liveInputs,
@@ -5541,10 +5809,30 @@ function createRemoteChildViewSource(options) {
5541
5809
  if (released) return void 0;
5542
5810
  const before = ownedBinding();
5543
5811
  if (before === void 0 || !isOpen(before)) return void 0;
5812
+ const fenceGeneration = options.generation.getSnapshot();
5544
5813
  const next = await reader.read(childId);
5545
5814
  const current = ownedBinding();
5546
5815
  if (next === void 0 || current === void 0 || !isOpen(current)) return void 0;
5547
- return hydrated(next, current);
5816
+ if (!Object.is(fenceGeneration, options.generation.getSnapshot())) return void 0;
5817
+ if (current.eventSource?.getSnapshot().revision !== next.revision) return void 0;
5818
+ return {
5819
+ ...hydrated(next, current),
5820
+ commit: (write) => {
5821
+ if (released) return false;
5822
+ if (!Object.is(fenceGeneration, options.generation.getSnapshot())) return false;
5823
+ const bindingNow = ownedBinding();
5824
+ if (bindingNow === void 0 || bindingNow !== current || !isOpen(bindingNow)) return false;
5825
+ if (bindingNow.eventSource?.getSnapshot().revision !== next.revision) return false;
5826
+ if (live !== void 0 && !live.refoldEligible(next.revision)) return false;
5827
+ write();
5828
+ if (live === void 0) return true;
5829
+ return live.acknowledgeWindowRefold({
5830
+ generation: fenceGeneration,
5831
+ binding: current,
5832
+ revision: next.revision
5833
+ });
5834
+ }
5835
+ };
5548
5836
  },
5549
5837
  async loadOlder() {
5550
5838
  if (released) return;
@@ -5556,12 +5844,16 @@ function createRemoteChildViewSource(options) {
5556
5844
  const handle = liveIngress.subscribe(childId, {
5557
5845
  onDurableEvent: (_id, event) => sinks.onDurableEvent(options.asEvent(event)),
5558
5846
  onLiveInput: (input) => sinks.onLiveInput(input),
5559
- onWindowReplaced: () => sinks.onWindowReplaced(),
5560
- onWindowPrepended: () => sinks.onWindowPrepended(),
5847
+ onWindowRefoldRequired: () => sinks.onWindowRefoldRequired(),
5561
5848
  onSessionSnapshotChanged: () => sinks.onSessionSnapshotChanged(),
5562
5849
  onProjectionsChanged: () => sinks.onProjectionsChanged()
5563
- }, snapshot.revision);
5564
- if (handle === void 0) return void 0;
5850
+ }, {
5851
+ revision: read.revision,
5852
+ transportToken: {
5853
+ generation: openFenceGeneration,
5854
+ binding
5855
+ }
5856
+ });
5565
5857
  live = handle;
5566
5858
  return { dispose: () => {
5567
5859
  handle.dispose();
@@ -5790,8 +6082,12 @@ function detachedPlan(value) {
5790
6082
  * owns: `semantics.presentationReader` by identity, the wire's
5791
6083
  * `sessions`/`connection.generation` for the official projection/echo reads,
5792
6084
  * and the eventSource borrow for the live ingress. Constructing this bundle
5793
- * installs no subscription and owns no disposal — the ingress subscription
5794
- * is created lazily by the bootstrap and disposed through its own handle.
6085
+ * installs exactly ONE watch — the ingress factory's process-lifetime
6086
+ * Connection-generation listener, whose lifetime is this bundle and the Client
6087
+ * context the generation source belongs to (there is no separate disposer for
6088
+ * it; see `live-ingress.ts`) — and no other subscription. The per-session
6089
+ * ingress subscription is created lazily by the bootstrap and disposed through
6090
+ * its own handle.
5795
6091
  */
5796
6092
  function createRemotePresentationSource(wire, backendRuntime) {
5797
6093
  const sessions = wire.client.sessions;
@@ -5846,6 +6142,18 @@ function createRemotePresentationSource(wire, backendRuntime) {
5846
6142
  if (captured === void 0 || typeof captured !== "object") return false;
5847
6143
  if (!Object.is(captured.generation, generation.getSnapshot())) return false;
5848
6144
  return sessions.binding(sessionId) === captured.binding;
6145
+ },
6146
+ windowRefoldProof(sessionId, revision) {
6147
+ const current = generation.getSnapshot();
6148
+ if (current === void 0) return void 0;
6149
+ const binding = sessions.binding(sessionId);
6150
+ if (binding === void 0) return void 0;
6151
+ if (binding.eventSource?.getSnapshot().revision !== revision) return void 0;
6152
+ return {
6153
+ generation: current,
6154
+ binding,
6155
+ revision
6156
+ };
5849
6157
  }
5850
6158
  },
5851
6159
  task: {
@@ -5863,6 +6171,7 @@ function createRemotePresentationSource(wire, backendRuntime) {
5863
6171
  sessions,
5864
6172
  reader: backendRuntime.semantics.presentationReader,
5865
6173
  liveIngress,
6174
+ generation,
5866
6175
  childCwd: (sessionId) => {
5867
6176
  const cwd = sessionReader.sessionStatus(sessionId)?.cwd;
5868
6177
  return typeof cwd === "string" ? cwd : "";
@@ -5993,10 +6302,19 @@ async function createRemoteApplicationRuntime(options) {
5993
6302
  });
5994
6303
  let backendRuntime;
5995
6304
  let ownerServices;
6305
+ /**
6306
+ * The composition-owned pre-dispatch write admission: OPEN for the whole live
6307
+ * surface, closed ONCE and synchronously by the application's surface-stop
6308
+ * boundary (`SelectedApplicationRuntime.stopSurfaceAdmission`). A write still
6309
+ * parked before dispatch when the surface stops is then refused before any
6310
+ * Host dispatch instead of being admitted silently.
6311
+ */
6312
+ let dispatchAdmissionOpen = true;
5996
6313
  try {
5997
6314
  backendRuntime = await createRemoteBackendRuntime({
5998
6315
  runtime: wire.client,
5999
6316
  fetch: wire.host.carrier.fetch,
6317
+ isDispatchAllowed: () => dispatchAdmissionOpen,
6000
6318
  ...options.promptSerializer === void 0 ? {} : { promptSerializer: options.promptSerializer }
6001
6319
  });
6002
6320
  ownerServices = createRemoteSessionOwnerServices(wire.client.sessions);
@@ -6035,6 +6353,9 @@ async function createRemoteApplicationRuntime(options) {
6035
6353
  backend: backendRuntime.backend,
6036
6354
  owners: ownerServices.owners,
6037
6355
  retirement: ownerServices.retirement,
6356
+ stopSurfaceAdmission: () => {
6357
+ dispatchAdmissionOpen = false;
6358
+ },
6038
6359
  disposeTransport: async () => {
6039
6360
  if (transportDisposed) return;
6040
6361
  transportDisposed = true;
@@ -6148,7 +6469,10 @@ async function createRemoteBackendRuntime(options) {
6148
6469
  }
6149
6470
  };
6150
6471
  try {
6151
- const semantics = createRemoteM3ASemantics(remoteM3ARuntimeSourceOf(options.runtime), { promptSerializer: options.promptSerializer ?? RemotePromptSerializerProduction.overSessions(options.runtime.sessions) });
6472
+ const semantics = createRemoteM3ASemantics(remoteM3ARuntimeSourceOf(options.runtime), {
6473
+ promptSerializer: options.promptSerializer ?? RemotePromptSerializerProduction.overSessions(options.runtime.sessions),
6474
+ ...options.isDispatchAllowed === void 0 ? {} : { isDispatchAllowed: options.isDispatchAllowed }
6475
+ });
6152
6476
  unwind.push(() => semantics.dispose());
6153
6477
  const config = new RemoteConfigPort(remoteConfigRuntimeSourceOf(options.runtime));
6154
6478
  unwind.push(() => config.dispose());