@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +33 -0
  2. package/README.en.md +103 -814
  3. package/README.md +102 -711
  4. package/cordis.patch.yml +186 -0
  5. package/dist/acp-preferences.d.mts +29 -0
  6. package/dist/acp-preferences.mjs +15 -0
  7. package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
  8. package/dist/builtins.mjs +3 -3
  9. package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
  10. package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
  11. package/dist/command-trust-DChWUamk.mjs +406 -0
  12. package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
  13. package/dist/daemon-launcher.d.mts +159 -0
  14. package/dist/daemon-launcher.mjs +2 -0
  15. package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
  16. package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
  17. package/dist/entry-control-DjNsE3I0.mjs +190 -0
  18. package/dist/extension/advanced.d.mts +1 -1
  19. package/dist/extension/unstable.d.mts +1 -1
  20. package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
  21. package/dist/extension-config.d.mts +29 -0
  22. package/dist/extension-config.mjs +22 -0
  23. package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
  24. package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
  25. package/dist/extensions.d.mts +2 -2
  26. package/dist/extensions.mjs +1 -1
  27. package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
  28. package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
  29. package/dist/host-runtime.d.mts +11 -5
  30. package/dist/host-runtime.mjs +4171 -920
  31. package/dist/index.d.mts +86 -174
  32. package/dist/index.mjs +38087 -9967
  33. package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
  34. package/dist/local-client.mjs +1158 -59
  35. package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
  36. package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
  37. package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
  38. package/dist/local-discovery-egN4_gsQ.mjs +2 -0
  39. package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
  40. package/dist/local-host.mjs +812 -89
  41. package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
  42. package/dist/local-scope-DamiMqPd.mjs +1340 -0
  43. package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
  44. package/dist/local-web-control-DMrjwCkl.mjs +454 -0
  45. package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
  46. package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  47. package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  48. package/dist/open-CmOBxSjN.mjs +63 -0
  49. package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
  50. package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
  51. package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
  52. package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
  53. package/dist/preferences.d.mts +17 -0
  54. package/dist/preferences.mjs +20 -0
  55. package/dist/preset-BcWqOtY7.mjs +46 -0
  56. package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
  57. package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
  58. package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
  59. package/dist/prompt-sections-DXmjB58H.mjs +634 -0
  60. package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
  61. package/dist/row-id-DPbyt9Nn.mjs +24 -0
  62. package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
  63. package/dist/schema-BTGYn8_X.d.mts +54 -0
  64. package/dist/schema-qE_P09zJ.mjs +124 -0
  65. package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
  66. package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
  67. package/dist/startup-CarQxWwi.d.mts +213 -0
  68. package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
  69. package/dist/startup.d.mts +2 -99
  70. package/dist/startup.mjs +2 -2
  71. package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
  72. package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
  73. package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
  74. package/dist/version-B9yC7bBk.mjs +83 -0
  75. package/dist/visual-tools.d.mts +1 -1
  76. package/dist/visual-tools.mjs +1 -1
  77. package/dist/web-preferences.d.mts +1 -1
  78. package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
  79. package/generated/dsh-presets/cordis.patch.yml +4 -2
  80. package/generated/dsh-presets/ptc.patch.yml +4 -0
  81. package/generated/dsh-presets/standard.patch.yml +7 -0
  82. package/generated/web-access/cordis.patch.yml +239 -0
  83. package/package.json +217 -170
  84. package/dist/entry-control-DnduyDiw.mjs +0 -92
  85. package/dist/local-discovery-C9VMjc0K.mjs +0 -759
  86. package/dist/local-discovery-CDaQHA_R.mjs +0 -2
  87. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
  88. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
  89. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
  90. package/dist/version-a-eF-QER.mjs +0 -80
@@ -0,0 +1,2232 @@
1
+ import { accessSync, constants, readdirSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { delimiter, join, posix, win32 } from "node:path";
4
+ import { isUserInvocable } from "@deepseek-ai/dsh-skill";
5
+ import { spawn } from "node:child_process";
6
+ import { DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES, DEFAULT_FILE_SEARCH_MAX_ENTRIES, DEFAULT_FILE_SEARCH_MAX_RESULTS, WorkspaceFileSearch } from "@deepseek-ai/dsh-file-reference-local/search";
7
+ import { classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature } from "@deepseek-ai/dsh-sandbox";
8
+ //#region src/domain/display/preset.ts
9
+ /** Whether a value is one of the complete display preset names. */
10
+ function isDisplayPreset(value) {
11
+ return value === "focus" || value === "compact" || value === "full";
12
+ }
13
+ /** Every preset whose projection exists in this build ships as available. */
14
+ function isDisplayPresetAvailable(preset) {
15
+ return preset === "focus" || preset === "compact" || preset === "full";
16
+ }
17
+ /** Whether a preset enables the model-facing Focus behavioral policy. The
18
+ * neutral behavioral answer is exactly the preset identity — it must never
19
+ * depend on the terminal disclosure policy. */
20
+ function isFocusDisplayPreset(preset) {
21
+ return preset === "focus";
22
+ }
23
+ /**
24
+ * Resolve the canonical field before the legacy Focus field. Every recognized
25
+ * preset (Compact included) is canonical as of PR3 and is never rewritten; an
26
+ * unrecognized value falls back to Full.
27
+ */
28
+ function resolveDisplayPreset(input) {
29
+ if (input.displayPreset !== void 0) {
30
+ if (isDisplayPreset(input.displayPreset)) return {
31
+ preset: input.displayPreset,
32
+ canonicalize: false,
33
+ source: "canonical"
34
+ };
35
+ return {
36
+ preset: "full",
37
+ canonicalize: true,
38
+ source: "invalid-canonical"
39
+ };
40
+ }
41
+ if (input.focusMode === "on") return {
42
+ preset: "focus",
43
+ canonicalize: true,
44
+ source: "legacy-focus"
45
+ };
46
+ return {
47
+ preset: "full",
48
+ canonicalize: true,
49
+ source: "legacy-full"
50
+ };
51
+ }
52
+ //#endregion
53
+ //#region src/domain/communication/policy.ts
54
+ /**
55
+ * Model-facing communication policy, independent of transcript presentation.
56
+ *
57
+ * Two independent axes (the PR #166 follow-up split):
58
+ * - `ProgressUpdates` owns the user-facing mid-turn update cadence;
59
+ * - `ResponseStyle` owns the density / explanation depth of visible text.
60
+ *
61
+ * Neither axis is a display preset: `DisplayState` owns what the surface can
62
+ * make visible, and the Focus preset suppresses the effective progress
63
+ * section through the live display state without mutating the saved
64
+ * preference. Registration of the sections belongs to the Direct
65
+ * system-prompt owner (`app/direct/system-prompt.ts`); this module owns the
66
+ * pure text/policy derivation.
67
+ * @module @xmoon76/dsh-pi-tui/domain/communication/policy
68
+ */
69
+ const DEFAULT_PROGRESS_UPDATES = "milestones";
70
+ const DEFAULT_RESPONSE_STYLE = "default";
71
+ /** The system-prompt section names: TUI-private, never host/preset names. */
72
+ const PROGRESS_UPDATES_SECTION_NAME = "tui:progress-updates";
73
+ const RESPONSE_STYLE_SECTION_NAME = "tui:response-style";
74
+ /** Settings documents are untrusted; missing or invalid values use Milestones. */
75
+ function parseProgressUpdates(value) {
76
+ switch (value) {
77
+ case "off":
78
+ case "milestones":
79
+ case "frequent": return value;
80
+ default: return DEFAULT_PROGRESS_UPDATES;
81
+ }
82
+ }
83
+ /** Settings documents are untrusted; missing or invalid values use Default. */
84
+ function parseResponseStyle(value) {
85
+ switch (value) {
86
+ case "default":
87
+ case "concise":
88
+ case "explanatory": return value;
89
+ default: return DEFAULT_RESPONSE_STYLE;
90
+ }
91
+ }
92
+ const progressPrompts = {
93
+ milestones: `# Progress updates: Milestones
94
+
95
+ Work quietly while a coherent phase is still in progress. Give a brief user-facing progress update only when a substantial phase has completed and the next phase is materially distinct, when the overall direction materially changes, or when required user input blocks further progress.
96
+
97
+ Do not report a partial finding merely because it was just discovered. If you are about to continue investigating the same question, continue working instead of reporting that partial conclusion.
98
+
99
+ Do not narrate individual tool calls, file reads, commands, or edits, and do not add a mandatory preamble before the first tool call.`,
100
+ frequent: `# Progress updates: Frequent
101
+
102
+ For longer or multi-step work, keep the user actively informed with brief updates as meaningful findings become established and before moving into the next significant piece of work. An opening update is useful when the work will take multiple steps, but do not add one for a trivial action.
103
+
104
+ Group related actions together. Report what was established and what you are doing next; do not narrate individual tool calls, file reads, commands, or edits.`,
105
+ off: `# Progress updates: Off
106
+
107
+ Do not provide progress narration while working. Continue through the task until you have a result to deliver, unless required user input or a blocker prevents further progress.
108
+
109
+ Do not add a preamble merely to announce upcoming tool use, and do not narrate individual tool calls, file reads, commands, or edits.`
110
+ };
111
+ const responsePrompts = {
112
+ default: "",
113
+ concise: `# Response style: Concise
114
+
115
+ Keep user-visible responses compact and result-first. Avoid unnecessary preambles, restating the request, repeated conclusions, and nonessential explanation.
116
+
117
+ Preserve information needed for correctness, decisions, blockers, and user action. Give fuller detail when the user explicitly asks for it.`,
118
+ explanatory: `# Response style: Explanatory
119
+
120
+ Explain relevant rationale, architecture, non-obvious behavior, and tradeoffs when they help the user understand the result or make a decision. When an alternative was materially relevant, explain why it was not chosen.
121
+
122
+ Prioritize explanations of why, constraints, and decisions over narration of the work performed. Do not add generic verbosity or turn the response into a syntax tutorial unless the user asks for one.`
123
+ };
124
+ /** The Focus surface owns what can reach the user, so the progress section
125
+ * reads BOTH live states: on Focus the effective progress text is empty
126
+ * regardless of the saved cadence (which is never mutated). */
127
+ function progressUpdatesPromptText(displayState, state) {
128
+ return isFocusDisplayPreset(displayState.preset) ? "" : progressPrompts[state.mode];
129
+ }
130
+ /** The effective response-style section text for the live state. */
131
+ function responseStylePromptText(state) {
132
+ return responsePrompts[state.style];
133
+ }
134
+ //#endregion
135
+ //#region src/runtime/process/errors.ts
136
+ /**
137
+ * Shared, TOTAL error-observation helpers for every async boundary in the
138
+ * TUI: the owned/detached entries (`tasks.ts`), the lifecycle roots
139
+ * (startup, exit, flush), the per-task callbacks and the diagnostics
140
+ * formatter. One implementation, one behavior — no drift between modules.
141
+ *
142
+ * CONTRACT (deliberately scoped, honestly worded): the SYNC boundary is
143
+ * total — observing any legal JavaScript value (a Proxy with a throwing
144
+ * `getPrototypeOf` trap, a throwing `message` getter, a throwing
145
+ * `toString`/`Symbol.toPrimitive`) can never make THIS code throw or
146
+ * reject; every observation is protected and every fallback is a fixed
147
+ * constant that never touches the value again. What is NOT guaranteed: an
148
+ * observer (getter/trap/coercion) that, WHILE being observed, spawns its
149
+ * OWN detached async work (e.g. `void Promise.reject(...)` inside
150
+ * `toString`) — that rejection belongs to the observer, not to this
151
+ * boundary, and no synchronous try/catch can intercept it. Callers must
152
+ * not describe this module as a strict "any legal value, zero side
153
+ * effects" guarantee.
154
+ * @module @xmoon76/dsh-pi-tui/runtime/process/errors
155
+ */
156
+ /**
157
+ * Describe an arbitrary thrown value as a string WITHOUT ever throwing:
158
+ * `instanceof`, property reads and coercion are all inside the protection,
159
+ * the fallbacks are FIXED constants that never touch the value again, and
160
+ * a hostile Proxy/getter/`Symbol.toPrimitive` yields a stable placeholder
161
+ * instead of escaping. (Best-effort beyond the sync boundary — see the
162
+ * module contract.)
163
+ */
164
+ function safeErrorMessage(value) {
165
+ try {
166
+ if (value instanceof Error) try {
167
+ const message = value.message;
168
+ return typeof message === "string" ? message : "<error with non-string message>";
169
+ } catch {
170
+ return "<error with unreadable message>";
171
+ }
172
+ return String(value);
173
+ } catch {
174
+ return "<unprintable error>";
175
+ }
176
+ }
177
+ /** Describe an arbitrary thrown value using its normal `String` form without
178
+ * allowing hostile coercion to escape the async boundary. */
179
+ function safeErrorString(value) {
180
+ try {
181
+ return String(value);
182
+ } catch {
183
+ return "<unprintable error>";
184
+ }
185
+ }
186
+ //#endregion
187
+ //#region src/runtime/process/tasks.ts
188
+ /**
189
+ * Whether an error represents an abort/cancel rather than a real failure.
190
+ * TOTAL over the whole `unknown` domain: every probe (prototype-chain
191
+ * walk, `name`/`code` getters) is inside the protection, and a hostile
192
+ * value that throws while being observed simply classifies as NOT a
193
+ * cancellation — recognizing a cancellation must never mint a new primary
194
+ * error.
195
+ */
196
+ function isCancellation(error) {
197
+ try {
198
+ if (!(error instanceof Error)) return false;
199
+ return error.name === "AbortError" || error.code === "ABORT_ERR";
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+ /** Build a cancellation-shaped error the classifier recognizes (a plain
205
+ * `new Error('...')` would route through the failure path). */
206
+ function cancellationError(message) {
207
+ const error = new Error(message);
208
+ error.name = "AbortError";
209
+ error.code = "ABORT_ERR";
210
+ return error;
211
+ }
212
+ /** Read the live session id for diagnostics WITHOUT ever throwing: a
213
+ * throwing `sessionId()` callback degrades to `undefined` (diagnostics
214
+ * must not crash classification or the final sink). */
215
+ function safeSessionId(options) {
216
+ try {
217
+ return options.sessionId?.();
218
+ } catch {
219
+ return;
220
+ }
221
+ }
222
+ /**
223
+ * Invoke the task factory SYNCHRONOUSLY (an ownership action inside the
224
+ * factory — a stop, a latch, a spawn — must take effect before the helper
225
+ * returns, so two calls in one input batch cannot both start), and convert
226
+ * a synchronous throw into a rejected promise so it classifies exactly like
227
+ * a rejection.
228
+ */
229
+ function invokeTask(task) {
230
+ try {
231
+ return Promise.resolve(task());
232
+ } catch (error) {
233
+ return Promise.reject(error);
234
+ }
235
+ }
236
+ /**
237
+ * Observe the settlement of an ALREADY-OWNED promise without taking ownership.
238
+ * The callback runs on fulfilment or rejection and its own result is dropped,
239
+ * so bookkeeping (for example removing a promise from a teardown-drained set)
240
+ * never adds a second, unhandled rejection branch next to the real owner's
241
+ * failure handling. Never use this to START work — that is `runDetached` /
242
+ * `runOwned`.
243
+ * @param promise - the promise whose failure semantics already have an owner.
244
+ * @param onSettled - runs once, on either settlement.
245
+ */
246
+ function observeSettled(promise, onSettled) {
247
+ promise.then(onSettled, onSettled);
248
+ }
249
+ /**
250
+ * Attach rejection handling to a fire-and-forget task. The factory is
251
+ * invoked synchronously (a synchronous throw is a rejection like any
252
+ * other); every rejection is caught and classified:
253
+ * - cancellation → debug diagnostics only (never a user error);
254
+ * - recoverable (per the options hook) → notify + warn;
255
+ * - anything else → warn.
256
+ * The log line carries the task label and the live session id — never the
257
+ * task payload (no API keys, prompt bodies, or shell output). A throwing
258
+ * notify/diag/sessionId path cannot escape: it lands in the handler-failure
259
+ * sink, which is itself total over the `unknown` domain.
260
+ */
261
+ function runDetached(label, task, options) {
262
+ invokeTask(task).catch((error) => {
263
+ if (isCancellation(error)) {
264
+ options.diag.debug(label, {
265
+ session: safeSessionId(options),
266
+ cancelled: true
267
+ });
268
+ return;
269
+ }
270
+ const message = safeErrorMessage(error);
271
+ options.diag.warn(label, {
272
+ session: safeSessionId(options),
273
+ error: message
274
+ });
275
+ if (options.recoverable?.(error) === true) options.notify?.(`${label}: ${message}`);
276
+ }).catch(handlerFailure(label, options));
277
+ }
278
+ /**
279
+ * The owned-workflow counterpart of {@link runDetached}: a fire-and-forget
280
+ * task whose RESULT drives user-visible state (a settled card, a restored
281
+ * draft, a queue mutation, a notification). The factory starts
282
+ * SYNCHRONOUSLY; the TASK phase (factory throw / task rejection) classifies
283
+ * with the error shape plus the task-local predicate; the onResult phase is
284
+ * classified as a PRIMARY failure — ERROR + onError, never a cancellation,
285
+ * regardless of error shape or task-local state; a terminal side-effect
286
+ * handler's (onCancel/onError/classifier) own sync/async throw is wrapped
287
+ * in a {@link HandlerFailure} and lands in the `${label} handler failed`
288
+ * sink exactly once, without mutating the thrown value. Never a bare
289
+ * `void somePromise()`: every owned flow goes through this entry
290
+ * (AGENTS.md).
291
+ */
292
+ function runOwned(label, task, options) {
293
+ invokeTask(task).then((result) => options.onResult?.(result), (error) => {
294
+ return classify(label, options, error, true);
295
+ }).catch((error) => {
296
+ if (isHandlerFailure(error)) throw error;
297
+ return classify(label, options, error, false);
298
+ }).catch(handlerFailure(label, options));
299
+ }
300
+ /**
301
+ * Classify one failure and record the classification diagnostics, then run
302
+ * the matching per-task callback. `allowCancellation` gates ALL cancellation
303
+ * classification: the task phase may treat an AbortError or a task-local
304
+ * state as a cancellation; the onResult phase may not (a result-consumer
305
+ * failure is a failure). A terminal side-effect handler's own sync/async
306
+ * failure is wrapped in {@link HandlerFailure} and propagated to the
307
+ * handler-failure sink — never re-classified, never repeated, never
308
+ * escaped. All diagnostics go through the never-throw helpers, so a
309
+ * hostile thrown value or a throwing sessionId/diag can never mint a new
310
+ * primary error.
311
+ */
312
+ function classify(label, options, error, allowCancellation) {
313
+ if (allowCancellation && (isCancellation(error) || taskLocalCancellation(options, error))) {
314
+ options.diag.debug(label, {
315
+ session: safeSessionId(options),
316
+ cancelled: true
317
+ });
318
+ if (options.onCancel !== void 0) return guardHandler(() => options.onCancel(error));
319
+ return;
320
+ }
321
+ options.diag.error(label, {
322
+ session: safeSessionId(options),
323
+ error: safeErrorMessage(error)
324
+ });
325
+ if (options.onError !== void 0) return guardHandler(() => options.onError(error));
326
+ }
327
+ /** The task-local predicate (cancellation classification is already gated
328
+ * by the caller). A throwing predicate is wrapped as a handler failure — it
329
+ * never re-routes the original error into the wrong classification and is
330
+ * never itself re-classified. */
331
+ function taskLocalCancellation(options, error) {
332
+ if (options.isCancellation === void 0) return false;
333
+ try {
334
+ return options.isCancellation(error) === true;
335
+ } catch (classifierError) {
336
+ throw new HandlerFailure(classifierError);
337
+ }
338
+ }
339
+ /**
340
+ * Immutable wrapper for a terminal side-effect handler's own failure. The
341
+ * thrown value is NEVER mutated (a primitive, null, or a frozen/non-
342
+ * extensible error must survive intact); the wrapper carries the original
343
+ * cause to the handler-failure sink, and the middle classification catch
344
+ * recognizes it and forwards it unchanged — so `onError`/`onCancel` run
345
+ * exactly once even when they throw.
346
+ */
347
+ var HandlerFailure = class {
348
+ cause;
349
+ constructor(cause) {
350
+ this.cause = cause;
351
+ handlerFailures.add(this);
352
+ }
353
+ };
354
+ /** Identity registry for the internal wrappers: `WeakSet.has` compares by
355
+ * identity and never walks the argument's prototype chain, so a hostile
356
+ * thrown value (a Proxy with a throwing `getPrototypeOf` trap) can be
357
+ * tested safely — `instanceof HandlerFailure` on an untrusted value could
358
+ * itself throw. */
359
+ const handlerFailures = /* @__PURE__ */ new WeakSet();
360
+ /** Whether a value is one of OUR wrapper instances (identity only; total
361
+ * over the whole `unknown` domain). */
362
+ function isHandlerFailure(value) {
363
+ return typeof value === "object" && value !== null && handlerFailures.has(value);
364
+ }
365
+ /** Run a per-task terminal callback; a sync or async failure is wrapped in
366
+ * {@link HandlerFailure} so the chain forwards it to the handler-failure
367
+ * sink instead of re-classifying it (and never repeats the callback). */
368
+ function guardHandler(invoke) {
369
+ try {
370
+ const outcome = invoke();
371
+ if (outcome !== void 0) return outcome.catch((error) => {
372
+ throw new HandlerFailure(error);
373
+ });
374
+ return;
375
+ } catch (error) {
376
+ throw new HandlerFailure(error);
377
+ }
378
+ }
379
+ /**
380
+ * The final sink of both helpers: a terminal side-effect handler
381
+ * (onResult's own invocation aside — see {@link runOwned}), a task-local
382
+ * classifier, or the diagnostics channel itself threw. The ENTIRE body is
383
+ * protected — wrapper unwrapping, error description, the session read and
384
+ * the diag call all live inside the try, and the fallback is a fixed
385
+ * constant that never touches the hostile value again — so the sink is a
386
+ * total function over the `unknown` domain: it can NEVER reject, and there
387
+ * is no lower sink to leak into.
388
+ */
389
+ function handlerFailure(label, options) {
390
+ return (error) => {
391
+ try {
392
+ const cause = isHandlerFailure(error) ? error.cause : error;
393
+ options.diag.error(`${label} handler failed`, {
394
+ session: safeSessionId(options),
395
+ error: safeErrorMessage(cause)
396
+ });
397
+ } catch {}
398
+ };
399
+ }
400
+ //#endregion
401
+ //#region src/domain/catalog/skill.ts
402
+ /**
403
+ * Neutral skill catalog vocabulary (TS8-E): the human-facing skill summary
404
+ * shape, the detached catalog (with its completeness flag) and the official
405
+ * user-invocation policy guard.
406
+ *
407
+ * This module is the transport/UI-neutral semantic owner: it consumes only the
408
+ * official `@deepseek-ai/dsh-skill` policy helper. It never resolves ctx
409
+ * services, acquires standing scopes, holds revision leases, reads a live
410
+ * Agent, or imports a Direct/Remote adapter — the structural Direct Host read
411
+ * lives in `runtime/direct/skill-catalog.ts`.
412
+ * @module @xmoon76/dsh-pi-tui/domain/catalog/skill
413
+ */
414
+ /**
415
+ * Whether one summary passes the OFFICIAL user-invocation policy — the
416
+ * neutral guard used by every human entry point (direct wrappers, `/skill`,
417
+ * the picker, and final body loads). A malformed `invocation` (missing,
418
+ * non-object, non-boolean flag) is treated as NOT user-invocable: the policy
419
+ * defaults are never reinterpreted, and a hostile entry can neither throw nor
420
+ * sneak into a human surface.
421
+ */
422
+ function isUserInvocableSkill(skill) {
423
+ const invocation = skill.invocation;
424
+ if (typeof invocation !== "object" || invocation === null) return false;
425
+ if (typeof invocation.userInvocable !== "boolean") return false;
426
+ return isUserInvocable(skill);
427
+ }
428
+ //#endregion
429
+ //#region src/runtime/direct/working-directory-direct.ts
430
+ /**
431
+ * The effective directory of one live Agent's Session: the official
432
+ * `workingDirectory.get(session)` value when the service is mounted, else the
433
+ * immutable header cwd — the INITIAL committed value of that same projection,
434
+ * so a minimal composition without the row keeps the historical read instead
435
+ * of inventing a directory.
436
+ *
437
+ * @param workingDirectory - the official service, or `undefined` when the
438
+ * composition does not mount the row.
439
+ * @param agent - the exact live Agent whose Session is read.
440
+ * @returns the effective absolute directory, or `undefined` when neither the
441
+ * service nor a header cwd can answer (never a Client-side guess).
442
+ */
443
+ function effectiveAgentCwd(workingDirectory, agent) {
444
+ if (workingDirectory === void 0) return agent.session.header.cwd;
445
+ return workingDirectory.get(agent.session);
446
+ }
447
+ /** The effective directory recorded by one official `workingDirectory`
448
+ * projection SNAPSHOT value: its wire view is `string | null`, where `null`
449
+ * is the legal "no directory recorded" state (the header had none) — an
450
+ * absent/foreign value reads `undefined` (unavailable), never a directory. */
451
+ function projectedWorkingDirectory(value) {
452
+ return typeof value === "string" && value !== "" ? value : void 0;
453
+ }
454
+ //#endregion
455
+ //#region src/runtime/config-port.ts
456
+ /** The canonical profile row id / Settings namespace for the durable TUI
457
+ * preferences (M6 PR-A). Every backend reads and writes this ONE row; the
458
+ * retired `tui-app` / `split-host-pi-tui-runtime` namespaces are migration
459
+ * sources only. */
460
+ const CANONICAL_TUI_SETTINGS_NS = "pi-tui-preferences";
461
+ /**
462
+ * Serialize every whole-document TUI-settings transaction in this process.
463
+ * The port has no compare-and-swap token, so a queue keyed only by one wrapper
464
+ * object would still allow two adapters around the same backend to lose a
465
+ * get → modify → replace update. The shared fallback key closes that gap;
466
+ * future adapters may expose a stable object as `mutationQueueKey` when they
467
+ * need independent settings stores while preserving the same queue contract.
468
+ */
469
+ const sharedTuiSettingsMutationKey = {};
470
+ const tuiSettingsMutationQueues = /* @__PURE__ */ new WeakMap();
471
+ function serializeTuiSettingsMutation(settings, task) {
472
+ const key = settings.mutationQueueKey ?? sharedTuiSettingsMutationKey;
473
+ const current = (tuiSettingsMutationQueues.get(key) ?? Promise.resolve()).catch(() => void 0).then(task);
474
+ tuiSettingsMutationQueues.set(key, current.then(() => void 0, () => void 0));
475
+ return current;
476
+ }
477
+ //#endregion
478
+ //#region src/domain/file-completion/query.ts
479
+ /**
480
+ * The neutral path query resolver (TS8-A, split out of the historical
481
+ * `src/file-completion/query.ts`): PURE — turns a raw token into the search
482
+ * directory, the basename term, the display prefix and whether the token
483
+ * names an EXPLICIT scope. No filesystem access, and no environment
484
+ * discovery: the facts this algebra needs arrive from the LOCALITY owner as
485
+ * an explicit {@link PathQueryEnvironment}, never from `homedir()` /
486
+ * `process.platform` inside the domain layer.
487
+ *
488
+ * A scoped token (`src/fo`, `../foo`, `../../foo`, `~/foo`, `/tmp/foo`,
489
+ * a drive-qualified path, or an UNC path) searches ONLY its resolved
490
+ * directory — never a whole-tree scan filtered by string. An unscoped token
491
+ * (`foo`, `nested`, `config`) is a whole-tree fuzzy query with an EMPTY
492
+ * display base.
493
+ * @module @xmoon76/dsh-pi-tui/domain/file-completion/query
494
+ */
495
+ /**
496
+ * The HOST filesystem's path algebra, selected from the EXPLICIT
497
+ * `windowsHost` fact. Every host-native path this module computes (a joined
498
+ * scope, an expanded `~`) goes through this api, so the domain never infers
499
+ * the running machine from the ambient `node:path` default export: a caller
500
+ * that injects a foreign host's facts gets that host's algebra.
501
+ */
502
+ function hostPathApi(windowsHost) {
503
+ return windowsHost ? win32 : posix;
504
+ }
505
+ /**
506
+ * Return the final path component without depending on the host OS dialect.
507
+ * Completion can present a Windows path while the client process is running
508
+ * on POSIX (and vice versa), so `node:path.basename` is not sufficient here.
509
+ */
510
+ function basenameOfPath(path) {
511
+ const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
512
+ return path.slice(separator + 1);
513
+ }
514
+ /**
515
+ * Expand a leading `~` in one token against the locality's home directory
516
+ * (other tokens unchanged). PURE — both the home directory AND the host
517
+ * platform are explicit facts: the joined result is a path on the HOST
518
+ * filesystem, so it uses that host's algebra.
519
+ * @param token - the raw token.
520
+ * @param homeDir - the locality owner's home directory fact.
521
+ * @param windowsHost - whether the filesystem host is Windows.
522
+ */
523
+ function expandHomeToken(token, homeDir, windowsHost) {
524
+ if (token === "~") return homeDir;
525
+ if (token.startsWith("~/") || token.startsWith("~\\")) return hostPathApi(windowsHost).join(homeDir, token.slice(2).replace(/\\/g, "/"));
526
+ return token;
527
+ }
528
+ /**
529
+ * Choose the separator immediately before the basename. This preserves a
530
+ * mixed Windows token's actual dialect (forward-slash drive paths stay
531
+ * forward-slashed, while backslash drive paths stay backslashed) instead of
532
+ * normalizing it to the host platform's preferred separator.
533
+ */
534
+ function separatorOfRaw(raw, windowsDialect) {
535
+ const slash = raw.lastIndexOf("/");
536
+ const backslash = raw.lastIndexOf("\\");
537
+ if (slash === -1 && backslash === -1) return windowsDialect ? "\\" : "/";
538
+ return backslash > slash ? "\\" : "/";
539
+ }
540
+ /** Whether the token is a leading-home form, including `~\\foo`. */
541
+ function isHomeToken$1(raw) {
542
+ return raw === "~" || raw.startsWith("~/") || raw.startsWith("~\\");
543
+ }
544
+ /** Whether one raw token is genuinely Windows-dialect. */
545
+ function isWindowsDialect(raw, winAbsolute) {
546
+ return winAbsolute || raw.includes("\\");
547
+ }
548
+ /** Whether an absolute path uses the Windows drive/UNC grammar. */
549
+ function isWindowsAbsolute(raw) {
550
+ return !raw.startsWith("/") && win32.isAbsolute(raw);
551
+ }
552
+ /** Join a relative scope while keeping POSIX fixtures usable for a
553
+ * Windows-looking token. The result is a path on the HOST filesystem, so the
554
+ * joiner comes from the EXPLICIT host fact (never `process.platform`); the
555
+ * TOKEN's own dialect only decides whether backslashes are the user's
556
+ * separators or ordinary characters.
557
+ *
558
+ * A `windowsDialect` token on a POSIX host has backslashes in the USER'S
559
+ * dialect, not as filesystem separators, so they are normalized; an
560
+ * unmistakable drive/UNC `cwd` selects the win32 joiner even on a POSIX host
561
+ * (that cwd string is itself a Windows path). */
562
+ function joinRelativeScope(cwd, rawPath, windowsDialect, windowsHost) {
563
+ const api = hostPathApi(windowsHost);
564
+ if (!windowsDialect) return api.join(cwd, rawPath);
565
+ const windowsCwd = /^[A-Za-z]:[\\/]/.test(cwd) || cwd.startsWith("\\\\");
566
+ if (windowsHost || windowsCwd) return win32.join(cwd, rawPath);
567
+ return api.join(cwd, rawPath.replace(/\\/g, "/"));
568
+ }
569
+ /** Whether the raw token names a directory that should be LISTED
570
+ * (`searchTerm === ''`). `.`/`..` root forms list their own relative
571
+ * directory; `./`/`../`/`~`/`/` list the scope root. */
572
+ function isBareScopeForm(raw) {
573
+ return raw === "" || raw === "." || raw === ".." || raw === "./" || raw === "../" || raw === "~" || raw === "~/" || raw === "~\\" || raw === "/" || raw === ".\\" || raw === "..\\";
574
+ }
575
+ /**
576
+ * Resolve ONE raw completion token into the pure path query.
577
+ * @param raw - the token as typed (quotes stripped; leading separator
578
+ * whitespace stripped by the caller).
579
+ * @param cwd - the completion base (the Client cwd for local completion, the
580
+ * Direct workspace cwd for the WORKSPACE compatibility scanner; relative
581
+ * forms resolve against it).
582
+ * @param environment - the locality owner's explicit environment facts.
583
+ */
584
+ function resolvePathQuery(raw, cwd, environment) {
585
+ const expanded = expandHomeToken(raw, environment.homeDir, environment.windowsHost);
586
+ const posixAbsolute = raw.startsWith("/");
587
+ const winAbsolute = isWindowsAbsolute(raw);
588
+ const windowsDialect = isWindowsDialect(raw, winAbsolute);
589
+ const absolute = isHomeToken$1(raw) || posixAbsolute || winAbsolute;
590
+ const tokenWindows = windowsDialect || environment.windowsHost;
591
+ const pathDirname = tokenWindows ? win32.dirname : posix.dirname;
592
+ const pathBasename = tokenWindows ? win32.basename : posix.basename;
593
+ const separator = separatorOfRaw(raw, windowsDialect);
594
+ if (isBareScopeForm(raw)) return {
595
+ raw,
596
+ searchBase: raw === "." || raw === ".." || raw === "./" || raw === "../" || raw === ".\\" || raw === "..\\" ? joinRelativeScope(cwd, raw, windowsDialect, environment.windowsHost) : absolute ? expanded : joinRelativeScope(cwd, expanded, windowsDialect, environment.windowsHost),
597
+ searchTerm: "",
598
+ displayBase: raw === "" ? "" : raw === "~" ? `~${separator}` : raw.endsWith("/") || raw.endsWith("\\") ? raw : `${raw}${separator}`,
599
+ explicitScope: true,
600
+ winAbsolute
601
+ };
602
+ if (raw.endsWith("/") || raw.endsWith("\\")) return {
603
+ raw,
604
+ searchBase: absolute ? expanded : joinRelativeScope(cwd, expanded, windowsDialect, environment.windowsHost),
605
+ searchTerm: "",
606
+ displayBase: raw,
607
+ explicitScope: true,
608
+ winAbsolute
609
+ };
610
+ const lastSlash = Math.max(raw.lastIndexOf("/"), raw.lastIndexOf("\\"));
611
+ const hasSeparator = lastSlash >= 0;
612
+ const displayBase = hasSeparator ? raw.slice(0, lastSlash + 1) : "";
613
+ const rawDir = hasSeparator ? raw.slice(0, lastSlash) : "";
614
+ const searchTerm = pathBasename(expanded);
615
+ const explicitScope = hasSeparator || absolute;
616
+ const searchBaseForScope = isHomeToken$1(raw) ? expandHomeToken(rawDir, environment.homeDir, environment.windowsHost) : absolute ? pathDirname(expanded) : joinRelativeScope(cwd, rawDir, windowsDialect, environment.windowsHost);
617
+ return {
618
+ raw,
619
+ searchBase: explicitScope ? searchBaseForScope : cwd,
620
+ searchTerm,
621
+ displayBase,
622
+ explicitScope,
623
+ winAbsolute
624
+ };
625
+ }
626
+ /**
627
+ * Reattach the query's display base onto one discovered candidate path.
628
+ * Discovery returns paths RELATIVE to the query's search base; the candidate
629
+ * the user accepts must read in the USER'S dialect (`../sibling-file.ts`,
630
+ * `~/pics/a.png`, `src/deep.ts`, `/tmp/x`). The SOURCE calls this before its
631
+ * candidates cross the port contract (the port's paths are user-facing).
632
+ * PURE.
633
+ */
634
+ function reattachDisplayBase(candidate, query) {
635
+ if (query.displayBase === "") return candidate;
636
+ return {
637
+ ...candidate,
638
+ path: `${query.displayBase}${candidate.path}`
639
+ };
640
+ }
641
+ /** Score one candidate against the query term (lowercased). */
642
+ function scorePathCandidate(candidate, lowerQuery) {
643
+ if (lowerQuery === "") {
644
+ const depthPenalty = candidate.path.split(/[\\/]/).length - 1;
645
+ return (candidate.kind === "directory" ? 120 : 100) - depthPenalty;
646
+ }
647
+ const lowerPath = candidate.path.toLowerCase();
648
+ const lowerBase = basenameOfPath(candidate.path).toLowerCase();
649
+ let score = 0;
650
+ if (lowerBase === lowerQuery) score = 100;
651
+ else if (lowerBase.startsWith(lowerQuery)) score = 80;
652
+ else if (lowerBase.includes(lowerQuery)) score = 50;
653
+ else if (lowerPath.includes(lowerQuery)) score = 30;
654
+ if (candidate.kind === "directory" && score > 0) score += 10;
655
+ return score;
656
+ }
657
+ /** Deterministic order: score desc, directories (kind) first, path asc. */
658
+ function compareScoredPaths(left, right) {
659
+ if (left.score !== right.score) return right.score - left.score;
660
+ if (left.candidate.kind !== right.candidate.kind) return left.candidate.kind === "directory" ? -1 : 1;
661
+ return left.candidate.path.localeCompare(right.candidate.path);
662
+ }
663
+ /**
664
+ * Rank, filter and bound one discovery set (the local scoring model — the
665
+ * SOURCE's own order for its Client-fs / Direct-workspace-compat consumers,
666
+ * NOT the live Session `@` mention path, whose ranking is the official Host
667
+ * authority's). PURE: path candidates in, ranked path candidates out — no UI
668
+ * DTOs, so a semantic adapter can own its ranking end-to-end.
669
+ */
670
+ function rankPathCandidates(candidates, term) {
671
+ const lowerQuery = term.toLowerCase();
672
+ return candidates.map((candidate) => ({
673
+ candidate,
674
+ score: scorePathCandidate(candidate, lowerQuery)
675
+ })).filter((entry) => entry.score > 0).sort(compareScoredPaths).slice(0, 50).map((entry) => entry.candidate);
676
+ }
677
+ /**
678
+ * Collect a finder's candidates under a FIXED memory bound: two independent
679
+ * sorted competitions run in parallel — `bestAll` (every file and directory)
680
+ * and `bestDirectories` (directories only) — each capped at
681
+ * {@link MAX_LOCAL_COMPLETION_SUGGESTIONS}. The scoring and tie-break are
682
+ * exactly {@link scorePathCandidate} / {@link compareScoredPaths}; this
683
+ * collector never models a second relevance order.
684
+ *
685
+ * A directory competes in BOTH sets independently: entering the all-types top
686
+ * 50 must not decide whether it also belongs to the directory top 50 (the old
687
+ * "rank everything, then filter directories" order is precisely what dropped
688
+ * the late Save Location candidates). Candidates scoring 0 for this term are
689
+ * discarded, and a path offered more than once keeps exactly one entry per
690
+ * competition.
691
+ */
692
+ function createBoundedFinderCandidateCollector(term) {
693
+ const lowerQuery = term.toLowerCase();
694
+ const bestAll = [];
695
+ const bestDirectories = [];
696
+ const offerInto = (entries, candidate, score) => {
697
+ const existing = entries.findIndex((entry) => entry.candidate.path === candidate.path);
698
+ if (existing !== -1) entries.splice(existing, 1);
699
+ entries.push({
700
+ candidate,
701
+ score
702
+ });
703
+ entries.sort(compareScoredPaths);
704
+ if (entries.length > 50) entries.length = 50;
705
+ };
706
+ return {
707
+ offer(candidate) {
708
+ const score = scorePathCandidate(candidate, lowerQuery);
709
+ if (score <= 0) return;
710
+ offerInto(bestAll, candidate, score);
711
+ if (candidate.kind === "directory") offerInto(bestDirectories, candidate, score);
712
+ },
713
+ finish() {
714
+ const merged = /* @__PURE__ */ new Map();
715
+ for (const entry of bestAll) merged.set(entry.candidate.path, entry.candidate);
716
+ for (const entry of bestDirectories) if (!merged.has(entry.candidate.path)) merged.set(entry.candidate.path, entry.candidate);
717
+ return [...merged.values()];
718
+ }
719
+ };
720
+ }
721
+ /** Escape regex metacharacters for a finder's regex pattern: the completion
722
+ * term is a LITERAL substring (the scoring model's input), so a filename
723
+ * containing `[`, `+`, `.` etc. must match as literal text, never as a regex.
724
+ * Both locality adapters pass the escaped term. */
725
+ function escapeFinderRegex(term) {
726
+ return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
727
+ }
728
+ /**
729
+ * Normalize ONE finder record (one `--print0` field, or one newline-dialect
730
+ * line) into a detached fact: the `./` prefix strip, the `.git` exclusion and
731
+ * the directory hint (a trailing `/`). PURE — the record stays a detached
732
+ * string. Returns `undefined` for an empty or excluded record.
733
+ */
734
+ function normalizeFinderRecord(raw) {
735
+ if (raw === "") return void 0;
736
+ const relative = raw.startsWith("./") ? raw.slice(2) : raw;
737
+ if (relative === ".git" || relative.startsWith(".git/") || relative.includes("/.git/")) return void 0;
738
+ return {
739
+ path: relative.endsWith("/") ? relative.slice(0, -1) : relative,
740
+ directoryHint: relative.endsWith("/")
741
+ };
742
+ }
743
+ /**
744
+ * Normalize a finder's COMPLETE stdout into detached records: NUL records when
745
+ * the finder honoured `--print0` (so legal filenames containing newlines
746
+ * survive), the newline fallback for a fake/older finder (preserving
747
+ * meaningful leading and trailing spaces in a filename). PURE — operates
748
+ * solely on detached strings. The streaming adapter path parses incrementally
749
+ * through {@link createFinderRecordStream} and only uses this whole-buffer
750
+ * form for the NUL-free dialect at process close.
751
+ */
752
+ function normalizeFinderRecords(stdout) {
753
+ const records = stdout.includes("\0") ? stdout.split("\0") : (() => {
754
+ const lines = stdout.split(/\r?\n/);
755
+ if (lines.at(-1) === "") lines.pop();
756
+ return lines;
757
+ })();
758
+ const out = [];
759
+ for (const record of records) {
760
+ const normalized = normalizeFinderRecord(record);
761
+ if (normalized !== void 0) out.push(normalized);
762
+ }
763
+ return out;
764
+ }
765
+ /**
766
+ * Parse a finder's stdout INCREMENTALLY: each NUL-terminated record is
767
+ * normalized and handed to `emit` as soon as it is complete, so neither the
768
+ * complete stdout nor the complete record list is ever retained. The finder's
769
+ * own record grammar is the one {@link normalizeFinderRecord} implements.
770
+ *
771
+ * A fake/older finder that ignored `--print0` is accepted through the newline
772
+ * fallback ONLY when its complete output contains no NUL: while the dialect is
773
+ * still unknown the bytes accumulate as one not-yet-terminated fragment (bounded
774
+ * by {@link MAX_UNTERMINATED_FINDER_CODE_UNITS}), and the first NUL proves the
775
+ * NUL dialect and commits that fragment as its first record.
776
+ *
777
+ * `shouldStop` is consulted before every record: when the consumer has
778
+ * abandoned this run (a deadline, an abort or a failure settled first), the
779
+ * stream stops consuming and reports `false` instead of continuing to feed a
780
+ * discarded collector.
781
+ */
782
+ function createFinderRecordStream(emit, options = {}) {
783
+ let pending = "";
784
+ let nulDialect = false;
785
+ let overflowed = false;
786
+ const emitRecord = (raw) => {
787
+ const record = normalizeFinderRecord(raw);
788
+ if (record !== void 0) emit(record);
789
+ };
790
+ return {
791
+ push(chunk) {
792
+ if (overflowed) return false;
793
+ pending += chunk;
794
+ let boundary = pending.indexOf("\0");
795
+ while (boundary !== -1) {
796
+ if (options.shouldStop?.() === true) return false;
797
+ nulDialect = true;
798
+ if (boundary > 65536) {
799
+ overflowed = true;
800
+ return false;
801
+ }
802
+ emitRecord(pending.slice(0, boundary));
803
+ pending = pending.slice(boundary + 1);
804
+ boundary = pending.indexOf("\0");
805
+ }
806
+ if (pending.length > 65536) {
807
+ overflowed = true;
808
+ return false;
809
+ }
810
+ return true;
811
+ },
812
+ finish() {
813
+ if (overflowed) return false;
814
+ if (nulDialect) return pending === "";
815
+ for (const record of normalizeFinderRecords(pending)) {
816
+ if (options.shouldStop?.() === true) return false;
817
+ emit(record);
818
+ }
819
+ pending = "";
820
+ return true;
821
+ }
822
+ };
823
+ }
824
+ /**
825
+ * The bounded recursive scan of one directory's SUBTREE: the root's direct
826
+ * children are always complete (a root-level `src/` must be found), deeper
827
+ * entries are capped at {@link MAX_FALLBACK_SCAN}. Paths are relative to
828
+ * `baseDir` (`sub/deep.ts`); `.git` is skipped (kimi parity); a symlinked
829
+ * directory is NEVER descended — at the search root and below it alike
830
+ * (cycle safety), so a link to a parent directory or to the workspace's
831
+ * outside cannot widen the scan or consume the traversal budget.
832
+ *
833
+ * ASYNC: the fuzzy fallback runs on the EDITOR path, so a synchronous
834
+ * whole-tree traversal would block the editor's event loop per keystroke. The
835
+ * scan yields to the event loop between directory levels and checks the
836
+ * AbortSignal inside the loop — the editor stays responsive and a cancelled
837
+ * request stops the traversal promptly.
838
+ */
839
+ async function scanSubtree(baseDir, driver, signal) {
840
+ const candidates = [];
841
+ const firstEntries = await driver.listDirectory(baseDir, "", signal);
842
+ if (signal.aborted || firstEntries === null) return [];
843
+ const stack = [];
844
+ for (const entry of firstEntries) {
845
+ if (entry.name === ".git") continue;
846
+ candidates.push({
847
+ path: entry.name,
848
+ kind: entry.kind
849
+ });
850
+ if (entry.descendable) stack.push(entry.name);
851
+ }
852
+ let scanned = 0;
853
+ while (stack.length > 0 && scanned < 2e3) {
854
+ if (signal.aborted) break;
855
+ const relativeDir = stack.pop() ?? "";
856
+ const entries = await driver.listDirectory(baseDir, relativeDir, signal);
857
+ if (entries === null) continue;
858
+ for (const entry of entries) {
859
+ if (signal.aborted || scanned >= 2e3) break;
860
+ if (entry.name === ".git") continue;
861
+ const path = `${relativeDir}/${entry.name}`;
862
+ scanned += 1;
863
+ candidates.push({
864
+ path,
865
+ kind: entry.kind
866
+ });
867
+ if (entry.kind === "directory" && entry.descendable) stack.push(path);
868
+ }
869
+ if (stack.length > 0) await new Promise((resolve) => setImmediate(resolve));
870
+ }
871
+ return signal.aborted ? [] : candidates;
872
+ }
873
+ /** Map one driver listing into path candidates, dropping `.git` (a `@` or
874
+ * `/image` listing never presents VCS internals). PURE. */
875
+ function listingCandidates(entries) {
876
+ return entries.filter((entry) => entry.name !== ".git").map((entry) => ({
877
+ path: entry.name,
878
+ kind: entry.kind
879
+ }));
880
+ }
881
+ /**
882
+ * Answer one resolved query with discovery facts. The routes, in order:
883
+ *
884
+ * 1. A scoped LISTING (explicit scope, empty term) reads the target
885
+ * directory's direct children.
886
+ * 2. An explicit scope with a NON-EMPTY term matches the named directory's
887
+ * DIRECT children first (Owner amendment D2): when any direct child scores
888
+ * on the term, exactly those candidates are returned — the user explicitly
889
+ * named this directory, so its own entries outrank a whole-subtree race and
890
+ * deeper candidates never run this round. Only with NO matching direct
891
+ * child (or an unreadable directory) does the query continue below.
892
+ * 3. A scoped or whole-tree FUZZY query uses the locality finder when
893
+ * available and the bounded subtree scan otherwise. Paths are relative to
894
+ * the QUERY's search base.
895
+ * @param query - the resolved path query (searchBase already absolute).
896
+ * @param driver - the locality's discovery boundary.
897
+ * @param signal - the editor's request abort.
898
+ */
899
+ async function discoverForQuery(query, driver, signal) {
900
+ if (query.explicitScope && query.searchTerm === "") {
901
+ if (signal.aborted) return [];
902
+ const direct = await driver.listDirectory(query.searchBase, "", signal);
903
+ if (signal.aborted || direct === null) return [];
904
+ return listingCandidates(direct);
905
+ }
906
+ if (query.explicitScope) {
907
+ if (signal.aborted) return [];
908
+ const direct = await driver.listDirectory(query.searchBase, "", signal);
909
+ if (signal.aborted) return [];
910
+ if (direct !== null) {
911
+ const lowerTerm = query.searchTerm.toLowerCase();
912
+ const matches = listingCandidates(direct).filter((candidate) => scorePathCandidate(candidate, lowerTerm) > 0);
913
+ if (matches.length > 0) return matches;
914
+ }
915
+ }
916
+ if (!query.winAbsolute && !query.raw.includes("\\")) {
917
+ const found = await driver.find(query.searchBase, query.searchTerm, signal);
918
+ if (signal.aborted) return [];
919
+ if (found !== null) {
920
+ const seen = new Set(found.map((candidate) => candidate.path));
921
+ const lowerTerm = query.searchTerm.toLowerCase();
922
+ const direct = await driver.listDirectory(query.searchBase, "", signal);
923
+ if (signal.aborted) return [];
924
+ const merged = (direct === null ? [] : listingCandidates(direct)).filter((candidate) => lowerTerm === "" || candidate.path.toLowerCase().includes(lowerTerm)).filter((candidate) => !seen.has(candidate.path));
925
+ return [...found, ...merged];
926
+ }
927
+ }
928
+ return scanSubtree(query.searchBase, driver, signal);
929
+ }
930
+ /** The system-prompt section name: TUI-private, never a host/preset name. */
931
+ const GIT_ATTRIBUTION_SECTION_NAME = "tui:git-attribution";
932
+ /** The official product identity (a product constant, never configurable). */
933
+ const PRODUCT_NAME = "@xmoon76/dsh-pi-tui";
934
+ const PRODUCT_EMAIL = "dsh-pi-tui@xmoon.org";
935
+ /** Settings values are untrusted; missing or invalid values stay Off. */
936
+ function parseGitAttributionMode(value) {
937
+ switch (value) {
938
+ case "off":
939
+ case "product":
940
+ case "product-model": return value;
941
+ default: return "off";
942
+ }
943
+ }
944
+ const attributionPrompts = {
945
+ off: "",
946
+ product: `# Git attribution
947
+
948
+ When you create a Git commit for work performed through dsh-pi-tui, include the following Git trailer exactly once:
949
+
950
+ Co-Authored-By: ${PRODUCT_NAME} <${PRODUCT_EMAIL}>
951
+
952
+ Preserve existing commit trailers. When amending a commit that already contains this exact trailer, do not add a duplicate.`,
953
+ "product-model": `# Git attribution
954
+
955
+ When you create a Git commit for work performed through dsh-pi-tui, include the following Git trailers exactly once:
956
+
957
+ Co-Authored-By: ${PRODUCT_NAME} <${PRODUCT_EMAIL}>
958
+ Assisted-By: {{provider}}/{{model}}
959
+
960
+ Preserve existing commit trailers. When amending a commit that already contains either exact trailer, do not add a duplicate.`
961
+ };
962
+ /** The effective attribution section text for the live mode. */
963
+ function gitAttributionPromptText(state) {
964
+ return attributionPrompts[state.mode];
965
+ }
966
+ //#endregion
967
+ //#region src/runtime/host-user-shell-port.ts
968
+ /** A started Remote run lost its terminal fact; automatic replay is forbidden. */
969
+ var HostUserShellOutcomeUnknownError = class extends Error {
970
+ constructor(message) {
971
+ super(message);
972
+ this.name = "HostUserShellOutcomeUnknownError";
973
+ }
974
+ };
975
+ /** The Host proved the sandbox runner/enforcement failed for this run. */
976
+ var HostUserShellSandboxRunnerError = class extends Error {
977
+ constructor(message) {
978
+ super(message);
979
+ this.name = "HostUserShellSandboxRunnerError";
980
+ }
981
+ };
982
+ /** The retained-tail bound of one settled stream. It is the semantic result
983
+ * bound shared by the Host mapping, the private wire decoder and the
984
+ * application's Session text. */
985
+ const MAX_HOST_USER_SHELL_STREAM_BYTES = 65536;
986
+ /** Bound on one refusal/failure message carried back to the Client. */
987
+ const MAX_HOST_USER_SHELL_MESSAGE_BYTES = 2048;
988
+ /** Bound on a Host-local spill path carried as a semantic fact. */
989
+ const MAX_HOST_USER_SHELL_SPILL_PATH_BYTES = 4096;
990
+ /** Total output budget of one settled result across BOTH streams. One stream
991
+ * may use the full per-stream cap; the other is then tail-clamped to the
992
+ * remainder, so the Session text can never grow with two independent caps. */
993
+ const MAX_HOST_USER_SHELL_RESULT_BYTES = 98304;
994
+ function tailOnCodePoint(bytes, maxBytes) {
995
+ if (bytes.length <= maxBytes) return {
996
+ text: bytes.toString("utf8"),
997
+ truncated: false
998
+ };
999
+ let start = bytes.length - maxBytes;
1000
+ while (start < bytes.length && (bytes[start] & 192) === 128) start += 1;
1001
+ return {
1002
+ text: bytes.subarray(start).toString("utf8"),
1003
+ truncated: true
1004
+ };
1005
+ }
1006
+ /**
1007
+ * Map one executor-collected stream to the bounded semantic output. The
1008
+ * executor's own truncation fact is preserved; a stream larger than the
1009
+ * semantic bound is clamped to its tail and marked truncated here.
1010
+ * @param output - the executor's collected output for one stream.
1011
+ * @param maxBytes - retained-tail bound (defaults to the per-stream cap).
1012
+ * @returns the bounded semantic output.
1013
+ */
1014
+ function boundedHostUserShellOutput(output, maxBytes = MAX_HOST_USER_SHELL_STREAM_BYTES) {
1015
+ const bounded = tailOnCodePoint(Buffer.from(output.text, "utf8"), maxBytes);
1016
+ return {
1017
+ text: bounded.text,
1018
+ truncated: output.truncated || bounded.truncated,
1019
+ ...output.spillPath === void 0 ? {} : { spillPath: output.spillPath }
1020
+ };
1021
+ }
1022
+ /**
1023
+ * Apply the TOTAL result budget across both streams. The per-stream caps are
1024
+ * independent; when both are large the second stream (stderr) is tail-clamped
1025
+ * to the remaining total budget and marked truncated, so one Session row can
1026
+ * never carry two full per-stream caps.
1027
+ * @param stdout - already per-stream bounded stdout.
1028
+ * @param stderr - already per-stream bounded stderr.
1029
+ * @returns the pair that satisfies the total result bound.
1030
+ */
1031
+ function boundedHostUserShellResultStreams(stdout, stderr) {
1032
+ const stdoutBytes = Buffer.byteLength(stdout.text, "utf8");
1033
+ if (stdoutBytes + Buffer.byteLength(stderr.text, "utf8") <= 98304) return {
1034
+ stdout,
1035
+ stderr
1036
+ };
1037
+ return {
1038
+ stdout,
1039
+ stderr: boundedHostUserShellOutput(stderr, Math.max(0, MAX_HOST_USER_SHELL_RESULT_BYTES - stdoutBytes))
1040
+ };
1041
+ }
1042
+ //#endregion
1043
+ //#region src/runtime/direct/file-completion/host-discovery.ts
1044
+ /**
1045
+ * The Direct Host discovery implementation (TS8-A, renamed by TS8-HF1): the
1046
+ * DIRECT process's filesystem behind the neutral {@link LocalDiscoveryDriver}
1047
+ * contract. Its ONE legitimate consumer is the explicit-path `@` navigation
1048
+ * route of the Session scope
1049
+ * (`runtime/direct/host-file-augmentation-direct.ts`), where the user
1050
+ * explicitly typed the scope (`@src/`, `@../`, `@/abs`, `@~/`).
1051
+ *
1052
+ * A BARE Session `@` query (`@foo`) never runs through this adapter — that
1053
+ * path is the OFFICIAL Host authority's (`ctx.fileReferences.list` through the
1054
+ * port), whose candidates arrive already filtered, ranked and bounded. The
1055
+ * sessionless `HostFileScope { kind: 'workspace', workspaceId }` route is the
1056
+ * OFFICIAL `WorkspaceFileSearch`
1057
+ * (`runtime/direct/file-completion/official-workspace-search.ts`) — this
1058
+ * finder never answers it.
1059
+ *
1060
+ * It owns the Direct Host process's own PATH/PATHEXT finder detection, its
1061
+ * `node:fs` facts and its fd/fdfind process. The small syscall-level
1062
+ * duplication against `client/file-completion/local-discovery.ts` is
1063
+ * deliberate: the two adapters read DIFFERENT machines under Remote, and one
1064
+ * concrete source owner for both localities is exactly what TS8-A removes.
1065
+ * @module @xmoon76/dsh-pi-tui/runtime/direct/file-completion/host-discovery
1066
+ */
1067
+ /**
1068
+ * The Direct Host process's explicit path-query environment facts. Under
1069
+ * Remote these are the HOST machine's facts, never the Client's; today Direct
1070
+ * runs in-process, so the numbers coincide — that coincidence is deliberately
1071
+ * not encoded in the domain contract.
1072
+ */
1073
+ function hostPathQueryEnvironment() {
1074
+ return {
1075
+ homeDir: homedir(),
1076
+ windowsHost: process.platform === "win32"
1077
+ };
1078
+ }
1079
+ /**
1080
+ * Locate an executable file-finder on the Direct Host process's PATH: `fd`
1081
+ * preferred, `fdfind` second. See the Client adapter for the probe contract.
1082
+ */
1083
+ function resolveFdPath() {
1084
+ const pathEntries = process.env.PATH?.split(delimiter) ?? [];
1085
+ 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()]);
1086
+ for (const name of ["fd", "fdfind"]) for (const entry of pathEntries) {
1087
+ const dir = entry === "" ? "." : entry;
1088
+ for (const suffix of ["", ...suffixes]) {
1089
+ const candidate = join(dir, `${name}${suffix}`);
1090
+ try {
1091
+ if (statSync(candidate).isFile() && accessSync(candidate, constants.X_OK) === void 0) return candidate;
1092
+ } catch {}
1093
+ }
1094
+ }
1095
+ return null;
1096
+ }
1097
+ /** Join a Host path WITHOUT collapsing a `..` segment. The Host's filesystem
1098
+ * backend anchors a POSIX path containing a `..` segment with its physical
1099
+ * spelling (the kernel resolves an intermediate symlink before the parent step),
1100
+ * so a search base that deliberately keeps that traversal may not be lexically
1101
+ * re-normalized on the way to a syscall. For every base the neutral resolver
1102
+ * already normalized (no `..` left) this is identical to `path.join`. */
1103
+ function hostJoin(baseDir, relative) {
1104
+ if (relative === "") return baseDir;
1105
+ return baseDir.endsWith("/") ? `${baseDir}${relative}` : `${baseDir}/${relative}`;
1106
+ }
1107
+ /** Whether one Dirent is a directory (symlinks followed; a broken link is a
1108
+ * file candidate — the fork's rule). */
1109
+ function entryIsDirectory(baseDir, name, entry) {
1110
+ if (entry.isDirectory()) return true;
1111
+ if (entry.isSymbolicLink()) try {
1112
+ return statSync(hostJoin(baseDir, name)).isDirectory();
1113
+ } catch {
1114
+ return false;
1115
+ }
1116
+ return false;
1117
+ }
1118
+ /** Run the Direct Host finder for one scoped query. Returns NULL on finder
1119
+ * FAILURE (non-zero exit, spawn error, truncated output, over-bound record,
1120
+ * over-budget run — the neutral policy then runs the bounded fallback), `[]`
1121
+ * on a genuine no-match or an abort.
1122
+ *
1123
+ * Like the Client adapter, the Host finder runs without an argv result cap,
1124
+ * streams every match into the same neutral two-top-50 collector, and owns the
1125
+ * ONE {@link MAX_FINDER_WALL_MS} wall budget (Owner amendment D4). */
1126
+ function runHostFinder(fdPath, baseDir, term, signal, finderWallMs, now = performance.now) {
1127
+ const args = [
1128
+ "--base-directory",
1129
+ baseDir,
1130
+ "-i",
1131
+ "--full-path",
1132
+ "--print0",
1133
+ "--type",
1134
+ "f",
1135
+ "--type",
1136
+ "d",
1137
+ "--type",
1138
+ "l",
1139
+ "--hidden",
1140
+ "--no-ignore",
1141
+ "--exclude",
1142
+ ".git",
1143
+ "--exclude",
1144
+ ".git/*",
1145
+ "--exclude",
1146
+ ".git/**"
1147
+ ];
1148
+ if (term !== "") args.push(escapeFinderRegex(term));
1149
+ return new Promise((resolve) => {
1150
+ if (signal.aborted) {
1151
+ resolve([]);
1152
+ return;
1153
+ }
1154
+ let child;
1155
+ try {
1156
+ child = spawn(fdPath, args, { stdio: [
1157
+ "ignore",
1158
+ "pipe",
1159
+ "ignore"
1160
+ ] });
1161
+ } catch {
1162
+ resolve(null);
1163
+ return;
1164
+ }
1165
+ const collector = createBoundedFinderCandidateCollector(term);
1166
+ const deadline = now.call(performance) + finderWallMs;
1167
+ let settled = false;
1168
+ let budgetTimer;
1169
+ const stopBudget = () => {
1170
+ if (budgetTimer !== void 0) {
1171
+ clearTimeout(budgetTimer);
1172
+ budgetTimer = void 0;
1173
+ }
1174
+ };
1175
+ const settle = (results) => {
1176
+ if (settled) return;
1177
+ settled = true;
1178
+ stopBudget();
1179
+ signal.removeEventListener("abort", onAbort);
1180
+ resolve(results);
1181
+ };
1182
+ const onAbort = () => {
1183
+ if (child.exitCode === null) child.kill("SIGKILL");
1184
+ settle([]);
1185
+ };
1186
+ signal.addEventListener("abort", onAbort, { once: true });
1187
+ if (now === performance.now) budgetTimer = setTimeout(() => {
1188
+ if (child.exitCode === null) child.kill("SIGKILL");
1189
+ settle(null);
1190
+ }, finderWallMs);
1191
+ let recordsSinceDeadlineCheck = 0;
1192
+ const records = createFinderRecordStream((record) => {
1193
+ let isDirectory = record.directoryHint;
1194
+ if (!isDirectory) try {
1195
+ isDirectory = statSync(hostJoin(baseDir, record.path)).isDirectory();
1196
+ } catch {
1197
+ isDirectory = false;
1198
+ }
1199
+ collector.offer({
1200
+ path: record.path,
1201
+ kind: isDirectory ? "directory" : "file"
1202
+ });
1203
+ recordsSinceDeadlineCheck += 1;
1204
+ if (recordsSinceDeadlineCheck >= 64) {
1205
+ recordsSinceDeadlineCheck = 0;
1206
+ if (now.call(performance) >= deadline) {
1207
+ if (child.exitCode === null) child.kill("SIGKILL");
1208
+ settle(null);
1209
+ }
1210
+ }
1211
+ }, { shouldStop: () => settled });
1212
+ child.stdout.setEncoding("utf-8");
1213
+ child.stdout.on("data", (chunk) => {
1214
+ if (settled) return;
1215
+ if (!records.push(chunk)) {
1216
+ if (child.exitCode === null) child.kill("SIGKILL");
1217
+ settle(null);
1218
+ }
1219
+ });
1220
+ child.on("error", () => settle(null));
1221
+ child.stdout.on("error", () => {
1222
+ if (child.exitCode === null) child.kill("SIGKILL");
1223
+ settle(null);
1224
+ });
1225
+ child.on("close", (code) => {
1226
+ if (signal.aborted) {
1227
+ settle([]);
1228
+ return;
1229
+ }
1230
+ if (code !== 0) {
1231
+ settle(null);
1232
+ return;
1233
+ }
1234
+ if (now.call(performance) >= deadline) {
1235
+ settle(null);
1236
+ return;
1237
+ }
1238
+ if (!records.finish()) {
1239
+ settle(null);
1240
+ return;
1241
+ }
1242
+ if (now.call(performance) >= deadline) {
1243
+ settle(null);
1244
+ return;
1245
+ }
1246
+ settle(collector.finish());
1247
+ });
1248
+ });
1249
+ }
1250
+ /**
1251
+ * The Direct Host discovery driver: the Direct Host process's OWN filesystem,
1252
+ * with a Host PATH finder when present.
1253
+ *
1254
+ * `fdPath` is a test/API pin: `undefined` probes the Host PATH, `null` FORCES
1255
+ * the bounded fallback (no finder), a string pins one finder.
1256
+ */
1257
+ var DirectHostDiscoveryDriver = class {
1258
+ fdPathValue;
1259
+ finderWallMsValue;
1260
+ nowValue;
1261
+ constructor(fdPath = void 0, finderWallMs = 500, now = performance.now) {
1262
+ this.fdPathValue = fdPath === void 0 ? resolveFdPath() : fdPath;
1263
+ this.finderWallMsValue = finderWallMs;
1264
+ this.nowValue = now;
1265
+ }
1266
+ /** The pinned/detected Host finder (null = bounded-fallback only). */
1267
+ get fdPath() {
1268
+ return this.fdPathValue;
1269
+ }
1270
+ async listDirectory(baseDir, relativeDir, signal) {
1271
+ if (signal.aborted) return null;
1272
+ let entries;
1273
+ try {
1274
+ entries = readdirSync(hostJoin(baseDir, relativeDir), { withFileTypes: true });
1275
+ } catch {
1276
+ return null;
1277
+ }
1278
+ if (signal.aborted) return null;
1279
+ const dir = hostJoin(baseDir, relativeDir);
1280
+ return entries.map((entry) => ({
1281
+ name: entry.name,
1282
+ kind: entryIsDirectory(dir, entry.name, entry) ? "directory" : "file",
1283
+ descendable: entry.isDirectory() && !entry.isSymbolicLink()
1284
+ }));
1285
+ }
1286
+ async find(baseDir, term, signal) {
1287
+ if (this.fdPathValue === null) return null;
1288
+ return runHostFinder(this.fdPathValue, baseDir, term, signal, this.finderWallMsValue, this.nowValue);
1289
+ }
1290
+ };
1291
+ //#endregion
1292
+ //#region src/runtime/direct/file-completion/official-workspace-search.ts
1293
+ /**
1294
+ * The OFFICIAL Host Workspace file search the sessionless `@file` surface uses
1295
+ * (M6-1/F5-B): a thin wrapper around the published
1296
+ * `@deepseek-ai/dsh-file-reference-local/search` primitive. It performs no
1297
+ * matching, ranking, traversal, path normalization or exclusion policy of its
1298
+ * own — the official `WorkspaceFileSearch` owns all of that, with the SAME
1299
+ * published defaults the official Host provider runs with:
1300
+ *
1301
+ * ```text
1302
+ * maxResults DEFAULT_FILE_SEARCH_MAX_RESULTS (20)
1303
+ * maxEntries DEFAULT_FILE_SEARCH_MAX_ENTRIES (50_000)
1304
+ * excludedDirectories DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES
1305
+ * ```
1306
+ *
1307
+ * The Direct in-process adapter and the Remote Host bridge both use this ONE
1308
+ * helper, so the two backends share the same discovery semantics. It is NOT
1309
+ * the retired Direct `fd`/`fdfind` scanner: no finder process, no custom
1310
+ * ranking, no broadened path syntax.
1311
+ *
1312
+ * CACHE BUDGET (plan §4.4): at most FOUR resident official indexes, evicted
1313
+ * least-recently-read while idle. When all four are in use, the fifth query
1314
+ * runs one temporary official search and disposes it in its own `finally` —
1315
+ * a live index is never interrupted and the map never grows past the budget.
1316
+ * Every entry is released on {@link OfficialWorkspaceSearchPool.dispose}.
1317
+ *
1318
+ * @module @xmoon76/dsh-pi-tui/runtime/direct/file-completion/official-workspace-search
1319
+ */
1320
+ /** The fixed search configuration (the published official defaults). */
1321
+ const OFFICIAL_FILE_SEARCH_CONFIG = {
1322
+ maxResults: DEFAULT_FILE_SEARCH_MAX_RESULTS,
1323
+ maxEntries: DEFAULT_FILE_SEARCH_MAX_ENTRIES,
1324
+ excludedDirectories: DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES
1325
+ };
1326
+ /** The resident-index budget the plan fixes. */
1327
+ const MAX_RESIDENT_INDEXES = 4;
1328
+ function mapCandidates(candidates) {
1329
+ return candidates.map((candidate) => ({
1330
+ path: candidate.path,
1331
+ kind: candidate.kind
1332
+ }));
1333
+ }
1334
+ /**
1335
+ * The bounded official-search cache shared by the Direct adapter and the
1336
+ * Remote Host bridge. One instance per owning Host row (or Direct runner);
1337
+ * {@link dispose} releases every resident official index.
1338
+ */
1339
+ var OfficialWorkspaceSearchPool = class {
1340
+ entries = /* @__PURE__ */ new Map();
1341
+ disposed = false;
1342
+ /**
1343
+ * Run ONE official workspace query against the registry-resolved root.
1344
+ * `signal` cancels only this caller's wait, exactly like the official
1345
+ * primitive. A disposed pool fails fast: no search is started for a row that
1346
+ * is already gone.
1347
+ */
1348
+ async list(root, query, signal) {
1349
+ if (this.disposed) throw new Error("the official workspace search pool is disposed");
1350
+ signal.throwIfAborted();
1351
+ const key = root.workspaceId;
1352
+ let resident = this.entries.get(key);
1353
+ if (resident !== void 0 && resident.canonicalPath !== root.path) {
1354
+ resident.search.dispose();
1355
+ this.entries.delete(key);
1356
+ resident = void 0;
1357
+ }
1358
+ if (resident === void 0) {
1359
+ if (!this.hasIdleSlot()) {
1360
+ const temporary = new WorkspaceFileSearch(root.path, OFFICIAL_FILE_SEARCH_CONFIG);
1361
+ try {
1362
+ const candidates = await temporary.list(query, signal);
1363
+ signal.throwIfAborted();
1364
+ return mapCandidates(candidates);
1365
+ } finally {
1366
+ temporary.dispose();
1367
+ }
1368
+ }
1369
+ resident = {
1370
+ canonicalPath: root.path,
1371
+ search: new WorkspaceFileSearch(root.path, OFFICIAL_FILE_SEARCH_CONFIG),
1372
+ active: 0
1373
+ };
1374
+ this.entries.set(key, resident);
1375
+ this.evictBeyondBudget();
1376
+ } else {
1377
+ this.entries.delete(key);
1378
+ this.entries.set(key, resident);
1379
+ }
1380
+ resident.active += 1;
1381
+ try {
1382
+ const candidates = await resident.search.list(query, signal);
1383
+ signal.throwIfAborted();
1384
+ return mapCandidates(candidates);
1385
+ } finally {
1386
+ resident.active -= 1;
1387
+ }
1388
+ }
1389
+ /**
1390
+ * Mark every resident official index stale (the Host `tool/result`
1391
+ * invalidation hook). The official primitive keeps answering from its stale
1392
+ * entries while the rebuild happens behind the caret — that advisory
1393
+ * freshness policy stays with the primitive.
1394
+ */
1395
+ invalidateAll() {
1396
+ for (const resident of this.entries.values()) resident.search.invalidate();
1397
+ }
1398
+ /** Abort traversal, release every resident index (service/Host disposal). */
1399
+ dispose() {
1400
+ if (this.disposed) return;
1401
+ this.disposed = true;
1402
+ for (const resident of this.entries.values()) resident.search.dispose();
1403
+ this.entries.clear();
1404
+ }
1405
+ /** The number of resident indexes (cache-budget probes). */
1406
+ get residentIndexes() {
1407
+ return this.entries.size;
1408
+ }
1409
+ hasIdleSlot() {
1410
+ if (this.entries.size < MAX_RESIDENT_INDEXES) return true;
1411
+ for (const resident of this.entries.values()) if (resident.active === 0) return true;
1412
+ return false;
1413
+ }
1414
+ evictBeyondBudget() {
1415
+ while (this.entries.size > MAX_RESIDENT_INDEXES) {
1416
+ let victimKey;
1417
+ for (const [key, resident] of this.entries) if (resident.active === 0) {
1418
+ victimKey = key;
1419
+ break;
1420
+ }
1421
+ if (victimKey === void 0) return;
1422
+ const victim = this.entries.get(victimKey);
1423
+ this.entries.delete(victimKey);
1424
+ victim?.search.dispose();
1425
+ }
1426
+ }
1427
+ };
1428
+ //#endregion
1429
+ //#region src/runtime/direct/host-file-augmentation-direct.ts
1430
+ /**
1431
+ * The session `@`-reference Host router (TS8-HF1): ONE Host-side authority
1432
+ * that answers a completion query with the routing boundary
1433
+ *
1434
+ * ```text
1435
+ * bare workspace fuzzy search -> official ctx.fileReferences.list
1436
+ * @foo @readme @src @.env (workspace index, cache, exclusions,
1437
+ * scoring, maxResults stay authoritative)
1438
+ *
1439
+ * explicit path navigation -> dsh-pi-tui Host scoped discovery
1440
+ * @src/ @src/uti @./ @../shared/foo (the exact scope the user typed:
1441
+ * @../../foo @/tmp/foo @~/Down recursive fuzzy inside it, explicit
1442
+ * Windows drive @C:/work/foo and UNC parent/absolute/native paths)
1443
+ * ```
1444
+ *
1445
+ * The decision is the TOKEN's explicit path navigation, never the resolved
1446
+ * search base's workspace containment (the superseded v1 rule): a user-typed
1447
+ * separator, a root form (`.`/`..`/`~`) or a Windows absolute path is what
1448
+ * selects the scoped route, so `@dist/` and `@link/foo` address their
1449
+ * explicitly named scope even when the official provider would exclude or not
1450
+ * traverse it.
1451
+ *
1452
+ * POSIX BOUNDARY: on a POSIX Host a backslash is an ordinary FILENAME character,
1453
+ * but the reused TS8-A path resolver selects its Windows dialect from the token
1454
+ * alone and normalizes the separators (a pinned cross-dialect contract of the
1455
+ * Client-local completion — `test/domain-file-completion.test.ts`). The
1456
+ * augmentation therefore does NOT CLAIM an ambiguous POSIX token that contains a
1457
+ * backslash: such a token is left to the official provider rather than searched
1458
+ * in a scope we cannot represent verbatim. This is a deliberate fail-closed
1459
+ * narrowing, not a claim that the token is a bare fuzzy query; delete the guard
1460
+ * once the shared resolver distinguishes host dialect, token dialect and literal
1461
+ * backslashes.
1462
+ *
1463
+ * PARENT-TRAVERSAL SPELLING: a relative scope is searched with the SAME spelling
1464
+ * the Host's local filesystem backend gives the accepted value. On a POSIX Host a
1465
+ * path containing a `..` segment is anchored with its PHYSICAL spelling by
1466
+ * `dsh-fs-local` (kernel resolves an intermediate symlink before the parent step);
1467
+ * the scoped search therefore keeps the raw `<cwd>/<displayBase>` concatenation for
1468
+ * those queries instead of the lexically joined directory, so completion and the
1469
+ * model's read can never land in two different physical directories. Windows, the
1470
+ * absolute forms (already verbatim) and the home shorthand (absolute normalized
1471
+ * value) keep the shared resolver's spelling.
1472
+ *
1473
+ * The official provider is called ONLY on the bare route; an authoritative
1474
+ * official `[]` stays empty and never falls back to the scanner. The scoped
1475
+ * route never calls the official provider and needs no capability from it.
1476
+ *
1477
+ * The explicit-scope route is ONE shared implementation
1478
+ * (`listPiTuiExplicitHostFileReferences`): the Session router below, the Direct
1479
+ * Workspace route and the Remote sessionless bridge all converge on it with
1480
+ * their OWN authority-resolved Host cwd (the Session's effective cwd, the
1481
+ * Workspace registry root), so a sessionless explicit query answers with the
1482
+ * same classification, discovery and ranking the Session scope has always had
1483
+ * — never a second scanner or a Client filesystem fact.
1484
+ *
1485
+ * Home shorthand (`@~`, `@~/Down`) is dsh-pi-tui INPUT syntax: discovery runs
1486
+ * against the Host HOME, but every returned candidate is materialized as an
1487
+ * ABSOLUTE Host path — DSH path resolution performs no shell-style `~`
1488
+ * expansion, so a literal `~/...` completion value would be unusable. Ranking
1489
+ * always scores the SCOPE-RELATIVE candidate, never the materialized absolute
1490
+ * path (the home prefix itself must not satisfy the path-substring tier).
1491
+ *
1492
+ * This authority receives HOST facts only (the live Agent, the Host discovery
1493
+ * driver, the Host path environment); it never reads the Client cwd, home or
1494
+ * platform.
1495
+ *
1496
+ * TODO(upstream-file-reference-explicit-scope): Delete the pi-tui
1497
+ * explicit-scope augmentation when the minimum supported DSH fileReferences
1498
+ * provider supports equivalent explicit scoped recursive search,
1499
+ * parent/absolute Host path navigation, explicit excluded/symlink scope
1500
+ * access, and a Host-home-safe completion representation.
1501
+ *
1502
+ * @module @xmoon76/dsh-pi-tui/runtime/direct/host-file-augmentation-direct
1503
+ */
1504
+ /** Whether the token names an EXPLICIT path scope (the frozen classifier,
1505
+ * decided from the raw token and the HOST platform — never from filesystem
1506
+ * existence, official result count, or workspace containment).
1507
+ *
1508
+ * A POSIX host has ONE separator: any `/` is an explicit scope, and the root
1509
+ * forms are explicit. A token that also contains a backslash is deliberately NOT
1510
+ * claimed (see the module comment): the reused resolver cannot represent its
1511
+ * literal POSIX scope, so the official provider keeps it.
1512
+ *
1513
+ * A Windows host treats `\` as a separator as well and accepts any
1514
+ * win32-absolute form (drive/UNC) even before its first separator is visible.
1515
+ *
1516
+ * The ONE classifier every Host-side caller shares (the Session router, the
1517
+ * Direct Workspace route and the Remote sessionless bridge): the bare/explicit
1518
+ * decision is the token's spelling against the HOST dialect, never the scope
1519
+ * the caller resolved, a filesystem fact or an official result count. */
1520
+ function isExplicitHostFileQuery(raw, environment) {
1521
+ if (raw === "") return false;
1522
+ if (environment.windowsHost) return raw === "." || raw === ".." || raw === "~" || raw.includes("/") || raw.includes("\\") || win32.isAbsolute(raw);
1523
+ if (raw.includes("\\")) return false;
1524
+ return raw === "." || raw === ".." || raw === "~" || raw.includes("/");
1525
+ }
1526
+ /** Whether the token is a leading-home form (`~`, `~/x`, `~\x`). */
1527
+ function isHomeToken(raw) {
1528
+ return raw === "~" || raw.startsWith("~/") || raw.startsWith("~\\");
1529
+ }
1530
+ /** Materialize one candidate discovered under a HOME scope as an ABSOLUTE Host
1531
+ * path (the `~` shorthand must never reach the prompt as literal text). */
1532
+ function materializeHostPath(candidate, searchBase, windowsHost) {
1533
+ return {
1534
+ path: (windowsHost ? win32 : posix).join(searchBase, candidate.path),
1535
+ kind: candidate.kind
1536
+ };
1537
+ }
1538
+ /** One `..` path SEGMENT — the exact shape the Host filesystem backend keys its
1539
+ * physical-spelling rule on (`dsh-fs-local`'s `localDisplayPath`). */
1540
+ const PARENT_SEGMENT = /(?:^|[\\/])\.\.(?:[\\/]|$)/u;
1541
+ /**
1542
+ * The directory one explicit scope searches.
1543
+ *
1544
+ * The Host's local filesystem backend anchors a POSIX path that contains a `..`
1545
+ * SEGMENT with its PHYSICAL spelling (the raw `<anchor>/<path>`, deliberately
1546
+ * unnormalized), so the kernel resolves an intermediate symlink BEFORE the parent
1547
+ * step; every other spelling goes through a lexical `resolve(anchor, path)`, and
1548
+ * Windows always resolves lexically. Two consequences drive this function:
1549
+ *
1550
+ * 1. The anchor is `<hostCwd>` for a relative scope and the value itself for an
1551
+ * absolute one, and the rule tests the WHOLE anchored spelling — so a `..`
1552
+ * carried by the SESSION CWD flips it just like one in the typed scope. The
1553
+ * consumer applies that rule to the value we hand it (`displayBase + name`), so
1554
+ * the search must use the same spelling; otherwise the completion could offer a
1555
+ * path the model's read resolves into a DIFFERENT physical directory.
1556
+ * 2. A home shorthand emits an ABSOLUTE value through `path.join`, which normalizes
1557
+ * lexically. Its scope must be normalized the same way: the bare `~`/`~/` root
1558
+ * form is the one form whose search base is the raw `homedir()` string, so a
1559
+ * `..`-bearing HOME would otherwise be searched physically while the value we
1560
+ * emit names the lexical directory.
1561
+ *
1562
+ * Absolute forms already spell their traversal verbatim. This is one segment test
1563
+ * plus one concatenation (plus one lexical normalize for the home root form) — the
1564
+ * consumer's own rule applied to the value we are about to hand it, not a second
1565
+ * path parser.
1566
+ */
1567
+ function scopeSearchBase(resolved, raw, hostCwd, environment) {
1568
+ const api = environment.windowsHost ? win32 : posix;
1569
+ if (isHomeToken(raw)) return api.normalize(resolved.searchBase);
1570
+ if (environment.windowsHost) return resolved.searchBase;
1571
+ if (raw.startsWith("/") || resolved.winAbsolute) return resolved.searchBase;
1572
+ const physicalScope = `${hostCwd}/${resolved.displayBase}`;
1573
+ return PARENT_SEGMENT.test(physicalScope) ? physicalScope : resolved.searchBase;
1574
+ }
1575
+ /**
1576
+ * Answer ONE explicit Host path scope (`@src/`, `@../shared/`, `@/abs`,
1577
+ * `@~/Down`) with the shared TS8-A machinery, anchored at `hostCwd`.
1578
+ *
1579
+ * The caller has already decided the query is EXPLICIT (through
1580
+ * {@link isExplicitHostFileQuery}) and owns everything else: the bare-fuzzy
1581
+ * route, the Owner/authorization gate, the WorkspaceId/Agent lifecycle, the
1582
+ * search base's authority and the file-existence safety policy. This helper
1583
+ * answers ONE question — for a scope the user explicitly named, how does the
1584
+ * HOST (its cwd dialect, its OS) complete it — with the frozen pipeline
1585
+ * `resolvePathQuery → scopeSearchBase → discoverForQuery → rankPathCandidates`
1586
+ * and the frozen output shapes (`~` emits ABSOLUTE Host paths, other scopes
1587
+ * reattach the user's display base). No path/ranking algorithm is duplicated
1588
+ * anywhere: every Session and Workspace caller converges here.
1589
+ *
1590
+ * Cancellation (the caller's `signal`) outranks every outcome: an aborted
1591
+ * request rejects at entry and after each await.
1592
+ */
1593
+ async function listPiTuiExplicitHostFileReferences(hostCwd, query, signal, deps) {
1594
+ signal.throwIfAborted();
1595
+ const resolved = resolvePathQuery(query, hostCwd, deps.environment);
1596
+ const searchBase = scopeSearchBase(resolved, query, hostCwd, deps.environment);
1597
+ const discovered = await discoverForQuery(searchBase === resolved.searchBase ? resolved : {
1598
+ ...resolved,
1599
+ searchBase
1600
+ }, deps.driver, signal);
1601
+ signal.throwIfAborted();
1602
+ const homeToken = isHomeToken(query);
1603
+ return {
1604
+ kind: "ok",
1605
+ items: rankPathCandidates(homeToken ? discovered : discovered.map((candidate) => reattachDisplayBase(candidate, resolved)), resolved.searchTerm).map((candidate) => homeToken ? materializeHostPath(candidate, resolved.searchBase, deps.environment.windowsHost) : {
1606
+ path: candidate.path,
1607
+ kind: candidate.kind
1608
+ })
1609
+ };
1610
+ }
1611
+ /**
1612
+ * Answer one session `@` completion query over the Host facts.
1613
+ *
1614
+ * Cancellation (the caller's `signal`) outranks every route: an aborted
1615
+ * request rejects at entry — before the route/capability decision — and again
1616
+ * after each await, so a cancelled scope never serves a late result and never
1617
+ * reports `unavailable`.
1618
+ *
1619
+ * @param agent - the live Agent the session scope resolved to.
1620
+ * @param query - the official query form (path text following `@`).
1621
+ * @param signal - caller cancellation.
1622
+ * @param deps - the Host facts this router answers with.
1623
+ */
1624
+ async function listPiTuiHostFileReferences(agent, query, signal, deps) {
1625
+ signal.throwIfAborted();
1626
+ if (!isExplicitHostFileQuery(query, deps.environment)) {
1627
+ const official = deps.official;
1628
+ if (official === void 0) return {
1629
+ kind: "unavailable",
1630
+ reason: "the official Host file-reference service is not mounted"
1631
+ };
1632
+ const candidates = await official.list(agent, query, signal);
1633
+ signal.throwIfAborted();
1634
+ return {
1635
+ kind: "ok",
1636
+ items: candidates.map((candidate) => ({
1637
+ path: candidate.path,
1638
+ kind: candidate.kind
1639
+ }))
1640
+ };
1641
+ }
1642
+ return listPiTuiExplicitHostFileReferences(effectiveAgentCwd(deps.workingDirectory, agent) ?? process.cwd(), query, signal, deps);
1643
+ }
1644
+ //#endregion
1645
+ //#region src/runtime/host-user-shell-execution.ts
1646
+ /**
1647
+ * The one Host user-shell execution core shared by the Direct adapter and the
1648
+ * authenticated split-Host service.
1649
+ *
1650
+ * Both policies run the raw command through the official subprocess seam as
1651
+ * `['bash', '-c', command]` (no wrapper, relay or shell-flag translation):
1652
+ * - `bypass` spawns that argv directly;
1653
+ * - `sandbox` resolves the EXACT Session policy and calls the installed
1654
+ * official `ctx.sandbox.confine` exactly once, requires `enforcement:
1655
+ * 'full'`, and spawns the EXACT argv returned by that one call.
1656
+ *
1657
+ * Output is bounded by the subprocess collect/spill dispositions and read only
1658
+ * after `done` AND `waitForExit` proved the managed range empty. Cancellation
1659
+ * is the caller's signal: the provider terminates the range, and this module
1660
+ * joins it before returning. No long-lived stream, acknowledgement window or
1661
+ * second process owner exists here.
1662
+ * @module @xmoon76/dsh-pi-tui/runtime/host-user-shell-execution
1663
+ */
1664
+ const HOST_USER_SHELL_SPILL_MAX_BYTES = 67108864;
1665
+ const HOST_USER_SHELL_GRACE_MS = 5e3;
1666
+ /** A final pre-spawn veto: throwing it prevents the spawn and is mapped by the
1667
+ * caller into its own truthful refusal. */
1668
+ var HostShellExecutionVeto = class extends Error {
1669
+ reason;
1670
+ constructor(reason, message) {
1671
+ super(message);
1672
+ this.name = "HostShellExecutionVeto";
1673
+ this.reason = reason;
1674
+ }
1675
+ };
1676
+ /** Bound a Host diagnostic so a wire message bound can never be exceeded. */
1677
+ function boundedHostShellMessage(text) {
1678
+ const bytes = Buffer.from(text, "utf8");
1679
+ if (bytes.length <= 2048) return text;
1680
+ let end = 2045;
1681
+ while (end > 0 && (bytes[end] & 192) === 128) end -= 1;
1682
+ return `${bytes.subarray(0, end).toString("utf8")}…`;
1683
+ }
1684
+ function hostShellDiagnostic(error) {
1685
+ return boundedHostShellMessage(error instanceof Error ? error.message : String(error));
1686
+ }
1687
+ function refused(message) {
1688
+ return {
1689
+ kind: "refused",
1690
+ reason: "policy-unavailable",
1691
+ message: boundedHostShellMessage(message)
1692
+ };
1693
+ }
1694
+ function failed(phase, message) {
1695
+ return {
1696
+ kind: "failed",
1697
+ phase,
1698
+ message: boundedHostShellMessage(message)
1699
+ };
1700
+ }
1701
+ function collectedOutput(reader) {
1702
+ if (reader === void 0) throw new Error("the Host subprocess did not expose the requested collected stream");
1703
+ const read = reader.readFrom(0);
1704
+ const spillPath = read.spillPath;
1705
+ if (spillPath !== void 0 && Buffer.byteLength(spillPath, "utf8") > 4096) return {
1706
+ text: read.text,
1707
+ truncated: read.lossy
1708
+ };
1709
+ return {
1710
+ text: read.text,
1711
+ truncated: read.lossy,
1712
+ ...spillPath === void 0 ? {} : { spillPath }
1713
+ };
1714
+ }
1715
+ /**
1716
+ * Execute one user-shell command to settlement through the official
1717
+ * subprocess seam. Never throws for a command-level failure; a thrown
1718
+ * {@link HostShellExecutionVeto} from `beforeSpawn` propagates without a spawn.
1719
+ * @param request - command, exact Host scope and the resolved official services.
1720
+ * @returns the bounded semantic result or a truthful refusal/failure.
1721
+ */
1722
+ async function executeHostShellOnce(request) {
1723
+ const { command, cwd, policy, signal, subprocess } = request;
1724
+ const rawArgv = [
1725
+ "bash",
1726
+ "-c",
1727
+ command
1728
+ ];
1729
+ let confined;
1730
+ if (policy === "sandbox") {
1731
+ const prepared = await confineSandbox(rawArgv, request);
1732
+ if ("kind" in prepared) return prepared;
1733
+ confined = prepared;
1734
+ }
1735
+ signal.throwIfAborted();
1736
+ const spec = {
1737
+ argv: confined?.argv ?? rawArgv,
1738
+ cwd,
1739
+ stdio: {
1740
+ stdin: "ignore",
1741
+ stdout: {
1742
+ maxBytes: MAX_HOST_USER_SHELL_STREAM_BYTES,
1743
+ spill: { maxBytes: HOST_USER_SHELL_SPILL_MAX_BYTES }
1744
+ },
1745
+ stderr: {
1746
+ maxBytes: MAX_HOST_USER_SHELL_STREAM_BYTES,
1747
+ spill: { maxBytes: HOST_USER_SHELL_SPILL_MAX_BYTES }
1748
+ }
1749
+ },
1750
+ graceMs: HOST_USER_SHELL_GRACE_MS,
1751
+ signal
1752
+ };
1753
+ request.beforeSpawn?.();
1754
+ signal.throwIfAborted();
1755
+ let handle;
1756
+ try {
1757
+ handle = subprocess.spawn(spec);
1758
+ } catch (error) {
1759
+ signal.throwIfAborted();
1760
+ if (confined !== void 0 && isRunnerSpawnFailure(error, confined.argv[0], cwd)) return failed("sandbox-runner", `the Host sandbox runner failed before the user command executed (${hostShellDiagnostic(error)})`);
1761
+ return refused(`the Host process could not start — nothing was executed (${hostShellDiagnostic(error)})`);
1762
+ }
1763
+ let outcome;
1764
+ try {
1765
+ outcome = await handle.done;
1766
+ if (!await handle.waitForExit()) throw new Error("the Host subprocess managed range did not become empty");
1767
+ } catch (error) {
1768
+ handle.terminate();
1769
+ let rangeEmpty = false;
1770
+ let observationError;
1771
+ try {
1772
+ rangeEmpty = await handle.waitForExit();
1773
+ } catch (retryError) {
1774
+ observationError = retryError;
1775
+ }
1776
+ if (!rangeEmpty) return failed("infrastructure", `${observationError === void 0 ? "the Host subprocess managed range was not confirmed empty" : `the Host subprocess managed range could not be observed (${hostShellDiagnostic(observationError)})`}; the process outcome is unknown and cleanup is not confirmed — do not treat this as a clean settlement (${hostShellDiagnostic(error)})`);
1777
+ if (outcome === void 0) {
1778
+ if (confined !== void 0 && isRunnerSpawnFailure(error, confined.argv[0], cwd)) return failed("sandbox-runner", `the Host sandbox runner failed before the user command executed (${hostShellDiagnostic(error)})`);
1779
+ if (signal.aborted) signal.throwIfAborted();
1780
+ return failed("infrastructure", `the Host process failed before reporting an outcome (${hostShellDiagnostic(error)})`);
1781
+ }
1782
+ }
1783
+ if (outcome === void 0) return failed("infrastructure", "the Host process did not report an outcome");
1784
+ let stdout;
1785
+ let stderr;
1786
+ try {
1787
+ stdout = collectedOutput(handle.collected.stdout);
1788
+ stderr = collectedOutput(handle.collected.stderr);
1789
+ } catch (error) {
1790
+ return failed("infrastructure", `the Host process output could not be read (${hostShellDiagnostic(error)})`);
1791
+ }
1792
+ if (confined !== void 0) {
1793
+ const runnerFailure = classifyRunnerFailure(outcome.exitCode, stderr.text, confined.runnerFailureRules);
1794
+ if (runnerFailure !== void 0) return failed("sandbox-runner", `the Host sandbox runner failed before the user command executed (${runnerFailure.detail})`);
1795
+ }
1796
+ const stderrTruncated = stderr.truncated;
1797
+ const exitNonzero = outcome.exitCode !== null && outcome.exitCode !== 0;
1798
+ const denied = confined !== void 0 && !(confined !== void 0 && exitNonzero && stderrTruncated) && matchesSignature(outcome.exitCode, stderr.text, confined.denialSignatures);
1799
+ const exit = outcome.exitCode !== null ? {
1800
+ kind: "exit",
1801
+ code: outcome.exitCode
1802
+ } : outcome.signal !== null ? {
1803
+ kind: "signal",
1804
+ signal: outcome.signal
1805
+ } : void 0;
1806
+ if (exit === void 0) return failed("infrastructure", "the Host process returned neither an exit code nor a terminating signal");
1807
+ if (exit.kind === "exit" && (exit.code < 0 || exit.code > 255)) return failed("infrastructure", `the Host process returned an unusable exit code ${String(exit.code)}`);
1808
+ const streams = boundedHostUserShellResultStreams(boundedHostUserShellOutput(stdout), boundedHostUserShellOutput(stderr));
1809
+ return {
1810
+ kind: "settled",
1811
+ result: {
1812
+ exit,
1813
+ stdout: streams.stdout,
1814
+ stderr: streams.stderr,
1815
+ sandboxDenied: denied,
1816
+ aborted: signal.aborted,
1817
+ timedOut: false
1818
+ }
1819
+ };
1820
+ }
1821
+ async function confineSandbox(rawArgv, request) {
1822
+ const { session, sandboxPolicy, sandbox, signal } = request;
1823
+ if (session === void 0) return refused("Host shell sandbox requires a live Session — nothing was executed");
1824
+ if (sandboxPolicy === void 0 || sandbox === void 0) return refused("Host shell sandbox policy is unavailable — nothing was executed");
1825
+ let resolved;
1826
+ let confined;
1827
+ try {
1828
+ resolved = await sandboxPolicy.resolve({ session });
1829
+ signal.throwIfAborted();
1830
+ if (resolved.mode === "danger-full-access") return refused("Host shell sandbox refuses danger-full-access — nothing was executed");
1831
+ confined = await sandbox.confine(rawArgv, resolved, signal);
1832
+ } catch (error) {
1833
+ signal.throwIfAborted();
1834
+ return refused(`Host shell sandbox could not establish confinement: ${hostShellDiagnostic(error)} — nothing was executed`);
1835
+ }
1836
+ if (confined.enforcement !== "full") return refused("Host shell sandbox enforcement is not full — nothing was executed");
1837
+ return confined;
1838
+ }
1839
+ //#endregion
1840
+ //#region src/app/agent/turn-policy.ts
1841
+ /** The Turn number of one boundary event (`turn/start`/`turn/end` data). */
1842
+ function turnNumberOf(event) {
1843
+ const data = event.data;
1844
+ if (typeof data !== "object" || data === null) return void 0;
1845
+ const turn = data.turn;
1846
+ return typeof turn === "number" ? turn : void 0;
1847
+ }
1848
+ /**
1849
+ * Install the per-Turn latch for ONE exact Session object on the Host's
1850
+ * synchronous `session/event` plane.
1851
+ *
1852
+ * Filtering is by the EXACT Session OBJECT (never a string id): a replaced
1853
+ * same-id Session can never move this Agent's frozen policy. The frozen
1854
+ * snapshot is cleared only by the `turn/end` of the SAME Turn number it was
1855
+ * frozen at — a late or foreign end boundary can never clear another Turn.
1856
+ * The listener is registered on the Agent's own scope by the caller, so it
1857
+ * unwinds with the Agent.
1858
+ *
1859
+ * @param source - the Host event plane (`ctx.on('session/event', ...)`).
1860
+ * @param session - the exact Session object this Agent drives (`agent.session`).
1861
+ * @param sample - the current-viewer sampler (called once per Turn).
1862
+ * @returns the latch; `currentTurn()` is `undefined` between Turns.
1863
+ */
1864
+ function installTuiPromptTurnLatch(source, session, sample) {
1865
+ let frozen;
1866
+ let frozenTurn;
1867
+ let disposed = false;
1868
+ const disposeListener = source.on("session/event", (eventSession, event) => {
1869
+ if (eventSession !== session) return;
1870
+ if (event.type === "turn/start") {
1871
+ frozen = sample();
1872
+ frozenTurn = turnNumberOf(event);
1873
+ return;
1874
+ }
1875
+ if (event.type === "turn/end" && frozenTurn !== void 0 && turnNumberOf(event) === frozenTurn) {
1876
+ frozen = void 0;
1877
+ frozenTurn = void 0;
1878
+ }
1879
+ }, { global: true });
1880
+ return {
1881
+ sessionId: session.id,
1882
+ currentTurn: () => frozen,
1883
+ snapshot: () => frozen,
1884
+ dispose: () => {
1885
+ if (disposed) return;
1886
+ disposed = true;
1887
+ frozen = void 0;
1888
+ frozenTurn = void 0;
1889
+ disposeListener();
1890
+ }
1891
+ };
1892
+ }
1893
+ //#endregion
1894
+ //#region src/domain/terminal-progress/interval.ts
1895
+ /**
1896
+ * Classify one official `turn/end.reason.kind` (plan §5.2). `completed` is the
1897
+ * DSH turn result (not a claim about every business step); `error` and
1898
+ * `max-tokens` (a resource ceiling, not success) are `error`; a cancelled /
1899
+ * blocked / non-live closer is honestly `idle`. An UNKNOWN upstream kind is
1900
+ * NOT guessed — the caller records it and the interval stays `idle`.
1901
+ *
1902
+ * @param kind - the durable `turn/end` reason kind.
1903
+ * @returns the proven outcome, or `undefined` for an unknown kind.
1904
+ */
1905
+ function classifyTerminalTurnEnd(kind) {
1906
+ switch (kind) {
1907
+ case "completed": return "done";
1908
+ case "error": return "error";
1909
+ case "max-tokens": return "error";
1910
+ case "aborted":
1911
+ case "blocked":
1912
+ case "interrupted":
1913
+ case "forked": return "idle";
1914
+ default: return;
1915
+ }
1916
+ }
1917
+ /**
1918
+ * Create one independent fold instance.
1919
+ * @param onUnknownReason - reports an unknown `turn/end.reason.kind` (the
1920
+ * Host/Direct owner injects its diagnostics channel here); the interval stays
1921
+ * `idle` instead of guessing.
1922
+ */
1923
+ function createTerminalProgressInterval(onUnknownReason) {
1924
+ let active = false;
1925
+ /** The turn opened by the newest live `turn/start` of THIS interval. */
1926
+ let openTurn;
1927
+ /** The classified outcome of the newest turn whose `turn/end` matched the
1928
+ * open turn — reset whenever a newer turn opens. */
1929
+ let lastClosed;
1930
+ /** The currently committed outcome of the interval (`idle` while running
1931
+ * without a proven result). */
1932
+ let outcome = "idle";
1933
+ const state = () => ({
1934
+ active,
1935
+ outcome
1936
+ });
1937
+ return {
1938
+ status(running) {
1939
+ if (running) {
1940
+ if (active) return void 0;
1941
+ active = true;
1942
+ openTurn = void 0;
1943
+ lastClosed = void 0;
1944
+ outcome = "idle";
1945
+ return state();
1946
+ }
1947
+ if (!active) return void 0;
1948
+ outcome = openTurn === void 0 ? lastClosed ?? "idle" : "idle";
1949
+ active = false;
1950
+ openTurn = void 0;
1951
+ lastClosed = void 0;
1952
+ return state();
1953
+ },
1954
+ turnStart(turn) {
1955
+ if (!active) return;
1956
+ openTurn = turn;
1957
+ lastClosed = void 0;
1958
+ },
1959
+ turnEnd(turn, reasonKind) {
1960
+ if (!active) return;
1961
+ if (openTurn !== turn) return;
1962
+ openTurn = void 0;
1963
+ const classified = classifyTerminalTurnEnd(reasonKind);
1964
+ if (classified === void 0) {
1965
+ onUnknownReason?.(reasonKind);
1966
+ lastClosed = "idle";
1967
+ return;
1968
+ }
1969
+ lastClosed = classified;
1970
+ },
1971
+ retire() {
1972
+ openTurn = void 0;
1973
+ lastClosed = void 0;
1974
+ if (!active && outcome === "idle") return void 0;
1975
+ active = false;
1976
+ return state();
1977
+ },
1978
+ apply(fact) {
1979
+ active = fact.active;
1980
+ outcome = fact.outcome;
1981
+ openTurn = void 0;
1982
+ lastClosed = void 0;
1983
+ return state();
1984
+ },
1985
+ reset() {
1986
+ active = false;
1987
+ openTurn = void 0;
1988
+ lastClosed = void 0;
1989
+ outcome = "idle";
1990
+ return state();
1991
+ },
1992
+ snapshot() {
1993
+ return state();
1994
+ }
1995
+ };
1996
+ }
1997
+ //#endregion
1998
+ //#region src/runtime/remote/pi-tui-terminal-progress-contract.ts
1999
+ /** The wire namespace (and Host Cordis service key) of the private stream. */
2000
+ const PI_TUI_TERMINAL_PROGRESS_NAMESPACE = "piTuiTerminalProgress";
2001
+ /** The private method's stable endpoint identity. */
2002
+ const PI_TUI_TERMINAL_PROGRESS_WATCH_ENDPOINT = "@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch";
2003
+ /** One strict JSON codec that validates a wire string. */
2004
+ function stringCodec(typeSymbol) {
2005
+ return {
2006
+ mode: "strict",
2007
+ typeSymbol,
2008
+ create: () => ({ parse: (value) => {
2009
+ if (typeof value !== "string") throw new TypeError(`${typeSymbol}: the wire value must be a string`);
2010
+ return value;
2011
+ } })
2012
+ };
2013
+ }
2014
+ /**
2015
+ * Validate and detach one `PiTuiTerminalProgressFrame`. This is the ONE
2016
+ * structural validator of the frame shape: the descriptor's `result` codec
2017
+ * uses it, and the R2 Client source must call it on every downlink item because
2018
+ * the framework does not (see the module JSDoc).
2019
+ */
2020
+ function parsePiTuiTerminalProgressFrame(value) {
2021
+ if (typeof value !== "object" || value === null) throw new TypeError("piTuiTerminalProgress/watch: the frame must be an object");
2022
+ const frame = value;
2023
+ if (frame.kind !== "snapshot" && frame.kind !== "update") throw new TypeError("piTuiTerminalProgress/watch: the frame kind must be snapshot or update");
2024
+ if (typeof frame.sessionId !== "string") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a string sessionId");
2025
+ if (typeof frame.hostEpoch !== "string") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a string hostEpoch");
2026
+ if (typeof frame.agentEpoch !== "number") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a numeric agentEpoch");
2027
+ if (typeof frame.revision !== "number") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a numeric revision");
2028
+ if (typeof frame.running !== "boolean") throw new TypeError("piTuiTerminalProgress/watch: the frame needs a boolean running");
2029
+ if (frame.outcome !== "idle" && frame.outcome !== "done" && frame.outcome !== "error") throw new TypeError("piTuiTerminalProgress/watch: the frame outcome must be idle, done or error");
2030
+ return {
2031
+ kind: frame.kind,
2032
+ sessionId: frame.sessionId,
2033
+ hostEpoch: frame.hostEpoch,
2034
+ agentEpoch: frame.agentEpoch,
2035
+ revision: frame.revision,
2036
+ running: frame.running,
2037
+ outcome: frame.outcome
2038
+ };
2039
+ }
2040
+ const PI_TUI_TERMINAL_PROGRESS_FRAME_CODEC = {
2041
+ mode: "strict",
2042
+ typeSymbol: "@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch:frame",
2043
+ create: () => ({ parse: parsePiTuiTerminalProgressFrame }),
2044
+ decode: parsePiTuiTerminalProgressFrame
2045
+ };
2046
+ /**
2047
+ * The ONE shared invocation descriptor both contributions derive from. The
2048
+ * Host registers this exact object; the Client mounts this exact object.
2049
+ */
2050
+ const PI_TUI_TERMINAL_PROGRESS_WATCH = {
2051
+ id: PI_TUI_TERMINAL_PROGRESS_WATCH_ENDPOINT,
2052
+ service: PI_TUI_TERMINAL_PROGRESS_NAMESPACE,
2053
+ namespace: PI_TUI_TERMINAL_PROGRESS_NAMESPACE,
2054
+ method: "watch",
2055
+ mode: "stream",
2056
+ invocation: { kind: "direct" },
2057
+ parameters: [{
2058
+ name: "sessionId",
2059
+ wire: "sessionId",
2060
+ source: "json",
2061
+ codec: stringCodec("@xmoon76/dsh-pi-tui#piTuiTerminalProgress/watch:sessionId")
2062
+ }],
2063
+ cancellation: { parameter: "signal" },
2064
+ result: PI_TUI_TERMINAL_PROGRESS_FRAME_CODEC
2065
+ };
2066
+ //#endregion
2067
+ //#region src/domain/communication/focus.ts
2068
+ /**
2069
+ * Focus Mode's model-facing behavioral policy (TS8-F3).
2070
+ *
2071
+ * Focus Mode is a presentation + behavioral-policy feature: the session log
2072
+ * stays lossless and the TUI only PROJECTS turn-intermediate activity into a
2073
+ * live Thought block. The neutral domain owns the section identity and the
2074
+ * pure prompt text; the projection itself lives in
2075
+ * `tui/transcript/focus-projection.ts`, the TUI surface in `tui-app.ts`, and
2076
+ * the section registration in `app/direct/system-prompt.ts`.
2077
+ *
2078
+ * The registering owner reads the shared state on EVERY assembly, so toggling
2079
+ * Focus never re-composes the agent nor re-registers the section — the next
2080
+ * model step simply sees the new value.
2081
+ * @module @xmoon76/dsh-pi-tui/domain/communication/focus
2082
+ */
2083
+ /** The system-prompt section name: TUI-private, never a host/preset name. */
2084
+ const FOCUS_SECTION_NAME = "tui:focus-mode";
2085
+ /**
2086
+ * The model-facing Focus instruction (plan §4): the user only sees the final
2087
+ * text message of each response, so mid-turn narration is wasted and
2088
+ * everything the user needs must land in the final message. Questions and
2089
+ * background work are explicit exceptions to the old hidden-context assumption:
2090
+ * both need truthful, self-contained visible communication.
2091
+ */
2092
+ const FOCUS_MODE_PROMPT = `# Focus mode
2093
+ The user has focus mode enabled. They only see your final text message in each response — not tool calls, tool results, or any text you write between tool calls. Intermediate assistant text is not visible. Progress-only intermediate assistant messages cannot reach the user on this surface, so continue working instead of generating them. Put the information the user needs into the final visible message: the outcome, important findings, changes made, relevant decisions, and anything still pending. Summarize hidden work rather than replaying the full hidden process. Do not assume they saw earlier output.
2094
+
2095
+ When you need user input, approval, or a decision, assume the user did not see hidden reasoning, tool calls, tool results, or mid-turn narration. Make the question self-contained: state what input or decision is needed and include the minimum context required to answer it. Do not refer to hidden context with phrases such as "as above", "the issue I mentioned", "that plan", or "the previous result", and do not dump the full hidden process merely to reconstruct context.
2096
+
2097
+ Continue useful work while independent background work runs, and wait in the foreground only when the immediate next action depends on that result. Do not claim the user's requested work is fully complete while a required background result is unresolved. If the turn ends first, make the visible final text a checkpoint that states what remains pending and what has already been established; do not pretend the whole request is complete or promise that a later wake is guaranteed.`;
2098
+ /**
2099
+ * The effective Focus section text for the live display state: the instruction
2100
+ * only while the Focus preset is active, else empty. The section is stable
2101
+ * behavioral policy — never `complete`, never dynamic context.
2102
+ */
2103
+ function focusPromptText(displayState) {
2104
+ return isFocusDisplayPreset(displayState.preset) ? FOCUS_MODE_PROMPT : "";
2105
+ }
2106
+ //#endregion
2107
+ //#region src/app/agent/prompt-sections.ts
2108
+ /**
2109
+ * The shared per-Agent TUI system-prompt section installer (M6 PR-C C2).
2110
+ *
2111
+ * Direct and Split Host both install the FOUR TUI-owned communication
2112
+ * sections through this one neutral `app/` implementation, so the assembled
2113
+ * model-facing text can never diverge between the backends. The pure text and
2114
+ * policy derivation stays in `domain/communication/**`; this module owns only
2115
+ * the per-Turn eligibility/focus evaluation and the section registration.
2116
+ *
2117
+ * Per-Turn policy (the accepted Owner Focus ruling):
2118
+ *
2119
+ * ```text
2120
+ * turn/start -> snapshotVoters(agent.session) => { eligible, focus } FROZEN
2121
+ * for exactly this Turn (the three preference axes stay LIVE
2122
+ * provider reads at each assembly)
2123
+ * turn/end -> the latch clears
2124
+ * eligible -> all four section texts participate (progress empty under focus)
2125
+ * !eligible -> NONE of the four section texts participates (empty text)
2126
+ * ```
2127
+ *
2128
+ * The registrations may exist per Agent while their text is empty on
2129
+ * non-TUI turns: section presence is not a claim of rendered text. The
2130
+ * `{{provider}}`/`{{model}}` variables stay owned by the official
2131
+ * `dsh-system-prompt` seam; this module never interpolates.
2132
+ *
2133
+ * `src/app/direct/system-prompt.ts` is the compatibility adapter for the
2134
+ * public `composeAgent` helper and the existing tests; the Host installer is
2135
+ * `src/app/host/features/agent-prompt.ts`. Neither may duplicate the section
2136
+ * names, orders or texts owned here.
2137
+ *
2138
+ * @module @xmoon76/dsh-pi-tui/app/agent/prompt-sections
2139
+ */
2140
+ /**
2141
+ * The always-eligible live-display policy used by the public `composeAgent`
2142
+ * compatibility adapter and the existing section tests: the display state IS
2143
+ * the frozen snapshot, evaluated live (the pre-C2 semantics).
2144
+ */
2145
+ function liveDisplayTurnPolicy(displayState) {
2146
+ return { currentTurn: () => ({
2147
+ eligible: true,
2148
+ focus: displayState.preset === "focus"
2149
+ }) };
2150
+ }
2151
+ /** The ephemeral display input one frozen Turn focus implies. */
2152
+ function turnDisplay(turn) {
2153
+ return { preset: turn.focus ? "focus" : "full" };
2154
+ }
2155
+ /** The effective progress text of one Turn (empty when not eligible). */
2156
+ function turnProgressText(turn, state) {
2157
+ if (turn === void 0 || !turn.eligible) return "";
2158
+ return progressUpdatesPromptText(turnDisplay(turn), state);
2159
+ }
2160
+ /** The effective response-style text of one Turn (empty when not eligible). */
2161
+ function turnResponseStyleText(turn, state) {
2162
+ if (turn === void 0 || !turn.eligible) return "";
2163
+ return responseStylePromptText(state);
2164
+ }
2165
+ /** The effective git-attribution text of one Turn (empty when not eligible). */
2166
+ function turnGitAttributionText(turn, state) {
2167
+ if (turn === void 0 || !turn.eligible) return "";
2168
+ return gitAttributionPromptText(state);
2169
+ }
2170
+ /** The effective Focus text of one Turn (empty when not eligible). */
2171
+ function turnFocusText(turn) {
2172
+ if (turn === void 0 || !turn.eligible) return "";
2173
+ return focusPromptText(turnDisplay(turn));
2174
+ }
2175
+ /**
2176
+ * Register the progress-updates section under one Turn policy. The state is a
2177
+ * PROVIDER read at every assembly: a preference change is seen by the next
2178
+ * model step without re-composition (the Host reads the canonical refs per
2179
+ * call; Direct passes its live holder).
2180
+ */
2181
+ function installProgressUpdatesSection(systemPrompt, turn, state) {
2182
+ return systemPrompt.section({
2183
+ name: PROGRESS_UPDATES_SECTION_NAME,
2184
+ order: 80,
2185
+ text: () => turnProgressText(turn.currentTurn(), state())
2186
+ });
2187
+ }
2188
+ /** Register the response-style section; each assembly reads the live state. */
2189
+ function installResponseStyleSection(systemPrompt, turn, state) {
2190
+ return systemPrompt.section({
2191
+ name: RESPONSE_STYLE_SECTION_NAME,
2192
+ order: 81,
2193
+ text: () => turnResponseStyleText(turn.currentTurn(), state())
2194
+ });
2195
+ }
2196
+ /** Register the git-attribution section; each assembly reads the live state. */
2197
+ function installGitAttributionSection(systemPrompt, turn, state) {
2198
+ return systemPrompt.section({
2199
+ name: GIT_ATTRIBUTION_SECTION_NAME,
2200
+ order: 82,
2201
+ text: () => turnGitAttributionText(turn.currentTurn(), state())
2202
+ });
2203
+ }
2204
+ /**
2205
+ * Register the Focus behavioral section under one Turn policy. It is
2206
+ * deliberately NOT `complete` (it must never replace the harness
2207
+ * identity/persona/tool guidance) and NOT dynamic context.
2208
+ */
2209
+ function installFocusSection(systemPrompt, turn) {
2210
+ return systemPrompt.section({
2211
+ name: FOCUS_SECTION_NAME,
2212
+ order: 90,
2213
+ text: () => turnFocusText(turn.currentTurn())
2214
+ });
2215
+ }
2216
+ /**
2217
+ * Register the four TUI-owned sections on one Agent's scoped prompt registry.
2218
+ * Names and orders are fixed (progress 80 / response 81 / git 82 / Focus 90);
2219
+ * every text provider reads the LIVE preference state AND the frozen Turn
2220
+ * snapshot at each assembly. The disposer list is registration order.
2221
+ */
2222
+ function installTuiPromptSections(input) {
2223
+ const { systemPrompt, turn, live } = input;
2224
+ return [
2225
+ installProgressUpdatesSection(systemPrompt, turn, live.progressUpdates),
2226
+ installResponseStyleSection(systemPrompt, turn, live.responseStyle),
2227
+ installGitAttributionSection(systemPrompt, turn, live.gitAttribution),
2228
+ installFocusSection(systemPrompt, turn)
2229
+ ];
2230
+ }
2231
+ //#endregion
2232
+ export { isFocusDisplayPreset as $, discoverForQuery as A, projectedWorkingDirectory as B, HostUserShellSandboxRunnerError as C, MAX_HOST_USER_SHELL_STREAM_BYTES as D, MAX_HOST_USER_SHELL_SPILL_PATH_BYTES as E, resolvePathQuery as F, runDetached as G, cancellationError as H, separatorOfRaw as I, safeErrorString as J, runOwned as K, CANONICAL_TUI_SETTINGS_NS as L, createBoundedFinderCandidateCollector as M, rankPathCandidates as N, parseGitAttributionMode as O, reattachDisplayBase as P, isDisplayPresetAvailable as Q, serializeTuiSettingsMutation as R, HostUserShellOutcomeUnknownError as S, MAX_HOST_USER_SHELL_RESULT_BYTES as T, isCancellation as U, isUserInvocableSkill as V, observeSettled as W, parseResponseStyle as X, parseProgressUpdates as Y, isDisplayPreset as Z, listPiTuiHostFileReferences as _, installTuiPromptSections as a, hostPathQueryEnvironment as b, PI_TUI_TERMINAL_PROGRESS_WATCH as c, HOST_USER_SHELL_GRACE_MS as d, resolveDisplayPreset as et, HostShellExecutionVeto as f, listPiTuiExplicitHostFileReferences as g, isExplicitHostFileQuery as h, installResponseStyleSection as i, escapeFinderRegex as j, createFinderRecordStream as k, createTerminalProgressInterval as l, hostShellDiagnostic as m, installGitAttributionSection as n, liveDisplayTurnPolicy as o, executeHostShellOnce as p, safeErrorMessage as q, installProgressUpdatesSection as r, PI_TUI_TERMINAL_PROGRESS_NAMESPACE as s, installFocusSection as t, installTuiPromptTurnLatch as u, OfficialWorkspaceSearchPool as v, MAX_HOST_USER_SHELL_MESSAGE_BYTES as w, resolveFdPath as x, DirectHostDiscoveryDriver as y, effectiveAgentCwd as z };