@xmoon76/dsh-pi-tui 0.5.1 → 0.5.3

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 (31) hide show
  1. package/README.en.md +130 -17
  2. package/README.md +76 -16
  3. package/cordis.patch.yml +17 -49
  4. package/dist/builtins.mjs +3 -2
  5. package/dist/context-summary-CxUpNkA9.mjs +2951 -0
  6. package/dist/extension/advanced.d.mts +2 -2
  7. package/dist/extension/unstable.d.mts +1 -1
  8. package/dist/{extensions-v3Rf-qJA.d.mts → extensions-DzpBiiYb.d.mts} +1 -1
  9. package/dist/{extensions-1WYBUQ8I.mjs → extensions-a-rxanjw.mjs} +3514 -2892
  10. package/dist/extensions.d.mts +2 -2
  11. package/dist/extensions.mjs +1 -1
  12. package/dist/index.d.mts +13 -11
  13. package/dist/index.mjs +20158 -7768
  14. package/dist/performance-host-BJT6scGF.mjs +266 -0
  15. package/dist/performance-host.d.mts +36 -0
  16. package/dist/performance-host.mjs +2 -0
  17. package/dist/performance-view-jvvd8Jn7.mjs +476 -0
  18. package/dist/{public-types-BEjj7FEb.d.mts → public-types-gZi3iFNh.d.mts} +1 -1
  19. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  20. package/dist/{runtime-CcQyhIvI.mjs → runtime-BtPH-UUb.mjs} +625 -261
  21. package/dist/session-BZLxhrPQ.mjs +5697 -0
  22. package/dist/{startup-CmTYVTGC.mjs → startup-D5Xu8diR.mjs} +22 -7
  23. package/dist/startup.d.mts +1 -2
  24. package/dist/startup.mjs +1 -1
  25. package/dist/tasks-D_z5Yjjr.mjs +267 -0
  26. package/dist/{terminal-progress-source-BfiTKDT-.mjs → terminal-progress-source-BlmksrSD.mjs} +116 -265
  27. package/generated/dsh-presets/cordis.patch.yml +8 -26
  28. package/generated/dsh-presets/minimal.patch.yml +17 -0
  29. package/generated/dsh-presets/ptc.patch.yml +8 -26
  30. package/generated/dsh-presets/standard.patch.yml +8 -26
  31. package/package.json +166 -146
@@ -0,0 +1,2951 @@
1
+ import { normalize } from "node:path";
2
+ //#region src/domain/transcript/content-blocks.ts
3
+ /** Match the Web JsonBlock serialized-payload bound. */
4
+ const FINALIZED_BLOCK_PAYLOAD_MAX_CHARS = 2e4;
5
+ /** The flat marker for one known attachment occurrence. */
6
+ function attachmentMarker(block) {
7
+ if (block.type === "image") return `🖼️ ${block.attachment.name ?? "image"}`;
8
+ if (block.type === "file") return `📄 ${block.attachment.name}`;
9
+ }
10
+ /**
11
+ * Build the lightweight ordered text projection used by user transcript
12
+ * search and loader-less rendering. Known attachments retain their positions;
13
+ * other non-text blocks remain in their structured content only.
14
+ */
15
+ function textWithAttachmentMarkers(blocks) {
16
+ let text = "";
17
+ let boundary = false;
18
+ for (const block of blocks) {
19
+ if (block.type === "text") {
20
+ if (boundary && text !== "" && !/\s$/.test(text) && !/^\s/.test(block.text)) text += " ";
21
+ boundary = false;
22
+ text += block.text;
23
+ continue;
24
+ }
25
+ const marker = attachmentMarker(block);
26
+ if (marker === void 0) continue;
27
+ if (text !== "" && !/\s$/.test(text)) text += " ";
28
+ text += marker;
29
+ boundary = true;
30
+ }
31
+ return text;
32
+ }
33
+ /** Sanitize and bound a provider-supplied block type for a heading. */
34
+ function safeBlockTypeLabel(type) {
35
+ if (typeof type !== "string") return "unknown";
36
+ const safeType = type.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
37
+ if (safeType === "") return "unknown";
38
+ return safeType.length <= 120 ? safeType : `${safeType.slice(0, 119)}…`;
39
+ }
40
+ /** Read and bound the type tag for the explicit unknown-block heading. */
41
+ function blockType(block) {
42
+ if (typeof block !== "object" || block === null) return "unknown";
43
+ return safeBlockTypeLabel(block.type);
44
+ }
45
+ /** Serialize one finalized block and keep its payload bounded. */
46
+ function boundedSerializedBlock(block) {
47
+ const serialized = JSON.stringify(block, null, 2) ?? String(block);
48
+ if (serialized.length <= 2e4) return serialized;
49
+ return `${serialized.slice(0, FINALIZED_BLOCK_PAYLOAD_MAX_CHARS)}\n… block payload truncated (${serialized.length} characters)`;
50
+ }
51
+ /**
52
+ * Explicit bounded fallback for a finalized block that has no first-class
53
+ * renderer. Callers should route known text/image/file/reasoning/tool-call
54
+ * blocks through their existing semantics before using this fallback.
55
+ */
56
+ function finalizedBlockFallbackText(block) {
57
+ return `Unknown block: ${blockType(block)}\n${boundedSerializedBlock(block)}`;
58
+ }
59
+ /** Render an open opaque block without inventing an unfinished payload. */
60
+ function openOpaqueBlockFallbackText(blockType) {
61
+ return `Unknown block: ${safeBlockTypeLabel(blockType)}\nnull`;
62
+ }
63
+ /** Whether a user message contains content the transcript should retain. */
64
+ function userBlocksVisibleNow(blocks) {
65
+ return blocks.some((block) => block.type !== "text" || block.text.trim() !== "");
66
+ }
67
+ //#endregion
68
+ //#region src/domain/transcript/semantics.ts
69
+ /** Classify one current TranscriptMessage without consulting display text. */
70
+ function classifyTranscriptMessage(message) {
71
+ switch (message.kind) {
72
+ case "user":
73
+ case "assistant": return { class: "conversation" };
74
+ case "thinking": return {
75
+ class: "process",
76
+ origin: "thinking"
77
+ };
78
+ case "tool":
79
+ if (message.origin === "turn-error" || message.origin === "turn-interrupted" || message.origin === "tool-not-started") return {
80
+ class: "attention",
81
+ origin: message.origin
82
+ };
83
+ return message.origin === void 0 ? { class: "process" } : {
84
+ class: "process",
85
+ origin: message.origin
86
+ };
87
+ case "system":
88
+ if (isSurfacedContext(message)) return {
89
+ class: "context",
90
+ origin: "injected-context"
91
+ };
92
+ if (message.origin === "turn-max-tokens") return {
93
+ class: "attention",
94
+ origin: message.origin
95
+ };
96
+ if (message.origin === "llm-retry") return {
97
+ class: "process",
98
+ origin: message.origin
99
+ };
100
+ return { class: "context" };
101
+ case "workflow": return {
102
+ class: "context",
103
+ origin: "workflow"
104
+ };
105
+ case "compaction": return {
106
+ class: "context",
107
+ origin: "compaction"
108
+ };
109
+ case "command": return {
110
+ class: "control",
111
+ origin: "command"
112
+ };
113
+ case "summary": return {
114
+ class: "context",
115
+ origin: "window-summary"
116
+ };
117
+ }
118
+ }
119
+ /**
120
+ * Whether a system row is an injected context boundary that Focus keeps
121
+ * visible when its Thought is collapsed. The fold's authoritative `context`
122
+ * marker intentionally covers unknown/future injection producers too.
123
+ */
124
+ function isSurfacedContext(message) {
125
+ return message.kind === "system" && message.context === true;
126
+ }
127
+ /**
128
+ * The tool names whose SETTLED card is surfaced human-interaction evidence —
129
+ * durable human decisions, not ordinary work. PR4's authoritative set is
130
+ * exactly these two: `ask_user_question` (the user's answers) and
131
+ * `exit_plan_mode` (the user's Plan review / approval result). Every other
132
+ * tool stays Process regardless of how rich its card looks or whether its
133
+ * execution happened to require an approval.
134
+ */
135
+ const SURFACED_INTERACTION_TOOL_NAMES = /* @__PURE__ */ new Set(["ask_user_question", "exit_plan_mode"]);
136
+ /** Whether one tool NAME belongs to the surfaced-interaction set, regardless of
137
+ * settled state. The fold uses this to keep such calls out of the turn's work
138
+ * accounting even while they are running. */
139
+ function isSurfacedInteractionToolName(name) {
140
+ return SURFACED_INTERACTION_TOOL_NAMES.has(name);
141
+ }
142
+ /**
143
+ * Whether one tool row is SETTLED human-interaction evidence rather than
144
+ * ordinary work-process evidence. The decision is source/tool identity only
145
+ * (kind + a name in {@link SURFACED_INTERACTION_TOOL_NAMES} + settled status) —
146
+ * never the display title or the result wording. A RUNNING question / plan
147
+ * review is owned by its active interaction panel and must NOT become a
148
+ * duplicate surfaced card. This orthogonal projection role deliberately does
149
+ * NOT add a fifth semantic class, and unknown tools stay Process.
150
+ */
151
+ function isSurfacedInteractionTool(message) {
152
+ return message.kind === "tool" && isSurfacedInteractionToolName(message.name) && message.status !== "running";
153
+ }
154
+ /**
155
+ * Post-turn replay evidence: the rows that MATERIALIZED after their owning
156
+ * turn's authoritative `turn/end` (weakly held sidecar — the fact dies with
157
+ * its row). The fold is the ONLY authority that can know this: a row's
158
+ * `turn`/`kind` alone cannot distinguish a durable row of a settled turn from
159
+ * a replay artifact that arrived afterwards.
160
+ *
161
+ * The provenance is exactly "this row was NEWLY created after the turn
162
+ * completed" — NEVER "this row was touched by a post-`turn/end` event". A
163
+ * `tool/result` that finds its own pending/running card still settles that
164
+ * card normally and leaves it fully legal Action evidence; only a newly
165
+ * created row (an orphan result or a fresh synthetic call card) earns the
166
+ * mark.
167
+ *
168
+ * Consumers share this ONE predicate so no surface invents its own fence:
169
+ * - the transcript keeps the row (search / Full / expanded Focus);
170
+ * - it is never Process aggregation evidence: it is excluded from the Action
171
+ * classifier, from Work-span membership, and from consecutive-read
172
+ * grouping (a group card is a synthesized object that could otherwise
173
+ * launder the provenance back into an aggregate).
174
+ */
175
+ const postTurnReplayEvidence = /* @__PURE__ */ new WeakSet();
176
+ /** Whether one row materialized after its owning turn's `turn/end` (see
177
+ * {@link postTurnReplayEvidence}). Presentation/persistence consumers use
178
+ * this to keep the row as transcript evidence while excluding it from the
179
+ * settled turn's Process/Action aggregates. */
180
+ function isPostTurnReplayEvidence(message) {
181
+ return postTurnReplayEvidence.has(message);
182
+ }
183
+ /** Mark one newly materialized row as post-turn replay evidence
184
+ * (fold-internal authority — called ONLY where a row is created while its
185
+ * owning turn is already `completed`). */
186
+ function markPostTurnReplayEvidence(message) {
187
+ postTurnReplayEvidence.add(message);
188
+ }
189
+ //#endregion
190
+ //#region src/domain/transcript/context-semantics.ts
191
+ /** One durable source narrowed to the readable-record shape; null for anything else. */
192
+ function asRecord(value) {
193
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
194
+ return value;
195
+ }
196
+ /** A record field read as a non-empty string, or null. */
197
+ function readString(record, key) {
198
+ const value = record[key];
199
+ return typeof value === "string" && value.length > 0 ? value : null;
200
+ }
201
+ /** Distinct non-empty `field` values of an array-valued source member, in first-seen order.
202
+ * The `seen` Set keeps a foreign/legacy log with a very large member array
203
+ * linear; an `includes()` scan here is an accidental O(n^2). */
204
+ function collect(source, member, field) {
205
+ const list = source[member];
206
+ if (!Array.isArray(list)) return [];
207
+ const seen = /* @__PURE__ */ new Set();
208
+ const names = [];
209
+ for (const entry of list) {
210
+ const record = asRecord(entry);
211
+ const value = record === null ? null : readString(record, field);
212
+ if (value !== null && !seen.has(value)) {
213
+ seen.add(value);
214
+ names.push(value);
215
+ }
216
+ }
217
+ return names;
218
+ }
219
+ /** A collected name list rendered as one label; null when the list is empty. */
220
+ function joined(names) {
221
+ return names.length > 0 ? names.join(", ") : null;
222
+ }
223
+ /**
224
+ * Project one durable message source onto its transcript role and producer
225
+ * name, exactly like the Web's contextProvenance: agent-instructions name
226
+ * their changed file paths, plugins their plugin id, skill invocations their
227
+ * skill name, session references their recalled labels; unknown kinds carry
228
+ * the kind itself.
229
+ * @param source - the logged user/message source, exactly as recorded.
230
+ * @returns the role and producer name to present for this context.
231
+ */
232
+ function contextProvenance(source) {
233
+ const record = asRecord(source);
234
+ const kind = record === null ? null : readString(record, "kind");
235
+ if (record === null || kind === null) return {
236
+ role: "inject",
237
+ label: null
238
+ };
239
+ switch (kind) {
240
+ case "session-reference": return {
241
+ role: "recall",
242
+ label: joined(collect(record, "references", "label")) ?? kind
243
+ };
244
+ case "agent-instructions": return {
245
+ role: "inject",
246
+ label: joined(collect(record, "changes", "path")) ?? kind
247
+ };
248
+ case "plugin": return {
249
+ role: "inject",
250
+ label: readString(record, "plugin") ?? kind
251
+ };
252
+ case "skill-invocation": return {
253
+ role: "inject",
254
+ label: readString(record, "name") ?? kind
255
+ };
256
+ default: return {
257
+ role: "inject",
258
+ label: kind
259
+ };
260
+ }
261
+ }
262
+ /** Whether a raw value is one of the declared context forms. */
263
+ function isTranscriptContextForm(value) {
264
+ return value === "instructions" || value === "catalog" || value === "snapshot" || value === "notice" || value === "relay" || value === "recall";
265
+ }
266
+ /**
267
+ * Project one logged context source onto the presentation-only metadata the
268
+ * transcript fold retains: the producer-declared `form` (the authority for
269
+ * presentation role and ambient clustering), the raw `kind`, a
270
+ * relay/notice sender, and the inject/recall role. This is the SINGLE
271
+ * parser of raw context sources; the fold and every projection consume its
272
+ * result. An absent/unknown form stays undefined — the caller must present
273
+ * the row as standalone generic Context.
274
+ * @param source - the logged user/message source, exactly as recorded.
275
+ */
276
+ function contextPresentation(source) {
277
+ const record = asRecord(source);
278
+ const role = contextProvenance(source).role;
279
+ if (record === null) return { role };
280
+ const kind = readString(record, "kind");
281
+ const form = record["form"];
282
+ const senderSessionId = readString(record, "senderSessionId");
283
+ return {
284
+ ...isTranscriptContextForm(form) ? { form } : {},
285
+ ...kind === null ? {} : { sourceKind: kind },
286
+ ...senderSessionId === null ? {} : { senderSessionId },
287
+ role
288
+ };
289
+ }
290
+ /** The ambient foundation forms: their adjacent rows may cluster. */
291
+ const AMBIENT_CONTEXT_FORMS = [
292
+ "instructions",
293
+ "catalog",
294
+ "snapshot"
295
+ ];
296
+ /** One injected Context row's presentation provenance, or undefined. */
297
+ function presentationOf(message) {
298
+ return message.kind === "system" ? message.contextPresentation : void 0;
299
+ }
300
+ /** The producer-declared form of one row, when recorded. */
301
+ function contextFormOf(message) {
302
+ return presentationOf(message)?.form;
303
+ }
304
+ /** Whether one row is ambient foundation (instructions/catalog/snapshot). */
305
+ function isAmbientContext(message) {
306
+ const form = contextFormOf(message);
307
+ return isSurfacedContext(message) && form !== void 0 && AMBIENT_CONTEXT_FORMS.includes(form);
308
+ }
309
+ /**
310
+ * The card-header icon SEMANTIC for one context injection, keyed by source
311
+ * kind so a reader can tell an instruction file from a skill catalog or a
312
+ * recalled session at a glance (the Web renders one browse icon for all of
313
+ * them). The glyph itself resolves through the concrete TUI palette at render
314
+ * time — fold state stores the semantic, never a concrete emoji/symbol, so an
315
+ * icon-style switch repaints ALREADY-FOLDED context cards immediately.
316
+ * @param source - the logged user/message source.
317
+ */
318
+ function contextIconSemantic(source) {
319
+ const record = asRecord(source);
320
+ switch (record === null ? null : readString(record, "kind")) {
321
+ case "agent-instructions": return "context-file";
322
+ case "skill-invocation": return "context-skill";
323
+ case "plugin": return readString(record ?? {}, "form") === "notice" ? "context-notice" : "context-plugin";
324
+ case "subagent-settled": return "context-notice";
325
+ case "session-reference": return "context-recall";
326
+ default: return "context-generic";
327
+ }
328
+ }
329
+ /** The producer's one-line notice summary, or null when absent. */
330
+ function contextSummary(source) {
331
+ const record = asRecord(source);
332
+ if (record === null) return null;
333
+ const summary = record["summary"];
334
+ return typeof summary === "string" && summary !== "" ? summary : null;
335
+ }
336
+ //#endregion
337
+ //#region src/runtime/process/disposal.ts
338
+ /**
339
+ * The ONE synchronous disposal primitive (M3-6 PR3 plan D1): attempt every
340
+ * cleanup step in caller-provided order, then surface the collected failure.
341
+ *
342
+ * The helper answers exactly one question — "attempt every synchronous
343
+ * cleanup step in this order, then surface collected failure(s)" — and owns
344
+ * nothing else: no async support, no ownership state, no logging, no retries
345
+ * and no fallback. Ownership slots stay inside the owning module; every
346
+ * orchestrator (bootstrap, TuiApp, SurfaceRuntime, the per-owner dispose
347
+ * methods) keeps its own order and passes it here.
348
+ *
349
+ * Failure contract:
350
+ * - zero failures: return;
351
+ * - exactly one failure: rethrow the EXACT original thrown value;
352
+ * - two or more failures: throw `AggregateError(failures, label)`.
353
+ *
354
+ * A throwing step never truncates its siblings.
355
+ * @module @xmoon76/dsh-pi-tui/runtime/process/disposal
356
+ */
357
+ /** Attempt every synchronous disposal step in order, surfacing failures. */
358
+ function runSyncDisposalSteps(label, steps) {
359
+ const failures = [];
360
+ for (const step of steps) try {
361
+ step();
362
+ } catch (error) {
363
+ failures.push(error);
364
+ }
365
+ if (failures.length === 1) throw failures[0];
366
+ if (failures.length > 1) throw new AggregateError(failures, label);
367
+ }
368
+ /**
369
+ * The same non-truncating attempt, for a batch that rolls back a PRIMARY failure:
370
+ * every rollback step is attempted in caller-provided order, then the PRIMARY
371
+ * value is thrown — aggregated by IDENTITY with the collected rollback failures,
372
+ * the primary first and the rollback values FLAT, in step order
373
+ * (`AggregateError([primary, r1, r2])`). One rollback obligation must never be
374
+ * skipped because an earlier one threw, and every value a step threw stays ONE
375
+ * entry — a user `AggregateError` is never flattened into its `.errors`. The step
376
+ * loop is inlined (not delegated to {@link runSyncDisposalSteps}, which would
377
+ * nest its own aggregate one level down).
378
+ */
379
+ function runSyncDisposalStepsWithPrimary(label, primary, steps) {
380
+ const failures = [];
381
+ for (const step of steps) try {
382
+ step();
383
+ } catch (error) {
384
+ failures.push(error);
385
+ }
386
+ if (failures.length === 0) throw primary;
387
+ throw new AggregateError([primary, ...failures], label);
388
+ }
389
+ //#endregion
390
+ //#region src/domain/media/format.ts
391
+ /**
392
+ * Human byte-size formatting for media limit messages (1024-based).
393
+ * @module @xmoon76/dsh-pi-tui/domain/media/format
394
+ */
395
+ function formatBytes(bytes) {
396
+ if (bytes < 1024) return `${bytes} B`;
397
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KiB`;
398
+ return `${(bytes / 1048576).toFixed(1)} MiB`;
399
+ }
400
+ //#endregion
401
+ //#region src/tui/presentation/terminal-text.ts
402
+ /**
403
+ * Untrusted-text projections for terminal-bound presentation.
404
+ *
405
+ * Source bytes, Session/Job facts and copy payloads stay authoritative and
406
+ * untouched; only the disposable display string is projected here. Two
407
+ * explicit policies exist:
408
+ *
409
+ * - {@link sanitizeDisplayText}: plain untrusted text (prose, labels,
410
+ * Markdown, command arguments). Every recognized ANSI/VT sequence and every
411
+ * unsafe C0/C1 character is removed. CRLF normalizes to LF, a lone CR to one
412
+ * ASCII space, TAB to three spaces. Nothing terminal-active survives.
413
+ * - {@link sanitizeDisplayLog}: untrusted log/terminal text. Same control
414
+ * removal, except strictly whitelisted complete CSI SGR (`ESC [ … m`) is
415
+ * retained and a lone CR becomes LF so progress frames read as log history
416
+ * instead of screen overwrite. The result ends in an app-owned `ESC[0m`
417
+ * whenever any SGR survives, so no source-controlled terminal state leaks
418
+ * past its display block.
419
+ *
420
+ * One linear-time scanner handles ESC/C1 introducers, whole CSI/OSC/DCS/SOS/
421
+ * PM/APC sequences (including unterminated tails) and the remaining control
422
+ * bytes. It is a pure `string -> string` projection: no cache, no process
423
+ * state, no side effects.
424
+ *
425
+ * @module @xmoon76/dsh-pi-tui/tui/presentation/terminal-text
426
+ */
427
+ const ESC = 27;
428
+ const BEL = 7;
429
+ const LF = 10;
430
+ const CR = 13;
431
+ const TAB = 9;
432
+ const DEL = 127;
433
+ const C1_CSI = 155;
434
+ const C1_ST = 156;
435
+ const C1_OSC = 157;
436
+ const C1_DCS = 144;
437
+ const C1_SOS = 152;
438
+ const C1_PM = 158;
439
+ const C1_APC = 159;
440
+ const BACKSLASH = 92;
441
+ /** The app-owned reset appended after a display block that kept any SGR. */
442
+ const SGR_RESET = "\x1B[0m";
443
+ /** SGR parameters permitted by the log whitelist (non-color attributes). */
444
+ const SGR_ATTRIBUTES = /* @__PURE__ */ new Set([
445
+ 0,
446
+ 1,
447
+ 2,
448
+ 3,
449
+ 4,
450
+ 7,
451
+ 9,
452
+ 22,
453
+ 23,
454
+ 24,
455
+ 27,
456
+ 29,
457
+ 39,
458
+ 49
459
+ ]);
460
+ /** True when any code unit needs the scanner (a C0 control, DEL or C1). */
461
+ function needsScan(source) {
462
+ for (let i = 0; i < source.length; i++) {
463
+ const code = source.charCodeAt(i);
464
+ if (code < 32 || code >= DEL && code <= 159) return true;
465
+ }
466
+ return false;
467
+ }
468
+ /** True for the standard 8/16-color foreground/background parameter set. */
469
+ function isStandardColor(value) {
470
+ return value >= 30 && value <= 37 || value >= 40 && value <= 47 || value >= 90 && value <= 97 || value >= 100 && value <= 107;
471
+ }
472
+ /**
473
+ * Validate one SGR parameter string (the bytes between `[` and `m`). Only
474
+ * decimal fields, the attribute set, standard colors and the `38/48;5;n` /
475
+ * `38/48;2;r;g;b` extended-color groups are accepted; every malformed,
476
+ * unknown, colon, empty or out-of-range parameter rejects the WHOLE sequence.
477
+ */
478
+ function isWhitelistedSgrParams(body) {
479
+ if (body === "") return true;
480
+ const parts = body.split(";");
481
+ for (const part of parts) {
482
+ if (part.length === 0 || part.length > 4) return false;
483
+ for (let k = 0; k < part.length; k++) {
484
+ const code = part.charCodeAt(k);
485
+ if (code < 48 || code > 57) return false;
486
+ }
487
+ }
488
+ let i = 0;
489
+ while (i < parts.length) {
490
+ const value = Number(parts[i]);
491
+ if (value === 38 || value === 48) {
492
+ const mode = parts[i + 1];
493
+ if (mode === "5") {
494
+ const n = parts[i + 2];
495
+ if (n === void 0 || Number(n) > 255) return false;
496
+ i += 3;
497
+ continue;
498
+ }
499
+ if (mode === "2") {
500
+ const r = parts[i + 2];
501
+ const g = parts[i + 3];
502
+ const b = parts[i + 4];
503
+ if (r === void 0 || g === void 0 || b === void 0) return false;
504
+ if (Number(r) > 255 || Number(g) > 255 || Number(b) > 255) return false;
505
+ i += 5;
506
+ continue;
507
+ }
508
+ return false;
509
+ }
510
+ if (!SGR_ATTRIBUTES.has(value) && !isStandardColor(value)) return false;
511
+ i++;
512
+ }
513
+ return true;
514
+ }
515
+ /**
516
+ * Consume one CSI sequence starting at its first parameter byte. Returns the
517
+ * index just past the sequence, plus the sequence itself when it is a complete
518
+ * `ESC [ … m` satisfying the log whitelist.
519
+ *
520
+ * A byte outside the parameter/intermediate/final classes ends the sequence
521
+ * early and resumes normal scanning at that byte; running off the end consumes
522
+ * the unterminated remainder.
523
+ */
524
+ function scanCsi(source, start, allowSgr) {
525
+ const len = source.length;
526
+ let j = start;
527
+ while (j < len) {
528
+ const code = source.charCodeAt(j);
529
+ if (code >= 32 && code <= 63) {
530
+ j++;
531
+ continue;
532
+ }
533
+ if (code >= 64 && code <= 126) {
534
+ if (allowSgr && code === 109) {
535
+ const body = source.slice(start, j);
536
+ if (isWhitelistedSgrParams(body)) return {
537
+ end: j + 1,
538
+ sgr: `\u001b[${body}m`
539
+ };
540
+ }
541
+ return { end: j + 1 };
542
+ }
543
+ break;
544
+ }
545
+ return { end: j };
546
+ }
547
+ /**
548
+ * Consume one string control (OSC/DCS/SOS/PM/APC) starting at its first
549
+ * payload byte. BEL terminates only OSC; `ESC \` and C1 ST terminate every
550
+ * string control. An unterminated string consumes to end of input.
551
+ */
552
+ function scanString(source, start, belTerminates) {
553
+ const len = source.length;
554
+ let j = start;
555
+ while (j < len) {
556
+ const code = source.charCodeAt(j);
557
+ if (belTerminates && code === BEL) return j + 1;
558
+ if (code === C1_ST) return j + 1;
559
+ if (code === ESC && j + 1 < len && source.charCodeAt(j + 1) === BACKSLASH) return j + 2;
560
+ j++;
561
+ }
562
+ return len;
563
+ }
564
+ /** Project one source string under either display policy. */
565
+ function project(source, keepSgr) {
566
+ if (!needsScan(source)) return source;
567
+ const len = source.length;
568
+ let out = "";
569
+ let keptSgr = false;
570
+ let i = 0;
571
+ while (i < len) {
572
+ const code = source.charCodeAt(i);
573
+ if (code === ESC) {
574
+ const next = i + 1 < len ? source.charCodeAt(i + 1) : -1;
575
+ if (next === 91) {
576
+ const csi = scanCsi(source, i + 2, keepSgr);
577
+ if (csi.sgr !== void 0) {
578
+ out += csi.sgr;
579
+ keptSgr = true;
580
+ }
581
+ i = csi.end;
582
+ continue;
583
+ }
584
+ if (next === 93) {
585
+ i = scanString(source, i + 2, true);
586
+ continue;
587
+ }
588
+ if (next === 80 || next === 88 || next === 94 || next === 95) {
589
+ i = scanString(source, i + 2, false);
590
+ continue;
591
+ }
592
+ if (next >= 32 && next <= 47) {
593
+ let j = i + 1;
594
+ while (j < len && source.charCodeAt(j) >= 32 && source.charCodeAt(j) <= 47) j++;
595
+ if (j < len && source.charCodeAt(j) >= 48 && source.charCodeAt(j) <= 126) j++;
596
+ i = j;
597
+ continue;
598
+ }
599
+ if (next >= 48 && next <= 126) {
600
+ i += 2;
601
+ continue;
602
+ }
603
+ i++;
604
+ continue;
605
+ }
606
+ if (code === C1_CSI) {
607
+ i = scanCsi(source, i + 1, false).end;
608
+ continue;
609
+ }
610
+ if (code === C1_OSC) {
611
+ i = scanString(source, i + 1, true);
612
+ continue;
613
+ }
614
+ if (code === C1_DCS || code === C1_SOS || code === C1_PM || code === C1_APC) {
615
+ i = scanString(source, i + 1, false);
616
+ continue;
617
+ }
618
+ if (code === LF) {
619
+ out += "\n";
620
+ i++;
621
+ continue;
622
+ }
623
+ if (code === CR) {
624
+ if (i + 1 < len && source.charCodeAt(i + 1) === LF) {
625
+ out += "\n";
626
+ i += 2;
627
+ continue;
628
+ }
629
+ out += keepSgr ? "\n" : " ";
630
+ i++;
631
+ continue;
632
+ }
633
+ if (code === TAB) {
634
+ out += " ";
635
+ i++;
636
+ continue;
637
+ }
638
+ if (code < 32 || code === DEL || code >= 128 && code <= 159) {
639
+ i++;
640
+ continue;
641
+ }
642
+ out += source[i];
643
+ i++;
644
+ }
645
+ if (keepSgr && keptSgr) out += SGR_RESET;
646
+ return out;
647
+ }
648
+ /**
649
+ * Project untrusted plain text onto terminal-safe display text: every escape
650
+ * sequence and unsafe control character is removed, CRLF becomes LF, a lone CR
651
+ * becomes one space and TAB becomes three spaces. Ordinary Unicode passes
652
+ * through verbatim and the exact input string is returned when no code unit
653
+ * needs projection.
654
+ */
655
+ function sanitizeDisplayText(source) {
656
+ return project(source, false);
657
+ }
658
+ /**
659
+ * Project untrusted log/terminal text onto terminal-safe display text:
660
+ * whitelisted complete SGR survives, a lone CR becomes LF so progress frames
661
+ * stay readable as history, and any retained SGR ends with an app-owned reset.
662
+ */
663
+ function sanitizeDisplayLog(source) {
664
+ return project(source, true);
665
+ }
666
+ //#endregion
667
+ //#region src/tui/presentation/lines.ts
668
+ /**
669
+ * Presentation-boundary projections shared by single-row renderers.
670
+ *
671
+ * @module @xmoon76/dsh-pi-tui/tui/presentation/lines
672
+ */
673
+ /**
674
+ * Project arbitrary presentation text onto exactly one physical terminal
675
+ * row.
676
+ *
677
+ * Raw/domain text must remain unchanged; call this only at a presentation
678
+ * boundary that semantically owns exactly one physical row (a renderer
679
+ * whose returned `string[]` element is budgeted as one terminal row).
680
+ * Width primitives (`visibleWidth`, `truncateToWidth`), marquee windowing,
681
+ * and hit-map construction are not newline sanitizers: an embedded CR/LF
682
+ * inside one array element escapes the row budget and the mouse hit map.
683
+ *
684
+ * Deliberately preserves ordinary/leading/trailing spaces (some
685
+ * presentation labels carry structural whitespace); it only collapses
686
+ * CR/LF row breaks into a single ordinary space, keeping the whole text
687
+ * visible instead of dropping every line after the first.
688
+ */
689
+ function singlePhysicalLine(text) {
690
+ return text.replace(/[\r\n]+/g, " ");
691
+ }
692
+ /**
693
+ * The stricter sibling of {@link singlePhysicalLine} for text that may also
694
+ * carry terminal escape sequences or other control characters (a Host
695
+ * session title/label): {@link sanitizeDisplayText} removes every recognized
696
+ * ANSI/VT sequence and unsafe control character (so a raw `\x1b[31m` can never
697
+ * leave visible `[31m` payload), then any remaining line break collapses to a
698
+ * space. TAB and CR are already normalized by the shared projection. The
699
+ * result is guaranteed to be a single physical row with no terminal-control
700
+ * content.
701
+ */
702
+ function sanitizedPhysicalLine(text) {
703
+ return sanitizeDisplayText(text).replace(/[\t\r\n]+/g, " ");
704
+ }
705
+ //#endregion
706
+ //#region src/tui/pickers/model-directory.ts
707
+ const IDENTITY_SEP = "\0";
708
+ const PROVIDER_DEFAULT = `${IDENTITY_SEP}provider-default`;
709
+ /** Full logical identity of a model row. Model ids are not globally unique. */
710
+ function modelIdentity(providerId, modelId) {
711
+ return `${providerId}${IDENTITY_SEP}${modelId}`;
712
+ }
713
+ /**
714
+ * Project the Host directory into identity-complete presentation rows. Pure:
715
+ * no terminal/component state, so the current/default/effort rules are unit
716
+ * testable without a rendering snapshot.
717
+ */
718
+ function projectModelDirectory(directory, current, sessionless) {
719
+ const models = [];
720
+ for (const group of directory.groups) for (const model of group.models) {
721
+ const matchesConfigured = current !== void 0 && current.provider === group.id && current.model === model.id;
722
+ const isCurrentModel = !sessionless && matchesConfigured;
723
+ const isDefault = directory.default.provider === group.id && directory.default.model === model.id;
724
+ models.push({
725
+ providerId: group.id,
726
+ providerName: group.name,
727
+ modelId: model.id,
728
+ modelName: model.name,
729
+ efforts: model.reasoning?.efforts ?? [],
730
+ ...model.reasoning?.defaultEffort === void 0 ? {} : { defaultEffort: model.reasoning.defaultEffort },
731
+ isCurrent: isCurrentModel,
732
+ isDefault,
733
+ ...isCurrentModel && current?.reasoningEffort !== void 0 ? { currentEffort: current.reasoningEffort } : {},
734
+ ...matchesConfigured && current?.reasoningEffort !== void 0 ? { configuredEffort: current.reasoningEffort } : {}
735
+ });
736
+ }
737
+ return {
738
+ models,
739
+ failures: directory.failures.map((failure) => ({
740
+ providerId: failure.id,
741
+ providerName: failure.name,
742
+ message: failure.message
743
+ }))
744
+ };
745
+ }
746
+ /** The picker-local effort CHOICES for one model, in cycle order. A model with
747
+ * NO effort metadata has none — the effort keys must be a true no-op there.
748
+ * The synthetic `provider default` joins the cycle only when the model
749
+ * declares efforts but no concrete default. */
750
+ function effortChoicesOf(row) {
751
+ if (row.efforts.length === 0) return [];
752
+ const efforts = row.efforts.map((effort) => ({
753
+ value: effort.id,
754
+ label: effort.name
755
+ }));
756
+ return row.defaultEffort === void 0 ? [{
757
+ value: PROVIDER_DEFAULT,
758
+ label: "Default"
759
+ }, ...efforts] : efforts;
760
+ }
761
+ /** The initial picker-local effort VALUE for one model: the configured/current
762
+ * explicit effort when advertised, else the model default, else the first
763
+ * candidate (provider default); `undefined` for a model with no effort
764
+ * metadata at all. */
765
+ function initialEffortOf(row, choices) {
766
+ if (choices.length === 0) return void 0;
767
+ const advertised = (value) => value !== void 0 && choices.some((choice) => choice.value === value) ? value : void 0;
768
+ return advertised(row.configuredEffort) ?? advertised(row.defaultEffort) ?? choices[0].value;
769
+ }
770
+ //#endregion
771
+ //#region src/tui/pickers/preset-display.ts
772
+ /** The shipped-preset display copy, shared by every preset picker surface.
773
+ *
774
+ * Fixed in English — the web surface's `BUILT_IN_PRESET_KEYS` mapping
775
+ * (`dsh-agent-preset-registry` display helpers), TUI-side. The shipped
776
+ * declarations publish no `name` (the official built-in classification), and
777
+ * their metadata language is not ours to control: mapping the known ids keeps
778
+ * the pickers English regardless of what the declarations say; everything else
779
+ * renders the declaration's own metadata. Names follow the upstream English
780
+ * locale.
781
+ * @module tui/pickers/preset-display
782
+ */
783
+ const BUILT_IN_PRESET_COPY = {
784
+ standard: {
785
+ name: "Standard mode",
786
+ description: "Full coding agent with file editing, shell, file and web search, skills, planning, goals, subagents, and workflows."
787
+ },
788
+ ptc: {
789
+ name: "PTC mode",
790
+ description: "All Standard mode capabilities, with tools exposed through the PTC mode SDK so the model can combine multi-step operations in one TypeScript program."
791
+ },
792
+ minimal: {
793
+ name: "Minimal mode",
794
+ description: "Minimal coding agent with a persistent shell."
795
+ },
796
+ cordis: {
797
+ name: "Creator mode",
798
+ description: "Built for creating custom agent presets, with all Standard mode capabilities plus runtime inspection, plugin experiments, and preset-authoring guidance."
799
+ }
800
+ };
801
+ /** Whether one roster row is a SHIPPED preset under the official 0.1.7
802
+ * classification: a known shipped id that publishes no `name` of its own.
803
+ * A declaration that names itself — even with a shipped id — owns its
804
+ * copy (the same rule as `isBuiltInPreset` upstream; kept local so the
805
+ * display layer carries no runtime import). */
806
+ function isBuiltInPresetRow(preset) {
807
+ return preset.name === void 0 && BUILT_IN_PRESET_COPY[preset.id] !== void 0;
808
+ }
809
+ /** Resolve one roster row's display copy: the TUI's fixed English copy for
810
+ * a shipped preset (official classification above), otherwise the preset's
811
+ * own published metadata — a user-authored copy is never translated. */
812
+ function presetDisplayText(preset) {
813
+ const builtIn = isBuiltInPresetRow(preset) ? BUILT_IN_PRESET_COPY[preset.id] : void 0;
814
+ if (builtIn !== void 0) return {
815
+ name: builtIn.name,
816
+ description: builtIn.description
817
+ };
818
+ return {
819
+ name: preset.name ?? preset.id,
820
+ ...preset.description === void 0 ? {} : { description: preset.description }
821
+ };
822
+ }
823
+ //#endregion
824
+ //#region src/tui/keybindings/hints.ts
825
+ /**
826
+ * The TSP renderer's FIXED parked-Question inspection chord (PR3-B B3 §3.8).
827
+ *
828
+ * The TSP interaction seat is not a Host command and owns no keymap action —
829
+ * `Alt+Q` is dispatched from the raw SDK key stream — so this label can never
830
+ * come from `keyHint`/`keysFor`. It also cannot go stale under a remap,
831
+ * because no remap exists for it. It lives HERE, with the key-label
832
+ * vocabulary, because the host-keybindings gate only sanctions key labels
833
+ * owned by this tree: a renderer module must not hard-code the chord itself.
834
+ */
835
+ const TSP_CONTINUED_INSPECTION_LABEL = "Alt+Q";
836
+ /**
837
+ * The History editor-seat tenant's ONE fixed-chord table (Phase 3B / B3-B).
838
+ *
839
+ * The seat is a per-surface COMPONENT contract, not a Host command: it owns no
840
+ * keymap action and no remap exists, so both the handler's KeyIds and the
841
+ * footer / key-badge labels are fixed. Keeping them in ONE table (and in this
842
+ * key-label authority, which is the sanctioned owner of fixed chords) means a
843
+ * hint and the handler it names can never drift into two string authorities.
844
+ */
845
+ const HISTORY_CHORDS = {
846
+ accept: {
847
+ keys: ["enter", "ctrl+j"],
848
+ label: "Enter"
849
+ },
850
+ scope: {
851
+ keys: ["tab"],
852
+ label: "Tab"
853
+ },
854
+ results: {
855
+ keys: [
856
+ "up",
857
+ "down",
858
+ "pageUp",
859
+ "pageDown"
860
+ ],
861
+ label: "↑/↓"
862
+ },
863
+ preview: {
864
+ keys: [
865
+ "alt+up",
866
+ "alt+down",
867
+ "alt+pageUp",
868
+ "alt+pageDown",
869
+ "alt+home",
870
+ "alt+end"
871
+ ],
872
+ label: "Alt+↑/↓"
873
+ },
874
+ copy: {
875
+ keys: ["alt+c"],
876
+ label: "Alt+C"
877
+ },
878
+ expand: {
879
+ keys: ["f2"],
880
+ label: "F2"
881
+ },
882
+ cancel: {
883
+ keys: ["escape", "ctrl+c"],
884
+ label: "Esc"
885
+ }
886
+ };
887
+ /** The display name of a bare (unmodified) key id. */
888
+ const BASE_KEY_LABELS = {
889
+ enter: "Enter",
890
+ escape: "Esc",
891
+ tab: "Tab",
892
+ space: "Space",
893
+ backspace: "Backspace",
894
+ delete: "Delete",
895
+ insert: "Insert",
896
+ home: "Home",
897
+ end: "End",
898
+ pageUp: "PageUp",
899
+ pageDown: "PageDown",
900
+ pageup: "PageUp",
901
+ pagedown: "PageDown",
902
+ up: "Up",
903
+ down: "Down",
904
+ left: "Left",
905
+ right: "Right",
906
+ "ctrl+[": "Ctrl+["
907
+ };
908
+ /** Format one KeyId as a human label (`ctrl+shift+f` → `Ctrl+Shift+F`). */
909
+ function formatKeyId(key) {
910
+ const parts = key.split("+");
911
+ const mods = [];
912
+ let base = "";
913
+ for (const part of parts) if (part === "ctrl") mods.push("Ctrl");
914
+ else if (part === "alt") mods.push("Alt");
915
+ else if (part === "shift") mods.push("Shift");
916
+ else if (part === "super") mods.push("Super");
917
+ else base = part;
918
+ const baseLabel = BASE_KEY_LABELS[base] ?? (base.length === 1 ? base.toUpperCase() : base);
919
+ return [...mods, baseLabel].join("+");
920
+ }
921
+ /** Format a `<leader>X` sequence label (`<leader>t` → `Leader T`). */
922
+ function formatLeaderSequence(completingKey) {
923
+ return `Leader ${formatKeyId(completingKey)}`;
924
+ }
925
+ /** The Job workspace's FIXED local keys (B1-C/B1-D, the same category as the
926
+ * History editor seat's labels below): the workspace owns NO keymap action for
927
+ * them — the page toggle and the current page's exact copy are screen-local,
928
+ * deliberately non-rebindable semantics — so they cannot come from `keyHint`,
929
+ * and they cannot lie either because no remap exists for them. The **key ids**
930
+ * live in this authority and the panel imports them for BOTH the handler and
931
+ * the hint, so an advertised key can never drift from the key that really acts
932
+ * (design language §7.1). */
933
+ const JOB_LOCAL_KEYS = {
934
+ /** Switch between the Output and Command pages, in both directions. */
935
+ switchPage: "tab",
936
+ /** Copy the current page's exact original. A BARE letter — the same key the
937
+ * Settings workspace's copy uses and the one the `[C]` affordance badges name —
938
+ * so the bar hint reads `c copy …` and badge and key agree (§4.1, §7.1). */
939
+ copy: "c"
940
+ };
941
+ /** Format one already-labelled key list for an ACTION-BAR HINT: a BARE
942
+ * unmodified letter stays lowercase (`s`, never `S`) because `S` reads as ⇧S in
943
+ * prose — the design language's key rule (§4.1). A modified chord keeps its
944
+ * formatted form (`Shift+S`), and a list keeps its OWN separator spacing
945
+ * (`s / Shift+S`, the same shape {@link formatKeyList} paints). */
946
+ function formatHintKeys(keys) {
947
+ return keys.split("/").map((part) => {
948
+ const core = part.trim();
949
+ const lowered = /^[A-Za-z]$/u.test(core) ? core.toLowerCase() : core;
950
+ return part.replace(core, lowered);
951
+ }).join("/");
952
+ }
953
+ /** Canonicalize one user query for both metadata matching and Host search. */
954
+ function sanitizeSessionSearchInput(value) {
955
+ const trimmed = value.replace(/\0/g, "").trim();
956
+ if (trimmed.length <= 500) return trimmed;
957
+ const truncated = trimmed.slice(0, 500);
958
+ const last = truncated.charCodeAt(499);
959
+ return last >= 55296 && last <= 56319 ? truncated.slice(0, 499) : truncated;
960
+ }
961
+ /** Metadata-only membership; content membership belongs to SessionReader.search(). */
962
+ function sessionRowMatchesQuery(row, query) {
963
+ const needle = query.toLowerCase();
964
+ return row.id.toLowerCase().includes(needle) || (row.title ?? "").toLowerCase().includes(needle) || (row.cwd ?? "").toLowerCase().includes(needle) || (row.preset ?? "").toLowerCase().includes(needle);
965
+ }
966
+ /** Lexical workspace equality; absent and empty roots match nothing. */
967
+ function sameWorkspace(a, b) {
968
+ if (a === void 0 || b === void 0 || a === "" || b === "") return false;
969
+ const strip = (path) => {
970
+ let end = path.length;
971
+ while (end > 1 && (path[end - 1] === "/" || path[end - 1] === "\\")) end -= 1;
972
+ return path.slice(0, end);
973
+ };
974
+ return normalize(strip(a)) === normalize(strip(b));
975
+ }
976
+ /** Parent-first lineage, preserving newest-first order at every level. */
977
+ function buildSessionTree(rows) {
978
+ const known = new Set(rows.map((row) => row.id));
979
+ const children = /* @__PURE__ */ new Map();
980
+ const roots = [];
981
+ for (const row of rows) if (row.parentSession !== void 0 && known.has(row.parentSession)) {
982
+ const list = children.get(row.parentSession);
983
+ if (list === void 0) children.set(row.parentSession, [row]);
984
+ else list.push(row);
985
+ } else roots.push(row);
986
+ const result = [];
987
+ const placed = /* @__PURE__ */ new Set();
988
+ const place = (row, depth) => {
989
+ if (placed.has(row.id)) return;
990
+ placed.add(row.id);
991
+ result.push({
992
+ row,
993
+ depth
994
+ });
995
+ for (const child of children.get(row.id) ?? []) place(child, depth + 1);
996
+ };
997
+ for (const root of roots) place(root, 0);
998
+ for (const row of rows) if (!placed.has(row.id)) place(row, 0);
999
+ return result;
1000
+ }
1001
+ //#endregion
1002
+ //#region src/tui/pickers/sessions.ts
1003
+ /**
1004
+ * Session-picker support for `/sessions`: pure row assembly and
1005
+ * presentation. The row model mirrors the kimicode web session rail — a
1006
+ * short id, a relative age, an optional title, and a workspace group —
1007
+ * rendered as one line per session in the TUI picker.
1008
+ *
1009
+ * This module is PURE presentation: it never touches `$DSH_HOME`, never
1010
+ * stats or reads session logs, and never folds a title — Host-owned session
1011
+ * derived state (titles, presets) arrives through the `SessionReader`
1012
+ * projection port (`src/runtime/session-reader-port.ts`); the Direct
1013
+ * adapter in `src/runtime/direct/` owns the official DSH projection,
1014
+ * cache, and observation semantics.
1015
+ * @module @xmoon76/dsh-pi-tui/tui/pickers/sessions
1016
+ */
1017
+ /** Strip the `session-` prefix and keep the first 8 characters, like the
1018
+ * kimicode card's short id. */
1019
+ function shortSessionId(id) {
1020
+ return id.replace(/^session[-_]/i, "").slice(0, 8);
1021
+ }
1022
+ /** kimicode-style workspace key: the last two path segments, or a placeholder.
1023
+ * The cwd is a Host/persistence boundary value — the group header is
1024
+ * rendered straight to the terminal, so the output is sanitized here (the
1025
+ * single group-derivation point covers the browse AND search views). */
1026
+ function workspaceKey(cwd) {
1027
+ if (cwd === void 0 || cwd === "") return "(no workspace)";
1028
+ return sanitizeTerminalText(cwd.split("/").slice(-2).join("/"));
1029
+ }
1030
+ /** Compact relative age of a session ("now", "2m", "3h", "5d", "3mo", "1y"). */
1031
+ function formatSessionAge(createdAt, now = Date.now()) {
1032
+ const diff = now - createdAt;
1033
+ if (diff < 0) return "now";
1034
+ const seconds = Math.floor(diff / 1e3);
1035
+ if (seconds < 60) return "now";
1036
+ const minutes = Math.floor(seconds / 60);
1037
+ if (minutes < 60) return `${minutes}m`;
1038
+ const hours = Math.floor(minutes / 60);
1039
+ if (hours < 24) return `${hours}h`;
1040
+ const days = Math.floor(hours / 24);
1041
+ if (days < 30) return `${days}d`;
1042
+ const months = Math.floor(days / 30);
1043
+ if (months < 12) return `${months}mo`;
1044
+ return `${Math.floor(months / 12)}y`;
1045
+ }
1046
+ /** Strip terminal control characters from untrusted text before it enters
1047
+ * the picker presentation. The shared presentation projection removes every
1048
+ * complete ANSI/OSC/APC sequence (including C1 8-bit forms and unterminated
1049
+ * tails), then every remaining C0 control, DEL and C1 control, and folds the
1050
+ * result onto exactly one physical row: the picker writes descriptions
1051
+ * straight to the terminal, and a terminal decoding UTF-8 interprets C1 code
1052
+ * points as control sequences, not text. Host snippets may carry persisted
1053
+ * control bytes (message/tool output) — a raw ESC/OSC would be interpreted,
1054
+ * not displayed. */
1055
+ function sanitizeTerminalText(value) {
1056
+ return sanitizedPhysicalLine(value);
1057
+ }
1058
+ /** Assemble one session row for the picker, marking the current session.
1059
+ * @param indent - tree depth for the "All" category: rows hang under their
1060
+ * parent with a `└─` prefix so subagent lineage reads at a glance.
1061
+ * @param contentHit - optional Host content-search hit for this row: the
1062
+ * snippet joins the description so the local filter (which matches
1063
+ * descriptions) surfaces content-only hits.
1064
+ */
1065
+ function sessionPickerItem(row, currentId, indent = 0, contentHit) {
1066
+ const marker = row.id === currentId ? "● " : "";
1067
+ const treePrefix = indent <= 0 ? "" : `${" ".repeat(indent)}└─ `;
1068
+ const meta = [sanitizeTerminalText(shortSessionId(row.id)), formatSessionAge(row.createdAt ?? row.updatedAt)];
1069
+ if (row.origin === "subagent") meta.push("sub");
1070
+ if (row.parentSession !== void 0) meta.push("fork");
1071
+ if (row.preset !== void 0) meta.push(`preset:${sanitizeTerminalText(row.preset)}`);
1072
+ if (row.live) meta.push("live");
1073
+ if (contentHit !== void 0) meta.push(`…${sanitizeTerminalText(contentHit.snippet)}…`);
1074
+ return {
1075
+ value: row.id,
1076
+ label: `${treePrefix}${marker}${row.title === void 0 ? sanitizeTerminalText(shortSessionId(row.id)) : sanitizeTerminalText(row.title)}`,
1077
+ description: meta.join(" · "),
1078
+ group: workspaceKey(row.cwd)
1079
+ };
1080
+ }
1081
+ /** Assemble one SEARCH-projection row: the browse presentation plus the
1082
+ * workspace in the searchable description. The search projection's
1083
+ * membership considers cwd, and the SelectList's substring filter searches
1084
+ * value/label/description only (never the group header) — so the search
1085
+ * view must carry the cwd in the description, or a cwd query would match
1086
+ * the union yet stay invisible. */
1087
+ function sessionSearchItem(row, currentId, indent = 0, contentHit) {
1088
+ const item = sessionPickerItem(row, currentId, indent, contentHit);
1089
+ if (row.cwd !== void 0 && row.cwd !== "") item.description = `${item.description} · ${sanitizeTerminalText(row.cwd)}`;
1090
+ return item;
1091
+ }
1092
+ /**
1093
+ * Split a session picker label into its FIXED presentation prefix (tree
1094
+ * connector + current-session marker) and the marqueeable title (plan
1095
+ * §7.7): the selected-row marquee scrolls only the title — the lineage
1096
+ * prefix and the `●` marker are layout regions that never move. The
1097
+ * derivation mirrors {@link sessionPickerItem}'s construction (never
1098
+ * guesses arbitrary prefixes).
1099
+ */
1100
+ function sessionLabelParts(label) {
1101
+ const tree = /^((?: )+└─ )/.exec(label)?.[1] ?? "";
1102
+ const rest = label.slice(tree.length);
1103
+ const marker = rest.startsWith("● ") ? "● " : "";
1104
+ return {
1105
+ prefix: tree + marker,
1106
+ title: rest.slice(marker.length)
1107
+ };
1108
+ }
1109
+ /**
1110
+ * Resolve one session row for a resume query: an exact id, a
1111
+ * `session-`-prefixed prefix, or a short-id prefix. Rows are newest-first,
1112
+ * so the first match is the most recent candidate.
1113
+ * @param rows - the picker rows, newest first.
1114
+ * @param query - the resume query (trimmed).
1115
+ * @returns the matching row, or undefined.
1116
+ */
1117
+ function findSessionMatch(rows, query) {
1118
+ const bare = query.replace(/^session[-_]/i, "");
1119
+ return rows.find((row) => row.id === query || row.id.startsWith(`session-${bare}`) || shortSessionId(row.id).startsWith(bare));
1120
+ }
1121
+ //#endregion
1122
+ //#region src/domain/media/file-summary.ts
1123
+ /**
1124
+ * Transport/UI-neutral textual summary of a durable file attachment (TS8-D
1125
+ * move out of the legacy root `src/content-block-presentation.ts`).
1126
+ *
1127
+ * The summary is media vocabulary, not transcript semantics, so it lives in
1128
+ * `domain/media/**` — that keeps `domain/transcript/**` from importing another
1129
+ * domain subtree while preserving ONE file-summary formatter for the PiTui
1130
+ * attachment card, pending presentation, tool presentation and the Markdown
1131
+ * exporter.
1132
+ * @module @xmoon76/dsh-pi-tui/domain/media/file-summary
1133
+ */
1134
+ /** Render a FileBlock attachment without exposing its opaque storage id. */
1135
+ function fileAttachmentSummary(attachment) {
1136
+ return `📄 ${attachment.name} · ${formatBytes(attachment.bytes)}`;
1137
+ }
1138
+ //#endregion
1139
+ //#region src/tui/transcript/tool-presentation.ts
1140
+ /** Figma row titles per variant (design literals, not translatable copy). */
1141
+ const VARIANT_TITLES = {
1142
+ search: "Search",
1143
+ read: "Read",
1144
+ bash: "Bash",
1145
+ write: "Write",
1146
+ edit: "Edit",
1147
+ code: "Code",
1148
+ others: "Tool call"
1149
+ };
1150
+ /**
1151
+ * Known tool name -> variant (the Web's TOOL_VARIANTS; cordis_define is
1152
+ * deliberately absent there too - a keyed toolview replaces the generic row).
1153
+ */
1154
+ const TOOL_VARIANTS = {
1155
+ bash: "bash",
1156
+ pwsh: "bash",
1157
+ read: "read",
1158
+ web_fetch: "read",
1159
+ web_search: "search",
1160
+ grep: "search",
1161
+ glob: "search",
1162
+ write: "write",
1163
+ edit: "edit",
1164
+ run_code: "code",
1165
+ skill: "read",
1166
+ cordis_package_inspect: "read",
1167
+ cordis_runtime_inspect: "read",
1168
+ cordis_run: "others",
1169
+ cordis_stop: "others",
1170
+ cordis_undefine: "others"
1171
+ };
1172
+ /** Tool-owned titles that refine a generic row variant without replacing it. */
1173
+ const TOOL_TITLES = {
1174
+ cordis_package_inspect: "Inspect",
1175
+ cordis_runtime_inspect: "Inspect",
1176
+ cordis_run: "Run Cordis Plugin",
1177
+ cordis_stop: "Stop Cordis Plugin",
1178
+ cordis_undefine: "Remove Cordis Plugin",
1179
+ pwsh: "Pwsh",
1180
+ skill: "Load skill"
1181
+ };
1182
+ /**
1183
+ * TUI-local titles for synthetic cards the session log produces without a
1184
+ * registry definition (local `!` shell runs, workflow bookkeeping, failure
1185
+ * lines). Same refinement mechanism as TOOL_TITLES; without these the cards
1186
+ * would fall into the generic Tool call title and lose their identity.
1187
+ */
1188
+ const TUI_TOOL_TITLES = {
1189
+ shell: "Shell",
1190
+ subagent: "Subagent",
1191
+ workflow: "Workflow",
1192
+ "workflow-member": "Workflow Agent",
1193
+ error: "Error",
1194
+ interrupted: "Interrupted",
1195
+ ask_user_question: "Question",
1196
+ get_goal: "Read Goal",
1197
+ create_goal: "Create Goal",
1198
+ update_goal: "Update Goal"
1199
+ };
1200
+ /** The goal tool family (all three share the `{"goal":…}` result shape). */
1201
+ const GOAL_TOOL_NAMES = /* @__PURE__ */ new Set([
1202
+ "get_goal",
1203
+ "create_goal",
1204
+ "update_goal"
1205
+ ]);
1206
+ /**
1207
+ * Tools whose folded result preview must never leak the raw result JSON
1208
+ * (web parity: the web's folded row shows only the args summary, never the
1209
+ * result). The TUI keeps its result-preview row but shows a parsed summary
1210
+ * instead — and nothing at all when the result cannot be parsed.
1211
+ *
1212
+ * `ralph`'s render already leads with a friendly line ("Ralph worker
1213
+ * reported completion after N rounds.") before the JSON report, so its
1214
+ * summary IS that first line. The agent-team family is deliberately NOT in
1215
+ * the set: it is experimental (not in the production bundle) and two of its
1216
+ * tools (`send_message`, `interrupt_agent`) share names with subagent tools
1217
+ * whose render text is friendly — a name-keyed set cannot tell them apart.
1218
+ */
1219
+ const FOLDED_JSON_RESULT_TOOLS = /* @__PURE__ */ new Set([
1220
+ "ralph",
1221
+ "schedule_create",
1222
+ "schedule_list",
1223
+ "schedule_delete",
1224
+ "cordis_inspect_list",
1225
+ "cordis_inspect_query",
1226
+ "cordis_inspect_self"
1227
+ ]);
1228
+ /** Parse a result text as JSON, tolerating a friendly prefix line before
1229
+ * the JSON document (e.g. ralph's "…\nFinal report:\n{…}"). */
1230
+ function parseJsonValue(text) {
1231
+ try {
1232
+ return JSON.parse(text);
1233
+ } catch {}
1234
+ const brace = text.indexOf("{");
1235
+ const bracket = text.indexOf("[");
1236
+ const start = bracket !== -1 && (brace === -1 || bracket < brace) ? bracket : brace;
1237
+ if (start > 0) try {
1238
+ return JSON.parse(text.slice(start));
1239
+ } catch {
1240
+ return;
1241
+ }
1242
+ }
1243
+ /** A non-empty string field, or undefined. */
1244
+ function stringField(value) {
1245
+ return typeof value === "string" && value !== "" ? value : void 0;
1246
+ }
1247
+ /**
1248
+ * The folded preview summary for one of {@link FOLDED_JSON_RESULT_TOOLS}:
1249
+ * a short human phrase derived from the parsed result JSON. Returns
1250
+ * undefined when nothing useful can be derived — the caller then shows NO
1251
+ * folded result preview (web parity), never the raw JSON.
1252
+ * @param name - the tool name.
1253
+ * @param text - the settled result text.
1254
+ */
1255
+ function foldedResultSummaryFor(name, text) {
1256
+ if (name === "ralph") {
1257
+ const line = firstLine(text);
1258
+ if (line !== "" && !line.startsWith("{")) return line;
1259
+ const parsed = parseJsonValue(text);
1260
+ if (typeof parsed === "object" && parsed !== null) {
1261
+ const record = parsed;
1262
+ const status = stringField(record.status);
1263
+ const rounds = typeof record.roundsStarted === "number" ? String(record.roundsStarted) : void 0;
1264
+ const parts = [status, rounds === void 0 ? void 0 : `${rounds} rounds`].filter((part) => part !== void 0);
1265
+ return parts.length === 0 ? void 0 : parts.join(" · ");
1266
+ }
1267
+ return;
1268
+ }
1269
+ const parsed = parseJsonValue(text);
1270
+ if (name === "schedule_list") {
1271
+ if (Array.isArray(parsed)) return parsed.length === 0 ? "no scheduled jobs" : `${parsed.length} scheduled`;
1272
+ if (typeof parsed === "object" && parsed !== null) return stringField(parsed.code);
1273
+ return;
1274
+ }
1275
+ if (name === "schedule_create") {
1276
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1277
+ const record = parsed;
1278
+ const parts = [stringField(record.kind), stringField(record.state)].filter((part) => part !== void 0);
1279
+ return parts.length === 0 ? void 0 : parts.join(" · ");
1280
+ }
1281
+ if (name === "schedule_delete") {
1282
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1283
+ const record = parsed;
1284
+ if (record.deleted === true) return "deleted";
1285
+ if (record.deleted === false) return "not found";
1286
+ return stringField(record.code);
1287
+ }
1288
+ if (name === "cordis_inspect_list") {
1289
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1290
+ const providers = parsed.providers;
1291
+ if (Array.isArray(providers)) return providers.length === 0 ? "no providers" : `${providers.length} providers`;
1292
+ return;
1293
+ }
1294
+ if (name === "cordis_inspect_query") {
1295
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1296
+ const record = parsed;
1297
+ const parts = [
1298
+ stringField(record.platform),
1299
+ stringField(record.provider),
1300
+ stringField(record.method)
1301
+ ].filter((part) => part !== void 0);
1302
+ return parts.length === 0 ? void 0 : parts.join(" · ");
1303
+ }
1304
+ if (name === "cordis_inspect_self") {
1305
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1306
+ const mode = stringField(parsed.mode);
1307
+ return mode === void 0 ? void 0 : `mode ${mode}`;
1308
+ }
1309
+ }
1310
+ function nonBlankString(value) {
1311
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
1312
+ }
1313
+ /** Parse standard and Agent Teams-compatible send_message arguments. */
1314
+ function sendMessageCallPresentation(argsRaw) {
1315
+ const parsed = parseArgs(argsRaw);
1316
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
1317
+ const args = parsed;
1318
+ const target = nonBlankString(args.agent_id) ?? nonBlankString(args.target);
1319
+ if (target === void 0 || typeof args.message !== "string") return void 0;
1320
+ return {
1321
+ target,
1322
+ message: args.message
1323
+ };
1324
+ }
1325
+ /** Parse standard and Agent Teams-compatible interrupt_agent arguments. */
1326
+ function interruptAgentCallPresentation(argsRaw) {
1327
+ const parsed = parseArgs(argsRaw);
1328
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
1329
+ const args = parsed;
1330
+ const target = nonBlankString(args.agent_id) ?? nonBlankString(args.target);
1331
+ return target === void 0 ? void 0 : { target };
1332
+ }
1333
+ /** Parse the terminal_send identity and payload. */
1334
+ function terminalSendCallPresentation(argsRaw) {
1335
+ const parsed = parseArgs(argsRaw);
1336
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
1337
+ const args = parsed;
1338
+ const sessionId = nonBlankString(args.sessionId);
1339
+ if (sessionId === void 0 || typeof args.text !== "string") return void 0;
1340
+ if (args.submit !== void 0 && typeof args.submit !== "boolean") return void 0;
1341
+ if (args.run_in_background !== void 0 && typeof args.run_in_background !== "boolean") return void 0;
1342
+ return {
1343
+ sessionId,
1344
+ text: args.text
1345
+ };
1346
+ }
1347
+ /** Parse list_agents scope without consulting any live registry. */
1348
+ function listAgentsCallPresentation(argsRaw) {
1349
+ const parsed = argsRaw.trim() === "" ? {} : parseArgs(argsRaw);
1350
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
1351
+ const scope = parsed.scope;
1352
+ if (scope === void 0) return { scope: "children" };
1353
+ return scope === "children" || scope === "descendants" ? { scope } : void 0;
1354
+ }
1355
+ /** Parse the display-only file declarations from a `present` call. */
1356
+ function presentCallPresentation(argsRaw) {
1357
+ const parsed = parseArgs(argsRaw);
1358
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
1359
+ const files = parsed.files;
1360
+ if (!Array.isArray(files)) return void 0;
1361
+ const presented = [];
1362
+ for (const file of files) {
1363
+ if (typeof file !== "object" || file === null || Array.isArray(file)) return void 0;
1364
+ const value = file;
1365
+ if (typeof value.path !== "string" || value.path.trim() === "") return void 0;
1366
+ if (value.description !== void 0 && typeof value.description !== "string") return void 0;
1367
+ presented.push({
1368
+ path: value.path,
1369
+ ...value.description === void 0 ? {} : { description: value.description }
1370
+ });
1371
+ }
1372
+ return { files: presented };
1373
+ }
1374
+ /** Count one structured list_agents snapshot. */
1375
+ function summarizeAgentEntries(entries) {
1376
+ let running = 0;
1377
+ let idle = 0;
1378
+ let ready = 0;
1379
+ let diagnostics = 0;
1380
+ for (const entry of entries) {
1381
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
1382
+ diagnostics += 1;
1383
+ continue;
1384
+ }
1385
+ const value = entry;
1386
+ if (value.kind === "diagnostic") {
1387
+ diagnostics += 1;
1388
+ continue;
1389
+ }
1390
+ if (value.kind !== void 0 && value.kind !== "child" && value.kind !== "agent") {
1391
+ diagnostics += 1;
1392
+ continue;
1393
+ }
1394
+ switch (value.status) {
1395
+ case "running":
1396
+ case "provisioning":
1397
+ running += 1;
1398
+ break;
1399
+ case "idle":
1400
+ idle += 1;
1401
+ break;
1402
+ case "ready":
1403
+ case "inactive":
1404
+ ready += 1;
1405
+ break;
1406
+ default: diagnostics += 1;
1407
+ }
1408
+ }
1409
+ return {
1410
+ total: running + idle + ready + diagnostics,
1411
+ running,
1412
+ idle,
1413
+ ready,
1414
+ ...diagnostics === 0 ? {} : { diagnostics }
1415
+ };
1416
+ }
1417
+ /** Parse both the structured snapshot and the standard rendered text. */
1418
+ function summarizeAgentListResult(text) {
1419
+ const parsed = parseJsonValue(text);
1420
+ if (Array.isArray(parsed)) return summarizeAgentEntries(parsed);
1421
+ const trimmed = text.trim();
1422
+ if (trimmed === "(no subagents)") return {
1423
+ total: 0,
1424
+ running: 0,
1425
+ idle: 0,
1426
+ ready: 0
1427
+ };
1428
+ if (trimmed === "") return void 0;
1429
+ let running = 0;
1430
+ let idle = 0;
1431
+ let ready = 0;
1432
+ let diagnostics = 0;
1433
+ let matched = 0;
1434
+ for (const line of trimmed.split(/\r\n|\r|\n/)) {
1435
+ if (/\[running\](?:\s|$)/.test(line)) {
1436
+ running += 1;
1437
+ matched += 1;
1438
+ continue;
1439
+ }
1440
+ if (/\[idle\](?:\s|$)/.test(line)) {
1441
+ idle += 1;
1442
+ matched += 1;
1443
+ continue;
1444
+ }
1445
+ if (/\[ready\](?:\s|$)/.test(line)) {
1446
+ ready += 1;
1447
+ matched += 1;
1448
+ continue;
1449
+ }
1450
+ if (/\[diagnostic:[^\]]+\]/.test(line)) {
1451
+ diagnostics += 1;
1452
+ matched += 1;
1453
+ continue;
1454
+ }
1455
+ if (/\[[a-z][^\]]*\]/.test(line)) {
1456
+ diagnostics += 1;
1457
+ matched += 1;
1458
+ }
1459
+ }
1460
+ if (matched === 0) return void 0;
1461
+ return {
1462
+ total: running + idle + ready + diagnostics,
1463
+ running,
1464
+ idle,
1465
+ ready,
1466
+ ...diagnostics === 0 ? {} : { diagnostics }
1467
+ };
1468
+ }
1469
+ /** Format a list snapshot without treating diagnostics as agents. */
1470
+ function formatAgentListSummary(summary) {
1471
+ if (summary.total === 0) return "no subagents";
1472
+ const agents = summary.running + summary.idle + summary.ready;
1473
+ const diagnostics = summary.diagnostics ?? 0;
1474
+ const parts = [diagnostics > 0 ? `${summary.total} ${summary.total === 1 ? "entry" : "entries"}` : `${agents} ${agents === 1 ? "agent" : "agents"}`];
1475
+ if (summary.running > 0) parts.push(`${summary.running} running`);
1476
+ if (summary.idle > 0) parts.push(`${summary.idle} idle`);
1477
+ if (summary.ready > 0) parts.push(`${summary.ready} ready`);
1478
+ if (diagnostics > 0) parts.push(`${diagnostics} ${diagnostics === 1 ? "diagnostic" : "diagnostics"}`);
1479
+ return parts.join(" · ");
1480
+ }
1481
+ /** A compact result line for a non-JSON action acknowledgement/error. */
1482
+ function firstActionResultDetail(text) {
1483
+ const trimmed = text.trim();
1484
+ if (trimmed === "") return void 0;
1485
+ const parsed = parseJsonValue(text);
1486
+ if (typeof parsed === "string") return firstLine(parsed);
1487
+ if (parsed !== void 0 || /^[\[{]/.test(trimmed)) return void 0;
1488
+ return firstLine(trimmed);
1489
+ }
1490
+ /** Pull a human detail out of a structured action error without raw JSON. */
1491
+ function actionErrorDetail(text) {
1492
+ const parsed = parseJsonValue(text);
1493
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
1494
+ const value = parsed;
1495
+ const code = nonBlankString(value.code);
1496
+ const message = nonBlankString(value.message ?? value.error ?? value.detail ?? value.reason);
1497
+ if (code !== void 0 && message !== void 0) return `${code}: ${message}`;
1498
+ return message ?? code;
1499
+ }
1500
+ return firstActionResultDetail(text) ?? (text.trim() === "" ? void 0 : firstLine(text.trim()));
1501
+ }
1502
+ /** Combine a structured error identity with any safe human detail. */
1503
+ function actionErrorResult(text, options) {
1504
+ const identity = options.error === void 0 ? void 0 : `${options.error.name}: ${options.error.code}`;
1505
+ const detail = actionErrorDetail(text);
1506
+ return identity === void 0 ? detail : detail === void 0 ? identity : `${identity}: ${detail}`;
1507
+ }
1508
+ const ACKNOWLEDGEMENT_STATUSES = /* @__PURE__ */ new Set([
1509
+ "accepted",
1510
+ "completed",
1511
+ "delivered",
1512
+ "ok",
1513
+ "sent",
1514
+ "success"
1515
+ ]);
1516
+ /** Derive a meaningful result for one action tool; receipt-only results vanish. */
1517
+ function actionResultSummary(kind, text) {
1518
+ const trimmed = text.trim();
1519
+ if (trimmed === "") return void 0;
1520
+ const parsed = parseJsonValue(text);
1521
+ if (kind === "terminal_send") {
1522
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
1523
+ const value = parsed;
1524
+ if (nonBlankString(value.status)?.toLowerCase() === "queued") return "queued";
1525
+ if (value.kind === "background") {
1526
+ const jobId = nonBlankString(value.jobId);
1527
+ return jobId === void 0 ? void 0 : `started background job ${jobId}`;
1528
+ }
1529
+ return;
1530
+ }
1531
+ const value = typeof parsed === "string" ? firstLine(parsed) : firstLine(trimmed);
1532
+ if (/^started background job\b/i.test(value)) return value;
1533
+ return /\bqueued\b/i.test(value) ? "queued" : void 0;
1534
+ }
1535
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
1536
+ const value = parsed;
1537
+ const status = nonBlankString(value.status)?.toLowerCase();
1538
+ if (status === "queued") return "queued";
1539
+ if (status !== void 0 && !ACKNOWLEDGEMENT_STATUSES.has(status)) return status;
1540
+ if (kind === "interrupt_agent") {
1541
+ const previous = nonBlankString(value.previousStatus);
1542
+ if (previous !== void 0) return `was ${previous}`;
1543
+ }
1544
+ return;
1545
+ }
1546
+ const value = typeof parsed === "string" ? firstLine(parsed) : firstLine(trimmed);
1547
+ if (value === "") return void 0;
1548
+ if (kind === "send_message" && /^message\s+(?:delivered|sent|accepted)\b/i.test(value)) return /\bqueued\b/i.test(value) ? "queued" : void 0;
1549
+ if (kind === "interrupt_agent" && /^interrupt\s+requested\s+for\s+agent\b/i.test(value)) return void 0;
1550
+ if (/^(?:ok|accepted|done|success|succeeded|sent|delivered)$/i.test(value)) return void 0;
1551
+ return firstActionResultDetail(value);
1552
+ }
1553
+ /**
1554
+ * Derive action semantics from the recorded call/result only. This is the
1555
+ * host fallback boundary: extension-owned renderers still take precedence in
1556
+ * the TUI, while replay remains deterministic and registry-independent.
1557
+ */
1558
+ function compactToolPresentation(name, argsRaw, result = "", options = {}) {
1559
+ if (name === "present") {
1560
+ const call = presentCallPresentation(argsRaw);
1561
+ const resultText = options.isError === true || options.error !== void 0 ? actionErrorResult(result, options) : void 0;
1562
+ const count = call === void 0 ? void 0 : `${call.files.length} ${call.files.length === 1 ? "file" : "files"}`;
1563
+ return {
1564
+ title: "Present files",
1565
+ ...count === void 0 ? {} : { summary: count },
1566
+ ...resultText === void 0 ? {} : { result: resultText }
1567
+ };
1568
+ }
1569
+ const send = name === "send_message" ? sendMessageCallPresentation(argsRaw) : void 0;
1570
+ if (send !== void 0) {
1571
+ const resultText = options.isError === true || options.error !== void 0 ? actionErrorResult(result, options) : actionResultSummary("send_message", result);
1572
+ return {
1573
+ title: "Send message",
1574
+ summary: send.target,
1575
+ payload: send.message,
1576
+ ...resultText === void 0 ? {} : { result: resultText }
1577
+ };
1578
+ }
1579
+ const terminal = name === "terminal_send" ? terminalSendCallPresentation(argsRaw) : void 0;
1580
+ if (terminal !== void 0) {
1581
+ const resultText = options.isError === true || options.error !== void 0 ? actionErrorResult(result, options) : actionResultSummary("terminal_send", result);
1582
+ return {
1583
+ title: "Terminal",
1584
+ summary: terminal.sessionId,
1585
+ payload: terminal.text,
1586
+ ...resultText === void 0 ? {} : { result: resultText }
1587
+ };
1588
+ }
1589
+ const interrupt = name === "interrupt_agent" ? interruptAgentCallPresentation(argsRaw) : void 0;
1590
+ if (interrupt !== void 0) {
1591
+ const resultText = options.isError === true || options.error !== void 0 ? actionErrorResult(result, options) : actionResultSummary("interrupt_agent", result);
1592
+ return {
1593
+ title: "Interrupt agent",
1594
+ summary: interrupt.target,
1595
+ ...resultText === void 0 ? {} : { result: resultText }
1596
+ };
1597
+ }
1598
+ const list = name === "list_agents" ? listAgentsCallPresentation(argsRaw) : void 0;
1599
+ if (list !== void 0) {
1600
+ const summary = options.isError === true || options.error !== void 0 ? actionErrorResult(result, options) : (() => {
1601
+ const snapshot = summarizeAgentListResult(result);
1602
+ return snapshot === void 0 ? void 0 : formatAgentListSummary(snapshot);
1603
+ })();
1604
+ return {
1605
+ title: "List agents",
1606
+ summary: list.scope,
1607
+ ...summary === void 0 ? {} : { result: summary }
1608
+ };
1609
+ }
1610
+ }
1611
+ /** Whether a valid action-tool call uses the compact semantic fallback. */
1612
+ function isCompactActionTool(name, argsRaw) {
1613
+ return compactToolPresentation(name, argsRaw) !== void 0;
1614
+ }
1615
+ /** Expanded semantic lines for action cards; list_agents keeps its history snapshot. */
1616
+ function compactToolExpandedLines(name, argsRaw, result = "", options = {}) {
1617
+ const presentation = compactToolPresentation(name, argsRaw, result, options);
1618
+ if (presentation === void 0) return void 0;
1619
+ if (name === "present") {
1620
+ const lines = presentCallPresentation(argsRaw)?.files.map((file) => file.description === void 0 || file.description === "" ? file.path : `${file.path} — ${file.description}`) ?? [];
1621
+ if (presentation.result !== void 0) lines.push(presentation.result);
1622
+ return lines;
1623
+ }
1624
+ if (name === "list_agents" && options.isError !== true && options.error === void 0) {
1625
+ const parsed = parseJsonValue(result);
1626
+ if (Array.isArray(parsed)) return JSON.stringify(parsed, null, 2).split("\n");
1627
+ if (result.trim() !== "") return result.split(/\r\n|\r|\n/);
1628
+ }
1629
+ const lines = presentation.payload === void 0 ? [] : presentation.payload.split(/\r\n|\r|\n/);
1630
+ if (presentation.result !== void 0) lines.push(presentation.result);
1631
+ return lines;
1632
+ }
1633
+ /** Summary key preference per variant (args-derived). */
1634
+ const SUMMARY_KEYS = {
1635
+ bash: ["description", "command"],
1636
+ read: [
1637
+ "path",
1638
+ "file_path",
1639
+ "url"
1640
+ ],
1641
+ search: [
1642
+ "query",
1643
+ "pattern",
1644
+ "url"
1645
+ ],
1646
+ write: ["path", "file_path"],
1647
+ edit: ["path", "file_path"],
1648
+ code: ["description"],
1649
+ others: []
1650
+ };
1651
+ /** Return the formal Tool card's preferred argument summary keys. Preparing
1652
+ * extraction treats this order as the best available choice at extraction time. */
1653
+ function toolSummaryKeys(name) {
1654
+ return SUMMARY_KEYS[classifyTool(name)] ?? [];
1655
+ }
1656
+ /** The first line of a text (the Web's ReasoningRow summary for settled rows). */
1657
+ function firstLine(text) {
1658
+ const newline = text.indexOf("\n");
1659
+ return newline === -1 ? text : text.slice(0, newline);
1660
+ }
1661
+ /**
1662
+ * Strip the workspace root from a workspace-rooted absolute path (display
1663
+ * only), exactly like the Web's relativizeToCwd: only the workspace-root
1664
+ * prefix is peeled, both `/` and `\` separators are handled, and a path
1665
+ * outside the root is returned unchanged.
1666
+ * @param text - the path to shorten.
1667
+ * @param cwd - session workspace root; absent or empty leaves the path unchanged.
1668
+ * @returns the path relative to the workspace root, or unchanged when it is not rooted there.
1669
+ */
1670
+ function relativizeToCwd(text, cwd) {
1671
+ if (cwd === void 0 || cwd === "") return text;
1672
+ const root = cwd.replace(/[/\\]+$/, "");
1673
+ if (text.startsWith(root + "/") || text.startsWith(root + "\\")) return text.slice(root.length + 1);
1674
+ return text;
1675
+ }
1676
+ function parseArgs(argsRaw) {
1677
+ try {
1678
+ return JSON.parse(argsRaw);
1679
+ } catch {
1680
+ return;
1681
+ }
1682
+ }
1683
+ function pickString(args, keys) {
1684
+ for (const key of keys) {
1685
+ const value = args[key];
1686
+ if (typeof value === "string" && value !== "") return value;
1687
+ }
1688
+ }
1689
+ /** The summary key preference for one row variant, falling back to the first
1690
+ * string arg value, then to the raw args text (Web deriveSummary). */
1691
+ function deriveSummary(name, argsRaw) {
1692
+ const parsed = parseArgs(argsRaw);
1693
+ if (typeof parsed !== "object" || parsed === null) return firstLine(argsRaw);
1694
+ const args = parsed;
1695
+ const picked = pickString(args, toolSummaryKeys(name));
1696
+ if (picked !== void 0) return firstLine(picked);
1697
+ for (const value of Object.values(args)) if (typeof value === "string" && value !== "") return firstLine(value);
1698
+ return firstLine(argsRaw);
1699
+ }
1700
+ /**
1701
+ * Tool-specific args summaries for tools whose natural one-line identity is
1702
+ * not a raw arg value (Web TodoRow/AskQuestionRow parity): `todo_write`
1703
+ * reads `done/total done` plus the first active item, `ask_user_question`
1704
+ * reads the first question text. Returns undefined for every other tool,
1705
+ * letting the generic derivation own the summary.
1706
+ * @param name - the tool name.
1707
+ * @param argsRaw - the raw arguments JSON.
1708
+ * @returns the tool-specific summary, or undefined when none applies.
1709
+ */
1710
+ function summarizeToolArgs(name, argsRaw) {
1711
+ const parsed = parseArgs(argsRaw);
1712
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1713
+ const args = parsed;
1714
+ if (name === "ask_user_question") {
1715
+ const questions = args.questions;
1716
+ if (!Array.isArray(questions) || questions.length === 0) return void 0;
1717
+ const first = questions[0];
1718
+ if (typeof first !== "object" || first === null) return void 0;
1719
+ const question = first.question;
1720
+ if (typeof question !== "string" || question === "") return void 0;
1721
+ return firstLine(question);
1722
+ }
1723
+ if (name === "create_goal") {
1724
+ const objective = args.objective;
1725
+ return typeof objective === "string" && objective !== "" ? firstLine(objective) : void 0;
1726
+ }
1727
+ if (name === "update_goal") {
1728
+ const action = args.action;
1729
+ return typeof action === "string" && action !== "" ? action : void 0;
1730
+ }
1731
+ if (name === "get_goal") return "";
1732
+ if (name === "skill") {
1733
+ const skillName = args.name;
1734
+ return typeof skillName === "string" && skillName !== "" ? firstLine(skillName) : void 0;
1735
+ }
1736
+ if (name !== "todo_write") return void 0;
1737
+ const todos = args.todos;
1738
+ if (!Array.isArray(todos)) return void 0;
1739
+ const done = todos.filter((todo) => typeof todo === "object" && todo !== null && todo.status === "completed").length;
1740
+ const active = todos.find((todo) => typeof todo === "object" && todo !== null && todo.status !== "completed");
1741
+ const content = active === void 0 ? "" : String(active.content ?? "");
1742
+ return `${done}/${todos.length} done${content === "" ? "" : ` · ${firstLine(content)}`}`;
1743
+ }
1744
+ /** Classify a tool name into its row variant; unknown names are `others`. */
1745
+ function classifyTool(name) {
1746
+ return Object.prototype.hasOwnProperty.call(TOOL_VARIANTS, name) ? TOOL_VARIANTS[name] : "others";
1747
+ }
1748
+ /** The structural icon semantic per exact tool name, for synthetic cards
1749
+ * without a registry entry (the glyph itself resolves through
1750
+ * src/tui/icons.ts — fold state never stores a concrete emoji/symbol). */
1751
+ const TOOL_SEMANTICS = {
1752
+ shell: "tool-shell",
1753
+ subagent: "subagent",
1754
+ workflow: "workflow",
1755
+ "workflow-member": "subagent",
1756
+ error: "error",
1757
+ interrupted: "interrupted",
1758
+ ask_user_question: "question"
1759
+ };
1760
+ /** The icon semantic per row variant, applied to every registered tool of
1761
+ * that class. */
1762
+ const VARIANT_SEMANTICS = {
1763
+ read: "tool-read",
1764
+ search: "tool-search",
1765
+ bash: "tool-shell",
1766
+ write: "tool-write",
1767
+ edit: "tool-edit",
1768
+ code: "tool-code",
1769
+ others: "tool-generic"
1770
+ };
1771
+ /**
1772
+ * The card header's leading icon semantic: exact-name entries first
1773
+ * (synthetic cards), then slash commands (a control action, not a tool),
1774
+ * then the tool's row-variant semantic, then the generic tool. The renderer
1775
+ * resolves the glyph through `iconFor(semantic, iconStyle)`.
1776
+ * @param name - the tool name.
1777
+ */
1778
+ function toolIconSemantic(name) {
1779
+ const exact = Object.prototype.hasOwnProperty.call(TOOL_SEMANTICS, name) ? TOOL_SEMANTICS[name] : void 0;
1780
+ if (exact !== void 0) return exact;
1781
+ if (name.startsWith("/")) return "slash-command";
1782
+ return VARIANT_SEMANTICS[classifyTool(name)];
1783
+ }
1784
+ /**
1785
+ * The short title used by live tool-call presentations. Known names reuse the
1786
+ * same exact-title and variant tables as formal tool cards; an unknown tool is
1787
+ * intentionally generic rather than exposing its raw model-facing name.
1788
+ */
1789
+ function toolTitle(name) {
1790
+ if (name === "") return "tool";
1791
+ const exact = Object.prototype.hasOwnProperty.call(TOOL_TITLES, name) ? TOOL_TITLES[name] : Object.prototype.hasOwnProperty.call(TUI_TOOL_TITLES, name) ? TUI_TOOL_TITLES[name] : void 0;
1792
+ if (exact !== void 0) return exact;
1793
+ const variant = classifyTool(name);
1794
+ return variant === "others" ? "Tool" : VARIANT_TITLES[variant];
1795
+ }
1796
+ /** Derive the folded preview from a tool name and its raw args JSON. */
1797
+ function parseCallPreview(name, argsRaw) {
1798
+ const parsed = parseArgs(argsRaw);
1799
+ if (typeof parsed !== "object" || parsed === null) return void 0;
1800
+ const args = parsed;
1801
+ if (name === "bash" || name === "pwsh") {
1802
+ const command = args.command;
1803
+ if (typeof command !== "string" || command === "") return void 0;
1804
+ const workdir = args.workdir;
1805
+ return {
1806
+ kind: "bash",
1807
+ command,
1808
+ ...typeof workdir === "string" && workdir !== "" ? { workdir } : {}
1809
+ };
1810
+ }
1811
+ if (name === "edit") {
1812
+ const oldText = args.old_string;
1813
+ const newText = args.new_string;
1814
+ if (typeof oldText !== "string" || typeof newText !== "string") return void 0;
1815
+ const path = typeof args.file_path === "string" && args.file_path !== "" ? args.file_path : args.path;
1816
+ return {
1817
+ kind: "diff",
1818
+ diffs: [{
1819
+ path: typeof path === "string" ? path : "",
1820
+ oldText,
1821
+ newText
1822
+ }]
1823
+ };
1824
+ }
1825
+ if (name === "write") {
1826
+ const content = args.content;
1827
+ if (typeof content !== "string" || content === "") return void 0;
1828
+ const path = typeof args.file_path === "string" && args.file_path !== "" ? args.file_path : args.path;
1829
+ return {
1830
+ kind: "diff",
1831
+ diffs: [{
1832
+ path: typeof path === "string" ? path : "",
1833
+ oldText: null,
1834
+ newText: content
1835
+ }]
1836
+ };
1837
+ }
1838
+ }
1839
+ /**
1840
+ * Parse the read tool's model-facing envelopes from a result: one
1841
+ * `<path>…</path> <type>…</type> <content>…numbered lines…</content>` block
1842
+ * per file read. A merged group card (groupConsecutiveReads) carries several
1843
+ * consecutive envelopes, hence the plural form; the single-envelope helper
1844
+ * below is the common-case convenience.
1845
+ * @param result - the tool result text.
1846
+ * @returns every parsed envelope; empty when the result is not a read envelope.
1847
+ */
1848
+ function parseReadEnvelopes(result) {
1849
+ const out = [];
1850
+ const block = /<path>([\s\S]*?)<\/path>\s*<type>[^<]*<\/type>\s*<content>([\s\S]*?)<\/content>/g;
1851
+ let match;
1852
+ while ((match = block.exec(result)) !== null) {
1853
+ const path = match[1] ?? "";
1854
+ const body = match[2] ?? "";
1855
+ const lines = [];
1856
+ let totalLines;
1857
+ for (const raw of body.split("\n")) {
1858
+ const numbered = /^(\d+): (.*)$/.exec(raw);
1859
+ if (numbered !== null) {
1860
+ lines.push({
1861
+ number: Number(numbered[1]),
1862
+ text: numbered[2] ?? ""
1863
+ });
1864
+ continue;
1865
+ }
1866
+ const end = /^\(End of file - total (\d+) lines\)$/.exec(raw);
1867
+ if (end !== null) {
1868
+ totalLines = Number(end[1]);
1869
+ continue;
1870
+ }
1871
+ const showing = /^\(Showing lines \d+-\d+ of (\d+) lines/.exec(raw);
1872
+ if (showing !== null) totalLines = Number(showing[1]);
1873
+ }
1874
+ out.push({
1875
+ path,
1876
+ lines,
1877
+ ...totalLines === void 0 ? {} : { totalLines }
1878
+ });
1879
+ }
1880
+ return out;
1881
+ }
1882
+ /**
1883
+ * Parse the write tool's XML confirmation envelope (`<path>…</path> <type>
1884
+ * …</type> <content>Created file</content>` — no file content is echoed).
1885
+ * The verb + path are the only material the envelope carries. A malformed
1886
+ * envelope — including a blank `<path>` — yields undefined, never a
1887
+ * partial parse (a whitespace path would surface as an invalid card row).
1888
+ * @param result - the tool result text.
1889
+ * @returns the envelope's verb and path, or undefined when the result is
1890
+ * not a well-formed write envelope.
1891
+ */
1892
+ function parseWriteEnvelope(result) {
1893
+ const match = /<path>([\s\S]*?)<\/path>\s*<type>[^<]*<\/type>\s*<content>([\s\S]*?)<\/content>/.exec(result);
1894
+ if (match === null) return void 0;
1895
+ const verb = /^\s*(Created|Updated)\s+file\s*$/.exec(match[2] ?? "")?.[1];
1896
+ if (verb !== "Created" && verb !== "Updated") return void 0;
1897
+ const path = (match[1] ?? "").trim();
1898
+ if (path === "") return void 0;
1899
+ return {
1900
+ verb,
1901
+ path
1902
+ };
1903
+ }
1904
+ /**
1905
+ * The folded preview suffix for a write card: ` — Created` / ` — Updated`
1906
+ * when the result is the tool's XML confirmation envelope, empty otherwise.
1907
+ * The folded row must NEVER dump the raw envelope (the read-card no-XML
1908
+ * rule; a malformed envelope yields no preview at all, not the raw text).
1909
+ * @param result - the tool result text.
1910
+ * @returns the verb suffix, or '' when the result is not a write envelope.
1911
+ */
1912
+ function writeFoldedPreview(result) {
1913
+ const envelope = parseWriteEnvelope(result);
1914
+ return envelope === void 0 ? "" : ` — ${envelope.verb}`;
1915
+ }
1916
+ /**
1917
+ * Parse the skill tool's XML instruction envelope (`<skill_content
1918
+ * name="…"> <skill_resources>…</skill_resources> <skill_instructions>…
1919
+ * </skill_instructions> </skill_content>`). The name attribute is XML-
1920
+ * escaped by the producer (escapeAttr: `&amp;`/`&quot;`/`&lt;`) and is
1921
+ * decoded here; the instructions body is embedded VERBATIM by the producer
1922
+ * (skills are trusted local content), so it is returned unmodified.
1923
+ *
1924
+ * The boundaries are OUTER-envelope-aware: the opener is the first
1925
+ * `<skill_content name="…">`, the instructions opener the first
1926
+ * `<skill_instructions>` after it, and the closers the last
1927
+ * `</skill_instructions>` / `</skill_content>` — so a body that itself
1928
+ * documents envelope-shaped XML (a complete nested block, or an unclosed
1929
+ * tag) never truncates the outer body. A MALFORMED first envelope never
1930
+ * borrows a later envelope's boundaries: a second `<skill_content name="…">`
1931
+ * opener between the first opener and its instructions opener means the
1932
+ * first envelope is incomplete, and the selected instructions body must
1933
+ * close every `<skill_content name="…">` opener it contains (unmatched
1934
+ * closing tags are tolerated) — without those guards, a first envelope
1935
+ * whose own boundaries are unclosed would cross-pair with a later
1936
+ * envelope's. An unclosed `<skill_content name="…">` example inside a body
1937
+ * is indistinguishable from such a malformed concatenation and degrades to
1938
+ * a header-only card, never raw tags.
1939
+ * @param result - the tool result text.
1940
+ * @returns the envelope's name and instruction body, or undefined when the
1941
+ * result is not a well-formed skill envelope (a blank name is malformed).
1942
+ */
1943
+ function parseSkillEnvelope(result) {
1944
+ const open = result.indexOf("<skill_content name=\"");
1945
+ if (open < 0) return void 0;
1946
+ const nameStart = open + 21;
1947
+ const nameEnd = result.indexOf("\"", nameStart);
1948
+ if (nameEnd < 0) return void 0;
1949
+ const instrOpen = result.indexOf("<skill_instructions>", nameEnd);
1950
+ if (instrOpen < 0) return void 0;
1951
+ const nestedOpen = result.indexOf("<skill_content name=\"", nameEnd);
1952
+ if (nestedOpen >= 0 && nestedOpen < instrOpen) return void 0;
1953
+ const outerClose = result.lastIndexOf("</skill_content>");
1954
+ if (outerClose < instrOpen) return void 0;
1955
+ const instrClose = result.lastIndexOf("</skill_instructions>", outerClose);
1956
+ if (instrClose <= instrOpen) return void 0;
1957
+ const bodyRegion = result.slice(instrOpen, instrClose);
1958
+ let contentDepth = 0;
1959
+ for (const token of bodyRegion.matchAll(/<skill_content name="|<\/skill_content>/g)) if (token[0] === "<skill_content name=\"") contentDepth += 1;
1960
+ else contentDepth = Math.max(0, contentDepth - 1);
1961
+ if (contentDepth > 0) return void 0;
1962
+ const rawName = result.slice(nameStart, nameEnd).trim();
1963
+ if (rawName === "") return void 0;
1964
+ const name = rawName.replaceAll("&quot;", "\"").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
1965
+ let body = result.slice(instrOpen + 20, instrClose);
1966
+ if (body.startsWith("\n")) body = body.slice(1);
1967
+ if (body.endsWith("\n")) body = body.slice(0, -1);
1968
+ return {
1969
+ name,
1970
+ instructions: body
1971
+ };
1972
+ }
1973
+ /**
1974
+ * The folded preview suffix for a skill card: ` — N lines` (the instruction
1975
+ * body's line count — the header already carries `skill · <name>`), empty
1976
+ * otherwise. The folded row never dumps the raw `<skill_content>` block.
1977
+ * @param result - the tool result text.
1978
+ * @returns the line-count suffix, or '' when the result is not a skill
1979
+ * envelope.
1980
+ */
1981
+ function skillFoldedPreview(result) {
1982
+ const envelope = parseSkillEnvelope(result);
1983
+ if (envelope === void 0) return "";
1984
+ const lines = envelope.instructions.split("\n").filter((line) => line !== "").length;
1985
+ return lines === 0 ? "" : ` — ${lines} lines of instructions`;
1986
+ }
1987
+ /**
1988
+ * The human-facing body lines of one injected context row, derived from the
1989
+ * model-facing text so the expanded row never leaks the envelope's raw XML
1990
+ * (the same no-XML rule as the read/write/skill tool cards):
1991
+ *
1992
+ * - a well-formed skill envelope (`<skill_content …>` — the skill loader
1993
+ * tool result and the user-explicit invocation injection share this
1994
+ * shape) renders its instructions body;
1995
+ * - a `<system-reminder>`-wrapped producer (the skill catalog, workspace
1996
+ * instructions — both bake their complete frame into the content,
1997
+ * harness caller-owned framing) renders its content with the wrapper tag
1998
+ * lines stripped; `<available_skills>` markers are stripped only when the
1999
+ * pair is present, so a lone marker inside real content survives;
2000
+ * - any OTHER text returns undefined and the caller keeps its raw-body
2001
+ * behavior (plain context rows are unchanged).
2002
+ *
2003
+ * A malformed skill envelope yields an EMPTY body, never the raw tags: the
2004
+ * header still names the producer, and the model-facing bytes are untouched
2005
+ * (presentation only).
2006
+ * @param text - the injected context message text, exactly as logged.
2007
+ * @returns the body lines to render, or undefined when no envelope shape
2008
+ * applies.
2009
+ */
2010
+ function systemContextBody(text) {
2011
+ const skill = parseSkillEnvelope(text);
2012
+ if (skill !== void 0) return skill.instructions.split("\n");
2013
+ if (text.trimStart().startsWith("<skill_content")) return [];
2014
+ const lines = text.split("\n");
2015
+ const first = lines[0]?.trim();
2016
+ const last = lines[lines.length - 1]?.trim();
2017
+ if (first !== "<system-reminder>" || last !== "</system-reminder>") return void 0;
2018
+ const body = lines.slice(1, -1);
2019
+ if (!(body.some((line) => line.trim() === "<available_skills>") && body.some((line) => line.trim() === "</available_skills>"))) return body;
2020
+ return body.filter((line) => line.trim() !== "<available_skills>" && line.trim() !== "</available_skills>");
2021
+ }
2022
+ /**
2023
+ * Parse the read_image tool's XML confirmation envelope (`<path>…</path>
2024
+ * <type>image</type> <content>PNG image, 800x600 px, … bytes</content>`).
2025
+ * @param result - the tool result text.
2026
+ * @returns the envelope's path and the content summary line, or undefined
2027
+ * when the result is not a well-formed image envelope (blank path or blank
2028
+ * summary are malformed).
2029
+ */
2030
+ function parseImageEnvelope(result) {
2031
+ const match = /<path>([\s\S]*?)<\/path>\s*<type>image<\/type>\s*<content>\s*\n?\s*([\s\S]*?)\s*\n?\s*<\/content>/.exec(result);
2032
+ if (match === null) return void 0;
2033
+ const path = (match[1] ?? "").trim();
2034
+ const summary = (match[2] ?? "").trim();
2035
+ if (path === "" || summary === "") return void 0;
2036
+ return {
2037
+ path,
2038
+ summary
2039
+ };
2040
+ }
2041
+ /**
2042
+ * The folded preview suffix for a read_image card: ` — <summary>` (e.g.
2043
+ * `PNG image · 800x600 px`), empty otherwise. The folded row never dumps
2044
+ * the raw envelope (the read-card no-XML rule).
2045
+ * @param result - the tool result text.
2046
+ * @returns the summary suffix, or '' when the result is not an image
2047
+ * envelope.
2048
+ */
2049
+ function imageFoldedPreview(result) {
2050
+ const envelope = parseImageEnvelope(result);
2051
+ return envelope === void 0 ? "" : ` — ${firstLine(envelope.summary)}`;
2052
+ }
2053
+ /**
2054
+ * The folded preview suffix for a read card: `— {N} lines` when the envelope
2055
+ * reports a total (or a line count), empty otherwise. A merged group card
2056
+ * (multiple envelopes) yields nothing — its head already carries "N files".
2057
+ */
2058
+ function readFoldedPreview(result) {
2059
+ const envelopes = parseReadEnvelopes(result);
2060
+ if (envelopes.length !== 1) return "";
2061
+ const envelope = envelopes[0];
2062
+ const total = envelope.totalLines ?? (envelope.lines.length > 0 ? envelope.lines.length : void 0);
2063
+ return total === void 0 ? "" : ` — ${total} lines`;
2064
+ }
2065
+ /**
2066
+ * The Web row-model header for one tool card: title = tool-owned title or the
2067
+ * variant design title; summary = SUMMARY_KEYS-derived args summary relativized
2068
+ * to the workspace root. Unknown variants carry the tool name alongside the
2069
+ * summary (the Web's `toolName · base` rule), with the separator dropped when
2070
+ * there is no summary text. Slash-command names render without their slash.
2071
+ * @param name - the tool name.
2072
+ * @param argsRaw - the raw arguments JSON string ('' when absent).
2073
+ * @param cwd - workspace root for relativization; optional.
2074
+ */
2075
+ function toolCardHeader(name, argsRaw, cwd) {
2076
+ const action = compactToolPresentation(name, argsRaw);
2077
+ if (action !== void 0) return {
2078
+ title: action.title,
2079
+ summary: action.summary ?? ""
2080
+ };
2081
+ const variant = classifyTool(name);
2082
+ const toolTitle = TOOL_TITLES[name] ?? TUI_TOOL_TITLES[name];
2083
+ const toolSummary = summarizeToolArgs(name, argsRaw);
2084
+ const base = argsRaw === "" ? "" : toolSummary ?? relativizeToCwd(deriveSummary(name, argsRaw), cwd);
2085
+ const summary = variant === "others" && toolTitle === void 0 ? base === "" ? "" : name + " · " + base : base;
2086
+ return {
2087
+ title: toolTitle ?? (name.startsWith("/") ? name.slice(1) : VARIANT_TITLES[variant]),
2088
+ summary
2089
+ };
2090
+ }
2091
+ /**
2092
+ * Render a completed web retrieval as display lines (Web WebBlock parity):
2093
+ * a `search` shows the provider answer and the source list (title — url,
2094
+ * snippet under each), a `fetch` shows the URL and HTTP status. Truncation
2095
+ * is marked in the same place the Web marks it: under the list/status.
2096
+ * Colors are the caller's (the render layer owns the palette).
2097
+ * @param view - the web result view from presentResult.
2098
+ * @returns the display lines; empty when the view carries nothing to show.
2099
+ */
2100
+ function webCardLines(view) {
2101
+ if (view.kind === "search") {
2102
+ const lines = [];
2103
+ if (view.answer !== void 0 && view.answer !== "") lines.push(view.answer);
2104
+ for (const source of view.sources) {
2105
+ const head = source.title === void 0 || source.title === "" ? source.url : `${source.title} — ${source.url}`;
2106
+ lines.push(`• ${head}`);
2107
+ if (source.snippet !== void 0 && source.snippet !== "") lines.push(` ${source.snippet}`);
2108
+ }
2109
+ if (view.truncated) lines.push("… truncated — more sources omitted");
2110
+ return lines;
2111
+ }
2112
+ const lines = [`${view.url} — HTTP ${view.statusCode}`];
2113
+ if (view.truncated) lines.push("… truncated — content capped");
2114
+ return lines;
2115
+ }
2116
+ /**
2117
+ * Render a generic card's rawInput as display lines, structured per tool
2118
+ * where the payload has a natural one-line shape (web TodoRow parity for
2119
+ * `todo_write`, a session/terminal target line for the rest). Unknown
2120
+ * object payloads fall back to pretty JSON — the same fallback the Web's
2121
+ * generic body uses. A string rawInput renders verbatim.
2122
+ * @param name - the tool name.
2123
+ * @param rawInput - the presenter's salient raw input.
2124
+ * @returns the display lines.
2125
+ */
2126
+ /** Checklist display lines for a todo list: `●` in progress, `○` pending,
2127
+ * `✓` completed (Web TodoRow parity). Malformed items are skipped. */
2128
+ function todoChecklistLines(todos) {
2129
+ const lines = [];
2130
+ for (const todo of todos) {
2131
+ if (typeof todo !== "object" || todo === null) continue;
2132
+ const item = todo;
2133
+ const content = typeof item.content === "string" ? item.content : String(item.content ?? "");
2134
+ const mark = item.status === "completed" ? "✓" : item.status === "in_progress" ? "●" : "○";
2135
+ lines.push(`${mark} ${content}`);
2136
+ }
2137
+ return lines;
2138
+ }
2139
+ function genericRawInputLines(name, rawInput) {
2140
+ if (typeof rawInput === "string") return rawInput === "" ? [] : [rawInput];
2141
+ if (typeof rawInput !== "object" || rawInput === null) return rawInput === void 0 ? [] : [String(rawInput)];
2142
+ if (name === "todo_write" && Array.isArray(rawInput)) return todoChecklistLines(rawInput);
2143
+ const args = rawInput;
2144
+ if (name === "todo_write") {
2145
+ const todos = args.todos;
2146
+ if (Array.isArray(todos)) return todoChecklistLines(todos);
2147
+ }
2148
+ if ((name === "terminal_read" || name === "terminal_signal" || name === "terminal_send") && typeof args.sessionId === "string") {
2149
+ const line = `session ${args.sessionId}`;
2150
+ return name === "terminal_send" && typeof args.text === "string" ? [`${line}: ${args.text}`] : [line];
2151
+ }
2152
+ if ((name === "session_event_trace" || name === "session_event_read" || name === "session_trace") && (args.seq !== void 0 || args.session_id !== void 0)) {
2153
+ const parts = [];
2154
+ if (args.session_id !== void 0) parts.push(String(args.session_id));
2155
+ if (args.seq !== void 0) parts.push(`seq ${String(args.seq)}`);
2156
+ return [parts.join(" · ")];
2157
+ }
2158
+ return JSON.stringify(rawInput, null, 2).split("\n");
2159
+ }
2160
+ /**
2161
+ * Flatten a settled result's content blocks to display lines, with the Web's
2162
+ * `resultText` semantics: text blocks verbatim, known file blocks as a
2163
+ * metadata-only row, images as a compact placeholder, and unknown finalized
2164
+ * blocks as an explicit bounded fallback. Empty content on a failed call
2165
+ * falls back to the structured error's `name: code` line.
2166
+ * @param blocks - the result content blocks.
2167
+ * @param error - the structured error, when the call failed.
2168
+ * @returns the display lines (may be empty).
2169
+ */
2170
+ function resultTextLines(blocks, error) {
2171
+ const lines = [];
2172
+ for (const block of blocks) if (block.type === "text") lines.push(...block.text.split("\n"));
2173
+ else if (block.type === "image") lines.push("[image]");
2174
+ else if (block.type === "file") lines.push(fileAttachmentSummary(block.attachment));
2175
+ else if (block.type === "reasoning" || block.type === "tool-call") lines.push(JSON.stringify(block, null, 2));
2176
+ else lines.push(finalizedBlockFallbackText(block));
2177
+ if (lines.length === 0 && error !== void 0) lines.push(`${error.name}: ${error.code}`);
2178
+ return lines;
2179
+ }
2180
+ /**
2181
+ * Parse and normalize the tool's `{"answers":[…]}` render text. A
2182
+ * malformed entry (non-object) invalidates the WHOLE text — the Web's
2183
+ * `answeredSummary` checks `answers.every(isAnswer)` the same way, and a
2184
+ * half-valid set would make the count and the rendered rows disagree.
2185
+ * Non-string `selected` members are dropped; missing id/custom normalize
2186
+ * to empty.
2187
+ * @param text - the settled result text.
2188
+ * @returns the normalized entries, or undefined when unparseable/malformed.
2189
+ */
2190
+ function parseAnswerEntries(text) {
2191
+ let parsed;
2192
+ try {
2193
+ parsed = JSON.parse(text);
2194
+ } catch {
2195
+ return;
2196
+ }
2197
+ if (typeof parsed !== "object" || parsed === null) return void 0;
2198
+ const answers = parsed.answers;
2199
+ if (!Array.isArray(answers)) return void 0;
2200
+ if (!answers.every((entry) => typeof entry === "object" && entry !== null)) return void 0;
2201
+ return answers.map((entry) => {
2202
+ const candidate = entry;
2203
+ return {
2204
+ id: typeof candidate.id === "string" ? candidate.id : "",
2205
+ selected: Array.isArray(candidate.selected) ? candidate.selected.filter((item) => typeof item === "string") : [],
2206
+ custom: typeof candidate.custom === "string" ? candidate.custom : ""
2207
+ };
2208
+ });
2209
+ }
2210
+ /**
2211
+ * The answered-count summary for a settled `ask_user_question` result
2212
+ * (Web AskQuestionRow parity): parses the tool's `{"answers":[…]}` render
2213
+ * text and counts the entries that actually carry an answer — a non-empty
2214
+ * `selected` list or a non-empty `custom` string (a skipped question has
2215
+ * neither and stays out of the count). Returns `N/M answered`, or undefined
2216
+ * when the text is not the expected answer JSON (the caller then falls back
2217
+ * to the generic presentation instead of inventing a count).
2218
+ * @param text - the settled result text.
2219
+ * @returns the answered-count summary, or undefined when unparseable.
2220
+ */
2221
+ function askAnswersSummary(text) {
2222
+ const entries = parseAnswerEntries(text);
2223
+ if (entries === void 0) return void 0;
2224
+ return `${entries.filter((entry) => entry.selected.length > 0 || entry.custom !== "").length}/${entries.length} answered`;
2225
+ }
2226
+ /**
2227
+ * The per-question display lines for a settled `ask_user_question` result
2228
+ * (the expanded card's body, complementing {@link askAnswersSummary}'s
2229
+ * count). Parses the tool's `{"answers":[…]}` render text and renders one
2230
+ * line per entry: `● <id> → <selected, custom>` for an answered question,
2231
+ * `○ <id> — skipped` when neither is present. Shares the normalization with
2232
+ * {@link askAnswersSummary}, so the rendered rows and the count always
2233
+ * agree; an unparseable/malformed text returns undefined.
2234
+ * @param text - the settled result text.
2235
+ * @returns the display lines, or undefined when unparseable/malformed.
2236
+ */
2237
+ function askAnswersLines(text) {
2238
+ const entries = parseAnswerEntries(text);
2239
+ if (entries === void 0) return void 0;
2240
+ return entries.map((entry) => {
2241
+ if (entry.selected.length > 0) return {
2242
+ text: `● ${entry.id} → ${entry.selected.join(", ")}`,
2243
+ skipped: false
2244
+ };
2245
+ if (entry.custom !== "") return {
2246
+ text: `● ${entry.id} → ${entry.custom}`,
2247
+ skipped: false
2248
+ };
2249
+ return {
2250
+ text: `○ ${entry.id} — skipped`,
2251
+ skipped: true
2252
+ };
2253
+ });
2254
+ }
2255
+ /** Parse a settled goal-tool result text, or undefined when it is not the
2256
+ * expected `{"goal":…}` JSON (the caller then falls back to the generic
2257
+ * presentation). */
2258
+ function parseGoalResult(text) {
2259
+ let parsed;
2260
+ try {
2261
+ parsed = JSON.parse(text);
2262
+ } catch {
2263
+ return;
2264
+ }
2265
+ if (typeof parsed !== "object" || parsed === null) return void 0;
2266
+ const value = parsed;
2267
+ if (value.goal === null) return { goal: null };
2268
+ if (typeof value.goal !== "object" || value.goal === null) return void 0;
2269
+ const goal = value.goal;
2270
+ const blocked = typeof goal.blockedReason === "object" && goal.blockedReason !== null ? goal.blockedReason : void 0;
2271
+ return {
2272
+ goal: {
2273
+ ...typeof goal.id === "string" ? { id: goal.id } : {},
2274
+ ...typeof goal.revision === "number" ? { revision: goal.revision } : {},
2275
+ ...typeof goal.objective === "string" ? { objective: goal.objective } : {},
2276
+ ...typeof goal.phase === "string" ? { phase: goal.phase } : {},
2277
+ ...typeof goal.roundsStarted === "number" ? { roundsStarted: goal.roundsStarted } : {},
2278
+ ...typeof goal.maxGoalRounds === "number" ? { maxGoalRounds: goal.maxGoalRounds } : {},
2279
+ ...blocked !== void 0 ? { blockedReason: {
2280
+ ...typeof blocked.code === "string" ? { code: blocked.code } : {},
2281
+ ...typeof blocked.message === "string" ? { message: blocked.message } : {}
2282
+ } } : {}
2283
+ },
2284
+ ...typeof value.activation === "string" ? { activation: value.activation } : {}
2285
+ };
2286
+ }
2287
+ /**
2288
+ * The one-line folded summary for a settled goal-tool result: `phase … ·
2289
+ * revision N · N/M rounds`, or `no goal set` for `{"goal":null}`.
2290
+ * Returns undefined when the text is not the expected result JSON (the
2291
+ * caller then falls back to the generic preview instead of inventing one).
2292
+ * @param text - the settled result text.
2293
+ */
2294
+ function goalResultSummary(text) {
2295
+ const value = parseGoalResult(text);
2296
+ if (value === void 0) return void 0;
2297
+ const goal = value.goal;
2298
+ if (goal === null) return "no goal set";
2299
+ const parts = [];
2300
+ if (goal.phase !== void 0) parts.push(`phase ${goal.phase}`);
2301
+ if (goal.revision !== void 0) parts.push(`revision ${goal.revision}`);
2302
+ if (goal.roundsStarted !== void 0) parts.push(goal.maxGoalRounds === void 0 ? `${goal.roundsStarted} rounds` : `${goal.roundsStarted}/${goal.maxGoalRounds} rounds`);
2303
+ return parts.length === 0 ? "goal" : parts.join(" · ");
2304
+ }
2305
+ /**
2306
+ * The expanded-card display lines for a settled goal-tool result: one field
2307
+ * per line (`● objective: …`, `● phase: … · revision N`, `● rounds: N/M`,
2308
+ * `● activation: …`, `● blocked: code — message`), or a single `no goal
2309
+ * set` line for `{"goal":null}`. Returns undefined when the text is not the
2310
+ * expected result JSON (the caller falls back to the generic presentation).
2311
+ * @param text - the settled result text.
2312
+ */
2313
+ function goalResultLines(text) {
2314
+ const value = parseGoalResult(text);
2315
+ if (value === void 0) return void 0;
2316
+ const goal = value.goal;
2317
+ if (goal === null) return ["no goal set"];
2318
+ const lines = [];
2319
+ if (goal.objective !== void 0 && goal.objective !== "") lines.push(`● objective: ${goal.objective}`);
2320
+ const identity = [];
2321
+ if (typeof goal.phase === "string" && goal.phase !== "") identity.push(goal.phase);
2322
+ if (goal.revision !== void 0) identity.push(`revision ${goal.revision}`);
2323
+ if (identity.length > 0) lines.push(`● ${identity.join(" · ")}`);
2324
+ if (goal.roundsStarted !== void 0) lines.push(goal.maxGoalRounds === void 0 ? `● rounds: ${goal.roundsStarted}` : `● rounds: ${goal.roundsStarted}/${goal.maxGoalRounds}`);
2325
+ const blocked = goal.blockedReason;
2326
+ if (blocked !== void 0 && (blocked.code !== void 0 || blocked.message !== void 0)) {
2327
+ const detail = [blocked.code, blocked.message].filter((part) => typeof part === "string" && part !== "").join(" — ");
2328
+ lines.push(`● blocked: ${detail}`);
2329
+ }
2330
+ if (value.activation !== void 0) lines.push(`● activation: ${value.activation}`);
2331
+ return lines;
2332
+ }
2333
+ /**
2334
+ * The folded-card call preview for tools whose args carry a one-line
2335
+ * identity (Web TodoRow/WebRow folded parity): `todo_write` summarizes
2336
+ * `done/total` plus the first active item, `web_search`/`web_fetch` show
2337
+ * the query/URL. Empty for every other tool (their folded row keeps the
2338
+ * header + result preview).
2339
+ * @param name - the tool name.
2340
+ * @param argsRaw - the raw arguments JSON.
2341
+ * @returns the preview line, or '' when the tool has none.
2342
+ */
2343
+ function foldedCallPreview(name, argsRaw) {
2344
+ const parsed = parseArgs(argsRaw);
2345
+ if (typeof parsed !== "object" || parsed === null) return "";
2346
+ const args = parsed;
2347
+ if (name === "todo_write") {
2348
+ const summary = summarizeToolArgs(name, argsRaw);
2349
+ return summary === void 0 ? "" : ` — ${summary}`;
2350
+ }
2351
+ if (name === "web_search") {
2352
+ const query = args.query;
2353
+ return typeof query === "string" && query !== "" ? ` — ${firstLine(query)}` : "";
2354
+ }
2355
+ if (name === "web_fetch") {
2356
+ const url = args.url;
2357
+ return typeof url === "string" && url !== "" ? ` — ${firstLine(url)}` : "";
2358
+ }
2359
+ if (name === "skill") {
2360
+ const skill = args.name;
2361
+ return typeof skill === "string" && skill !== "" ? ` — ${firstLine(skill)}` : "";
2362
+ }
2363
+ return "";
2364
+ }
2365
+ /**
2366
+ * The Focus compact Tool line for one raw tool call: presenter-first,
2367
+ * static fallback second (plan §9.1/§9.4). The tool-owned presentCall
2368
+ * view wins when the live registry has one; otherwise the Web row-model
2369
+ * header (toolCardHeader) renders the same semantic. The fold stores the
2370
+ * RAW call facts — this helper is the ONLY place the compact line is
2371
+ * formatted, so the TranscriptFolder never bakes presentation strings.
2372
+ * @param tool - the raw call facts (name + raw arguments JSON).
2373
+ * @param options - the live presenter bridge and the workspace root for
2374
+ * path relativization (both optional — replay degrades to the fallback).
2375
+ * @returns the one-line display, e.g. `Load skill session-review`,
2376
+ * `Read src/index.ts`, `vendor_probe cache-01`.
2377
+ */
2378
+ function focusToolDisplay(tool, options = {}) {
2379
+ const owned = options.presenter?.call(tool.name, tool.args);
2380
+ if (owned !== void 0) return formatOwnedCallForCompactFocus(tool.name, owned);
2381
+ return focusToolFallbackDisplay(tool.name, tool.args, options.cwd);
2382
+ }
2383
+ /** The compact line from a tool-owned presentCall view. The official shell
2384
+ * presenters split the COMMAND (`title` / `rawInput`) from the human
2385
+ * `description` that is "shown in the UI"; the Focus Tool slot is a
2386
+ * description surface, so it prefers that description and never re-derives
2387
+ * the command from args. Because a description alone loses the tool's
2388
+ * identity, the two description-backed paths (foreground terminal and
2389
+ * background generic execute) prefix it with the human-facing tool title —
2390
+ * `Bash · Show working tree status`. Every other path keeps the previous
2391
+ * title / rawInput behavior, and the terminal title's FULL command still
2392
+ * renders in the expanded tool card — the compact row is exactly ONE
2393
+ * physical framebuffer row, so only a first logical line may surface here. */
2394
+ function formatOwnedCallForCompactFocus(name, view) {
2395
+ if (view.card === "terminal") {
2396
+ const description = firstLine((view.description ?? "").replace(/\r\n|\r/g, "\n")).trim();
2397
+ if (description !== "") return `${compactFocusToolIdentity(name)} · ${description}`;
2398
+ return firstLine(view.title.replace(/\r\n|\r/g, "\n"));
2399
+ }
2400
+ if (view.card === "diff") return firstLine(view.title.replace(/\r\n|\r/g, "\n"));
2401
+ if (view.kind === "execute") {
2402
+ const description = firstContentText(view);
2403
+ if (description !== void 0) return `${compactFocusToolIdentity(name)} · ${description}`;
2404
+ }
2405
+ const raw = typeof view.rawInput === "string" ? view.rawInput.trim() : void 0;
2406
+ if (raw === void 0 || raw === "") return view.title;
2407
+ return view.title.endsWith(raw) ? view.title : `${view.title} ${firstLine(raw)}`;
2408
+ }
2409
+ /** The human-facing tool identity for a description-backed compact row.
2410
+ * Reuses the formal title mapping; a name it resolves only to the generic
2411
+ * `Tool`/`tool` keeps its raw name so a custom tool is never flattened to a
2412
+ * meaningless `Tool · description` (same unknown-tool identity principle as
2413
+ * the static fallback). */
2414
+ function compactFocusToolIdentity(name) {
2415
+ const title = toolTitle(name);
2416
+ return title === "Tool" || title === "tool" ? name : title;
2417
+ }
2418
+ /** The first meaningful text block of a call view's content as one logical
2419
+ * line — the official Bash background presenter puts its human description
2420
+ * in `content[0]`. Undefined when no non-blank text block exists. */
2421
+ function firstContentText(view) {
2422
+ for (const block of view.content ?? []) {
2423
+ if (block.type !== "text") continue;
2424
+ const line = firstLine(block.text.replace(/\r\n|\r/g, "\n")).trim();
2425
+ if (line !== "") return line;
2426
+ }
2427
+ }
2428
+ /** The compact line from the static Web row-model header (replay /
2429
+ * registry-unavailable fallback). An unknown tool's header title is the
2430
+ * generic "Tool call" — the compact line names the actual tool instead
2431
+ * (plan §9.3: an unknown custom tool is still a Tool). */
2432
+ function focusToolFallbackDisplay(name, argsRaw, cwd) {
2433
+ const action = compactToolPresentation(name, argsRaw);
2434
+ if (action !== void 0) return `${action.summary === void 0 ? action.title : `${action.title} ${action.summary}`}${action.payload === void 0 || action.payload === "" ? "" : ` · ${firstLine(action.payload)}`}`;
2435
+ const header = toolCardHeader(name, argsRaw, cwd);
2436
+ if (!(classifyTool(name) !== "others" || TOOL_TITLES[name] !== void 0 || TUI_TOOL_TITLES[name] !== void 0)) return header.summary === "" ? name : header.summary.replace(" · ", " ");
2437
+ return header.summary === "" ? header.title : `${header.title} ${header.summary}`;
2438
+ }
2439
+ /**
2440
+ * Build the presentation bridge over a tool-definition lookup (the runner
2441
+ * passes a scoped registry read, e.g. `ctx.get('tools')?.get(name, scope)`).
2442
+ * Mirrors the host apiproxy's presenter invocations: args are JSON-parsed and
2443
+ * the callbacks are guarded so a throwing tool presenter degrades to the
2444
+ * generic card. An absent registry yields no views, so the cards fall back to
2445
+ * the generic presentation instead of failing.
2446
+ * @param get - resolve one tool definition by name (scope already applied).
2447
+ */
2448
+ function toolPresenterFrom(get) {
2449
+ return {
2450
+ call(name, argsRaw) {
2451
+ const definition = get(name);
2452
+ if (definition?.presentCall === void 0) return void 0;
2453
+ const parsed = parseArgs(argsRaw);
2454
+ if (parsed === void 0) return void 0;
2455
+ try {
2456
+ return definition.presentCall(parsed);
2457
+ } catch {
2458
+ return;
2459
+ }
2460
+ },
2461
+ result(name, argsRaw, result) {
2462
+ const definition = get(name);
2463
+ if (definition?.presentResult === void 0) return void 0;
2464
+ const parsed = parseArgs(argsRaw);
2465
+ if (parsed === void 0) return void 0;
2466
+ try {
2467
+ return definition.presentResult(parsed, {
2468
+ content: [...result.content],
2469
+ isError: result.isError,
2470
+ ...result.meta === void 0 ? {} : { meta: result.meta }
2471
+ });
2472
+ } catch {
2473
+ return;
2474
+ }
2475
+ }
2476
+ };
2477
+ }
2478
+ /**
2479
+ * Subagent-family tool names whose call args may carry an explicit
2480
+ * model/provider override. Matched by REGISTERED name; unknown names are
2481
+ * ignored so third-party subagent-like tools keep their default rendering.
2482
+ */
2483
+ const SUBAGENT_TOOL_NAMES = /* @__PURE__ */ new Set([
2484
+ "subagent",
2485
+ "subagent_route",
2486
+ "subagent_router",
2487
+ "subagent_fork"
2488
+ ]);
2489
+ /**
2490
+ * Extract the model · provider display line for a subagent-family tool call.
2491
+ *
2492
+ * COMPATIBILITY CONTRACT: the line renders ONLY when the call args actually
2493
+ * carry a model/provider — the top-level `model`/`provider` shape
2494
+ * (subagent_route / subagent_router) or the `agentOptions.model/provider`
2495
+ * shape. Every other call returns `undefined` and the card renders exactly
2496
+ * as before; unknown tool names and unparseable args are ignored. The
2497
+ * official `subagent` tool's model lives in deployment config (never in
2498
+ * the call args), so it naturally renders nothing.
2499
+ * @param name - the tool's registered name.
2500
+ * @param argsRaw - the raw tool-call arguments JSON ('' or malformed → none).
2501
+ * @returns `model · provider` (either part alone when only one is present),
2502
+ * or undefined when the call carries no model/provider.
2503
+ */
2504
+ function subagentModelDisplay(name, argsRaw) {
2505
+ if (!SUBAGENT_TOOL_NAMES.has(name)) return void 0;
2506
+ const parsed = parseArgs(argsRaw);
2507
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
2508
+ const args = parsed;
2509
+ const opts = typeof args.agentOptions === "object" && args.agentOptions !== null ? args.agentOptions : void 0;
2510
+ const parts = [typeof args.model === "string" && args.model !== "" ? args.model : typeof opts?.model === "string" && opts.model !== "" ? opts.model : void 0, typeof args.provider === "string" && args.provider !== "" ? args.provider : typeof opts?.provider === "string" && opts.provider !== "" ? opts.provider : void 0].filter((part) => part !== void 0);
2511
+ return parts.length === 0 ? void 0 : parts.join(" · ");
2512
+ }
2513
+ //#endregion
2514
+ //#region src/tui/transcript/context-structure.ts
2515
+ /**
2516
+ * Renderer-neutral ambient Context presentation structure.
2517
+ *
2518
+ * The semantic question "is this row an ambient Context fact?" belongs to the
2519
+ * canonical semantic source (`domain/transcript/context-semantics.ts`). THIS module owns the presentation question: "which
2520
+ * presentation role does one surfaced Context row take, and where do adjacent
2521
+ * ambient facts form ONE presentation container with ONE owner?".
2522
+ *
2523
+ * Clustering is computed from RAW transcript chronology. Hiding Process rows in
2524
+ * a projection must never merge two Context rows that were not adjacent in the
2525
+ * raw transcript. The module is deliberately renderer-free: it never reads
2526
+ * width, theme, icons, preset, disclosure state, search state or a component.
2527
+ * @module @xmoon76/dsh-pi-tui/tui/transcript/context-structure
2528
+ */
2529
+ /** Whether one row is a standalone producer notice. */
2530
+ function isNoticeContext(message) {
2531
+ return isSurfacedContext(message) && contextFormOf(message) === "notice";
2532
+ }
2533
+ /** Whether one row is another Agent's relayed message. */
2534
+ function isRelayContext(message) {
2535
+ return isSurfacedContext(message) && contextFormOf(message) === "relay";
2536
+ }
2537
+ /** Whether one row is recalled material from another session. The legacy
2538
+ * session-reference role counts even when its producer did not declare the
2539
+ * form, so a recalled row is never clustered as ambient. The A-layer provenance
2540
+ * accessor is private to the transitional semantic source, so the legacy role
2541
+ * is read from the row's own field here. */
2542
+ function isRecallContext(message) {
2543
+ if (!isSurfacedContext(message)) return false;
2544
+ if (contextFormOf(message) === "recall") return true;
2545
+ return message.kind === "system" && message.contextPresentation?.role === "recall";
2546
+ }
2547
+ /** The presentation role of one injected Context row; undefined when the row
2548
+ * is not surfaced Context. Unknown/missing forms fail open to `generic`
2549
+ * (standalone), never to ambient. */
2550
+ function contextPresentationKind(message) {
2551
+ if (!isSurfacedContext(message)) return void 0;
2552
+ if (isAmbientContext(message)) return "ambient";
2553
+ if (isNoticeContext(message)) return "notice";
2554
+ if (isRelayContext(message)) return "relay";
2555
+ if (isRecallContext(message)) return "recall";
2556
+ return "generic";
2557
+ }
2558
+ /**
2559
+ * Group raw-adjacent same-turn ambient Context rows into clusters.
2560
+ *
2561
+ * A cluster forms ONLY when every requirement holds: same turn, raw-adjacent
2562
+ * TranscriptMessage rows, each row surfaced Context, each row ambient form.
2563
+ * A single eligible row stays an ordinary ambient row (no cluster). Every
2564
+ * non-ambient boundary (Conversation, Process, Attention, notice, relay,
2565
+ * recall, unknown Context, workflow, compaction, window summary, turn
2566
+ * boundary) ends the current run.
2567
+ * @param messages - the transcript window in raw chronology.
2568
+ */
2569
+ function clusterAdjacentAmbientContext(messages) {
2570
+ const clusters = [];
2571
+ let run = [];
2572
+ const flush = () => {
2573
+ const first = run[0];
2574
+ if (first !== void 0 && run.length >= 2) clusters.push({
2575
+ kind: "context-cluster",
2576
+ turn: first.turn,
2577
+ members: run,
2578
+ owner: first
2579
+ });
2580
+ run = [];
2581
+ };
2582
+ for (const message of messages) {
2583
+ if (isAmbientContext(message)) {
2584
+ const first = run[0];
2585
+ if (first !== void 0 && first.turn !== message.turn) flush();
2586
+ run.push(message);
2587
+ continue;
2588
+ }
2589
+ flush();
2590
+ }
2591
+ flush();
2592
+ const byMember = /* @__PURE__ */ new Map();
2593
+ for (const cluster of clusters) for (const member of cluster.members) byMember.set(member, cluster);
2594
+ return {
2595
+ clusters,
2596
+ byMember
2597
+ };
2598
+ }
2599
+ //#endregion
2600
+ //#region src/tui/transcript/structure.ts
2601
+ /**
2602
+ * Canonical preset-neutral transcript structure projection.
2603
+ *
2604
+ * This module owns the ONE semantic segmentation of a raw transcript window:
2605
+ * maximal contiguous same-turn Process runs become {@link TranscriptWorkSpan}s
2606
+ * and raw-adjacent same-turn ambient Context runs become
2607
+ * {@link ContextCluster}s (every other semantic boundary ends a run). It is
2608
+ * deliberately blind to the active preset, the surface, disclosure state,
2609
+ * search state, render width and the renderer registry: it answers only
2610
+ * "where does the raw chronology form Work, a Context cluster, or a
2611
+ * standalone row?".
2612
+ *
2613
+ * `projectCompact()` is the Compact materialization adapter over this
2614
+ * structure, Full materializes it with expanded-flat Work and the shared
2615
+ * cluster presentation, and expanded Focus consumes it for its process tail.
2616
+ * The same boundary identity is therefore never re-derived per preset.
2617
+ *
2618
+ * A Work span may CARRY a foldable Context row as a structural part without
2619
+ * making it Process: the row keeps its Context semantics, its source bytes and
2620
+ * its own disclosure, but no longer splits one turn's Activity/Thought. Two
2621
+ * narrow forms qualify: a `form:'snapshot'` singleton / snapshot-only raw
2622
+ * cluster, and a `tool-jobs` Notice with durable same-turn `next-step`
2623
+ * delivery evidence. A mixed `instructions`/`catalog`/`snapshot` cluster and
2624
+ * every other Notice form stay independent Context boundaries.
2625
+ *
2626
+ * The projector is a single forward pass plus the linear ambient-clustering
2627
+ * pass (O(n)); wrappers are freshly allocated each call, but their
2628
+ * `owner`/`members` always reference the original `TranscriptMessage`
2629
+ * objects, so presentation caches can compare owner + member identity/order.
2630
+ * @module @xmoon76/dsh-pi-tui/tui/transcript/structure
2631
+ */
2632
+ /**
2633
+ * Whether one row continues the current Work run. Process rows with a turn
2634
+ * number extend the run only while the turn is unchanged; turn-less rows
2635
+ * (window summaries, standalone control-plane commands) never enter Work by
2636
+ * construction — a `kind: 'command'` row has no turn and a `control` class.
2637
+ * A settled surfaced-interaction card (question / Plan review) is
2638
+ * human-decision evidence, not Process work — it never joins a span (and so
2639
+ * never counts toward its tool count/preview); it flushes the run and
2640
+ * renders standalone. Exported so the live Preparing ownership consumes the
2641
+ * SAME boundary authority as every projection: a settled interaction closes
2642
+ * the trailing run.
2643
+ *
2644
+ * This predicate deliberately does NOT admit Snapshot Context: it also answers
2645
+ * Process/live-Preparing eligibility. Work PRESENTATION carriage is decided by
2646
+ * {@link isFoldableSnapshotContext} inside {@link projectTranscriptStructure}.
2647
+ */
2648
+ function isTranscriptWorkMember(message) {
2649
+ return "turn" in message && classifyTranscriptMessage(message).class === "process" && !isSurfacedInteractionTool(message) && !isPostTurnReplayEvidence(message);
2650
+ }
2651
+ /** Whether one row is a producer-declared Snapshot Context row (the ONE
2652
+ * ambient form whose disclosure follows the surrounding Work/Thought). */
2653
+ function isSnapshotContext(message) {
2654
+ return isSurfacedContext(message) && contextFormOf(message) === "snapshot";
2655
+ }
2656
+ /** Per-cluster memo of {@link isSnapshotOnlyCluster}: cluster wrappers are
2657
+ * freshly allocated per projection pass but may be queried once per member by
2658
+ * the structure scan and the Focus disposition. The WeakMap keeps every scan
2659
+ * linear for one large snapshot run (no per-member `every()` rescan). */
2660
+ const snapshotOnlyClusterMemo = /* @__PURE__ */ new WeakMap();
2661
+ /** Whether one raw-adjacent ambient cluster consists ONLY of Snapshot rows, so
2662
+ * the whole cluster may be carried inside a Work span without tearing a mixed
2663
+ * foundation cluster apart. Memoized per cluster object; a cluster wrapper is
2664
+ * never reused across projection passes. */
2665
+ function isSnapshotOnlyCluster(cluster) {
2666
+ const memoized = snapshotOnlyClusterMemo.get(cluster);
2667
+ if (memoized !== void 0) return memoized;
2668
+ const result = cluster.members.every(isSnapshotContext);
2669
+ snapshotOnlyClusterMemo.set(cluster, result);
2670
+ return result;
2671
+ }
2672
+ /**
2673
+ * The narrow display-layer predicate: may this Snapshot row's presentation be
2674
+ * carried by the same-turn Work/Thought instead of ending it?
2675
+ *
2676
+ * The answer is source-derived (`form:'snapshot'`) and depends on the raw
2677
+ * adjacency result: a Snapshot that shares its raw-adjacent ambient cluster
2678
+ * with `instructions`/`catalog` is part of one indivisible mixed Context
2679
+ * cluster and stays a Work boundary. A singleton Snapshot or a snapshot-only
2680
+ * cluster is foldable.
2681
+ * @param message - one raw transcript row.
2682
+ * @param clusterByMember - raw-adjacency membership for the SAME window.
2683
+ */
2684
+ function isFoldableSnapshotContext(message, clusterByMember) {
2685
+ if (!isSnapshotContext(message)) return false;
2686
+ const cluster = clusterByMember.get(message);
2687
+ return cluster === void 0 || isSnapshotOnlyCluster(cluster);
2688
+ }
2689
+ /**
2690
+ * Whether one row is a Working `tool-jobs` completion Notice with durable
2691
+ * same-turn `next-step` delivery evidence.
2692
+ *
2693
+ * This is a NARROW exception, never a generic notice rule: the producer-declared
2694
+ * `sourceKind === 'tool-jobs'` AND `form === 'notice'` are both required, plus
2695
+ * the fold's presentation-only `sameTurnNextStep` flag derived from the durable
2696
+ * `agent/inbox/spliced` insert/claim identity chain. A `next-turn` wakeup, a
2697
+ * foreign/legacy log, a different producer (including `subagent-settled`) or a
2698
+ * missing claim carries no flag and therefore stays an independent Context
2699
+ * boundary.
2700
+ */
2701
+ function isWorkingToolJobsNotice(message) {
2702
+ if (!isSurfacedContext(message)) return false;
2703
+ const presentation = message.contextPresentation;
2704
+ return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.form === "notice" && presentation.sourceKind === "tool-jobs";
2705
+ }
2706
+ /**
2707
+ * The complete narrow display-layer eligibility: may this Context row be
2708
+ * carried by the same-turn Work/Thought instead of ending it? Only a foldable
2709
+ * Snapshot or a proven Working `tool-jobs` Notice qualifies; every other
2710
+ * surfaced Context remains a boundary.
2711
+ */
2712
+ function isFoldableWorkContext(message, clusterByMember) {
2713
+ return isFoldableSnapshotContext(message, clusterByMember) || isWorkingToolJobsNotice(message);
2714
+ }
2715
+ /**
2716
+ * Segment one raw transcript window into canonical structural blocks.
2717
+ *
2718
+ * Ambient Context clusters are computed FIRST from raw adjacency, so a hidden
2719
+ * Process row can never merge two Context rows that were not adjacent, and a
2720
+ * cluster is a Work boundary exactly like a standalone Context row — except a
2721
+ * snapshot-only cluster, which is carried as a nested part of the surrounding
2722
+ * same-turn Work.
2723
+ *
2724
+ * Snapshot Context rows seen before the first Process of a same-turn run are
2725
+ * held in a CALL-LOCAL pending buffer: they join the run once a real Process
2726
+ * arrives, or materialize as their original Context block(s) when a hard
2727
+ * boundary or the window end arrives first. The buffer never persists across
2728
+ * calls and never invents a Process-free Work span.
2729
+ *
2730
+ * A settled surfaced-interaction card is its own boundary and belongs to
2731
+ * neither the preceding nor the following span. The result partitions
2732
+ * `messages` exactly: every input row appears once, in raw order, either as a
2733
+ * `message` block, a Work member, or a cluster member.
2734
+ * @param messages - the transcript window in raw chronology.
2735
+ */
2736
+ function projectTranscriptStructure(messages) {
2737
+ const clustering = clusterAdjacentAmbientContext(messages);
2738
+ const out = [];
2739
+ let runParts = [];
2740
+ let runMembers = [];
2741
+ let runTurn;
2742
+ let pendingParts = [];
2743
+ let pendingMembers = [];
2744
+ let pendingTurn;
2745
+ const materializePending = () => {
2746
+ for (const part of pendingParts) if (part.kind === "message") out.push({
2747
+ kind: "message",
2748
+ message: part.message
2749
+ });
2750
+ else out.push({
2751
+ kind: "context-cluster",
2752
+ cluster: part.cluster
2753
+ });
2754
+ pendingParts = [];
2755
+ pendingMembers = [];
2756
+ pendingTurn = void 0;
2757
+ };
2758
+ const pushPending = (parts, members, turn) => {
2759
+ if (pendingMembers.length > 0 && pendingTurn !== turn) materializePending();
2760
+ pendingParts.push(...parts);
2761
+ pendingMembers.push(...members);
2762
+ pendingTurn = turn;
2763
+ };
2764
+ const flush = () => {
2765
+ materializePending();
2766
+ const owner = runMembers[0];
2767
+ if (owner !== void 0 && runTurn !== void 0) out.push({
2768
+ kind: "work",
2769
+ span: {
2770
+ kind: "work",
2771
+ turn: runTurn,
2772
+ members: runMembers,
2773
+ owner,
2774
+ parts: runParts
2775
+ }
2776
+ });
2777
+ runParts = [];
2778
+ runMembers = [];
2779
+ runTurn = void 0;
2780
+ };
2781
+ for (const message of messages) {
2782
+ const cluster = clustering.byMember.get(message);
2783
+ if (cluster !== void 0) {
2784
+ if (message !== cluster.owner) continue;
2785
+ if (!isSnapshotOnlyCluster(cluster)) {
2786
+ flush();
2787
+ out.push({
2788
+ kind: "context-cluster",
2789
+ cluster
2790
+ });
2791
+ continue;
2792
+ }
2793
+ if (runMembers.length > 0) {
2794
+ if (runTurn === cluster.turn) {
2795
+ runParts.push({
2796
+ kind: "context-cluster",
2797
+ cluster
2798
+ });
2799
+ runMembers.push(...cluster.members);
2800
+ continue;
2801
+ }
2802
+ flush();
2803
+ }
2804
+ pushPending([{
2805
+ kind: "context-cluster",
2806
+ cluster
2807
+ }], cluster.members, cluster.turn);
2808
+ continue;
2809
+ }
2810
+ if (isFoldableWorkContext(message, clustering.byMember)) {
2811
+ if (runMembers.length > 0) {
2812
+ if (runTurn === message.turn) {
2813
+ runParts.push({
2814
+ kind: "message",
2815
+ message
2816
+ });
2817
+ runMembers.push(message);
2818
+ continue;
2819
+ }
2820
+ flush();
2821
+ }
2822
+ pushPending([{
2823
+ kind: "message",
2824
+ message
2825
+ }], [message], message.turn);
2826
+ continue;
2827
+ }
2828
+ if (isSurfacedInteractionTool(message)) {
2829
+ flush();
2830
+ out.push({
2831
+ kind: "message",
2832
+ message
2833
+ });
2834
+ continue;
2835
+ }
2836
+ if (isTranscriptWorkMember(message)) {
2837
+ if (runMembers.length > 0 && runTurn !== message.turn) flush();
2838
+ if (runMembers.length === 0) {
2839
+ if (pendingMembers.length > 0 && pendingTurn !== message.turn) materializePending();
2840
+ runParts = pendingParts;
2841
+ runMembers = pendingMembers;
2842
+ pendingParts = [];
2843
+ pendingMembers = [];
2844
+ pendingTurn = void 0;
2845
+ }
2846
+ runParts.push({
2847
+ kind: "message",
2848
+ message
2849
+ });
2850
+ runMembers.push(message);
2851
+ runTurn = message.turn;
2852
+ continue;
2853
+ }
2854
+ flush();
2855
+ out.push({
2856
+ kind: "message",
2857
+ message
2858
+ });
2859
+ }
2860
+ flush();
2861
+ return out;
2862
+ }
2863
+ /**
2864
+ * Map every Work member to its canonical span in one linear pass. Disclosure,
2865
+ * search and pruning read Work ownership through THIS index instead of
2866
+ * scanning a preset materialization (or re-projecting Compact) merely to ask
2867
+ * "which Work span owns this row?".
2868
+ * @param structure - the canonical structural blocks for one window.
2869
+ */
2870
+ function workByMemberOf(structure) {
2871
+ const byMember = /* @__PURE__ */ new Map();
2872
+ for (const block of structure) {
2873
+ if (block.kind !== "work") continue;
2874
+ for (const member of block.span.members) byMember.set(member, block.span);
2875
+ }
2876
+ return byMember;
2877
+ }
2878
+ /**
2879
+ * Map every Context-cluster member to its canonical cluster. Presentation
2880
+ * layers that reorder or hoist rows (collapsed/expanded Focus) consume THIS
2881
+ * identity instead of re-clustering the reordered sequence, so canonical
2882
+ * membership stays the only cluster authority. Snapshot-only clusters nested
2883
+ * inside a Work span are included: their members must resolve to BOTH their
2884
+ * Work and cluster ancestors for disclosure/search.
2885
+ * @param structure - the canonical structural blocks for one window.
2886
+ */
2887
+ function clusterByMemberOf(structure) {
2888
+ const byMember = /* @__PURE__ */ new Map();
2889
+ const add = (cluster) => {
2890
+ for (const member of cluster.members) byMember.set(member, cluster);
2891
+ };
2892
+ for (const block of structure) {
2893
+ if (block.kind === "context-cluster") {
2894
+ add(block.cluster);
2895
+ continue;
2896
+ }
2897
+ if (block.kind !== "work") continue;
2898
+ for (const part of block.span.parts) if (part.kind === "context-cluster") add(part.cluster);
2899
+ }
2900
+ return byMember;
2901
+ }
2902
+ //#endregion
2903
+ //#region src/tui/transcript/context-summary.ts
2904
+ /**
2905
+ * Renderer-neutral structured summary of one ambient Context cluster.
2906
+ *
2907
+ * The collapsed cluster header summarizes its members from STRUCTURED
2908
+ * provenance only — each row's producer label or its declared form, never
2909
+ * arbitrary payload text. Duplicate labels compress to `label ×N` for display
2910
+ * only: the underlying transcript rows are never deduplicated, reordered or
2911
+ * removed.
2912
+ *
2913
+ * This module derives strings only; the header chrome (disclosure marker,
2914
+ * identity icon, theme, width) belongs to the PiTui component in
2915
+ * `tui/components/transcript/context-cluster.ts`.
2916
+ * @module @xmoon76/dsh-pi-tui/tui/transcript/context-summary
2917
+ */
2918
+ /** The structured display name of one ambient Context member: its producer
2919
+ * label, else its declared form, else the generic role name. Never payload
2920
+ * text. */
2921
+ function memberDisplayName(member) {
2922
+ if (member.kind !== "system") return "Context";
2923
+ if (member.label !== void 0 && member.label !== "") return member.label;
2924
+ const form = contextFormOf(member);
2925
+ return form === void 0 ? "Context" : form;
2926
+ }
2927
+ /**
2928
+ * The compressed summary parts of one cluster, in first-seen member order:
2929
+ * consecutive runs of the same display name become `name ×N`. Display-only —
2930
+ * the caller must not treat the parts as the member list.
2931
+ */
2932
+ function contextClusterSummaryParts(cluster) {
2933
+ const parts = [];
2934
+ const counts = /* @__PURE__ */ new Map();
2935
+ const order = [];
2936
+ for (const member of cluster.members) {
2937
+ const name = memberDisplayName(member);
2938
+ const seen = counts.get(name);
2939
+ if (seen === void 0) {
2940
+ counts.set(name, 1);
2941
+ order.push(name);
2942
+ } else counts.set(name, seen + 1);
2943
+ }
2944
+ for (const name of order) {
2945
+ const count = counts.get(name) ?? 1;
2946
+ parts.push(count > 1 ? `${name} ×${count}` : name);
2947
+ }
2948
+ return parts;
2949
+ }
2950
+ //#endregion
2951
+ export { sameWorkspace as $, readFoldedPreview as A, isSurfacedInteractionToolName as At, toolTitle as B, imageFoldedPreview as C, contextIconSemantic as Ct, parseReadEnvelopes as D, isPostTurnReplayEvidence as Dt, parseImageEnvelope as E, contextSummary as Et, systemContextBody as F, userBlocksVisibleNow as Ft, formatSessionAge as G, writeFoldedPreview as H, toolCardHeader as I, sessionPickerItem as J, sanitizeTerminalText as K, toolIconSemantic as L, resultTextLines as M, finalizedBlockFallbackText as Mt, skillFoldedPreview as N, openOpaqueBlockFallbackText as Nt, parseSkillEnvelope as O, isSurfacedContext as Ot, subagentModelDisplay as P, textWithAttachmentMarkers as Pt, buildSessionTree as Q, toolPresenterFrom as R, goalResultSummary as S, contextFormOf as St, parseCallPreview as T, contextProvenance as Tt, fileAttachmentSummary as U, webCardLines as V, findSessionMatch as W, shortSessionId as X, sessionSearchItem as Y, workspaceKey as Z, focusToolDisplay as _, sanitizeDisplayLog as _t, projectTranscriptStructure as a, formatHintKeys as at, genericRawInputLines as b, runSyncDisposalSteps as bt, contextPresentationKind as c, isBuiltInPresetRow as ct, GOAL_TOOL_NAMES as d, effortChoicesOf as dt, sanitizeSessionSearchInput as et, askAnswersLines as f, initialEffortOf as ft, firstLine as g, singlePhysicalLine as gt, compactToolPresentation as h, sanitizedPhysicalLine as ht, isTranscriptWorkMember as i, TSP_CONTINUED_INSPECTION_LABEL as it, relativizeToCwd as j, markPostTurnReplayEvidence as jt, parseWriteEnvelope as k, isSurfacedInteractionTool as kt, isNoticeContext as l, presetDisplayText as lt, compactToolExpandedLines as m, projectModelDirectory as mt, clusterByMemberOf as n, HISTORY_CHORDS as nt, workByMemberOf as o, formatKeyId as ot, askAnswersSummary as p, modelIdentity as pt, sessionLabelParts as q, isFoldableWorkContext as r, JOB_LOCAL_KEYS as rt, clusterAdjacentAmbientContext as s, formatLeaderSequence as st, contextClusterSummaryParts as t, sessionRowMatchesQuery as tt, FOLDED_JSON_RESULT_TOOLS as u, PROVIDER_DEFAULT as ut, foldedCallPreview as v, sanitizeDisplayText as vt, isCompactActionTool as w, contextPresentation as wt, goalResultLines as x, runSyncDisposalStepsWithPrimary as xt, foldedResultSummaryFor as y, formatBytes as yt, toolSummaryKeys as z };