@xmoon76/dsh-pi-tui 0.5.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.
Files changed (31) hide show
  1. package/README.en.md +130 -17
  2. package/README.md +76 -16
  3. package/cordis.patch.yml +17 -49
  4. package/dist/builtins.mjs +3 -2
  5. package/dist/context-summary-CxUpNkA9.mjs +2951 -0
  6. package/dist/extension/advanced.d.mts +2 -2
  7. package/dist/extension/unstable.d.mts +1 -1
  8. package/dist/{extensions-v3Rf-qJA.d.mts → extensions-DzpBiiYb.d.mts} +1 -1
  9. package/dist/{extensions-1WYBUQ8I.mjs → extensions-a-rxanjw.mjs} +3514 -2892
  10. package/dist/extensions.d.mts +2 -2
  11. package/dist/extensions.mjs +1 -1
  12. package/dist/index.d.mts +13 -11
  13. package/dist/index.mjs +20158 -7768
  14. package/dist/performance-host-BJT6scGF.mjs +266 -0
  15. package/dist/performance-host.d.mts +36 -0
  16. package/dist/performance-host.mjs +2 -0
  17. package/dist/performance-view-jvvd8Jn7.mjs +476 -0
  18. package/dist/{public-types-BEjj7FEb.d.mts → public-types-gZi3iFNh.d.mts} +1 -1
  19. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  20. package/dist/{runtime-CcQyhIvI.mjs → runtime-BtPH-UUb.mjs} +625 -261
  21. package/dist/session-BZLxhrPQ.mjs +5697 -0
  22. package/dist/{startup-CmTYVTGC.mjs → startup-D5Xu8diR.mjs} +22 -7
  23. package/dist/startup.d.mts +1 -2
  24. package/dist/startup.mjs +1 -1
  25. package/dist/tasks-D_z5Yjjr.mjs +267 -0
  26. package/dist/{terminal-progress-source-BfiTKDT-.mjs → terminal-progress-source-BlmksrSD.mjs} +116 -265
  27. package/generated/dsh-presets/cordis.patch.yml +8 -26
  28. package/generated/dsh-presets/minimal.patch.yml +17 -0
  29. package/generated/dsh-presets/ptc.patch.yml +8 -26
  30. package/generated/dsh-presets/standard.patch.yml +8 -26
  31. package/package.json +166 -146
@@ -1,7 +1,9 @@
1
- import { a as PI_TUI_EXTENSIONS_SERVICE, n as extensions_exports } from "./extensions-1WYBUQ8I.mjs";
2
- import { n as TUI_STARTUP_SERVICE } from "./startup-CmTYVTGC.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, dt as cancellationError, f as listPiTuiHostFileReferences, ft as isCancellation, gt as safeErrorMessage, 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-BfiTKDT-.mjs";
1
+ import { n as TUI_STARTUP_SERVICE } from "./startup-D5Xu8diR.mjs";
2
+ import { n as isCancellation, o as safeErrorMessage, t as cancellationError } from "./tasks-D_z5Yjjr.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";
4
5
  import { t as builtins_exports } from "./builtins.mjs";
6
+ import { a as performance_host_exports } from "./performance-host-BJT6scGF.mjs";
5
7
  import { createRequire } from "node:module";
6
8
  import { randomUUID } from "node:crypto";
7
9
  import { Context } from "@deepseek-ai/cordis";
@@ -497,14 +499,32 @@ var RemoteConfigMirror = class {
497
499
  /**
498
500
  * Serialized namespace write.
499
501
  *
500
- * A write first guarantees a CURRENT mirror (so the revision fence it
501
- * carries was read from the live document), dispatches the official
502
- * `settings.mutate` with that revision, and only then refreshes from
503
- * authority. The mutate's returned view is deliberately NOT trusted as the
504
- * mirror's new state: the refreshed `describe` snapshot is the only new
505
- * authority, which is what makes "never an optimistic local write" true.
502
+ * A write first guarantees a CURRENT mirror (so it can dispatch at all),
503
+ * dispatches the official `settings.mutate` with the revision the CALLER's
504
+ * decision unit was read at, and only then refreshes from authority. The
505
+ * mutate's returned view is deliberately NOT trusted as the mirror's new
506
+ * state: the refreshed `describe` snapshot is the only new authority, which
507
+ * is what makes "never an optimistic local write" true.
508
+ *
509
+ * `baseRevision` is the revision of the snapshot an op set was RECONCILED
510
+ * against (`RemoteTuiSettingsConfig.replace` diffing a whole document). The
511
+ * refresh above must not replace it: re-reading the fence here would
512
+ * re-authorize a decision taken against the older document, letting the
513
+ * stale op silently supersede a concurrent external write instead of
514
+ * surfacing the conflict. Callers that build their ops directly from the
515
+ * current mirror (provider profiles, permission presets, …) omit it and keep
516
+ * the refreshed revision.
517
+ *
518
+ * `refreshFailure` owns the ONE ambiguity left: the official mutate may have
519
+ * committed while the post-settlement refresh could not complete. `reject`
520
+ * (default) keeps that as a failed write, which is what a caller that RE-READS
521
+ * the mirror afterwards needs — it must never mistake a last-known value for the
522
+ * committed one (`RemoteSubagentModelSelectionConfig.set`). `record` reports the
523
+ * committed write as committed, marks the snapshot non-current and records the
524
+ * cause; the whole-document `replace` uses it so its consumer re-reads the
525
+ * authority itself and reports accepted-but-unverified instead of a refusal.
506
526
  */
507
- async mutate(ns, ops) {
527
+ async mutate(ns, ops, baseRevision, refreshFailure = "reject") {
508
528
  await this.enqueueWrite(async () => {
509
529
  await this.ensureCurrent();
510
530
  const snapshot = this.lastKnown();
@@ -515,9 +535,25 @@ var RemoteConfigMirror = class {
515
535
  if (ops.length === 0) return;
516
536
  const descriptor = snapshot.namespaces?.get(ns);
517
537
  if (descriptor === void 0) throw new Error(`settings namespace "${ns}" is not available in this deployment`);
518
- const result = await settledResult(this.settings.mutate(ns, [...ops], descriptor.revision));
519
- if (!result.ok) throw new Error(`settings.mutate(${ns}) failed: ${remoteFailureMessage(result.error)}`);
520
- await this.describe();
538
+ const result = await settledResult(this.settings.mutate(ns, [...ops], baseRevision ?? descriptor.revision));
539
+ if (!result.ok) {
540
+ this.invalidate();
541
+ try {
542
+ await this.describe();
543
+ } catch (error) {
544
+ this.recordFailure(error);
545
+ }
546
+ throw new Error(`settings.mutate(${ns}) failed: ${remoteFailureMessage(result.error)}`);
547
+ }
548
+ if (refreshFailure === "reject") {
549
+ await this.describe();
550
+ return;
551
+ }
552
+ try {
553
+ await this.describe();
554
+ } catch (error) {
555
+ this.recordFailure(error);
556
+ }
521
557
  });
522
558
  }
523
559
  /** Drop the cached snapshot (and any in-flight read's publication right). */
@@ -680,7 +716,7 @@ var RemoteTuiSettingsConfig = class {
680
716
  if (descriptor === void 0) throw new Error("settings entry \"tui-app\" is unavailable on this connection");
681
717
  if (descriptor.value === void 0) throw new Error("settings entry \"tui-app\" exposes no form projection");
682
718
  const ops = diffTuiSettings(descriptor.value, descriptor.user, doc);
683
- await this.mirror.mutate(TUI_SETTINGS_NS, ops);
719
+ await this.mirror.mutate(TUI_SETTINGS_NS, ops, descriptor.revision, "record");
684
720
  }
685
721
  };
686
722
  /** The Direct M5 trust read, replayed from the mirrored descriptor's USER
@@ -1088,6 +1124,7 @@ var RemoteConfigPort = class {
1088
1124
  permissions;
1089
1125
  presetDefault;
1090
1126
  subagentModelSelection;
1127
+ web;
1091
1128
  /** `undefined` while the `tui-app` namespace is absent from the mirror
1092
1129
  * (the port's documented absence contract). */
1093
1130
  get tuiSettings() {
@@ -1110,6 +1147,7 @@ var RemoteConfigPort = class {
1110
1147
  this.permissions = new RemotePermissionConfig(this.mirror, source.remote.commands);
1111
1148
  this.presetDefault = new RemotePresetDefaultConfig(this.mirror);
1112
1149
  this.subagentModelSelection = new RemoteSubagentModelSelectionConfig(this.mirror);
1150
+ this.web = new RemoteUnsupportedWebProviderConfig();
1113
1151
  }
1114
1152
  /** Commit one fresh mirror snapshot (or leave the last-known value). A
1115
1153
  * failure is RECORDED as well as thrown, so `readiness()` stays truthful
@@ -1149,6 +1187,39 @@ var RemoteConfigPort = class {
1149
1187
  this.credentialConfig.dispose();
1150
1188
  }
1151
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
+ };
1152
1223
  //#endregion
1153
1224
  //#region src/runtime/remote/session-archive-remote.ts
1154
1225
  /** The official absolute export path (`dsh-session-log-export` routes). */
@@ -1349,7 +1420,8 @@ function createPiTuiHostFileReferenceRuntime(deps) {
1349
1420
  return await listPiTuiHostFileReferences(agent, query, signal, {
1350
1421
  official: deps.official(),
1351
1422
  driver,
1352
- environment
1423
+ environment,
1424
+ workingDirectory: deps.workingDirectory?.()
1353
1425
  });
1354
1426
  } };
1355
1427
  }
@@ -1369,7 +1441,10 @@ var PiTuiFileReferenceHostService = class extends TypertRemoteService {
1369
1441
  */
1370
1442
  constructor(ctx, deps) {
1371
1443
  super(ctx, PI_TUI_FILE_REFERENCES_NAMESPACE);
1372
- this.runtime = createPiTuiHostFileReferenceRuntime(deps);
1444
+ this.runtime = createPiTuiHostFileReferenceRuntime({
1445
+ ...deps,
1446
+ workingDirectory: () => ctx.get("workingDirectory")
1447
+ });
1373
1448
  }
1374
1449
  /**
1375
1450
  * The private Remote method (`piTuiFileReferences/list`, see
@@ -1678,6 +1753,7 @@ const HOST_PREREQUISITE_SERVICES = [
1678
1753
  "commands",
1679
1754
  "fileReferences",
1680
1755
  "fs",
1756
+ "workingDirectory",
1681
1757
  "llm",
1682
1758
  "sessions",
1683
1759
  "sessionProjections",
@@ -1713,19 +1789,29 @@ function mergeCause(failure, secondary) {
1713
1789
  function assertHostPrerequisites(hostContext) {
1714
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`);
1715
1791
  }
1716
- /** 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. */
1717
1801
  function createInProcessCarrier(hostContext) {
1718
- const shared = hostContext.connection.createSharedFetchHandler("/api");
1802
+ const connection = hostContext.connection;
1803
+ const peer = connection.browserPeer;
1804
+ const shared = connection.createSharedFetchHandler("/api");
1719
1805
  const gateway = hostContext.typertGateway;
1720
1806
  return {
1721
1807
  ownsHost: true,
1722
1808
  fetch(input, init) {
1723
1809
  const request = input instanceof Request ? new Request(input, init) : new Request(new URL(String(input), IN_PROCESS_BASE_URL), init);
1724
- return shared.fetch(request);
1810
+ return shared.fetch(request, peer);
1725
1811
  },
1726
1812
  openStream(endpoint, payload, signal, uplink) {
1727
1813
  return (async function* () {
1728
- yield* await gateway.wireStream.open(endpoint, payload, uplink ?? emptyUplink(), void 0, signal);
1814
+ yield* await gateway.wireStream.open(endpoint, payload, uplink ?? emptyUplink(), peer, signal);
1729
1815
  })();
1730
1816
  }
1731
1817
  };
@@ -1803,6 +1889,9 @@ async function createRemoteHostRuntime(hostContext, options = {}) {
1803
1889
  const statsFiber = hostContext.plugin(sessionStats);
1804
1890
  fibers.push(statsFiber);
1805
1891
  await statsFiber;
1892
+ const performanceFiber = hostContext.plugin(performance_host_exports);
1893
+ fibers.push(performanceFiber);
1894
+ await performanceFiber;
1806
1895
  const outlineFiber = hostContext.plugin(sessionTurnOutline);
1807
1896
  fibers.push(outlineFiber);
1808
1897
  await outlineFiber;
@@ -1915,6 +2004,13 @@ let officialClientModulesPromise;
1915
2004
  * Load the six official Client bundles once per process and freeze their
1916
2005
  * captured module exports. Concurrent callers share the same promise.
1917
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
+ *
1918
2014
  * Failure semantics: a rejected capture stays cached (fail fast, no silent
1919
2015
  * retry). ESM evaluates each bundle at most once per process, so bundles
1920
2016
  * already imported during a failed capture can never re-register — a retry
@@ -1926,15 +2022,18 @@ function loadOfficialClientModulesOnce() {
1926
2022
  }
1927
2023
  /**
1928
2024
  * Exact scoped loader capture: install a temporary `window.__ModuleLoader__`,
1929
- * dynamic-import the six bundles in dependency order, validate and evaluate
1930
- * every registration, freeze the module-export table, and restore the
1931
- * 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.
1932
2030
  */
1933
2031
  /**
1934
2032
  * The exact scoped loader admission rules (module-internal seam, exercised by
1935
2033
  * the L5 loader-exactness test): reject an unknown registration id, a
1936
2034
  * duplicate id, a non-function factory, and a `/client` dependency requested
1937
- * 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.
1938
2037
  */
1939
2038
  function createScopedClientModuleLoader(expectedIds) {
1940
2039
  const nodeRequire = createRequire(import.meta.url);
@@ -1956,12 +2055,30 @@ function createScopedClientModuleLoader(expectedIds) {
1956
2055
  registrations.set(id, factory);
1957
2056
  captured.set(id, factory(requireModule));
1958
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
+ };
1959
2075
  return {
1960
2076
  load,
1961
2077
  requireModule,
1962
2078
  registeredIds: () => [...registrations.keys()],
2079
+ acceptImported,
1963
2080
  assertComplete() {
1964
- 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`);
1965
2082
  }
1966
2083
  };
1967
2084
  }
@@ -2013,13 +2130,13 @@ async function captureOfficialClientModules() {
2013
2130
  const loader = createScopedClientModuleLoader(EXPECTED_REGISTRATION_IDS);
2014
2131
  const restoreShim = installScopedModuleLoaderShim(loader.load);
2015
2132
  try {
2016
- 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));
2017
2134
  loader.assertComplete();
2018
2135
  } finally {
2019
2136
  restoreShim();
2020
2137
  }
2021
2138
  const captured = /* @__PURE__ */ new Map();
2022
- 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`));
2023
2140
  return freezeOfficialClientModules(captured);
2024
2141
  }
2025
2142
  function freezeOfficialClientModules(captured) {
@@ -2126,11 +2243,14 @@ async function createRemoteClientRuntime(options) {
2126
2243
  typertFiber = context.plugin(modules.typert);
2127
2244
  await typertFiber;
2128
2245
  connectionFiber = context.plugin((connectionContext) => {
2129
- modules.connection.installConnection(connectionContext, { transport: {
2130
- ownsHost: true,
2131
- fetch: carrier.fetch,
2132
- openStream: carrier.openStream
2133
- } });
2246
+ modules.connection.installConnection(connectionContext, {
2247
+ interactions: "answer",
2248
+ transport: {
2249
+ ownsHost: true,
2250
+ fetch: carrier.fetch,
2251
+ openStream: carrier.openStream
2252
+ }
2253
+ });
2134
2254
  });
2135
2255
  await connectionFiber;
2136
2256
  gatewayFiber = context.plugin(modules.gateway);
@@ -2658,32 +2778,55 @@ var RemotePluginManagerPort = class {
2658
2778
  });
2659
2779
  }
2660
2780
  async inspect(spec, registry, signal) {
2661
- const result = await this.remote.pluginManager.inspect(spec, registry === void 0 ? void 0 : { registry }, signal);
2662
- 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;
2663
2805
  }
2664
2806
  async setBundleEnabled(name, enabled) {
2665
- 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)));
2666
2808
  }
2667
2809
  async setPluginEnabled(id, enabled) {
2668
- 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)));
2669
2811
  }
2670
2812
  async removeBundle(name) {
2671
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.removeBundle(name), "removeBundle"));
2813
+ return detachChange(await this.currentness("removeBundle", () => this.remote.pluginManager.removeBundle(name)));
2672
2814
  }
2673
2815
  async startInstall(request) {
2674
2816
  const options = {
2675
2817
  requestId: pluginInstallRequestId(request.requestId),
2676
2818
  registry: request.registry,
2677
- ...request.enabled === void 0 ? {} : { enabled: request.enabled }
2819
+ ...request.enabled === void 0 ? {} : { enabled: request.enabled },
2820
+ ...request.approvedBuilds === void 0 ? {} : { approvedBuilds: [...request.approvedBuilds] }
2678
2821
  };
2679
- 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)));
2680
2823
  }
2681
2824
  async waitForInstall(requestId) {
2682
- 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)));
2683
2826
  return result === null ? null : detachChange(result);
2684
2827
  }
2685
2828
  async cancelInstall(requestId) {
2686
- 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)));
2687
2830
  return Object.freeze({ status: result.status });
2688
2831
  }
2689
2832
  subscribeInstall(listener) {
@@ -2901,7 +3044,8 @@ const STATUS_PROJECTION_KEYS = [
2901
3044
  "agentPreset",
2902
3045
  "title",
2903
3046
  "goal",
2904
- "permissions"
3047
+ "permissions",
3048
+ "piTuiPerformance"
2905
3049
  ];
2906
3050
  /** The projection keys the Remote STATUS/WELCOME current facts are read from:
2907
3051
  * EXACTLY what `sessionStatus()` reads (`STATUS_PROJECTION_KEYS`, the tuple
@@ -2936,6 +3080,7 @@ var RemoteSessionReader = class {
2936
3080
  cwd: row.cwd,
2937
3081
  ...row.parentId === void 0 ? {} : { parentSession: row.parentId },
2938
3082
  ...row.origin === void 0 ? {} : { origin: row.origin },
3083
+ ...row.formatStatus === void 0 ? {} : { formatStatus: row.formatStatus },
2939
3084
  live: false
2940
3085
  };
2941
3086
  });
@@ -3182,9 +3327,15 @@ function acquireMainSurfaceReference(sessions, sessionId, signal) {
3182
3327
  source: "tuiMainView",
3183
3328
  ...signal === void 0 ? {} : { signal }
3184
3329
  });
3330
+ const binding = reference.binding;
3185
3331
  return {
3186
3332
  sessionId,
3187
- 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
+ },
3188
3339
  release: () => {
3189
3340
  reference.release();
3190
3341
  }
@@ -3310,10 +3461,12 @@ var RemoteSessionWriter = class {
3310
3461
  sessions;
3311
3462
  generation;
3312
3463
  serializer;
3313
- constructor(sessions, generation, serializer) {
3464
+ admission;
3465
+ constructor(sessions, generation, serializer, admission) {
3314
3466
  this.sessions = sessions;
3315
3467
  this.generation = generation;
3316
3468
  this.serializer = serializer;
3469
+ this.admission = admission;
3317
3470
  }
3318
3471
  /**
3319
3472
  * Resolve and PIN the exact generation for one addressed session after
@@ -3384,6 +3537,10 @@ var RemoteSessionWriter = class {
3384
3537
  handle.abandon();
3385
3538
  return remoteNotDispatched();
3386
3539
  }
3540
+ if (this.admission?.isDispatchAllowed() === false) {
3541
+ handle.abandon();
3542
+ return remoteNotDispatched();
3543
+ }
3387
3544
  const result = await binding.session.prompt(serialized.content, mode, void 0, handle.requestId);
3388
3545
  if (result.ok) return {
3389
3546
  kind: "committed",
@@ -3528,7 +3685,8 @@ function classifyCreateFailure(error, requestedSessionId) {
3528
3685
  const FORK_REFUSAL_CODES = /* @__PURE__ */ new Set([
3529
3686
  "gateway/bad-request",
3530
3687
  "session/not-found",
3531
- "session/fork-unavailable"
3688
+ "session/fork-unavailable",
3689
+ "session/migration-required"
3532
3690
  ]);
3533
3691
  function classifyForkFailure(error) {
3534
3692
  const code = errorCode$1(error);
@@ -3559,11 +3717,9 @@ function classifyForkFailure(error) {
3559
3717
  /** The experimental Remote session lifecycle. */
3560
3718
  var RemoteSessionLifecycle = class {
3561
3719
  sessions;
3562
- session;
3563
3720
  generation;
3564
- constructor(sessions, session, generation) {
3721
+ constructor(sessions, generation) {
3565
3722
  this.sessions = sessions;
3566
- this.session = session;
3567
3723
  this.generation = generation;
3568
3724
  }
3569
3725
  async create(request) {
@@ -3578,51 +3734,20 @@ var RemoteSessionLifecycle = class {
3578
3734
  outcome: { kind: "cancelled" }
3579
3735
  };
3580
3736
  const ownership = () => !Object.is(captured, this.generation.getSnapshot()) || isAborted(request.signal) ? "superseded" : "current";
3581
- if (request.agentPreset !== void 0) return this.createWithPreset(request, cwd, ownership);
3582
3737
  let id;
3583
3738
  try {
3584
- id = String(await this.sessions.create({
3739
+ id = await this.sessions.create({
3740
+ ...cwd === void 0 ? {} : { cwd },
3585
3741
  sessionId: request.sessionId,
3586
- ...cwd === void 0 ? {} : { cwd }
3587
- }));
3742
+ ...request.agentPreset === void 0 ? {} : { agentPreset: request.agentPreset }
3743
+ });
3588
3744
  } catch (error) {
3589
3745
  return {
3590
3746
  ownership: ownership(),
3591
3747
  outcome: classifyCreateFailure(error, request.sessionId)
3592
3748
  };
3593
3749
  }
3594
- const handle = { session: { id } };
3595
- if (ownership() === "superseded") return {
3596
- ownership: "superseded",
3597
- outcome: {
3598
- kind: "created",
3599
- handle
3600
- }
3601
- };
3602
- return this.ownPublishedSession(id, ownership, request.signal);
3603
- }
3604
- /**
3605
- * Guaranteed-fresh TUI create with an explicit preset: one Host mutation
3606
- * (`session.create` with the preset) preserves creation-time atomicity. The
3607
- * official generated Remote THROWS on transport/envelope failure; normalize
3608
- * it so a post-dispatch failure is `indeterminate` with the requested id as
3609
- * correlation (v2 §0.7.3), never a rejected Promise.
3610
- */
3611
- async createWithPreset(request, cwd, ownership) {
3612
- const result = await this.session.create({
3613
- sessionId: request.sessionId,
3614
- ...cwd === void 0 ? {} : { cwd },
3615
- ...request.agentPreset === void 0 ? {} : { agentPreset: request.agentPreset }
3616
- }).catch((error) => ({
3617
- ok: false,
3618
- error
3619
- }));
3620
- if (!result.ok) return {
3621
- ownership: ownership(),
3622
- outcome: classifyCreateFailure(result.error, request.sessionId)
3623
- };
3624
- const publishedId = result.value.sessionId;
3625
- if (typeof publishedId !== "string" || publishedId === "") return {
3750
+ if (typeof id !== "string" || id === "") return {
3626
3751
  ownership: ownership(),
3627
3752
  outcome: {
3628
3753
  kind: "indeterminate",
@@ -3633,29 +3758,7 @@ var RemoteSessionLifecycle = class {
3633
3758
  requestedSessionId: request.sessionId
3634
3759
  }
3635
3760
  };
3636
- const handle = { session: { id: publishedId } };
3637
- if (ownership() === "superseded") return {
3638
- ownership: "superseded",
3639
- outcome: {
3640
- kind: "created",
3641
- handle
3642
- }
3643
- };
3644
- try {
3645
- await this.sessions.refresh();
3646
- } catch (error) {
3647
- return {
3648
- ownership: ownership(),
3649
- outcome: {
3650
- kind: "published-with-error",
3651
- sessionId: publishedId,
3652
- error: {
3653
- code: "session/reconcile-failed",
3654
- message: `the created Session could not be reconciled into Client state: ${remoteFailureMessage(error)}`
3655
- }
3656
- }
3657
- };
3658
- }
3761
+ const handle = { session: { id } };
3659
3762
  if (ownership() === "superseded") return {
3660
3763
  ownership: "superseded",
3661
3764
  outcome: {
@@ -3663,7 +3766,7 @@ var RemoteSessionLifecycle = class {
3663
3766
  handle
3664
3767
  }
3665
3768
  };
3666
- return this.ownPublishedSession(publishedId, ownership, request.signal);
3769
+ return this.ownPublishedSession(id, ownership, request.signal);
3667
3770
  }
3668
3771
  /**
3669
3772
  * Take Client generation ownership of a just-published Session.
@@ -3753,6 +3856,45 @@ var RemoteSessionLifecycle = class {
3753
3856
  outcome: { kind: "cancelled" }
3754
3857
  };
3755
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
+ }
3756
3898
  return {
3757
3899
  ownership: "current",
3758
3900
  outcome: {
@@ -3788,7 +3930,8 @@ var RemoteSessionLifecycle = class {
3788
3930
  try {
3789
3931
  childId = String(await this.sessions.fork({
3790
3932
  sessionId: request.sourceSessionId,
3791
- ...request.atSeq === void 0 ? {} : { atSeq: request.atSeq }
3933
+ ...request.atSeq === void 0 ? {} : { atSeq: request.atSeq },
3934
+ allowMigration: false
3792
3935
  }));
3793
3936
  } catch (error) {
3794
3937
  return {
@@ -3912,6 +4055,7 @@ var RemoteSubagentPort = class {
3912
4055
  let signal;
3913
4056
  let canonical;
3914
4057
  let requestId;
4058
+ let timeZone;
3915
4059
  try {
3916
4060
  signal = context.makeSignal();
3917
4061
  canonical = [];
@@ -3924,6 +4068,7 @@ var RemoteSubagentPort = class {
3924
4068
  kind: "rejected",
3925
4069
  reason: { kind: "cancelled" }
3926
4070
  };
4071
+ timeZone = context.clientTimeZone();
3927
4072
  requestId = randomUUID();
3928
4073
  } catch (error) {
3929
4074
  return {
@@ -3940,7 +4085,8 @@ var RemoteSubagentPort = class {
3940
4085
  childSessionId: request.childSessionId,
3941
4086
  mode: "continuable",
3942
4087
  delivery: request.delivery,
3943
- content: canonical
4088
+ content: canonical,
4089
+ clientTimeZone: timeZone
3944
4090
  }, signal);
3945
4091
  if (result.ok) return {
3946
4092
  kind: "ok",
@@ -4818,8 +4964,8 @@ function createRemoteM3ASemantics(runtime, options) {
4818
4964
  return {
4819
4965
  sessionReader: new RemoteSessionReader(sessions, generation),
4820
4966
  pendingInputReader: new RemotePendingInputReader(sessions, generation),
4821
- sessionWriter: new RemoteSessionWriter(sessions, generation, options.promptSerializer),
4822
- 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),
4823
4969
  subagent: new RemoteSubagentPort(remote.subagents),
4824
4970
  catalog: {
4825
4971
  models: modelCatalog,
@@ -5135,6 +5281,11 @@ var RemoteTaskReader = class {
5135
5281
  * re-enters it ONCE before giving up — otherwise one transient failure would
5136
5282
  * turn every later read (including the Task Center's own retry) into a
5137
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);
5138
5289
  * - `state === 'ready'` WITHOUT `subagentCatalog`: the official Client clears
5139
5290
  * the projection store and still settles `ready` when `session.projections`
5140
5291
  * answers a null/missing Session, so this is a REAL read failure — exactly
@@ -5174,6 +5325,7 @@ var RemoteTaskReader = class {
5174
5325
  }
5175
5326
  continue;
5176
5327
  }
5328
+ if (state === "migration-required") throw new Error(`the subagentCatalog projection requires an official migration for Session ${sessionId}`);
5177
5329
  const entries = projection.values.subagentCatalog;
5178
5330
  if (entries === void 0) throw new Error(`the subagentCatalog projection is unavailable for Session ${sessionId}`);
5179
5331
  return entries;
@@ -5243,174 +5395,325 @@ var RemoteTaskReader = class {
5243
5395
  //#endregion
5244
5396
  //#region src/app/remote/live-ingress.ts
5245
5397
  /**
5246
- * Create the ingress factory. The factory holds no subscription state until
5247
- * `subscribe` runs; each handle owns exactly one eventSource subscription plus
5248
- * the current-fact projection faces, and detaches on an exact BINDING
5249
- * replacement or an explicit dispose — never on a Connection generation
5250
- * 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).
5251
5413
  */
5252
5414
  function createRemoteLiveIngress(sessions, generation, projectionKeys = []) {
5253
- return { subscribe(sessionId, sinks, hydrateRevision) {
5254
- const capturedGeneration = generation.getSnapshot();
5255
- if (capturedGeneration === void 0) return void 0;
5256
- const binding = sessions.binding(sessionId);
5257
- if (binding === void 0) return void 0;
5258
- /** The transient tuples whose `start` input is ALREADY reflected in the
5259
- * presentation (the read-side partition rule: ONE start per
5260
- * attemptId+turn+step, then chunks). Seeded from the CURRENT window's
5261
- * transient baseline (the cold hydrate synthesized those starts), so a
5262
- * chunk arriving for an ALREADY-STARTED attempt never re-starts it
5263
- * (a re-start would reset its live blocks and drop painted transient
5264
- * output). Retired on settle-assistant (the attempt is durable now)
5265
- * and re-seeded on a window replace. */
5266
- 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;
5267
5462
  const seedTuplesFromWindow = (entries) => {
5268
5463
  for (const entry of entries) {
5269
5464
  if (entry.type !== "transient") continue;
5270
5465
  startedTuples.add(`${entry.event.data.attemptId}:${entry.event.data.turn}:${entry.event.data.step}`);
5271
5466
  }
5272
5467
  };
5273
- seedTuplesFromWindow(binding.eventSource.getSnapshot().entries);
5274
- /** Transient chunks retained for a late subscriber baseline — NOT a
5275
- * second tracker: this mirrors the read-side `liveInputs` partition
5276
- * so a `replace` change can replay the new window's baseline through
5277
- * the SAME sinks. */
5278
- let disposed = false;
5279
- let unsubscribe;
5280
- const subscriptionRevision = binding.eventSource.getSnapshot().revision;
5281
- let lastRevision = subscriptionRevision;
5282
- const missedHydrationEvents = hydrateRevision !== void 0 && subscriptionRevision > hydrateRevision;
5283
- /** The exact retained binding is the ONLY retirement condition: a
5284
- * same-id rollover replaces the binding object, so its subscription
5285
- * must detach. */
5286
- const isBindingReplaced = () => disposed || sessions.binding(sessionId) !== binding;
5287
- /** Adopt the current Connection generation. A generation ROLLOVER
5288
- * (reconnect, network loss) does NOT retire the retained binding — it
5289
- * invalidates the OLD generation's async results and must drive the
5290
- * authoritative re-hydrate. Detaching here instead would leave the
5291
- * Remote surface permanently dead after any reconnect, because nothing
5292
- * re-establishes this subscription for an unchanged subject. */
5293
- let fencedGeneration = capturedGeneration;
5294
- const adoptGeneration = () => {
5295
- const current = generation.getSnapshot();
5296
- if (Object.is(fencedGeneration, current)) return "same";
5297
- fencedGeneration = current;
5298
- return "replaced";
5468
+ const detach = () => {
5469
+ const current = attached;
5470
+ if (current === void 0) return;
5471
+ attached = void 0;
5472
+ current.detach();
5299
5473
  };
5300
- /** Partition the CHANGE entries into durable events + live inputs
5301
- * (same tuple/start rule as the reader). */
5302
- const partitionChange = (entries) => {
5303
- const durable = [];
5304
- const live = [];
5305
- for (const entry of entries) {
5306
- if (entry.type === "event") {
5307
- durable.push(entry.event);
5308
- continue;
5309
- }
5310
- const { attemptId, turn, step, chunk } = entry.event.data;
5311
- const key = `${attemptId}:${turn}:${step}`;
5312
- if (!startedTuples.has(key)) {
5313
- 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
+ }
5314
5569
  live.push({
5315
- kind: "start",
5570
+ kind: "chunk",
5316
5571
  sessionId,
5317
5572
  attemptId,
5318
5573
  turn,
5319
- step
5574
+ step,
5575
+ time: entry.event.time,
5576
+ chunk
5320
5577
  });
5321
5578
  }
5322
- live.push({
5323
- kind: "chunk",
5324
- sessionId,
5325
- attemptId,
5326
- turn,
5327
- step,
5328
- time: entry.event.time,
5329
- chunk
5330
- });
5331
- }
5332
- return {
5333
- durable,
5334
- live
5579
+ return {
5580
+ durable,
5581
+ live
5582
+ };
5335
5583
  };
5336
- };
5337
- const publish = () => {
5338
- if (isBindingReplaced()) {
5339
- dispose();
5340
- return;
5341
- }
5342
- if (adoptGeneration() === "replaced") lastRevision = -1;
5343
- const window = binding.eventSource.getSnapshot();
5344
- if (window.revision === lastRevision) return;
5345
- lastRevision = window.revision;
5346
- const change = window.change;
5347
- if (change === void 0) {
5348
- sinks.onWindowReplaced(sessionId);
5349
- return;
5350
- }
5351
- switch (change.kind) {
5352
- case "append": {
5353
- const { durable, live } = partitionChange(change.entries);
5354
- for (const input of live) sinks.onLiveInput(input);
5355
- for (const event of durable) sinks.onDurableEvent(sessionId, event);
5584
+ const publish = () => {
5585
+ if (isBindingReplaced()) {
5586
+ dispose();
5356
5587
  return;
5357
5588
  }
5358
- case "prepend":
5359
- sinks.onWindowPrepended(sessionId);
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();
5360
5597
  return;
5361
- case "replace":
5362
- startedTuples.clear();
5363
- seedTuplesFromWindow(binding.eventSource.getSnapshot().entries);
5364
- sinks.onWindowReplaced(sessionId);
5598
+ }
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");
5365
5604
  return;
5366
- case "settle-assistant":
5367
- if (change.entry !== void 0) sinks.onDurableEvent(sessionId, change.entry.event);
5368
- for (const key of startedTuples) if (key.startsWith(`${change.attemptId}:`)) startedTuples.delete(key);
5605
+ }
5606
+ if (change === void 0 || change.kind === "replace") {
5607
+ requireRefold();
5369
5608
  return;
5370
- }
5371
- };
5372
- const dispose = () => {
5373
- if (disposed) return;
5374
- disposed = true;
5375
- unsubscribe?.();
5376
- unsubscribe = void 0;
5377
- unsubscribeSnapshot();
5378
- unsubscribeProjections();
5609
+ }
5610
+ if (window.revision !== lastDeliveredRevision + 1) {
5611
+ requireRefold();
5612
+ return;
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();
5379
5669
  };
5380
- let lastSnapshotChange = 0;
5381
- const onSnapshot = () => {
5382
- if (isBindingReplaced()) {
5383
- dispose();
5384
- return;
5385
- }
5386
- lastSnapshotChange += 1;
5387
- 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);
5388
5681
  };
5389
- const unsubscribeSnapshot = binding.session.subscribe(onSnapshot);
5390
- let projectionRefreshQueued = false;
5391
- const onProjections = () => {
5392
- if (isBindingReplaced()) {
5393
- dispose();
5682
+ const onGeneration = () => {
5683
+ if (disposed) return;
5684
+ if (attached === void 0) {
5685
+ tryAttach();
5394
5686
  return;
5395
5687
  }
5396
- if (projectionRefreshQueued) return;
5397
- projectionRefreshQueued = true;
5398
- queueMicrotask(() => {
5399
- projectionRefreshQueued = false;
5400
- if (disposed || isBindingReplaced()) return;
5401
- sinks.onProjectionsChanged(sessionId);
5402
- });
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();
5403
5694
  };
5404
- const unsubscribeProjections = (() => {
5405
- const offs = projectionKeys.map((key) => binding.session.projections.faceOf(key).subscribe(onProjections));
5406
- return () => {
5407
- 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"
5408
5710
  };
5409
- })();
5410
- unsubscribe = binding.eventSource.subscribe(publish);
5411
- publish();
5412
- if (!disposed && missedHydrationEvents && lastRevision === subscriptionRevision) sinks.onWindowReplaced(sessionId);
5413
- return { dispose };
5711
+ }
5712
+ return {
5713
+ dispose,
5714
+ acknowledgeWindowRefold,
5715
+ refoldEligible
5716
+ };
5414
5717
  } };
5415
5718
  }
5416
5719
  //#endregion
@@ -5461,6 +5764,7 @@ function createRemoteChildViewSource(options) {
5461
5764
  return;
5462
5765
  }
5463
5766
  let read;
5767
+ const openFenceGeneration = options.generation.getSnapshot();
5464
5768
  try {
5465
5769
  read = await reader.read(childId, target.signal);
5466
5770
  } catch (error) {
@@ -5483,6 +5787,10 @@ function createRemoteChildViewSource(options) {
5483
5787
  reference.release();
5484
5788
  throw childOpenFailure(childId, opened.openState, opened.openError);
5485
5789
  }
5790
+ if (!Object.is(openFenceGeneration, options.generation.getSnapshot()) || binding.eventSource?.getSnapshot().revision !== read.revision) {
5791
+ reference.release();
5792
+ return;
5793
+ }
5486
5794
  const hydrated = (snapshot, current) => ({
5487
5795
  durableEvents: snapshot.durableEvents,
5488
5796
  liveInputs: snapshot.liveInputs,
@@ -5501,10 +5809,30 @@ function createRemoteChildViewSource(options) {
5501
5809
  if (released) return void 0;
5502
5810
  const before = ownedBinding();
5503
5811
  if (before === void 0 || !isOpen(before)) return void 0;
5812
+ const fenceGeneration = options.generation.getSnapshot();
5504
5813
  const next = await reader.read(childId);
5505
5814
  const current = ownedBinding();
5506
5815
  if (next === void 0 || current === void 0 || !isOpen(current)) return void 0;
5507
- 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
+ };
5508
5836
  },
5509
5837
  async loadOlder() {
5510
5838
  if (released) return;
@@ -5516,12 +5844,16 @@ function createRemoteChildViewSource(options) {
5516
5844
  const handle = liveIngress.subscribe(childId, {
5517
5845
  onDurableEvent: (_id, event) => sinks.onDurableEvent(options.asEvent(event)),
5518
5846
  onLiveInput: (input) => sinks.onLiveInput(input),
5519
- onWindowReplaced: () => sinks.onWindowReplaced(),
5520
- onWindowPrepended: () => sinks.onWindowPrepended(),
5847
+ onWindowRefoldRequired: () => sinks.onWindowRefoldRequired(),
5521
5848
  onSessionSnapshotChanged: () => sinks.onSessionSnapshotChanged(),
5522
5849
  onProjectionsChanged: () => sinks.onProjectionsChanged()
5523
- }, snapshot.revision);
5524
- if (handle === void 0) return void 0;
5850
+ }, {
5851
+ revision: read.revision,
5852
+ transportToken: {
5853
+ generation: openFenceGeneration,
5854
+ binding
5855
+ }
5856
+ });
5525
5857
  live = handle;
5526
5858
  return { dispose: () => {
5527
5859
  handle.dispose();
@@ -5750,8 +6082,12 @@ function detachedPlan(value) {
5750
6082
  * owns: `semantics.presentationReader` by identity, the wire's
5751
6083
  * `sessions`/`connection.generation` for the official projection/echo reads,
5752
6084
  * and the eventSource borrow for the live ingress. Constructing this bundle
5753
- * installs no subscription and owns no disposal — the ingress subscription
5754
- * 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.
5755
6091
  */
5756
6092
  function createRemotePresentationSource(wire, backendRuntime) {
5757
6093
  const sessions = wire.client.sessions;
@@ -5806,6 +6142,18 @@ function createRemotePresentationSource(wire, backendRuntime) {
5806
6142
  if (captured === void 0 || typeof captured !== "object") return false;
5807
6143
  if (!Object.is(captured.generation, generation.getSnapshot())) return false;
5808
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
+ };
5809
6157
  }
5810
6158
  },
5811
6159
  task: {
@@ -5823,6 +6171,7 @@ function createRemotePresentationSource(wire, backendRuntime) {
5823
6171
  sessions,
5824
6172
  reader: backendRuntime.semantics.presentationReader,
5825
6173
  liveIngress,
6174
+ generation,
5826
6175
  childCwd: (sessionId) => {
5827
6176
  const cwd = sessionReader.sessionStatus(sessionId)?.cwd;
5828
6177
  return typeof cwd === "string" ? cwd : "";
@@ -5953,10 +6302,19 @@ async function createRemoteApplicationRuntime(options) {
5953
6302
  });
5954
6303
  let backendRuntime;
5955
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;
5956
6313
  try {
5957
6314
  backendRuntime = await createRemoteBackendRuntime({
5958
6315
  runtime: wire.client,
5959
6316
  fetch: wire.host.carrier.fetch,
6317
+ isDispatchAllowed: () => dispatchAdmissionOpen,
5960
6318
  ...options.promptSerializer === void 0 ? {} : { promptSerializer: options.promptSerializer }
5961
6319
  });
5962
6320
  ownerServices = createRemoteSessionOwnerServices(wire.client.sessions);
@@ -5995,6 +6353,9 @@ async function createRemoteApplicationRuntime(options) {
5995
6353
  backend: backendRuntime.backend,
5996
6354
  owners: ownerServices.owners,
5997
6355
  retirement: ownerServices.retirement,
6356
+ stopSurfaceAdmission: () => {
6357
+ dispatchAdmissionOpen = false;
6358
+ },
5998
6359
  disposeTransport: async () => {
5999
6360
  if (transportDisposed) return;
6000
6361
  transportDisposed = true;
@@ -6108,7 +6469,10 @@ async function createRemoteBackendRuntime(options) {
6108
6469
  }
6109
6470
  };
6110
6471
  try {
6111
- 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
+ });
6112
6476
  unwind.push(() => semantics.dispose());
6113
6477
  const config = new RemoteConfigPort(remoteConfigRuntimeSourceOf(options.runtime));
6114
6478
  unwind.push(() => config.dispose());