@xmoon76/dsh-pi-tui 0.5.4 → 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 (46) hide show
  1. package/README.en.md +28 -7
  2. package/README.md +25 -6
  3. package/dist/application-runtime-CbBO4bY-.mjs +6860 -0
  4. package/dist/bootstrap-DLOydLLj.mjs +108410 -0
  5. package/dist/builtins.mjs +2 -3
  6. package/dist/client-bootstrap-DwSFzcTW.mjs +872 -0
  7. package/dist/context-summary-Bz0AGXa1.mjs +12027 -0
  8. package/dist/{context-summary-DAisTA_7.mjs → context-summary-D9mhxPXL.mjs} +1468 -10
  9. package/dist/custom-items-CKrOBCox.mjs +655 -0
  10. package/dist/disposal-BYBbEpVY.mjs +54 -0
  11. package/dist/dispose-cause-BzcXo4hu.mjs +123 -0
  12. package/dist/dist-C7QMk0ws.mjs +15431 -0
  13. package/dist/{entry-control-DvSrndWd.mjs → entry-control-DnduyDiw.mjs} +12 -31
  14. package/dist/{extensions-CcuMY4n2.mjs → extensions-pcFiH7Qe.mjs} +758 -68
  15. package/dist/extensions.mjs +1 -1
  16. package/dist/host-bootstrap-CKdfLkNS.mjs +188 -0
  17. package/dist/host-foundation-probe-CYHsbAw6.mjs +143 -0
  18. package/dist/host-prerequisites-9JBTtVNu.mjs +36 -0
  19. package/dist/host-runtime.d.mts +26 -0
  20. package/dist/host-runtime.mjs +450 -0
  21. package/dist/index.d.mts +8 -1
  22. package/dist/index.mjs +5192 -2118
  23. package/dist/local-client.mjs +1681 -188
  24. package/dist/local-discovery-CXnLT4GF.mjs +755 -0
  25. package/dist/local-discovery-DVFFpfBG.mjs +2 -0
  26. package/dist/local-host.mjs +927 -78
  27. package/dist/local-transport-C9aonplC.mjs +513 -0
  28. package/dist/performance-host.d.mts +2 -2
  29. package/dist/performance-host.mjs +258 -1
  30. package/dist/pi-tui-remote-contribution-DRk6Tl3J.mjs +78 -0
  31. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  32. package/dist/pi-tui-terminal-progress-contract-XTQKj-WW.mjs +905 -0
  33. package/dist/{runtime-vc4mdr-R.mjs → runtime-Bh5OsftD.mjs} +655 -675
  34. package/dist/runtime-C5ROZqFj.mjs +2 -0
  35. package/dist/{session-tdJHLnJR.mjs → session-4keoXjk0.mjs} +2341 -217
  36. package/dist/session-B2zqv4wr.mjs +10869 -0
  37. package/dist/{startup-JaVZoTIl.mjs → startup-Ct2UUjUL.mjs} +7 -6
  38. package/dist/startup.d.mts +1 -1
  39. package/dist/startup.mjs +1 -1
  40. package/dist/{client-bootstrap-F5DHFI9t.mjs → terminal-progress-source-BhufrZ74.mjs} +3431 -3007
  41. package/dist/terminal-progress-source-CsBinCJ_.mjs +965 -0
  42. package/package.json +125 -116
  43. package/dist/host-bootstrap-DAgKknbY.mjs +0 -119
  44. package/dist/performance-host-CcDJjjVA.mjs +0 -266
  45. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  46. package/dist/terminal-progress-source-xor3vakJ.mjs +0 -2256
@@ -1,2256 +0,0 @@
1
- import { _t as parseFooterLayout, gt as isFooterLayout } from "./extensions-CcuMY4n2.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
- * Project one profile value onto the merge's per-route facts: whether a
820
- * profile EXISTS for the route, and the explicit `apiKeyEnv` it names.
821
- * A primitive or an absent value is still a configuration fact: an absent
822
- * profile is the only "not present" case.
823
- */
824
- function providerProfileProjectionOf(profile) {
825
- if (profile === void 0) return { present: false };
826
- if (typeof profile !== "object" || profile === null) return { present: true };
827
- const namedRef = profile.apiKeyEnv;
828
- return {
829
- present: true,
830
- ...typeof namedRef === "string" ? { namedRef } : {}
831
- };
832
- }
833
- /**
834
- * Merge the configurable-provider directory with the existing settings
835
- * section into the /login option list.
836
- *
837
- * The PROVIDER identity is the ROUTE: two routes that name the same
838
- * credential reference are two providers, and both stay visible (the
839
- * credential READ is deduplicated by reference later, in the read planner —
840
- * not here, where the route is the identity). The deepseek official builtin
841
- * leads and keeps its own route.
842
- *
843
- * @param entries - the llm directory entries (or undefined when the llm
844
- * service is absent — degrades to the official target only).
845
- * @param readProfile - project ONE route's profile facts from the adapter's
846
- * single settings snapshot; undefined when the route's profile could not
847
- * be read at all.
848
- * @returns the merged options, deepseek official first, one entry per route.
849
- */
850
- function providerOptionsFor(entries, readProfile) {
851
- const options = [];
852
- const seenRoutes = /* @__PURE__ */ new Set();
853
- const push = (option) => {
854
- if (seenRoutes.has(option.route)) return;
855
- seenRoutes.add(option.route);
856
- options.push(option);
857
- };
858
- push({
859
- label: "deepseek official",
860
- ref: "DEEPSEEK_API_KEY",
861
- route: "deepseek-official",
862
- configured: true,
863
- declared: false,
864
- namesCredential: true,
865
- group: "configured",
866
- settingsNs: "",
867
- settingsPath: []
868
- });
869
- if (entries === void 0) return options;
870
- for (const entry of entries) {
871
- if (entry.provider.length === 0 || entry.settingsNs.length === 0) continue;
872
- const profile = readProfile(entry);
873
- const configured = profile?.present === true;
874
- const namedRef = profile?.namedRef;
875
- const namesCredential = namedRef !== void 0 && namedRef !== "";
876
- const ref = namesCredential ? namedRef : deriveKeyRef(entry.provider);
877
- push({
878
- label: entry.displayName,
879
- ref,
880
- route: entry.provider,
881
- configured,
882
- declared: entry.declared === true,
883
- namesCredential,
884
- group: configured ? "configured" : entry.declared === true ? "custom" : "available",
885
- settingsNs: entry.settingsNs,
886
- settingsPath: [...entry.settingsPath]
887
- });
888
- }
889
- return options;
890
- }
891
- /** Resolve a /login or /logout argument with the SAME rules the command has
892
- * always used: a route name (or a label's first word) wins, then a literal
893
- * env-var-looking name (uppercased like the old behavior); anything else is
894
- * unknown. */
895
- function classifyCredentialArg(arg, options) {
896
- const trimmed = arg.trim();
897
- if (trimmed === "") return void 0;
898
- const needle = trimmed.toLowerCase();
899
- const route = options.find((option) => option.route !== void 0 && option.route.toLowerCase() === needle) ?? options.find((option) => option.label.toLowerCase() === needle || option.label.split(" ")[0].toLowerCase() === needle);
900
- if (route !== void 0) return {
901
- kind: "route",
902
- option: route
903
- };
904
- const exactRef = options.find((option) => option.ref.toLowerCase() === needle);
905
- if (exactRef !== void 0) return {
906
- kind: "ref",
907
- ref: exactRef.ref
908
- };
909
- if (/^[a-zA-Z][a-zA-Z0-9_]*$/.test(trimmed)) return {
910
- kind: "ref",
911
- ref: trimmed.toUpperCase()
912
- };
913
- }
914
- //#endregion
915
- //#region src/runtime/session-lifecycle-port.ts
916
- /** A lifecycle outcome that must ABORT the caller's transition, carrying the
917
- * two independent axes so a Remote caller never has to parse a string. */
918
- var LifecycleError = class extends Error {
919
- settlement;
920
- ownership;
921
- publishedSessionId;
922
- /** CORRELATION ONLY for an indeterminate create — never publication proof. */
923
- requestedSessionId;
924
- constructor(settlement, ownership, message, publishedSessionId, requestedSessionId) {
925
- super(message);
926
- this.name = "LifecycleError";
927
- this.settlement = settlement;
928
- this.ownership = ownership;
929
- this.publishedSessionId = publishedSessionId;
930
- this.requestedSessionId = requestedSessionId;
931
- }
932
- };
933
- /** Unwrap a CREATE result for the runner's transition: a `created` result that
934
- * still owns the surface yields the handle; everything else aborts with a
935
- * machine-readable `LifecycleError` (a superseded create is NOT committed to
936
- * the local surface, though its identity stays available). */
937
- function requireCreated(result) {
938
- const { ownership, outcome } = result;
939
- switch (outcome.kind) {
940
- case "created":
941
- 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);
942
- return outcome.handle;
943
- 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);
944
- 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);
945
- case "rejected": throw new LifecycleError(outcome.kind, ownership, `${outcome.error.message} (${outcome.error.code})`, void 0);
946
- case "cancelled": throw new LifecycleError("cancelled", ownership, "the Session creation was cancelled before dispatch", void 0);
947
- }
948
- }
949
- /** Unwrap an OPEN result for the runner's transition. */
950
- function requireOpened(result) {
951
- const { ownership, outcome } = result;
952
- switch (outcome.kind) {
953
- case "opened":
954
- if (ownership === "superseded") throw new LifecycleError("superseded", ownership, "the Session was opened but the local surface was superseded", outcome.handle.session.id);
955
- return outcome.handle;
956
- case "unavailable": throw new LifecycleError("unavailable", ownership, outcome.message, void 0);
957
- case "cancelled": throw new LifecycleError("cancelled", ownership, "the Session open was cancelled before selection", void 0);
958
- }
959
- }
960
- /** Extract the Direct ownership handle (the real AgentHandle with
961
- * `dispose()`) from a lifecycle result. Accepts both the converged
962
- * SessionHandle and a legacy AgentHandle so transition code cannot lose the
963
- * ownership capability. Remote handles lack `direct` and yield undefined. */
964
- function ownerHandleOf(next) {
965
- const handle = next;
966
- if (handle.direct?.ownerHandle !== void 0) return handle.direct.ownerHandle;
967
- if (typeof handle.dispose === "function") return handle;
968
- }
969
- /** Extract the live in-process agent from a lifecycle result (the Direct
970
- * SessionHandle via `direct.agent`, or a legacy AgentHandle's `agent`).
971
- * Remote handles yield undefined. */
972
- function directAgentOf(next) {
973
- const handle = next;
974
- return handle.direct?.agent ?? handle.agent;
975
- }
976
- /** Extract the Remote Client generation owner from a lifecycle result. A
977
- * Direct handle yields undefined. A composing Remote caller must release it
978
- * exactly once on retirement — including when a superseded transition discards
979
- * the handle. The Remote session-owner provider (`app/remote/session-owners.ts`)
980
- * consumes it as the sole ownership mapping source; the Direct runner never
981
- * interprets it. */
982
- function clientOwnerOf(next) {
983
- return next.client;
984
- }
985
- //#endregion
986
- //#region src/runtime/deliverables-port.ts
987
- /** One DEFINITE read refusal the preview renders as a state (never a guess). */
988
- var DeliveredFileReadError = class extends Error {
989
- code;
990
- constructor(code, message, options) {
991
- super(message, options);
992
- this.name = "DeliveredFileReadError";
993
- this.code = code;
994
- }
995
- };
996
- /**
997
- * The official refusal code → the preview's semantic code.
998
- *
999
- * `gateway/lookup-not-found` is the generated Remote's ASSEMBLY refusal when its
1000
- * Session-derived `workspaceFileScope` lookup cannot resolve the identity (a
1001
- * closed/unknown Session): the preview's `session-unavailable`, never a
1002
- * fabricated "Host says the file is missing".
1003
- */
1004
- const OFFICIAL_CODE_MAP = {
1005
- "workspace-file/not-found": "not-found",
1006
- "workspace-file/not-text": "not-text",
1007
- "workspace-file/not-regular-file": "not-regular-file",
1008
- "workspace-file/too-large": "too-large",
1009
- "gateway/lookup-not-found": "session-unavailable"
1010
- };
1011
- /** Whether one value is a module/instance code carrier. */
1012
- function codeOf(error) {
1013
- if (typeof error !== "object" || error === null) return void 0;
1014
- const code = error.code;
1015
- return typeof code === "string" ? code : void 0;
1016
- }
1017
- /**
1018
- * Map ONE official failure onto the port's vocabulary.
1019
- *
1020
- * A recognized `workspace-file/*` refusal becomes a definite
1021
- * {@link DeliveredFileReadError}; ANYTHING else is returned as-is so the caller
1022
- * keeps its own honesty (the UI reports an unknown failure and its diagnostics
1023
- * channel records the cause) instead of receiving a fabricated state.
1024
- * @param error - the thrown/rejected Host value.
1025
- * @returns the mapped refusal, or the original error when unrecognized.
1026
- */
1027
- function deliveredFileReadErrorFrom(error) {
1028
- const code = codeOf(error);
1029
- if (code === void 0) return error;
1030
- const mapped = OFFICIAL_CODE_MAP[code];
1031
- if (mapped === void 0) return error;
1032
- return new DeliveredFileReadError(mapped, error instanceof Error ? error.message : `${code}`, { cause: error });
1033
- }
1034
- //#endregion
1035
- //#region src/runtime/capability.ts
1036
- /** The capabilities the experimental Remote backend serves: exactly the
1037
- * ports its M3-3B assembly provides. A capability is added HERE only when its
1038
- * Remote port genuinely serves the semantic contract (no misleading empty
1039
- * defaults), so the set is deliberately explicit rather than derived. */
1040
- const REMOTE_IMPLEMENTED_CAPABILITIES = [
1041
- "session-read",
1042
- "session-write",
1043
- "session-lifecycle",
1044
- "subagent",
1045
- "interaction",
1046
- "catalog",
1047
- "config",
1048
- "host-file",
1049
- "session-archive",
1050
- "host-command",
1051
- "plugin-manager",
1052
- "job-observation"
1053
- ];
1054
- /** The capabilities the Direct backend ACTUALLY serves today: one port per
1055
- * entry, nothing more — never advertise what is not served. */
1056
- const DIRECT_IMPLEMENTED_CAPABILITIES = [
1057
- "session-read",
1058
- "session-write",
1059
- "session-lifecycle",
1060
- "subagent",
1061
- "interaction",
1062
- "catalog",
1063
- "config",
1064
- "host-file",
1065
- "session-archive",
1066
- "host-command",
1067
- "plugin-manager",
1068
- "job-observation"
1069
- ];
1070
- //#endregion
1071
- //#region src/runtime/write-outcome.ts
1072
- /**
1073
- * Pinned Gateway infrastructure codes raised strictly BEFORE the addressed
1074
- * business method is invoked (descriptor/argument/receiver/endpoint resolution
1075
- * and context/lookup provider resolution — all inside `prepareInvocation` and
1076
- * boundary decoding): such a failure proves the operation did not commit. The
1077
- * only Gateway code raised AFTER invocation is `gateway/result-invalid`, so it
1078
- * is deliberately absent.
1079
- */
1080
- const GATEWAY_PRE_INVOCATION_CODES = /* @__PURE__ */ new Set([
1081
- "gateway/ambiguous-endpoint",
1082
- "gateway/arguments-invalid",
1083
- "gateway/binding-invalid",
1084
- "gateway/context-failed",
1085
- "gateway/context-not-found",
1086
- "gateway/context-unavailable",
1087
- "gateway/definition-unavailable",
1088
- "gateway/input-invalid",
1089
- "gateway/invocation-unavailable",
1090
- "gateway/lookup-failed",
1091
- "gateway/lookup-not-found",
1092
- "gateway/lookup-unavailable",
1093
- "gateway/method-unavailable",
1094
- "gateway/provider-mismatch",
1095
- "gateway/service-unavailable",
1096
- "gateway/signature-invalid"
1097
- ]);
1098
- /**
1099
- * Whether a failure code PROVES the addressed operation was refused: domain
1100
- * codes, `gateway/bad-request`, and the pinned pre-invocation Gateway
1101
- * infrastructure codes qualify. `gateway/cancelled`, `gateway/internal`,
1102
- * `gateway/result-invalid`, an unknown `gateway/*` code, or a code-less failure
1103
- * do NOT (the commit state stays unproven).
1104
- *
1105
- * SCOPE: this predicate expresses ONLY the D2.2-verified write vocabulary plus
1106
- * the pinned Gateway pre-invocation codes. It is NOT a general
1107
- * idempotency/commit judgement: a domain code does not universally prove that
1108
- * no mutation happened (e.g. `session/workspace-attach-failed` can follow a
1109
- * successful Session create/fork). Later operation families (D2.3/D2.4) must
1110
- * use their own operation-specific settlement table rather than extending this
1111
- * helper.
1112
- */
1113
- function isRemoteBusinessRefusalCode(code) {
1114
- if (code === void 0) return false;
1115
- if (code === "gateway/bad-request") return true;
1116
- if (code.startsWith("gateway/")) return GATEWAY_PRE_INVOCATION_CODES.has(code);
1117
- return true;
1118
- }
1119
- //#endregion
1120
- //#region src/runtime/subagent-outcome.ts
1121
- /**
1122
- * Backend-neutral outcome/error classification for one subagent viewer prompt
1123
- * (TS8-F4): the stable refusal taxonomy shared by the Direct and Remote
1124
- * adapters. Pure and never throwing — it reads structural `code` values only,
1125
- * so the subagent package stays resolvable from the dsh installation and is
1126
- * never imported here.
1127
- * @module @xmoon76/dsh-pi-tui/runtime/subagent-outcome
1128
- */
1129
- /**
1130
- * Settle a failed viewer prompt. A caller cancellation and every PROVEN refusal
1131
- * code are rejected (a domain `subagent/*` admission refusal, `gateway/bad-request`,
1132
- * or a pre-invocation Gateway infrastructure code); only a carrier/internal/
1133
- * post-invocation failure (`gateway/internal`, `gateway/result-invalid`, an
1134
- * unknown `gateway/*` code) or a code-less throw settles `indeterminate`.
1135
- */
1136
- function classifySubagentPromptSettlement(error) {
1137
- const reason = classifySubagentPromptError(error);
1138
- if (reason.kind !== "error") return {
1139
- kind: "rejected",
1140
- reason
1141
- };
1142
- if (isRemoteBusinessRefusalCode(remoteErrorCode(error))) return {
1143
- kind: "rejected",
1144
- reason
1145
- };
1146
- return {
1147
- kind: "indeterminate",
1148
- message: reason.message
1149
- };
1150
- }
1151
- /**
1152
- * Classify an official prompt failure into the stable reason set. The Direct
1153
- * adapter reads the official RemoteError vocabulary structurally (the `code`
1154
- * string; the subagent package stays resolvable from the dsh installation,
1155
- * never an import here).
1156
- */
1157
- function classifySubagentPromptError(error) {
1158
- if (isAbortError(error)) return { kind: "cancelled" };
1159
- const code = remoteErrorCode(error);
1160
- if (code === "gateway/cancelled") return { kind: "cancelled" };
1161
- if (code === "subagent/parent-unavailable") return { kind: "parent-unavailable" };
1162
- if (code === "subagent/not-resumable" || code === "subagent/not-found" || code === "subagent/catalog-diagnostic") return { kind: "stale-child" };
1163
- if (code === "subagent/unauthorized") return { kind: "unauthorized" };
1164
- if (code === "subagent/delivery-unavailable" || code === "subagent/projections-unavailable") return { kind: "unavailable" };
1165
- return {
1166
- kind: "error",
1167
- message: safeSubagentErrorMessage(error)
1168
- };
1169
- }
1170
- /** The stable failure code of a structural official failure, if any. */
1171
- function remoteErrorCode(error) {
1172
- if (typeof error !== "object" || error === null) return void 0;
1173
- const code = error.code;
1174
- return typeof code === "string" && code !== "" ? code : void 0;
1175
- }
1176
- function isAbortError(error) {
1177
- return typeof error === "object" && error !== null && error.name === "AbortError";
1178
- }
1179
- /** One-line safe error text (never throws on hostile values). Shared with the
1180
- * Direct adapter's pre-dispatch catch so both settle the same wording. */
1181
- function safeSubagentErrorMessage(error) {
1182
- if (error === void 0 || error === null) return "unknown error";
1183
- if (typeof error === "string") return error;
1184
- if (error instanceof Error) {
1185
- const message = error.message;
1186
- return message === "" ? error.name : message;
1187
- }
1188
- if (typeof error === "object") {
1189
- const message = error.message;
1190
- if (typeof message === "string" && message !== "") return message;
1191
- }
1192
- try {
1193
- return String(error);
1194
- } catch {
1195
- return "unknown error";
1196
- }
1197
- }
1198
- //#endregion
1199
- //#region src/runtime/presentation-read-port.ts
1200
- /** Detach the official `turnOutline` wire view into the picker DTO — only
1201
- * well-formed entries cross (shared by the Direct projection read and the
1202
- * Remote binding projection read); a foreign-shaped value reads unknown. */
1203
- function detachedTurnOutline(value) {
1204
- if (!Array.isArray(value)) return void 0;
1205
- const entries = [];
1206
- for (const entry of value) {
1207
- if (typeof entry !== "object" || entry === null) return void 0;
1208
- const record = entry;
1209
- if (typeof record.turn !== "number" || typeof record.seq !== "number") return void 0;
1210
- if (typeof record.prompt !== "string" || typeof record.response !== "string") return void 0;
1211
- entries.push({
1212
- turn: record.turn,
1213
- seq: record.seq,
1214
- prompt: record.prompt,
1215
- response: record.response
1216
- });
1217
- }
1218
- return Object.freeze(entries);
1219
- }
1220
- //#endregion
1221
- //#region src/runtime/session-status-projection.ts
1222
- /**
1223
- * Detach the official projection values into the status DTO. Fields are
1224
- * only present when their official projection value is well-formed; nothing
1225
- * is coerced, defaulted or copied from another subject.
1226
- */
1227
- function detachedSessionStatus(sessionId, values, cwd) {
1228
- const record = { sessionId };
1229
- if (typeof cwd === "string" && cwd !== "") record.cwd = cwd;
1230
- const model = modelSelectionFact(values.modelSelection);
1231
- if (model !== void 0) record.model = model;
1232
- if (typeof values.agentPreset === "string" && values.agentPreset !== "") record.preset = values.agentPreset;
1233
- if (typeof values.title === "string" && values.title !== "") record.title = values.title;
1234
- const permissionValue = values.permissions;
1235
- if (typeof permissionValue === "object" && permissionValue !== null) {
1236
- const current = permissionValue.currentValue;
1237
- if (typeof current === "string" && current !== "") record.permission = current;
1238
- }
1239
- if ("goal" in values) {
1240
- const goal = goalFact(values.goal);
1241
- if (goal !== void 0) record.goal = goal;
1242
- }
1243
- const pressure = numericRecord(values.contextPressure);
1244
- const breakdownValue = values.contextBreakdown;
1245
- const breakdown = typeof breakdownValue === "object" && breakdownValue !== null ? numericRecord(breakdownValue) : void 0;
1246
- const hasBreakdown = breakdown !== void 0 && typeof breakdown.systemTokens === "number" && typeof breakdown.toolsTokens === "number" && typeof breakdown.messageTokens === "number";
1247
- if (pressure !== void 0 && Object.keys(pressure).length > 0 || hasBreakdown) record.context = {
1248
- ...pressure ?? {},
1249
- ...hasBreakdown ? { breakdown: {
1250
- systemTokens: breakdown.systemTokens,
1251
- toolsTokens: breakdown.toolsTokens,
1252
- messageTokens: breakdown.messageTokens
1253
- } } : {}
1254
- };
1255
- const todos = detachedTodos(values.todos);
1256
- if (todos !== void 0) record.todos = todos;
1257
- const usageValue = numericRecord(values.tokenUsage);
1258
- if (usageValue !== void 0 && typeof usageValue.uncachedInputTokens === "number" && typeof usageValue.outputTokens === "number" && typeof usageValue.cacheReadTokens === "number" && typeof usageValue.cacheWriteTokens === "number") record.usage = {
1259
- uncachedInputTokens: usageValue.uncachedInputTokens,
1260
- outputTokens: usageValue.outputTokens,
1261
- cacheReadTokens: usageValue.cacheReadTokens,
1262
- cacheWriteTokens: usageValue.cacheWriteTokens
1263
- };
1264
- const performance = performanceProjection(values.piTuiPerformance);
1265
- if (performance !== void 0) record.performance = performance;
1266
- return record;
1267
- }
1268
- /** A finite non-negative projection number, or `undefined` (never coerced,
1269
- * never defaulted). */
1270
- function finiteNumber(value) {
1271
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1272
- }
1273
- /** Whether every entry of a candidate tuple is present (the shape gate). */
1274
- function allDefined(values) {
1275
- return values.every((entry) => entry !== void 0);
1276
- }
1277
- /**
1278
- * Detach the bundle's own `piTuiPerformance` wire value: BOTH scopes with all
1279
- * of their finite non-negative counters, or `undefined` — a malformed,
1280
- * foreign or partial value reads absent (the capability cannot answer), never
1281
- * a partially copied or coerced projection.
1282
- */
1283
- function performanceProjection(value) {
1284
- if (typeof value !== "object" || value === null) return void 0;
1285
- const source = value;
1286
- const recent = typeof source.recent === "object" && source.recent !== null ? source.recent : void 0;
1287
- const all = typeof source.all === "object" && source.all !== null ? source.all : void 0;
1288
- if (recent === void 0 || all === void 0) return void 0;
1289
- const fields = [
1290
- finiteNumber(recent.outputTokens),
1291
- finiteNumber(recent.modelMs),
1292
- finiteNumber(recent.samples),
1293
- finiteNumber(recent.firstTokenMs),
1294
- finiteNumber(recent.firstTokenSamples),
1295
- finiteNumber(all.outputTokens),
1296
- finiteNumber(all.modelMs),
1297
- finiteNumber(all.samples)
1298
- ];
1299
- if (!allDefined(fields)) return void 0;
1300
- const [recentOutputTokens, recentModelMs, recentSamples, firstTokenMs, firstTokenSamples, allOutputTokens, allModelMs, allSamples] = fields;
1301
- return {
1302
- recent: {
1303
- outputTokens: recentOutputTokens,
1304
- modelMs: recentModelMs,
1305
- samples: recentSamples,
1306
- firstTokenMs,
1307
- firstTokenSamples
1308
- },
1309
- all: {
1310
- outputTokens: allOutputTokens,
1311
- modelMs: allModelMs,
1312
- samples: allSamples
1313
- }
1314
- };
1315
- }
1316
- /** Narrow the official `goal` projection view: `null` (no goal) is a LEGAL
1317
- * value and stays distinct from `undefined` (unavailable); the current goal
1318
- * is read from `goal.{objective,phase}` with the phase vocabulary validated. */
1319
- function goalFact(value) {
1320
- if (value === null) return null;
1321
- if (typeof value !== "object") return void 0;
1322
- const current = value.goal;
1323
- if (typeof current !== "object" || current === null) return void 0;
1324
- const goal = current;
1325
- if (typeof goal.objective !== "string" || goal.objective === "") return void 0;
1326
- if (goal.phase !== "active" && goal.phase !== "paused" && goal.phase !== "blocked" && goal.phase !== "complete") return;
1327
- return {
1328
- objective: goal.objective,
1329
- phase: goal.phase
1330
- };
1331
- }
1332
- /** Narrow an unknown projection value to its numeric fields (no coercion). */
1333
- function numericRecord(value) {
1334
- if (typeof value !== "object" || value === null) return void 0;
1335
- const source = value;
1336
- const out = {};
1337
- for (const [key, entry] of Object.entries(source)) if (typeof entry === "number") out[key] = entry;
1338
- return out;
1339
- }
1340
- /** The effective selection off the official `modelSelection` fold:
1341
- * `next ?? lastUsed`, validated to the normalized shape. */
1342
- function modelSelectionFact(value) {
1343
- if (typeof value !== "object" || value === null) return void 0;
1344
- const fold = value;
1345
- for (const candidate of [fold.next, fold.lastUsed]) {
1346
- if (typeof candidate !== "object" || candidate === null) continue;
1347
- const selection = candidate;
1348
- if (typeof selection.provider !== "string" || selection.provider === "") continue;
1349
- if (typeof selection.model !== "string" || selection.model === "") continue;
1350
- return {
1351
- provider: selection.provider,
1352
- model: selection.model,
1353
- ...typeof selection.reasoningEffort === "string" && selection.reasoningEffort !== "" ? { reasoningEffort: selection.reasoningEffort } : {}
1354
- };
1355
- }
1356
- }
1357
- /** Detach the official `todos` whole-list snapshot. The projection's
1358
- * LEGAL `null` (no `todo/write` yet) stays `null`; only `undefined` (the
1359
- * projection value was absent — capability unavailable) reads absent. */
1360
- function detachedTodos(value) {
1361
- if (value === null) return null;
1362
- if (value === void 0) return void 0;
1363
- if (!Array.isArray(value)) return void 0;
1364
- const todos = [];
1365
- for (const item of value) {
1366
- if (typeof item !== "object" || item === null) return void 0;
1367
- const todo = item;
1368
- if (typeof todo.content !== "string") return void 0;
1369
- if (todo.status !== "pending" && todo.status !== "in_progress" && todo.status !== "completed") return void 0;
1370
- todos.push({
1371
- content: todo.content,
1372
- status: todo.status
1373
- });
1374
- }
1375
- return Object.freeze(todos);
1376
- }
1377
- //#endregion
1378
- //#region src/runtime/interaction-port.ts
1379
- /** The official Host code for a late answer whose reply is already queued. */
1380
- const QUESTION_REPLY_QUEUED = "REPLY_QUEUED";
1381
- /** The official Host code for a late answer that does not name each question. */
1382
- const QUESTION_BAD_ANSWER = "BAD_ANSWER";
1383
- /**
1384
- * One rejected late answer with the Host's stable code (`REPLY_QUEUED`,
1385
- * `BAD_ANSWER`, `CALLER_NOT_LIVE`, or a transport/gateway code). Both
1386
- * adapters throw THIS shape so a consumer can offer truthful recovery
1387
- * without switching on a backend.
1388
- */
1389
- var QuestionAnswerError = class extends Error {
1390
- code;
1391
- constructor(code, message, options) {
1392
- super(message, options);
1393
- this.name = "QuestionAnswerError";
1394
- this.code = code;
1395
- }
1396
- };
1397
- /** Wrap an unknown failure from the late-answer path in the port vocabulary. */
1398
- function questionAnswerError(error) {
1399
- if (error instanceof QuestionAnswerError) return error;
1400
- 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 });
1401
- }
1402
- //#endregion
1403
- //#region src/runtime/direct/file-completion/host-discovery.ts
1404
- /**
1405
- * The Direct Host discovery implementation (TS8-A, renamed by TS8-HF1): the
1406
- * DIRECT process's filesystem behind the neutral {@link LocalDiscoveryDriver}
1407
- * contract. It has two legitimate consumers:
1408
- *
1409
- * ```text
1410
- * 1. the sessionless `HostFileScope { kind: 'workspace', cwd }` compatibility
1411
- * path of `DirectHostFilePort` (the cold surface with no official carrier);
1412
- * 2. the explicit-path `@` navigation route of the Session scope
1413
- * (`runtime/direct/host-file-augmentation-direct.ts`), where the user
1414
- * explicitly typed the scope (`@src/`, `@../`, `@/abs`, `@~/`).
1415
- * ```
1416
- *
1417
- * A BARE Session `@` query (`@foo`) never runs through this adapter — that
1418
- * path is the OFFICIAL Host authority's (`ctx.fileReferences.list` through the
1419
- * port), whose candidates arrive already filtered, ranked and bounded.
1420
- *
1421
- * It owns the Direct Host process's own PATH/PATHEXT finder detection, its
1422
- * `node:fs` facts and its fd/fdfind process. The small syscall-level
1423
- * duplication against `client/file-completion/local-discovery.ts` is
1424
- * deliberate: the two adapters read DIFFERENT machines under Remote, and one
1425
- * concrete source owner for both localities is exactly what TS8-A removes.
1426
- * @module @xmoon76/dsh-pi-tui/runtime/direct/file-completion/host-discovery
1427
- */
1428
- /**
1429
- * The Direct Host process's explicit path-query environment facts. Under
1430
- * Remote these are the HOST machine's facts, never the Client's; today Direct
1431
- * runs in-process, so the numbers coincide — that coincidence is deliberately
1432
- * not encoded in the domain contract.
1433
- */
1434
- function hostPathQueryEnvironment() {
1435
- return {
1436
- homeDir: homedir(),
1437
- windowsHost: process.platform === "win32"
1438
- };
1439
- }
1440
- /**
1441
- * Locate an executable file-finder on the Direct Host process's PATH: `fd`
1442
- * preferred, `fdfind` second. See the Client adapter for the probe contract.
1443
- */
1444
- function resolveFdPath() {
1445
- const pathEntries = process.env.PATH?.split(delimiter) ?? [];
1446
- 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()]);
1447
- for (const name of ["fd", "fdfind"]) for (const entry of pathEntries) {
1448
- const dir = entry === "" ? "." : entry;
1449
- for (const suffix of ["", ...suffixes]) {
1450
- const candidate = join(dir, `${name}${suffix}`);
1451
- try {
1452
- if (statSync(candidate).isFile() && accessSync(candidate, constants.X_OK) === void 0) return candidate;
1453
- } catch {}
1454
- }
1455
- }
1456
- return null;
1457
- }
1458
- /** Join a Host path WITHOUT collapsing a `..` segment. The Host's filesystem
1459
- * backend anchors a POSIX path containing a `..` segment with its physical
1460
- * spelling (the kernel resolves an intermediate symlink before the parent step),
1461
- * so a search base that deliberately keeps that traversal may not be lexically
1462
- * re-normalized on the way to a syscall. For every base the neutral resolver
1463
- * already normalized (no `..` left) this is identical to `path.join`. */
1464
- function hostJoin(baseDir, relative) {
1465
- if (relative === "") return baseDir;
1466
- return baseDir.endsWith("/") ? `${baseDir}${relative}` : `${baseDir}/${relative}`;
1467
- }
1468
- /** Whether one Dirent is a directory (symlinks followed; a broken link is a
1469
- * file candidate — the fork's rule). */
1470
- function entryIsDirectory(baseDir, name, entry) {
1471
- if (entry.isDirectory()) return true;
1472
- if (entry.isSymbolicLink()) try {
1473
- return statSync(hostJoin(baseDir, name)).isDirectory();
1474
- } catch {
1475
- return false;
1476
- }
1477
- return false;
1478
- }
1479
- /** Run the Direct Host finder for one scoped query. Returns NULL on finder
1480
- * FAILURE (the neutral policy then runs the bounded fallback), `[]` on a
1481
- * genuine no-match or an abort. */
1482
- function runHostFinder(fdPath, baseDir, term, signal) {
1483
- const args = [
1484
- "--base-directory",
1485
- baseDir,
1486
- "--max-results",
1487
- String(100),
1488
- "-i",
1489
- "--full-path",
1490
- "--print0",
1491
- "--type",
1492
- "f",
1493
- "--type",
1494
- "d",
1495
- "--type",
1496
- "l",
1497
- "--hidden",
1498
- "--exclude",
1499
- ".git",
1500
- "--exclude",
1501
- ".git/*",
1502
- "--exclude",
1503
- ".git/**"
1504
- ];
1505
- if (term !== "") args.push(escapeFinderRegex(term));
1506
- return new Promise((resolve) => {
1507
- if (signal.aborted) {
1508
- resolve([]);
1509
- return;
1510
- }
1511
- let child;
1512
- try {
1513
- child = spawn(fdPath, args, { stdio: [
1514
- "ignore",
1515
- "pipe",
1516
- "ignore"
1517
- ] });
1518
- } catch {
1519
- resolve(null);
1520
- return;
1521
- }
1522
- let stdout = "";
1523
- let settled = false;
1524
- const settle = (results) => {
1525
- if (settled) return;
1526
- settled = true;
1527
- signal.removeEventListener("abort", onAbort);
1528
- resolve(results);
1529
- };
1530
- const onAbort = () => {
1531
- if (child.exitCode === null) child.kill("SIGKILL");
1532
- settle([]);
1533
- };
1534
- signal.addEventListener("abort", onAbort, { once: true });
1535
- child.stdout.setEncoding("utf-8");
1536
- child.stdout.on("data", (chunk) => {
1537
- stdout += chunk;
1538
- });
1539
- child.on("error", () => settle(null));
1540
- child.on("close", (code) => {
1541
- if (signal.aborted) {
1542
- settle([]);
1543
- return;
1544
- }
1545
- if (code !== 0) {
1546
- settle(null);
1547
- return;
1548
- }
1549
- const results = [];
1550
- for (const record of normalizeFinderRecords(stdout)) {
1551
- let isDirectory = record.directoryHint;
1552
- if (!isDirectory) try {
1553
- isDirectory = statSync(hostJoin(baseDir, record.path)).isDirectory();
1554
- } catch {
1555
- isDirectory = false;
1556
- }
1557
- results.push({
1558
- path: record.path,
1559
- kind: isDirectory ? "directory" : "file"
1560
- });
1561
- }
1562
- settle(results);
1563
- });
1564
- });
1565
- }
1566
- /**
1567
- * The Direct Host discovery driver: the Direct Host process's OWN filesystem,
1568
- * with a Host PATH finder when present.
1569
- *
1570
- * `fdPath` is a test/API pin: `undefined` probes the Host PATH, `null` FORCES
1571
- * the bounded fallback (no finder), a string pins one finder.
1572
- */
1573
- var DirectHostDiscoveryDriver = class {
1574
- fdPathValue;
1575
- constructor(fdPath = void 0) {
1576
- this.fdPathValue = fdPath === void 0 ? resolveFdPath() : fdPath;
1577
- }
1578
- /** The pinned/detected Host finder (null = bounded-fallback only). */
1579
- get fdPath() {
1580
- return this.fdPathValue;
1581
- }
1582
- async listDirectory(baseDir, relativeDir, signal) {
1583
- if (signal.aborted) return null;
1584
- let entries;
1585
- try {
1586
- entries = readdirSync(hostJoin(baseDir, relativeDir), { withFileTypes: true });
1587
- } catch {
1588
- return null;
1589
- }
1590
- if (signal.aborted) return null;
1591
- const dir = hostJoin(baseDir, relativeDir);
1592
- return entries.map((entry) => ({
1593
- name: entry.name,
1594
- kind: entryIsDirectory(dir, entry.name, entry) ? "directory" : "file",
1595
- descendable: entry.isDirectory() && !entry.isSymbolicLink()
1596
- }));
1597
- }
1598
- async find(baseDir, term, signal) {
1599
- if (this.fdPathValue === null) return null;
1600
- return runHostFinder(this.fdPathValue, baseDir, term, signal);
1601
- }
1602
- };
1603
- //#endregion
1604
- //#region src/runtime/direct/host-file-augmentation-direct.ts
1605
- /**
1606
- * The session `@`-reference Host router (TS8-HF1): ONE Host-side authority
1607
- * that answers a completion query with the routing boundary
1608
- *
1609
- * ```text
1610
- * bare workspace fuzzy search -> official ctx.fileReferences.list
1611
- * @foo @readme @src @.env (workspace index, cache, exclusions,
1612
- * scoring, maxResults stay authoritative)
1613
- *
1614
- * explicit path navigation -> dsh-pi-tui Host scoped discovery
1615
- * @src/ @src/uti @./ @../shared/foo (the exact scope the user typed:
1616
- * @../../foo @/tmp/foo @~/Down recursive fuzzy inside it, explicit
1617
- * Windows drive @C:/work/foo and UNC parent/absolute/native paths)
1618
- * ```
1619
- *
1620
- * The decision is the TOKEN's explicit path navigation, never the resolved
1621
- * search base's workspace containment (the superseded v1 rule): a user-typed
1622
- * separator, a root form (`.`/`..`/`~`) or a Windows absolute path is what
1623
- * selects the scoped route, so `@dist/` and `@link/foo` address their
1624
- * explicitly named scope even when the official provider would exclude or not
1625
- * traverse it.
1626
- *
1627
- * POSIX BOUNDARY: on a POSIX Host a backslash is an ordinary FILENAME character,
1628
- * but the reused TS8-A path resolver selects its Windows dialect from the token
1629
- * alone and normalizes the separators (a pinned cross-dialect contract of the
1630
- * Client-local completion — `test/domain-file-completion.test.ts`). The
1631
- * augmentation therefore does NOT CLAIM an ambiguous POSIX token that contains a
1632
- * backslash: such a token is left to the official provider rather than searched
1633
- * in a scope we cannot represent verbatim. This is a deliberate fail-closed
1634
- * narrowing, not a claim that the token is a bare fuzzy query; delete the guard
1635
- * once the shared resolver distinguishes host dialect, token dialect and literal
1636
- * backslashes.
1637
- *
1638
- * PARENT-TRAVERSAL SPELLING: a relative scope is searched with the SAME spelling
1639
- * the Host's local filesystem backend gives the accepted value. On a POSIX Host a
1640
- * path containing a `..` segment is anchored with its PHYSICAL spelling by
1641
- * `dsh-fs-local` (kernel resolves an intermediate symlink before the parent step);
1642
- * the scoped search therefore keeps the raw `<cwd>/<displayBase>` concatenation for
1643
- * those queries instead of the lexically joined directory, so completion and the
1644
- * model's read can never land in two different physical directories. Windows, the
1645
- * absolute forms (already verbatim) and the home shorthand (absolute normalized
1646
- * value) keep the shared resolver's spelling.
1647
- *
1648
- * The official provider is called ONLY on the bare route; an authoritative
1649
- * official `[]` stays empty and never falls back to the scanner. The scoped
1650
- * route never calls the official provider and needs no capability from it.
1651
- *
1652
- * Home shorthand (`@~`, `@~/Down`) is dsh-pi-tui INPUT syntax: discovery runs
1653
- * against the Host HOME, but every returned candidate is materialized as an
1654
- * ABSOLUTE Host path — DSH path resolution performs no shell-style `~`
1655
- * expansion, so a literal `~/...` completion value would be unusable. Ranking
1656
- * always scores the SCOPE-RELATIVE candidate, never the materialized absolute
1657
- * path (the home prefix itself must not satisfy the path-substring tier).
1658
- *
1659
- * This authority receives HOST facts only (the live Agent, the Host discovery
1660
- * driver, the Host path environment); it never reads the Client cwd, home or
1661
- * platform.
1662
- *
1663
- * TODO(upstream-file-reference-explicit-scope): Delete the pi-tui
1664
- * explicit-scope augmentation when the minimum supported DSH fileReferences
1665
- * provider supports equivalent explicit scoped recursive search,
1666
- * parent/absolute Host path navigation, explicit excluded/symlink scope
1667
- * access, and a Host-home-safe completion representation.
1668
- *
1669
- * @module @xmoon76/dsh-pi-tui/runtime/direct/host-file-augmentation-direct
1670
- */
1671
- /** Whether the token names an EXPLICIT path scope (the frozen classifier,
1672
- * decided from the raw token and the HOST platform — never from filesystem
1673
- * existence, official result count, or workspace containment).
1674
- *
1675
- * A POSIX host has ONE separator: any `/` is an explicit scope, and the root
1676
- * forms are explicit. A token that also contains a backslash is deliberately NOT
1677
- * claimed (see the module comment): the reused resolver cannot represent its
1678
- * literal POSIX scope, so the official provider keeps it.
1679
- *
1680
- * A Windows host treats `\` as a separator as well and accepts any
1681
- * win32-absolute form (drive/UNC) even before its first separator is visible. */
1682
- function isExplicitPathNavigation(raw, environment) {
1683
- if (raw === "") return false;
1684
- if (environment.windowsHost) return raw === "." || raw === ".." || raw === "~" || raw.includes("/") || raw.includes("\\") || win32.isAbsolute(raw);
1685
- if (raw.includes("\\")) return false;
1686
- return raw === "." || raw === ".." || raw === "~" || raw.includes("/");
1687
- }
1688
- /** Whether the token is a leading-home form (`~`, `~/x`, `~\x`). */
1689
- function isHomeToken(raw) {
1690
- return raw === "~" || raw.startsWith("~/") || raw.startsWith("~\\");
1691
- }
1692
- /** Materialize one candidate discovered under a HOME scope as an ABSOLUTE Host
1693
- * path (the `~` shorthand must never reach the prompt as literal text). */
1694
- function materializeHostPath(candidate, searchBase, windowsHost) {
1695
- return {
1696
- path: (windowsHost ? win32 : posix).join(searchBase, candidate.path),
1697
- kind: candidate.kind
1698
- };
1699
- }
1700
- /** One `..` path SEGMENT — the exact shape the Host filesystem backend keys its
1701
- * physical-spelling rule on (`dsh-fs-local`'s `localDisplayPath`). */
1702
- const PARENT_SEGMENT = /(?:^|[\\/])\.\.(?:[\\/]|$)/u;
1703
- /**
1704
- * The directory one explicit scope searches.
1705
- *
1706
- * The Host's local filesystem backend anchors a POSIX path that contains a `..`
1707
- * SEGMENT with its PHYSICAL spelling (the raw `<anchor>/<path>`, deliberately
1708
- * unnormalized), so the kernel resolves an intermediate symlink BEFORE the parent
1709
- * step; every other spelling goes through a lexical `resolve(anchor, path)`, and
1710
- * Windows always resolves lexically. Two consequences drive this function:
1711
- *
1712
- * 1. The anchor is `<hostCwd>` for a relative scope and the value itself for an
1713
- * absolute one, and the rule tests the WHOLE anchored spelling — so a `..`
1714
- * carried by the SESSION CWD flips it just like one in the typed scope. The
1715
- * consumer applies that rule to the value we hand it (`displayBase + name`), so
1716
- * the search must use the same spelling; otherwise the completion could offer a
1717
- * path the model's read resolves into a DIFFERENT physical directory.
1718
- * 2. A home shorthand emits an ABSOLUTE value through `path.join`, which normalizes
1719
- * lexically. Its scope must be normalized the same way: the bare `~`/`~/` root
1720
- * form is the one form whose search base is the raw `homedir()` string, so a
1721
- * `..`-bearing HOME would otherwise be searched physically while the value we
1722
- * emit names the lexical directory.
1723
- *
1724
- * Absolute forms already spell their traversal verbatim. This is one segment test
1725
- * plus one concatenation (plus one lexical normalize for the home root form) — the
1726
- * consumer's own rule applied to the value we are about to hand it, not a second
1727
- * path parser.
1728
- */
1729
- function scopeSearchBase(resolved, raw, hostCwd, environment) {
1730
- const api = environment.windowsHost ? win32 : posix;
1731
- if (isHomeToken(raw)) return api.normalize(resolved.searchBase);
1732
- if (environment.windowsHost) return resolved.searchBase;
1733
- if (raw.startsWith("/") || resolved.winAbsolute) return resolved.searchBase;
1734
- const physicalScope = `${hostCwd}/${resolved.displayBase}`;
1735
- return PARENT_SEGMENT.test(physicalScope) ? physicalScope : resolved.searchBase;
1736
- }
1737
- /**
1738
- * Answer one session `@` completion query over the Host facts.
1739
- *
1740
- * Cancellation (the caller's `signal`) outranks every route: an aborted
1741
- * request rejects at entry — before the route/capability decision — and again
1742
- * after each await, so a cancelled scope never serves a late result and never
1743
- * reports `unavailable`.
1744
- *
1745
- * @param agent - the live Agent the session scope resolved to.
1746
- * @param query - the official query form (path text following `@`).
1747
- * @param signal - caller cancellation.
1748
- * @param deps - the Host facts this router answers with.
1749
- */
1750
- async function listPiTuiHostFileReferences(agent, query, signal, deps) {
1751
- signal.throwIfAborted();
1752
- if (!isExplicitPathNavigation(query, deps.environment)) {
1753
- const official = deps.official;
1754
- if (official === void 0) return {
1755
- kind: "unavailable",
1756
- reason: "the official Host file-reference service is not mounted"
1757
- };
1758
- const candidates = await official.list(agent, query, signal);
1759
- signal.throwIfAborted();
1760
- return {
1761
- kind: "ok",
1762
- items: candidates.map((candidate) => ({
1763
- path: candidate.path,
1764
- kind: candidate.kind
1765
- }))
1766
- };
1767
- }
1768
- const workspaceCwd = effectiveAgentCwd(deps.workingDirectory, agent) ?? process.cwd();
1769
- const resolved = resolvePathQuery(query, workspaceCwd, deps.environment);
1770
- const searchBase = scopeSearchBase(resolved, query, workspaceCwd, deps.environment);
1771
- const discovered = await discoverForQuery(searchBase === resolved.searchBase ? resolved : {
1772
- ...resolved,
1773
- searchBase
1774
- }, deps.driver, signal);
1775
- signal.throwIfAborted();
1776
- const homeToken = isHomeToken(query);
1777
- return {
1778
- kind: "ok",
1779
- items: rankPathCandidates(homeToken ? discovered : discovered.map((candidate) => reattachDisplayBase(candidate, resolved)), resolved.searchTerm).map((candidate) => homeToken ? materializeHostPath(candidate, resolved.searchBase, deps.environment.windowsHost) : {
1780
- path: candidate.path,
1781
- kind: candidate.kind
1782
- })
1783
- };
1784
- }
1785
- //#endregion
1786
- //#region src/runtime/plugin-manager-mapping.ts
1787
- /** Generate one install request id (the branded shape is a plain string). */
1788
- function pluginInstallRequestId(value) {
1789
- return value;
1790
- }
1791
- /** Resolve one official localized text to the English fallback. */
1792
- function localizedText(value) {
1793
- if (value === void 0) return void 0;
1794
- return typeof value === "string" ? value : value.en;
1795
- }
1796
- function detachIncompatible(entry) {
1797
- return Object.freeze({
1798
- name: entry.name,
1799
- version: entry.version,
1800
- runtimeVersion: entry.runtimeVersion,
1801
- requirements: Object.freeze({ ...entry.requirements })
1802
- });
1803
- }
1804
- function detachError(error) {
1805
- if (error === void 0) return void 0;
1806
- return Object.freeze({
1807
- code: error.code,
1808
- ...error.diagnostic === void 0 ? {} : { diagnostic: error.diagnostic },
1809
- ...error.incompatible === void 0 ? {} : { incompatible: Object.freeze(error.incompatible.map(detachIncompatible)) }
1810
- });
1811
- }
1812
- function pickMeta(meta) {
1813
- const title = localizedText(meta.title);
1814
- const description = localizedText(meta.description);
1815
- return {
1816
- ...title === void 0 ? {} : { title },
1817
- ...description === void 0 ? {} : { description }
1818
- };
1819
- }
1820
- function detachBundle(bundle) {
1821
- const rows = bundle.rows.map((row) => Object.freeze({
1822
- rowId: row.rowId,
1823
- moduleName: row.moduleName,
1824
- ...row.meta === void 0 ? {} : pickMeta(row.meta),
1825
- ...row.entryId === void 0 ? {} : { entryId: String(row.entryId) }
1826
- }));
1827
- return Object.freeze({
1828
- name: bundle.name,
1829
- official: bundle.official,
1830
- availability: bundle.availability,
1831
- ...bundle.installTarget === void 0 ? {} : { installTarget: Object.freeze({
1832
- spec: bundle.installTarget.spec,
1833
- version: bundle.installTarget.version
1834
- }) },
1835
- ...bundle.version === void 0 ? {} : { version: bundle.version },
1836
- ...bundle.meta === void 0 ? {} : pickMeta(bundle.meta),
1837
- ...bundle.description === void 0 ? {} : { description: bundle.description },
1838
- enabled: bundle.enabled,
1839
- installed: bundle.installed,
1840
- optional: bundle.optional,
1841
- ...bundle.source === void 0 ? {} : { source: bundle.source },
1842
- removable: bundle.removable,
1843
- ...bundle.readOnlyReason === void 0 ? {} : { readOnlyReason: bundle.readOnlyReason },
1844
- ...bundle.error === void 0 ? {} : { error: detachError(bundle.error) },
1845
- rows: Object.freeze(rows),
1846
- overrides: Object.freeze([...bundle.overrides])
1847
- });
1848
- }
1849
- function detachPlugin(entry) {
1850
- const addressable = "patchId" in entry;
1851
- return Object.freeze({
1852
- entryId: String(entry.entryId),
1853
- moduleName: entry.moduleName,
1854
- ...entry.meta === void 0 ? {} : pickMeta(entry.meta),
1855
- enabled: entry.enabled,
1856
- fiberPhase: entry.fiberPhase,
1857
- ...addressable ? { patchId: entry.patchId } : { readOnlyReason: entry.readOnlyReason }
1858
- });
1859
- }
1860
- function detachRegistries(registries) {
1861
- return Object.freeze({
1862
- registry: registries.registry,
1863
- fallbackRegistries: Object.freeze([...registries.fallbackRegistries]),
1864
- resolved: registries.resolved
1865
- });
1866
- }
1867
- function detachExemptions(value) {
1868
- return Object.freeze(Object.entries(value.exemptions).map(([packageVersion, runtimeVersions]) => Object.freeze({
1869
- packageVersion,
1870
- runtimeVersions: Object.freeze([...runtimeVersions])
1871
- })));
1872
- }
1873
- /** Map one complete snapshot read onto the detached surface facts. */
1874
- function detachPluginManagerSnapshot(input) {
1875
- return Object.freeze({
1876
- bundles: Object.freeze(input.bundles.map(detachBundle)),
1877
- plugins: Object.freeze(input.plugins.map(detachPlugin)),
1878
- registries: detachRegistries(input.registries),
1879
- exemptions: detachExemptions(input.exemptions),
1880
- exemptionWarnings: Object.freeze([...input.exemptions.warnings])
1881
- });
1882
- }
1883
- function detachPackageResult(result) {
1884
- return Object.freeze({
1885
- exitCode: result.exitCode,
1886
- output: result.output,
1887
- truncated: result.truncated,
1888
- ...result.kind === void 0 ? {} : { kind: result.kind },
1889
- ...result.timedOut === void 0 ? {} : { timedOut: result.timedOut },
1890
- ...result.incompatible === void 0 ? {} : { incompatible: Object.freeze(result.incompatible.map(detachIncompatible)) }
1891
- });
1892
- }
1893
- /** Map one persisted change and its observed application outcome. */
1894
- function detachChange(result) {
1895
- return Object.freeze({
1896
- changed: result.changed,
1897
- application: result.application,
1898
- ...result.restartReason === void 0 ? {} : { restartReason: result.restartReason },
1899
- stage: result.stage,
1900
- target: result.target,
1901
- ...result.enabled === void 0 ? {} : { enabled: result.enabled },
1902
- ...result.error === void 0 ? {} : { error: detachError(result.error) },
1903
- ...result.warnings === void 0 ? {} : { warnings: Object.freeze([...result.warnings]) },
1904
- ...result.bundle === void 0 ? {} : { bundle: result.bundle },
1905
- ...result.version === void 0 ? {} : { version: result.version },
1906
- ...result.pendingBuilds === void 0 ? {} : { pendingBuilds: Object.freeze([...result.pendingBuilds]) },
1907
- ...result.approvedBuilds === void 0 ? {} : { approvedBuilds: Object.freeze([...result.approvedBuilds]) },
1908
- ...result.packageResult === void 0 ? {} : { packageResult: detachPackageResult(result.packageResult) },
1909
- ...result.registries === void 0 ? {} : { registries: Object.freeze([...result.registries]) },
1910
- ...result.failedAt === void 0 ? {} : { failedAt: result.failedAt }
1911
- });
1912
- }
1913
- /** Map what a spec names before installation. */
1914
- function detachInspection(inspection) {
1915
- if (inspection.status === "accepted") return Object.freeze({
1916
- status: "accepted",
1917
- kind: inspection.kind,
1918
- ...inspection.name === void 0 ? {} : { name: inspection.name },
1919
- ...inspection.version === void 0 ? {} : { version: inspection.version },
1920
- ...inspection.description === void 0 ? {} : { description: inspection.description },
1921
- bundle: inspection.bundle,
1922
- registry: inspection.registry,
1923
- ...inspection.host === void 0 ? {} : { host: inspection.host }
1924
- });
1925
- return Object.freeze({
1926
- status: "refused",
1927
- problem: inspection.problem,
1928
- reason: inspection.reason,
1929
- ...inspection.registries === void 0 ? {} : { registries: Object.freeze([...inspection.registries]) }
1930
- });
1931
- }
1932
- /** Map one official install-phase announcement. */
1933
- function detachPhase(progress) {
1934
- return Object.freeze({
1935
- requestId: String(progress.requestId),
1936
- phase: progress.phase,
1937
- ...progress.attempt === void 0 ? {} : { attempt: Object.freeze({
1938
- registry: progress.attempt.registry,
1939
- index: progress.attempt.index,
1940
- total: progress.attempt.total
1941
- }) }
1942
- });
1943
- }
1944
- /** Map one pnpm output chunk. */
1945
- function detachLog(chunk) {
1946
- return Object.freeze({
1947
- ...chunk.requestId === void 0 ? {} : { requestId: String(chunk.requestId) },
1948
- jobId: chunk.jobId,
1949
- stream: chunk.stream,
1950
- text: chunk.text
1951
- });
1952
- }
1953
- //#endregion
1954
- //#region src/domain/terminal-progress/interval.ts
1955
- /**
1956
- * Classify one official `turn/end.reason.kind` (plan §5.2). `completed` is the
1957
- * DSH turn result (not a claim about every business step); `error` and
1958
- * `max-tokens` (a resource ceiling, not success) are `error`; a cancelled /
1959
- * blocked / non-live closer is honestly `idle`. An UNKNOWN upstream kind is
1960
- * NOT guessed — the caller records it and the interval stays `idle`.
1961
- *
1962
- * @param kind - the durable `turn/end` reason kind.
1963
- * @returns the proven outcome, or `undefined` for an unknown kind.
1964
- */
1965
- function classifyTerminalTurnEnd(kind) {
1966
- switch (kind) {
1967
- case "completed": return "done";
1968
- case "error": return "error";
1969
- case "max-tokens": return "error";
1970
- case "aborted":
1971
- case "blocked":
1972
- case "interrupted":
1973
- case "forked": return "idle";
1974
- default: return;
1975
- }
1976
- }
1977
- /**
1978
- * Create one independent fold instance.
1979
- * @param onUnknownReason - reports an unknown `turn/end.reason.kind` (the
1980
- * Host/Direct owner injects its diagnostics channel here); the interval stays
1981
- * `idle` instead of guessing.
1982
- */
1983
- function createTerminalProgressInterval(onUnknownReason) {
1984
- let active = false;
1985
- /** The turn opened by the newest live `turn/start` of THIS interval. */
1986
- let openTurn;
1987
- /** The classified outcome of the newest turn whose `turn/end` matched the
1988
- * open turn — reset whenever a newer turn opens. */
1989
- let lastClosed;
1990
- /** The currently committed outcome of the interval (`idle` while running
1991
- * without a proven result). */
1992
- let outcome = "idle";
1993
- const state = () => ({
1994
- active,
1995
- outcome
1996
- });
1997
- return {
1998
- status(running) {
1999
- if (running) {
2000
- if (active) return void 0;
2001
- active = true;
2002
- openTurn = void 0;
2003
- lastClosed = void 0;
2004
- outcome = "idle";
2005
- return state();
2006
- }
2007
- if (!active) return void 0;
2008
- outcome = openTurn === void 0 ? lastClosed ?? "idle" : "idle";
2009
- active = false;
2010
- openTurn = void 0;
2011
- lastClosed = void 0;
2012
- return state();
2013
- },
2014
- turnStart(turn) {
2015
- if (!active) return;
2016
- openTurn = turn;
2017
- lastClosed = void 0;
2018
- },
2019
- turnEnd(turn, reasonKind) {
2020
- if (!active) return;
2021
- if (openTurn !== turn) return;
2022
- openTurn = void 0;
2023
- const classified = classifyTerminalTurnEnd(reasonKind);
2024
- if (classified === void 0) {
2025
- onUnknownReason?.(reasonKind);
2026
- lastClosed = "idle";
2027
- return;
2028
- }
2029
- lastClosed = classified;
2030
- },
2031
- retire() {
2032
- openTurn = void 0;
2033
- lastClosed = void 0;
2034
- if (!active && outcome === "idle") return void 0;
2035
- active = false;
2036
- return state();
2037
- },
2038
- apply(fact) {
2039
- active = fact.active;
2040
- outcome = fact.outcome;
2041
- openTurn = void 0;
2042
- lastClosed = void 0;
2043
- return state();
2044
- },
2045
- reset() {
2046
- active = false;
2047
- openTurn = void 0;
2048
- lastClosed = void 0;
2049
- outcome = "idle";
2050
- return state();
2051
- },
2052
- snapshot() {
2053
- return state();
2054
- }
2055
- };
2056
- }
2057
- //#endregion
2058
- //#region src/runtime/plugin-manager-port.ts
2059
- /**
2060
- * One plugin mutation's result arrived after the operation's authoritative
2061
- * currentness context was superseded. The write may have been applied, so this
2062
- * is NOT a refusal: the caller must present the outcome as indeterminate and
2063
- * let the authoritative inventory reread decide what is true. A backend
2064
- * adapter raises it only when its own currentness authority proves the reply
2065
- * belongs to a superseded context; this module names no transport.
2066
- */
2067
- var PluginManagerStaleResultError = class extends Error {
2068
- constructor(operation) {
2069
- super(`pluginManager.${operation} returned after its currentness context was superseded; the authoritative inventory reread decides the outcome`);
2070
- this.name = "PluginManagerStaleResultError";
2071
- }
2072
- };
2073
- //#endregion
2074
- //#region src/runtime/remote/pi-tui-terminal-progress-contract.ts
2075
- /** The wire namespace (and Host Cordis service key) of the private stream. */
2076
- const PI_TUI_TERMINAL_PROGRESS_NAMESPACE = "piTuiTerminalProgress";
2077
- /** The private method's stable endpoint identity. */
2078
- const PI_TUI_TERMINAL_PROGRESS_WATCH_ENDPOINT = "@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch";
2079
- /** One strict JSON codec that validates a wire string. */
2080
- function stringCodec(typeSymbol) {
2081
- return {
2082
- mode: "strict",
2083
- typeSymbol,
2084
- create: () => ({ parse: (value) => {
2085
- if (typeof value !== "string") throw new TypeError(`${typeSymbol}: the wire value must be a string`);
2086
- return value;
2087
- } })
2088
- };
2089
- }
2090
- /**
2091
- * Validate and detach one `PiTuiTerminalProgressFrame`. This is the ONE
2092
- * structural validator of the frame shape: the descriptor's `result` codec
2093
- * uses it, and the R2 Client source must call it on every downlink item because
2094
- * the framework does not (see the module JSDoc).
2095
- */
2096
- function parsePiTuiTerminalProgressFrame(value) {
2097
- if (typeof value !== "object" || value === null) throw new TypeError("piTuiTerminalProgress/watch: the frame must be an object");
2098
- const frame = value;
2099
- if (frame.kind !== "snapshot" && frame.kind !== "update") throw new TypeError("piTuiTerminalProgress/watch: the frame kind must be snapshot or update");
2100
- if (typeof frame.sessionId !== "string") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a string sessionId");
2101
- if (typeof frame.hostEpoch !== "string") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a string hostEpoch");
2102
- if (typeof frame.agentEpoch !== "number") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a numeric agentEpoch");
2103
- if (typeof frame.revision !== "number") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a numeric revision");
2104
- if (typeof frame.running !== "boolean") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a boolean running");
2105
- if (frame.outcome !== "idle" && frame.outcome !== "done" && frame.outcome !== "error") throw new TypeError("piTuiTerminalProgress/watch: the frame outcome must be idle, done or error");
2106
- return {
2107
- kind: frame.kind,
2108
- sessionId: frame.sessionId,
2109
- hostEpoch: frame.hostEpoch,
2110
- agentEpoch: frame.agentEpoch,
2111
- revision: frame.revision,
2112
- running: frame.running,
2113
- outcome: frame.outcome
2114
- };
2115
- }
2116
- const PI_TUI_TERMINAL_PROGRESS_FRAME_CODEC = {
2117
- mode: "strict",
2118
- typeSymbol: "@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch:frame",
2119
- create: () => ({ parse: parsePiTuiTerminalProgressFrame }),
2120
- decode: parsePiTuiTerminalProgressFrame
2121
- };
2122
- /**
2123
- * The ONE shared invocation descriptor both contributions derive from. The
2124
- * Host registers this exact object; the Client mounts this exact object.
2125
- */
2126
- const PI_TUI_TERMINAL_PROGRESS_WATCH = {
2127
- id: PI_TUI_TERMINAL_PROGRESS_WATCH_ENDPOINT,
2128
- service: PI_TUI_TERMINAL_PROGRESS_NAMESPACE,
2129
- namespace: PI_TUI_TERMINAL_PROGRESS_NAMESPACE,
2130
- method: "watch",
2131
- mode: "stream",
2132
- invocation: { kind: "direct" },
2133
- parameters: [{
2134
- name: "sessionId",
2135
- wire: "sessionId",
2136
- source: "json",
2137
- codec: stringCodec("@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch:sessionId")
2138
- }],
2139
- cancellation: { parameter: "signal" },
2140
- result: PI_TUI_TERMINAL_PROGRESS_FRAME_CODEC
2141
- };
2142
- //#endregion
2143
- //#region src/app/remote/terminal-progress-source.ts
2144
- /** Consecutive frame-less watch endings tolerated before failing closed. */
2145
- const EMPTY_WATCH_REOPEN_LIMIT = 3;
2146
- /**
2147
- * Consume the ONE Remote progress watch of one session for as long as the caller
2148
- * stays current, re-establishing it whenever the Host retires it.
2149
- *
2150
- * @param source - the Remote progress source.
2151
- * @param sessionId - the main session this authority belongs to.
2152
- * @param signal - the caller's lifetime; aborting it stops the consumption at
2153
- * the next fact and before any re-open.
2154
- * @param consumer - the currentness fence and the fact sink.
2155
- * @throws when the Host keeps ending the watch without ever delivering a frame.
2156
- */
2157
- async function consumeRemoteTerminalProgress(source, sessionId, signal, consumer) {
2158
- let emptyReopens = 0;
2159
- for (;;) {
2160
- let frames = 0;
2161
- try {
2162
- for await (const fact of source.open(sessionId, signal)) {
2163
- if (signal.aborted || !consumer.isCurrent()) return;
2164
- frames += 1;
2165
- consumer.onFact(fact);
2166
- }
2167
- } catch (error) {
2168
- if (signal.aborted) return;
2169
- throw error;
2170
- }
2171
- if (signal.aborted || !consumer.isCurrent()) return;
2172
- if (frames === 0) {
2173
- emptyReopens += 1;
2174
- if (emptyReopens > EMPTY_WATCH_REOPEN_LIMIT) throw new Error(`the Remote terminal-progress watch of ${sessionId} ended without a frame ${String(emptyReopens)} times`);
2175
- } else emptyReopens = 0;
2176
- }
2177
- }
2178
- /**
2179
- * Assemble the source over the ONE Remote Client graph. It constructs no
2180
- * Client and owns no subscription of its own; the provenance of an accepted
2181
- * frame lives only for the watch that observed it (see {@link createRemoteTerminalProgressSource}).
2182
- */
2183
- function createRemoteTerminalProgressSource(deps) {
2184
- /**
2185
- * Judge one frame against the provenance of THIS watch.
2186
- *
2187
- * @param previous - the last frame accepted by this watch, or `undefined`
2188
- * before its opening baseline. It deliberately never crosses watches: a
2189
- * settled `done`/`error` belongs to the interval ONE watch observed, so a new
2190
- * watch (a reconnect, a re-adopted session, a re-retained binding, another TUI
2191
- * owner) opens on the Host's current `running` truth and `idle` — the plan's
2192
- * "a new binding default to idle" — instead of inheriting a result it cannot
2193
- * prove.
2194
- * @param opened - whether this watch already delivered its opening baseline.
2195
- * @returns the fact to publish, or `undefined` for a frame that must be dropped.
2196
- * @throws when the stream cannot be interpreted at all.
2197
- */
2198
- const acceptFrame = (frame, sessionId, opened, previous) => {
2199
- if (!opened) {
2200
- if (frame.kind !== "snapshot") throw new Error(`the Remote terminal-progress stream of ${sessionId} did not open with a snapshot`);
2201
- return {
2202
- kind: "snapshot",
2203
- restart: true,
2204
- running: frame.running,
2205
- outcome: "idle"
2206
- };
2207
- }
2208
- if (previous !== void 0 && frame.revision < previous.revision) throw new Error(`the Remote terminal-progress stream of ${sessionId} moved its revision backwards`);
2209
- if (frame.kind === "snapshot") return {
2210
- kind: "snapshot",
2211
- restart: true,
2212
- running: frame.running,
2213
- outcome: "idle"
2214
- };
2215
- if (previous === void 0) return void 0;
2216
- if (frame.hostEpoch !== previous.hostEpoch) return;
2217
- if (frame.agentEpoch < previous.agentEpoch) return void 0;
2218
- if (frame.revision <= previous.revision) return void 0;
2219
- return {
2220
- kind: "update",
2221
- restart: frame.agentEpoch > previous.agentEpoch,
2222
- running: frame.running,
2223
- outcome: frame.outcome
2224
- };
2225
- };
2226
- return { async *open(sessionId, signal) {
2227
- const capturedGeneration = deps.generation.getSnapshot();
2228
- const capturedBinding = deps.binding(sessionId);
2229
- if (capturedGeneration === void 0 || capturedBinding === void 0) throw new Error(`the Remote terminal-progress watch of ${sessionId} has no retained Session binding`);
2230
- const handle = deps.remote.piTuiTerminalProgress.watch(sessionId, signal);
2231
- try {
2232
- let opened = false;
2233
- /** This watch's own provenance: it dies with the watch. */
2234
- let accepted;
2235
- for await (const item of handle) {
2236
- if (signal.aborted) return;
2237
- 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`);
2238
- const frame = parsePiTuiTerminalProgressFrame(item);
2239
- if (frame.sessionId !== sessionId) throw new Error(`the Remote terminal-progress stream of ${sessionId} delivered a frame of ${frame.sessionId}`);
2240
- const fact = acceptFrame(frame, sessionId, opened, accepted);
2241
- if (fact === void 0) continue;
2242
- opened = true;
2243
- accepted = {
2244
- hostEpoch: frame.hostEpoch,
2245
- agentEpoch: frame.agentEpoch,
2246
- revision: frame.revision
2247
- };
2248
- yield fact;
2249
- }
2250
- } finally {
2251
- handle.dispose();
2252
- }
2253
- } };
2254
- }
2255
- //#endregion
2256
- export { activeFooterItemIds as $, deliveredFileReadErrorFrom as A, deriveKeyRef as B, classifySubagentPromptSettlement as C, DIRECT_IMPLEMENTED_CAPABILITIES as D, isRemoteBusinessRefusalCode as E, requireCreated as F, rankPathCandidates as G, providerOptionsFor as H, requireOpened as I, separatorOfRaw as J, reattachDisplayBase as K, PROTOCOL_CHOICES as L, clientOwnerOf as M, directAgentOf as N, REMOTE_IMPLEMENTED_CAPABILITIES as O, ownerHandleOf as P, DEFAULT_CUSTOM_COMMAND_REFRESH_MS as Q, ROUTE_PATTERN as R, detachedTurnOutline as S, GATEWAY_PRE_INVOCATION_CODES as T, providerProfileProjectionOf as U, getPath as V, SupersededReadError as W, escapeFinderRegex as X, discoverForQuery as Y, normalizeFinderRecords as Z, QUESTION_BAD_ANSWER as _, PluginManagerStaleResultError as a, executableCommandItemIds as at, questionAnswerError as b, detachInspection as c, parseFooterCommandConfig as ct, detachPluginManagerSnapshot as d, resolveUserCommandItemFallbackActivationIds as dt, customCommandConfigOf as et, pluginInstallRequestId as f, resolveUserLayerFooterMode as ft, resolveFdPath as g, projectedWorkingDirectory as gt, hostPathQueryEnvironment as h, effectiveAgentCwd as ht, PI_TUI_TERMINAL_PROGRESS_WATCH as i, effectiveCustomCommandTimeoutMs as it, LifecycleError as j, DeliveredFileReadError as k, detachLog as l, resolveTrustedFooterCommand as lt, DirectHostDiscoveryDriver as m, contextPressureOccupancy as mt, createRemoteTerminalProgressSource as n, customItemName as nt, createTerminalProgressInterval as o, parseFooterCustomItem as ot, listPiTuiHostFileReferences as p, MAX_COMMAND_TIMEOUT_MS as pt, resolvePathQuery as q, PI_TUI_TERMINAL_PROGRESS_NAMESPACE as r, effectiveCustomCommandRefreshMs as rt, detachChange as s, parseFooterCustomItems as st, consumeRemoteTerminalProgress as t, customItemId as tt, detachPhase as u, resolveUserCommandItemActivationIds as ut, QUESTION_REPLY_QUEUED as v, safeSubagentErrorMessage as w, detachedSessionStatus as x, QuestionAnswerError as y, classifyCredentialArg as z };