@xmoon76/dsh-pi-tui 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.en.md +28 -7
  2. package/README.md +25 -6
  3. package/dist/application-runtime-CbBO4bY-.mjs +6860 -0
  4. package/dist/bootstrap-DLOydLLj.mjs +108410 -0
  5. package/dist/builtins.mjs +2 -3
  6. package/dist/client-bootstrap-DwSFzcTW.mjs +872 -0
  7. package/dist/context-summary-Bz0AGXa1.mjs +12027 -0
  8. package/dist/{context-summary-DAisTA_7.mjs → context-summary-D9mhxPXL.mjs} +1468 -10
  9. package/dist/custom-items-CKrOBCox.mjs +655 -0
  10. package/dist/disposal-BYBbEpVY.mjs +54 -0
  11. package/dist/dispose-cause-BzcXo4hu.mjs +123 -0
  12. package/dist/dist-C7QMk0ws.mjs +15431 -0
  13. package/dist/{entry-control-DvSrndWd.mjs → entry-control-DnduyDiw.mjs} +12 -31
  14. package/dist/{extensions-CcuMY4n2.mjs → extensions-pcFiH7Qe.mjs} +758 -68
  15. package/dist/extensions.mjs +1 -1
  16. package/dist/host-bootstrap-CKdfLkNS.mjs +188 -0
  17. package/dist/host-foundation-probe-CYHsbAw6.mjs +143 -0
  18. package/dist/host-prerequisites-9JBTtVNu.mjs +36 -0
  19. package/dist/host-runtime.d.mts +26 -0
  20. package/dist/host-runtime.mjs +450 -0
  21. package/dist/index.d.mts +8 -1
  22. package/dist/index.mjs +5192 -2118
  23. package/dist/local-client.mjs +1681 -188
  24. package/dist/local-discovery-CXnLT4GF.mjs +755 -0
  25. package/dist/local-discovery-DVFFpfBG.mjs +2 -0
  26. package/dist/local-host.mjs +927 -78
  27. package/dist/local-transport-C9aonplC.mjs +513 -0
  28. package/dist/performance-host.d.mts +2 -2
  29. package/dist/performance-host.mjs +258 -1
  30. package/dist/pi-tui-remote-contribution-DRk6Tl3J.mjs +78 -0
  31. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  32. package/dist/pi-tui-terminal-progress-contract-XTQKj-WW.mjs +905 -0
  33. package/dist/{runtime-vc4mdr-R.mjs → runtime-Bh5OsftD.mjs} +655 -675
  34. package/dist/runtime-C5ROZqFj.mjs +2 -0
  35. package/dist/{session-tdJHLnJR.mjs → session-4keoXjk0.mjs} +2341 -217
  36. package/dist/session-B2zqv4wr.mjs +10869 -0
  37. package/dist/{startup-JaVZoTIl.mjs → startup-Ct2UUjUL.mjs} +7 -6
  38. package/dist/startup.d.mts +1 -1
  39. package/dist/startup.mjs +1 -1
  40. package/dist/{client-bootstrap-F5DHFI9t.mjs → terminal-progress-source-BhufrZ74.mjs} +3431 -3007
  41. package/dist/terminal-progress-source-CsBinCJ_.mjs +965 -0
  42. package/package.json +125 -116
  43. package/dist/host-bootstrap-DAgKknbY.mjs +0 -119
  44. package/dist/performance-host-CcDJjjVA.mjs +0 -266
  45. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  46. package/dist/terminal-progress-source-xor3vakJ.mjs +0 -2256
@@ -1,5 +1,6 @@
1
- import { t as cancellationError } from "./tasks-D_z5Yjjr.mjs";
2
- import { $t as contextFormOf, B as systemContextBody, Ct as effortChoicesOf, Dt as sanitizedPhysicalLine, Et as projectModelDirectory, G as toolTitle, I as relativizeToCwd, Mt as formatBytes, Nt as runSyncDisposalSteps, St as PROVIDER_DEFAULT, Ut as subCallDisplayStatus, V as toolCardHeader, X as formatSessionAge, Z as sanitizeTerminalText, a as projectTranscriptStructure, at as sanitizeSessionSearchInput, bt as isBuiltInPresetRow, c as contextPresentationKind, d as assistantVisualPresentation, ft as TSP_CONTINUED_INSPECTION_LABEL, ht as TSP_VISUAL_SELECT_LABEL, it as sameWorkspace, jt as sanitizeDisplayText, mt as TSP_VISUAL_COPY_LABEL, nt as workspaceKey, pt as TSP_VISUAL_CHORDS, rt as buildSessionTree, t as contextClusterSummaryParts, tt as shortSessionId, u as planVisualPlacement, wt as initialEffortOf, xt as presetDisplayText, yt as matchesKeyId } from "./context-summary-DAisTA_7.mjs";
1
+ import { vt as hideFooterRefInTsp } from "./extensions-pcFiH7Qe.mjs";
2
+ import { o as customItemName, v as cancellationError } from "./custom-items-CKrOBCox.mjs";
3
+ import { $ as imageProtocolPreference, At as effortChoicesOf, B as relativizeToCwd, Bt as TSP_FOOTER_NOTICES, Dt as isBuiltInPresetRow, Et as matchesKeyId, G as toolCardHeader, Ht as runSyncDisposalSteps, Nt as projectModelDirectory, Ot as presetDisplayText, Pt as sanitizedPhysicalLine, Qt as subCallDisplayStatus, Rt as sanitizeDisplayText, St as TSP_VISUAL_SELECT_LABEL, W as systemContextBody, Y as toolTitle, bt as TSP_VISUAL_CHORDS, cn as contextFormOf, ct as buildSessionTree, d as planVisualPlacement, f as assistantVisualPresentation, g as createBuiltinFooterRegistry, jt as initialEffortOf, kt as PROVIDER_DEFAULT, l as contextPresentationKind, lt as sameWorkspace, nt as sanitizeTerminalText, o as projectTranscriptStructure, ot as shortSessionId, pt as FooterCustomItemCatalog, st as workspaceKey, t as contextClusterSummaryParts, tt as formatSessionAge, ut as sanitizeSessionSearchInput, xt as TSP_VISUAL_COPY_LABEL, yt as TSP_CONTINUED_INSPECTION_LABEL, zt as formatBytes } from "./context-summary-D9mhxPXL.mjs";
3
4
  import { A as chartValueRows, B as humanFacingVisualResult, D as chartHumanText, L as PRESENT_VISUAL_TOOL_NAME, O as chartProjection, T as chartDisplayTitle, _ as authorizeSvg, b as svgDetailRows, d as visualFactLine, f as visualParts, j as admitSvg, m as visualPartsFromText, x as svgDigest } from "./runtime-status-0lp9CM0V.mjs";
4
5
  import { View, connect, html, span, ui } from "@stencil-hq/tern";
5
6
  //#region src/tui/tsp/editor.ts
@@ -173,6 +174,67 @@ function createTspComposer(sinks) {
173
174
  };
174
175
  }
175
176
  //#endregion
177
+ //#region src/tui/tsp/picker-text.ts
178
+ const graphemeSegmenter$2 = new Intl.Segmenter("en", { granularity: "grapheme" });
179
+ /**
180
+ * East Asian Wide/Fullwidth, emoji and supplementary planes occupy two columns;
181
+ * everything else one. A conservative classification is fine here: it only makes
182
+ * a wrap earlier and the layout budget smaller.
183
+ */
184
+ const WIDE_GRAPHEME = /[\u1100-\u115F\u2E80-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]|[\u{1F000}-\u{1FAFF}]|[\u{20000}-\u{3FFFD}]/u;
185
+ const columnsOf = (grapheme) => {
186
+ if (grapheme === " ") return 3;
187
+ return WIDE_GRAPHEME.test(grapheme) ? 2 : 1;
188
+ };
189
+ /** The display columns of one text (never UTF-16 units). */
190
+ function displayWidth(text) {
191
+ let width = 0;
192
+ for (const { segment } of graphemeSegmenter$2.segment(text)) width += columnsOf(segment);
193
+ return width;
194
+ }
195
+ /**
196
+ * Clamp `text` to `columns` display columns with a MIDDLE ellipsis: a head and a
197
+ * tail both survive.
198
+ *
199
+ * {@link clampColumns} keeps the head only, which is enough when the value's tail
200
+ * carries nothing (`fact` rows). A strip chip is the ONE place an advertised effort
201
+ * NAME is shown for a candidate that is not the draft, and names are free-form: two
202
+ * of them can differ only in their tail (`Extended thinking (low)` vs
203
+ * `Extended thinking (high)`), where a head-only clamp would render one label for
204
+ * two different candidates. The ellipsis is the design language's content
205
+ * truncation; the complete text stays with its owner.
206
+ */
207
+ function clampMiddle(text, columns) {
208
+ if (displayWidth(text) <= columns) return text;
209
+ const budget = Math.max(2, columns - 1);
210
+ const head = Math.max(1, Math.ceil(budget / 2));
211
+ const tail = Math.max(1, budget - head);
212
+ const graphemes = [...graphemeSegmenter$2.segment(text)].map((entry) => entry.segment);
213
+ const take = (source, room) => {
214
+ const kept = [];
215
+ let used = 0;
216
+ for (const grapheme of source) {
217
+ const cell = columnsOf(grapheme);
218
+ if (used + cell > room) break;
219
+ kept.push(grapheme);
220
+ used += cell;
221
+ }
222
+ return kept;
223
+ };
224
+ const left = take(graphemes, head).join("");
225
+ const right = take([...graphemes].reverse(), tail).reverse().join("");
226
+ return `${left.trimEnd()}…${right.trimStart()}`;
227
+ }
228
+ /**
229
+ * The ONE-line form of a text: every whitespace run — an explicit LF, CRLF, CR
230
+ * or Unicode line/paragraph separator included — collapses to a single space, so
231
+ * the result is exactly one rendered line. The complete value always stays
232
+ * readable on a Details page.
233
+ */
234
+ function oneLine(text) {
235
+ return text.replace(/\s+/gu, " ").trim();
236
+ }
237
+ //#endregion
176
238
  //#region src/tui/tsp/interaction.ts
177
239
  /**
178
240
  * TspInteractionSeat (PR3-B B3 — the B3 addendum's §3.4-§3.8): the TSP
@@ -209,6 +271,51 @@ const LAYER_KEY = "interaction-layer";
209
271
  const LAYER_ID = "layer";
210
272
  /** The free-text `ui.input` key; its node id is `layer.modal-<epoch>.answer`. */
211
273
  const ANSWER_KEY = "answer";
274
+ /** The native Questions form's key, scoped by the page visit. */
275
+ const QUESTIONS_KEY = "qform";
276
+ /** The native Tool approval's key. */
277
+ const APPROVAL_TOOL_KEY = "approval-tool";
278
+ /** The Review button row's key, scoped by the page visit. */
279
+ const REVIEW_ROW_KEY = "review-actions";
280
+ /** The safe (optionless/Masked) form's button row key, scoped by the visit. */
281
+ const FORM_ROW_KEY = "form-actions";
282
+ /**
283
+ * The arguments block's bound: a FRACTION of its overlay body, so the native
284
+ * decision controls stay inside the visible card on a narrow or short pane
285
+ * while the FULL text stays readable by scrolling. It is a relation to the real
286
+ * container, never a measured pixel or line budget.
287
+ */
288
+ const APPROVAL_ARGS_BOUNDS = { h: .5 };
289
+ /**
290
+ * The one scoped role of the native Tool approval. The seat paints it and the
291
+ * renderer's ONE scoped stylesheet keys on it, so the two cannot drift: it is
292
+ * exported for exactly that reason, not as a general-purpose surface API.
293
+ */
294
+ const NATIVE_APPROVAL_ROLE = "dsh-native-approval";
295
+ /** The Native item token prefix: a stable INDEX, never a source question id. */
296
+ const ITEM_PREFIX = "q-";
297
+ /** The Native choice token prefix: a stable INDEX, never a source label. */
298
+ const CHOICE_PREFIX = "o-";
299
+ /** The pointer action names of the Review page's three real buttons. */
300
+ const REVIEW_SUBMIT_ACTION = "review-submit";
301
+ const REVIEW_BACK_ACTION = "review-back";
302
+ const REVIEW_CANCEL_ACTION = "review-cancel";
303
+ /** The pointer action names of the safe form's three real buttons. */
304
+ const FORM_NEXT_ACTION = "form-next";
305
+ const FORM_BACK_ACTION = "form-back";
306
+ const FORM_CANCEL_ACTION = "form-cancel";
307
+ /** The pointer action of one option of the safe form's own choice list. */
308
+ const FORM_CHOICE_ACTION = "form-choice";
309
+ /** The safe form's choice-list row key, scoped by the visit like its button row. */
310
+ const FORM_CHOICES_KEY = "form-choices";
311
+ /** The native page actions the client emits on the Questions form itself. */
312
+ const PAGE_NEXT = "next";
313
+ const PAGE_BACK = "back";
314
+ const PAGE_SKIP = "skip";
315
+ const PAGE_SUBMIT = "submit";
316
+ /** The native approval actions that may carry a decision at all. */
317
+ const TOOL_ALLOW = "allow";
318
+ const TOOL_DENY = "deny";
212
319
  /** One bullet per grapheme cluster for a masked value's DISPLAY. */
213
320
  const MASK_GLYPH = "•";
214
321
  const segmenter$2 = new Intl.Segmenter("en", { granularity: "grapheme" });
@@ -258,6 +365,15 @@ function maskedValue(text) {
258
365
  function bare(key) {
259
366
  return key.ctrl !== true && key.alt !== true && key.meta !== true && key.shift !== true;
260
367
  }
368
+ /**
369
+ * A bare digit as a 0-based option index — the same numbers the native form
370
+ * prints on its choice keycaps. `Key.name` is a lowercase character, so `1`–`9`
371
+ * arrive as themselves and every other name parses to `NaN`.
372
+ */
373
+ function digitOf(key) {
374
+ const value = Number.parseInt(key.name, 10);
375
+ return Number.isNaN(value) || value < 1 || value > 9 ? void 0 : value - 1;
376
+ }
261
377
  /** One option label with its `(recommended)` presentation suffix split off. */
262
378
  function parseRecommended(label) {
263
379
  const suffix = /\s*\(recommended\)\s*$/i;
@@ -541,6 +657,44 @@ function createTspInteractionSeat(options) {
541
657
  slot.text = draftAt(slot, slot.tab)?.custom ?? "";
542
658
  slot.cursor = slot.text.length;
543
659
  };
660
+ /**
661
+ * The ONE "apply a selection" entry: the keyboard row and the native pointer
662
+ * both arrive here, so there is exactly one answer semantic in the seat.
663
+ * `labels` is the COMPLETE selection the caller wants for the current
664
+ * question. A single-select choice replaces the selection AND clears a custom
665
+ * answer (`submitBatch` prefers a nonblank custom for single-select, so
666
+ * keeping it would submit old text instead of the choice just made) — and the
667
+ * LIVE editor buffer goes with it, or the replaced text would resurrect the
668
+ * moment this question's Other row is opened again. An empty multi-select set
669
+ * clears the choices but never fabricates a skip (the `syncTextDraft` rule).
670
+ * With `toggle` the labels are ADDED to / REMOVED from the existing set (the
671
+ * multi-select rule), so a second pick never discards the first one.
672
+ */
673
+ const applySelection = (slot, labels, toggle = false) => {
674
+ const draft = draftAt(slot, slot.tab);
675
+ const question = questionAt(slot, slot.tab);
676
+ if (draft === void 0 || question === void 0) return;
677
+ if (question.multiSelect !== true && labels.length > 1) return;
678
+ if (toggle && question.multiSelect !== true) return;
679
+ const before = answerKey(draft);
680
+ if (!toggle) draft.selected.clear();
681
+ for (const label of labels) if (toggle) {
682
+ if (draft.selected.has(label)) draft.selected.delete(label);
683
+ else draft.selected.add(label);
684
+ } else draft.selected.add(label);
685
+ if (draft.selected.size > 0) draft.skipped = false;
686
+ if (question.multiSelect !== true && draft.selected.size > 0) {
687
+ draft.custom = "";
688
+ if (slot.textOwner === slot.tab) {
689
+ slot.text = "";
690
+ slot.cursor = 0;
691
+ }
692
+ }
693
+ if (answerKey(draft) !== before) {
694
+ slot.keyboardCursorShown = false;
695
+ notifyMutation(slot);
696
+ }
697
+ };
544
698
  /** The recommended row (intent.approve match, else a `(recommended)` suffix). */
545
699
  const seedHighlight = (slot) => {
546
700
  const seat = seatRows(slot);
@@ -556,20 +710,25 @@ function createTspInteractionSeat(options) {
556
710
  };
557
711
  /** Synchronize the page-local mode after a page change (or at construction). */
558
712
  const syncQuestionState = (slot) => {
713
+ slot.keyboardCursorShown = false;
714
+ seedText(slot);
559
715
  if (optionless(slot)) {
560
716
  slot.editing = slot.tab;
561
- seedText(slot);
562
717
  return;
563
718
  }
564
719
  slot.editing = void 0;
565
720
  seedHighlight(slot);
566
721
  };
722
+ /** The ONE page move. Every entry (keyboard, native Next/Skip/Back/Submit)
723
+ * goes through here, so a new page always gets a new native node id. */
567
724
  const advance = (slot) => {
568
725
  slot.tab += 1;
726
+ slot.visitEpoch += 1;
569
727
  syncQuestionState(slot);
570
728
  };
571
729
  const moveBack = (slot) => {
572
730
  slot.tab = Math.max(0, slot.tab - 1);
731
+ slot.visitEpoch += 1;
573
732
  syncQuestionState(slot);
574
733
  };
575
734
  /** Forward paging with the ONE continue/skip authority (an unanswered
@@ -583,10 +742,38 @@ function createTspInteractionSeat(options) {
583
742
  draft.custom = "";
584
743
  draft.skipped = true;
585
744
  notifyMutation(slot);
745
+ if (active !== slot || slot.settled) return;
586
746
  }
587
747
  }
588
748
  advance(slot);
589
749
  };
750
+ /**
751
+ * An explicit Skip of the CURRENT question: its local answer is dropped (a
752
+ * question the user skipped must never carry an old choice into the final
753
+ * batch), the draft is marked skipped, and the page advances once. This is the
754
+ * native Skip button; the keyboard Right keeps {@link moveForward}'s
755
+ * answered-stays rule.
756
+ */
757
+ const skipCurrent = (slot) => {
758
+ const draft = draftAt(slot, slot.tab);
759
+ if (draft !== void 0) {
760
+ const before = answerKey(draft);
761
+ draft.selected.clear();
762
+ draft.custom = "";
763
+ draft.skipped = true;
764
+ if (slot.textOwner === slot.tab) {
765
+ slot.text = "";
766
+ slot.cursor = 0;
767
+ }
768
+ if (answerKey(draft) !== before) notifyMutation(slot);
769
+ if (active !== slot || slot.settled) return;
770
+ }
771
+ advance(slot);
772
+ };
773
+ /** Open the Review page (the one `tab === questions.length` state). */
774
+ const goReview = (slot) => {
775
+ advance(slot);
776
+ };
590
777
  const enterEdit = (slot) => {
591
778
  slot.editing = slot.tab;
592
779
  seedText(slot);
@@ -655,30 +842,13 @@ function createTspInteractionSeat(options) {
655
842
  enterEdit(slot);
656
843
  return;
657
844
  }
658
- const draft = draftAt(slot, slot.tab);
659
845
  const question = questionAt(slot, slot.tab);
660
- if (draft === void 0 || question === void 0 || row.value === void 0) return;
846
+ if (question === void 0 || row.value === void 0) return;
661
847
  if (question.multiSelect === true) {
662
- if (!draftAnswered(draft)) {
663
- const before = answerKey(draft);
664
- draft.selected.clear();
665
- draft.custom = "";
666
- draft.skipped = true;
667
- if (answerKey(draft) !== before) notifyMutation(slot);
668
- }
669
- advance(slot);
848
+ moveForward(slot);
670
849
  return;
671
850
  }
672
- const before = answerKey(draft);
673
- draft.selected.clear();
674
- draft.selected.add(row.value);
675
- draft.custom = "";
676
- draft.skipped = false;
677
- if (slot.textOwner === slot.tab) {
678
- slot.text = "";
679
- slot.cursor = 0;
680
- }
681
- if (answerKey(draft) !== before) notifyMutation(slot);
851
+ applySelection(slot, [row.value]);
682
852
  advance(slot);
683
853
  };
684
854
  /** Space on a multi-select option (a real change only). */
@@ -691,11 +861,8 @@ function createTspInteractionSeat(options) {
691
861
  }
692
862
  const draft = draftAt(slot, slot.tab);
693
863
  if (draft === void 0 || row.value === void 0) return;
694
- const before = answerKey(draft);
695
- if (draft.selected.has(row.value)) draft.selected.delete(row.value);
696
- else draft.selected.add(row.value);
697
- draft.skipped = false;
698
- if (answerKey(draft) !== before) notifyMutation(slot);
864
+ const labels = [...draft.selected];
865
+ applySelection(slot, draft.selected.has(row.value) ? labels.filter((label) => label !== row.value) : [...labels, row.value]);
699
866
  };
700
867
  /** The final answer batch, normalized EXACTLY like `QuestionFlow.submit()`:
701
868
  * `skipped` → no answer; a nonblank single-select custom replaces the
@@ -929,11 +1096,13 @@ function createTspInteractionSeat(options) {
929
1096
  const seat = seatRows(slot);
930
1097
  if (key.name === "up") {
931
1098
  slot.highlight = Math.max(0, slot.highlight - 1);
1099
+ slot.keyboardCursorShown = true;
932
1100
  options.render();
933
1101
  return true;
934
1102
  }
935
1103
  if (key.name === "down") {
936
1104
  slot.highlight = Math.min(seat.length - 1, slot.highlight + 1);
1105
+ slot.keyboardCursorShown = true;
937
1106
  options.render();
938
1107
  return true;
939
1108
  }
@@ -957,40 +1126,346 @@ function createTspInteractionSeat(options) {
957
1126
  options.render();
958
1127
  return true;
959
1128
  }
1129
+ const digit = digitOf(key);
1130
+ if (digit !== void 0 && bare(key)) {
1131
+ const row = seat[digit];
1132
+ if (row !== void 0 && row.kind === "option" && row.value !== void 0) {
1133
+ const draft = draftAt(slot, slot.tab);
1134
+ if (draft !== void 0) {
1135
+ const multi = questionAt(slot, slot.tab)?.multiSelect === true;
1136
+ applySelection(slot, multi && draft.selected.has(row.value) ? [...draft.selected].filter((label) => label !== row.value) : multi ? [...draft.selected, row.value] : [row.value]);
1137
+ slot.highlight = digit;
1138
+ }
1139
+ }
1140
+ options.render();
1141
+ return true;
1142
+ }
960
1143
  return true;
961
1144
  };
962
1145
  const overlayKey = () => `modal-${modalEpoch}`;
963
- const approvalOverlay = (slot) => {
964
- const body = [ui.text({
965
- key: "tool",
966
- text: sanitizedPhysicalLine(`tool: ${slot.request.toolName}`)
967
- })];
968
- if (slot.request.reason !== void 0 && slot.request.reason !== "") body.push(ui.text({
969
- key: "reason",
970
- text: sanitizeDisplayText(slot.request.reason)
1146
+ /** The wire id of one DIRECT child of the current modal overlay. The id is
1147
+ * the region name plus the keys the tree was really built with — the same
1148
+ * derivation the SDK performs — never a guessed path. */
1149
+ const overlayId = (key) => `${LAYER_ID}.${overlayKey()}.${key}`;
1150
+ /** The native Questions form's key/id for THIS page visit. The visit epoch is
1151
+ * what makes a superseded visit's node id unreachable. */
1152
+ const questionsKey = (slot) => `${QUESTIONS_KEY}-${slot.visitEpoch}`;
1153
+ const questionsId = (slot) => overlayId(questionsKey(slot));
1154
+ /** The SDK's `other` answer child of the native form: keyed `<item>.other`. */
1155
+ const otherKey = (slot) => `${ITEM_PREFIX}${slot.tab}.other`;
1156
+ const otherId = (slot) => `${questionsId(slot)}.${otherKey(slot)}`;
1157
+ /** The Review row's key/id: scoped by the visit, so an earlier visit's
1158
+ * Submit button is a DIFFERENT node and can never commit again. */
1159
+ const reviewRowKey = (slot) => `${REVIEW_ROW_KEY}-${slot.visitEpoch}`;
1160
+ /** The safe form's button row, scoped by the visit for the same reason. */
1161
+ const formRowKey = (slot) => `${FORM_ROW_KEY}-${slot.visitEpoch}`;
1162
+ /** The safe form's own choice list, and one option's pick button inside it. */
1163
+ const formChoicesKey = (slot) => `${FORM_CHOICES_KEY}-${slot.visitEpoch}`;
1164
+ const formChoiceId = (slot, index) => `${overlayId(formChoicesKey(slot))}.${CHOICE_PREFIX}${index}.pick`;
1165
+ /** One button of the current Review row / safe-form row, by its real id. */
1166
+ const rowButtonId = (rowKey, buttonKey) => `${overlayId(rowKey)}.${buttonKey}`;
1167
+ /** Whether the CURRENT page is the native choice/steps presentation. */
1168
+ const usesNativeSteps = (slot) => {
1169
+ if (!options.nativeQuestions || slot.tab >= slot.questions.length) return false;
1170
+ const question = slot.questions[slot.tab];
1171
+ return question.masked !== true && (question.options?.length ?? 0) > 0;
1172
+ };
1173
+ /**
1174
+ * Whether the CURRENT page is a same-style "safe" page (masked or optionless).
1175
+ * It is the ONE predicate behind both the presentation choice and the page's
1176
+ * initial editing state, so an input can never be painted as unreachable.
1177
+ */
1178
+ const safeFormPage = (slot) => {
1179
+ if (slot.tab >= slot.questions.length) return false;
1180
+ return slot.questions[slot.tab].masked === true || optionless(slot);
1181
+ };
1182
+ /** Whether the CURRENT page uses the same-style safe form (a non-native pane
1183
+ * keeps the legacy text presentation instead: it has no `button` kind). */
1184
+ const usesSafeForm = (slot) => options.nativeQuestions && safeFormPage(slot);
1185
+ /**
1186
+ * The Native `items` projection: one entry per source question, IN SOURCE
1187
+ * ORDER, addressed by a stable index token (`q-N` / `o-N`) so a duplicate
1188
+ * option label or an odd source id can never collide with another answer.
1189
+ * The mapping lives only here — there is no second dictionary — and the
1190
+ * projection neither reads nor writes the Host. Labels keep the request's
1191
+ * real text (nothing is shortened for a screenshot); `recommended` is a
1192
+ * plain, non-misleading note on the real option. `required` is deliberately
1193
+ * `false` for every question: this flow allows Skip, so the Native form must
1194
+ * not invent a stronger business rule than the source request carries.
1195
+ */
1196
+ const nativeItems = (slot) => slot.questions.map((question, index) => {
1197
+ const choices = (question.options ?? []).map((option, at) => {
1198
+ const { label } = parseRecommended(option.label);
1199
+ const recommended = isRecommended(question, option);
1200
+ const detail = option.description === void 0 || option.description === "" ? void 0 : sanitizeDisplayText(option.description);
1201
+ return {
1202
+ value: `${CHOICE_PREFIX}${at}`,
1203
+ label: sanitizedPhysicalLine(label),
1204
+ ...recommended ? { detail: detail === void 0 ? "Recommended" : `${detail} · Recommended` } : detail === void 0 ? {} : { detail }
1205
+ };
1206
+ });
1207
+ const plain = choices.length === 0 ? {} : { choices };
1208
+ return {
1209
+ id: `${ITEM_PREFIX}${index}`,
1210
+ prompt: sanitizeDisplayText(question.question),
1211
+ ...question.detail === void 0 || question.detail === "" ? {} : { description: sanitizeDisplayText(question.detail) },
1212
+ ...plain,
1213
+ ...question.multiSelect === true ? { multi: true } : {},
1214
+ ...choices.length === 0 || question.masked === true ? {} : { other: { placeholder: "Type something…" } },
1215
+ required: false
1216
+ };
1217
+ });
1218
+ /**
1219
+ * The Native `answers` projection: a Render Props view of `slot.drafts`, and
1220
+ * a SELECTION-ONLY one. A custom answer belongs to the controlled `other`
1221
+ * input (two different semantics are never merged into one Native value), a
1222
+ * skipped or unanswered question is simply absent, and a masked question is
1223
+ * NEVER projected — its plaintext can therefore not reach `answers` at all.
1224
+ * This is not a second answer store: every later decision re-derives from the
1225
+ * drafts.
1226
+ */
1227
+ const nativeAnswers = (slot) => {
1228
+ const answers = {};
1229
+ for (const [index, question] of slot.questions.entries()) {
1230
+ if (question.masked === true) continue;
1231
+ const draft = slot.drafts[index];
1232
+ const picked = [];
1233
+ for (const [at, option] of (question.options ?? []).entries()) if (draft.selected.has(option.label)) picked.push(`${CHOICE_PREFIX}${at}`);
1234
+ if (picked.length === 0) continue;
1235
+ answers[`${ITEM_PREFIX}${index}`] = question.multiSelect === true ? picked : picked[0];
1236
+ }
1237
+ return answers;
1238
+ };
1239
+ /** The one-line keyboard cursor of a page the native form cannot highlight. */
1240
+ /**
1241
+ * The one-line keyboard cursor of the current page: which row the arrows are
1242
+ * on, and the key that actually acts on it. The hint is the REAL binding — a
1243
+ * multi page toggles with Space and continues with Enter, a single page
1244
+ * selects with Enter — so a user who follows it can never be misled.
1245
+ */
1246
+ const keyboardCursorLine = (slot) => {
1247
+ const row = seatRows(slot)[slot.highlight];
1248
+ if (row === void 0) return "Keyboard cursor: none · up/down move";
1249
+ const label = sanitizedPhysicalLine(row.label);
1250
+ if (row.kind === "other") return `Keyboard cursor: [${slot.highlight + 1}] ${label} · Enter type`;
1251
+ const multi = questionAt(slot, slot.tab)?.multiSelect === true;
1252
+ return `Keyboard cursor: [${slot.highlight + 1}] ${label} · ` + (multi ? "space toggle · enter continue" : "enter select");
1253
+ };
1254
+ /**
1255
+ * The native page's answer field, as the SDK's `<item>.other` child. A masked
1256
+ * page sends BULLETS only (one per grapheme, with the caret counted the same
1257
+ * way), so the plaintext can never reach the frame; a plain page sends its own
1258
+ * text. Either way the value is the CURRENT page's buffer (see
1259
+ * `syncQuestionState`), never another page's.
1260
+ */
1261
+ const nativeOtherField = (slot) => {
1262
+ if (questionAt(slot, slot.tab)?.masked === true) return {
1263
+ text: maskedValue(slot.text),
1264
+ cursor: graphemeCountBefore(slot.text, slot.cursor),
1265
+ placeholder: "Type your answer"
1266
+ };
1267
+ return {
1268
+ text: slot.text,
1269
+ cursor: slot.cursor,
1270
+ placeholder: "Type something…"
1271
+ };
1272
+ };
1273
+ /**
1274
+ * Whether one option of the CURRENT page is the recommended one.
1275
+ *
1276
+ * There is exactly ONE rule — the one `seatRows` already applies: an explicit
1277
+ * `(recommended)` suffix OR the request's `intent.approve` label. Every
1278
+ * projection (native steps, safe form, legacy rows) reads it here, so a
1279
+ * projection can never silently redefine what "recommended" means.
1280
+ */
1281
+ const isRecommended = (question, option) => {
1282
+ const { recommended } = parseRecommended(option.label);
1283
+ return recommended || question.intent?.approve !== void 0 && option.label === question.intent.approve;
1284
+ };
1285
+ /** The native choice/steps page of the current question. */
1286
+ const nativeStepsOverlay = (slot) => {
1287
+ const question = slot.questions[slot.tab];
1288
+ const total = slot.questions.length;
1289
+ const body = [];
1290
+ const statusText = slot.status?.text;
1291
+ if (statusText !== void 0 && statusText !== "") body.push(ui.text({
1292
+ key: "status",
1293
+ text: sanitizedPhysicalLine(statusText)
971
1294
  }));
972
- if (slot.request.arguments !== void 0) body.push(ui.code({
973
- key: "args",
974
- text: sanitizeDisplayText(slot.request.arguments)
1295
+ if (question.header !== void 0) body.push(ui.text({
1296
+ key: "header",
1297
+ text: sanitizedPhysicalLine(question.header)
975
1298
  }));
976
- if (slot.request.danger === true) body.push(ui.text({
977
- key: "danger",
978
- text: "Dangerous command",
979
- tone: "error"
1299
+ body.push(ui.questions({
1300
+ key: questionsKey(slot),
1301
+ variant: "steps",
1302
+ items: nativeItems(slot),
1303
+ step: slot.tab,
1304
+ answers: nativeAnswers(slot),
1305
+ submit: "Review answers"
1306
+ }, ui.input({
1307
+ key: otherKey(slot),
1308
+ ...nativeOtherField(slot)
1309
+ })));
1310
+ if (slot.keyboardCursorShown) body.push(ui.text({
1311
+ key: "keyboard-cursor",
1312
+ text: keyboardCursorLine(slot)
1313
+ }));
1314
+ return ui.overlay({
1315
+ key: overlayKey(),
1316
+ modal: true,
1317
+ head: `Question ${slot.tab + 1}/${total}`,
1318
+ anchor: "center",
1319
+ size: "lg"
1320
+ }, ...body);
1321
+ };
1322
+ /**
1323
+ * The optionless / masked page: the same overlay style, but a real controlled
1324
+ * input and REAL buttons — never a text line that pretends to be one. A
1325
+ * masked value is projected as bullets ONLY (the input's own `secret` affordance
1326
+ * would hand the plaintext to the client, so the seat keeps computing bullets).
1327
+ */
1328
+ const safeFormOverlay = (slot) => {
1329
+ const question = slot.questions[slot.tab];
1330
+ const total = slot.questions.length;
1331
+ const masked = question.masked === true;
1332
+ const rowKey = formRowKey(slot);
1333
+ const body = [];
1334
+ const statusText = slot.status?.text;
1335
+ if (statusText !== void 0 && statusText !== "") body.push(ui.text({
1336
+ key: "status",
1337
+ text: sanitizedPhysicalLine(statusText)
1338
+ }));
1339
+ if (question.header !== void 0) body.push(ui.text({
1340
+ key: "header",
1341
+ text: sanitizedPhysicalLine(question.header)
980
1342
  }));
981
1343
  body.push(ui.text({
982
- key: "hint",
983
- text: "y allow once · n reject · esc cancel"
1344
+ key: "question",
1345
+ wrap: "word",
1346
+ text: sanitizeDisplayText(question.question)
984
1347
  }));
1348
+ if (question.detail !== void 0) body.push(ui.text({
1349
+ key: "detail",
1350
+ wrap: "word",
1351
+ text: sanitizeDisplayText(question.detail)
1352
+ }));
1353
+ seatRows(slot);
1354
+ const options = question.options ?? [];
1355
+ if (options.length > 0) body.push(ui.col({
1356
+ key: formChoicesKey(slot),
1357
+ gap: "xs"
1358
+ }, ...options.map((option, index) => ui.col({
1359
+ key: `${CHOICE_PREFIX}${index}`,
1360
+ gap: "none"
1361
+ }, ui.button({
1362
+ key: "pick",
1363
+ text: sanitizedPhysicalLine(parseRecommended(option.label).label + (isRecommended(question, option) ? " (recommended)" : "")),
1364
+ keys: index < 9 ? [String(index + 1)] : void 0,
1365
+ on: draftAt(slot, slot.tab)?.selected.has(option.label) === true,
1366
+ actions: { click: FORM_CHOICE_ACTION }
1367
+ }), ...option.description === void 0 || option.description === "" ? [] : [ui.text({
1368
+ key: "detail",
1369
+ wrap: "word",
1370
+ text: sanitizeDisplayText(option.description)
1371
+ })]))));
1372
+ body.push(ui.input({
1373
+ key: ANSWER_KEY,
1374
+ text: masked ? maskedValue(slot.text) : slot.text,
1375
+ cursor: masked ? graphemeCountBefore(slot.text, slot.cursor) : slot.cursor,
1376
+ prompt: "> ",
1377
+ placeholder: "Type your answer"
1378
+ }));
1379
+ if (options.length > 0 && slot.keyboardCursorShown) body.push(ui.text({
1380
+ key: "keyboard-cursor",
1381
+ text: keyboardCursorLine(slot)
1382
+ }));
1383
+ body.push(ui.row({
1384
+ key: rowKey,
1385
+ gap: "md",
1386
+ justify: "between"
1387
+ }, ui.button({
1388
+ key: "back",
1389
+ text: "Back",
1390
+ actions: { click: FORM_BACK_ACTION }
1391
+ }), ui.button({
1392
+ key: "next",
1393
+ text: "Next",
1394
+ variant: "primary",
1395
+ ...slot.editing === slot.tab ? { keys: ["⏎"] } : {},
1396
+ actions: { click: FORM_NEXT_ACTION }
1397
+ }), ui.button({
1398
+ key: "cancel",
1399
+ text: "Cancel",
1400
+ actions: { click: FORM_CANCEL_ACTION }
1401
+ })));
985
1402
  return ui.overlay({
986
1403
  key: overlayKey(),
987
1404
  modal: true,
988
- head: "Approval required",
1405
+ head: `Question ${slot.tab + 1}/${total}`,
989
1406
  anchor: "center",
990
- size: "md"
1407
+ size: "lg"
991
1408
  }, ...body);
992
1409
  };
993
- const questionOverlay = (slot) => {
1410
+ /**
1411
+ * The Review page (the ONE `tab === questions.length` state): the real
1412
+ * question text with its real answer in source order, so the confirmation is
1413
+ * readable rather than indexed. Its three buttons are the only pointer path to
1414
+ * the original `submitBatch` / back / `cancelQuestion`.
1415
+ */
1416
+ const reviewOverlay = (slot) => {
1417
+ const rowKey = reviewRowKey(slot);
1418
+ const answered = slot.drafts.filter((draft) => !draft.skipped && (draft.selected.size > 0 || draft.custom.trim() !== "")).length;
1419
+ const skipped = slot.drafts.filter((draft) => draft.skipped).length;
1420
+ const unanswered = slot.drafts.length - answered - skipped;
1421
+ const body = [ui.text({
1422
+ key: "summary",
1423
+ text: sanitizedPhysicalLine(`${slot.questions.length} question${slot.questions.length === 1 ? "" : "s"} · ${answered} answered · ${skipped} skipped` + (unanswered === 0 ? "" : ` · ${unanswered} not answered`))
1424
+ })];
1425
+ for (const [index, question] of slot.questions.entries()) {
1426
+ const draft = slot.drafts[index];
1427
+ body.push(ui.col({
1428
+ key: `entry-${index}`,
1429
+ gap: "none"
1430
+ }, ui.text({
1431
+ key: "prompt",
1432
+ wrap: "word",
1433
+ text: sanitizeDisplayText(question.question)
1434
+ }), ui.text({
1435
+ key: "answer",
1436
+ wrap: "word",
1437
+ text: sanitizeDisplayText(answerSummary(question, draft))
1438
+ })));
1439
+ }
1440
+ body.push(ui.row({
1441
+ key: rowKey,
1442
+ gap: "md",
1443
+ justify: "between"
1444
+ }, ui.button({
1445
+ key: "back",
1446
+ text: "Back",
1447
+ actions: { click: REVIEW_BACK_ACTION }
1448
+ }), ui.button({
1449
+ key: "submit",
1450
+ text: "Submit answers",
1451
+ variant: "primary",
1452
+ keys: ["⏎"],
1453
+ actions: { click: REVIEW_SUBMIT_ACTION }
1454
+ }), ui.button({
1455
+ key: "cancel",
1456
+ text: "Cancel",
1457
+ actions: { click: REVIEW_CANCEL_ACTION }
1458
+ })));
1459
+ return ui.overlay({
1460
+ key: overlayKey(),
1461
+ modal: true,
1462
+ head: "Review answers",
1463
+ anchor: "center",
1464
+ size: "lg"
1465
+ }, ...body);
1466
+ };
1467
+ /** The legacy text form, kept for a pane without the native interaction kinds. */
1468
+ const legacyQuestionOverlay = (slot) => {
994
1469
  const total = slot.questions.length;
995
1470
  const body = [];
996
1471
  if (slot.tab >= total) {
@@ -1114,6 +1589,105 @@ function createTspInteractionSeat(options) {
1114
1589
  size: "md"
1115
1590
  }, ...body);
1116
1591
  };
1592
+ /**
1593
+ * The presentation this pane negotiated: Review, then the safe form for a
1594
+ * masked/optionless page, then the native steps form — all as ordinary
1595
+ * children of the ONE modal overlay, and all reading the same Slot. A pane
1596
+ * without the native kinds keeps the legacy text form (a smaller fallback,
1597
+ * not a second flow).
1598
+ */
1599
+ const questionOverlay = (slot) => {
1600
+ if (!options.nativeQuestions) return legacyQuestionOverlay(slot);
1601
+ if (slot.tab >= slot.questions.length) return reviewOverlay(slot);
1602
+ if (usesNativeSteps(slot)) return nativeStepsOverlay(slot);
1603
+ return safeFormOverlay(slot);
1604
+ };
1605
+ /** The native approval: the full tool facts FIRST, then the native control. */
1606
+ const nativeApprovalOverlay = (slot) => {
1607
+ const request = slot.request;
1608
+ const body = [ui.text({
1609
+ key: "tool-name",
1610
+ wrap: "word",
1611
+ text: sanitizedPhysicalLine(`Tool: ${request.toolName}`)
1612
+ })];
1613
+ if (request.reason !== void 0 && request.reason !== "") body.push(ui.text({
1614
+ key: "reason",
1615
+ wrap: "word",
1616
+ text: sanitizeDisplayText(request.reason)
1617
+ }));
1618
+ if (request.danger === true) body.push(ui.badge({
1619
+ key: "danger",
1620
+ tone: "error",
1621
+ text: "Dangerous command"
1622
+ }));
1623
+ if (request.arguments !== void 0) body.push(ui.scroll({
1624
+ key: "args",
1625
+ variant: "bar",
1626
+ max: APPROVAL_ARGS_BOUNDS
1627
+ }, ui.code({
1628
+ key: "body",
1629
+ wrap: true,
1630
+ text: sanitizeDisplayText(request.arguments)
1631
+ })));
1632
+ body.push(ui.tool({
1633
+ key: APPROVAL_TOOL_KEY,
1634
+ role: NATIVE_APPROVAL_ROLE,
1635
+ name: sanitizedPhysicalLine(request.toolName),
1636
+ title: "Approve tool call",
1637
+ status: "ask",
1638
+ confirm: "card",
1639
+ frame: "inline",
1640
+ ask: {
1641
+ text: "Allow this tool call?",
1642
+ allow: "Allow once",
1643
+ deny: "Reject",
1644
+ always: false
1645
+ }
1646
+ }));
1647
+ body.push(ui.text({
1648
+ key: "hint",
1649
+ text: "Y allow once · N reject · Esc cancel"
1650
+ }));
1651
+ return ui.overlay({
1652
+ key: overlayKey(),
1653
+ modal: true,
1654
+ head: "Approval required",
1655
+ anchor: "center",
1656
+ size: "lg"
1657
+ }, ...body);
1658
+ };
1659
+ /** The legacy text approval (a pane without the native approval capability). */
1660
+ const legacyApprovalOverlay = (slot) => {
1661
+ const body = [ui.text({
1662
+ key: "tool",
1663
+ text: sanitizedPhysicalLine(`tool: ${slot.request.toolName}`)
1664
+ })];
1665
+ if (slot.request.reason !== void 0 && slot.request.reason !== "") body.push(ui.text({
1666
+ key: "reason",
1667
+ text: sanitizeDisplayText(slot.request.reason)
1668
+ }));
1669
+ if (slot.request.arguments !== void 0) body.push(ui.code({
1670
+ key: "args",
1671
+ text: sanitizeDisplayText(slot.request.arguments)
1672
+ }));
1673
+ if (slot.request.danger === true) body.push(ui.text({
1674
+ key: "danger",
1675
+ text: "Dangerous command",
1676
+ tone: "error"
1677
+ }));
1678
+ body.push(ui.text({
1679
+ key: "hint",
1680
+ text: "y allow once · n reject · esc cancel"
1681
+ }));
1682
+ return ui.overlay({
1683
+ key: overlayKey(),
1684
+ modal: true,
1685
+ head: "Approval required",
1686
+ anchor: "center",
1687
+ size: "md"
1688
+ }, ...body);
1689
+ };
1690
+ const approvalOverlay = (slot) => options.nativeApproval ? nativeApprovalOverlay(slot) : legacyApprovalOverlay(slot);
1117
1691
  const listOverlay = (callbacks) => {
1118
1692
  const { rows, index } = listState(callbacks);
1119
1693
  const body = rows.map((row, position) => ui.text({
@@ -1132,6 +1706,184 @@ function createTspInteractionSeat(options) {
1132
1706
  size: "md"
1133
1707
  }, ...body);
1134
1708
  };
1709
+ /**
1710
+ * The Review page's three real buttons. The event must address the EXACT
1711
+ * button node id of the CURRENT review visit — not a substring, not the
1712
+ * overlay — so a button of an earlier visit can never submit again.
1713
+ */
1714
+ const reviewActionEvent = (slot, event) => {
1715
+ if (event.id === rowButtonId(reviewRowKey(slot), "submit") && event.act === REVIEW_SUBMIT_ACTION) {
1716
+ submitBatch(slot);
1717
+ return true;
1718
+ }
1719
+ if (event.id === rowButtonId(reviewRowKey(slot), "back") && event.act === REVIEW_BACK_ACTION) {
1720
+ moveBack(slot);
1721
+ options.render();
1722
+ return true;
1723
+ }
1724
+ if (event.id === rowButtonId(reviewRowKey(slot), "cancel") && event.act === REVIEW_CANCEL_ACTION) {
1725
+ cancelQuestion(slot);
1726
+ return true;
1727
+ }
1728
+ return false;
1729
+ };
1730
+ /** The safe form's buttons AND its own option list: same exact-id rule. */
1731
+ const formActionEvent = (slot, event) => {
1732
+ if (event.act === FORM_CHOICE_ACTION) {
1733
+ const question = questionAt(slot, slot.tab);
1734
+ const offered = question?.options ?? [];
1735
+ for (const [index, option] of offered.entries()) {
1736
+ if (event.id !== formChoiceId(slot, index)) continue;
1737
+ slot.keyboardCursorShown = false;
1738
+ applySelection(slot, [option.label], question?.multiSelect === true);
1739
+ options.render();
1740
+ return true;
1741
+ }
1742
+ return false;
1743
+ }
1744
+ if (event.id === rowButtonId(formRowKey(slot), "next") && event.act === FORM_NEXT_ACTION) {
1745
+ commitText(slot);
1746
+ options.render();
1747
+ return true;
1748
+ }
1749
+ if (event.id === rowButtonId(formRowKey(slot), "back") && event.act === FORM_BACK_ACTION) {
1750
+ moveBack(slot);
1751
+ options.render();
1752
+ return true;
1753
+ }
1754
+ if (event.id === rowButtonId(formRowKey(slot), "cancel") && event.act === FORM_CANCEL_ACTION) {
1755
+ cancelQuestion(slot);
1756
+ return true;
1757
+ }
1758
+ return false;
1759
+ };
1760
+ /**
1761
+ * A native choice `change`: admitted only for the CURRENT visit's form node,
1762
+ * only for the CURRENT page's item token, and only with a value made of
1763
+ * `o-N` tokens this question really offers. The client's JSON is treated as a
1764
+ * claim to verify, never as authority: an out-of-range or malformed token is
1765
+ * dropped instead of inventing an answer.
1766
+ */
1767
+ const nativeChoiceEvent = (slot, event) => {
1768
+ if (event.id !== questionsId(slot)) return false;
1769
+ if (event.item !== `${ITEM_PREFIX}${slot.tab}`) return false;
1770
+ const question = questionAt(slot, slot.tab);
1771
+ if (question === void 0 || question.masked === true) return false;
1772
+ const raw = event.value;
1773
+ const tokens = Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : void 0;
1774
+ if (tokens === void 0) return false;
1775
+ if (question.multiSelect !== true && tokens.length !== 1) return false;
1776
+ const offered = question.options ?? [];
1777
+ const labels = [];
1778
+ for (const token of tokens) {
1779
+ if (typeof token !== "string" || !token.startsWith(CHOICE_PREFIX)) return false;
1780
+ const index = Number.parseInt(token.slice(2), 10);
1781
+ const option = offered[index];
1782
+ if (option === void 0 || `${CHOICE_PREFIX}${index}` !== token) return false;
1783
+ labels.push(option.label);
1784
+ }
1785
+ slot.keyboardCursorShown = false;
1786
+ applySelection(slot, labels);
1787
+ options.render();
1788
+ return true;
1789
+ };
1790
+ /**
1791
+ * A native page action (`next` / `skip` / `back` / `submit`). The node id
1792
+ * already pins the request AND the page visit; an `item` that names a
1793
+ * different page is refused, and `submit` is honoured only on the last
1794
+ * question — where it opens the Review page and NEVER settles.
1795
+ */
1796
+ const nativePageEvent = (slot, event) => {
1797
+ if (event.id !== questionsId(slot)) return false;
1798
+ if (event.act === PAGE_SUBMIT) {
1799
+ if (event.item !== void 0) return false;
1800
+ if (slot.tab !== slot.questions.length - 1) return false;
1801
+ goReview(slot);
1802
+ options.render();
1803
+ return true;
1804
+ }
1805
+ if (event.item !== `${ITEM_PREFIX}${slot.tab}`) return false;
1806
+ if (event.act === PAGE_NEXT) {
1807
+ moveForward(slot);
1808
+ options.render();
1809
+ return true;
1810
+ }
1811
+ if (event.act === PAGE_SKIP) {
1812
+ skipCurrent(slot);
1813
+ options.render();
1814
+ return true;
1815
+ }
1816
+ if (event.act === PAGE_BACK) {
1817
+ moveBack(slot);
1818
+ options.render();
1819
+ return true;
1820
+ }
1821
+ return false;
1822
+ };
1823
+ /**
1824
+ * A native Tool approval. ONLY the current approval Tool node's own
1825
+ * `allow`/`deny` with NO scope value is a decision: `always`, a
1826
+ * `session`/`always` value, another node's action, a settled slot, an aborted
1827
+ * lifetime or a replaced request all fall through as nothing. The decision
1828
+ * then runs the ORIGINAL settlement, exactly like the `y`/`n` keys.
1829
+ */
1830
+ const approvalEvent = (slot, event) => {
1831
+ if (event.ev !== "action") return false;
1832
+ if (event.id !== overlayId(APPROVAL_TOOL_KEY)) return false;
1833
+ if (event.value !== void 0) return false;
1834
+ if (slot.signal?.aborted === true) return false;
1835
+ if (event.act === TOOL_ALLOW) {
1836
+ settle(slot, () => slot.resolve("allowed-once"));
1837
+ return true;
1838
+ }
1839
+ if (event.act === TOOL_DENY) {
1840
+ settle(slot, () => slot.resolve("rejected"));
1841
+ return true;
1842
+ }
1843
+ return false;
1844
+ };
1845
+ /**
1846
+ * Gate one pointer/native event of the active modal.
1847
+ *
1848
+ * `true` means the CALLER must re-assert the seat's own focus — the existing
1849
+ * contract for a claim addressed at the (masked) composer underneath. A
1850
+ * native action the seat applied already committed its own frame through
1851
+ * `options.render()` (which applies focus), so it answers `false`; anything
1852
+ * that is not an exact hit on the current form answers `false` too and is
1853
+ * still swallowed by the modal-first branch, because a form that owns the
1854
+ * keyboard owns the pane.
1855
+ */
1856
+ const handleEvent = (event) => {
1857
+ if (active === void 0 && !listOpen) return false;
1858
+ const slot = active;
1859
+ if (slot !== void 0 && slot.settled !== true && slot.signal?.aborted !== true && "sf" in event && event.sf === options.surfaceId) {
1860
+ if (slot.kind === "approval") {
1861
+ if ((event.ev === "action" || event.ev === "change") && approvalEvent(slot, event)) return false;
1862
+ } else if (slot.tab >= slot.questions.length) {
1863
+ if (event.ev === "action" && reviewActionEvent(slot, event)) return false;
1864
+ } else if (usesNativeSteps(slot)) {
1865
+ if (event.ev === "change") {
1866
+ if (nativeChoiceEvent(slot, event)) return false;
1867
+ options.render();
1868
+ return false;
1869
+ }
1870
+ if (event.ev === "action" && nativePageEvent(slot, event)) return false;
1871
+ if (event.ev === "focus" && event.id === otherId(slot)) {
1872
+ enterEdit(slot);
1873
+ options.render();
1874
+ return true;
1875
+ }
1876
+ } else if (usesSafeForm(slot)) {
1877
+ if (event.ev === "action" && formActionEvent(slot, event)) return false;
1878
+ if (event.ev === "focus" && event.id === overlayId(ANSWER_KEY)) {
1879
+ enterEdit(slot);
1880
+ options.render();
1881
+ return true;
1882
+ }
1883
+ }
1884
+ }
1885
+ return event.ev === "focus" || event.ev === "edit" || event.ev === "undo" || event.ev === "send";
1886
+ };
1135
1887
  const renderEmptyLayer = () => ui.col({ key: LAYER_KEY });
1136
1888
  const renderLayer = () => {
1137
1889
  if (active !== void 0) return ui.col({ key: LAYER_KEY }, active.kind === "approval" ? approvalOverlay(active) : questionOverlay(active));
@@ -1140,8 +1892,10 @@ function createTspInteractionSeat(options) {
1140
1892
  return renderEmptyLayer();
1141
1893
  };
1142
1894
  const desiredFocusId = () => {
1143
- if (active !== void 0 && active.kind === "question" && active.editing === active.tab) return `${LAYER_ID}.${overlayKey()}.${ANSWER_KEY}`;
1144
- return null;
1895
+ const slot = active;
1896
+ if (slot === void 0 || slot.kind !== "question") return null;
1897
+ if (slot.editing !== slot.tab || slot.tab >= slot.questions.length) return null;
1898
+ return usesNativeSteps(slot) ? otherId(slot) : overlayId(ANSWER_KEY);
1145
1899
  };
1146
1900
  return {
1147
1901
  presenter: {
@@ -1196,6 +1950,8 @@ function createTspInteractionSeat(options) {
1196
1950
  detach: void 0,
1197
1951
  settled: false,
1198
1952
  tab: initial === void 0 ? 0 : Math.min(Math.max(0, initial.tab), questions.length),
1953
+ visitEpoch: 0,
1954
+ keyboardCursorShown: false,
1199
1955
  highlight: 0,
1200
1956
  editing: void 0,
1201
1957
  textOwner: -1,
@@ -1217,6 +1973,9 @@ function createTspInteractionSeat(options) {
1217
1973
  notify(text, kind) {
1218
1974
  options.notify(text, kind);
1219
1975
  },
1976
+ presentedModalKind() {
1977
+ return active?.kind;
1978
+ },
1220
1979
  setQuestionAttention(parkedCount) {
1221
1980
  if (disposed || parkedCount === attention) return;
1222
1981
  attention = parkedCount;
@@ -1246,10 +2005,7 @@ function createTspInteractionSeat(options) {
1246
2005
  return handleListKey(key, callbacks);
1247
2006
  },
1248
2007
  openContinuedList,
1249
- handleEvent(event) {
1250
- if (active === void 0 && !listOpen) return false;
1251
- return event.ev === "focus" || event.ev === "edit" || event.ev === "undo" || event.ev === "send";
1252
- },
2008
+ handleEvent,
1253
2009
  renderLayer,
1254
2010
  renderEmptyLayer,
1255
2011
  desiredFocusId,
@@ -1261,67 +2017,6 @@ function createTspInteractionSeat(options) {
1261
2017
  };
1262
2018
  }
1263
2019
  //#endregion
1264
- //#region src/tui/tsp/picker-text.ts
1265
- const graphemeSegmenter$2 = new Intl.Segmenter("en", { granularity: "grapheme" });
1266
- /**
1267
- * East Asian Wide/Fullwidth, emoji and supplementary planes occupy two columns;
1268
- * everything else one. A conservative classification is fine here: it only makes
1269
- * a wrap earlier and the layout budget smaller.
1270
- */
1271
- const WIDE_GRAPHEME = /[\u1100-\u115F\u2E80-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]|[\u{1F000}-\u{1FAFF}]|[\u{20000}-\u{3FFFD}]/u;
1272
- const columnsOf = (grapheme) => {
1273
- if (grapheme === " ") return 3;
1274
- return WIDE_GRAPHEME.test(grapheme) ? 2 : 1;
1275
- };
1276
- /** The display columns of one text (never UTF-16 units). */
1277
- function displayWidth(text) {
1278
- let width = 0;
1279
- for (const { segment } of graphemeSegmenter$2.segment(text)) width += columnsOf(segment);
1280
- return width;
1281
- }
1282
- /**
1283
- * Clamp `text` to `columns` display columns with a MIDDLE ellipsis: a head and a
1284
- * tail both survive.
1285
- *
1286
- * {@link clampColumns} keeps the head only, which is enough when the value's tail
1287
- * carries nothing (`fact` rows). A strip chip is the ONE place an advertised effort
1288
- * NAME is shown for a candidate that is not the draft, and names are free-form: two
1289
- * of them can differ only in their tail (`Extended thinking (low)` vs
1290
- * `Extended thinking (high)`), where a head-only clamp would render one label for
1291
- * two different candidates. The ellipsis is the design language's content
1292
- * truncation; the complete text stays with its owner.
1293
- */
1294
- function clampMiddle(text, columns) {
1295
- if (displayWidth(text) <= columns) return text;
1296
- const budget = Math.max(2, columns - 1);
1297
- const head = Math.max(1, Math.ceil(budget / 2));
1298
- const tail = Math.max(1, budget - head);
1299
- const graphemes = [...graphemeSegmenter$2.segment(text)].map((entry) => entry.segment);
1300
- const take = (source, room) => {
1301
- const kept = [];
1302
- let used = 0;
1303
- for (const grapheme of source) {
1304
- const cell = columnsOf(grapheme);
1305
- if (used + cell > room) break;
1306
- kept.push(grapheme);
1307
- used += cell;
1308
- }
1309
- return kept;
1310
- };
1311
- const left = take(graphemes, head).join("");
1312
- const right = take([...graphemes].reverse(), tail).reverse().join("");
1313
- return `${left.trimEnd()}…${right.trimStart()}`;
1314
- }
1315
- /**
1316
- * The ONE-line form of a text: every whitespace run — an explicit LF, CRLF, CR
1317
- * or Unicode line/paragraph separator included — collapses to a single space, so
1318
- * the result is exactly one rendered line. The complete value always stays
1319
- * readable on a Details page.
1320
- */
1321
- function oneLine(text) {
1322
- return text.replace(/\s+/gu, " ").trim();
1323
- }
1324
- //#endregion
1325
2020
  //#region src/tui/tsp/model-picker-state.ts
1326
2021
  /** The stable wire/local id of one model row. JSON keeps provider and model
1327
2022
  * distinct (model ids are not globally unique) in a printable identifier. */
@@ -2024,11 +2719,13 @@ function rowIntent$1(panel, item, kind) {
2024
2719
  * - a row activation (`activate` — the client's own click on the already-highlighted
2025
2720
  * row — or `Enter`) opens the read-only Full details page DIRECTLY: there is no
2026
2721
  * intermediate page and no second-level effort menu;
2027
- * - that read-only page is a native `overlay` Reader (`ui.text` with the client's
2028
- * own wrapping and a native scroll container) grouped into Identity /
2029
- * Configuration / Description: a picker row is ONE ellipsized line and cannot
2030
- * carry a long value. No overlay ON TOP of a picker, no `ui.el`, no self-drawn
2031
- * button, no global action menu.
2722
+ * - that read-only page is a native `overlay` Reader with a native scroll
2723
+ * container, grouped into Identity / Configuration / Description: a picker row is
2724
+ * ONE ellipsized line and cannot carry a long value. Each labelled group's facts
2725
+ * reach the page as ONE `ui.kv` grid where the pane negotiated `kv`, and as the
2726
+ * original label/value `ui.text` pair where it did not; the Description stays a
2727
+ * complete `ui.text` with the client's own wrapping either way. No overlay ON TOP
2728
+ * of a picker, no `ui.el`, no self-drawn button, no global action menu.
2032
2729
  * @module tui/tsp/model-picker-view
2033
2730
  */
2034
2731
  /**
@@ -2187,6 +2884,28 @@ function pickerState$1(panel) {
2187
2884
  const MODEL_DETAILS_BODY_KEY_PREFIX = "model-details-body-";
2188
2885
  const MODEL_DETAILS_READER_KEY = "model-details-reader";
2189
2886
  const MODEL_DETAILS_BACK_KEY = "model-details-back";
2887
+ /** The Reader groups whose facts are labelled short facts: `Identity` and
2888
+ * `Configuration`. `Description` is one value whose head IS its subject, so it is
2889
+ * never a grid row and keeps its own complete wrapped text at every capability. */
2890
+ const GRIDDED_GROUP_IDS = ["identity", "configuration"];
2891
+ /**
2892
+ * A group's facts as the pairs one grid paints, or `undefined` when the group
2893
+ * cannot be one.
2894
+ *
2895
+ * The grid aligns a `k` with a `v`, so EVERY fact it carries must have a label. The
2896
+ * state module gives every labelled group a label on every fact; a group that ever
2897
+ * stopped satisfying that falls back to the original text rows rather than shipping
2898
+ * an empty `k` or dropping a fact, because the Reader's contract is that everything
2899
+ * it projects reaches the page.
2900
+ */
2901
+ function gridItems(group) {
2902
+ const facts = group.facts;
2903
+ if (!facts.every((fact) => fact.label !== void 0)) return void 0;
2904
+ return facts.map((fact) => ({
2905
+ k: sanitizeDisplayText(fact.label),
2906
+ v: sanitizeDisplayText(fact.value)
2907
+ }));
2908
+ }
2190
2909
  /**
2191
2910
  * The read-only Reader: the `details` page's ONE node tree, in the layer region,
2192
2911
  * as a native `overlay` instead of a picker.
@@ -2217,14 +2936,21 @@ function detailsReader(panel, deps) {
2217
2936
  }, ui.row({
2218
2937
  key: `${MODEL_DETAILS_BACK_KEY}-${scope}`,
2219
2938
  onClick: deps.bind({ kind: "back" })
2220
- }, ui.text(span("Back", "accent"))), ui.col({ key: `${MODEL_DETAILS_BODY_KEY_PREFIX}${scope}` }, ...row === void 0 ? [ui.text(span("No model is selected.", "muted"))] : [...panel.notice === void 0 ? [] : [ui.text({ wrap: "word" }, span(sanitizeDisplayText(panel.notice.text), panel.notice.tone))], ...groups.flatMap((group, index) => [ui.col({
2221
- key: `reader-group-${group.id}`,
2222
- gap: "xs"
2223
- }, ui.text(span(sanitizeDisplayText(group.head), "muted")), ...group.facts.flatMap((fact) => [...fact.label === void 0 ? [] : [ui.text(span(sanitizeDisplayText(fact.label), "muted"))], ui.text({
2224
- key: fact.id,
2225
- text: sanitizeDisplayText(fact.value),
2226
- wrap: fact.wrap
2227
- })])), ...index === groups.length - 1 ? [] : [ui.rule(), ui.spacer({ size: "lg" })]])]));
2939
+ }, ui.text(span("Back", "accent"))), ui.col({ key: `${MODEL_DETAILS_BODY_KEY_PREFIX}${scope}` }, ...row === void 0 ? [ui.text(span("No model is selected.", "muted"))] : [...panel.notice === void 0 ? [] : [ui.text({ wrap: "word" }, span(sanitizeDisplayText(panel.notice.text), panel.notice.tone))], ...groups.flatMap((group, index) => {
2940
+ const items = deps.nativeKv && GRIDDED_GROUP_IDS.includes(group.id) ? gridItems(group) : void 0;
2941
+ return [ui.col({
2942
+ key: `reader-group-${group.id}`,
2943
+ gap: "xs"
2944
+ }, ui.text(span(sanitizeDisplayText(group.head), "muted")), ...items === void 0 ? group.facts.flatMap((fact) => [...fact.label === void 0 ? [] : [ui.text(span(sanitizeDisplayText(fact.label), "muted"))], ui.text({
2945
+ key: fact.id,
2946
+ text: sanitizeDisplayText(fact.value),
2947
+ wrap: fact.wrap
2948
+ })]) : [ui.kv({
2949
+ key: `reader-kv-${group.id}`,
2950
+ layout: "grid",
2951
+ items
2952
+ })]), ...index === groups.length - 1 ? [] : [ui.rule(), ui.spacer({ size: "lg" })]];
2953
+ })]));
2228
2954
  }
2229
2955
  function modelListPicker(panel, deps, key) {
2230
2956
  highlightedModel(panel);
@@ -2296,6 +3022,10 @@ var TspModelPicker = class {
2296
3022
  /** The ONE Surface owner's native scroll op, addressed by a wire id of the
2297
3023
  * frame this presenter built. The presenter never owns a Surface. */
2298
3024
  nativeScroll;
3025
+ /** Whether the pane negotiated the read-only `kv` kind. The Reader's short
3026
+ * facts paint as one grid per group when it did, and as the plain labelled
3027
+ * text rows when it did not. A display fact only — it gates no command. */
3028
+ nativeKv;
2299
3029
  panel;
2300
3030
  serial = 0;
2301
3031
  /** The current frame's event targets: node id -> the revision it was built
@@ -2314,6 +3044,7 @@ var TspModelPicker = class {
2314
3044
  this.canInteract = deps.canInteract;
2315
3045
  this.notify = deps.notify;
2316
3046
  this.nativeScroll = deps.nativeScroll;
3047
+ this.nativeKv = deps.nativeKv;
2317
3048
  }
2318
3049
  presentation = {
2319
3050
  open: (request) => this.open(request),
@@ -2389,6 +3120,7 @@ var TspModelPicker = class {
2389
3120
  * draft whose value is still advertised, and never keep a highlight the new
2390
3121
  * catalogue cannot reach. */
2391
3122
  hydrate(panel, directory) {
3123
+ const firstHydration = panel.directory === void 0;
2392
3124
  const projection = projectModelDirectory(directory.directory, directory.current, panel.request.subject.sessionless);
2393
3125
  panel.directory = directory;
2394
3126
  panel.rows = projection.models;
@@ -2400,6 +3132,14 @@ var TspModelPicker = class {
2400
3132
  }
2401
3133
  panel.phase = "ready";
2402
3134
  panel.notice = void 0;
3135
+ if (firstHydration && panel.request.entry === "effort") {
3136
+ const row = highlightedModel(panel);
3137
+ if (row !== void 0 && modelChoices(row).length > 0 && stripOffered(panel)) panel.zone = "strip";
3138
+ else panel.notice = {
3139
+ text: "Reasoning effort is unavailable for this model",
3140
+ tone: "muted"
3141
+ };
3142
+ }
2403
3143
  this.align(panel);
2404
3144
  this.change(panel);
2405
3145
  }
@@ -2641,7 +3381,8 @@ var TspModelPicker = class {
2641
3381
  return true;
2642
3382
  }
2643
3383
  if (event.ev !== "action") return false;
2644
- const intent = actionIntent$1(target.panel, event.act, event.value);
3384
+ const value = typeof event.value === "string" ? event.value : void 0;
3385
+ const intent = actionIntent$1(target.panel, event.act, value);
2645
3386
  if (intent !== void 0) this.act(target.panel, target.revision, intent);
2646
3387
  return true;
2647
3388
  }
@@ -2657,6 +3398,7 @@ var TspModelPicker = class {
2657
3398
  const revision = panel.revision;
2658
3399
  const layer = modelPickerLayer(panel, {
2659
3400
  paneWidth: this.cols * this.cellWidth,
3401
+ nativeKv: this.nativeKv,
2660
3402
  bind: (intent) => () => this.act(panel, revision, intent)
2661
3403
  });
2662
3404
  for (const root of View.from({ layer }).regions) {
@@ -3552,32 +4294,75 @@ function detailsBackRow(panel, deps) {
3552
4294
  }));
3553
4295
  }
3554
4296
  /** The Details page's identity block: the complete values, wrapped by the client
3555
- * at the layout's real width — never pre-split. */
3556
- function detailsIdentity(panel, row) {
4297
+ * at the layout's real width — never pre-split.
4298
+ *
4299
+ * A pane that negotiated the read-only `kv` kind gets the FOUR facts as ONE native
4300
+ * grid: the client owns the two columns, so a narrow pane stops paying a separate
4301
+ * label line for every fact. A pane that did not gets the ORIGINAL eight text nodes,
4302
+ * in the original order, with the original keys, `wrap` and muted label role. The
4303
+ * choice is a layout for the same four facts and nothing else — the relationship
4304
+ * lines, the failure reason, the description and the guide are outside it, and no
4305
+ * branch keeps a hidden copy of what the other branch already painted. */
4306
+ function detailsIdentity(panel, row, nativeKv) {
3557
4307
  const relations = statusRelations(panel, row);
3558
4308
  return [ui.col({
3559
4309
  key: `preset-details-identity-${readingScope(panel)}`,
3560
4310
  gap: "xs"
3561
- }, ui.text(span("Name", "muted")), ui.text({
3562
- key: "details-name",
3563
- text: sanitizeDisplayText(row.name),
3564
- wrap: "char"
3565
- }), ui.text(span("ID", "muted")), ui.text({
3566
- key: "details-id",
3567
- text: sanitizeDisplayText(row.id),
3568
- wrap: "char"
3569
- }), ui.text(span("Type", "muted")), ui.text({
3570
- key: "details-type",
3571
- text: row.builtIn ? "Built-in" : "Custom"
3572
- }), ui.text(span("Scope", "muted")), ui.text({
3573
- key: "details-scope",
3574
- spans: [
3575
- span("Use: ", "muted"),
3576
- span(panel.request.subject.sessionless ? "next session only" : "current blank session"),
3577
- span(" · Default: ", "muted"),
3578
- span("future new sessions")
4311
+ }, ...nativeKv ? [ui.kv({
4312
+ key: `preset-details-kv-identity-${readingScope(panel)}`,
4313
+ layout: "grid",
4314
+ items: [
4315
+ {
4316
+ k: "Name",
4317
+ v: sanitizeDisplayText(row.name)
4318
+ },
4319
+ {
4320
+ k: "ID",
4321
+ v: sanitizeDisplayText(row.id)
4322
+ },
4323
+ {
4324
+ k: "Type",
4325
+ v: row.builtIn ? "Built-in" : "Custom"
4326
+ },
4327
+ {
4328
+ k: "Scope",
4329
+ v: [
4330
+ span("Use: ", "muted"),
4331
+ span(panel.request.subject.sessionless ? "next session only" : "current blank session"),
4332
+ span(" · Default: ", "muted"),
4333
+ span("future new sessions")
4334
+ ]
4335
+ }
3579
4336
  ]
3580
- }), ...relations.flatMap((relation) => [ui.text({
4337
+ })] : [
4338
+ ui.text(span("Name", "muted")),
4339
+ ui.text({
4340
+ key: "details-name",
4341
+ text: sanitizeDisplayText(row.name),
4342
+ wrap: "char"
4343
+ }),
4344
+ ui.text(span("ID", "muted")),
4345
+ ui.text({
4346
+ key: "details-id",
4347
+ text: sanitizeDisplayText(row.id),
4348
+ wrap: "char"
4349
+ }),
4350
+ ui.text(span("Type", "muted")),
4351
+ ui.text({
4352
+ key: "details-type",
4353
+ text: row.builtIn ? "Built-in" : "Custom"
4354
+ }),
4355
+ ui.text(span("Scope", "muted")),
4356
+ ui.text({
4357
+ key: "details-scope",
4358
+ spans: [
4359
+ span("Use: ", "muted"),
4360
+ span(panel.request.subject.sessionless ? "next session only" : "current blank session"),
4361
+ span(" · Default: ", "muted"),
4362
+ span("future new sessions")
4363
+ ]
4364
+ })
4365
+ ], ...relations.flatMap((relation) => [ui.text({
3581
4366
  key: relation.id,
3582
4367
  spans: [span(`${relation.label}: `, "muted"), span(sanitizeDisplayText(relation.value))]
3583
4368
  })]), ...row.broken === void 0 ? [] : [ui.text(span("Failed to load", "muted")), ui.text({
@@ -3609,7 +4394,7 @@ function detailsOverlay(panel, deps) {
3609
4394
  key: "details-notice",
3610
4395
  wrap: "word"
3611
4396
  }, span(sanitizeDisplayText(notice), "muted"))], ...row === void 0 ? [ui.text(span("No preset is selected.", "muted"))] : [
3612
- ...detailsIdentity(panel, row),
4397
+ ...detailsIdentity(panel, row, deps.nativeKv),
3613
4398
  ui.rule(),
3614
4399
  ui.spacer({ size: "sm" }),
3615
4400
  ...row.description === void 0 || row.description.trim() === "" ? [ui.text(span("No description provided.", "muted"))] : [ui.text(span("Description", "muted")), ui.text({
@@ -3655,6 +4440,11 @@ var TspPresetPicker = class {
3655
4440
  /** The ONE Surface owner's native scroll op, addressed by a wire id of the frame
3656
4441
  * this presenter built. The presenter never owns a Surface. */
3657
4442
  nativeScroll;
4443
+ /** Whether the pane negotiated the read-only `kv` kind: the Details page lays its
4444
+ * four identity facts out as one grid when it did, and keeps the original
4445
+ * label-over-value text lines when it did not. A client display fact only — it
4446
+ * gates no command, opens nothing and never retires a reading. */
4447
+ nativeKv;
3658
4448
  panel;
3659
4449
  serial = 0;
3660
4450
  /** The current frame's event targets: node id -> the revision it was built for. An
@@ -3671,6 +4461,7 @@ var TspPresetPicker = class {
3671
4461
  this.canInteract = deps.canInteract;
3672
4462
  this.notify = deps.notify;
3673
4463
  this.nativeScroll = deps.nativeScroll;
4464
+ this.nativeKv = deps.nativeKv;
3674
4465
  }
3675
4466
  presentation = {
3676
4467
  open: (request) => this.open(request),
@@ -4023,7 +4814,10 @@ var TspPresetPicker = class {
4023
4814
  panel.revision++;
4024
4815
  }
4025
4816
  const revision = panel.revision;
4026
- const layer = presetPickerLayer(panel, { bind: (intent) => () => this.act(panel, revision, intent) });
4817
+ const layer = presetPickerLayer(panel, {
4818
+ nativeKv: this.nativeKv,
4819
+ bind: (intent) => () => this.act(panel, revision, intent)
4820
+ });
4027
4821
  for (const root of View.from({ layer }).regions) {
4028
4822
  const visit = (node) => {
4029
4823
  if (node === void 0) return;
@@ -4314,7 +5108,25 @@ function rowStateText(panel, row) {
4314
5108
  const base = row.id === panel.request.subject.currentSessionId ? "Current session" : row.live ? "Live session" : "Persisted session";
4315
5109
  return row.formatStatus === "migration-required" ? `${base} · Migration required` : base;
4316
5110
  }
4317
- function detailReader(panel, bind) {
5111
+ /** The excerpt group's id: the ONE group whose body is Host content the user reads
5112
+ * as prose, so it is never a grid row (see `detailReader`). */
5113
+ const EXCERPT_GROUP_ID = "excerpt";
5114
+ /**
5115
+ * The read-only Session Details Reader.
5116
+ *
5117
+ * The four fact groups (Identity / Activity / Lineage / Configuration) are labelled
5118
+ * short facts, so on a pane that negotiated `kv` each paints as ONE native grid: the
5119
+ * client aligns every label with its value instead of paying a separate line per
5120
+ * label, which is what lets a narrow pane show more of the same facts at once. The
5121
+ * values are the SAME complete strings the text branch sends and the client owns any
5122
+ * wrapping (`KvItem` has no `wrap`), so an unbroken ID or a long cwd stays whole.
5123
+ *
5124
+ * The Host search excerpt is a different shape: its value is matched CONTENT read as
5125
+ * prose, so it keeps its own `Matching content` label plus one complete wrapped
5126
+ * `ui.text` at EVERY capability. A pane without `kv` keeps the original per-fact text
5127
+ * rows verbatim, in the same order, with the same scroll body and the same Back row.
5128
+ */
5129
+ function detailReader(panel, bind, nativeKv) {
4318
5130
  const row = rowFor(panel, panel.selected);
4319
5131
  const scope = `${panel.serial}-${panel.readerEpoch}`;
4320
5132
  const bodyKey = `${DETAILS_BODY_KEY_PREFIX}${scope}`;
@@ -4347,7 +5159,7 @@ function detailReader(panel, bind) {
4347
5159
  facts: [["Agent preset", row.preset ?? "Unknown preset"]]
4348
5160
  },
4349
5161
  ...result?.snippet === void 0 ? [] : [{
4350
- id: "excerpt",
5162
+ id: EXCERPT_GROUP_ID,
4351
5163
  head: `Host search excerpt · ${result.source}`,
4352
5164
  facts: [["Matching content", result.snippet]]
4353
5165
  }]
@@ -4366,10 +5178,17 @@ function detailReader(panel, bind) {
4366
5178
  }, ...row === void 0 ? [ui.text(span("The selected session is no longer available.", "muted"))] : groups.map((group) => ui.col({
4367
5179
  key: `session-browser-group-${group.id}`,
4368
5180
  gap: "xs"
4369
- }, ui.text(span(sanitizeTerminalText(group.head), "muted")), ...group.facts.flatMap(([label, value]) => [ui.text(span(label, "muted")), ui.text({ wrap: "word" }, sanitizeTerminalText(value))]))))));
4370
- }
4371
- function layer(panel, bind) {
4372
- return panel.page === "details" ? detailReader(panel, bind) : pickerLayer(panel);
5181
+ }, ui.text(span(sanitizeTerminalText(group.head), "muted")), ...nativeKv && group.id !== EXCERPT_GROUP_ID ? [ui.kv({
5182
+ key: `session-browser-kv-${group.id}`,
5183
+ layout: "grid",
5184
+ items: group.facts.map(([label, value]) => ({
5185
+ k: sanitizeTerminalText(label),
5186
+ v: sanitizeTerminalText(value)
5187
+ }))
5188
+ })] : group.facts.flatMap(([label, value]) => [ui.text(span(label, "muted")), ui.text({ wrap: "word" }, sanitizeTerminalText(value))]))))));
5189
+ }
5190
+ function layer(panel, bind, nativeKv) {
5191
+ return panel.page === "details" ? detailReader(panel, bind, nativeKv) : pickerLayer(panel);
4373
5192
  }
4374
5193
  var TspSessionBrowser = class {
4375
5194
  surfaceId;
@@ -4378,6 +5197,10 @@ var TspSessionBrowser = class {
4378
5197
  notify;
4379
5198
  nativeScroll;
4380
5199
  scrollSupported;
5200
+ /** Whether the pane negotiated the read-only `kv` kind. Like `scrollSupported`
5201
+ * it is a fixed mount-time capability of the pane, NOT panel state: it is never
5202
+ * part of a snapshot or a draft a re-read can rewrite. */
5203
+ nativeKv;
4381
5204
  panel;
4382
5205
  serial = 0;
4383
5206
  suspended = false;
@@ -4390,6 +5213,7 @@ var TspSessionBrowser = class {
4390
5213
  this.notify = deps.notify;
4391
5214
  this.nativeScroll = deps.nativeScroll;
4392
5215
  this.scrollSupported = deps.scrollSupported;
5216
+ this.nativeKv = deps.nativeKv;
4393
5217
  }
4394
5218
  presentation = {
4395
5219
  open: (request) => this.open(request),
@@ -4733,7 +5557,7 @@ var TspSessionBrowser = class {
4733
5557
  panel.revision++;
4734
5558
  }
4735
5559
  const revision = panel.revision;
4736
- const node = layer(panel, (intent) => () => this.act(panel, revision, intent));
5560
+ const node = layer(panel, (intent) => () => this.act(panel, revision, intent), this.nativeKv);
4737
5561
  const pickerKey = `session-browser-picker-${panel.serial}`;
4738
5562
  const backKey = `session-browser-back-${panel.serial}-${panel.readerEpoch}`;
4739
5563
  for (const root of View.from({ layer: node }).regions) {
@@ -4757,6 +5581,797 @@ var TspSessionBrowser = class {
4757
5581
  }
4758
5582
  };
4759
5583
  //#endregion
5584
+ //#region src/tui/tsp/statusline-view.ts
5585
+ /**
5586
+ * TSP-7 PR-A/PR-B/PR-D: the native statusline projection — the TSP renderer's
5587
+ * read-only `ui.status` rows built from the ONE committed `StatusSnapshot`.
5588
+ *
5589
+ * This module is a PURE projection: no IO, no timers, no filesystem, no
5590
+ * SDK session, no store access. It reads the existing builtin footer item
5591
+ * definitions (`createBuiltinFooterRegistry()`) and maps their already-
5592
+ * sanitized `FooterSegment.spans` text onto `ui.seg` nodes — it never
5593
+ * re-implements a token/context/permission formatter and never parses the
5594
+ * ANSI output of `FooterComposer.render()`.
5595
+ *
5596
+ * Modes (PR-D):
5597
+ * - `default` — the frozen PR-A/PR-B two-row shape (byte-for-byte the same
5598
+ * item set/keys/priorities; PR-D must not change it).
5599
+ * - `compact` — the plan's OWN fixed single native row (NOT the PiTui
5600
+ * `COMPACT_FOOTER_LAYOUT`): permission, cwd, git, run on the left; plan,
5601
+ * the attention badge and the context pressure on the right, with the
5602
+ * right-side facts above the environment ones so a narrow pane keeps them.
5603
+ * - `custom` — the validated `FooterLayoutV1` placements, each rendered by
5604
+ * its OWN registry definition at `preferred` density; unsupported refs
5605
+ * (USER command items, extension items, unknown ids) keep their placement
5606
+ * with a visible `Unavailable` marker — they are never silently dropped.
5607
+ *
5608
+ * Every item omits itself when its fact is absent, and a row with no segment
5609
+ * produces no `status` node at all — the dock never shows a blank native
5610
+ * status line.
5611
+ * @module @xmoon76/dsh-pi-tui/tui/tsp/statusline-view
5612
+ */
5613
+ /**
5614
+ * The immutable builtin-only lookup for the FROZEN default/compact presets
5615
+ * (PR-A/PR-B). It is created ONCE at module load: those two presets render a
5616
+ * fixed builtin item set with no custom source ever attached, so a shared
5617
+ * immutable registry is their single source. The CONFIGURED `custom`
5618
+ * projection deliberately does NOT use it — every mount compiles its own
5619
+ * registry with the USER catalog attached (see compileNativeFooterPresentation).
5620
+ */
5621
+ const BUILTIN_PRESET_REGISTRY = createBuiltinFooterRegistry();
5622
+ /**
5623
+ * The fixed render context of the six PR-A items: none of them reads the task
5624
+ * browser gate or the extension footer text.
5625
+ */
5626
+ const NO_SURFACE_HINTS = {
5627
+ taskBrowserAvailable: false,
5628
+ extensionFooterText: ""
5629
+ };
5630
+ /** The PR-A + PR-B priority numbers (Tern drops the smallest first, PER ROW). */
5631
+ const PRIORITY = {
5632
+ /** PR-B: the attention badge — the highest row-1 claim (a failure or a
5633
+ * blocked human wait outranks every environment fact). */
5634
+ attention: 110,
5635
+ permission: 95,
5636
+ cwd: 50,
5637
+ git: 30,
5638
+ plan: 100,
5639
+ /** PR-B: the machine run phase — above the environment items, below attention. */
5640
+ run: 105,
5641
+ tokens: 60,
5642
+ context: 100,
5643
+ /** PR-B: the cache share. */
5644
+ cache: 35,
5645
+ /** PR-B: the recent (R5) / whole-session (All) output rate. */
5646
+ speed: 45,
5647
+ /** PR-B: the time-to-first-token — the first statistic Tern may drop. */
5648
+ ttfb: 25
5649
+ };
5650
+ /**
5651
+ * Row 1 (the working environment + the run state / attention): permission, cwd,
5652
+ * git branch, run state on the LEFT, the plan state and the attention badge on
5653
+ * the RIGHT.
5654
+ */
5655
+ const ROW_ONE = [
5656
+ {
5657
+ id: "permission-preset",
5658
+ format: "compact",
5659
+ key: "status-r1-permission",
5660
+ icon: "shield",
5661
+ priority: PRIORITY.permission
5662
+ },
5663
+ {
5664
+ id: "cwd",
5665
+ format: "basename",
5666
+ key: "status-r1-cwd",
5667
+ icon: "folder",
5668
+ priority: PRIORITY.cwd
5669
+ },
5670
+ {
5671
+ id: "git-branch",
5672
+ format: "plain",
5673
+ key: "status-r1-git",
5674
+ icon: "git-branch",
5675
+ priority: PRIORITY.git
5676
+ },
5677
+ {
5678
+ id: "run-state",
5679
+ format: "plain",
5680
+ key: "status-r1-run",
5681
+ icon: "run",
5682
+ density: "compact",
5683
+ priority: PRIORITY.run
5684
+ },
5685
+ {
5686
+ id: "plan-state",
5687
+ format: "plain",
5688
+ key: "status-r1-plan",
5689
+ icon: "plan",
5690
+ side: "right",
5691
+ priority: PRIORITY.plan
5692
+ },
5693
+ {
5694
+ id: "tasks",
5695
+ format: "badge",
5696
+ key: "status-r1-attention",
5697
+ icon: "tasks",
5698
+ side: "right",
5699
+ density: "compact",
5700
+ priority: PRIORITY.attention
5701
+ }
5702
+ ];
5703
+ /** Row 2 (the statistics): tokens, cache, TTFB and the rate on the LEFT, the
5704
+ * context pressure on the RIGHT. Every item omits itself when its fact is
5705
+ * absent, so a missing sample never paints a fabricated zero. */
5706
+ const ROW_TWO = [
5707
+ {
5708
+ id: "token-usage",
5709
+ format: "pi",
5710
+ key: "status-r2-tokens",
5711
+ icon: "tokens",
5712
+ priority: PRIORITY.tokens
5713
+ },
5714
+ {
5715
+ id: "cache-hit",
5716
+ format: "pi",
5717
+ key: "status-r2-cache",
5718
+ icon: "cache",
5719
+ priority: PRIORITY.cache
5720
+ },
5721
+ {
5722
+ id: "performance",
5723
+ format: "latency",
5724
+ key: "status-r2-ttfb",
5725
+ icon: "timer",
5726
+ priority: PRIORITY.ttfb
5727
+ },
5728
+ {
5729
+ id: "performance",
5730
+ format: "speed-both",
5731
+ key: "status-r2-speed",
5732
+ icon: "gauge",
5733
+ priority: PRIORITY.speed
5734
+ },
5735
+ {
5736
+ id: "context",
5737
+ format: "percent",
5738
+ key: "status-r2-context",
5739
+ icon: "context",
5740
+ side: "right",
5741
+ priority: PRIORITY.context
5742
+ }
5743
+ ];
5744
+ /**
5745
+ * PR-D: the TSP compact preset — ONE native row, in the plan's fixed segment
5746
+ * order (§2.2). It is deliberately NOT the PiTui `COMPACT_FOOTER_LAYOUT`: no
5747
+ * Model (the Composer owns it), no stats row, and the right-side attention
5748
+ * and context facts sit ABOVE the left environment ones so a narrow pane that
5749
+ * drops by priority keeps them (`tasks` 110 > run 105 > context 109 > plan
5750
+ * 100 > permission 95 > cwd 50 > git 30).
5751
+ */
5752
+ const COMPACT_ROW = [
5753
+ {
5754
+ id: "permission-preset",
5755
+ format: "compact",
5756
+ key: "status-r1-permission",
5757
+ icon: "shield",
5758
+ priority: 95
5759
+ },
5760
+ {
5761
+ id: "cwd",
5762
+ format: "basename",
5763
+ key: "status-r1-cwd",
5764
+ icon: "folder",
5765
+ priority: 50
5766
+ },
5767
+ {
5768
+ id: "git-branch",
5769
+ format: "plain",
5770
+ key: "status-r1-git",
5771
+ icon: "git-branch",
5772
+ priority: 30
5773
+ },
5774
+ {
5775
+ id: "run-state",
5776
+ format: "plain",
5777
+ key: "status-r1-run",
5778
+ icon: "run",
5779
+ density: "compact",
5780
+ priority: 105
5781
+ },
5782
+ {
5783
+ id: "plan-state",
5784
+ format: "plain",
5785
+ key: "status-r1-plan",
5786
+ icon: "plan",
5787
+ side: "right",
5788
+ priority: 100
5789
+ },
5790
+ {
5791
+ id: "tasks",
5792
+ format: "badge",
5793
+ key: "status-r1-attention",
5794
+ icon: "tasks",
5795
+ side: "right",
5796
+ density: "compact",
5797
+ priority: 110
5798
+ },
5799
+ {
5800
+ id: "context",
5801
+ format: "percent",
5802
+ key: "status-r1-context",
5803
+ icon: "context",
5804
+ side: "right",
5805
+ priority: 109
5806
+ }
5807
+ ];
5808
+ /** Resolve one builtin definition; an unknown id is an internal contract break. */
5809
+ function definition(id) {
5810
+ const def = BUILTIN_PRESET_REGISTRY.get(id);
5811
+ if (def === void 0) throw new Error(`missing builtin status item: ${id}`);
5812
+ return def;
5813
+ }
5814
+ /**
5815
+ * Project one builtin segment's SEMANTIC tone onto the native one.
5816
+ *
5817
+ * Only the severity/muted family has a portable meaning in Tern: the PiTui
5818
+ * palette tones (`text`, `textStrong`, `border`, `primary`, `roleUser`,
5819
+ * `shellMode`) are terminal-theme tokens with no negotiated Tern counterpart,
5820
+ * so they stay unset and the client's own text styling applies. The tones that
5821
+ * DO carry a claim about the fact — a dangerous permission preset, a failure, a
5822
+ * success, a de-emphasized value — are forwarded verbatim, because dropping
5823
+ * them would let the client paint "yolo" exactly like "read-only".
5824
+ *
5825
+ * Colour is never the only carrier: the builtin's own text is always present.
5826
+ */
5827
+ function nativeTone(tone) {
5828
+ switch (tone) {
5829
+ case "warning": return "warning";
5830
+ case "error": return "error";
5831
+ case "success": return "success";
5832
+ case "accent": return "accent";
5833
+ case "textMuted":
5834
+ case "textDim": return "muted";
5835
+ default: return;
5836
+ }
5837
+ }
5838
+ /**
5839
+ * Render one PR-A item through its existing builtin formatter and return the
5840
+ * safe plain text plus the semantic tone, or `undefined` when the item has no
5841
+ * value to show.
5842
+ */
5843
+ function itemText(snapshot, item) {
5844
+ const segment = definition(item.id).render(snapshot, {
5845
+ id: item.id,
5846
+ format: item.format
5847
+ }, item.density ?? "preferred", NO_SURFACE_HINTS);
5848
+ if (segment === null) return void 0;
5849
+ const text = segment.spans.map((span) => span.text).join("");
5850
+ if (text === "") return void 0;
5851
+ return {
5852
+ text,
5853
+ tone: nativeTone(segment.spans.find((span) => span.tone !== void 0)?.tone)
5854
+ };
5855
+ }
5856
+ /**
5857
+ * The no-composer-affordance fallback: nothing is provided, so every
5858
+ * default-On item falls back to its historical visible form. The real mount
5859
+ * always passes the LIVE capability result — this default exists for the
5860
+ * pure projection's unconfigured/unnegotiated shape.
5861
+ */
5862
+ const NO_COMPOSER_AFFORDANCES = {
5863
+ permission: false,
5864
+ model: false,
5865
+ reasoning: false
5866
+ };
5867
+ /** Build one row's `ui.seg` children (an absent item contributes nothing).
5868
+ * The PR-F universal visibility filter runs BEFORE rendering: a hidden
5869
+ * placement never reaches the formatter (so it can never surface an
5870
+ * `Unavailable` marker or consume a separator/priority slot). */
5871
+ function rowSegments(snapshot, items, affordances) {
5872
+ const segments = [];
5873
+ for (const item of items) {
5874
+ if (hideFooterRefInTsp({
5875
+ id: item.id,
5876
+ format: item.format
5877
+ }, affordances)) continue;
5878
+ const rendered = itemText(snapshot, item);
5879
+ if (rendered === void 0) continue;
5880
+ segments.push(ui.seg({
5881
+ key: item.key,
5882
+ text: rendered.text,
5883
+ ...item.icon === void 0 ? {} : { icon: item.icon },
5884
+ ...rendered.tone === void 0 ? {} : { tone: rendered.tone },
5885
+ ...item.side === void 0 ? {} : { side: item.side },
5886
+ priority: item.priority
5887
+ }));
5888
+ }
5889
+ return segments;
5890
+ }
5891
+ /**
5892
+ * Compile one boot-time footer config into the renderer's immutable
5893
+ * presentation. The layout and the item classification were already decided
5894
+ * by the domain resolver; this step builds the ONE mount-local registry —
5895
+ * a fresh `createBuiltinFooterRegistry()` with the USER text catalog attached
5896
+ * through `setCustomSource` (never the module-level builtin-only lookup, and
5897
+ * never a second per-frame rebuild).
5898
+ *
5899
+ * The returned notices are the renderer-owned ones the resolver could not
5900
+ * decide (the domain must not carry a second builtin id list): whether a
5901
+ * custom layout actually references an item with no renderable definition —
5902
+ * a USER command item, an extension item or an unknown id — is a REGISTRY
5903
+ * fact, decided here against the real definitions.
5904
+ */
5905
+ function compileNativeFooterPresentation(config) {
5906
+ const notices = [...config.notices];
5907
+ const registry = createBuiltinFooterRegistry();
5908
+ const catalog = new FooterCustomItemCatalog(config.userTextItems);
5909
+ registry.setCustomSource(catalog);
5910
+ if (config.mode === "custom" && config.layout !== void 0) {
5911
+ let unsupported = false;
5912
+ for (const row of config.layout.rows) for (const ref of [...row.left, ...row.right]) {
5913
+ if (ref.id === "view-scope") continue;
5914
+ if (ref.hideInTsp === true) continue;
5915
+ if (isExtensionId(ref.id)) {
5916
+ unsupported = true;
5917
+ continue;
5918
+ }
5919
+ if (registry.get(ref.id) === void 0) unsupported = true;
5920
+ }
5921
+ if (unsupported && !notices.includes(TSP_FOOTER_NOTICES.unavailableItems)) notices.push(TSP_FOOTER_NOTICES.unavailableItems);
5922
+ }
5923
+ return {
5924
+ mode: config.mode,
5925
+ layout: config.layout,
5926
+ registry,
5927
+ userCommandIds: config.userCommandIds,
5928
+ notices
5929
+ };
5930
+ }
5931
+ /** The visibility bound of an unavailable item's clamped name (cells). */
5932
+ const UNAVAILABLE_NAME_CELLS = 18;
5933
+ /**
5934
+ * The visible marker for one unsupported placement. The label never carries
5935
+ * the underlying command string or plugin path — only the user-facing name
5936
+ * (for a USER command item) or the fixed kind word.
5937
+ */
5938
+ function unavailableText(kind, name) {
5939
+ if (kind === "command" && name !== void 0 && name !== "") return `Unavailable: ${clampMiddle(sanitizedPhysicalLine(name), UNAVAILABLE_NAME_CELLS)}`;
5940
+ return `Unavailable: ${kind}`;
5941
+ }
5942
+ /** One unsupported placement's native shape: the warning marker. */
5943
+ function unavailableSeg(kind, name) {
5944
+ return {
5945
+ text: unavailableText(kind, name),
5946
+ tone: "warning"
5947
+ };
5948
+ }
5949
+ /** Whether an id belongs to the extension namespace (`ext:…`). */
5950
+ function isExtensionId(id) {
5951
+ return id.startsWith("ext:");
5952
+ }
5953
+ /**
5954
+ * Render one custom placement through its registry definition at `preferred`
5955
+ * density, or return the placement's unavailable marker. Returns `undefined`
5956
+ * only for a legitimately absent fact (the item renders nothing) and for the
5957
+ * retired inert `view-scope` item. The returned importance is the user's
5958
+ * override when present, otherwise the resolved definition's default (the
5959
+ * unavailable markers use the fixed plan priority 70).
5960
+ */
5961
+ function customRefSegments(snapshot, presentation, ref, side) {
5962
+ if (ref.id === "view-scope") return void 0;
5963
+ if (isExtensionId(ref.id)) return {
5964
+ ...unavailableSeg("extension"),
5965
+ importance: ref.importance ?? 70
5966
+ };
5967
+ const def = presentation.registry.get(ref.id);
5968
+ if (def === void 0) {
5969
+ if (ref.id.startsWith("user:")) return {
5970
+ ...unavailableSeg(presentation.userCommandIds.has(ref.id) ? "command" : "item", customItemName(ref.id)),
5971
+ importance: ref.importance ?? 70
5972
+ };
5973
+ return {
5974
+ ...unavailableSeg("item"),
5975
+ importance: ref.importance ?? 70
5976
+ };
5977
+ }
5978
+ const segment = def.render(snapshot, ref, "preferred", NO_SURFACE_HINTS);
5979
+ if (segment === null) return void 0;
5980
+ if (segment.spans.length === 0) return void 0;
5981
+ let text = sanitizedPhysicalLine(segment.spans.map((span) => span.text).join(""));
5982
+ if (text === "") return void 0;
5983
+ if (ref.prefix !== void 0) text = `${sanitizedPhysicalLine(ref.prefix)}${text}`;
5984
+ if (ref.suffix !== void 0) text = `${text}${sanitizedPhysicalLine(ref.suffix)}`;
5985
+ const tone = ref.tone !== void 0 && ref.tone !== "auto" ? nativeTone(ref.tone) : nativeTone(segment.spans.find((span) => span.tone !== void 0)?.tone);
5986
+ return {
5987
+ text,
5988
+ tone,
5989
+ importance: ref.importance ?? def.defaultImportance
5990
+ };
5991
+ }
5992
+ /**
5993
+ * The custom rows: one `ui.status` per layout row (1..2), each with the
5994
+ * left-zone and right-zone segments in their persisted placement order.
5995
+ * Keys are derived from the STABLE PLACEMENT PATH (row/zone/index) — never
5996
+ * from the bare user id — so a duplicate id keeps two independent segments.
5997
+ */
5998
+ function customRows(snapshot, presentation, affordances) {
5999
+ const layout = presentation.layout;
6000
+ if (layout === void 0) return [];
6001
+ const rows = [];
6002
+ for (const [rowIndex, row] of layout.rows.entries()) {
6003
+ const rowNumber = rowIndex + 1;
6004
+ const segments = [];
6005
+ for (const [zone, refs] of [["left", row.left], ["right", row.right]]) for (const [index, ref] of refs.entries()) {
6006
+ if (hideFooterRefInTsp(ref, affordances)) continue;
6007
+ const rendered = customRefSegments(snapshot, presentation, ref, zone);
6008
+ if (rendered === void 0) continue;
6009
+ segments.push(ui.seg({
6010
+ key: `footer-r${rowNumber}-${zone[0]}${index}`,
6011
+ text: rendered.text,
6012
+ ...rendered.tone === void 0 ? {} : { tone: rendered.tone },
6013
+ ...zone === "left" ? {} : { side: "right" },
6014
+ priority: rendered.importance
6015
+ }));
6016
+ }
6017
+ if (segments.length > 0) rows.push(ui.status({ key: `status-row-${rowNumber}` }, ...segments));
6018
+ }
6019
+ return rows;
6020
+ }
6021
+ function nativeStatuslineRows(snapshot, presentation, affordances = NO_COMPOSER_AFFORDANCES) {
6022
+ if (presentation === void 0 || presentation.mode === "default") {
6023
+ const rows = [];
6024
+ const rowOne = rowSegments(snapshot, ROW_ONE, affordances);
6025
+ if (rowOne.length > 0) rows.push(ui.status({ key: "status-row-1" }, ...rowOne));
6026
+ const rowTwo = rowSegments(snapshot, ROW_TWO, affordances);
6027
+ if (rowTwo.length > 0) rows.push(ui.status({ key: "status-row-2" }, ...rowTwo));
6028
+ return rows;
6029
+ }
6030
+ if (presentation.mode === "compact") {
6031
+ const row = rowSegments(snapshot, COMPACT_ROW, affordances);
6032
+ if (row.length > 0) return [ui.status({ key: "status-row-1" }, ...row)];
6033
+ return [];
6034
+ }
6035
+ return customRows(snapshot, presentation, affordances);
6036
+ }
6037
+ //#endregion
6038
+ //#region src/tui/tsp/quiet-composer-view.ts
6039
+ /**
6040
+ * TSP-7 PR-E: the Quiet Composer v2 presentational view.
6041
+ *
6042
+ * ONE pure view over render-time read-only values and synchronous click
6043
+ * callbacks: the controlled production `ui.editor`, the left Permission
6044
+ * trigger + popup, and the right Model / Effort / Stop / Send controls inside
6045
+ * the ONE rounded composer shell. It owns no business state, no timer and no
6046
+ * SDK session; the renderer passes the already-controlled editor node and
6047
+ * live values sampled at render time.
6048
+ *
6049
+ * The single scoped stylesheet below is the Owner-frozen v2 demo sheet mapped
6050
+ * to the product role namespace (`dsh.composer.*` / `dsh.footer.group`).
6051
+ * @module @xmoon76/dsh-pi-tui/tui/tsp/quiet-composer-view
6052
+ */
6053
+ /** The ONE surface-scoped stylesheet name the renderer installs. */
6054
+ const QUIET_COMPOSER_SHEET = "dsh-quiet-composer";
6055
+ /** The product role hooks used by the view and the stylesheet. */
6056
+ const QUIET_COMPOSER_ROLES = {
6057
+ shell: "dsh.composer.shell",
6058
+ controls: "dsh.composer.controls",
6059
+ permissionStack: "dsh.composer.permission-stack",
6060
+ permission: "dsh.composer.permission",
6061
+ permissionMenu: "dsh.composer.permission-menu",
6062
+ permissionOption: "dsh.composer.permission.option",
6063
+ right: "dsh.composer.right",
6064
+ model: "dsh.composer.model",
6065
+ effort: "dsh.composer.effort",
6066
+ send: "dsh.composer.send",
6067
+ stop: "dsh.composer.stop",
6068
+ footerGroup: "dsh.footer.group"
6069
+ };
6070
+ /** Build the ONE Quiet Composer shell (editor + controls). */
6071
+ function quietComposerView(input) {
6072
+ const scope = input.scope;
6073
+ const permission = input.permission;
6074
+ const permissionTitle = permission.interactive ? `Permission: ${permission.label} — click to choose` : `Permission: ${permission.label} — the current permission is not selectable from this session`;
6075
+ const menu = permission.expanded ? ui.col({
6076
+ key: "composer-permission-menu",
6077
+ role: QUIET_COMPOSER_ROLES.permissionMenu
6078
+ }, ...permission.options.map((option) => html.button({
6079
+ key: `composer-permission-option-${scope}-${permission.menuEpoch}-${option.id}`,
6080
+ role: QUIET_COMPOSER_ROLES.permissionOption,
6081
+ title: option.label,
6082
+ aria: option.label,
6083
+ ...option.selected || option.highlighted === true ? { attrs: {
6084
+ ...option.selected ? { "data-current": "true" } : {},
6085
+ ...option.highlighted === true ? { "data-highlight": "true" } : {}
6086
+ } } : {},
6087
+ onClick: () => input.onPermissionChoose(option.id, permission.menuEpoch)
6088
+ }, `${option.label}${option.selected ? " ✓" : ""}`))) : void 0;
6089
+ return ui.col({
6090
+ key: "quiet-composer",
6091
+ role: QUIET_COMPOSER_ROLES.shell,
6092
+ gap: "none"
6093
+ }, input.editor, ui.row({
6094
+ key: "composer-controls",
6095
+ role: QUIET_COMPOSER_ROLES.controls,
6096
+ gap: "sm",
6097
+ align: "center"
6098
+ }, ui.col({
6099
+ key: "composer-permission-stack",
6100
+ role: QUIET_COMPOSER_ROLES.permissionStack,
6101
+ gap: "none"
6102
+ }, ...menu === void 0 ? [] : [menu], html.button({
6103
+ key: `composer-permission-${scope}`,
6104
+ role: QUIET_COMPOSER_ROLES.permission,
6105
+ title: permissionTitle,
6106
+ aria: "Permission",
6107
+ ...permission.interactive ? {} : { attrs: { "aria-disabled": "true" } },
6108
+ onClick: () => input.onPermissionToggle()
6109
+ }, ui.icon({
6110
+ key: "permission-icon",
6111
+ name: "shield"
6112
+ }), `${permission.label} ${permission.expanded ? "▴" : "▾"}`)), ui.row({
6113
+ key: "composer-right",
6114
+ role: QUIET_COMPOSER_ROLES.right,
6115
+ gap: "sm",
6116
+ align: "center"
6117
+ }, html.button({
6118
+ key: `composer-model-${scope}`,
6119
+ role: QUIET_COMPOSER_ROLES.model,
6120
+ title: input.model.title,
6121
+ aria: "Switch model",
6122
+ ...input.model.interactive ? {} : { attrs: { "aria-disabled": "true" } },
6123
+ onClick: () => input.onModel()
6124
+ }, input.model.label), html.button({
6125
+ key: `composer-effort-${scope}`,
6126
+ role: QUIET_COMPOSER_ROLES.effort,
6127
+ title: input.effort.title,
6128
+ aria: "Change reasoning effort",
6129
+ ...input.effort.interactive ? {} : { attrs: { "aria-disabled": "true" } },
6130
+ onClick: () => input.onEffort()
6131
+ }, input.effort.label), ...input.busy ? [html.button({
6132
+ key: `composer-stop-${scope}r${input.busyEpoch}`,
6133
+ role: QUIET_COMPOSER_ROLES.stop,
6134
+ title: "Stop the running turn",
6135
+ aria: "Stop the running turn",
6136
+ onClick: () => input.onStop()
6137
+ }, "Stop")] : [], html.button({
6138
+ key: `composer-send-${scope}`,
6139
+ role: QUIET_COMPOSER_ROLES.send,
6140
+ title: input.sendable ? "Send message" : "Type a message to send",
6141
+ aria: "Send message",
6142
+ ...input.sendable ? {} : { attrs: {
6143
+ "aria-disabled": "true",
6144
+ disabled: "disabled"
6145
+ } },
6146
+ onClick: () => input.onSend()
6147
+ }, "↑"))));
6148
+ }
6149
+ /** The ONE scoped sheet: every selector starts from the two product role
6150
+ * hooks, so no rule can reach another TSP panel or Tern chrome. */
6151
+ const QUIET_COMPOSER_STYLES = `
6152
+ [data-role='dsh.composer.shell'] {
6153
+ display: flex;
6154
+ flex-direction: column;
6155
+ gap: 8px;
6156
+ padding: 12px;
6157
+ border: 1px solid var(--l2);
6158
+ border-radius: 12px;
6159
+ background: var(--card);
6160
+ margin-bottom: 4px;
6161
+ }
6162
+ [data-role='dsh.composer.shell'] .sf-editor {
6163
+ min-height: calc(2 * var(--sf-lh));
6164
+ padding: 2px 2px 0;
6165
+ border: 0;
6166
+ border-radius: 0;
6167
+ background: transparent;
6168
+ box-shadow: none;
6169
+ outline: 0;
6170
+ color: var(--t1);
6171
+ font-family: var(--sans);
6172
+ }
6173
+ [data-role='dsh.composer.shell'] .sf-editor.focused {
6174
+ border: 0;
6175
+ box-shadow: none;
6176
+ outline: 0;
6177
+ }
6178
+ [data-role='dsh.composer.shell'] .sf-editor .sf-ed-ph {
6179
+ color: var(--t4);
6180
+ }
6181
+ [data-role='dsh.composer.shell'] .sf-editor .sf-caret {
6182
+ background: var(--accent);
6183
+ }
6184
+ [data-role='dsh.composer.controls'] {
6185
+ display: flex;
6186
+ align-items: center;
6187
+ gap: 8px;
6188
+ flex-wrap: nowrap;
6189
+ }
6190
+ [data-role='dsh.composer.permission-stack'] {
6191
+ position: relative;
6192
+ flex-shrink: 0;
6193
+ }
6194
+ [data-role='dsh.composer.permission'] {
6195
+ display: inline-flex;
6196
+ align-items: center;
6197
+ gap: 4px;
6198
+ padding: 4px 2px;
6199
+ border: 0;
6200
+ border-radius: 0;
6201
+ background: transparent;
6202
+ color: var(--t2);
6203
+ font-family: var(--sans);
6204
+ font-size: 12px;
6205
+ line-height: 1.5;
6206
+ cursor: pointer;
6207
+ flex-shrink: 0;
6208
+ }
6209
+ [data-role='dsh.composer.permission']:hover {
6210
+ color: var(--t1);
6211
+ }
6212
+ [data-role='dsh.composer.permission'] .sf-icon {
6213
+ color: var(--t3);
6214
+ }
6215
+ [data-role='dsh.composer.permission-menu'] {
6216
+ position: absolute;
6217
+ bottom: calc(100% + 6px);
6218
+ left: 0;
6219
+ z-index: 10;
6220
+ display: flex;
6221
+ flex-direction: column;
6222
+ gap: 2px;
6223
+ min-width: 168px;
6224
+ padding: 4px;
6225
+ border: 1px solid var(--l2);
6226
+ border-radius: 8px;
6227
+ background: var(--pop-bg);
6228
+ box-shadow: none;
6229
+ }
6230
+ [data-role='dsh.composer.permission-menu'] [data-role='dsh.composer.permission.option'] {
6231
+ display: flex;
6232
+ align-items: center;
6233
+ justify-content: space-between;
6234
+ gap: 8px;
6235
+ padding: 5px 8px;
6236
+ border: 0;
6237
+ border-radius: 6px;
6238
+ background: transparent;
6239
+ color: var(--t2);
6240
+ font-family: var(--sans);
6241
+ font-size: 12px;
6242
+ line-height: 1.5;
6243
+ text-align: left;
6244
+ cursor: pointer;
6245
+ }
6246
+ [data-role='dsh.composer.permission-menu'] [data-role='dsh.composer.permission.option']:hover {
6247
+ background: rgb(from var(--t1) r g b / 4%);
6248
+ }
6249
+ [data-role='dsh.composer.permission-menu'] [data-role='dsh.composer.permission.option'][data-highlight='true'] {
6250
+ background: rgb(from var(--t1) r g b / 7%);
6251
+ }
6252
+ [data-role='dsh.composer.permission-menu'] [data-role='dsh.composer.permission.option'][data-current='true'] {
6253
+ color: var(--t1);
6254
+ font-weight: 500;
6255
+ }
6256
+ [data-role='dsh.composer.right'] {
6257
+ margin-left: auto;
6258
+ display: flex;
6259
+ align-items: center;
6260
+ gap: 8px;
6261
+ min-width: 0;
6262
+ flex-wrap: nowrap;
6263
+ }
6264
+ [data-role='dsh.composer.model'] {
6265
+ display: inline-block;
6266
+ flex-shrink: 1;
6267
+ max-width: 240px;
6268
+ min-width: 0;
6269
+ overflow: hidden;
6270
+ text-overflow: ellipsis;
6271
+ white-space: nowrap;
6272
+ padding: 4px 2px;
6273
+ border: 0;
6274
+ border-radius: 0;
6275
+ background: transparent;
6276
+ color: var(--t1);
6277
+ font-family: var(--sans);
6278
+ font-size: 12px;
6279
+ line-height: 1.5;
6280
+ text-align: left;
6281
+ cursor: pointer;
6282
+ }
6283
+ [data-role='dsh.composer.model']:hover {
6284
+ color: var(--t1);
6285
+ background: var(--l1);
6286
+ }
6287
+ [data-role='dsh.composer.effort'] {
6288
+ flex-shrink: 0;
6289
+ padding: 4px 2px;
6290
+ border: none;
6291
+ background: transparent;
6292
+ color: var(--t3);
6293
+ font-family: var(--sans);
6294
+ font-size: 12px;
6295
+ line-height: 1.5;
6296
+ cursor: pointer;
6297
+ }
6298
+ [data-role='dsh.composer.effort']:hover {
6299
+ color: var(--t1);
6300
+ }
6301
+ [data-role='dsh.composer.send'] {
6302
+ display: inline-flex;
6303
+ align-items: center;
6304
+ justify-content: center;
6305
+ width: 30px;
6306
+ height: 30px;
6307
+ padding: 0;
6308
+ border: none;
6309
+ border-radius: 50%;
6310
+ background: var(--accent-fill);
6311
+ color: #fff;
6312
+ font-family: var(--sans);
6313
+ font-size: 15px;
6314
+ font-weight: 600;
6315
+ line-height: 1;
6316
+ cursor: pointer;
6317
+ flex-shrink: 0;
6318
+ }
6319
+ [data-role='dsh.composer.send']:hover {
6320
+ filter: brightness(1.06);
6321
+ }
6322
+ [data-role='dsh.composer.send'][aria-disabled='true'] {
6323
+ opacity: 0.75;
6324
+ background: var(--l1);
6325
+ color: var(--t3);
6326
+ box-shadow: inset 0 0 0 1px var(--l3);
6327
+ cursor: not-allowed;
6328
+ filter: none;
6329
+ }
6330
+ [data-role='dsh.composer.stop'] {
6331
+ flex-shrink: 0;
6332
+ padding: 4px 10px;
6333
+ border: 1px solid rgb(from var(--bad) r g b / 35%);
6334
+ border-radius: 999px;
6335
+ background: transparent;
6336
+ color: var(--bad);
6337
+ font-family: var(--sans);
6338
+ font-size: 12px;
6339
+ font-weight: 500;
6340
+ line-height: 1.5;
6341
+ cursor: pointer;
6342
+ }
6343
+ [data-role='dsh.composer.stop']:hover {
6344
+ background: rgb(from var(--bad) r g b / 10%);
6345
+ }
6346
+ [data-role='dsh.footer.group'] {
6347
+ display: flex;
6348
+ flex-direction: column;
6349
+ gap: 0;
6350
+ margin: 0;
6351
+ padding: 0;
6352
+ }
6353
+ [data-role='dsh.footer.group'] .sf-status {
6354
+ height: var(--sf-lh);
6355
+ min-height: 0;
6356
+ line-height: var(--sf-lh);
6357
+ background: transparent;
6358
+ border: none;
6359
+ box-shadow: none;
6360
+ outline: none;
6361
+ margin: 0;
6362
+ padding-top: 0;
6363
+ padding-bottom: 0;
6364
+ }
6365
+ [data-role='dsh.footer.group'] .sf-status .sf-st-row {
6366
+ height: var(--sf-lh);
6367
+ min-height: 0;
6368
+ line-height: var(--sf-lh);
6369
+ margin: 0;
6370
+ padding-top: 0;
6371
+ padding-bottom: 0;
6372
+ }
6373
+ `;
6374
+ //#endregion
4760
6375
  //#region src/tui/tsp/work-hub.ts
4761
6376
  /**
4762
6377
  * The internal native TSP Work Hub (PR4 B3-A1).
@@ -6079,6 +7694,7 @@ function imageIdentityText(ref) {
6079
7694
  function imageStatusText(state) {
6080
7695
  switch (state.state) {
6081
7696
  case "unsupported": return "Native image display unavailable in this Tern pane";
7697
+ case "disabled": return "Image preview disabled by PI_IMAGE_PROTOCOL";
6082
7698
  case "no-scope": return "Image unavailable for this session";
6083
7699
  case "loading": return "Loading image…";
6084
7700
  case "error": return "Image read failed";
@@ -6115,7 +7731,7 @@ function imageBlockNodes(block, state, keyPrefix) {
6115
7731
  key: `${keyPrefix}${block.index}-info`,
6116
7732
  text: sanitizeDisplayText(info)
6117
7733
  })];
6118
- if (state === void 0 || state.state === "unsupported" || state.state === "no-scope") return nodes;
7734
+ if (state === void 0 || state.state === "unsupported" || state.state === "disabled" || state.state === "no-scope") return nodes;
6119
7735
  const blob = state.state === "ready" ? state.blobId : PENDING_IMAGE_BLOB_ID;
6120
7736
  nodes.push(ui.image({
6121
7737
  key: `${keyPrefix}${block.index}-image`,
@@ -6825,16 +8441,6 @@ function transcriptView(structure, keys, options = {}) {
6825
8441
  * product path never loads it.
6826
8442
  * @module @xmoon76/dsh-pi-tui/tui/tsp/session
6827
8443
  */
6828
- /**
6829
- * The banner the composer-active renderer pins in its dock. The PR3-A
6830
- * read-only banner (with its bare `q` quit key) retired together with the
6831
- * composer: a typed `q` is EDITOR TEXT now. Like the PR3-A banner, it names
6832
- * NO chord labels — the renderer owns no keymap (there is no authority to
6833
- * route a chord label through), and the host-keybindings gate keeps its
6834
- * sanctioned-seam list closed to non-keymap copy. The submit/newline
6835
- * gestures are the SDK editor's own affordances.
6836
- */
6837
- const DOCK_BANNER = "DSH TSP renderer · experimental composer";
6838
8444
  /** The exact kinds and feature the Reader's document and keys require. */
6839
8445
  const WORK_DETAILS_KINDS = [
6840
8446
  "col",
@@ -6888,6 +8494,7 @@ function errorText(value) {
6888
8494
  }
6889
8495
  /** Mount the renderer over an already-connected SDK session. */
6890
8496
  function mountTspRenderer(session, options) {
8497
+ const imagePreference = imageProtocolPreference(process.env);
6891
8498
  const surface = session.open({
6892
8499
  mode: "inline",
6893
8500
  title: "dsh"
@@ -6933,6 +8540,39 @@ function mountTspRenderer(session, options) {
6933
8540
  outline: 1px solid var(--accent);
6934
8541
  outline-offset: 1px;
6935
8542
  }
8543
+ `);
8544
+ /**
8545
+ * The native modal capability: the EXACT kind set each composite really
8546
+ * paints, read from the negotiated handshake — never from a version label or
8547
+ * a window size. Questions needs its own form kind plus the pieces of the
8548
+ * same-style safe/Review pages; the Tool approval additionally needs
8549
+ * `badge` is in the set because a dangerous request paints a danger marker,
8550
+ * and an approval that cannot show one is not an honest approval. It also
8551
+ * needs `styles`, because the pane must be able to hide the Enter keycap below
8552
+ * before the form may advertise a shortcut the application deliberately
8553
+ * refuses to honour. A pane that lacks either half keeps the text form; it
8554
+ * never gets a misleading affordance and never a fabricated result.
8555
+ */
8556
+ const nativeQuestionsCapable = () => [
8557
+ "questions",
8558
+ "button",
8559
+ "input",
8560
+ "overlay",
8561
+ "col",
8562
+ "row",
8563
+ "text"
8564
+ ].every((kind) => session.caps.kinds.includes(kind));
8565
+ const nativeApprovalCapable = () => [
8566
+ "tool",
8567
+ "overlay",
8568
+ "col",
8569
+ "text",
8570
+ "code",
8571
+ "scroll",
8572
+ "badge"
8573
+ ].every((kind) => session.caps.kinds.includes(kind)) && session.caps.features.includes("styles");
8574
+ if (nativeApprovalCapable()) surface.stylesheet("dsh-native-approval-shortcuts", `
8575
+ [data-role="${NATIVE_APPROVAL_ROLE}"] .sf-tool-ask-btn .sf-kbd { display: none; }
6936
8576
  `);
6937
8577
  let disposed = false;
6938
8578
  let exitRequested = false;
@@ -7000,9 +8640,9 @@ function mountTspRenderer(session, options) {
7000
8640
  */
7001
8641
  let disposeTask;
7002
8642
  const dock = {
7003
- statusLine: DOCK_BANNER,
7004
8643
  notices: [],
7005
- welcome: []
8644
+ welcome: [],
8645
+ footerNotices: []
7006
8646
  };
7007
8647
  const pending = {
7008
8648
  queued: [],
@@ -7048,7 +8688,10 @@ function mountTspRenderer(session, options) {
7048
8688
  },
7049
8689
  beforeModalSeat: () => {
7050
8690
  retireWorkDetails("modal");
7051
- }
8691
+ },
8692
+ surfaceId: surface.id,
8693
+ nativeQuestions: nativeQuestionsCapable(),
8694
+ nativeApproval: nativeApprovalCapable()
7052
8695
  });
7053
8696
  modelPicker = new TspModelPicker({
7054
8697
  render: () => render(),
@@ -7056,7 +8699,8 @@ function mountTspRenderer(session, options) {
7056
8699
  notify: (text, kind) => display.notify(text, kind),
7057
8700
  nativeScroll: (id, to) => {
7058
8701
  surface.scroll(id, to);
7059
- }
8702
+ },
8703
+ nativeKv: session.caps.kinds.includes("kv")
7060
8704
  });
7061
8705
  presetPicker = new TspPresetPicker({
7062
8706
  render: () => render(),
@@ -7064,7 +8708,8 @@ function mountTspRenderer(session, options) {
7064
8708
  notify: (text, kind) => display.notify(text, kind),
7065
8709
  nativeScroll: (id, to) => {
7066
8710
  surface.scroll(id, to);
7067
- }
8711
+ },
8712
+ nativeKv: session.caps.kinds.includes("kv")
7068
8713
  });
7069
8714
  sessionBrowser = new TspSessionBrowser({
7070
8715
  surfaceId: surface.id,
@@ -7074,7 +8719,8 @@ function mountTspRenderer(session, options) {
7074
8719
  nativeScroll: (id, to) => {
7075
8720
  surface.scroll(id, to);
7076
8721
  },
7077
- scrollSupported: session.caps.features.includes("scroll")
8722
+ scrollSupported: session.caps.features.includes("scroll"),
8723
+ nativeKv: session.caps.kinds.includes("kv")
7078
8724
  });
7079
8725
  modelPicker.resize(session.caps.cols, session.caps.cell.w);
7080
8726
  workHub = new TspWorkHub({
@@ -7227,6 +8873,59 @@ function mountTspRenderer(session, options) {
7227
8873
  let imageBinding;
7228
8874
  let imageBindingInstalled = false;
7229
8875
  /**
8876
+ * TSP-7 PR-A: the read-only status reader, installed ONCE by the mount. It
8877
+ * is sampled ONLY at the formal display commit point — never on a render,
8878
+ * never through a subscription — so the renderer never observes a
8879
+ * half-applied store state.
8880
+ */
8881
+ let statusReader;
8882
+ /** TSP-7 PR-A: the one-time binding latch (a lifecycle fact, not a cache). */
8883
+ let statusReaderInstalled = false;
8884
+ /**
8885
+ * TSP-7 PR-D: the compiled footer presentation of THIS mount (undefined =
8886
+ * the frozen PR-A/B default — a direct test mount that never bound a
8887
+ * config). Immutable for the renderer's whole life: the boot snapshot is
8888
+ * compiled once at bind time and never re-read (a settings change needs a
8889
+ * new TSP process, not a repaint).
8890
+ */
8891
+ let footerPresentation;
8892
+ /**
8893
+ * TSP-7 PR-A: the last FORMALLY COMMITTED, displayable snapshot reference.
8894
+ * It is a read-only presentation pointer — never patched, derived or
8895
+ * persisted — cleared at every hydration begin so an outgoing subject's
8896
+ * status can never paint beside the incoming one's transcript.
8897
+ */
8898
+ let presentedStatus;
8899
+ /**
8900
+ * PR-C (external review r3): the busy-LIFETIME identity of the current
8901
+ * display subject — a renderer-local presentation serial advanced at every
8902
+ * FALSE→TRUE busy edge of the formally-committed snapshot (and reset with
8903
+ * the subject at hydration). It is the same class of ephemeral identity as
8904
+ * `readerEpoch`/`noticeSeq`, NOT a business mirror: nothing reads it except
8905
+ * the Stop button's node key, so a click minted against turn A's Stop can
8906
+ * never resolve onto turn B's re-painted button — the old node id is simply
8907
+ * absent from the current view and the SDK's own dispatch drops it.
8908
+ */
8909
+ let busyEpoch = 0;
8910
+ /**
8911
+ * TSP-7 PR-E: the ONLY local presentation state of the Quiet Composer
8912
+ * Permission menu. `permissionMenuEpoch` advances on every false→true
8913
+ * expansion so a click minted for an older expansion can never resolve onto
8914
+ * the new one; `permissionMenuIndex` is the keyboard-highlighted option.
8915
+ * Neither is a business pending flag: the StatusRuntime owns every write.
8916
+ */
8917
+ let permissionMenuOpen = false;
8918
+ let permissionMenuEpoch = 0;
8919
+ let permissionMenuIndex = 0;
8920
+ /** Close the menu and invalidate in-flight option identities. Returns
8921
+ * whether the menu was open (the caller decides whether to repaint). */
8922
+ function closePermissionMenu() {
8923
+ if (!permissionMenuOpen) return false;
8924
+ permissionMenuOpen = false;
8925
+ permissionMenuIndex = 0;
8926
+ return true;
8927
+ }
8928
+ /**
7230
8929
  * PR-C: the immutable image scope of the CURRENT display subject, captured
7231
8930
  * ONCE per projection source. An ordinary repaint or delta REUSES it: the
7232
8931
  * scope is never re-resolved when an async read settles, so a retired
@@ -7292,6 +8991,15 @@ function mountTspRenderer(session, options) {
7292
8991
  * the return to the composer after a modal — the pre-B3 one-shot latch left
7293
8992
  * the composer dead after the first modal close). */
7294
8993
  let lastAppliedFocusId;
8994
+ /** The ONE composer-chrome capability gate (PR-C row / PR-E Quiet
8995
+ * Composer): without `el`+`styles` the renderer keeps the controlled
8996
+ * editor + native footer only, never a fake text button. */
8997
+ const composerChromeSupported = () => session.caps.features.includes("styles") && session.caps.kinds.includes("el");
8998
+ /** The editor's REAL node path: inside the Quiet Composer Shell it is
8999
+ * `dock.quiet-composer.composer` (region -> shell key -> editor key); the
9000
+ * no-chrome branch keeps the historical `dock.composer`. ONE function so
9001
+ * `applyFocus` can never focus two paths or the wrong one. */
9002
+ const composerEditorFocusId = () => composerChromeSupported() ? "dock.quiet-composer.composer" : "dock.composer";
7295
9003
  /** Apply the seat's desired hardware focus after a committed frame. */
7296
9004
  const applyFocus = (force) => {
7297
9005
  if (disposed) return;
@@ -7300,10 +9008,11 @@ function mountTspRenderer(session, options) {
7300
9008
  lastAppliedFocusId = void 0;
7301
9009
  return;
7302
9010
  }
7303
- const desired = seat.hasModalSeat() ? seat.desiredFocusId() : workHub?.isOpen() === true ? workHub.desiredFocusId() ?? null : sessionBrowser?.isOpen() === true ? sessionBrowser.desiredFocusId() ?? null : presetPicker?.isOpen() === true ? presetPicker.desiredFocusId() ?? null : modelPicker?.isOpen() === true ? modelPicker.desiredFocusId() ?? null : "dock.composer";
9011
+ const composerFocusId = composerEditorFocusId();
9012
+ const desired = seat.hasModalSeat() ? seat.desiredFocusId() : workHub?.isOpen() === true ? workHub.desiredFocusId() ?? null : sessionBrowser?.isOpen() === true ? sessionBrowser.desiredFocusId() ?? null : presetPicker?.isOpen() === true ? presetPicker.desiredFocusId() ?? null : modelPicker?.isOpen() === true ? modelPicker.desiredFocusId() ?? null : composerFocusId;
7304
9013
  if (!force && desired === lastAppliedFocusId) return;
7305
9014
  lastAppliedFocusId = desired;
7306
- composer.setFocused(desired === "dock.composer");
9015
+ composer.setFocused(desired === composerFocusId);
7307
9016
  surface.focus(desired);
7308
9017
  };
7309
9018
  /** Whether the pane negotiated everything the Reader's document needs. */
@@ -7566,9 +9275,12 @@ function mountTspRenderer(session, options) {
7566
9275
  /**
7567
9276
  * PR-C: whether the pane can carry a native image at all. The `image` kind
7568
9277
  * and the `blobs` feature are NEGOTIATED by the client — the mapper never
7569
- * infers them from a TypeScript prop.
9278
+ * infers them from a TypeScript prop. The SAME `PI_IMAGE_PROTOCOL` policy
9279
+ * that governs PiTui pixels governs this native TSP path: only `auto` may
9280
+ * send an image node/blob. Any explicit value is a deliberate disable of
9281
+ * ANSI/native image preview, not a request to emulate another transport.
7570
9282
  */
7571
- const nativeImagesSupported = () => session.caps.kinds.includes("image") && session.caps.features.includes("blobs");
9283
+ const nativeImagesSupported = () => imagePreference === "auto" && session.caps.kinds.includes("image") && session.caps.features.includes("blobs");
7572
9284
  /**
7573
9285
  * PR-C: the image attachments the CURRENT window projects, in window
7574
9286
  * order. The row rule is the mapper's own ({@link toolRowImageBlocks}), so
@@ -7632,7 +9344,8 @@ function mountTspRenderer(session, options) {
7632
9344
  const states = /* @__PURE__ */ new Map();
7633
9345
  const refs = projectedImageRefs();
7634
9346
  if (!nativeImagesSupported()) {
7635
- for (const ref of refs) states.set(ref.attachmentId, { state: "unsupported" });
9347
+ const state = imagePreference === "auto" ? { state: "unsupported" } : { state: "disabled" };
9348
+ for (const ref of refs) states.set(ref.attachmentId, state);
7636
9349
  return states;
7637
9350
  }
7638
9351
  const scope = activeImageScope;
@@ -8084,7 +9797,8 @@ function mountTspRenderer(session, options) {
8084
9797
  * publish.
8085
9798
  */
8086
9799
  const dockPreviewLimit = () => {
8087
- if (!(previewStylesSupported() && session.caps.features.includes("blobs") && session.caps.kinds.includes("image"))) return 0;
9800
+ if (!nativeImagesSupported()) return 0;
9801
+ if (!previewStylesSupported()) return 0;
8088
9802
  const cols = session.caps.cols;
8089
9803
  return cols < 72 ? 0 : cols < 100 ? 1 : 2;
8090
9804
  };
@@ -8111,9 +9825,16 @@ function mountTspRenderer(session, options) {
8111
9825
  text: sanitizeDisplayText(`DSH session ${facts.sessionId}${model}`)
8112
9826
  }));
8113
9827
  }
8114
- for (const item of pending.queued) lines.push(ui.text({
8115
- key: `queue-${item.id}`,
8116
- text: sanitizeDisplayText(`queued (${item.mode}): ${item.text}`)
9828
+ for (const item of pending.queued) {
9829
+ const sending = item.local === true ? " — sending…" : "";
9830
+ lines.push(ui.text({
9831
+ key: `queue-${item.id}`,
9832
+ text: sanitizeDisplayText(`queued (${item.mode}): ${item.text}${sending}`)
9833
+ }));
9834
+ }
9835
+ if (!pending.running && pending.queued.some((item) => item.local !== true)) lines.push(ui.text({
9836
+ key: "queue-parked-hint",
9837
+ text: "waiting for the next prompt — send a message to continue"
8117
9838
  }));
8118
9839
  for (const [index, row] of pending.tail.entries()) lines.push(ui.text({
8119
9840
  key: `tail-${index}`,
@@ -8128,11 +9849,15 @@ function mountTspRenderer(session, options) {
8128
9849
  text: pendingSubmit === "submit" ? "Submitting…" : "Queued…"
8129
9850
  }));
8130
9851
  const draftCount = imageBinding?.draftImages.occurrences().length ?? 0;
8131
- const statusLine = draftCount === 0 ? dock.statusLine : `Draft ${draftCount} · ${dock.statusLine === "" ? DOCK_BANNER : dock.statusLine}`;
8132
- if (statusLine !== "") lines.push(ui.text({
8133
- key: "status",
9852
+ if (draftCount > 0) lines.push(ui.text({
9853
+ key: "draft-count",
9854
+ wrap: "none",
9855
+ text: `Draft ${draftCount}`
9856
+ }));
9857
+ for (const legacy of legacyDockLines()) lines.push(ui.text({
9858
+ key: legacy.key,
8134
9859
  wrap: "none",
8135
- text: sanitizedPhysicalLine(statusLine)
9860
+ text: sanitizedPhysicalLine(legacy.text)
8136
9861
  }));
8137
9862
  if (seat.attentionCount() > 0) lines.push(ui.text({
8138
9863
  key: "question-attention",
@@ -8150,6 +9875,10 @@ function mountTspRenderer(session, options) {
8150
9875
  text: `${TSP_VISUAL_SELECT_LABEL} select visual · ${TSP_VISUAL_COPY_LABEL} copy`
8151
9876
  }));
8152
9877
  }
9878
+ for (const notice of dock.footerNotices) lines.push(ui.text({
9879
+ key: `notice-${notice.id}`,
9880
+ text: notice.kind === "error" ? `! ${sanitizeDisplayText(notice.text)}` : sanitizeDisplayText(notice.text)
9881
+ }));
8153
9882
  for (const notice of dock.notices) {
8154
9883
  const noticeText = sanitizeDisplayText(notice.text);
8155
9884
  lines.push(ui.text({
@@ -8159,14 +9888,18 @@ function mountTspRenderer(session, options) {
8159
9888
  }
8160
9889
  const preview = dockDraftNodes(draftStates);
8161
9890
  if (preview !== void 0) lines.push(preview);
8162
- lines.push(ui.editor({
8163
- key: "composer",
8164
- text: composer.state().text,
8165
- cursor: composer.state().cursor,
8166
- maxLines: 8,
8167
- placeholder: "Message",
8168
- prompt: "> "
8169
- }));
9891
+ const editorNode = composerEditorNode();
9892
+ const quietShell = composerActionsSupported() ? quietComposerNode(editorNode) : void 0;
9893
+ lines.push(quietShell ?? editorNode);
9894
+ const footerRows = presentedStatus !== void 0 && !hydrating ? nativeStatuslineRows(presentedStatus, footerPresentation, nativeFooterAffordances()) : [];
9895
+ if (footerRows.length > 0) {
9896
+ if (composerActionsSupported()) lines.push(ui.col({
9897
+ key: "footer-group",
9898
+ role: QUIET_COMPOSER_ROLES.footerGroup,
9899
+ gap: "none"
9900
+ }, ...footerRows));
9901
+ else lines.push(...footerRows);
9902
+ }
8170
9903
  return ui.col({ key: "dock" }, ...lines);
8171
9904
  };
8172
9905
  const loadingMain = () => ui.col({ key: "transcript" }, ui.md({
@@ -8181,6 +9914,7 @@ function mountTspRenderer(session, options) {
8181
9914
  retiredSource = void 0;
8182
9915
  hydrating = false;
8183
9916
  scopeEpoch += 1;
9917
+ closePermissionMenu();
8184
9918
  scopePrefix = `s${scopeEpoch}-`;
8185
9919
  scopeKeys = new TranscriptNodeKeys();
8186
9920
  releaseImageSubscriptions();
@@ -8195,29 +9929,52 @@ function mountTspRenderer(session, options) {
8195
9929
  if (!rebuildLastMain()) return;
8196
9930
  render();
8197
9931
  };
8198
- /** Mutable renderer-local mirror of the last committed status facts. */
9932
+ /** Mutable renderer-local mirror of the last committed status facts (the
9933
+ * facts the legacy dock lines still read; the machine facts the activity
9934
+ * projection consumes live in the surface's store, not here). */
8199
9935
  const statusFacts = {};
8200
- const flushStatus = () => {
8201
- const parts = [];
8202
- if (statusFacts.busy === true || statusFacts.working === true) parts.push("working");
8203
- if (statusFacts.planMode === true) parts.push("plan");
8204
- if (statusFacts.compactionPhase !== void 0 && statusFacts.compactionPhase !== "idle") parts.push(`compacting (${statusFacts.compactionPhase})`);
8205
- if (statusFacts.sessionTitle !== void 0 && statusFacts.sessionTitle !== "") parts.push(statusFacts.sessionTitle);
9936
+ /**
9937
+ * TSP-7 PR-A: the legacy dock text lines that survive as SHORT standalone
9938
+ * rows. They are the facts no PR-A native item carries (the session title and
9939
+ * the todo completion count) plus the compaction phase, an immediate state
9940
+ * channel that must not depend on a status commit. The banner's `plan` word
9941
+ * migrated to the native plan-state row; the run-phase display lives in the
9942
+ * surface's activity projection (the native run seg), not this mirror.
9943
+ */
9944
+ const legacyDockLines = () => {
9945
+ const lines = [];
9946
+ if (statusFacts.compactionPhase !== void 0 && statusFacts.compactionPhase !== "idle") lines.push({
9947
+ key: "compaction-phase",
9948
+ text: `compacting (${statusFacts.compactionPhase})`
9949
+ });
9950
+ if (statusFacts.sessionTitle !== void 0 && statusFacts.sessionTitle !== "") lines.push({
9951
+ key: "session-title",
9952
+ text: statusFacts.sessionTitle
9953
+ });
8206
9954
  const todos = statusFacts.todos;
8207
9955
  if (todos !== void 0 && todos.length > 0) {
8208
9956
  const open = todos.filter((todo) => todo.status !== "completed").length;
8209
- parts.push(`todos ${todos.length - open}/${todos.length}`);
9957
+ lines.push({
9958
+ key: "todos",
9959
+ text: `todos ${todos.length - open}/${todos.length}`
9960
+ });
8210
9961
  }
8211
- dock.statusLine = parts.length === 0 ? DOCK_BANNER : `${DOCK_BANNER} · ${parts.join(" · ")}`;
9962
+ return lines;
9963
+ };
9964
+ const flushStatus = () => {
8212
9965
  render();
8213
9966
  };
8214
9967
  const display = {
8215
9968
  setTranscript,
8216
- commitDisplaySubject() {},
9969
+ commitDisplaySubject() {
9970
+ if (disposed) return;
9971
+ if (statusReader === void 0) throw new Error("the TSP renderer has no status reader: the mount must bind one");
9972
+ const previous = presentedStatus;
9973
+ presentedStatus = statusReader.snapshot();
9974
+ if (previous !== void 0 && previous.activity.busy !== true && presentedStatus.activity.busy === true) busyEpoch += 1;
9975
+ render();
9976
+ },
8217
9977
  commitStatusFacts(facts) {
8218
- if (facts.busy !== void 0) statusFacts.busy = facts.busy;
8219
- if (facts.working !== void 0) statusFacts.working = facts.working;
8220
- if (facts.planMode !== void 0) statusFacts.planMode = facts.planMode;
8221
9978
  if ("sessionTitle" in facts) statusFacts.sessionTitle = facts.sessionTitle;
8222
9979
  if (facts.todos !== void 0) statusFacts.todos = facts.todos;
8223
9980
  if (facts.compactionPhase !== void 0) statusFacts.compactionPhase = facts.compactionPhase;
@@ -8229,6 +9986,7 @@ function mountTspRenderer(session, options) {
8229
9986
  },
8230
9987
  beginSessionHydration() {
8231
9988
  if (disposed) return;
9989
+ closePermissionMenu();
8232
9990
  retireWorkDetails("session-change");
8233
9991
  sessionBrowser?.retire();
8234
9992
  modelPicker?.retire();
@@ -8237,6 +9995,8 @@ function mountTspRenderer(session, options) {
8237
9995
  seat.closeTransientList();
8238
9996
  hydrating = true;
8239
9997
  retiredSource = projectionScope;
9998
+ presentedStatus = void 0;
9999
+ busyEpoch = 0;
8240
10000
  releaseImageSubscriptions();
8241
10001
  clearVisualFrameState();
8242
10002
  lastStreamingToolPreviews = [];
@@ -8339,6 +10099,353 @@ function mountTspRenderer(session, options) {
8339
10099
  if (workHub?.isOpen() === true || sessionBrowser?.isOpen() === true || presetPicker?.isOpen() === true || modelPicker?.isOpen() === true) return false;
8340
10100
  return true;
8341
10101
  };
10102
+ const composerActionsSupported = () => composerChromeSupported();
10103
+ /** The native Model picker the composer's Model/Effort buttons open needs
10104
+ * the picker surface itself (`picker`/`row`/`overlay`); `el`+`styles` alone
10105
+ * only proves the button can paint, not that its business entry can run. */
10106
+ const modelPickerCapable = () => [
10107
+ "picker",
10108
+ "row",
10109
+ "overlay"
10110
+ ].every((kind) => session.caps.kinds.includes(kind));
10111
+ /** The REAL `/model` business entry: negotiated picker kinds AND the
10112
+ * registered UI opener (a Host-owned `/model` leaves the name registered
10113
+ * but no TUI opener). */
10114
+ const modelPickerAvailable = () => composerActionsSupported() && modelPickerCapable() && (boundHandlers?.modelPickerAvailable?.() ?? true);
10115
+ /** The three standard presets the Quiet Composer menu may offer, in the
10116
+ * Owner-frozen order. `auto`/custom presets stay available through
10117
+ * `/permission` and Shift+Tab but never enter this three-row menu. */
10118
+ const STANDARD_PERMISSION_OPTIONS = [
10119
+ {
10120
+ id: "read-only",
10121
+ label: "Read Only"
10122
+ },
10123
+ {
10124
+ id: "workspace-write",
10125
+ label: "Workspace Write"
10126
+ },
10127
+ {
10128
+ id: "danger-full-access",
10129
+ label: "Full Access"
10130
+ }
10131
+ ];
10132
+ /** The render-time menu projection: catalog ids intersected with the
10133
+ * standard three, and the authoritative current id marked selected. */
10134
+ const permissionMenuOptions = () => {
10135
+ const handlers = boundHandlers;
10136
+ if (handlers === void 0) return [];
10137
+ const roster = handlers.permissionOptions?.() ?? [];
10138
+ const fact = presentedStatus?.access.permissionPreset;
10139
+ return STANDARD_PERMISSION_OPTIONS.filter((option) => roster.includes(option.id)).map((option) => ({
10140
+ id: option.id,
10141
+ label: option.label,
10142
+ selected: fact?.matched === true && fact.id === option.id
10143
+ }));
10144
+ };
10145
+ /** Whether the Quiet Composer really provides an operable Permission
10146
+ * control for the CURRENT main subject — the PR-F footer fallback reads
10147
+ * this exact fact (never a status value guess). */
10148
+ const permissionComposerAffordance = () => composerActionsSupported() && boundHandlers !== void 0 && presentedStatus?.view.subject.kind === "main" && presentedStatus?.access.permissionPreset?.matched === true && permissionMenuOptions().length > 0;
10149
+ /**
10150
+ * PR-F: the LIVE composer capability facts the universal footer visibility
10151
+ * uses for its default-On fallback. Each flag means "the TSP dock really
10152
+ * presents and can operate this control now" — never "a status value
10153
+ * exists". PR-E now provides the real Permission control; the model and
10154
+ * reasoning controls exist whenever the Quiet Composer chrome does.
10155
+ */
10156
+ const nativeFooterAffordances = () => ({
10157
+ permission: permissionComposerAffordance(),
10158
+ model: modelPickerAvailable(),
10159
+ reasoning: modelPickerAvailable()
10160
+ });
10161
+ if (composerActionsSupported()) surface.stylesheet(QUIET_COMPOSER_SHEET, QUIET_COMPOSER_STYLES);
10162
+ /**
10163
+ * PR-C (TSP-7 §3.3): the ONE shared submit helper — the Editor's Enter
10164
+ * branch and the Send button both run EXACTLY this sequence (the frozen
10165
+ * PR3-B §3.4 before-callback ordering). No business-level filtering lives
10166
+ * here: the submission controller owns admission, rollback and the queue.
10167
+ */
10168
+ const submitComposerDraft = (handlers, gesture) => {
10169
+ handlers.noteUserInput();
10170
+ const serializedDraft = composer.getDraft();
10171
+ composer.setDraft("");
10172
+ handlers.submit(serializedDraft, gesture);
10173
+ };
10174
+ /**
10175
+ * PR-C (TSP-7 §3.3): the ONE pointer admission predicate of the composer
10176
+ * controls. A click arrives on the SDK node-handler channel (not through
10177
+ * `dispatchKey`), so it re-checks the CURRENT seat here: disposal, the
10178
+ * hydration window, the pre-bind renderer, a modal seat, the temporary
10179
+ * Reader and any open native presenter each own the input before the dock
10180
+ * does. It is a shared local predicate — no `enabled` mirror is persisted
10181
+ * and no second state machine exists.
10182
+ */
10183
+ const composerActionsAdmitted = () => visualActionsAdmitted();
10184
+ /**
10185
+ * PR-C (TSP-7): the Send click — the same one-shot submit path as Enter. A
10186
+ * wire-form-empty draft (no text AND no image placeholder) is refused here:
10187
+ * the client does not enforce `disabled` on an `el` button (measured), so
10188
+ * the program is the one that must not submit an empty prompt.
10189
+ */
10190
+ const composerSendClicked = () => {
10191
+ if (!composerActionsAdmitted()) return;
10192
+ const handlers = boundHandlers;
10193
+ if (handlers === void 0) return;
10194
+ if (!composerDraftSubmittable()) return;
10195
+ submitComposerDraft(handlers, "enter");
10196
+ };
10197
+ /**
10198
+ * PR-C (TSP-7): the Stop click — the EXISTING cancel intent, exactly like
10199
+ * Ctrl+C. It re-checks the busy fact at click time (a one-frame-old painted
10200
+ * button must never cancel a NEW session's run) and never reads or writes
10201
+ * the draft.
10202
+ */
10203
+ const composerStopClicked = () => {
10204
+ if (!composerActionsAdmitted()) return;
10205
+ const handlers = boundHandlers;
10206
+ if (handlers === void 0) return;
10207
+ if (presentedStatus?.activity.busy !== true) return;
10208
+ handlers.cancel();
10209
+ };
10210
+ /** PR-C (TSP-7): whether the live wire-form draft carries a submittable
10211
+ * payload — non-empty text or at least one staged image placeholder. */
10212
+ const composerDraftSubmittable = () => {
10213
+ if (composer.getDraft() !== "") return true;
10214
+ return (imageBinding?.draftImages.occurrences().length ?? 0) > 0;
10215
+ };
10216
+ /**
10217
+ * PR-C (TSP-7): the Model/Effort click — the ONE registered `/model`
10218
+ * command's own UI entry (§3.1's late-bound seam), admitted only on the
10219
+ * current seat. The draft and caret are untouched: the picker is a modal
10220
+ * layer over the same composer.
10221
+ */
10222
+ const composerModelClicked = (entry) => {
10223
+ if (!composerActionsAdmitted()) return;
10224
+ const handlers = boundHandlers;
10225
+ if (handlers === void 0) return;
10226
+ try {
10227
+ handlers.openModelPicker(entry);
10228
+ } catch (error) {
10229
+ display.notify("model selection is unavailable in this session (the /model command is not registered)", "error");
10230
+ options.logError?.("tsp renderer: composer model entry refused", { error: errorText(error) });
10231
+ }
10232
+ };
10233
+ /** The Quiet Composer's narrow-pane threshold (measured: 400px pane is
10234
+ * below this, the 637px GUI pane is above it). */
10235
+ const QUIET_COMPOSER_NARROW_COLS = 56;
10236
+ /** The bounded display budgets of the Quiet Composer labels. */
10237
+ const QUIET_COMPOSER_MODEL_WIDTH = 34;
10238
+ const QUIET_COMPOSER_MODEL_NARROW_WIDTH = 14;
10239
+ const QUIET_COMPOSER_PERMISSION_WIDTH = 24;
10240
+ /** The controlled editor node: the SAME program-owned draft/cursor cell,
10241
+ * with the v2 placeholder and NO `> ` prompt inside the quiet shell. */
10242
+ const composerEditorNode = () => {
10243
+ const state = composer.state();
10244
+ return composerActionsSupported() ? ui.editor({
10245
+ key: "composer",
10246
+ text: state.text,
10247
+ cursor: state.cursor,
10248
+ maxLines: 8,
10249
+ placeholder: "What would you like to work on?"
10250
+ }) : ui.editor({
10251
+ key: "composer",
10252
+ text: state.text,
10253
+ cursor: state.cursor,
10254
+ maxLines: 8,
10255
+ placeholder: "Message",
10256
+ prompt: "> "
10257
+ });
10258
+ };
10259
+ /** The authoritative permission label, one-line sanitized and bounded. */
10260
+ const permissionTriggerLabel = () => {
10261
+ const fact = presentedStatus?.access.permissionPreset;
10262
+ const source = fact?.label !== void 0 && fact.label !== "" ? fact.label : fact?.id;
10263
+ const clean = source === void 0 ? "" : sanitizedPhysicalLine(source).trim();
10264
+ if (clean === "") return "Permission";
10265
+ if (session.caps.cols < QUIET_COMPOSER_NARROW_COLS && fact?.id === "workspace-write") return "Write";
10266
+ return clampMiddle(clean, QUIET_COMPOSER_PERMISSION_WIDTH);
10267
+ };
10268
+ /** The edit-time admission of the permission menu: a real main-subject
10269
+ * permission fact, a non-empty standard roster, the bound UI owner and no
10270
+ * modal/Reader/picker/hydration/disposed owner. */
10271
+ const permissionMenuAdmitted = () => permissionComposerAffordance() && visualActionsAdmitted();
10272
+ /** Toggle the menu; opening starts a NEW expansion identity and lands the
10273
+ * keyboard highlight on the current preset when one is present. */
10274
+ const composerPermissionToggled = () => {
10275
+ if (!permissionMenuAdmitted()) return;
10276
+ if (permissionMenuOpen) {
10277
+ closePermissionMenu();
10278
+ render();
10279
+ return;
10280
+ }
10281
+ const options = permissionMenuOptions();
10282
+ if (options.length === 0) return;
10283
+ permissionMenuOpen = true;
10284
+ permissionMenuEpoch += 1;
10285
+ const selected = options.findIndex((option) => option.selected);
10286
+ permissionMenuIndex = selected < 0 ? 0 : selected;
10287
+ render();
10288
+ };
10289
+ /** One admitted option click. The captured expansion scope and epoch are
10290
+ * both re-checked against the live renderer before the single writer is
10291
+ * called; the menu closes FIRST so no second click can ever double-apply. */
10292
+ const permissionOptionChosen = (renderScope, id, menuEpoch) => {
10293
+ if (disposed || hydrating || !inputBound) return;
10294
+ if (renderScope !== scopeEpoch || !permissionMenuOpen || menuEpoch !== permissionMenuEpoch) return;
10295
+ if (!permissionMenuAdmitted()) {
10296
+ closePermissionMenu();
10297
+ render();
10298
+ return;
10299
+ }
10300
+ const option = permissionMenuOptions().find((candidate) => candidate.id === id);
10301
+ if (option === void 0) {
10302
+ closePermissionMenu();
10303
+ render();
10304
+ return;
10305
+ }
10306
+ closePermissionMenu();
10307
+ render();
10308
+ if (option.selected) return;
10309
+ const select = boundHandlers?.selectPermission;
10310
+ if (select === void 0) {
10311
+ display.notify("permission selection is unavailable in this session", "error");
10312
+ return;
10313
+ }
10314
+ try {
10315
+ select(id);
10316
+ } catch (error) {
10317
+ display.notify("permission selection is unavailable in this session", "error");
10318
+ options.logError?.("tsp renderer: permission selection entry refused", { error: errorText(error) });
10319
+ }
10320
+ };
10321
+ /** The menu's keyboard slice: Up/Down cycle, Enter chooses the highlighted
10322
+ * option, Escape closes ONLY the menu. Returns true when the key was
10323
+ * consumed by the menu. */
10324
+ const permissionMenuHandleKey = (key) => {
10325
+ if (!permissionMenuOpen) return false;
10326
+ const optionsNow = permissionMenuOptions();
10327
+ if (optionsNow.length === 0) {
10328
+ closePermissionMenu();
10329
+ render();
10330
+ return false;
10331
+ }
10332
+ const count = optionsNow.length;
10333
+ if (key.name === "up") {
10334
+ permissionMenuIndex = (Math.min(permissionMenuIndex, count - 1) - 1 + count) % count;
10335
+ render();
10336
+ return true;
10337
+ }
10338
+ if (key.name === "down") {
10339
+ permissionMenuIndex = (Math.min(permissionMenuIndex, count - 1) + 1) % count;
10340
+ render();
10341
+ return true;
10342
+ }
10343
+ if (key.name === "enter") {
10344
+ const option = optionsNow[Math.min(permissionMenuIndex, count - 1)];
10345
+ permissionOptionChosen(scopeEpoch, option.id, permissionMenuEpoch);
10346
+ return true;
10347
+ }
10348
+ if (key.name === "escape") {
10349
+ closePermissionMenu();
10350
+ render();
10351
+ return true;
10352
+ }
10353
+ if (closePermissionMenu()) render();
10354
+ return false;
10355
+ };
10356
+ /** The Quiet Composer's model/effort labels + title, with the frozen
10357
+ * narrow-pane degradation and external-fact sanitization. */
10358
+ const quietComposerModelView = () => {
10359
+ const model = presentedStatus?.composition.model;
10360
+ const cleanName = model?.displayName === void 0 ? void 0 : sanitizedPhysicalLine(model.displayName).trim();
10361
+ const cleanEffort = model?.reasoningEffort === void 0 ? void 0 : sanitizedPhysicalLine(model.reasoningEffort).trim();
10362
+ const narrow = session.caps.cols < QUIET_COMPOSER_NARROW_COLS;
10363
+ return {
10364
+ label: `${(cleanName === void 0 || cleanName === "" ? void 0 : clampMiddle(cleanName, narrow ? QUIET_COMPOSER_MODEL_NARROW_WIDTH : QUIET_COMPOSER_MODEL_WIDTH)) ?? "Model"} ▾`,
10365
+ title: model === void 0 ? "Model — type /model to switch" : `Model ${cleanName}${cleanEffort === void 0 || cleanEffort === "" ? "" : ` · effort ${cleanEffort}`} — type /model to switch`,
10366
+ interactive: boundHandlers !== void 0
10367
+ };
10368
+ };
10369
+ /** The narrow-pane effort abbreviation: keep the REAL value's identity,
10370
+ * never a guessed `H` for every non-High value. Unknown free-form values
10371
+ * keep a bounded prefix instead of being relabelled. */
10372
+ const narrowEffortLabel = (value) => {
10373
+ switch (value.toLowerCase()) {
10374
+ case "low": return "L";
10375
+ case "medium": return "M";
10376
+ case "high": return "H";
10377
+ case "max": return "Max";
10378
+ case "off": return "Off";
10379
+ default: return clampMiddle(value, 6);
10380
+ }
10381
+ };
10382
+ const quietComposerEffortView = () => {
10383
+ const effort = presentedStatus?.composition.model?.reasoningEffort;
10384
+ const clean = effort === void 0 ? void 0 : sanitizedPhysicalLine(effort).trim();
10385
+ if (clean === void 0 || clean === "") return {
10386
+ label: "Effort ▾",
10387
+ title: "Reasoning effort — type /model to change",
10388
+ interactive: boundHandlers !== void 0
10389
+ };
10390
+ return {
10391
+ label: `${session.caps.cols < QUIET_COMPOSER_NARROW_COLS ? narrowEffortLabel(clean) : clampMiddle(clean, 14)} ▾`,
10392
+ title: `Reasoning effort ${clean} — type /model to change`,
10393
+ interactive: boundHandlers !== void 0
10394
+ };
10395
+ };
10396
+ /** Build the ONE Quiet Composer shell around the controlled editor. */
10397
+ const quietComposerNode = (editor) => {
10398
+ if (!composerActionsSupported()) return void 0;
10399
+ if (permissionMenuOpen && !permissionMenuAdmitted()) closePermissionMenu();
10400
+ const baseOptions = permissionMenuOptions();
10401
+ const index = Math.min(Math.max(0, permissionMenuIndex), Math.max(0, baseOptions.length - 1));
10402
+ permissionMenuIndex = index;
10403
+ const options = baseOptions.map((option, optionIndex) => ({
10404
+ ...option,
10405
+ highlighted: optionIndex === index
10406
+ }));
10407
+ const model = quietComposerModelView();
10408
+ const effort = quietComposerEffortView();
10409
+ const renderScope = scopeEpoch;
10410
+ return quietComposerView({
10411
+ editor,
10412
+ scope: `s${renderScope}`,
10413
+ busyEpoch,
10414
+ permission: {
10415
+ label: permissionTriggerLabel(),
10416
+ interactive: permissionComposerAffordance(),
10417
+ expanded: permissionMenuOpen && options.length > 0,
10418
+ options,
10419
+ menuEpoch: permissionMenuEpoch
10420
+ },
10421
+ model,
10422
+ effort,
10423
+ busy: presentedStatus?.activity.busy === true && !hydrating,
10424
+ sendable: composerDraftSubmittable(),
10425
+ onPermissionToggle: () => {
10426
+ composerPermissionToggled();
10427
+ },
10428
+ onPermissionChoose: (id, menuEpoch) => {
10429
+ permissionOptionChosen(renderScope, id, menuEpoch);
10430
+ },
10431
+ onModel: () => {
10432
+ if (closePermissionMenu()) render();
10433
+ composerModelClicked("models");
10434
+ },
10435
+ onEffort: () => {
10436
+ if (closePermissionMenu()) render();
10437
+ composerModelClicked("effort");
10438
+ },
10439
+ onSend: () => {
10440
+ if (closePermissionMenu()) render();
10441
+ composerSendClicked();
10442
+ },
10443
+ onStop: () => {
10444
+ if (closePermissionMenu()) render();
10445
+ composerStopClicked();
10446
+ }
10447
+ });
10448
+ };
8342
10449
  /** The EXACT payload of one admitted publication: the final ChartFact as
8343
10450
  * pretty JSON, or the admitted SVG source verbatim (never trimmed). */
8344
10451
  const visualCopyPayload = (publication) => {
@@ -8455,6 +10562,7 @@ function mountTspRenderer(session, options) {
8455
10562
  return false;
8456
10563
  }
8457
10564
  if (key.ctrl === true && key.name === "c") {
10565
+ if (closePermissionMenu()) render();
8458
10566
  handlers.cancel();
8459
10567
  return false;
8460
10568
  }
@@ -8462,6 +10570,7 @@ function mountTspRenderer(session, options) {
8462
10570
  if (sessionBrowser?.handleKey(key)) return false;
8463
10571
  if (presetPicker?.handleKey(key)) return false;
8464
10572
  if (modelPicker?.handleKey(key)) return false;
10573
+ if (permissionMenuHandleKey(key)) return false;
8465
10574
  if (key.name === "escape") {
8466
10575
  handlers.cancel();
8467
10576
  return false;
@@ -8480,12 +10589,7 @@ function mountTspRenderer(session, options) {
8480
10589
  return false;
8481
10590
  }
8482
10591
  const edit = composer.applyKey(key);
8483
- if (edit.kind === "submit") {
8484
- handlers.noteUserInput();
8485
- const serializedDraft = composer.getDraft();
8486
- composer.setDraft("");
8487
- handlers.submit(serializedDraft, edit.gesture);
8488
- }
10592
+ if (edit.kind === "submit") submitComposerDraft(handlers, edit.gesture);
8489
10593
  if (edit.kind === "edited") handlers.noteUserInput();
8490
10594
  if (edit.kind === "exit-empty") return true;
8491
10595
  return false;
@@ -8528,7 +10632,7 @@ function mountTspRenderer(session, options) {
8528
10632
  }
8529
10633
  if (details.phase === "open" && handleDetailsEvent(input.event)) return false;
8530
10634
  if ("sf" in input.event && input.event.sf === details.surface.id) return false;
8531
- if (input.event.ev === "focus" || input.event.ev === "edit" || input.event.ev === "undo" || input.event.ev === "send" || input.event.ev === "toggle" || input.event.ev === "select" || input.event.ev === "activate" || input.event.ev === "action") return false;
10635
+ if (input.event.ev === "focus" || input.event.ev === "edit" || input.event.ev === "undo" || input.event.ev === "send" || input.event.ev === "toggle" || input.event.ev === "select" || input.event.ev === "activate" || input.event.ev === "action" || input.event.ev === "change") return false;
8532
10636
  }
8533
10637
  if (input.event.ev === "toggle" && input.event.sf === surface.id) {
8534
10638
  let disclosure;
@@ -8637,6 +10741,26 @@ function mountTspRenderer(session, options) {
8637
10741
  imageBindingInstalled = true;
8638
10742
  imageBinding = binding;
8639
10743
  },
10744
+ bindStatusReader: (reader) => {
10745
+ if (disposed) throw new Error("cannot bind status reader after TSP renderer disposal");
10746
+ if (statusReaderInstalled) throw new Error("the TSP renderer status reader is already bound");
10747
+ statusReaderInstalled = true;
10748
+ statusReader = reader;
10749
+ },
10750
+ bindNativeFooterConfig: (config) => {
10751
+ if (disposed) throw new Error("cannot bind the footer config after TSP renderer disposal");
10752
+ if (footerPresentation !== void 0) throw new Error("the TSP renderer footer config is already bound");
10753
+ footerPresentation = compileNativeFooterPresentation(config);
10754
+ const footerNotices = footerPresentation.notices.map((text, index) => ({
10755
+ id: `fn${index + 1}`,
10756
+ text,
10757
+ kind: "error"
10758
+ }));
10759
+ if (footerNotices.length > 0) {
10760
+ dock.footerNotices = footerNotices;
10761
+ render();
10762
+ }
10763
+ },
8640
10764
  bindInput: (handlers) => {
8641
10765
  if (disposed) throw new Error("the TSP renderer is disposed");
8642
10766
  if (inputBound) throw new Error("the TSP renderer input is already bound");