@xmoon76/dsh-pi-tui 0.5.3 → 0.5.5

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 (59) hide show
  1. package/README.en.md +195 -150
  2. package/README.md +137 -103
  3. package/cordis.patch.yml +54 -2
  4. package/dist/application-runtime-CbBO4bY-.mjs +6860 -0
  5. package/dist/bootstrap-DLOydLLj.mjs +108410 -0
  6. package/dist/builtins.mjs +2 -3
  7. package/dist/client-bootstrap-DwSFzcTW.mjs +872 -0
  8. package/dist/context-summary-Bz0AGXa1.mjs +12027 -0
  9. package/dist/context-summary-D9mhxPXL.mjs +10015 -0
  10. package/dist/custom-items-CKrOBCox.mjs +655 -0
  11. package/dist/disposal-BYBbEpVY.mjs +54 -0
  12. package/dist/dispose-cause-BzcXo4hu.mjs +123 -0
  13. package/dist/dispose-cause-CNFuUnjR.mjs +24 -0
  14. package/dist/dist-C7QMk0ws.mjs +15431 -0
  15. package/dist/entry-control-DnduyDiw.mjs +92 -0
  16. package/dist/extension/advanced.d.mts +1 -1
  17. package/dist/extension/unstable.d.mts +1 -1
  18. package/dist/{extensions-DzpBiiYb.d.mts → extensions-Bte3XOt5.d.mts} +1 -1
  19. package/dist/{extensions-a-rxanjw.mjs → extensions-pcFiH7Qe.mjs} +1498 -410
  20. package/dist/extensions.d.mts +2 -2
  21. package/dist/extensions.mjs +1 -1
  22. package/dist/host-bootstrap-CKdfLkNS.mjs +188 -0
  23. package/dist/host-foundation-probe-CYHsbAw6.mjs +143 -0
  24. package/dist/host-prerequisites-9JBTtVNu.mjs +36 -0
  25. package/dist/host-runtime.d.mts +26 -0
  26. package/dist/host-runtime.mjs +450 -0
  27. package/dist/index.d.mts +9 -2
  28. package/dist/index.mjs +45779 -24480
  29. package/dist/local-client.mjs +1816 -0
  30. package/dist/local-discovery-CXnLT4GF.mjs +755 -0
  31. package/dist/local-discovery-DVFFpfBG.mjs +2 -0
  32. package/dist/local-host.mjs +1025 -0
  33. package/dist/local-transport-C9aonplC.mjs +513 -0
  34. package/dist/performance-host.d.mts +2 -2
  35. package/dist/performance-host.mjs +258 -1
  36. package/dist/{performance-view-jvvd8Jn7.mjs → performance-view-CfGvLZyD.mjs} +1 -1
  37. package/dist/pi-tui-remote-contribution-DRk6Tl3J.mjs +78 -0
  38. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  39. package/dist/pi-tui-terminal-progress-contract-XTQKj-WW.mjs +905 -0
  40. package/dist/{public-types-gZi3iFNh.d.mts → public-types-Dgf1bDke.d.mts} +3 -3
  41. package/dist/{runtime-BtPH-UUb.mjs → runtime-Bh5OsftD.mjs} +1311 -1024
  42. package/dist/runtime-C5ROZqFj.mjs +2 -0
  43. package/dist/runtime-status-0lp9CM0V.mjs +1923 -0
  44. package/dist/session-4keoXjk0.mjs +10869 -0
  45. package/dist/session-B2zqv4wr.mjs +10869 -0
  46. package/dist/{startup-D5Xu8diR.mjs → startup-Ct2UUjUL.mjs} +55 -13
  47. package/dist/startup.d.mts +2 -1
  48. package/dist/startup.mjs +1 -1
  49. package/dist/terminal-progress-source-BhufrZ74.mjs +6000 -0
  50. package/dist/terminal-progress-source-CsBinCJ_.mjs +965 -0
  51. package/dist/visual-tools.d.mts +62 -0
  52. package/dist/visual-tools.mjs +556 -0
  53. package/generated/dsh-presets/README.md +1 -1
  54. package/package.json +145 -117
  55. package/dist/context-summary-CxUpNkA9.mjs +0 -2951
  56. package/dist/performance-host-BJT6scGF.mjs +0 -266
  57. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  58. package/dist/session-BZLxhrPQ.mjs +0 -5697
  59. package/dist/terminal-progress-source-BlmksrSD.mjs +0 -2200
@@ -1,2200 +0,0 @@
1
- import { ht as parseFooterLayout, mt as isFooterLayout } from "./extensions-a-rxanjw.mjs";
2
- import { accessSync, constants, readdirSync, statSync } from "node:fs";
3
- import { delimiter, join, posix, win32 } from "node:path";
4
- import { homedir } from "node:os";
5
- import { spawn } from "node:child_process";
6
- //#region src/runtime/direct/working-directory-direct.ts
7
- /**
8
- * The effective directory of one live Agent's Session: the official
9
- * `workingDirectory.get(session)` value when the service is mounted, else the
10
- * immutable header cwd — the INITIAL committed value of that same projection,
11
- * so a minimal composition without the row keeps the historical read instead
12
- * of inventing a directory.
13
- *
14
- * @param workingDirectory - the official service, or `undefined` when the
15
- * composition does not mount the row.
16
- * @param agent - the exact live Agent whose Session is read.
17
- * @returns the effective absolute directory, or `undefined` when neither the
18
- * service nor a header cwd can answer (never a Client-side guess).
19
- */
20
- function effectiveAgentCwd(workingDirectory, agent) {
21
- if (workingDirectory === void 0) return agent.session.header.cwd;
22
- return workingDirectory.get(agent.session);
23
- }
24
- /** The effective directory recorded by one official `workingDirectory`
25
- * projection SNAPSHOT value: its wire view is `string | null`, where `null`
26
- * is the legal "no directory recorded" state (the header had none) — an
27
- * absent/foreign value reads `undefined` (unavailable), never a directory. */
28
- function projectedWorkingDirectory(value) {
29
- return typeof value === "string" && value !== "" ? value : void 0;
30
- }
31
- //#endregion
32
- //#region src/runtime/session-reader-port.ts
33
- /** The official context-pressure occupancy numerator shared by both
34
- * backends: `projectedTokens ?? pressureTokens` over the raw projection
35
- * value (an absent/foreign-shaped field is not coerced; a projection with
36
- * neither field reads unmeasured). */
37
- function contextPressureOccupancy(value) {
38
- if (typeof value !== "object" || value === null) return void 0;
39
- const pressure = value;
40
- if (typeof pressure.projectedTokens === "number") return pressure.projectedTokens;
41
- if (typeof pressure.pressureTokens === "number") return pressure.pressureTokens;
42
- }
43
- //#endregion
44
- //#region src/domain/footer/command-config.ts
45
- /** The timeout ceiling. */
46
- const MAX_COMMAND_TIMEOUT_MS = 1e3;
47
- /** The minimum refresh interval (plan §17.7). */
48
- const MIN_COMMAND_REFRESH_MS = 1e3;
49
- //#endregion
50
- //#region src/domain/footer/command-trust.ts
51
- /**
52
- * The footer command TRUST GATE (plan §17.4): a repository/project config
53
- * must NEVER silently trigger arbitrary shell execution. The command is
54
- * read ONLY from the settings descriptor's USER layer (the stored
55
- * document's user section) — never from the merged/resolved value, which
56
- * a project layer could influence. When the user layer cannot prove the
57
- * command, command mode is disabled and the native layout applies.
58
- * @module @xmoon76/dsh-pi-tui/domain/footer/command-trust
59
- */
60
- /** Validate the persisted footerCommand value (bounds per plan §17.3). */
61
- function parseFooterCommandConfig(input) {
62
- if (typeof input !== "object" || input === null) return void 0;
63
- const raw = input;
64
- if (raw.schemaVersion !== 1) return void 0;
65
- if (typeof raw.command !== "string" || raw.command.trim() === "") return void 0;
66
- if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(raw.command)) return void 0;
67
- const timeoutMs = raw.timeoutMs === void 0 ? 300 : typeof raw.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? Math.min(Math.max(1, raw.timeoutMs), MAX_COMMAND_TIMEOUT_MS) : 300;
68
- const refreshIntervalMs = raw.refreshIntervalMs === void 0 ? MIN_COMMAND_REFRESH_MS : typeof raw.refreshIntervalMs === "number" && Number.isFinite(raw.refreshIntervalMs) ? Math.max(MIN_COMMAND_REFRESH_MS, raw.refreshIntervalMs) : MIN_COMMAND_REFRESH_MS;
69
- const maxRows = raw.maxRows === void 0 ? 1 : typeof raw.maxRows === "number" && Number.isFinite(raw.maxRows) ? Math.min(Math.max(1, Math.floor(raw.maxRows)), 2) : 1;
70
- return {
71
- command: raw.command,
72
- timeoutMs,
73
- refreshIntervalMs,
74
- maxRows
75
- };
76
- }
77
- /**
78
- * Resolve the TRUSTED command config: the footerCommand value must be
79
- * present in the USER layer of the tui-app settings descriptor. A
80
- * merged/project-supplied value is refused (undefined = command mode
81
- * disabled, native fallback, diagnostic warning).
82
- * @param descriptors - the settings provider's describe() output.
83
- * @param namespace - the tui-app settings/profile Config namespace value.
84
- * @returns the validated config, or undefined when untrusted/invalid.
85
- */
86
- function resolveTrustedFooterCommand(descriptors, namespace) {
87
- if (descriptors === void 0) return void 0;
88
- const descriptor = descriptors.find((entry) => entry.ns === namespace);
89
- if (descriptor === void 0) return void 0;
90
- const user = descriptor.user;
91
- if (typeof user !== "object" || user === null) return void 0;
92
- const raw = user.footerCommand;
93
- return parseFooterCommandConfig(raw);
94
- }
95
- /**
96
- * Resolve the USER layer's declared footer mode. Command mode must be
97
- * user-layer-owned as well: a project can flip the MERGED `footer:
98
- * command`, but the gate never lets a project config silently trigger the
99
- * user's command — the user layer must declare the command mode too.
100
- * @returns the user layer's footer value, or undefined when absent.
101
- */
102
- function resolveUserLayerFooterMode(descriptors, namespace) {
103
- if (descriptors === void 0) return void 0;
104
- const descriptor = descriptors.find((entry) => entry.ns === namespace);
105
- if (descriptor === void 0) return void 0;
106
- const user = descriptor.user;
107
- if (typeof user !== "object" || user === null) return void 0;
108
- const mode = user.footer;
109
- return typeof mode === "string" ? mode : void 0;
110
- }
111
- /**
112
- * Resolve the USER layer's declared custom layout (PR D activation trust):
113
- * the layout whose refs MAY authorize custom command items — but only
114
- * while the USER layer itself declares footer: custom (see
115
- * resolveUserCommandItemActivationIds). A project can supply a MERGED
116
- * `footerLayout` for rendering, but it can never activate a dormant USER
117
- * command — the same principle as the command-mode gate above: the user
118
- * layer must own the layout that decides what executes.
119
- * @returns the validated USER-layer layout, or undefined when absent or
120
- * invalid (an invalid user layout authorizes nothing — fail-safe).
121
- */
122
- function resolveUserLayerFooterLayout(descriptors, namespace) {
123
- if (descriptors === void 0) return void 0;
124
- const descriptor = descriptors.find((entry) => entry.ns === namespace);
125
- if (descriptor === void 0) return void 0;
126
- const user = descriptor.user;
127
- if (typeof user !== "object" || user === null) return void 0;
128
- const layout = user.footerLayout;
129
- const parsed = parseFooterLayout(layout);
130
- return isFooterLayout(parsed) ? parsed : void 0;
131
- }
132
- /**
133
- * Resolve the USER layer's declared footerFallbackMode (the native mode
134
- * the user's own command-mode fallback restores).
135
- */
136
- function resolveUserLayerFooterFallbackMode(descriptors, namespace) {
137
- if (descriptors === void 0) return void 0;
138
- const descriptor = descriptors.find((entry) => entry.ns === namespace);
139
- if (descriptor === void 0) return void 0;
140
- const user = descriptor.user;
141
- if (typeof user !== "object" || user === null) return void 0;
142
- const mode = user.footerFallbackMode;
143
- return typeof mode === "string" ? mode : void 0;
144
- }
145
- /** The shared empty authorization set. */
146
- const EMPTY_IDS = /* @__PURE__ */ new Set();
147
- /** Every item id a layout references (the authorization projection). */
148
- function layoutRefIds(layout) {
149
- const ids = /* @__PURE__ */ new Set();
150
- for (const row of layout.rows) {
151
- for (const ref of row.left) ids.add(ref.id);
152
- for (const ref of row.right) ids.add(ref.id);
153
- }
154
- return ids;
155
- }
156
- /**
157
- * The ids the USER layer AUTHORIZES for custom command item execution
158
- * (PR D activation trust, mode-gated): the USER custom layout's refs, but
159
- * ONLY while the USER layer itself declares `footer: custom`. A stale
160
- * leftover layout under `footer: default/compact` (the /settings switch
161
- * deliberately keeps the old layout) authorizes NOTHING — a project
162
- * flipping the MERGED mode to custom can never resurrect a dormant USER
163
- * command. `footer: command` authorizes nothing while the whole-footer
164
- * command surface runs (the caller suspends per-item runners); the native
165
- * fallback case uses resolveUserCommandItemFallbackActivationIds.
166
- */
167
- function resolveUserCommandItemActivationIds(descriptors, namespace) {
168
- if (resolveUserLayerFooterMode(descriptors, namespace) !== "custom") return EMPTY_IDS;
169
- const layout = resolveUserLayerFooterLayout(descriptors, namespace);
170
- return layout === void 0 ? EMPTY_IDS : layoutRefIds(layout);
171
- }
172
- /**
173
- * The ids authorized for the native FALLBACK surface (a merged
174
- * `footer: command` the USER layer does not own). The FULL semantic is
175
- * encoded HERE so no caller can forget the outer mode gate:
176
- *
177
- * USER footer === 'command'
178
- * && USER footerFallbackMode === 'custom'
179
- * && valid USER footerLayout
180
- * → the layout's refs
181
- * otherwise → empty
182
- *
183
- * A USER who never opted into command mode (footer: default/compact)
184
- * authorizes NOTHING even with stale fallback metadata; a PROJECT
185
- * forcing the merged command mode can never turn it into execution
186
- * authorization.
187
- */
188
- function resolveUserCommandItemFallbackActivationIds(descriptors, namespace) {
189
- if (resolveUserLayerFooterMode(descriptors, namespace) !== "command") return EMPTY_IDS;
190
- if (resolveUserLayerFooterFallbackMode(descriptors, namespace) !== "custom") return EMPTY_IDS;
191
- const layout = resolveUserLayerFooterLayout(descriptors, namespace);
192
- return layout === void 0 ? EMPTY_IDS : layoutRefIds(layout);
193
- }
194
- //#endregion
195
- //#region src/domain/footer/custom-items.ts
196
- /**
197
- * User-owned custom footer item definitions (PR C + PR D), neutral half
198
- * (TS5 §13.3): the persisted raw settings shapes, their validation and
199
- * normalization, and the config-effective values. Custom definitions are
200
- * persisted separately from FooterLayoutV1: the layout stores only the
201
- * canonical `user:*` reference, while this module owns what that item IS.
202
- * The presentation compilation (FooterItemDefinition / runtime catalog) lives
203
- * in `tui/footer/custom-item-catalog.ts`.
204
- * @module @xmoon76/dsh-pi-tui/domain/footer/custom-items
205
- */
206
- /** The namespace reserved for user-created definitions. */
207
- const CUSTOM_FOOTER_ITEM_PREFIX = "user:";
208
- /** The default refresh interval for a custom command item (PR D §5.2):
209
- * several command items can coexist, so the default must not spawn one
210
- * process per item per second (the whole-footer M5 default is 1s). */
211
- const DEFAULT_CUSTOM_COMMAND_REFRESH_MS = 5e3;
212
- const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/u;
213
- const TONES = /* @__PURE__ */ new Set([
214
- "primary",
215
- "accent",
216
- "text",
217
- "textStrong",
218
- "textDim",
219
- "textMuted",
220
- "border",
221
- "success",
222
- "warning",
223
- "error",
224
- "roleUser",
225
- "shellMode"
226
- ]);
227
- /** The EXACT key set a v1 text definition may carry. A known-kind object
228
- * with any OTHER key is forward-compatible raw data (plan §12.1 — an
229
- * "unknown field object" keeps its raw slot): a future client's field must
230
- * never be silently normalized away by an unrelated save. */
231
- const TEXT_ITEM_KEYS = /* @__PURE__ */ new Set([
232
- "schemaVersion",
233
- "id",
234
- "kind",
235
- "text",
236
- "tone"
237
- ]);
238
- /** The EXACT key set a v1 command definition may carry (same rule). */
239
- const COMMAND_ITEM_KEYS = /* @__PURE__ */ new Set([
240
- "schemaVersion",
241
- "id",
242
- "kind",
243
- "command",
244
- "refreshIntervalMs",
245
- "timeoutMs",
246
- "tone"
247
- ]);
248
- /** Whether the raw object carries a key outside the allowed v1 set. */
249
- function hasUnknownKeys(raw, allowed) {
250
- for (const key of Object.keys(raw)) if (!allowed.has(key)) return true;
251
- return false;
252
- }
253
- /** The validated runner config for one command definition (maxRows is
254
- * always 1 — a custom command item is exactly one line; the composer owns
255
- * width/truncation). The custom-item DEFAULT refresh is 5s (several items
256
- * can coexist — the whole-footer 1s default would spawn a process per
257
- * item per second), so an ABSENT refreshIntervalMs is projected to the
258
- * custom default BEFORE the shared parser runs: an absent default and an
259
- * explicit 5s must produce the SAME cadence. The parser already validated
260
- * the definition, so this is defensive. This is the ONE projection both
261
- * the runtime and the effective-value helpers consume, so the UI, the
262
- * dirty comparator and the real execution can never drift apart. */
263
- function customCommandConfigOf(item) {
264
- return parseFooterCommandConfig({
265
- schemaVersion: 1,
266
- command: item.command,
267
- timeoutMs: item.timeoutMs,
268
- refreshIntervalMs: item.refreshIntervalMs ?? 5e3,
269
- maxRows: 1
270
- });
271
- }
272
- /** The effective refresh interval of a command definition (absent = the
273
- * 5s default). Dirty comparison and the runtime use the EFFECTIVE value so
274
- * an absent default and an explicit default are the same fact. The value
275
- * is the SAME normalized value the runner executes (the shared parser
276
- * clamps refresh to >= 1s): a hand-edited out-of-range raw value is
277
- * preserved in storage for forward compatibility, but the UI and the
278
- * dirty comparator never lie about the real cadence. */
279
- function effectiveCustomCommandRefreshMs(item) {
280
- return customCommandConfigOf(item)?.refreshIntervalMs ?? 5e3;
281
- }
282
- /** The effective timeout of a command definition (absent = the whole-footer
283
- * 300ms default; the shared parser clamps to 1..1000ms — the UI reports
284
- * the same value the runner enforces). */
285
- function effectiveCustomCommandTimeoutMs(item) {
286
- return customCommandConfigOf(item)?.timeoutMs ?? 300;
287
- }
288
- function codePointLength(text) {
289
- return [...text].length;
290
- }
291
- /** Normalize the name typed by the user and return undefined for a name that
292
- * cannot form a stable user namespace id. Colons are reserved so a user name
293
- * cannot impersonate another canonical namespace such as `ext:*`. */
294
- function normalizeCustomItemName(input) {
295
- const name = input.trim();
296
- if (name === "" || CONTROL_CHARS.test(name)) return void 0;
297
- if (name.includes(":")) return void 0;
298
- if (codePointLength(name) > 64) return void 0;
299
- return name;
300
- }
301
- /** Convert a user-facing name to the deterministic persisted id. */
302
- function customItemId(name) {
303
- const normalized = normalizeCustomItemName(name);
304
- return normalized === void 0 ? void 0 : `${CUSTOM_FOOTER_ITEM_PREFIX}${normalized}`;
305
- }
306
- /** Return the user-facing part of a canonical id. */
307
- function customItemName(id) {
308
- return id.startsWith("user:") ? id.slice(5) : id;
309
- }
310
- function isTone(value) {
311
- return value === "auto" || typeof value === "string" && TONES.has(value);
312
- }
313
- /** Parse one persisted definition. Invalid definitions are rejected at this
314
- * boundary; callers can keep the rest of the collection. */
315
- function parseFooterCustomItem(input) {
316
- try {
317
- if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
318
- const raw = input;
319
- if (raw.schemaVersion !== 1) return void 0;
320
- if (typeof raw.id !== "string" || customItemId(customItemName(raw.id)) !== raw.id) return void 0;
321
- if (raw.tone !== void 0 && !isTone(raw.tone)) return void 0;
322
- const tone = raw.tone === void 0 ? void 0 : raw.tone;
323
- if (raw.kind === "text") {
324
- if (hasUnknownKeys(raw, TEXT_ITEM_KEYS)) return void 0;
325
- if (typeof raw.text !== "string" || raw.text.trim() === "" || CONTROL_CHARS.test(raw.text)) return void 0;
326
- if (codePointLength(raw.text) > 256) return void 0;
327
- return {
328
- schemaVersion: 1,
329
- id: raw.id,
330
- kind: "text",
331
- text: raw.text,
332
- ...tone === void 0 ? {} : { tone }
333
- };
334
- }
335
- if (raw.kind === "command") {
336
- if (hasUnknownKeys(raw, COMMAND_ITEM_KEYS)) return void 0;
337
- const refresh = typeof raw.refreshIntervalMs === "number" && Number.isFinite(raw.refreshIntervalMs) ? raw.refreshIntervalMs : void 0;
338
- const timeout = typeof raw.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? raw.timeoutMs : void 0;
339
- const config = parseFooterCommandConfig({
340
- schemaVersion: 1,
341
- command: raw.command,
342
- timeoutMs: timeout,
343
- refreshIntervalMs: refresh,
344
- maxRows: 1
345
- });
346
- if (config === void 0) return void 0;
347
- const command = config.command;
348
- return {
349
- schemaVersion: 1,
350
- id: raw.id,
351
- kind: "command",
352
- command,
353
- ...refresh === void 0 ? {} : { refreshIntervalMs: refresh },
354
- ...timeout === void 0 ? {} : { timeoutMs: timeout },
355
- ...tone === void 0 ? {} : { tone }
356
- };
357
- }
358
- return;
359
- } catch {
360
- return;
361
- }
362
- }
363
- /** Parse the collection without letting one malformed or duplicate entry
364
- * break startup. The first definition for an id wins deterministically. A
365
- * hostile collection-level proxy/iterator fails closed as one invalid
366
- * collection instead of escaping into startup or reload. */
367
- function parseFooterCustomItems(input) {
368
- try {
369
- if (input === void 0) return {
370
- items: [],
371
- invalidCount: 0
372
- };
373
- if (!Array.isArray(input)) return {
374
- items: [],
375
- invalidCount: 1
376
- };
377
- const items = [];
378
- const ids = /* @__PURE__ */ new Set();
379
- let invalidCount = 0;
380
- for (const candidate of input) {
381
- const item = parseFooterCustomItem(candidate);
382
- if (item === void 0 || ids.has(item.id)) {
383
- invalidCount += 1;
384
- continue;
385
- }
386
- ids.add(item.id);
387
- items.push(item);
388
- }
389
- return {
390
- items,
391
- invalidCount
392
- };
393
- } catch {
394
- return {
395
- items: [],
396
- invalidCount: 1
397
- };
398
- }
399
- }
400
- /** Every item id a layout references (the authorization / active-set
401
- * projection). An absent layout activates nothing. */
402
- function activeFooterItemIds(layout) {
403
- const ids = /* @__PURE__ */ new Set();
404
- if (layout === void 0) return ids;
405
- for (const row of layout.rows) {
406
- for (const ref of row.left) ids.add(ref.id);
407
- for (const ref of row.right) ids.add(ref.id);
408
- }
409
- return ids;
410
- }
411
- /** The EXECUTABLE command item ids (PR D activation trust, final formula):
412
- *
413
- * executable = USER trusted definitions ∩ USER-authorized ids ∩
414
- * currently rendered layout ids
415
- *
416
- * The trusted definitions come from the USER-layer semantic read; the
417
- * authorized ids come from the ConfigPort's mode-gated projection (a stale
418
- * leftover USER layout under footer: default/compact authorizes nothing); the
419
- * rendered layout is what the composer actually shows — a command hidden by
420
- * the merged layout must not keep running in the background. A /footer save is
421
- * the special case where the just-committed validated layout is both
422
- * authorized and rendered. */
423
- function executableCommandItemIds(trustedCommands, authorizedIds, renderedLayout) {
424
- const trustedIds = new Set(trustedCommands.map((item) => item.id));
425
- const renderedIds = activeFooterItemIds(renderedLayout);
426
- const executable = /* @__PURE__ */ new Set();
427
- for (const id of renderedIds) if (trustedIds.has(id) && authorizedIds.has(id)) executable.add(id);
428
- return executable;
429
- }
430
- /** Escape regex metacharacters for a finder's regex pattern: the completion
431
- * term is a LITERAL substring (the scoring model's input), so a filename
432
- * containing `[`, `+`, `.` etc. must match as literal text, never as a regex.
433
- * Both locality adapters pass the escaped term. */
434
- function escapeFinderRegex(term) {
435
- return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
436
- }
437
- /**
438
- * Normalize one finder's stdout into detached records: NUL records when the
439
- * finder honoured `--print0` (so legal filenames containing newlines survive),
440
- * the newline fallback for a fake/older finder (preserving meaningful leading
441
- * and trailing spaces in a filename), the `./` prefix strip, the directory
442
- * hint and the `.git` exclusion. PURE — operates solely on detached strings.
443
- */
444
- function normalizeFinderRecords(stdout) {
445
- const records = stdout.includes("\0") ? stdout.split("\0").filter((record) => record !== "") : (() => {
446
- const lines = stdout.split(/\r?\n/);
447
- if (lines.at(-1) === "") lines.pop();
448
- return lines.filter((line) => line !== "");
449
- })();
450
- const out = [];
451
- for (const line of records) {
452
- const relative = line.startsWith("./") ? line.slice(2) : line;
453
- if (relative === ".git" || relative.startsWith(".git/") || relative.includes("/.git/")) continue;
454
- out.push({
455
- path: relative.endsWith("/") ? relative.slice(0, -1) : relative,
456
- directoryHint: relative.endsWith("/")
457
- });
458
- }
459
- return out;
460
- }
461
- /**
462
- * The bounded recursive scan of one directory's SUBTREE: the root's direct
463
- * children are always complete (a root-level `src/` must be found), deeper
464
- * entries are capped at {@link MAX_FALLBACK_SCAN}. Paths are relative to
465
- * `baseDir` (`sub/deep.ts`); `.git` is skipped (kimi parity); a symlinked
466
- * directory is NEVER descended — at the search root and below it alike
467
- * (cycle safety), so a link to a parent directory or to the workspace's
468
- * outside cannot widen the scan or consume the traversal budget.
469
- *
470
- * ASYNC: the fuzzy fallback runs on the EDITOR path, so a synchronous
471
- * whole-tree traversal would block the editor's event loop per keystroke. The
472
- * scan yields to the event loop between directory levels and checks the
473
- * AbortSignal inside the loop — the editor stays responsive and a cancelled
474
- * request stops the traversal promptly.
475
- */
476
- async function scanSubtree(baseDir, driver, signal) {
477
- const candidates = [];
478
- const firstEntries = await driver.listDirectory(baseDir, "", signal);
479
- if (signal.aborted || firstEntries === null) return [];
480
- const stack = [];
481
- for (const entry of firstEntries) {
482
- if (entry.name === ".git") continue;
483
- candidates.push({
484
- path: entry.name,
485
- kind: entry.kind
486
- });
487
- if (entry.descendable) stack.push(entry.name);
488
- }
489
- let scanned = 0;
490
- while (stack.length > 0 && scanned < 2e3) {
491
- if (signal.aborted) break;
492
- const relativeDir = stack.pop() ?? "";
493
- const entries = await driver.listDirectory(baseDir, relativeDir, signal);
494
- if (entries === null) continue;
495
- for (const entry of entries) {
496
- if (signal.aborted || scanned >= 2e3) break;
497
- if (entry.name === ".git") continue;
498
- const path = `${relativeDir}/${entry.name}`;
499
- scanned += 1;
500
- candidates.push({
501
- path,
502
- kind: entry.kind
503
- });
504
- if (entry.kind === "directory" && entry.descendable) stack.push(path);
505
- }
506
- if (stack.length > 0) await new Promise((resolve) => setImmediate(resolve));
507
- }
508
- return signal.aborted ? [] : candidates;
509
- }
510
- /** Map one driver listing into path candidates, dropping `.git` (a `@` or
511
- * `/image` listing never presents VCS internals). PURE. */
512
- function listingCandidates(entries) {
513
- return entries.filter((entry) => entry.name !== ".git").map((entry) => ({
514
- path: entry.name,
515
- kind: entry.kind
516
- }));
517
- }
518
- /**
519
- * Answer one resolved query with discovery facts: a scoped LISTING (empty
520
- * term) reads the target directory's direct children; a scoped or whole-tree
521
- * FUZZY query uses the locality finder when available and the bounded subtree
522
- * scan otherwise. Paths are relative to the QUERY's search base.
523
- * @param query - the resolved path query (searchBase already absolute).
524
- * @param driver - the locality's discovery boundary.
525
- * @param signal - the editor's request abort.
526
- */
527
- async function discoverForQuery(query, driver, signal) {
528
- if (query.explicitScope && query.searchTerm === "") {
529
- if (signal.aborted) return [];
530
- const direct = await driver.listDirectory(query.searchBase, "", signal);
531
- if (signal.aborted || direct === null) return [];
532
- return listingCandidates(direct);
533
- }
534
- if (!query.winAbsolute && !query.raw.includes("\\")) {
535
- const found = await driver.find(query.searchBase, query.searchTerm, signal);
536
- if (signal.aborted) return [];
537
- if (found !== null) {
538
- const seen = new Set(found.map((candidate) => candidate.path));
539
- const lowerTerm = query.searchTerm.toLowerCase();
540
- const direct = await driver.listDirectory(query.searchBase, "", signal);
541
- if (signal.aborted) return [];
542
- const merged = (direct === null ? [] : listingCandidates(direct)).filter((candidate) => lowerTerm === "" || candidate.path.toLowerCase().includes(lowerTerm)).filter((candidate) => !seen.has(candidate.path));
543
- return [...found, ...merged];
544
- }
545
- }
546
- return scanSubtree(query.searchBase, driver, signal);
547
- }
548
- //#endregion
549
- //#region src/domain/file-completion/query.ts
550
- /**
551
- * The neutral path query resolver (TS8-A, split out of the historical
552
- * `src/file-completion/query.ts`): PURE — turns a raw token into the search
553
- * directory, the basename term, the display prefix and whether the token
554
- * names an EXPLICIT scope. No filesystem access, and no environment
555
- * discovery: the facts this algebra needs arrive from the LOCALITY owner as
556
- * an explicit {@link PathQueryEnvironment}, never from `homedir()` /
557
- * `process.platform` inside the domain layer.
558
- *
559
- * A scoped token (`src/fo`, `../foo`, `../../foo`, `~/foo`, `/tmp/foo`,
560
- * a drive-qualified path, or an UNC path) searches ONLY its resolved
561
- * directory — never a whole-tree scan filtered by string. An unscoped token
562
- * (`foo`, `nested`, `config`) is a whole-tree fuzzy query with an EMPTY
563
- * display base.
564
- * @module @xmoon76/dsh-pi-tui/domain/file-completion/query
565
- */
566
- /**
567
- * The HOST filesystem's path algebra, selected from the EXPLICIT
568
- * `windowsHost` fact. Every host-native path this module computes (a joined
569
- * scope, an expanded `~`) goes through this api, so the domain never infers
570
- * the running machine from the ambient `node:path` default export: a caller
571
- * that injects a foreign host's facts gets that host's algebra.
572
- */
573
- function hostPathApi(windowsHost) {
574
- return windowsHost ? win32 : posix;
575
- }
576
- /**
577
- * Return the final path component without depending on the host OS dialect.
578
- * Completion can present a Windows path while the client process is running
579
- * on POSIX (and vice versa), so `node:path.basename` is not sufficient here.
580
- */
581
- function basenameOfPath(path) {
582
- const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
583
- return path.slice(separator + 1);
584
- }
585
- /**
586
- * Expand a leading `~` in one token against the locality's home directory
587
- * (other tokens unchanged). PURE — both the home directory AND the host
588
- * platform are explicit facts: the joined result is a path on the HOST
589
- * filesystem, so it uses that host's algebra.
590
- * @param token - the raw token.
591
- * @param homeDir - the locality owner's home directory fact.
592
- * @param windowsHost - whether the filesystem host is Windows.
593
- */
594
- function expandHomeToken(token, homeDir, windowsHost) {
595
- if (token === "~") return homeDir;
596
- if (token.startsWith("~/") || token.startsWith("~\\")) return hostPathApi(windowsHost).join(homeDir, token.slice(2).replace(/\\/g, "/"));
597
- return token;
598
- }
599
- /**
600
- * Choose the separator immediately before the basename. This preserves a
601
- * mixed Windows token's actual dialect (forward-slash drive paths stay
602
- * forward-slashed, while backslash drive paths stay backslashed) instead of
603
- * normalizing it to the host platform's preferred separator.
604
- */
605
- function separatorOfRaw(raw, windowsDialect) {
606
- const slash = raw.lastIndexOf("/");
607
- const backslash = raw.lastIndexOf("\\");
608
- if (slash === -1 && backslash === -1) return windowsDialect ? "\\" : "/";
609
- return backslash > slash ? "\\" : "/";
610
- }
611
- /** Whether the token is a leading-home form, including `~\\foo`. */
612
- function isHomeToken$1(raw) {
613
- return raw === "~" || raw.startsWith("~/") || raw.startsWith("~\\");
614
- }
615
- /** Whether one raw token is genuinely Windows-dialect. */
616
- function isWindowsDialect(raw, winAbsolute) {
617
- return winAbsolute || raw.includes("\\");
618
- }
619
- /** Whether an absolute path uses the Windows drive/UNC grammar. */
620
- function isWindowsAbsolute(raw) {
621
- return !raw.startsWith("/") && win32.isAbsolute(raw);
622
- }
623
- /** Join a relative scope while keeping POSIX fixtures usable for a
624
- * Windows-looking token. The result is a path on the HOST filesystem, so the
625
- * joiner comes from the EXPLICIT host fact (never `process.platform`); the
626
- * TOKEN's own dialect only decides whether backslashes are the user's
627
- * separators or ordinary characters.
628
- *
629
- * A `windowsDialect` token on a POSIX host has backslashes in the USER'S
630
- * dialect, not as filesystem separators, so they are normalized; an
631
- * unmistakable drive/UNC `cwd` selects the win32 joiner even on a POSIX host
632
- * (that cwd string is itself a Windows path). */
633
- function joinRelativeScope(cwd, rawPath, windowsDialect, windowsHost) {
634
- const api = hostPathApi(windowsHost);
635
- if (!windowsDialect) return api.join(cwd, rawPath);
636
- const windowsCwd = /^[A-Za-z]:[\\/]/.test(cwd) || cwd.startsWith("\\\\");
637
- if (windowsHost || windowsCwd) return win32.join(cwd, rawPath);
638
- return api.join(cwd, rawPath.replace(/\\/g, "/"));
639
- }
640
- /** Whether the raw token names a directory that should be LISTED
641
- * (`searchTerm === ''`). `.`/`..` root forms list their own relative
642
- * directory; `./`/`../`/`~`/`/` list the scope root. */
643
- function isBareScopeForm(raw) {
644
- return raw === "" || raw === "." || raw === ".." || raw === "./" || raw === "../" || raw === "~" || raw === "~/" || raw === "~\\" || raw === "/" || raw === ".\\" || raw === "..\\";
645
- }
646
- /**
647
- * Resolve ONE raw completion token into the pure path query.
648
- * @param raw - the token as typed (quotes stripped; leading separator
649
- * whitespace stripped by the caller).
650
- * @param cwd - the completion base (the Client cwd for local completion, the
651
- * Direct workspace cwd for the WORKSPACE compatibility scanner; relative
652
- * forms resolve against it).
653
- * @param environment - the locality owner's explicit environment facts.
654
- */
655
- function resolvePathQuery(raw, cwd, environment) {
656
- const expanded = expandHomeToken(raw, environment.homeDir, environment.windowsHost);
657
- const posixAbsolute = raw.startsWith("/");
658
- const winAbsolute = isWindowsAbsolute(raw);
659
- const windowsDialect = isWindowsDialect(raw, winAbsolute);
660
- const absolute = isHomeToken$1(raw) || posixAbsolute || winAbsolute;
661
- const tokenWindows = windowsDialect || environment.windowsHost;
662
- const pathDirname = tokenWindows ? win32.dirname : posix.dirname;
663
- const pathBasename = tokenWindows ? win32.basename : posix.basename;
664
- const separator = separatorOfRaw(raw, windowsDialect);
665
- if (isBareScopeForm(raw)) return {
666
- raw,
667
- searchBase: raw === "." || raw === ".." || raw === "./" || raw === "../" || raw === ".\\" || raw === "..\\" ? joinRelativeScope(cwd, raw, windowsDialect, environment.windowsHost) : absolute ? expanded : joinRelativeScope(cwd, expanded, windowsDialect, environment.windowsHost),
668
- searchTerm: "",
669
- displayBase: raw === "" ? "" : raw === "~" ? `~${separator}` : raw.endsWith("/") || raw.endsWith("\\") ? raw : `${raw}${separator}`,
670
- explicitScope: true,
671
- winAbsolute
672
- };
673
- if (raw.endsWith("/") || raw.endsWith("\\")) return {
674
- raw,
675
- searchBase: absolute ? expanded : joinRelativeScope(cwd, expanded, windowsDialect, environment.windowsHost),
676
- searchTerm: "",
677
- displayBase: raw,
678
- explicitScope: true,
679
- winAbsolute
680
- };
681
- const lastSlash = Math.max(raw.lastIndexOf("/"), raw.lastIndexOf("\\"));
682
- const hasSeparator = lastSlash >= 0;
683
- const displayBase = hasSeparator ? raw.slice(0, lastSlash + 1) : "";
684
- const rawDir = hasSeparator ? raw.slice(0, lastSlash) : "";
685
- const searchTerm = pathBasename(expanded);
686
- const explicitScope = hasSeparator || absolute;
687
- const searchBaseForScope = isHomeToken$1(raw) ? expandHomeToken(rawDir, environment.homeDir, environment.windowsHost) : absolute ? pathDirname(expanded) : joinRelativeScope(cwd, rawDir, windowsDialect, environment.windowsHost);
688
- return {
689
- raw,
690
- searchBase: explicitScope ? searchBaseForScope : cwd,
691
- searchTerm,
692
- displayBase,
693
- explicitScope,
694
- winAbsolute
695
- };
696
- }
697
- /**
698
- * Reattach the query's display base onto one discovered candidate path.
699
- * Discovery returns paths RELATIVE to the query's search base; the candidate
700
- * the user accepts must read in the USER'S dialect (`../sibling-file.ts`,
701
- * `~/pics/a.png`, `src/deep.ts`, `/tmp/x`). The SOURCE calls this before its
702
- * candidates cross the port contract (the port's paths are user-facing).
703
- * PURE.
704
- */
705
- function reattachDisplayBase(candidate, query) {
706
- if (query.displayBase === "") return candidate;
707
- return {
708
- ...candidate,
709
- path: `${query.displayBase}${candidate.path}`
710
- };
711
- }
712
- /** Score one candidate against the query term (lowercased). */
713
- function scorePathCandidate(candidate, lowerQuery) {
714
- if (lowerQuery === "") {
715
- const depthPenalty = candidate.path.split(/[\\/]/).length - 1;
716
- return (candidate.kind === "directory" ? 120 : 100) - depthPenalty;
717
- }
718
- const lowerPath = candidate.path.toLowerCase();
719
- const lowerBase = basenameOfPath(candidate.path).toLowerCase();
720
- let score = 0;
721
- if (lowerBase === lowerQuery) score = 100;
722
- else if (lowerBase.startsWith(lowerQuery)) score = 80;
723
- else if (lowerBase.includes(lowerQuery)) score = 50;
724
- else if (lowerPath.includes(lowerQuery)) score = 30;
725
- if (candidate.kind === "directory" && score > 0) score += 10;
726
- return score;
727
- }
728
- /** Deterministic order: score desc, directories (kind) first, path asc. */
729
- function compareScoredPaths(left, right) {
730
- if (left.score !== right.score) return right.score - left.score;
731
- if (left.candidate.kind !== right.candidate.kind) return left.candidate.kind === "directory" ? -1 : 1;
732
- return left.candidate.path.localeCompare(right.candidate.path);
733
- }
734
- /**
735
- * Rank, filter and bound one discovery set (the local scoring model — the
736
- * SOURCE's own order for its Client-fs / Direct-workspace-compat consumers,
737
- * NOT the live Session `@` mention path, whose ranking is the official Host
738
- * authority's). PURE: path candidates in, ranked path candidates out — no UI
739
- * DTOs, so a semantic adapter can own its ranking end-to-end.
740
- */
741
- function rankPathCandidates(candidates, term) {
742
- const lowerQuery = term.toLowerCase();
743
- return candidates.map((candidate) => ({
744
- candidate,
745
- score: scorePathCandidate(candidate, lowerQuery)
746
- })).filter((entry) => entry.score > 0).sort(compareScoredPaths).slice(0, 50).map((entry) => entry.candidate);
747
- }
748
- //#endregion
749
- //#region src/runtime/read-error.ts
750
- /**
751
- * A typed semantic READ failure: the read was superseded by a connection or
752
- * surface change, so its result must not be presented as the current Host
753
- * state. Remote adapters throw this instead of a generic Error so a consumer
754
- * can stay UI-silent (v2 §0.2.3/§0.3.1) rather than surfacing a stale failure.
755
- * Host-free; no I/O.
756
- * @module @xmoon76/dsh-pi-tui/read-error
757
- */
758
- /** The read no longer owns the surface (generation change or superseded epoch). */
759
- var SupersededReadError = class extends Error {
760
- reason;
761
- constructor(reason) {
762
- super(reason);
763
- this.name = "SupersededReadError";
764
- this.reason = reason;
765
- }
766
- };
767
- //#endregion
768
- //#region src/domain/catalog/provider.ts
769
- /**
770
- * Read a value at a dotted path inside a plain object (the web schema-form
771
- * `getPath` semantics, structural here so /login needs no schema package).
772
- * @param value - the object to walk.
773
- * @param path - path segments; the empty path returns `value` itself.
774
- * @returns the value at the path, or undefined when any segment is missing.
775
- */
776
- function getPath(value, path) {
777
- let current = value;
778
- for (const key of path) {
779
- if (Array.isArray(current)) {
780
- current = current[Number(key)];
781
- continue;
782
- }
783
- if (typeof current !== "object" || current === null) return void 0;
784
- current = current[key];
785
- }
786
- return current;
787
- }
788
- /**
789
- * Derive the conventional credential reference for a provider route: the web
790
- * Models page never asks for an environment-variable name, so a typed key
791
- * stores under this derived reference and the profile records it as
792
- * `apiKeyEnv`. Kept byte-identical to the web's `deriveKeyRef`.
793
- * @param provider - provider route id (e.g. `anthropic`, `minimax-cn`).
794
- * @returns the derived reference name (e.g. `MINIMAX_CN_API_KEY`).
795
- */
796
- function deriveKeyRef(provider) {
797
- return `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
798
- }
799
- /**
800
- * A route id usable as a settings key AND as the stem of a credential name.
801
- * The web create card's pattern: the leading letter is the second half of
802
- * that — `deriveKeyRef` uppercases the id and replaces every non-alphanumeric
803
- * run with `_`, and a credential reference is a POSIX shell identifier, which
804
- * cannot start with a digit. A digit-leading id passes every check this card
805
- * makes and then fails at the credential seam with a raw regular expression
806
- * the user cannot act on.
807
- */
808
- const ROUTE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
809
- /** The wire protocols a hand-declared route may name. Mirrors the pi-ai
810
- * adapter's `supportedProtocols()`; keep in step with
811
- * `@deepseek-ai/dsh-llm-pi-ai`'s `PROTOCOLS` table (the drift gate is the
812
- * adapter's own — a protocol it stops serving must be removed here too). */
813
- const PROTOCOL_CHOICES = [
814
- "openai-completions",
815
- "openai-responses",
816
- "anthropic-messages"
817
- ];
818
- /**
819
- * Merge the configurable-provider directory with the existing settings
820
- * section into the /login option list.
821
- *
822
- * @param entries - the llm directory entries (or undefined when the llm
823
- * service is absent — degrades to the official target only).
824
- * @param readSection - read one settings namespace's resolved section (the
825
- * settings service's `get`); absent namespaces read as undefined.
826
- * @returns the merged options, deepseek official first, deduped by ref.
827
- */
828
- function providerOptionsFor(entries, readSection) {
829
- const options = [];
830
- const seen = /* @__PURE__ */ new Set();
831
- const push = (option) => {
832
- if (seen.has(option.ref)) return;
833
- seen.add(option.ref);
834
- options.push(option);
835
- };
836
- push({
837
- label: "deepseek official",
838
- ref: "DEEPSEEK_API_KEY",
839
- route: "deepseek-official",
840
- configured: true,
841
- declared: false,
842
- namesCredential: true,
843
- group: "configured",
844
- settingsNs: "",
845
- settingsPath: []
846
- });
847
- if (entries === void 0) return options;
848
- for (const entry of entries) {
849
- if (entry.provider.length === 0 || entry.settingsNs.length === 0) continue;
850
- const section = readSection(entry.settingsNs);
851
- const profile = entry.settingsPath.length === 0 ? section : getPath(section, entry.settingsPath);
852
- const configured = profile !== void 0;
853
- const namedRef = configured && typeof profile === "object" && profile !== null && typeof profile.apiKeyEnv === "string" ? profile.apiKeyEnv : void 0;
854
- const namesCredential = namedRef !== void 0 && namedRef !== "";
855
- const ref = namesCredential ? namedRef : deriveKeyRef(entry.provider);
856
- push({
857
- label: entry.displayName,
858
- ref,
859
- route: entry.provider,
860
- configured,
861
- declared: entry.declared === true,
862
- namesCredential,
863
- group: configured ? "configured" : entry.declared === true ? "custom" : "available",
864
- settingsNs: entry.settingsNs,
865
- settingsPath: [...entry.settingsPath]
866
- });
867
- }
868
- return options;
869
- }
870
- /** The credential-target options for /login and /logout: the deepseek
871
- * official ref always first, then every llm-pi-ai provider route's
872
- * apiKeyEnv (deduped by ref). `providers` is the llm-pi-ai settings
873
- * section's `providers` dict, or undefined when the adapter or the settings
874
- * service is absent — which degrades /login to the official target only.
875
- * Kept as the settings-only fallback when the llm directory is absent. */
876
- function credentialOptionsFor(providers) {
877
- const options = [{
878
- label: "deepseek official",
879
- ref: "DEEPSEEK_API_KEY"
880
- }];
881
- if (providers === void 0) return options;
882
- const seen = new Set(options.map((option) => option.ref));
883
- for (const [route, profile] of Object.entries(providers)) {
884
- const ref = profile?.apiKeyEnv;
885
- if (ref === void 0 || ref === "" || seen.has(ref)) continue;
886
- seen.add(ref);
887
- options.push({
888
- label: route,
889
- ref
890
- });
891
- }
892
- return options;
893
- }
894
- /** Resolve a /login or /logout argument to a credential ref. A
895
- * case-insensitive llm-pi-ai route name wins, then a literal env-var-looking
896
- * name (any casing, uppercased like the old behavior — `/login my_key` sets
897
- * `MY_KEY`); anything else is unknown and returns undefined so the caller
898
- * can list the valid options. */
899
- function resolveCredentialArg(arg, options) {
900
- const trimmed = arg.trim();
901
- if (trimmed === "") return void 0;
902
- const needle = trimmed.toLowerCase();
903
- const route = options.find((option) => option.label.toLowerCase() === needle || option.label.split(" ")[0].toLowerCase() === needle);
904
- if (route !== void 0) return route.ref;
905
- if (/^[a-zA-Z][a-zA-Z0-9_]*$/.test(trimmed)) return trimmed.toUpperCase();
906
- }
907
- //#endregion
908
- //#region src/runtime/session-lifecycle-port.ts
909
- /** A lifecycle outcome that must ABORT the caller's transition, carrying the
910
- * two independent axes so a Remote caller never has to parse a string. */
911
- var LifecycleError = class extends Error {
912
- settlement;
913
- ownership;
914
- publishedSessionId;
915
- /** CORRELATION ONLY for an indeterminate create — never publication proof. */
916
- requestedSessionId;
917
- constructor(settlement, ownership, message, publishedSessionId, requestedSessionId) {
918
- super(message);
919
- this.name = "LifecycleError";
920
- this.settlement = settlement;
921
- this.ownership = ownership;
922
- this.publishedSessionId = publishedSessionId;
923
- this.requestedSessionId = requestedSessionId;
924
- }
925
- };
926
- /** Unwrap a CREATE result for the runner's transition: a `created` result that
927
- * still owns the surface yields the handle; everything else aborts with a
928
- * machine-readable `LifecycleError` (a superseded create is NOT committed to
929
- * the local surface, though its identity stays available). */
930
- function requireCreated(result) {
931
- const { ownership, outcome } = result;
932
- switch (outcome.kind) {
933
- case "created":
934
- if (ownership === "superseded") throw new LifecycleError("superseded", ownership, `Session "${outcome.handle.session.id}" was created, but the local surface was superseded — do not retry creation`, outcome.handle.session.id);
935
- return outcome.handle;
936
- case "published-with-error": throw new LifecycleError(outcome.kind, ownership, `Session "${outcome.sessionId}" was published, but workspace attach/reconcile failed: ${outcome.error.message} (${outcome.error.code}) — do not retry creation`, outcome.sessionId);
937
- case "indeterminate": throw new LifecycleError(outcome.kind, ownership, `the create is indeterminate — do not retry: ${outcome.error.message} (${outcome.error.code})`, void 0, outcome.requestedSessionId);
938
- case "rejected": throw new LifecycleError(outcome.kind, ownership, `${outcome.error.message} (${outcome.error.code})`, void 0);
939
- case "cancelled": throw new LifecycleError("cancelled", ownership, "the Session creation was cancelled before dispatch", void 0);
940
- }
941
- }
942
- /** Unwrap an OPEN result for the runner's transition. */
943
- function requireOpened(result) {
944
- const { ownership, outcome } = result;
945
- switch (outcome.kind) {
946
- case "opened":
947
- if (ownership === "superseded") throw new LifecycleError("superseded", ownership, "the Session was opened but the local surface was superseded", outcome.handle.session.id);
948
- return outcome.handle;
949
- case "unavailable": throw new LifecycleError("unavailable", ownership, outcome.message, void 0);
950
- case "cancelled": throw new LifecycleError("cancelled", ownership, "the Session open was cancelled before selection", void 0);
951
- }
952
- }
953
- /** Extract the Direct ownership handle (the real AgentHandle with
954
- * `dispose()`) from a lifecycle result. Accepts both the converged
955
- * SessionHandle and a legacy AgentHandle so transition code cannot lose the
956
- * ownership capability. Remote handles lack `direct` and yield undefined. */
957
- function ownerHandleOf(next) {
958
- const handle = next;
959
- if (handle.direct?.ownerHandle !== void 0) return handle.direct.ownerHandle;
960
- if (typeof handle.dispose === "function") return handle;
961
- }
962
- /** Extract the live in-process agent from a lifecycle result (the Direct
963
- * SessionHandle via `direct.agent`, or a legacy AgentHandle's `agent`).
964
- * Remote handles yield undefined. */
965
- function directAgentOf(next) {
966
- const handle = next;
967
- return handle.direct?.agent ?? handle.agent;
968
- }
969
- /** Extract the Remote Client generation owner from a lifecycle result. A
970
- * Direct handle yields undefined. A composing Remote caller must release it
971
- * exactly once on retirement — including when a superseded transition discards
972
- * the handle. The Remote session-owner provider (`app/remote/session-owners.ts`)
973
- * consumes it as the sole ownership mapping source; the Direct runner never
974
- * interprets it. */
975
- function clientOwnerOf(next) {
976
- return next.client;
977
- }
978
- //#endregion
979
- //#region src/runtime/capability.ts
980
- /** The capabilities the experimental Remote backend serves: exactly the
981
- * ports its M3-3B assembly provides. A capability is added HERE only when its
982
- * Remote port genuinely serves the semantic contract (no misleading empty
983
- * defaults), so the set is deliberately explicit rather than derived. */
984
- const REMOTE_IMPLEMENTED_CAPABILITIES = [
985
- "session-read",
986
- "session-write",
987
- "session-lifecycle",
988
- "subagent",
989
- "interaction",
990
- "catalog",
991
- "config",
992
- "host-file",
993
- "session-archive",
994
- "host-command",
995
- "plugin-manager",
996
- "job-observation"
997
- ];
998
- /** The capabilities the Direct backend ACTUALLY serves today: one port per
999
- * entry, nothing more — never advertise what is not served. */
1000
- const DIRECT_IMPLEMENTED_CAPABILITIES = [
1001
- "session-read",
1002
- "session-write",
1003
- "session-lifecycle",
1004
- "subagent",
1005
- "interaction",
1006
- "catalog",
1007
- "config",
1008
- "host-file",
1009
- "session-archive",
1010
- "host-command",
1011
- "plugin-manager",
1012
- "job-observation"
1013
- ];
1014
- //#endregion
1015
- //#region src/runtime/write-outcome.ts
1016
- /**
1017
- * Pinned Gateway infrastructure codes raised strictly BEFORE the addressed
1018
- * business method is invoked (descriptor/argument/receiver/endpoint resolution
1019
- * and context/lookup provider resolution — all inside `prepareInvocation` and
1020
- * boundary decoding): such a failure proves the operation did not commit. The
1021
- * only Gateway code raised AFTER invocation is `gateway/result-invalid`, so it
1022
- * is deliberately absent.
1023
- */
1024
- const GATEWAY_PRE_INVOCATION_CODES = /* @__PURE__ */ new Set([
1025
- "gateway/ambiguous-endpoint",
1026
- "gateway/arguments-invalid",
1027
- "gateway/binding-invalid",
1028
- "gateway/context-failed",
1029
- "gateway/context-not-found",
1030
- "gateway/context-unavailable",
1031
- "gateway/definition-unavailable",
1032
- "gateway/input-invalid",
1033
- "gateway/invocation-unavailable",
1034
- "gateway/lookup-failed",
1035
- "gateway/lookup-not-found",
1036
- "gateway/lookup-unavailable",
1037
- "gateway/method-unavailable",
1038
- "gateway/provider-mismatch",
1039
- "gateway/service-unavailable",
1040
- "gateway/signature-invalid"
1041
- ]);
1042
- /**
1043
- * Whether a failure code PROVES the addressed operation was refused: domain
1044
- * codes, `gateway/bad-request`, and the pinned pre-invocation Gateway
1045
- * infrastructure codes qualify. `gateway/cancelled`, `gateway/internal`,
1046
- * `gateway/result-invalid`, an unknown `gateway/*` code, or a code-less failure
1047
- * do NOT (the commit state stays unproven).
1048
- *
1049
- * SCOPE: this predicate expresses ONLY the D2.2-verified write vocabulary plus
1050
- * the pinned Gateway pre-invocation codes. It is NOT a general
1051
- * idempotency/commit judgement: a domain code does not universally prove that
1052
- * no mutation happened (e.g. `session/workspace-attach-failed` can follow a
1053
- * successful Session create/fork). Later operation families (D2.3/D2.4) must
1054
- * use their own operation-specific settlement table rather than extending this
1055
- * helper.
1056
- */
1057
- function isRemoteBusinessRefusalCode(code) {
1058
- if (code === void 0) return false;
1059
- if (code === "gateway/bad-request") return true;
1060
- if (code.startsWith("gateway/")) return GATEWAY_PRE_INVOCATION_CODES.has(code);
1061
- return true;
1062
- }
1063
- //#endregion
1064
- //#region src/runtime/subagent-outcome.ts
1065
- /**
1066
- * Backend-neutral outcome/error classification for one subagent viewer prompt
1067
- * (TS8-F4): the stable refusal taxonomy shared by the Direct and Remote
1068
- * adapters. Pure and never throwing — it reads structural `code` values only,
1069
- * so the subagent package stays resolvable from the dsh installation and is
1070
- * never imported here.
1071
- * @module @xmoon76/dsh-pi-tui/runtime/subagent-outcome
1072
- */
1073
- /**
1074
- * Settle a failed viewer prompt. A caller cancellation and every PROVEN refusal
1075
- * code are rejected (a domain `subagent/*` admission refusal, `gateway/bad-request`,
1076
- * or a pre-invocation Gateway infrastructure code); only a carrier/internal/
1077
- * post-invocation failure (`gateway/internal`, `gateway/result-invalid`, an
1078
- * unknown `gateway/*` code) or a code-less throw settles `indeterminate`.
1079
- */
1080
- function classifySubagentPromptSettlement(error) {
1081
- const reason = classifySubagentPromptError(error);
1082
- if (reason.kind !== "error") return {
1083
- kind: "rejected",
1084
- reason
1085
- };
1086
- if (isRemoteBusinessRefusalCode(remoteErrorCode(error))) return {
1087
- kind: "rejected",
1088
- reason
1089
- };
1090
- return {
1091
- kind: "indeterminate",
1092
- message: reason.message
1093
- };
1094
- }
1095
- /**
1096
- * Classify an official prompt failure into the stable reason set. The Direct
1097
- * adapter reads the official RemoteError vocabulary structurally (the `code`
1098
- * string; the subagent package stays resolvable from the dsh installation,
1099
- * never an import here).
1100
- */
1101
- function classifySubagentPromptError(error) {
1102
- if (isAbortError(error)) return { kind: "cancelled" };
1103
- const code = remoteErrorCode(error);
1104
- if (code === "gateway/cancelled") return { kind: "cancelled" };
1105
- if (code === "subagent/parent-unavailable") return { kind: "parent-unavailable" };
1106
- if (code === "subagent/not-resumable" || code === "subagent/not-found" || code === "subagent/catalog-diagnostic") return { kind: "stale-child" };
1107
- if (code === "subagent/unauthorized") return { kind: "unauthorized" };
1108
- if (code === "subagent/delivery-unavailable" || code === "subagent/projections-unavailable") return { kind: "unavailable" };
1109
- return {
1110
- kind: "error",
1111
- message: safeSubagentErrorMessage(error)
1112
- };
1113
- }
1114
- /** The stable failure code of a structural official failure, if any. */
1115
- function remoteErrorCode(error) {
1116
- if (typeof error !== "object" || error === null) return void 0;
1117
- const code = error.code;
1118
- return typeof code === "string" && code !== "" ? code : void 0;
1119
- }
1120
- function isAbortError(error) {
1121
- return typeof error === "object" && error !== null && error.name === "AbortError";
1122
- }
1123
- /** One-line safe error text (never throws on hostile values). Shared with the
1124
- * Direct adapter's pre-dispatch catch so both settle the same wording. */
1125
- function safeSubagentErrorMessage(error) {
1126
- if (error === void 0 || error === null) return "unknown error";
1127
- if (typeof error === "string") return error;
1128
- if (error instanceof Error) {
1129
- const message = error.message;
1130
- return message === "" ? error.name : message;
1131
- }
1132
- if (typeof error === "object") {
1133
- const message = error.message;
1134
- if (typeof message === "string" && message !== "") return message;
1135
- }
1136
- try {
1137
- return String(error);
1138
- } catch {
1139
- return "unknown error";
1140
- }
1141
- }
1142
- //#endregion
1143
- //#region src/runtime/presentation-read-port.ts
1144
- /** Detach the official `turnOutline` wire view into the picker DTO — only
1145
- * well-formed entries cross (shared by the Direct projection read and the
1146
- * Remote binding projection read); a foreign-shaped value reads unknown. */
1147
- function detachedTurnOutline(value) {
1148
- if (!Array.isArray(value)) return void 0;
1149
- const entries = [];
1150
- for (const entry of value) {
1151
- if (typeof entry !== "object" || entry === null) return void 0;
1152
- const record = entry;
1153
- if (typeof record.turn !== "number" || typeof record.seq !== "number") return void 0;
1154
- if (typeof record.prompt !== "string" || typeof record.response !== "string") return void 0;
1155
- entries.push({
1156
- turn: record.turn,
1157
- seq: record.seq,
1158
- prompt: record.prompt,
1159
- response: record.response
1160
- });
1161
- }
1162
- return Object.freeze(entries);
1163
- }
1164
- //#endregion
1165
- //#region src/runtime/session-status-projection.ts
1166
- /**
1167
- * Detach the official projection values into the status DTO. Fields are
1168
- * only present when their official projection value is well-formed; nothing
1169
- * is coerced, defaulted or copied from another subject.
1170
- */
1171
- function detachedSessionStatus(sessionId, values, cwd) {
1172
- const record = { sessionId };
1173
- if (typeof cwd === "string" && cwd !== "") record.cwd = cwd;
1174
- const model = modelSelectionFact(values.modelSelection);
1175
- if (model !== void 0) record.model = model;
1176
- if (typeof values.agentPreset === "string" && values.agentPreset !== "") record.preset = values.agentPreset;
1177
- if (typeof values.title === "string" && values.title !== "") record.title = values.title;
1178
- const permissionValue = values.permissions;
1179
- if (typeof permissionValue === "object" && permissionValue !== null) {
1180
- const current = permissionValue.currentValue;
1181
- if (typeof current === "string" && current !== "") record.permission = current;
1182
- }
1183
- if ("goal" in values) {
1184
- const goal = goalFact(values.goal);
1185
- if (goal !== void 0) record.goal = goal;
1186
- }
1187
- const pressure = numericRecord(values.contextPressure);
1188
- const breakdownValue = values.contextBreakdown;
1189
- const breakdown = typeof breakdownValue === "object" && breakdownValue !== null ? numericRecord(breakdownValue) : void 0;
1190
- const hasBreakdown = breakdown !== void 0 && typeof breakdown.systemTokens === "number" && typeof breakdown.toolsTokens === "number" && typeof breakdown.messageTokens === "number";
1191
- if (pressure !== void 0 && Object.keys(pressure).length > 0 || hasBreakdown) record.context = {
1192
- ...pressure ?? {},
1193
- ...hasBreakdown ? { breakdown: {
1194
- systemTokens: breakdown.systemTokens,
1195
- toolsTokens: breakdown.toolsTokens,
1196
- messageTokens: breakdown.messageTokens
1197
- } } : {}
1198
- };
1199
- const todos = detachedTodos(values.todos);
1200
- if (todos !== void 0) record.todos = todos;
1201
- const usageValue = numericRecord(values.tokenUsage);
1202
- if (usageValue !== void 0 && typeof usageValue.uncachedInputTokens === "number" && typeof usageValue.outputTokens === "number" && typeof usageValue.cacheReadTokens === "number" && typeof usageValue.cacheWriteTokens === "number") record.usage = {
1203
- uncachedInputTokens: usageValue.uncachedInputTokens,
1204
- outputTokens: usageValue.outputTokens,
1205
- cacheReadTokens: usageValue.cacheReadTokens,
1206
- cacheWriteTokens: usageValue.cacheWriteTokens
1207
- };
1208
- const performance = performanceProjection(values.piTuiPerformance);
1209
- if (performance !== void 0) record.performance = performance;
1210
- return record;
1211
- }
1212
- /** A finite non-negative projection number, or `undefined` (never coerced,
1213
- * never defaulted). */
1214
- function finiteNumber(value) {
1215
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1216
- }
1217
- /** Whether every entry of a candidate tuple is present (the shape gate). */
1218
- function allDefined(values) {
1219
- return values.every((entry) => entry !== void 0);
1220
- }
1221
- /**
1222
- * Detach the bundle's own `piTuiPerformance` wire value: BOTH scopes with all
1223
- * of their finite non-negative counters, or `undefined` — a malformed,
1224
- * foreign or partial value reads absent (the capability cannot answer), never
1225
- * a partially copied or coerced projection.
1226
- */
1227
- function performanceProjection(value) {
1228
- if (typeof value !== "object" || value === null) return void 0;
1229
- const source = value;
1230
- const recent = typeof source.recent === "object" && source.recent !== null ? source.recent : void 0;
1231
- const all = typeof source.all === "object" && source.all !== null ? source.all : void 0;
1232
- if (recent === void 0 || all === void 0) return void 0;
1233
- const fields = [
1234
- finiteNumber(recent.outputTokens),
1235
- finiteNumber(recent.modelMs),
1236
- finiteNumber(recent.samples),
1237
- finiteNumber(recent.firstTokenMs),
1238
- finiteNumber(recent.firstTokenSamples),
1239
- finiteNumber(all.outputTokens),
1240
- finiteNumber(all.modelMs),
1241
- finiteNumber(all.samples)
1242
- ];
1243
- if (!allDefined(fields)) return void 0;
1244
- const [recentOutputTokens, recentModelMs, recentSamples, firstTokenMs, firstTokenSamples, allOutputTokens, allModelMs, allSamples] = fields;
1245
- return {
1246
- recent: {
1247
- outputTokens: recentOutputTokens,
1248
- modelMs: recentModelMs,
1249
- samples: recentSamples,
1250
- firstTokenMs,
1251
- firstTokenSamples
1252
- },
1253
- all: {
1254
- outputTokens: allOutputTokens,
1255
- modelMs: allModelMs,
1256
- samples: allSamples
1257
- }
1258
- };
1259
- }
1260
- /** Narrow the official `goal` projection view: `null` (no goal) is a LEGAL
1261
- * value and stays distinct from `undefined` (unavailable); the current goal
1262
- * is read from `goal.{objective,phase}` with the phase vocabulary validated. */
1263
- function goalFact(value) {
1264
- if (value === null) return null;
1265
- if (typeof value !== "object") return void 0;
1266
- const current = value.goal;
1267
- if (typeof current !== "object" || current === null) return void 0;
1268
- const goal = current;
1269
- if (typeof goal.objective !== "string" || goal.objective === "") return void 0;
1270
- if (goal.phase !== "active" && goal.phase !== "paused" && goal.phase !== "blocked" && goal.phase !== "complete") return;
1271
- return {
1272
- objective: goal.objective,
1273
- phase: goal.phase
1274
- };
1275
- }
1276
- /** Narrow an unknown projection value to its numeric fields (no coercion). */
1277
- function numericRecord(value) {
1278
- if (typeof value !== "object" || value === null) return void 0;
1279
- const source = value;
1280
- const out = {};
1281
- for (const [key, entry] of Object.entries(source)) if (typeof entry === "number") out[key] = entry;
1282
- return out;
1283
- }
1284
- /** The effective selection off the official `modelSelection` fold:
1285
- * `next ?? lastUsed`, validated to the normalized shape. */
1286
- function modelSelectionFact(value) {
1287
- if (typeof value !== "object" || value === null) return void 0;
1288
- const fold = value;
1289
- for (const candidate of [fold.next, fold.lastUsed]) {
1290
- if (typeof candidate !== "object" || candidate === null) continue;
1291
- const selection = candidate;
1292
- if (typeof selection.provider !== "string" || selection.provider === "") continue;
1293
- if (typeof selection.model !== "string" || selection.model === "") continue;
1294
- return {
1295
- provider: selection.provider,
1296
- model: selection.model,
1297
- ...typeof selection.reasoningEffort === "string" && selection.reasoningEffort !== "" ? { reasoningEffort: selection.reasoningEffort } : {}
1298
- };
1299
- }
1300
- }
1301
- /** Detach the official `todos` whole-list snapshot. The projection's
1302
- * LEGAL `null` (no `todo/write` yet) stays `null`; only `undefined` (the
1303
- * projection value was absent — capability unavailable) reads absent. */
1304
- function detachedTodos(value) {
1305
- if (value === null) return null;
1306
- if (value === void 0) return void 0;
1307
- if (!Array.isArray(value)) return void 0;
1308
- const todos = [];
1309
- for (const item of value) {
1310
- if (typeof item !== "object" || item === null) return void 0;
1311
- const todo = item;
1312
- if (typeof todo.content !== "string") return void 0;
1313
- if (todo.status !== "pending" && todo.status !== "in_progress" && todo.status !== "completed") return void 0;
1314
- todos.push({
1315
- content: todo.content,
1316
- status: todo.status
1317
- });
1318
- }
1319
- return Object.freeze(todos);
1320
- }
1321
- //#endregion
1322
- //#region src/runtime/interaction-port.ts
1323
- /** The official Host code for a late answer whose reply is already queued. */
1324
- const QUESTION_REPLY_QUEUED = "REPLY_QUEUED";
1325
- /** The official Host code for a late answer that does not name each question. */
1326
- const QUESTION_BAD_ANSWER = "BAD_ANSWER";
1327
- /**
1328
- * One rejected late answer with the Host's stable code (`REPLY_QUEUED`,
1329
- * `BAD_ANSWER`, `CALLER_NOT_LIVE`, or a transport/gateway code). Both
1330
- * adapters throw THIS shape so a consumer can offer truthful recovery
1331
- * without switching on a backend.
1332
- */
1333
- var QuestionAnswerError = class extends Error {
1334
- code;
1335
- constructor(code, message, options) {
1336
- super(message, options);
1337
- this.name = "QuestionAnswerError";
1338
- this.code = code;
1339
- }
1340
- };
1341
- /** Wrap an unknown failure from the late-answer path in the port vocabulary. */
1342
- function questionAnswerError(error) {
1343
- if (error instanceof QuestionAnswerError) return error;
1344
- 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 });
1345
- }
1346
- //#endregion
1347
- //#region src/runtime/direct/file-completion/host-discovery.ts
1348
- /**
1349
- * The Direct Host discovery implementation (TS8-A, renamed by TS8-HF1): the
1350
- * DIRECT process's filesystem behind the neutral {@link LocalDiscoveryDriver}
1351
- * contract. It has two legitimate consumers:
1352
- *
1353
- * ```text
1354
- * 1. the sessionless `HostFileScope { kind: 'workspace', cwd }` compatibility
1355
- * path of `DirectHostFilePort` (the cold surface with no official carrier);
1356
- * 2. the explicit-path `@` navigation route of the Session scope
1357
- * (`runtime/direct/host-file-augmentation-direct.ts`), where the user
1358
- * explicitly typed the scope (`@src/`, `@../`, `@/abs`, `@~/`).
1359
- * ```
1360
- *
1361
- * A BARE Session `@` query (`@foo`) never runs through this adapter — that
1362
- * path is the OFFICIAL Host authority's (`ctx.fileReferences.list` through the
1363
- * port), whose candidates arrive already filtered, ranked and bounded.
1364
- *
1365
- * It owns the Direct Host process's own PATH/PATHEXT finder detection, its
1366
- * `node:fs` facts and its fd/fdfind process. The small syscall-level
1367
- * duplication against `client/file-completion/local-discovery.ts` is
1368
- * deliberate: the two adapters read DIFFERENT machines under Remote, and one
1369
- * concrete source owner for both localities is exactly what TS8-A removes.
1370
- * @module @xmoon76/dsh-pi-tui/runtime/direct/file-completion/host-discovery
1371
- */
1372
- /**
1373
- * The Direct Host process's explicit path-query environment facts. Under
1374
- * Remote these are the HOST machine's facts, never the Client's; today Direct
1375
- * runs in-process, so the numbers coincide — that coincidence is deliberately
1376
- * not encoded in the domain contract.
1377
- */
1378
- function hostPathQueryEnvironment() {
1379
- return {
1380
- homeDir: homedir(),
1381
- windowsHost: process.platform === "win32"
1382
- };
1383
- }
1384
- /**
1385
- * Locate an executable file-finder on the Direct Host process's PATH: `fd`
1386
- * preferred, `fdfind` second. See the Client adapter for the probe contract.
1387
- */
1388
- function resolveFdPath() {
1389
- const pathEntries = process.env.PATH?.split(delimiter) ?? [];
1390
- const suffixes = (process.env.PATHEXT || (process.platform === "win32" ? ".COM;.EXE;.BAT;.CMD" : "")).split(";").map((suffix) => suffix.trim()).filter((suffix) => suffix !== "").flatMap((suffix) => suffix.toLowerCase() === suffix ? [suffix] : [suffix, suffix.toLowerCase()]);
1391
- for (const name of ["fd", "fdfind"]) for (const entry of pathEntries) {
1392
- const dir = entry === "" ? "." : entry;
1393
- for (const suffix of ["", ...suffixes]) {
1394
- const candidate = join(dir, `${name}${suffix}`);
1395
- try {
1396
- if (statSync(candidate).isFile() && accessSync(candidate, constants.X_OK) === void 0) return candidate;
1397
- } catch {}
1398
- }
1399
- }
1400
- return null;
1401
- }
1402
- /** Join a Host path WITHOUT collapsing a `..` segment. The Host's filesystem
1403
- * backend anchors a POSIX path containing a `..` segment with its physical
1404
- * spelling (the kernel resolves an intermediate symlink before the parent step),
1405
- * so a search base that deliberately keeps that traversal may not be lexically
1406
- * re-normalized on the way to a syscall. For every base the neutral resolver
1407
- * already normalized (no `..` left) this is identical to `path.join`. */
1408
- function hostJoin(baseDir, relative) {
1409
- if (relative === "") return baseDir;
1410
- return baseDir.endsWith("/") ? `${baseDir}${relative}` : `${baseDir}/${relative}`;
1411
- }
1412
- /** Whether one Dirent is a directory (symlinks followed; a broken link is a
1413
- * file candidate — the fork's rule). */
1414
- function entryIsDirectory(baseDir, name, entry) {
1415
- if (entry.isDirectory()) return true;
1416
- if (entry.isSymbolicLink()) try {
1417
- return statSync(hostJoin(baseDir, name)).isDirectory();
1418
- } catch {
1419
- return false;
1420
- }
1421
- return false;
1422
- }
1423
- /** Run the Direct Host finder for one scoped query. Returns NULL on finder
1424
- * FAILURE (the neutral policy then runs the bounded fallback), `[]` on a
1425
- * genuine no-match or an abort. */
1426
- function runHostFinder(fdPath, baseDir, term, signal) {
1427
- const args = [
1428
- "--base-directory",
1429
- baseDir,
1430
- "--max-results",
1431
- String(100),
1432
- "-i",
1433
- "--full-path",
1434
- "--print0",
1435
- "--type",
1436
- "f",
1437
- "--type",
1438
- "d",
1439
- "--type",
1440
- "l",
1441
- "--hidden",
1442
- "--exclude",
1443
- ".git",
1444
- "--exclude",
1445
- ".git/*",
1446
- "--exclude",
1447
- ".git/**"
1448
- ];
1449
- if (term !== "") args.push(escapeFinderRegex(term));
1450
- return new Promise((resolve) => {
1451
- if (signal.aborted) {
1452
- resolve([]);
1453
- return;
1454
- }
1455
- let child;
1456
- try {
1457
- child = spawn(fdPath, args, { stdio: [
1458
- "ignore",
1459
- "pipe",
1460
- "ignore"
1461
- ] });
1462
- } catch {
1463
- resolve(null);
1464
- return;
1465
- }
1466
- let stdout = "";
1467
- let settled = false;
1468
- const settle = (results) => {
1469
- if (settled) return;
1470
- settled = true;
1471
- signal.removeEventListener("abort", onAbort);
1472
- resolve(results);
1473
- };
1474
- const onAbort = () => {
1475
- if (child.exitCode === null) child.kill("SIGKILL");
1476
- settle([]);
1477
- };
1478
- signal.addEventListener("abort", onAbort, { once: true });
1479
- child.stdout.setEncoding("utf-8");
1480
- child.stdout.on("data", (chunk) => {
1481
- stdout += chunk;
1482
- });
1483
- child.on("error", () => settle(null));
1484
- child.on("close", (code) => {
1485
- if (signal.aborted) {
1486
- settle([]);
1487
- return;
1488
- }
1489
- if (code !== 0) {
1490
- settle(null);
1491
- return;
1492
- }
1493
- const results = [];
1494
- for (const record of normalizeFinderRecords(stdout)) {
1495
- let isDirectory = record.directoryHint;
1496
- if (!isDirectory) try {
1497
- isDirectory = statSync(hostJoin(baseDir, record.path)).isDirectory();
1498
- } catch {
1499
- isDirectory = false;
1500
- }
1501
- results.push({
1502
- path: record.path,
1503
- kind: isDirectory ? "directory" : "file"
1504
- });
1505
- }
1506
- settle(results);
1507
- });
1508
- });
1509
- }
1510
- /**
1511
- * The Direct Host discovery driver: the Direct Host process's OWN filesystem,
1512
- * with a Host PATH finder when present.
1513
- *
1514
- * `fdPath` is a test/API pin: `undefined` probes the Host PATH, `null` FORCES
1515
- * the bounded fallback (no finder), a string pins one finder.
1516
- */
1517
- var DirectHostDiscoveryDriver = class {
1518
- fdPathValue;
1519
- constructor(fdPath = void 0) {
1520
- this.fdPathValue = fdPath === void 0 ? resolveFdPath() : fdPath;
1521
- }
1522
- /** The pinned/detected Host finder (null = bounded-fallback only). */
1523
- get fdPath() {
1524
- return this.fdPathValue;
1525
- }
1526
- async listDirectory(baseDir, relativeDir, signal) {
1527
- if (signal.aborted) return null;
1528
- let entries;
1529
- try {
1530
- entries = readdirSync(hostJoin(baseDir, relativeDir), { withFileTypes: true });
1531
- } catch {
1532
- return null;
1533
- }
1534
- if (signal.aborted) return null;
1535
- const dir = hostJoin(baseDir, relativeDir);
1536
- return entries.map((entry) => ({
1537
- name: entry.name,
1538
- kind: entryIsDirectory(dir, entry.name, entry) ? "directory" : "file",
1539
- descendable: entry.isDirectory() && !entry.isSymbolicLink()
1540
- }));
1541
- }
1542
- async find(baseDir, term, signal) {
1543
- if (this.fdPathValue === null) return null;
1544
- return runHostFinder(this.fdPathValue, baseDir, term, signal);
1545
- }
1546
- };
1547
- //#endregion
1548
- //#region src/runtime/direct/host-file-augmentation-direct.ts
1549
- /**
1550
- * The session `@`-reference Host router (TS8-HF1): ONE Host-side authority
1551
- * that answers a completion query with the routing boundary
1552
- *
1553
- * ```text
1554
- * bare workspace fuzzy search -> official ctx.fileReferences.list
1555
- * @foo @readme @src @.env (workspace index, cache, exclusions,
1556
- * scoring, maxResults stay authoritative)
1557
- *
1558
- * explicit path navigation -> dsh-pi-tui Host scoped discovery
1559
- * @src/ @src/uti @./ @../shared/foo (the exact scope the user typed:
1560
- * @../../foo @/tmp/foo @~/Down recursive fuzzy inside it, explicit
1561
- * Windows drive @C:/work/foo and UNC parent/absolute/native paths)
1562
- * ```
1563
- *
1564
- * The decision is the TOKEN's explicit path navigation, never the resolved
1565
- * search base's workspace containment (the superseded v1 rule): a user-typed
1566
- * separator, a root form (`.`/`..`/`~`) or a Windows absolute path is what
1567
- * selects the scoped route, so `@dist/` and `@link/foo` address their
1568
- * explicitly named scope even when the official provider would exclude or not
1569
- * traverse it.
1570
- *
1571
- * POSIX BOUNDARY: on a POSIX Host a backslash is an ordinary FILENAME character,
1572
- * but the reused TS8-A path resolver selects its Windows dialect from the token
1573
- * alone and normalizes the separators (a pinned cross-dialect contract of the
1574
- * Client-local completion — `test/domain-file-completion.test.ts`). The
1575
- * augmentation therefore does NOT CLAIM an ambiguous POSIX token that contains a
1576
- * backslash: such a token is left to the official provider rather than searched
1577
- * in a scope we cannot represent verbatim. This is a deliberate fail-closed
1578
- * narrowing, not a claim that the token is a bare fuzzy query; delete the guard
1579
- * once the shared resolver distinguishes host dialect, token dialect and literal
1580
- * backslashes.
1581
- *
1582
- * PARENT-TRAVERSAL SPELLING: a relative scope is searched with the SAME spelling
1583
- * the Host's local filesystem backend gives the accepted value. On a POSIX Host a
1584
- * path containing a `..` segment is anchored with its PHYSICAL spelling by
1585
- * `dsh-fs-local` (kernel resolves an intermediate symlink before the parent step);
1586
- * the scoped search therefore keeps the raw `<cwd>/<displayBase>` concatenation for
1587
- * those queries instead of the lexically joined directory, so completion and the
1588
- * model's read can never land in two different physical directories. Windows, the
1589
- * absolute forms (already verbatim) and the home shorthand (absolute normalized
1590
- * value) keep the shared resolver's spelling.
1591
- *
1592
- * The official provider is called ONLY on the bare route; an authoritative
1593
- * official `[]` stays empty and never falls back to the scanner. The scoped
1594
- * route never calls the official provider and needs no capability from it.
1595
- *
1596
- * Home shorthand (`@~`, `@~/Down`) is dsh-pi-tui INPUT syntax: discovery runs
1597
- * against the Host HOME, but every returned candidate is materialized as an
1598
- * ABSOLUTE Host path — DSH path resolution performs no shell-style `~`
1599
- * expansion, so a literal `~/...` completion value would be unusable. Ranking
1600
- * always scores the SCOPE-RELATIVE candidate, never the materialized absolute
1601
- * path (the home prefix itself must not satisfy the path-substring tier).
1602
- *
1603
- * This authority receives HOST facts only (the live Agent, the Host discovery
1604
- * driver, the Host path environment); it never reads the Client cwd, home or
1605
- * platform.
1606
- *
1607
- * TODO(upstream-file-reference-explicit-scope): Delete the pi-tui
1608
- * explicit-scope augmentation when the minimum supported DSH fileReferences
1609
- * provider supports equivalent explicit scoped recursive search,
1610
- * parent/absolute Host path navigation, explicit excluded/symlink scope
1611
- * access, and a Host-home-safe completion representation.
1612
- *
1613
- * @module @xmoon76/dsh-pi-tui/runtime/direct/host-file-augmentation-direct
1614
- */
1615
- /** Whether the token names an EXPLICIT path scope (the frozen classifier,
1616
- * decided from the raw token and the HOST platform — never from filesystem
1617
- * existence, official result count, or workspace containment).
1618
- *
1619
- * A POSIX host has ONE separator: any `/` is an explicit scope, and the root
1620
- * forms are explicit. A token that also contains a backslash is deliberately NOT
1621
- * claimed (see the module comment): the reused resolver cannot represent its
1622
- * literal POSIX scope, so the official provider keeps it.
1623
- *
1624
- * A Windows host treats `\` as a separator as well and accepts any
1625
- * win32-absolute form (drive/UNC) even before its first separator is visible. */
1626
- function isExplicitPathNavigation(raw, environment) {
1627
- if (raw === "") return false;
1628
- if (environment.windowsHost) return raw === "." || raw === ".." || raw === "~" || raw.includes("/") || raw.includes("\\") || win32.isAbsolute(raw);
1629
- if (raw.includes("\\")) return false;
1630
- return raw === "." || raw === ".." || raw === "~" || raw.includes("/");
1631
- }
1632
- /** Whether the token is a leading-home form (`~`, `~/x`, `~\x`). */
1633
- function isHomeToken(raw) {
1634
- return raw === "~" || raw.startsWith("~/") || raw.startsWith("~\\");
1635
- }
1636
- /** Materialize one candidate discovered under a HOME scope as an ABSOLUTE Host
1637
- * path (the `~` shorthand must never reach the prompt as literal text). */
1638
- function materializeHostPath(candidate, searchBase, windowsHost) {
1639
- return {
1640
- path: (windowsHost ? win32 : posix).join(searchBase, candidate.path),
1641
- kind: candidate.kind
1642
- };
1643
- }
1644
- /** One `..` path SEGMENT — the exact shape the Host filesystem backend keys its
1645
- * physical-spelling rule on (`dsh-fs-local`'s `localDisplayPath`). */
1646
- const PARENT_SEGMENT = /(?:^|[\\/])\.\.(?:[\\/]|$)/u;
1647
- /**
1648
- * The directory one explicit scope searches.
1649
- *
1650
- * The Host's local filesystem backend anchors a POSIX path that contains a `..`
1651
- * SEGMENT with its PHYSICAL spelling (the raw `<anchor>/<path>`, deliberately
1652
- * unnormalized), so the kernel resolves an intermediate symlink BEFORE the parent
1653
- * step; every other spelling goes through a lexical `resolve(anchor, path)`, and
1654
- * Windows always resolves lexically. Two consequences drive this function:
1655
- *
1656
- * 1. The anchor is `<hostCwd>` for a relative scope and the value itself for an
1657
- * absolute one, and the rule tests the WHOLE anchored spelling — so a `..`
1658
- * carried by the SESSION CWD flips it just like one in the typed scope. The
1659
- * consumer applies that rule to the value we hand it (`displayBase + name`), so
1660
- * the search must use the same spelling; otherwise the completion could offer a
1661
- * path the model's read resolves into a DIFFERENT physical directory.
1662
- * 2. A home shorthand emits an ABSOLUTE value through `path.join`, which normalizes
1663
- * lexically. Its scope must be normalized the same way: the bare `~`/`~/` root
1664
- * form is the one form whose search base is the raw `homedir()` string, so a
1665
- * `..`-bearing HOME would otherwise be searched physically while the value we
1666
- * emit names the lexical directory.
1667
- *
1668
- * Absolute forms already spell their traversal verbatim. This is one segment test
1669
- * plus one concatenation (plus one lexical normalize for the home root form) — the
1670
- * consumer's own rule applied to the value we are about to hand it, not a second
1671
- * path parser.
1672
- */
1673
- function scopeSearchBase(resolved, raw, hostCwd, environment) {
1674
- const api = environment.windowsHost ? win32 : posix;
1675
- if (isHomeToken(raw)) return api.normalize(resolved.searchBase);
1676
- if (environment.windowsHost) return resolved.searchBase;
1677
- if (raw.startsWith("/") || resolved.winAbsolute) return resolved.searchBase;
1678
- const physicalScope = `${hostCwd}/${resolved.displayBase}`;
1679
- return PARENT_SEGMENT.test(physicalScope) ? physicalScope : resolved.searchBase;
1680
- }
1681
- /**
1682
- * Answer one session `@` completion query over the Host facts.
1683
- *
1684
- * Cancellation (the caller's `signal`) outranks every route: an aborted
1685
- * request rejects at entry — before the route/capability decision — and again
1686
- * after each await, so a cancelled scope never serves a late result and never
1687
- * reports `unavailable`.
1688
- *
1689
- * @param agent - the live Agent the session scope resolved to.
1690
- * @param query - the official query form (path text following `@`).
1691
- * @param signal - caller cancellation.
1692
- * @param deps - the Host facts this router answers with.
1693
- */
1694
- async function listPiTuiHostFileReferences(agent, query, signal, deps) {
1695
- signal.throwIfAborted();
1696
- if (!isExplicitPathNavigation(query, deps.environment)) {
1697
- const official = deps.official;
1698
- if (official === void 0) return {
1699
- kind: "unavailable",
1700
- reason: "the official Host file-reference service is not mounted"
1701
- };
1702
- const candidates = await official.list(agent, query, signal);
1703
- signal.throwIfAborted();
1704
- return {
1705
- kind: "ok",
1706
- items: candidates.map((candidate) => ({
1707
- path: candidate.path,
1708
- kind: candidate.kind
1709
- }))
1710
- };
1711
- }
1712
- const workspaceCwd = effectiveAgentCwd(deps.workingDirectory, agent) ?? process.cwd();
1713
- const resolved = resolvePathQuery(query, workspaceCwd, deps.environment);
1714
- const searchBase = scopeSearchBase(resolved, query, workspaceCwd, deps.environment);
1715
- const discovered = await discoverForQuery(searchBase === resolved.searchBase ? resolved : {
1716
- ...resolved,
1717
- searchBase
1718
- }, deps.driver, signal);
1719
- signal.throwIfAborted();
1720
- const homeToken = isHomeToken(query);
1721
- return {
1722
- kind: "ok",
1723
- items: rankPathCandidates(homeToken ? discovered : discovered.map((candidate) => reattachDisplayBase(candidate, resolved)), resolved.searchTerm).map((candidate) => homeToken ? materializeHostPath(candidate, resolved.searchBase, deps.environment.windowsHost) : {
1724
- path: candidate.path,
1725
- kind: candidate.kind
1726
- })
1727
- };
1728
- }
1729
- //#endregion
1730
- //#region src/runtime/plugin-manager-mapping.ts
1731
- /** Generate one install request id (the branded shape is a plain string). */
1732
- function pluginInstallRequestId(value) {
1733
- return value;
1734
- }
1735
- /** Resolve one official localized text to the English fallback. */
1736
- function localizedText(value) {
1737
- if (value === void 0) return void 0;
1738
- return typeof value === "string" ? value : value.en;
1739
- }
1740
- function detachIncompatible(entry) {
1741
- return Object.freeze({
1742
- name: entry.name,
1743
- version: entry.version,
1744
- runtimeVersion: entry.runtimeVersion,
1745
- requirements: Object.freeze({ ...entry.requirements })
1746
- });
1747
- }
1748
- function detachError(error) {
1749
- if (error === void 0) return void 0;
1750
- return Object.freeze({
1751
- code: error.code,
1752
- ...error.diagnostic === void 0 ? {} : { diagnostic: error.diagnostic },
1753
- ...error.incompatible === void 0 ? {} : { incompatible: Object.freeze(error.incompatible.map(detachIncompatible)) }
1754
- });
1755
- }
1756
- function pickMeta(meta) {
1757
- const title = localizedText(meta.title);
1758
- const description = localizedText(meta.description);
1759
- return {
1760
- ...title === void 0 ? {} : { title },
1761
- ...description === void 0 ? {} : { description }
1762
- };
1763
- }
1764
- function detachBundle(bundle) {
1765
- const rows = bundle.rows.map((row) => Object.freeze({
1766
- rowId: row.rowId,
1767
- moduleName: row.moduleName,
1768
- ...row.meta === void 0 ? {} : pickMeta(row.meta),
1769
- ...row.entryId === void 0 ? {} : { entryId: String(row.entryId) }
1770
- }));
1771
- return Object.freeze({
1772
- name: bundle.name,
1773
- official: bundle.official,
1774
- availability: bundle.availability,
1775
- ...bundle.installTarget === void 0 ? {} : { installTarget: Object.freeze({
1776
- spec: bundle.installTarget.spec,
1777
- version: bundle.installTarget.version
1778
- }) },
1779
- ...bundle.version === void 0 ? {} : { version: bundle.version },
1780
- ...bundle.meta === void 0 ? {} : pickMeta(bundle.meta),
1781
- ...bundle.description === void 0 ? {} : { description: bundle.description },
1782
- enabled: bundle.enabled,
1783
- installed: bundle.installed,
1784
- optional: bundle.optional,
1785
- ...bundle.source === void 0 ? {} : { source: bundle.source },
1786
- removable: bundle.removable,
1787
- ...bundle.readOnlyReason === void 0 ? {} : { readOnlyReason: bundle.readOnlyReason },
1788
- ...bundle.error === void 0 ? {} : { error: detachError(bundle.error) },
1789
- rows: Object.freeze(rows),
1790
- overrides: Object.freeze([...bundle.overrides])
1791
- });
1792
- }
1793
- function detachPlugin(entry) {
1794
- const addressable = "patchId" in entry;
1795
- return Object.freeze({
1796
- entryId: String(entry.entryId),
1797
- moduleName: entry.moduleName,
1798
- ...entry.meta === void 0 ? {} : pickMeta(entry.meta),
1799
- enabled: entry.enabled,
1800
- fiberPhase: entry.fiberPhase,
1801
- ...addressable ? { patchId: entry.patchId } : { readOnlyReason: entry.readOnlyReason }
1802
- });
1803
- }
1804
- function detachRegistries(registries) {
1805
- return Object.freeze({
1806
- registry: registries.registry,
1807
- fallbackRegistries: Object.freeze([...registries.fallbackRegistries]),
1808
- resolved: registries.resolved
1809
- });
1810
- }
1811
- function detachExemptions(value) {
1812
- return Object.freeze(Object.entries(value.exemptions).map(([packageVersion, runtimeVersions]) => Object.freeze({
1813
- packageVersion,
1814
- runtimeVersions: Object.freeze([...runtimeVersions])
1815
- })));
1816
- }
1817
- /** Map one complete snapshot read onto the detached surface facts. */
1818
- function detachPluginManagerSnapshot(input) {
1819
- return Object.freeze({
1820
- bundles: Object.freeze(input.bundles.map(detachBundle)),
1821
- plugins: Object.freeze(input.plugins.map(detachPlugin)),
1822
- registries: detachRegistries(input.registries),
1823
- exemptions: detachExemptions(input.exemptions),
1824
- exemptionWarnings: Object.freeze([...input.exemptions.warnings])
1825
- });
1826
- }
1827
- function detachPackageResult(result) {
1828
- return Object.freeze({
1829
- exitCode: result.exitCode,
1830
- output: result.output,
1831
- truncated: result.truncated,
1832
- ...result.kind === void 0 ? {} : { kind: result.kind },
1833
- ...result.timedOut === void 0 ? {} : { timedOut: result.timedOut },
1834
- ...result.incompatible === void 0 ? {} : { incompatible: Object.freeze(result.incompatible.map(detachIncompatible)) }
1835
- });
1836
- }
1837
- /** Map one persisted change and its observed application outcome. */
1838
- function detachChange(result) {
1839
- return Object.freeze({
1840
- changed: result.changed,
1841
- application: result.application,
1842
- ...result.restartReason === void 0 ? {} : { restartReason: result.restartReason },
1843
- stage: result.stage,
1844
- target: result.target,
1845
- ...result.enabled === void 0 ? {} : { enabled: result.enabled },
1846
- ...result.error === void 0 ? {} : { error: detachError(result.error) },
1847
- ...result.warnings === void 0 ? {} : { warnings: Object.freeze([...result.warnings]) },
1848
- ...result.bundle === void 0 ? {} : { bundle: result.bundle },
1849
- ...result.version === void 0 ? {} : { version: result.version },
1850
- ...result.pendingBuilds === void 0 ? {} : { pendingBuilds: Object.freeze([...result.pendingBuilds]) },
1851
- ...result.approvedBuilds === void 0 ? {} : { approvedBuilds: Object.freeze([...result.approvedBuilds]) },
1852
- ...result.packageResult === void 0 ? {} : { packageResult: detachPackageResult(result.packageResult) },
1853
- ...result.registries === void 0 ? {} : { registries: Object.freeze([...result.registries]) },
1854
- ...result.failedAt === void 0 ? {} : { failedAt: result.failedAt }
1855
- });
1856
- }
1857
- /** Map what a spec names before installation. */
1858
- function detachInspection(inspection) {
1859
- if (inspection.status === "accepted") return Object.freeze({
1860
- status: "accepted",
1861
- kind: inspection.kind,
1862
- ...inspection.name === void 0 ? {} : { name: inspection.name },
1863
- ...inspection.version === void 0 ? {} : { version: inspection.version },
1864
- ...inspection.description === void 0 ? {} : { description: inspection.description },
1865
- bundle: inspection.bundle,
1866
- registry: inspection.registry,
1867
- ...inspection.host === void 0 ? {} : { host: inspection.host }
1868
- });
1869
- return Object.freeze({
1870
- status: "refused",
1871
- problem: inspection.problem,
1872
- reason: inspection.reason,
1873
- ...inspection.registries === void 0 ? {} : { registries: Object.freeze([...inspection.registries]) }
1874
- });
1875
- }
1876
- /** Map one official install-phase announcement. */
1877
- function detachPhase(progress) {
1878
- return Object.freeze({
1879
- requestId: String(progress.requestId),
1880
- phase: progress.phase,
1881
- ...progress.attempt === void 0 ? {} : { attempt: Object.freeze({
1882
- registry: progress.attempt.registry,
1883
- index: progress.attempt.index,
1884
- total: progress.attempt.total
1885
- }) }
1886
- });
1887
- }
1888
- /** Map one pnpm output chunk. */
1889
- function detachLog(chunk) {
1890
- return Object.freeze({
1891
- ...chunk.requestId === void 0 ? {} : { requestId: String(chunk.requestId) },
1892
- jobId: chunk.jobId,
1893
- stream: chunk.stream,
1894
- text: chunk.text
1895
- });
1896
- }
1897
- //#endregion
1898
- //#region src/domain/terminal-progress/interval.ts
1899
- /**
1900
- * Classify one official `turn/end.reason.kind` (plan §5.2). `completed` is the
1901
- * DSH turn result (not a claim about every business step); `error` and
1902
- * `max-tokens` (a resource ceiling, not success) are `error`; a cancelled /
1903
- * blocked / non-live closer is honestly `idle`. An UNKNOWN upstream kind is
1904
- * NOT guessed — the caller records it and the interval stays `idle`.
1905
- *
1906
- * @param kind - the durable `turn/end` reason kind.
1907
- * @returns the proven outcome, or `undefined` for an unknown kind.
1908
- */
1909
- function classifyTerminalTurnEnd(kind) {
1910
- switch (kind) {
1911
- case "completed": return "done";
1912
- case "error": return "error";
1913
- case "max-tokens": return "error";
1914
- case "aborted":
1915
- case "blocked":
1916
- case "interrupted":
1917
- case "forked": return "idle";
1918
- default: return;
1919
- }
1920
- }
1921
- /**
1922
- * Create one independent fold instance.
1923
- * @param onUnknownReason - reports an unknown `turn/end.reason.kind` (the
1924
- * Host/Direct owner injects its diagnostics channel here); the interval stays
1925
- * `idle` instead of guessing.
1926
- */
1927
- function createTerminalProgressInterval(onUnknownReason) {
1928
- let active = false;
1929
- /** The turn opened by the newest live `turn/start` of THIS interval. */
1930
- let openTurn;
1931
- /** The classified outcome of the newest turn whose `turn/end` matched the
1932
- * open turn — reset whenever a newer turn opens. */
1933
- let lastClosed;
1934
- /** The currently committed outcome of the interval (`idle` while running
1935
- * without a proven result). */
1936
- let outcome = "idle";
1937
- const state = () => ({
1938
- active,
1939
- outcome
1940
- });
1941
- return {
1942
- status(running) {
1943
- if (running) {
1944
- if (active) return void 0;
1945
- active = true;
1946
- openTurn = void 0;
1947
- lastClosed = void 0;
1948
- outcome = "idle";
1949
- return state();
1950
- }
1951
- if (!active) return void 0;
1952
- outcome = openTurn === void 0 ? lastClosed ?? "idle" : "idle";
1953
- active = false;
1954
- openTurn = void 0;
1955
- lastClosed = void 0;
1956
- return state();
1957
- },
1958
- turnStart(turn) {
1959
- if (!active) return;
1960
- openTurn = turn;
1961
- lastClosed = void 0;
1962
- },
1963
- turnEnd(turn, reasonKind) {
1964
- if (!active) return;
1965
- if (openTurn !== turn) return;
1966
- openTurn = void 0;
1967
- const classified = classifyTerminalTurnEnd(reasonKind);
1968
- if (classified === void 0) {
1969
- onUnknownReason?.(reasonKind);
1970
- lastClosed = "idle";
1971
- return;
1972
- }
1973
- lastClosed = classified;
1974
- },
1975
- retire() {
1976
- openTurn = void 0;
1977
- lastClosed = void 0;
1978
- if (!active && outcome === "idle") return void 0;
1979
- active = false;
1980
- return state();
1981
- },
1982
- apply(fact) {
1983
- active = fact.active;
1984
- outcome = fact.outcome;
1985
- openTurn = void 0;
1986
- lastClosed = void 0;
1987
- return state();
1988
- },
1989
- reset() {
1990
- active = false;
1991
- openTurn = void 0;
1992
- lastClosed = void 0;
1993
- outcome = "idle";
1994
- return state();
1995
- },
1996
- snapshot() {
1997
- return state();
1998
- }
1999
- };
2000
- }
2001
- //#endregion
2002
- //#region src/runtime/plugin-manager-port.ts
2003
- /**
2004
- * One plugin mutation's result arrived after the operation's authoritative
2005
- * currentness context was superseded. The write may have been applied, so this
2006
- * is NOT a refusal: the caller must present the outcome as indeterminate and
2007
- * let the authoritative inventory reread decide what is true. A backend
2008
- * adapter raises it only when its own currentness authority proves the reply
2009
- * belongs to a superseded context; this module names no transport.
2010
- */
2011
- var PluginManagerStaleResultError = class extends Error {
2012
- constructor(operation) {
2013
- super(`pluginManager.${operation} returned after its currentness context was superseded; the authoritative inventory reread decides the outcome`);
2014
- this.name = "PluginManagerStaleResultError";
2015
- }
2016
- };
2017
- //#endregion
2018
- //#region src/runtime/remote/pi-tui-terminal-progress-contract.ts
2019
- /** The wire namespace (and Host Cordis service key) of the private stream. */
2020
- const PI_TUI_TERMINAL_PROGRESS_NAMESPACE = "piTuiTerminalProgress";
2021
- /** The private method's stable endpoint identity. */
2022
- const PI_TUI_TERMINAL_PROGRESS_WATCH_ENDPOINT = "@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch";
2023
- /** One strict JSON codec that validates a wire string. */
2024
- function stringCodec(typeSymbol) {
2025
- return {
2026
- mode: "strict",
2027
- typeSymbol,
2028
- create: () => ({ parse: (value) => {
2029
- if (typeof value !== "string") throw new TypeError(`${typeSymbol}: the wire value must be a string`);
2030
- return value;
2031
- } })
2032
- };
2033
- }
2034
- /**
2035
- * Validate and detach one `PiTuiTerminalProgressFrame`. This is the ONE
2036
- * structural validator of the frame shape: the descriptor's `result` codec
2037
- * uses it, and the R2 Client source must call it on every downlink item because
2038
- * the framework does not (see the module JSDoc).
2039
- */
2040
- function parsePiTuiTerminalProgressFrame(value) {
2041
- if (typeof value !== "object" || value === null) throw new TypeError("piTuiTerminalProgress/watch: the frame must be an object");
2042
- const frame = value;
2043
- if (frame.kind !== "snapshot" && frame.kind !== "update") throw new TypeError("piTuiTerminalProgress/watch: the frame kind must be snapshot or update");
2044
- if (typeof frame.sessionId !== "string") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a string sessionId");
2045
- if (typeof frame.hostEpoch !== "string") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a string hostEpoch");
2046
- if (typeof frame.agentEpoch !== "number") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a numeric agentEpoch");
2047
- if (typeof frame.revision !== "number") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a numeric revision");
2048
- if (typeof frame.running !== "boolean") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a boolean running");
2049
- if (frame.outcome !== "idle" && frame.outcome !== "done" && frame.outcome !== "error") throw new TypeError("piTuiTerminalProgress/watch: the frame outcome must be idle, done or error");
2050
- return {
2051
- kind: frame.kind,
2052
- sessionId: frame.sessionId,
2053
- hostEpoch: frame.hostEpoch,
2054
- agentEpoch: frame.agentEpoch,
2055
- revision: frame.revision,
2056
- running: frame.running,
2057
- outcome: frame.outcome
2058
- };
2059
- }
2060
- const PI_TUI_TERMINAL_PROGRESS_FRAME_CODEC = {
2061
- mode: "strict",
2062
- typeSymbol: "@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch:frame",
2063
- create: () => ({ parse: parsePiTuiTerminalProgressFrame }),
2064
- decode: parsePiTuiTerminalProgressFrame
2065
- };
2066
- /**
2067
- * The ONE shared invocation descriptor both contributions derive from. The
2068
- * Host registers this exact object; the Client mounts this exact object.
2069
- */
2070
- const PI_TUI_TERMINAL_PROGRESS_WATCH = {
2071
- id: PI_TUI_TERMINAL_PROGRESS_WATCH_ENDPOINT,
2072
- service: PI_TUI_TERMINAL_PROGRESS_NAMESPACE,
2073
- namespace: PI_TUI_TERMINAL_PROGRESS_NAMESPACE,
2074
- method: "watch",
2075
- mode: "stream",
2076
- invocation: { kind: "direct" },
2077
- parameters: [{
2078
- name: "sessionId",
2079
- wire: "sessionId",
2080
- source: "json",
2081
- codec: stringCodec("@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch:sessionId")
2082
- }],
2083
- cancellation: { parameter: "signal" },
2084
- result: PI_TUI_TERMINAL_PROGRESS_FRAME_CODEC
2085
- };
2086
- //#endregion
2087
- //#region src/app/remote/terminal-progress-source.ts
2088
- /** Consecutive frame-less watch endings tolerated before failing closed. */
2089
- const EMPTY_WATCH_REOPEN_LIMIT = 3;
2090
- /**
2091
- * Consume the ONE Remote progress watch of one session for as long as the caller
2092
- * stays current, re-establishing it whenever the Host retires it.
2093
- *
2094
- * @param source - the Remote progress source.
2095
- * @param sessionId - the main session this authority belongs to.
2096
- * @param signal - the caller's lifetime; aborting it stops the consumption at
2097
- * the next fact and before any re-open.
2098
- * @param consumer - the currentness fence and the fact sink.
2099
- * @throws when the Host keeps ending the watch without ever delivering a frame.
2100
- */
2101
- async function consumeRemoteTerminalProgress(source, sessionId, signal, consumer) {
2102
- let emptyReopens = 0;
2103
- for (;;) {
2104
- let frames = 0;
2105
- try {
2106
- for await (const fact of source.open(sessionId, signal)) {
2107
- if (signal.aborted || !consumer.isCurrent()) return;
2108
- frames += 1;
2109
- consumer.onFact(fact);
2110
- }
2111
- } catch (error) {
2112
- if (signal.aborted) return;
2113
- throw error;
2114
- }
2115
- if (signal.aborted || !consumer.isCurrent()) return;
2116
- if (frames === 0) {
2117
- emptyReopens += 1;
2118
- if (emptyReopens > EMPTY_WATCH_REOPEN_LIMIT) throw new Error(`the Remote terminal-progress watch of ${sessionId} ended without a frame ${String(emptyReopens)} times`);
2119
- } else emptyReopens = 0;
2120
- }
2121
- }
2122
- /**
2123
- * Assemble the source over the ONE Remote Client graph. It constructs no
2124
- * Client and owns no subscription of its own; the provenance of an accepted
2125
- * frame lives only for the watch that observed it (see {@link createRemoteTerminalProgressSource}).
2126
- */
2127
- function createRemoteTerminalProgressSource(deps) {
2128
- /**
2129
- * Judge one frame against the provenance of THIS watch.
2130
- *
2131
- * @param previous - the last frame accepted by this watch, or `undefined`
2132
- * before its opening baseline. It deliberately never crosses watches: a
2133
- * settled `done`/`error` belongs to the interval ONE watch observed, so a new
2134
- * watch (a reconnect, a re-adopted session, a re-retained binding, another TUI
2135
- * owner) opens on the Host's current `running` truth and `idle` — the plan's
2136
- * "a new binding default to idle" — instead of inheriting a result it cannot
2137
- * prove.
2138
- * @param opened - whether this watch already delivered its opening baseline.
2139
- * @returns the fact to publish, or `undefined` for a frame that must be dropped.
2140
- * @throws when the stream cannot be interpreted at all.
2141
- */
2142
- const acceptFrame = (frame, sessionId, opened, previous) => {
2143
- if (!opened) {
2144
- if (frame.kind !== "snapshot") throw new Error(`the Remote terminal-progress stream of ${sessionId} did not open with a snapshot`);
2145
- return {
2146
- kind: "snapshot",
2147
- restart: true,
2148
- running: frame.running,
2149
- outcome: "idle"
2150
- };
2151
- }
2152
- if (previous !== void 0 && frame.revision < previous.revision) throw new Error(`the Remote terminal-progress stream of ${sessionId} moved its revision backwards`);
2153
- if (frame.kind === "snapshot") return {
2154
- kind: "snapshot",
2155
- restart: true,
2156
- running: frame.running,
2157
- outcome: "idle"
2158
- };
2159
- if (previous === void 0) return void 0;
2160
- if (frame.hostEpoch !== previous.hostEpoch) return;
2161
- if (frame.agentEpoch < previous.agentEpoch) return void 0;
2162
- if (frame.revision <= previous.revision) return void 0;
2163
- return {
2164
- kind: "update",
2165
- restart: frame.agentEpoch > previous.agentEpoch,
2166
- running: frame.running,
2167
- outcome: frame.outcome
2168
- };
2169
- };
2170
- return { async *open(sessionId, signal) {
2171
- const capturedGeneration = deps.generation.getSnapshot();
2172
- const capturedBinding = deps.binding(sessionId);
2173
- if (capturedGeneration === void 0 || capturedBinding === void 0) throw new Error(`the Remote terminal-progress watch of ${sessionId} has no retained Session binding`);
2174
- const handle = deps.remote.piTuiTerminalProgress.watch(sessionId, signal);
2175
- try {
2176
- let opened = false;
2177
- /** This watch's own provenance: it dies with the watch. */
2178
- let accepted;
2179
- for await (const item of handle) {
2180
- if (signal.aborted) return;
2181
- if (!Object.is(capturedGeneration, deps.generation.getSnapshot()) || deps.binding(sessionId) !== capturedBinding) throw new Error(`the Remote terminal-progress watch of ${sessionId} lost its transport identity`);
2182
- const frame = parsePiTuiTerminalProgressFrame(item);
2183
- if (frame.sessionId !== sessionId) throw new Error(`the Remote terminal-progress stream of ${sessionId} delivered a frame of ${frame.sessionId}`);
2184
- const fact = acceptFrame(frame, sessionId, opened, accepted);
2185
- if (fact === void 0) continue;
2186
- opened = true;
2187
- accepted = {
2188
- hostEpoch: frame.hostEpoch,
2189
- agentEpoch: frame.agentEpoch,
2190
- revision: frame.revision
2191
- };
2192
- yield fact;
2193
- }
2194
- } finally {
2195
- handle.dispose();
2196
- }
2197
- } };
2198
- }
2199
- //#endregion
2200
- export { customItemName as $, clientOwnerOf as A, resolveCredentialArg as B, classifySubagentPromptSettlement as C, DIRECT_IMPLEMENTED_CAPABILITIES as D, isRemoteBusinessRefusalCode as E, PROTOCOL_CHOICES as F, separatorOfRaw as G, rankPathCandidates as H, ROUTE_PATTERN as I, normalizeFinderRecords as J, discoverForQuery as K, credentialOptionsFor as L, ownerHandleOf as M, requireCreated as N, REMOTE_IMPLEMENTED_CAPABILITIES as O, requireOpened as P, customItemId as Q, deriveKeyRef as R, detachedTurnOutline as S, GATEWAY_PRE_INVOCATION_CODES as T, reattachDisplayBase as U, SupersededReadError as V, resolvePathQuery as W, activeFooterItemIds as X, DEFAULT_CUSTOM_COMMAND_REFRESH_MS as Y, customCommandConfigOf as Z, QUESTION_BAD_ANSWER as _, PluginManagerStaleResultError as a, parseFooterCommandConfig as at, questionAnswerError as b, detachInspection as c, resolveUserCommandItemFallbackActivationIds as ct, detachPluginManagerSnapshot as d, contextPressureOccupancy as dt, effectiveCustomCommandRefreshMs as et, pluginInstallRequestId as f, effectiveAgentCwd as ft, resolveFdPath as g, hostPathQueryEnvironment as h, PI_TUI_TERMINAL_PROGRESS_WATCH as i, parseFooterCustomItems as it, directAgentOf as j, LifecycleError as k, detachLog as l, resolveUserLayerFooterMode as lt, DirectHostDiscoveryDriver as m, createRemoteTerminalProgressSource as n, executableCommandItemIds as nt, createTerminalProgressInterval as o, resolveTrustedFooterCommand as ot, listPiTuiHostFileReferences as p, projectedWorkingDirectory as pt, escapeFinderRegex as q, PI_TUI_TERMINAL_PROGRESS_NAMESPACE as r, parseFooterCustomItem as rt, detachChange as s, resolveUserCommandItemActivationIds as st, consumeRemoteTerminalProgress as t, effectiveCustomCommandTimeoutMs as tt, detachPhase as u, MAX_COMMAND_TIMEOUT_MS as ut, QUESTION_REPLY_QUEUED as v, safeSubagentErrorMessage as w, detachedSessionStatus as x, QuestionAnswerError as y, providerOptionsFor as z };