@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +33 -0
  2. package/README.en.md +103 -814
  3. package/README.md +102 -711
  4. package/cordis.patch.yml +186 -0
  5. package/dist/acp-preferences.d.mts +29 -0
  6. package/dist/acp-preferences.mjs +15 -0
  7. package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
  8. package/dist/builtins.mjs +3 -3
  9. package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
  10. package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
  11. package/dist/command-trust-DChWUamk.mjs +406 -0
  12. package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
  13. package/dist/daemon-launcher.d.mts +159 -0
  14. package/dist/daemon-launcher.mjs +2 -0
  15. package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
  16. package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
  17. package/dist/entry-control-DjNsE3I0.mjs +190 -0
  18. package/dist/extension/advanced.d.mts +1 -1
  19. package/dist/extension/unstable.d.mts +1 -1
  20. package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
  21. package/dist/extension-config.d.mts +29 -0
  22. package/dist/extension-config.mjs +22 -0
  23. package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
  24. package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
  25. package/dist/extensions.d.mts +2 -2
  26. package/dist/extensions.mjs +1 -1
  27. package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
  28. package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
  29. package/dist/host-runtime.d.mts +11 -5
  30. package/dist/host-runtime.mjs +4171 -920
  31. package/dist/index.d.mts +86 -174
  32. package/dist/index.mjs +38087 -9967
  33. package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
  34. package/dist/local-client.mjs +1158 -59
  35. package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
  36. package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
  37. package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
  38. package/dist/local-discovery-egN4_gsQ.mjs +2 -0
  39. package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
  40. package/dist/local-host.mjs +812 -89
  41. package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
  42. package/dist/local-scope-DamiMqPd.mjs +1340 -0
  43. package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
  44. package/dist/local-web-control-DMrjwCkl.mjs +454 -0
  45. package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
  46. package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  47. package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  48. package/dist/open-CmOBxSjN.mjs +63 -0
  49. package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
  50. package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
  51. package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
  52. package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
  53. package/dist/preferences.d.mts +17 -0
  54. package/dist/preferences.mjs +20 -0
  55. package/dist/preset-BcWqOtY7.mjs +46 -0
  56. package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
  57. package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
  58. package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
  59. package/dist/prompt-sections-DXmjB58H.mjs +634 -0
  60. package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
  61. package/dist/row-id-DPbyt9Nn.mjs +24 -0
  62. package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
  63. package/dist/schema-BTGYn8_X.d.mts +54 -0
  64. package/dist/schema-qE_P09zJ.mjs +124 -0
  65. package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
  66. package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
  67. package/dist/startup-CarQxWwi.d.mts +213 -0
  68. package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
  69. package/dist/startup.d.mts +2 -99
  70. package/dist/startup.mjs +2 -2
  71. package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
  72. package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
  73. package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
  74. package/dist/version-B9yC7bBk.mjs +83 -0
  75. package/dist/visual-tools.d.mts +1 -1
  76. package/dist/visual-tools.mjs +1 -1
  77. package/dist/web-preferences.d.mts +1 -1
  78. package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
  79. package/generated/dsh-presets/cordis.patch.yml +4 -2
  80. package/generated/dsh-presets/ptc.patch.yml +4 -0
  81. package/generated/dsh-presets/standard.patch.yml +7 -0
  82. package/generated/web-access/cordis.patch.yml +239 -0
  83. package/package.json +217 -170
  84. package/dist/entry-control-DnduyDiw.mjs +0 -92
  85. package/dist/local-discovery-C9VMjc0K.mjs +0 -759
  86. package/dist/local-discovery-CDaQHA_R.mjs +0 -2
  87. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
  88. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
  89. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
  90. package/dist/version-a-eF-QER.mjs +0 -80
@@ -1,14 +1,18 @@
1
1
  import { n as isCancellation, o as safeErrorMessage } from "./tasks-D_z5Yjjr.mjs";
2
- import { F as parseKey, M as isKeyRelease, N as isKeyRepeat, ut as stripControlChars } from "./dist-CIsR7cz4.mjs";
3
- import { r as parsePiTuiTerminalProgressFrame } from "./pi-tui-terminal-progress-contract-CdBH9j78.mjs";
2
+ import { f as stripControlChars } from "./command-trust-DChWUamk.mjs";
3
+ import { F as parseKey, M as isKeyRelease, N as isKeyRepeat } from "./dist-BFgC-5tL.mjs";
4
+ import { r as parsePiTuiTerminalProgressFrame } from "./pi-tui-terminal-progress-contract-B3RoEzjK.mjs";
5
+ import { t as extensionConfigRowId } from "./row-id-DPbyt9Nn.mjs";
4
6
  import "node:module";
7
+ import { createHash } from "node:crypto";
5
8
  import { readFileSync, realpathSync } from "node:fs";
6
9
  import { dirname, join } from "node:path";
7
10
  import "node:os";
8
11
  import "commander";
9
12
  import "@deepseek-ai/dsh-cmdline";
13
+ import z from "@deepseek-ai/schemastery";
10
14
  import { parseCommand } from "@deepseek-ai/dsh-commands";
11
- import { Service } from "@deepseek-ai/cordis";
15
+ import { Service, symbols } from "@deepseek-ai/cordis";
12
16
  //#region \0rolldown/runtime.js
13
17
  var __defProp = Object.defineProperty;
14
18
  var __exportAll = (all, no_symbols) => {
@@ -43,8 +47,8 @@ const COMPAT = {
43
47
  "package.json's version), the runtime floor it imposes, the recommended published DSH",
44
48
  "target and the recovery wording. The floor and the target are distinct values and",
45
49
  "must stay independently derived. Consumed by src/startup.ts (inlined by the bundler)",
46
- "and, through scripts/lib/dsh-compat.mjs, by the release tooling, the",
47
- "installation-doc gate and the release-notes tests.",
50
+ "and, through scripts/lib/dsh-compat.mjs, by the release tooling and the",
51
+ "release-notes tests.",
48
52
  "package.json restates the newest row's `dshFrom` as `engines.dsh` `>=<dshFrom>`; DSH",
49
53
  "prefers that field over the DSH peer ranges and only falls back to the peers when it",
50
54
  "is absent, so the peers keep the npm-level fallback in sync with the same floor",
@@ -53,11 +57,11 @@ const COMPAT = {
53
57
  "not by itself qualify every such prerelease."
54
58
  ],
55
59
  current: {
56
- "since": "0.5.6",
57
- "requires": "DeepSeek Harness 0.2.2-rc.1 or later",
58
- "upgradeDsh": "0.2.2-rc.1",
59
- "upgradeCommand": "npm install -g --allow-scripts=@deepseek-ai/dsh-subprocess-local,koffi,node-pty @deepseek-ai/dsh@0.2.2-rc.1",
60
- "guidance": "The 0.5.6 release requires DeepSeek Harness 0.2.2-rc.1 or later; this checkout validates that runtime floor and targets 0.2.2-rc.1. The previous 0.2.1-rc.* family is no longer supported, so finish in-flight turns and background jobs before upgrading. See README.en.md for the DSH/TUI pairing table, and docs/guides/dsh-compatibility.md for compatibility/recovery rules."
60
+ "since": "0.5.8",
61
+ "requires": "DeepSeek Harness 0.2.2-rc.3 or later",
62
+ "upgradeDsh": "0.2.2-rc.5",
63
+ "upgradeCommand": "npm install -g --allow-scripts=@deepseek-ai/dsh-subprocess-local,koffi,node-pty @deepseek-ai/dsh@0.2.2-rc.5",
64
+ "guidance": "The 0.5.8 release requires DeepSeek Harness 0.2.2-rc.3 or later; this checkout validates that runtime floor and targets 0.2.2-rc.5 (validated pairing; on Hosts older than rc.5 the automatic web-search routing decision may differ). The previous 0.2.2-rc.2 and 0.2.2-rc.1 pairings are no longer claimed by this release, so finish in-flight turns and background jobs before upgrading. See README.en.md for the DSH/TUI pairing table, and docs/guides/dsh-compatibility.md for compatibility/recovery rules."
61
65
  },
62
66
  floor: {
63
67
  "below": "0.1.0-rc.8",
@@ -154,6 +158,19 @@ const COMPAT = {
154
158
  "dshFrom": "0.2.2-rc.1",
155
159
  "tui": "0.5.6",
156
160
  "versions": ["0.2.2-rc.1"]
161
+ },
162
+ {
163
+ "dshFrom": "0.2.2-rc.2",
164
+ "versions": ["0.2.2-rc.2"]
165
+ },
166
+ {
167
+ "dshFrom": "0.2.2-rc.3",
168
+ "tui": "0.5.8",
169
+ "versions": [
170
+ "0.2.2-rc.3",
171
+ "0.2.2-rc.4",
172
+ "0.2.2-rc.5"
173
+ ]
157
174
  }
158
175
  ]
159
176
  };
@@ -174,34 +191,53 @@ const CURRENT_DSH_REQUIREMENT = {
174
191
  }))];
175
192
  /** Service provided by this plugin and injected by the TUI runner row. */
176
193
  const TUI_STARTUP_SERVICE = "tuiStartup";
194
+ z.object({ backend: z.string().default("direct").volatile() });
177
195
  //#endregion
178
196
  //#region src/client/launcher/version.ts
179
197
  /**
180
- * The Client-local launcher/version reads: the installed dsh (DeepSeek
181
- * Harness CLI) version, resolved from the launcher's real path — `process.argv[1]`
182
- * is the `dsh` bin, whose realpath walks up to the `@deepseek-ai/dsh/package.json`
183
- * that owns it — plus the bundle's OWN version reads (`bundleVersion`,
184
- * `packageVersion`). The header and the welcome card show the harness the TUI
185
- * runs on, not this bundle's own patch level; `dshVersion` is undefined when
186
- * the launcher path is unreadable. The combined welcome-card display line lives
187
- * in the application presentation owner (`app/surface/version-display.ts`).
198
+ * The Client-local launcher/version reads: the installed DSH (DeepSeek
199
+ * Harness) runtime version and the bundle's OWN version. The header, welcome
200
+ * card, status footer and About page show the harness this Client runs on, not
201
+ * this bundle's own patch level; `dshVersion` is undefined when the installed
202
+ * runtime identity is unreadable.
188
203
  *
189
- * This is Client-local platform IO: it reads the local process argv and the
190
- * locally installed package manifests. The zero-dependency startup island keeps
191
- * its own private comparator and never imports this module.
204
+ * Direct: `process.argv[1]` is the `dsh` bin, whose realpath walks up to the
205
+ * `@deepseek-ai/dsh/package.json` that owns it. Split surface Client: argv[1]
206
+ * is `dist/local-client.mjs`, so the version comes ONLY from the official
207
+ * Profile launcher's `SPLIT_PROCESS_DSH_ANCHOR` manifest — never from argv or
208
+ * this bundle's manifest.
209
+ *
210
+ * This is Client-local platform IO: it reads the local process environment and
211
+ * installed package manifests. The zero-dependency startup island keeps its
212
+ * own private comparator and never imports this module.
192
213
  * @module @xmoon76/dsh-pi-tui/client/launcher/version
193
214
  */
194
- /** @returns the installed dsh version string, or undefined. */
215
+ /** Read one JSON object manifest; an unreadable path, malformed JSON or a
216
+ * non-object root is unavailable. */
217
+ function readManifestObject(path) {
218
+ try {
219
+ const manifest = JSON.parse(readFileSync(realpathSync(path), "utf8"));
220
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) return void 0;
221
+ return manifest;
222
+ } catch {
223
+ return;
224
+ }
225
+ }
226
+ /** @returns the installed dsh runtime version string, or undefined. */
195
227
  function dshVersion() {
228
+ if (process.env.SPLIT_PROCESS_CLIENT_MODE === "surface") {
229
+ const anchor = process.env.SPLIT_PROCESS_DSH_ANCHOR;
230
+ if (anchor === void 0 || anchor === "") return void 0;
231
+ const manifest = readManifestObject(anchor);
232
+ return manifest?.name === "@deepseek-ai/dsh" && typeof manifest.version === "string" && manifest.version !== "" ? manifest.version : void 0;
233
+ }
196
234
  const bin = process.argv[1];
197
235
  if (bin === void 0) return void 0;
198
236
  try {
199
237
  let dir = dirname(realpathSync(bin));
200
238
  for (let depth = 0; depth < 8; depth += 1) {
201
- try {
202
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
203
- if (pkg.name === "@deepseek-ai/dsh" && typeof pkg.version === "string") return pkg.version;
204
- } catch {}
239
+ const pkg = readManifestObject(join(dir, "package.json"));
240
+ if (pkg?.name === "@deepseek-ai/dsh" && typeof pkg.version === "string") return pkg.version;
205
241
  const parent = dirname(dir);
206
242
  if (parent === dir) return void 0;
207
243
  dir = parent;
@@ -219,33 +255,18 @@ function dshVersion() {
219
255
  function ownBundleVersion() {
220
256
  let dir = import.meta.dirname;
221
257
  for (let depth = 0; depth < 8; depth += 1) {
222
- try {
223
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
224
- if (pkg.name === "@xmoon76/dsh-pi-tui" && typeof pkg.version === "string") return pkg.version;
225
- } catch {}
258
+ const pkg = readManifestObject(join(dir, "package.json"));
259
+ if (pkg?.name === "@xmoon76/dsh-pi-tui" && typeof pkg.version === "string") return pkg.version;
226
260
  const parent = dirname(dir);
227
261
  if (parent === dir) return void 0;
228
262
  dir = parent;
229
263
  }
230
264
  }
231
265
  /**
232
- * The bundle's own version, read from package.json at runtime so the welcome
233
- * card never drifts from the shipped version. The DISPLAYED version prefers
234
- * the installed dsh version (`dshVersion` — shared with the header badge),
235
- * falling back to this one.
236
- * @returns the version string, or a fallback when the file is unreadable.
237
- */
238
- function packageVersion$1() {
239
- return dshVersion() ?? ownBundleVersion() ?? "0.0.0";
240
- }
241
- /**
242
266
  * The BUNDLE's OWN version (`@xmoon76/dsh-pi-tui`'s package.json),
243
- * INDEPENDENT of the installed dsh version. The status snapshot's
244
- * host.tuiVersion and the footer's `version(format=tui)` item must report
245
- * the TUI's own patch level — the welcome-card helper above deliberately
246
- * prefers the dsh version for display, so reusing it made `tui` show the
247
- * harness version (and `both` show the dsh version twice) inside a real
248
- * dsh installation (the review's P2).
267
+ * INDEPENDENT of the installed dsh version. This is the ONE TUI bundle version
268
+ * semantic consumed by the header/welcome card, About, `boot.bundle` and the
269
+ * extension host's own version.
249
270
  * @returns the bundle version string, or a fallback when the file is unreadable.
250
271
  */
251
272
  function bundleVersion() {
@@ -819,19 +840,35 @@ const APP_KEYBINDINGS = {
819
840
  "app.exit.request": {
820
841
  id: "app.exit.request",
821
842
  defaultKeys: ["ctrl+c", "ctrl+d"],
822
- description: "Quit the TUI (keyboard exit requires a same-key second press; the default clear-draft and forward-delete editor behaviors are preserved)",
843
+ description: "Exit this TUI (a same-key second press confirms; a daemon Host keeps running; the editor keeps its default clear-draft and forward-delete behavior)",
823
844
  category: "Agent",
824
845
  scope: "global",
825
846
  configurable: true
826
847
  },
848
+ "app.transcript.search.view": {
849
+ id: "app.transcript.search.view",
850
+ defaultKeys: ["ctrl+f"],
851
+ description: "Search the rendered transcript view",
852
+ category: "Transcript",
853
+ scope: "global",
854
+ configurable: true
855
+ },
827
856
  "app.transcript.search": {
828
857
  id: "app.transcript.search",
829
- defaultKeys: ["ctrl+f", "ctrl+shift+f"],
830
- description: "Search the transcript",
858
+ defaultKeys: ["ctrl+shift+f"],
859
+ description: "Search the full transcript history",
831
860
  category: "Transcript",
832
861
  scope: "global",
833
862
  configurable: true
834
863
  },
864
+ "app.transcript.search.scope": {
865
+ id: "app.transcript.search.scope",
866
+ defaultKeys: ["tab"],
867
+ description: "Switch transcript search scope",
868
+ category: "Transcript",
869
+ scope: "search",
870
+ configurable: false
871
+ },
835
872
  "app.transcript.jumpLatest": {
836
873
  id: "app.transcript.jumpLatest",
837
874
  defaultKeys: ["ctrl+end"],
@@ -952,6 +989,14 @@ const APP_KEYBINDINGS = {
952
989
  scope: "editor",
953
990
  configurable: true
954
991
  },
992
+ "app.queue.open": {
993
+ id: "app.queue.open",
994
+ defaultKeys: ["alt+i"],
995
+ description: "Manage queued messages",
996
+ category: "Panels",
997
+ scope: "global",
998
+ configurable: true
999
+ },
955
1000
  "app.history.search": {
956
1001
  id: "app.history.search",
957
1002
  defaultKeys: ["ctrl+r"],
@@ -1124,18 +1169,34 @@ const APP_KEYBINDINGS = {
1124
1169
  scope: "tasks",
1125
1170
  configurable: false
1126
1171
  },
1127
- "tasks.type.next": {
1128
- id: "tasks.type.next",
1172
+ "tasks.tab.next": {
1173
+ id: "tasks.tab.next",
1129
1174
  defaultKeys: ["tab"],
1130
- description: "Cycle the task type filter forward",
1175
+ description: "Switch to the Team page of the Task Center",
1131
1176
  category: "Tasks",
1132
1177
  scope: "tasks",
1133
1178
  configurable: false
1134
1179
  },
1135
- "tasks.type.previous": {
1136
- id: "tasks.type.previous",
1180
+ "tasks.tab.previous": {
1181
+ id: "tasks.tab.previous",
1137
1182
  defaultKeys: ["shift+tab"],
1138
- description: "Cycle the task type filter backward",
1183
+ description: "Switch back to the Work page of the Task Center",
1184
+ category: "Tasks",
1185
+ scope: "tasks",
1186
+ configurable: false
1187
+ },
1188
+ "tasks.type.filter": {
1189
+ id: "tasks.type.filter",
1190
+ defaultKeys: ["f"],
1191
+ description: "Open the Work type filter list",
1192
+ category: "Tasks",
1193
+ scope: "tasks",
1194
+ configurable: false
1195
+ },
1196
+ "tasks.jobs.toggleHistory": {
1197
+ id: "tasks.jobs.toggleHistory",
1198
+ defaultKeys: ["j"],
1199
+ description: "Show or hide tracked past Jobs",
1139
1200
  category: "Tasks",
1140
1201
  scope: "tasks",
1141
1202
  configurable: false
@@ -1249,6 +1310,7 @@ const VIEWER_BLOCKED_PARENT_ACTIONS = /* @__PURE__ */ new Set([
1249
1310
  "app.input.dequeue",
1250
1311
  "app.permission.cycle",
1251
1312
  "app.transcript.search",
1313
+ "app.transcript.search.view",
1252
1314
  "app.visual.selectNext",
1253
1315
  "app.visual.copySelected",
1254
1316
  "app.visual.openSelected",
@@ -1503,6 +1565,534 @@ function parseUserKeybindings(raw, options = {}) {
1503
1565
  }
1504
1566
  /** The default leader timeout (plan §6 M6: pending prefix expiry). */
1505
1567
  const DEFAULT_LEADER_TIMEOUT_MS = 1500;
1568
+ const SEARCH_PROVIDER_IDS = /* @__PURE__ */ new Set(["deepseek-official", "deepseek-search-api"]);
1569
+ const FETCH_PROVIDER_IDS = /* @__PURE__ */ new Set(["http", "deepseek-fetch-api"]);
1570
+ function assertSearchProviderId(id) {
1571
+ if (!SEARCH_PROVIDER_IDS.has(id)) throw new Error(`unsupported web search provider id "${id}"`);
1572
+ }
1573
+ function assertSearchProviderReplaceable(value) {
1574
+ if (value === void 0 || value === "") return;
1575
+ if (typeof value !== "string") throw new Error("the configured Web search provider is unreadable and cannot be replaced");
1576
+ if (!SEARCH_PROVIDER_IDS.has(value)) throw new Error(`the configured Web search provider uses a custom route "${value}" and cannot be replaced`);
1577
+ }
1578
+ function assertFetchProviderId(id) {
1579
+ if (!FETCH_PROVIDER_IDS.has(id)) throw new Error(`unsupported web fetch provider id "${id}"`);
1580
+ }
1581
+ function assertFetchProviderReplaceable(value) {
1582
+ if (value === void 0 || value === "") return;
1583
+ if (typeof value !== "string") throw new Error("the configured Web fetch provider is unreadable and cannot be replaced");
1584
+ if (!FETCH_PROVIDER_IDS.has(value)) throw new Error(`the configured Web fetch provider uses a custom route "${value}" and cannot be replaced`);
1585
+ }
1586
+ function assertSearchApiCount(count) {
1587
+ if (!Number.isInteger(count) || count < 1 || count > 50) throw new Error(`the web search API count must be an integer from 1 through 50`);
1588
+ }
1589
+ /** The official rc.2 `searchBilling` / `fetchBilling` closed enum. */
1590
+ const WEB_API_BILLING_MODES = /* @__PURE__ */ new Set([
1591
+ "auto",
1592
+ "account",
1593
+ "api-key"
1594
+ ]);
1595
+ /** Whether `mode` is one of the official closed billing modes. */
1596
+ function isWebApiBilling(mode) {
1597
+ return WEB_API_BILLING_MODES.has(mode);
1598
+ }
1599
+ /** Accept exactly the official closed billing enum; anything else (including a
1600
+ * legacy free-form value) is refused before it can reach the Host settings. */
1601
+ function assertWebApiBilling(mode) {
1602
+ if (!WEB_API_BILLING_MODES.has(mode)) throw new Error(`unsupported web API billing mode "${mode}" (the official modes are auto, account and api-key)`);
1603
+ }
1604
+ /** The official billing mode of one `web-deepseek-api` descriptor field, or
1605
+ * `undefined` when the field is absent or outside the closed enum. `undefined`
1606
+ * is UNAVAILABLE — the adapters must never silently default it to `auto`. */
1607
+ function readWebApiBilling(value, field) {
1608
+ const raw = value[field];
1609
+ return typeof raw === "string" && WEB_API_BILLING_MODES.has(raw) ? raw : void 0;
1610
+ }
1611
+ /** The display fact for a configured URL the Host cannot prove parseable.
1612
+ * The value is deliberately NOT echoed: reporting only that it is configured
1613
+ * is safer than guessing which bytes are credentials. */
1614
+ const UNPARSEABLE_WEB_OVERRIDE_URL = "[configured URL unavailable]";
1615
+ /** Mask the credential-bearing parts of one DISPLAYED URL override fact.
1616
+ * Structured URL parsing is the authority: the LAST `@` separates the
1617
+ * userinfo from the host (so a password containing `@` cannot leak), while
1618
+ * query/fragment and every raw control character are dropped. A value that
1619
+ * cannot be parsed as an http(s) URL is reported only as configured, never
1620
+ * echoed. */
1621
+ function maskWebProviderOverrideUrl(value) {
1622
+ if (/[\u0000-\u001f\u007f]/u.test(value)) return UNPARSEABLE_WEB_OVERRIDE_URL;
1623
+ let parsed;
1624
+ try {
1625
+ parsed = new URL(value);
1626
+ } catch {
1627
+ return UNPARSEABLE_WEB_OVERRIDE_URL;
1628
+ }
1629
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return UNPARSEABLE_WEB_OVERRIDE_URL;
1630
+ if (parsed.host === "") return UNPARSEABLE_WEB_OVERRIDE_URL;
1631
+ const authority = `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
1632
+ return parsed.username === "" && parsed.password === "" ? authority : `${parsed.protocol}//***@${parsed.host}${parsed.pathname}`;
1633
+ }
1634
+ /** Project one `web-deepseek-api` descriptor value into the advanced override
1635
+ * facts both adapters report. The URL fields are masked for display (userinfo
1636
+ * and query/fragment never survive); the `*ApiKeyEnv` fields are environment
1637
+ * NAMES, not secret values, and are copied verbatim. */
1638
+ function webApiAdvancedFactsOf(value) {
1639
+ const copyField = (field) => {
1640
+ const raw = value[field];
1641
+ if (typeof raw !== "string" || raw === "") return void 0;
1642
+ return field === "searchBaseURL" || field === "fetchBaseURL" ? maskWebProviderOverrideUrl(raw) : raw;
1643
+ };
1644
+ const searchBaseURL = copyField("searchBaseURL");
1645
+ const searchApiKeyEnv = copyField("searchApiKeyEnv");
1646
+ const fetchBaseURL = copyField("fetchBaseURL");
1647
+ const fetchApiKeyEnv = copyField("fetchApiKeyEnv");
1648
+ const legacyOverrideDetected = [
1649
+ "baseURL",
1650
+ "apiKeyEnv",
1651
+ "apiKey"
1652
+ ].some((field) => typeof value[field] === "string" && value[field] !== "");
1653
+ return {
1654
+ ...searchBaseURL !== void 0 ? { searchBaseURL } : {},
1655
+ ...searchApiKeyEnv !== void 0 ? { searchApiKeyEnv } : {},
1656
+ ...fetchBaseURL !== void 0 ? { fetchBaseURL } : {},
1657
+ ...fetchApiKeyEnv !== void 0 ? { fetchApiKeyEnv } : {},
1658
+ ...legacyOverrideDetected ? { legacyOverrideDetected: true } : {}
1659
+ };
1660
+ }
1661
+ /** Project one capability's layering facts from the SAME `web` descriptor's
1662
+ * `base`/`user` projections. `undefined` when either layer is not a plain
1663
+ * object: the caller MUST treat that as an unreadable section, never as "no
1664
+ * USER override". */
1665
+ function webProviderSelectionFactsOf(base, user, field) {
1666
+ if (!isPlainRecord$2(base) || !isPlainRecord$2(user)) return void 0;
1667
+ const baseValue = base[field];
1668
+ const userValue = user[field];
1669
+ return {
1670
+ baseId: typeof baseValue === "string" && baseValue !== "" ? baseValue : void 0,
1671
+ userSet: Object.hasOwn(user, field),
1672
+ userId: typeof userValue === "string" && userValue !== "" ? userValue : void 0
1673
+ };
1674
+ }
1675
+ /** Whether a value is a plain data object (not an array, null, or class instance). */
1676
+ function isPlainRecord$2(value) {
1677
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1678
+ const proto = Object.getPrototypeOf(value);
1679
+ return proto === Object.prototype || proto === null;
1680
+ }
1681
+ //#endregion
1682
+ //#region src/domain/mcp/server-config.ts
1683
+ /**
1684
+ * FR4 — the pure MCP server configuration editing domain (S1).
1685
+ *
1686
+ * Everything here is transport/UI-neutral policy over ONE official
1687
+ * `mcp-manager` settings descriptor: the server-name grammar, the
1688
+ * User-added / Inherited / Overridden provenance classification of one
1689
+ * entry (from the SAME descriptor's `base`/`user` layers), the per-transport
1690
+ * draft validation (cross-transport fields, `${credential:REF}` template
1691
+ * syntax), and the projection of one edit intent onto the official
1692
+ * `SettingsPathOp[]` batch (dirty field paths only; unknown/hidden fields
1693
+ * are never rewritten).
1694
+ *
1695
+ * There is NO IO here: the owning adapter supplies the descriptor facts, the
1696
+ * controller supplies the draft. The official Host schema/manager remains the
1697
+ * final validator — these rules exist so a broken draft is refused BEFORE a
1698
+ * settings mutation is dispatched, and so a User-only delete and an
1699
+ * inherited-override reset (the SAME official `unset ['servers', name]`)
1700
+ * are distinguished by their `base`/`user` preconditions, never by wording.
1701
+ *
1702
+ * @module @xmoon76/dsh-pi-tui/domain/mcp/server-config
1703
+ */
1704
+ /** The official server-name grammar (`@deepseek-ai/dsh-mcp-client`). */
1705
+ const MCP_SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
1706
+ /** Whether one string is a valid `${credential:REF}` template per the
1707
+ * official mcp-client rules (adjacent plain text allowed; every other
1708
+ * `${...}` occurrence is invalid). */
1709
+ function validTemplateSyntax(value) {
1710
+ for (const match of value.matchAll(/\$\{([^}]*)\}/gu)) if (!/^\$\{credential:[A-Za-z_][A-Za-z0-9_]*\}$/u.test(match[0] ?? "")) return false;
1711
+ return true;
1712
+ }
1713
+ /**
1714
+ * Whether one env/header key is acceptable. The official Settings path op uses
1715
+ * each segment as a LITERAL object key (`Object.defineProperty(result, head)`),
1716
+ * and the `mcp-manager` schema types env/headers as `z.dict(String)` with no
1717
+ * key grammar of its own — so a dot, a `$` or a colon is a legal key. Only an
1718
+ * empty key and embedded control characters are refused (they cannot be
1719
+ * painted or round-tripped).
1720
+ */
1721
+ function validMapKey(key) {
1722
+ return key !== "" && !/[\u0000-\u001f\u007f]/u.test(key);
1723
+ }
1724
+ /**
1725
+ * Validate one whole draft (Add or an edited form): name grammar first, then
1726
+ * the per-transport cross-field rules, then the template syntax of every
1727
+ * templated string. Returns every issue found (the UI shows them all); an
1728
+ * empty list means the draft is dispatchable.
1729
+ */
1730
+ function validateMcpServerDraft(name, draft) {
1731
+ const issues = [];
1732
+ if (!MCP_SERVER_NAME_PATTERN.test(name)) issues.push({
1733
+ field: "name",
1734
+ message: "the name may contain 1-32 ASCII letters, digits, \"_\" or \"-\""
1735
+ });
1736
+ if (draft.transport === "stdio") {
1737
+ if (draft.command.trim() === "") issues.push({
1738
+ field: "command",
1739
+ message: "a stdio server requires a command"
1740
+ });
1741
+ for (const [index, arg] of draft.args.entries()) if (!validTemplateSyntax(arg)) issues.push({
1742
+ field: "args",
1743
+ message: `argument ${String(index + 1)} has an invalid \${credential:REF} token`
1744
+ });
1745
+ for (const [key, value] of draft.env) {
1746
+ if (!validMapKey(key)) issues.push({
1747
+ field: "env",
1748
+ message: `invalid env key ${JSON.stringify(key)}`
1749
+ });
1750
+ if (!validTemplateSyntax(value)) issues.push({
1751
+ field: "env",
1752
+ message: `env ${JSON.stringify(key)} has an invalid \${credential:REF} token`
1753
+ });
1754
+ }
1755
+ if (!validTemplateSyntax(draft.command)) issues.push({
1756
+ field: "command",
1757
+ message: `the command has an invalid \${credential:REF} token`
1758
+ });
1759
+ if (!validTemplateSyntax(draft.cwd)) issues.push({
1760
+ field: "cwd",
1761
+ message: `the working directory has an invalid \${credential:REF} token`
1762
+ });
1763
+ } else {
1764
+ if (draft.url.trim() === "") issues.push({
1765
+ field: "url",
1766
+ message: "a streamable-http server requires a URL"
1767
+ });
1768
+ for (const [key, value] of draft.headers) {
1769
+ if (!validMapKey(key)) issues.push({
1770
+ field: "headers",
1771
+ message: `invalid header key ${JSON.stringify(key)}`
1772
+ });
1773
+ if (!validTemplateSyntax(value)) issues.push({
1774
+ field: "headers",
1775
+ message: `header ${JSON.stringify(key)} has an invalid \${credential:REF} token`
1776
+ });
1777
+ }
1778
+ if (!validTemplateSyntax(draft.url)) issues.push({
1779
+ field: "url",
1780
+ message: `the URL has an invalid \${credential:REF} token`
1781
+ });
1782
+ }
1783
+ return issues;
1784
+ }
1785
+ /** Diff one edited draft against the effective entry. */
1786
+ function diffMcpServerDraft(effective, draft) {
1787
+ const scalars = /* @__PURE__ */ new Set();
1788
+ if (effective.transport !== draft.transport) scalars.add("transport");
1789
+ if (draft.transport === "stdio" || effective.transport === "stdio") {
1790
+ if ((effective.command ?? "") !== draft.command) scalars.add("command");
1791
+ if ((effective.cwd ?? "") !== draft.cwd) scalars.add("cwd");
1792
+ }
1793
+ if (draft.transport === "streamable-http" || effective.transport === "streamable-http") {
1794
+ if ((effective.url ?? "") !== draft.url) scalars.add("url");
1795
+ }
1796
+ if ((effective.enabled ?? true) !== draft.enabled) scalars.add("enabled");
1797
+ const effectiveArgs = effective.args ?? [];
1798
+ if (effectiveArgs.length !== draft.args.length || effectiveArgs.some((arg, index) => arg !== draft.args[index])) scalars.add("args");
1799
+ const dictPatch = (before, after) => {
1800
+ const set = /* @__PURE__ */ new Map();
1801
+ const unset = [];
1802
+ for (const [key, value] of after) if (before?.get(key) !== value) set.set(key, value);
1803
+ for (const key of before?.keys() ?? []) if (!after.has(key)) unset.push(key);
1804
+ return {
1805
+ set,
1806
+ unset
1807
+ };
1808
+ };
1809
+ const env = dictPatch(effective.env, draft.env);
1810
+ const headers = dictPatch(effective.headers, draft.headers);
1811
+ if (env.set.size > 0 || env.unset.length > 0) scalars.add("env");
1812
+ if (headers.set.size > 0 || headers.unset.length > 0) scalars.add("headers");
1813
+ return {
1814
+ scalars,
1815
+ ...env.set.size > 0 || env.unset.length > 0 ? { env } : {},
1816
+ ...headers.set.size > 0 || headers.unset.length > 0 ? { headers } : {}
1817
+ };
1818
+ }
1819
+ /**
1820
+ * Project one ADD onto the official ops (the legal whole-entry `set` for a
1821
+ * NEW user-only server): transport + the transport's own fields + `enabled`.
1822
+ * Cross-transport fields are omitted entirely (the official schema defaults
1823
+ * them), and the deferred budget fields are never restated.
1824
+ */
1825
+ function mcpAddOps(name, draft) {
1826
+ const value = {
1827
+ transport: draft.transport,
1828
+ enabled: draft.enabled
1829
+ };
1830
+ if (draft.transport === "stdio") {
1831
+ value.command = draft.command;
1832
+ value.args = [...draft.args];
1833
+ value.cwd = draft.cwd;
1834
+ if (draft.env.size > 0) value.env = Object.fromEntries(draft.env);
1835
+ } else {
1836
+ value.url = draft.url;
1837
+ if (draft.headers.size > 0) value.headers = Object.fromEntries(draft.headers);
1838
+ }
1839
+ return [{
1840
+ op: "set",
1841
+ path: ["servers", name],
1842
+ value
1843
+ }];
1844
+ }
1845
+ /** The stdio fields a transport switch away must clear (official schema
1846
+ * defaults: '' / [] / {}). */
1847
+ const STDIO_SWITCH_FIELDS = [
1848
+ "command",
1849
+ "args",
1850
+ "env",
1851
+ "cwd"
1852
+ ];
1853
+ /** The streamable-http fields a transport switch away must clear. */
1854
+ const HTTP_SWITCH_FIELDS = ["url", "headers"];
1855
+ /**
1856
+ * Project one EDIT onto the official ops: ONLY the dirty field paths. An
1857
+ * existing entry is never restated as a whole object (a whole `set` would
1858
+ * wash away hidden/unknown and deferred fields); `env`/`headers` patch per
1859
+ * key, `args` replace as one list (the official dirty-list semantics), and a
1860
+ * transport switch explicitly resets the OLD transport's fields to the
1861
+ * official schema defaults — an `unset` there would resurrect an INHERITED
1862
+ * value, so the switch path never emits an unset for the abandoned fields.
1863
+ */
1864
+ function mcpEditOps(name, effective, draft, patch) {
1865
+ const ops = [];
1866
+ const root = ["servers", name];
1867
+ const switched = patch.scalars.has("transport");
1868
+ if (switched) {
1869
+ ops.push({
1870
+ op: "set",
1871
+ path: [...root, "transport"],
1872
+ value: draft.transport
1873
+ });
1874
+ const abandon = draft.transport === "stdio" ? HTTP_SWITCH_FIELDS : STDIO_SWITCH_FIELDS;
1875
+ for (const field of abandon) {
1876
+ const fallback = field === "args" ? [] : field === "env" || field === "headers" ? {} : "";
1877
+ ops.push({
1878
+ op: "set",
1879
+ path: [...root, field],
1880
+ value: fallback
1881
+ });
1882
+ }
1883
+ }
1884
+ if (draft.transport === "stdio") {
1885
+ if (patch.scalars.has("command")) ops.push({
1886
+ op: "set",
1887
+ path: [...root, "command"],
1888
+ value: draft.command
1889
+ });
1890
+ if (patch.scalars.has("cwd")) ops.push({
1891
+ op: "set",
1892
+ path: [...root, "cwd"],
1893
+ value: draft.cwd
1894
+ });
1895
+ if (patch.scalars.has("args")) ops.push({
1896
+ op: "set",
1897
+ path: [...root, "args"],
1898
+ value: [...draft.args]
1899
+ });
1900
+ const envPatch = patch.env;
1901
+ if (envPatch !== void 0) {
1902
+ for (const [key, value] of envPatch.set) ops.push({
1903
+ op: "set",
1904
+ path: [
1905
+ ...root,
1906
+ "env",
1907
+ key
1908
+ ],
1909
+ value
1910
+ });
1911
+ if (!switched) for (const key of envPatch.unset) ops.push({
1912
+ op: "unset",
1913
+ path: [
1914
+ ...root,
1915
+ "env",
1916
+ key
1917
+ ]
1918
+ });
1919
+ }
1920
+ } else {
1921
+ if (patch.scalars.has("url")) ops.push({
1922
+ op: "set",
1923
+ path: [...root, "url"],
1924
+ value: draft.url
1925
+ });
1926
+ const headersPatch = patch.headers;
1927
+ if (headersPatch !== void 0) {
1928
+ for (const [key, value] of headersPatch.set) ops.push({
1929
+ op: "set",
1930
+ path: [
1931
+ ...root,
1932
+ "headers",
1933
+ key
1934
+ ],
1935
+ value
1936
+ });
1937
+ if (!switched) for (const key of headersPatch.unset) ops.push({
1938
+ op: "unset",
1939
+ path: [
1940
+ ...root,
1941
+ "headers",
1942
+ key
1943
+ ]
1944
+ });
1945
+ }
1946
+ }
1947
+ if (patch.scalars.has("enabled")) ops.push({
1948
+ op: "set",
1949
+ path: [...root, "enabled"],
1950
+ value: draft.enabled
1951
+ });
1952
+ return ops;
1953
+ }
1954
+ /**
1955
+ * The official op of BOTH terminal actions — the SAME `unset
1956
+ * ['servers', name]`. The caller's precondition (user-only vs inherited
1957
+ * override) is what distinguishes Delete from Reset; the official mutate
1958
+ * resolves the difference (user-only: gone; inherited: base restored).
1959
+ */
1960
+ function mcpRemoveOps(name) {
1961
+ return [{
1962
+ op: "unset",
1963
+ path: ["servers", name]
1964
+ }];
1965
+ }
1966
+ /** The official op of the Enable/Disable toggle. */
1967
+ function mcpSetEnabledOps(name, enabled) {
1968
+ return [{
1969
+ op: "set",
1970
+ path: [
1971
+ "servers",
1972
+ name,
1973
+ "enabled"
1974
+ ],
1975
+ value: enabled
1976
+ }];
1977
+ }
1978
+ /** Whether one raw value is a plain record (not an array/null). */
1979
+ function isPlainRecord$1(value) {
1980
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1981
+ }
1982
+ /** Read one layer's `servers` map (own keys only — a name like `__proto__`
1983
+ * must never resolve through the prototype chain). */
1984
+ function serverMapOf(layer) {
1985
+ if (!isPlainRecord$1(layer)) return void 0;
1986
+ const servers = layer.servers;
1987
+ return isPlainRecord$1(servers) ? servers : void 0;
1988
+ }
1989
+ /** Structural equality of two detached JSON-shaped values: key order does not
1990
+ * matter for objects, array order does, and absent ≠ present. */
1991
+ function structurallyEqual(left, right) {
1992
+ if (left === right) return true;
1993
+ if (Array.isArray(left) || Array.isArray(right)) return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => structurallyEqual(item, right[index]));
1994
+ if (isPlainRecord$1(left) && isPlainRecord$1(right)) {
1995
+ const keys = Object.keys(left);
1996
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && structurallyEqual(left[key], right[key]));
1997
+ }
1998
+ return false;
1999
+ }
2000
+ /**
2001
+ * Classify one configured name from ONE descriptor's `base`/`value` layers.
2002
+ * The USER layer is deliberately NOT consulted for ownership (the official
2003
+ * ConfigEditor materializes inherited entries into the USER patch on any
2004
+ * write). An absent name (neither layer holds it) is `undefined`: the caller
2005
+ * must treat it as not-config-owned (plugin-owned/retained/unknown), never
2006
+ * guess.
2007
+ */
2008
+ function classifyMcpServerProvenance(base, value, name) {
2009
+ const baseServers = serverMapOf(base);
2010
+ const valueServers = serverMapOf(value);
2011
+ if (valueServers === void 0 || !Object.hasOwn(valueServers, name)) return void 0;
2012
+ if (baseServers === void 0 || !Object.hasOwn(baseServers, name)) return "user-added";
2013
+ return structurallyEqual(baseServers[name], valueServers[name]) ? "inherited" : "overridden";
2014
+ }
2015
+ /**
2016
+ * The base dict key sets of one raw base entry (own keys only), or `undefined`
2017
+ * when the descriptor carries no base entry / no dict fields.
2018
+ */
2019
+ function baseDictKeysOf(baseEntry) {
2020
+ if (!isPlainRecord$1(baseEntry)) return void 0;
2021
+ const of = (value) => {
2022
+ if (!isPlainRecord$1(value)) return void 0;
2023
+ return new Set(Object.keys(value));
2024
+ };
2025
+ const env = of(baseEntry.env);
2026
+ const headers = of(baseEntry.headers);
2027
+ if (env === void 0 && headers === void 0) return void 0;
2028
+ return {
2029
+ ...env === void 0 ? {} : { env },
2030
+ ...headers === void 0 ? {} : { headers }
2031
+ };
2032
+ }
2033
+ /** Project one effective entry value into the transport-fact DTO (strings,
2034
+ * string lists and string maps only). A field that IS present with the wrong
2035
+ * type refuses the WHOLE entry: a silently coerced draft would overwrite the
2036
+ * stored value with a guess. The effective `enabled` defaults to true per the
2037
+ * official schema. */
2038
+ function projectMcpServerEntry(value) {
2039
+ if (!isPlainRecord$1(value)) return void 0;
2040
+ const transport = value.transport;
2041
+ if (transport !== "stdio" && transport !== "streamable-http") return void 0;
2042
+ const stringOf = (input) => typeof input === "string" ? input : void 0;
2043
+ const listOf = (input) => {
2044
+ if (!Array.isArray(input) || !input.every((item) => typeof item === "string")) return void 0;
2045
+ return Object.freeze([...input]);
2046
+ };
2047
+ const mapOf = (input) => {
2048
+ if (!isPlainRecord$1(input)) return void 0;
2049
+ const out = /* @__PURE__ */ new Map();
2050
+ for (const [key, entry] of Object.entries(input)) {
2051
+ if (typeof entry !== "string") return void 0;
2052
+ out.set(key, entry);
2053
+ }
2054
+ return out;
2055
+ };
2056
+ if (value.enabled !== void 0 && typeof value.enabled !== "boolean") return void 0;
2057
+ const enabled = typeof value.enabled === "boolean" ? { enabled: value.enabled } : {};
2058
+ if (transport === "stdio") {
2059
+ for (const field of ["command", "cwd"]) if (value[field] !== void 0 && typeof value[field] !== "string") return void 0;
2060
+ const args = value.args === void 0 ? Object.freeze([]) : listOf(value.args);
2061
+ const env = value.env === void 0 ? /* @__PURE__ */ new Map() : mapOf(value.env);
2062
+ if (args === void 0 || env === void 0) return void 0;
2063
+ return Object.freeze({
2064
+ transport,
2065
+ command: stringOf(value.command) ?? "",
2066
+ args,
2067
+ cwd: stringOf(value.cwd) ?? "",
2068
+ env,
2069
+ ...enabled
2070
+ });
2071
+ }
2072
+ if (value.url !== void 0 && typeof value.url !== "string") return void 0;
2073
+ const headers = value.headers === void 0 ? /* @__PURE__ */ new Map() : mapOf(value.headers);
2074
+ if (headers === void 0) return void 0;
2075
+ return Object.freeze({
2076
+ transport,
2077
+ url: stringOf(value.url) ?? "",
2078
+ headers,
2079
+ ...enabled
2080
+ });
2081
+ }
2082
+ //#endregion
2083
+ //#region src/runtime/cua-access-port.ts
2084
+ /**
2085
+ * The Host/provider cannot serve the CUA access surface at all: the official
2086
+ * bundle is not loaded, the provider is unavailable, the generated Remote
2087
+ * namespace is not mounted, or the Client has no Host connection. This is a
2088
+ * definite unavailable, never a denied permission or a fabricated Ready.
2089
+ */
2090
+ var CuaAccessUnavailableError = class extends Error {
2091
+ constructor(message = "the official Computer Use access service is not available on this Host") {
2092
+ super(message);
2093
+ this.name = "CuaAccessUnavailableError";
2094
+ }
2095
+ };
1506
2096
  //#endregion
1507
2097
  //#region src/runtime/session-lifecycle-port.ts
1508
2098
  /**
@@ -2028,6 +2618,69 @@ function normalizeInputEvent(data) {
2028
2618
  };
2029
2619
  }
2030
2620
  //#endregion
2621
+ //#region src/domain/session/model-selection.ts
2622
+ function recordOf(value) {
2623
+ return typeof value === "object" && value !== null ? value : void 0;
2624
+ }
2625
+ /**
2626
+ * Normalize untrusted event data into a detached model-selection value.
2627
+ * Provider and model identifiers are intentionally not trimmed: whitespace is
2628
+ * part of an identifier if a provider elected to use it.
2629
+ */
2630
+ function normalizeModelSelection(value) {
2631
+ const record = recordOf(value);
2632
+ if (record === void 0 || typeof record.provider !== "string" || record.provider.length === 0 || typeof record.model !== "string" || record.model.length === 0) return void 0;
2633
+ if (record.reasoningEffort === void 0 || record.reasoningEffort === null) return {
2634
+ provider: record.provider,
2635
+ model: record.model
2636
+ };
2637
+ if (typeof record.reasoningEffort !== "string" || record.reasoningEffort.length === 0) return void 0;
2638
+ return {
2639
+ provider: record.provider,
2640
+ model: record.model,
2641
+ reasoningEffort: record.reasoningEffort
2642
+ };
2643
+ }
2644
+ /** Compare provider, model, and the presence/value of reasoning effort.
2645
+ * Defensive by contract: malformed runtime values (null, non-objects) are
2646
+ * never equal to anything, so untrusted event data cannot throw here. */
2647
+ function sameModelSelection(left, right) {
2648
+ if (left === void 0 || right === void 0) return false;
2649
+ if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) return false;
2650
+ return left.provider === right.provider && left.model === right.model && left.reasoningEffort === right.reasoningEffort;
2651
+ }
2652
+ function requestConfig(header) {
2653
+ const headerRecord = recordOf(header);
2654
+ return headerRecord === void 0 ? void 0 : recordOf(headerRecord.config);
2655
+ }
2656
+ /**
2657
+ * Read the raw selection used for pending-intent matching. This intentionally
2658
+ * keeps an adapter-generated effort: consumption compares the exact request
2659
+ * header fields, not the sanitized user-facing representation.
2660
+ */
2661
+ function rawSelectionFromRequestHeader(header) {
2662
+ const config = requestConfig(header);
2663
+ if (config === void 0 || typeof config.provider !== "string" || config.provider.length === 0 || typeof config.model !== "string" || config.model.length === 0) return void 0;
2664
+ if (config.reasoningEffort === void 0 || config.reasoningEffort === null) return {
2665
+ provider: config.provider,
2666
+ model: config.model
2667
+ };
2668
+ if (typeof config.reasoningEffort !== "string" || config.reasoningEffort.length === 0) return void 0;
2669
+ return {
2670
+ provider: config.provider,
2671
+ model: config.model,
2672
+ reasoningEffort: config.reasoningEffort
2673
+ };
2674
+ }
2675
+ /** Clone a detached value so a Host-owned selection cannot cross the boundary by alias. */
2676
+ function copyModelSelection(value) {
2677
+ return value === void 0 ? void 0 : {
2678
+ provider: value.provider,
2679
+ model: value.model,
2680
+ ...value.reasoningEffort === void 0 ? {} : { reasoningEffort: value.reasoningEffort }
2681
+ };
2682
+ }
2683
+ //#endregion
2031
2684
  //#region src/domain/command/policy.ts
2032
2685
  /**
2033
2686
  * The transport/UI-neutral command-line policy (plan §27 / TS8-F3): which slash
@@ -2064,7 +2717,6 @@ const SESSIONLESS_COMMANDS = /* @__PURE__ */ new Set([
2064
2717
  "focus",
2065
2718
  "footer",
2066
2719
  "settings",
2067
- "help",
2068
2720
  "attach",
2069
2721
  "image",
2070
2722
  "login",
@@ -2081,13 +2733,56 @@ const SESSIONLESS_COMMANDS = /* @__PURE__ */ new Set([
2081
2733
  "keybindings",
2082
2734
  "plugins",
2083
2735
  "web",
2736
+ "acp",
2084
2737
  "quit",
2085
2738
  "statusline",
2086
2739
  "status",
2087
2740
  "view-image",
2088
2741
  "deliverables",
2089
2742
  "reload-client",
2090
- "schedule"
2743
+ "schedule",
2744
+ "queue"
2745
+ ]);
2746
+ /**
2747
+ * Sessionless commands that are IMMEDIATE controls: they do not depend on the
2748
+ * Session identity a pending navigation will publish.
2749
+ *
2750
+ * - `/exit` / `/quit`: the user's quit must not wait for a navigation; a
2751
+ * stuck Workspace pre-selection would otherwise hang the slash exit.
2752
+ * - `/reload-client`: its safety decision reads the live facts synchronously
2753
+ * and must be made at request time. Deferring it past the transition would
2754
+ * re-judge the request after `pending` cleared and reload a Client the
2755
+ * in-flight-transition policy was refusing.
2756
+ *
2757
+ * The submission transition fence must never defer these behind an unsettled
2758
+ * navigation (it would change the control's decision point).
2759
+ */
2760
+ const IMMEDIATE_SESSIONLESS_COMMANDS = /* @__PURE__ */ new Set([
2761
+ "exit",
2762
+ "quit",
2763
+ "reload-client"
2764
+ ]);
2765
+ /**
2766
+ * Session-navigation entries whose SESSIONLESS local route is their OWN
2767
+ * admission: `/new`'s single-flight marker, the session-browser picker
2768
+ * (`/sessions`, `/resume`, `/search`) and the `/fork`/`/rewind` entries.
2769
+ *
2770
+ * The submission transition fence defers a sessionless-capable command until a
2771
+ * pending Session transition settles, so the route decision sees the settled
2772
+ * surface. These names are the navigation authority themselves and must run
2773
+ * IMMEDIATELY: their own guard answers the pending transition (a deferred
2774
+ * `/new` would no longer be the documented "already starting" refusal — it
2775
+ * would create a SECOND Session after the first settled), and their
2776
+ * sessionless effects (a picker, an explicit refusal) are visible without a
2777
+ * command card.
2778
+ */
2779
+ const SESSION_NAVIGATION_COMMANDS = /* @__PURE__ */ new Set([
2780
+ "new",
2781
+ "sessions",
2782
+ "resume",
2783
+ "search",
2784
+ "fork",
2785
+ "rewind"
2091
2786
  ]);
2092
2787
  /**
2093
2788
  * The LOCAL-execute command set (PR5 v2 §1C-6 narrows its semantic role):
@@ -2120,7 +2815,6 @@ const LOCAL_COMMANDS = /* @__PURE__ */ new Set([
2120
2815
  "focus",
2121
2816
  "footer",
2122
2817
  "fork",
2123
- "help",
2124
2818
  "attach",
2125
2819
  "image",
2126
2820
  "keybindings",
@@ -2147,11 +2841,13 @@ const LOCAL_COMMANDS = /* @__PURE__ */ new Set([
2147
2841
  "transcript",
2148
2842
  "yolo",
2149
2843
  "web",
2844
+ "acp",
2150
2845
  "view-image",
2151
2846
  "deliverables",
2152
2847
  "statusline",
2153
2848
  "reload-client",
2154
- "schedule"
2849
+ "schedule",
2850
+ "queue"
2155
2851
  ]);
2156
2852
  /**
2157
2853
  * The STATIC host-owned command catalog (P1-04): the ownership sets
@@ -2276,6 +2972,24 @@ function isPlainExitPrompt(text) {
2276
2972
  return text.trim() === "exit";
2277
2973
  }
2278
2974
  /**
2975
+ * Classify one exit intent against the live authority facts. This is the ONE
2976
+ * exit classifier: Direct and daemon branches differ only in the final
2977
+ * destination, and an unknown activity is NEVER treated as idle (a daemon
2978
+ * Client must not detach as if nothing were running, and a Direct process
2979
+ * must not claim the in-process Host has nothing to retire).
2980
+ * @param input - the captured backend/presence/activity/entry facts.
2981
+ * @returns the single decision the exit-intent coordinator executes.
2982
+ */
2983
+ function classifyExitIntent(input) {
2984
+ if (input.sessionPresence === "none") {
2985
+ if (input.activity !== "idle") return "show-unknown-choice";
2986
+ return input.currentBackend === "direct" ? "direct-exit" : "client-detach";
2987
+ }
2988
+ if (input.activity === "unknown") return "show-unknown-choice";
2989
+ if (input.activity === "working") return input.currentBackend === "direct" ? "show-direct-choice" : "show-daemon-choice";
2990
+ return input.currentBackend === "direct" ? "direct-exit" : "client-detach";
2991
+ }
2992
+ /**
2279
2993
  * The TUI-local commands whose OWN handler performs no persistent Host write
2280
2994
  * (they read/browse/stage locally, open a read-only panel, or are the reload
2281
2995
  * command itself). Their execution never holds the accepted-command reload
@@ -2293,7 +3007,6 @@ const READ_ONLY_LOCAL_COMMANDS = /* @__PURE__ */ new Set([
2293
3007
  "reload",
2294
3008
  "exit",
2295
3009
  "quit",
2296
- "help",
2297
3010
  "keybindings",
2298
3011
  "copy",
2299
3012
  "attach",
@@ -3157,6 +3870,42 @@ var AutocompleteRegistry = class {
3157
3870
  };
3158
3871
  //#endregion
3159
3872
  //#region src/extension/internal/settings-registry.ts
3873
+ /** Whether one value is a JSON scalar a persisted choice may write. */
3874
+ function isPersistedScalar(value) {
3875
+ return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
3876
+ }
3877
+ /** Validate and freeze one author-declared persisted descriptor. Every error
3878
+ * is a registration-time failure; the registry never repairs a declaration. */
3879
+ function persistedDescriptorOf(contribution) {
3880
+ const descriptor = contribution.persisted;
3881
+ if (descriptor === null || typeof descriptor !== "object") throw new Error("persisted settings row requires a persisted descriptor");
3882
+ if (contribution.values !== void 0 || contribution.onChange !== void 0) throw new Error("a persisted settings row cannot declare runtime values or onChange");
3883
+ const path = descriptor.path;
3884
+ if (!Array.isArray(path) || path.length === 0) throw new Error("persisted settings path must be a non-empty array");
3885
+ for (const segment of path) if (typeof segment !== "string" || segment === "") throw new Error("persisted settings path segments must be non-empty strings");
3886
+ const choices = descriptor.choices;
3887
+ if (!Array.isArray(choices) || choices.length === 0) throw new Error("persisted settings choices must be a non-empty array");
3888
+ const ids = /* @__PURE__ */ new Set();
3889
+ const frozenChoices = [];
3890
+ for (const choice of choices) {
3891
+ if (choice === null || typeof choice !== "object") throw new Error("persisted settings choices must be objects");
3892
+ if (typeof choice.id !== "string" || choice.id === "") throw new Error("persisted settings choice ids must be non-empty strings");
3893
+ if (ids.has(choice.id)) throw new Error(`duplicate persisted settings choice id "${choice.id}"`);
3894
+ ids.add(choice.id);
3895
+ if (choice.label !== void 0 && typeof choice.label !== "string") throw new Error(`persisted settings choice "${choice.id}" label must be a string`);
3896
+ if (choice.op === "set") {
3897
+ if (!isPersistedScalar(choice.value)) throw new Error(`persisted settings choice "${choice.id}" value must be a JSON scalar`);
3898
+ frozenChoices.push(Object.freeze({ ...choice }));
3899
+ } else if (choice.op === "unset") {
3900
+ if (Object.hasOwn(choice, "value")) throw new Error(`persisted settings choice "${choice.id}" is unset and must not carry a value`);
3901
+ frozenChoices.push(Object.freeze({ ...choice }));
3902
+ } else throw new Error("persisted settings choice has an unsupported op");
3903
+ }
3904
+ return Object.freeze({
3905
+ path: Object.freeze([...path]),
3906
+ choices: Object.freeze(frozenChoices)
3907
+ });
3908
+ }
3160
3909
  /**
3161
3910
  * The settings registry. One instance backs the runner; the extension
3162
3911
  * service exposes registration; the runner asks {@link rows} when
@@ -3180,18 +3929,21 @@ var SettingsRegistry = class {
3180
3929
  register(contribution, owner) {
3181
3930
  if (this.records.has(contribution.id)) throw new Error(`duplicate settings row id "${contribution.id}"`);
3182
3931
  if (contribution.label === "") throw new Error("settings row label must not be empty");
3932
+ const persisted = contribution.persisted === void 0 ? void 0 : persistedDescriptorOf(contribution);
3183
3933
  this.nextRegistrationToken += 1;
3184
3934
  const record = {
3185
3935
  id: contribution.id,
3186
3936
  label: contribution.label,
3187
3937
  description: contribution.description,
3188
- values: contribution.values ?? [],
3938
+ values: persisted === void 0 ? contribution.values ?? [] : persisted.choices.map((choice) => choice.id),
3189
3939
  order: contribution.order ?? 0,
3190
3940
  owner,
3941
+ mode: persisted === void 0 ? "runtime" : "persisted",
3942
+ persisted,
3191
3943
  registrationToken: this.nextRegistrationToken,
3192
3944
  currentValue: contribution.currentValue,
3193
3945
  applyEpoch: 0,
3194
- onChange: contribution.onChange,
3946
+ onChange: persisted === void 0 ? contribution.onChange : void 0,
3195
3947
  disposed: false
3196
3948
  };
3197
3949
  this.records.set(contribution.id, record);
@@ -3271,6 +4023,7 @@ var SettingsRegistry = class {
3271
4023
  async applyInternal(id, value) {
3272
4024
  const record = this.records.get(id);
3273
4025
  if (record === void 0 || record.disposed) return "gone";
4026
+ if (record.mode === "persisted") return "rejected";
3274
4027
  const epoch = record.applyEpoch + 1;
3275
4028
  record.applyEpoch = epoch;
3276
4029
  const onChange = record.onChange;
@@ -3298,7 +4051,9 @@ var SettingsRegistry = class {
3298
4051
  for (const record of this.records.values()) if (!record.disposed) return true;
3299
4052
  return false;
3300
4053
  }
3301
- /** An immutable snapshot (Plugin Manager diagnostics). */
4054
+ /** An immutable snapshot (Plugin Manager diagnostics). Runtime-only rows
4055
+ * keep their original seven facts; a persisted row adds its frozen mode
4056
+ * and author descriptor. */
3302
4057
  snapshot() {
3303
4058
  return {
3304
4059
  rows: this.rows().map((record) => ({
@@ -3308,7 +4063,11 @@ var SettingsRegistry = class {
3308
4063
  currentValue: record.currentValue,
3309
4064
  values: record.values,
3310
4065
  order: record.order,
3311
- owner: record.owner
4066
+ owner: record.owner,
4067
+ ...record.mode === "persisted" ? {
4068
+ mode: "persisted",
4069
+ persisted: record.persisted
4070
+ } : {}
3312
4071
  })),
3313
4072
  revision: this.revision
3314
4073
  };
@@ -3505,6 +4264,13 @@ const RESERVED_HOST_KEYS = [
3505
4264
  shift: false,
3506
4265
  super: false
3507
4266
  },
4267
+ {
4268
+ key: "i",
4269
+ ctrl: false,
4270
+ alt: true,
4271
+ shift: false,
4272
+ super: false
4273
+ },
3508
4274
  {
3509
4275
  key: "k",
3510
4276
  ctrl: false,
@@ -5906,6 +6672,304 @@ function questionAnswerError(error) {
5906
6672
  return new QuestionAnswerError(typeof error === "object" && error !== null && typeof error.code === "string" ? error.code : "question/answer-failed", typeof error === "object" && error !== null && typeof error.message === "string" ? error.message : String(error), { cause: error });
5907
6673
  }
5908
6674
  //#endregion
6675
+ //#region src/runtime/subagent-settings.ts
6676
+ function plainRecord$1(value) {
6677
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
6678
+ const prototype = Object.getPrototypeOf(value);
6679
+ return prototype === Object.prototype || prototype === null ? value : void 0;
6680
+ }
6681
+ function validLimits(value) {
6682
+ return Object.hasOwn(value, "maxDepth") && typeof value.maxDepth === "number" && Number.isSafeInteger(value.maxDepth) && value.maxDepth >= 0 && Object.hasOwn(value, "maxActiveSubagents") && typeof value.maxActiveSubagents === "number" && Number.isSafeInteger(value.maxActiveSubagents) && value.maxActiveSubagents >= 1;
6683
+ }
6684
+ function routesOf(value) {
6685
+ if (!Array.isArray(value)) return void 0;
6686
+ const routes = [];
6687
+ for (const item of value) {
6688
+ const route = plainRecord$1(item);
6689
+ if (route === void 0 || typeof route.provider !== "string" || route.provider.length === 0 || typeof route.model !== "string" || route.model.length === 0) return void 0;
6690
+ routes.push(Object.freeze({
6691
+ provider: route.provider,
6692
+ model: route.model
6693
+ }));
6694
+ }
6695
+ return Object.freeze(routes);
6696
+ }
6697
+ function modelSelectionOf(value) {
6698
+ if (!Object.hasOwn(value, "enabled") || typeof value.enabled !== "boolean") return void 0;
6699
+ const allowedModels = routesOf(value.allowedModels);
6700
+ if (allowedModels === void 0) return void 0;
6701
+ return Object.freeze({
6702
+ enabled: value.enabled,
6703
+ allowedModels
6704
+ });
6705
+ }
6706
+ function sameRoutes(left, right) {
6707
+ return left.length === right.length && left.every((route, index) => route.provider === right[index]?.provider && route.model === right[index]?.model);
6708
+ }
6709
+ function projectSubagentLimits(effectiveValue, inheritedValue) {
6710
+ const effectiveRecord = plainRecord$1(effectiveValue);
6711
+ const inheritedRecord = plainRecord$1(inheritedValue);
6712
+ if (effectiveRecord === void 0 || inheritedRecord === void 0 || !validLimits(effectiveRecord) || !validLimits(inheritedRecord)) return void 0;
6713
+ const effective = Object.freeze({
6714
+ maxDepth: effectiveRecord.maxDepth,
6715
+ maxActiveSubagents: effectiveRecord.maxActiveSubagents
6716
+ });
6717
+ const inherited = Object.freeze({
6718
+ maxDepth: inheritedRecord.maxDepth,
6719
+ maxActiveSubagents: inheritedRecord.maxActiveSubagents
6720
+ });
6721
+ return Object.freeze({
6722
+ effective,
6723
+ inherited,
6724
+ overridden: Object.freeze({
6725
+ maxDepth: effective.maxDepth !== inherited.maxDepth,
6726
+ maxActiveSubagents: effective.maxActiveSubagents !== inherited.maxActiveSubagents
6727
+ })
6728
+ });
6729
+ }
6730
+ function projectSubagentModelSelection(effectiveValue, inheritedValue) {
6731
+ const effectiveRecord = plainRecord$1(effectiveValue);
6732
+ const inheritedRecord = plainRecord$1(inheritedValue);
6733
+ if (effectiveRecord === void 0 || inheritedRecord === void 0) return void 0;
6734
+ const effective = modelSelectionOf(effectiveRecord);
6735
+ const inherited = modelSelectionOf(inheritedRecord);
6736
+ if (effective === void 0 || inherited === void 0) return void 0;
6737
+ return Object.freeze({
6738
+ effective,
6739
+ inherited,
6740
+ overridden: Object.freeze({
6741
+ enabled: effective.enabled !== inherited.enabled,
6742
+ allowedModels: !sameRoutes(effective.allowedModels, inherited.allowedModels)
6743
+ })
6744
+ });
6745
+ }
6746
+ //#endregion
6747
+ //#region src/runtime/host-settings-sections.ts
6748
+ function plainRecord(value) {
6749
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
6750
+ const prototype = Object.getPrototypeOf(value);
6751
+ return prototype === Object.prototype || prototype === null ? value : void 0;
6752
+ }
6753
+ function positiveSafeInteger(value) {
6754
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
6755
+ }
6756
+ function positiveFinite(value) {
6757
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
6758
+ }
6759
+ function projectAgentLoopSettings(effectiveValue, inheritedValue) {
6760
+ const effectiveRecord = plainRecord(effectiveValue);
6761
+ const inheritedRecord = plainRecord(inheritedValue);
6762
+ if (effectiveRecord === void 0 || inheritedRecord === void 0) return void 0;
6763
+ const effectiveBudget = effectiveRecord.maxParallelToolCalls;
6764
+ const inheritedBudget = inheritedRecord.maxParallelToolCalls;
6765
+ if (!positiveSafeInteger(effectiveBudget) || !positiveSafeInteger(inheritedBudget)) return void 0;
6766
+ return Object.freeze({
6767
+ effective: Object.freeze({ maxParallelToolCalls: effectiveBudget }),
6768
+ inherited: Object.freeze({ maxParallelToolCalls: inheritedBudget }),
6769
+ overridden: Object.freeze({ maxParallelToolCalls: effectiveBudget !== inheritedBudget })
6770
+ });
6771
+ }
6772
+ function projectShellExecutionSettings(executor) {
6773
+ return (effectiveValue, inheritedValue) => {
6774
+ const effectiveRecord = plainRecord(effectiveValue);
6775
+ const inheritedRecord = plainRecord(inheritedValue);
6776
+ if (effectiveRecord === void 0 || inheritedRecord === void 0) return void 0;
6777
+ const timeoutMs = effectiveRecord.timeoutMs;
6778
+ const maxOutputBytes = effectiveRecord.maxOutputBytes;
6779
+ const inheritedTimeoutMs = inheritedRecord.timeoutMs;
6780
+ const inheritedMaxOutputBytes = inheritedRecord.maxOutputBytes;
6781
+ if (!positiveFinite(timeoutMs) || !positiveFinite(maxOutputBytes) || !positiveFinite(inheritedTimeoutMs) || !positiveFinite(inheritedMaxOutputBytes)) return void 0;
6782
+ return Object.freeze({
6783
+ effective: Object.freeze({
6784
+ executor,
6785
+ timeoutMs,
6786
+ maxOutputBytes
6787
+ }),
6788
+ inherited: Object.freeze({
6789
+ executor,
6790
+ timeoutMs: inheritedTimeoutMs,
6791
+ maxOutputBytes: inheritedMaxOutputBytes
6792
+ }),
6793
+ overridden: Object.freeze({
6794
+ executor: false,
6795
+ timeoutMs: timeoutMs !== inheritedTimeoutMs,
6796
+ maxOutputBytes: maxOutputBytes !== inheritedMaxOutputBytes
6797
+ })
6798
+ });
6799
+ };
6800
+ }
6801
+ function projectSessionLogUpload(effectiveValue, inheritedValue) {
6802
+ const effectiveRecord = plainRecord(effectiveValue);
6803
+ const inheritedRecord = plainRecord(inheritedValue);
6804
+ if (effectiveRecord === void 0 || inheritedRecord === void 0) return void 0;
6805
+ if (typeof effectiveRecord.enabled !== "boolean" || typeof inheritedRecord.enabled !== "boolean") return void 0;
6806
+ return Object.freeze({
6807
+ effective: Object.freeze({ enabled: effectiveRecord.enabled }),
6808
+ inherited: Object.freeze({ enabled: inheritedRecord.enabled }),
6809
+ overridden: Object.freeze({ enabled: effectiveRecord.enabled !== inheritedRecord.enabled })
6810
+ });
6811
+ }
6812
+ //#endregion
6813
+ //#region src/domain/extension-config/data.ts
6814
+ /** Distinguishes a non-JSON data projection from an absent `data` field. */
6815
+ const INVALID_EXTENSION_CONFIG_DATA = Symbol("invalid-extension-config-data");
6816
+ /** Detach one `data` projection into an owned JSON-only tree. */
6817
+ function detach(value, seen) {
6818
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
6819
+ if (typeof value === "number") return Number.isFinite(value) ? value : INVALID_EXTENSION_CONFIG_DATA;
6820
+ if (typeof value !== "object") return INVALID_EXTENSION_CONFIG_DATA;
6821
+ if (seen.has(value)) return INVALID_EXTENSION_CONFIG_DATA;
6822
+ seen.add(value);
6823
+ if (Array.isArray(value)) {
6824
+ const entries = [];
6825
+ for (const entry of value) {
6826
+ const child = detach(entry, seen);
6827
+ if (child === INVALID_EXTENSION_CONFIG_DATA) return INVALID_EXTENSION_CONFIG_DATA;
6828
+ entries.push(child);
6829
+ }
6830
+ seen.delete(value);
6831
+ return entries;
6832
+ }
6833
+ const proto = Object.getPrototypeOf(value);
6834
+ if (proto !== Object.prototype && proto !== null) return INVALID_EXTENSION_CONFIG_DATA;
6835
+ const detached = {};
6836
+ for (const [key, entry] of Object.entries(value)) {
6837
+ const child = detach(entry, seen);
6838
+ if (child === INVALID_EXTENSION_CONFIG_DATA) return INVALID_EXTENSION_CONFIG_DATA;
6839
+ Object.defineProperty(detached, key, {
6840
+ value: child,
6841
+ enumerable: true,
6842
+ writable: true,
6843
+ configurable: true
6844
+ });
6845
+ }
6846
+ seen.delete(value);
6847
+ return detached;
6848
+ }
6849
+ /** Detach one caller-supplied Config value into an owned JSON-only tree. */
6850
+ function detachExtensionConfigValue(value) {
6851
+ if (value === void 0) return {
6852
+ kind: "ok",
6853
+ value: void 0
6854
+ };
6855
+ const detached = detach(value, /* @__PURE__ */ new Set());
6856
+ return detached === INVALID_EXTENSION_CONFIG_DATA ? {
6857
+ kind: "invalid",
6858
+ reason: "the extension configuration value is not JSON"
6859
+ } : {
6860
+ kind: "ok",
6861
+ value: detached
6862
+ };
6863
+ }
6864
+ /**
6865
+ * Project one descriptor layer's `data` field into a detached JSON value.
6866
+ * An absent layer or absent `data` is a successful `undefined`; an unreadable
6867
+ * layer shape or non-JSON value is `invalid` (the caller reports `unreadable`).
6868
+ */
6869
+ function projectExtensionConfigData(layer) {
6870
+ if (layer === void 0) return {
6871
+ kind: "ok",
6872
+ value: void 0
6873
+ };
6874
+ if (typeof layer !== "object" || layer === null || Array.isArray(layer)) return {
6875
+ kind: "invalid",
6876
+ reason: "the official Host settings layer is not a plain form projection"
6877
+ };
6878
+ return detachExtensionConfigValue(Reflect.get(layer, "data"));
6879
+ }
6880
+ /**
6881
+ * Materialize ONE owned, JSON-validated operation snapshot before any
6882
+ * asynchronous/queued work: every path is copied and every `set` value is
6883
+ * detached into a JSON-only tree. `set(undefined)` is a caller error — deletion
6884
+ * is the explicit `unset` intent, never an absent set payload.
6885
+ *
6886
+ * This is a transport-boundary check, not a second schema: field names,
6887
+ * paths and volatility remain the official Settings validator's authority.
6888
+ * It exists so a delayed Remote dispatch cannot observe a caller-mutated
6889
+ * object (or a later non-JSON value) instead of the admitted input.
6890
+ */
6891
+ function snapshotExtensionConfigOps(ops) {
6892
+ const snapshot = [];
6893
+ for (const op of ops) {
6894
+ const path = [...op.path];
6895
+ if (op.op === "unset") {
6896
+ snapshot.push({
6897
+ op: "unset",
6898
+ path
6899
+ });
6900
+ continue;
6901
+ }
6902
+ if (op.value === void 0) return {
6903
+ kind: "invalid",
6904
+ reason: "the extension configuration set value must not be undefined; use unset"
6905
+ };
6906
+ const detached = detachExtensionConfigValue(op.value);
6907
+ if (detached.kind === "invalid") return {
6908
+ kind: "invalid",
6909
+ reason: detached.reason
6910
+ };
6911
+ snapshot.push({
6912
+ op: "set",
6913
+ path,
6914
+ value: detached.value
6915
+ });
6916
+ }
6917
+ return {
6918
+ kind: "ok",
6919
+ ops: snapshot
6920
+ };
6921
+ }
6922
+ /** Whether one descriptor layer owns the `data` field (own-property presence,
6923
+ * never value inequality). */
6924
+ function extensionConfigUserDataPresent(user) {
6925
+ return typeof user === "object" && user !== null && !Array.isArray(user) && Object.hasOwn(user, "data");
6926
+ }
6927
+ //#endregion
6928
+ //#region src/runtime/plugin-manager-ownership.ts
6929
+ /**
6930
+ * Process-local ownership registry for Direct Client-local `./tui` Loader
6931
+ * entries.
6932
+ *
6933
+ * The Host Plugin Manager projection may only hide entries that the actual
6934
+ * Client mount owner created; an arbitrary profile/Host row whose id merely
6935
+ * looks like `pi-tui-client-<32 hex>` must stay visible and manageable. The
6936
+ * owner marks an entry after a successful `loader.create`, unmarks it after
6937
+ * the official Loader removal, and the Direct Plugin Manager adapter reads
6938
+ * exactly that live set for its current Loader instance.
6939
+ *
6940
+ * The registry is intentionally process-local and WeakMap-scoped: it is not a
6941
+ * second Host inventory, not persisted, and never crosses the wire.
6942
+ *
6943
+ * @module @xmoon76/dsh-pi-tui/runtime/plugin-manager-ownership
6944
+ */
6945
+ const OWNED = /* @__PURE__ */ new WeakMap();
6946
+ /** Normalize a Cordis service proxy to its ONE underlying loader object. */
6947
+ function loaderIdentity(loader) {
6948
+ return loader[symbols.original] ?? loader;
6949
+ }
6950
+ /** Mark one entry as created by the CURRENT Client mount owner. */
6951
+ function markOwnedClientExtensionEntry(loader, entryId) {
6952
+ const key = loaderIdentity(loader);
6953
+ let entries = OWNED.get(key);
6954
+ if (entries === void 0) {
6955
+ entries = /* @__PURE__ */ new Set();
6956
+ OWNED.set(key, entries);
6957
+ }
6958
+ entries.add(entryId);
6959
+ }
6960
+ /** Remove one entry from the current Client mount owner's set. */
6961
+ function unmarkOwnedClientExtensionEntry(loader, entryId) {
6962
+ OWNED.get(loaderIdentity(loader))?.delete(entryId);
6963
+ }
6964
+ /**
6965
+ * The exact ids owned by a Client mount owner on this Loader, or `undefined`
6966
+ * when the Process has no loader service.
6967
+ */
6968
+ function ownedClientExtensionEntryIds(loader) {
6969
+ if (loader === void 0) return void 0;
6970
+ return OWNED.get(loaderIdentity(loader));
6971
+ }
6972
+ //#endregion
5909
6973
  //#region src/runtime/plugin-manager-mapping.ts
5910
6974
  /** Generate one install request id (the branded shape is a plain string). */
5911
6975
  function pluginInstallRequestId(value) {
@@ -5964,7 +7028,7 @@ function detachBundle(bundle) {
5964
7028
  optional: bundle.optional,
5965
7029
  ...bundle.source === void 0 ? {} : { source: bundle.source },
5966
7030
  removable: bundle.removable,
5967
- updatable: bundle.updatable,
7031
+ ...bundle.update === void 0 ? {} : { update: bundle.update },
5968
7032
  ...bundle.readOnlyReason === void 0 ? {} : { readOnlyReason: bundle.readOnlyReason },
5969
7033
  ...bundle.error === void 0 ? {} : { error: detachError(bundle.error) },
5970
7034
  rows: Object.freeze(rows),
@@ -5999,7 +7063,7 @@ function detachExemptions(value) {
5999
7063
  function detachPluginManagerSnapshot(input) {
6000
7064
  return Object.freeze({
6001
7065
  bundles: Object.freeze(input.bundles.map(detachBundle)),
6002
- plugins: Object.freeze(input.plugins.map(detachPlugin)),
7066
+ plugins: Object.freeze((input.ownedClientEntryIds === void 0 ? input.plugins : input.plugins.filter((plugin) => !input.ownedClientEntryIds.has(String(plugin.entryId)))).map(detachPlugin)),
6003
7067
  registries: detachRegistries(input.registries),
6004
7068
  exemptions: detachExemptions(input.exemptions),
6005
7069
  exemptionWarnings: Object.freeze([...input.exemptions.warnings])
@@ -6128,6 +7192,217 @@ function detachPluginUpdateResult(result) {
6128
7192
  });
6129
7193
  }
6130
7194
  //#endregion
7195
+ //#region src/runtime/host-directory-browse-port.ts
7196
+ /** The official code that proves the Host refused the requested path. */
7197
+ const HOST_DIRECTORY_UNREADABLE_CODES = /* @__PURE__ */ new Set(["directory-unreadable", "directory-picker/unreadable"]);
7198
+ /**
7199
+ * The official codes that prove the browse SURFACE could not answer at all:
7200
+ * the composed picker is not the browse backend, the addressed Host endpoint
7201
+ * or service is not available, or the peer was retired. These are availability
7202
+ * facts, never a statement about the requested directory.
7203
+ *
7204
+ * `gateway/internal` is deliberately ABSENT: the official controller also uses
7205
+ * it for ANY unexpected handler failure (`browseFailure` folds a non-seam error
7206
+ * into `gateway/internal`), and the Client carrier folds a dropped transport
7207
+ * into the same code, so it is not an authoritative availability
7208
+ * discriminator. Such a failure stays observable instead of becoming a
7209
+ * fabricated `unavailable`.
7210
+ */
7211
+ const HOST_DIRECTORY_UNAVAILABLE_CODES = /* @__PURE__ */ new Set([
7212
+ "directory-picker/unavailable",
7213
+ "gateway/cancelled",
7214
+ "gateway/peer-disposed",
7215
+ "gateway/service-unavailable",
7216
+ "gateway/context-unavailable",
7217
+ "gateway/invocation-unavailable",
7218
+ "gateway/method-unavailable",
7219
+ "gateway/definition-unavailable",
7220
+ "gateway/lookup-unavailable"
7221
+ ]);
7222
+ /** Read a structural official failure code (never match on message text). */
7223
+ function hostDirectoryBrowseCode(error) {
7224
+ if (typeof error !== "object" || error === null) return void 0;
7225
+ const code = error.code;
7226
+ return typeof code === "string" && code !== "" ? code : void 0;
7227
+ }
7228
+ /** The display/diagnostic text of one official failure. */
7229
+ function hostDirectoryBrowseReason(error) {
7230
+ if (error instanceof Error) return error.message;
7231
+ if (typeof error === "object" && error !== null) {
7232
+ const message = error.message;
7233
+ if (typeof message === "string") return message;
7234
+ }
7235
+ return String(error);
7236
+ }
7237
+ /**
7238
+ * Classify one caught official browse failure into an outcome.
7239
+ *
7240
+ * Only the Host's own refusal and the browse surface's availability vocabulary
7241
+ * are mapped. Anything else (a programming or protocol fault) stays
7242
+ * observable: the caller rethrows it instead of receiving a fabricated
7243
+ * `unavailable` or an empty listing.
7244
+ */
7245
+ function hostDirectoryBrowseFailureOutcome(error) {
7246
+ const code = hostDirectoryBrowseCode(error);
7247
+ if (code === void 0) return void 0;
7248
+ if (HOST_DIRECTORY_UNREADABLE_CODES.has(code)) return {
7249
+ kind: "failed",
7250
+ reason: hostDirectoryBrowseReason(error),
7251
+ code
7252
+ };
7253
+ if (HOST_DIRECTORY_UNAVAILABLE_CODES.has(code)) return {
7254
+ kind: "unavailable",
7255
+ reason: hostDirectoryBrowseReason(error),
7256
+ code
7257
+ };
7258
+ }
7259
+ //#endregion
7260
+ //#region src/runtime/mcp-server-port.ts
7261
+ function isRecord$1(value) {
7262
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7263
+ }
7264
+ function isFiniteNumber(value) {
7265
+ return typeof value === "number" && Number.isFinite(value);
7266
+ }
7267
+ function isStringArray(value) {
7268
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
7269
+ }
7270
+ /** One detached cleanup result. */
7271
+ function detachCloseResult(value) {
7272
+ if (!isRecord$1(value) || typeof value.closeConfirmed !== "boolean") return void 0;
7273
+ if (value.cleanupError !== void 0 && typeof value.cleanupError !== "string") return void 0;
7274
+ return {
7275
+ closeConfirmed: value.closeConfirmed,
7276
+ ...value.cleanupError === void 0 ? {} : { cleanupError: value.cleanupError }
7277
+ };
7278
+ }
7279
+ /**
7280
+ * Detach one official status value. An unrecognized status is `undefined` (the
7281
+ * whole frame is refused): a management surface must never paint a state it
7282
+ * cannot classify, and an unknown future state is NOT silently coerced to
7283
+ * `disabled`/`connected`.
7284
+ */
7285
+ function detachMcpServerStatus(value) {
7286
+ if (!isRecord$1(value)) return void 0;
7287
+ switch (value.state) {
7288
+ case "disabled": return Object.freeze({ state: "disabled" });
7289
+ case "closed": {
7290
+ const result = detachCloseResult(value.result);
7291
+ return result === void 0 ? void 0 : Object.freeze({
7292
+ state: "closed",
7293
+ result: Object.freeze(result)
7294
+ });
7295
+ }
7296
+ case "waiting-credentials": return typeof value.lastError === "string" ? Object.freeze({
7297
+ state: "waiting-credentials",
7298
+ lastError: value.lastError
7299
+ }) : void 0;
7300
+ case "connecting": return isFiniteNumber(value.attempt) && value.attempt >= 0 ? Object.freeze({
7301
+ state: "connecting",
7302
+ attempt: value.attempt
7303
+ }) : void 0;
7304
+ case "connected": return isFiniteNumber(value.toolCount) && value.toolCount >= 0 && isFiniteNumber(value.connectedAt) ? Object.freeze({
7305
+ state: "connected",
7306
+ toolCount: value.toolCount,
7307
+ connectedAt: value.connectedAt
7308
+ }) : void 0;
7309
+ case "reconnecting": return isFiniteNumber(value.attempt) && isFiniteNumber(value.maxAttempts) && isFiniteNumber(value.nextRetryAtMs) && typeof value.lastError === "string" ? Object.freeze({
7310
+ state: "reconnecting",
7311
+ attempt: value.attempt,
7312
+ maxAttempts: value.maxAttempts,
7313
+ nextRetryAtMs: value.nextRetryAtMs,
7314
+ lastError: value.lastError
7315
+ }) : void 0;
7316
+ case "failed":
7317
+ if (value.reason === "load") return typeof value.lastError === "string" ? Object.freeze({
7318
+ state: "failed",
7319
+ reason: "load",
7320
+ lastError: value.lastError
7321
+ }) : void 0;
7322
+ if (value.reason === "cleanup") {
7323
+ const result = detachCloseResult(value.result);
7324
+ return result === void 0 ? void 0 : Object.freeze({
7325
+ state: "failed",
7326
+ reason: "cleanup",
7327
+ result: Object.freeze(result)
7328
+ });
7329
+ }
7330
+ if (value.reason === "gave-up" || value.reason === "reconnect-disabled" || value.reason === "unclosed-generation") {
7331
+ if (value.lastError !== void 0 && typeof value.lastError !== "string") return void 0;
7332
+ return Object.freeze({
7333
+ state: "failed",
7334
+ reason: value.reason,
7335
+ ...value.lastError === void 0 ? {} : { lastError: value.lastError }
7336
+ });
7337
+ }
7338
+ return;
7339
+ default: return;
7340
+ }
7341
+ }
7342
+ /** Detach one official `McpManagedServerView`; `undefined` = invalid wire value. */
7343
+ function detachMcpServerView(value) {
7344
+ if (!isRecord$1(value)) return void 0;
7345
+ const { name, configured } = value;
7346
+ if (typeof name !== "string" || typeof configured !== "boolean") return void 0;
7347
+ const status = detachMcpServerStatus(value.status);
7348
+ if (status === void 0) return void 0;
7349
+ return Object.freeze({
7350
+ name,
7351
+ configured,
7352
+ status
7353
+ });
7354
+ }
7355
+ /**
7356
+ * Detach one official roster (the `watch`/`list` frame). A single invalid
7357
+ * member refuses the WHOLE frame: a partial roster would silently hide a
7358
+ * server from the management surface.
7359
+ */
7360
+ function detachMcpServerRoster(value) {
7361
+ if (!Array.isArray(value)) return void 0;
7362
+ const servers = [];
7363
+ for (const entry of value) {
7364
+ const view = detachMcpServerView(entry);
7365
+ if (view === void 0) return void 0;
7366
+ servers.push(view);
7367
+ }
7368
+ return Object.freeze(servers);
7369
+ }
7370
+ /** Detach one official `McpProbeResult`; `undefined` = invalid wire value. */
7371
+ function detachMcpProbeResult(value) {
7372
+ if (!isRecord$1(value)) return void 0;
7373
+ if (typeof value.ok !== "boolean") return void 0;
7374
+ const closure = detachCloseResult(value);
7375
+ if (closure === void 0) return void 0;
7376
+ if (value.ok) {
7377
+ if (!isStringArray(value.toolNames) || typeof value.truncated !== "boolean" || !isFiniteNumber(value.durationMs)) return;
7378
+ if (value.serverInfo !== void 0) {
7379
+ if (!isRecord$1(value.serverInfo) || typeof value.serverInfo.name !== "string" || typeof value.serverInfo.version !== "string") return void 0;
7380
+ }
7381
+ return Object.freeze({
7382
+ ok: true,
7383
+ toolNames: Object.freeze([...value.toolNames]),
7384
+ truncated: value.truncated,
7385
+ durationMs: value.durationMs,
7386
+ ...value.serverInfo === void 0 ? {} : { serverInfo: Object.freeze({
7387
+ name: value.serverInfo.name,
7388
+ version: value.serverInfo.version
7389
+ }) },
7390
+ closeConfirmed: closure.closeConfirmed,
7391
+ ...closure.cleanupError === void 0 ? {} : { cleanupError: closure.cleanupError }
7392
+ });
7393
+ }
7394
+ if (value.stage !== "connect" && value.stage !== "list") return void 0;
7395
+ if (typeof value.message !== "string" || !isFiniteNumber(value.durationMs)) return void 0;
7396
+ return Object.freeze({
7397
+ ok: false,
7398
+ stage: value.stage,
7399
+ message: value.message,
7400
+ durationMs: value.durationMs,
7401
+ closeConfirmed: closure.closeConfirmed,
7402
+ ...closure.cleanupError === void 0 ? {} : { cleanupError: closure.cleanupError }
7403
+ });
7404
+ }
7405
+ //#endregion
6131
7406
  //#region src/runtime/plugin-manager-port.ts
6132
7407
  /**
6133
7408
  * One plugin mutation's result arrived after the operation's authoritative
@@ -6144,6 +7419,702 @@ var PluginManagerStaleResultError = class extends Error {
6144
7419
  }
6145
7420
  };
6146
7421
  //#endregion
7422
+ //#region src/domain/extension-config/client-entry.ts
7423
+ /**
7424
+ * The ONE Client-local extension entry identity.
7425
+ *
7426
+ * A Client-mounted external `./tui` package uses a deterministic Loader entry
7427
+ * id derived from its validated profile Config row id:
7428
+ * `pi-tui-client-` + the same 32 lowercase hex characters. Keeping the
7429
+ * derivation neutral lets the mount owner and the Host Plugin Manager
7430
+ * projection agree without either layer importing the other.
7431
+ *
7432
+ * @module @xmoon76/dsh-pi-tui/domain/extension-config/client-entry
7433
+ */
7434
+ /** The stable Client entry-id prefix. */
7435
+ const CLIENT_EXTENSION_ENTRY_PREFIX = "pi-tui-client-";
7436
+ const HASH_SUFFIX = /^[0-9a-f]{32}$/u;
7437
+ /**
7438
+ * Derive the only allowed Client entry id for one validated Config row id.
7439
+ *
7440
+ * @param configRowId - the package's `pi-tui-extcfg-<32 hex>` row id.
7441
+ * @returns the matching `pi-tui-client-<32 hex>` Loader entry id.
7442
+ */
7443
+ function clientExtensionEntryId(configRowId) {
7444
+ if (!configRowId.startsWith("pi-tui-extcfg-")) throw new Error(`client extension: invalid Config row id "${configRowId}"`);
7445
+ const suffix = configRowId.slice(14);
7446
+ if (!HASH_SUFFIX.test(suffix)) throw new Error(`client extension: invalid Config row id hash "${configRowId}"`);
7447
+ return `${CLIENT_EXTENSION_ENTRY_PREFIX}${suffix}`;
7448
+ }
7449
+ //#endregion
7450
+ //#region src/app/plugin-manager/client-extension-discovery.ts
7451
+ /**
7452
+ * Read-only Client-extension qualification over ONE active DSH profile.
7453
+ *
7454
+ * This module is a pure projection: the caller supplies the official package
7455
+ * identity, whether the active profile selects it, and the Loader rows the
7456
+ * official resolution actually mounted. Nothing here calls npm, mounts a
7457
+ * fiber, imports a package's `./tui` entry, writes the profile or changes the
7458
+ * native DSH plugin-manager state — the result only says whether PiTui may
7459
+ * treat the package as a Client extension candidate later. It is NOT a second
7460
+ * plugin manager, and `candidate` is never an ACTIVE-surface claim.
7461
+ *
7462
+ * @module @xmoon76/dsh-pi-tui/app/plugin-manager/client-extension-discovery
7463
+ */
7464
+ /** The ONE trusted Host-safe module every opted-in package's row names. */
7465
+ const EXTENSION_CONFIG_MODULE = "@xmoon76/dsh-pi-tui/extension-config";
7466
+ /** The package subpath a Client extension opt-in must export. */
7467
+ const CLIENT_TUI_ENTRY_EXPORT = "./tui";
7468
+ /** The only opt-in value PiTui currently understands. */
7469
+ const CLIENT_TUI_LOCAL = "tui-local";
7470
+ function isRecord(value) {
7471
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7472
+ }
7473
+ /**
7474
+ * Qualify one package as a PiTui Client extension candidate.
7475
+ *
7476
+ * `not-opted-in` means the active profile has no opt-in for the package: it
7477
+ * declares no `dshPiTui` metadata, or the profile does not select its bundle
7478
+ * (an installed but unselected package contributes no Loader row at all).
7479
+ * `invalid-opt-in` means the profile selects a package that DID declare the
7480
+ * opt-in but the declaration and its mounted row cannot be honored; `reason`
7481
+ * names the first exact inconsistency. Neither outcome changes the native
7482
+ * installed/enabled state — the caller only loses or gains a Client candidate.
7483
+ *
7484
+ * @param input - official package identity, selection fact and mounted rows.
7485
+ * @returns the candidate, a non-opt-in, or the exact opt-in defect.
7486
+ */
7487
+ function discoverClientExtension(input) {
7488
+ const { package: pkg, selectedBundle, effectiveRows } = input;
7489
+ const meta = pkg.manifest.dshPiTui;
7490
+ if (meta === void 0) return { kind: "not-opted-in" };
7491
+ if (!selectedBundle) return { kind: "not-opted-in" };
7492
+ if (!isRecord(meta)) return {
7493
+ kind: "invalid-opt-in",
7494
+ reason: "dshPiTui metadata is not an object"
7495
+ };
7496
+ if (meta.manifestVersion !== 1) return {
7497
+ kind: "invalid-opt-in",
7498
+ reason: `dshPiTui.manifestVersion is not ${String(1)}`
7499
+ };
7500
+ const entrypoints = meta.entrypoints;
7501
+ if (!isRecord(entrypoints) || entrypoints["./tui"] !== "tui-local") return {
7502
+ kind: "invalid-opt-in",
7503
+ reason: `dshPiTui.entrypoints["${CLIENT_TUI_ENTRY_EXPORT}"] is not "${CLIENT_TUI_LOCAL}"`
7504
+ };
7505
+ const exportsField = pkg.manifest.exports;
7506
+ if (!isRecord(exportsField) || !Object.hasOwn(exportsField, "./tui")) return {
7507
+ kind: "invalid-opt-in",
7508
+ reason: `package exports declare no "${CLIENT_TUI_ENTRY_EXPORT}" entry`
7509
+ };
7510
+ const configRowId = extensionConfigRowId(pkg.name);
7511
+ const rows = effectiveRows.filter((row) => row.id === configRowId);
7512
+ if (rows.length === 0) return {
7513
+ kind: "invalid-opt-in",
7514
+ reason: `profile has no Loader row "${configRowId}"`
7515
+ };
7516
+ if (rows.length > 1) return {
7517
+ kind: "invalid-opt-in",
7518
+ reason: `profile mounts "${configRowId}" ${String(rows.length)} times`
7519
+ };
7520
+ if (rows[0].name !== "@xmoon76/dsh-pi-tui/extension-config") return {
7521
+ kind: "invalid-opt-in",
7522
+ reason: `Load row "${configRowId}" mounts "${rows[0].name}", not "${EXTENSION_CONFIG_MODULE}"`
7523
+ };
7524
+ return {
7525
+ kind: "candidate",
7526
+ packageName: pkg.name,
7527
+ configRowId,
7528
+ tuiSpecifier: `${pkg.name}/tui`
7529
+ };
7530
+ }
7531
+ //#endregion
7532
+ //#region src/app/client-extensions/discovery.ts
7533
+ /** The live profile Loader rows the official Host snapshot reports. */
7534
+ function effectiveRowsOf(snapshot) {
7535
+ const rows = [];
7536
+ for (const row of snapshot.plugins) {
7537
+ if (row.patchId === void 0 || !row.enabled || row.fiberPhase !== "active") continue;
7538
+ rows.push({
7539
+ id: row.patchId,
7540
+ name: row.moduleName
7541
+ });
7542
+ }
7543
+ return rows;
7544
+ }
7545
+ /**
7546
+ * Qualify every ENABLED official bundle against the CURRENT Client's own
7547
+ * installed package identity.
7548
+ *
7549
+ * Order is the official bundle order, so two Clients with the same Host
7550
+ * snapshot produce the same deterministic candidate order. A duplicate
7551
+ * manifest package name reached through two enabled bundles is a profile
7552
+ * identity defect: both outcomes are downgraded to `invalid-opt-in` instead
7553
+ * of letting one alias mount a package the other alias also names.
7554
+ *
7555
+ * @param snapshot - ONE authenticated official Host Plugin Manager snapshot.
7556
+ * @param pluginPackages - the current Client process's official package table.
7557
+ * @param parentURL - a `file:` URL inside the current Client install whose
7558
+ * Node lookup order applies to `packageOf`.
7559
+ * @returns one immutable outcome per enabled bundle, in snapshot order.
7560
+ */
7561
+ function discoverCurrentClientExtensions(snapshot, pluginPackages, parentURL) {
7562
+ const effectiveRows = effectiveRowsOf(snapshot);
7563
+ const outcomes = [];
7564
+ for (const bundle of snapshot.bundles) {
7565
+ if (!bundle.enabled) continue;
7566
+ const pkg = pluginPackages.packageOf(bundle.name, parentURL);
7567
+ if (pkg === void 0) {
7568
+ outcomes.push({
7569
+ kind: "unresolved",
7570
+ bundleName: bundle.name,
7571
+ reason: `the Client process cannot resolve bundle "${bundle.name}"`
7572
+ });
7573
+ continue;
7574
+ }
7575
+ const discovery = discoverClientExtension({
7576
+ package: {
7577
+ name: pkg.name,
7578
+ manifest: pkg.manifest
7579
+ },
7580
+ selectedBundle: true,
7581
+ effectiveRows
7582
+ });
7583
+ if (discovery.kind === "candidate") outcomes.push({
7584
+ kind: "candidate",
7585
+ bundleName: bundle.name,
7586
+ packageName: pkg.name,
7587
+ packageDir: pkg.dir,
7588
+ configRowId: discovery.configRowId,
7589
+ tuiSpecifier: discovery.tuiSpecifier,
7590
+ ...bundle.version !== void 0 ? { packageVersion: bundle.version } : typeof pkg.manifest.version === "string" ? { packageVersion: pkg.manifest.version } : {}
7591
+ });
7592
+ else if (discovery.kind === "invalid-opt-in") outcomes.push({
7593
+ kind: "invalid-opt-in",
7594
+ bundleName: bundle.name,
7595
+ packageName: pkg.name,
7596
+ reason: discovery.reason
7597
+ });
7598
+ else outcomes.push({
7599
+ kind: "not-opted-in",
7600
+ bundleName: bundle.name,
7601
+ packageName: pkg.name
7602
+ });
7603
+ }
7604
+ return freezeDuplicatePackageOutcomes(outcomes);
7605
+ }
7606
+ /** Fail closed when two enabled bundles resolve to one manifest package. */
7607
+ function freezeDuplicatePackageOutcomes(outcomes) {
7608
+ const byPackage = /* @__PURE__ */ new Map();
7609
+ outcomes.forEach((outcome, index) => {
7610
+ if (outcome.kind === "unresolved") return;
7611
+ const indexes = byPackage.get(outcome.packageName);
7612
+ if (indexes === void 0) byPackage.set(outcome.packageName, [index]);
7613
+ else indexes.push(index);
7614
+ });
7615
+ for (const [packageName, indexes] of byPackage) {
7616
+ if (indexes.length < 2) continue;
7617
+ for (const index of indexes) outcomes[index] = {
7618
+ kind: "invalid-opt-in",
7619
+ bundleName: outcomes[index].bundleName,
7620
+ packageName,
7621
+ reason: `multiple enabled bundles resolve to package "${packageName}"`
7622
+ };
7623
+ }
7624
+ return Object.freeze(outcomes.map((outcome) => Object.freeze(outcome)));
7625
+ }
7626
+ //#endregion
7627
+ //#region src/app/client-extensions/mount-owner.ts
7628
+ /**
7629
+ * The ONE Client-local mount owner for external PiTui `./tui` packages.
7630
+ *
7631
+ * Direct and every split Client construct the SAME owner over their own
7632
+ * EXISTING Cordis Context/Loader and the current process's official
7633
+ * `PluginPackages` table. The owner never reads the profile, never invents a
7634
+ * second package manager or extension service, and never treats the Host
7635
+ * Plugin Manager's `enabled` fact as an ACTIVE UI claim:
7636
+ *
7637
+ * ```text
7638
+ * Host PM snapshot -> discoverCurrentClientExtensions (existing pure policy)
7639
+ * -> ConfigPort.extensionConfigs.read(packageName)
7640
+ * -> official Loader.create({ id, name: '<pkg>/tui', config: effective })
7641
+ * -> real Entry/Fiber ACTIVE
7642
+ * -> this Client's piTuiExtensions ledger (Footer/Command contributions)
7643
+ * ```
7644
+ *
7645
+ * Lifecycle rules that are load-bearing here:
7646
+ * - the Loader entry id is always `pi-tui-client-` + the validated 32-char
7647
+ * `extensionConfigRowId` hash (`:` is the Loader tree separator and is never
7648
+ * allowed in an id);
7649
+ * - `loader.create()` resolving is NOT proof of activation: the real
7650
+ * `Entry.fiber` must exist, settle and be ACTIVE;
7651
+ * - `loader.remove()` unregisters synchronously but does not await the old
7652
+ * Fiber's terminal cleanup: the owner captures the fiber first, removes the
7653
+ * entry, then awaits that fiber's disposal before the id may be reused;
7654
+ * - a same-PID byte change is NEVER hot-imported: the old Entry stays the
7655
+ * active code and the package becomes `reload-required`;
7656
+ * - per-package failures stay Client-local and never block the other package.
7657
+ *
7658
+ * @module @xmoon76/dsh-pi-tui/app/client-extensions/mount-owner
7659
+ */
7660
+ /** Cordis `FiberState.ACTIVE` (the enum is a const enum with no runtime value). */
7661
+ const FIBER_ACTIVE = 2;
7662
+ /**
7663
+ * Bound on ONE third-party plugin's activation. A missing Cordis dependency
7664
+ * can leave a fiber PENDING forever; without a bound one broken plugin would
7665
+ * hold the whole serialized reconcile. This is a failure bound, not a
7666
+ * success window: an ACTIVE fiber settles immediately.
7667
+ */
7668
+ const ACTIVATION_TIMEOUT_MS = 15e3;
7669
+ /** One bounded activation wait over the REAL fiber lifecycle. */
7670
+ async function awaitActiveFiber(fiber, signal, timeoutMs = ACTIVATION_TIMEOUT_MS) {
7671
+ const timeout = AbortSignal.timeout(timeoutMs);
7672
+ const combined = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
7673
+ const aborted = new Promise((_resolve, reject) => {
7674
+ const onAbort = () => {
7675
+ reject(/* @__PURE__ */ new Error(timeout.aborted ? `./tui activation did not settle within ${String(timeoutMs)}ms` : "client extension activation was aborted"));
7676
+ };
7677
+ if (combined.aborted) {
7678
+ onAbort();
7679
+ return;
7680
+ }
7681
+ combined.addEventListener("abort", onAbort, { once: true });
7682
+ });
7683
+ await Promise.race([fiber.await(), aborted]);
7684
+ if (fiber.state !== FIBER_ACTIVE) throw new Error(`./tui fiber is not active after activation (state ${String(fiber.state)})`);
7685
+ }
7686
+ /** Whether two detached JSON Config values are equivalent. */
7687
+ function sameJsonValue(left, right) {
7688
+ return JSON.stringify(left) === JSON.stringify(right);
7689
+ }
7690
+ /** Whether two observations carry the same externally visible fact. */
7691
+ function sameObservation(left, right) {
7692
+ return left.packageName === right.packageName && left.phase === right.phase && left.entryId === right.entryId && left.configRevision === right.configRevision && left.codeIdentity === right.codeIdentity && left.reason === right.reason;
7693
+ }
7694
+ /**
7695
+ * Resolve the EXACT module URL the official Loader's ESM import uses. The
7696
+ * official Loader exposes its own resolved Node module loader; this is the
7697
+ * same resolver/parent URL the real import will use — never a `require`
7698
+ * condition, never a second resolver.
7699
+ */
7700
+ function resolveImportedModuleUrl(loader, specifier, parentURL) {
7701
+ const internal = loader.internal;
7702
+ if (internal === void 0) return void 0;
7703
+ try {
7704
+ const url = (internal.version === "v2" ? internal.resolveSync(parentURL, { specifier }) : internal.resolveSync(specifier, parentURL, {})).url;
7705
+ if (typeof url !== "string" || !url.startsWith("file:")) return void 0;
7706
+ return url;
7707
+ } catch {
7708
+ return;
7709
+ }
7710
+ }
7711
+ /** Hash the exact bytes of the module the Loader will import. */
7712
+ function readCodeIdentity(loader, specifier, parentURL) {
7713
+ const url = resolveImportedModuleUrl(loader, specifier, parentURL);
7714
+ if (url === void 0) return void 0;
7715
+ try {
7716
+ return createHash("sha256").update(readFileSync(new URL(url))).digest("hex");
7717
+ } catch {
7718
+ return;
7719
+ }
7720
+ }
7721
+ /**
7722
+ * Process-lifetime identity memory per Loader: Node's ESM cache is
7723
+ * process-scoped, so a same-PID surface revision must inherit the identity
7724
+ * the previous revision actually imported. A fresh owner must never mistake a
7725
+ * cached v1 module for a newly written v2 file.
7726
+ */
7727
+ const PROCESS_KNOWN_CODE_IDENTITIES = /* @__PURE__ */ new WeakMap();
7728
+ function processKnownCodeIdentities(loader) {
7729
+ const key = loader[symbols.original] ?? loader;
7730
+ let known = PROCESS_KNOWN_CODE_IDENTITIES.get(key);
7731
+ if (known === void 0) {
7732
+ known = /* @__PURE__ */ new Map();
7733
+ PROCESS_KNOWN_CODE_IDENTITIES.set(key, known);
7734
+ }
7735
+ return known;
7736
+ }
7737
+ /**
7738
+ * Process-lifetime official package-version memory per Loader. Version is the
7739
+ * authoritative Host package-update fact; an unchanged thin `./tui` entry can
7740
+ * re-export a changed implementation, so entry-file bytes alone are not an
7741
+ * update identity. The map is conservative: a version that cannot be compared
7742
+ * never becomes a false ACTIVE claim.
7743
+ */
7744
+ const PROCESS_KNOWN_PACKAGE_VERSIONS = /* @__PURE__ */ new WeakMap();
7745
+ function processKnownPackageVersions(loader) {
7746
+ const key = loader[symbols.original] ?? loader;
7747
+ let known = PROCESS_KNOWN_PACKAGE_VERSIONS.get(key);
7748
+ if (known === void 0) {
7749
+ known = /* @__PURE__ */ new Map();
7750
+ PROCESS_KNOWN_PACKAGE_VERSIONS.set(key, known);
7751
+ }
7752
+ return known;
7753
+ }
7754
+ /** Create the ONE Client-local mount owner. */
7755
+ function createClientExtensionMountOwner(options) {
7756
+ const { loader, pluginPackages, config, parentURL } = options;
7757
+ const mounted = /* @__PURE__ */ new Map();
7758
+ /**
7759
+ * The code identity this Client has ALREADY imported for a package, even
7760
+ * after a disable unloads its entry. Node's ESM cache never forgets a URL,
7761
+ * so a later re-enable must not claim newer file bytes it cannot load.
7762
+ */
7763
+ const knownCodeIdentity = processKnownCodeIdentities(loader);
7764
+ const knownPackageVersion = processKnownPackageVersions(loader);
7765
+ const observations = /* @__PURE__ */ new Map();
7766
+ const observationListeners = /* @__PURE__ */ new Set();
7767
+ let observationRevision = 0;
7768
+ let reconcileTail = Promise.resolve();
7769
+ let disposed = false;
7770
+ /** Reconcile epoch: a superseded reconcile may never publish. */
7771
+ let reconciliation = 0;
7772
+ const warn = (message, fields) => {
7773
+ options.diag?.warn(message, fields);
7774
+ };
7775
+ const isCurrent = (epoch) => !disposed && epoch === reconciliation && options.signal?.aborted !== true;
7776
+ const setObservation = (observation) => {
7777
+ const previous = observations.get(observation.packageName);
7778
+ if (previous !== void 0 && sameObservation(previous, observation)) return;
7779
+ observations.set(observation.packageName, Object.freeze(observation));
7780
+ observationRevision += 1;
7781
+ if (observation.phase === "reload-required" && previous?.phase !== "reload-required") options.notifyReloadRequired?.(observation.packageName, observation.reason ?? "reload required");
7782
+ for (const listener of [...observationListeners]) listener();
7783
+ };
7784
+ /** Remove one package's observation as a semantic change. */
7785
+ const deleteObservation = (packageName) => {
7786
+ if (!observations.delete(packageName)) return;
7787
+ observationRevision += 1;
7788
+ for (const listener of [...observationListeners]) listener();
7789
+ };
7790
+ /** Capture the live fiber and remove the entry, then await terminal cleanup. */
7791
+ const unloadEntry = async (entry) => {
7792
+ let fiber;
7793
+ try {
7794
+ fiber = loader.resolve(entry.entryId).fiber;
7795
+ } catch {
7796
+ fiber = void 0;
7797
+ }
7798
+ loader.remove(entry.entryId);
7799
+ unmarkOwnedClientExtensionEntry(loader, entry.entryId);
7800
+ if (fiber !== void 0) {
7801
+ await fiber.dispose();
7802
+ await fiber.await();
7803
+ }
7804
+ if (Object.hasOwn(loader.store, entry.entryId)) throw new Error(`client extension: entry "${entry.entryId}" survived its removal`);
7805
+ };
7806
+ /** Remove a not-yet-published entry created by the current reconcile. */
7807
+ const discardCreatedEntry = async (entryId) => {
7808
+ let fiber;
7809
+ try {
7810
+ fiber = loader.resolve(entryId).fiber;
7811
+ } catch {
7812
+ return;
7813
+ }
7814
+ try {
7815
+ loader.remove(entryId);
7816
+ unmarkOwnedClientExtensionEntry(loader, entryId);
7817
+ } catch {}
7818
+ if (fiber !== void 0) await Promise.resolve(fiber.dispose()).catch(() => void 0);
7819
+ };
7820
+ /** Resolve the real entry/fiber pair after `loader.create` resolved. */
7821
+ const requireActiveFiber = async (entryId, epoch) => {
7822
+ const fiber = loader.resolve(entryId).fiber;
7823
+ if (fiber === void 0) throw new Error(`./tui entry "${entryId}" produced no live Fiber`);
7824
+ await awaitActiveFiber(fiber, options.signal);
7825
+ if (!isCurrent(epoch)) throw new Error("client extension activation was superseded");
7826
+ return fiber;
7827
+ };
7828
+ const reconcileNow = async (snapshot) => {
7829
+ const epoch = ++reconciliation;
7830
+ const outcomes = discoverCurrentClientExtensions(snapshot, pluginPackages, parentURL);
7831
+ const candidates = /* @__PURE__ */ new Map();
7832
+ for (const outcome of outcomes) {
7833
+ if (outcome.kind !== "candidate") continue;
7834
+ clientExtensionEntryId(outcome.configRowId);
7835
+ candidates.set(outcome.packageName, outcome);
7836
+ }
7837
+ for (const [packageName, entry] of [...mounted]) {
7838
+ if (candidates.has(packageName)) continue;
7839
+ try {
7840
+ await unloadEntry(entry);
7841
+ mounted.delete(packageName);
7842
+ deleteObservation(packageName);
7843
+ } catch (error) {
7844
+ setObservation({
7845
+ packageName,
7846
+ phase: "error",
7847
+ entryId: entry.entryId,
7848
+ reason: "cleanup failed"
7849
+ });
7850
+ warn("client extension: cleanup failed while unloading an ineligible package", {
7851
+ packageName,
7852
+ entryId: entry.entryId,
7853
+ error: error instanceof Error ? error.message : String(error)
7854
+ });
7855
+ }
7856
+ if (!isCurrent(epoch)) return;
7857
+ }
7858
+ const current = new Set(outcomes.map((outcome) => outcome.kind === "unresolved" ? outcome.bundleName : outcome.packageName));
7859
+ for (const packageName of [...observations.keys()]) if (!current.has(packageName) && !mounted.has(packageName)) deleteObservation(packageName);
7860
+ for (const outcome of outcomes) {
7861
+ if (outcome.kind === "candidate") continue;
7862
+ const packageName = outcome.kind === "unresolved" ? outcome.bundleName : outcome.packageName;
7863
+ setObservation({
7864
+ packageName,
7865
+ phase: outcome.kind,
7866
+ ...outcome.kind === "not-opted-in" ? {} : { reason: outcome.reason }
7867
+ });
7868
+ }
7869
+ if (candidates.size === 0) return;
7870
+ try {
7871
+ await config.refresh();
7872
+ } catch (error) {
7873
+ warn("client extension: per-package Config refresh failed", { error: error instanceof Error ? error.message : String(error) });
7874
+ }
7875
+ if (!isCurrent(epoch)) return;
7876
+ for (const candidate of outcomes) {
7877
+ if (candidate.kind !== "candidate") continue;
7878
+ if (!isCurrent(epoch)) return;
7879
+ const { packageName, tuiSpecifier, configRowId, packageVersion } = candidate;
7880
+ const read = config.read(packageName);
7881
+ if (read.kind !== "ready") {
7882
+ const previous = mounted.get(packageName);
7883
+ if (previous !== void 0) try {
7884
+ await unloadEntry(previous);
7885
+ mounted.delete(packageName);
7886
+ } catch (error) {
7887
+ setObservation({
7888
+ packageName,
7889
+ phase: "error",
7890
+ entryId: previous.entryId,
7891
+ reason: "cleanup failed after Config became unavailable"
7892
+ });
7893
+ warn("client extension: cleanup failed after Config became unavailable", {
7894
+ packageName,
7895
+ entryId: previous.entryId,
7896
+ error: error instanceof Error ? error.message : String(error)
7897
+ });
7898
+ continue;
7899
+ }
7900
+ setObservation({
7901
+ packageName,
7902
+ phase: "unavailable",
7903
+ reason: read.reason
7904
+ });
7905
+ continue;
7906
+ }
7907
+ const identity = readCodeIdentity(loader, tuiSpecifier, parentURL);
7908
+ const previous = mounted.get(packageName);
7909
+ if (previous !== void 0) {
7910
+ if (previous.packageVersion !== packageVersion) {
7911
+ setObservation({
7912
+ packageName,
7913
+ phase: "reload-required",
7914
+ entryId: previous.entryId,
7915
+ ...previous.codeIdentity === void 0 ? {} : { codeIdentity: previous.codeIdentity },
7916
+ reason: "the installed package version changed; restart this Client to load the new ./tui code"
7917
+ });
7918
+ continue;
7919
+ }
7920
+ if (identity === void 0) {
7921
+ setObservation({
7922
+ packageName,
7923
+ phase: "reload-required",
7924
+ entryId: previous.entryId,
7925
+ ...knownCodeIdentity.get(packageName) === void 0 ? {} : { codeIdentity: knownCodeIdentity.get(packageName) },
7926
+ reason: "the installed ./tui bytes cannot be verified; restart this Client to reload them"
7927
+ });
7928
+ continue;
7929
+ }
7930
+ const appliedIdentity = knownCodeIdentity.get(packageName);
7931
+ if (appliedIdentity !== identity) {
7932
+ setObservation({
7933
+ packageName,
7934
+ phase: "reload-required",
7935
+ entryId: previous.entryId,
7936
+ ...appliedIdentity === void 0 ? {} : { codeIdentity: appliedIdentity },
7937
+ reason: "the installed ./tui bytes differ from the running entry; restart this Client to load them"
7938
+ });
7939
+ continue;
7940
+ }
7941
+ if (!sameJsonValue(previous.configValue, read.effective) || previous.configRevision !== read.revision) {
7942
+ try {
7943
+ await loader.update(previous.entryId, { config: read.effective });
7944
+ await requireActiveFiber(previous.entryId, epoch);
7945
+ } catch (error) {
7946
+ await unloadEntry(previous).catch(() => void 0);
7947
+ mounted.delete(packageName);
7948
+ setObservation({
7949
+ packageName,
7950
+ phase: "error",
7951
+ entryId: previous.entryId,
7952
+ reason: "config update failed"
7953
+ });
7954
+ warn("client extension: config update failed", {
7955
+ packageName,
7956
+ entryId: previous.entryId,
7957
+ error: error instanceof Error ? error.message : String(error)
7958
+ });
7959
+ continue;
7960
+ }
7961
+ mounted.set(packageName, {
7962
+ ...previous,
7963
+ configRevision: read.revision,
7964
+ configValue: read.effective
7965
+ });
7966
+ }
7967
+ const applied = mounted.get(packageName);
7968
+ setObservation({
7969
+ packageName,
7970
+ phase: "active",
7971
+ entryId: applied.entryId,
7972
+ configRevision: applied.configRevision,
7973
+ ...applied.codeIdentity === void 0 ? {} : { codeIdentity: applied.codeIdentity }
7974
+ });
7975
+ continue;
7976
+ }
7977
+ if (knownCodeIdentity.has(packageName)) {
7978
+ const knownIdentity = knownCodeIdentity.get(packageName);
7979
+ if (knownIdentity === void 0 || identity === void 0 || knownIdentity !== identity) {
7980
+ setObservation({
7981
+ packageName,
7982
+ phase: "reload-required",
7983
+ ...knownIdentity === void 0 ? {} : { codeIdentity: knownIdentity },
7984
+ reason: "the installed ./tui bytes differ from (or cannot be verified against) the code this Client already loaded; restart this Client"
7985
+ });
7986
+ continue;
7987
+ }
7988
+ }
7989
+ if (knownPackageVersion.has(packageName)) {
7990
+ if (knownPackageVersion.get(packageName) !== packageVersion) {
7991
+ setObservation({
7992
+ packageName,
7993
+ phase: "reload-required",
7994
+ reason: "the installed package version changed; restart this Client to load the new ./tui code"
7995
+ });
7996
+ continue;
7997
+ }
7998
+ }
7999
+ const entryId = clientExtensionEntryId(configRowId);
8000
+ if (Object.hasOwn(loader.store, entryId)) {
8001
+ setObservation({
8002
+ packageName,
8003
+ phase: "error",
8004
+ entryId,
8005
+ reason: `the Client entry id "${entryId}" is already owned by another Loader entry`
8006
+ });
8007
+ continue;
8008
+ }
8009
+ setObservation({
8010
+ packageName,
8011
+ phase: "pending",
8012
+ reason: "activating ./tui"
8013
+ });
8014
+ knownCodeIdentity.set(packageName, identity);
8015
+ knownPackageVersion.set(packageName, packageVersion);
8016
+ try {
8017
+ await loader.create({
8018
+ id: entryId,
8019
+ name: tuiSpecifier,
8020
+ config: read.effective
8021
+ });
8022
+ markOwnedClientExtensionEntry(loader, entryId);
8023
+ if (!isCurrent(epoch)) {
8024
+ await discardCreatedEntry(entryId);
8025
+ return;
8026
+ }
8027
+ await requireActiveFiber(entryId, epoch);
8028
+ const verified = config.read(packageName);
8029
+ if (verified.kind !== "ready" || !Object.is(verified.generation, read.generation)) {
8030
+ await discardCreatedEntry(entryId);
8031
+ setObservation({
8032
+ packageName,
8033
+ phase: "unavailable",
8034
+ reason: "the Host Config generation changed while the Client entry was activating; refresh and retry"
8035
+ });
8036
+ continue;
8037
+ }
8038
+ mounted.set(packageName, {
8039
+ packageName,
8040
+ entryId,
8041
+ configRevision: verified.revision,
8042
+ configValue: verified.effective,
8043
+ codeIdentity: identity,
8044
+ packageVersion
8045
+ });
8046
+ setObservation({
8047
+ packageName,
8048
+ phase: "active",
8049
+ entryId,
8050
+ configRevision: verified.revision,
8051
+ ...identity === void 0 ? {} : { codeIdentity: identity }
8052
+ });
8053
+ } catch (error) {
8054
+ await discardCreatedEntry(entryId);
8055
+ setObservation({
8056
+ packageName,
8057
+ phase: "error",
8058
+ entryId,
8059
+ reason: "the ./tui module could not be activated"
8060
+ });
8061
+ warn("client extension: ./tui activation failed", {
8062
+ packageName,
8063
+ entryId,
8064
+ error: error instanceof Error ? error.message : String(error)
8065
+ });
8066
+ }
8067
+ }
8068
+ };
8069
+ return {
8070
+ reconcile(snapshot) {
8071
+ if (disposed) return Promise.reject(/* @__PURE__ */ new Error("client extension mount owner is disposed"));
8072
+ const run = reconcileTail.then(() => reconcileNow(snapshot));
8073
+ reconcileTail = run.then(() => void 0, () => void 0);
8074
+ return run;
8075
+ },
8076
+ async dispose() {
8077
+ if (disposed) return;
8078
+ disposed = true;
8079
+ reconciliation += 1;
8080
+ observationListeners.clear();
8081
+ await reconcileTail.catch(() => void 0);
8082
+ const errors = [];
8083
+ for (const [packageName, entry] of [...mounted].reverse()) try {
8084
+ await unloadEntry(entry);
8085
+ mounted.delete(packageName);
8086
+ deleteObservation(packageName);
8087
+ } catch (error) {
8088
+ errors.push(error);
8089
+ setObservation({
8090
+ packageName,
8091
+ phase: "error",
8092
+ entryId: entry.entryId,
8093
+ reason: "cleanup failed"
8094
+ });
8095
+ }
8096
+ if (errors.length === 1) throw errors[0];
8097
+ if (errors.length > 1) throw new AggregateError(errors, "client extension mount owner disposal failed");
8098
+ },
8099
+ observation() {
8100
+ return Object.freeze([...observations.values()]);
8101
+ },
8102
+ revision() {
8103
+ return observationRevision;
8104
+ },
8105
+ subscribe(listener) {
8106
+ if (disposed) return () => {};
8107
+ observationListeners.add(listener);
8108
+ let active = true;
8109
+ return () => {
8110
+ if (!active) return;
8111
+ active = false;
8112
+ observationListeners.delete(listener);
8113
+ };
8114
+ }
8115
+ };
8116
+ }
8117
+ //#endregion
6147
8118
  //#region src/app/remote/terminal-progress-source.ts
6148
8119
  /** Consecutive frame-less watch endings tolerated before failing closed. */
6149
8120
  const EMPTY_WATCH_REOPEN_LIMIT = 3;
@@ -6257,4 +8228,4 @@ function createRemoteTerminalProgressSource(deps) {
6257
8228
  } };
6258
8229
  }
6259
8230
  //#endregion
6260
- export { ownerHandleOf as $, settledWriteMessage as A, classifyCommandLine as B, classifyRemoteWriteFailure as C, dshVersion as Ct, remoteFailureMessage as D, remoteFailureCode as E, __exportAll as Et, extensions_exports as F, shouldConsumeAdvertisedMiss as G, isPlainExitPrompt as H, PI_TUI_EXTENSIONS_SERVICE as I, deliveredFileReadErrorFrom as J, normalizeInputEvent as K, InvalidateBatcher as L, isRemoteBusinessRefusalCode as M, ScheduleOutcomeUnknownError as N, remoteNotDispatched as O, ScheduleUnavailableError as P, directAgentOf as Q, LOCAL_COMMANDS as R, REMOTE_IMPLEMENTED_CAPABILITIES as S, bundleVersion as St, isRemoteCancellation as T, TUI_STARTUP_SERVICE as Tt, localCommandMayWrite as U, isBareCommandLine as V, normalizeSkillInvocation as W, WorkspaceSelectionError as X, LifecycleError as Y, clientOwnerOf as Z, detachedSessionStatus as _, getPath as _t, detachInspection as a, isTerminalAmbiguousKeyId as at, safeSubagentErrorMessage as b, SupersededReadError as bt, detachPluginManagerSnapshot as c, VIEWER_BLOCKED_PARENT_ACTIONS as ct, detachPluginVersionList as d, isTextProducingKeyId as dt, requireCreated as et, pluginInstallRequestId as f, isValidKeyId as ft, questionAnswerError as g, deriveKeyRef as gt, QuestionAnswerError as h, classifyCredentialArg as ht, detachChange as i, isPhysicalEscapeAction as it, GATEWAY_PRE_INVOCATION_CODES as j, remoteRejected as k, detachPluginUpdateProgress as l, canonicalizeKeyId as lt, QUESTION_REPLY_QUEUED as m, ROUTE_PATTERN as mt, createRemoteTerminalProgressSource as n, DEFAULT_LEADER_TIMEOUT_MS as nt, detachLog as o, parseUserKeybindings as ot, QUESTION_BAD_ANSWER as p, PROTOCOL_CHOICES as pt, DeliveredFileReadError as q, PluginManagerStaleResultError as r, isEditorSubmitPreSubmitKey as rt, detachPhase as s, APP_KEYBINDINGS as st, consumeRemoteTerminalProgress as t, requireOpened as tt, detachPluginUpdateResult as u, isRuntimeBindableKeyId as ut, detachedTurnOutline as v, providerOptionsFor as vt, copyFailureDetails as w, packageVersion$1 as wt, DIRECT_IMPLEMENTED_CAPABILITIES as x, contextPressureOccupancy as xt, classifySubagentPromptSettlement as y, providerProfileProjectionOf as yt, SESSIONLESS_COMMANDS as z };
8231
+ export { SESSIONLESS_COMMANDS as $, isValidKeyId as $t, detachedSessionStatus as A, projectMcpServerEntry as At, remoteFailureMessage as B, readWebApiBilling as Bt, projectShellExecutionSettings as C, baseDictKeysOf as Ct, QUESTION_REPLY_QUEUED as D, mcpEditOps as Dt, QUESTION_BAD_ANSWER as E, mcpAddOps as Et, REMOTE_IMPLEMENTED_CAPABILITIES as F, assertSearchProviderId as Ft, isRemoteBusinessRefusalCode as G, isPhysicalEscapeAction as Gt, remoteRejected as H, webProviderSelectionFactsOf as Ht, classifyRemoteWriteFailure as I, assertSearchProviderReplaceable as It, extensions_exports as J, APP_KEYBINDINGS as Jt, ScheduleOutcomeUnknownError as K, isTerminalAmbiguousKeyId as Kt, copyFailureDetails as L, assertWebApiBilling as Lt, classifySubagentPromptSettlement as M, assertFetchProviderId as Mt, safeSubagentErrorMessage as N, assertFetchProviderReplaceable as Nt, QuestionAnswerError as O, mcpRemoveOps as Ot, DIRECT_IMPLEMENTED_CAPABILITIES as P, assertSearchApiCount as Pt, LOCAL_COMMANDS as Q, isTextProducingKeyId as Qt, isRemoteCancellation as R, isWebApiBilling as Rt, projectSessionLogUpload as S, CuaAccessUnavailableError as St, projectSubagentModelSelection as T, diffMcpServerDraft as Tt, settledWriteMessage as U, DEFAULT_LEADER_TIMEOUT_MS as Ut, remoteNotDispatched as V, webApiAdvancedFactsOf as Vt, GATEWAY_PRE_INVOCATION_CODES as W, isEditorSubmitPreSubmitKey as Wt, InvalidateBatcher as X, canonicalizeKeyId as Xt, PI_TUI_EXTENSIONS_SERVICE as Y, VIEWER_BLOCKED_PARENT_ACTIONS as Yt, IMMEDIATE_SESSIONLESS_COMMANDS as Z, isRuntimeBindableKeyId as Zt, ownedClientExtensionEntryIds as _, clientOwnerOf as _t, detachMcpProbeResult as a, providerOptionsFor as an, localCommandMayWrite as at, snapshotExtensionConfigOps as b, requireCreated as bt, detachChange as c, contextPressureOccupancy as cn, copyModelSelection as ct, detachPhase as d, TUI_STARTUP_SERVICE as dn, sameModelSelection as dt, PROTOCOL_CHOICES as en, SESSION_NAVIGATION_COMMANDS as et, detachPluginManagerSnapshot as f, __exportAll as fn, normalizeInputEvent as ft, pluginInstallRequestId as g, WorkspaceSelectionError as gt, detachPluginVersionList as h, LifecycleError as ht, PluginManagerStaleResultError as i, getPath as in, isPlainExitPrompt as it, detachedTurnOutline as j, validateMcpServerDraft as jt, questionAnswerError as k, mcpSetEnabledOps as kt, detachInspection as l, bundleVersion as ln, normalizeModelSelection as lt, detachPluginUpdateResult as m, deliveredFileReadErrorFrom as mt, createRemoteTerminalProgressSource as n, classifyCredentialArg as nn, classifyExitIntent as nt, detachMcpServerRoster as o, providerProfileProjectionOf as on, normalizeSkillInvocation as ot, detachPluginUpdateProgress as p, DeliveredFileReadError as pt, ScheduleUnavailableError as q, parseUserKeybindings as qt, createClientExtensionMountOwner as r, deriveKeyRef as rn, isBareCommandLine as rt, hostDirectoryBrowseFailureOutcome as s, SupersededReadError as sn, shouldConsumeAdvertisedMiss as st, consumeRemoteTerminalProgress as t, ROUTE_PATTERN as tn, classifyCommandLine as tt, detachLog as u, dshVersion as un, rawSelectionFromRequestHeader as ut, extensionConfigUserDataPresent as v, directAgentOf as vt, projectSubagentLimits as w, classifyMcpServerProvenance as wt, projectAgentLoopSettings as x, requireOpened as xt, projectExtensionConfigData as y, ownerHandleOf as yt, remoteFailureCode as z, maskWebProviderOverrideUrl as zt };