@xmoon76/dsh-pi-tui 0.5.3 → 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 (35) hide show
  1. package/README.en.md +174 -150
  2. package/README.md +118 -103
  3. package/cordis.patch.yml +54 -2
  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-a-rxanjw.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 +1 -1
  17. package/dist/index.mjs +45243 -27018
  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-BtPH-UUb.mjs → runtime-vc4mdr-R.mjs} +1395 -1088
  26. package/dist/{session-BZLxhrPQ.mjs → session-tdJHLnJR.mjs} +3329 -281
  27. package/dist/{startup-D5Xu8diR.mjs → startup-JaVZoTIl.mjs} +54 -13
  28. package/dist/startup.d.mts +2 -1
  29. package/dist/startup.mjs +1 -1
  30. package/dist/{terminal-progress-source-BlmksrSD.mjs → terminal-progress-source-xor3vakJ.mjs} +102 -46
  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/package.json +132 -113
  35. package/dist/context-summary-CxUpNkA9.mjs +0 -2951
@@ -1,9 +1,9 @@
1
- import { n as TUI_STARTUP_SERVICE } from "./startup-D5Xu8diR.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 { A as clientOwnerOf, C as classifySubagentPromptSettlement, E as isRemoteBusinessRefusalCode, L as credentialOptionsFor, O as REMOTE_IMPLEMENTED_CAPABILITIES, S as detachedTurnOutline, T as GATEWAY_PRE_INVOCATION_CODES, V as SupersededReadError, a as PluginManagerStaleResultError, c as detachInspection, ct as resolveUserCommandItemFallbackActivationIds, d as detachPluginManagerSnapshot, dt as contextPressureOccupancy, f as pluginInstallRequestId, h as hostPathQueryEnvironment, i as PI_TUI_TERMINAL_PROGRESS_WATCH, it as parseFooterCustomItems, l as detachLog, lt as resolveUserLayerFooterMode, m as DirectHostDiscoveryDriver, n as createRemoteTerminalProgressSource, o as createTerminalProgressInterval, ot as resolveTrustedFooterCommand, p as listPiTuiHostFileReferences, r as PI_TUI_TERMINAL_PROGRESS_NAMESPACE, s as detachChange, st as resolveUserCommandItemActivationIds, u as detachPhase, x as detachedSessionStatus, y as QuestionAnswerError, z as providerOptionsFor } from "./terminal-progress-source-BlmksrSD.mjs";
4
- import { a as PI_TUI_EXTENSIONS_SERVICE, n as extensions_exports } from "./extensions-a-rxanjw.mjs";
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,10 +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;
1127
1266
  web;
1267
+ visualTools;
1128
1268
  /** `undefined` while the `tui-app` namespace is absent from the mirror
1129
1269
  * (the port's documented absence contract). */
1130
1270
  get tuiSettings() {
@@ -1144,9 +1284,11 @@ var RemoteConfigPort = class {
1144
1284
  this.credentialConfig = new RemoteCredentialConfig(bound.remote.credentials, on, source.connection.generation);
1145
1285
  this.credentials = this.credentialConfig;
1146
1286
  this.authorization = new RemoteAuthorizationConfig();
1287
+ this.account = new RemoteUnsupportedAccountConfig();
1147
1288
  this.permissions = new RemotePermissionConfig(this.mirror, source.remote.commands);
1148
1289
  this.presetDefault = new RemotePresetDefaultConfig(this.mirror);
1149
1290
  this.subagentModelSelection = new RemoteSubagentModelSelectionConfig(this.mirror);
1291
+ this.visualTools = new RemoteVisualToolsConfig(this.mirror);
1150
1292
  this.web = new RemoteUnsupportedWebProviderConfig();
1151
1293
  }
1152
1294
  /** Commit one fresh mirror snapshot (or leave the last-known value). A
@@ -1220,6 +1362,72 @@ var RemoteUnsupportedWebProviderConfig = class {
1220
1362
  this.refuse();
1221
1363
  }
1222
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
+ };
1223
1431
  //#endregion
1224
1432
  //#region src/runtime/remote/session-archive-remote.ts
1225
1433
  /** The official absolute export path (`dsh-session-log-export` routes). */
@@ -1382,1139 +1590,1153 @@ const PI_TUI_CLIENT_CONTRIBUTION = {
1382
1590
  descriptors: [PI_TUI_FILE_REFERENCES_LIST, PI_TUI_TERMINAL_PROGRESS_WATCH]
1383
1591
  };
1384
1592
  //#endregion
1385
- //#region src/runtime/remote/pi-tui-file-reference-host-bridge.ts
1593
+ //#region src/app/remote/dispose-cause.ts
1386
1594
  /**
1387
- * The Remote Host-side bridge for the private `piTuiFileReferences` endpoint
1388
- * (TS8-HF1): a CONSTRUCTION/ADAPTATION seam ONLY. It binds the private Remote
1389
- * method to the SAME Host-scoped completion authority the Direct adapter uses
1390
- * (`runtime/direct/host-file-augmentation-direct.ts` + the Direct Host
1391
- * discovery driver) and returns a transport-neutral `list` runtime.
1392
- *
1393
- * It owns NO Cordis service, NO Typert registration and NO lifecycle policy —
1394
- * the Cordis service, its Typert contribution registration and its disposal
1395
- * remain with the Remote Host composition
1396
- * (`app/remote/pi-tui-file-reference-host.ts`). The dependency direction is
1397
- * therefore `app/remote/** -> runtime/remote/** -> runtime/direct/**`, never
1398
- * `app/remote/** -> runtime/direct/**`.
1595
+ * Transport-neutral disposal failure chaining for the Remote composition.
1399
1596
  *
1400
- * The bridge lives in `runtime/remote/**` because that layer may consume the
1401
- * 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.
1402
1601
  *
1403
- * @module @xmoon76/dsh-pi-tui/runtime/remote/pi-tui-file-reference-host-bridge
1602
+ * @module app/remote/dispose-cause
1404
1603
  */
1405
1604
  /**
1406
- * Bind the private Remote method to the Host-scoped completion authority.
1407
- * The Host finder is resolved ONCE for the runtime's lifetime (it is a pure
1408
- * 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.
1409
1608
  */
1410
- function createPiTuiHostFileReferenceRuntime(deps) {
1411
- const driver = new DirectHostDiscoveryDriver(deps.fdPath);
1412
- const environment = hostPathQueryEnvironment();
1413
- return { async list(sessionId, query, signal) {
1414
- signal.throwIfAborted();
1415
- const agent = deps.agentFor(sessionId);
1416
- if (agent === void 0) return {
1417
- kind: "unavailable",
1418
- reason: "the requested Session has no live Host Agent"
1419
- };
1420
- return await listPiTuiHostFileReferences(agent, query, signal, {
1421
- official: deps.official(),
1422
- driver,
1423
- environment,
1424
- workingDirectory: deps.workingDirectory?.()
1425
- });
1426
- } };
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;
1427
1614
  }
1428
1615
  //#endregion
1429
- //#region src/app/remote/pi-tui-file-reference-host.ts
1616
+ //#region src/app/remote/client-runtime.ts
1430
1617
  /**
1431
- * The Host endpoint of the private augmentation. One instance per Remote Host
1432
- * 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
1433
1640
  */
1434
- var PiTuiFileReferenceHostService = class extends TypertRemoteService {
1435
- /** The Typert registry owns the explicit invocation definitions. */
1436
- static inject = ["typert"];
1437
- runtime;
1438
- /**
1439
- * @param ctx - the Host context this row is mounted in.
1440
- * @param deps - the narrow Host facts the composition resolved.
1441
- */
1442
- constructor(ctx, deps) {
1443
- super(ctx, PI_TUI_FILE_REFERENCES_NAMESPACE);
1444
- this.runtime = createPiTuiHostFileReferenceRuntime({
1445
- ...deps,
1446
- workingDirectory: () => ctx.get("workingDirectory")
1447
- });
1448
- }
1449
- /**
1450
- * The private Remote method (`piTuiFileReferences/list`, see
1451
- * `pi-tui-file-reference-contract.ts`). Cancellation outranks every outcome.
1452
- */
1453
- list(sessionId, query, signal) {
1454
- 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"
1455
1669
  }
1456
- };
1457
- //#endregion
1458
- //#region src/app/remote/terminal-progress-host.ts
1459
- /** The structural `turn/start` / `turn/end` payload read (never a guessed shape). */
1460
- function turnOf(data) {
1461
- const turn = data?.turn;
1462
- return typeof turn === "number" ? turn : void 0;
1463
- }
1464
- /** The merge-extensible `turn/end.reason.kind` discriminant. */
1465
- function reasonKindOf(data) {
1466
- const reason = data?.reason;
1467
- 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;
1468
1694
  }
1469
1695
  /**
1470
- * Frames one subscriber may fall behind by before the stream is failed instead
1471
- * of silently losing an edge. A real run produces a handful of transitions, so
1472
- * 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.
1473
1702
  */
1474
- const SUBSCRIBER_QUEUE_LIMIT = 64;
1475
1703
  /**
1476
- * One subscriber's ordered frame queue. The Host ALWAYS mutates the record
1477
- * before pushing, so a queue can never observe a frame the record has not
1478
- * committed, and `close()` is idempotent.
1479
- *
1480
- * An overflowing queue FAILS the reader: dropping frames and continuing would
1481
- * 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.
1482
1709
  */
1483
- var FrameQueue = class {
1484
- frames = [];
1485
- wake;
1486
- closed = false;
1487
- failure;
1488
- limit = SUBSCRIBER_QUEUE_LIMIT;
1489
- push(frame) {
1490
- if (this.closed || this.failure !== void 0) return;
1491
- if (this.frames.length >= this.limit) {
1492
- this.failure = /* @__PURE__ */ new Error("piTuiTerminalProgress: the subscriber queue overflowed");
1493
- this.frames.length = 0;
1494
- const wake = this.wake;
1495
- this.wake = void 0;
1496
- wake?.();
1497
- return;
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;
1498
1720
  }
1499
- this.frames.push(frame);
1500
- const wake = this.wake;
1501
- this.wake = void 0;
1502
- wake?.();
1503
- }
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
+ };
1504
1730
  /**
1505
- * End the consumer's read AFTER every frame already committed to it: a
1506
- * disposal publishes the retired interval BEFORE it ends the watchers, and a
1507
- * 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.
1508
1740
  */
1509
- close() {
1510
- if (this.closed) return;
1511
- this.closed = true;
1512
- const wake = this.wake;
1513
- this.wake = void 0;
1514
- wake?.();
1515
- }
1516
- async next() {
1517
- for (;;) {
1518
- const frame = this.frames.shift();
1519
- if (frame !== void 0) return {
1520
- value: frame,
1521
- done: false
1522
- };
1523
- if (this.failure !== void 0) throw this.failure;
1524
- if (this.closed) return {
1525
- value: void 0,
1526
- done: true
1527
- };
1528
- await new Promise((resolve) => {
1529
- this.wake = resolve;
1530
- });
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);
1531
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();
1532
1809
  }
1533
- };
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
+ ];
1534
1841
  /**
1535
- * The Host endpoint of the private stream. One instance per Remote Host
1536
- * 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`).
1537
1849
  */
1538
- var PiTuiTerminalProgressHostService = class extends TypertRemoteService {
1539
- /** The Typert registry owns the explicit invocation definition. */
1540
- static inject = ["typert"];
1541
- /** The narrow Host facts the composition resolved (explicit field: the
1542
- * strip-only TS loader rejects parameter properties). */
1543
- deps;
1544
- /** One opaque identity per Host plugin instance: a Host restart, a new
1545
- * composition or a re-mounted fiber all invalidate older frames. */
1546
- hostEpoch = `host-${randomEpoch()}`;
1547
- records = /* @__PURE__ */ new Map();
1548
- /** Monotonic Agent-lifetime counter: a replacement ALWAYS outranks every
1549
- * earlier lifetime of the same session, even after its record was dropped. */
1550
- epochCounter = 0;
1551
- disposed = false;
1552
- /**
1553
- * @param ctx - the Host context this row is mounted in.
1554
- * @param deps - the narrow Host facts the composition resolved.
1555
- */
1556
- constructor(ctx, deps) {
1557
- super(ctx, PI_TUI_TERMINAL_PROGRESS_NAMESPACE);
1558
- this.deps = deps;
1559
- ctx.on("agent/status", ({ agent, status }) => {
1560
- this.onAgentStatus(agent, status);
1561
- }, { global: true });
1562
- ctx.on("session/event", (session, event) => {
1563
- this.onSessionEvent(session, event.type, event.data);
1564
- }, { global: true });
1565
- ctx.on("agent/disposed", ({ agent }) => {
1566
- this.onAgentDisposed(agent);
1567
- }, { global: true });
1568
- ctx.effect(() => () => {
1569
- this.closeAll();
1570
- }, "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);
1571
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;
1572
1880
  /**
1573
- * The private Remote method (`piTuiTerminalProgress/watch`): the ONE
1574
- * per-session ordered stream, opening with the authoritative snapshot of the
1575
- * 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.
1576
1887
  *
1577
- * The subscriber is registered and the cut (revision + current state) is
1578
- * captured in the SAME synchronous block before the first `yield`, so an
1579
- * update can neither be lost between the snapshot and the subscription nor be
1580
- * 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.
1581
1894
  */
1582
- async *watch(sessionId, signal) {
1583
- const record = this.recordFor(sessionId);
1584
- const queue = new FrameQueue();
1585
- const cut = record.revision;
1586
- const snapshot = {
1587
- kind: "snapshot",
1588
- sessionId,
1589
- hostEpoch: this.hostEpoch,
1590
- agentEpoch: record.agentEpoch,
1591
- revision: cut,
1592
- running: record.running,
1593
- outcome: record.outcome
1594
- };
1595
- record.subscribers.add(queue);
1596
- const onAbort = () => {
1597
- queue.close();
1598
- };
1599
- if (signal.aborted) queue.close();
1600
- else signal.addEventListener("abort", onAbort, { once: true });
1601
- try {
1602
- yield snapshot;
1603
- for (;;) {
1604
- const next = await queue.next();
1605
- if (next.done === true) return;
1606
- yield next.value;
1607
- }
1608
- } finally {
1609
- signal.removeEventListener("abort", onAbort);
1610
- record.subscribers.delete(queue);
1611
- this.reclaim(record);
1612
- }
1613
- }
1614
- /**
1615
- * Drop a record nobody watches and no Agent owns. A watch of a session that
1616
- * has no live Agent must not leave an empty record behind for the rest of the
1617
- * Host's life: it is observable by nothing, and the next Agent lifetime starts
1618
- * a FRESH record carrying a HIGHER `agentEpoch` (the epoch counter never
1619
- * rewinds), so no Client provenance can be resurrected across the gap.
1620
- */
1621
- reclaim(record) {
1622
- if (record.subscribers.size > 0 || record.agent !== void 0) return;
1623
- if (this.records.get(record.sessionId) === record) this.records.delete(record.sessionId);
1624
- }
1625
- /** The live `agent/status` transition of one Agent (plan §6.4). */
1626
- onAgentStatus(agent, status) {
1627
- if (this.deps.agentFor(agent.session.id) !== agent) return;
1628
- const record = this.recordFor(agent.session.id);
1629
- if (record.agent !== agent) return;
1630
- this.publish(record, record.fold.status(status === "running"));
1631
- }
1632
- /** One durable Session event (plan §6.4): evidence only, never an interim commit. */
1633
- onSessionEvent(session, type, data) {
1634
- const record = this.records.get(session.id);
1635
- if (record === void 0 || record.agent === void 0) return;
1636
- if (record.session !== session) return;
1637
- if (type === "turn/start") {
1638
- const turn = turnOf(data);
1639
- if (turn !== void 0) record.fold.turnStart(turn);
1640
- return;
1641
- }
1642
- if (type === "turn/end") {
1643
- const turn = turnOf(data);
1644
- const kind = reasonKindOf(data);
1645
- if (turn !== void 0 && kind !== void 0) record.fold.turnEnd(turn, kind);
1646
- }
1647
- }
1648
- /** The Agent lifetime ended (plan §6.4): retire honestly, end the watchers. */
1649
- onAgentDisposed(agent) {
1650
- const record = this.records.get(agent.session.id);
1651
- if (record === void 0 || record.agent !== agent) return;
1652
- const retired = record.fold.retire();
1653
- if (retired !== void 0) this.publish(record, retired);
1654
- this.records.delete(agent.session.id);
1655
- for (const subscriber of record.subscribers) subscriber.close();
1656
- }
1657
- /**
1658
- * The record of one session, bound to the live Agent the authoritative Host
1659
- * registry currently holds. Creation AND a replaced Agent lifetime consume a
1660
- * new `agentEpoch` and reset the interval: a new Agent can never inherit the
1661
- * previous lifetime's evidence (plan §6.3/§6.4).
1662
- */
1663
- recordFor(sessionId) {
1664
- let record = this.records.get(sessionId);
1665
- if (record === void 0) {
1666
- record = {
1667
- sessionId,
1668
- agent: void 0,
1669
- session: void 0,
1670
- agentEpoch: 0,
1671
- fold: createTerminalProgressInterval((kind) => {
1672
- this.deps.onUnknownReason(kind);
1673
- }),
1674
- revision: 0,
1675
- running: false,
1676
- outcome: "idle",
1677
- subscribers: /* @__PURE__ */ new Set()
1678
- };
1679
- this.records.set(sessionId, record);
1680
- }
1681
- const live = this.deps.agentFor(sessionId);
1682
- if (live !== void 0 && live !== record.agent) this.rebind(record, live);
1683
- return record;
1684
- }
1685
- /**
1686
- * Bind one Agent lifetime: the running truth is read from the Agent's OWN
1687
- * current status (a plugin mounted mid-run may therefore report `working`),
1688
- * but the outcome starts at `idle` — an unobserved start can never prove a
1689
- * settlement. The rebind is ALWAYS published, because the epoch change is
1690
- * itself a fact the Client must fence on.
1691
- */
1692
- rebind(record, agent) {
1693
- record.agent = agent;
1694
- record.session = agent.session;
1695
- record.agentEpoch = ++this.epochCounter;
1696
- const running = agent.status === "running";
1697
- record.fold.apply({
1698
- active: running,
1699
- 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
+ });
1700
1927
  });
1701
- record.running = running;
1702
- record.outcome = "idle";
1703
- record.revision += 1;
1704
- this.broadcast(record, "update");
1705
- }
1706
- /** Commit one fold transition: mutate the record FIRST, then broadcast. */
1707
- publish(record, next) {
1708
- if (next === void 0) return;
1709
- if (next.active === record.running && next.outcome === record.outcome) return;
1710
- record.running = next.active;
1711
- record.outcome = next.outcome;
1712
- record.revision += 1;
1713
- this.broadcast(record, "update");
1714
- }
1715
- broadcast(record, kind) {
1716
- const frame = {
1717
- kind,
1718
- sessionId: record.sessionId,
1719
- hostEpoch: this.hostEpoch,
1720
- agentEpoch: record.agentEpoch,
1721
- revision: record.revision,
1722
- running: record.running,
1723
- 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")
1724
1943
  };
1725
- for (const subscriber of record.subscribers) subscriber.push(frame);
1726
- }
1727
- /** End every watcher (the row's fiber is going away). */
1728
- closeAll() {
1729
- if (this.disposed) return;
1730
- this.disposed = true;
1731
- 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;
1732
1950
  }
1733
- };
1734
- /** An opaque, process-unique Host-plugin identity (the wire sees only a string). */
1735
- function randomEpoch() {
1736
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1951
+ const { connection, sessions, jobs } = services;
1952
+ return {
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
+ }
1967
+ }
1968
+ };
1737
1969
  }
1738
- //#endregion
1739
- //#region src/app/remote/host-runtime.ts
1740
- /**
1741
- * Host services the ordinary Host Context must already expose before any M3
1742
- * row mounts. The check fails fast with
1743
- * the missing service named instead of parking the runtime.
1744
- */
1745
- const HOST_PREREQUISITE_SERVICES = [
1746
- "credentials",
1747
- "userQuestions",
1748
- "typert",
1749
- "typertGateway",
1750
- "agents",
1751
- "agentDefaultModel",
1752
- "attachments",
1753
- "commands",
1754
- "fileReferences",
1755
- "fs",
1756
- "workingDirectory",
1757
- "llm",
1758
- "sessions",
1759
- "sessionProjections",
1760
- "sessionQuery",
1761
- "workspaceRegistry",
1762
- "jobController"
1763
- ];
1764
- /**
1765
- * Fixed private base URL used only to construct valid `Request` objects for
1766
- * the shared Fetch handler. It is not a global location, a server URL, a TCP
1767
- * listener, or an authentication surface.
1768
- */
1769
- const IN_PROCESS_BASE_URL = "http://dsh-pi-tui-remote.in-process/";
1770
- async function* emptyUplink() {}
1771
1970
  /**
1772
- * Attach one secondary failure to `failure`'s cause chain without losing an
1773
- * existing cause: when the failure already carries a cause, both aggregate
1774
- * into a single `AggregateError`. Shared by the three composition owners so
1775
- * cleanup failures never mask the original construction/readiness error.
1776
- * A `undefined` secondary is a no-op (nothing to attach).
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.
1777
1975
  */
1778
- function mergeCause(failure, secondary) {
1779
- if (secondary === void 0) return failure;
1780
- const existingCause = failure.cause;
1781
- failure.cause = existingCause === void 0 ? secondary : new AggregateError([existingCause, secondary], "remote composition: aggregated failure causes");
1782
- return 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;
2008
+ }
2009
+ signal.addEventListener("abort", abortListener, { once: true });
2010
+ }
2011
+ settle();
2012
+ });
1783
2013
  }
1784
- /**
1785
- * Fail fast when the ordinary Host lacks one of the required base services.
1786
- * Reads via the reflect store so the diagnostic can name the missing key
1787
- * without depending on any one service's shape.
1788
- */
1789
- function assertHostPrerequisites(hostContext) {
1790
- for (const service of HOST_PREREQUISITE_SERVICES) if (hostContext.reflect.get(service) === void 0) throw new Error(`remote host runtime: the Host Context is missing the required "${service}" service`);
2014
+ //#endregion
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");
1791
2019
  }
1792
- /** Build the in-process carrier over the Host connection + gateway seams.
1793
- *
1794
- * The carrier speaks for the Host Connection's OWN owner Peer
1795
- * (`HostConnectionService.browserPeer`, created inside the service constructor
1796
- * with `principal: { kind: 'owner' }` and disposed by the Connection plugin
1797
- * fiber). The SAME reference is passed to the shared Fetch handler and to
1798
- * `wireStream.open`, so one identity — and one lifetime — covers both the
1799
- * unary and the streaming path; the carrier never creates, caches, or disposes
1800
- * a Peer of its own. */
1801
- function createInProcessCarrier(hostContext) {
1802
- const connection = hostContext.connection;
1803
- const peer = connection.browserPeer;
1804
- const shared = connection.createSharedFetchHandler("/api");
1805
- const gateway = hostContext.typertGateway;
2020
+ /** The echo attachment view of one staged image (display facts only). */
2021
+ function previewOf(image) {
1806
2022
  return {
1807
- ownsHost: true,
1808
- fetch(input, init) {
1809
- const request = input instanceof Request ? new Request(input, init) : new Request(new URL(String(input), IN_PROCESS_BASE_URL), init);
1810
- return shared.fetch(request, peer);
1811
- },
1812
- openStream(endpoint, payload, signal, uplink) {
1813
- return (async function* () {
1814
- yield* await gateway.wireStream.open(endpoint, payload, uplink ?? emptyUplink(), peer, signal);
1815
- })();
2023
+ type: "image",
2024
+ value: {
2025
+ previewUrl: "",
2026
+ ...image.name !== void 0 ? { name: image.name } : {},
2027
+ width: image.width,
2028
+ height: image.height
1816
2029
  }
1817
2030
  };
1818
2031
  }
1819
- /**
1820
- * Mount the exact additive official Host closure (§2.4.1) onto the existing
1821
- * Host Context and await every fiber. The existing `jobController` service is
1822
- * asserted before and after construction and never re-mounted.
1823
- *
1824
- * On a partial construction failure the already-mounted fibers unwind in
1825
- * reverse order before the original error rethrows.
1826
- */
1827
- async function createRemoteHostRuntime(hostContext, options = {}) {
1828
- assertHostPrerequisites(hostContext);
1829
- const diag = options.diag ?? { warn: (message, fields) => {
1830
- hostContext.logger("remote-host").warn(message, fields);
1831
- } };
1832
- /** The live Agent of one session, read PER CALL through the authoritative
1833
- * Host registry (never a composition-time snapshot). */
1834
- const liveAgentFor = (sessionId) => hostContext.reflect.get("agents")?.get(sessionId);
1835
- const jobControllerBefore = hostContext.reflect.get("jobController");
1836
- const userQuestionsBefore = hostContext.reflect.get("userQuestions");
1837
- const fibers = [];
1838
- let carrier;
1839
- let disposed = false;
1840
- /**
1841
- * Reverse-dispose every mounted fiber. Per-step error isolation: one
1842
- * rejecting disposer cannot truncate the remaining cleanup. Returns the
1843
- * collected disposal errors instead of throwing, so the construction
1844
- * failure path can rethrow the ORIGINAL error with the cleanup failures
1845
- * attached as its `cause`.
1846
- */
1847
- const collectUnwind = async () => {
1848
- const errors = [];
1849
- for (let index = fibers.length - 1; index >= 0; index -= 1) try {
1850
- await fibers[index].dispose();
1851
- } catch (error) {
1852
- errors.push(error);
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
2042
+ };
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
+ };
1853
2093
  }
1854
- fibers.length = 0;
1855
- return errors;
1856
- };
1857
- try {
1858
- const contributionFiber = hostContext.inject(["typert"], (contributionCtx) => {
1859
- contributionCtx.effect(() => contributionCtx.typert.register(PI_TUI_HOST_CONTRIBUTION), "pi-tui-private-remote-host");
1860
- });
1861
- fibers.push(contributionFiber);
1862
- await contributionFiber;
1863
- const fileReferenceFiber = hostContext.inject(PiTuiFileReferenceHostService.inject, (pluginCtx) => {
1864
- new PiTuiFileReferenceHostService(pluginCtx, {
1865
- agentFor: (sessionId) => liveAgentFor(sessionId),
1866
- official: () => hostContext.reflect.get("fileReferences")
1867
- });
1868
- });
1869
- fibers.push(fileReferenceFiber);
1870
- await fileReferenceFiber;
1871
- const terminalProgressFiber = hostContext.inject(PiTuiTerminalProgressHostService.inject, (pluginCtx) => {
1872
- new PiTuiTerminalProgressHostService(pluginCtx, {
1873
- agentFor: (sessionId) => liveAgentFor(sessionId),
1874
- onUnknownReason: (kind) => {
1875
- diag.warn("terminal progress: unknown turn/end reason", { kind });
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
+ };
1876
2109
  }
1877
- });
1878
- });
1879
- fibers.push(terminalProgressFiber);
1880
- await terminalProgressFiber;
1881
- const connFiber = hostContext.plugin((connectionContext) => {
1882
- new HostConnectionService(connectionContext, [], {});
1883
- });
1884
- fibers.push(connFiber);
1885
- await connFiber;
1886
- const uploadFiber = hostContext.plugin(FileUploads);
1887
- fibers.push(uploadFiber);
1888
- await uploadFiber;
1889
- const statsFiber = hostContext.plugin(sessionStats);
1890
- fibers.push(statsFiber);
1891
- await statsFiber;
1892
- const performanceFiber = hostContext.plugin(performance_host_exports);
1893
- fibers.push(performanceFiber);
1894
- await performanceFiber;
1895
- const outlineFiber = hostContext.plugin(sessionTurnOutline);
1896
- fibers.push(outlineFiber);
1897
- await outlineFiber;
1898
- const sessionCtrlFiber = hostContext.inject(SessionController.inject, (controllerContext) => {
1899
- new SessionController(controllerContext, { nativeOpen: false });
1900
- });
1901
- fibers.push(sessionCtrlFiber);
1902
- await sessionCtrlFiber;
1903
- const settingsFiber = hostContext.plugin(SettingsController);
1904
- fibers.push(settingsFiber);
1905
- await settingsFiber;
1906
- const remotesFiber = hostContext.plugin({
1907
- inject,
1908
- apply
1909
- });
1910
- fibers.push(remotesFiber);
1911
- await remotesFiber;
1912
- const exportFiber = hostContext.plugin(sessionLogExport);
1913
- fibers.push(exportFiber);
1914
- await exportFiber;
1915
- const jobControllerAfter = hostContext.reflect.get("jobController");
1916
- 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");
1917
- const userQuestionsAfter = hostContext.reflect.get("userQuestions");
1918
- 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");
1919
- carrier = createInProcessCarrier(hostContext);
1920
- } catch (error) {
1921
- const disposeErrors = await collectUnwind();
1922
- if (disposeErrors.length > 0) {
1923
- const secondary = disposeErrors.length === 1 ? disposeErrors[0] : new AggregateError(disposeErrors, "remote host runtime: unwind disposal failures");
1924
- throw mergeCause(error instanceof Error ? error : new Error(String(error)), secondary);
2110
+ }
1925
2111
  }
1926
- throw error;
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
+ };
1927
2119
  }
1928
- return {
1929
- hostContext,
1930
- carrier,
1931
- async dispose() {
1932
- if (disposed) return;
1933
- disposed = true;
1934
- const disposeErrors = await collectUnwind();
1935
- if (disposeErrors.length > 0) {
1936
- const failure = disposeErrors[0] instanceof Error ? disposeErrors[0] : new Error(String(disposeErrors[0]));
1937
- if (disposeErrors.length > 1) mergeCause(failure, new AggregateError(disposeErrors.slice(1), "remote host runtime: remaining disposal failures"));
1938
- throw failure;
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
+ });
1939
2163
  }
1940
2164
  }
1941
- };
1942
- }
2165
+ return {
2166
+ kind: "ok",
2167
+ content: Object.freeze(parts)
2168
+ };
2169
+ }
2170
+ };
1943
2171
  //#endregion
1944
- //#region src/app/remote/client-runtime.ts
1945
- /**
1946
- * Experimental official Client runtime composition (M3-1).
1947
- *
1948
- * Owns the official Client bundle capture, the Client `Context`, the exact
1949
- * plugin mount order, the explicit `/remote` contributions, initial
1950
- * readiness, and reverse disposal.
1951
- * It does not assemble the TUI semantic `Backend`.
1952
- *
1953
- * rc.2 publishes the six required Client plugin entries as Web
1954
- * module-loader bundles: each bundle registers through
1955
- * `window.__ModuleLoader__.load(...)`, which plain Node dynamic imports
1956
- * cannot consume directly. The scoped loader below is therefore a packaging
1957
- * adapter only: it is installed around exactly the six dynamic imports,
1958
- * rejects unknown/duplicate/missing registrations, and restores the previous
1959
- * process state before any Client plugin runs.
1960
- *
1961
- * Because ESM evaluates each bundle at most once per process, the capture is
1962
- * a process-wide single-flight: the captured package module exports are
1963
- * reused for every Client `Context`, while each Context still gets its own
1964
- * independent Connection, Gateway, Remote namespaces, Sessions, Jobs,
1965
- * subscriptions, and lifetimes. Captured bundle factories are never re-run.
1966
- *
1967
- * @module app/remote/client-runtime
1968
- */
1969
- /**
1970
- * The exact allowlist: dynamic import specifier paired with its expected
1971
- * `__ModuleLoader__` registration id (§9.1). Kept distinct by design.
1972
- */
1973
- const OFFICIAL_CLIENT_BUNDLES = [
1974
- {
1975
- specifier: "@deepseek-ai/dsh-typert-registry/client",
1976
- id: "@deepseek-ai/dsh-typert-registry"
1977
- },
1978
- {
1979
- specifier: "@deepseek-ai/dsh-client-connection/client",
1980
- id: "@deepseek-ai/dsh-client-connection"
1981
- },
1982
- {
1983
- specifier: "@deepseek-ai/dsh-api-gateway/client",
1984
- id: "@deepseek-ai/dsh-api-gateway"
1985
- },
1986
- {
1987
- specifier: "@deepseek-ai/dsh-client-file-upload/client",
1988
- id: "@deepseek-ai/dsh-client-file-upload"
1989
- },
1990
- {
1991
- specifier: "@deepseek-ai/dsh-api-session-controller/client",
1992
- id: "@deepseek-ai/dsh-api-session-controller"
1993
- },
1994
- {
1995
- specifier: "@deepseek-ai/dsh-api-job-controller/client",
1996
- id: "@deepseek-ai/dsh-api-job-controller"
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: []
2180
+ };
2181
+ async execute(_request) {
2182
+ return {
2183
+ kind: "unavailable",
2184
+ reason: {
2185
+ reason: "carrier-gap",
2186
+ message: CARRIER_GAP_MESSAGE
2187
+ }
2188
+ };
1997
2189
  }
1998
- ];
1999
- /** Expected registration ids, in dependency order. */
2000
- const EXPECTED_REGISTRATION_IDS = OFFICIAL_CLIENT_BUNDLES.map((bundle) => bundle.id);
2001
- /** Process-wide single-flight capture; module code evaluates once per process. */
2002
- let officialClientModulesPromise;
2190
+ };
2191
+ //#endregion
2192
+ //#region src/runtime/remote/pi-tui-file-reference-host-bridge.ts
2003
2193
  /**
2004
- * Load the six official Client bundles once per process and freeze their
2005
- * captured module exports. Concurrent callers share the same promise.
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.
2006
2199
  *
2007
- * DSH 0.2.1-rc.1 and later select the `./client` entry by condition: `@deepseek-ai/dsh-typert-registry`,
2008
- * `@deepseek-ai/dsh-client-connection` and `@deepseek-ai/dsh-api-gateway` publish
2009
- * a standalone Node ESM variant (which never touches `window.__ModuleLoader__`),
2010
- * while the remaining three publish the browser loader factory. Both channels
2011
- * feed one table, so the registration order below still holds for every
2012
- * `/client` dependency.
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/**`.
2013
2206
  *
2014
- * Failure semantics: a rejected capture stays cached (fail fast, no silent
2015
- * retry). ESM evaluates each bundle at most once per process, so bundles
2016
- * already imported during a failed capture can never re-register — a retry
2017
- * would deterministically fail the completeness check anyway.
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
2018
2211
  */
2019
- function loadOfficialClientModulesOnce() {
2020
- officialClientModulesPromise ??= captureOfficialClientModules();
2021
- return officialClientModulesPromise;
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
+ } };
2022
2234
  }
2235
+ //#endregion
2236
+ //#region src/app/remote/pi-tui-file-reference-host.ts
2023
2237
  /**
2024
- * Exact scoped loader capture: install a temporary `window.__ModuleLoader__`,
2025
- * dynamic-import the six bundles in dependency order, admit each bundle from
2026
- * exactly the channel the published `./client` entry selected (loader
2027
- * registration or standalone Node module — see {@link captureOfficialClientModules}),
2028
- * freeze the module-export table, and restore the previous process state in
2029
- * `finally` — before any Client Context exists.
2238
+ * The Host endpoint of the private augmentation. One instance per Remote Host
2239
+ * composition; the descriptor leaves with the owning fiber.
2030
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
+ });
2255
+ }
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;
2270
+ }
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;
2275
+ }
2031
2276
  /**
2032
- * The exact scoped loader admission rules (module-internal seam, exercised by
2033
- * the L5 loader-exactness test): reject an unknown registration id, a
2034
- * duplicate id, a non-function factory, and a `/client` dependency requested
2035
- * before its dependency-order capture; admit a directly imported Node bundle
2036
- * for an id the loader did not register; report missing expected ids.
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.
2037
2280
  */
2038
- function createScopedClientModuleLoader(expectedIds) {
2039
- const nodeRequire = createRequire(import.meta.url);
2040
- const registrations = /* @__PURE__ */ new Map();
2041
- const captured = /* @__PURE__ */ new Map();
2042
- const requireModule = (specifier) => {
2043
- if (specifier.endsWith("/client")) {
2044
- const id = specifier.slice(0, -7);
2045
- const module = captured.get(id);
2046
- if (module === void 0) throw new Error(`official Client module ${specifier} was requested before ${id} was captured`);
2047
- return module;
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.
2286
+ *
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).
2289
+ */
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);
2048
2419
  }
2049
- return nodeRequire(specifier);
2050
- };
2051
- const load = ({ id, factory }) => {
2052
- if (!expectedIds.includes(id)) throw new Error(`official Client bundle loader received an unexpected registration id: ${String(id)}`);
2053
- if (registrations.has(id)) throw new Error(`official Client bundle ${id} registered twice`);
2054
- if (typeof factory !== "function") throw new Error(`official Client bundle ${id} registered a non-function factory`);
2055
- registrations.set(id, factory);
2056
- captured.set(id, factory(requireModule));
2057
- };
2420
+ }
2058
2421
  /**
2059
- * Admit one directly imported bundle whose `./client` entry did not register
2060
- * through the loader shim (the standalone Node variant). The module joins the
2061
- * SAME table {@link requireModule} resolves `/client` dependencies from, so a
2062
- * registering bundle can still depend on a Node-variant one. A bundle that did
2063
- * register is left to its own registration: the browser factory result is the
2064
- * authoritative module for that id.
2065
- * @param id - the bundle's registration id.
2066
- * @param module - the imported module namespace.
2067
- * @throws when the id is unexpected or already admitted by a direct import.
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.
2068
2427
  */
2069
- const acceptImported = (id, module) => {
2070
- if (!expectedIds.includes(id)) throw new Error(`official Client bundle import produced an unexpected id: ${String(id)}`);
2071
- if (registrations.has(id)) return;
2072
- if (captured.has(id)) throw new Error(`official Client bundle ${id} was imported as a Node module twice`);
2073
- captured.set(id, module);
2074
- };
2075
- return {
2076
- load,
2077
- requireModule,
2078
- registeredIds: () => [...registrations.keys()],
2079
- acceptImported,
2080
- assertComplete() {
2081
- for (const id of expectedIds) if (!captured.has(id)) throw new Error(`official Client bundle ${id} was neither registered through __ModuleLoader__ nor imported as a Node module`);
2082
- }
2083
- };
2084
- }
2085
- /**
2086
- * Install the temporary `window.__ModuleLoader__` shim around exactly the six
2087
- * bundle imports, preserving the exact previous process state: when
2088
- * `globalThis.window` is absent, only the minimal temporary object is created
2089
- * and deleted again; when a `window` own property already exists (including a
2090
- * property whose value is `undefined`/`null`, and accessor descriptors), its
2091
- * exact property descriptor is restored, and any pre-existing
2092
- * `__ModuleLoader__` property descriptor on an existing window object is
2093
- * preserved and restored verbatim.
2094
- * @returns the restore function; it must run before any Client plugin executes
2095
- * (and on every failure path).
2096
- */
2097
- function installScopedModuleLoaderShim(load) {
2098
- const globalScope = globalThis;
2099
- const previousWindowDescriptor = Object.getOwnPropertyDescriptor(globalScope, "window");
2100
- const previousWindowValue = previousWindowDescriptor?.value;
2101
- const usableExistingWindow = typeof previousWindowValue === "object" && previousWindowValue !== null || typeof previousWindowValue === "function";
2102
- let previousLoaderDescriptor;
2103
- const install = () => {
2104
- if (usableExistingWindow) {
2105
- const existingWindow = previousWindowValue;
2106
- previousLoaderDescriptor = Object.getOwnPropertyDescriptor(existingWindow, "__ModuleLoader__");
2107
- existingWindow.__ModuleLoader__ = { load };
2108
- } else Object.defineProperty(globalScope, "window", {
2109
- configurable: true,
2110
- writable: true,
2111
- value: { __ModuleLoader__: { load } }
2112
- });
2113
- };
2114
- const restore = () => {
2115
- if (previousWindowDescriptor === void 0) {
2116
- delete globalScope.window;
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);
2117
2447
  return;
2118
2448
  }
2119
- Object.defineProperty(globalScope, "window", previousWindowDescriptor);
2120
- if (usableExistingWindow) {
2121
- const existingWindow = previousWindowValue;
2122
- if (previousLoaderDescriptor === void 0) delete existingWindow.__ModuleLoader__;
2123
- else Object.defineProperty(existingWindow, "__ModuleLoader__", previousLoaderDescriptor);
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);
2124
2453
  }
2125
- };
2126
- install();
2127
- return restore;
2128
- }
2129
- async function captureOfficialClientModules() {
2130
- const loader = createScopedClientModuleLoader(EXPECTED_REGISTRATION_IDS);
2131
- const restoreShim = installScopedModuleLoaderShim(loader.load);
2132
- try {
2133
- for (const bundle of OFFICIAL_CLIENT_BUNDLES) loader.acceptImported(bundle.id, await import(bundle.specifier));
2134
- loader.assertComplete();
2135
- } finally {
2136
- restoreShim();
2137
2454
  }
2138
- const captured = /* @__PURE__ */ new Map();
2139
- for (const id of EXPECTED_REGISTRATION_IDS) captured.set(id, loader.requireModule(`${id}/client`));
2140
- return freezeOfficialClientModules(captured);
2141
- }
2142
- function freezeOfficialClientModules(captured) {
2143
- const modules = {
2144
- typert: captured.get("@deepseek-ai/dsh-typert-registry"),
2145
- connection: captured.get("@deepseek-ai/dsh-client-connection"),
2146
- gateway: captured.get("@deepseek-ai/dsh-api-gateway"),
2147
- fileUpload: captured.get("@deepseek-ai/dsh-client-file-upload"),
2148
- session: captured.get("@deepseek-ai/dsh-api-session-controller"),
2149
- jobs: captured.get("@deepseek-ai/dsh-api-job-controller")
2150
- };
2151
- 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}`);
2152
- return Object.freeze(modules);
2153
- }
2154
- /** Explicit generated `/remote` contributions (§2.4.2), never the aggregate. */
2155
- const REMOTE_CONTRIBUTIONS = [
2156
- sessionRemote,
2157
- jobRemote,
2158
- commandsRemote,
2159
- subagentsRemote,
2160
- agentPresetsRemote,
2161
- pluginManagerRemote,
2162
- settingsRemote,
2163
- permissionPresetsRemote,
2164
- llmRemote,
2165
- fileUploadsRemote,
2166
- userQuestionsRemote
2167
- ];
2168
- /**
2169
- * Reverse-dispose the recorded `/remote` contribution disposers. Per-step
2170
- * error isolation: one rejecting disposer cannot truncate the remaining
2171
- * cleanup. Returns the collected cleanup errors in encounter order.
2172
- *
2173
- * Exported so the L5 suite can exercise the exact collection semantics the
2174
- * production composition relies on (module-internal seam, like
2175
- * `createScopedClientModuleLoader`).
2176
- */
2177
- async function disposeRemoteContributions(disposers) {
2178
- const errors = [];
2179
- for (let index = disposers.length - 1; index >= 0; index -= 1) try {
2180
- await disposers[index]();
2181
- } catch (error) {
2182
- errors.push(error);
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();
2183
2463
  }
2184
- return errors;
2185
- }
2186
- /**
2187
- * Compose one fresh official Client `Context` over the Host carrier:
2188
- * typert -> Connection (explicit transport) -> Gateway -> the eleven explicit
2189
- * `/remote` contributions -> the private pi-tui contribution (TS8-HF1) ->
2190
- * fileUpload -> Sessions -> Jobs, then wait for initial readiness. On
2191
- * construction failure the partial composition unwinds immediately; the
2192
- * loader shim is never active during plugin execution.
2193
- */
2194
- async function createRemoteClientRuntime(options) {
2195
- const modules = await loadOfficialClientModulesOnce();
2196
- const { carrier } = options;
2197
- const context = new Context();
2198
- let typertFiber;
2199
- let connectionFiber;
2200
- let gatewayFiber;
2201
- let fileUploadFiber;
2202
- let sessionFiber;
2203
- let jobsFiber;
2204
- let services;
2205
- const contributionDisposers = [];
2206
- let disposed = false;
2207
2464
  /**
2208
- * The frozen §16 shutdown sequence: domain Clients (reverse), the explicit
2209
- * `/remote` contributions (reverse), Gateway/Connection/Typert (reverse),
2210
- * then the Client root. Unwinding a partial composition runs the SAME
2211
- * order over whatever subset exists: a fiber whose startup rejected is
2212
- * already assigned, so it unwinds at its own position; only stages that
2213
- * were never reached are skipped.
2214
- *
2215
- * Contribution-disposer failures are isolated (collected, never allowed to
2216
- * truncate the remaining cleanup). Cordis contains unload-disposer failures
2217
- * inside `fiber.dispose()` (they are logged there, never propagated), so
2218
- * the fiber steps cannot reject.
2219
- *
2220
- * @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).
2221
2469
  */
2222
- const shutdown = async () => {
2223
- for (const fiber of [
2224
- jobsFiber,
2225
- sessionFiber,
2226
- fileUploadFiber
2227
- ]) await fiber?.dispose();
2228
- const contributionErrors = await disposeRemoteContributions(contributionDisposers);
2229
- contributionDisposers.length = 0;
2230
- for (const fiber of [
2231
- gatewayFiber,
2232
- connectionFiber,
2233
- typertFiber
2234
- ]) await fiber?.dispose();
2235
- await context.fiber.dispose();
2236
- return contributionErrors;
2237
- };
2238
- const unwind = async () => {
2239
- disposed = true;
2240
- return shutdown();
2241
- };
2242
- try {
2243
- typertFiber = context.plugin(modules.typert);
2244
- await typertFiber;
2245
- connectionFiber = context.plugin((connectionContext) => {
2246
- modules.connection.installConnection(connectionContext, {
2247
- interactions: "answer",
2248
- transport: {
2249
- ownsHost: true,
2250
- fetch: carrier.fetch,
2251
- openStream: carrier.openStream
2252
- }
2253
- });
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"
2254
2507
  });
2255
- await connectionFiber;
2256
- gatewayFiber = context.plugin(modules.gateway);
2257
- await gatewayFiber;
2258
- for (const contribution of REMOTE_CONTRIBUTIONS) contributionDisposers.push(await context.remote.$mount(contribution));
2259
- contributionDisposers.push(await context.remote.$mount(PI_TUI_CLIENT_CONTRIBUTION));
2260
- fileUploadFiber = context.plugin(modules.fileUpload);
2261
- await fileUploadFiber;
2262
- sessionFiber = context.plugin(modules.session);
2263
- await sessionFiber;
2264
- jobsFiber = context.plugin(modules.jobs);
2265
- await jobsFiber;
2266
- services = {
2267
- connection: context.get("connection"),
2268
- sessions: context.get("sessions"),
2269
- 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
2270
2531
  };
2271
- await waitForInitialReadiness(services.connection, services.sessions, options.signal);
2272
- } catch (error) {
2273
- const cleanupErrors = await unwind();
2274
- const failure = error instanceof Error ? error : new Error(String(error));
2275
- if (cleanupErrors.length > 0) mergeCause(failure, cleanupErrors.length === 1 ? cleanupErrors[0] : new AggregateError(cleanupErrors, "remote client runtime: unwind disposal failures"));
2276
- throw failure;
2532
+ for (const subscriber of record.subscribers) subscriber.push(frame);
2277
2533
  }
2278
- const { connection, sessions, jobs } = services;
2279
- return {
2280
- context,
2281
- connection,
2282
- sessions,
2283
- jobs,
2284
- remote: context.remote,
2285
- async dispose() {
2286
- if (disposed) return;
2287
- disposed = true;
2288
- const cleanupErrors = await shutdown();
2289
- if (cleanupErrors.length > 0) {
2290
- const failure = cleanupErrors[0] instanceof Error ? cleanupErrors[0] : new Error(String(cleanupErrors[0]));
2291
- if (cleanupErrors.length > 1) mergeCause(failure, new AggregateError(cleanupErrors.slice(1), "remote client runtime: remaining disposal failures"));
2292
- throw failure;
2293
- }
2294
- }
2295
- };
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)}`;
2296
2544
  }
2545
+ //#endregion
2546
+ //#region src/app/remote/host-prerequisites.ts
2297
2547
  /**
2298
- * Initial readiness: a defined Connection
2299
- * generation AND a `ready` Session list. Subscription-driven with no
2300
- * production timeout; the lifecycle signal aborts the wait and every listener
2301
- * 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.
2302
2551
  */
2303
- async function waitForInitialReadiness(connection, sessions, signal) {
2304
- const isReady = () => connection.generation.getSnapshot() !== void 0 && sessions.list.getSnapshot().phase === "ready";
2305
- if (signal?.aborted) throw new Error("remote client runtime: aborted before initial readiness", { cause: signal.reason });
2306
- if (isReady()) return;
2307
- await new Promise((resolve, reject) => {
2308
- let settled = false;
2309
- let abortListener;
2310
- const settle = () => {
2311
- if (settled) return;
2312
- if (isReady()) {
2313
- settled = true;
2314
- cleanup();
2315
- resolve();
2316
- }
2317
- };
2318
- const generationUnsubscribe = connection.generation.subscribe(settle);
2319
- const listUnsubscribe = sessions.list.subscribe(settle);
2320
- const cleanup = () => {
2321
- generationUnsubscribe();
2322
- listUnsubscribe();
2323
- if (abortListener !== void 0) signal?.removeEventListener("abort", abortListener);
2324
- };
2325
- if (signal !== void 0) {
2326
- abortListener = () => {
2327
- if (settled) return;
2328
- settled = true;
2329
- cleanup();
2330
- reject(new Error("remote client runtime: aborted before initial readiness", { cause: signal.reason }));
2331
- };
2332
- if (signal.aborted) {
2333
- abortListener();
2334
- return;
2335
- }
2336
- signal.addEventListener("abort", abortListener, { once: true });
2337
- }
2338
- settle();
2339
- });
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`);
2340
2579
  }
2341
2580
  //#endregion
2342
- //#region src/runtime/remote/prompt-serializer-remote.ts
2343
- /** Base64-encode one byte buffer (Node Buffer, kept inside the adapter). */
2344
- function base64Of(bytes) {
2345
- return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
2346
- }
2347
- /** The echo attachment view of one staged image (display facts only). */
2348
- function previewOf(image) {
2349
- return {
2350
- type: "image",
2351
- value: {
2352
- previewUrl: "",
2353
- ...image.name !== void 0 ? { name: image.name } : {},
2354
- width: image.width,
2355
- height: image.height
2356
- }
2357
- };
2358
- }
2359
- /** Detach the official imageLimits projection value; `undefined` when the
2360
- * projection is absent for this session (the recheck then keeps only the
2361
- * Client-side conservative caps — never a guessed limit). */
2362
- function detachedImageLimits(value) {
2363
- if (typeof value !== "object" || value === null) return void 0;
2364
- const limits = value;
2365
- if (typeof limits.maxImagesPerMessage !== "number" || typeof limits.maxMessageImageBytes !== "number") return void 0;
2366
- return {
2367
- maxImagesPerMessage: limits.maxImagesPerMessage,
2368
- maxMessageImageBytes: limits.maxMessageImageBytes
2369
- };
2370
- }
2371
- /** The production Remote prompt serializer. */
2372
- var RemotePromptSerializerProduction = class RemotePromptSerializerProduction {
2373
- attachments;
2374
- sessions;
2375
- constructor(attachments) {
2376
- this.attachments = attachments;
2377
- }
2378
- /** Build the production serializer over the official Client sessions face:
2379
- * recalled durable images read their authorized bytes through the exact
2380
- * retained binding, addressed by the PreparedPrompt's own session id. */
2381
- static overSessions(sessions) {
2382
- const serializer = new RemotePromptSerializerProduction({ async readAttachment(sessionId, attachmentId) {
2383
- const binding = sessions.binding(sessionId);
2384
- if (binding === void 0) return {
2385
- ok: false,
2386
- error: /* @__PURE__ */ new Error(`session "${sessionId}" is not available for an attachment read`)
2387
- };
2388
- const result = await binding.session.readAttachment(attachmentId);
2389
- if (result.ok) return {
2390
- ok: true,
2391
- data: result.value.data
2392
- };
2393
- return {
2394
- ok: false,
2395
- error: result.error
2396
- };
2397
- } });
2398
- serializer.sessions = sessions;
2399
- return serializer;
2400
- }
2401
- preflight(prepared) {
2402
- const prompt = prepared;
2403
- if (prompt === void 0 || prompt === null || typeof prompt !== "object" || !Array.isArray(prompt.segments)) return {
2404
- kind: "unsupported",
2405
- reason: "the submission carries no prepared prompt snapshot"
2406
- };
2407
- if (prompt.hasFiles) return {
2408
- kind: "unsupported",
2409
- reason: "generic file attachments require an upload receipt this Remote composition does not provide"
2410
- };
2411
- for (const segment of prompt.segments) if (segment.type === "image") {
2412
- if (segment.image.recalledRef === void 0 && segment.image.byteLength === 0) return {
2413
- kind: "unsupported",
2414
- reason: "a staged image carries neither local bytes nor a durable reference"
2415
- };
2416
- if (segment.image.recalledRef !== void 0 && this.attachments === void 0) return {
2417
- kind: "unsupported",
2418
- reason: "recalled durable images need the official attachment read, which this composition does not provide"
2419
- };
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;
2603
+ return {
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
+ })();
2420
2613
  }
2421
- if (this.sessions !== void 0) {
2422
- const images = prompt.segments.filter((segment) => segment.type === "image");
2423
- if (images.length > 0) {
2424
- const binding = this.sessions.binding(prompt.sessionId);
2425
- const limits = binding === void 0 ? void 0 : detachedImageLimits(binding.session.projections.faceOf("imageLimits").getSnapshot());
2426
- if (limits !== void 0) {
2427
- if (images.length > limits.maxImagesPerMessage) return {
2428
- kind: "unsupported",
2429
- reason: `too many images: ${images.length} attached, the current limit is ${limits.maxImagesPerMessage} per message`
2430
- };
2431
- const aggregate = images.reduce((total, segment) => total + segment.image.byteLength, 0);
2432
- if (aggregate > limits.maxMessageImageBytes) return {
2433
- kind: "unsupported",
2434
- reason: `images total ${aggregate} bytes; the current aggregate limit is ${limits.maxMessageImageBytes} bytes`
2435
- };
2614
+ };
2615
+ }
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);
2650
+ }
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 });
2436
2673
  }
2437
- }
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);
2438
2722
  }
2439
- return {
2440
- kind: "ok",
2441
- echo: {
2442
- text: prompt.segments.map((segment) => segment.type === "text" ? segment.text : segment.type === "image" ? "[image]" : "[file]").join(""),
2443
- attachments: prompt.segments.filter((segment) => segment.type === "image").map((segment) => previewOf(segment.image))
2444
- }
2445
- };
2723
+ throw error;
2446
2724
  }
2447
- async serialize(prepared, signal) {
2448
- const prompt = prepared;
2449
- if (prompt === void 0 || prompt === null || typeof prompt !== "object" || !Array.isArray(prompt.segments)) return {
2450
- kind: "unsupported",
2451
- reason: "the submission carries no prepared prompt snapshot"
2452
- };
2453
- if (prompt.hasFiles) return {
2454
- kind: "unsupported",
2455
- reason: "generic file attachments require an upload receipt this Remote composition does not provide"
2456
- };
2457
- const parts = [];
2458
- for (const segment of prompt.segments) {
2459
- signal?.throwIfAborted();
2460
- if (segment.type === "text") {
2461
- if (segment.text !== "") parts.push({
2462
- type: "text",
2463
- text: segment.text
2464
- });
2465
- continue;
2466
- }
2467
- if (segment.type === "image") {
2468
- const image = segment.image;
2469
- if (image.recalledRef !== void 0) {
2470
- const read = await this.attachments.readAttachment(prompt.sessionId, image.recalledRef.attachmentId);
2471
- signal?.throwIfAborted();
2472
- if (!read.ok) return {
2473
- kind: "unsupported",
2474
- reason: `the durable image bytes could not be read for re-send (${String(read.error)})`
2475
- };
2476
- parts.push({
2477
- type: "image",
2478
- mediaType: image.mediaType,
2479
- data: base64Of(read.data),
2480
- ...image.name !== void 0 ? { name: image.name } : {}
2481
- });
2482
- continue;
2483
- }
2484
- parts.push({
2485
- type: "image",
2486
- mediaType: image.mediaType,
2487
- data: base64Of(image.bytes),
2488
- ...image.name !== void 0 ? { name: image.name } : {}
2489
- });
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;
2490
2736
  }
2491
2737
  }
2492
- return {
2493
- kind: "ok",
2494
- content: Object.freeze(parts)
2495
- };
2496
- }
2497
- };
2498
- //#endregion
2499
- //#region src/runtime/remote/host-user-shell-remote.ts
2500
- /** The one truthful message every Remote admission returns. */
2501
- const CARRIER_GAP_MESSAGE = "Host user-shell execution is unavailable in this Remote composition — nothing was executed";
2502
- /** The Remote backend's Host user-shell port: truthful, inert, fail-closed. */
2503
- var RemoteHostUserShellPort = class {
2504
- availability = {
2505
- supported: false,
2506
- policies: []
2507
2738
  };
2508
- async execute(_request) {
2509
- return {
2510
- kind: "unavailable",
2511
- reason: {
2512
- reason: "carrier-gap",
2513
- message: CARRIER_GAP_MESSAGE
2514
- }
2515
- };
2516
- }
2517
- };
2739
+ }
2518
2740
  //#endregion
2519
2741
  //#region src/runtime/remote/interaction-remote.ts
2520
2742
  const USER_QUESTIONS_PROJECTION_KEY = "userQuestions";
@@ -2890,6 +3112,90 @@ var RemotePluginManagerPort = class {
2890
3112
  }
2891
3113
  };
2892
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
2893
3199
  //#region src/runtime/remote/job-observation-remote.ts
2894
3200
  /**
2895
3201
  * The Job-Stop operation-specific settlement table.
@@ -4981,6 +5287,7 @@ function createRemoteM3ASemantics(runtime, options) {
4981
5287
  $on: forwardedEvents
4982
5288
  }, generation),
4983
5289
  jobObservation: new RemoteJobObservationPort(runtime.jobs),
5290
+ deliveredFileRead: new RemoteDeliveredFileReadPort(remote.workspaceFiles, generation),
4984
5291
  dispose() {
4985
5292
  if (disposed) return;
4986
5293
  disposed = true;
@@ -4993,10 +5300,10 @@ function createRemoteM3ASemantics(runtime, options) {
4993
5300
  //#endregion
4994
5301
  //#region src/app/remote/session-owners.ts
4995
5302
  /**
4996
- * M3-2 Remote Session owner services: the exact-`SessionBinding` provider of
5303
+ * Remote Session owner services: the exact-`SessionBinding` provider of
4997
5304
  * the consumer-owned `SessionOwnerAccess` / `SessionOwnerRetirement` seams.
4998
5305
  *
4999
- * 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
5000
5307
  * `SessionReference.binding` OBJECT a retained `ClientSessionOwner` carries is
5001
5308
  * the generation token —
5002
5309
  *
@@ -5017,7 +5324,7 @@ function createRemoteM3ASemantics(runtime, options) {
5017
5324
  * exact Client reference exactly once, and `whenIdleOrAbort` observes the
5018
5325
  * official `SessionSnapshot.running` without ever cancelling the Host session.
5019
5326
  *
5020
- * M3-2 composition note: this provider is not wired into any production
5327
+ * Composition note: this provider is not wired into any production
5021
5328
  * bootstrap yet (M3-3B/M3-4 own the Remote runtime selection seam). Tests and
5022
5329
  * the future Remote composition construct it directly.
5023
5330
  *