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

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 (39) hide show
  1. package/README.en.md +200 -124
  2. package/README.md +132 -90
  3. package/cordis.patch.yml +54 -50
  4. package/dist/builtins.mjs +2 -2
  5. package/dist/client-bootstrap-F5DHFI9t.mjs +5576 -0
  6. package/dist/context-summary-DAisTA_7.mjs +8557 -0
  7. package/dist/dispose-cause-CNFuUnjR.mjs +24 -0
  8. package/dist/entry-control-DvSrndWd.mjs +111 -0
  9. package/dist/extension/advanced.d.mts +1 -1
  10. package/dist/extension/unstable.d.mts +1 -1
  11. package/dist/{extensions-DzpBiiYb.d.mts → extensions-Bte3XOt5.d.mts} +1 -1
  12. package/dist/{extensions-VuoIE_Jc.mjs → extensions-CcuMY4n2.mjs} +722 -324
  13. package/dist/extensions.d.mts +2 -2
  14. package/dist/extensions.mjs +1 -1
  15. package/dist/host-bootstrap-DAgKknbY.mjs +119 -0
  16. package/dist/index.d.mts +10 -10
  17. package/dist/index.mjs +52682 -30024
  18. package/dist/local-client.mjs +323 -0
  19. package/dist/local-host.mjs +176 -0
  20. package/dist/{performance-host-BJT6scGF.mjs → performance-host-CcDJjjVA.mjs} +1 -1
  21. package/dist/performance-host.mjs +1 -1
  22. package/dist/{performance-view-jvvd8Jn7.mjs → performance-view-CfGvLZyD.mjs} +1 -1
  23. package/dist/{public-types-gZi3iFNh.d.mts → public-types-Dgf1bDke.d.mts} +3 -3
  24. package/dist/runtime-status-0lp9CM0V.mjs +1923 -0
  25. package/dist/{runtime-Dq6HoyjZ.mjs → runtime-vc4mdr-R.mjs} +1907 -1276
  26. package/dist/{session-DTauqYx6.mjs → session-tdJHLnJR.mjs} +3420 -339
  27. package/dist/{startup-CWQl0-0n.mjs → startup-JaVZoTIl.mjs} +69 -13
  28. package/dist/startup.d.mts +2 -2
  29. package/dist/startup.mjs +1 -1
  30. package/dist/{terminal-progress-source-Dpwz3csm.mjs → terminal-progress-source-xor3vakJ.mjs} +172 -49
  31. package/dist/visual-tools.d.mts +62 -0
  32. package/dist/visual-tools.mjs +556 -0
  33. package/generated/dsh-presets/README.md +1 -1
  34. package/generated/dsh-presets/cordis.patch.yml +8 -26
  35. package/generated/dsh-presets/minimal.patch.yml +17 -0
  36. package/generated/dsh-presets/ptc.patch.yml +8 -26
  37. package/generated/dsh-presets/standard.patch.yml +8 -26
  38. package/package.json +184 -154
  39. package/dist/context-summary-CxQnkDEN.mjs +0 -2478
@@ -1,9 +1,9 @@
1
- import { n as TUI_STARTUP_SERVICE } from "./startup-CWQl0-0n.mjs";
1
+ import { n as TUI_STARTUP_SERVICE } from "./startup-JaVZoTIl.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 deliveredFileReadErrorFrom, C as classifySubagentPromptSettlement, E as isRemoteBusinessRefusalCode, H as providerOptionsFor, M as clientOwnerOf, O as REMOTE_IMPLEMENTED_CAPABILITIES, S as detachedTurnOutline, T as GATEWAY_PRE_INVOCATION_CODES, U as providerProfileProjectionOf, V as getPath, W as SupersededReadError, a as PluginManagerStaleResultError, c as detachInspection, d as detachPluginManagerSnapshot, dt as resolveUserCommandItemFallbackActivationIds, f as pluginInstallRequestId, ft as resolveUserLayerFooterMode, h as hostPathQueryEnvironment, i as PI_TUI_TERMINAL_PROGRESS_WATCH, k as DeliveredFileReadError, l as detachLog, lt as resolveTrustedFooterCommand, m as DirectHostDiscoveryDriver, mt as contextPressureOccupancy, n as createRemoteTerminalProgressSource, o as createTerminalProgressInterval, p as listPiTuiHostFileReferences, r as PI_TUI_TERMINAL_PROGRESS_NAMESPACE, s as detachChange, st as parseFooterCustomItems, u as detachPhase, ut as resolveUserCommandItemActivationIds, x as detachedSessionStatus, y as QuestionAnswerError } from "./terminal-progress-source-xor3vakJ.mjs";
4
+ import { a as PI_TUI_EXTENSIONS_SERVICE, n as extensions_exports } from "./extensions-CcuMY4n2.mjs";
5
5
  import { t as builtins_exports } from "./builtins.mjs";
6
- import { a as performance_host_exports } from "./performance-host-BJT6scGF.mjs";
6
+ import { a as performance_host_exports } from "./performance-host-CcDJjjVA.mjs";
7
7
  import { createRequire } from "node:module";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import { Context } from "@deepseek-ai/cordis";
@@ -19,6 +19,7 @@ import jobRemote from "@deepseek-ai/dsh-api-job-controller/remote";
19
19
  import settingsRemote from "@deepseek-ai/dsh-api-settings-controller/remote";
20
20
  import userQuestionsRemote from "@deepseek-ai/dsh-user-questions/remote";
21
21
  import fileUploadsRemote from "@deepseek-ai/dsh-client-file-upload/remote";
22
+ import workspaceFilesRemote from "@deepseek-ai/dsh-api-workspace-files/remote";
22
23
  import SessionController from "@deepseek-ai/dsh-api-session-controller";
23
24
  import { apply, inject } from "@deepseek-ai/dsh-api-remotes";
24
25
  import SettingsController from "@deepseek-ai/dsh-api-settings-controller";
@@ -171,7 +172,7 @@ function remoteNotDispatched() {
171
172
  * semantic contract as `src/runtime/direct/config-direct.ts`; no Remote-only
172
173
  * Config semantics and no Direct fallback exist.
173
174
  *
174
- * Published mapping (see docs/client-server-migration.md):
175
+ * Published mapping (see docs/architecture/host-client.md):
175
176
  *
176
177
  * ```text
177
178
  * TUI settings / footer trust / custom items / providers / permissions /
@@ -213,6 +214,7 @@ const PROVIDER_SETTINGS_NS = "llm-pi-ai";
213
214
  const PERMISSION_SETTINGS_NS = "permission";
214
215
  const PRESET_REGISTRY_NS = "agent-preset-registry";
215
216
  const SUBAGENT_SETTINGS_NS = "subagent-model-selection-settings";
217
+ const VISUAL_TOOLS_NS = "pi-tui-visual-tools";
216
218
  /** The provider route grammar the adapter-owned profile-slot rule enforces
217
219
  * (same rule the Direct adapter applies). */
218
220
  const PROVIDER_ROUTE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
@@ -252,20 +254,6 @@ function detachedValue(value) {
252
254
  return;
253
255
  }
254
256
  }
255
- /** Read the `llm-pi-ai` section's `providers` dict detached (the settings-only
256
- * fallback the Direct adapter applies when the directory is unavailable). */
257
- function piAiProvidersOf(section) {
258
- const record = plainRecord(section);
259
- if (record === void 0) return void 0;
260
- const providers = plainRecord(record.providers);
261
- if (providers === void 0) return void 0;
262
- const out = {};
263
- for (const [route, profile] of Object.entries(providers)) {
264
- const entry = plainRecord(profile);
265
- out[route] = entry === void 0 ? profile : { ...typeof entry.apiKeyEnv === "string" ? { apiKeyEnv: entry.apiKeyEnv } : {} };
266
- }
267
- return out;
268
- }
269
257
  /** Bounded re-describe attempts when an invalidation races a read. 5 is
270
258
  * enough for a document/adapter/catalog event burst; a persistent storm
271
259
  * fails loudly (SupersededReadError) instead of committing a stale result. */
@@ -405,6 +393,11 @@ var RemoteConfigMirror = class {
405
393
  providers() {
406
394
  return this.snapshot?.providers;
407
395
  }
396
+ /** The provider-directory read failure of the last committed snapshot, if
397
+ * the directory read failed. */
398
+ providersFailure() {
399
+ return this.snapshot?.providersFailure;
400
+ }
408
401
  permissionPresetNames() {
409
402
  return this.snapshot?.permissionPresetNames ?? [];
410
403
  }
@@ -486,7 +479,8 @@ var RemoteConfigMirror = class {
486
479
  invalidation,
487
480
  namespaces,
488
481
  settingsFailure,
489
- providers: providersResult.ok && Array.isArray(providersResult.value) ? providersResult.value.map(copyProviderEntry) : void 0,
482
+ providers: providersResult.ok && Array.isArray(providersResult.value) ? providersResult.value.map(copyProviderEntry) : this.snapshot?.providers,
483
+ providersFailure: providersResult.ok ? void 0 : remoteFailureMessage(providersResult.error),
490
484
  permissionPresetNames: catalogResult.ok && Array.isArray(catalogResult.value?.options) ? catalogResult.value.options.flatMap((option) => typeof option?.value === "string" ? [option.value] : []) : [],
491
485
  permissionDefaultPreset: catalogResult.ok && typeof catalogResult.value?.defaultPreset === "string" ? catalogResult.value.defaultPreset : void 0,
492
486
  presetRosterDefault: presetsResult.ok && Array.isArray(presetsResult.value?.presets) ? presetsResult.value.presets.find((preset) => preset.isDefault === true)?.id : void 0
@@ -805,28 +799,122 @@ var RemoteProviderProfileConfig = class {
805
799
  * over its per-entry sections when present, the settings-only fallback
806
800
  * otherwise (the same merge the Direct adapter wires). */
807
801
  listCredentialOptions() {
802
+ if (this.mirror.providersFailure() !== void 0 || this.mirror.readiness() !== "ready") return providerOptionsFor([], () => void 0).map((option) => remoteCredentialOptionOf(option));
808
803
  const directory = this.mirror.providers();
809
- if (directory !== void 0) return providerOptionsFor(directory, (ns) => this.mirror.namespace(ns)?.value).map((option) => remoteCredentialOptionOf(option));
810
- return credentialOptionsFor(piAiProvidersOf(this.mirror.namespace(PROVIDER_SETTINGS_NS)?.value)).map((option, index) => {
811
- const route = index === 0 ? "deepseek-official" : option.label;
812
- return {
813
- ...option,
814
- route,
804
+ if (directory !== void 0) return providerOptionsFor(directory, (entry) => providerProfileProjectionOf(this.remoteProfileOf(entry))).map((option) => remoteCredentialOptionOf(option));
805
+ return this.settingsOnlyCatalog().options;
806
+ }
807
+ /**
808
+ * The ONE provider snapshot the Models page reads. The Remote mirror is
809
+ * already ONE committed snapshot (one settings describe + one directory
810
+ * read per generation), so the projection reads the mirror and never
811
+ * dispatches a second wire fetch. A directory the mirror could not read
812
+ * degrades to the settings-only fallback (the same fail-soft rule the
813
+ * Direct adapter applies).
814
+ */
815
+ readCatalog() {
816
+ const directory = this.mirror.providers();
817
+ const failure = this.mirror.providersFailure();
818
+ if (failure !== void 0) return {
819
+ options: [],
820
+ profiles: [],
821
+ failure: `the provider directory could not be read: ${failure}`
822
+ };
823
+ if (directory === void 0) return this.settingsOnlyCatalog();
824
+ const rawProfiles = /* @__PURE__ */ new Map();
825
+ for (const entry of directory) {
826
+ if (entry.provider.length === 0 || entry.settingsNs.length === 0) continue;
827
+ rawProfiles.set(entry.provider, this.remoteProfileOf(entry));
828
+ }
829
+ const options = providerOptionsFor(directory, (entry) => providerProfileProjectionOf(this.remoteProfileOf(entry))).map((option) => remoteCredentialOptionOf(option));
830
+ const profiles = options.map((option) => {
831
+ const raw = rawProfiles.get(option.route);
832
+ if (option.route === "deepseek-official" && raw === void 0) return {
833
+ route: option.route,
815
834
  configured: true,
816
- declared: false,
817
- namesCredential: true,
818
- group: "configured",
819
- canProvisionProfile: canProvisionKeylessProfile(PROVIDER_SETTINGS_NS, ["providers", route], route)
835
+ displayName: option.label,
836
+ models: []
820
837
  };
838
+ return remoteProviderFactsOf(option.route, option.label, raw);
821
839
  });
840
+ const readiness = this.mirror.readiness();
841
+ if (readiness === "unavailable") return {
842
+ options: [],
843
+ profiles: [],
844
+ failure: "the configuration mirror is unavailable"
845
+ };
846
+ if (readiness === "stale") return {
847
+ options,
848
+ profiles,
849
+ stale: true
850
+ };
851
+ return {
852
+ options,
853
+ profiles
854
+ };
855
+ }
856
+ /**
857
+ * The settings-only fallback (no mirrored directory): the conventional
858
+ * llm-pi-ai `providers` slot is the only profile location. Every profile
859
+ * route stays a provider — a keyless profile is still a CONFIGURED
860
+ * provider; the presence of a key is not the membership authority.
861
+ */
862
+ settingsOnlyCatalog() {
863
+ const section = this.mirror.namespace(PROVIDER_SETTINGS_NS)?.value;
864
+ const declared = plainRecord(plainRecord(section)?.providers);
865
+ const entries = declared === void 0 ? [] : Object.keys(declared).map((route) => ({
866
+ provider: route,
867
+ displayName: route,
868
+ settingsNs: PROVIDER_SETTINGS_NS,
869
+ settingsPath: ["providers", route]
870
+ }));
871
+ const options = providerOptionsFor(entries, (entry) => providerProfileProjectionOf(declared?.[entry.provider])).map((option) => remoteCredentialOptionOf(option));
872
+ return {
873
+ options,
874
+ profiles: options.map((option) => {
875
+ const raw = declared?.[option.route];
876
+ if (option.route === "deepseek-official" && raw === void 0) return {
877
+ route: option.route,
878
+ configured: true,
879
+ displayName: option.label,
880
+ models: []
881
+ };
882
+ return remoteProviderFactsOf(option.route, option.label, raw);
883
+ })
884
+ };
885
+ }
886
+ /** One directory entry's profile value, read from the mirror's ONE
887
+ * committed snapshot (no wire dispatch). */
888
+ remoteProfileOf(entry) {
889
+ const section = this.mirror.namespace(entry.settingsNs)?.value;
890
+ return entry.settingsPath.length === 0 ? section : getPath(section, entry.settingsPath);
891
+ }
892
+ readProfile(route) {
893
+ const directory = this.mirror.providers();
894
+ if (directory !== void 0) {
895
+ const entry = directory.find((candidate) => candidate.provider === route);
896
+ if (entry !== void 0) {
897
+ const section = this.mirror.namespace(entry.settingsNs)?.value;
898
+ const profile = entry.settingsPath.length === 0 ? section : getPath(section, entry.settingsPath);
899
+ return remoteProviderFactsOf(route, entry.displayName, profile);
900
+ }
901
+ }
902
+ const section = this.mirror.namespace(PROVIDER_SETTINGS_NS)?.value;
903
+ return remoteProviderFactsOf(route, route, section?.providers?.[route]);
904
+ }
905
+ configGuide() {
906
+ return {};
822
907
  }
823
908
  async writeProfile(route, profile) {
824
909
  if (!canProvisionKeylessProfile(PROVIDER_SETTINGS_NS, ["providers", route], route)) throw new Error("invalid provider route");
910
+ await this.mirror.ensureCurrent();
911
+ const descriptor = this.mirror.namespace(PROVIDER_SETTINGS_NS);
912
+ if (getPath(descriptor?.value, ["providers", route]) !== void 0) throw new Error(`provider route "${route}" already exists`);
825
913
  await this.mirror.mutate(PROVIDER_SETTINGS_NS, [{
826
914
  op: "set",
827
915
  path: ["providers", route],
828
916
  value: profile
829
- }]);
917
+ }], descriptor?.revision);
830
918
  }
831
919
  async writeKeylessProfile(route) {
832
920
  if (route === "deepseek-official") return {
@@ -837,11 +925,16 @@ var RemoteProviderProfileConfig = class {
837
925
  await this.mirror.ensureCurrent();
838
926
  const directory = this.mirror.providers();
839
927
  if (directory === void 0) {
928
+ const descriptor = this.mirror.namespace(PROVIDER_SETTINGS_NS);
929
+ if (getPath(descriptor?.value, ["providers", route]) !== void 0) return {
930
+ kind: "skipped",
931
+ reason: `provider route "${route}" already has a profile`
932
+ };
840
933
  await this.mirror.mutate(PROVIDER_SETTINGS_NS, [{
841
934
  op: "set",
842
935
  path: ["providers", route],
843
936
  value: {}
844
- }]);
937
+ }], descriptor?.revision);
845
938
  return { kind: "written" };
846
939
  }
847
940
  const entry = directory.find((candidate) => candidate.provider === route);
@@ -854,11 +947,16 @@ var RemoteProviderProfileConfig = class {
854
947
  kind: "skipped",
855
948
  reason: `hostile or malformed directory entry for ${route}`
856
949
  };
950
+ const descriptor = this.mirror.namespace(entry.settingsNs);
951
+ if (getPath(descriptor?.value, path) !== void 0) return {
952
+ kind: "skipped",
953
+ reason: `provider route "${route}" already has a profile`
954
+ };
857
955
  await this.mirror.mutate(entry.settingsNs, [{
858
956
  op: "set",
859
957
  path,
860
958
  value: {}
861
- }]);
959
+ }], descriptor?.revision);
862
960
  return { kind: "written" };
863
961
  }
864
962
  };
@@ -1107,6 +1205,46 @@ function assertOfficialSubagentRoutes(routes) {
1107
1205
  }
1108
1206
  }
1109
1207
  /**
1208
+ * The Remote visual-tools switch: the mirrored `pi-tui-visual-tools` form
1209
+ * section over the official generated settings remote. The write is a
1210
+ * revision-checked path mutation and the mirror's post-settlement refresh is
1211
+ * the only new authority — the mutate reply is never trusted as the new value.
1212
+ *
1213
+ * The Host registry itself is not observable on the wire, so `applied` stays
1214
+ * `undefined`: the UI may present the committed configuration but must not
1215
+ * claim the runtime registration took effect.
1216
+ */
1217
+ var RemoteVisualToolsConfig = class {
1218
+ mirror;
1219
+ constructor(mirror) {
1220
+ this.mirror = mirror;
1221
+ }
1222
+ read() {
1223
+ const view = this.mirror.namespace(VISUAL_TOOLS_NS);
1224
+ if (view === void 0) return void 0;
1225
+ const enabled = plainRecord(view.value)?.enabled;
1226
+ if (typeof enabled !== "boolean") return void 0;
1227
+ const revision = view.revision;
1228
+ if (typeof revision !== "number") return void 0;
1229
+ return {
1230
+ enabled,
1231
+ revision,
1232
+ userOverridden: plainRecord(view.user)?.enabled !== void 0,
1233
+ applied: void 0
1234
+ };
1235
+ }
1236
+ async setEnabled(enabled, expectedRevision) {
1237
+ const view = this.mirror.namespace(VISUAL_TOOLS_NS);
1238
+ if (view === void 0) throw new Error(`settings namespace "${VISUAL_TOOLS_NS}" is not available in this deployment`);
1239
+ if (view.value === void 0) throw new Error(`settings namespace "${VISUAL_TOOLS_NS}" exposes no form projection`);
1240
+ await this.mirror.mutate(VISUAL_TOOLS_NS, [{
1241
+ op: "set",
1242
+ path: ["enabled"],
1243
+ value: enabled
1244
+ }], expectedRevision, "record");
1245
+ }
1246
+ };
1247
+ /**
1110
1248
  * The Remote config port over ONE Client runtime source. The mirror is
1111
1249
  * created first (its invalidation listeners are installed in its
1112
1250
  * constructor, before the first describe), then every sub-domain projects
@@ -1121,9 +1259,12 @@ var RemoteConfigPort = class {
1121
1259
  providers;
1122
1260
  credentials;
1123
1261
  authorization;
1262
+ account;
1124
1263
  permissions;
1125
1264
  presetDefault;
1126
1265
  subagentModelSelection;
1266
+ web;
1267
+ visualTools;
1127
1268
  /** `undefined` while the `tui-app` namespace is absent from the mirror
1128
1269
  * (the port's documented absence contract). */
1129
1270
  get tuiSettings() {
@@ -1143,9 +1284,12 @@ var RemoteConfigPort = class {
1143
1284
  this.credentialConfig = new RemoteCredentialConfig(bound.remote.credentials, on, source.connection.generation);
1144
1285
  this.credentials = this.credentialConfig;
1145
1286
  this.authorization = new RemoteAuthorizationConfig();
1287
+ this.account = new RemoteUnsupportedAccountConfig();
1146
1288
  this.permissions = new RemotePermissionConfig(this.mirror, source.remote.commands);
1147
1289
  this.presetDefault = new RemotePresetDefaultConfig(this.mirror);
1148
1290
  this.subagentModelSelection = new RemoteSubagentModelSelectionConfig(this.mirror);
1291
+ this.visualTools = new RemoteVisualToolsConfig(this.mirror);
1292
+ this.web = new RemoteUnsupportedWebProviderConfig();
1149
1293
  }
1150
1294
  /** Commit one fresh mirror snapshot (or leave the last-known value). A
1151
1295
  * failure is RECORDED as well as thrown, so `readiness()` stays truthful
@@ -1185,6 +1329,105 @@ var RemoteConfigPort = class {
1185
1329
  this.credentialConfig.dispose();
1186
1330
  }
1187
1331
  };
1332
+ /**
1333
+ * The Remote backend's Web provider sub-domain: INTENTIONALLY unsupported in
1334
+ * S2. The wire carries no web-provider selection read (the `settings` mirror
1335
+ * exposes plugin forms for the CLIENT-owned surfaces only) and no write RPC for
1336
+ * a Host namespace, so the section is presented as unsupported on this backend
1337
+ * and every write fails closed instead of naming a Host settings namespace or
1338
+ * reporting a success it cannot observe. Remote web-provider support is owned
1339
+ * by a later stage (S3/S4) together with the Host generated-settings parity.
1340
+ */
1341
+ var RemoteUnsupportedWebProviderConfig = class {
1342
+ available() {
1343
+ return false;
1344
+ }
1345
+ async read() {}
1346
+ refuse() {
1347
+ throw new Error("web provider settings are not supported on this backend");
1348
+ }
1349
+ async setSearchProvider() {
1350
+ this.refuse();
1351
+ }
1352
+ async setFetchProvider() {
1353
+ this.refuse();
1354
+ }
1355
+ async setSearchApiCount() {
1356
+ this.refuse();
1357
+ }
1358
+ async setSendOriginalQuestion() {
1359
+ this.refuse();
1360
+ }
1361
+ async setSearchApiBaseURL() {
1362
+ this.refuse();
1363
+ }
1364
+ };
1365
+ /** Detached provider facts for the Remote Models detail (the same semantic
1366
+ * projection as Direct's adapter). */
1367
+ function remoteProviderFactsOf(route, fallbackLabel, profile) {
1368
+ if (typeof profile !== "object" || profile === null || Array.isArray(profile)) return {
1369
+ route,
1370
+ configured: profile !== void 0,
1371
+ displayName: fallbackLabel,
1372
+ models: []
1373
+ };
1374
+ const record = profile;
1375
+ const models = Array.isArray(record.models) ? record.models.flatMap((entry) => {
1376
+ if (typeof entry === "string") return [entry];
1377
+ if (typeof entry === "object" && entry !== null && typeof entry.id === "string") return [entry.id];
1378
+ return [];
1379
+ }) : [];
1380
+ return {
1381
+ route,
1382
+ configured: true,
1383
+ ...typeof record.api === "string" && record.api !== "" ? { api: record.api } : {},
1384
+ ...typeof record.baseURL === "string" && record.baseURL !== "" ? { baseURL: record.baseURL } : {},
1385
+ displayName: typeof record.displayName === "string" && record.displayName !== "" ? record.displayName : fallbackLabel,
1386
+ models,
1387
+ ...typeof record.apiKeyEnv === "string" && record.apiKeyEnv !== "" ? { apiKeyEnv: record.apiKeyEnv } : {}
1388
+ };
1389
+ }
1390
+ /**
1391
+ * The Remote backend's DeepSeek Account sub-domain: INTENTIONALLY unsupported
1392
+ * for this stage. The rc.2 wire publishes no account state/attempt/profile/
1393
+ * balance/sign-out RPC, and the browser callback origin is a Host listener
1394
+ * fact that must never be synthesized by a Client. Every operation fails
1395
+ * closed; the Account page states the backend limitation instead of faking a
1396
+ * sign-in or a signed-out state.
1397
+ */
1398
+ var RemoteUnsupportedAccountConfig = class {
1399
+ available() {
1400
+ return false;
1401
+ }
1402
+ refuse() {
1403
+ throw new Error("DeepSeek Account is not supported on this backend");
1404
+ }
1405
+ async getState() {
1406
+ this.refuse();
1407
+ }
1408
+ async getProfile(_client) {
1409
+ this.refuse();
1410
+ }
1411
+ async getBalance(_client) {
1412
+ this.refuse();
1413
+ }
1414
+ watch(_signal) {
1415
+ return (async function* empty() {})();
1416
+ }
1417
+ getCallbackOrigin() {}
1418
+ async startSignIn(_client) {
1419
+ this.refuse();
1420
+ }
1421
+ async cancelSignIn(_id) {
1422
+ this.refuse();
1423
+ }
1424
+ async signOut(_client) {
1425
+ this.refuse();
1426
+ }
1427
+ hasRunningAccountTasks() {
1428
+ return false;
1429
+ }
1430
+ };
1188
1431
  //#endregion
1189
1432
  //#region src/runtime/remote/session-archive-remote.ts
1190
1433
  /** The official absolute export path (`dsh-session-log-export` routes). */
@@ -1347,1093 +1590,1153 @@ const PI_TUI_CLIENT_CONTRIBUTION = {
1347
1590
  descriptors: [PI_TUI_FILE_REFERENCES_LIST, PI_TUI_TERMINAL_PROGRESS_WATCH]
1348
1591
  };
1349
1592
  //#endregion
1350
- //#region src/runtime/remote/pi-tui-file-reference-host-bridge.ts
1593
+ //#region src/app/remote/dispose-cause.ts
1351
1594
  /**
1352
- * The Remote Host-side bridge for the private `piTuiFileReferences` endpoint
1353
- * (TS8-HF1): a CONSTRUCTION/ADAPTATION seam ONLY. It binds the private Remote
1354
- * method to the SAME Host-scoped completion authority the Direct adapter uses
1355
- * (`runtime/direct/host-file-augmentation-direct.ts` + the Direct Host
1356
- * discovery driver) and returns a transport-neutral `list` runtime.
1357
- *
1358
- * It owns NO Cordis service, NO Typert registration and NO lifecycle policy —
1359
- * the Cordis service, its Typert contribution registration and its disposal
1360
- * remain with the Remote Host composition
1361
- * (`app/remote/pi-tui-file-reference-host.ts`). The dependency direction is
1362
- * therefore `app/remote/** -> runtime/remote/** -> runtime/direct/**`, never
1363
- * `app/remote/** -> runtime/direct/**`.
1595
+ * Transport-neutral disposal failure chaining for the Remote composition.
1364
1596
  *
1365
- * The bridge lives in `runtime/remote/**` because that layer may consume the
1366
- * Direct Host implementation; the composition layer may not.
1597
+ * The helper is shared by the Host composition, the official Client runtime,
1598
+ * the Client UI subtree and the application aggregate. It deliberately lives
1599
+ * beside them (not inside `host-runtime.ts`) so a Client-only process entry can
1600
+ * reuse it without importing a Host-only value graph.
1367
1601
  *
1368
- * @module @xmoon76/dsh-pi-tui/runtime/remote/pi-tui-file-reference-host-bridge
1602
+ * @module app/remote/dispose-cause
1369
1603
  */
1370
1604
  /**
1371
- * Bind the private Remote method to the Host-scoped completion authority.
1372
- * The Host finder is resolved ONCE for the runtime's lifetime (it is a pure
1373
- * PATH pin; a later PATH change is not a Host completion fact).
1605
+ * Attach one secondary failure to `failure`'s cause chain without losing an
1606
+ * existing cause: when the failure already carries a cause, both aggregate
1607
+ * into a single `AggregateError`. A `undefined` secondary is a no-op.
1374
1608
  */
1375
- function createPiTuiHostFileReferenceRuntime(deps) {
1376
- const driver = new DirectHostDiscoveryDriver(deps.fdPath);
1377
- const environment = hostPathQueryEnvironment();
1378
- return { async list(sessionId, query, signal) {
1379
- signal.throwIfAborted();
1380
- const agent = deps.agentFor(sessionId);
1381
- if (agent === void 0) return {
1382
- kind: "unavailable",
1383
- reason: "the requested Session has no live Host Agent"
1384
- };
1385
- return await listPiTuiHostFileReferences(agent, query, signal, {
1386
- official: deps.official(),
1387
- driver,
1388
- environment
1389
- });
1390
- } };
1609
+ function mergeCause(failure, secondary) {
1610
+ if (secondary === void 0) return failure;
1611
+ const existingCause = failure.cause;
1612
+ failure.cause = existingCause === void 0 ? secondary : new AggregateError([existingCause, secondary], "remote composition: aggregated failure causes");
1613
+ return failure;
1391
1614
  }
1392
1615
  //#endregion
1393
- //#region src/app/remote/pi-tui-file-reference-host.ts
1616
+ //#region src/app/remote/client-runtime.ts
1394
1617
  /**
1395
- * The Host endpoint of the private augmentation. One instance per Remote Host
1396
- * composition; the descriptor leaves with the owning fiber.
1618
+ * Experimental official Client runtime composition (M3-1).
1619
+ *
1620
+ * Owns the official Client bundle capture, the Client `Context`, the exact
1621
+ * plugin mount order, the explicit `/remote` contributions, initial
1622
+ * readiness, and reverse disposal.
1623
+ * It does not assemble the TUI semantic `Backend`.
1624
+ *
1625
+ * rc.2 publishes the six required Client plugin entries as Web
1626
+ * module-loader bundles: each bundle registers through
1627
+ * `window.__ModuleLoader__.load(...)`, which plain Node dynamic imports
1628
+ * cannot consume directly. The scoped loader below is therefore a packaging
1629
+ * adapter only: it is installed around exactly the six dynamic imports,
1630
+ * rejects unknown/duplicate/missing registrations, and restores the previous
1631
+ * process state before any Client plugin runs.
1632
+ *
1633
+ * Because ESM evaluates each bundle at most once per process, the capture is
1634
+ * a process-wide single-flight: the captured package module exports are
1635
+ * reused for every Client `Context`, while each Context still gets its own
1636
+ * independent Connection, Gateway, Remote namespaces, Sessions, Jobs,
1637
+ * subscriptions, and lifetimes. Captured bundle factories are never re-run.
1638
+ *
1639
+ * @module app/remote/client-runtime
1397
1640
  */
1398
- var PiTuiFileReferenceHostService = class extends TypertRemoteService {
1399
- /** The Typert registry owns the explicit invocation definitions. */
1400
- static inject = ["typert"];
1401
- runtime;
1402
- /**
1403
- * @param ctx - the Host context this row is mounted in.
1404
- * @param deps - the narrow Host facts the composition resolved.
1405
- */
1406
- constructor(ctx, deps) {
1407
- super(ctx, PI_TUI_FILE_REFERENCES_NAMESPACE);
1408
- this.runtime = createPiTuiHostFileReferenceRuntime(deps);
1409
- }
1410
- /**
1411
- * The private Remote method (`piTuiFileReferences/list`, see
1412
- * `pi-tui-file-reference-contract.ts`). Cancellation outranks every outcome.
1413
- */
1414
- list(sessionId, query, signal) {
1415
- return this.runtime.list(sessionId, query, signal);
1641
+ /**
1642
+ * The exact allowlist: dynamic import specifier paired with its expected
1643
+ * `__ModuleLoader__` registration id (§9.1). Kept distinct by design.
1644
+ */
1645
+ const OFFICIAL_CLIENT_BUNDLES = [
1646
+ {
1647
+ specifier: "@deepseek-ai/dsh-typert-registry/client",
1648
+ id: "@deepseek-ai/dsh-typert-registry"
1649
+ },
1650
+ {
1651
+ specifier: "@deepseek-ai/dsh-client-connection/client",
1652
+ id: "@deepseek-ai/dsh-client-connection"
1653
+ },
1654
+ {
1655
+ specifier: "@deepseek-ai/dsh-api-gateway/client",
1656
+ id: "@deepseek-ai/dsh-api-gateway"
1657
+ },
1658
+ {
1659
+ specifier: "@deepseek-ai/dsh-client-file-upload/client",
1660
+ id: "@deepseek-ai/dsh-client-file-upload"
1661
+ },
1662
+ {
1663
+ specifier: "@deepseek-ai/dsh-api-session-controller/client",
1664
+ id: "@deepseek-ai/dsh-api-session-controller"
1665
+ },
1666
+ {
1667
+ specifier: "@deepseek-ai/dsh-api-job-controller/client",
1668
+ id: "@deepseek-ai/dsh-api-job-controller"
1416
1669
  }
1417
- };
1418
- //#endregion
1419
- //#region src/app/remote/terminal-progress-host.ts
1420
- /** The structural `turn/start` / `turn/end` payload read (never a guessed shape). */
1421
- function turnOf(data) {
1422
- const turn = data?.turn;
1423
- return typeof turn === "number" ? turn : void 0;
1424
- }
1425
- /** The merge-extensible `turn/end.reason.kind` discriminant. */
1426
- function reasonKindOf(data) {
1427
- const reason = data?.reason;
1428
- return typeof reason?.kind === "string" ? reason.kind : void 0;
1670
+ ];
1671
+ /** Expected registration ids, in dependency order. */
1672
+ const EXPECTED_REGISTRATION_IDS = OFFICIAL_CLIENT_BUNDLES.map((bundle) => bundle.id);
1673
+ /** Process-wide single-flight capture; module code evaluates once per process. */
1674
+ let officialClientModulesPromise;
1675
+ /**
1676
+ * Load the six official Client bundles once per process and freeze their
1677
+ * captured module exports. Concurrent callers share the same promise.
1678
+ *
1679
+ * DSH 0.2.1-rc.1 and later select the `./client` entry by condition: `@deepseek-ai/dsh-typert-registry`,
1680
+ * `@deepseek-ai/dsh-client-connection` and `@deepseek-ai/dsh-api-gateway` publish
1681
+ * a standalone Node ESM variant (which never touches `window.__ModuleLoader__`),
1682
+ * while the remaining three publish the browser loader factory. Both channels
1683
+ * feed one table, so the registration order below still holds for every
1684
+ * `/client` dependency.
1685
+ *
1686
+ * Failure semantics: a rejected capture stays cached (fail fast, no silent
1687
+ * retry). ESM evaluates each bundle at most once per process, so bundles
1688
+ * already imported during a failed capture can never re-register — a retry
1689
+ * would deterministically fail the completeness check anyway.
1690
+ */
1691
+ function loadOfficialClientModulesOnce() {
1692
+ officialClientModulesPromise ??= captureOfficialClientModules();
1693
+ return officialClientModulesPromise;
1429
1694
  }
1430
1695
  /**
1431
- * Frames one subscriber may fall behind by before the stream is failed instead
1432
- * of silently losing an edge. A real run produces a handful of transitions, so
1433
- * only a consumer that stopped draining can reach it.
1696
+ * Exact scoped loader capture: install a temporary `window.__ModuleLoader__`,
1697
+ * dynamic-import the six bundles in dependency order, admit each bundle from
1698
+ * exactly the channel the published `./client` entry selected (loader
1699
+ * registration or standalone Node module — see {@link captureOfficialClientModules}),
1700
+ * freeze the module-export table, and restore the previous process state in
1701
+ * `finally` — before any Client Context exists.
1434
1702
  */
1435
- const SUBSCRIBER_QUEUE_LIMIT = 64;
1436
1703
  /**
1437
- * One subscriber's ordered frame queue. The Host ALWAYS mutates the record
1438
- * before pushing, so a queue can never observe a frame the record has not
1439
- * committed, and `close()` is idempotent.
1440
- *
1441
- * An overflowing queue FAILS the reader: dropping frames and continuing would
1442
- * let a stream report a settlement whose running edge it lost (plan §6.5).
1704
+ * The exact scoped loader admission rules (module-internal seam, exercised by
1705
+ * the L5 loader-exactness test): reject an unknown registration id, a
1706
+ * duplicate id, a non-function factory, and a `/client` dependency requested
1707
+ * before its dependency-order capture; admit a directly imported Node bundle
1708
+ * for an id the loader did not register; report missing expected ids.
1443
1709
  */
1444
- var FrameQueue = class {
1445
- frames = [];
1446
- wake;
1447
- closed = false;
1448
- failure;
1449
- limit = SUBSCRIBER_QUEUE_LIMIT;
1450
- push(frame) {
1451
- if (this.closed || this.failure !== void 0) return;
1452
- if (this.frames.length >= this.limit) {
1453
- this.failure = /* @__PURE__ */ new Error("piTuiTerminalProgress: the subscriber queue overflowed");
1454
- this.frames.length = 0;
1455
- const wake = this.wake;
1456
- this.wake = void 0;
1457
- wake?.();
1458
- return;
1459
- }
1460
- this.frames.push(frame);
1461
- const wake = this.wake;
1462
- this.wake = void 0;
1463
- wake?.();
1464
- }
1710
+ function createScopedClientModuleLoader(expectedIds) {
1711
+ const nodeRequire = createRequire(import.meta.url);
1712
+ const registrations = /* @__PURE__ */ new Map();
1713
+ const captured = /* @__PURE__ */ new Map();
1714
+ const requireModule = (specifier) => {
1715
+ if (specifier.endsWith("/client")) {
1716
+ const id = specifier.slice(0, -7);
1717
+ const module = captured.get(id);
1718
+ if (module === void 0) throw new Error(`official Client module ${specifier} was requested before ${id} was captured`);
1719
+ return module;
1720
+ }
1721
+ return nodeRequire(specifier);
1722
+ };
1723
+ const load = ({ id, factory }) => {
1724
+ if (!expectedIds.includes(id)) throw new Error(`official Client bundle loader received an unexpected registration id: ${String(id)}`);
1725
+ if (registrations.has(id)) throw new Error(`official Client bundle ${id} registered twice`);
1726
+ if (typeof factory !== "function") throw new Error(`official Client bundle ${id} registered a non-function factory`);
1727
+ registrations.set(id, factory);
1728
+ captured.set(id, factory(requireModule));
1729
+ };
1465
1730
  /**
1466
- * End the consumer's read AFTER every frame already committed to it: a
1467
- * disposal publishes the retired interval BEFORE it ends the watchers, and a
1468
- * committed terminal fact must never be dropped in flight.
1731
+ * Admit one directly imported bundle whose `./client` entry did not register
1732
+ * through the loader shim (the standalone Node variant). The module joins the
1733
+ * SAME table {@link requireModule} resolves `/client` dependencies from, so a
1734
+ * registering bundle can still depend on a Node-variant one. A bundle that did
1735
+ * register is left to its own registration: the browser factory result is the
1736
+ * authoritative module for that id.
1737
+ * @param id - the bundle's registration id.
1738
+ * @param module - the imported module namespace.
1739
+ * @throws when the id is unexpected or already admitted by a direct import.
1469
1740
  */
1470
- close() {
1471
- if (this.closed) return;
1472
- this.closed = true;
1473
- const wake = this.wake;
1474
- this.wake = void 0;
1475
- wake?.();
1476
- }
1477
- async next() {
1478
- for (;;) {
1479
- const frame = this.frames.shift();
1480
- if (frame !== void 0) return {
1481
- value: frame,
1482
- done: false
1483
- };
1484
- if (this.failure !== void 0) throw this.failure;
1485
- if (this.closed) return {
1486
- value: void 0,
1487
- done: true
1488
- };
1489
- await new Promise((resolve) => {
1490
- this.wake = resolve;
1491
- });
1741
+ const acceptImported = (id, module) => {
1742
+ if (!expectedIds.includes(id)) throw new Error(`official Client bundle import produced an unexpected id: ${String(id)}`);
1743
+ if (registrations.has(id)) return;
1744
+ if (captured.has(id)) throw new Error(`official Client bundle ${id} was imported as a Node module twice`);
1745
+ captured.set(id, module);
1746
+ };
1747
+ return {
1748
+ load,
1749
+ requireModule,
1750
+ registeredIds: () => [...registrations.keys()],
1751
+ acceptImported,
1752
+ assertComplete() {
1753
+ 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`);
1754
+ }
1755
+ };
1756
+ }
1757
+ /**
1758
+ * Install the temporary `window.__ModuleLoader__` shim around exactly the six
1759
+ * bundle imports, preserving the exact previous process state: when
1760
+ * `globalThis.window` is absent, only the minimal temporary object is created
1761
+ * and deleted again; when a `window` own property already exists (including a
1762
+ * property whose value is `undefined`/`null`, and accessor descriptors), its
1763
+ * exact property descriptor is restored, and any pre-existing
1764
+ * `__ModuleLoader__` property descriptor on an existing window object is
1765
+ * preserved and restored verbatim.
1766
+ * @returns the restore function; it must run before any Client plugin executes
1767
+ * (and on every failure path).
1768
+ */
1769
+ function installScopedModuleLoaderShim(load) {
1770
+ const globalScope = globalThis;
1771
+ const previousWindowDescriptor = Object.getOwnPropertyDescriptor(globalScope, "window");
1772
+ const previousWindowValue = previousWindowDescriptor?.value;
1773
+ const usableExistingWindow = typeof previousWindowValue === "object" && previousWindowValue !== null || typeof previousWindowValue === "function";
1774
+ let previousLoaderDescriptor;
1775
+ const install = () => {
1776
+ if (usableExistingWindow) {
1777
+ const existingWindow = previousWindowValue;
1778
+ previousLoaderDescriptor = Object.getOwnPropertyDescriptor(existingWindow, "__ModuleLoader__");
1779
+ existingWindow.__ModuleLoader__ = { load };
1780
+ } else Object.defineProperty(globalScope, "window", {
1781
+ configurable: true,
1782
+ writable: true,
1783
+ value: { __ModuleLoader__: { load } }
1784
+ });
1785
+ };
1786
+ const restore = () => {
1787
+ if (previousWindowDescriptor === void 0) {
1788
+ delete globalScope.window;
1789
+ return;
1790
+ }
1791
+ Object.defineProperty(globalScope, "window", previousWindowDescriptor);
1792
+ if (usableExistingWindow) {
1793
+ const existingWindow = previousWindowValue;
1794
+ if (previousLoaderDescriptor === void 0) delete existingWindow.__ModuleLoader__;
1795
+ else Object.defineProperty(existingWindow, "__ModuleLoader__", previousLoaderDescriptor);
1492
1796
  }
1797
+ };
1798
+ install();
1799
+ return restore;
1800
+ }
1801
+ async function captureOfficialClientModules() {
1802
+ const loader = createScopedClientModuleLoader(EXPECTED_REGISTRATION_IDS);
1803
+ const restoreShim = installScopedModuleLoaderShim(loader.load);
1804
+ try {
1805
+ for (const bundle of OFFICIAL_CLIENT_BUNDLES) loader.acceptImported(bundle.id, await import(bundle.specifier));
1806
+ loader.assertComplete();
1807
+ } finally {
1808
+ restoreShim();
1493
1809
  }
1494
- };
1810
+ const captured = /* @__PURE__ */ new Map();
1811
+ for (const id of EXPECTED_REGISTRATION_IDS) captured.set(id, loader.requireModule(`${id}/client`));
1812
+ return freezeOfficialClientModules(captured);
1813
+ }
1814
+ function freezeOfficialClientModules(captured) {
1815
+ const modules = {
1816
+ typert: captured.get("@deepseek-ai/dsh-typert-registry"),
1817
+ connection: captured.get("@deepseek-ai/dsh-client-connection"),
1818
+ gateway: captured.get("@deepseek-ai/dsh-api-gateway"),
1819
+ fileUpload: captured.get("@deepseek-ai/dsh-client-file-upload"),
1820
+ session: captured.get("@deepseek-ai/dsh-api-session-controller"),
1821
+ jobs: captured.get("@deepseek-ai/dsh-api-job-controller")
1822
+ };
1823
+ for (const [id, module] of Object.entries(modules)) if (module === void 0) throw new Error(`official Client bundle capture produced no module exports for ${id}`);
1824
+ return Object.freeze(modules);
1825
+ }
1826
+ /** Explicit generated `/remote` contributions (§2.4.2), never the aggregate. */
1827
+ const REMOTE_CONTRIBUTIONS = [
1828
+ sessionRemote,
1829
+ jobRemote,
1830
+ commandsRemote,
1831
+ subagentsRemote,
1832
+ agentPresetsRemote,
1833
+ pluginManagerRemote,
1834
+ settingsRemote,
1835
+ permissionPresetsRemote,
1836
+ llmRemote,
1837
+ fileUploadsRemote,
1838
+ userQuestionsRemote,
1839
+ workspaceFilesRemote
1840
+ ];
1495
1841
  /**
1496
- * The Host endpoint of the private stream. One instance per Remote Host
1497
- * composition; the descriptors and the subscriptions leave with the fiber.
1842
+ * Reverse-dispose the recorded `/remote` contribution disposers. Per-step
1843
+ * error isolation: one rejecting disposer cannot truncate the remaining
1844
+ * cleanup. Returns the collected cleanup errors in encounter order.
1845
+ *
1846
+ * Exported so the L5 suite can exercise the exact collection semantics the
1847
+ * production composition relies on (module-internal seam, like
1848
+ * `createScopedClientModuleLoader`).
1498
1849
  */
1499
- var PiTuiTerminalProgressHostService = class extends TypertRemoteService {
1500
- /** The Typert registry owns the explicit invocation definition. */
1501
- static inject = ["typert"];
1502
- /** The narrow Host facts the composition resolved (explicit field: the
1503
- * strip-only TS loader rejects parameter properties). */
1504
- deps;
1505
- /** One opaque identity per Host plugin instance: a Host restart, a new
1506
- * composition or a re-mounted fiber all invalidate older frames. */
1507
- hostEpoch = `host-${randomEpoch()}`;
1508
- records = /* @__PURE__ */ new Map();
1509
- /** Monotonic Agent-lifetime counter: a replacement ALWAYS outranks every
1510
- * earlier lifetime of the same session, even after its record was dropped. */
1511
- epochCounter = 0;
1512
- disposed = false;
1513
- /**
1514
- * @param ctx - the Host context this row is mounted in.
1515
- * @param deps - the narrow Host facts the composition resolved.
1516
- */
1517
- constructor(ctx, deps) {
1518
- super(ctx, PI_TUI_TERMINAL_PROGRESS_NAMESPACE);
1519
- this.deps = deps;
1520
- ctx.on("agent/status", ({ agent, status }) => {
1521
- this.onAgentStatus(agent, status);
1522
- }, { global: true });
1523
- ctx.on("session/event", (session, event) => {
1524
- this.onSessionEvent(session, event.type, event.data);
1525
- }, { global: true });
1526
- ctx.on("agent/disposed", ({ agent }) => {
1527
- this.onAgentDisposed(agent);
1528
- }, { global: true });
1529
- ctx.effect(() => () => {
1530
- this.closeAll();
1531
- }, "pi-tui-terminal-progress-watchers");
1850
+ async function disposeRemoteContributions(disposers) {
1851
+ const errors = [];
1852
+ for (let index = disposers.length - 1; index >= 0; index -= 1) try {
1853
+ await disposers[index]();
1854
+ } catch (error) {
1855
+ errors.push(error);
1532
1856
  }
1857
+ return errors;
1858
+ }
1859
+ /**
1860
+ * Compose one fresh official Client `Context` over the Host carrier:
1861
+ * typert -> Connection (explicit transport) -> Gateway -> the eleven explicit
1862
+ * `/remote` contributions -> the private pi-tui contribution (TS8-HF1) ->
1863
+ * fileUpload -> Sessions -> Jobs, then wait for initial readiness. On
1864
+ * construction failure the partial composition unwinds immediately; the
1865
+ * loader shim is never active during plugin execution.
1866
+ */
1867
+ async function createRemoteClientRuntime(options) {
1868
+ const modules = await loadOfficialClientModulesOnce();
1869
+ const { carrier } = options;
1870
+ const context = new Context();
1871
+ let typertFiber;
1872
+ let connectionFiber;
1873
+ let gatewayFiber;
1874
+ let fileUploadFiber;
1875
+ let sessionFiber;
1876
+ let jobsFiber;
1877
+ let services;
1878
+ const contributionDisposers = [];
1879
+ let disposed = false;
1533
1880
  /**
1534
- * The private Remote method (`piTuiTerminalProgress/watch`): the ONE
1535
- * per-session ordered stream, opening with the authoritative snapshot of the
1536
- * instant it subscribes and then every real Host-side change (plan §6.5).
1881
+ * The frozen §16 shutdown sequence: domain Clients (reverse), the explicit
1882
+ * `/remote` contributions (reverse), Gateway/Connection/Typert (reverse),
1883
+ * then the Client root. Unwinding a partial composition runs the SAME
1884
+ * order over whatever subset exists: a fiber whose startup rejected is
1885
+ * already assigned, so it unwinds at its own position; only stages that
1886
+ * were never reached are skipped.
1537
1887
  *
1538
- * The subscriber is registered and the cut (revision + current state) is
1539
- * captured in the SAME synchronous block before the first `yield`, so an
1540
- * update can neither be lost between the snapshot and the subscription nor be
1541
- * replayed twice.
1888
+ * Contribution-disposer failures are isolated (collected, never allowed to
1889
+ * truncate the remaining cleanup). Cordis contains unload-disposer failures
1890
+ * inside `fiber.dispose()` (they are logged there, never propagated), so
1891
+ * the fiber steps cannot reject.
1892
+ *
1893
+ * @returns the collected contribution-disposer cleanup errors.
1542
1894
  */
1543
- async *watch(sessionId, signal) {
1544
- const record = this.recordFor(sessionId);
1545
- const queue = new FrameQueue();
1546
- const cut = record.revision;
1547
- const snapshot = {
1548
- kind: "snapshot",
1549
- sessionId,
1550
- hostEpoch: this.hostEpoch,
1551
- agentEpoch: record.agentEpoch,
1552
- revision: cut,
1553
- running: record.running,
1554
- outcome: record.outcome
1555
- };
1556
- record.subscribers.add(queue);
1557
- const onAbort = () => {
1558
- queue.close();
1559
- };
1560
- if (signal.aborted) queue.close();
1561
- else signal.addEventListener("abort", onAbort, { once: true });
1562
- try {
1563
- yield snapshot;
1564
- for (;;) {
1565
- const next = await queue.next();
1566
- if (next.done === true) return;
1567
- yield next.value;
1568
- }
1569
- } finally {
1570
- signal.removeEventListener("abort", onAbort);
1571
- record.subscribers.delete(queue);
1572
- this.reclaim(record);
1573
- }
1574
- }
1575
- /**
1576
- * Drop a record nobody watches and no Agent owns. A watch of a session that
1577
- * has no live Agent must not leave an empty record behind for the rest of the
1578
- * Host's life: it is observable by nothing, and the next Agent lifetime starts
1579
- * a FRESH record carrying a HIGHER `agentEpoch` (the epoch counter never
1580
- * rewinds), so no Client provenance can be resurrected across the gap.
1581
- */
1582
- reclaim(record) {
1583
- if (record.subscribers.size > 0 || record.agent !== void 0) return;
1584
- if (this.records.get(record.sessionId) === record) this.records.delete(record.sessionId);
1585
- }
1586
- /** The live `agent/status` transition of one Agent (plan §6.4). */
1587
- onAgentStatus(agent, status) {
1588
- if (this.deps.agentFor(agent.session.id) !== agent) return;
1589
- const record = this.recordFor(agent.session.id);
1590
- if (record.agent !== agent) return;
1591
- this.publish(record, record.fold.status(status === "running"));
1592
- }
1593
- /** One durable Session event (plan §6.4): evidence only, never an interim commit. */
1594
- onSessionEvent(session, type, data) {
1595
- const record = this.records.get(session.id);
1596
- if (record === void 0 || record.agent === void 0) return;
1597
- if (record.session !== session) return;
1598
- if (type === "turn/start") {
1599
- const turn = turnOf(data);
1600
- if (turn !== void 0) record.fold.turnStart(turn);
1601
- return;
1602
- }
1603
- if (type === "turn/end") {
1604
- const turn = turnOf(data);
1605
- const kind = reasonKindOf(data);
1606
- if (turn !== void 0 && kind !== void 0) record.fold.turnEnd(turn, kind);
1607
- }
1608
- }
1609
- /** The Agent lifetime ended (plan §6.4): retire honestly, end the watchers. */
1610
- onAgentDisposed(agent) {
1611
- const record = this.records.get(agent.session.id);
1612
- if (record === void 0 || record.agent !== agent) return;
1613
- const retired = record.fold.retire();
1614
- if (retired !== void 0) this.publish(record, retired);
1615
- this.records.delete(agent.session.id);
1616
- for (const subscriber of record.subscribers) subscriber.close();
1617
- }
1618
- /**
1619
- * The record of one session, bound to the live Agent the authoritative Host
1620
- * registry currently holds. Creation AND a replaced Agent lifetime consume a
1621
- * new `agentEpoch` and reset the interval: a new Agent can never inherit the
1622
- * previous lifetime's evidence (plan §6.3/§6.4).
1623
- */
1624
- recordFor(sessionId) {
1625
- let record = this.records.get(sessionId);
1626
- if (record === void 0) {
1627
- record = {
1628
- sessionId,
1629
- agent: void 0,
1630
- session: void 0,
1631
- agentEpoch: 0,
1632
- fold: createTerminalProgressInterval((kind) => {
1633
- this.deps.onUnknownReason(kind);
1634
- }),
1635
- revision: 0,
1636
- running: false,
1637
- outcome: "idle",
1638
- subscribers: /* @__PURE__ */ new Set()
1639
- };
1640
- this.records.set(sessionId, record);
1641
- }
1642
- const live = this.deps.agentFor(sessionId);
1643
- if (live !== void 0 && live !== record.agent) this.rebind(record, live);
1644
- return record;
1645
- }
1646
- /**
1647
- * Bind one Agent lifetime: the running truth is read from the Agent's OWN
1648
- * current status (a plugin mounted mid-run may therefore report `working`),
1649
- * but the outcome starts at `idle` — an unobserved start can never prove a
1650
- * settlement. The rebind is ALWAYS published, because the epoch change is
1651
- * itself a fact the Client must fence on.
1652
- */
1653
- rebind(record, agent) {
1654
- record.agent = agent;
1655
- record.session = agent.session;
1656
- record.agentEpoch = ++this.epochCounter;
1657
- const running = agent.status === "running";
1658
- record.fold.apply({
1659
- active: running,
1660
- outcome: "idle"
1895
+ const shutdown = async () => {
1896
+ for (const fiber of [
1897
+ jobsFiber,
1898
+ sessionFiber,
1899
+ fileUploadFiber
1900
+ ]) await fiber?.dispose();
1901
+ const contributionErrors = await disposeRemoteContributions(contributionDisposers);
1902
+ contributionDisposers.length = 0;
1903
+ for (const fiber of [
1904
+ gatewayFiber,
1905
+ connectionFiber,
1906
+ typertFiber
1907
+ ]) await fiber?.dispose();
1908
+ await context.fiber.dispose();
1909
+ return contributionErrors;
1910
+ };
1911
+ const unwind = async () => {
1912
+ disposed = true;
1913
+ return shutdown();
1914
+ };
1915
+ try {
1916
+ typertFiber = context.plugin(modules.typert);
1917
+ await typertFiber;
1918
+ connectionFiber = context.plugin((connectionContext) => {
1919
+ modules.connection.installConnection(connectionContext, {
1920
+ interactions: "answer",
1921
+ transport: {
1922
+ ownsHost: true,
1923
+ fetch: carrier.fetch,
1924
+ openStream: carrier.openStream
1925
+ }
1926
+ });
1661
1927
  });
1662
- record.running = running;
1663
- record.outcome = "idle";
1664
- record.revision += 1;
1665
- this.broadcast(record, "update");
1666
- }
1667
- /** Commit one fold transition: mutate the record FIRST, then broadcast. */
1668
- publish(record, next) {
1669
- if (next === void 0) return;
1670
- if (next.active === record.running && next.outcome === record.outcome) return;
1671
- record.running = next.active;
1672
- record.outcome = next.outcome;
1673
- record.revision += 1;
1674
- this.broadcast(record, "update");
1675
- }
1676
- broadcast(record, kind) {
1677
- const frame = {
1678
- kind,
1679
- sessionId: record.sessionId,
1680
- hostEpoch: this.hostEpoch,
1681
- agentEpoch: record.agentEpoch,
1682
- revision: record.revision,
1683
- running: record.running,
1684
- outcome: record.outcome
1928
+ await connectionFiber;
1929
+ gatewayFiber = context.plugin(modules.gateway);
1930
+ await gatewayFiber;
1931
+ for (const contribution of REMOTE_CONTRIBUTIONS) contributionDisposers.push(await context.remote.$mount(contribution));
1932
+ contributionDisposers.push(await context.remote.$mount(PI_TUI_CLIENT_CONTRIBUTION));
1933
+ fileUploadFiber = context.plugin(modules.fileUpload);
1934
+ await fileUploadFiber;
1935
+ sessionFiber = context.plugin(modules.session);
1936
+ await sessionFiber;
1937
+ jobsFiber = context.plugin(modules.jobs);
1938
+ await jobsFiber;
1939
+ services = {
1940
+ connection: context.get("connection"),
1941
+ sessions: context.get("sessions"),
1942
+ jobs: context.get("jobs")
1685
1943
  };
1686
- for (const subscriber of record.subscribers) subscriber.push(frame);
1687
- }
1688
- /** End every watcher (the row's fiber is going away). */
1689
- closeAll() {
1690
- if (this.disposed) return;
1691
- this.disposed = true;
1692
- for (const record of this.records.values()) for (const subscriber of record.subscribers) subscriber.close();
1944
+ await waitForInitialReadiness(services.connection, services.sessions, options.signal);
1945
+ } catch (error) {
1946
+ const cleanupErrors = await unwind();
1947
+ const failure = error instanceof Error ? error : new Error(String(error));
1948
+ if (cleanupErrors.length > 0) mergeCause(failure, cleanupErrors.length === 1 ? cleanupErrors[0] : new AggregateError(cleanupErrors, "remote client runtime: unwind disposal failures"));
1949
+ throw failure;
1693
1950
  }
1694
- };
1695
- /** An opaque, process-unique Host-plugin identity (the wire sees only a string). */
1696
- function randomEpoch() {
1697
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1698
- }
1699
- //#endregion
1700
- //#region src/app/remote/host-runtime.ts
1701
- /**
1702
- * Host services the ordinary Host Context must already expose before any M3
1703
- * row mounts. The check fails fast with
1704
- * the missing service named instead of parking the runtime.
1705
- */
1706
- const HOST_PREREQUISITE_SERVICES = [
1707
- "credentials",
1708
- "userQuestions",
1709
- "typert",
1710
- "typertGateway",
1711
- "agents",
1712
- "agentDefaultModel",
1713
- "attachments",
1714
- "commands",
1715
- "fileReferences",
1716
- "fs",
1717
- "llm",
1718
- "sessions",
1719
- "sessionProjections",
1720
- "sessionQuery",
1721
- "workspaceRegistry",
1722
- "jobController"
1723
- ];
1724
- /**
1725
- * Fixed private base URL used only to construct valid `Request` objects for
1726
- * the shared Fetch handler. It is not a global location, a server URL, a TCP
1727
- * listener, or an authentication surface.
1728
- */
1729
- const IN_PROCESS_BASE_URL = "http://dsh-pi-tui-remote.in-process/";
1730
- async function* emptyUplink() {}
1731
- /**
1732
- * Attach one secondary failure to `failure`'s cause chain without losing an
1733
- * existing cause: when the failure already carries a cause, both aggregate
1734
- * into a single `AggregateError`. Shared by the three composition owners so
1735
- * cleanup failures never mask the original construction/readiness error.
1736
- * A `undefined` secondary is a no-op (nothing to attach).
1737
- */
1738
- function mergeCause(failure, secondary) {
1739
- if (secondary === void 0) return failure;
1740
- const existingCause = failure.cause;
1741
- failure.cause = existingCause === void 0 ? secondary : new AggregateError([existingCause, secondary], "remote composition: aggregated failure causes");
1742
- return failure;
1743
- }
1744
- /**
1745
- * Fail fast when the ordinary Host lacks one of the required base services.
1746
- * Reads via the reflect store so the diagnostic can name the missing key
1747
- * without depending on any one service's shape.
1748
- */
1749
- function assertHostPrerequisites(hostContext) {
1750
- 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
- }
1752
- /** Build the in-process carrier over the Host connection + gateway seams. */
1753
- function createInProcessCarrier(hostContext) {
1754
- const shared = hostContext.connection.createSharedFetchHandler("/api");
1755
- const gateway = hostContext.typertGateway;
1951
+ const { connection, sessions, jobs } = services;
1756
1952
  return {
1757
- ownsHost: true,
1758
- fetch(input, init) {
1759
- 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);
1761
- },
1762
- openStream(endpoint, payload, signal, uplink) {
1763
- return (async function* () {
1764
- yield* await gateway.wireStream.open(endpoint, payload, uplink ?? emptyUplink(), void 0, signal);
1765
- })();
1953
+ context,
1954
+ connection,
1955
+ sessions,
1956
+ jobs,
1957
+ remote: context.remote,
1958
+ async dispose() {
1959
+ if (disposed) return;
1960
+ disposed = true;
1961
+ const cleanupErrors = await shutdown();
1962
+ if (cleanupErrors.length > 0) {
1963
+ const failure = cleanupErrors[0] instanceof Error ? cleanupErrors[0] : new Error(String(cleanupErrors[0]));
1964
+ if (cleanupErrors.length > 1) mergeCause(failure, new AggregateError(cleanupErrors.slice(1), "remote client runtime: remaining disposal failures"));
1965
+ throw failure;
1966
+ }
1766
1967
  }
1767
1968
  };
1768
1969
  }
1769
1970
  /**
1770
- * Mount the exact additive official Host closure (§2.4.1) onto the existing
1771
- * Host Context and await every fiber. The existing `jobController` service is
1772
- * asserted before and after construction and never re-mounted.
1773
- *
1774
- * On a partial construction failure the already-mounted fibers unwind in
1775
- * reverse order before the original error rethrows.
1971
+ * Initial readiness: a defined Connection
1972
+ * generation AND a `ready` Session list. Subscription-driven with no
1973
+ * production timeout; the lifecycle signal aborts the wait and every listener
1974
+ * is removed on settle or abort.
1776
1975
  */
1777
- async function createRemoteHostRuntime(hostContext, options = {}) {
1778
- assertHostPrerequisites(hostContext);
1779
- const diag = options.diag ?? { warn: (message, fields) => {
1780
- hostContext.logger("remote-host").warn(message, fields);
1781
- } };
1782
- /** The live Agent of one session, read PER CALL through the authoritative
1783
- * Host registry (never a composition-time snapshot). */
1784
- const liveAgentFor = (sessionId) => hostContext.reflect.get("agents")?.get(sessionId);
1785
- const jobControllerBefore = hostContext.reflect.get("jobController");
1786
- const userQuestionsBefore = hostContext.reflect.get("userQuestions");
1787
- const fibers = [];
1788
- let carrier;
1789
- let disposed = false;
1790
- /**
1791
- * Reverse-dispose every mounted fiber. Per-step error isolation: one
1792
- * rejecting disposer cannot truncate the remaining cleanup. Returns the
1793
- * collected disposal errors instead of throwing, so the construction
1794
- * failure path can rethrow the ORIGINAL error with the cleanup failures
1795
- * attached as its `cause`.
1796
- */
1797
- const collectUnwind = async () => {
1798
- const errors = [];
1799
- for (let index = fibers.length - 1; index >= 0; index -= 1) try {
1800
- await fibers[index].dispose();
1801
- } catch (error) {
1802
- errors.push(error);
1803
- }
1804
- fibers.length = 0;
1805
- return errors;
1806
- };
1807
- try {
1808
- const contributionFiber = hostContext.inject(["typert"], (contributionCtx) => {
1809
- contributionCtx.effect(() => contributionCtx.typert.register(PI_TUI_HOST_CONTRIBUTION), "pi-tui-private-remote-host");
1810
- });
1811
- fibers.push(contributionFiber);
1812
- await contributionFiber;
1813
- const fileReferenceFiber = hostContext.inject(PiTuiFileReferenceHostService.inject, (pluginCtx) => {
1814
- new PiTuiFileReferenceHostService(pluginCtx, {
1815
- agentFor: (sessionId) => liveAgentFor(sessionId),
1816
- official: () => hostContext.reflect.get("fileReferences")
1817
- });
1818
- });
1819
- fibers.push(fileReferenceFiber);
1820
- await fileReferenceFiber;
1821
- const terminalProgressFiber = hostContext.inject(PiTuiTerminalProgressHostService.inject, (pluginCtx) => {
1822
- new PiTuiTerminalProgressHostService(pluginCtx, {
1823
- agentFor: (sessionId) => liveAgentFor(sessionId),
1824
- onUnknownReason: (kind) => {
1825
- diag.warn("terminal progress: unknown turn/end reason", { kind });
1826
- }
1827
- });
1828
- });
1829
- fibers.push(terminalProgressFiber);
1830
- await terminalProgressFiber;
1831
- const connFiber = hostContext.plugin((connectionContext) => {
1832
- new HostConnectionService(connectionContext, [], {});
1833
- });
1834
- fibers.push(connFiber);
1835
- await connFiber;
1836
- const uploadFiber = hostContext.plugin(FileUploads);
1837
- fibers.push(uploadFiber);
1838
- await uploadFiber;
1839
- const statsFiber = hostContext.plugin(sessionStats);
1840
- fibers.push(statsFiber);
1841
- await statsFiber;
1842
- const performanceFiber = hostContext.plugin(performance_host_exports);
1843
- fibers.push(performanceFiber);
1844
- await performanceFiber;
1845
- const outlineFiber = hostContext.plugin(sessionTurnOutline);
1846
- fibers.push(outlineFiber);
1847
- await outlineFiber;
1848
- const sessionCtrlFiber = hostContext.inject(SessionController.inject, (controllerContext) => {
1849
- new SessionController(controllerContext, { nativeOpen: false });
1850
- });
1851
- fibers.push(sessionCtrlFiber);
1852
- await sessionCtrlFiber;
1853
- const settingsFiber = hostContext.plugin(SettingsController);
1854
- fibers.push(settingsFiber);
1855
- await settingsFiber;
1856
- const remotesFiber = hostContext.plugin({
1857
- inject,
1858
- apply
1859
- });
1860
- fibers.push(remotesFiber);
1861
- await remotesFiber;
1862
- const exportFiber = hostContext.plugin(sessionLogExport);
1863
- fibers.push(exportFiber);
1864
- await exportFiber;
1865
- const jobControllerAfter = hostContext.reflect.get("jobController");
1866
- if (jobControllerAfter === void 0 || jobControllerAfter.typertRemote === void 0 || jobControllerAfter.typertRemote !== jobControllerBefore.typertRemote) throw new Error("remote host runtime: the existing jobController service was replaced by the M3 composition");
1867
- const userQuestionsAfter = hostContext.reflect.get("userQuestions");
1868
- if (userQuestionsAfter === void 0 || userQuestionsAfter.typertRemote === void 0 || userQuestionsAfter.typertRemote !== userQuestionsBefore?.typertRemote) throw new Error("remote host runtime: the existing userQuestions service was replaced by the M3 composition");
1869
- carrier = createInProcessCarrier(hostContext);
1870
- } catch (error) {
1871
- const disposeErrors = await collectUnwind();
1872
- if (disposeErrors.length > 0) {
1873
- const secondary = disposeErrors.length === 1 ? disposeErrors[0] : new AggregateError(disposeErrors, "remote host runtime: unwind disposal failures");
1874
- throw mergeCause(error instanceof Error ? error : new Error(String(error)), secondary);
1875
- }
1876
- throw error;
1877
- }
1878
- return {
1879
- hostContext,
1880
- carrier,
1881
- async dispose() {
1882
- if (disposed) return;
1883
- disposed = true;
1884
- const disposeErrors = await collectUnwind();
1885
- if (disposeErrors.length > 0) {
1886
- const failure = disposeErrors[0] instanceof Error ? disposeErrors[0] : new Error(String(disposeErrors[0]));
1887
- if (disposeErrors.length > 1) mergeCause(failure, new AggregateError(disposeErrors.slice(1), "remote host runtime: remaining disposal failures"));
1888
- throw failure;
1976
+ async function waitForInitialReadiness(connection, sessions, signal) {
1977
+ const isReady = () => connection.generation.getSnapshot() !== void 0 && sessions.list.getSnapshot().phase === "ready";
1978
+ if (signal?.aborted) throw new Error("remote client runtime: aborted before initial readiness", { cause: signal.reason });
1979
+ if (isReady()) return;
1980
+ await new Promise((resolve, reject) => {
1981
+ let settled = false;
1982
+ let abortListener;
1983
+ const settle = () => {
1984
+ if (settled) return;
1985
+ if (isReady()) {
1986
+ settled = true;
1987
+ cleanup();
1988
+ resolve();
1989
+ }
1990
+ };
1991
+ const generationUnsubscribe = connection.generation.subscribe(settle);
1992
+ const listUnsubscribe = sessions.list.subscribe(settle);
1993
+ const cleanup = () => {
1994
+ generationUnsubscribe();
1995
+ listUnsubscribe();
1996
+ if (abortListener !== void 0) signal?.removeEventListener("abort", abortListener);
1997
+ };
1998
+ if (signal !== void 0) {
1999
+ abortListener = () => {
2000
+ if (settled) return;
2001
+ settled = true;
2002
+ cleanup();
2003
+ reject(new Error("remote client runtime: aborted before initial readiness", { cause: signal.reason }));
2004
+ };
2005
+ if (signal.aborted) {
2006
+ abortListener();
2007
+ return;
1889
2008
  }
2009
+ signal.addEventListener("abort", abortListener, { once: true });
1890
2010
  }
1891
- };
2011
+ settle();
2012
+ });
1892
2013
  }
1893
2014
  //#endregion
1894
- //#region src/app/remote/client-runtime.ts
1895
- /**
1896
- * Experimental official Client runtime composition (M3-1).
1897
- *
1898
- * Owns the official Client bundle capture, the Client `Context`, the exact
1899
- * plugin mount order, the explicit `/remote` contributions, initial
1900
- * readiness, and reverse disposal.
1901
- * It does not assemble the TUI semantic `Backend`.
1902
- *
1903
- * rc.2 publishes the six required Client plugin entries as Web
1904
- * module-loader bundles: each bundle registers through
1905
- * `window.__ModuleLoader__.load(...)`, which plain Node dynamic imports
1906
- * cannot consume directly. The scoped loader below is therefore a packaging
1907
- * adapter only: it is installed around exactly the six dynamic imports,
1908
- * rejects unknown/duplicate/missing registrations, and restores the previous
1909
- * process state before any Client plugin runs.
1910
- *
1911
- * Because ESM evaluates each bundle at most once per process, the capture is
1912
- * a process-wide single-flight: the captured package module exports are
1913
- * reused for every Client `Context`, while each Context still gets its own
1914
- * independent Connection, Gateway, Remote namespaces, Sessions, Jobs,
1915
- * subscriptions, and lifetimes. Captured bundle factories are never re-run.
1916
- *
1917
- * @module app/remote/client-runtime
1918
- */
1919
- /**
1920
- * The exact allowlist: dynamic import specifier paired with its expected
1921
- * `__ModuleLoader__` registration id (§9.1). Kept distinct by design.
1922
- */
1923
- const OFFICIAL_CLIENT_BUNDLES = [
1924
- {
1925
- specifier: "@deepseek-ai/dsh-typert-registry/client",
1926
- id: "@deepseek-ai/dsh-typert-registry"
1927
- },
1928
- {
1929
- specifier: "@deepseek-ai/dsh-client-connection/client",
1930
- id: "@deepseek-ai/dsh-client-connection"
1931
- },
1932
- {
1933
- specifier: "@deepseek-ai/dsh-api-gateway/client",
1934
- id: "@deepseek-ai/dsh-api-gateway"
1935
- },
1936
- {
1937
- specifier: "@deepseek-ai/dsh-client-file-upload/client",
1938
- id: "@deepseek-ai/dsh-client-file-upload"
1939
- },
1940
- {
1941
- specifier: "@deepseek-ai/dsh-api-session-controller/client",
1942
- id: "@deepseek-ai/dsh-api-session-controller"
1943
- },
1944
- {
1945
- specifier: "@deepseek-ai/dsh-api-job-controller/client",
1946
- id: "@deepseek-ai/dsh-api-job-controller"
1947
- }
1948
- ];
1949
- /** Expected registration ids, in dependency order. */
1950
- const EXPECTED_REGISTRATION_IDS = OFFICIAL_CLIENT_BUNDLES.map((bundle) => bundle.id);
1951
- /** Process-wide single-flight capture; module code evaluates once per process. */
1952
- let officialClientModulesPromise;
1953
- /**
1954
- * Load the six official Client bundles once per process and freeze their
1955
- * captured module exports. Concurrent callers share the same promise.
1956
- *
1957
- * Failure semantics: a rejected capture stays cached (fail fast, no silent
1958
- * retry). ESM evaluates each bundle at most once per process, so bundles
1959
- * already imported during a failed capture can never re-register — a retry
1960
- * would deterministically fail the completeness check anyway.
1961
- */
1962
- function loadOfficialClientModulesOnce() {
1963
- officialClientModulesPromise ??= captureOfficialClientModules();
1964
- return officialClientModulesPromise;
2015
+ //#region src/runtime/remote/prompt-serializer-remote.ts
2016
+ /** Base64-encode one byte buffer (Node Buffer, kept inside the adapter). */
2017
+ function base64Of(bytes) {
2018
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
1965
2019
  }
1966
- /**
1967
- * 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.
1971
- */
1972
- /**
1973
- * The exact scoped loader admission rules (module-internal seam, exercised by
1974
- * the L5 loader-exactness test): reject an unknown registration id, a
1975
- * duplicate id, a non-function factory, and a `/client` dependency requested
1976
- * before its dependency-order capture; report missing expected ids.
1977
- */
1978
- function createScopedClientModuleLoader(expectedIds) {
1979
- const nodeRequire = createRequire(import.meta.url);
1980
- const registrations = /* @__PURE__ */ new Map();
1981
- const captured = /* @__PURE__ */ new Map();
1982
- const requireModule = (specifier) => {
1983
- if (specifier.endsWith("/client")) {
1984
- const id = specifier.slice(0, -7);
1985
- const module = captured.get(id);
1986
- if (module === void 0) throw new Error(`official Client module ${specifier} was requested before ${id} was captured`);
1987
- return module;
1988
- }
1989
- return nodeRequire(specifier);
1990
- };
1991
- const load = ({ id, factory }) => {
1992
- if (!expectedIds.includes(id)) throw new Error(`official Client bundle loader received an unexpected registration id: ${String(id)}`);
1993
- if (registrations.has(id)) throw new Error(`official Client bundle ${id} registered twice`);
1994
- if (typeof factory !== "function") throw new Error(`official Client bundle ${id} registered a non-function factory`);
1995
- registrations.set(id, factory);
1996
- captured.set(id, factory(requireModule));
1997
- };
2020
+ /** The echo attachment view of one staged image (display facts only). */
2021
+ function previewOf(image) {
1998
2022
  return {
1999
- load,
2000
- requireModule,
2001
- registeredIds: () => [...registrations.keys()],
2002
- assertComplete() {
2003
- for (const id of expectedIds) if (!registrations.has(id)) throw new Error(`official Client bundle ${id} never registered through __ModuleLoader__`);
2023
+ type: "image",
2024
+ value: {
2025
+ previewUrl: "",
2026
+ ...image.name !== void 0 ? { name: image.name } : {},
2027
+ width: image.width,
2028
+ height: image.height
2004
2029
  }
2005
2030
  };
2006
2031
  }
2007
- /**
2008
- * Install the temporary `window.__ModuleLoader__` shim around exactly the six
2009
- * bundle imports, preserving the exact previous process state: when
2010
- * `globalThis.window` is absent, only the minimal temporary object is created
2011
- * and deleted again; when a `window` own property already exists (including a
2012
- * property whose value is `undefined`/`null`, and accessor descriptors), its
2013
- * exact property descriptor is restored, and any pre-existing
2014
- * `__ModuleLoader__` property descriptor on an existing window object is
2015
- * preserved and restored verbatim.
2016
- * @returns the restore function; it must run before any Client plugin executes
2017
- * (and on every failure path).
2018
- */
2019
- function installScopedModuleLoaderShim(load) {
2020
- const globalScope = globalThis;
2021
- const previousWindowDescriptor = Object.getOwnPropertyDescriptor(globalScope, "window");
2022
- const previousWindowValue = previousWindowDescriptor?.value;
2023
- const usableExistingWindow = typeof previousWindowValue === "object" && previousWindowValue !== null || typeof previousWindowValue === "function";
2024
- let previousLoaderDescriptor;
2025
- const install = () => {
2026
- if (usableExistingWindow) {
2027
- const existingWindow = previousWindowValue;
2028
- previousLoaderDescriptor = Object.getOwnPropertyDescriptor(existingWindow, "__ModuleLoader__");
2029
- existingWindow.__ModuleLoader__ = { load };
2030
- } else Object.defineProperty(globalScope, "window", {
2031
- configurable: true,
2032
- writable: true,
2033
- value: { __ModuleLoader__: { load } }
2034
- });
2032
+ /** Detach the official imageLimits projection value; `undefined` when the
2033
+ * projection is absent for this session (the recheck then keeps only the
2034
+ * Client-side conservative caps — never a guessed limit). */
2035
+ function detachedImageLimits(value) {
2036
+ if (typeof value !== "object" || value === null) return void 0;
2037
+ const limits = value;
2038
+ if (typeof limits.maxImagesPerMessage !== "number" || typeof limits.maxMessageImageBytes !== "number") return void 0;
2039
+ return {
2040
+ maxImagesPerMessage: limits.maxImagesPerMessage,
2041
+ maxMessageImageBytes: limits.maxMessageImageBytes
2035
2042
  };
2036
- const restore = () => {
2037
- if (previousWindowDescriptor === void 0) {
2038
- delete globalScope.window;
2039
- return;
2043
+ }
2044
+ /** The production Remote prompt serializer. */
2045
+ var RemotePromptSerializerProduction = class RemotePromptSerializerProduction {
2046
+ attachments;
2047
+ sessions;
2048
+ constructor(attachments) {
2049
+ this.attachments = attachments;
2050
+ }
2051
+ /** Build the production serializer over the official Client sessions face:
2052
+ * recalled durable images read their authorized bytes through the exact
2053
+ * retained binding, addressed by the PreparedPrompt's own session id. */
2054
+ static overSessions(sessions) {
2055
+ const serializer = new RemotePromptSerializerProduction({ async readAttachment(sessionId, attachmentId) {
2056
+ const binding = sessions.binding(sessionId);
2057
+ if (binding === void 0) return {
2058
+ ok: false,
2059
+ error: /* @__PURE__ */ new Error(`session "${sessionId}" is not available for an attachment read`)
2060
+ };
2061
+ const result = await binding.session.readAttachment(attachmentId);
2062
+ if (result.ok) return {
2063
+ ok: true,
2064
+ data: result.value.data
2065
+ };
2066
+ return {
2067
+ ok: false,
2068
+ error: result.error
2069
+ };
2070
+ } });
2071
+ serializer.sessions = sessions;
2072
+ return serializer;
2073
+ }
2074
+ preflight(prepared) {
2075
+ const prompt = prepared;
2076
+ if (prompt === void 0 || prompt === null || typeof prompt !== "object" || !Array.isArray(prompt.segments)) return {
2077
+ kind: "unsupported",
2078
+ reason: "the submission carries no prepared prompt snapshot"
2079
+ };
2080
+ if (prompt.hasFiles) return {
2081
+ kind: "unsupported",
2082
+ reason: "generic file attachments require an upload receipt this Remote composition does not provide"
2083
+ };
2084
+ for (const segment of prompt.segments) if (segment.type === "image") {
2085
+ if (segment.image.recalledRef === void 0 && segment.image.byteLength === 0) return {
2086
+ kind: "unsupported",
2087
+ reason: "a staged image carries neither local bytes nor a durable reference"
2088
+ };
2089
+ if (segment.image.recalledRef !== void 0 && this.attachments === void 0) return {
2090
+ kind: "unsupported",
2091
+ reason: "recalled durable images need the official attachment read, which this composition does not provide"
2092
+ };
2040
2093
  }
2041
- Object.defineProperty(globalScope, "window", previousWindowDescriptor);
2042
- if (usableExistingWindow) {
2043
- const existingWindow = previousWindowValue;
2044
- if (previousLoaderDescriptor === void 0) delete existingWindow.__ModuleLoader__;
2045
- else Object.defineProperty(existingWindow, "__ModuleLoader__", previousLoaderDescriptor);
2094
+ if (this.sessions !== void 0) {
2095
+ const images = prompt.segments.filter((segment) => segment.type === "image");
2096
+ if (images.length > 0) {
2097
+ const binding = this.sessions.binding(prompt.sessionId);
2098
+ const limits = binding === void 0 ? void 0 : detachedImageLimits(binding.session.projections.faceOf("imageLimits").getSnapshot());
2099
+ if (limits !== void 0) {
2100
+ if (images.length > limits.maxImagesPerMessage) return {
2101
+ kind: "unsupported",
2102
+ reason: `too many images: ${images.length} attached, the current limit is ${limits.maxImagesPerMessage} per message`
2103
+ };
2104
+ const aggregate = images.reduce((total, segment) => total + segment.image.byteLength, 0);
2105
+ if (aggregate > limits.maxMessageImageBytes) return {
2106
+ kind: "unsupported",
2107
+ reason: `images total ${aggregate} bytes; the current aggregate limit is ${limits.maxMessageImageBytes} bytes`
2108
+ };
2109
+ }
2110
+ }
2046
2111
  }
2112
+ return {
2113
+ kind: "ok",
2114
+ echo: {
2115
+ text: prompt.segments.map((segment) => segment.type === "text" ? segment.text : segment.type === "image" ? "[image]" : "[file]").join(""),
2116
+ attachments: prompt.segments.filter((segment) => segment.type === "image").map((segment) => previewOf(segment.image))
2117
+ }
2118
+ };
2119
+ }
2120
+ async serialize(prepared, signal) {
2121
+ const prompt = prepared;
2122
+ if (prompt === void 0 || prompt === null || typeof prompt !== "object" || !Array.isArray(prompt.segments)) return {
2123
+ kind: "unsupported",
2124
+ reason: "the submission carries no prepared prompt snapshot"
2125
+ };
2126
+ if (prompt.hasFiles) return {
2127
+ kind: "unsupported",
2128
+ reason: "generic file attachments require an upload receipt this Remote composition does not provide"
2129
+ };
2130
+ const parts = [];
2131
+ for (const segment of prompt.segments) {
2132
+ signal?.throwIfAborted();
2133
+ if (segment.type === "text") {
2134
+ if (segment.text !== "") parts.push({
2135
+ type: "text",
2136
+ text: segment.text
2137
+ });
2138
+ continue;
2139
+ }
2140
+ if (segment.type === "image") {
2141
+ const image = segment.image;
2142
+ if (image.recalledRef !== void 0) {
2143
+ const read = await this.attachments.readAttachment(prompt.sessionId, image.recalledRef.attachmentId);
2144
+ signal?.throwIfAborted();
2145
+ if (!read.ok) return {
2146
+ kind: "unsupported",
2147
+ reason: `the durable image bytes could not be read for re-send (${String(read.error)})`
2148
+ };
2149
+ parts.push({
2150
+ type: "image",
2151
+ mediaType: image.mediaType,
2152
+ data: base64Of(read.data),
2153
+ ...image.name !== void 0 ? { name: image.name } : {}
2154
+ });
2155
+ continue;
2156
+ }
2157
+ parts.push({
2158
+ type: "image",
2159
+ mediaType: image.mediaType,
2160
+ data: base64Of(image.bytes),
2161
+ ...image.name !== void 0 ? { name: image.name } : {}
2162
+ });
2163
+ }
2164
+ }
2165
+ return {
2166
+ kind: "ok",
2167
+ content: Object.freeze(parts)
2168
+ };
2169
+ }
2170
+ };
2171
+ //#endregion
2172
+ //#region src/runtime/remote/host-user-shell-remote.ts
2173
+ /** The one truthful message every Remote admission returns. */
2174
+ const CARRIER_GAP_MESSAGE = "Host user-shell execution is unavailable in this Remote composition — nothing was executed";
2175
+ /** The Remote backend's Host user-shell port: truthful, inert, fail-closed. */
2176
+ var RemoteHostUserShellPort = class {
2177
+ availability = {
2178
+ supported: false,
2179
+ policies: []
2047
2180
  };
2048
- install();
2049
- return restore;
2181
+ async execute(_request) {
2182
+ return {
2183
+ kind: "unavailable",
2184
+ reason: {
2185
+ reason: "carrier-gap",
2186
+ message: CARRIER_GAP_MESSAGE
2187
+ }
2188
+ };
2189
+ }
2190
+ };
2191
+ //#endregion
2192
+ //#region src/runtime/remote/pi-tui-file-reference-host-bridge.ts
2193
+ /**
2194
+ * The Remote Host-side bridge for the private `piTuiFileReferences` endpoint
2195
+ * (TS8-HF1): a CONSTRUCTION/ADAPTATION seam ONLY. It binds the private Remote
2196
+ * method to the SAME Host-scoped completion authority the Direct adapter uses
2197
+ * (`runtime/direct/host-file-augmentation-direct.ts` + the Direct Host
2198
+ * discovery driver) and returns a transport-neutral `list` runtime.
2199
+ *
2200
+ * It owns NO Cordis service, NO Typert registration and NO lifecycle policy —
2201
+ * the Cordis service, its Typert contribution registration and its disposal
2202
+ * remain with the Remote Host composition
2203
+ * (`app/remote/pi-tui-file-reference-host.ts`). The dependency direction is
2204
+ * therefore `app/remote/** -> runtime/remote/** -> runtime/direct/**`, never
2205
+ * `app/remote/** -> runtime/direct/**`.
2206
+ *
2207
+ * The bridge lives in `runtime/remote/**` because that layer may consume the
2208
+ * Direct Host implementation; the composition layer may not.
2209
+ *
2210
+ * @module @xmoon76/dsh-pi-tui/runtime/remote/pi-tui-file-reference-host-bridge
2211
+ */
2212
+ /**
2213
+ * Bind the private Remote method to the Host-scoped completion authority.
2214
+ * The Host finder is resolved ONCE for the runtime's lifetime (it is a pure
2215
+ * PATH pin; a later PATH change is not a Host completion fact).
2216
+ */
2217
+ function createPiTuiHostFileReferenceRuntime(deps) {
2218
+ const driver = new DirectHostDiscoveryDriver(deps.fdPath);
2219
+ const environment = hostPathQueryEnvironment();
2220
+ return { async list(sessionId, query, signal) {
2221
+ signal.throwIfAborted();
2222
+ const agent = deps.agentFor(sessionId);
2223
+ if (agent === void 0) return {
2224
+ kind: "unavailable",
2225
+ reason: "the requested Session has no live Host Agent"
2226
+ };
2227
+ return await listPiTuiHostFileReferences(agent, query, signal, {
2228
+ official: deps.official(),
2229
+ driver,
2230
+ environment,
2231
+ workingDirectory: deps.workingDirectory?.()
2232
+ });
2233
+ } };
2050
2234
  }
2051
- async function captureOfficialClientModules() {
2052
- const loader = createScopedClientModuleLoader(EXPECTED_REGISTRATION_IDS);
2053
- const restoreShim = installScopedModuleLoaderShim(loader.load);
2054
- try {
2055
- for (const bundle of OFFICIAL_CLIENT_BUNDLES) await import(bundle.specifier);
2056
- loader.assertComplete();
2057
- } finally {
2058
- restoreShim();
2235
+ //#endregion
2236
+ //#region src/app/remote/pi-tui-file-reference-host.ts
2237
+ /**
2238
+ * The Host endpoint of the private augmentation. One instance per Remote Host
2239
+ * composition; the descriptor leaves with the owning fiber.
2240
+ */
2241
+ var PiTuiFileReferenceHostService = class extends TypertRemoteService {
2242
+ /** The Typert registry owns the explicit invocation definitions. */
2243
+ static inject = ["typert"];
2244
+ runtime;
2245
+ /**
2246
+ * @param ctx - the Host context this row is mounted in.
2247
+ * @param deps - the narrow Host facts the composition resolved.
2248
+ */
2249
+ constructor(ctx, deps) {
2250
+ super(ctx, PI_TUI_FILE_REFERENCES_NAMESPACE);
2251
+ this.runtime = createPiTuiHostFileReferenceRuntime({
2252
+ ...deps,
2253
+ workingDirectory: () => ctx.get("workingDirectory")
2254
+ });
2059
2255
  }
2060
- const captured = /* @__PURE__ */ new Map();
2061
- for (const id of loader.registeredIds()) captured.set(id, loader.requireModule(`${id}/client`));
2062
- return freezeOfficialClientModules(captured);
2256
+ /**
2257
+ * The private Remote method (`piTuiFileReferences/list`, see
2258
+ * `pi-tui-file-reference-contract.ts`). Cancellation outranks every outcome.
2259
+ */
2260
+ list(sessionId, query, signal) {
2261
+ return this.runtime.list(sessionId, query, signal);
2262
+ }
2263
+ };
2264
+ //#endregion
2265
+ //#region src/app/remote/terminal-progress-host.ts
2266
+ /** The structural `turn/start` / `turn/end` payload read (never a guessed shape). */
2267
+ function turnOf(data) {
2268
+ const turn = data?.turn;
2269
+ return typeof turn === "number" ? turn : void 0;
2063
2270
  }
2064
- function freezeOfficialClientModules(captured) {
2065
- const modules = {
2066
- typert: captured.get("@deepseek-ai/dsh-typert-registry"),
2067
- connection: captured.get("@deepseek-ai/dsh-client-connection"),
2068
- gateway: captured.get("@deepseek-ai/dsh-api-gateway"),
2069
- fileUpload: captured.get("@deepseek-ai/dsh-client-file-upload"),
2070
- session: captured.get("@deepseek-ai/dsh-api-session-controller"),
2071
- jobs: captured.get("@deepseek-ai/dsh-api-job-controller")
2072
- };
2073
- for (const [id, module] of Object.entries(modules)) if (module === void 0) throw new Error(`official Client bundle capture produced no module exports for ${id}`);
2074
- return Object.freeze(modules);
2271
+ /** The merge-extensible `turn/end.reason.kind` discriminant. */
2272
+ function reasonKindOf(data) {
2273
+ const reason = data?.reason;
2274
+ return typeof reason?.kind === "string" ? reason.kind : void 0;
2075
2275
  }
2076
- /** Explicit generated `/remote` contributions (§2.4.2), never the aggregate. */
2077
- const REMOTE_CONTRIBUTIONS = [
2078
- sessionRemote,
2079
- jobRemote,
2080
- commandsRemote,
2081
- subagentsRemote,
2082
- agentPresetsRemote,
2083
- pluginManagerRemote,
2084
- settingsRemote,
2085
- permissionPresetsRemote,
2086
- llmRemote,
2087
- fileUploadsRemote,
2088
- userQuestionsRemote
2089
- ];
2090
2276
  /**
2091
- * Reverse-dispose the recorded `/remote` contribution disposers. Per-step
2092
- * error isolation: one rejecting disposer cannot truncate the remaining
2093
- * cleanup. Returns the collected cleanup errors in encounter order.
2277
+ * Frames one subscriber may fall behind by before the stream is failed instead
2278
+ * of silently losing an edge. A real run produces a handful of transitions, so
2279
+ * only a consumer that stopped draining can reach it.
2280
+ */
2281
+ const SUBSCRIBER_QUEUE_LIMIT = 64;
2282
+ /**
2283
+ * One subscriber's ordered frame queue. The Host ALWAYS mutates the record
2284
+ * before pushing, so a queue can never observe a frame the record has not
2285
+ * committed, and `close()` is idempotent.
2094
2286
  *
2095
- * Exported so the L5 suite can exercise the exact collection semantics the
2096
- * production composition relies on (module-internal seam, like
2097
- * `createScopedClientModuleLoader`).
2287
+ * An overflowing queue FAILS the reader: dropping frames and continuing would
2288
+ * let a stream report a settlement whose running edge it lost (plan §6.5).
2098
2289
  */
2099
- async function disposeRemoteContributions(disposers) {
2100
- const errors = [];
2101
- for (let index = disposers.length - 1; index >= 0; index -= 1) try {
2102
- await disposers[index]();
2103
- } catch (error) {
2104
- errors.push(error);
2290
+ var FrameQueue = class {
2291
+ frames = [];
2292
+ wake;
2293
+ closed = false;
2294
+ failure;
2295
+ limit = SUBSCRIBER_QUEUE_LIMIT;
2296
+ push(frame) {
2297
+ if (this.closed || this.failure !== void 0) return;
2298
+ if (this.frames.length >= this.limit) {
2299
+ this.failure = /* @__PURE__ */ new Error("piTuiTerminalProgress: the subscriber queue overflowed");
2300
+ this.frames.length = 0;
2301
+ const wake = this.wake;
2302
+ this.wake = void 0;
2303
+ wake?.();
2304
+ return;
2305
+ }
2306
+ this.frames.push(frame);
2307
+ const wake = this.wake;
2308
+ this.wake = void 0;
2309
+ wake?.();
2310
+ }
2311
+ /**
2312
+ * End the consumer's read AFTER every frame already committed to it: a
2313
+ * disposal publishes the retired interval BEFORE it ends the watchers, and a
2314
+ * committed terminal fact must never be dropped in flight.
2315
+ */
2316
+ close() {
2317
+ if (this.closed) return;
2318
+ this.closed = true;
2319
+ const wake = this.wake;
2320
+ this.wake = void 0;
2321
+ wake?.();
2322
+ }
2323
+ async next() {
2324
+ for (;;) {
2325
+ const frame = this.frames.shift();
2326
+ if (frame !== void 0) return {
2327
+ value: frame,
2328
+ done: false
2329
+ };
2330
+ if (this.failure !== void 0) throw this.failure;
2331
+ if (this.closed) return {
2332
+ value: void 0,
2333
+ done: true
2334
+ };
2335
+ await new Promise((resolve) => {
2336
+ this.wake = resolve;
2337
+ });
2338
+ }
2339
+ }
2340
+ };
2341
+ /**
2342
+ * The Host endpoint of the private stream. One instance per Remote Host
2343
+ * composition; the descriptors and the subscriptions leave with the fiber.
2344
+ */
2345
+ var PiTuiTerminalProgressHostService = class extends TypertRemoteService {
2346
+ /** The Typert registry owns the explicit invocation definition. */
2347
+ static inject = ["typert"];
2348
+ /** The narrow Host facts the composition resolved (explicit field: the
2349
+ * strip-only TS loader rejects parameter properties). */
2350
+ deps;
2351
+ /** One opaque identity per Host plugin instance: a Host restart, a new
2352
+ * composition or a re-mounted fiber all invalidate older frames. */
2353
+ hostEpoch = `host-${randomEpoch()}`;
2354
+ records = /* @__PURE__ */ new Map();
2355
+ /** Monotonic Agent-lifetime counter: a replacement ALWAYS outranks every
2356
+ * earlier lifetime of the same session, even after its record was dropped. */
2357
+ epochCounter = 0;
2358
+ disposed = false;
2359
+ /**
2360
+ * @param ctx - the Host context this row is mounted in.
2361
+ * @param deps - the narrow Host facts the composition resolved.
2362
+ */
2363
+ constructor(ctx, deps) {
2364
+ super(ctx, PI_TUI_TERMINAL_PROGRESS_NAMESPACE);
2365
+ this.deps = deps;
2366
+ ctx.on("agent/status", ({ agent, status }) => {
2367
+ this.onAgentStatus(agent, status);
2368
+ }, { global: true });
2369
+ ctx.on("session/event", (session, event) => {
2370
+ this.onSessionEvent(session, event.type, event.data);
2371
+ }, { global: true });
2372
+ ctx.on("agent/disposed", ({ agent }) => {
2373
+ this.onAgentDisposed(agent);
2374
+ }, { global: true });
2375
+ ctx.effect(() => () => {
2376
+ this.closeAll();
2377
+ }, "pi-tui-terminal-progress-watchers");
2378
+ }
2379
+ /**
2380
+ * The private Remote method (`piTuiTerminalProgress/watch`): the ONE
2381
+ * per-session ordered stream, opening with the authoritative snapshot of the
2382
+ * instant it subscribes and then every real Host-side change (plan §6.5).
2383
+ *
2384
+ * The subscriber is registered and the cut (revision + current state) is
2385
+ * captured in the SAME synchronous block before the first `yield`, so an
2386
+ * update can neither be lost between the snapshot and the subscription nor be
2387
+ * replayed twice.
2388
+ */
2389
+ async *watch(sessionId, signal) {
2390
+ const record = this.recordFor(sessionId);
2391
+ const queue = new FrameQueue();
2392
+ const cut = record.revision;
2393
+ const snapshot = {
2394
+ kind: "snapshot",
2395
+ sessionId,
2396
+ hostEpoch: this.hostEpoch,
2397
+ agentEpoch: record.agentEpoch,
2398
+ revision: cut,
2399
+ running: record.running,
2400
+ outcome: record.outcome
2401
+ };
2402
+ record.subscribers.add(queue);
2403
+ const onAbort = () => {
2404
+ queue.close();
2405
+ };
2406
+ if (signal.aborted) queue.close();
2407
+ else signal.addEventListener("abort", onAbort, { once: true });
2408
+ try {
2409
+ yield snapshot;
2410
+ for (;;) {
2411
+ const next = await queue.next();
2412
+ if (next.done === true) return;
2413
+ yield next.value;
2414
+ }
2415
+ } finally {
2416
+ signal.removeEventListener("abort", onAbort);
2417
+ record.subscribers.delete(queue);
2418
+ this.reclaim(record);
2419
+ }
2420
+ }
2421
+ /**
2422
+ * Drop a record nobody watches and no Agent owns. A watch of a session that
2423
+ * has no live Agent must not leave an empty record behind for the rest of the
2424
+ * Host's life: it is observable by nothing, and the next Agent lifetime starts
2425
+ * a FRESH record carrying a HIGHER `agentEpoch` (the epoch counter never
2426
+ * rewinds), so no Client provenance can be resurrected across the gap.
2427
+ */
2428
+ reclaim(record) {
2429
+ if (record.subscribers.size > 0 || record.agent !== void 0) return;
2430
+ if (this.records.get(record.sessionId) === record) this.records.delete(record.sessionId);
2431
+ }
2432
+ /** The live `agent/status` transition of one Agent (plan §6.4). */
2433
+ onAgentStatus(agent, status) {
2434
+ if (this.deps.agentFor(agent.session.id) !== agent) return;
2435
+ const record = this.recordFor(agent.session.id);
2436
+ if (record.agent !== agent) return;
2437
+ this.publish(record, record.fold.status(status === "running"));
2438
+ }
2439
+ /** One durable Session event (plan §6.4): evidence only, never an interim commit. */
2440
+ onSessionEvent(session, type, data) {
2441
+ const record = this.records.get(session.id);
2442
+ if (record === void 0 || record.agent === void 0) return;
2443
+ if (record.session !== session) return;
2444
+ if (type === "turn/start") {
2445
+ const turn = turnOf(data);
2446
+ if (turn !== void 0) record.fold.turnStart(turn);
2447
+ return;
2448
+ }
2449
+ if (type === "turn/end") {
2450
+ const turn = turnOf(data);
2451
+ const kind = reasonKindOf(data);
2452
+ if (turn !== void 0 && kind !== void 0) record.fold.turnEnd(turn, kind);
2453
+ }
2454
+ }
2455
+ /** The Agent lifetime ended (plan §6.4): retire honestly, end the watchers. */
2456
+ onAgentDisposed(agent) {
2457
+ const record = this.records.get(agent.session.id);
2458
+ if (record === void 0 || record.agent !== agent) return;
2459
+ const retired = record.fold.retire();
2460
+ if (retired !== void 0) this.publish(record, retired);
2461
+ this.records.delete(agent.session.id);
2462
+ for (const subscriber of record.subscribers) subscriber.close();
2105
2463
  }
2106
- return errors;
2107
- }
2108
- /**
2109
- * Compose one fresh official Client `Context` over the Host carrier:
2110
- * typert -> Connection (explicit transport) -> Gateway -> the eleven explicit
2111
- * `/remote` contributions -> the private pi-tui contribution (TS8-HF1) ->
2112
- * fileUpload -> Sessions -> Jobs, then wait for initial readiness. On
2113
- * construction failure the partial composition unwinds immediately; the
2114
- * loader shim is never active during plugin execution.
2115
- */
2116
- async function createRemoteClientRuntime(options) {
2117
- const modules = await loadOfficialClientModulesOnce();
2118
- const { carrier } = options;
2119
- const context = new Context();
2120
- let typertFiber;
2121
- let connectionFiber;
2122
- let gatewayFiber;
2123
- let fileUploadFiber;
2124
- let sessionFiber;
2125
- let jobsFiber;
2126
- let services;
2127
- const contributionDisposers = [];
2128
- let disposed = false;
2129
2464
  /**
2130
- * The frozen §16 shutdown sequence: domain Clients (reverse), the explicit
2131
- * `/remote` contributions (reverse), Gateway/Connection/Typert (reverse),
2132
- * then the Client root. Unwinding a partial composition runs the SAME
2133
- * order over whatever subset exists: a fiber whose startup rejected is
2134
- * already assigned, so it unwinds at its own position; only stages that
2135
- * were never reached are skipped.
2136
- *
2137
- * Contribution-disposer failures are isolated (collected, never allowed to
2138
- * truncate the remaining cleanup). Cordis contains unload-disposer failures
2139
- * inside `fiber.dispose()` (they are logged there, never propagated), so
2140
- * the fiber steps cannot reject.
2141
- *
2142
- * @returns the collected contribution-disposer cleanup errors.
2465
+ * The record of one session, bound to the live Agent the authoritative Host
2466
+ * registry currently holds. Creation AND a replaced Agent lifetime consume a
2467
+ * new `agentEpoch` and reset the interval: a new Agent can never inherit the
2468
+ * previous lifetime's evidence (plan §6.3/§6.4).
2143
2469
  */
2144
- const shutdown = async () => {
2145
- for (const fiber of [
2146
- jobsFiber,
2147
- sessionFiber,
2148
- fileUploadFiber
2149
- ]) await fiber?.dispose();
2150
- const contributionErrors = await disposeRemoteContributions(contributionDisposers);
2151
- contributionDisposers.length = 0;
2152
- for (const fiber of [
2153
- gatewayFiber,
2154
- connectionFiber,
2155
- typertFiber
2156
- ]) await fiber?.dispose();
2157
- await context.fiber.dispose();
2158
- return contributionErrors;
2159
- };
2160
- const unwind = async () => {
2161
- disposed = true;
2162
- return shutdown();
2163
- };
2164
- try {
2165
- typertFiber = context.plugin(modules.typert);
2166
- await typertFiber;
2167
- connectionFiber = context.plugin((connectionContext) => {
2168
- modules.connection.installConnection(connectionContext, { transport: {
2169
- ownsHost: true,
2170
- fetch: carrier.fetch,
2171
- openStream: carrier.openStream
2172
- } });
2470
+ recordFor(sessionId) {
2471
+ let record = this.records.get(sessionId);
2472
+ if (record === void 0) {
2473
+ record = {
2474
+ sessionId,
2475
+ agent: void 0,
2476
+ session: void 0,
2477
+ agentEpoch: 0,
2478
+ fold: createTerminalProgressInterval((kind) => {
2479
+ this.deps.onUnknownReason(kind);
2480
+ }),
2481
+ revision: 0,
2482
+ running: false,
2483
+ outcome: "idle",
2484
+ subscribers: /* @__PURE__ */ new Set()
2485
+ };
2486
+ this.records.set(sessionId, record);
2487
+ }
2488
+ const live = this.deps.agentFor(sessionId);
2489
+ if (live !== void 0 && live !== record.agent) this.rebind(record, live);
2490
+ return record;
2491
+ }
2492
+ /**
2493
+ * Bind one Agent lifetime: the running truth is read from the Agent's OWN
2494
+ * current status (a plugin mounted mid-run may therefore report `working`),
2495
+ * but the outcome starts at `idle` — an unobserved start can never prove a
2496
+ * settlement. The rebind is ALWAYS published, because the epoch change is
2497
+ * itself a fact the Client must fence on.
2498
+ */
2499
+ rebind(record, agent) {
2500
+ record.agent = agent;
2501
+ record.session = agent.session;
2502
+ record.agentEpoch = ++this.epochCounter;
2503
+ const running = agent.status === "running";
2504
+ record.fold.apply({
2505
+ active: running,
2506
+ outcome: "idle"
2173
2507
  });
2174
- await connectionFiber;
2175
- gatewayFiber = context.plugin(modules.gateway);
2176
- await gatewayFiber;
2177
- for (const contribution of REMOTE_CONTRIBUTIONS) contributionDisposers.push(await context.remote.$mount(contribution));
2178
- contributionDisposers.push(await context.remote.$mount(PI_TUI_CLIENT_CONTRIBUTION));
2179
- fileUploadFiber = context.plugin(modules.fileUpload);
2180
- await fileUploadFiber;
2181
- sessionFiber = context.plugin(modules.session);
2182
- await sessionFiber;
2183
- jobsFiber = context.plugin(modules.jobs);
2184
- await jobsFiber;
2185
- services = {
2186
- connection: context.get("connection"),
2187
- sessions: context.get("sessions"),
2188
- jobs: context.get("jobs")
2508
+ record.running = running;
2509
+ record.outcome = "idle";
2510
+ record.revision += 1;
2511
+ this.broadcast(record, "update");
2512
+ }
2513
+ /** Commit one fold transition: mutate the record FIRST, then broadcast. */
2514
+ publish(record, next) {
2515
+ if (next === void 0) return;
2516
+ if (next.active === record.running && next.outcome === record.outcome) return;
2517
+ record.running = next.active;
2518
+ record.outcome = next.outcome;
2519
+ record.revision += 1;
2520
+ this.broadcast(record, "update");
2521
+ }
2522
+ broadcast(record, kind) {
2523
+ const frame = {
2524
+ kind,
2525
+ sessionId: record.sessionId,
2526
+ hostEpoch: this.hostEpoch,
2527
+ agentEpoch: record.agentEpoch,
2528
+ revision: record.revision,
2529
+ running: record.running,
2530
+ outcome: record.outcome
2189
2531
  };
2190
- await waitForInitialReadiness(services.connection, services.sessions, options.signal);
2191
- } catch (error) {
2192
- const cleanupErrors = await unwind();
2193
- const failure = error instanceof Error ? error : new Error(String(error));
2194
- if (cleanupErrors.length > 0) mergeCause(failure, cleanupErrors.length === 1 ? cleanupErrors[0] : new AggregateError(cleanupErrors, "remote client runtime: unwind disposal failures"));
2195
- throw failure;
2532
+ for (const subscriber of record.subscribers) subscriber.push(frame);
2196
2533
  }
2197
- const { connection, sessions, jobs } = services;
2198
- return {
2199
- context,
2200
- connection,
2201
- sessions,
2202
- jobs,
2203
- remote: context.remote,
2204
- async dispose() {
2205
- if (disposed) return;
2206
- disposed = true;
2207
- const cleanupErrors = await shutdown();
2208
- if (cleanupErrors.length > 0) {
2209
- const failure = cleanupErrors[0] instanceof Error ? cleanupErrors[0] : new Error(String(cleanupErrors[0]));
2210
- if (cleanupErrors.length > 1) mergeCause(failure, new AggregateError(cleanupErrors.slice(1), "remote client runtime: remaining disposal failures"));
2211
- throw failure;
2212
- }
2213
- }
2214
- };
2534
+ /** End every watcher (the row's fiber is going away). */
2535
+ closeAll() {
2536
+ if (this.disposed) return;
2537
+ this.disposed = true;
2538
+ for (const record of this.records.values()) for (const subscriber of record.subscribers) subscriber.close();
2539
+ }
2540
+ };
2541
+ /** An opaque, process-unique Host-plugin identity (the wire sees only a string). */
2542
+ function randomEpoch() {
2543
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
2215
2544
  }
2545
+ //#endregion
2546
+ //#region src/app/remote/host-prerequisites.ts
2216
2547
  /**
2217
- * Initial readiness: a defined Connection
2218
- * generation AND a `ready` Session list. Subscription-driven with no
2219
- * production timeout; the lifecycle signal aborts the wait and every listener
2220
- * is removed on settle or abort.
2548
+ * Host services the ordinary Host Context must already expose before any
2549
+ * Remote Host row mounts. The check fails fast with the missing service named
2550
+ * instead of parking the runtime.
2221
2551
  */
2222
- async function waitForInitialReadiness(connection, sessions, signal) {
2223
- const isReady = () => connection.generation.getSnapshot() !== void 0 && sessions.list.getSnapshot().phase === "ready";
2224
- if (signal?.aborted) throw new Error("remote client runtime: aborted before initial readiness", { cause: signal.reason });
2225
- if (isReady()) return;
2226
- await new Promise((resolve, reject) => {
2227
- let settled = false;
2228
- let abortListener;
2229
- const settle = () => {
2230
- if (settled) return;
2231
- if (isReady()) {
2232
- settled = true;
2233
- cleanup();
2234
- resolve();
2235
- }
2236
- };
2237
- const generationUnsubscribe = connection.generation.subscribe(settle);
2238
- const listUnsubscribe = sessions.list.subscribe(settle);
2239
- const cleanup = () => {
2240
- generationUnsubscribe();
2241
- listUnsubscribe();
2242
- if (abortListener !== void 0) signal?.removeEventListener("abort", abortListener);
2243
- };
2244
- if (signal !== void 0) {
2245
- abortListener = () => {
2246
- if (settled) return;
2247
- settled = true;
2248
- cleanup();
2249
- reject(new Error("remote client runtime: aborted before initial readiness", { cause: signal.reason }));
2250
- };
2251
- if (signal.aborted) {
2252
- abortListener();
2253
- return;
2254
- }
2255
- signal.addEventListener("abort", abortListener, { once: true });
2256
- }
2257
- settle();
2258
- });
2552
+ const REMOTE_HOST_PREREQUISITE_SERVICES = [
2553
+ "credentials",
2554
+ "userQuestions",
2555
+ "typert",
2556
+ "typertGateway",
2557
+ "agents",
2558
+ "agentDefaultModel",
2559
+ "attachments",
2560
+ "commands",
2561
+ "fileReferences",
2562
+ "fs",
2563
+ "workingDirectory",
2564
+ "llm",
2565
+ "sessions",
2566
+ "sessionProjections",
2567
+ "sessionQuery",
2568
+ "workspaceRegistry",
2569
+ "jobController",
2570
+ "workspaceFiles"
2571
+ ];
2572
+ /**
2573
+ * Fail fast when the ordinary Host lacks one of the required base services.
2574
+ * Reads via the reflect store so the diagnostic can name the missing key
2575
+ * without depending on any one service's shape.
2576
+ */
2577
+ function assertRemoteHostPrerequisites(hostContext) {
2578
+ for (const service of REMOTE_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`);
2259
2579
  }
2260
2580
  //#endregion
2261
- //#region src/runtime/remote/prompt-serializer-remote.ts
2262
- /** Base64-encode one byte buffer (Node Buffer, kept inside the adapter). */
2263
- function base64Of(bytes) {
2264
- return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
2265
- }
2266
- /** The echo attachment view of one staged image (display facts only). */
2267
- function previewOf(image) {
2581
+ //#region src/app/remote/host-runtime.ts
2582
+ /**
2583
+ * Fixed private base URL used only to construct valid `Request` objects for
2584
+ * the shared Fetch handler. It is not a global location, a server URL, a TCP
2585
+ * listener, or an authentication surface.
2586
+ */
2587
+ const IN_PROCESS_BASE_URL = "http://dsh-pi-tui-remote.in-process/";
2588
+ async function* emptyUplink() {}
2589
+ /** Build the in-process carrier over the Host connection + gateway seams.
2590
+ *
2591
+ * The carrier speaks for the Host Connection's OWN owner Peer
2592
+ * (`HostConnectionService.browserPeer`, created inside the service constructor
2593
+ * with `principal: { kind: 'owner' }` and disposed by the Connection plugin
2594
+ * fiber). The SAME reference is passed to the shared Fetch handler and to
2595
+ * `wireStream.open`, so one identity — and one lifetime — covers both the
2596
+ * unary and the streaming path; the carrier never creates, caches, or disposes
2597
+ * a Peer of its own. */
2598
+ function createInProcessCarrier(hostContext) {
2599
+ const connection = hostContext.connection;
2600
+ const peer = connection.browserPeer;
2601
+ const shared = connection.createSharedFetchHandler("/api");
2602
+ const gateway = hostContext.typertGateway;
2268
2603
  return {
2269
- type: "image",
2270
- value: {
2271
- previewUrl: "",
2272
- ...image.name !== void 0 ? { name: image.name } : {},
2273
- width: image.width,
2274
- height: image.height
2604
+ ownsHost: true,
2605
+ fetch(input, init) {
2606
+ const request = input instanceof Request ? new Request(input, init) : new Request(new URL(String(input), IN_PROCESS_BASE_URL), init);
2607
+ return shared.fetch(request, peer);
2608
+ },
2609
+ openStream(endpoint, payload, signal, uplink) {
2610
+ return (async function* () {
2611
+ yield* await gateway.wireStream.open(endpoint, payload, uplink ?? emptyUplink(), peer, signal);
2612
+ })();
2275
2613
  }
2276
2614
  };
2277
2615
  }
2278
- /** Detach the official imageLimits projection value; `undefined` when the
2279
- * projection is absent for this session (the recheck then keeps only the
2280
- * Client-side conservative caps — never a guessed limit). */
2281
- function detachedImageLimits(value) {
2282
- if (typeof value !== "object" || value === null) return void 0;
2283
- const limits = value;
2284
- if (typeof limits.maxImagesPerMessage !== "number" || typeof limits.maxMessageImageBytes !== "number") return void 0;
2285
- return {
2286
- maxImagesPerMessage: limits.maxImagesPerMessage,
2287
- maxMessageImageBytes: limits.maxMessageImageBytes
2288
- };
2289
- }
2290
- /** The production Remote prompt serializer. */
2291
- var RemotePromptSerializerProduction = class RemotePromptSerializerProduction {
2292
- attachments;
2293
- sessions;
2294
- constructor(attachments) {
2295
- this.attachments = attachments;
2296
- }
2297
- /** Build the production serializer over the official Client sessions face:
2298
- * recalled durable images read their authorized bytes through the exact
2299
- * retained binding, addressed by the PreparedPrompt's own session id. */
2300
- static overSessions(sessions) {
2301
- const serializer = new RemotePromptSerializerProduction({ async readAttachment(sessionId, attachmentId) {
2302
- const binding = sessions.binding(sessionId);
2303
- if (binding === void 0) return {
2304
- ok: false,
2305
- error: /* @__PURE__ */ new Error(`session "${sessionId}" is not available for an attachment read`)
2306
- };
2307
- const result = await binding.session.readAttachment(attachmentId);
2308
- if (result.ok) return {
2309
- ok: true,
2310
- data: result.value.data
2311
- };
2312
- return {
2313
- ok: false,
2314
- error: result.error
2315
- };
2316
- } });
2317
- serializer.sessions = sessions;
2318
- return serializer;
2319
- }
2320
- preflight(prepared) {
2321
- const prompt = prepared;
2322
- if (prompt === void 0 || prompt === null || typeof prompt !== "object" || !Array.isArray(prompt.segments)) return {
2323
- kind: "unsupported",
2324
- reason: "the submission carries no prepared prompt snapshot"
2325
- };
2326
- if (prompt.hasFiles) return {
2327
- kind: "unsupported",
2328
- reason: "generic file attachments require an upload receipt this Remote composition does not provide"
2329
- };
2330
- for (const segment of prompt.segments) if (segment.type === "image") {
2331
- if (segment.image.recalledRef === void 0 && segment.image.byteLength === 0) return {
2332
- kind: "unsupported",
2333
- reason: "a staged image carries neither local bytes nor a durable reference"
2334
- };
2335
- if (segment.image.recalledRef !== void 0 && this.attachments === void 0) return {
2336
- kind: "unsupported",
2337
- reason: "recalled durable images need the official attachment read, which this composition does not provide"
2338
- };
2339
- }
2340
- if (this.sessions !== void 0) {
2341
- const images = prompt.segments.filter((segment) => segment.type === "image");
2342
- if (images.length > 0) {
2343
- const binding = this.sessions.binding(prompt.sessionId);
2344
- const limits = binding === void 0 ? void 0 : detachedImageLimits(binding.session.projections.faceOf("imageLimits").getSnapshot());
2345
- if (limits !== void 0) {
2346
- if (images.length > limits.maxImagesPerMessage) return {
2347
- kind: "unsupported",
2348
- reason: `too many images: ${images.length} attached, the current limit is ${limits.maxImagesPerMessage} per message`
2349
- };
2350
- const aggregate = images.reduce((total, segment) => total + segment.image.byteLength, 0);
2351
- if (aggregate > limits.maxMessageImageBytes) return {
2352
- kind: "unsupported",
2353
- reason: `images total ${aggregate} bytes; the current aggregate limit is ${limits.maxMessageImageBytes} bytes`
2354
- };
2355
- }
2356
- }
2616
+ /**
2617
+ * Mount the exact additive official Host closure (§2.4.1) onto the existing
2618
+ * Host Context and await every fiber. The existing `jobController` service is
2619
+ * asserted before and after construction and never re-mounted.
2620
+ *
2621
+ * On a partial construction failure the already-mounted fibers unwind in
2622
+ * reverse order before the original error rethrows.
2623
+ */
2624
+ async function createRemoteHostRuntime(hostContext, options = {}) {
2625
+ assertRemoteHostPrerequisites(hostContext);
2626
+ const diag = options.diag ?? { warn: (message, fields) => {
2627
+ hostContext.logger("remote-host").warn(message, fields);
2628
+ } };
2629
+ /** The live Agent of one session, read PER CALL through the authoritative
2630
+ * Host registry (never a composition-time snapshot). */
2631
+ const liveAgentFor = (sessionId) => hostContext.reflect.get("agents")?.get(sessionId);
2632
+ const jobControllerBefore = hostContext.reflect.get("jobController");
2633
+ const userQuestionsBefore = hostContext.reflect.get("userQuestions");
2634
+ const fibers = [];
2635
+ let carrier;
2636
+ let disposed = false;
2637
+ /**
2638
+ * Reverse-dispose every mounted fiber. Per-step error isolation: one
2639
+ * rejecting disposer cannot truncate the remaining cleanup. Returns the
2640
+ * collected disposal errors instead of throwing, so the construction
2641
+ * failure path can rethrow the ORIGINAL error with the cleanup failures
2642
+ * attached as its `cause`.
2643
+ */
2644
+ const collectUnwind = async () => {
2645
+ const errors = [];
2646
+ for (let index = fibers.length - 1; index >= 0; index -= 1) try {
2647
+ await fibers[index].dispose();
2648
+ } catch (error) {
2649
+ errors.push(error);
2357
2650
  }
2358
- return {
2359
- kind: "ok",
2360
- echo: {
2361
- text: prompt.segments.map((segment) => segment.type === "text" ? segment.text : segment.type === "image" ? "[image]" : "[file]").join(""),
2362
- attachments: prompt.segments.filter((segment) => segment.type === "image").map((segment) => previewOf(segment.image))
2363
- }
2364
- };
2365
- }
2366
- async serialize(prepared, signal) {
2367
- const prompt = prepared;
2368
- if (prompt === void 0 || prompt === null || typeof prompt !== "object" || !Array.isArray(prompt.segments)) return {
2369
- kind: "unsupported",
2370
- reason: "the submission carries no prepared prompt snapshot"
2371
- };
2372
- if (prompt.hasFiles) return {
2373
- kind: "unsupported",
2374
- reason: "generic file attachments require an upload receipt this Remote composition does not provide"
2375
- };
2376
- const parts = [];
2377
- for (const segment of prompt.segments) {
2378
- signal?.throwIfAborted();
2379
- if (segment.type === "text") {
2380
- if (segment.text !== "") parts.push({
2381
- type: "text",
2382
- text: segment.text
2383
- });
2384
- continue;
2385
- }
2386
- if (segment.type === "image") {
2387
- const image = segment.image;
2388
- if (image.recalledRef !== void 0) {
2389
- const read = await this.attachments.readAttachment(prompt.sessionId, image.recalledRef.attachmentId);
2390
- signal?.throwIfAborted();
2391
- if (!read.ok) return {
2392
- kind: "unsupported",
2393
- reason: `the durable image bytes could not be read for re-send (${String(read.error)})`
2394
- };
2395
- parts.push({
2396
- type: "image",
2397
- mediaType: image.mediaType,
2398
- data: base64Of(read.data),
2399
- ...image.name !== void 0 ? { name: image.name } : {}
2400
- });
2401
- continue;
2651
+ fibers.length = 0;
2652
+ return errors;
2653
+ };
2654
+ try {
2655
+ const contributionFiber = hostContext.inject(["typert"], (contributionCtx) => {
2656
+ contributionCtx.effect(() => contributionCtx.typert.register(PI_TUI_HOST_CONTRIBUTION), "pi-tui-private-remote-host");
2657
+ });
2658
+ fibers.push(contributionFiber);
2659
+ await contributionFiber;
2660
+ const fileReferenceFiber = hostContext.inject(PiTuiFileReferenceHostService.inject, (pluginCtx) => {
2661
+ new PiTuiFileReferenceHostService(pluginCtx, {
2662
+ agentFor: (sessionId) => liveAgentFor(sessionId),
2663
+ official: () => hostContext.reflect.get("fileReferences")
2664
+ });
2665
+ });
2666
+ fibers.push(fileReferenceFiber);
2667
+ await fileReferenceFiber;
2668
+ const terminalProgressFiber = hostContext.inject(PiTuiTerminalProgressHostService.inject, (pluginCtx) => {
2669
+ new PiTuiTerminalProgressHostService(pluginCtx, {
2670
+ agentFor: (sessionId) => liveAgentFor(sessionId),
2671
+ onUnknownReason: (kind) => {
2672
+ diag.warn("terminal progress: unknown turn/end reason", { kind });
2402
2673
  }
2403
- parts.push({
2404
- type: "image",
2405
- mediaType: image.mediaType,
2406
- data: base64Of(image.bytes),
2407
- ...image.name !== void 0 ? { name: image.name } : {}
2408
- });
2409
- }
2674
+ });
2675
+ });
2676
+ fibers.push(terminalProgressFiber);
2677
+ await terminalProgressFiber;
2678
+ const connFiber = hostContext.plugin((connectionContext) => {
2679
+ new HostConnectionService(connectionContext, [], {});
2680
+ });
2681
+ fibers.push(connFiber);
2682
+ await connFiber;
2683
+ const uploadFiber = hostContext.plugin(FileUploads);
2684
+ fibers.push(uploadFiber);
2685
+ await uploadFiber;
2686
+ const statsFiber = hostContext.plugin(sessionStats);
2687
+ fibers.push(statsFiber);
2688
+ await statsFiber;
2689
+ const performanceFiber = hostContext.plugin(performance_host_exports);
2690
+ fibers.push(performanceFiber);
2691
+ await performanceFiber;
2692
+ const outlineFiber = hostContext.plugin(sessionTurnOutline);
2693
+ fibers.push(outlineFiber);
2694
+ await outlineFiber;
2695
+ const sessionCtrlFiber = hostContext.inject(SessionController.inject, (controllerContext) => {
2696
+ new SessionController(controllerContext, { nativeOpen: false });
2697
+ });
2698
+ fibers.push(sessionCtrlFiber);
2699
+ await sessionCtrlFiber;
2700
+ const settingsFiber = hostContext.plugin(SettingsController);
2701
+ fibers.push(settingsFiber);
2702
+ await settingsFiber;
2703
+ const remotesFiber = hostContext.plugin({
2704
+ inject,
2705
+ apply
2706
+ });
2707
+ fibers.push(remotesFiber);
2708
+ await remotesFiber;
2709
+ const exportFiber = hostContext.plugin(sessionLogExport);
2710
+ fibers.push(exportFiber);
2711
+ await exportFiber;
2712
+ const jobControllerAfter = hostContext.reflect.get("jobController");
2713
+ if (jobControllerAfter === void 0 || jobControllerAfter.typertRemote === void 0 || jobControllerAfter.typertRemote !== jobControllerBefore.typertRemote) throw new Error("remote host runtime: the existing jobController service was replaced by the M3 composition");
2714
+ const userQuestionsAfter = hostContext.reflect.get("userQuestions");
2715
+ if (userQuestionsAfter === void 0 || userQuestionsAfter.typertRemote === void 0 || userQuestionsAfter.typertRemote !== userQuestionsBefore?.typertRemote) throw new Error("remote host runtime: the existing userQuestions service was replaced by the M3 composition");
2716
+ carrier = createInProcessCarrier(hostContext);
2717
+ } catch (error) {
2718
+ const disposeErrors = await collectUnwind();
2719
+ if (disposeErrors.length > 0) {
2720
+ const secondary = disposeErrors.length === 1 ? disposeErrors[0] : new AggregateError(disposeErrors, "remote host runtime: unwind disposal failures");
2721
+ throw mergeCause(error instanceof Error ? error : new Error(String(error)), secondary);
2410
2722
  }
2411
- return {
2412
- kind: "ok",
2413
- content: Object.freeze(parts)
2414
- };
2723
+ throw error;
2415
2724
  }
2416
- };
2417
- //#endregion
2418
- //#region src/runtime/remote/host-user-shell-remote.ts
2419
- /** The one truthful message every Remote admission returns. */
2420
- const CARRIER_GAP_MESSAGE = "Host user-shell execution is unavailable in this Remote composition — nothing was executed";
2421
- /** The Remote backend's Host user-shell port: truthful, inert, fail-closed. */
2422
- var RemoteHostUserShellPort = class {
2423
- availability = {
2424
- supported: false,
2425
- policies: []
2426
- };
2427
- async execute(_request) {
2428
- return {
2429
- kind: "unavailable",
2430
- reason: {
2431
- reason: "carrier-gap",
2432
- message: CARRIER_GAP_MESSAGE
2725
+ return {
2726
+ hostContext,
2727
+ carrier,
2728
+ async dispose() {
2729
+ if (disposed) return;
2730
+ disposed = true;
2731
+ const disposeErrors = await collectUnwind();
2732
+ if (disposeErrors.length > 0) {
2733
+ const failure = disposeErrors[0] instanceof Error ? disposeErrors[0] : new Error(String(disposeErrors[0]));
2734
+ if (disposeErrors.length > 1) mergeCause(failure, new AggregateError(disposeErrors.slice(1), "remote host runtime: remaining disposal failures"));
2735
+ throw failure;
2433
2736
  }
2434
- };
2435
- }
2436
- };
2737
+ }
2738
+ };
2739
+ }
2437
2740
  //#endregion
2438
2741
  //#region src/runtime/remote/interaction-remote.ts
2439
2742
  const USER_QUESTIONS_PROJECTION_KEY = "userQuestions";
@@ -2697,32 +3000,55 @@ var RemotePluginManagerPort = class {
2697
3000
  });
2698
3001
  }
2699
3002
  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"));
3003
+ return detachInspection(await this.currentness("inspect", () => this.remote.pluginManager.inspect(spec, registry === void 0 ? void 0 : { registry }, signal)));
3004
+ }
3005
+ /**
3006
+ * One Remote result (a read or a settlement) fenced to the Connection
3007
+ * generation captured BEFORE dispatch. The fence covers success, an official
3008
+ * refusal result and a transport rejection alike: a reply carried by a
3009
+ * superseded generation is never presented as the new generation's definite
3010
+ * outcome. The Host may already have applied a write (or advanced an
3011
+ * install), so the caller's authoritative inventory reread / request-id
3012
+ * reconcile decides the visible outcome. An unchanged generation preserves
3013
+ * the original error and its real refusal taxonomy.
3014
+ */
3015
+ async currentness(operation, call) {
3016
+ const captured = this.generation.getSnapshot();
3017
+ const stillCurrent = () => Object.is(captured, this.generation.getSnapshot());
3018
+ let value;
3019
+ try {
3020
+ value = unwrapRemote$1(await call(), operation);
3021
+ } catch (error) {
3022
+ if (!stillCurrent()) throw new PluginManagerStaleResultError(operation);
3023
+ throw error;
3024
+ }
3025
+ if (!stillCurrent()) throw new PluginManagerStaleResultError(operation);
3026
+ return value;
2702
3027
  }
2703
3028
  async setBundleEnabled(name, enabled) {
2704
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.setBundleEnabled(name, enabled), "setBundleEnabled"));
3029
+ return detachChange(await this.currentness("setBundleEnabled", () => this.remote.pluginManager.setBundleEnabled(name, enabled)));
2705
3030
  }
2706
3031
  async setPluginEnabled(id, enabled) {
2707
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.setPluginEnabled(id, enabled), "setPluginEnabled"));
3032
+ return detachChange(await this.currentness("setPluginEnabled", () => this.remote.pluginManager.setPluginEnabled(id, enabled)));
2708
3033
  }
2709
3034
  async removeBundle(name) {
2710
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.removeBundle(name), "removeBundle"));
3035
+ return detachChange(await this.currentness("removeBundle", () => this.remote.pluginManager.removeBundle(name)));
2711
3036
  }
2712
3037
  async startInstall(request) {
2713
3038
  const options = {
2714
3039
  requestId: pluginInstallRequestId(request.requestId),
2715
3040
  registry: request.registry,
2716
- ...request.enabled === void 0 ? {} : { enabled: request.enabled }
3041
+ ...request.enabled === void 0 ? {} : { enabled: request.enabled },
3042
+ ...request.approvedBuilds === void 0 ? {} : { approvedBuilds: [...request.approvedBuilds] }
2717
3043
  };
2718
- return detachChange(unwrapRemote$1(await this.remote.pluginManager.installBundle(request.spec, options), "installBundle"));
3044
+ return detachChange(await this.currentness("installBundle", () => this.remote.pluginManager.installBundle(request.spec, options)));
2719
3045
  }
2720
3046
  async waitForInstall(requestId) {
2721
- const result = unwrapRemote$1(await this.remote.pluginManager.waitForInstall(pluginInstallRequestId(requestId)), "waitForInstall");
3047
+ const result = await this.currentness("waitForInstall", () => this.remote.pluginManager.waitForInstall(pluginInstallRequestId(requestId)));
2722
3048
  return result === null ? null : detachChange(result);
2723
3049
  }
2724
3050
  async cancelInstall(requestId) {
2725
- const result = unwrapRemote$1(await this.remote.pluginManager.cancelInstall(pluginInstallRequestId(requestId)), "cancelInstall");
3051
+ const result = await this.currentness("cancelInstall", () => this.remote.pluginManager.cancelInstall(pluginInstallRequestId(requestId)));
2726
3052
  return Object.freeze({ status: result.status });
2727
3053
  }
2728
3054
  subscribeInstall(listener) {
@@ -2786,6 +3112,90 @@ var RemotePluginManagerPort = class {
2786
3112
  }
2787
3113
  };
2788
3114
  //#endregion
3115
+ //#region src/runtime/remote/deliverables-remote.ts
3116
+ /**
3117
+ * The experimental Remote delivered-file read adapter (Delivered files PR2 /
3118
+ * M11): the semantic {@link DeliveredFileReadPort} over the OFFICIAL generated
3119
+ * `workspaceFiles` Remote namespace.
3120
+ *
3121
+ * The Host remains the only authority for the Session's workspace scope, the
3122
+ * byte/line caps and the refusal taxonomy; this adapter owns no workspace
3123
+ * truth and never falls back to a Direct read or the Client filesystem.
3124
+ *
3125
+ * CURRENTNESS: the Connection generation is captured BEFORE dispatch and
3126
+ * compared after it — a reply (success OR refusal) carried by a superseded
3127
+ * generation is stale, so it becomes the repository's existing
3128
+ * `SupersededReadError` instead of the new generation's definite outcome. An
3129
+ * unchanged generation preserves the official refusal (mapped to the port's
3130
+ * vocabulary) and the caller's own cancellation.
3131
+ *
3132
+ * Full contract: docs/architecture/host-client.md.
3133
+ * @module @xmoon76/dsh-pi-tui/runtime/remote/deliverables-remote
3134
+ */
3135
+ function statOf(value) {
3136
+ return value.bytes === void 0 ? { version: value.version } : {
3137
+ version: value.version,
3138
+ bytes: value.bytes
3139
+ };
3140
+ }
3141
+ /** One official result's business value, or its refusal thrown. */
3142
+ function unwrap(result) {
3143
+ if (!result.ok) throw result.error;
3144
+ return result.value;
3145
+ }
3146
+ /** Remote delivered-file reads over the generated `workspaceFiles` namespace. */
3147
+ var RemoteDeliveredFileReadPort = class {
3148
+ namespace;
3149
+ generation;
3150
+ constructor(namespace, generation) {
3151
+ this.namespace = namespace;
3152
+ this.generation = generation;
3153
+ }
3154
+ async stat(sessionId, path, signal) {
3155
+ return statOf(await this.fenced("stat", signal, (namespace) => namespace.stat(sessionId, path, signal)));
3156
+ }
3157
+ async read(sessionId, path, offset, signal) {
3158
+ const limit = 120;
3159
+ const page = await this.fenced("read", signal, (namespace) => namespace.read(sessionId, path, {
3160
+ offset,
3161
+ limit
3162
+ }, signal));
3163
+ return {
3164
+ stat: statOf(page),
3165
+ offset,
3166
+ limit,
3167
+ text: page.text,
3168
+ lines: page.lines,
3169
+ eof: page.eof
3170
+ };
3171
+ }
3172
+ /**
3173
+ * One Remote read fenced to the Connection generation captured BEFORE
3174
+ * dispatch. `operation` names the intent in the stale diagnostic.
3175
+ */
3176
+ async fenced(operation, signal, call) {
3177
+ const namespace = this.namespace;
3178
+ if (namespace === void 0) throw new DeliveredFileReadError("service-unavailable", "the workspaceFiles Remote namespace is not mounted");
3179
+ if (signal.aborted) throw abortReason(signal);
3180
+ const captured = this.generation.getSnapshot();
3181
+ const stillCurrent = () => Object.is(captured, this.generation.getSnapshot());
3182
+ let value;
3183
+ try {
3184
+ value = unwrap(await call(namespace));
3185
+ } catch (error) {
3186
+ if (signal.aborted) throw abortReason(signal);
3187
+ if (!stillCurrent()) throw new SupersededReadError(`delivered file ${operation} superseded`);
3188
+ throw deliveredFileReadErrorFrom(error);
3189
+ }
3190
+ if (!stillCurrent()) throw new SupersededReadError(`delivered file ${operation} superseded`);
3191
+ return value;
3192
+ }
3193
+ };
3194
+ /** The caller's cancellation reason (an `Error` for every standard abort). */
3195
+ function abortReason(signal) {
3196
+ return signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("delivered file read aborted");
3197
+ }
3198
+ //#endregion
2789
3199
  //#region src/runtime/remote/job-observation-remote.ts
2790
3200
  /**
2791
3201
  * The Job-Stop operation-specific settlement table.
@@ -2976,6 +3386,7 @@ var RemoteSessionReader = class {
2976
3386
  cwd: row.cwd,
2977
3387
  ...row.parentId === void 0 ? {} : { parentSession: row.parentId },
2978
3388
  ...row.origin === void 0 ? {} : { origin: row.origin },
3389
+ ...row.formatStatus === void 0 ? {} : { formatStatus: row.formatStatus },
2979
3390
  live: false
2980
3391
  };
2981
3392
  });
@@ -3222,9 +3633,15 @@ function acquireMainSurfaceReference(sessions, sessionId, signal) {
3222
3633
  source: "tuiMainView",
3223
3634
  ...signal === void 0 ? {} : { signal }
3224
3635
  });
3636
+ const binding = reference.binding;
3225
3637
  return {
3226
3638
  sessionId,
3227
- bindingIdentity: reference.binding,
3639
+ bindingIdentity: binding,
3640
+ ready: reference.ready,
3641
+ openState: () => {
3642
+ const session = binding.session;
3643
+ return session !== void 0 && typeof session.getSnapshot === "function" ? session.getSnapshot() : {};
3644
+ },
3228
3645
  release: () => {
3229
3646
  reference.release();
3230
3647
  }
@@ -3350,10 +3767,12 @@ var RemoteSessionWriter = class {
3350
3767
  sessions;
3351
3768
  generation;
3352
3769
  serializer;
3353
- constructor(sessions, generation, serializer) {
3770
+ admission;
3771
+ constructor(sessions, generation, serializer, admission) {
3354
3772
  this.sessions = sessions;
3355
3773
  this.generation = generation;
3356
3774
  this.serializer = serializer;
3775
+ this.admission = admission;
3357
3776
  }
3358
3777
  /**
3359
3778
  * Resolve and PIN the exact generation for one addressed session after
@@ -3424,6 +3843,10 @@ var RemoteSessionWriter = class {
3424
3843
  handle.abandon();
3425
3844
  return remoteNotDispatched();
3426
3845
  }
3846
+ if (this.admission?.isDispatchAllowed() === false) {
3847
+ handle.abandon();
3848
+ return remoteNotDispatched();
3849
+ }
3427
3850
  const result = await binding.session.prompt(serialized.content, mode, void 0, handle.requestId);
3428
3851
  if (result.ok) return {
3429
3852
  kind: "committed",
@@ -3568,7 +3991,8 @@ function classifyCreateFailure(error, requestedSessionId) {
3568
3991
  const FORK_REFUSAL_CODES = /* @__PURE__ */ new Set([
3569
3992
  "gateway/bad-request",
3570
3993
  "session/not-found",
3571
- "session/fork-unavailable"
3994
+ "session/fork-unavailable",
3995
+ "session/migration-required"
3572
3996
  ]);
3573
3997
  function classifyForkFailure(error) {
3574
3998
  const code = errorCode$1(error);
@@ -3599,11 +4023,9 @@ function classifyForkFailure(error) {
3599
4023
  /** The experimental Remote session lifecycle. */
3600
4024
  var RemoteSessionLifecycle = class {
3601
4025
  sessions;
3602
- session;
3603
4026
  generation;
3604
- constructor(sessions, session, generation) {
4027
+ constructor(sessions, generation) {
3605
4028
  this.sessions = sessions;
3606
- this.session = session;
3607
4029
  this.generation = generation;
3608
4030
  }
3609
4031
  async create(request) {
@@ -3618,51 +4040,20 @@ var RemoteSessionLifecycle = class {
3618
4040
  outcome: { kind: "cancelled" }
3619
4041
  };
3620
4042
  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
4043
  let id;
3623
4044
  try {
3624
- id = String(await this.sessions.create({
4045
+ id = await this.sessions.create({
4046
+ ...cwd === void 0 ? {} : { cwd },
3625
4047
  sessionId: request.sessionId,
3626
- ...cwd === void 0 ? {} : { cwd }
3627
- }));
4048
+ ...request.agentPreset === void 0 ? {} : { agentPreset: request.agentPreset }
4049
+ });
3628
4050
  } catch (error) {
3629
4051
  return {
3630
4052
  ownership: ownership(),
3631
4053
  outcome: classifyCreateFailure(error, request.sessionId)
3632
4054
  };
3633
4055
  }
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 {
4056
+ if (typeof id !== "string" || id === "") return {
3666
4057
  ownership: ownership(),
3667
4058
  outcome: {
3668
4059
  kind: "indeterminate",
@@ -3673,29 +4064,7 @@ var RemoteSessionLifecycle = class {
3673
4064
  requestedSessionId: request.sessionId
3674
4065
  }
3675
4066
  };
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
- }
4067
+ const handle = { session: { id } };
3699
4068
  if (ownership() === "superseded") return {
3700
4069
  ownership: "superseded",
3701
4070
  outcome: {
@@ -3703,7 +4072,7 @@ var RemoteSessionLifecycle = class {
3703
4072
  handle
3704
4073
  }
3705
4074
  };
3706
- return this.ownPublishedSession(publishedId, ownership, request.signal);
4075
+ return this.ownPublishedSession(id, ownership, request.signal);
3707
4076
  }
3708
4077
  /**
3709
4078
  * Take Client generation ownership of a just-published Session.
@@ -3793,6 +4162,45 @@ var RemoteSessionLifecycle = class {
3793
4162
  outcome: { kind: "cancelled" }
3794
4163
  };
3795
4164
  }
4165
+ try {
4166
+ await owner.ready;
4167
+ } catch (error) {
4168
+ owner.release();
4169
+ if (!Object.is(captured, this.generation.getSnapshot())) return {
4170
+ ownership: "superseded",
4171
+ outcome: { kind: "cancelled" }
4172
+ };
4173
+ if (isAborted(request.signal)) return {
4174
+ ownership: "superseded",
4175
+ outcome: { kind: "cancelled" }
4176
+ };
4177
+ return {
4178
+ ownership: "current",
4179
+ outcome: {
4180
+ kind: "unavailable",
4181
+ message: `session "${request.sessionId}" failed to open: ${remoteFailureMessage(error)}`
4182
+ }
4183
+ };
4184
+ }
4185
+ if (!Object.is(captured, this.generation.getSnapshot()) || isAborted(request.signal)) {
4186
+ owner.release();
4187
+ return {
4188
+ ownership: "superseded",
4189
+ outcome: { kind: "cancelled" }
4190
+ };
4191
+ }
4192
+ const opened = owner.openState();
4193
+ if (opened.openState !== "open") {
4194
+ owner.release();
4195
+ 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})`;
4196
+ return {
4197
+ ownership: "current",
4198
+ outcome: {
4199
+ kind: "unavailable",
4200
+ message: `session "${request.sessionId}" failed to open: ${reason}`
4201
+ }
4202
+ };
4203
+ }
3796
4204
  return {
3797
4205
  ownership: "current",
3798
4206
  outcome: {
@@ -3828,7 +4236,8 @@ var RemoteSessionLifecycle = class {
3828
4236
  try {
3829
4237
  childId = String(await this.sessions.fork({
3830
4238
  sessionId: request.sourceSessionId,
3831
- ...request.atSeq === void 0 ? {} : { atSeq: request.atSeq }
4239
+ ...request.atSeq === void 0 ? {} : { atSeq: request.atSeq },
4240
+ allowMigration: false
3832
4241
  }));
3833
4242
  } catch (error) {
3834
4243
  return {
@@ -3952,6 +4361,7 @@ var RemoteSubagentPort = class {
3952
4361
  let signal;
3953
4362
  let canonical;
3954
4363
  let requestId;
4364
+ let timeZone;
3955
4365
  try {
3956
4366
  signal = context.makeSignal();
3957
4367
  canonical = [];
@@ -3964,6 +4374,7 @@ var RemoteSubagentPort = class {
3964
4374
  kind: "rejected",
3965
4375
  reason: { kind: "cancelled" }
3966
4376
  };
4377
+ timeZone = context.clientTimeZone();
3967
4378
  requestId = randomUUID();
3968
4379
  } catch (error) {
3969
4380
  return {
@@ -3980,7 +4391,8 @@ var RemoteSubagentPort = class {
3980
4391
  childSessionId: request.childSessionId,
3981
4392
  mode: "continuable",
3982
4393
  delivery: request.delivery,
3983
- content: canonical
4394
+ content: canonical,
4395
+ clientTimeZone: timeZone
3984
4396
  }, signal);
3985
4397
  if (result.ok) return {
3986
4398
  kind: "ok",
@@ -4858,8 +5270,8 @@ function createRemoteM3ASemantics(runtime, options) {
4858
5270
  return {
4859
5271
  sessionReader: new RemoteSessionReader(sessions, generation),
4860
5272
  pendingInputReader: new RemotePendingInputReader(sessions, generation),
4861
- sessionWriter: new RemoteSessionWriter(sessions, generation, options.promptSerializer),
4862
- sessionLifecycle: new RemoteSessionLifecycle(sessions, remote.session, generation),
5273
+ sessionWriter: new RemoteSessionWriter(sessions, generation, options.promptSerializer, options.isDispatchAllowed === void 0 ? void 0 : { isDispatchAllowed: options.isDispatchAllowed }),
5274
+ sessionLifecycle: new RemoteSessionLifecycle(sessions, generation),
4863
5275
  subagent: new RemoteSubagentPort(remote.subagents),
4864
5276
  catalog: {
4865
5277
  models: modelCatalog,
@@ -4875,6 +5287,7 @@ function createRemoteM3ASemantics(runtime, options) {
4875
5287
  $on: forwardedEvents
4876
5288
  }, generation),
4877
5289
  jobObservation: new RemoteJobObservationPort(runtime.jobs),
5290
+ deliveredFileRead: new RemoteDeliveredFileReadPort(remote.workspaceFiles, generation),
4878
5291
  dispose() {
4879
5292
  if (disposed) return;
4880
5293
  disposed = true;
@@ -4887,10 +5300,10 @@ function createRemoteM3ASemantics(runtime, options) {
4887
5300
  //#endregion
4888
5301
  //#region src/app/remote/session-owners.ts
4889
5302
  /**
4890
- * M3-2 Remote Session owner services: the exact-`SessionBinding` provider of
5303
+ * Remote Session owner services: the exact-`SessionBinding` provider of
4891
5304
  * the consumer-owned `SessionOwnerAccess` / `SessionOwnerRetirement` seams.
4892
5305
  *
4893
- * Identity authority (frozen by M3-2; see `docs/client-server-migration.md` M3-2): the exact
5306
+ * Identity authority (see `docs/architecture/host-client.md`): the exact
4894
5307
  * `SessionReference.binding` OBJECT a retained `ClientSessionOwner` carries is
4895
5308
  * the generation token —
4896
5309
  *
@@ -4911,7 +5324,7 @@ function createRemoteM3ASemantics(runtime, options) {
4911
5324
  * exact Client reference exactly once, and `whenIdleOrAbort` observes the
4912
5325
  * official `SessionSnapshot.running` without ever cancelling the Host session.
4913
5326
  *
4914
- * M3-2 composition note: this provider is not wired into any production
5327
+ * Composition note: this provider is not wired into any production
4915
5328
  * bootstrap yet (M3-3B/M3-4 own the Remote runtime selection seam). Tests and
4916
5329
  * the future Remote composition construct it directly.
4917
5330
  *
@@ -5175,6 +5588,11 @@ var RemoteTaskReader = class {
5175
5588
  * re-enters it ONCE before giving up — otherwise one transient failure would
5176
5589
  * turn every later read (including the Task Center's own retry) into a
5177
5590
  * permanent failure;
5591
+ * - `state === 'migration-required'` (0.2.1-rc.1): the Session needs an official
5592
+ * migration before its projections can be read. Settled and NOT an
5593
+ * authoritative catalog, so this read fails closed with a named error
5594
+ * rather than reporting an empty membership (the fuller migration UX
5595
+ * belongs to the Session-migration stage);
5178
5596
  * - `state === 'ready'` WITHOUT `subagentCatalog`: the official Client clears
5179
5597
  * the projection store and still settles `ready` when `session.projections`
5180
5598
  * answers a null/missing Session, so this is a REAL read failure — exactly
@@ -5214,6 +5632,7 @@ var RemoteTaskReader = class {
5214
5632
  }
5215
5633
  continue;
5216
5634
  }
5635
+ if (state === "migration-required") throw new Error(`the subagentCatalog projection requires an official migration for Session ${sessionId}`);
5217
5636
  const entries = projection.values.subagentCatalog;
5218
5637
  if (entries === void 0) throw new Error(`the subagentCatalog projection is unavailable for Session ${sessionId}`);
5219
5638
  return entries;
@@ -5283,174 +5702,325 @@ var RemoteTaskReader = class {
5283
5702
  //#endregion
5284
5703
  //#region src/app/remote/live-ingress.ts
5285
5704
  /**
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).
5705
+ * Create the ingress factory.
5706
+ *
5707
+ * LIFETIME CONTRACT: the factory installs exactly ONE process-lifetime watch —
5708
+ * a listener on the official Connection generation source, used to remember that
5709
+ * a rollover happened even while no handle exists (a surface rebuild must then
5710
+ * treat its cold attach as verify-first). That watch is NOT owned by a handle
5711
+ * and is never explicitly released: its lifetime is the owning presentation
5712
+ * bundle / Client runtime — the official generation source belongs to the same
5713
+ * Client context and stops delivering when that context is disposed, and the
5714
+ * presentation source (`src/app/remote/presentation-source.ts`) is created once
5715
+ * per aggregate with no separate disposer. Each `subscribe` handle additionally
5716
+ * owns exactly one eventSource subscription plus the current-fact projection
5717
+ * faces, and detaches on an exact BINDING replacement or an explicit `dispose` —
5718
+ * never on a Connection generation rollover, which it adopts (see the module
5719
+ * contract above).
5291
5720
  */
5292
5721
  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();
5722
+ /**
5723
+ * Whether this process observed a Connection rollover. A COLD attach that
5724
+ * happens after one may be hydrating the retained PREVIOUS-generation window
5725
+ * (the upstream journal stream keeps it until the opening page is republished)
5726
+ * and the official faces carry no window-generation marker, so such a handle
5727
+ * starts in verify-first mode: the first publication reconciles the window
5728
+ * instead of being trusted as an incremental delta.
5729
+ */
5730
+ let observedRollover = false;
5731
+ let lastSeenGeneration = generation.getSnapshot();
5732
+ const trackRollover = () => {
5733
+ const current = generation.getSnapshot();
5734
+ if (current !== void 0 && current !== lastSeenGeneration) observedRollover = true;
5735
+ lastSeenGeneration = current;
5736
+ };
5737
+ generation.subscribe(trackRollover);
5738
+ return { subscribe(sessionId, sinks, hydrate) {
5739
+ let disposed = false;
5740
+ let attached;
5741
+ let startedTuples = /* @__PURE__ */ new Set();
5742
+ /** The revision of the last increment DELIVERED — or the revision one
5743
+ * acknowledged recovery committed. Delivery bookkeeping only. */
5744
+ let lastDeliveredRevision = -1;
5745
+ /** `recovering` = the incremental sequence is untrustworthy; the owner
5746
+ * must re-fold the official window and acknowledge the revision. */
5747
+ let mode = "incremental";
5748
+ /** The FULL identity the last wakeup was issued for: a NEW generation,
5749
+ * binding, revision or open state re-arms it. Comparing revisions alone
5750
+ * would swallow a mid-re-fold rollover whose read is already doomed by
5751
+ * the transport fence — the handle would stay recovering with no future
5752
+ * wakeup. */
5753
+ let notified;
5754
+ let notifyQueued = false;
5755
+ /** The Connection generation the delivered sequence belongs to. */
5756
+ let fencedGeneration = generation.getSnapshot();
5757
+ /**
5758
+ * The window revision the OLD generation had published when a rollover was
5759
+ * detected. The upstream RemoteJournalStream KEEPS the old published
5760
+ * window after a reconnect until the new generation's opening page
5761
+ * arrives (`packages/api/gateway/src/client/journal-stream.ts`), so a
5762
+ * re-fold performed in that gap reads a window that is still the DEAD
5763
+ * generation's — its revision and open state look perfectly current. Until
5764
+ * the new generation republishes (a new revision / `replace`), no
5765
+ * acknowledgement may claim that window, otherwise the opening page then
5766
+ * arrives as an ordinary append and the original missing rows return.
5767
+ */
5768
+ let rolloverBaselineRevision;
5307
5769
  const seedTuplesFromWindow = (entries) => {
5308
5770
  for (const entry of entries) {
5309
5771
  if (entry.type !== "transient") continue;
5310
5772
  startedTuples.add(`${entry.event.data.attemptId}:${entry.event.data.turn}:${entry.event.data.step}`);
5311
5773
  }
5312
5774
  };
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";
5775
+ const detach = () => {
5776
+ const current = attached;
5777
+ if (current === void 0) return;
5778
+ attached = void 0;
5779
+ current.detach();
5339
5780
  };
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);
5781
+ const dispose = () => {
5782
+ if (disposed) return;
5783
+ disposed = true;
5784
+ unsubscribeGeneration();
5785
+ detach();
5786
+ };
5787
+ /** Ask the fold OWNER to reconcile the CURRENT official window. Intent
5788
+ * only, coalesced, deferred by exactly one microtask so the caller's
5789
+ * `handle = subscribe(...)` assignment always completes first. Every
5790
+ * later revision, the loading→open transition and any change of the
5791
+ * generation/binding identity re-arm it. */
5792
+ /** The reason of the pending (coalesced) wakeup: a recovery anywhere in the
5793
+ * window escalates a paging wakeup, never the other way round. */
5794
+ let pendingRefoldReason = "recovery";
5795
+ const requireRefold = (reason = "recovery") => {
5796
+ if (disposed) return;
5797
+ const current = attached;
5798
+ if (current === void 0) return;
5799
+ if (reason === "recovery") pendingRefoldReason = "recovery";
5800
+ else if (!notifyQueued && notified === void 0) pendingRefoldReason = "paging";
5801
+ mode = "recovering";
5802
+ const window = current.binding.eventSource.getSnapshot();
5803
+ const open = current.binding.session.getSnapshot().openState === "open";
5804
+ if (notified !== void 0 && Object.is(notified.generation, fencedGeneration) && Object.is(notified.binding, current.binding) && notified.revision === window.revision && notified.open === open) return;
5805
+ notified = {
5806
+ generation: fencedGeneration,
5807
+ binding: current.binding,
5808
+ revision: window.revision,
5809
+ open
5810
+ };
5811
+ if (notifyQueued) return;
5812
+ notifyQueued = true;
5813
+ queueMicrotask(() => {
5814
+ notifyQueued = false;
5815
+ if (disposed || mode !== "recovering") return;
5816
+ const still = attached;
5817
+ if (still === void 0 || sessions.binding(sessionId) !== still.binding) return;
5818
+ sinks.onWindowRefoldRequired(sessionId, pendingRefoldReason);
5819
+ pendingRefoldReason = "recovery";
5820
+ });
5821
+ };
5822
+ /** Acknowledge one committed re-fold (see the interface contract). The
5823
+ * proof is re-validated against the LIVE official state here. */
5824
+ const acknowledgeWindowRefold = (proof) => {
5825
+ if (disposed) return false;
5826
+ const current = attached;
5827
+ if (current === void 0) return false;
5828
+ if (!Object.is(proof.binding, current.binding)) return false;
5829
+ const liveGeneration = generation.getSnapshot();
5830
+ if (!Object.is(proof.generation, liveGeneration)) return false;
5831
+ const window = current.binding.eventSource.getSnapshot();
5832
+ if (window.revision !== proof.revision) return false;
5833
+ if (current.binding.session.getSnapshot().openState !== "open") return false;
5834
+ if (!refoldEligible(proof.revision)) return false;
5835
+ fencedGeneration = liveGeneration;
5836
+ startedTuples = /* @__PURE__ */ new Set();
5837
+ seedTuplesFromWindow(window.entries);
5838
+ lastDeliveredRevision = proof.revision;
5839
+ rolloverBaselineRevision = void 0;
5840
+ mode = "incremental";
5841
+ notified = void 0;
5842
+ return true;
5843
+ };
5844
+ /** One attachment: the receiver over this EXACT binding's official
5845
+ * channels. A replaced same-id binding retires it (the owner's commit
5846
+ * path installs the next one). */
5847
+ const attach = (capturedGeneration, binding) => {
5848
+ startedTuples = /* @__PURE__ */ new Set();
5849
+ seedTuplesFromWindow(binding.eventSource.getSnapshot().entries);
5850
+ const subscriptionRevision = binding.eventSource.getSnapshot().revision;
5851
+ lastDeliveredRevision = subscriptionRevision;
5852
+ mode = "incremental";
5853
+ notified = void 0;
5854
+ let lastSnapshotChange = 0;
5855
+ const isBindingReplaced = () => disposed || sessions.binding(sessionId) !== binding;
5856
+ const partitionChange = (entries) => {
5857
+ const durable = [];
5858
+ const live = [];
5859
+ for (const entry of entries) {
5860
+ if (entry.type === "event") {
5861
+ durable.push(entry.event);
5862
+ continue;
5863
+ }
5864
+ const { attemptId, turn, step, chunk } = entry.event.data;
5865
+ const key = `${attemptId}:${turn}:${step}`;
5866
+ if (!startedTuples.has(key)) {
5867
+ startedTuples.add(key);
5868
+ live.push({
5869
+ kind: "start",
5870
+ sessionId,
5871
+ attemptId,
5872
+ turn,
5873
+ step
5874
+ });
5875
+ }
5354
5876
  live.push({
5355
- kind: "start",
5877
+ kind: "chunk",
5356
5878
  sessionId,
5357
5879
  attemptId,
5358
5880
  turn,
5359
- step
5881
+ step,
5882
+ time: entry.event.time,
5883
+ chunk
5360
5884
  });
5361
5885
  }
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
5886
+ return {
5887
+ durable,
5888
+ live
5889
+ };
5375
5890
  };
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);
5891
+ const publish = () => {
5892
+ if (isBindingReplaced()) {
5893
+ dispose();
5894
+ return;
5895
+ }
5896
+ const liveGeneration = generation.getSnapshot();
5897
+ if (!Object.is(fencedGeneration, liveGeneration)) {
5898
+ fencedGeneration = liveGeneration;
5899
+ rolloverBaselineRevision = binding.eventSource.getSnapshot().revision;
5900
+ requireRefold();
5901
+ }
5902
+ if (mode === "recovering") {
5903
+ requireRefold();
5396
5904
  return;
5397
5905
  }
5398
- case "prepend":
5399
- sinks.onWindowPrepended(sessionId);
5906
+ const window = binding.eventSource.getSnapshot();
5907
+ if (window.revision === lastDeliveredRevision) return;
5908
+ const change = window.change;
5909
+ if (change !== void 0 && change.kind === "prepend") {
5910
+ requireRefold("paging");
5400
5911
  return;
5401
- case "replace":
5402
- startedTuples.clear();
5403
- seedTuplesFromWindow(binding.eventSource.getSnapshot().entries);
5404
- sinks.onWindowReplaced(sessionId);
5912
+ }
5913
+ if (change === void 0 || change.kind === "replace") {
5914
+ requireRefold();
5405
5915
  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);
5916
+ }
5917
+ if (window.revision !== lastDeliveredRevision + 1) {
5918
+ requireRefold();
5409
5919
  return;
5410
- }
5411
- };
5412
- const dispose = () => {
5413
- if (disposed) return;
5414
- disposed = true;
5415
- unsubscribe?.();
5416
- unsubscribe = void 0;
5417
- unsubscribeSnapshot();
5418
- unsubscribeProjections();
5920
+ }
5921
+ switch (change.kind) {
5922
+ case "append": {
5923
+ const { durable, live } = partitionChange(change.entries);
5924
+ for (const input of live) sinks.onLiveInput(input);
5925
+ for (const event of durable) sinks.onDurableEvent(sessionId, event);
5926
+ lastDeliveredRevision = window.revision;
5927
+ return;
5928
+ }
5929
+ case "settle-assistant":
5930
+ if (change.entry !== void 0) sinks.onDurableEvent(sessionId, change.entry.event);
5931
+ for (const key of startedTuples) if (key.startsWith(`${change.attemptId}:`)) startedTuples.delete(key);
5932
+ lastDeliveredRevision = window.revision;
5933
+ return;
5934
+ }
5935
+ };
5936
+ const onSnapshot = () => {
5937
+ if (isBindingReplaced()) {
5938
+ dispose();
5939
+ return;
5940
+ }
5941
+ lastSnapshotChange += 1;
5942
+ sinks.onSessionSnapshotChanged(sessionId);
5943
+ if (mode === "recovering") requireRefold();
5944
+ };
5945
+ let projectionRefreshQueued = false;
5946
+ const onProjections = () => {
5947
+ if (isBindingReplaced()) {
5948
+ dispose();
5949
+ return;
5950
+ }
5951
+ if (projectionRefreshQueued) return;
5952
+ projectionRefreshQueued = true;
5953
+ queueMicrotask(() => {
5954
+ projectionRefreshQueued = false;
5955
+ if (disposed || isBindingReplaced()) return;
5956
+ sinks.onProjectionsChanged(sessionId);
5957
+ });
5958
+ };
5959
+ const unsubscribeSnapshot = binding.session.subscribe(onSnapshot);
5960
+ const offs = projectionKeys.map((key) => binding.session.projections.faceOf(key).subscribe(onProjections));
5961
+ const unsubscribeEvent = binding.eventSource.subscribe(publish);
5962
+ attached = {
5963
+ binding,
5964
+ detach: () => {
5965
+ unsubscribeEvent();
5966
+ unsubscribeSnapshot();
5967
+ for (const off of offs) off();
5968
+ }
5969
+ };
5970
+ const hydrateToken = hydrate?.transportToken;
5971
+ if (!(hydrate === void 0 || Object.is(hydrateToken?.binding, binding) && Object.is(hydrateToken?.generation, capturedGeneration))) {
5972
+ rolloverBaselineRevision = subscriptionRevision;
5973
+ requireRefold();
5974
+ } else if (hydrate !== void 0 && hydrate.revision !== subscriptionRevision) requireRefold();
5975
+ publish();
5419
5976
  };
5420
- let lastSnapshotChange = 0;
5421
- const onSnapshot = () => {
5422
- if (isBindingReplaced()) {
5423
- dispose();
5424
- return;
5425
- }
5426
- lastSnapshotChange += 1;
5427
- sinks.onSessionSnapshotChanged(sessionId);
5977
+ /** Attach as soon as BOTH official inputs exist. Driven only by the
5978
+ * official generation channel (the bootstrap/viewer calls this once on
5979
+ * entry); never a timer. */
5980
+ const tryAttach = () => {
5981
+ if (disposed || attached !== void 0) return;
5982
+ const liveGeneration = generation.getSnapshot();
5983
+ if (liveGeneration === void 0) return;
5984
+ const binding = sessions.binding(sessionId);
5985
+ if (binding === void 0) return;
5986
+ fencedGeneration = liveGeneration;
5987
+ attach(liveGeneration, binding);
5428
5988
  };
5429
- const unsubscribeSnapshot = binding.session.subscribe(onSnapshot);
5430
- let projectionRefreshQueued = false;
5431
- const onProjections = () => {
5432
- if (isBindingReplaced()) {
5433
- dispose();
5989
+ const onGeneration = () => {
5990
+ if (disposed) return;
5991
+ if (attached === void 0) {
5992
+ tryAttach();
5434
5993
  return;
5435
5994
  }
5436
- if (projectionRefreshQueued) return;
5437
- projectionRefreshQueued = true;
5438
- queueMicrotask(() => {
5439
- projectionRefreshQueued = false;
5440
- if (disposed || isBindingReplaced()) return;
5441
- sinks.onProjectionsChanged(sessionId);
5442
- });
5995
+ const liveGeneration = generation.getSnapshot();
5996
+ if (Object.is(fencedGeneration, liveGeneration)) return;
5997
+ const current = attached;
5998
+ fencedGeneration = liveGeneration;
5999
+ rolloverBaselineRevision = current === void 0 ? void 0 : current.binding.eventSource.getSnapshot().revision;
6000
+ requireRefold();
5443
6001
  };
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();
6002
+ const refoldEligible = (revision) => !(rolloverBaselineRevision !== void 0 && revision === rolloverBaselineRevision);
6003
+ const unsubscribeGeneration = generation.subscribe(() => {
6004
+ trackRollover();
6005
+ onGeneration();
6006
+ });
6007
+ const verifyFirst = observedRollover;
6008
+ tryAttach();
6009
+ if (verifyFirst && attached !== void 0) {
6010
+ mode = "recovering";
6011
+ const window = attached.binding.eventSource.getSnapshot();
6012
+ notified = {
6013
+ generation: fencedGeneration,
6014
+ binding: attached.binding,
6015
+ revision: window.revision,
6016
+ open: attached.binding.session.getSnapshot().openState === "open"
5448
6017
  };
5449
- })();
5450
- unsubscribe = binding.eventSource.subscribe(publish);
5451
- publish();
5452
- if (!disposed && missedHydrationEvents && lastRevision === subscriptionRevision) sinks.onWindowReplaced(sessionId);
5453
- return { dispose };
6018
+ }
6019
+ return {
6020
+ dispose,
6021
+ acknowledgeWindowRefold,
6022
+ refoldEligible
6023
+ };
5454
6024
  } };
5455
6025
  }
5456
6026
  //#endregion
@@ -5501,6 +6071,7 @@ function createRemoteChildViewSource(options) {
5501
6071
  return;
5502
6072
  }
5503
6073
  let read;
6074
+ const openFenceGeneration = options.generation.getSnapshot();
5504
6075
  try {
5505
6076
  read = await reader.read(childId, target.signal);
5506
6077
  } catch (error) {
@@ -5523,6 +6094,10 @@ function createRemoteChildViewSource(options) {
5523
6094
  reference.release();
5524
6095
  throw childOpenFailure(childId, opened.openState, opened.openError);
5525
6096
  }
6097
+ if (!Object.is(openFenceGeneration, options.generation.getSnapshot()) || binding.eventSource?.getSnapshot().revision !== read.revision) {
6098
+ reference.release();
6099
+ return;
6100
+ }
5526
6101
  const hydrated = (snapshot, current) => ({
5527
6102
  durableEvents: snapshot.durableEvents,
5528
6103
  liveInputs: snapshot.liveInputs,
@@ -5541,10 +6116,30 @@ function createRemoteChildViewSource(options) {
5541
6116
  if (released) return void 0;
5542
6117
  const before = ownedBinding();
5543
6118
  if (before === void 0 || !isOpen(before)) return void 0;
6119
+ const fenceGeneration = options.generation.getSnapshot();
5544
6120
  const next = await reader.read(childId);
5545
6121
  const current = ownedBinding();
5546
6122
  if (next === void 0 || current === void 0 || !isOpen(current)) return void 0;
5547
- return hydrated(next, current);
6123
+ if (!Object.is(fenceGeneration, options.generation.getSnapshot())) return void 0;
6124
+ if (current.eventSource?.getSnapshot().revision !== next.revision) return void 0;
6125
+ return {
6126
+ ...hydrated(next, current),
6127
+ commit: (write) => {
6128
+ if (released) return false;
6129
+ if (!Object.is(fenceGeneration, options.generation.getSnapshot())) return false;
6130
+ const bindingNow = ownedBinding();
6131
+ if (bindingNow === void 0 || bindingNow !== current || !isOpen(bindingNow)) return false;
6132
+ if (bindingNow.eventSource?.getSnapshot().revision !== next.revision) return false;
6133
+ if (live !== void 0 && !live.refoldEligible(next.revision)) return false;
6134
+ write();
6135
+ if (live === void 0) return true;
6136
+ return live.acknowledgeWindowRefold({
6137
+ generation: fenceGeneration,
6138
+ binding: current,
6139
+ revision: next.revision
6140
+ });
6141
+ }
6142
+ };
5548
6143
  },
5549
6144
  async loadOlder() {
5550
6145
  if (released) return;
@@ -5556,12 +6151,16 @@ function createRemoteChildViewSource(options) {
5556
6151
  const handle = liveIngress.subscribe(childId, {
5557
6152
  onDurableEvent: (_id, event) => sinks.onDurableEvent(options.asEvent(event)),
5558
6153
  onLiveInput: (input) => sinks.onLiveInput(input),
5559
- onWindowReplaced: () => sinks.onWindowReplaced(),
5560
- onWindowPrepended: () => sinks.onWindowPrepended(),
6154
+ onWindowRefoldRequired: () => sinks.onWindowRefoldRequired(),
5561
6155
  onSessionSnapshotChanged: () => sinks.onSessionSnapshotChanged(),
5562
6156
  onProjectionsChanged: () => sinks.onProjectionsChanged()
5563
- }, snapshot.revision);
5564
- if (handle === void 0) return void 0;
6157
+ }, {
6158
+ revision: read.revision,
6159
+ transportToken: {
6160
+ generation: openFenceGeneration,
6161
+ binding
6162
+ }
6163
+ });
5565
6164
  live = handle;
5566
6165
  return { dispose: () => {
5567
6166
  handle.dispose();
@@ -5790,8 +6389,12 @@ function detachedPlan(value) {
5790
6389
  * owns: `semantics.presentationReader` by identity, the wire's
5791
6390
  * `sessions`/`connection.generation` for the official projection/echo reads,
5792
6391
  * 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.
6392
+ * installs exactly ONE watch — the ingress factory's process-lifetime
6393
+ * Connection-generation listener, whose lifetime is this bundle and the Client
6394
+ * context the generation source belongs to (there is no separate disposer for
6395
+ * it; see `live-ingress.ts`) — and no other subscription. The per-session
6396
+ * ingress subscription is created lazily by the bootstrap and disposed through
6397
+ * its own handle.
5795
6398
  */
5796
6399
  function createRemotePresentationSource(wire, backendRuntime) {
5797
6400
  const sessions = wire.client.sessions;
@@ -5846,6 +6449,18 @@ function createRemotePresentationSource(wire, backendRuntime) {
5846
6449
  if (captured === void 0 || typeof captured !== "object") return false;
5847
6450
  if (!Object.is(captured.generation, generation.getSnapshot())) return false;
5848
6451
  return sessions.binding(sessionId) === captured.binding;
6452
+ },
6453
+ windowRefoldProof(sessionId, revision) {
6454
+ const current = generation.getSnapshot();
6455
+ if (current === void 0) return void 0;
6456
+ const binding = sessions.binding(sessionId);
6457
+ if (binding === void 0) return void 0;
6458
+ if (binding.eventSource?.getSnapshot().revision !== revision) return void 0;
6459
+ return {
6460
+ generation: current,
6461
+ binding,
6462
+ revision
6463
+ };
5849
6464
  }
5850
6465
  },
5851
6466
  task: {
@@ -5863,6 +6478,7 @@ function createRemotePresentationSource(wire, backendRuntime) {
5863
6478
  sessions,
5864
6479
  reader: backendRuntime.semantics.presentationReader,
5865
6480
  liveIngress,
6481
+ generation,
5866
6482
  childCwd: (sessionId) => {
5867
6483
  const cwd = sessionReader.sessionStatus(sessionId)?.cwd;
5868
6484
  return typeof cwd === "string" ? cwd : "";
@@ -5993,10 +6609,19 @@ async function createRemoteApplicationRuntime(options) {
5993
6609
  });
5994
6610
  let backendRuntime;
5995
6611
  let ownerServices;
6612
+ /**
6613
+ * The composition-owned pre-dispatch write admission: OPEN for the whole live
6614
+ * surface, closed ONCE and synchronously by the application's surface-stop
6615
+ * boundary (`SelectedApplicationRuntime.stopSurfaceAdmission`). A write still
6616
+ * parked before dispatch when the surface stops is then refused before any
6617
+ * Host dispatch instead of being admitted silently.
6618
+ */
6619
+ let dispatchAdmissionOpen = true;
5996
6620
  try {
5997
6621
  backendRuntime = await createRemoteBackendRuntime({
5998
6622
  runtime: wire.client,
5999
6623
  fetch: wire.host.carrier.fetch,
6624
+ isDispatchAllowed: () => dispatchAdmissionOpen,
6000
6625
  ...options.promptSerializer === void 0 ? {} : { promptSerializer: options.promptSerializer }
6001
6626
  });
6002
6627
  ownerServices = createRemoteSessionOwnerServices(wire.client.sessions);
@@ -6035,6 +6660,9 @@ async function createRemoteApplicationRuntime(options) {
6035
6660
  backend: backendRuntime.backend,
6036
6661
  owners: ownerServices.owners,
6037
6662
  retirement: ownerServices.retirement,
6663
+ stopSurfaceAdmission: () => {
6664
+ dispatchAdmissionOpen = false;
6665
+ },
6038
6666
  disposeTransport: async () => {
6039
6667
  if (transportDisposed) return;
6040
6668
  transportDisposed = true;
@@ -6148,7 +6776,10 @@ async function createRemoteBackendRuntime(options) {
6148
6776
  }
6149
6777
  };
6150
6778
  try {
6151
- const semantics = createRemoteM3ASemantics(remoteM3ARuntimeSourceOf(options.runtime), { promptSerializer: options.promptSerializer ?? RemotePromptSerializerProduction.overSessions(options.runtime.sessions) });
6779
+ const semantics = createRemoteM3ASemantics(remoteM3ARuntimeSourceOf(options.runtime), {
6780
+ promptSerializer: options.promptSerializer ?? RemotePromptSerializerProduction.overSessions(options.runtime.sessions),
6781
+ ...options.isDispatchAllowed === void 0 ? {} : { isDispatchAllowed: options.isDispatchAllowed }
6782
+ });
6152
6783
  unwind.push(() => semantics.dispose());
6153
6784
  const config = new RemoteConfigPort(remoteConfigRuntimeSourceOf(options.runtime));
6154
6785
  unwind.push(() => config.dispose());