@xmoon76/dsh-pi-tui 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.en.md +28 -7
  2. package/README.md +25 -6
  3. package/dist/application-runtime-CbBO4bY-.mjs +6860 -0
  4. package/dist/bootstrap-DLOydLLj.mjs +108410 -0
  5. package/dist/builtins.mjs +2 -3
  6. package/dist/client-bootstrap-DwSFzcTW.mjs +872 -0
  7. package/dist/context-summary-Bz0AGXa1.mjs +12027 -0
  8. package/dist/{context-summary-DAisTA_7.mjs → context-summary-D9mhxPXL.mjs} +1468 -10
  9. package/dist/custom-items-CKrOBCox.mjs +655 -0
  10. package/dist/disposal-BYBbEpVY.mjs +54 -0
  11. package/dist/dispose-cause-BzcXo4hu.mjs +123 -0
  12. package/dist/dist-C7QMk0ws.mjs +15431 -0
  13. package/dist/{entry-control-DvSrndWd.mjs → entry-control-DnduyDiw.mjs} +12 -31
  14. package/dist/{extensions-CcuMY4n2.mjs → extensions-pcFiH7Qe.mjs} +758 -68
  15. package/dist/extensions.mjs +1 -1
  16. package/dist/host-bootstrap-CKdfLkNS.mjs +188 -0
  17. package/dist/host-foundation-probe-CYHsbAw6.mjs +143 -0
  18. package/dist/host-prerequisites-9JBTtVNu.mjs +36 -0
  19. package/dist/host-runtime.d.mts +26 -0
  20. package/dist/host-runtime.mjs +450 -0
  21. package/dist/index.d.mts +8 -1
  22. package/dist/index.mjs +5192 -2118
  23. package/dist/local-client.mjs +1681 -188
  24. package/dist/local-discovery-CXnLT4GF.mjs +755 -0
  25. package/dist/local-discovery-DVFFpfBG.mjs +2 -0
  26. package/dist/local-host.mjs +927 -78
  27. package/dist/local-transport-C9aonplC.mjs +513 -0
  28. package/dist/performance-host.d.mts +2 -2
  29. package/dist/performance-host.mjs +258 -1
  30. package/dist/pi-tui-remote-contribution-DRk6Tl3J.mjs +78 -0
  31. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  32. package/dist/pi-tui-terminal-progress-contract-XTQKj-WW.mjs +905 -0
  33. package/dist/{runtime-vc4mdr-R.mjs → runtime-Bh5OsftD.mjs} +655 -675
  34. package/dist/runtime-C5ROZqFj.mjs +2 -0
  35. package/dist/{session-tdJHLnJR.mjs → session-4keoXjk0.mjs} +2341 -217
  36. package/dist/session-B2zqv4wr.mjs +10869 -0
  37. package/dist/{startup-JaVZoTIl.mjs → startup-Ct2UUjUL.mjs} +7 -6
  38. package/dist/startup.d.mts +1 -1
  39. package/dist/startup.mjs +1 -1
  40. package/dist/{client-bootstrap-F5DHFI9t.mjs → terminal-progress-source-BhufrZ74.mjs} +3431 -3007
  41. package/dist/terminal-progress-source-CsBinCJ_.mjs +965 -0
  42. package/package.json +125 -116
  43. package/dist/host-bootstrap-DAgKknbY.mjs +0 -119
  44. package/dist/performance-host-CcDJjjVA.mjs +0 -266
  45. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  46. package/dist/terminal-progress-source-xor3vakJ.mjs +0 -2256
@@ -0,0 +1,655 @@
1
+ import { bt as parseFooterLayout, yt as isFooterLayout } from "./extensions-pcFiH7Qe.mjs";
2
+ //#region src/runtime/process/errors.ts
3
+ /**
4
+ * Shared, TOTAL error-observation helpers for every async boundary in the
5
+ * TUI: the owned/detached entries (`tasks.ts`), the lifecycle roots
6
+ * (startup, exit, flush), the per-task callbacks and the diagnostics
7
+ * formatter. One implementation, one behavior — no drift between modules.
8
+ *
9
+ * CONTRACT (deliberately scoped, honestly worded): the SYNC boundary is
10
+ * total — observing any legal JavaScript value (a Proxy with a throwing
11
+ * `getPrototypeOf` trap, a throwing `message` getter, a throwing
12
+ * `toString`/`Symbol.toPrimitive`) can never make THIS code throw or
13
+ * reject; every observation is protected and every fallback is a fixed
14
+ * constant that never touches the value again. What is NOT guaranteed: an
15
+ * observer (getter/trap/coercion) that, WHILE being observed, spawns its
16
+ * OWN detached async work (e.g. `void Promise.reject(...)` inside
17
+ * `toString`) — that rejection belongs to the observer, not to this
18
+ * boundary, and no synchronous try/catch can intercept it. Callers must
19
+ * not describe this module as a strict "any legal value, zero side
20
+ * effects" guarantee.
21
+ * @module @xmoon76/dsh-pi-tui/runtime/process/errors
22
+ */
23
+ /**
24
+ * Describe an arbitrary thrown value as a string WITHOUT ever throwing:
25
+ * `instanceof`, property reads and coercion are all inside the protection,
26
+ * the fallbacks are FIXED constants that never touch the value again, and
27
+ * a hostile Proxy/getter/`Symbol.toPrimitive` yields a stable placeholder
28
+ * instead of escaping. (Best-effort beyond the sync boundary — see the
29
+ * module contract.)
30
+ */
31
+ function safeErrorMessage(value) {
32
+ try {
33
+ if (value instanceof Error) try {
34
+ const message = value.message;
35
+ return typeof message === "string" ? message : "<error with non-string message>";
36
+ } catch {
37
+ return "<error with unreadable message>";
38
+ }
39
+ return String(value);
40
+ } catch {
41
+ return "<unprintable error>";
42
+ }
43
+ }
44
+ /** Describe an arbitrary thrown value using its normal `String` form without
45
+ * allowing hostile coercion to escape the async boundary. */
46
+ function safeErrorString(value) {
47
+ try {
48
+ return String(value);
49
+ } catch {
50
+ return "<unprintable error>";
51
+ }
52
+ }
53
+ //#endregion
54
+ //#region src/runtime/process/tasks.ts
55
+ /**
56
+ * Whether an error represents an abort/cancel rather than a real failure.
57
+ * TOTAL over the whole `unknown` domain: every probe (prototype-chain
58
+ * walk, `name`/`code` getters) is inside the protection, and a hostile
59
+ * value that throws while being observed simply classifies as NOT a
60
+ * cancellation — recognizing a cancellation must never mint a new primary
61
+ * error.
62
+ */
63
+ function isCancellation(error) {
64
+ try {
65
+ if (!(error instanceof Error)) return false;
66
+ return error.name === "AbortError" || error.code === "ABORT_ERR";
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+ /** Build a cancellation-shaped error the classifier recognizes (a plain
72
+ * `new Error('...')` would route through the failure path). */
73
+ function cancellationError(message) {
74
+ const error = new Error(message);
75
+ error.name = "AbortError";
76
+ error.code = "ABORT_ERR";
77
+ return error;
78
+ }
79
+ /** Read the live session id for diagnostics WITHOUT ever throwing: a
80
+ * throwing `sessionId()` callback degrades to `undefined` (diagnostics
81
+ * must not crash classification or the final sink). */
82
+ function safeSessionId(options) {
83
+ try {
84
+ return options.sessionId?.();
85
+ } catch {
86
+ return;
87
+ }
88
+ }
89
+ /**
90
+ * Invoke the task factory SYNCHRONOUSLY (an ownership action inside the
91
+ * factory — a stop, a latch, a spawn — must take effect before the helper
92
+ * returns, so two calls in one input batch cannot both start), and convert
93
+ * a synchronous throw into a rejected promise so it classifies exactly like
94
+ * a rejection.
95
+ */
96
+ function invokeTask(task) {
97
+ try {
98
+ return Promise.resolve(task());
99
+ } catch (error) {
100
+ return Promise.reject(error);
101
+ }
102
+ }
103
+ /**
104
+ * Observe the settlement of an ALREADY-OWNED promise without taking ownership.
105
+ * The callback runs on fulfilment or rejection and its own result is dropped,
106
+ * so bookkeeping (for example removing a promise from a teardown-drained set)
107
+ * never adds a second, unhandled rejection branch next to the real owner's
108
+ * failure handling. Never use this to START work — that is `runDetached` /
109
+ * `runOwned`.
110
+ * @param promise - the promise whose failure semantics already have an owner.
111
+ * @param onSettled - runs once, on either settlement.
112
+ */
113
+ function observeSettled(promise, onSettled) {
114
+ promise.then(onSettled, onSettled);
115
+ }
116
+ /**
117
+ * Attach rejection handling to a fire-and-forget task. The factory is
118
+ * invoked synchronously (a synchronous throw is a rejection like any
119
+ * other); every rejection is caught and classified:
120
+ * - cancellation → debug diagnostics only (never a user error);
121
+ * - recoverable (per the options hook) → notify + warn;
122
+ * - anything else → warn.
123
+ * The log line carries the task label and the live session id — never the
124
+ * task payload (no API keys, prompt bodies, or shell output). A throwing
125
+ * notify/diag/sessionId path cannot escape: it lands in the handler-failure
126
+ * sink, which is itself total over the `unknown` domain.
127
+ */
128
+ function runDetached(label, task, options) {
129
+ invokeTask(task).catch((error) => {
130
+ if (isCancellation(error)) {
131
+ options.diag.debug(label, {
132
+ session: safeSessionId(options),
133
+ cancelled: true
134
+ });
135
+ return;
136
+ }
137
+ const message = safeErrorMessage(error);
138
+ options.diag.warn(label, {
139
+ session: safeSessionId(options),
140
+ error: message
141
+ });
142
+ if (options.recoverable?.(error) === true) options.notify?.(`${label}: ${message}`);
143
+ }).catch(handlerFailure(label, options));
144
+ }
145
+ /**
146
+ * The owned-workflow counterpart of {@link runDetached}: a fire-and-forget
147
+ * task whose RESULT drives user-visible state (a settled card, a restored
148
+ * draft, a queue mutation, a notification). The factory starts
149
+ * SYNCHRONOUSLY; the TASK phase (factory throw / task rejection) classifies
150
+ * with the error shape plus the task-local predicate; the onResult phase is
151
+ * classified as a PRIMARY failure — ERROR + onError, never a cancellation,
152
+ * regardless of error shape or task-local state; a terminal side-effect
153
+ * handler's (onCancel/onError/classifier) own sync/async throw is wrapped
154
+ * in a {@link HandlerFailure} and lands in the `${label} handler failed`
155
+ * sink exactly once, without mutating the thrown value. Never a bare
156
+ * `void somePromise()`: every owned flow goes through this entry
157
+ * (AGENTS.md).
158
+ */
159
+ function runOwned(label, task, options) {
160
+ invokeTask(task).then((result) => options.onResult?.(result), (error) => {
161
+ return classify(label, options, error, true);
162
+ }).catch((error) => {
163
+ if (isHandlerFailure(error)) throw error;
164
+ return classify(label, options, error, false);
165
+ }).catch(handlerFailure(label, options));
166
+ }
167
+ /**
168
+ * Classify one failure and record the classification diagnostics, then run
169
+ * the matching per-task callback. `allowCancellation` gates ALL cancellation
170
+ * classification: the task phase may treat an AbortError or a task-local
171
+ * state as a cancellation; the onResult phase may not (a result-consumer
172
+ * failure is a failure). A terminal side-effect handler's own sync/async
173
+ * failure is wrapped in {@link HandlerFailure} and propagated to the
174
+ * handler-failure sink — never re-classified, never repeated, never
175
+ * escaped. All diagnostics go through the never-throw helpers, so a
176
+ * hostile thrown value or a throwing sessionId/diag can never mint a new
177
+ * primary error.
178
+ */
179
+ function classify(label, options, error, allowCancellation) {
180
+ if (allowCancellation && (isCancellation(error) || taskLocalCancellation(options, error))) {
181
+ options.diag.debug(label, {
182
+ session: safeSessionId(options),
183
+ cancelled: true
184
+ });
185
+ if (options.onCancel !== void 0) return guardHandler(() => options.onCancel(error));
186
+ return;
187
+ }
188
+ options.diag.error(label, {
189
+ session: safeSessionId(options),
190
+ error: safeErrorMessage(error)
191
+ });
192
+ if (options.onError !== void 0) return guardHandler(() => options.onError(error));
193
+ }
194
+ /** The task-local predicate (cancellation classification is already gated
195
+ * by the caller). A throwing predicate is wrapped as a handler failure — it
196
+ * never re-routes the original error into the wrong classification and is
197
+ * never itself re-classified. */
198
+ function taskLocalCancellation(options, error) {
199
+ if (options.isCancellation === void 0) return false;
200
+ try {
201
+ return options.isCancellation(error) === true;
202
+ } catch (classifierError) {
203
+ throw new HandlerFailure(classifierError);
204
+ }
205
+ }
206
+ /**
207
+ * Immutable wrapper for a terminal side-effect handler's own failure. The
208
+ * thrown value is NEVER mutated (a primitive, null, or a frozen/non-
209
+ * extensible error must survive intact); the wrapper carries the original
210
+ * cause to the handler-failure sink, and the middle classification catch
211
+ * recognizes it and forwards it unchanged — so `onError`/`onCancel` run
212
+ * exactly once even when they throw.
213
+ */
214
+ var HandlerFailure = class {
215
+ cause;
216
+ constructor(cause) {
217
+ this.cause = cause;
218
+ handlerFailures.add(this);
219
+ }
220
+ };
221
+ /** Identity registry for the internal wrappers: `WeakSet.has` compares by
222
+ * identity and never walks the argument's prototype chain, so a hostile
223
+ * thrown value (a Proxy with a throwing `getPrototypeOf` trap) can be
224
+ * tested safely — `instanceof HandlerFailure` on an untrusted value could
225
+ * itself throw. */
226
+ const handlerFailures = /* @__PURE__ */ new WeakSet();
227
+ /** Whether a value is one of OUR wrapper instances (identity only; total
228
+ * over the whole `unknown` domain). */
229
+ function isHandlerFailure(value) {
230
+ return typeof value === "object" && value !== null && handlerFailures.has(value);
231
+ }
232
+ /** Run a per-task terminal callback; a sync or async failure is wrapped in
233
+ * {@link HandlerFailure} so the chain forwards it to the handler-failure
234
+ * sink instead of re-classifying it (and never repeats the callback). */
235
+ function guardHandler(invoke) {
236
+ try {
237
+ const outcome = invoke();
238
+ if (outcome !== void 0) return outcome.catch((error) => {
239
+ throw new HandlerFailure(error);
240
+ });
241
+ return;
242
+ } catch (error) {
243
+ throw new HandlerFailure(error);
244
+ }
245
+ }
246
+ /**
247
+ * The final sink of both helpers: a terminal side-effect handler
248
+ * (onResult's own invocation aside — see {@link runOwned}), a task-local
249
+ * classifier, or the diagnostics channel itself threw. The ENTIRE body is
250
+ * protected — wrapper unwrapping, error description, the session read and
251
+ * the diag call all live inside the try, and the fallback is a fixed
252
+ * constant that never touches the hostile value again — so the sink is a
253
+ * total function over the `unknown` domain: it can NEVER reject, and there
254
+ * is no lower sink to leak into.
255
+ */
256
+ function handlerFailure(label, options) {
257
+ return (error) => {
258
+ try {
259
+ const cause = isHandlerFailure(error) ? error.cause : error;
260
+ options.diag.error(`${label} handler failed`, {
261
+ session: safeSessionId(options),
262
+ error: safeErrorMessage(cause)
263
+ });
264
+ } catch {}
265
+ };
266
+ }
267
+ //#endregion
268
+ //#region src/domain/footer/command-config.ts
269
+ /** The timeout ceiling. */
270
+ const MAX_COMMAND_TIMEOUT_MS = 1e3;
271
+ /** The minimum refresh interval (plan §17.7). */
272
+ const MIN_COMMAND_REFRESH_MS = 1e3;
273
+ //#endregion
274
+ //#region src/domain/footer/command-trust.ts
275
+ /**
276
+ * The footer command TRUST GATE (plan §17.4): a repository/project config
277
+ * must NEVER silently trigger arbitrary shell execution. The command is
278
+ * read ONLY from the settings descriptor's USER layer (the stored
279
+ * document's user section) — never from the merged/resolved value, which
280
+ * a project layer could influence. When the user layer cannot prove the
281
+ * command, command mode is disabled and the native layout applies.
282
+ * @module @xmoon76/dsh-pi-tui/domain/footer/command-trust
283
+ */
284
+ /** Validate the persisted footerCommand value (bounds per plan §17.3). */
285
+ function parseFooterCommandConfig(input) {
286
+ if (typeof input !== "object" || input === null) return void 0;
287
+ const raw = input;
288
+ if (raw.schemaVersion !== 1) return void 0;
289
+ if (typeof raw.command !== "string" || raw.command.trim() === "") return void 0;
290
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(raw.command)) return void 0;
291
+ const timeoutMs = raw.timeoutMs === void 0 ? 300 : typeof raw.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? Math.min(Math.max(1, raw.timeoutMs), MAX_COMMAND_TIMEOUT_MS) : 300;
292
+ const refreshIntervalMs = raw.refreshIntervalMs === void 0 ? MIN_COMMAND_REFRESH_MS : typeof raw.refreshIntervalMs === "number" && Number.isFinite(raw.refreshIntervalMs) ? Math.max(MIN_COMMAND_REFRESH_MS, raw.refreshIntervalMs) : MIN_COMMAND_REFRESH_MS;
293
+ const maxRows = raw.maxRows === void 0 ? 1 : typeof raw.maxRows === "number" && Number.isFinite(raw.maxRows) ? Math.min(Math.max(1, Math.floor(raw.maxRows)), 2) : 1;
294
+ return {
295
+ command: raw.command,
296
+ timeoutMs,
297
+ refreshIntervalMs,
298
+ maxRows
299
+ };
300
+ }
301
+ /**
302
+ * Resolve the TRUSTED command config: the footerCommand value must be
303
+ * present in the USER layer of the tui-app settings descriptor. A
304
+ * merged/project-supplied value is refused (undefined = command mode
305
+ * disabled, native fallback, diagnostic warning).
306
+ * @param descriptors - the settings provider's describe() output.
307
+ * @param namespace - the tui-app settings/profile Config namespace value.
308
+ * @returns the validated config, or undefined when untrusted/invalid.
309
+ */
310
+ function resolveTrustedFooterCommand(descriptors, namespace) {
311
+ if (descriptors === void 0) return void 0;
312
+ const descriptor = descriptors.find((entry) => entry.ns === namespace);
313
+ if (descriptor === void 0) return void 0;
314
+ const user = descriptor.user;
315
+ if (typeof user !== "object" || user === null) return void 0;
316
+ const raw = user.footerCommand;
317
+ return parseFooterCommandConfig(raw);
318
+ }
319
+ /**
320
+ * Resolve the USER layer's declared footer mode. Command mode must be
321
+ * user-layer-owned as well: a project can flip the MERGED `footer:
322
+ * command`, but the gate never lets a project config silently trigger the
323
+ * user's command — the user layer must declare the command mode too.
324
+ * @returns the user layer's footer value, or undefined when absent.
325
+ */
326
+ function resolveUserLayerFooterMode(descriptors, namespace) {
327
+ if (descriptors === void 0) return void 0;
328
+ const descriptor = descriptors.find((entry) => entry.ns === namespace);
329
+ if (descriptor === void 0) return void 0;
330
+ const user = descriptor.user;
331
+ if (typeof user !== "object" || user === null) return void 0;
332
+ const mode = user.footer;
333
+ return typeof mode === "string" ? mode : void 0;
334
+ }
335
+ /**
336
+ * Resolve the USER layer's declared custom layout (PR D activation trust):
337
+ * the layout whose refs MAY authorize custom command items — but only
338
+ * while the USER layer itself declares footer: custom (see
339
+ * resolveUserCommandItemActivationIds). A project can supply a MERGED
340
+ * `footerLayout` for rendering, but it can never activate a dormant USER
341
+ * command — the same principle as the command-mode gate above: the user
342
+ * layer must own the layout that decides what executes.
343
+ * @returns the validated USER-layer layout, or undefined when absent or
344
+ * invalid (an invalid user layout authorizes nothing — fail-safe).
345
+ */
346
+ function resolveUserLayerFooterLayout(descriptors, namespace) {
347
+ if (descriptors === void 0) return void 0;
348
+ const descriptor = descriptors.find((entry) => entry.ns === namespace);
349
+ if (descriptor === void 0) return void 0;
350
+ const user = descriptor.user;
351
+ if (typeof user !== "object" || user === null) return void 0;
352
+ const layout = user.footerLayout;
353
+ const parsed = parseFooterLayout(layout);
354
+ return isFooterLayout(parsed) ? parsed : void 0;
355
+ }
356
+ /**
357
+ * Resolve the USER layer's declared footerFallbackMode (the native mode
358
+ * the user's own command-mode fallback restores).
359
+ */
360
+ function resolveUserLayerFooterFallbackMode(descriptors, namespace) {
361
+ if (descriptors === void 0) return void 0;
362
+ const descriptor = descriptors.find((entry) => entry.ns === namespace);
363
+ if (descriptor === void 0) return void 0;
364
+ const user = descriptor.user;
365
+ if (typeof user !== "object" || user === null) return void 0;
366
+ const mode = user.footerFallbackMode;
367
+ return typeof mode === "string" ? mode : void 0;
368
+ }
369
+ /** The shared empty authorization set. */
370
+ const EMPTY_IDS = /* @__PURE__ */ new Set();
371
+ /** Every item id a layout references (the authorization projection). */
372
+ function layoutRefIds(layout) {
373
+ const ids = /* @__PURE__ */ new Set();
374
+ for (const row of layout.rows) {
375
+ for (const ref of row.left) ids.add(ref.id);
376
+ for (const ref of row.right) ids.add(ref.id);
377
+ }
378
+ return ids;
379
+ }
380
+ /**
381
+ * The ids the USER layer AUTHORIZES for custom command item execution
382
+ * (PR D activation trust, mode-gated): the USER custom layout's refs, but
383
+ * ONLY while the USER layer itself declares `footer: custom`. A stale
384
+ * leftover layout under `footer: default/compact` (the /settings switch
385
+ * deliberately keeps the old layout) authorizes NOTHING — a project
386
+ * flipping the MERGED mode to custom can never resurrect a dormant USER
387
+ * command. `footer: command` authorizes nothing while the whole-footer
388
+ * command surface runs (the caller suspends per-item runners); the native
389
+ * fallback case uses resolveUserCommandItemFallbackActivationIds.
390
+ */
391
+ function resolveUserCommandItemActivationIds(descriptors, namespace) {
392
+ if (resolveUserLayerFooterMode(descriptors, namespace) !== "custom") return EMPTY_IDS;
393
+ const layout = resolveUserLayerFooterLayout(descriptors, namespace);
394
+ return layout === void 0 ? EMPTY_IDS : layoutRefIds(layout);
395
+ }
396
+ /**
397
+ * The ids authorized for the native FALLBACK surface (a merged
398
+ * `footer: command` the USER layer does not own). The FULL semantic is
399
+ * encoded HERE so no caller can forget the outer mode gate:
400
+ *
401
+ * USER footer === 'command'
402
+ * && USER footerFallbackMode === 'custom'
403
+ * && valid USER footerLayout
404
+ * → the layout's refs
405
+ * otherwise → empty
406
+ *
407
+ * A USER who never opted into command mode (footer: default/compact)
408
+ * authorizes NOTHING even with stale fallback metadata; a PROJECT
409
+ * forcing the merged command mode can never turn it into execution
410
+ * authorization.
411
+ */
412
+ function resolveUserCommandItemFallbackActivationIds(descriptors, namespace) {
413
+ if (resolveUserLayerFooterMode(descriptors, namespace) !== "command") return EMPTY_IDS;
414
+ if (resolveUserLayerFooterFallbackMode(descriptors, namespace) !== "custom") return EMPTY_IDS;
415
+ const layout = resolveUserLayerFooterLayout(descriptors, namespace);
416
+ return layout === void 0 ? EMPTY_IDS : layoutRefIds(layout);
417
+ }
418
+ //#endregion
419
+ //#region src/domain/footer/custom-items.ts
420
+ /**
421
+ * User-owned custom footer item definitions (PR C + PR D), neutral half
422
+ * (TS5 §13.3): the persisted raw settings shapes, their validation and
423
+ * normalization, and the config-effective values. Custom definitions are
424
+ * persisted separately from FooterLayoutV1: the layout stores only the
425
+ * canonical `user:*` reference, while this module owns what that item IS.
426
+ * The presentation compilation (FooterItemDefinition / runtime catalog) lives
427
+ * in `tui/footer/custom-item-catalog.ts`.
428
+ * @module @xmoon76/dsh-pi-tui/domain/footer/custom-items
429
+ */
430
+ /** The namespace reserved for user-created definitions. */
431
+ const CUSTOM_FOOTER_ITEM_PREFIX = "user:";
432
+ /** The default refresh interval for a custom command item (PR D §5.2):
433
+ * several command items can coexist, so the default must not spawn one
434
+ * process per item per second (the whole-footer M5 default is 1s). */
435
+ const DEFAULT_CUSTOM_COMMAND_REFRESH_MS = 5e3;
436
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/u;
437
+ const TONES = /* @__PURE__ */ new Set([
438
+ "primary",
439
+ "accent",
440
+ "text",
441
+ "textStrong",
442
+ "textDim",
443
+ "textMuted",
444
+ "border",
445
+ "success",
446
+ "warning",
447
+ "error",
448
+ "roleUser",
449
+ "shellMode"
450
+ ]);
451
+ /** The EXACT key set a v1 text definition may carry. A known-kind object
452
+ * with any OTHER key is forward-compatible raw data (plan §12.1 — an
453
+ * "unknown field object" keeps its raw slot): a future client's field must
454
+ * never be silently normalized away by an unrelated save. */
455
+ const TEXT_ITEM_KEYS = /* @__PURE__ */ new Set([
456
+ "schemaVersion",
457
+ "id",
458
+ "kind",
459
+ "text",
460
+ "tone"
461
+ ]);
462
+ /** The EXACT key set a v1 command definition may carry (same rule). */
463
+ const COMMAND_ITEM_KEYS = /* @__PURE__ */ new Set([
464
+ "schemaVersion",
465
+ "id",
466
+ "kind",
467
+ "command",
468
+ "refreshIntervalMs",
469
+ "timeoutMs",
470
+ "tone"
471
+ ]);
472
+ /** Whether the raw object carries a key outside the allowed v1 set. */
473
+ function hasUnknownKeys(raw, allowed) {
474
+ for (const key of Object.keys(raw)) if (!allowed.has(key)) return true;
475
+ return false;
476
+ }
477
+ /** The validated runner config for one command definition (maxRows is
478
+ * always 1 — a custom command item is exactly one line; the composer owns
479
+ * width/truncation). The custom-item DEFAULT refresh is 5s (several items
480
+ * can coexist — the whole-footer 1s default would spawn a process per
481
+ * item per second), so an ABSENT refreshIntervalMs is projected to the
482
+ * custom default BEFORE the shared parser runs: an absent default and an
483
+ * explicit 5s must produce the SAME cadence. The parser already validated
484
+ * the definition, so this is defensive. This is the ONE projection both
485
+ * the runtime and the effective-value helpers consume, so the UI, the
486
+ * dirty comparator and the real execution can never drift apart. */
487
+ function customCommandConfigOf(item) {
488
+ return parseFooterCommandConfig({
489
+ schemaVersion: 1,
490
+ command: item.command,
491
+ timeoutMs: item.timeoutMs,
492
+ refreshIntervalMs: item.refreshIntervalMs ?? 5e3,
493
+ maxRows: 1
494
+ });
495
+ }
496
+ /** The effective refresh interval of a command definition (absent = the
497
+ * 5s default). Dirty comparison and the runtime use the EFFECTIVE value so
498
+ * an absent default and an explicit default are the same fact. The value
499
+ * is the SAME normalized value the runner executes (the shared parser
500
+ * clamps refresh to >= 1s): a hand-edited out-of-range raw value is
501
+ * preserved in storage for forward compatibility, but the UI and the
502
+ * dirty comparator never lie about the real cadence. */
503
+ function effectiveCustomCommandRefreshMs(item) {
504
+ return customCommandConfigOf(item)?.refreshIntervalMs ?? 5e3;
505
+ }
506
+ /** The effective timeout of a command definition (absent = the whole-footer
507
+ * 300ms default; the shared parser clamps to 1..1000ms — the UI reports
508
+ * the same value the runner enforces). */
509
+ function effectiveCustomCommandTimeoutMs(item) {
510
+ return customCommandConfigOf(item)?.timeoutMs ?? 300;
511
+ }
512
+ function codePointLength(text) {
513
+ return [...text].length;
514
+ }
515
+ /** Normalize the name typed by the user and return undefined for a name that
516
+ * cannot form a stable user namespace id. Colons are reserved so a user name
517
+ * cannot impersonate another canonical namespace such as `ext:*`. */
518
+ function normalizeCustomItemName(input) {
519
+ const name = input.trim();
520
+ if (name === "" || CONTROL_CHARS.test(name)) return void 0;
521
+ if (name.includes(":")) return void 0;
522
+ if (codePointLength(name) > 64) return void 0;
523
+ return name;
524
+ }
525
+ /** Convert a user-facing name to the deterministic persisted id. */
526
+ function customItemId(name) {
527
+ const normalized = normalizeCustomItemName(name);
528
+ return normalized === void 0 ? void 0 : `${CUSTOM_FOOTER_ITEM_PREFIX}${normalized}`;
529
+ }
530
+ /** Return the user-facing part of a canonical id. */
531
+ function customItemName(id) {
532
+ return id.startsWith("user:") ? id.slice(5) : id;
533
+ }
534
+ function isTone(value) {
535
+ return value === "auto" || typeof value === "string" && TONES.has(value);
536
+ }
537
+ /** Parse one persisted definition. Invalid definitions are rejected at this
538
+ * boundary; callers can keep the rest of the collection. */
539
+ function parseFooterCustomItem(input) {
540
+ try {
541
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
542
+ const raw = input;
543
+ if (raw.schemaVersion !== 1) return void 0;
544
+ if (typeof raw.id !== "string" || customItemId(customItemName(raw.id)) !== raw.id) return void 0;
545
+ if (raw.tone !== void 0 && !isTone(raw.tone)) return void 0;
546
+ const tone = raw.tone === void 0 ? void 0 : raw.tone;
547
+ if (raw.kind === "text") {
548
+ if (hasUnknownKeys(raw, TEXT_ITEM_KEYS)) return void 0;
549
+ if (typeof raw.text !== "string" || raw.text.trim() === "" || CONTROL_CHARS.test(raw.text)) return void 0;
550
+ if (codePointLength(raw.text) > 256) return void 0;
551
+ return {
552
+ schemaVersion: 1,
553
+ id: raw.id,
554
+ kind: "text",
555
+ text: raw.text,
556
+ ...tone === void 0 ? {} : { tone }
557
+ };
558
+ }
559
+ if (raw.kind === "command") {
560
+ if (hasUnknownKeys(raw, COMMAND_ITEM_KEYS)) return void 0;
561
+ const refresh = typeof raw.refreshIntervalMs === "number" && Number.isFinite(raw.refreshIntervalMs) ? raw.refreshIntervalMs : void 0;
562
+ const timeout = typeof raw.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? raw.timeoutMs : void 0;
563
+ const config = parseFooterCommandConfig({
564
+ schemaVersion: 1,
565
+ command: raw.command,
566
+ timeoutMs: timeout,
567
+ refreshIntervalMs: refresh,
568
+ maxRows: 1
569
+ });
570
+ if (config === void 0) return void 0;
571
+ const command = config.command;
572
+ return {
573
+ schemaVersion: 1,
574
+ id: raw.id,
575
+ kind: "command",
576
+ command,
577
+ ...refresh === void 0 ? {} : { refreshIntervalMs: refresh },
578
+ ...timeout === void 0 ? {} : { timeoutMs: timeout },
579
+ ...tone === void 0 ? {} : { tone }
580
+ };
581
+ }
582
+ return;
583
+ } catch {
584
+ return;
585
+ }
586
+ }
587
+ /** Parse the collection without letting one malformed or duplicate entry
588
+ * break startup. The first definition for an id wins deterministically. A
589
+ * hostile collection-level proxy/iterator fails closed as one invalid
590
+ * collection instead of escaping into startup or reload. */
591
+ function parseFooterCustomItems(input) {
592
+ try {
593
+ if (input === void 0) return {
594
+ items: [],
595
+ invalidCount: 0
596
+ };
597
+ if (!Array.isArray(input)) return {
598
+ items: [],
599
+ invalidCount: 1
600
+ };
601
+ const items = [];
602
+ const ids = /* @__PURE__ */ new Set();
603
+ let invalidCount = 0;
604
+ for (const candidate of input) {
605
+ const item = parseFooterCustomItem(candidate);
606
+ if (item === void 0 || ids.has(item.id)) {
607
+ invalidCount += 1;
608
+ continue;
609
+ }
610
+ ids.add(item.id);
611
+ items.push(item);
612
+ }
613
+ return {
614
+ items,
615
+ invalidCount
616
+ };
617
+ } catch {
618
+ return {
619
+ items: [],
620
+ invalidCount: 1
621
+ };
622
+ }
623
+ }
624
+ /** Every item id a layout references (the authorization / active-set
625
+ * projection). An absent layout activates nothing. */
626
+ function activeFooterItemIds(layout) {
627
+ const ids = /* @__PURE__ */ new Set();
628
+ if (layout === void 0) return ids;
629
+ for (const row of layout.rows) {
630
+ for (const ref of row.left) ids.add(ref.id);
631
+ for (const ref of row.right) ids.add(ref.id);
632
+ }
633
+ return ids;
634
+ }
635
+ /** The EXECUTABLE command item ids (PR D activation trust, final formula):
636
+ *
637
+ * executable = USER trusted definitions ∩ USER-authorized ids ∩
638
+ * currently rendered layout ids
639
+ *
640
+ * The trusted definitions come from the USER-layer semantic read; the
641
+ * authorized ids come from the ConfigPort's mode-gated projection (a stale
642
+ * leftover USER layout under footer: default/compact authorizes nothing); the
643
+ * rendered layout is what the composer actually shows — a command hidden by
644
+ * the merged layout must not keep running in the background. A /footer save is
645
+ * the special case where the just-committed validated layout is both
646
+ * authorized and rendered. */
647
+ function executableCommandItemIds(trustedCommands, authorizedIds, renderedLayout) {
648
+ const trustedIds = new Set(trustedCommands.map((item) => item.id));
649
+ const renderedIds = activeFooterItemIds(renderedLayout);
650
+ const executable = /* @__PURE__ */ new Set();
651
+ for (const id of renderedIds) if (trustedIds.has(id) && authorizedIds.has(id)) executable.add(id);
652
+ return executable;
653
+ }
654
+ //#endregion
655
+ export { safeErrorMessage as C, runOwned as S, MAX_COMMAND_TIMEOUT_MS as _, customItemId as a, observeSettled as b, effectiveCustomCommandTimeoutMs as c, parseFooterCustomItems as d, parseFooterCommandConfig as f, resolveUserLayerFooterMode as g, resolveUserCommandItemFallbackActivationIds as h, customCommandConfigOf as i, executableCommandItemIds as l, resolveUserCommandItemActivationIds as m, DEFAULT_CUSTOM_COMMAND_REFRESH_MS as n, customItemName as o, resolveTrustedFooterCommand as p, activeFooterItemIds as r, effectiveCustomCommandRefreshMs as s, CUSTOM_FOOTER_ITEM_PREFIX as t, parseFooterCustomItem as u, cancellationError as v, safeErrorString as w, runDetached as x, isCancellation as y };