@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,634 @@
1
+ import { r as isFocusDisplayPreset } from "./preset-BcWqOtY7.mjs";
2
+ import { d as boundedHostUserShellResultStreams, l as MAX_HOST_USER_SHELL_STREAM_BYTES, o as MAX_HOST_USER_SHELL_MESSAGE_BYTES, u as boundedHostUserShellOutput } from "./pi-tui-terminal-progress-contract-B3RoEzjK.mjs";
3
+ import { isUserInvocable } from "@deepseek-ai/dsh-skill";
4
+ 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";
5
+ import { classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature } from "@deepseek-ai/dsh-sandbox";
6
+ //#region src/domain/catalog/skill.ts
7
+ /**
8
+ * Neutral skill catalog vocabulary (TS8-E): the human-facing skill summary
9
+ * shape, the detached catalog (with its completeness flag) and the official
10
+ * user-invocation policy guard.
11
+ *
12
+ * This module is the transport/UI-neutral semantic owner: it consumes only the
13
+ * official `@deepseek-ai/dsh-skill` policy helper. It never resolves ctx
14
+ * services, acquires standing scopes, holds revision leases, reads a live
15
+ * Agent, or imports a Direct/Remote adapter — the structural Direct Host read
16
+ * lives in `runtime/direct/skill-catalog.ts`.
17
+ * @module @xmoon76/dsh-pi-tui/domain/catalog/skill
18
+ */
19
+ /**
20
+ * Whether one summary passes the OFFICIAL user-invocation policy — the
21
+ * neutral guard used by every human entry point (direct wrappers, `/skill`,
22
+ * the picker, and final body loads). A malformed `invocation` (missing,
23
+ * non-object, non-boolean flag) is treated as NOT user-invocable: the policy
24
+ * defaults are never reinterpreted, and a hostile entry can neither throw nor
25
+ * sneak into a human surface.
26
+ */
27
+ function isUserInvocableSkill(skill) {
28
+ const invocation = skill.invocation;
29
+ if (typeof invocation !== "object" || invocation === null) return false;
30
+ if (typeof invocation.userInvocable !== "boolean") return false;
31
+ return isUserInvocable(skill);
32
+ }
33
+ //#endregion
34
+ //#region src/domain/communication/policy.ts
35
+ /**
36
+ * Model-facing communication policy, independent of transcript presentation.
37
+ *
38
+ * Two independent axes (the PR #166 follow-up split):
39
+ * - `ProgressUpdates` owns the user-facing mid-turn update cadence;
40
+ * - `ResponseStyle` owns the density / explanation depth of visible text.
41
+ *
42
+ * Neither axis is a display preset: `DisplayState` owns what the surface can
43
+ * make visible, and the Focus preset suppresses the effective progress
44
+ * section through the live display state without mutating the saved
45
+ * preference. Registration of the sections belongs to the Direct
46
+ * system-prompt owner (`app/direct/system-prompt.ts`); this module owns the
47
+ * pure text/policy derivation.
48
+ * @module @xmoon76/dsh-pi-tui/domain/communication/policy
49
+ */
50
+ const DEFAULT_PROGRESS_UPDATES = "milestones";
51
+ const DEFAULT_RESPONSE_STYLE = "default";
52
+ /** The system-prompt section names: TUI-private, never host/preset names. */
53
+ const PROGRESS_UPDATES_SECTION_NAME = "tui:progress-updates";
54
+ const RESPONSE_STYLE_SECTION_NAME = "tui:response-style";
55
+ /** Settings documents are untrusted; missing or invalid values use Milestones. */
56
+ function parseProgressUpdates(value) {
57
+ switch (value) {
58
+ case "off":
59
+ case "milestones":
60
+ case "frequent": return value;
61
+ default: return DEFAULT_PROGRESS_UPDATES;
62
+ }
63
+ }
64
+ /** Settings documents are untrusted; missing or invalid values use Default. */
65
+ function parseResponseStyle(value) {
66
+ switch (value) {
67
+ case "default":
68
+ case "concise":
69
+ case "explanatory": return value;
70
+ default: return DEFAULT_RESPONSE_STYLE;
71
+ }
72
+ }
73
+ const progressPrompts = {
74
+ milestones: `# Progress updates: Milestones
75
+
76
+ 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.
77
+
78
+ 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.
79
+
80
+ Do not narrate individual tool calls, file reads, commands, or edits, and do not add a mandatory preamble before the first tool call.`,
81
+ frequent: `# Progress updates: Frequent
82
+
83
+ 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.
84
+
85
+ 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.`,
86
+ off: `# Progress updates: Off
87
+
88
+ 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.
89
+
90
+ Do not add a preamble merely to announce upcoming tool use, and do not narrate individual tool calls, file reads, commands, or edits.`
91
+ };
92
+ const responsePrompts = {
93
+ default: "",
94
+ concise: `# Response style: Concise
95
+
96
+ Keep user-visible responses compact and result-first. Avoid unnecessary preambles, restating the request, repeated conclusions, and nonessential explanation.
97
+
98
+ Preserve information needed for correctness, decisions, blockers, and user action. Give fuller detail when the user explicitly asks for it.`,
99
+ explanatory: `# Response style: Explanatory
100
+
101
+ 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.
102
+
103
+ 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.`
104
+ };
105
+ /** The Focus surface owns what can reach the user, so the progress section
106
+ * reads BOTH live states: on Focus the effective progress text is empty
107
+ * regardless of the saved cadence (which is never mutated). */
108
+ function progressUpdatesPromptText(displayState, state) {
109
+ return isFocusDisplayPreset(displayState.preset) ? "" : progressPrompts[state.mode];
110
+ }
111
+ /** The effective response-style section text for the live state. */
112
+ function responseStylePromptText(state) {
113
+ return responsePrompts[state.style];
114
+ }
115
+ /** The system-prompt section name: TUI-private, never a host/preset name. */
116
+ const GIT_ATTRIBUTION_SECTION_NAME = "tui:git-attribution";
117
+ /** The official product identity (a product constant, never configurable). */
118
+ const PRODUCT_NAME = "@xmoon76/dsh-pi-tui";
119
+ const PRODUCT_EMAIL = "dsh-pi-tui@xmoon.org";
120
+ /** Settings values are untrusted; missing or invalid values stay Off. */
121
+ function parseGitAttributionMode(value) {
122
+ switch (value) {
123
+ case "off":
124
+ case "product":
125
+ case "product-model": return value;
126
+ default: return "off";
127
+ }
128
+ }
129
+ const attributionPrompts = {
130
+ off: "",
131
+ product: `# Git attribution
132
+
133
+ When you create a Git commit for work performed through dsh-pi-tui, include the following Git trailer exactly once:
134
+
135
+ Co-Authored-By: ${PRODUCT_NAME} <${PRODUCT_EMAIL}>
136
+
137
+ Preserve existing commit trailers. When amending a commit that already contains this exact trailer, do not add a duplicate.`,
138
+ "product-model": `# Git attribution
139
+
140
+ When you create a Git commit for work performed through dsh-pi-tui, include the following Git trailers exactly once:
141
+
142
+ Co-Authored-By: ${PRODUCT_NAME} <${PRODUCT_EMAIL}>
143
+ Assisted-By: {{provider}}/{{model}}
144
+
145
+ Preserve existing commit trailers. When amending a commit that already contains either exact trailer, do not add a duplicate.`
146
+ };
147
+ /** The effective attribution section text for the live mode. */
148
+ function gitAttributionPromptText(state) {
149
+ return attributionPrompts[state.mode];
150
+ }
151
+ //#endregion
152
+ //#region src/runtime/direct/file-completion/official-workspace-search.ts
153
+ /**
154
+ * The OFFICIAL Host Workspace file search the sessionless `@file` surface uses
155
+ * (M6-1/F5-B): a thin wrapper around the published
156
+ * `@deepseek-ai/dsh-file-reference-local/search` primitive. It performs no
157
+ * matching, ranking, traversal, path normalization or exclusion policy of its
158
+ * own — the official `WorkspaceFileSearch` owns all of that, with the SAME
159
+ * published defaults the official Host provider runs with:
160
+ *
161
+ * ```text
162
+ * maxResults DEFAULT_FILE_SEARCH_MAX_RESULTS (20)
163
+ * maxEntries DEFAULT_FILE_SEARCH_MAX_ENTRIES (50_000)
164
+ * excludedDirectories DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES
165
+ * ```
166
+ *
167
+ * The Direct in-process adapter and the Remote Host bridge both use this ONE
168
+ * helper, so the two backends share the same discovery semantics. It is NOT
169
+ * the retired Direct `fd`/`fdfind` scanner: no finder process, no custom
170
+ * ranking, no broadened path syntax.
171
+ *
172
+ * CACHE BUDGET (plan §4.4): at most FOUR resident official indexes, evicted
173
+ * least-recently-read while idle. When all four are in use, the fifth query
174
+ * runs one temporary official search and disposes it in its own `finally` —
175
+ * a live index is never interrupted and the map never grows past the budget.
176
+ * Every entry is released on {@link OfficialWorkspaceSearchPool.dispose}.
177
+ *
178
+ * @module @xmoon76/dsh-pi-tui/runtime/direct/file-completion/official-workspace-search
179
+ */
180
+ /** The fixed search configuration (the published official defaults). */
181
+ const OFFICIAL_FILE_SEARCH_CONFIG = {
182
+ maxResults: DEFAULT_FILE_SEARCH_MAX_RESULTS,
183
+ maxEntries: DEFAULT_FILE_SEARCH_MAX_ENTRIES,
184
+ excludedDirectories: DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES
185
+ };
186
+ /** The resident-index budget the plan fixes. */
187
+ const MAX_RESIDENT_INDEXES = 4;
188
+ function mapCandidates(candidates) {
189
+ return candidates.map((candidate) => ({
190
+ path: candidate.path,
191
+ kind: candidate.kind
192
+ }));
193
+ }
194
+ /**
195
+ * The bounded official-search cache shared by the Direct adapter and the
196
+ * Remote Host bridge. One instance per owning Host row (or Direct runner);
197
+ * {@link dispose} releases every resident official index.
198
+ */
199
+ var OfficialWorkspaceSearchPool = class {
200
+ entries = /* @__PURE__ */ new Map();
201
+ disposed = false;
202
+ /**
203
+ * Run ONE official workspace query against the registry-resolved root.
204
+ * `signal` cancels only this caller's wait, exactly like the official
205
+ * primitive. A disposed pool fails fast: no search is started for a row that
206
+ * is already gone.
207
+ */
208
+ async list(root, query, signal) {
209
+ if (this.disposed) throw new Error("the official workspace search pool is disposed");
210
+ signal.throwIfAborted();
211
+ const key = root.workspaceId;
212
+ let resident = this.entries.get(key);
213
+ if (resident !== void 0 && resident.canonicalPath !== root.path) {
214
+ resident.search.dispose();
215
+ this.entries.delete(key);
216
+ resident = void 0;
217
+ }
218
+ if (resident === void 0) {
219
+ if (!this.hasIdleSlot()) {
220
+ const temporary = new WorkspaceFileSearch(root.path, OFFICIAL_FILE_SEARCH_CONFIG);
221
+ try {
222
+ const candidates = await temporary.list(query, signal);
223
+ signal.throwIfAborted();
224
+ return mapCandidates(candidates);
225
+ } finally {
226
+ temporary.dispose();
227
+ }
228
+ }
229
+ resident = {
230
+ canonicalPath: root.path,
231
+ search: new WorkspaceFileSearch(root.path, OFFICIAL_FILE_SEARCH_CONFIG),
232
+ active: 0
233
+ };
234
+ this.entries.set(key, resident);
235
+ this.evictBeyondBudget();
236
+ } else {
237
+ this.entries.delete(key);
238
+ this.entries.set(key, resident);
239
+ }
240
+ resident.active += 1;
241
+ try {
242
+ const candidates = await resident.search.list(query, signal);
243
+ signal.throwIfAborted();
244
+ return mapCandidates(candidates);
245
+ } finally {
246
+ resident.active -= 1;
247
+ }
248
+ }
249
+ /**
250
+ * Mark every resident official index stale (the Host `tool/result`
251
+ * invalidation hook). The official primitive keeps answering from its stale
252
+ * entries while the rebuild happens behind the caret — that advisory
253
+ * freshness policy stays with the primitive.
254
+ */
255
+ invalidateAll() {
256
+ for (const resident of this.entries.values()) resident.search.invalidate();
257
+ }
258
+ /** Abort traversal, release every resident index (service/Host disposal). */
259
+ dispose() {
260
+ if (this.disposed) return;
261
+ this.disposed = true;
262
+ for (const resident of this.entries.values()) resident.search.dispose();
263
+ this.entries.clear();
264
+ }
265
+ /** The number of resident indexes (cache-budget probes). */
266
+ get residentIndexes() {
267
+ return this.entries.size;
268
+ }
269
+ hasIdleSlot() {
270
+ if (this.entries.size < MAX_RESIDENT_INDEXES) return true;
271
+ for (const resident of this.entries.values()) if (resident.active === 0) return true;
272
+ return false;
273
+ }
274
+ evictBeyondBudget() {
275
+ while (this.entries.size > MAX_RESIDENT_INDEXES) {
276
+ let victimKey;
277
+ for (const [key, resident] of this.entries) if (resident.active === 0) {
278
+ victimKey = key;
279
+ break;
280
+ }
281
+ if (victimKey === void 0) return;
282
+ const victim = this.entries.get(victimKey);
283
+ this.entries.delete(victimKey);
284
+ victim?.search.dispose();
285
+ }
286
+ }
287
+ };
288
+ //#endregion
289
+ //#region src/runtime/host-user-shell-execution.ts
290
+ /**
291
+ * The one Host user-shell execution core shared by the Direct adapter and the
292
+ * authenticated split-Host service.
293
+ *
294
+ * Both policies run the raw command through the official subprocess seam as
295
+ * `['bash', '-c', command]` (no wrapper, relay or shell-flag translation):
296
+ * - `bypass` spawns that argv directly;
297
+ * - `sandbox` resolves the EXACT Session policy and calls the installed
298
+ * official `ctx.sandbox.confine` exactly once, requires `enforcement:
299
+ * 'full'`, and spawns the EXACT argv returned by that one call.
300
+ *
301
+ * Output is bounded by the subprocess collect/spill dispositions and read only
302
+ * after `done` AND `waitForExit` proved the managed range empty. Cancellation
303
+ * is the caller's signal: the provider terminates the range, and this module
304
+ * joins it before returning. No long-lived stream, acknowledgement window or
305
+ * second process owner exists here.
306
+ * @module @xmoon76/dsh-pi-tui/runtime/host-user-shell-execution
307
+ */
308
+ const HOST_USER_SHELL_SPILL_MAX_BYTES = 67108864;
309
+ const HOST_USER_SHELL_GRACE_MS = 5e3;
310
+ /** A final pre-spawn veto: throwing it prevents the spawn and is mapped by the
311
+ * caller into its own truthful refusal. */
312
+ var HostShellExecutionVeto = class extends Error {
313
+ reason;
314
+ constructor(reason, message) {
315
+ super(message);
316
+ this.name = "HostShellExecutionVeto";
317
+ this.reason = reason;
318
+ }
319
+ };
320
+ /** Bound a Host diagnostic so a wire message bound can never be exceeded. */
321
+ function boundedHostShellMessage(text) {
322
+ const bytes = Buffer.from(text, "utf8");
323
+ if (bytes.length <= 2048) return text;
324
+ let end = MAX_HOST_USER_SHELL_MESSAGE_BYTES - 3;
325
+ while (end > 0 && (bytes[end] & 192) === 128) end -= 1;
326
+ return `${bytes.subarray(0, end).toString("utf8")}…`;
327
+ }
328
+ function hostShellDiagnostic(error) {
329
+ return boundedHostShellMessage(error instanceof Error ? error.message : String(error));
330
+ }
331
+ function refused(message) {
332
+ return {
333
+ kind: "refused",
334
+ reason: "policy-unavailable",
335
+ message: boundedHostShellMessage(message)
336
+ };
337
+ }
338
+ function failed(phase, message) {
339
+ return {
340
+ kind: "failed",
341
+ phase,
342
+ message: boundedHostShellMessage(message)
343
+ };
344
+ }
345
+ function collectedOutput(reader) {
346
+ if (reader === void 0) throw new Error("the Host subprocess did not expose the requested collected stream");
347
+ const read = reader.readFrom(0);
348
+ const spillPath = read.spillPath;
349
+ if (spillPath !== void 0 && Buffer.byteLength(spillPath, "utf8") > 4096) return {
350
+ text: read.text,
351
+ truncated: read.lossy
352
+ };
353
+ return {
354
+ text: read.text,
355
+ truncated: read.lossy,
356
+ ...spillPath === void 0 ? {} : { spillPath }
357
+ };
358
+ }
359
+ /**
360
+ * Execute one user-shell command to settlement through the official
361
+ * subprocess seam. Never throws for a command-level failure; a thrown
362
+ * {@link HostShellExecutionVeto} from `beforeSpawn` propagates without a spawn.
363
+ * @param request - command, exact Host scope and the resolved official services.
364
+ * @returns the bounded semantic result or a truthful refusal/failure.
365
+ */
366
+ async function executeHostShellOnce(request) {
367
+ const { command, cwd, policy, signal, subprocess } = request;
368
+ const rawArgv = [
369
+ "bash",
370
+ "-c",
371
+ command
372
+ ];
373
+ let confined;
374
+ if (policy === "sandbox") {
375
+ const prepared = await confineSandbox(rawArgv, request);
376
+ if ("kind" in prepared) return prepared;
377
+ confined = prepared;
378
+ }
379
+ signal.throwIfAborted();
380
+ const spec = {
381
+ argv: confined?.argv ?? rawArgv,
382
+ cwd,
383
+ stdio: {
384
+ stdin: "ignore",
385
+ stdout: {
386
+ maxBytes: MAX_HOST_USER_SHELL_STREAM_BYTES,
387
+ spill: { maxBytes: HOST_USER_SHELL_SPILL_MAX_BYTES }
388
+ },
389
+ stderr: {
390
+ maxBytes: MAX_HOST_USER_SHELL_STREAM_BYTES,
391
+ spill: { maxBytes: HOST_USER_SHELL_SPILL_MAX_BYTES }
392
+ }
393
+ },
394
+ graceMs: HOST_USER_SHELL_GRACE_MS,
395
+ signal
396
+ };
397
+ request.beforeSpawn?.();
398
+ signal.throwIfAborted();
399
+ let handle;
400
+ try {
401
+ handle = subprocess.spawn(spec);
402
+ } catch (error) {
403
+ signal.throwIfAborted();
404
+ 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)})`);
405
+ return refused(`the Host process could not start — nothing was executed (${hostShellDiagnostic(error)})`);
406
+ }
407
+ let outcome;
408
+ try {
409
+ outcome = await handle.done;
410
+ if (!await handle.waitForExit()) throw new Error("the Host subprocess managed range did not become empty");
411
+ } catch (error) {
412
+ handle.terminate();
413
+ let rangeEmpty = false;
414
+ let observationError;
415
+ try {
416
+ rangeEmpty = await handle.waitForExit();
417
+ } catch (retryError) {
418
+ observationError = retryError;
419
+ }
420
+ 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)})`);
421
+ if (outcome === void 0) {
422
+ 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)})`);
423
+ if (signal.aborted) signal.throwIfAborted();
424
+ return failed("infrastructure", `the Host process failed before reporting an outcome (${hostShellDiagnostic(error)})`);
425
+ }
426
+ }
427
+ if (outcome === void 0) return failed("infrastructure", "the Host process did not report an outcome");
428
+ let stdout;
429
+ let stderr;
430
+ try {
431
+ stdout = collectedOutput(handle.collected.stdout);
432
+ stderr = collectedOutput(handle.collected.stderr);
433
+ } catch (error) {
434
+ return failed("infrastructure", `the Host process output could not be read (${hostShellDiagnostic(error)})`);
435
+ }
436
+ if (confined !== void 0) {
437
+ const runnerFailure = classifyRunnerFailure(outcome.exitCode, stderr.text, confined.runnerFailureRules);
438
+ if (runnerFailure !== void 0) return failed("sandbox-runner", `the Host sandbox runner failed before the user command executed (${runnerFailure.detail})`);
439
+ }
440
+ const stderrTruncated = stderr.truncated;
441
+ const exitNonzero = outcome.exitCode !== null && outcome.exitCode !== 0;
442
+ const denied = confined !== void 0 && !(confined !== void 0 && exitNonzero && stderrTruncated) && matchesSignature(outcome.exitCode, stderr.text, confined.denialSignatures);
443
+ const exit = outcome.exitCode !== null ? {
444
+ kind: "exit",
445
+ code: outcome.exitCode
446
+ } : outcome.signal !== null ? {
447
+ kind: "signal",
448
+ signal: outcome.signal
449
+ } : void 0;
450
+ if (exit === void 0) return failed("infrastructure", "the Host process returned neither an exit code nor a terminating signal");
451
+ if (exit.kind === "exit" && (exit.code < 0 || exit.code > 255)) return failed("infrastructure", `the Host process returned an unusable exit code ${String(exit.code)}`);
452
+ const streams = boundedHostUserShellResultStreams(boundedHostUserShellOutput(stdout), boundedHostUserShellOutput(stderr));
453
+ return {
454
+ kind: "settled",
455
+ result: {
456
+ exit,
457
+ stdout: streams.stdout,
458
+ stderr: streams.stderr,
459
+ sandboxDenied: denied,
460
+ aborted: signal.aborted,
461
+ timedOut: false
462
+ }
463
+ };
464
+ }
465
+ async function confineSandbox(rawArgv, request) {
466
+ const { session, sandboxPolicy, sandbox, signal } = request;
467
+ if (session === void 0) return refused("Host shell sandbox requires a live Session — nothing was executed");
468
+ if (sandboxPolicy === void 0 || sandbox === void 0) return refused("Host shell sandbox policy is unavailable — nothing was executed");
469
+ let resolved;
470
+ let confined;
471
+ try {
472
+ resolved = await sandboxPolicy.resolve({ session });
473
+ signal.throwIfAborted();
474
+ if (resolved.mode === "danger-full-access") return refused("Host shell sandbox refuses danger-full-access — nothing was executed");
475
+ confined = await sandbox.confine(rawArgv, resolved, signal);
476
+ } catch (error) {
477
+ signal.throwIfAborted();
478
+ return refused(`Host shell sandbox could not establish confinement: ${hostShellDiagnostic(error)} — nothing was executed`);
479
+ }
480
+ if (confined.enforcement !== "full") return refused("Host shell sandbox enforcement is not full — nothing was executed");
481
+ return confined;
482
+ }
483
+ //#endregion
484
+ //#region src/domain/communication/focus.ts
485
+ /**
486
+ * Focus Mode's model-facing behavioral policy (TS8-F3).
487
+ *
488
+ * Focus Mode is a presentation + behavioral-policy feature: the session log
489
+ * stays lossless and the TUI only PROJECTS turn-intermediate activity into a
490
+ * live Thought block. The neutral domain owns the section identity and the
491
+ * pure prompt text; the projection itself lives in
492
+ * `tui/transcript/focus-projection.ts`, the TUI surface in `tui-app.ts`, and
493
+ * the section registration in `app/direct/system-prompt.ts`.
494
+ *
495
+ * The registering owner reads the shared state on EVERY assembly, so toggling
496
+ * Focus never re-composes the agent nor re-registers the section — the next
497
+ * model step simply sees the new value.
498
+ * @module @xmoon76/dsh-pi-tui/domain/communication/focus
499
+ */
500
+ /** The system-prompt section name: TUI-private, never a host/preset name. */
501
+ const FOCUS_SECTION_NAME = "tui:focus-mode";
502
+ /**
503
+ * The model-facing Focus instruction (plan §4): the user only sees the final
504
+ * text message of each response, so mid-turn narration is wasted and
505
+ * everything the user needs must land in the final message. Questions and
506
+ * background work are explicit exceptions to the old hidden-context assumption:
507
+ * both need truthful, self-contained visible communication.
508
+ */
509
+ const FOCUS_MODE_PROMPT = `# Focus mode
510
+ 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.
511
+
512
+ 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.
513
+
514
+ 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.`;
515
+ /**
516
+ * The effective Focus section text for the live display state: the instruction
517
+ * only while the Focus preset is active, else empty. The section is stable
518
+ * behavioral policy — never `complete`, never dynamic context.
519
+ */
520
+ function focusPromptText(displayState) {
521
+ return isFocusDisplayPreset(displayState.preset) ? FOCUS_MODE_PROMPT : "";
522
+ }
523
+ //#endregion
524
+ //#region src/app/agent/prompt-sections.ts
525
+ /**
526
+ * The shared per-Agent TUI system-prompt section installer (M6 PR-C C2).
527
+ *
528
+ * Direct and Split Host both install the FOUR TUI-owned communication
529
+ * sections through this one neutral `app/` implementation, so the assembled
530
+ * model-facing text can never diverge between the backends. The pure text and
531
+ * policy derivation stays in `domain/communication/**`; this module owns only
532
+ * the per-Turn eligibility/focus evaluation and the section registration.
533
+ *
534
+ * Per-Turn policy (the accepted Owner Focus ruling):
535
+ *
536
+ * ```text
537
+ * turn/start -> snapshotVoters(agent.session) => { eligible, focus } FROZEN
538
+ * for exactly this Turn (the three preference axes stay LIVE
539
+ * provider reads at each assembly)
540
+ * turn/end -> the latch clears
541
+ * eligible -> all four section texts participate (progress empty under focus)
542
+ * !eligible -> NONE of the four section texts participates (empty text)
543
+ * ```
544
+ *
545
+ * The registrations may exist per Agent while their text is empty on
546
+ * non-TUI turns: section presence is not a claim of rendered text. The
547
+ * `{{provider}}`/`{{model}}` variables stay owned by the official
548
+ * `dsh-system-prompt` seam; this module never interpolates.
549
+ *
550
+ * `src/app/direct/system-prompt.ts` is the compatibility adapter for the
551
+ * public `composeAgent` helper and the existing tests; the Host installer is
552
+ * `src/app/host/features/agent-prompt.ts`. Neither may duplicate the section
553
+ * names, orders or texts owned here.
554
+ *
555
+ * @module @xmoon76/dsh-pi-tui/app/agent/prompt-sections
556
+ */
557
+ /**
558
+ * The always-eligible live-display policy used by the public `composeAgent`
559
+ * compatibility adapter and the existing section tests: the display state IS
560
+ * the frozen snapshot, evaluated live (the pre-C2 semantics).
561
+ */
562
+ function liveDisplayTurnPolicy(displayState) {
563
+ return { currentTurn: () => ({
564
+ eligible: true,
565
+ focus: displayState.preset === "focus"
566
+ }) };
567
+ }
568
+ /** The ephemeral display input one frozen Turn focus implies. */
569
+ function turnDisplay(turn) {
570
+ return { preset: turn.focus ? "focus" : "full" };
571
+ }
572
+ /** The effective progress text of one Turn (empty when not eligible). */
573
+ function turnProgressText(turn, state) {
574
+ if (turn === void 0 || !turn.eligible) return "";
575
+ return progressUpdatesPromptText(turnDisplay(turn), state);
576
+ }
577
+ /** The effective response-style text of one Turn (empty when not eligible). */
578
+ function turnResponseStyleText(turn, state) {
579
+ if (turn === void 0 || !turn.eligible) return "";
580
+ return responseStylePromptText(state);
581
+ }
582
+ /** The effective git-attribution text of one Turn (empty when not eligible). */
583
+ function turnGitAttributionText(turn, state) {
584
+ if (turn === void 0 || !turn.eligible) return "";
585
+ return gitAttributionPromptText(state);
586
+ }
587
+ /** The effective Focus text of one Turn (empty when not eligible). */
588
+ function turnFocusText(turn) {
589
+ if (turn === void 0 || !turn.eligible) return "";
590
+ return focusPromptText(turnDisplay(turn));
591
+ }
592
+ /**
593
+ * Register the progress-updates section under one Turn policy. The state is a
594
+ * PROVIDER read at every assembly: a preference change is seen by the next
595
+ * model step without re-composition (the Host reads the canonical refs per
596
+ * call; Direct passes its live holder).
597
+ */
598
+ function installProgressUpdatesSection(systemPrompt, turn, state) {
599
+ return systemPrompt.section({
600
+ name: PROGRESS_UPDATES_SECTION_NAME,
601
+ order: 80,
602
+ text: () => turnProgressText(turn.currentTurn(), state())
603
+ });
604
+ }
605
+ /** Register the response-style section; each assembly reads the live state. */
606
+ function installResponseStyleSection(systemPrompt, turn, state) {
607
+ return systemPrompt.section({
608
+ name: RESPONSE_STYLE_SECTION_NAME,
609
+ order: 81,
610
+ text: () => turnResponseStyleText(turn.currentTurn(), state())
611
+ });
612
+ }
613
+ /** Register the git-attribution section; each assembly reads the live state. */
614
+ function installGitAttributionSection(systemPrompt, turn, state) {
615
+ return systemPrompt.section({
616
+ name: GIT_ATTRIBUTION_SECTION_NAME,
617
+ order: 82,
618
+ text: () => turnGitAttributionText(turn.currentTurn(), state())
619
+ });
620
+ }
621
+ /**
622
+ * Register the Focus behavioral section under one Turn policy. It is
623
+ * deliberately NOT `complete` (it must never replace the harness
624
+ * identity/persona/tool guidance) and NOT dynamic context.
625
+ */
626
+ function installFocusSection(systemPrompt, turn) {
627
+ return systemPrompt.section({
628
+ name: FOCUS_SECTION_NAME,
629
+ order: 90,
630
+ text: () => turnFocusText(turn.currentTurn())
631
+ });
632
+ }
633
+ //#endregion
634
+ export { liveDisplayTurnPolicy as a, OfficialWorkspaceSearchPool as c, parseResponseStyle as d, isUserInvocableSkill as f, installResponseStyleSection as i, parseGitAttributionMode as l, installGitAttributionSection as n, HostShellExecutionVeto as o, installProgressUpdatesSection as r, executeHostShellOnce as s, installFocusSection as t, parseProgressUpdates as u };