@xmoon76/dsh-pi-tui 0.5.7 → 0.5.9

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 (78) hide show
  1. package/README.en.md +64 -26
  2. package/README.md +64 -26
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-C9nl6e13.mjs → bootstrap-CVyHGQDX.mjs} +22330 -6888
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-CGezi85O.mjs → client-bootstrap-4UoeVIHE.mjs} +2407 -1830
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-H_1r5Cqs.mjs → daemon-launcher-DxIgjBHW.mjs} +1551 -57
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/diagnostics-Db5iVcuJ.mjs +123 -0
  14. package/dist/{entry-control-jBfKn1qO.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-6a5vvJUT.mjs → extensions-Dx7ncPNA.mjs} +1 -4
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DK7n5jDu.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22766 -6893
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +719 -93
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-BPZw1wEd.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-BMoNXZjJ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-Bq3jLAn1.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +970 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DEuGAy8l.mjs → local-scope-5DEKA_lW.mjs} +1075 -31
  43. package/dist/{local-transport-X4ZCe2uE.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DKWtXIkr.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-DC0XQr5O.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-Cihe8PPS.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-CARqn3kV.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-D4DHyXDo.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -335
  70. package/dist/{transcript-view-a7cROAaI.mjs → transcript-view-B6vCnukn.mjs} +2284 -1166
  71. package/dist/{transcript-view-hvNVkPtv.mjs → transcript-view-DSSdE2vK.mjs} +2191 -765
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +25 -8
  74. package/dist/local-acp-listener-CNkguN5-.mjs +0 -2566
  75. package/dist/local-daemon-control-Bg9s2aYi.mjs +0 -1424
  76. package/dist/local-daemon-control-Cu_4FIdd.mjs +0 -1585
  77. package/dist/local-profile-daemon-admin-AXgVH-6y.mjs +0 -91
  78. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -1,5 +1,6 @@
1
+ import { o as shortSessionId } from "./browser-CDUSHIIr.mjs";
1
2
  import { d as resolveCommandFooterFallback, l as isFooterLayout, u as parseFooterLayout } from "./command-trust-DChWUamk.mjs";
2
- import { $ as parseFooterCustomItems, B as truncateToWidth, H as wrapTextWithAnsi, J as customItemName, Q as parseFooterCustomItem, R as sliceByColumn, V as visibleWidth, q as customItemId, r as CombinedAutocompleteProvider, w as fuzzyFilter } from "./dist-BFgC-5tL.mjs";
3
+ import { $ as parseFooterCustomItem, H as visibleWidth, J as customItemId, T as fuzzyFilter, U as wrapTextWithAnsi, V as truncateToWidth, Y as customItemName, et as parseFooterCustomItems, i as CombinedAutocompleteProvider, z as sliceByColumn } from "./recall-scope-9Nuoto_i.mjs";
3
4
  import { createHash } from "node:crypto";
4
5
  import { accessSync, appendFileSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
5
6
  import { delimiter, dirname, join, posix, win32 } from "node:path";
@@ -11,9 +12,9 @@ import { parseExitStatus } from "@deepseek-ai/dsh-shell";
11
12
  import { ToolCallId, expandAssistantStream as expandAssistantStream$1 } from "@deepseek-ai/dsh-llm";
12
13
  import { open, readdir, stat } from "node:fs/promises";
13
14
  import { formatFileMention } from "@deepseek-ai/dsh-file-reference/grammar";
14
- import { Chalk } from "chalk";
15
15
  import { Marked } from "marked";
16
16
  import { eastAsianWidth } from "get-east-asian-width";
17
+ import { Chalk } from "chalk";
17
18
  import { SaxesParser } from "saxes";
18
19
  import { html, ui } from "@stencil-hq/tern";
19
20
  //#region src/client/history/store.ts
@@ -696,6 +697,25 @@ function classifyTranscriptMessage(message) {
696
697
  }
697
698
  }
698
699
  /**
700
+ * The ONE internal numeric model-turn reader shared by transcript consumers:
701
+ * the row's admitted semantic-turn ownership, or `undefined` when the row
702
+ * owns none (a command, a window summary, or a compaction that never proved a
703
+ * numeric owner). A standalone compaction is a real transcript row that
704
+ * belongs to NO model turn — never `0`, never a placement anchor. This is
705
+ * SEMANTIC ownership; the fold's presentation placement (`TranscriptFolder`
706
+ * `placementAnchorOf`) is a separate fact and must never be promoted here.
707
+ *
708
+ * Already-narrowed accesses on tool/system/assistant/user rows keep their
709
+ * definite `turn`; this helper exists for the generic row readers (window,
710
+ * grouping, Focus projection, search navigation) whose union includes the
711
+ * optional-turn compaction row.
712
+ */
713
+ function transcriptTurnOf(message) {
714
+ if (!("turn" in message)) return void 0;
715
+ const turn = message.turn;
716
+ return typeof turn === "number" ? turn : void 0;
717
+ }
718
+ /**
699
719
  * Whether a system row is an injected context boundary that Focus keeps
700
720
  * visible when its Thought is collapsed. The fold's authoritative `context`
701
721
  * marker intentionally covers unknown/future injection producers too.
@@ -849,7 +869,9 @@ function isTranscriptContextForm(value) {
849
869
  * relay/notice sender, and the inject/recall role. This is the SINGLE
850
870
  * parser of raw context sources; the fold and every projection consume its
851
871
  * result. An absent/unknown form stays undefined — the caller must present
852
- * the row as standalone generic Context.
872
+ * the row as standalone generic Context. `formDeclared` preserves the raw
873
+ * PRESENCE of the member (even an unknown or non-string value) so eligibility
874
+ * can distinguish "no form declared" from "declared but not understood".
853
875
  * @param source - the logged user/message source, exactly as recorded.
854
876
  */
855
877
  function contextPresentation(source) {
@@ -858,11 +880,19 @@ function contextPresentation(source) {
858
880
  if (record === null) return { role };
859
881
  const kind = readString(record, "kind");
860
882
  const form = record["form"];
883
+ const formDeclared = Object.hasOwn(record, "form");
861
884
  const senderSessionId = readString(record, "senderSessionId");
885
+ const entries = record["entries"];
886
+ const completeCatalogUpdate = kind === "skill-catalog" && form === "catalog" && record["update"] === true && !Object.hasOwn(record, "incomplete") && Array.isArray(entries) && entries.every((entry) => {
887
+ const item = asRecord(entry);
888
+ return item !== null && readString(item, "name") !== null && typeof item["description"] === "string";
889
+ });
862
890
  return {
863
891
  ...isTranscriptContextForm(form) ? { form } : {},
892
+ ...formDeclared ? { formDeclared: true } : {},
864
893
  ...kind === null ? {} : { sourceKind: kind },
865
894
  ...senderSessionId === null ? {} : { senderSessionId },
895
+ ...completeCatalogUpdate ? { completeCatalogUpdate: true } : {},
866
896
  role
867
897
  };
868
898
  }
@@ -886,6 +916,22 @@ function isAmbientContext(message) {
886
916
  return isSurfacedContext(message) && form !== void 0 && AMBIENT_CONTEXT_FORMS.includes(form);
887
917
  }
888
918
  /**
919
+ * Whether one row is an image-bearing `ptc-mode` injected Context row.
920
+ *
921
+ * This is a STRUCTURED MEDIA question only: surfaced Context + the exact
922
+ * producer source kind `ptc-mode` + at least one real `image` ContentBlock.
923
+ * It deliberately says nothing about same-turn delivery/carriage (that is the
924
+ * separate `sameTurnNextStep` presentation flag), nothing about producer
925
+ * intent subtypes (none exist yet) and never parses the flat text. The
926
+ * producer's text-only Spill Context and its environment-reset Context are
927
+ * therefore never image-bearing rows.
928
+ */
929
+ function isPtcImageContext(message) {
930
+ if (!isSurfacedContext(message)) return false;
931
+ if (message.contextPresentation?.sourceKind !== "ptc-mode") return false;
932
+ return message.content !== void 0 && message.content.some((block) => block.type === "image");
933
+ }
934
+ /**
889
935
  * The card-header icon SEMANTIC for one context injection, keyed by source
890
936
  * kind so a reader can tell an instruction file from a skill catalog or a
891
937
  * recalled session at a glance (the Web renders one browse icon for all of
@@ -939,8 +985,9 @@ function recentTurnThreshold(messages, recentTurns, kinds) {
939
985
  if (recentTurns <= 0) return Number.POSITIVE_INFINITY;
940
986
  const turns = /* @__PURE__ */ new Set();
941
987
  for (const message of messages) {
942
- if (message.kind === "summary" || !("turn" in message)) continue;
943
- if (kinds === void 0 || kinds.includes(message.kind)) turns.add(message.turn);
988
+ const turn = transcriptTurnOf(message);
989
+ if (turn === void 0) continue;
990
+ if (kinds === void 0 || kinds.includes(message.kind)) turns.add(turn);
944
991
  }
945
992
  const sorted = [...turns].sort((a, b) => b - a);
946
993
  if (sorted.length <= recentTurns) return 0;
@@ -1908,12 +1955,18 @@ function windowMessages(messages, maxTurns, endTurn) {
1908
1955
  if (maxTurns <= 0) return [...messages];
1909
1956
  if (endTurn !== void 0) {
1910
1957
  const turns = /* @__PURE__ */ new Set();
1911
- for (const message of messages) if ("turn" in message) turns.add(message.turn);
1958
+ for (const message of messages) {
1959
+ const turn = transcriptTurnOf(message);
1960
+ if (turn !== void 0) turns.add(turn);
1961
+ }
1912
1962
  const sorted = [...turns].sort((a, b) => b - a);
1913
1963
  const anchor = sorted.indexOf(endTurn);
1914
1964
  if (anchor === -1) return windowMessages(messages, maxTurns);
1915
1965
  const windowTurns = new Set(sorted.slice(anchor, anchor + maxTurns));
1916
- const kept = messages.filter((message) => !("turn" in message) || windowTurns.has(message.turn));
1966
+ const kept = messages.filter((message) => {
1967
+ const turn = transcriptTurnOf(message);
1968
+ return turn === void 0 || windowTurns.has(turn);
1969
+ });
1917
1970
  const newerTurns = new Set(sorted.slice(0, anchor));
1918
1971
  const oldTurns = new Set(sorted.slice(anchor + maxTurns));
1919
1972
  if (newerTurns.size === 0 && oldTurns.size === 0) return kept;
@@ -1933,10 +1986,11 @@ function windowMessages(messages, maxTurns, endTurn) {
1933
1986
  let oldTools = 0;
1934
1987
  let oldCount = 0;
1935
1988
  for (const message of messages) {
1936
- if ("turn" in message && message.turn < boundary) {
1989
+ const turn = transcriptTurnOf(message);
1990
+ if (turn !== void 0 && turn < boundary) {
1937
1991
  oldCount += 1;
1938
1992
  if (message.kind === "tool") oldTools += 1;
1939
- oldTurns.add(message.turn);
1993
+ oldTurns.add(turn);
1940
1994
  continue;
1941
1995
  }
1942
1996
  kept.push(message);
@@ -2062,6 +2116,16 @@ function assistantLatestStepOf(activity) {
2062
2116
  }
2063
2117
  /** Whether an Assistant crossed an admitted human-steer boundary and is
2064
2118
  * therefore a persistent conversation answer rather than Focus process. */
2119
+ /** Whether the exact Assistant row's step has authoritative continuation
2120
+ * evidence in the Fold: a real tool/call or step boundary after its
2121
+ * settlement, or a later output that confirmed its streaming candidate. The
2122
+ * Focus projection holds a latest-step settled Assistant back as the pending
2123
+ * final ONLY when this fact is absent; presentation row kind/order never
2124
+ * answers that question. */
2125
+ function assistantStepIntermediateOf(activity, message) {
2126
+ const step = assistantStepOf(message);
2127
+ return step !== void 0 && activity.intermediateAssistantSteps.has(step);
2128
+ }
2065
2129
  function assistantCommittedBeforeSteer(activity, message) {
2066
2130
  if (message.kind !== "assistant") return false;
2067
2131
  const step = assistantStepOf(message);
@@ -2444,9 +2508,15 @@ function assistantEntryHasInterruptionEvidence(entry) {
2444
2508
  * the shared {@link WorkflowProjection} owns the projection itself. */
2445
2509
  var TranscriptFolder = class TranscriptFolder {
2446
2510
  items = [];
2447
- /** Durable next-step identities awaiting a claim or replacement. */
2511
+ /** The observed valid positional prefix of the durable next-step queue,
2512
+ * awaiting a claim, cancellation or replacement. A fragment that cannot
2513
+ * address this prefix exactly discards it (fail open); JS splice clamping is
2514
+ * never positional evidence. */
2448
2515
  pendingNextSteps = [];
2449
- /** Claimed next-step identities, including their insertion time. */
2516
+ /** Unconsumed positive claim candidates: removed from next-step by an
2517
+ * official full-drain claim in this same open turn, awaiting the actual
2518
+ * `user/message` append. Retired at the owning turn's step/turn end and when
2519
+ * a newer open turn is accepted. */
2450
2520
  claimedNextStepTurns = /* @__PURE__ */ new Map();
2451
2521
  /** The assistant message object per (turn, step); streaming text lands in place. */
2452
2522
  assistantEntries = /* @__PURE__ */ new Map();
@@ -2579,21 +2649,15 @@ var TranscriptFolder = class TranscriptFolder {
2579
2649
  * turn 0 itself is a perfectly legal first turn (an in-turn-0 command
2580
2650
  * anchored to 0 must NOT be re-anchored away by turn 1). */
2581
2651
  seenAcceptedTurnStart = false;
2582
- /** The placement-anchor AUTHORITY for turn-less standalone rows (plan
2583
- * §8.1/§9): one anchor per command object, written at append time and
2584
- * re-anchored with the leading prefix. Search navigation, the fast
2585
- * indexed window's physical ranges and the non-monotonic defensive window
2586
- * all derive placement from this ONE sidecar — never a semantic `turn` on
2587
- * the row. */
2588
- commandPlacementTurns = /* @__PURE__ */ new WeakMap();
2589
- /** The placement anchor a fused command HANDS OVER to its combined
2590
- * manual-compaction owner: the visible representative of a manual
2591
- * `/compact` is the compaction card, so its window/search placement must
2592
- * inherit the command's anchor (a pre-turn or replayed manual compaction
2593
- * would otherwise keep the legacy `currentTurn` and anchor the wrong
2594
- * bounded window). Written at fuse time; re-anchored with the leading
2595
- * prefix exactly like the command sidecar. */
2596
- manualCompactionPlacementTurns = /* @__PURE__ */ new WeakMap();
2652
+ /** The placement-anchor AUTHORITY for standalone rows (plan §4.3): one
2653
+ * anchor per command object, per compaction WITHOUT an admitted numeric
2654
+ * model-turn owner, and per successfully fused compaction representative.
2655
+ * Written at append time and re-anchored with the leading prefix. Search
2656
+ * navigation, the fast indexed window's physical ranges and the
2657
+ * non-monotonic defensive window all derive placement from this ONE sidecar
2658
+ * — never a semantic `turn` on the row, never a second dedicated map, and
2659
+ * never the reverse (an anchor is not ownership). */
2660
+ standalonePlacementTurns = /* @__PURE__ */ new WeakMap();
2597
2661
  /** Manual-compaction correlation legs (post-PR166 plan §7): bounded direct
2598
2662
  * lookups so `command/done.sourceEventSeq` and compaction
2599
2663
  * `sourceCommandId` never scan history. */
@@ -2771,6 +2835,7 @@ var TranscriptFolder = class TranscriptFolder {
2771
2835
  tools: /* @__PURE__ */ new Map(),
2772
2836
  thinkingTail: "",
2773
2837
  confirmedSteps: /* @__PURE__ */ new Set(),
2838
+ intermediateAssistantSteps: /* @__PURE__ */ new Set(),
2774
2839
  settledSteps: /* @__PURE__ */ new Set(),
2775
2840
  firstVisibleAssistantTimes: /* @__PURE__ */ new Map(),
2776
2841
  committedAnswerSteps: /* @__PURE__ */ new Set(),
@@ -3006,6 +3071,7 @@ var TranscriptFolder = class TranscriptFolder {
3006
3071
  activity.messageConfirmed = text === "" ? void 0 : text.slice(-TranscriptFolder.MESSAGE_TAIL_CAP);
3007
3072
  activity.messageConfirmedStep = candidate.step;
3008
3073
  activity.confirmedSteps.add(candidate.step);
3074
+ activity.intermediateAssistantSteps.add(candidate.step);
3009
3075
  activity.messageCandidate = void 0;
3010
3076
  }
3011
3077
  /** Commit the exact previous text-only answer once its next step admits a
@@ -3064,72 +3130,77 @@ var TranscriptFolder = class TranscriptFolder {
3064
3130
  this.turnValueSet.add(turn);
3065
3131
  }
3066
3132
  /** The FIRST REAL model turn (turn/start) adopts the leading standalone
3067
- * prefix (pre-turn commands): their anchors — 0 until now — re-anchor to
3068
- * the first turn value, so an anchored search window that contains the
3069
- * first turn reveals them (the raw prefix itself renders from index 0).
3070
- * Only turn/start adopts the prefix: a GHOST legacy turn (a pre-turn
3071
- * manual compaction registering the initial currentTurn) is not a real
3072
- * turn and must not consume it. */
3133
+ * prefix (pre-turn commands AND pre-turn standalone compactions): their
3134
+ * anchors — 0 until now — re-anchor to the first accepted turn value, so an
3135
+ * anchored search window that contains the first turn reveals them (the raw
3136
+ * prefix itself renders from index 0). Only a REAL turn/start adopts the
3137
+ * prefix. A fused representative is skipped: its command was already
3138
+ * re-anchored through the ONE hand-over path, so the command stays the only
3139
+ * independent anchor authority regardless of fusion order. */
3073
3140
  adoptLeadingAnchors(turn) {
3074
3141
  if (this.seenAcceptedTurnStart) return;
3075
3142
  this.seenAcceptedTurnStart = true;
3076
3143
  if (this.pendingAnchorEntries.length === 0) return;
3077
3144
  for (const index of this.pendingAnchorEntries) {
3078
3145
  const item = this.items[index];
3079
- if (item !== void 0 && item.kind === "command") this.setPlacementAnchor(item, index, turn);
3146
+ if (item === void 0) continue;
3147
+ if (item.kind === "compaction" && item.sourceCommand !== void 0) continue;
3148
+ if (item.kind === "command" || item.kind === "compaction") this.setPlacementAnchor(item, index, turn);
3080
3149
  }
3081
3150
  this.pendingAnchorEntries.length = 0;
3082
3151
  }
3083
- /** The PRESENTATION placement anchor of one turn-less standalone row: the
3084
- * turn currently open, else the latest known turn, else 0 while the log
3085
- * still has no turn (re-anchored by {@link appendTurnIndex}). This anchor
3086
- * drives window/search navigation ONLY — it is never stored on the row as
3087
- * a semantic `turn` (post-PR166 plan §8.1). */
3152
+ /** The PRESENTATION placement anchor of one standalone row: the turn
3153
+ * currently open, else the latest registered log-order turn, else 0 while
3154
+ * the log still has no turn (re-anchored by {@link adoptLeadingAnchors}).
3155
+ * This anchor drives window/search navigation ONLY — it is never stored on
3156
+ * the row as a semantic `turn`, and a numeric owner never consumes it. */
3088
3157
  placementAnchorTurn() {
3089
3158
  if (this.openTurn !== void 0) return this.openTurn;
3090
3159
  return this.turnValues.length > 0 ? this.turnValues[this.turnValues.length - 1] : 0;
3091
3160
  }
3092
- /** Write one command's placement anchor and hand it over to an already
3093
- * fused manual-compaction owner: the owner is the VISIBLE representative,
3094
- * so its sidecar and search entry must follow the same anchor. */
3161
+ /** Write one standalone row's placement anchor and hand a COMMAND's anchor
3162
+ * over to an already fused manual-compaction representative: the card is
3163
+ * the VISIBLE owner, so its sidecar and search entry follow the same
3164
+ * anchor. This is the ONE write path — the anchor is never inferred back
3165
+ * into semantic ownership. */
3095
3166
  setPlacementAnchor(message, index, turn) {
3096
- this.commandPlacementTurns.set(message, turn);
3167
+ this.standalonePlacementTurns.set(message, turn);
3097
3168
  const entry = this.searchEntries[index];
3098
3169
  if (entry !== void 0) entry.turn = turn;
3170
+ if (message.kind !== "command") return;
3099
3171
  const owner = this.compactionOwnerByCommandId.get(message.commandId);
3100
3172
  if (owner === void 0) return;
3101
3173
  const compaction = this.items[owner];
3102
3174
  if (compaction !== void 0 && compaction.kind === "compaction") {
3103
- this.manualCompactionPlacementTurns.set(compaction, turn);
3175
+ this.standalonePlacementTurns.set(compaction, turn);
3104
3176
  const ownerEntry = this.searchEntries[owner];
3105
3177
  if (ownerEntry !== void 0) ownerEntry.turn = turn;
3106
3178
  }
3107
3179
  }
3108
- /** The placement anchor of one turn-less standalone row from the shared
3109
- * authority sidecar (undefined for turn-owned rows): a plain command, or
3110
- * the COMBINED manual-compaction owner inheriting its fused command's
3111
- * anchor. */
3180
+ /** The placement anchor of one standalone row from the shared authority
3181
+ * sidecar (undefined for numeric-turn-owned rows): a plain command, a
3182
+ * compaction with no admitted numeric owner, or a fused representative
3183
+ * inheriting its command's anchor. Never semantic ownership. */
3112
3184
  placementAnchorOf(message) {
3113
- if (message.kind === "command") return this.commandPlacementTurns.get(message);
3114
- if (message.kind === "compaction" && message.sourceCommand !== void 0) return this.manualCompactionPlacementTurns.get(message);
3185
+ return this.standalonePlacementTurns.get(message);
3115
3186
  }
3116
3187
  /** Append one folded message, maintaining the window projections. Returns
3117
3188
  * the raw item index (the stable search identity). */
3118
3189
  appendItem(message) {
3119
3190
  this.items.push(message);
3120
3191
  const index = this.items.length - 1;
3192
+ if (message.kind === "command") setTranscriptTiming(message, pointTiming(message.time));
3121
3193
  const corpus = transcriptSearchCorpus(message);
3122
- const ownsTurn = "turn" in message;
3123
- const anchorTurn = ownsTurn ? message.turn : this.placementAnchorTurn();
3124
- if (!ownsTurn && message.kind === "command") this.commandPlacementTurns.set(message, anchorTurn);
3194
+ const turn = transcriptTurnOf(message);
3195
+ const anchorTurn = turn ?? this.placementAnchorTurn();
3125
3196
  this.searchEntries.push({
3126
3197
  turn: anchorTurn,
3127
3198
  normalizedText: corpus.normalizedText,
3128
3199
  spans: corpus.spans
3129
3200
  });
3130
- if (!ownsTurn && !this.seenAcceptedTurnStart) this.pendingAnchorEntries.push(index);
3201
+ if (turn === void 0 && (message.kind === "command" || message.kind === "compaction")) this.setPlacementAnchor(message, index, anchorTurn);
3202
+ if (turn === void 0 && !this.seenAcceptedTurnStart) this.pendingAnchorEntries.push(index);
3131
3203
  this.searchRevisionCounter += 1;
3132
- const turn = ownsTurn ? message.turn : void 0;
3133
3204
  if (turn !== void 0) {
3134
3205
  if (this.turnValues.length === 0) this.appendTurnIndex(turn);
3135
3206
  else if (this.turnsMonotonic) {
@@ -3184,7 +3255,8 @@ var TranscriptFolder = class TranscriptFolder {
3184
3255
  if (group !== void 0 && this.representativeOf(index) !== index) continue;
3185
3256
  const card = group ?? this.items[index];
3186
3257
  if (card === void 0) continue;
3187
- if ("turn" in card && !(card.kind === "compaction" && card.sourceCommand !== void 0)) entry.turn = card.turn;
3258
+ const cardTurn = transcriptTurnOf(card);
3259
+ if (cardTurn !== void 0 && !(card.kind === "compaction" && card.sourceCommand !== void 0)) entry.turn = cardTurn;
3188
3260
  const corpus = transcriptSearchCorpus(card);
3189
3261
  entry.normalizedText = corpus.normalizedText;
3190
3262
  entry.spans = corpus.spans;
@@ -3341,7 +3413,8 @@ var TranscriptFolder = class TranscriptFolder {
3341
3413
  continue;
3342
3414
  }
3343
3415
  const item = this.items[index];
3344
- if (item !== void 0 && "turn" in item && this.isVisible(item)) this.addGroupedTurn(item.turn);
3416
+ const turn = item === void 0 ? void 0 : transcriptTurnOf(item);
3417
+ if (item !== void 0 && turn !== void 0 && this.isVisible(item)) this.addGroupedTurn(turn);
3345
3418
  }
3346
3419
  this.groupedTurnIndexDirty = false;
3347
3420
  }
@@ -3528,7 +3601,8 @@ var TranscriptFolder = class TranscriptFolder {
3528
3601
  flush();
3529
3602
  runTurn = void 0;
3530
3603
  if (item.kind === "tool" && absoluteCounts) this.groupedToolCount += 1;
3531
- if ("turn" in item) this.addGroupedTurn(item.turn);
3604
+ const turn = transcriptTurnOf(item);
3605
+ if (turn !== void 0) this.addGroupedTurn(turn);
3532
3606
  }
3533
3607
  flush();
3534
3608
  }
@@ -3669,7 +3743,7 @@ var TranscriptFolder = class TranscriptFolder {
3669
3743
  /** The turn value of one raw row, when it carries one. */
3670
3744
  turnOfRaw(index) {
3671
3745
  const item = this.items[index];
3672
- return item !== void 0 && "turn" in item ? item.turn : void 0;
3746
+ return item === void 0 ? void 0 : transcriptTurnOf(item);
3673
3747
  }
3674
3748
  /** Re-group one LOCAL span from the display order: detach its existing groups,
3675
3749
  * then rebuild the runs over the final display order (bounded by the span). */
@@ -3921,7 +3995,7 @@ var TranscriptFolder = class TranscriptFolder {
3921
3995
  if (members === void 0) return false;
3922
3996
  const meta = this.groupMeta.get(previousGroup);
3923
3997
  const firstMember = this.items[members[0]];
3924
- const firstTurn = meta?.firstTurn ?? (firstMember !== void 0 && "turn" in firstMember ? firstMember.turn : previous.turn);
3998
+ const firstTurn = meta?.firstTurn ?? (firstMember === void 0 ? previous.turn : transcriptTurnOf(firstMember) ?? previous.turn);
3925
3999
  const wasCross = meta?.spansTurns ?? this.crossTurn(members);
3926
4000
  this.removeGroupedTurn(previousGroup.turn);
3927
4001
  this.removeGroupedTurn(item.turn);
@@ -3985,10 +4059,10 @@ var TranscriptFolder = class TranscriptFolder {
3985
4059
  crossTurn(members) {
3986
4060
  if (members.length <= 1) return false;
3987
4061
  const first = this.items[members[0]];
3988
- const turn = "turn" in first ? first.turn : void 0;
4062
+ const turn = transcriptTurnOf(first);
3989
4063
  for (let i = 1; i < members.length; i += 1) {
3990
4064
  const member = this.items[members[i]];
3991
- if (("turn" in member ? member.turn : void 0) !== turn) return true;
4065
+ if (transcriptTurnOf(member) !== turn) return true;
3992
4066
  }
3993
4067
  return false;
3994
4068
  }
@@ -4626,6 +4700,22 @@ var TranscriptFolder = class TranscriptFolder {
4626
4700
  isDeclaredToolCall(turn, step, callId) {
4627
4701
  return this.declaredToolCallsByStep.get(stepKey(turn, step))?.has(callId) === true;
4628
4702
  }
4703
+ /** Whether this step's durable evidence owns a same-step ACTUAL tool call
4704
+ * that the lane convergence places on the Assistant's FOLLOWING display side
4705
+ * (text-then-call). A cold fold can observe the call event BEFORE the
4706
+ * settlement; the existing lane relation is the display authority, and a
4707
+ * conformant raw row needs no relation. A call on the preceding side, a
4708
+ * requested-but-never-started call (no card) and an older-step call are not
4709
+ * continuation. */
4710
+ assistantStepHasFollowingActualCall(turn, step) {
4711
+ const declared = this.declaredToolCallsByStep.get(stepKey(turn, step));
4712
+ if (declared === void 0) return false;
4713
+ for (const callId of declared) {
4714
+ if (!this.toolCardIndexOf.has(toolCallKey(turn, step, callId))) continue;
4715
+ if (this.toolRowEvidence(turn, step, callId)?.position === "after") return true;
4716
+ }
4717
+ return false;
4718
+ }
4629
4719
  /** Whether a proven Tool row already sits on the physical side its evidence
4630
4720
  * asks for (so it keeps its own slot and needs no relation). */
4631
4721
  toolRowIsConformant(evidence, anchorIndex) {
@@ -5212,7 +5302,7 @@ var TranscriptFolder = class TranscriptFolder {
5212
5302
  if (anchor !== void 0) anchoredRows.set(message, anchor);
5213
5303
  else windowInput.push(message);
5214
5304
  }
5215
- const allTurns = [...new Set(windowInput.filter((message) => "turn" in message).map((message) => message.turn))].sort((a, b) => a - b);
5305
+ const allTurns = [...new Set(windowInput.map((message) => transcriptTurnOf(message)).filter((turn) => turn !== void 0))].sort((a, b) => a - b);
5216
5306
  const windowed = windowMessages(windowInput, maxTurns, options.endTurn);
5217
5307
  const sortedDesc = [...allTurns].sort((a, b) => b - a);
5218
5308
  const anchorIndex = options.endTurn === void 0 ? -1 : sortedDesc.indexOf(options.endTurn);
@@ -5229,7 +5319,10 @@ var TranscriptFolder = class TranscriptFolder {
5229
5319
  if (windowedBody.has(message)) messages.push(message);
5230
5320
  }
5231
5321
  const visibleSet = /* @__PURE__ */ new Set();
5232
- for (const message of messages) if ("turn" in message) visibleSet.add(message.turn);
5322
+ for (const message of messages) {
5323
+ const turn = transcriptTurnOf(message);
5324
+ if (turn !== void 0) visibleSet.add(turn);
5325
+ }
5233
5326
  const visibleTurnValues = [...visibleSet].sort((a, b) => a - b);
5234
5327
  const firstTurn = visibleTurnValues[0] ?? this.turnValues[range.start];
5235
5328
  const lastTurn = visibleTurnValues[visibleTurnValues.length - 1] ?? this.turnValues[range.end];
@@ -5257,7 +5350,7 @@ var TranscriptFolder = class TranscriptFolder {
5257
5350
  }
5258
5351
  if (leading.length > 0) projected.messages = [...leading, ...projected.messages];
5259
5352
  }
5260
- const visibleTurns = projected.messages.filter((message) => "turn" in message).map((message) => message.turn);
5353
+ const visibleTurns = projected.messages.map((message) => transcriptTurnOf(message)).filter((turn) => turn !== void 0);
5261
5354
  const firstTurn = visibleTurns[0] ?? this.turnValues[range.start];
5262
5355
  const lastTurn = visibleTurns[visibleTurns.length - 1] ?? this.turnValues[range.end];
5263
5356
  const facts = this.crossTurnGroups > 0 ? this.groupedTurnFacts(this.turnValues[range.start], this.turnValues[range.end]) : void 0;
@@ -5548,17 +5641,19 @@ var TranscriptFolder = class TranscriptFolder {
5548
5641
  const compactionId = typeof data.compactionId === "string" ? data.compactionId : void 0;
5549
5642
  let index = compactionId === void 0 ? void 0 : this.compacting.get(compactionId);
5550
5643
  if (index === void 0) {
5644
+ const ownerTurn = kind === "compaction/start" || kind === "compaction/end" ? compactionOwnerTurnOf(data.turn) : void 0;
5551
5645
  const created = {
5552
5646
  kind: "compaction",
5553
- turn: this.currentTurn,
5554
5647
  text: "",
5555
5648
  items: 0,
5556
5649
  tokens: 0,
5557
- running: true
5650
+ running: true,
5651
+ ...ownerTurn === void 0 ? {} : { turn: ownerTurn }
5558
5652
  };
5559
5653
  this.appendItem(created);
5560
5654
  index = this.items.length - 1;
5561
5655
  setTranscriptTiming(created, pointTiming(event.time));
5656
+ if (ownerTurn !== void 0 && this.activityByTurn.get(ownerTurn)?.completed === true) markPostTurnReplayEvidence(created);
5562
5657
  if (compactionId !== void 0) this.compacting.set(compactionId, index);
5563
5658
  }
5564
5659
  const entry = this.items[index];
@@ -5641,15 +5736,12 @@ var TranscriptFolder = class TranscriptFolder {
5641
5736
  compaction.sourceCommand = message;
5642
5737
  this.fusedCommands.add(message);
5643
5738
  this.compactionOwnerByCommandId.set(message.commandId, target);
5644
- const anchor = this.commandPlacementTurns.get(message);
5739
+ const compactionPoint = transcriptTimingOf(compaction)?.startedAt;
5740
+ const commandPoint = transcriptTimingOf(message)?.startedAt;
5741
+ const earliestPoint = compactionPoint === void 0 ? commandPoint : commandPoint === void 0 ? compactionPoint : Math.min(compactionPoint, commandPoint);
5742
+ if (earliestPoint !== void 0) setTranscriptTiming(compaction, pointTiming(earliestPoint));
5743
+ const anchor = this.placementAnchorOf(message);
5645
5744
  if (anchor !== void 0) this.setPlacementAnchor(message, index, anchor);
5646
- const ghostIndex = this.turnValues.indexOf(compaction.turn);
5647
- if (ghostIndex >= 0 && this.turnStarts[ghostIndex] === target && this.activityByTurn.get(compaction.turn)?.startedAt === void 0 && (ghostIndex + 1 >= this.turnStarts.length || this.turnStarts[ghostIndex + 1] === target + 1)) {
5648
- this.turnValues.splice(ghostIndex, 1);
5649
- this.turnStarts.splice(ghostIndex, 1);
5650
- this.turnValueSet.delete(compaction.turn);
5651
- this.removeGroupedTurn(compaction.turn);
5652
- }
5653
5745
  this.markSearchEntryDirty(target);
5654
5746
  this.markSearchEntryDirty(index);
5655
5747
  }
@@ -5721,15 +5813,25 @@ var TranscriptFolder = class TranscriptFolder {
5721
5813
  }
5722
5814
  if (kind === "agent/inbox/spliced") {
5723
5815
  const data = event.data;
5724
- const inserted = data.inserted.map((message) => ({
5816
+ const insertedSource = data.inserted;
5817
+ const inserted = Array.isArray(insertedSource) ? insertedSource.map((message) => ({
5725
5818
  id: message.id,
5726
5819
  insertionTurn: this.openTurn,
5727
5820
  insertionTime: event.time
5728
- }));
5729
- let removed = [];
5730
- if (data.target === "next-step") removed = this.pendingNextSteps.splice(data.start, data.removedCount ?? 0, ...inserted);
5731
- for (const { id } of inserted) this.claimedNextStepTurns.delete(id);
5732
- if (data.target === "next-step" && data.outcome !== "canceled") for (const identity of removed) this.claimedNextStepTurns.set(identity.id, identity);
5821
+ })) : [];
5822
+ const validInserted = Array.isArray(insertedSource) && inserted.every((identity) => typeof identity.id === "string" && identity.id !== "");
5823
+ if (validInserted) for (const { id } of inserted) this.claimedNextStepTurns.delete(id);
5824
+ if (data.target !== "next-step") return;
5825
+ const removedCount = data.removedCount ?? 0;
5826
+ if (!(validInserted && Number.isSafeInteger(data.start) && data.start >= 0 && Number.isSafeInteger(removedCount) && removedCount >= 0 && data.start <= this.pendingNextSteps.length && data.start + removedCount <= this.pendingNextSteps.length)) {
5827
+ this.pendingNextSteps.length = 0;
5828
+ this.claimedNextStepTurns.clear();
5829
+ return;
5830
+ }
5831
+ const priorObservedLength = this.pendingNextSteps.length;
5832
+ const removed = this.pendingNextSteps.splice(data.start, removedCount, ...inserted);
5833
+ if (!(data.start === 0 && removedCount > 0 && removedCount === priorObservedLength && inserted.length === 0 && data.outcome === void 0)) return;
5834
+ for (const identity of removed) if (identity.insertionTurn !== void 0 && identity.insertionTurn === this.openTurn) this.claimedNextStepTurns.set(identity.id, identity);
5733
5835
  return;
5734
5836
  }
5735
5837
  if (kind === "compaction/start" || kind === "compaction/summary" || kind === "compaction/end" || kind === "session/end-seed") {
@@ -5785,6 +5887,11 @@ var TranscriptFolder = class TranscriptFolder {
5785
5887
  }
5786
5888
  }
5787
5889
  this.usage.onStepStart(event.data.turn, event.data.step);
5890
+ const latestSettled = activity.lastAssistantStep;
5891
+ if (latestSettled !== void 0 && event.data.step > latestSettled && activity.settledSteps.has(latestSettled) && !activity.intermediateAssistantSteps.has(latestSettled)) {
5892
+ activity.intermediateAssistantSteps.add(latestSettled);
5893
+ activity.revision += 1;
5894
+ }
5788
5895
  const candidate = activity.messageCandidate;
5789
5896
  if (candidate !== void 0 && candidate.step < event.data.step) {
5790
5897
  this.confirmMessageCandidate(activity);
@@ -5796,6 +5903,9 @@ var TranscriptFolder = class TranscriptFolder {
5796
5903
  case "step/end": {
5797
5904
  const activity = this.activityFor(event.data.turn);
5798
5905
  if (activity.completed) break;
5906
+ if (event.data.turn === this.openTurn) {
5907
+ for (const identity of this.claimedNextStepTurns.values()) if (identity.insertionTurn === this.openTurn) this.claimedNextStepTurns.delete(identity.id);
5908
+ }
5799
5909
  this.markAttemptEvidenceInterrupted(event.data.turn, event.data.step);
5800
5910
  this.clearPreparingStartsForStep(event.data.turn, event.data.step);
5801
5911
  this.usage.onStepEnd(event.data.turn, event.data.step);
@@ -5811,18 +5921,22 @@ var TranscriptFolder = class TranscriptFolder {
5811
5921
  this.adoptLeadingAnchors(event.data.turn);
5812
5922
  activity.completed = false;
5813
5923
  activity.reason = void 0;
5814
- if (event.data.turn === this.currentTurn) this.openTurn = event.data.turn;
5924
+ if (event.data.turn === this.currentTurn) {
5925
+ for (const identity of this.claimedNextStepTurns.values()) if (identity.insertionTurn !== event.data.turn) this.claimedNextStepTurns.delete(identity.id);
5926
+ this.openTurn = event.data.turn;
5927
+ }
5815
5928
  activity.revision += 1;
5816
5929
  break;
5817
5930
  }
5818
5931
  case "user/message": {
5819
5932
  const claimedIdentity = this.claimedNextStepTurns.get(event.data.id);
5820
- const wasClaimedFromNextStep = this.claimedNextStepTurns.delete(event.data.id);
5821
- const isMidTurnSteer = wasClaimedFromNextStep && claimedIdentity !== void 0 && claimedIdentity.insertionTurn === this.currentTurn;
5933
+ this.claimedNextStepTurns.delete(event.data.id);
5934
+ const openTurn = this.openTurn;
5935
+ const deliveredThisTurn = claimedIdentity !== void 0 && openTurn !== void 0 && claimedIdentity.insertionTurn === openTurn && this.currentTurn === openTurn;
5936
+ const isMidTurnSteer = deliveredThisTurn;
5822
5937
  const blocks = event.data.content;
5823
5938
  const text = textWithAttachmentMarkers(blocks);
5824
5939
  const sourcePresentation = contextPresentation(event.data.source);
5825
- const sameTurnNextStepDelivery = wasClaimedFromNextStep === true && claimedIdentity !== void 0 && claimedIdentity.insertionTurn === this.currentTurn && (sourcePresentation.sourceKind === "tool-jobs" && sourcePresentation.form === "notice" || sourcePresentation.sourceKind === "agent-message" && sourcePresentation.form === "relay" || sourcePresentation.sourceKind === "subagent-settled" && sourcePresentation.form === "notice");
5826
5940
  if (sourcePresentation.sourceKind === "user") {
5827
5941
  if (!userBlocksVisibleNow(blocks)) break;
5828
5942
  const activity = this.activityFor(this.currentTurn);
@@ -5852,7 +5966,8 @@ var TranscriptFolder = class TranscriptFolder {
5852
5966
  ...summary === null ? {} : { summary },
5853
5967
  icon: contextIconSemantic(event.data.source),
5854
5968
  context: true,
5855
- contextPresentation: sameTurnNextStepDelivery ? {
5969
+ ...sourcePresentation.sourceKind === "ptc-mode" && blocks.some((block) => block.type === "image") ? { content: blocks } : {},
5970
+ contextPresentation: deliveredThisTurn ? {
5856
5971
  ...sourcePresentation,
5857
5972
  sameTurnNextStep: true
5858
5973
  } : sourcePresentation
@@ -5923,8 +6038,10 @@ var TranscriptFolder = class TranscriptFolder {
5923
6038
  if (!alreadySettled) activity.assistantMessages += 1;
5924
6039
  activity.settledSteps.add(event.data.step);
5925
6040
  const staleForFocus = event.data.step < priorLast;
6041
+ if (!staleForFocus && this.assistantStepHasFollowingActualCall(event.data.turn, event.data.step)) activity.intermediateAssistantSteps.add(event.data.step);
5926
6042
  if (!staleForFocus) activity.lastAssistantVisible = event.data.interrupted === true || assistantBlocksVisibleNow(messageBlocks);
5927
6043
  activity.lastAssistantStep = Math.max(priorLast, event.data.step);
6044
+ if (priorLast !== void 0 && event.data.step > priorLast && activity.settledSteps.has(priorLast) && !activity.intermediateAssistantSteps.has(priorLast)) activity.intermediateAssistantSteps.add(priorLast);
5928
6045
  if (staleForFocus) {
5929
6046
  if (activity.messageConfirmedStep === event.data.step) activity.messageConfirmed = text === "" ? void 0 : text.slice(-TranscriptFolder.MESSAGE_TAIL_CAP);
5930
6047
  } else {
@@ -5993,7 +6110,15 @@ var TranscriptFolder = class TranscriptFolder {
5993
6110
  status: "running"
5994
6111
  };
5995
6112
  }
5996
- this.confirmMessageCandidate(activity);
6113
+ const provenPrecedingSameStepCall = (step) => event.data.step === step && this.toolRowEvidence(callTurn, event.data.step, key)?.position === "before";
6114
+ const candidate = activity.messageCandidate;
6115
+ if (candidate !== void 0) {
6116
+ if (event.data.step > candidate.step || event.data.step === candidate.step && !provenPrecedingSameStepCall(candidate.step)) this.confirmMessageCandidate(activity);
6117
+ } else {
6118
+ const latest = activity.lastAssistantStep;
6119
+ if (latest !== void 0 && event.data.step > latest && activity.settledSteps.has(latest) && !activity.intermediateAssistantSteps.has(latest)) activity.intermediateAssistantSteps.add(latest);
6120
+ else if (latest !== void 0 && event.data.step === latest && activity.settledSteps.has(latest) && !provenPrecedingSameStepCall(latest) && !activity.intermediateAssistantSteps.has(latest)) activity.intermediateAssistantSteps.add(latest);
6121
+ }
5997
6122
  this.syncMessage(activity);
5998
6123
  activity.revision += 1;
5999
6124
  }
@@ -6111,6 +6236,7 @@ var TranscriptFolder = class TranscriptFolder {
6111
6236
  case "turn/end": {
6112
6237
  const endTurn = event.data.turn;
6113
6238
  if (this.openTurn === endTurn) this.openTurn = void 0;
6239
+ for (const identity of this.claimedNextStepTurns.values()) if (identity.insertionTurn === endTurn) this.claimedNextStepTurns.delete(identity.id);
6114
6240
  const endActivity = this.activityFor(endTurn);
6115
6241
  endActivity.pendingPreSteerAnswerStep = void 0;
6116
6242
  if (endActivity.completed) break;
@@ -6260,6 +6386,14 @@ var TranscriptFolder = class TranscriptFolder {
6260
6386
  }
6261
6387
  }
6262
6388
  };
6389
+ /** The official compaction lifecycle's admitted model-turn owner: a safe
6390
+ * non-negative integer from `compaction/start` or an end-only `compaction/end`.
6391
+ * The official `null` (standalone maintenance) and every missing/invalid value
6392
+ * admit NO numeric owner — never fall back to the fold's current/open turn.
6393
+ * Zero is a legal owner; this is a numeric test, never truthiness. */
6394
+ function compactionOwnerTurnOf(turn) {
6395
+ return typeof turn === "number" && Number.isSafeInteger(turn) && turn >= 0 ? turn : void 0;
6396
+ }
6263
6397
  /** Validate and retain the official `command/done` outcome (post-PR166 plan
6264
6398
  * §6): only a SUCCESS may carry the `sourceEventSeq` relationship, and the
6265
6399
  * sequence must be a safe non-negative integer — anything malformed is
@@ -7479,6 +7613,50 @@ function joinRelativeScope(cwd, rawPath, windowsDialect, windowsHost) {
7479
7613
  function isBareScopeForm(raw) {
7480
7614
  return raw === "" || raw === "." || raw === ".." || raw === "./" || raw === "../" || raw === "~" || raw === "~/" || raw === "~\\" || raw === "/" || raw === ".\\" || raw === "..\\";
7481
7615
  }
7616
+ /** Whether a raw token names an unambiguous local Windows NTFS path.
7617
+ * Drive-relative (`C:foo`), PowerShell provider/PSDrive-qualified (`HKLM:`,
7618
+ * `Env:`) and UNC/network (`\\\\server\\share`) spellings are not the promised
7619
+ * local path shape and are refused by the Windows literal-path completion
7620
+ * route rather than guessed. A normal drive-absolute (`C:\\x`), rooted/relative
7621
+ * (`\\x`, `sub\\x`, `.\\x`) or home token is admitted. */
7622
+ const WINDOWS_UNC_PREFIX = /^[\\/]{2}/u;
7623
+ const WINDOWS_DRIVE_RELATIVE = /^[A-Za-z]:(?![/\\])/u;
7624
+ const WINDOWS_PROVIDER_PATH = /^[A-Za-z][A-Za-z0-9_-]+:/u;
7625
+ function unsupportedWindowsPathToken(raw) {
7626
+ if (raw === "") return false;
7627
+ if (WINDOWS_UNC_PREFIX.test(raw)) return true;
7628
+ if (WINDOWS_DRIVE_RELATIVE.test(raw)) return true;
7629
+ return WINDOWS_PROVIDER_PATH.test(raw);
7630
+ }
7631
+ /**
7632
+ * Turn one Windows Host literal token into the token the path query resolves.
7633
+ * Only the promised local NTFS shapes reach the query; an unambiguous
7634
+ * drive-relative (`C:foo`), PowerShell provider/PSDrive-qualified (`HKLM:`,
7635
+ * `Env:`) or UNC/network spelling is a truthful unavailable. An UNQUOTED home
7636
+ * token (`~`, `~/x`, `~\x`) is expanded against the injected home directory and
7637
+ * returned ABSOLUTE, so accepting it as a PowerShell single-quoted literal
7638
+ * cannot change the expansion. A quoted `~` never reaches this function as a
7639
+ * home token (the Client sends the literal `./~...` form instead).
7640
+ * PURE: both the home directory and the host platform are explicit facts.
7641
+ * @param raw - the raw token as typed (quotes already handled by the caller).
7642
+ * @param homeDir - the locality owner's home directory fact.
7643
+ */
7644
+ function resolveWindowsHostPrefix(raw, homeDir) {
7645
+ if (unsupportedWindowsPathToken(raw)) return {
7646
+ kind: "unavailable",
7647
+ reason: "the Windows path form is not an unambiguous local NTFS path (drive-relative, provider or UNC spellings are not supported)"
7648
+ };
7649
+ if (raw !== "~" && !raw.startsWith("~/") && !raw.startsWith("~\\")) return {
7650
+ kind: "ok",
7651
+ prefix: raw
7652
+ };
7653
+ const tail = raw === "~" ? "" : raw.slice(2);
7654
+ const joined = tail === "" ? homeDir : win32.join(homeDir, tail);
7655
+ return {
7656
+ kind: "ok",
7657
+ prefix: raw === "~" || tail === "" || tail.endsWith("/") || tail.endsWith("\\") ? `${joined.replace(/[\\/]+$/u, "")}\\` : joined
7658
+ };
7659
+ }
7482
7660
  /**
7483
7661
  * Resolve ONE raw completion token into the pure path query.
7484
7662
  * @param raw - the token as typed (quotes stripped; leading separator
@@ -8207,193 +8385,6 @@ async function suggestPathArgument(argumentText, cwd, localFdPath = void 0) {
8207
8385
  * AND get the matching `getArgumentCompletions` wiring. */
8208
8386
  const FILE_ARGUMENT_COMMANDS = /* @__PURE__ */ new Set(["attach", "image"]);
8209
8387
  //#endregion
8210
- //#region src/tui/theme/runtime.ts
8211
- /**
8212
- * The live terminal palette + ANSI/TUI theme objects (TS8-E): the ONE owner
8213
- * of the mutable current palette and of the chalk-backed style helpers,
8214
- * searchable-picker/settings-list/editor/markdown themes and the host
8215
- * markdown options. Every TUI renderer and every terminal-rendering
8216
- * extension adapter (`extension/internal/component-compiler.ts`,
8217
- * `slot-outlet.ts`) consumes this owner; the neutral palette vocabulary and
8218
- * built-in palettes live in `domain/display/theme.ts`.
8219
- * @module @xmoon76/dsh-pi-tui/tui/theme/runtime
8220
- */
8221
- /** The active palette; style helpers read it on every call, so swapping is live. */
8222
- let currentPalette = darkColors;
8223
- /**
8224
- * Switch the active palette; callers must invalidate rendered components.
8225
- * `custom` uses the full palette in `customPalette`, or falls back to dark.
8226
- * @param theme - the palette family.
8227
- * @param custom - the resolved custom palette when `theme` is `custom`.
8228
- */
8229
- function setTheme(theme, custom) {
8230
- if (theme === "custom" && custom !== void 0) currentPalette = withSearchCurrentTokens(custom);
8231
- else currentPalette = theme === "light" ? lightColors : darkColors;
8232
- }
8233
- const chalk = new Chalk({ level: 3 });
8234
- const hex = (token) => chalk.hex(currentPalette[token] ?? currentPalette.text);
8235
- /** Paint text with an explicit hex colour. Brand assets (the welcome whale
8236
- * gradient) use a fixed ramp that is NOT a semantic token: it must not
8237
- * follow the active palette, and custom themes do not override it. */
8238
- const hexPaint = (hexValue, text) => chalk.hex(hexValue)(text);
8239
- /** Style helpers by token name. The strong/dim/italic helpers accept an
8240
- * optional TONE OVERRIDE (the footer layout's semantic tone override):
8241
- * the override replaces the token, the style stays. */
8242
- const color = {
8243
- primary: (text) => hex("primary")(text),
8244
- accent: (text) => hex("accent")(text),
8245
- text: (text) => hex("text")(text),
8246
- textStrong: (text, tone) => chalk.bold.hex(currentPalette[tone ?? "textStrong"] ?? currentPalette.textStrong)(text),
8247
- textDim: (text, tone) => hex(tone ?? "textDim")(text),
8248
- textMuted: (text) => hex("textMuted")(text),
8249
- border: (text) => hex("border")(text),
8250
- borderFocus: (text) => hex("borderFocus")(text),
8251
- success: (text) => hex("success")(text),
8252
- warning: (text) => hex("warning")(text),
8253
- error: (text) => hex("error")(text),
8254
- diffAdded: (text) => hex("diffAdded")(text),
8255
- diffRemoved: (text) => hex("diffRemoved")(text),
8256
- diffAddedStrong: (text) => chalk.bold.hex(currentPalette.diffAddedStrong)(text),
8257
- diffRemovedStrong: (text) => chalk.bold.hex(currentPalette.diffRemovedStrong)(text),
8258
- diffGutter: (text) => hex("diffGutter")(text),
8259
- diffMeta: (text) => hex("diffMeta")(text),
8260
- roleUser: (text) => hex("roleUser")(text),
8261
- /** User-bubble background paint (dsh-web `--dsw-specific-bubble`
8262
- * parity): the whole user row reads as a floating block. The token is
8263
- * optional — an absent `roleUserBg` makes this an identity function. */
8264
- roleUserBg: (text) => currentPalette.roleUserBg === void 0 ? text : chalk.bgHex(currentPalette.roleUserBg)(text),
8265
- shellMode: (text) => hex("shellMode")(text),
8266
- /** Ordinary visible transcript-search occurrence: explicit themed ink on a
8267
- * yellow block, separate from the current occurrence. */
8268
- searchMatch: (text) => chalk.hex(currentPalette.searchMatchFg ?? currentPalette.text).bgHex(currentPalette.searchMatchBg ?? currentPalette.warning)(text),
8269
- /** The current card's REAL visible title/anchor when the exact source cells
8270
- * cannot be proven. Same orange role as the current block but deliberately not
8271
- * bold: the bold current style is reserved for a Full source-proven cell or
8272
- * View's current mounted rendered occurrence. */
8273
- searchCardAnchor: (text) => chalk.hex(currentPalette.searchCurrentFg ?? currentPalette.textStrong).bgHex(currentPalette.searchCurrentBg ?? currentPalette.primary)(text),
8274
- /** The current search occurrence (Full source-proven, or View's current
8275
- * mounted rendered occurrence): bold with an explicit themed
8276
- * foreground AND background. NEVER the terminal's inverse attribute — a
8277
- * palette that omits the tokens has them filled at apply time
8278
- * ({@link withSearchCurrentTokens}), and this helper's own derivation stays
8279
- * inside the palette. */
8280
- searchCurrent: (text) => chalk.bold.hex(currentPalette.searchCurrentFg ?? currentPalette.textStrong).bgHex(currentPalette.searchCurrentBg ?? currentPalette.primary)(text),
8281
- /** The LEGACY anchor-only ROW wash used when no visible card-anchor geometry
8282
- * (header or first visible non-image text row) is available: it marks only the
8283
- * owning row, never a proven occurrence, and ordinary query words on that row
8284
- * keep their yellow block. A card with visible anchor geometry uses
8285
- * {@link searchCardAnchor} instead. */
8286
- searchAnchorBg: (text) => chalk.bgHex(currentPalette.searchAnchorBg ?? currentPalette.border)(text),
8287
- /** Plain italics (kimi thinking parity); an optional tone override
8288
- * colors the italic run. */
8289
- italic: (text, tone) => tone === void 0 ? chalk.italic(text) : chalk.italic.hex(currentPalette[tone] ?? currentPalette.text)(text),
8290
- /** Dim + italic for reasoning: intermediate thinking never reads like output. */
8291
- textDimItalic: (text) => chalk.italic.hex(currentPalette.textDim)(text)
8292
- };
8293
- /** SearchablePicker palette from the semantic tokens (a structural
8294
- * superset of the upstream SelectListTheme, so it still satisfies the
8295
- * Editor's autocomplete theme slot). */
8296
- const selectListTheme = {
8297
- selectedPrefix: (text) => color.primary(text),
8298
- selectedText: (text) => chalk.bold.hex(currentPalette.textStrong)(text),
8299
- description: (text) => color.textDim(text),
8300
- scrollInfo: (text) => color.textMuted(text),
8301
- noMatch: (text) => color.textMuted(text),
8302
- groupHeader: (text) => color.textDim(text)
8303
- };
8304
- /**
8305
- * The readable half of a task/job state: the Title Case status WORD that
8306
- * carries the shared `‣` marker (design language `docs/architecture/design-language.md`
8307
- * §3.2 role 9 — colour is never the only signal, §3.3.3). The word is paired
8308
- * with {@link taskStatusColor}'s token; the two must stay one vocabulary, so
8309
- * this map lives beside the colour map (`docs/architecture/design-language.md` §10) and
8310
- * is never forked.
8311
- *
8312
- * A status the map does not name is Title-cased verbatim: the surface may not
8313
- * rename a real state it does not know, and a future wire status must still
8314
- * paint a readable word.
8315
- */
8316
- function taskStatusWord(status) {
8317
- switch (status) {
8318
- case "running": return "Running";
8319
- case "stopping": return "Stopping";
8320
- case "completed": return "Completed";
8321
- case "failed": return "Failed";
8322
- case "killed": return "Killed";
8323
- case "timed_out": return "Timed out";
8324
- case "lost": return "Lost";
8325
- case "inactive": return "Inactive";
8326
- case "awaiting answer": return "Awaiting answer";
8327
- default: return status.charAt(0).toUpperCase() + status.slice(1);
8328
- }
8329
- }
8330
- /**
8331
- * Status-dot colour for a job status (dsh-web StateDot parity:
8332
- * running = ongoing/primary, stopping/killed = warning, completed = done/dim,
8333
- * failed/timed-out/lost = error). Unknown statuses fall back to the
8334
- * muted token so a future wire status never crashes the renderer.
8335
- */
8336
- function taskStatusColor(status) {
8337
- switch (status) {
8338
- case "running": return color.primary;
8339
- case "stopping": return color.warning;
8340
- case "completed": return color.textDim;
8341
- case "failed":
8342
- case "killed": return color.warning;
8343
- case "timed_out":
8344
- case "lost": return color.error;
8345
- default: return color.textMuted;
8346
- }
8347
- }
8348
- /**
8349
- * SettingsList palette from the semantic tokens. A FUNCTION, not a
8350
- * module-level constant: `cursor` is a pre-rendered ANSI string, so a
8351
- * constant would freeze the cursor colour at module load and never follow
8352
- * a live theme switch. Call it fresh for every overlay/settings open.
8353
- */
8354
- function settingsListTheme() {
8355
- return {
8356
- label: (text, selected) => selected ? chalk.bold.hex(currentPalette.textStrong)(text) : color.text(text),
8357
- value: (text, selected) => selected ? color.primary(text) : color.textDim(text),
8358
- description: (text) => color.textDim(text),
8359
- cursor: color.primary("> "),
8360
- hint: (text) => color.textMuted(text)
8361
- };
8362
- }
8363
- /** Editor palette: focused border uses the brand token. */
8364
- const editorTheme = {
8365
- borderColor: (text) => color.border(text),
8366
- selectList: selectListTheme
8367
- };
8368
- /**
8369
- * Markdown rendering options shared by EVERY host transcript renderer
8370
- * (assistant cards, thinking blocks, plugin component compilation).
8371
- * LaTeX-to-Unicode rendering is deliberately OFF (the kimi-host parity
8372
- * choice): the Earendil 0.84.4 re-vendor introduced `renderLatex`
8373
- * defaulting to true, which silently changed how `$...$`/`$$...$$`
8374
- * segments in assistant output render. Keep the pre-re-vendor rendering;
8375
- * revisit as an explicit setting if LaTeX output ever becomes a product
8376
- * requirement.
8377
- */
8378
- const HOST_MARKDOWN_OPTIONS = { renderLatex: false };
8379
- /** Markdown palette for assistant messages. */
8380
- const markdownTheme = {
8381
- heading: (text) => chalk.bold.hex(currentPalette.textStrong)(text),
8382
- link: (text) => color.primary(text),
8383
- linkUrl: (text) => color.textMuted(text),
8384
- code: (text) => color.primary(text),
8385
- codeBlock: (text) => text,
8386
- codeBlockBorder: (text) => color.textMuted(text),
8387
- quote: (text) => color.textDim(text),
8388
- quoteBorder: (text) => color.textDim(text),
8389
- hr: (text) => color.border(text),
8390
- listBullet: (text) => color.text(text.replace(/^-/, "•")),
8391
- bold: (text) => chalk.bold(text),
8392
- italic: (text) => chalk.italic(text),
8393
- strikethrough: (text) => chalk.strikethrough(text),
8394
- underline: (text) => chalk.underline(text)
8395
- };
8396
- //#endregion
8397
8388
  //#region src/tui/presentation/terminal-text.ts
8398
8389
  /**
8399
8390
  * Untrusted-text projections for terminal-bound presentation.
@@ -8711,27 +8702,214 @@ function sanitizedPhysicalLine(text) {
8711
8702
  return sanitizeDisplayText(text).replace(/[\t\r\n]+/g, " ");
8712
8703
  }
8713
8704
  //#endregion
8714
- //#region src/tui/pickers/model-directory.ts
8715
- const IDENTITY_SEP = "\0";
8716
- const PROVIDER_DEFAULT = `${IDENTITY_SEP}provider-default`;
8717
- /** Full logical identity of a model row. Model ids are not globally unique. */
8718
- function modelIdentity(providerId, modelId) {
8719
- return `${providerId}${IDENTITY_SEP}${modelId}`;
8720
- }
8705
+ //#region src/tui/theme/runtime.ts
8721
8706
  /**
8722
- * Project the Host directory into identity-complete presentation rows. Pure:
8723
- * no terminal/component state, so the current/default/effort rules are unit
8724
- * testable without a rendering snapshot.
8707
+ * The live terminal palette + ANSI/TUI theme objects (TS8-E): the ONE owner
8708
+ * of the mutable current palette and of the chalk-backed style helpers,
8709
+ * searchable-picker/settings-list/editor/markdown themes and the host
8710
+ * markdown options. Every TUI renderer and every terminal-rendering
8711
+ * extension adapter (`extension/internal/component-compiler.ts`,
8712
+ * `slot-outlet.ts`) consumes this owner; the neutral palette vocabulary and
8713
+ * built-in palettes live in `domain/display/theme.ts`.
8714
+ * @module @xmoon76/dsh-pi-tui/tui/theme/runtime
8725
8715
  */
8726
- function projectModelDirectory(directory, current, sessionless) {
8727
- const models = [];
8728
- for (const group of directory.groups) for (const model of group.models) {
8729
- const matchesConfigured = current !== void 0 && current.provider === group.id && current.model === model.id;
8730
- const isCurrentModel = !sessionless && matchesConfigured;
8731
- const isDefault = directory.default.provider === group.id && directory.default.model === model.id;
8732
- models.push({
8733
- providerId: group.id,
8734
- providerName: group.name,
8716
+ /** The active palette; style helpers read it on every call, so swapping is live. */
8717
+ let currentPalette = darkColors;
8718
+ /**
8719
+ * Switch the active palette; callers must invalidate rendered components.
8720
+ * `custom` uses the full palette in `customPalette`, or falls back to dark.
8721
+ * @param theme - the palette family.
8722
+ * @param custom - the resolved custom palette when `theme` is `custom`.
8723
+ */
8724
+ function setTheme(theme, custom) {
8725
+ if (theme === "custom" && custom !== void 0) currentPalette = withSearchCurrentTokens(custom);
8726
+ else currentPalette = theme === "light" ? lightColors : darkColors;
8727
+ }
8728
+ const chalk = new Chalk({ level: 3 });
8729
+ const hex = (token) => chalk.hex(currentPalette[token] ?? currentPalette.text);
8730
+ /** Paint text with an explicit hex colour. Brand assets (the welcome whale
8731
+ * gradient) use a fixed ramp that is NOT a semantic token: it must not
8732
+ * follow the active palette, and custom themes do not override it. */
8733
+ const hexPaint = (hexValue, text) => chalk.hex(hexValue)(text);
8734
+ /** Style helpers by token name. The strong/dim/italic helpers accept an
8735
+ * optional TONE OVERRIDE (the footer layout's semantic tone override):
8736
+ * the override replaces the token, the style stays. */
8737
+ const color = {
8738
+ primary: (text) => hex("primary")(text),
8739
+ accent: (text) => hex("accent")(text),
8740
+ text: (text) => hex("text")(text),
8741
+ textStrong: (text, tone) => chalk.bold.hex(currentPalette[tone ?? "textStrong"] ?? currentPalette.textStrong)(text),
8742
+ textDim: (text, tone) => hex(tone ?? "textDim")(text),
8743
+ textMuted: (text) => hex("textMuted")(text),
8744
+ border: (text) => hex("border")(text),
8745
+ borderFocus: (text) => hex("borderFocus")(text),
8746
+ success: (text) => hex("success")(text),
8747
+ warning: (text) => hex("warning")(text),
8748
+ error: (text) => hex("error")(text),
8749
+ diffAdded: (text) => hex("diffAdded")(text),
8750
+ diffRemoved: (text) => hex("diffRemoved")(text),
8751
+ diffAddedStrong: (text) => chalk.bold.hex(currentPalette.diffAddedStrong)(text),
8752
+ diffRemovedStrong: (text) => chalk.bold.hex(currentPalette.diffRemovedStrong)(text),
8753
+ diffGutter: (text) => hex("diffGutter")(text),
8754
+ diffMeta: (text) => hex("diffMeta")(text),
8755
+ roleUser: (text) => hex("roleUser")(text),
8756
+ /** User-bubble background paint (dsh-web `--dsw-specific-bubble`
8757
+ * parity): the whole user row reads as a floating block. The token is
8758
+ * optional — an absent `roleUserBg` makes this an identity function. */
8759
+ roleUserBg: (text) => currentPalette.roleUserBg === void 0 ? text : chalk.bgHex(currentPalette.roleUserBg)(text),
8760
+ shellMode: (text) => hex("shellMode")(text),
8761
+ /** Ordinary visible transcript-search occurrence: explicit themed ink on a
8762
+ * yellow block, separate from the current occurrence. */
8763
+ searchMatch: (text) => chalk.hex(currentPalette.searchMatchFg ?? currentPalette.text).bgHex(currentPalette.searchMatchBg ?? currentPalette.warning)(text),
8764
+ /** The current card's REAL visible title/anchor when the exact source cells
8765
+ * cannot be proven. Same orange role as the current block but deliberately not
8766
+ * bold: the bold current style is reserved for a Full source-proven cell or
8767
+ * View's current mounted rendered occurrence. */
8768
+ searchCardAnchor: (text) => chalk.hex(currentPalette.searchCurrentFg ?? currentPalette.textStrong).bgHex(currentPalette.searchCurrentBg ?? currentPalette.primary)(text),
8769
+ /** The current search occurrence (Full source-proven, or View's current
8770
+ * mounted rendered occurrence): bold with an explicit themed
8771
+ * foreground AND background. NEVER the terminal's inverse attribute — a
8772
+ * palette that omits the tokens has them filled at apply time
8773
+ * ({@link withSearchCurrentTokens}), and this helper's own derivation stays
8774
+ * inside the palette. */
8775
+ searchCurrent: (text) => chalk.bold.hex(currentPalette.searchCurrentFg ?? currentPalette.textStrong).bgHex(currentPalette.searchCurrentBg ?? currentPalette.primary)(text),
8776
+ /** The LEGACY anchor-only ROW wash used when no visible card-anchor geometry
8777
+ * (header or first visible non-image text row) is available: it marks only the
8778
+ * owning row, never a proven occurrence, and ordinary query words on that row
8779
+ * keep their yellow block. A card with visible anchor geometry uses
8780
+ * {@link searchCardAnchor} instead. */
8781
+ searchAnchorBg: (text) => chalk.bgHex(currentPalette.searchAnchorBg ?? currentPalette.border)(text),
8782
+ /** Plain italics (kimi thinking parity); an optional tone override
8783
+ * colors the italic run. */
8784
+ italic: (text, tone) => tone === void 0 ? chalk.italic(text) : chalk.italic.hex(currentPalette[tone] ?? currentPalette.text)(text),
8785
+ /** Dim + italic for reasoning: intermediate thinking never reads like output. */
8786
+ textDimItalic: (text) => chalk.italic.hex(currentPalette.textDim)(text)
8787
+ };
8788
+ /** SearchablePicker palette from the semantic tokens (a structural
8789
+ * superset of the upstream SelectListTheme, so it still satisfies the
8790
+ * Editor's autocomplete theme slot). */
8791
+ const selectListTheme = {
8792
+ selectedPrefix: (text) => color.primary(text),
8793
+ selectedText: (text) => chalk.bold.hex(currentPalette.textStrong)(text),
8794
+ description: (text) => color.textDim(text),
8795
+ scrollInfo: (text) => color.textMuted(text),
8796
+ noMatch: (text) => color.textMuted(text),
8797
+ groupHeader: (text) => color.textDim(text)
8798
+ };
8799
+ /**
8800
+ * The readable half of a task/job state: the Title Case status WORD that
8801
+ * carries the shared `‣` marker (design language `docs/architecture/design-language.md`
8802
+ * §3.2 role 9 — colour is never the only signal, §3.3.3). The word is paired
8803
+ * with {@link taskStatusColor}'s token; the two must stay one vocabulary, so
8804
+ * this map lives beside the colour map (`docs/architecture/design-language.md` §10) and
8805
+ * is never forked.
8806
+ *
8807
+ * A status the map does not name is Title-cased verbatim: the surface may not
8808
+ * rename a real state it does not know, and a future wire status must still
8809
+ * paint a readable word.
8810
+ */
8811
+ function taskStatusWord(status) {
8812
+ switch (status) {
8813
+ case "running": return "Running";
8814
+ case "stopping": return "Stopping";
8815
+ case "completed": return "Completed";
8816
+ case "failed": return "Failed";
8817
+ case "killed": return "Killed";
8818
+ case "timed_out": return "Timed out";
8819
+ case "lost": return "Lost";
8820
+ case "inactive": return "Inactive";
8821
+ case "awaiting answer": return "Awaiting answer";
8822
+ default: return status.charAt(0).toUpperCase() + status.slice(1);
8823
+ }
8824
+ }
8825
+ /**
8826
+ * Status-dot colour for a job status (dsh-web StateDot parity:
8827
+ * running = ongoing/primary, stopping/killed = warning, completed = done/dim,
8828
+ * failed/timed-out/lost = error). Unknown statuses fall back to the
8829
+ * muted token so a future wire status never crashes the renderer.
8830
+ */
8831
+ function taskStatusColor(status) {
8832
+ switch (status) {
8833
+ case "running": return color.primary;
8834
+ case "stopping": return color.warning;
8835
+ case "completed": return color.textDim;
8836
+ case "failed":
8837
+ case "killed": return color.warning;
8838
+ case "timed_out":
8839
+ case "lost": return color.error;
8840
+ default: return color.textMuted;
8841
+ }
8842
+ }
8843
+ /**
8844
+ * SettingsList palette from the semantic tokens. A FUNCTION, not a
8845
+ * module-level constant: `cursor` is a pre-rendered ANSI string, so a
8846
+ * constant would freeze the cursor colour at module load and never follow
8847
+ * a live theme switch. Call it fresh for every overlay/settings open.
8848
+ */
8849
+ function settingsListTheme() {
8850
+ return {
8851
+ label: (text, selected) => selected ? chalk.bold.hex(currentPalette.textStrong)(text) : color.text(text),
8852
+ value: (text, selected) => selected ? color.primary(text) : color.textDim(text),
8853
+ description: (text) => color.textDim(text),
8854
+ cursor: color.primary("> "),
8855
+ hint: (text) => color.textMuted(text)
8856
+ };
8857
+ }
8858
+ /** Editor palette: focused border uses the brand token. */
8859
+ const editorTheme = {
8860
+ borderColor: (text) => color.border(text),
8861
+ selectList: selectListTheme
8862
+ };
8863
+ /**
8864
+ * Markdown rendering options shared by EVERY host transcript renderer
8865
+ * (assistant cards, thinking blocks, plugin component compilation).
8866
+ * LaTeX-to-Unicode rendering is deliberately OFF (the kimi-host parity
8867
+ * choice): the Earendil 0.84.4 re-vendor introduced `renderLatex`
8868
+ * defaulting to true, which silently changed how `$...$`/`$$...$$`
8869
+ * segments in assistant output render. Keep the pre-re-vendor rendering;
8870
+ * revisit as an explicit setting if LaTeX output ever becomes a product
8871
+ * requirement.
8872
+ */
8873
+ const HOST_MARKDOWN_OPTIONS = { renderLatex: false };
8874
+ /** Markdown palette for assistant messages. */
8875
+ const markdownTheme = {
8876
+ heading: (text) => chalk.bold.hex(currentPalette.textStrong)(text),
8877
+ link: (text) => color.primary(text),
8878
+ linkUrl: (text) => color.textMuted(text),
8879
+ code: (text) => color.primary(text),
8880
+ codeBlock: (text) => text,
8881
+ codeBlockBorder: (text) => color.textMuted(text),
8882
+ quote: (text) => color.textDim(text),
8883
+ quoteBorder: (text) => color.textDim(text),
8884
+ hr: (text) => color.border(text),
8885
+ listBullet: (text) => color.text(text.replace(/^-/, "•")),
8886
+ bold: (text) => chalk.bold(text),
8887
+ italic: (text) => chalk.italic(text),
8888
+ strikethrough: (text) => chalk.strikethrough(text),
8889
+ underline: (text) => chalk.underline(text)
8890
+ };
8891
+ //#endregion
8892
+ //#region src/tui/pickers/model-directory.ts
8893
+ const IDENTITY_SEP = "\0";
8894
+ const PROVIDER_DEFAULT = `${IDENTITY_SEP}provider-default`;
8895
+ /** Full logical identity of a model row. Model ids are not globally unique. */
8896
+ function modelIdentity(providerId, modelId) {
8897
+ return `${providerId}${IDENTITY_SEP}${modelId}`;
8898
+ }
8899
+ /**
8900
+ * Project the Host directory into identity-complete presentation rows. Pure:
8901
+ * no terminal/component state, so the current/default/effort rules are unit
8902
+ * testable without a rendering snapshot.
8903
+ */
8904
+ function projectModelDirectory(directory, current, sessionless) {
8905
+ const models = [];
8906
+ for (const group of directory.groups) for (const model of group.models) {
8907
+ const matchesConfigured = current !== void 0 && current.provider === group.id && current.model === model.id;
8908
+ const isCurrentModel = !sessionless && matchesConfigured;
8909
+ const isDefault = directory.default.provider === group.id && directory.default.model === model.id;
8910
+ models.push({
8911
+ providerId: group.id,
8912
+ providerName: group.name,
8735
8913
  modelId: model.id,
8736
8914
  modelName: model.name,
8737
8915
  efforts: model.reasoning?.efforts ?? [],
@@ -8776,6 +8954,139 @@ function initialEffortOf(row, choices) {
8776
8954
  return advertised(row.configuredEffort) ?? advertised(row.defaultEffort) ?? choices[0].value;
8777
8955
  }
8778
8956
  //#endregion
8957
+ //#region src/tui/tsp/preset-guide-content.ts
8958
+ /** The official English Mode Guides of the four SHIPPED presets.
8959
+ *
8960
+ * The copy is a verbatim transcription of the official Web surface's curated
8961
+ * help, pinned to
8962
+ * `deepseek-ai/deepseek-harness@d743267388641bc76f17c45ce8b4c231aed1d32c`
8963
+ * `packages/client/ui-agent-preset/src/client/guide-locales.ts` (the `guideEn`
8964
+ * seat): the intro, the mode explanation and the usage examples, unchanged.
8965
+ * Refreshing the official wording means refreshing that pin — this module never
8966
+ * translates, rewrites or generates guide text of its own.
8967
+ *
8968
+ * Source license: the upstream repository is MIT (`Copyright (c) 2026
8969
+ * DeepSeek`); this transcription keeps the upstream wording and attributes the
8970
+ * source in this header rather than duplicating a license file, per the
8971
+ * repository's vendoring-attribution practice for small quoted excerpts.
8972
+ *
8973
+ * The Guide is READ-ONLY static content: it is not part of the live roster and
8974
+ * carries no business authority. A Custom declaration that reuses a shipped id
8975
+ * must never borrow an official Guide, so the lookup requires the caller's
8976
+ * ALREADY-DERIVED shipped classification instead of trusting the id alone.
8977
+ * @module tui/tsp/preset-guide-content
8978
+ */
8979
+ /** The two Markdown sections the official Web dialog renders, in order. */
8980
+ const GUIDE_SECTION_HEADS = {
8981
+ modeDetails: "Mode details",
8982
+ howToUse: "How to use"
8983
+ };
8984
+ /** The four shipped presets' pinned official copy, keyed by shipped id. */
8985
+ const BUILT_IN_GUIDES = {
8986
+ standard: {
8987
+ intro: "Choose Standard mode when starting a new task. Describe what you want to accomplish, point to the relevant files, and explain how to check the result.",
8988
+ explanation: [
8989
+ "### How it works",
8990
+ "The agent calls tools directly to read and edit files, search, and run terminal commands. It includes Skills, planning, goals, subagents, workflows, and context compaction.",
8991
+ "### When to choose it",
8992
+ "Start here for everyday coding, file work, and research. Standard mode can also write scripts and process files in batches. PTC changes how tool calls are organized; it is not required for batch tasks."
8993
+ ].join("\n\n"),
8994
+ usage: [
8995
+ "### Fix a bug",
8996
+ "> Find out why submitting the search form twice makes the results disappear. Fix it and run the relevant tests. Explain the cause and what changed.",
8997
+ "Expected output: a code change, the relevant test results, and an explanation of the cause.",
8998
+ "### Organize project notes",
8999
+ "> Read the Markdown notes in this project. Summarize the agreed decisions and open questions, with links to the source files.",
9000
+ "Expected output: a summary with references that you can check against the original notes."
9001
+ ].join("\n\n")
9002
+ },
9003
+ ptc: {
9004
+ intro: "Choose PTC mode when starting a new task. Specify the input files, processing rules, and output format. The agent writes the code.",
9005
+ explanation: [
9006
+ "### How tools are called",
9007
+ "PTC means Programmatic Tool Calling. In this built-in preset, the agent uses run_code to write a TypeScript program that calls tools through a generated SDK. The program can use loops, conditions, error handling, and concurrent calls where appropriate.",
9008
+ "### What reaches the model",
9009
+ "Tool results first reach the program, which can filter and combine them. The model receives what the program prints or returns; image results are attached separately. Nested tool calls are still recorded and remain subject to tool permissions.",
9010
+ "### Compared with Standard mode",
9011
+ "Both modes can handle coding and batch tasks. Standard mode exposes individual tools directly; PTC organizes tool calls in code. The current PTC preset leaves the workflow tool disabled. Speed and token use depend on the task and how the program handles its results."
9012
+ ].join("\n\n"),
9013
+ usage: [
9014
+ "### Check a set of configuration files",
9015
+ "> Check all JSON files in configs/. List missing required fields and invalid values against schema.json. Save a CSV with one row per issue. Include unreadable files in the report and keep checking the rest. Leave the original files unchanged.",
9016
+ "Expected output: an issue summary and a CSV report. The program can repeat the same checks, handle individual failures, and collect the results.",
9017
+ "### Summarize error logs",
9018
+ "> Analyze the log files in logs/. Group errors by service and error type. Show the ten most frequent groups and one example from each. Save the full counts to a CSV.",
9019
+ "Expected output: the top error groups and a complete count table. Intermediate data can be aggregated in the program before the summary reaches the model."
9020
+ ].join("\n\n")
9021
+ },
9022
+ minimal: {
9023
+ intro: "Choose Minimal mode for a new task. For a comparison, hold the model, permissions, input, and starting workspace state constant across runs.",
9024
+ explanation: [
9025
+ "### What is included",
9026
+ "One persistent shell tool and a fixed system prompt. The built-in preset does not load Skills, planning, context compaction, or the standard runtime context.",
9027
+ "### When to choose it",
9028
+ "Use it as a baseline for experiments and comparisons. It can still read files and execute scripts through shell commands, but offers fewer built-in ways to manage a long task. Fewer tools does not necessarily make it easier for a beginner."
9029
+ ].join("\n\n"),
9030
+ usage: [
9031
+ "### Compare performance on a small bug fix",
9032
+ "> Run the tests for this project, find the cause of the failure, and make the smallest fix. Run the relevant tests again and report the result.",
9033
+ "Run the same task separately in Standard and Minimal modes from the same starting state. Compare task completion, tool calls, and the resulting changes. Minimal mode performs the work through terminal commands."
9034
+ ].join("\n\n")
9035
+ },
9036
+ cordis: {
9037
+ intro: "Choose Creator mode for a new task. Describe the capability you want, where it should appear, and how you will verify it.",
9038
+ explanation: [
9039
+ "### What you can create",
9040
+ "Creator mode includes the standard task tools plus runtime inspection, persistent plugin management, and guidance for authoring Cordis plugins and agent presets. It can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.",
9041
+ "### Plugins and modes",
9042
+ "A plugin adds capabilities to DSH, such as a tool, a service connection, or a UI entry. A mode is an agent preset that selects tools and defines how the agent works in a task. A plugin can be included in a custom preset.",
9043
+ "### How the result takes effect",
9044
+ "Ask the agent to install and verify the result, not just generate source code. A plugin may load immediately or require a restart, depending on what it changes. A newly created preset is selected when starting a new task."
9045
+ ].join("\n\n"),
9046
+ usage: [
9047
+ "### Add a UI",
9048
+ "> Create a DSH plugin that adds a project notes entry to the sidebar. Let me browse the Markdown files in this workspace and preview a selected note. Install it and verify that the page opens.",
9049
+ "Expected output: an installed plugin with a working entry and preview page, plus any remaining activation steps.",
9050
+ "### Add a tool",
9051
+ "> Create a plugin with a tool that reads this project’s test report and summarizes the failed tests. Register it and verify it with a sample report.",
9052
+ "Expected output: a plugin with a callable tool and a verified sample call.",
9053
+ "### Create my own mode",
9054
+ "> Create a “Code review” mode based on Standard mode. Have it prioritize potential bugs and test gaps, cite file paths and lines, and ask before modifying files. Save it as a selectable preset.",
9055
+ "Expected output: a custom preset for new tasks. These review instructions guide the agent; permission settings determine which actions it can execute."
9056
+ ].join("\n\n")
9057
+ }
9058
+ };
9059
+ /**
9060
+ * The complete read-only Markdown body of one shipped preset's Mode guide: the
9061
+ * two official sections the Web dialog shows, rendered as ONE continuous
9062
+ * scrolling body instead of behind a second layer of tabs or a modal.
9063
+ */
9064
+ function copyMarkdown(copy) {
9065
+ return [
9066
+ `## ${GUIDE_SECTION_HEADS.modeDetails}`,
9067
+ copy.intro,
9068
+ copy.explanation,
9069
+ `## ${GUIDE_SECTION_HEADS.howToUse}`,
9070
+ copy.usage
9071
+ ].join("\n\n");
9072
+ }
9073
+ /**
9074
+ * The official Mode guide of one row, or `undefined` when the row must not have
9075
+ * one.
9076
+ *
9077
+ * `builtIn` is the row's ALREADY-DERIVED shipped classification — the value
9078
+ * `isBuiltInPresetRow` produced from the raw roster DTO. It is checked FIRST and
9079
+ * on its own: the shipped-id table is consulted only for a row the official
9080
+ * classification really calls shipped, so a user declaration that happens to
9081
+ * reuse `standard`/`ptc`/`minimal`/`cordis` (and therefore publishes its own
9082
+ * `name`) keeps its own copy and never inherits an official Guide.
9083
+ */
9084
+ function builtInGuide(row) {
9085
+ if (!row.builtIn) return void 0;
9086
+ const copy = BUILT_IN_GUIDES[row.id];
9087
+ return copy === void 0 ? void 0 : copyMarkdown(copy);
9088
+ }
9089
+ //#endregion
8779
9090
  //#region src/tui/pickers/preset-display.ts
8780
9091
  /** The shipped-preset display copy, shared by every preset picker surface.
8781
9092
  *
@@ -9015,19 +9326,25 @@ const QUEUE_CHORDS = {
9015
9326
  }
9016
9327
  };
9017
9328
  /**
9018
- * The Session Workspace tree's FIXED local chord (PR2).
9329
+ * The Session Workspace's FIXED local chords (PR2 tree cycle, PR3 Inspect).
9019
9330
  *
9020
9331
  * The fullscreen PiTUI tree is a per-surface COMPONENT contract, not a Host
9021
- * command: Tab/Shift+Tab step between Workspace Folder titles and have no
9022
- * keymap action or remap. Keeping the handler and painted label in this ONE
9023
- * key-label authority means a footer hint and the admitted keys cannot drift
9024
- * into two authorities — the same category as the History/Delivered-files
9025
- * fixed chords.
9026
- */
9027
- const SESSION_WORKSPACE_CHORDS = { folderCycle: {
9028
- keys: ["tab", "shift+tab"],
9029
- label: "Tab/Shift+Tab"
9030
- } };
9332
+ * command: Tab/Shift+Tab step between Workspace Folder titles and F2 opens the
9333
+ * read-only Inspector, so none of them has a keymap action or remap. Keeping
9334
+ * the handler and painted label in this ONE key-label authority means a footer
9335
+ * hint and the admitted keys cannot drift into two authorities — the same
9336
+ * category as the History/Delivered-files fixed chords.
9337
+ */
9338
+ const SESSION_WORKSPACE_CHORDS = {
9339
+ folderCycle: {
9340
+ keys: ["tab", "shift+tab"],
9341
+ label: "Tab/Shift+Tab"
9342
+ },
9343
+ inspect: {
9344
+ keys: ["f2"],
9345
+ label: "F2"
9346
+ }
9347
+ };
9031
9348
  /** The display name of a bare (unmodified) key id. */
9032
9349
  const BASE_KEY_LABELS = {
9033
9350
  enter: "Enter",
@@ -9059,7 +9376,7 @@ function formatKeyId(key) {
9059
9376
  else if (part === "shift") mods.push("Shift");
9060
9377
  else if (part === "super") mods.push("Super");
9061
9378
  else base = part;
9062
- const baseLabel = BASE_KEY_LABELS[base] ?? (base.length === 1 ? base.toUpperCase() : base);
9379
+ const baseLabel = BASE_KEY_LABELS[base] ?? (base.length === 1 || /^f\d+$/u.test(base) ? base.toUpperCase() : base);
9063
9380
  return [...mods, baseLabel].join("+");
9064
9381
  }
9065
9382
  /** Format a `<leader>X` sequence label (`<leader>t` → `Leader T`). */
@@ -9111,11 +9428,19 @@ const TSP_VISUAL_COPY_LABEL = formatKeyId(TSP_VISUAL_CHORDS.copy);
9111
9428
  const JOB_LOCAL_KEYS = {
9112
9429
  /** Switch between the Output and Command pages, in both directions. */
9113
9430
  switchPage: "tab",
9431
+ /** Toggle the Output page's adaptive multi-line Command preview. */
9432
+ togglePreview: "f2",
9114
9433
  /** Copy the current page's exact original. A BARE letter — the same key the
9115
9434
  * Settings workspace's copy uses and the one the `[C]` affordance badges name —
9116
9435
  * so the bar hint reads `c copy …` and badge and key agree (§4.1, §7.1). */
9117
9436
  copy: "c"
9118
9437
  };
9438
+ /** Fixed Job Find search-row keys (owned here so panels never hard-code chords). */
9439
+ const JOB_SEARCH_LOCAL_KEYS = {
9440
+ commit: "enter",
9441
+ next: "n",
9442
+ prev: "shift+n"
9443
+ };
9119
9444
  /**
9120
9445
  * The SVG Viewer's FIXED screen-local chords (PR2.5).
9121
9446
  *
@@ -10608,79 +10933,77 @@ function renderWelcomeWhaleLines(variant) {
10608
10933
  const colors = WELCOME_WHALE_COLORS;
10609
10934
  return welcomeWhalePlainLines(variant).map((line, index) => hexPaint(colors[Math.min(index, colors.length - 1)], line));
10610
10935
  }
10611
- /** Strip the `session-`/`session_` prefix and keep the first 8 characters, like
10612
- * the kimicode card's short id. */
10613
- function shortSessionId(id) {
10614
- return id.replace(/^session[-_]/i, "").slice(0, 8);
10615
- }
10616
- /** A canonical full Session id: the `session-`/`session_` prefix plus 32 hex
10617
- * characters, optionally written as a hyphenated canonical UUID. A BARE UUID
10618
- * is NOT a canonical Session id — it must match an official listed row. */
10619
- const CANONICAL_SESSION_ID = /^session[-_](?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
10620
- /** The CLI automatic-prefix rule: at least four ASCII hex digits after the
10621
- * optional `session-`/`session_` prefix. Deliberately stricter than the
10622
- * `/resume` matcher; the CLI must not auto-resume a word-like query. */
10623
- const CLI_PREFIX = /^[0-9a-f]{4,}$/i;
10624
- /** Whether `query` is a canonical full Session id that may be opened WITHOUT
10625
- * a roster read (the explicit full-id launch contract). */
10626
- function canonicalFullSessionId(query) {
10627
- return CANONICAL_SESSION_ID.test(query);
10628
- }
10629
- /** The legal automatic prefix `query` carries, or undefined. The returned
10630
- * value is the bare hex prefix (the leading Session prefix stripped). */
10631
- function cliAutoPrefix(query) {
10632
- const bare = query.replace(/^session[-_]/i, "");
10633
- return CLI_PREFIX.test(bare) ? bare : void 0;
10634
- }
10635
- /**
10636
- * Resolve one session row for a typed resume query. A full id wins over the
10637
- * row order; otherwise only a UNIQUE non-empty prefix (the `session-` form or
10638
- * the short id) is resolved. An ambiguous or missing prefix returns undefined
10639
- * so the read owner seeds the same global Browser search instead of guessing.
10640
- * @param rows - the listed main-session rows (never re-filtered here).
10641
- * @param query - the resume query.
10642
- * @returns the matching row, or undefined.
10643
- */
10644
- function findSessionMatch(rows, query) {
10645
- const exact = rows.find((row) => row.id === query);
10646
- if (exact !== void 0) return exact;
10647
- const bare = query.replace(/^session[-_]/i, "");
10648
- if (bare === "") return void 0;
10649
- let candidate;
10650
- for (const row of rows) {
10651
- if (!row.id.replace(/^session[-_]/i, "").startsWith(bare) && !shortSessionId(row.id).startsWith(bare)) continue;
10652
- if (candidate !== void 0) return void 0;
10653
- candidate = row;
10654
- }
10655
- return candidate;
10936
+ //#endregion
10937
+ //#region src/app/command/session-browser-presentation.ts
10938
+ /** Whether the Client-root eligibility proves THIS Client may answer the
10939
+ * pending candidate the Host reported for `sessionId`. */
10940
+ function classifyLiveEligibility(sessionId, eligibility) {
10941
+ const live = eligibility?.filter((entry) => entry.live && entry.sessionId === sessionId) ?? [];
10942
+ if (live.some((entry) => entry.kind === "approval")) return {
10943
+ pending: "approval",
10944
+ answerable: true
10945
+ };
10946
+ const questions = live.filter((entry) => entry.kind === "question");
10947
+ if (questions.length === 0) return {
10948
+ pending: "unknown",
10949
+ answerable: false
10950
+ };
10951
+ return {
10952
+ pending: questions.every((entry) => entry.subtype === "plan-review") ? "plan-review" : "question",
10953
+ answerable: true
10954
+ };
10656
10955
  }
10657
- /**
10658
- * Resolve one CLI `--session` value before the Browser mounts: an exact
10659
- * official row id first (including historical non-standard ids), then — only
10660
- * for a legal CLI automatic prefix — the SAME unique-prefix primitive
10661
- * `/resume` uses. An ambiguous, missing or word-like query returns undefined
10662
- * so the startup Browser keeps it as one global search instead of guessing.
10663
- * A subagent child is never an automatic main-Session selection.
10664
- */
10665
- function chooseListedSession(rows, query) {
10666
- if (query === "" || /^session[-_]$/i.test(query)) return void 0;
10667
- const exact = rows.find((row) => row.id === query);
10668
- if (exact !== void 0) return exact;
10669
- if (cliAutoPrefix(query) === void 0) return void 0;
10670
- return findSessionMatch(rows.filter((row) => row.origin !== "subagent"), query);
10671
- }
10672
- /** Canonicalize one user query for both metadata matching and Host search. */
10673
- function sanitizeSessionSearchInput(value) {
10674
- const trimmed = value.replace(/\0/g, "").trim();
10675
- if (trimmed.length <= 500) return trimmed;
10676
- const truncated = trimmed.slice(0, 500);
10677
- const last = truncated.charCodeAt(499);
10678
- return last >= 55296 && last <= 56319 ? truncated.slice(0, 499) : truncated;
10679
- }
10680
- /** Metadata-only membership; content membership belongs to SessionReader.search(). */
10681
- function sessionRowMatchesQuery(row, query) {
10682
- const needle = query.toLowerCase();
10683
- return row.id.toLowerCase().includes(needle) || (row.title ?? "").toLowerCase().includes(needle) || (row.cwd ?? "").toLowerCase().includes(needle) || (row.preset ?? "").toLowerCase().includes(needle) || (row.workspace?.title ?? "").toLowerCase().includes(needle) || (row.workspace?.path ?? "").toLowerCase().includes(needle);
10956
+ function classifyPending(activity, eligibility) {
10957
+ if (activity === void 0) return {
10958
+ pending: "unknown",
10959
+ answerable: false
10960
+ };
10961
+ const { attention, attentionSourceState, continuedQuestionCallIds } = activity;
10962
+ if (attentionSourceState === "known" && (attention === "question" || attention === "plan-review") && (continuedQuestionCallIds?.length ?? 0) > 0 && eligibility !== void 0) return {
10963
+ pending: "late-answer",
10964
+ answerable: true
10965
+ };
10966
+ if (attention === "none") return {
10967
+ pending: attentionSourceState === "known" ? "none" : attentionSourceState,
10968
+ answerable: false
10969
+ };
10970
+ if (attention === "unknown") return {
10971
+ pending: attentionSourceState === "known" ? "unknown" : attentionSourceState,
10972
+ answerable: false
10973
+ };
10974
+ return {
10975
+ pending: "unverified",
10976
+ answerable: false
10977
+ };
10978
+ }
10979
+ /** The ONE pure Session Browser admission/classification policy.
10980
+ *
10981
+ * `activity` must be the exact accepted sample for this row and roster
10982
+ * revision. Search deliberately does not use Activity: every known blank is
10983
+ * excluded from an ordinary query, while Browse retains a proved Needs/Working
10984
+ * row as a real active-session exception. */
10985
+ function classifySessionBrowserRow(row, activity, eligibility, status) {
10986
+ const exactActivity = activity?.sessionId === row.id ? activity : void 0;
10987
+ const exactStatus = status?.sessionId === row.id ? status : void 0;
10988
+ const live = classifyLiveEligibility(row.id, eligibility);
10989
+ const derived = classifyPending(exactActivity, eligibility);
10990
+ const pending = live.answerable ? live.pending : derived.pending;
10991
+ const answerable = live.answerable || derived.answerable;
10992
+ const childRunning = exactActivity?.runningChildren;
10993
+ const completionUnread = exactStatus?.completionUnread === true;
10994
+ const working = exactActivity?.running === true || (childRunning ?? 0) > 0;
10995
+ const normal = row.origin !== "subagent";
10996
+ return {
10997
+ priority: answerable ? "needs" : working ? "working" : completionUnread ? "unread" : "recent",
10998
+ pending,
10999
+ running: exactActivity?.running,
11000
+ childRunning,
11001
+ completionUnread,
11002
+ answerable,
11003
+ source: exactActivity?.attentionSourceState ?? "unknown",
11004
+ browseEligible: normal && (row.blank !== true || answerable || working),
11005
+ searchEligible: normal && row.blank !== true
11006
+ };
10684
11007
  }
10685
11008
  //#endregion
10686
11009
  //#region src/tui/pickers/sessions.ts
@@ -10739,8 +11062,7 @@ function sanitizeTerminalText(value) {
10739
11062
  function sessionBrowserErrorNotice(kind, message) {
10740
11063
  const safe = sanitizeTerminalText(message).replace(/\s+\(raw log: .*\)$/u, "");
10741
11064
  const unknownEvent = /contains event type "([^"]+)"/u.exec(safe)?.[1];
10742
- const text = unknownEvent === void 0 ? `${kind === "search" ? "Search failed" : "Session details unavailable"}: ${safe}` : `unknown event ${unknownEvent}`;
10743
- return truncateToWidth(text, 40, "…");
11065
+ return unknownEvent === void 0 ? `${kind === "search" ? "Search failed" : "Session details unavailable"}: ${safe}` : `unknown event ${unknownEvent}`;
10744
11066
  }
10745
11067
  //#endregion
10746
11068
  //#region src/tui/icons.ts
@@ -13321,11 +13643,34 @@ function subagentJobViewHint(status, detail) {
13321
13643
  }
13322
13644
  //#endregion
13323
13645
  //#region src/tui/presentation/session-workspace-view.ts
13646
+ /**
13647
+ * M5-U-D — the ONE pure projection of the fullscreen PiTUI Session Workspace.
13648
+ *
13649
+ * This module is UI-only: it imports no backend, adapter, Agent or transport,
13650
+ * performs no IO and holds no state. It answers three questions for the ONE
13651
+ * panel that paints them, from facts the panel already received:
13652
+ *
13653
+ * 1. which single group each listed main Session belongs to
13654
+ * (`Needs attention` → `Working` → `Recent`),
13655
+ * 2. which Sessions the current Workspace scope really lists,
13656
+ * 3. what the header may truthfully say about attention OUTSIDE that scope.
13657
+ *
13658
+ * Authority chain (all read-only, all already sampled by their owner):
13659
+ * `SessionReader.list()` is the ONLY roster; `SessionWorkspaceFactsPort.
13660
+ * readActivity()` is the ONLY activity sample; the Client-root forwarded
13661
+ * answer eligibility (G567) is the ONLY positive answerability proof. A reader
13662
+ * `attention` value alone is NEVER the permission to answer, so a pending
13663
+ * candidate this Client cannot prove it can answer is `unverified` — never a
13664
+ * Needs row and never a fabricated `No pending`.
13665
+ *
13666
+ * @module @xmoon76/dsh-pi-tui/tui/presentation/session-workspace-view
13667
+ */
13324
13668
  /** The ONE verbose pending wording shared by Peek/Details. */
13325
13669
  const SESSION_PENDING_LABEL = {
13326
13670
  question: "Question",
13327
13671
  approval: "Approval",
13328
13672
  "plan-review": "Plan review",
13673
+ "late-answer": "Late answer",
13329
13674
  none: "No pending",
13330
13675
  unknown: "Pending unknown",
13331
13676
  unavailable: "Pending unavailable",
@@ -13339,13 +13684,23 @@ const SESSION_SOURCE_LABEL = {
13339
13684
  unavailable: "unavailable",
13340
13685
  denied: "denied"
13341
13686
  };
13342
- /** The ONE compact row status: only positive, action-relevant facts. */
13687
+ /** The ONE verbose row status wording shared by Peek/Details and the panels. */
13343
13688
  function workspaceRowStatusLabel(fact) {
13344
- if (fact.priority === "needs") return fact.running === true ? "Needs attention · Working" : "Needs attention";
13345
- if (fact.priority === "working") return "Working";
13689
+ if (fact.priority === "needs") {
13690
+ const base = `Needs attention · ${SESSION_PENDING_LABEL[fact.pending]}`;
13691
+ return fact.running === true || (fact.childRunning ?? 0) > 0 ? `${base} · ${workspaceWorkingLabel(fact)}` : base;
13692
+ }
13693
+ if (fact.priority === "working") return workspaceWorkingLabel(fact);
13694
+ if (fact.priority === "unread") return "Completed · unread";
13346
13695
  if (fact.pending === "unverified") return "Pending · not actionable here";
13347
13696
  return "";
13348
13697
  }
13698
+ /** The ONE compact working wording: `0` is never printed as a positive fact. */
13699
+ function workspaceWorkingLabel(fact) {
13700
+ const count = fact.childRunning;
13701
+ if (count === void 0 || count <= 0) return "Working";
13702
+ return `Working · ${count} running ${count === 1 ? "child" : "children"}`;
13703
+ }
13349
13704
  /** Display title collisions by the shortest unique Host path tail. The ID is a
13350
13705
  * final fallback only when Host paths themselves remain indistinguishable. */
13351
13706
  function workspaceDisplayLabels(workspaces) {
@@ -13412,9 +13767,10 @@ function visibleWorkspaceBrowserRows(model, display, selectedSessionId, currentS
13412
13767
  const facts = group.ids.map((id) => model.rowsById.get(id));
13413
13768
  const needs = facts.filter((fact) => fact.priority === "needs").length;
13414
13769
  const working = facts.filter((fact) => fact.priority === "working").length;
13770
+ const unread = facts.filter((fact) => fact.priority === "unread").length;
13415
13771
  const current = group.workspaceId === model.currentWorkspaceId;
13416
13772
  const next = group.workspaceId === model.nextCreateWorkspaceId;
13417
- const defaultExpanded = current || next || needs + working > 0;
13773
+ const defaultExpanded = current || next || needs + working + unread > 0;
13418
13774
  const expanded = display.expanded.get(group.workspaceId) ?? defaultExpanded;
13419
13775
  const groupRows = [];
13420
13776
  rows.push({
@@ -13426,6 +13782,7 @@ function visibleWorkspaceBrowserRows(model, display, selectedSessionId, currentS
13426
13782
  total: group.ids.length,
13427
13783
  needs,
13428
13784
  working,
13785
+ unread,
13429
13786
  expanded,
13430
13787
  current,
13431
13788
  next
@@ -13486,41 +13843,13 @@ function inScope(fact, scope, currentWorkspaceId, baselineProven) {
13486
13843
  case "unassigned": return baselineProven && fact.membership.kind === "unassigned";
13487
13844
  }
13488
13845
  }
13489
- /** Whether the Client-root eligibility proves THIS Client may answer the
13490
- * pending candidate the Host reported for `sessionId`. */
13491
- function provedAnswerable(fact, eligibility) {
13492
- if (fact.attentionSourceState !== "known") return false;
13493
- if (fact.attention === "approval") return eligibility?.some((entry) => entry.sessionId === fact.sessionId && entry.kind === "approval") === true;
13494
- if (fact.attention !== "question" && fact.attention !== "plan-review") return false;
13495
- if (eligibility?.some((entry) => entry.sessionId === fact.sessionId && entry.kind === "question") === true) return true;
13496
- return eligibility !== void 0 && (fact.continuedQuestionCallIds?.length ?? 0) > 0;
13497
- }
13498
- function classifyPending(activity, eligibility) {
13499
- if (activity === void 0) return {
13500
- pending: "unknown",
13501
- answerable: false
13502
- };
13503
- const { attention, attentionSourceState } = activity;
13504
- if (attention === "none") return {
13505
- pending: attentionSourceState === "known" ? "none" : attentionSourceState,
13506
- answerable: false
13507
- };
13508
- if (attention === "unknown") return {
13509
- pending: attentionSourceState === "known" ? "unknown" : attentionSourceState,
13510
- answerable: false
13511
- };
13512
- const answerable = provedAnswerable(activity, eligibility);
13513
- return {
13514
- pending: answerable ? attention : "unverified",
13515
- answerable
13516
- };
13517
- }
13518
13846
  /** Build the ONE view of one frame. Every input is an official fact or the
13519
13847
  * previous pure ordering; nothing here reads, writes or invents a Session. */
13520
13848
  function buildSessionWorkspaceView(input) {
13521
13849
  const roster = input.rows.filter((row) => row.origin !== "subagent");
13522
13850
  const activityById = /* @__PURE__ */ new Map();
13523
13851
  for (const activity of input.activity ?? []) activityById.set(activity.sessionId, activity);
13852
+ const statusById = input.status;
13524
13853
  const currentWorkspaceId = currentWorkspaceOf(input.workspaces, input.currentSessionId);
13525
13854
  const rosterIndex = /* @__PURE__ */ new Map();
13526
13855
  roster.forEach((row, index) => {
@@ -13532,17 +13861,31 @@ function buildSessionWorkspaceView(input) {
13532
13861
  });
13533
13862
  const rowsById = /* @__PURE__ */ new Map();
13534
13863
  const classified = [];
13864
+ /** Derived in the SAME classification pass, before the skip: a hidden quiet
13865
+ * current blank may only move its marker onto the existing New action of its
13866
+ * ONE proved official Workspace. It is never added back to the eligible
13867
+ * projection or the group ids. */
13868
+ let currentQuietBlankWorkspaceId;
13535
13869
  for (const row of roster) {
13536
- const activity = activityById.get(row.id);
13537
- const { pending, answerable } = classifyPending(activity, input.answerEligibility);
13870
+ const classification = classifySessionBrowserRow(row, activityById.get(row.id), input.answerEligibility, statusById?.get(row.id));
13871
+ if (!classification.browseEligible) {
13872
+ if (row.id === input.currentSessionId && row.blank === true && input.workspaceBaselineProven) {
13873
+ const membership = workspaceMembershipOf(input.workspaces, row.id, true);
13874
+ if (membership.kind === "assigned") currentQuietBlankWorkspaceId = membership.workspaceIds[0];
13875
+ }
13876
+ continue;
13877
+ }
13538
13878
  const fact = {
13539
13879
  sessionId: row.id,
13540
- priority: answerable ? "needs" : activity?.running === true ? "working" : "recent",
13541
- group: answerable ? "needs" : activity?.running === true ? "working" : "recent",
13542
- pending,
13543
- running: activity?.running,
13544
- answerable,
13545
- source: activity?.attentionSourceState ?? "unknown",
13880
+ priority: classification.priority,
13881
+ group: classification.priority,
13882
+ pending: classification.pending,
13883
+ running: classification.running,
13884
+ childRunning: classification.childRunning,
13885
+ completionUnread: classification.completionUnread,
13886
+ isCurrent: row.id === input.currentSessionId,
13887
+ answerable: classification.answerable,
13888
+ source: classification.source,
13546
13889
  membership: workspaceMembershipOf(input.workspaces, row.id, input.workspaceBaselineProven)
13547
13890
  };
13548
13891
  rowsById.set(row.id, fact);
@@ -13553,6 +13896,7 @@ function buildSessionWorkspaceView(input) {
13553
13896
  const priority = [
13554
13897
  "needs",
13555
13898
  "working",
13899
+ "unread",
13556
13900
  "recent"
13557
13901
  ];
13558
13902
  const byPriority = priority.indexOf(left.priority) - priority.indexOf(right.priority);
@@ -13571,6 +13915,7 @@ function buildSessionWorkspaceView(input) {
13571
13915
  for (const kind of [
13572
13916
  "needs",
13573
13917
  "working",
13918
+ "unread",
13574
13919
  "recent"
13575
13920
  ]) {
13576
13921
  const ids = scoped.filter((fact) => fact.priority === kind).sort(orderOf).map((fact) => fact.sessionId);
@@ -13578,9 +13923,10 @@ function buildSessionWorkspaceView(input) {
13578
13923
  groups.push({
13579
13924
  kind,
13580
13925
  workspaceId: kind,
13581
- title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : "Recent",
13926
+ title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : kind === "unread" ? "Completed · unread" : "Recent",
13582
13927
  path: "",
13583
- ids
13928
+ ids,
13929
+ unread: kind === "unread" ? ids.length : 0
13584
13930
  });
13585
13931
  listIds.push(...ids);
13586
13932
  }
@@ -13590,97 +13936,610 @@ function buildSessionWorkspaceView(input) {
13590
13936
  rowsById,
13591
13937
  outsideAttention: { kind: "none" },
13592
13938
  currentWorkspaceId,
13939
+ currentQuietBlankWorkspaceId,
13593
13940
  nextCreateWorkspaceId: input.nextCreateWorkspaceId,
13594
13941
  workspaceBaselineProven: input.workspaceBaselineProven
13595
13942
  };
13596
13943
  }
13597
- if (!input.workspaceBaselineProven) {
13598
- const scoped = classified.filter((fact) => inScope(fact, input.scope, currentWorkspaceId, false));
13599
- const legacyGroups = [];
13600
- const legacyListIds = [];
13601
- for (const kind of [
13602
- "needs",
13603
- "working",
13604
- "recent"
13605
- ]) {
13606
- const ids = scoped.filter((fact) => fact.priority === kind).sort(orderOf).map((fact) => fact.sessionId);
13607
- if (ids.length === 0) continue;
13608
- legacyGroups.push({
13609
- kind,
13610
- workspaceId: kind,
13611
- title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : "Recent",
13612
- path: "",
13613
- ids
13614
- });
13615
- legacyListIds.push(...ids);
13616
- }
13617
- return {
13618
- groups: legacyGroups,
13619
- listIds: legacyListIds,
13620
- rowsById,
13621
- outsideAttention: { kind: "none" },
13622
- currentWorkspaceId,
13623
- nextCreateWorkspaceId: input.nextCreateWorkspaceId,
13624
- workspaceBaselineProven: false
13625
- };
13944
+ if (!input.workspaceBaselineProven) {
13945
+ const scoped = classified.filter((fact) => inScope(fact, input.scope, currentWorkspaceId, false));
13946
+ const legacyGroups = [];
13947
+ const legacyListIds = [];
13948
+ for (const kind of [
13949
+ "needs",
13950
+ "working",
13951
+ "unread",
13952
+ "recent"
13953
+ ]) {
13954
+ const ids = scoped.filter((fact) => fact.priority === kind).sort(orderOf).map((fact) => fact.sessionId);
13955
+ if (ids.length === 0) continue;
13956
+ legacyGroups.push({
13957
+ kind,
13958
+ workspaceId: kind,
13959
+ title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : kind === "unread" ? "Completed · unread" : "Recent",
13960
+ path: "",
13961
+ ids,
13962
+ unread: kind === "unread" ? ids.length : 0
13963
+ });
13964
+ legacyListIds.push(...ids);
13965
+ }
13966
+ return {
13967
+ groups: legacyGroups,
13968
+ listIds: legacyListIds,
13969
+ rowsById,
13970
+ outsideAttention: { kind: "none" },
13971
+ currentWorkspaceId,
13972
+ currentQuietBlankWorkspaceId,
13973
+ nextCreateWorkspaceId: input.nextCreateWorkspaceId,
13974
+ workspaceBaselineProven: false
13975
+ };
13976
+ }
13977
+ const listIds = classified.filter((fact) => inScope(fact, input.scope, currentWorkspaceId, input.workspaceBaselineProven)).sort(orderOf).map((fact) => fact.sessionId);
13978
+ const groups = [];
13979
+ if (input.workspaceBaselineProven) {
13980
+ for (const workspace of input.workspaces) {
13981
+ const ids = classified.filter((fact) => fact.membership.kind === "assigned" && fact.membership.workspaceIds[0] === workspace.workspaceId).sort(orderOf).map((fact) => fact.sessionId);
13982
+ groups.push({
13983
+ workspaceId: workspace.workspaceId,
13984
+ title: workspace.title,
13985
+ path: workspace.path,
13986
+ ids,
13987
+ unread: ids.filter((id) => rowsById.get(id)?.priority === "unread").length
13988
+ });
13989
+ }
13990
+ const ambiguous = classified.filter((fact) => fact.membership.kind === "ambiguous").sort(orderOf).map((fact) => fact.sessionId);
13991
+ const unassigned = classified.filter((fact) => fact.membership.kind === "unassigned").sort(orderOf).map((fact) => fact.sessionId);
13992
+ if (ambiguous.length > 0) groups.push({
13993
+ workspaceId: "ambiguous",
13994
+ title: "Membership ambiguous",
13995
+ path: "",
13996
+ ids: ambiguous,
13997
+ unread: ambiguous.filter((id) => rowsById.get(id)?.priority === "unread").length
13998
+ });
13999
+ if (unassigned.length > 0) groups.push({
14000
+ workspaceId: "unassigned",
14001
+ title: "Unassigned",
14002
+ path: "",
14003
+ ids: unassigned,
14004
+ unread: unassigned.filter((id) => rowsById.get(id)?.priority === "unread").length
14005
+ });
14006
+ const priorityWorkspaceId = currentWorkspaceId ?? input.nextCreateWorkspaceId;
14007
+ if (priorityWorkspaceId !== void 0) {
14008
+ const priorityIndex = groups.findIndex((group) => group.workspaceId === priorityWorkspaceId);
14009
+ if (priorityIndex > 0) groups.unshift(...groups.splice(priorityIndex, 1));
14010
+ }
14011
+ }
14012
+ let outsideAttention = { kind: "none" };
14013
+ if (input.scope.kind !== "all" && input.scope.kind !== "pending") {
14014
+ let count = 0;
14015
+ let unknown = false;
14016
+ for (const fact of classified) {
14017
+ if (inScope(fact, input.scope, currentWorkspaceId, input.workspaceBaselineProven)) continue;
14018
+ if (fact.answerable) {
14019
+ count += 1;
14020
+ continue;
14021
+ }
14022
+ if (fact.pending !== "none") unknown = true;
14023
+ }
14024
+ outsideAttention = unknown ? { kind: "unknown" } : {
14025
+ kind: "count",
14026
+ count
14027
+ };
14028
+ }
14029
+ return {
14030
+ groups,
14031
+ listIds,
14032
+ rowsById,
14033
+ outsideAttention,
14034
+ currentWorkspaceId,
14035
+ currentQuietBlankWorkspaceId,
14036
+ nextCreateWorkspaceId: input.nextCreateWorkspaceId,
14037
+ workspaceBaselineProven: input.workspaceBaselineProven
14038
+ };
14039
+ }
14040
+ //#endregion
14041
+ //#region src/tui/presentation/session-inspector-view.ts
14042
+ /** The display token for an absent optional value: unknown, never zero. */
14043
+ const MISSING = "—";
14044
+ /** One display duration with a real unit. This is presentation only: the raw
14045
+ * millisecond values stay the Inspector DTO's authority. */
14046
+ function formatInspectorDuration(ms) {
14047
+ if (!Number.isFinite(ms) || ms < 0) return MISSING;
14048
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
14049
+ const totalSeconds = Math.floor(ms / 1e3);
14050
+ const seconds = totalSeconds % 60;
14051
+ const totalMinutes = Math.floor(totalSeconds / 60);
14052
+ if (totalMinutes < 1) {
14053
+ const text = (ms / 1e3).toFixed(1);
14054
+ return `${text.endsWith(".0") ? text.slice(0, -2) : text}s`;
14055
+ }
14056
+ if (totalMinutes < 60) return `${totalMinutes}m${String(seconds).padStart(2, "0")}s`;
14057
+ const minutes = totalMinutes % 60;
14058
+ return `${Math.floor(totalMinutes / 60)}h${String(minutes).padStart(2, "0")}m${String(seconds).padStart(2, "0")}s`;
14059
+ }
14060
+ /** One display rate with a real unit; absent samples stay unknown. */
14061
+ function formatInspectorRate(tokensPerSec) {
14062
+ if (tokensPerSec === void 0 || !Number.isFinite(tokensPerSec)) return MISSING;
14063
+ const text = tokensPerSec.toFixed(1);
14064
+ return `${text.endsWith(".0") ? text.slice(0, -2) : text} tok/s`;
14065
+ }
14066
+ /** Context occupancy: approximate percentage and/or used/window, independently
14067
+ * missing. The percentage is never painted without a legal denominator. */
14068
+ function contextValue(data) {
14069
+ const context = data.context;
14070
+ if (context === void 0) return MISSING;
14071
+ const parts = [];
14072
+ if (context.percent !== void 0) parts.push(`≈${context.percent}%`);
14073
+ if (context.usedTokens !== void 0) parts.push(context.windowTokens === void 0 ? `${formatTokens(context.usedTokens)} tokens` : `${formatTokens(context.usedTokens)} / ${formatTokens(context.windowTokens)}`);
14074
+ else if (context.windowTokens !== void 0) parts.push(`window ${formatTokens(context.windowTokens)}`);
14075
+ return parts.length === 0 ? MISSING : parts.join(" · ");
14076
+ }
14077
+ /** One official membership label from the proven Workspace facts, never from a
14078
+ * cwd. Unknown/unassigned/ambiguous keep their own truthful words. */
14079
+ function membershipValue(fact, workspaces, baselineProven) {
14080
+ if (fact === void 0 || !baselineProven) return "Unknown";
14081
+ switch (fact.membership.kind) {
14082
+ case "unknown": return "Unknown";
14083
+ case "unassigned": return "Unassigned";
14084
+ case "ambiguous": return `Ambiguous (${fact.membership.workspaceIds.map(sanitizedPhysicalLine).join(", ")})`;
14085
+ case "assigned": return fact.membership.workspaceIds.map((id) => {
14086
+ const workspace = workspaces.find((candidate) => candidate.workspaceId === id);
14087
+ if (workspace === void 0) return sanitizedPhysicalLine(id);
14088
+ const title = sanitizedPhysicalLine(workspace.title);
14089
+ const path = sanitizedPhysicalLine(workspace.path);
14090
+ return path === "" ? title : `${title} · ${path}`;
14091
+ }).join(" · ");
14092
+ }
14093
+ }
14094
+ /** The positive identity/state facts of one Session row. Only proven facts are
14095
+ * painted; `ing`/`live`/`current` never imply one another. */
14096
+ function stateParts(row, fact, currentSessionId) {
14097
+ const parts = [];
14098
+ if (row.id === currentSessionId) parts.push("Current");
14099
+ parts.push(row.live ? "Live" : "Persisted");
14100
+ if (fact !== void 0) {
14101
+ const status = workspaceRowStatusLabel(fact);
14102
+ if (status === "Pending · not actionable here") parts.push("Pending unverified");
14103
+ else if (status !== "") parts.push(status);
14104
+ }
14105
+ if (row.formatStatus === "migration-required") parts.push("Migration required");
14106
+ return parts;
14107
+ }
14108
+ /** The official goal objective/phase, with legal null kept as 'No goal'. */
14109
+ function goalFacts(data) {
14110
+ const goal = data.goal;
14111
+ if (goal === void 0) return [{
14112
+ label: "Goal",
14113
+ value: "Unknown"
14114
+ }, {
14115
+ label: "Goal phase",
14116
+ value: MISSING
14117
+ }];
14118
+ if (goal === null) return [{
14119
+ label: "Goal",
14120
+ value: "No goal"
14121
+ }, {
14122
+ label: "Goal phase",
14123
+ value: MISSING
14124
+ }];
14125
+ return [{
14126
+ label: "Goal",
14127
+ value: sanitizedPhysicalLine(goal.objective)
14128
+ }, {
14129
+ label: "Goal phase",
14130
+ value: goal.phase
14131
+ }];
14132
+ }
14133
+ /** The official TODO status counts, preserving legal null and unknown. */
14134
+ function todoFacts(data) {
14135
+ const todos = data.todos;
14136
+ if (todos === void 0) return [
14137
+ {
14138
+ label: "Pending",
14139
+ value: "Unknown"
14140
+ },
14141
+ {
14142
+ label: "In progress",
14143
+ value: "Unknown"
14144
+ },
14145
+ {
14146
+ label: "Completed",
14147
+ value: "Unknown"
14148
+ }
14149
+ ];
14150
+ if (todos === null) return [
14151
+ {
14152
+ label: "Pending",
14153
+ value: "No todo record"
14154
+ },
14155
+ {
14156
+ label: "In progress",
14157
+ value: MISSING
14158
+ },
14159
+ {
14160
+ label: "Completed",
14161
+ value: MISSING
14162
+ }
14163
+ ];
14164
+ return [
14165
+ {
14166
+ label: "Pending",
14167
+ value: String(todos.pending)
14168
+ },
14169
+ {
14170
+ label: "In progress",
14171
+ value: String(todos.inProgress)
14172
+ },
14173
+ {
14174
+ label: "Completed",
14175
+ value: String(todos.completed)
14176
+ }
14177
+ ];
14178
+ }
14179
+ /** The complete display groups, in reading order. Roster/Activity/Workspace/
14180
+ * Lineage facts stay available while the exact cut is loading or failed; only
14181
+ * the cut-owned values become unknown. */
14182
+ function inspectorGroups(input, data) {
14183
+ const row = input.row;
14184
+ const fact = input.fact;
14185
+ const model = data?.model;
14186
+ const modelValue = model === void 0 ? MISSING : `${sanitizedPhysicalLine(model.provider)}/${sanitizedPhysicalLine(model.model)}`;
14187
+ const rosterPreset = row.preset === void 0 ? "Unknown" : `${sanitizedPhysicalLine(row.preset)} (roster)`;
14188
+ return [
14189
+ {
14190
+ id: "session",
14191
+ head: "Whole session",
14192
+ facts: [
14193
+ {
14194
+ label: "Model",
14195
+ value: modelValue
14196
+ },
14197
+ {
14198
+ label: "Effort",
14199
+ value: model?.reasoningEffort === void 0 ? MISSING : sanitizedPhysicalLine(model.reasoningEffort)
14200
+ },
14201
+ {
14202
+ label: "Preset",
14203
+ value: data?.preset === void 0 ? rosterPreset : sanitizedPhysicalLine(data.preset)
14204
+ },
14205
+ {
14206
+ label: "Context",
14207
+ value: data === void 0 ? MISSING : contextValue(data)
14208
+ }
14209
+ ]
14210
+ },
14211
+ {
14212
+ id: "activity",
14213
+ head: "Activity",
14214
+ facts: [
14215
+ {
14216
+ label: "Turns",
14217
+ value: data?.stats === void 0 ? MISSING : String(data.stats.turns)
14218
+ },
14219
+ {
14220
+ label: "Steps",
14221
+ value: data?.stats === void 0 ? MISSING : String(data.stats.steps)
14222
+ },
14223
+ {
14224
+ label: "Running",
14225
+ value: fact?.running === true ? "Yes" : fact?.running === false ? "No" : "Unknown"
14226
+ },
14227
+ {
14228
+ label: "Pending",
14229
+ value: fact === void 0 ? "Unknown" : SESSION_PENDING_LABEL[fact.pending]
14230
+ },
14231
+ {
14232
+ label: "Source",
14233
+ value: fact === void 0 ? "unknown" : SESSION_SOURCE_LABEL[fact.source]
14234
+ }
14235
+ ]
14236
+ },
14237
+ {
14238
+ id: "usage",
14239
+ head: "Token usage",
14240
+ facts: data?.usage === void 0 ? [
14241
+ {
14242
+ label: "Uncached input",
14243
+ value: MISSING
14244
+ },
14245
+ {
14246
+ label: "Output",
14247
+ value: MISSING
14248
+ },
14249
+ {
14250
+ label: "Cache read",
14251
+ value: MISSING
14252
+ },
14253
+ {
14254
+ label: "Cache write",
14255
+ value: MISSING
14256
+ },
14257
+ {
14258
+ label: "Total",
14259
+ value: MISSING
14260
+ },
14261
+ {
14262
+ label: "Cache hit",
14263
+ value: MISSING
14264
+ }
14265
+ ] : [
14266
+ {
14267
+ label: "Uncached input",
14268
+ value: formatTokens(data.usage.uncachedInputTokens)
14269
+ },
14270
+ {
14271
+ label: "Output",
14272
+ value: formatTokens(data.usage.outputTokens)
14273
+ },
14274
+ {
14275
+ label: "Cache read",
14276
+ value: formatTokens(data.usage.cacheReadTokens)
14277
+ },
14278
+ {
14279
+ label: "Cache write",
14280
+ value: formatTokens(data.usage.cacheWriteTokens)
14281
+ },
14282
+ {
14283
+ label: "Total",
14284
+ value: formatTokens(data.usage.totalTokens)
14285
+ },
14286
+ {
14287
+ label: "Cache hit",
14288
+ value: data.usage.cacheHitPct === void 0 ? MISSING : `${data.usage.cacheHitPct.toFixed(1)}%`
14289
+ }
14290
+ ]
14291
+ },
14292
+ {
14293
+ id: "performance",
14294
+ head: "Performance",
14295
+ facts: data?.stats === void 0 ? [
14296
+ {
14297
+ label: "LLM",
14298
+ value: MISSING
14299
+ },
14300
+ {
14301
+ label: "Tool",
14302
+ value: MISSING
14303
+ },
14304
+ {
14305
+ label: "Avg TTFT",
14306
+ value: MISSING
14307
+ },
14308
+ {
14309
+ label: "Decode",
14310
+ value: MISSING
14311
+ }
14312
+ ] : [
14313
+ {
14314
+ label: "LLM",
14315
+ value: formatInspectorDuration(data.stats.llmMs)
14316
+ },
14317
+ {
14318
+ label: "Tool",
14319
+ value: formatInspectorDuration(data.stats.toolMs)
14320
+ },
14321
+ {
14322
+ label: "Avg TTFT",
14323
+ value: data.stats.avgTtftMs === void 0 ? MISSING : formatInspectorDuration(data.stats.avgTtftMs)
14324
+ },
14325
+ {
14326
+ label: "Decode",
14327
+ value: formatInspectorRate(data.stats.decodeTokensPerSec)
14328
+ }
14329
+ ]
14330
+ },
14331
+ {
14332
+ id: "workspace",
14333
+ head: "Workspace & dates",
14334
+ facts: [
14335
+ {
14336
+ label: "Workspace",
14337
+ value: membershipValue(fact, input.workspaces, input.workspaceBaselineProven)
14338
+ },
14339
+ {
14340
+ label: "Created in",
14341
+ value: row.cwd === void 0 ? "Unknown" : sanitizedPhysicalLine(row.cwd)
14342
+ },
14343
+ {
14344
+ label: "Effective cwd",
14345
+ value: data?.effectiveCwd === void 0 ? "Unknown" : sanitizedPhysicalLine(data.effectiveCwd)
14346
+ },
14347
+ {
14348
+ label: "Created",
14349
+ value: row.createdAt === void 0 ? "Unknown" : new Date(row.createdAt).toISOString()
14350
+ },
14351
+ {
14352
+ label: "Updated",
14353
+ value: new Date(row.updatedAt).toISOString()
14354
+ }
14355
+ ]
14356
+ },
14357
+ {
14358
+ id: "goal",
14359
+ head: "Goal & todo",
14360
+ facts: data === void 0 ? [
14361
+ {
14362
+ label: "Goal",
14363
+ value: "Unknown"
14364
+ },
14365
+ {
14366
+ label: "Goal phase",
14367
+ value: MISSING
14368
+ },
14369
+ {
14370
+ label: "Pending",
14371
+ value: "Unknown"
14372
+ },
14373
+ {
14374
+ label: "In progress",
14375
+ value: "Unknown"
14376
+ },
14377
+ {
14378
+ label: "Completed",
14379
+ value: "Unknown"
14380
+ }
14381
+ ] : [...goalFacts(data), ...todoFacts(data)]
14382
+ },
14383
+ {
14384
+ id: "lineage",
14385
+ head: "Lineage",
14386
+ facts: [{
14387
+ label: "Parent session",
14388
+ value: row.parentSession === void 0 ? "No parent session" : sanitizedPhysicalLine(row.parentSession)
14389
+ }]
14390
+ },
14391
+ ...input.excerpt?.snippet === void 0 ? [] : [{
14392
+ id: "excerpt",
14393
+ head: `Host search excerpt · ${input.excerpt.source}`,
14394
+ facts: [{
14395
+ label: "Matching content",
14396
+ value: sanitizedPhysicalLine(input.excerpt.snippet)
14397
+ }],
14398
+ prose: true
14399
+ }]
14400
+ ];
14401
+ }
14402
+ /** The compact selected-preview groups. Only facts the current cut really
14403
+ * carries are listed; a missing goal/todo/parent/model adds no fake entry, and
14404
+ * the roster preset/parent hints stay visibly labelled. Relative freshness is
14405
+ * the row's own `Updated` line, so the compact view never repeats ISO time. */
14406
+ function summaryGroupsOf(input, data, row) {
14407
+ const groups = [];
14408
+ if (input.excerpt !== void 0) groups.push({
14409
+ id: "excerpt",
14410
+ head: `Match · ${input.excerpt.source}`,
14411
+ facts: input.excerpt.snippet === void 0 ? [] : [{
14412
+ label: "Matching content",
14413
+ value: sanitizedPhysicalLine(input.excerpt.snippet)
14414
+ }],
14415
+ prose: true
14416
+ });
14417
+ const modelFacts = [];
14418
+ if (data?.model !== void 0) {
14419
+ modelFacts.push({
14420
+ label: "Model",
14421
+ value: `${sanitizedPhysicalLine(data.model.provider)}/${sanitizedPhysicalLine(data.model.model)}`
14422
+ });
14423
+ if (data.model.reasoningEffort !== void 0) modelFacts.push({
14424
+ label: "Effort",
14425
+ value: sanitizedPhysicalLine(data.model.reasoningEffort)
14426
+ });
14427
+ }
14428
+ const preset = data?.preset !== void 0 ? sanitizedPhysicalLine(data.preset) : row.preset === void 0 ? void 0 : `${sanitizedPhysicalLine(row.preset)} (roster)`;
14429
+ if (preset !== void 0) modelFacts.push({
14430
+ label: "Preset",
14431
+ value: preset
14432
+ });
14433
+ if (data?.context !== void 0) {
14434
+ const context = contextValue(data);
14435
+ if (context !== MISSING) modelFacts.push({
14436
+ label: "Context",
14437
+ value: context
14438
+ });
14439
+ }
14440
+ if (modelFacts.length > 0) groups.push({
14441
+ id: "model-context",
14442
+ head: "Model & Context",
14443
+ facts: modelFacts
14444
+ });
14445
+ const activityFacts = [];
14446
+ if (data?.stats !== void 0) {
14447
+ activityFacts.push({
14448
+ label: "Turns",
14449
+ value: String(data.stats.turns)
14450
+ });
14451
+ activityFacts.push({
14452
+ label: "Steps",
14453
+ value: String(data.stats.steps)
14454
+ });
13626
14455
  }
13627
- const listIds = classified.filter((fact) => inScope(fact, input.scope, currentWorkspaceId, input.workspaceBaselineProven)).sort(orderOf).map((fact) => fact.sessionId);
13628
- const groups = [];
13629
- if (input.workspaceBaselineProven) {
13630
- for (const workspace of input.workspaces) {
13631
- const ids = classified.filter((fact) => fact.membership.kind === "assigned" && fact.membership.workspaceIds[0] === workspace.workspaceId).sort(orderOf).map((fact) => fact.sessionId);
13632
- groups.push({
13633
- workspaceId: workspace.workspaceId,
13634
- title: workspace.title,
13635
- path: workspace.path,
13636
- ids
13637
- });
13638
- }
13639
- const ambiguous = classified.filter((fact) => fact.membership.kind === "ambiguous").sort(orderOf).map((fact) => fact.sessionId);
13640
- const unassigned = classified.filter((fact) => fact.membership.kind === "unassigned").sort(orderOf).map((fact) => fact.sessionId);
13641
- if (ambiguous.length > 0) groups.push({
13642
- workspaceId: "ambiguous",
13643
- title: "Membership ambiguous",
13644
- path: "",
13645
- ids: ambiguous
14456
+ if (data?.goal !== null && data?.goal !== void 0) activityFacts.push({
14457
+ label: "Goal phase",
14458
+ value: sanitizedPhysicalLine(data.goal.phase)
14459
+ });
14460
+ if (data?.todos !== null && data?.todos !== void 0) {
14461
+ const total = data.todos.pending + data.todos.inProgress + data.todos.completed;
14462
+ activityFacts.push({
14463
+ label: "Todo",
14464
+ value: `${data.todos.completed}/${total}`
13646
14465
  });
13647
- if (unassigned.length > 0) groups.push({
13648
- workspaceId: "unassigned",
13649
- title: "Unassigned",
13650
- path: "",
13651
- ids: unassigned
14466
+ }
14467
+ if (row.parentSession !== void 0) activityFacts.push({
14468
+ label: "Parent",
14469
+ value: sanitizedPhysicalLine(shortSessionId(row.parentSession))
14470
+ });
14471
+ if (activityFacts.length > 0) groups.push({
14472
+ id: "activity-goal",
14473
+ head: "Activity & Goal",
14474
+ facts: activityFacts
14475
+ });
14476
+ const usageFacts = [];
14477
+ if (data?.usage !== void 0) {
14478
+ usageFacts.push({
14479
+ label: "Total",
14480
+ value: formatTokens(data.usage.totalTokens)
14481
+ });
14482
+ if (data.usage.cacheHitPct !== void 0) usageFacts.push({
14483
+ label: "Cache hit",
14484
+ value: `${data.usage.cacheHitPct.toFixed(1)}%`
14485
+ });
14486
+ usageFacts.push({
14487
+ label: "Output",
14488
+ value: formatTokens(data.usage.outputTokens)
13652
14489
  });
13653
- const priorityWorkspaceId = currentWorkspaceId ?? input.nextCreateWorkspaceId;
13654
- if (priorityWorkspaceId !== void 0) {
13655
- const priorityIndex = groups.findIndex((group) => group.workspaceId === priorityWorkspaceId);
13656
- if (priorityIndex > 0) groups.unshift(...groups.splice(priorityIndex, 1));
13657
- }
13658
14490
  }
13659
- let outsideAttention = { kind: "none" };
13660
- if (input.scope.kind !== "all" && input.scope.kind !== "pending") {
13661
- let count = 0;
13662
- let unknown = false;
13663
- for (const fact of classified) {
13664
- if (inScope(fact, input.scope, currentWorkspaceId, input.workspaceBaselineProven)) continue;
13665
- if (fact.answerable) {
13666
- count += 1;
13667
- continue;
13668
- }
13669
- if (fact.pending !== "none") unknown = true;
13670
- }
13671
- outsideAttention = unknown ? { kind: "unknown" } : {
13672
- kind: "count",
13673
- count
14491
+ if (data?.stats !== void 0) usageFacts.push({
14492
+ label: "LLM",
14493
+ value: formatInspectorDuration(data.stats.llmMs)
14494
+ });
14495
+ if (usageFacts.length > 0) groups.push({
14496
+ id: "usage",
14497
+ head: "Usage",
14498
+ facts: usageFacts
14499
+ });
14500
+ return groups;
14501
+ }
14502
+ /** Build the ONE display projection of the selected Session's Inspector. */
14503
+ function buildSessionInspectorView(input) {
14504
+ const row = input.row;
14505
+ const inspector = input.inspector;
14506
+ const matching = inspector !== void 0 && inspector.sessionId === row.id && (inspector.state !== "ready" || inspector.data.sessionId === row.id) ? inspector : void 0;
14507
+ const rosterTitle = row.title === void 0 || row.title.trim() === "" ? void 0 : sanitizedPhysicalLine(row.title);
14508
+ const stateLabel = stateParts(row, input.fact, input.currentSessionId).join(" · ");
14509
+ const identityState = `${row.id === input.currentSessionId ? "Current session" : row.live ? "Live session" : "Persisted session"}${row.formatStatus === "migration-required" ? " · Migration required" : ""}`;
14510
+ const data = matching?.state === "ready" ? matching.data : void 0;
14511
+ const title = data?.title === void 0 ? rosterTitle ?? sanitizedPhysicalLine(shortSessionId(row.id)) : sanitizedPhysicalLine(data.title);
14512
+ const groups = inspectorGroups(input, data);
14513
+ const base = {
14514
+ sessionId: row.id,
14515
+ fullId: sanitizedPhysicalLine(row.id),
14516
+ shortId: sanitizedPhysicalLine(shortSessionId(row.id)),
14517
+ title,
14518
+ stateLabel,
14519
+ identityState,
14520
+ freshness: `Updated ${formatSessionAge(row.updatedAt)}`,
14521
+ summaryGroups: summaryGroupsOf(input, data, row)
14522
+ };
14523
+ if (matching === void 0 || matching.state === "loading") return {
14524
+ ...base,
14525
+ state: "loading",
14526
+ notice: "Loading statistics…",
14527
+ groups
14528
+ };
14529
+ if (matching.state !== "ready") {
14530
+ const notice = matching.state === "unavailable" ? "Statistics unavailable" : matching.state === "denied" ? "Access denied" : matching.state === "migration-required" ? "Migration required" : `Statistics failed: ${sanitizedPhysicalLine(matching.message)}`;
14531
+ return {
14532
+ ...base,
14533
+ state: matching.state,
14534
+ notice,
14535
+ groups
13674
14536
  };
13675
14537
  }
13676
14538
  return {
13677
- groups,
13678
- listIds,
13679
- rowsById,
13680
- outsideAttention,
13681
- currentWorkspaceId,
13682
- nextCreateWorkspaceId: input.nextCreateWorkspaceId,
13683
- workspaceBaselineProven: input.workspaceBaselineProven
14539
+ ...base,
14540
+ state: matching.refreshing ? "refreshing" : "ready",
14541
+ notice: matching.refreshing ? "Refreshing" : "",
14542
+ groups
13684
14543
  };
13685
14544
  }
13686
14545
  //#endregion
@@ -15018,358 +15877,6 @@ function planVisualPlacement(input) {
15018
15877
  definitions
15019
15878
  };
15020
15879
  }
15021
- /** Create ONE recall kernel (TSP I-A). */
15022
- function createHistoryRecallScope() {
15023
- /** The recall projection, newest first — what ↑/↓ can recall and what
15024
- * {@link HistoryRecallScope.snapshot} reports. */
15025
- const snapshot = [];
15026
- /**
15027
- * The SCOPE-BOUND TEMPORARY SUBMISSIONS of the OPEN scope, in submission
15028
- * order (newest first): one entry per input accepted by
15029
- * {@link HistoryRecallScope.rememberAccepted} for the scope's owner, each
15030
- * carrying its own OCCURRENCE token. A Session's hydration reseeds recall
15031
- * from the session-scoped JSONL rows, while a submission's own append is
15032
- * ordered behind the session transition (the submit FIFO turn and
15033
- * `ensureSession()`), so a submission accepted inside the
15034
- * publication→hydration window is absent from the snapshot and would be
15035
- * wiped by the reseed.
15036
- *
15037
- * The list is the scope's TRUE submission sequence and is never re-ordered
15038
- * or shrunk; the write owner settles OCCURRENCES into
15039
- * {@link scopeSettlements}, never into this list. The whole list is dropped
15040
- * only when the scope is replaced (or consumed by its owner's reseed / the
15041
- * pool's adoption).
15042
- */
15043
- const scopeInputs = [];
15044
- /**
15045
- * The ordered settlements of the OPEN scope (oldest first): one report per
15046
- * settled submission, produced by the session-history owner from the SAME
15047
- * synchronous stack as its append (or from its policy skip). The order is
15048
- * the APPEND order, which is the file's row order — the authoritative order
15049
- * of the rows the reseed snapshot carries. This queue is bounded, so it is
15050
- * NOT the authority for "was this occurrence settled"; that fact lives in
15051
- * {@link scopeSettled}.
15052
- */
15053
- const scopeSettlements = [];
15054
- /**
15055
- * The DURABLE per-occurrence settlement fact of the OPEN scope, keyed by the
15056
- * occurrence token: which outcome settled it and the session id its row
15057
- * carried. Bounded by the scope's own occurrences (never by the queue), so a
15058
- * settlement the queue evicted can neither resurrect the occurrence nor lose
15059
- * it.
15060
- */
15061
- const scopeSettled = /* @__PURE__ */ new Map();
15062
- /** The LIVE occurrence tokens of the open scope: the durable facts above are
15063
- * kept for exactly these (bounded by the scope cap, never by the queue). */
15064
- const scopeOccurrences = /* @__PURE__ */ new Set();
15065
- /** The number of APPENDS this scope's settlements reported per row owner —
15066
- * the exact watermark of how many of the snapshot's newest rows the window
15067
- * owns, even for settlements the bounded queue evicted. */
15068
- const scopeAppends = /* @__PURE__ */ new Map();
15069
- /**
15070
- * The recent successful WRITTEN settlements of the OPEN scope, per row
15071
- * owner, in the writer's true synchronous append order (oldest first). This
15072
- * is the only authority for the cold-seed prefix: `ts` can never reproduce
15073
- * this order. Bounded to {@link INPUT_RECALL_LIMIT} per owner; skips and
15074
- * tokenless writers are included because they are real appends.
15075
- */
15076
- const scopeWritten = /* @__PURE__ */ new Map();
15077
- /**
15078
- * The number of positions the last recall reconcile visited — a
15079
- * HEADLESS-TEST HOOK pinning the frozen plan's O(100) bound (never read by
15080
- * production code).
15081
- */
15082
- let reconcileSteps = 0;
15083
- /** The next occurrence token (monotonic per process/mount; only equality
15084
- * matters). */
15085
- let scopeTokenSeq = 0;
15086
- /**
15087
- * The owner the OPEN scope's entries were accepted for (`undefined` = the
15088
- * sessionless pool). The pool is a real scope: a deferred start and the
15089
- * Remote startup resume both accept input before any hydration reseeds the
15090
- * recall, and the first published owner ADOPTS the pool's entries (that
15091
- * submission is persisted under the new Session, so the snapshot cannot
15092
- * carry it yet).
15093
- */
15094
- let scopeOwner = void 0;
15095
- /** Whether a recall scope is open. Open at construction (the sessionless
15096
- * pool); closed by the owning owner's hydration reseed commit. */
15097
- let scopeOpen = true;
15098
- /** Drop every durable trace of one occurrence the scope no longer holds. */
15099
- const forgetScopeInput = (entry) => {
15100
- scopeOccurrences.delete(entry.token);
15101
- scopeSettled.delete(entry.token);
15102
- };
15103
- /** The number of runs of consecutive identical text in the scope. */
15104
- const countScopeRuns = () => {
15105
- let runs = 0;
15106
- let previous;
15107
- for (const entry of scopeInputs) if (entry.text !== previous) {
15108
- runs += 1;
15109
- previous = entry.text;
15110
- }
15111
- return runs;
15112
- };
15113
- /**
15114
- * APPEND entries (newest first) into the recall snapshot with the SAME
15115
- * semantics the PiTui editor + mirror always used: only CONSECUTIVE
15116
- * duplicates collapse, the cap keeps the newest 100. Non-consecutive
15117
- * repeats like `['a', 'b', 'a']` are legal history and survive.
15118
- */
15119
- const appendSnapshot = (entries) => {
15120
- let last;
15121
- for (const entry of entries) {
15122
- const trimmed = entry.trim();
15123
- if (trimmed === "" || trimmed === last) continue;
15124
- last = trimmed;
15125
- snapshot.push(trimmed);
15126
- }
15127
- if (snapshot.length > 100) snapshot.length = 100;
15128
- };
15129
- const snapshotOf = () => [...snapshot];
15130
- const rememberAccepted = (text) => {
15131
- const trimmed = text.trim();
15132
- if (trimmed === "") return void 0;
15133
- if (snapshot[0] !== trimmed) {
15134
- snapshot.unshift(trimmed);
15135
- if (snapshot.length > 100) snapshot.pop();
15136
- }
15137
- if (!scopeOpen) return void 0;
15138
- scopeTokenSeq += 1;
15139
- const token = scopeTokenSeq;
15140
- const entry = {
15141
- owner: scopeOwner,
15142
- token,
15143
- text: trimmed
15144
- };
15145
- const head = scopeInputs[0];
15146
- if (head !== void 0 && head.text === trimmed) {
15147
- let runStart = scopeInputs.length;
15148
- for (let index = 0; index < scopeInputs.length; index += 1) if (scopeInputs[index].text !== trimmed) {
15149
- runStart = index;
15150
- break;
15151
- }
15152
- const first = scopeInputs[runStart - 1];
15153
- const older = scopeInputs.slice(runStart);
15154
- for (let index = 0; index < runStart - 1; index += 1) forgetScopeInput(scopeInputs[index]);
15155
- scopeInputs.length = 0;
15156
- scopeInputs.push(entry, first, ...older);
15157
- scopeOccurrences.add(token);
15158
- return token;
15159
- }
15160
- scopeInputs.unshift(entry);
15161
- scopeOccurrences.add(token);
15162
- if (countScopeRuns() > 100) {
15163
- const oldest = scopeInputs[scopeInputs.length - 1];
15164
- let runStart = scopeInputs.length - 1;
15165
- while (runStart > 0 && scopeInputs[runStart - 1].text === oldest.text) runStart -= 1;
15166
- for (let index = scopeInputs.length - 1; index >= runStart; index -= 1) forgetScopeInput(scopeInputs[index]);
15167
- scopeInputs.length = runStart;
15168
- }
15169
- return token;
15170
- };
15171
- const seed = (entries) => {
15172
- appendSnapshot(entries);
15173
- };
15174
- /**
15175
- * Record ONE settlement of the OPEN scope, in append order. The input-history
15176
- * owner calls this from the SAME synchronous stack as its append (the detached
15177
- * task's factory is invoked synchronously) and ALSO when its write policy
15178
- * skips a submission, and it carries the submission's occurrence token
15179
- * whenever the settled submission was a scope Enter. That token — not the
15180
- * text — is what attributes the settlement to exactly one occurrence, so
15181
- * repeated identical submissions stay distinguishable, and the ordering of
15182
- * the settled submissions is what places them against every other
15183
- * session-history writer (a steer, a shell line, a sessionless command).
15184
- */
15185
- const settle = (settlement) => {
15186
- if (!scopeOpen) return;
15187
- const appendsBefore = scopeAppends.get(settlement.owner) ?? 0;
15188
- if (settlement.outcome === "written") {
15189
- scopeAppends.set(settlement.owner, appendsBefore + 1);
15190
- const written = scopeWritten.get(settlement.owner) ?? [];
15191
- written.push({
15192
- writeId: settlement.writeId,
15193
- text: settlement.text
15194
- });
15195
- if (written.length > 100) written.shift();
15196
- scopeWritten.set(settlement.owner, written);
15197
- }
15198
- if (settlement.token !== void 0 && scopeOccurrences.has(settlement.token)) scopeSettled.set(settlement.token, {
15199
- owner: settlement.owner,
15200
- outcome: settlement.outcome,
15201
- appendsBefore
15202
- });
15203
- scopeSettlements.push(settlement);
15204
- if (scopeSettlements.length > 100) scopeSettlements.shift();
15205
- };
15206
- /**
15207
- * REPLACE the whole recall projection with the entries of the CURRENT
15208
- * workspace. Session switches must not recall the previous workspace's
15209
- * inputs nor pollute the new workspace's persisted history, so the host
15210
- * resets on every session change. The OPEN scope's occurrences ride along:
15211
- * every successful write keeps its own row once, a policy-skipped occurrence
15212
- * is inserted where its settlement placed it, and a still-unsettled
15213
- * occurrence keeps its rank in the scope's submission order. The commit
15214
- * closes the scope, so ordinary submissions use the plain
15215
- * {@link rememberAccepted} path again.
15216
- * @param entries - the new workspace's persisted entries, newest first.
15217
- * @param owner - the owner whose hydration committed this reseed. The
15218
- * sessionless boot seed passes no owner: it only seeds the recall pool and
15219
- * leaves the scope open (boot is not a published Session).
15220
- */
15221
- const reset = (entries, owner, writeIds) => {
15222
- if (writeIds !== void 0 && writeIds.length !== entries.length) throw new Error("history recall reset: writeIds must stay positionally aligned with entries");
15223
- let seedEntries = entries;
15224
- if (owner !== void 0 && writeIds !== void 0) {
15225
- const written = scopeWritten.get(owner) ?? [];
15226
- const writtenText = /* @__PURE__ */ new Map();
15227
- for (const item of written) {
15228
- if (item.writeId === void 0) throw new Error("history recall reset: a written settlement of the open scope carries no writeId");
15229
- writtenText.set(item.writeId, item.text);
15230
- }
15231
- const baseline = [];
15232
- for (let index = 0; index < entries.length; index += 1) {
15233
- const writeId = writeIds[index];
15234
- if (writeId !== void 0 && writtenText.get(writeId) === entries[index]) continue;
15235
- baseline.push(entries[index]);
15236
- }
15237
- const normalized = [...written].reverse().map((item) => item.text);
15238
- normalized.push(...baseline);
15239
- seedEntries = normalized.slice(0, 100);
15240
- }
15241
- snapshot.length = 0;
15242
- if (owner === void 0) {
15243
- appendSnapshot(seedEntries);
15244
- return;
15245
- }
15246
- const settlements = scopeSettlements.filter((settlement) => settlement.owner === owner);
15247
- const retainedTokens = /* @__PURE__ */ new Set();
15248
- let retainedWrites = 0;
15249
- for (const settlement of settlements) {
15250
- if (settlement.outcome === "written") retainedWrites += 1;
15251
- if (settlement.token !== void 0) retainedTokens.add(settlement.token);
15252
- }
15253
- const covered = Math.min(scopeAppends.get(owner) ?? 0, seedEntries.length);
15254
- const ranks = /* @__PURE__ */ new Map();
15255
- for (let index = 0; index < scopeInputs.length; index += 1) ranks.set(scopeInputs[index].token, index);
15256
- const windowTexts = [];
15257
- const windowRanks = [];
15258
- const windowRows = [];
15259
- let writeSeen = 0;
15260
- for (let index = settlements.length - 1; index >= 0; index -= 1) {
15261
- const settlement = settlements[index];
15262
- const rank = settlement.token === void 0 ? void 0 : ranks.get(settlement.token);
15263
- if (settlement.outcome === "written") {
15264
- writeSeen += 1;
15265
- if (writeSeen > covered) continue;
15266
- windowTexts.push(seedEntries[writeSeen - 1]);
15267
- } else {
15268
- if (rank === void 0) continue;
15269
- windowTexts.push(scopeInputs[rank].text);
15270
- }
15271
- windowRanks.push(rank);
15272
- windowRows.push(settlement.outcome === "written");
15273
- }
15274
- for (let row = retainedWrites; row < covered; row += 1) {
15275
- windowTexts.push(seedEntries[row]);
15276
- windowRanks.push(void 0);
15277
- windowRows.push(true);
15278
- }
15279
- const before = [];
15280
- const after = [];
15281
- for (let index = 0; index < scopeInputs.length; index += 1) {
15282
- const token = scopeInputs[index].token;
15283
- if (retainedTokens.has(token)) continue;
15284
- const settled = scopeSettled.get(token);
15285
- if (settled === void 0) before.push(index);
15286
- else if (settled.outcome === "skipped" && settled.owner === owner) after.push({
15287
- rank: index,
15288
- newerRows: covered - settled.appendsBefore
15289
- });
15290
- }
15291
- after.sort((left, right) => left.newerRows - right.newerRows || left.rank - right.rank);
15292
- reconcileSteps = 0;
15293
- const merged = [];
15294
- let next = 0;
15295
- let rowsSeen = 0;
15296
- let skipped = 0;
15297
- const emitEvictedSkips = (upTo) => {
15298
- while (skipped < after.length && after[skipped].newerRows <= upTo) {
15299
- merged.push(scopeInputs[after[skipped].rank].text);
15300
- skipped += 1;
15301
- }
15302
- };
15303
- for (let index = 0; index < windowTexts.length; index += 1) {
15304
- reconcileSteps += 1;
15305
- const windowRank = windowRanks[index];
15306
- while (next < before.length && (windowRank === void 0 || before[next] < windowRank)) {
15307
- reconcileSteps += 1;
15308
- merged.push(scopeInputs[before[next]].text);
15309
- next += 1;
15310
- }
15311
- emitEvictedSkips(rowsSeen);
15312
- merged.push(windowTexts[index]);
15313
- if (windowRows[index] === true) {
15314
- rowsSeen += 1;
15315
- emitEvictedSkips(rowsSeen);
15316
- }
15317
- }
15318
- while (next < before.length) {
15319
- reconcileSteps += 1;
15320
- merged.push(scopeInputs[before[next]].text);
15321
- next += 1;
15322
- }
15323
- emitEvictedSkips(covered);
15324
- appendSnapshot([...merged, ...seedEntries.slice(covered)]);
15325
- scopeInputs.length = 0;
15326
- scopeSettlements.length = 0;
15327
- scopeSettled.clear();
15328
- scopeOccurrences.clear();
15329
- scopeAppends.clear();
15330
- scopeWritten.clear();
15331
- scopeOpen = false;
15332
- scopeOwner = owner;
15333
- };
15334
- /**
15335
- * Open the RECALL SCOPE of the owner a commit section is publishing (ordinary
15336
- * transition, fork adoption) or creating (the first Session). The owner's
15337
- * hydration reseeds recall from its disk rows afterwards, so inputs accepted
15338
- * in that gap belong to the new owner and must survive the reseed.
15339
- * A REPLACED owner's pending submissions are dropped with the scope — that is
15340
- * what keeps Session A's input out of Session B's recall — while the
15341
- * SESSIONLESS pool's entries are ADOPTED by the first published owner (that
15342
- * submission is persisted under the new Session; there is no outgoing owner
15343
- * to fence).
15344
- */
15345
- const begin = (owner) => {
15346
- if (scopeOwner !== void 0) {
15347
- scopeInputs.length = 0;
15348
- scopeSettlements.length = 0;
15349
- scopeSettled.clear();
15350
- scopeOccurrences.clear();
15351
- scopeAppends.clear();
15352
- scopeWritten.clear();
15353
- }
15354
- snapshot.length = 0;
15355
- appendSnapshot(scopeInputs.filter((entry) => {
15356
- const settled = scopeSettled.get(entry.token);
15357
- return settled === void 0 || settled.owner === owner;
15358
- }).map((entry) => entry.text));
15359
- scopeOwner = owner;
15360
- scopeOpen = true;
15361
- };
15362
- return {
15363
- snapshot: snapshotOf,
15364
- rememberAccepted,
15365
- seed,
15366
- begin,
15367
- reset,
15368
- settle,
15369
- reconcileStepsForTest: () => reconcileSteps,
15370
- scopeFactCountForTest: () => scopeSettled.size
15371
- };
15372
- }
15373
15880
  //#endregion
15374
15881
  //#region src/client/history/reverse-reader.ts
15375
15882
  /**
@@ -16295,29 +16802,378 @@ function shellCommandIsOpen(lines) {
16295
16802
  index += 2;
16296
16803
  continue;
16297
16804
  }
16298
- if (character === "<" && line[index + 1] === "<") {
16299
- const parsed = heredocAt(line, index);
16300
- if (parsed !== void 0) {
16301
- declared.push(parsed);
16805
+ if (character === "<" && line[index + 1] === "<") {
16806
+ const parsed = heredocAt(line, index);
16807
+ if (parsed !== void 0) {
16808
+ declared.push(parsed);
16809
+ index += 2;
16810
+ continue;
16811
+ }
16812
+ }
16813
+ if (substitution > 0) {
16814
+ if (character === "(") substitution += 1;
16815
+ else if (character === ")") substitution -= 1;
16816
+ index += 1;
16817
+ continue;
16818
+ }
16819
+ if (brace > 0) {
16820
+ if (character === "{") brace += 1;
16821
+ else if (character === "}") brace -= 1;
16822
+ }
16823
+ index += 1;
16824
+ }
16825
+ if (!trailingContinuation && declared.length > 0) bodies.push(...declared.splice(0, declared.length));
16826
+ }
16827
+ return quote !== void 0 || backtick || substitution > 0 || brace > 0 || declared.length > 0 || bodies.length > 0 || trailingContinuation;
16828
+ }
16829
+ /**
16830
+ * The PowerShell literal-path adaptation. A PowerShell Host shell has no
16831
+ * command/variable candidate source in this version, so ONLY a clearly
16832
+ * delimited single-line literal path token may reach the Host path bridge.
16833
+ * Backslash is an ordinary filename character in PowerShell; a single-quoted
16834
+ * literal is always literal (`''` is one apostrophe); double-quoted content is
16835
+ * accepted only while it stays literal (no `$` interpolation and no backtick
16836
+ * escape anywhere in the token). Variable/subexpression/backtick/here-string/
16837
+ * mixed quoting and multi-line continuations yield no candidates at all.
16838
+ */
16839
+ /** The finite quote classes recognized by PowerShell's parser
16840
+ * (`CharTraits.IsSingleQuote` / `IsDoubleQuote`). This adapter only lets an
16841
+ * ASCII quote DELIMIT a raw token; recognized smart single quotes may appear
16842
+ * as doubled literal content, exactly as the adapter itself emits them. */
16843
+ const POWERSHELL_SINGLE_QUOTE_CHARACTERS = /* @__PURE__ */ new Set([
16844
+ "'",
16845
+ "‘",
16846
+ "’",
16847
+ "‚",
16848
+ "‛"
16849
+ ]);
16850
+ const POWERSHELL_DOUBLE_QUOTE_CHARACTERS = /* @__PURE__ */ new Set([
16851
+ "\"",
16852
+ "“",
16853
+ "”",
16854
+ "„"
16855
+ ]);
16856
+ function isPowerShellSingleQuoteCharacter(character) {
16857
+ return character !== void 0 && POWERSHELL_SINGLE_QUOTE_CHARACTERS.has(character);
16858
+ }
16859
+ function isPowerShellDoubleQuoteCharacter(character) {
16860
+ return character !== void 0 && POWERSHELL_DOUBLE_QUOTE_CHARACTERS.has(character);
16861
+ }
16862
+ /** One bare PowerShell word delimiter; unquoted whitespace and PowerShell
16863
+ * control operators/commas end the word. */
16864
+ function isPowerShellWordDelimiter(character) {
16865
+ return character === " " || character === " " || character === "\n" || character === ";" || character === "|" || character === "&" || character === "(" || character === ")" || character === "{" || character === "}" || character === "<" || character === ">" || character === ",";
16866
+ }
16867
+ /** Find the closing ASCII quote after `from`, honoring a doubled quote of the
16868
+ * SAME recognized class. A single smart delimiter is returned as the close;
16869
+ * the caller refuses it because only an ASCII delimiter is unambiguous here. */
16870
+ function findPowerShellClosingQuote(line, from, quote) {
16871
+ for (let index = from; index < line.length; index += 1) {
16872
+ const character = line[index];
16873
+ if (quote === "'") {
16874
+ if (!isPowerShellSingleQuoteCharacter(character)) continue;
16875
+ if (line[index + 1] === character) {
16876
+ index += 1;
16877
+ continue;
16878
+ }
16879
+ return index;
16880
+ }
16881
+ if (character === "`") {
16882
+ index += 1;
16883
+ continue;
16884
+ }
16885
+ if (character === "\"") {
16886
+ if (line[index + 1] === "\"") {
16887
+ index += 1;
16888
+ continue;
16889
+ }
16890
+ return index;
16891
+ }
16892
+ if (isPowerShellDoubleQuoteCharacter(character)) return index;
16893
+ }
16894
+ return -1;
16895
+ }
16896
+ function powerShellWordRole(line, prefixLength, tokenStart) {
16897
+ let index = prefixLength;
16898
+ let firstWord = "";
16899
+ let priorWords = 0;
16900
+ let current = "";
16901
+ let started = false;
16902
+ let quote;
16903
+ let initialCall = false;
16904
+ const finish = () => {
16905
+ if (!started) return;
16906
+ priorWords += 1;
16907
+ if (firstWord === "") firstWord = current;
16908
+ current = "";
16909
+ started = false;
16910
+ };
16911
+ while (index < tokenStart) {
16912
+ const character = line[index];
16913
+ if (quote === "'") {
16914
+ if (isPowerShellSingleQuoteCharacter(character)) {
16915
+ if (line[index + 1] === character) {
16916
+ current += character;
16917
+ index += 2;
16918
+ continue;
16919
+ }
16920
+ if (character !== "'") return { kind: "unavailable" };
16921
+ quote = void 0;
16922
+ index += 1;
16923
+ continue;
16924
+ }
16925
+ current += character;
16926
+ index += 1;
16927
+ continue;
16928
+ }
16929
+ if (quote === "\"") {
16930
+ if (character === "`" || character === "$") return { kind: "unavailable" };
16931
+ if (character === "\"") {
16932
+ if (line[index + 1] === "\"") {
16933
+ current += "\"";
16934
+ index += 2;
16935
+ continue;
16936
+ }
16937
+ quote = void 0;
16938
+ index += 1;
16939
+ continue;
16940
+ }
16941
+ if (isPowerShellDoubleQuoteCharacter(character)) return { kind: "unavailable" };
16942
+ current += character;
16943
+ index += 1;
16944
+ continue;
16945
+ }
16946
+ if (character === " " || character === " " || character === "\n" || character === ",") {
16947
+ finish();
16948
+ index += 1;
16949
+ continue;
16950
+ }
16951
+ if (character === "&") {
16952
+ if (priorWords === 0 && !started && current === "" && !initialCall && (index + 1 === line.length || line[index + 1] === " " || line[index + 1] === " ")) {
16953
+ initialCall = true;
16954
+ index += 1;
16955
+ continue;
16956
+ }
16957
+ return { kind: "unavailable" };
16958
+ }
16959
+ if (character === ";" || character === "|" || character === "(" || character === ")" || character === "{" || character === "}" || character === "<" || character === ">") return { kind: "unavailable" };
16960
+ if (character === "'" || character === "\"") {
16961
+ if (started) return { kind: "unavailable" };
16962
+ started = true;
16963
+ quote = character;
16964
+ index += 1;
16965
+ continue;
16966
+ }
16967
+ if (isPowerShellSingleQuoteCharacter(character) || isPowerShellDoubleQuoteCharacter(character)) return { kind: "unavailable" };
16968
+ if (character === "`" || character === "$") return { kind: "unavailable" };
16969
+ if (!started && (character === "#" || line.startsWith("--%", index) || character === "@" || character === "[")) return { kind: "unavailable" };
16970
+ current += character;
16971
+ started = true;
16972
+ index += 1;
16973
+ }
16974
+ if (quote !== void 0) return { kind: "unavailable" };
16975
+ finish();
16976
+ if (initialCall && priorWords === 0) return { kind: "callArgument" };
16977
+ if (priorWords === 0) return { kind: "command" };
16978
+ return {
16979
+ kind: "argument",
16980
+ firstWord,
16981
+ priorWords
16982
+ };
16983
+ }
16984
+ function scanPowerShellWord(line, prefixLength, col) {
16985
+ let tokenStart = prefixLength;
16986
+ let value = "";
16987
+ let rawLength = 0;
16988
+ let quote;
16989
+ let startedQuoted = false;
16990
+ let closedQuote = false;
16991
+ let uncertain = false;
16992
+ let index = prefixLength;
16993
+ while (index < col) {
16994
+ const character = line[index];
16995
+ if (quote === "'") {
16996
+ if (isPowerShellSingleQuoteCharacter(character)) {
16997
+ if (line[index + 1] === character) {
16998
+ value += character;
16999
+ rawLength += 2;
17000
+ index += 2;
17001
+ continue;
17002
+ }
17003
+ quote = void 0;
17004
+ closedQuote = true;
17005
+ index += 1;
17006
+ continue;
17007
+ }
17008
+ value += character;
17009
+ rawLength += 1;
17010
+ index += 1;
17011
+ continue;
17012
+ }
17013
+ if (quote === "\"") {
17014
+ if (character === "\"") {
17015
+ if (line[index + 1] === "\"") {
17016
+ value += "\"";
17017
+ rawLength += 2;
16302
17018
  index += 2;
16303
17019
  continue;
16304
17020
  }
16305
- }
16306
- if (substitution > 0) {
16307
- if (character === "(") substitution += 1;
16308
- else if (character === ")") substitution -= 1;
17021
+ quote = void 0;
17022
+ closedQuote = true;
16309
17023
  index += 1;
16310
17024
  continue;
16311
17025
  }
16312
- if (brace > 0) {
16313
- if (character === "{") brace += 1;
16314
- else if (character === "}") brace -= 1;
17026
+ if (character === "`" || character === "$" || isPowerShellDoubleQuoteCharacter(character)) {
17027
+ uncertain = true;
17028
+ break;
16315
17029
  }
17030
+ value += character;
17031
+ rawLength += 1;
16316
17032
  index += 1;
17033
+ continue;
16317
17034
  }
16318
- if (!trailingContinuation && declared.length > 0) bodies.push(...declared.splice(0, declared.length));
17035
+ if (isPowerShellWordDelimiter(character)) {
17036
+ tokenStart = index + 1;
17037
+ value = "";
17038
+ rawLength = 0;
17039
+ quote = void 0;
17040
+ startedQuoted = false;
17041
+ closedQuote = false;
17042
+ index += 1;
17043
+ continue;
17044
+ }
17045
+ if (rawLength === 0) {
17046
+ if (character === "#") {
17047
+ uncertain = true;
17048
+ break;
17049
+ }
17050
+ if (character === "-" && line.startsWith("--%", index)) {
17051
+ uncertain = true;
17052
+ break;
17053
+ }
17054
+ }
17055
+ if (character === "'" || character === "\"") {
17056
+ if (rawLength > 0) {
17057
+ uncertain = true;
17058
+ break;
17059
+ }
17060
+ startedQuoted = true;
17061
+ quote = character;
17062
+ rawLength += 1;
17063
+ index += 1;
17064
+ continue;
17065
+ }
17066
+ if (isPowerShellSingleQuoteCharacter(character) || isPowerShellDoubleQuoteCharacter(character)) {
17067
+ uncertain = true;
17068
+ break;
17069
+ }
17070
+ if (character === "`" || character === "$") {
17071
+ uncertain = true;
17072
+ break;
17073
+ }
17074
+ if ((character === "@" || character === "[") && rawLength === 0) {
17075
+ uncertain = true;
17076
+ break;
17077
+ }
17078
+ value += character;
17079
+ rawLength += 1;
17080
+ index += 1;
16319
17081
  }
16320
- return quote !== void 0 || backtick || substitution > 0 || brace > 0 || declared.length > 0 || bodies.length > 0 || trailingContinuation;
17082
+ if (closedQuote && quote === void 0) uncertain = true;
17083
+ if (quote === "'" && isPowerShellSingleQuoteCharacter(line[col - 1]) && line[col - 1] === line[col]) uncertain = true;
17084
+ if (quote === "\"" && (line[col - 1] === "`" || line[col - 1] === "\"" && line[col] === "\"")) uncertain = true;
17085
+ let end = col;
17086
+ if (!uncertain) {
17087
+ if (quote !== void 0) {
17088
+ const closing = findPowerShellClosingQuote(line, col, quote);
17089
+ if (closing === -1) {
17090
+ end = line.length;
17091
+ if (quote === "\"" && /[`$]/u.test(line.slice(col))) uncertain = true;
17092
+ } else {
17093
+ if (quote === "'" && line[closing] !== "'") uncertain = true;
17094
+ if (quote === "\"" && line[closing] !== "\"") uncertain = true;
17095
+ const tail = line.slice(col, closing);
17096
+ if (quote === "\"" && /[`$]/u.test(tail)) uncertain = true;
17097
+ end = closing + 1;
17098
+ if (end < line.length && !isPowerShellWordDelimiter(line[end])) uncertain = true;
17099
+ }
17100
+ } else {
17101
+ let tailIndex = col;
17102
+ while (tailIndex < line.length) {
17103
+ const character = line[tailIndex];
17104
+ if (isPowerShellWordDelimiter(character)) break;
17105
+ if (character === "$" || character === "`" || character === "'" || character === "\"" || isPowerShellSingleQuoteCharacter(character) || isPowerShellDoubleQuoteCharacter(character)) {
17106
+ uncertain = true;
17107
+ break;
17108
+ }
17109
+ tailIndex += 1;
17110
+ }
17111
+ end = tailIndex;
17112
+ }
17113
+ }
17114
+ const closingQuoteAfterCursor = quote !== void 0 && findPowerShellClosingQuote(line, col, quote) !== -1;
17115
+ return {
17116
+ start: tokenStart,
17117
+ value,
17118
+ quote,
17119
+ closingQuoteAfterCursor,
17120
+ startedQuoted,
17121
+ uncertain,
17122
+ end
17123
+ };
17124
+ }
17125
+ /** Whether a decoded PowerShell token is a literal PATH word in its proven
17126
+ * role. A bare executable command position is never admitted; only an initial
17127
+ * `&` call argument or an ordinary argument may complete. */
17128
+ function isPowerShellPathValue(value, role, startedQuoted) {
17129
+ if (role === "command" || role === "unavailable") return false;
17130
+ if (value === "") return role === "argument";
17131
+ if (!startedQuoted && value.startsWith("-")) return false;
17132
+ const pathShape = value === "." || value === ".." || value.startsWith(".\\") || value.startsWith("./") || value.startsWith("..\\") || value.startsWith("../") || value.startsWith("~") || /^[A-Za-z]:[\\/]/u.test(value) || value.includes("\\") || value.includes("/");
17133
+ if (role === "callArgument") return startedQuoted || pathShape;
17134
+ return true;
17135
+ }
17136
+ /** Parse one PowerShell `!`/`!!` line for a literal path position. */
17137
+ function powershellCompletionContext(line, col) {
17138
+ if (!line.startsWith("!")) return void 0;
17139
+ const prefixLength = line.startsWith("!!") ? 2 : 1;
17140
+ if (col < prefixLength) return void 0;
17141
+ const scan = scanPowerShellWord(line, prefixLength, col);
17142
+ if (scan.uncertain) return void 0;
17143
+ if (scan.start === col && scan.end > col) return void 0;
17144
+ const role = powerShellWordRole(line, prefixLength, scan.start);
17145
+ if (role.kind === "unavailable") return void 0;
17146
+ if (!isPowerShellPathValue(scan.value, role.kind, scan.startedQuoted)) return void 0;
17147
+ if (role.kind === "argument" && /^git$/iu.test(role.firstWord) && role.priorWords === 1) return void 0;
17148
+ return {
17149
+ kind: "paths",
17150
+ prefix: line.slice(scan.start, col),
17151
+ priorWords: [],
17152
+ word: {
17153
+ valuePrefix: scan.value,
17154
+ quote: scan.quote,
17155
+ closingQuoteAfterCursor: scan.closingQuoteAfterCursor
17156
+ }
17157
+ };
17158
+ }
17159
+ /** The RAW range one PowerShell literal-path acceptance replaces: the whole
17160
+ * current token, including a closing quote after the cursor. */
17161
+ function powershellWordRange(line, prefixLength, col) {
17162
+ const scan = scanPowerShellWord(line, prefixLength, col);
17163
+ if (scan.uncertain) return void 0;
17164
+ if (scan.start === col && scan.end > col) return void 0;
17165
+ if (powerShellWordRole(line, prefixLength, scan.start).kind === "unavailable") return void 0;
17166
+ return {
17167
+ start: scan.start,
17168
+ end: scan.end
17169
+ };
17170
+ }
17171
+ /** Encode one literal path as a PowerShell single-quoted literal. Every
17172
+ * single-quote character in the official class is a delimiter; doubling the
17173
+ * ORIGINAL character makes it literal content. Double-quote class characters
17174
+ * are plain content inside this single-quoted literal. */
17175
+ function powershellPathLiteral(value) {
17176
+ return `'${value.replace(/['\u2018\u2019\u201A\u201B]/gu, (quote) => `${quote}${quote}`)}'`;
16321
17177
  }
16322
17178
  /** The RAW range a WHOLE-WORD acceptance replaces: the raw word start, and the
16323
17179
  * raw word end. A closing quote the cursor is inside is part of the range (the
@@ -16447,7 +17303,7 @@ async function suggestShellCompletion(context, port, target, options) {
16447
17303
  items: candidates.map((candidate) => {
16448
17304
  const directory = candidate.endsWith("/") || candidate.endsWith("\\");
16449
17305
  return {
16450
- value: port.pathAuthority === "host" && context.word !== void 0 ? hostPathLiteral(candidate, context.word, directory) : candidate,
17306
+ value: port.pathAuthority === "host" && context.word !== void 0 ? port.pathLiteralDialect === "powershell" ? powershellPathLiteral(candidate) : hostPathLiteral(candidate, context.word, directory) : candidate,
16451
17307
  label: candidate
16452
17308
  };
16453
17309
  }),
@@ -17148,17 +18004,21 @@ var MentionProvider = class {
17148
18004
  const currentLine = lines[cursorLine] ?? "";
17149
18005
  const textBeforeCursor = currentLine.slice(0, cursorCol);
17150
18006
  const requestScope = this.scopeOf();
17151
- if (this.inputModeSource() !== "prompt" && cursorLine > 0 && shellCommandIsOpen(lines.slice(0, cursorLine))) {
17152
- if (generation === this.requestGeneration) this.requestSnapshot = null;
17153
- return null;
18007
+ const shellDialect = this.hostShellCompletion?.pathLiteralDialect ?? "bash";
18008
+ if (this.inputModeSource() !== "prompt" && cursorLine > 0) {
18009
+ if (shellDialect === "powershell" || shellCommandIsOpen(lines.slice(0, cursorLine))) {
18010
+ if (generation === this.requestGeneration) this.requestSnapshot = null;
18011
+ return null;
18012
+ }
17154
18013
  }
17155
18014
  const shellLine = this.virtualWireShellContext(lines, cursorLine, cursorCol) ?? {
17156
18015
  line: currentLine,
17157
18016
  cursorCol,
17158
18017
  prefixLength: 0
17159
18018
  };
17160
- const shellContext = this.hostShellCompletion === void 0 ? void 0 : shellCompletionContext(shellLine.line, shellLine.cursorCol);
17161
- if (shellContext !== void 0) {
18019
+ const shellContext = this.hostShellCompletion === void 0 ? void 0 : shellDialect === "powershell" ? powershellCompletionContext(shellLine.line, shellLine.cursorCol) : shellCompletionContext(shellLine.line, shellLine.cursorCol);
18020
+ const quietPowerShellArgument = shellDialect === "powershell" && shellContext?.kind === "paths" && shellContext.word?.valuePrefix === "" && options.force !== true;
18021
+ if (shellContext !== void 0 && !quietPowerShellArgument) {
17162
18022
  const port = this.hostShellCompletion;
17163
18023
  if (!(shellContext.kind === "paths" && port.pathAuthority === "client")) {
17164
18024
  const suggestions = await suggestShellCompletion(shellContext, port, shellCompletionTargetOf(requestScope), options);
@@ -17199,7 +18059,7 @@ var MentionProvider = class {
17199
18059
  const literalShellLine = textBeforeCursor.trimStart().startsWith("!");
17200
18060
  if (semantic !== null || literalShellLine) {
17201
18061
  const port = this.hostShellCompletion;
17202
- if (port === void 0 || port.pathAuthority === "host") return this.withRequestSnapshot(generation, requestScope, requestMode, requestLocalCwd, lines, cursorLine, cursorCol, null, false);
18062
+ if (port === void 0 || port.pathAuthority === "host" || port.pathLiteralDialect === "powershell") return this.withRequestSnapshot(generation, requestScope, requestMode, requestLocalCwd, lines, cursorLine, cursorCol, null, false);
17203
18063
  try {
17204
18064
  const result = await this.inner.getSuggestions(lines, cursorLine, cursorCol, options);
17205
18065
  return this.withRequestSnapshot(generation, requestScope, requestMode, requestLocalCwd, lines, cursorLine, cursorCol, result, false);
@@ -17451,7 +18311,8 @@ var MentionProvider = class {
17451
18311
  cursorLine,
17452
18312
  cursorCol
17453
18313
  };
17454
- const shellContext = shellCompletionContext(shellLine.line, shellLine.cursorCol);
18314
+ const shellDialect = this.hostShellCompletion?.pathLiteralDialect ?? "bash";
18315
+ const shellContext = shellDialect === "powershell" ? powershellCompletionContext(shellLine.line, shellLine.cursorCol) : shellCompletionContext(shellLine.line, shellLine.cursorCol);
17455
18316
  const wholeWordShell = shellContext?.kind === "command" || shellContext?.kind === "subcommand";
17456
18317
  const start = cursorCol - bodyPrefix.length;
17457
18318
  if (!wholeWordShell && (start < 0 || currentLine.slice(start, cursorCol) !== bodyPrefix)) return {
@@ -17484,6 +18345,25 @@ var MentionProvider = class {
17484
18345
  cursorLine,
17485
18346
  cursorCol
17486
18347
  };
18348
+ if (shellDialect === "powershell") {
18349
+ const scanPrefixLength = wire === null ? currentLine.startsWith("!!") ? 2 : 1 : wire.prefixLength;
18350
+ const range = powershellWordRange(shellLine.line, scanPrefixLength, shellLine.cursorCol);
18351
+ if (range === void 0) return {
18352
+ lines,
18353
+ cursorLine,
18354
+ cursorCol
18355
+ };
18356
+ const directory = item.label.endsWith("/") || item.label.endsWith("\\");
18357
+ const rawStart = range.start - shellLine.prefixLength;
18358
+ const rawEnd = range.end - shellLine.prefixLength;
18359
+ const newLines = [...lines];
18360
+ newLines[cursorLine] = `${currentLine.slice(0, rawStart)}${item.value}${currentLine.slice(rawEnd)}`;
18361
+ return {
18362
+ lines: newLines,
18363
+ cursorLine,
18364
+ cursorCol: rawStart + item.value.length - (directory ? 1 : 0)
18365
+ };
18366
+ }
17487
18367
  const suffix = shellWordSuffix(shellLine.line, shellLine.cursorCol, shellContext.word?.quote);
17488
18368
  const before = currentLine.slice(0, start);
17489
18369
  const after = currentLine.slice(cursorCol + suffix.length);
@@ -17696,6 +18576,12 @@ function createInstalledAutocompleteProvider(options) {
17696
18576
  /** Find the Assistant entry that owns the structural latest step. A late
17697
18577
  * durable message can append after newer process evidence, so physical array
17698
18578
  * order is not a reliable final-answer identity. */
18579
+ /**
18580
+ * The structural Assistant row owning one exact step (the LAST physical row for
18581
+ * that step). Physical position alone is not step identity: a late older-step
18582
+ * settlement can be appended after the latest-step row, so callers that need
18583
+ * the turn's latest candidate must select by step first.
18584
+ */
17699
18585
  function assistantForStep(group, step) {
17700
18586
  for (let index = group.length - 1; index >= 0; index -= 1) {
17701
18587
  const member = group[index];
@@ -18664,13 +19550,15 @@ function clusterAdjacentAmbientContext(messages) {
18664
19550
  *
18665
19551
  * A Work span may CARRY a foldable Context row as a structural part without
18666
19552
  * making it Process: the row keeps its Context semantics, its source bytes and
18667
- * its own disclosure, but no longer splits one turn's Activity/Thought. Four
19553
+ * its own disclosure, but no longer splits one turn's Activity/Thought. Seven
18668
19554
  * narrow forms qualify: a `form:'snapshot'` singleton / snapshot-only raw
18669
- * cluster, a `tool-jobs` Notice, an `agent-message` relay and a
18670
- * `subagent-settled` Notice, each of the last three with durable same-turn
18671
- * `next-step` delivery evidence. A mixed
18672
- * `instructions`/`catalog`/`snapshot` cluster and every other Notice/relay form
18673
- * stay independent Context boundaries.
19555
+ * cluster, a `tool-jobs` Notice, an `agent-message` relay, a
19556
+ * `subagent-settled` Notice, a `repeat-tool-reminder` Notice and an
19557
+ * image-bearing `ptc-mode` Context, each of the last five with durable
19558
+ * same-turn `next-step` delivery evidence, plus a complete `skill-catalog`
19559
+ * replacement that may only TRAIL an already-established same-turn Work. A
19560
+ * mixed `instructions`/`catalog`/`snapshot` cluster and every other
19561
+ * Notice/relay form stay independent Context boundaries.
18674
19562
  *
18675
19563
  * The projector is a single forward pass plus the linear ambient-clustering
18676
19564
  * pass (O(n)); wrappers are freshly allocated each call, but their
@@ -18695,12 +19583,19 @@ function clusterAdjacentAmbientContext(messages) {
18695
19583
  * {@link isFoldableSnapshotContext} inside {@link projectTranscriptStructure}.
18696
19584
  */
18697
19585
  function isTranscriptWorkMember(message) {
18698
- return "turn" in message && classifyTranscriptMessage(message).class === "process" && !isSurfacedInteractionTool(message) && !isPostTurnReplayEvidence(message);
19586
+ return transcriptTurnOf(message) !== void 0 && classifyTranscriptMessage(message).class === "process" && !isSurfacedInteractionTool(message) && !isPostTurnReplayEvidence(message);
18699
19587
  }
18700
19588
  /** Whether one row is a producer-declared Snapshot Context row (the ONE
18701
- * ambient form whose disclosure follows the surrounding Work/Thought). */
19589
+ * ambient form whose disclosure follows the surrounding Work/Thought).
19590
+ *
19591
+ * A `ptc-mode` row that declares ANY form is malformed/foreign (the real PTC
19592
+ * producer omits `form`): it must never borrow the Snapshot carriage through a
19593
+ * forged/legacy `form:'snapshot'`. The structured-media predicate remains
19594
+ * form-neutral, so such rows still render their original blocks standalone. */
18702
19595
  function isSnapshotContext(message) {
18703
- return isSurfacedContext(message) && contextFormOf(message) === "snapshot";
19596
+ if (!isSurfacedContext(message) || contextFormOf(message) !== "snapshot") return false;
19597
+ const presentation = message.contextPresentation;
19598
+ return !(presentation?.sourceKind === "ptc-mode" && presentation.formDeclared === true);
18704
19599
  }
18705
19600
  /** Per-cluster memo of {@link isSnapshotOnlyCluster}: cluster wrappers are
18706
19601
  * freshly allocated per projection pass but may be queried once per member by
@@ -18735,69 +19630,17 @@ function isFoldableSnapshotContext(message, clusterByMember) {
18735
19630
  const cluster = clusterByMember.get(message);
18736
19631
  return cluster === void 0 || isSnapshotOnlyCluster(cluster);
18737
19632
  }
18738
- /**
18739
- * Whether one row is a Working `tool-jobs` completion Notice with durable
18740
- * same-turn `next-step` delivery evidence.
18741
- *
18742
- * This is a NARROW exception, never a generic notice rule: the producer-declared
18743
- * `sourceKind === 'tool-jobs'` AND `form === 'notice'` are both required, plus
18744
- * the fold's presentation-only `sameTurnNextStep` flag derived from the durable
18745
- * `agent/inbox/spliced` insert/claim identity chain. A `next-turn` wakeup, a
18746
- * foreign/legacy log, a different producer (including `subagent-settled`) or a
18747
- * missing claim carries no flag and therefore stays an independent Context
18748
- * boundary.
18749
- */
18750
- function isWorkingToolJobsNotice(message) {
18751
- if (!isSurfacedContext(message)) return false;
18752
- const presentation = message.contextPresentation;
18753
- return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.form === "notice" && presentation.sourceKind === "tool-jobs";
18754
- }
18755
- /**
18756
- * Whether one row is a same-turn delivered Agent relay (`agent-message` +
18757
- * `relay`) with durable next-step delivery evidence.
18758
- *
18759
- * This is the narrow sibling of {@link isWorkingToolJobsNotice}: the
18760
- * producer-declared `sourceKind === 'agent-message'` AND `form === 'relay'`
18761
- * are both required, plus the fold's presentation-only `sameTurnNextStep`
18762
- * flag derived from the durable `agent/inbox/spliced` insert/claim identity
18763
- * chain. A `next-turn` wakeup, a foreign/legacy log, a crossed source/form
18764
- * pair or a missing claim carries no flag and therefore stays an independent
18765
- * Context boundary.
18766
- */
18767
- function isWorkingAgentRelay(message) {
18768
- if (!isSurfacedContext(message)) return false;
18769
- const presentation = message.contextPresentation;
18770
- return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.sourceKind === "agent-message" && presentation.form === "relay";
18771
- }
18772
- /**
18773
- * Whether one row is a same-turn delivered subagent settlement Notice
18774
- * (`subagent-settled` + `notice`) with durable next-step delivery evidence.
18775
- *
18776
- * This is the narrow sibling of {@link isWorkingToolJobsNotice}: the
18777
- * producer-declared `sourceKind === 'subagent-settled'` AND `form === 'notice'`
18778
- * are both required, plus the fold's presentation-only `sameTurnNextStep` flag
18779
- * derived from the durable `agent/inbox/spliced` insert/claim identity chain.
18780
- * The settlement's textual outcome (`completed` / `error` / `aborted` / …) is
18781
- * deliberately NOT inspected: every settlement that arrived through the same
18782
- * proven delivery is carried the same way, and its raw body is never rewritten.
18783
- * A `next-turn` wakeup, a foreign/legacy log, a crossed source/form pair or a
18784
- * missing claim carries no flag and therefore stays an independent Context
18785
- * boundary.
18786
- */
18787
- function isWorkingSubagentSettledNotice(message) {
18788
- if (!isSurfacedContext(message)) return false;
19633
+ function workContextCarriageOf(message, clusterByMember) {
19634
+ if (!isSurfacedContext(message)) return void 0;
18789
19635
  const presentation = message.contextPresentation;
18790
- return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.sourceKind === "subagent-settled" && presentation.form === "notice";
18791
- }
18792
- /**
18793
- * The complete narrow display-layer eligibility: may this Context row be
18794
- * carried by the same-turn Work/Thought instead of ending it? Only a foldable
18795
- * Snapshot, a proven Working `tool-jobs` Notice, a proven same-turn Agent
18796
- * relay or a proven same-turn subagent settlement Notice qualifies; every
18797
- * other surfaced Context remains a boundary.
18798
- */
18799
- function isFoldableWorkContext(message, clusterByMember) {
18800
- return isFoldableSnapshotContext(message, clusterByMember) || isWorkingToolJobsNotice(message) || isWorkingAgentRelay(message) || isWorkingSubagentSettledNotice(message);
19636
+ if (isFoldableSnapshotContext(message, clusterByMember)) return "thought";
19637
+ if (presentation?.sameTurnNextStep === true) {
19638
+ const sourceKind = presentation.sourceKind;
19639
+ const form = presentation.form;
19640
+ if (sourceKind === "tool-jobs" && form === "notice") return "thought";
19641
+ if (sourceKind === "agent-message" && form === "relay" || sourceKind === "subagent-settled" && form === "notice" || sourceKind === "repeat-tool-reminder" && form === "notice" || sourceKind === "ptc-mode" && form === void 0 && presentation.formDeclared !== true && isPtcImageContext(message)) return "work";
19642
+ }
19643
+ if (presentation?.completeCatalogUpdate === true && clusterByMember.get(message) === void 0) return "trailing-work";
18801
19644
  }
18802
19645
  /**
18803
19646
  * Segment one raw transcript window into canonical structural blocks.
@@ -18894,9 +19737,28 @@ function projectTranscriptStructure(messages) {
18894
19737
  }], cluster.members, cluster.turn);
18895
19738
  continue;
18896
19739
  }
18897
- if (isFoldableWorkContext(message, clustering.byMember)) {
18898
- if (runMembers.length > 0) {
18899
- if (runTurn === message.turn) {
19740
+ if (isSurfacedContext(message)) {
19741
+ const carriage = workContextCarriageOf(message, clustering.byMember);
19742
+ if (carriage === "thought" || carriage === "work") {
19743
+ if (runMembers.length > 0) {
19744
+ if (runTurn === message.turn) {
19745
+ runParts.push({
19746
+ kind: "message",
19747
+ message
19748
+ });
19749
+ runMembers.push(message);
19750
+ continue;
19751
+ }
19752
+ flush();
19753
+ }
19754
+ pushPending([{
19755
+ kind: "message",
19756
+ message
19757
+ }], [message], message.turn);
19758
+ continue;
19759
+ }
19760
+ if (carriage === "trailing-work") {
19761
+ if (runMembers.length > 0 && runTurn === message.turn) {
18900
19762
  runParts.push({
18901
19763
  kind: "message",
18902
19764
  message
@@ -18905,12 +19767,12 @@ function projectTranscriptStructure(messages) {
18905
19767
  continue;
18906
19768
  }
18907
19769
  flush();
19770
+ out.push({
19771
+ kind: "message",
19772
+ message
19773
+ });
19774
+ continue;
18908
19775
  }
18909
- pushPending([{
18910
- kind: "message",
18911
- message
18912
- }], [message], message.turn);
18913
- continue;
18914
19776
  }
18915
19777
  if (isSurfacedInteractionTool(message)) {
18916
19778
  flush();
@@ -18991,16 +19853,22 @@ function clusterByMemberOf(structure) {
18991
19853
  /**
18992
19854
  * Renderer-neutral Focus presentation projection.
18993
19855
  *
18994
- * The Focus projection over one windowed transcript (plan §12/§33): a turn with
18995
- * an initial prompt is grouped as `user(s) -> FocusActivity`; a turn with only
18996
- * same-turn steers starts with `FocusActivity` and keeps those steers in
18997
- * process order. A turn woken by injected-context keeps that LEADING prefix at
18998
- * its original foundation position before the Thought. Collapsed turns HIDE
18999
- * process rows (a committed pre-steer answer is the explicit exception) and
19000
- * expanded turns restore raw chronology with the final assistant held back.
19001
- * A foldable Context row (producer-declared Snapshot, a `tool-jobs` Notice, an
19002
- * `agent-message` relay or a `subagent-settled` Notice with durable same-turn
19003
- * next-step evidence) follows the same rule unless it shares a raw-adjacent
19856
+ * The Focus projection over one windowed transcript (plan §12/§33): ONE logical
19857
+ * turn owns ONE Thought summary. The turn's primary presentation region is its
19858
+ * maximal run of eligible rows, bridged across a bounded run of standalone
19859
+ * control rows (a command, or a source-command-correlated manual compaction)
19860
+ * only when eligible same-turn evidence continues after that run. A turn with an
19861
+ * initial prompt is grouped as `user(s) -> FocusActivity`; a turn with only
19862
+ * same-turn steers starts with `FocusActivity` and keeps those steers in process
19863
+ * order. A turn woken by injected-context keeps that LEADING prefix at its
19864
+ * original foundation position before the Thought. Collapsed turns HIDE process
19865
+ * rows (a committed pre-steer answer is the explicit exception) and expanded
19866
+ * turns restore raw chronology with the final assistant held back. A foldable
19867
+ * Context row (producer-declared Snapshot, a `tool-jobs` Notice, an
19868
+ * `agent-message` relay, a `subagent-settled` Notice, a
19869
+ * `repeat-tool-reminder` Notice or an image-bearing `ptc-mode` Context with
19870
+ * durable same-turn next-step evidence) follows the same rule unless it shares
19871
+ * a raw-adjacent
19004
19872
  * cluster with `instructions`/`catalog`: it joins the Thought instead of
19005
19873
  * becoming turn foundation, while a mixed ambient cluster keeps its indivisible
19006
19874
  * foundation position.
@@ -19021,15 +19889,75 @@ function clusterByMemberOf(structure) {
19021
19889
  * collapsed Focus reorder would otherwise lift it above the turn's held-back
19022
19890
  * final and invert the real chronology (`assistant final` → `Context
19023
19891
  * compacted`). Treating turn-less rows as BOUNDARIES makes the projection
19024
- * agree with the fold: `process A -> Thought A`, `command -> standalone`,
19025
- * `process B -> Thought B`. Both runs may still belong to one model turn (the
19026
- * run-owner component cache supports that), and the semantic disclosure
19027
- * identity stays the turn number.
19892
+ * agree with the fold: the Turn keeps its ONE summary, the command stays a
19893
+ * standalone control row (bridged only while eligible same-Turn evidence
19894
+ * continues), and any later disjoint region fails open in raw order instead of
19895
+ * minting a second Thought. All of those rows may belong to one model turn; the
19896
+ * semantic disclosure identity stays the turn number.
19028
19897
  */
19029
19898
  function focusProjectionTurnOf(message) {
19030
19899
  if (message.kind === "command") return void 0;
19031
19900
  if (message.kind === "compaction" && message.sourceCommand !== void 0) return void 0;
19032
- return "turn" in message ? message.turn : void 0;
19901
+ return transcriptTurnOf(message);
19902
+ }
19903
+ /**
19904
+ * The settled latest-step Assistant that is still the PENDING final of an open
19905
+ * Turn, or undefined when it has authoritative continuation evidence (the Fold's
19906
+ * step/continuation fact), is committed, has display blocks, or is not settled.
19907
+ */
19908
+ function focusPendingFinal(rows, activity) {
19909
+ if (activity === void 0 || activity.completed) return void 0;
19910
+ const latestStep = assistantLatestStepOf(activity);
19911
+ if (latestStep === void 0) return void 0;
19912
+ const latestAssistant = assistantForStep(rows, latestStep);
19913
+ if (latestAssistant === void 0 || !assistantStepSettledOf(activity, latestAssistant) || latestAssistant.displayBlocks !== void 0 || assistantCommittedBeforeSteer(activity, latestAssistant) || assistantStepIntermediateOf(activity, latestAssistant)) return void 0;
19914
+ return latestAssistant;
19915
+ }
19916
+ /** The turn's PRIMARY presentation region derived from the canonical raw
19917
+ * window: the same `focusPrimaryRegion` the projection emits. Used by the live
19918
+ * tail placement so a SUPPRESSED pending final still answers by region
19919
+ * membership, never by its own identity. */
19920
+ function focusPrimaryRegionOfTurn(messages, activities, turn) {
19921
+ const activity = activities.get(turn);
19922
+ const rows = focusRowsByTurn(messages).get(turn);
19923
+ if (activity === void 0 || rows === void 0) return void 0;
19924
+ const startMessage = messages.find((message) => focusProjectionTurnOf(message) === turn && !isPostTurnReplayEvidence(message));
19925
+ if (startMessage === void 0) return void 0;
19926
+ const start = messages.indexOf(startMessage);
19927
+ if (start < 0) return void 0;
19928
+ return focusPrimaryRegion(messages, start, turn, eligibleFinalAssistant(activity, rows));
19929
+ }
19930
+ /** Every message the ACTUAL all-expanded Focus projection can materialize on
19931
+ * the current preset: top-level rows plus members of a materialized Work span.
19932
+ * A suppressed pending/final row is absent; a Work emitted raw by a fail-open
19933
+ * region contributes no span. Search reveal/root grants use this so a
19934
+ * nonrecoverable hidden row mints no ancestor. */
19935
+ function focusMaterializedMessages(messages, activities) {
19936
+ const out = /* @__PURE__ */ new Set();
19937
+ for (const block of projectFocus(messages, activities, new Set(activities.keys()), true)) if (block.kind === "message") out.add(block.message);
19938
+ else if (block.kind === "work") for (const member of block.span.members) out.add(member);
19939
+ return out;
19940
+ }
19941
+ /**
19942
+ * The row a turn's expanded Focus holds back / emits as its final, per turn:
19943
+ * the qualified final once `turn/end` authoritatively qualifies it, otherwise
19944
+ * the still-pending latest-step Assistant. One rows pass; consumers use it to
19945
+ * recognize the final by IDENTITY instead of `assistant without containerPath`.
19946
+ */
19947
+ function focusHeldBackFinalByTurn(messages, activities) {
19948
+ const out = /* @__PURE__ */ new Map();
19949
+ for (const [turn, rows] of focusRowsByTurn(messages)) {
19950
+ const activity = activities.get(turn);
19951
+ if (activity === void 0) continue;
19952
+ const final = eligibleFinalAssistant(activity, rows);
19953
+ if (final !== void 0) {
19954
+ out.set(turn, final.message);
19955
+ continue;
19956
+ }
19957
+ const pending = focusPendingFinal(rows, activity);
19958
+ if (pending !== void 0) out.set(turn, pending);
19959
+ }
19960
+ return out;
19033
19961
  }
19034
19962
  /**
19035
19963
  * The Thought block for one turn: the caller-resolved TURN-LEVEL Action
@@ -19063,25 +19991,102 @@ const EMPTY_ACTION_STATS = {
19063
19991
  types: /* @__PURE__ */ new Map()
19064
19992
  };
19065
19993
  /**
19994
+ * Whether one turn-less row is a standalone control-plane row the shared region
19995
+ * policy may bridge: a `kind:'command'` lifecycle, or a manual compaction card
19996
+ * already fused with the exact command that owns it (`sourceCommand`). No other
19997
+ * turn-less row is transparent — a window summary, a replay artifact and an
19998
+ * unrelated compaction boundary all end the region.
19999
+ */
20000
+ function isFocusBridgeControlRow(message) {
20001
+ return message.kind === "command" || message.kind === "compaction" && message.sourceCommand !== void 0;
20002
+ }
20003
+ /**
20004
+ * Every eligible row of each projection turn, in window order. Post-turn replay
20005
+ * evidence is transcript evidence, NOT turn identity: it may neither open nor
20006
+ * join a Focus root, so it is omitted here and emitted standalone. One linear
20007
+ * pass; the final candidate and the bridge fences read these rows once.
20008
+ */
20009
+ function focusRowsByTurn(messages) {
20010
+ const byTurn = /* @__PURE__ */ new Map();
20011
+ for (const message of messages) {
20012
+ const turn = focusProjectionTurnOf(message);
20013
+ if (turn === void 0 || isPostTurnReplayEvidence(message)) continue;
20014
+ const rows = byTurn.get(turn);
20015
+ if (rows === void 0) byTurn.set(turn, [message]);
20016
+ else rows.push(message);
20017
+ }
20018
+ return byTurn;
20019
+ }
20020
+ /**
20021
+ * Segment the primary presentation region of one logical Turn.
20022
+ *
20023
+ * The region starts at the turn's first eligible row and continues through its
20024
+ * remaining eligible rows in raw order. A bounded, maximal run of standalone
20025
+ * control rows is consumed INTO the region only when the same turn's eligible
20026
+ * evidence resumes after that run and the run has not crossed the turn's
20027
+ * qualified final. Otherwise the region ends there: the control rows and every
20028
+ * later row of that turn render independently (a command at the window tail is
20029
+ * simply not bridged yet). A different turn, any other turn-less boundary and a
20030
+ * replay-marked row are hard fences; the bounded lookahead never scans the rest
20031
+ * of the window per row, so the whole projection stays linear.
20032
+ * @param messages - the windowed transcript.
20033
+ * @param start - the region's first eligible row index.
20034
+ * @param turn - the logical Turn being segmented.
20035
+ * @param final - the Turn's qualified final, when it has one. A final that has
20036
+ * already appeared before a control run makes that run a hard chronology
20037
+ * fence (nothing may move across it).
20038
+ */
20039
+ function focusPrimaryRegion(messages, start, turn, final) {
20040
+ const members = [messages[start]];
20041
+ let sawFinal = final !== void 0 && messages[start] === final.message;
20042
+ let index = start + 1;
20043
+ while (index < messages.length) {
20044
+ const next = messages[index];
20045
+ const nextTurn = focusProjectionTurnOf(next);
20046
+ if (nextTurn === turn) {
20047
+ if (isPostTurnReplayEvidence(next)) break;
20048
+ members.push(next);
20049
+ if (final !== void 0 && next === final.message) sawFinal = true;
20050
+ index += 1;
20051
+ continue;
20052
+ }
20053
+ if (nextTurn !== void 0 || !isFocusBridgeControlRow(next)) break;
20054
+ let runEnd = index;
20055
+ while (runEnd < messages.length) {
20056
+ const candidate = messages[runEnd];
20057
+ if (focusProjectionTurnOf(candidate) !== void 0 || !isFocusBridgeControlRow(candidate)) break;
20058
+ runEnd += 1;
20059
+ }
20060
+ const continuation = messages[runEnd];
20061
+ if (sawFinal || continuation === void 0 || focusProjectionTurnOf(continuation) !== turn || isPostTurnReplayEvidence(continuation)) break;
20062
+ for (let run = index; run < runEnd; run += 1) members.push(messages[run]);
20063
+ index = runEnd;
20064
+ }
20065
+ return {
20066
+ members,
20067
+ end: index
20068
+ };
20069
+ }
20070
+ /**
19066
20071
  * One linear pass over the window: each turn's WHOLE-TURN action aggregate
19067
- * (addendum v2 §18). Focus stats describe the turn, not the row run: a
19068
- * turn-less entry can split one turn into separate consecutive runs
19069
- * ({@link consecutiveTurnGroup}), and every Thought block of that turn must
19070
- * still report the same turn-level number — never merely its own run's.
19071
- * A search reveal / disclosure state cannot change it because none of them
19072
- * participate here. O(n) once per projection, never a per-frame rescan of an
19073
- * unchanged window.
20072
+ * (addendum v2 §18). Focus stats describe the logical Turn, not its primary
20073
+ * presentation region: bridged control rows and a fail-open later region change
20074
+ * neither the aggregate nor its loaded-window scope, and the ONE summary always
20075
+ * reports the same turn-level number. A search reveal / disclosure state cannot
20076
+ * change it because none of them participate here. O(n) once per projection,
20077
+ * never a per-frame rescan of an unchanged window.
19074
20078
  */
19075
20079
  function focusActionStatsByTurn(messages) {
19076
20080
  const accumulators = /* @__PURE__ */ new Map();
19077
20081
  for (const message of messages) {
19078
- if (!("turn" in message)) continue;
20082
+ const turn = transcriptTurnOf(message);
20083
+ if (turn === void 0) continue;
19079
20084
  const source = compactActionSourceOf(message);
19080
20085
  if (source === void 0) continue;
19081
- let accumulator = accumulators.get(message.turn);
20086
+ let accumulator = accumulators.get(turn);
19082
20087
  if (accumulator === void 0) {
19083
20088
  accumulator = newCompactActionStats();
19084
- accumulators.set(message.turn, accumulator);
20089
+ accumulators.set(turn, accumulator);
19085
20090
  }
19086
20091
  addCompactActionStats(accumulator, source);
19087
20092
  }
@@ -19095,8 +20100,8 @@ function focusActionStatsByTurn(messages) {
19095
20100
  * renders an UNQUALIFIED durable mid-turn `form:'notice'` AFTER the Thought
19096
20101
  * (visible process feedback, never inside the hidden Action candidate set),
19097
20102
  * and hides ordinary Process inside the collapsed root. A proven Working
19098
- * `tool-jobs` Notice, same-turn Agent relay or subagent settlement Notice is
19099
- * carried by that same Thought instead.
20103
+ * `tool-jobs` Notice, same-turn Agent relay, subagent settlement Notice or
20104
+ * repeat-tool-reminder Notice is carried by that same Thought instead.
19100
20105
  * Expanded Focus restores the exact raw chronology.
19101
20106
  */
19102
20107
  function projectFocus(messages, activities, expandedTurns, focusMode) {
@@ -19105,12 +20110,42 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19105
20110
  message
19106
20111
  }));
19107
20112
  const actionStatsByTurn = focusActionStatsByTurn(messages);
20113
+ const rowsByTurn = focusRowsByTurn(messages);
20114
+ const finalByTurn = /* @__PURE__ */ new Map();
20115
+ const pendingByTurn = /* @__PURE__ */ new Map();
20116
+ for (const [turn, rows] of rowsByTurn) {
20117
+ const final = eligibleFinalAssistant(activities.get(turn), rows);
20118
+ if (final !== void 0) finalByTurn.set(turn, final);
20119
+ const pending = focusPendingFinal(rows, activities.get(turn));
20120
+ if (pending !== void 0) pendingByTurn.set(turn, pending);
20121
+ }
19108
20122
  const out = [];
20123
+ const rootedTurns = /* @__PURE__ */ new Set();
19109
20124
  let index = 0;
19110
20125
  while (index < messages.length) {
19111
20126
  const message = messages[index];
19112
20127
  const turn = focusProjectionTurnOf(message);
19113
- if (turn === void 0) {
20128
+ const activity = turn === void 0 ? void 0 : activities.get(turn);
20129
+ if (turn === void 0 || activity === void 0 || isPostTurnReplayEvidence(message) || rootedTurns.has(turn)) {
20130
+ if (!isPostTurnReplayEvidence(message) && turn !== void 0 && activity !== void 0 && rootedTurns.has(turn)) {
20131
+ if (pendingByTurn.get(turn) === message) {
20132
+ index += 1;
20133
+ continue;
20134
+ }
20135
+ const qualified = finalByTurn.get(turn);
20136
+ if (qualified !== void 0 && qualified.message === message) {
20137
+ out.push(qualified.truncated ? {
20138
+ kind: "message",
20139
+ message,
20140
+ truncated: true
20141
+ } : {
20142
+ kind: "message",
20143
+ message
20144
+ });
20145
+ index += 1;
20146
+ continue;
20147
+ }
20148
+ }
19114
20149
  out.push({
19115
20150
  kind: "message",
19116
20151
  message
@@ -19118,38 +20153,26 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19118
20153
  index += 1;
19119
20154
  continue;
19120
20155
  }
19121
- const group = consecutiveTurnGroup(messages, index, turn);
19122
- index += group.length;
19123
- const activity = activities.get(turn);
19124
- if (activity === void 0) {
19125
- for (const member of group) out.push({
19126
- kind: "message",
19127
- message: member
19128
- });
19129
- continue;
19130
- }
20156
+ const final = finalByTurn.get(turn);
20157
+ const region = focusPrimaryRegion(messages, index, turn, final);
20158
+ index = region.end;
20159
+ rootedTurns.add(turn);
20160
+ const members = region.members;
20161
+ const regionFinal = final !== void 0 && members.includes(final.message) ? final : void 0;
19131
20162
  const actionStats = actionStatsByTurn.get(turn) ?? EMPTY_ACTION_STATS;
19132
20163
  const expanded = expandedTurns.has(turn);
19133
- const final = eligibleFinalAssistant(activity, group);
19134
- const isCommittedAnswer = (member) => activity !== void 0 && assistantCommittedBeforeSteer(activity, member);
19135
- let latestAssistantIndex = -1;
19136
- for (let memberIndex = group.length - 1; memberIndex >= 0; memberIndex -= 1) if (group[memberIndex]?.kind === "assistant") {
19137
- latestAssistantIndex = memberIndex;
19138
- break;
19139
- }
19140
- const latestAssistant = latestAssistantIndex < 0 ? void 0 : group[latestAssistantIndex];
19141
- const laterProcess = latestAssistantIndex < 0 ? false : group.slice(latestAssistantIndex + 1).some((member) => member.kind !== "user" && !isSurfacedContext(member));
19142
- const pendingFinalAssistant = !activity.completed && latestAssistant?.kind === "assistant" && assistantStepOf(latestAssistant) === assistantLatestStepOf(activity) && assistantStepSettledOf(activity, latestAssistant) && latestAssistant.displayBlocks === void 0 && !isCommittedAnswer(latestAssistant) && !laterProcess ? latestAssistant : void 0;
20164
+ const rootOwner = members[0];
20165
+ const isCommittedAnswer = (member) => assistantCommittedBeforeSteer(activity, member);
19143
20166
  if (expanded) {
19144
- const rootOwner = group[0];
19145
- const boundary = focusThoughtLeadBoundary(group);
19146
- for (const member of group.slice(0, boundary)) out.push({
20167
+ const boundary = focusThoughtLeadBoundary(members);
20168
+ for (const member of members.slice(0, boundary)) out.push({
19147
20169
  kind: "message",
19148
20170
  message: member
19149
20171
  });
19150
- if (activity !== void 0) out.push(...focusActivityBlock(activity, group[0], actionStats, void 0));
20172
+ out.push(...focusActivityBlock(activity, rootOwner, actionStats, void 0));
20173
+ const pendingFinalAssistant = pendingByTurn.get(turn);
19151
20174
  const emitTailRow = (member) => {
19152
- if (isFocusPersistentInputRow(member)) {
20175
+ if (isFocusPersistentInputRow(member) || isFocusBridgeControlRow(member)) {
19153
20176
  out.push({
19154
20177
  kind: "message",
19155
20178
  message: member,
@@ -19157,7 +20180,7 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19157
20180
  });
19158
20181
  return;
19159
20182
  }
19160
- if (final !== void 0 && member === final.message) return;
20183
+ if (regionFinal !== void 0 && member === regionFinal.message) return;
19161
20184
  if (member === pendingFinalAssistant) return;
19162
20185
  if (isCommittedAnswer(member)) {
19163
20186
  out.push({
@@ -19177,7 +20200,7 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19177
20200
  focusPresentationOwner: rootOwner
19178
20201
  });
19179
20202
  };
19180
- for (const block of focusExpandedTailStructure(group, boundary)) if (block.kind === "work") out.push({
20203
+ for (const block of focusExpandedTailStructure(members, boundary)) if (block.kind === "work") out.push({
19181
20204
  kind: "work",
19182
20205
  span: block.span,
19183
20206
  focusOwnerTurn: turn,
@@ -19185,75 +20208,79 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19185
20208
  });
19186
20209
  else if (block.kind === "context-cluster") for (const member of block.cluster.members) emitTailRow(member);
19187
20210
  else emitTailRow(block.message);
19188
- if (final !== void 0) out.push(final.truncated ? {
20211
+ if (regionFinal !== void 0) out.push(regionFinal.truncated ? {
19189
20212
  kind: "message",
19190
- message: final.message,
20213
+ message: regionFinal.message,
19191
20214
  truncated: true
19192
20215
  } : {
19193
20216
  kind: "message",
19194
- message: final.message
20217
+ message: regionFinal.message
19195
20218
  });
19196
20219
  continue;
19197
20220
  }
19198
- const leadBoundary = focusThoughtLeadBoundary(group);
20221
+ const leadBoundary = focusThoughtLeadBoundary(members);
19199
20222
  const foldableSnapshots = {
19200
- clusterByMember: clusterAdjacentAmbientContext(group).byMember,
19201
- workByMember: workByMemberOf(projectTranscriptStructure(group)),
19202
- thoughtOwned: activity !== void 0
20223
+ clusterByMember: clusterAdjacentAmbientContext(members).byMember,
20224
+ workByMember: workByMemberOf(projectTranscriptStructure(members)),
20225
+ thoughtOwned: true
19203
20226
  };
19204
- const firstCommittedIndex = group.findIndex(isCommittedAnswer);
20227
+ const firstCommittedIndex = members.findIndex(isCommittedAnswer);
19205
20228
  const hidden = [];
19206
20229
  const preThought = [];
19207
20230
  const postThought = [];
19208
- if (firstCommittedIndex < 0) {
19209
- for (let index = 0; index < group.length; index += 1) {
19210
- const member = group[index];
19211
- const disposition = collapsedFocusRowDisposition(member, index, leadBoundary, foldableSnapshots);
19212
- if (disposition === "pre-thought" || disposition === "post-thought") (disposition === "pre-thought" ? preThought : postThought).push(member);
19213
- else if (member.kind !== "compaction" && member !== final?.message) hidden.push(member);
20231
+ const preCommittedCompactions = [];
20232
+ if (firstCommittedIndex < 0) for (let memberIndex = 0; memberIndex < members.length; memberIndex += 1) {
20233
+ const member = members[memberIndex];
20234
+ if (isFocusBridgeControlRow(member)) {
20235
+ preThought.push(member);
20236
+ continue;
19214
20237
  }
19215
- out.push(...preThought.map((member) => ({
19216
- kind: "message",
19217
- message: member
19218
- })));
19219
- out.push(...focusActivityBlock(activity, group[0], actionStats, hidden));
19220
- out.push(...postThought.map((member) => ({
19221
- kind: "message",
19222
- message: member
19223
- })));
19224
- for (const member of group) if (member.kind === "compaction") out.push({
19225
- kind: "message",
19226
- message: member
19227
- });
19228
- } else {
19229
- const beforeCommitted = group.slice(0, firstCommittedIndex);
19230
- for (let index = 0; index < beforeCommitted.length; index += 1) {
19231
- const member = beforeCommitted[index];
19232
- const disposition = collapsedFocusRowDisposition(member, index, leadBoundary, foldableSnapshots);
19233
- if (disposition === "pre-thought" || disposition === "post-thought") (disposition === "pre-thought" ? preThought : postThought).push(member);
19234
- else if (member.kind !== "compaction") hidden.push(member);
20238
+ if (member.kind === "compaction") {
20239
+ preCommittedCompactions.push(member);
20240
+ continue;
20241
+ }
20242
+ if (regionFinal !== void 0 && member === regionFinal.message) continue;
20243
+ const disposition = collapsedFocusRowDisposition(member, memberIndex, leadBoundary, foldableSnapshots);
20244
+ if (disposition === "hidden") hidden.push(member);
20245
+ else (disposition === "pre-thought" ? preThought : postThought).push(member);
20246
+ }
20247
+ else {
20248
+ const beforeCommitted = members.slice(0, firstCommittedIndex);
20249
+ for (let memberIndex = 0; memberIndex < beforeCommitted.length; memberIndex += 1) {
20250
+ const member = beforeCommitted[memberIndex];
20251
+ if (isFocusBridgeControlRow(member)) {
20252
+ preThought.push(member);
20253
+ continue;
20254
+ }
20255
+ if (member.kind === "compaction") {
20256
+ preCommittedCompactions.push(member);
20257
+ continue;
20258
+ }
20259
+ const disposition = collapsedFocusRowDisposition(member, memberIndex, leadBoundary, foldableSnapshots);
20260
+ if (disposition === "hidden") hidden.push(member);
20261
+ else (disposition === "pre-thought" ? preThought : postThought).push(member);
19235
20262
  }
19236
20263
  const postCommittedFoldableSnapshots = {
19237
20264
  ...foldableSnapshots,
19238
20265
  thoughtOwned: false
19239
20266
  };
19240
20267
  const postCommitted = [];
19241
- for (let index = firstCommittedIndex; index < group.length; index += 1) {
19242
- const member = group[index];
19243
- if (final !== void 0 && member === final.message) continue;
19244
- if (collapsedFocusRowDisposition(member, index, leadBoundary, postCommittedFoldableSnapshots) !== "hidden" || member.kind === "compaction" || isCommittedAnswer(member)) postCommitted.push(member);
20268
+ for (let memberIndex = firstCommittedIndex; memberIndex < members.length; memberIndex += 1) {
20269
+ const member = members[memberIndex];
20270
+ if (regionFinal !== void 0 && member === regionFinal.message) continue;
20271
+ if (collapsedFocusRowDisposition(member, memberIndex, leadBoundary, postCommittedFoldableSnapshots) !== "hidden" || isFocusBridgeControlRow(member) || member.kind === "compaction" || isCommittedAnswer(member)) postCommitted.push(member);
19245
20272
  else hidden.push(member);
19246
20273
  }
19247
20274
  out.push(...preThought.map((member) => ({
19248
20275
  kind: "message",
19249
20276
  message: member
19250
20277
  })));
19251
- out.push(...focusActivityBlock(activity, group[0], actionStats, hidden));
20278
+ out.push(...focusActivityBlock(activity, rootOwner, actionStats, hidden));
19252
20279
  out.push(...postThought.map((member) => ({
19253
20280
  kind: "message",
19254
20281
  message: member
19255
20282
  })));
19256
- for (const member of beforeCommitted) if (member.kind === "compaction") out.push({
20283
+ for (const member of preCommittedCompactions) out.push({
19257
20284
  kind: "message",
19258
20285
  message: member
19259
20286
  });
@@ -19261,32 +20288,91 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19261
20288
  kind: "message",
19262
20289
  message: member
19263
20290
  });
20291
+ if (regionFinal !== void 0) out.push(regionFinal.truncated ? {
20292
+ kind: "message",
20293
+ message: regionFinal.message,
20294
+ truncated: true
20295
+ } : {
20296
+ kind: "message",
20297
+ message: regionFinal.message
20298
+ });
20299
+ continue;
19264
20300
  }
19265
- if (final !== void 0) out.push(final.truncated ? {
20301
+ out.push(...preThought.map((member) => ({
20302
+ kind: "message",
20303
+ message: member
20304
+ })));
20305
+ out.push(...focusActivityBlock(activity, rootOwner, actionStats, hidden));
20306
+ out.push(...postThought.map((member) => ({
20307
+ kind: "message",
20308
+ message: member
20309
+ })));
20310
+ for (const member of preCommittedCompactions) out.push({
19266
20311
  kind: "message",
19267
- message: final.message,
20312
+ message: member
20313
+ });
20314
+ if (regionFinal !== void 0) out.push(regionFinal.truncated ? {
20315
+ kind: "message",
20316
+ message: regionFinal.message,
19268
20317
  truncated: true
19269
20318
  } : {
19270
20319
  kind: "message",
19271
- message: final.message
20320
+ message: regionFinal.message
19272
20321
  });
19273
20322
  }
19274
20323
  return out;
19275
20324
  }
19276
20325
  /**
19277
- * The canonical structural blocks the expanded Focus TAIL consumes: one turn
19278
- * group from its Thought-lead boundary onward. The held-back final is included,
19279
- * so cluster membership is computed from exactly the raw adjacency the window
19280
- * would give. `projectFocus` emits a canonical Work span as a nested `work`
19281
- * block (F6); this exported seam lets the convergence oracle compare
20326
+ * The canonical structural blocks the expanded Focus TAIL consumes: one logical
20327
+ * Turn's primary presentation region from its Thought-lead boundary onward
20328
+ * (bridged control rows included at their raw positions). The held-back final is
20329
+ * included, so cluster membership is computed from exactly the raw adjacency the
20330
+ * window would give. `projectFocus` emits a canonical Work span as a nested
20331
+ * `work` block (F6); this exported seam lets the convergence oracle compare
19282
20332
  * Work/cluster boundary IDENTITY (owner and member objects) instead of display
19283
20333
  * strings (plan §25).
19284
- * @param group - one turn's consecutive raw messages.
19285
- * @param boundary - the group's Thought-lead boundary ({@link focusThoughtLeadBoundary}).
19286
- * Passed in so one expanded group computes the boundary once.
20334
+ * @param region - one logical Turn's primary region members, in raw order.
20335
+ * @param boundary - the region's Thought-lead boundary
20336
+ * ({@link focusThoughtLeadBoundary}). Passed in so one expanded region
20337
+ * computes the boundary once.
19287
20338
  */
19288
- function focusExpandedTailStructure(group, boundary) {
19289
- return projectTranscriptStructure(group.slice(boundary));
20339
+ function focusExpandedTailStructure(region, boundary) {
20340
+ return projectTranscriptStructure(region.slice(boundary));
20341
+ }
20342
+ /**
20343
+ * The projected live-call owner at the RAW transcript tail: the ONE root of the
20344
+ * open Turn whose PRIMARY region actually reaches the tail, plus the exact
20345
+ * canonical Work when that Work owns the call. `undefined` when the tail is an
20346
+ * independent boundary (a turn-less command/window row, replay evidence, a
20347
+ * foreign/completed Turn) or belongs to a later fail-open region of the same
20348
+ * Turn.
20349
+ *
20350
+ * PiTui and TSP use this ONE placement. The authority is the ACTUAL expanded
20351
+ * projection (the region's emitted rows/Work), never "the numeric turn of the
20352
+ * canonical tail": a later disjoint region of the same open Turn is not the
20353
+ * root's region, so its rows may not adopt the live call.
20354
+ */
20355
+ function focusLiveTailPlacement(messages, activities, expandedBlocks) {
20356
+ const expanded = expandedBlocks ?? projectFocus(messages, activities, new Set(activities.keys()), true);
20357
+ const openActivityOf = (turn) => {
20358
+ const block = expanded.find((candidate) => candidate.kind === "activity" && candidate.activity.turn === turn);
20359
+ return block?.kind === "activity" && !block.activity.completed ? block : void 0;
20360
+ };
20361
+ const trailing = projectTranscriptStructure(messages).at(-1);
20362
+ if (trailing === void 0) return void 0;
20363
+ const tailWork = trailing.kind === "work" ? trailing.span : void 0;
20364
+ const tailMessage = trailing.kind === "work" ? void 0 : trailing.kind === "message" ? trailing.message : trailing.kind === "context-cluster" ? trailing.cluster.members.at(-1) : void 0;
20365
+ const tailTurn = tailWork !== void 0 ? tailWork.turn : tailMessage !== void 0 && "turn" in tailMessage ? tailMessage.turn : void 0;
20366
+ if (tailTurn === void 0) return void 0;
20367
+ const activity = openActivityOf(tailTurn);
20368
+ if (activity === void 0) return void 0;
20369
+ if (tailWork !== void 0) return expanded.some((block) => block.kind === "work" && block.span.owner === tailWork.owner) ? {
20370
+ rootOwner: activity.owner,
20371
+ workOwner: tailWork.owner
20372
+ } : void 0;
20373
+ if (tailMessage === void 0) return void 0;
20374
+ const primary = focusPrimaryRegionOfTurn(messages, activities, tailTurn);
20375
+ return primary !== void 0 && primary.members.includes(tailMessage) ? { rootOwner: activity.owner } : void 0;
19290
20376
  }
19291
20377
  /** Rows that remain visible outside the collapsed Thought as persistent
19292
20378
  * input/context boundaries. The semantic class stays Context for injected
@@ -19299,50 +20385,25 @@ function isFocusPersistentInputRow(message) {
19299
20385
  }
19300
20386
  function collapsedFocusRowDisposition(message, index, leadBoundary, foldableSnapshots) {
19301
20387
  if (!isFocusPersistentInputRow(message)) return "hidden";
19302
- if (foldableSnapshots.thoughtOwned && index >= leadBoundary && isFoldableWorkContext(message, foldableSnapshots.clusterByMember) && (!(isWorkingAgentRelay(message) || isWorkingSubagentSettledNotice(message)) || foldableSnapshots.workByMember.has(message))) return "hidden";
20388
+ if (foldableSnapshots.thoughtOwned && index >= leadBoundary) {
20389
+ const carriage = workContextCarriageOf(message, foldableSnapshots.clusterByMember);
20390
+ if (carriage === "thought" || (carriage === "work" || carriage === "trailing-work") && foldableSnapshots.workByMember.has(message)) return "hidden";
20391
+ }
19303
20392
  if (index >= leadBoundary && isNoticeContext(message)) return "post-thought";
19304
20393
  return "pre-thought";
19305
20394
  }
19306
- /**
19307
- * One turn's maximal run of CONSECUTIVE same-turn rows starting at `start`.
19308
- * A turn-less entry (window summary) may SPLIT a turn into separate runs, and
19309
- * the projection folds each run independently — this helper is shared by the
19310
- * projection and the collapsed visibility predicate so their index and
19311
- * `focusThoughtLeadBoundary` math can never diverge on a non-monotonic window.
19312
- * @param messages - the transcript window.
19313
- * @param start - the run's first index.
19314
- * @param turn - the run's turn number.
19315
- */
19316
- /**
19317
- * The consecutive rows of ONE Focus projection turn, starting at `start`.
19318
- *
19319
- * Exported so a caller that needs the Focus disposition of a SINGLE row can
19320
- * project that turn's own group instead of the whole loaded history (the search
19321
- * seat's ancestry probe). It is the SAME segmentation `projectFocus` walks, so
19322
- * the slice and the full projection can never disagree.
19323
- */
19324
- function consecutiveTurnGroup(messages, start, turn) {
19325
- const group = [messages[start]];
19326
- let index = start + 1;
19327
- while (index < messages.length) {
19328
- const next = messages[index];
19329
- if (focusProjectionTurnOf(next) !== turn) break;
19330
- group.push(next);
19331
- index += 1;
19332
- }
19333
- return group;
19334
- }
19335
20395
  /** The Thought-lead boundary of one turn group: the prefix that stays above the
19336
20396
  * Thought. It starts after the FIRST unmarked user row when one exists; a turn
19337
20397
  * with no human user (an inject-woken / next-turn wakeup turn) starts at the
19338
20398
  * group beginning. In both cases the boundary then consumes leading surfaced
19339
- * Context rows that are NOT foldable (the wakeup cause, `instructions`,
19340
- * `catalog`, an unqualified notice or relay). The first FOLDABLE Context row
19341
- * (Snapshot, a proven Working tool-jobs Notice, Agent relay or subagent
19342
- * settlement Notice) ends the
19343
- * foundation and becomes Thought content — so a next-turn wakeup notice stays
19344
- * visible while the Snapshot and same-turn deliveries that arrive during the
19345
- * work fold with it. A mixed
20399
+ * Context rows that are NOT Thought/Work carriage candidates (the wakeup cause,
20400
+ * `instructions`, an independent or not-yet-attachable `catalog`, an
20401
+ * unqualified notice or relay). The first carried Context row (`thought` or
20402
+ * `work`) ends the foundation and becomes Thought content — so a next-turn
20403
+ * wakeup notice stays visible while the Snapshot and same-turn deliveries that
20404
+ * arrive during the work fold with it. A `trailing-work` catalog (and an
20405
+ * independent catalog) remains foundation content until a real preceding Work
20406
+ * exists and it is actually carried. A mixed
19346
20407
  * `instructions`/`catalog` + Snapshot cluster keeps its indivisible foundation
19347
20408
  * position. `llm/retry`/max-token orchestration rows are not surfaced Context,
19348
20409
  * so they never enter the prefix. Without steer metadata the first user remains
@@ -19354,7 +20415,8 @@ function focusThoughtLeadBoundary(group) {
19354
20415
  while (true) {
19355
20416
  const member = group[end];
19356
20417
  if (member === void 0 || !isSurfacedContext(member)) break;
19357
- if (isFoldableWorkContext(member, clusterByMember)) break;
20418
+ const carriage = workContextCarriageOf(member, clusterByMember);
20419
+ if (carriage === "thought" || carriage === "work") break;
19358
20420
  end += 1;
19359
20421
  }
19360
20422
  return end;
@@ -19588,7 +20650,7 @@ function summarizeWorkSpan(span) {
19588
20650
  * nothing; an equal-time following row, by contrast, is already visible and
19589
20651
  * closes the Activity from the same instant (a point span hides its duration —
19590
20652
  * a coarse clock must never leave it live). A following block with NO proven
19591
- * time (a local command card, a synthetic window summary) keeps the span out of
20653
+ * time (a Client-local shell card, a synthetic window summary) keeps the span out of
19592
20654
  * the live tail without closing it. The lookup is an exact offline 2D
19593
20655
  * dominance-min, so no ordering assumption about the Activities' starts is
19594
20656
  * needed.
@@ -19597,15 +20659,15 @@ function summarizeWorkSpan(span) {
19597
20659
  * end after its turn, so a row of a later turn can never lengthen an
19598
20660
  * already-frozen Activity.
19599
20661
  *
19600
- * KNOWN LIMIT (pinned by `test/activity-clock.test.ts` as a live/cold
19601
- * differential): the canonical Work MEMBERSHIP (which Process rows share one
19602
- * span) is decided by the fold's row ORDER, not by this clock. When cold
19603
- * hydration appends a step's settlement AFTER that step's tool rows while its
19604
- * first visible text preceded them, cold shows ONE Activity where the live fold
19605
- * showed TWO; a raw-adjacent settled-read pair is moreover MERGED by the fold's
19606
- * read grouping before any display rule could act. Converging that belongs to
19607
- * the fold's display-order authority (the `convergeStepLaneOrder` mechanism plus
19608
- * display-aware read grouping) and is tracked as a separate unit.
20662
+ * KNOWN LIMIT: the canonical Work MEMBERSHIP (which Process rows share one
20663
+ * span) is decided by the display-order authority — `projectTranscriptStructure`
20664
+ * plus the fold's lane/read-group convergence — never by this clock. A cold
20665
+ * hydration materializes a settlement at its raw log position while the live
20666
+ * lane may have projected its first visible text earlier; the existing
20667
+ * convergence mechanism and its live/cold parity tests supply the qualified
20668
+ * order. This clock derives lifetimes from the rows that authority already
20669
+ * ordered; it never reorders membership and never fabricates a boundary from
20670
+ * an unqualified row position.
19609
20671
  * @param structure - the canonical structural blocks for one window.
19610
20672
  * @param turnActivities - the folded turn boundary facts of the SAME snapshot.
19611
20673
  */
@@ -19723,8 +20785,9 @@ function interactionBoundaryOf(span) {
19723
20785
  /** The first ACTUALLY VISIBLE time of one non-Process boundary block: the
19724
20786
  * earliest reliable sidecar start among the row(s) that carry the boundary.
19725
20787
  * `undefined` means the block has no provable first-visible evidence (a
19726
- * synthetic window summary, a command row, a row the fold could not time) —
19727
- * the Activity then stays open rather than freezing at a fabricated time. */
20788
+ * synthetic window summary, or a row the fold could not time) — the Activity
20789
+ * then stays open rather than freezing at a fabricated time. A real command
20790
+ * row carries its own point sidecar and therefore closes the Activity. */
19728
20791
  function boundaryTimeOf(block) {
19729
20792
  if (block.kind === "message") return transcriptTimingOf(block.message)?.startedAt;
19730
20793
  if (block.kind === "context-cluster") {
@@ -21342,11 +22405,19 @@ function toolNode(message, key, options) {
21342
22405
  }, ...body.args, ...children, ...body.result);
21343
22406
  }
21344
22407
  /**
21345
- * The safe body of one injected Context row through the existing
21346
- * `systemContextBody` helper (never a raw `<system-reminder>` XML envelope);
21347
- * a body that is not an envelope at all is shown verbatim.
21348
- */
21349
- function contextBodyNodes(message) {
22408
+ * The safe body of one injected Context row.
22409
+ *
22410
+ * An image-bearing `ptc-mode` Context renders its ORIGINAL structured content
22411
+ * through the same ordered body path User/Assistant messages use: text blocks
22412
+ * stay text and each image block becomes its identity line plus (when the pane
22413
+ * negotiated native images) the shared `ui.image` node. The flat text is not
22414
+ * painted beside it — it carries the same markers and would duplicate them.
22415
+ * Every other Context keeps the existing `systemContextBody` XML-envelope
22416
+ * treatment (never a raw `<system-reminder>` frame), with a body that is not an
22417
+ * envelope shown verbatim.
22418
+ */
22419
+ function contextBodyNodes(message, options) {
22420
+ if (isPtcImageContext(message)) return bodyContentNodes(message.content, options);
21350
22421
  const body = systemContextBody(message.text);
21351
22422
  if (body === void 0) return [ui.md({
21352
22423
  key: "body",
@@ -21358,7 +22429,7 @@ function contextBodyNodes(message) {
21358
22429
  text: sanitizeDisplayText(body.join("\n"))
21359
22430
  })];
21360
22431
  }
21361
- function contextMemberNode(message, key) {
22432
+ function contextMemberNode(message, key, options) {
21362
22433
  const kind = contextPresentationKind(message);
21363
22434
  const head = sanitizedPhysicalLine(message.label ?? contextFormOf(message) ?? "Context");
21364
22435
  return ui.card({
@@ -21367,7 +22438,7 @@ function contextMemberNode(message, key) {
21367
22438
  }, ui.badge({
21368
22439
  key: "kind",
21369
22440
  text: kind ?? "generic"
21370
- }), ...contextBodyNodes(message));
22441
+ }), ...contextBodyNodes(message, options));
21371
22442
  }
21372
22443
  function contextClusterMemberNode(message, key, options) {
21373
22444
  const kind = contextPresentationKind(message);
@@ -21381,14 +22452,14 @@ function contextClusterMemberNode(message, key, options) {
21381
22452
  key: "identity",
21382
22453
  text: head,
21383
22454
  wrap: "none"
21384
- }), ...contextBodyNodes(message));
22455
+ }), ...contextBodyNodes(message, options));
21385
22456
  const expanded = disclosure.expandedContextRowOwners.has(message);
21386
22457
  return ui.section({
21387
22458
  key,
21388
22459
  head,
21389
22460
  collapsible: true,
21390
22461
  collapsed: !expanded
21391
- }, ...expanded ? contextBodyNodes(message) : []);
22462
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21392
22463
  }
21393
22464
  function canCollapseContextRow(message) {
21394
22465
  const kind = contextPresentationKind(message);
@@ -21445,7 +22516,7 @@ function relayContextRowNode(message, key, options, allowDisclosure) {
21445
22516
  if (!allowDisclosure || disclosure === void 0 || !canCollapseContextRow(message)) return ui.card({
21446
22517
  key,
21447
22518
  head: title
21448
- }, ...contextBodyNodes(message));
22519
+ }, ...contextBodyNodes(message, options));
21449
22520
  const expanded = disclosure.expandedContextRowOwners.has(message);
21450
22521
  const preview = relayHeadPreview(sanitizeDisplayText(message.text));
21451
22522
  return ui.section({
@@ -21470,13 +22541,13 @@ function relayContextRowNode(message, key, options, allowDisclosure) {
21470
22541
  })]),
21471
22542
  collapsible: true,
21472
22543
  collapsed: !expanded
21473
- }, ...expanded ? contextBodyNodes(message) : []);
22544
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21474
22545
  }
21475
22546
  function contextRowNode(message, key, options, allowDisclosure = true) {
21476
22547
  const disclosure = options.innerDisclosure;
21477
22548
  const kind = contextPresentationKind(message);
21478
22549
  if (message.context === true && kind === "relay") return relayContextRowNode(message, key, options, allowDisclosure);
21479
- if (message.context !== true || !allowDisclosure || disclosure === void 0 || !canCollapseContextRow(message)) return contextMemberNode(message, key);
22550
+ if (message.context !== true || !allowDisclosure || disclosure === void 0 || !canCollapseContextRow(message)) return contextMemberNode(message, key, options);
21480
22551
  const expanded = disclosure.expandedContextRowOwners.has(message);
21481
22552
  if (kind === "notice") {
21482
22553
  const title = message.label === void 0 || message.label === "" ? "Notice" : sanitizedPhysicalLine(message.label);
@@ -21496,7 +22567,7 @@ function contextRowNode(message, key, options, allowDisclosure = true) {
21496
22567
  })]),
21497
22568
  collapsible: true,
21498
22569
  collapsed: !expanded
21499
- }, ...expanded ? contextBodyNodes(message) : []);
22570
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21500
22571
  }
21501
22572
  const identity = kind === "recall" ? message.label === void 0 || message.label === "" ? "Session recall" : `Session recall · ${sanitizedPhysicalLine(message.label)}` : message.label ?? contextFormOf(message) ?? "Context";
21502
22573
  return ui.section({
@@ -21504,7 +22575,7 @@ function contextRowNode(message, key, options, allowDisclosure = true) {
21504
22575
  head: sanitizedPhysicalLine(identity),
21505
22576
  collapsible: true,
21506
22577
  collapsed: !expanded
21507
- }, ...expanded ? contextBodyNodes(message) : []);
22578
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21508
22579
  }
21509
22580
  function systemNode(message, key, options, allowDisclosure = true) {
21510
22581
  if (message.context === true) return contextRowNode(message, key, options, allowDisclosure);
@@ -22152,7 +23223,8 @@ function imageRefIdsOf(message) {
22152
23223
  if (message.displayBlocks !== void 0) {
22153
23224
  for (const display of message.displayBlocks) if (display.kind === "content") pushBlocks([display.block]);
22154
23225
  } else if (message.content !== void 0) pushBlocks(message.content);
22155
- } else if (message.kind === "tool") visitRow(message);
23226
+ } else if (message.kind === "system") pushBlocks(message.content);
23227
+ else if (message.kind === "tool") visitRow(message);
22156
23228
  imageRefIdsCache.set(message, {
22157
23229
  display,
22158
23230
  assistant,
@@ -22260,6 +23332,7 @@ function messageStampOf(message, key, options) {
22260
23332
  break;
22261
23333
  case "system":
22262
23334
  parts.push(disclosureTokenOf(message, key, options));
23335
+ parts.push(imageTokensOf(message, options));
22263
23336
  break;
22264
23337
  case "command":
22265
23338
  case "compaction":
@@ -22341,6 +23414,17 @@ function focusDuration(activity, options) {
22341
23414
  const duration = formatCompactDuration(options.focusElapsedMs?.get(activity));
22342
23415
  return duration === "0s" ? void 0 : duration;
22343
23416
  }
23417
+ /** The bounded one-line collapsed Action body the Focus root head paints (and
23418
+ * the root stamp must follow): the SAME derivation for the head and the stamp,
23419
+ * never a content hash. */
23420
+ function focusRootActionBody(action, options) {
23421
+ if (action === void 0) return void 0;
23422
+ const body = compactActionBody(compactActionPresentation(action, {
23423
+ ...options.toolPresenter === void 0 ? {} : { presenter: options.toolPresenter },
23424
+ ...options.cwd === void 0 ? {} : { cwd: options.cwd }
23425
+ }));
23426
+ return body === void 0 ? void 0 : sanitizedPhysicalLine(body);
23427
+ }
22344
23428
  function focusRootHead(slot, options) {
22345
23429
  const phase = options.focusPhase ?? "working";
22346
23430
  const duration = focusDuration(slot.activity, options);
@@ -22372,10 +23456,7 @@ function focusRootHead(slot, options) {
22372
23456
  index: preview.index,
22373
23457
  ...preview.name === void 0 ? {} : { name: preview.name }
22374
23458
  })));
22375
- const action = slot.action === void 0 ? void 0 : compactActionBody(compactActionPresentation(slot.action, {
22376
- ...options.toolPresenter === void 0 ? {} : { presenter: options.toolPresenter },
22377
- ...options.cwd === void 0 ? {} : { cwd: options.cwd }
22378
- }));
23459
+ const action = focusRootActionBody(slot.action, options);
22379
23460
  if (preparing !== void 0 || action !== void 0) head.push(ui.text({
22380
23461
  key: "action",
22381
23462
  text: sanitizedPhysicalLine(`Action: ${preparing ?? action}`),
@@ -22454,7 +23535,7 @@ function focusNestedWorkDescriptor(span, keys, options, prefix, lifetime, prepar
22454
23535
  materialize: () => focusNestedWorkNode(span, keys, options, prefix, lifetime, preparing)
22455
23536
  };
22456
23537
  }
22457
- function focusMainBlocks(blocks, keys, options, prefix, preparingByRootOwner, preparingByWorkOwner, standalonePreparing, workLifetimes) {
23538
+ function focusMainBlocks(blocks, keys, options, prefix, preparingByRootOwner, preparingByWorkOwner, standalonePreparing, attachedPreparingRootOwner, workLifetimes) {
22458
23539
  const slotsByOwner = /* @__PURE__ */ new Map();
22459
23540
  const rootsWithWorkPreparing = /* @__PURE__ */ new Set();
22460
23541
  const rows = [];
@@ -22495,11 +23576,20 @@ function focusMainBlocks(blocks, keys, options, prefix, preparingByRootOwner, pr
22495
23576
  slot.children.push(focusNestedWorkDescriptor(block.span, keys, options, prefix, workLifetimes.get(block.span.owner), preparingByWorkOwner.get(block.span.owner) ?? []));
22496
23577
  }
22497
23578
  }
23579
+ const deferredStandalone = [];
22498
23580
  for (const slot of slotsByOwner.values()) {
22499
23581
  if (!slot.expanded || slot.preparing.length === 0 || rootsWithWorkPreparing.has(slot.owner)) continue;
22500
- slot.children.push(...slot.preparing.map((preview) => preparingDescriptor(preview, options.cwd, "")));
23582
+ if (attachedPreparingRootOwner === slot.owner) {
23583
+ slot.children.push(...slot.preparing.map((preview) => preparingDescriptor(preview, options.cwd, "")));
23584
+ continue;
23585
+ }
23586
+ deferredStandalone.push(...slot.preparing);
22501
23587
  }
22502
- return [...rows.map((row) => "draft" in row ? focusRootDescriptor(row, keys, options, prefix) : row), ...standalonePreparing.map((preview) => preparingDescriptor(preview, options.cwd, prefix))];
23588
+ return [
23589
+ ...rows.map((row) => "draft" in row ? focusRootDescriptor(row, keys, options, prefix) : row),
23590
+ ...standalonePreparing.map((preview) => preparingDescriptor(preview, options.cwd, prefix)),
23591
+ ...deferredStandalone.map((preview) => preparingDescriptor(preview, options.cwd, prefix))
23592
+ ];
22503
23593
  }
22504
23594
  /** The ONE Focus Activity root descriptor (canonical occurrence owner). */
22505
23595
  function focusRootDescriptor(slot, keys, options, prefix) {
@@ -22516,6 +23606,9 @@ function focusRootDescriptor(slot, keys, options, prefix) {
22516
23606
  ];
22517
23607
  for (const preview of slot.preparing) stamp.push(...preparingStampOf(preview, options.cwd));
22518
23608
  for (const child of slot.children) stamp.push(...child.stamp);
23609
+ for (const part of compactActionStatParts(slot.actionStats)) stamp.push(sanitizedPhysicalLine(part));
23610
+ const actionBody = focusRootActionBody(slot.action, options);
23611
+ if (actionBody !== void 0) stamp.push(actionBody);
22519
23612
  if (slot.action !== void 0) stamp.push(options.cwd ?? "");
22520
23613
  return {
22521
23614
  key,
@@ -22540,48 +23633,72 @@ function focusRootDescriptor(slot, keys, options, prefix) {
22540
23633
  }
22541
23634
  };
22542
23635
  }
22543
- /** Preparing belongs either to the exact canonical trailing Work owner, to a
22544
- * root-only post-Assistant run in the same final occurrence, or stays standalone. */
23636
+ /** Preparing belongs either to the exact canonical trailing Work owner, to the
23637
+ * ONE open logical Turn whose region reaches the raw tail, or stays standalone.
23638
+ * A Turn whose collapsed summary still owns the Action slot while an independent
23639
+ * trailing control boundary sits outside its region is reported as a header-only
23640
+ * root: `attachedPreparingRootOwner` is then absent so an EXPANDED root renders
23641
+ * the live run standalone after that boundary instead of fabricating ancestry.
23642
+ */
22545
23643
  function focusPreparingPlacement(messages, blocks, options) {
22546
23644
  const groups = groupPreparingPreviews(options.preparingPreviews ?? []);
22547
23645
  if (groups.length === 0 || options.window?.hasNewer !== false) return {
22548
23646
  byRootOwner: /* @__PURE__ */ new Map(),
22549
23647
  byWorkOwner: /* @__PURE__ */ new Map(),
22550
- standalone: []
23648
+ standalone: [],
23649
+ attachedRootOwner: void 0
22551
23650
  };
22552
23651
  const activities = options.turnActivities ?? EMPTY_TURN_ACTIVITIES;
22553
23652
  const expandedBlocks = projectFocus(messages, activities, new Set(activities.keys()), true);
22554
23653
  const trailing = projectTranscriptStructure(messages).at(-1);
22555
- let rootOwner;
22556
- let workOwner;
23654
+ const placement = focusLiveTailPlacement(messages, activities, expandedBlocks);
23655
+ const placementTurn = placement === void 0 || !("turn" in placement.rootOwner) ? void 0 : placement.rootOwner.turn;
23656
+ const rootOfTurn = (turn) => {
23657
+ const projected = expandedBlocks.find((block) => block.kind === "activity" && block.activity.turn === turn);
23658
+ return projected?.kind === "activity" ? projected.owner : void 0;
23659
+ };
23660
+ const standalone = () => ({
23661
+ byRootOwner: /* @__PURE__ */ new Map(),
23662
+ byWorkOwner: /* @__PURE__ */ new Map(),
23663
+ standalone: groups.flatMap(([, previews]) => previews),
23664
+ attachedRootOwner: void 0
23665
+ });
23666
+ const selectionFor = (turn) => groups.find(([groupTurn]) => groupTurn === turn)?.[1] ?? [];
22557
23667
  let turn;
23668
+ let workOwner;
23669
+ let attachedRootOwner;
22558
23670
  if (trailing?.kind === "work") {
22559
- turn = trailing.span.turn;
22560
- if (activities.get(turn)?.completed === false) {
22561
- const projected = expandedBlocks.findLast((block) => block.kind === "work" && block.span.owner === trailing.span.owner);
22562
- if (projected?.kind === "work") {
22563
- rootOwner = projected.focusPresentationOwner;
22564
- workOwner = rootOwner === void 0 ? void 0 : trailing.span.owner;
22565
- }
22566
- }
22567
- } else {
22568
- const lastMessage = trailing?.kind === "message" ? trailing.message : trailing?.kind === "context-cluster" ? trailing.cluster.members.at(-1) : void 0;
22569
- if (lastMessage !== void 0 && "turn" in lastMessage && !(lastMessage.kind === "compaction" && lastMessage.sourceCommand !== void 0) && activities.get(lastMessage.turn)?.completed === false) {
22570
- turn = lastMessage.turn;
22571
- const projected = expandedBlocks.findLast((block) => block.kind === "activity" && block.activity.turn === turn);
22572
- rootOwner = projected?.kind === "activity" ? projected.owner : void 0;
22573
- }
23671
+ if (placement?.workOwner !== void 0 && placement.workOwner === trailing.span.owner) {
23672
+ turn = placementTurn;
23673
+ attachedRootOwner = placement.rootOwner;
23674
+ workOwner = placement.workOwner;
23675
+ }
23676
+ } else if (placement !== void 0) {
23677
+ turn = placementTurn;
23678
+ attachedRootOwner = placement.rootOwner;
23679
+ }
23680
+ if (turn === void 0) {
23681
+ const openPreviewTurn = groups.map(([groupTurn]) => groupTurn).filter((groupTurn) => activities.get(groupTurn)?.completed === false).at(-1);
23682
+ const rootOwner = openPreviewTurn === void 0 ? void 0 : rootOfTurn(openPreviewTurn);
23683
+ const selected = openPreviewTurn === void 0 ? [] : selectionFor(openPreviewTurn);
23684
+ if (rootOwner === void 0 || openPreviewTurn === void 0 || selected.length === 0 || !blocks.some((block) => block.kind === "activity" && block.owner === rootOwner)) return {
23685
+ ...standalone(),
23686
+ standalone: [...groups.filter(([groupTurn]) => groupTurn !== openPreviewTurn).flatMap(([, previews]) => previews), ...selected]
23687
+ };
23688
+ return {
23689
+ byRootOwner: /* @__PURE__ */ new Map([[rootOwner, selected]]),
23690
+ byWorkOwner: /* @__PURE__ */ new Map(),
23691
+ standalone: groups.filter(([groupTurn]) => groupTurn !== openPreviewTurn).flatMap(([, previews]) => previews),
23692
+ attachedRootOwner: void 0
23693
+ };
22574
23694
  }
22575
- if (rootOwner === void 0 || turn === void 0 || !blocks.some((block) => block.kind === "activity" && block.owner === rootOwner)) return {
22576
- byRootOwner: /* @__PURE__ */ new Map(),
22577
- byWorkOwner: /* @__PURE__ */ new Map(),
22578
- standalone: groups.flatMap(([, previews]) => previews)
22579
- };
22580
- const selected = groups.find(([groupTurn]) => groupTurn === turn)?.[1] ?? [];
23695
+ if (attachedRootOwner === void 0 || !blocks.some((block) => block.kind === "activity" && block.owner === attachedRootOwner)) return standalone();
23696
+ const selected = selectionFor(turn);
22581
23697
  return {
22582
- byRootOwner: selected.length === 0 ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map([[rootOwner, selected]]),
23698
+ byRootOwner: selected.length === 0 ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map([[attachedRootOwner, selected]]),
22583
23699
  byWorkOwner: workOwner === void 0 || selected.length === 0 ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map([[workOwner, selected]]),
22584
- standalone: groups.filter(([groupTurn]) => groupTurn !== turn).flatMap(([, previews]) => previews)
23700
+ standalone: groups.filter(([groupTurn]) => groupTurn !== turn).flatMap(([, previews]) => previews),
23701
+ attachedRootOwner
22585
23702
  };
22586
23703
  }
22587
23704
  /** The members whose current transcript body is actually materialized. */
@@ -22753,9 +23870,10 @@ function settledFinalAssistantStats(messages, activities) {
22753
23870
  if (activities === void 0) return EMPTY_ASSISTANT_STATS;
22754
23871
  const rowsByTurn = /* @__PURE__ */ new Map();
22755
23872
  for (const message of messages) {
22756
- if (!("turn" in message)) continue;
22757
- const rows = rowsByTurn.get(message.turn);
22758
- if (rows === void 0) rowsByTurn.set(message.turn, [message]);
23873
+ const turn = transcriptTurnOf(message);
23874
+ if (turn === void 0) continue;
23875
+ const rows = rowsByTurn.get(turn);
23876
+ if (rows === void 0) rowsByTurn.set(turn, [message]);
22759
23877
  else rows.push(message);
22760
23878
  }
22761
23879
  const result = /* @__PURE__ */ new Map();
@@ -22842,7 +23960,7 @@ function describeTranscriptMainBlocksForPreset(messages, keys, options) {
22842
23960
  const focusBlocks = projectFocus(messages, options.turnActivities ?? EMPTY_TURN_ACTIVITIES, options.expandedFocusTurns ?? EMPTY_TURN_SET, true);
22843
23961
  const workLifetimes = resolveWorkLifetimes(structure, options.turnActivities ?? EMPTY_TURN_ACTIVITIES);
22844
23962
  const preparing = focusPreparingPlacement(messages, focusBlocks, options);
22845
- return focusMainBlocks(focusBlocks, keys, renderOptions, prefix, preparing.byRootOwner, preparing.byWorkOwner, preparing.standalone, workLifetimes);
23963
+ return focusMainBlocks(focusBlocks, keys, renderOptions, prefix, preparing.byRootOwner, preparing.byWorkOwner, preparing.standalone, preparing.attachedRootOwner, workLifetimes);
22846
23964
  }
22847
23965
  return legacyMainBlocks(structure, keys, renderOptions, prefix, trailing, adopted, standalone);
22848
23966
  }
@@ -22881,4 +23999,4 @@ const EMPTY_TURN_SET = /* @__PURE__ */ new Set();
22881
23999
  const EMPTY_TURN_ACTIVITIES = /* @__PURE__ */ new Map();
22882
24000
  const EMPTY_ASSISTANT_STATS = /* @__PURE__ */ new Map();
22883
24001
  //#endregion
22884
- export { effectiveWorkflowRunOpen as $, welcomeWhaleGradientColors as $n, createBoundedFinderCandidateCollector as $r, askAnswersLines as $t, summarizeWorkSpan as A, SVG_TOOL_NAME as Ai, admitSvg as An, modelIdentity as Ar, authorizeSvg as At, FocusActivityComponent as B, userBlocksVisibleNow as Bi, formatSessionAge as Bn, markdownTheme as Br, workspaceRowStatusLabel as Bt, proveCaretEdit as C, textOf as Ci, toolIconSemantic as Cn, matchesKeyId as Cr, setAssistantVisualPresentation as Ct, contextClusterSummaryParts as D, transcriptSearchSourceKey as Di, webCardLines as Dn, PROVIDER_DEFAULT as Dr, visualFactLine as Dt, FocusTimingStore as E, transcriptSearchMatchKey as Ei, toolTitle as En, presetDisplayText as Er, isModelOnlyReplacement as Et, clusterByMemberOf as F, isSurfacedInteractionTool as Fi, imageProtocolPreference as Fn, sanitizeDisplaySegment as Fr, SESSION_PENDING_LABEL as Ft, compactActionSlotLine as G, historyFilePath as Gi, chooseListedSession as Gn, taskStatusWord as Gr, subagentJobTranscriptId as Gt, formatCompactDuration as H, isAssistantTokenDelta as Hi, sessionBrowserErrorNotice as Hn, setTheme as Hr, isTaskItemFailure as Ht, isFoldableWorkContext as I, latestLine as Ii, thinkingPreviewTail as In, sanitizeDisplayText as Ir, SESSION_SOURCE_LABEL as It, compactSlotLine as J, sessionRowMatchesQuery as Jn, ClientLocalDiscoveryDriver as Jr, taskRowSelectionDisposition as Jt, compactActionStatsSignature as K, loadHistoryFile as Ki, findSessionMatch as Kn, FILE_ARGUMENT_COMMANDS as Kr, subagentJobViewHint as Kt, projectTranscriptStructure as L, finalizedBlockFallbackText as Li, iconFor as Ln, HOST_MARKDOWN_OPTIONS as Lr, buildSessionWorkspaceView as Lt, consecutiveTurnGroup as M, isVisualToolName as Mi, SVG_MAX_RASTER_PIXELS as Mn, sanitizedPhysicalLine as Mr, svgDigest as Mt, focusProjectionTurnOf as N, recentTurnThreshold as Ni, SVG_MAX_RASTER_SIDE as Nn, singlePhysicalLine as Nr, chartDisplayTitle as Nt, activityClockOf as O, workflowReadablePhase as Oi, writeFoldedPreview as On, effortChoicesOf as Or, visualPartsForStatus as Ot, projectFocus as P, isSurfacedContext as Pi, SVG_RASTER_TIMEOUT_MS as Pn, sanitizeDisplayLog as Pr, chartTextRows as Pt, effectiveWorkflowPhaseOpen as Q, renderWelcomeWhaleLines as Qn, escapeFinderRegex as Qr, GOAL_TOOL_NAMES as Qt, workByMemberOf as R, openOpaqueBlockFallbackText as Ri, iconLead as Rn, color as Rr, currentWorkspaceOf as Rt, pastedBodySpan as S, subCallDisplayStatus as Si, toolCardHeader as Sn, formatLeaderSequence as Sr, clearAssistantVisualPresentation as St, isLocalShellCard as T, rawSourceRangeForNormalizedMatch as Ti, toolSummaryKeys as Tn, isBuiltInPresetRow as Tr, collectPublishedVisuals as Tt, compactActionPresentation as U, usageFromAssistantSettlement as Ui, workspaceKey as Un, settingsListTheme as Ur, projectTaskItems as Ut, compactActionStatParts as V, StepUsageAccumulator as Vi, sanitizeTerminalText as Vn, selectListTheme as Vr, isTaskItemActive as Vt, compactActionSignature as W, appendHistoryRecord as Wi, canonicalFullSessionId as Wn, taskStatusColor as Wr, rowGroup as Wt, createDisplayProjection as X, WELCOME_WHALE_WIDTH as Xn, createFinderRecordStream as Xr, viewerAccessHint as Xt, compactThinkSlotLine as Y, shortSessionId as Yn, clientPathQueryEnvironment as Yr, taskTreePrefix as Yt, advanceWorkflowDisclosureState as Z, pickWelcomeWhaleVariant as Zn, discoverForQuery as Zr, FOLDED_JSON_RESULT_TOOLS as Zt, VISUAL_COPY_ROLE as _, resolveTspNativeFooterConfig as _i, relativizeToCwd as _n, TSP_VISUAL_CHORDS as _r, FileHistorySearchSource as _t, dockDraftImageNodes as a, attachmentCountLabel as ai, foldedResultSummaryFor as an, FooterItemRegistry as ar, eligibleFinalAssistant as at, publishedVisualTitle as b, assistantStepOf as bi, subagentModelDisplay as bn, formatHintKeys as br, assistantVisualPresentation as bt, imageRefProblem as c, SessionOperationBarrier as ci, goalResultSummary as cn, HISTORY_CHORDS as cr, stripAtQuotes as ct, visibleTranscriptMembers as d, createSessionScopeAuthority as di, parseCallPreview as dn, SESSION_WORKSPACE_CHORDS as dr, splitTokenRemainder as dt, rankPathCandidates as ei, askAnswersSummary as en, welcomeWhalePlainLines as er, workflowCountsText as et, TSP_WORKFLOW_BROWSE_ACTION as f, darkColors as fi, parseImageEnvelope as fn, SVG_VIEWER_CHORDS as fr, extractInlineSkillPrefix as ft, VISUAL_COPY_KEY as g, TSP_FOOTER_NOTICES as gi, readFoldedPreview as gn, TSP_SEARCH_CHORD_LABEL as gr, shellPrefixForMode as gt, VISUAL_COPY_ACTION as h, withSearchCurrentTokens as hi, parseWriteEnvelope as hn, TSP_SEARCH_CHORD as hr, serializedDraftHasPayload as ht, describeTranscriptMainBlocksForPreset as i, QueueManagerController as ii, foldedCallPreview as in, tasksItem as ir, workflowStatusCounts as it, projectCompact as j, humanFacingVisualResult as ji, SVG_MAX_PNG_BYTES as jn, projectModelDirectory as jr, svgDetailRows as jt, resolveWorkLifetimes as k, PRESENT_VISUAL_TOOL_NAME as ki, fileAttachmentSummary as kn, initialEffortOf as kr, visualPartsFromText as kt, toolRowImageBlocks as l, TransitionInProgressError as li, imageFoldedPreview as ln, JOB_LOCAL_KEYS as lr, isOpenQuotedToken as lt, transcriptCopyPayload as m, lightColors as mi, parseSkillEnvelope as mn, TSP_CONTINUED_INSPECTION_LABEL as mr, serializeEditorInput as mt, TranscriptNodeKeys as n, resolvePathQuery as ni, compactToolPresentation as nn, createBuiltinFooterRegistry as nr, workflowRunSummaryText as nt, imageDisplayName as o, queueManagerCommandResult as oi, genericRawInputLines as on, shortCwd as or, createInstalledAutocompleteProvider as ot, TRANSCRIPT_COPY_ACTION as p, detectThemeFromBackground as pi, parseReadEnvelopes as pn, SVG_VIEWER_SCROLL_LABEL as pr, editorModeFromHistoryEntry as pt, compactPreparingSummary as q, loadHistoryRecords as qi, sanitizeSessionSearchInput as qn, suggestPathArgument as qr, taskRowLabel as qt, describeTranscriptMainBlocks as r, separatorOfRaw as ri, firstLine as rn, modelItem as rr, workflowRunViewAllVisible as rt, imageIdentityText as s, formatBytes as si, goalResultLines as sn, DELIVERED_FILES_CHORDS as sr, classifyFileCompletionContext as st, MAX_IMAGE_BLOB_BYTES as t, reattachDisplayBase as ti, compactToolExpandedLines as tn, FooterCustomItemCatalog as tr, workflowPhasePresentations as tt, toolRowProjectsImages as u, SessionScopeSupersededError as ui, isCompactActionTool as un, QUEUE_CHORDS as ur, splitQueryRemainder as ut, VISUAL_FIGURE_KEY_PREFIX as v, TranscriptFolder as vi, resultTextLines as vn, TSP_VISUAL_COPY_LABEL as vr, createHistoryRecallScope as vt, candidateImagePathFromPaste as w, TranscriptWindowController as wi, toolPresenterFrom as wn, parseShellWords as wr, asVisualSessionEvents as wt, PasteRangeTracker as x, childOwnEvents as xi, systemContextBody as xn, formatKeyId as xr, assistantVisualPresentationRevision as xt, VISUAL_FIGURE_ROLE as y, assistantPresentationRevision as yi, skillFoldedPreview as yn, TSP_VISUAL_SELECT_LABEL as yr, planVisualPlacement as yt, contextPresentationKind as z, textWithAttachmentMarkers as zi, iconPrefix as zn, editorTheme as zr, visibleWorkspaceBrowserRows as zt };
24002
+ export { advanceWorkflowDisclosureState as $, tasksItem as $n, reattachDisplayBase as $r, askAnswersLines as $t, summarizeWorkSpan as A, humanFacingVisualResult as Ai, admitSvg as An, color as Ar, visualPartsFromText as At, workContextCarriageOf as B, textWithAttachmentMarkers as Bi, formatSessionAge as Bn, singlePhysicalLine as Br, workspaceRowStatusLabel as Bt, proveCaretEdit as C, TranscriptWindowController as Ci, toolIconSemantic as Cn, builtInGuide as Cr, clearAssistantVisualPresentation as Ct, contextClusterSummaryParts as D, workflowReadablePhase as Di, webCardLines as Dn, modelIdentity as Dr, isModelOnlyReplacement as Dt, FocusTimingStore as E, transcriptSearchSourceKey as Ei, toolTitle as En, initialEffortOf as Er, collectPublishedVisuals as Et, focusProjectionTurnOf as F, isSurfacedInteractionTool as Fi, imageProtocolPreference as Fn, setTheme as Fr, chartTextRows as Ft, compactActionPresentation as G, appendHistoryRecord as Gi, WELCOME_WHALE_WIDTH as Gn, suggestPathArgument as Gr, subagentJobTranscriptId as Gt, FocusActivityComponent as H, StepUsageAccumulator as Hi, sessionBrowserErrorNotice as Hn, sanitizeDisplaySegment as Hr, isTaskItemFailure as Ht, projectFocus as I, transcriptTurnOf as Ii, thinkingPreviewTail as In, settingsListTheme as Ir, buildSessionInspectorView as It, compactActionStatsSignature as J, loadHistoryRecords as Ji, welcomeWhaleGradientColors as Jn, createFinderRecordStream as Jr, taskRowSelectionDisposition as Jt, compactActionSignature as K, historyFilePath as Ki, pickWelcomeWhaleVariant as Kn, ClientLocalDiscoveryDriver as Kr, subagentJobViewHint as Kt, clusterByMemberOf as L, latestLine as Li, iconFor as Ln, taskStatusColor as Lr, buildSessionWorkspaceView as Lt, focusHeldBackFinalByTurn as M, recentTurnThreshold as Mi, SVG_MAX_RASTER_PIXELS as Mn, editorTheme as Mr, svgDetailRows as Mt, focusLiveTailPlacement as N, isPtcImageContext as Ni, SVG_MAX_RASTER_SIDE as Nn, markdownTheme as Nr, svgDigest as Nt, activityClockOf as O, PRESENT_VISUAL_TOOL_NAME as Oi, writeFoldedPreview as On, projectModelDirectory as Or, visualFactLine as Ot, focusMaterializedMessages as P, isSurfacedContext as Pi, SVG_RASTER_TIMEOUT_MS as Pn, selectListTheme as Pr, chartDisplayTitle as Pt, createDisplayProjection as Q, modelItem as Qn, rankPathCandidates as Qr, GOAL_TOOL_NAMES as Qt, projectTranscriptStructure as R, finalizedBlockFallbackText as Ri, iconLead as Rn, taskStatusWord as Rr, currentWorkspaceOf as Rt, pastedBodySpan as S, textOf as Si, toolCardHeader as Sn, presetDisplayText as Sr, assistantVisualPresentationRevision as St, isLocalShellCard as T, transcriptSearchMatchKey as Ti, toolSummaryKeys as Tn, effortChoicesOf as Tr, asVisualSessionEvents as Tt, compactActionStatParts as U, isAssistantTokenDelta as Ui, workspaceKey as Un, sanitizeDisplayText as Ur, projectTaskItems as Ut, contextPresentationKind as V, userBlocksVisibleNow as Vi, sanitizeTerminalText as Vn, sanitizeDisplayLog as Vr, isTaskItemActive as Vt, formatCompactDuration as W, usageFromAssistantSettlement as Wi, classifySessionBrowserRow as Wn, FILE_ARGUMENT_COMMANDS as Wr, rowGroup as Wt, compactSlotLine as X, FooterCustomItemCatalog as Xn, escapeFinderRegex as Xr, viewerAccessHint as Xt, compactPreparingSummary as Y, welcomeWhalePlainLines as Yn, discoverForQuery as Yr, taskTreePrefix as Yt, compactThinkSlotLine as Z, createBuiltinFooterRegistry as Zn, createBoundedFinderCandidateCollector as Zr, FOLDED_JSON_RESULT_TOOLS as Zt, VISUAL_COPY_ROLE as _, TranscriptFolder as _i, relativizeToCwd as _n, formatKeyId as _r, serializedDraftHasPayload as _t, dockDraftImageNodes as a, queueManagerCommandResult as ai, foldedResultSummaryFor as an, JOB_SEARCH_LOCAL_KEYS as ar, workflowRunViewAllVisible as at, publishedVisualTitle as b, childOwnEvents as bi, subagentModelDisplay as bn, parseShellWords as br, planVisualPlacement as bt, imageRefProblem as c, TransitionInProgressError as ci, goalResultSummary as cn, SVG_VIEWER_CHORDS as cr, createInstalledAutocompleteProvider as ct, visibleTranscriptMembers as d, darkColors as di, parseCallPreview as dn, TSP_SEARCH_CHORD as dr, isOpenQuotedToken as dt, resolvePathQuery as ei, askAnswersSummary as en, FooterItemRegistry as er, effectiveWorkflowPhaseOpen as et, TSP_WORKFLOW_BROWSE_ACTION as f, detectThemeFromBackground as fi, parseImageEnvelope as fn, TSP_SEARCH_CHORD_LABEL as fr, splitQueryRemainder as ft, VISUAL_COPY_KEY as g, resolveTspNativeFooterConfig as gi, readFoldedPreview as gn, formatHintKeys as gr, serializeEditorInput as gt, VISUAL_COPY_ACTION as h, TSP_FOOTER_NOTICES as hi, parseWriteEnvelope as hn, TSP_VISUAL_SELECT_LABEL as hr, editorModeFromHistoryEntry as ht, describeTranscriptMainBlocksForPreset as i, attachmentCountLabel as ii, foldedCallPreview as in, JOB_LOCAL_KEYS as ir, workflowRunSummaryText as it, projectCompact as j, isVisualToolName as ji, SVG_MAX_PNG_BYTES as jn, currentPalette as jr, authorizeSvg as jt, resolveWorkLifetimes as k, SVG_TOOL_NAME as ki, fileAttachmentSummary as kn, HOST_MARKDOWN_OPTIONS as kr, visualPartsForStatus as kt, toolRowImageBlocks as l, SessionScopeSupersededError as li, imageFoldedPreview as ln, SVG_VIEWER_SCROLL_LABEL as lr, classifyFileCompletionContext as lt, transcriptCopyPayload as m, withSearchCurrentTokens as mi, parseSkillEnvelope as mn, TSP_VISUAL_COPY_LABEL as mr, extractInlineSkillPrefix as mt, TranscriptNodeKeys as n, separatorOfRaw as ni, compactToolPresentation as nn, DELIVERED_FILES_CHORDS as nr, workflowCountsText as nt, imageDisplayName as o, formatBytes as oi, genericRawInputLines as on, QUEUE_CHORDS as or, workflowStatusCounts as ot, TRANSCRIPT_COPY_ACTION as p, lightColors as pi, parseReadEnvelopes as pn, TSP_VISUAL_CHORDS as pr, splitTokenRemainder as pt, compactActionSlotLine as q, loadHistoryFile as qi, renderWelcomeWhaleLines as qn, clientPathQueryEnvironment as qr, taskRowLabel as qt, describeTranscriptMainBlocks as r, QueueManagerController as ri, firstLine as rn, HISTORY_CHORDS as rr, workflowPhasePresentations as rt, imageIdentityText as s, SessionOperationBarrier as si, goalResultLines as sn, SESSION_WORKSPACE_CHORDS as sr, eligibleFinalAssistant as st, MAX_IMAGE_BLOB_BYTES as t, resolveWindowsHostPrefix as ti, compactToolExpandedLines as tn, shortCwd as tr, effectiveWorkflowRunOpen as tt, toolRowProjectsImages as u, createSessionScopeAuthority as ui, isCompactActionTool as un, TSP_CONTINUED_INSPECTION_LABEL as ur, stripAtQuotes as ut, VISUAL_FIGURE_KEY_PREFIX as v, assistantPresentationRevision as vi, resultTextLines as vn, formatLeaderSequence as vr, shellPrefixForMode as vt, candidateImagePathFromPaste as w, rawSourceRangeForNormalizedMatch as wi, toolPresenterFrom as wn, PROVIDER_DEFAULT as wr, setAssistantVisualPresentation as wt, PasteRangeTracker as x, subCallDisplayStatus as xi, systemContextBody as xn, isBuiltInPresetRow as xr, assistantVisualPresentation as xt, VISUAL_FIGURE_ROLE as y, assistantStepOf as yi, skillFoldedPreview as yn, matchesKeyId as yr, FileHistorySearchSource as yt, workByMemberOf as z, openOpaqueBlockFallbackText as zi, iconPrefix as zn, sanitizedPhysicalLine as zr, visibleWorkspaceBrowserRows as zt };