@xmoon76/dsh-pi-tui 0.5.8 → 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 (77) hide show
  1. package/README.en.md +61 -25
  2. package/README.md +61 -25
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-CMIjGyuk.mjs → bootstrap-CVyHGQDX.mjs} +21901 -6575
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-BjGPc-DM.mjs → client-bootstrap-4UoeVIHE.mjs} +2488 -2734
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-Dult7Jxv.mjs → daemon-launcher-DxIgjBHW.mjs} +1549 -172
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/{local-profile-daemon-admin-BmQSdzT0.mjs → diagnostics-Db5iVcuJ.mjs} +3 -90
  14. package/dist/{entry-control-DjNsE3I0.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-B4uLpSTv.mjs → extensions-Dx7ncPNA.mjs} +1 -1
  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-DMNTmNrH.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 +22334 -6695
  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 +292 -63
  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-uOBfFq5j.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-egN4_gsQ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-DOSsCh9q.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +952 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DamiMqPd.mjs → local-scope-5DEKA_lW.mjs} +1023 -96
  43. package/dist/{local-transport-Iwo0mtu3.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DMrjwCkl.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-C6tSs86s.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-CstInGIA.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-EG5UqIcd.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-CpfpQO_h.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -332
  70. package/dist/{transcript-view-CuJYWkhp.mjs → transcript-view-B6vCnukn.mjs} +2096 -977
  71. package/dist/{transcript-view-C1YtJ49Y.mjs → transcript-view-DSSdE2vK.mjs} +2078 -651
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +20 -3
  74. package/dist/local-acp-listener-B65J0Bx4.mjs +0 -3115
  75. package/dist/local-daemon-control-C14q9KnD.mjs +0 -1588
  76. package/dist/local-daemon-control-TCnERL7n.mjs +0 -1424
  77. 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";
@@ -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
@@ -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
@@ -13320,11 +13643,34 @@ function subagentJobViewHint(status, detail) {
13320
13643
  }
13321
13644
  //#endregion
13322
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
+ */
13323
13668
  /** The ONE verbose pending wording shared by Peek/Details. */
13324
13669
  const SESSION_PENDING_LABEL = {
13325
13670
  question: "Question",
13326
13671
  approval: "Approval",
13327
13672
  "plan-review": "Plan review",
13673
+ "late-answer": "Late answer",
13328
13674
  none: "No pending",
13329
13675
  unknown: "Pending unknown",
13330
13676
  unavailable: "Pending unavailable",
@@ -13338,13 +13684,23 @@ const SESSION_SOURCE_LABEL = {
13338
13684
  unavailable: "unavailable",
13339
13685
  denied: "denied"
13340
13686
  };
13341
- /** The ONE compact row status: only positive, action-relevant facts. */
13687
+ /** The ONE verbose row status wording shared by Peek/Details and the panels. */
13342
13688
  function workspaceRowStatusLabel(fact) {
13343
- if (fact.priority === "needs") return fact.running === true ? "Needs attention · Working" : "Needs attention";
13344
- 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";
13345
13695
  if (fact.pending === "unverified") return "Pending · not actionable here";
13346
13696
  return "";
13347
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
+ }
13348
13704
  /** Display title collisions by the shortest unique Host path tail. The ID is a
13349
13705
  * final fallback only when Host paths themselves remain indistinguishable. */
13350
13706
  function workspaceDisplayLabels(workspaces) {
@@ -13411,9 +13767,10 @@ function visibleWorkspaceBrowserRows(model, display, selectedSessionId, currentS
13411
13767
  const facts = group.ids.map((id) => model.rowsById.get(id));
13412
13768
  const needs = facts.filter((fact) => fact.priority === "needs").length;
13413
13769
  const working = facts.filter((fact) => fact.priority === "working").length;
13770
+ const unread = facts.filter((fact) => fact.priority === "unread").length;
13414
13771
  const current = group.workspaceId === model.currentWorkspaceId;
13415
13772
  const next = group.workspaceId === model.nextCreateWorkspaceId;
13416
- const defaultExpanded = current || next || needs + working > 0;
13773
+ const defaultExpanded = current || next || needs + working + unread > 0;
13417
13774
  const expanded = display.expanded.get(group.workspaceId) ?? defaultExpanded;
13418
13775
  const groupRows = [];
13419
13776
  rows.push({
@@ -13425,6 +13782,7 @@ function visibleWorkspaceBrowserRows(model, display, selectedSessionId, currentS
13425
13782
  total: group.ids.length,
13426
13783
  needs,
13427
13784
  working,
13785
+ unread,
13428
13786
  expanded,
13429
13787
  current,
13430
13788
  next
@@ -13485,41 +13843,13 @@ function inScope(fact, scope, currentWorkspaceId, baselineProven) {
13485
13843
  case "unassigned": return baselineProven && fact.membership.kind === "unassigned";
13486
13844
  }
13487
13845
  }
13488
- /** Whether the Client-root eligibility proves THIS Client may answer the
13489
- * pending candidate the Host reported for `sessionId`. */
13490
- function provedAnswerable(fact, eligibility) {
13491
- if (fact.attentionSourceState !== "known") return false;
13492
- if (fact.attention === "approval") return eligibility?.some((entry) => entry.sessionId === fact.sessionId && entry.kind === "approval") === true;
13493
- if (fact.attention !== "question" && fact.attention !== "plan-review") return false;
13494
- if (eligibility?.some((entry) => entry.sessionId === fact.sessionId && entry.kind === "question") === true) return true;
13495
- return eligibility !== void 0 && (fact.continuedQuestionCallIds?.length ?? 0) > 0;
13496
- }
13497
- function classifyPending(activity, eligibility) {
13498
- if (activity === void 0) return {
13499
- pending: "unknown",
13500
- answerable: false
13501
- };
13502
- const { attention, attentionSourceState } = activity;
13503
- if (attention === "none") return {
13504
- pending: attentionSourceState === "known" ? "none" : attentionSourceState,
13505
- answerable: false
13506
- };
13507
- if (attention === "unknown") return {
13508
- pending: attentionSourceState === "known" ? "unknown" : attentionSourceState,
13509
- answerable: false
13510
- };
13511
- const answerable = provedAnswerable(activity, eligibility);
13512
- return {
13513
- pending: answerable ? attention : "unverified",
13514
- answerable
13515
- };
13516
- }
13517
13846
  /** Build the ONE view of one frame. Every input is an official fact or the
13518
13847
  * previous pure ordering; nothing here reads, writes or invents a Session. */
13519
13848
  function buildSessionWorkspaceView(input) {
13520
13849
  const roster = input.rows.filter((row) => row.origin !== "subagent");
13521
13850
  const activityById = /* @__PURE__ */ new Map();
13522
13851
  for (const activity of input.activity ?? []) activityById.set(activity.sessionId, activity);
13852
+ const statusById = input.status;
13523
13853
  const currentWorkspaceId = currentWorkspaceOf(input.workspaces, input.currentSessionId);
13524
13854
  const rosterIndex = /* @__PURE__ */ new Map();
13525
13855
  roster.forEach((row, index) => {
@@ -13531,17 +13861,31 @@ function buildSessionWorkspaceView(input) {
13531
13861
  });
13532
13862
  const rowsById = /* @__PURE__ */ new Map();
13533
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;
13534
13869
  for (const row of roster) {
13535
- const activity = activityById.get(row.id);
13536
- 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
+ }
13537
13878
  const fact = {
13538
13879
  sessionId: row.id,
13539
- priority: answerable ? "needs" : activity?.running === true ? "working" : "recent",
13540
- group: answerable ? "needs" : activity?.running === true ? "working" : "recent",
13541
- pending,
13542
- running: activity?.running,
13543
- answerable,
13544
- 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,
13545
13889
  membership: workspaceMembershipOf(input.workspaces, row.id, input.workspaceBaselineProven)
13546
13890
  };
13547
13891
  rowsById.set(row.id, fact);
@@ -13552,6 +13896,7 @@ function buildSessionWorkspaceView(input) {
13552
13896
  const priority = [
13553
13897
  "needs",
13554
13898
  "working",
13899
+ "unread",
13555
13900
  "recent"
13556
13901
  ];
13557
13902
  const byPriority = priority.indexOf(left.priority) - priority.indexOf(right.priority);
@@ -13570,6 +13915,7 @@ function buildSessionWorkspaceView(input) {
13570
13915
  for (const kind of [
13571
13916
  "needs",
13572
13917
  "working",
13918
+ "unread",
13573
13919
  "recent"
13574
13920
  ]) {
13575
13921
  const ids = scoped.filter((fact) => fact.priority === kind).sort(orderOf).map((fact) => fact.sessionId);
@@ -13577,9 +13923,10 @@ function buildSessionWorkspaceView(input) {
13577
13923
  groups.push({
13578
13924
  kind,
13579
13925
  workspaceId: kind,
13580
- title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : "Recent",
13926
+ title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : kind === "unread" ? "Completed · unread" : "Recent",
13581
13927
  path: "",
13582
- ids
13928
+ ids,
13929
+ unread: kind === "unread" ? ids.length : 0
13583
13930
  });
13584
13931
  listIds.push(...ids);
13585
13932
  }
@@ -13589,6 +13936,7 @@ function buildSessionWorkspaceView(input) {
13589
13936
  rowsById,
13590
13937
  outsideAttention: { kind: "none" },
13591
13938
  currentWorkspaceId,
13939
+ currentQuietBlankWorkspaceId,
13592
13940
  nextCreateWorkspaceId: input.nextCreateWorkspaceId,
13593
13941
  workspaceBaselineProven: input.workspaceBaselineProven
13594
13942
  };
@@ -13600,6 +13948,7 @@ function buildSessionWorkspaceView(input) {
13600
13948
  for (const kind of [
13601
13949
  "needs",
13602
13950
  "working",
13951
+ "unread",
13603
13952
  "recent"
13604
13953
  ]) {
13605
13954
  const ids = scoped.filter((fact) => fact.priority === kind).sort(orderOf).map((fact) => fact.sessionId);
@@ -13607,9 +13956,10 @@ function buildSessionWorkspaceView(input) {
13607
13956
  legacyGroups.push({
13608
13957
  kind,
13609
13958
  workspaceId: kind,
13610
- title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : "Recent",
13959
+ title: kind === "needs" ? "Needs attention" : kind === "working" ? "Working" : kind === "unread" ? "Completed · unread" : "Recent",
13611
13960
  path: "",
13612
- ids
13961
+ ids,
13962
+ unread: kind === "unread" ? ids.length : 0
13613
13963
  });
13614
13964
  legacyListIds.push(...ids);
13615
13965
  }
@@ -13619,6 +13969,7 @@ function buildSessionWorkspaceView(input) {
13619
13969
  rowsById,
13620
13970
  outsideAttention: { kind: "none" },
13621
13971
  currentWorkspaceId,
13972
+ currentQuietBlankWorkspaceId,
13622
13973
  nextCreateWorkspaceId: input.nextCreateWorkspaceId,
13623
13974
  workspaceBaselineProven: false
13624
13975
  };
@@ -13632,7 +13983,8 @@ function buildSessionWorkspaceView(input) {
13632
13983
  workspaceId: workspace.workspaceId,
13633
13984
  title: workspace.title,
13634
13985
  path: workspace.path,
13635
- ids
13986
+ ids,
13987
+ unread: ids.filter((id) => rowsById.get(id)?.priority === "unread").length
13636
13988
  });
13637
13989
  }
13638
13990
  const ambiguous = classified.filter((fact) => fact.membership.kind === "ambiguous").sort(orderOf).map((fact) => fact.sessionId);
@@ -13641,13 +13993,15 @@ function buildSessionWorkspaceView(input) {
13641
13993
  workspaceId: "ambiguous",
13642
13994
  title: "Membership ambiguous",
13643
13995
  path: "",
13644
- ids: ambiguous
13996
+ ids: ambiguous,
13997
+ unread: ambiguous.filter((id) => rowsById.get(id)?.priority === "unread").length
13645
13998
  });
13646
13999
  if (unassigned.length > 0) groups.push({
13647
14000
  workspaceId: "unassigned",
13648
14001
  title: "Unassigned",
13649
14002
  path: "",
13650
- ids: unassigned
14003
+ ids: unassigned,
14004
+ unread: unassigned.filter((id) => rowsById.get(id)?.priority === "unread").length
13651
14005
  });
13652
14006
  const priorityWorkspaceId = currentWorkspaceId ?? input.nextCreateWorkspaceId;
13653
14007
  if (priorityWorkspaceId !== void 0) {
@@ -13678,109 +14032,615 @@ function buildSessionWorkspaceView(input) {
13678
14032
  rowsById,
13679
14033
  outsideAttention,
13680
14034
  currentWorkspaceId,
14035
+ currentQuietBlankWorkspaceId,
13681
14036
  nextCreateWorkspaceId: input.nextCreateWorkspaceId,
13682
14037
  workspaceBaselineProven: input.workspaceBaselineProven
13683
14038
  };
13684
14039
  }
13685
14040
  //#endregion
13686
- //#region src/domain/visual/chart.ts
13687
- const CHART_FACT_KEYS = [
13688
- "version",
13689
- "type",
13690
- "kind",
13691
- "title",
13692
- "unit",
13693
- "series"
13694
- ];
13695
- const CHART_POINT_KEYS = ["label", "value"];
13696
- const CHART_KINDS = ["bars", "spark"];
13697
- function isRecord$1(value) {
13698
- return typeof value === "object" && value !== null && !Array.isArray(value);
13699
- }
13700
- function hasOnlyKeys$1(value, keys) {
13701
- const allowed = new Set(keys);
13702
- return Object.keys(value).every((key) => allowed.has(key));
13703
- }
13704
- /** Count Unicode code points, not UTF-16 units. */
13705
- function codePointLength(text) {
13706
- let count = 0;
13707
- for (const _ of text) count += 1;
13708
- return count;
13709
- }
13710
- /** Display width in terminal cells (East Asian wide/fullwidth count double). */
13711
- function displayWidth(text) {
13712
- let width = 0;
13713
- for (const char of text) width += eastAsianWidth(char.codePointAt(0) ?? 0);
13714
- return width;
13715
- }
13716
- /** Deterministic, locale-independent number text. */
13717
- function formatChartNumber(value) {
13718
- return Object.is(value, -0) ? "0" : String(value);
13719
- }
13720
- /** Validate one chart point object and narrow it. */
13721
- function parsePoint(value) {
13722
- if (!isRecord$1(value) || !hasOnlyKeys$1(value, CHART_POINT_KEYS)) return void 0;
13723
- const { label, value: pointValue } = value;
13724
- if (typeof label !== "string" || label === "" || codePointLength(label) > 48) return void 0;
13725
- if (typeof pointValue !== "number" || !Number.isFinite(pointValue)) return void 0;
13726
- return {
13727
- label,
13728
- value: pointValue
13729
- };
13730
- }
13731
- /** Validate the kind/title/unit/series core shared by args and the fact. */
13732
- function chartCoreProblem(kind, title, unit, series) {
13733
- if (typeof kind !== "string" || !CHART_KINDS.includes(kind)) return "kind must be \"bars\" or \"spark\"";
13734
- if (typeof title !== "string" || title.trim() === "" || codePointLength(title) > 100) return `title must be a non-empty string of at most 100 Unicode code points`;
13735
- if (unit !== void 0 && (typeof unit !== "string" || unit === "" || codePointLength(unit) > 32)) return `unit must be a non-empty string of at most 32 Unicode code points`;
13736
- if (!Array.isArray(series) || series.length < 2 || series.length > 12) return `series must contain between 2 and 12 points`;
13737
- for (const [index, point] of series.entries()) if (parsePoint(point) === void 0) return `series[${index}] must be a finite number with a non-empty label of at most 48 Unicode code points`;
13738
- }
13739
- /** Strict parse of one durable machine-line fact. */
13740
- function parseChartFact(value) {
13741
- if (!isRecord$1(value) || !hasOnlyKeys$1(value, CHART_FACT_KEYS)) return void 0;
13742
- if (value.version !== 1 || value.type !== "chart") return void 0;
13743
- if (chartCoreProblem(value.kind, value.title, value.unit, value.series) !== void 0) return void 0;
13744
- const series = [];
13745
- for (const raw of value.series) {
13746
- const point = parsePoint(raw);
13747
- if (point === void 0) return void 0;
13748
- series.push(point);
13749
- }
13750
- return {
13751
- version: 1,
13752
- type: "chart",
13753
- kind: value.kind,
13754
- title: value.title,
13755
- ...value.unit === void 0 ? {} : { unit: value.unit },
13756
- series
13757
- };
13758
- }
13759
- /** The unit suffix used after one value (never parsed back as a number). */
13760
- function valueText(fact, point) {
13761
- const number = formatChartNumber(point.value);
13762
- return fact.unit === void 0 ? number : `${number} ${fact.unit}`;
13763
- }
13764
- /** The per-point value rows shared by every renderer (no title duplication). */
13765
- function chartValueRows(fact) {
13766
- return [...fact.series.map((point) => `${point.label} ${valueText(fact, point)}`), `${fact.series.length} supplied value${fact.series.length === 1 ? "" : "s"}`];
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;
13767
14107
  }
13768
- /** The final fact's display title (title + unit), the committed label. */
13769
- function chartDisplayTitle(fact) {
13770
- return fact.unit === void 0 ? fact.title : `${fact.title} (${fact.unit})`;
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
+ }];
13771
14132
  }
13772
- /**
13773
- * The durable, self-contained human text. It repeats the title because this
13774
- * text is also what search, copy and Markdown export read without a card
13775
- * header; the graphical card bodies use {@link chartValueRows} instead.
13776
- */
13777
- function chartHumanText(fact) {
13778
- return [chartDisplayTitle(fact), ...chartValueRows(fact)].join("\n");
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
+ ];
13779
14178
  }
13780
- /** The TSP native chart projection (one summary, the same ordered series). */
13781
- function chartProjection(fact) {
13782
- return {
13783
- kind: fact.kind,
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
+ });
14455
+ }
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}`
14465
+ });
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)
14489
+ });
14490
+ }
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
14536
+ };
14537
+ }
14538
+ return {
14539
+ ...base,
14540
+ state: matching.refreshing ? "refreshing" : "ready",
14541
+ notice: matching.refreshing ? "Refreshing" : "",
14542
+ groups
14543
+ };
14544
+ }
14545
+ //#endregion
14546
+ //#region src/domain/visual/chart.ts
14547
+ const CHART_FACT_KEYS = [
14548
+ "version",
14549
+ "type",
14550
+ "kind",
14551
+ "title",
14552
+ "unit",
14553
+ "series"
14554
+ ];
14555
+ const CHART_POINT_KEYS = ["label", "value"];
14556
+ const CHART_KINDS = ["bars", "spark"];
14557
+ function isRecord$1(value) {
14558
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14559
+ }
14560
+ function hasOnlyKeys$1(value, keys) {
14561
+ const allowed = new Set(keys);
14562
+ return Object.keys(value).every((key) => allowed.has(key));
14563
+ }
14564
+ /** Count Unicode code points, not UTF-16 units. */
14565
+ function codePointLength(text) {
14566
+ let count = 0;
14567
+ for (const _ of text) count += 1;
14568
+ return count;
14569
+ }
14570
+ /** Display width in terminal cells (East Asian wide/fullwidth count double). */
14571
+ function displayWidth(text) {
14572
+ let width = 0;
14573
+ for (const char of text) width += eastAsianWidth(char.codePointAt(0) ?? 0);
14574
+ return width;
14575
+ }
14576
+ /** Deterministic, locale-independent number text. */
14577
+ function formatChartNumber(value) {
14578
+ return Object.is(value, -0) ? "0" : String(value);
14579
+ }
14580
+ /** Validate one chart point object and narrow it. */
14581
+ function parsePoint(value) {
14582
+ if (!isRecord$1(value) || !hasOnlyKeys$1(value, CHART_POINT_KEYS)) return void 0;
14583
+ const { label, value: pointValue } = value;
14584
+ if (typeof label !== "string" || label === "" || codePointLength(label) > 48) return void 0;
14585
+ if (typeof pointValue !== "number" || !Number.isFinite(pointValue)) return void 0;
14586
+ return {
14587
+ label,
14588
+ value: pointValue
14589
+ };
14590
+ }
14591
+ /** Validate the kind/title/unit/series core shared by args and the fact. */
14592
+ function chartCoreProblem(kind, title, unit, series) {
14593
+ if (typeof kind !== "string" || !CHART_KINDS.includes(kind)) return "kind must be \"bars\" or \"spark\"";
14594
+ if (typeof title !== "string" || title.trim() === "" || codePointLength(title) > 100) return `title must be a non-empty string of at most 100 Unicode code points`;
14595
+ if (unit !== void 0 && (typeof unit !== "string" || unit === "" || codePointLength(unit) > 32)) return `unit must be a non-empty string of at most 32 Unicode code points`;
14596
+ if (!Array.isArray(series) || series.length < 2 || series.length > 12) return `series must contain between 2 and 12 points`;
14597
+ for (const [index, point] of series.entries()) if (parsePoint(point) === void 0) return `series[${index}] must be a finite number with a non-empty label of at most 48 Unicode code points`;
14598
+ }
14599
+ /** Strict parse of one durable machine-line fact. */
14600
+ function parseChartFact(value) {
14601
+ if (!isRecord$1(value) || !hasOnlyKeys$1(value, CHART_FACT_KEYS)) return void 0;
14602
+ if (value.version !== 1 || value.type !== "chart") return void 0;
14603
+ if (chartCoreProblem(value.kind, value.title, value.unit, value.series) !== void 0) return void 0;
14604
+ const series = [];
14605
+ for (const raw of value.series) {
14606
+ const point = parsePoint(raw);
14607
+ if (point === void 0) return void 0;
14608
+ series.push(point);
14609
+ }
14610
+ return {
14611
+ version: 1,
14612
+ type: "chart",
14613
+ kind: value.kind,
14614
+ title: value.title,
14615
+ ...value.unit === void 0 ? {} : { unit: value.unit },
14616
+ series
14617
+ };
14618
+ }
14619
+ /** The unit suffix used after one value (never parsed back as a number). */
14620
+ function valueText(fact, point) {
14621
+ const number = formatChartNumber(point.value);
14622
+ return fact.unit === void 0 ? number : `${number} ${fact.unit}`;
14623
+ }
14624
+ /** The per-point value rows shared by every renderer (no title duplication). */
14625
+ function chartValueRows(fact) {
14626
+ return [...fact.series.map((point) => `${point.label} ${valueText(fact, point)}`), `${fact.series.length} supplied value${fact.series.length === 1 ? "" : "s"}`];
14627
+ }
14628
+ /** The final fact's display title (title + unit), the committed label. */
14629
+ function chartDisplayTitle(fact) {
14630
+ return fact.unit === void 0 ? fact.title : `${fact.title} (${fact.unit})`;
14631
+ }
14632
+ /**
14633
+ * The durable, self-contained human text. It repeats the title because this
14634
+ * text is also what search, copy and Markdown export read without a card
14635
+ * header; the graphical card bodies use {@link chartValueRows} instead.
14636
+ */
14637
+ function chartHumanText(fact) {
14638
+ return [chartDisplayTitle(fact), ...chartValueRows(fact)].join("\n");
14639
+ }
14640
+ /** The TSP native chart projection (one summary, the same ordered series). */
14641
+ function chartProjection(fact) {
14642
+ return {
14643
+ kind: fact.kind,
13784
14644
  summary: chartDisplayTitle(fact),
13785
14645
  series: fact.series.map((point) => ({
13786
14646
  label: point.label,
@@ -15017,358 +15877,6 @@ function planVisualPlacement(input) {
15017
15877
  definitions
15018
15878
  };
15019
15879
  }
15020
- /** Create ONE recall kernel (TSP I-A). */
15021
- function createHistoryRecallScope() {
15022
- /** The recall projection, newest first — what ↑/↓ can recall and what
15023
- * {@link HistoryRecallScope.snapshot} reports. */
15024
- const snapshot = [];
15025
- /**
15026
- * The SCOPE-BOUND TEMPORARY SUBMISSIONS of the OPEN scope, in submission
15027
- * order (newest first): one entry per input accepted by
15028
- * {@link HistoryRecallScope.rememberAccepted} for the scope's owner, each
15029
- * carrying its own OCCURRENCE token. A Session's hydration reseeds recall
15030
- * from the session-scoped JSONL rows, while a submission's own append is
15031
- * ordered behind the session transition (the submit FIFO turn and
15032
- * `ensureSession()`), so a submission accepted inside the
15033
- * publication→hydration window is absent from the snapshot and would be
15034
- * wiped by the reseed.
15035
- *
15036
- * The list is the scope's TRUE submission sequence and is never re-ordered
15037
- * or shrunk; the write owner settles OCCURRENCES into
15038
- * {@link scopeSettlements}, never into this list. The whole list is dropped
15039
- * only when the scope is replaced (or consumed by its owner's reseed / the
15040
- * pool's adoption).
15041
- */
15042
- const scopeInputs = [];
15043
- /**
15044
- * The ordered settlements of the OPEN scope (oldest first): one report per
15045
- * settled submission, produced by the session-history owner from the SAME
15046
- * synchronous stack as its append (or from its policy skip). The order is
15047
- * the APPEND order, which is the file's row order — the authoritative order
15048
- * of the rows the reseed snapshot carries. This queue is bounded, so it is
15049
- * NOT the authority for "was this occurrence settled"; that fact lives in
15050
- * {@link scopeSettled}.
15051
- */
15052
- const scopeSettlements = [];
15053
- /**
15054
- * The DURABLE per-occurrence settlement fact of the OPEN scope, keyed by the
15055
- * occurrence token: which outcome settled it and the session id its row
15056
- * carried. Bounded by the scope's own occurrences (never by the queue), so a
15057
- * settlement the queue evicted can neither resurrect the occurrence nor lose
15058
- * it.
15059
- */
15060
- const scopeSettled = /* @__PURE__ */ new Map();
15061
- /** The LIVE occurrence tokens of the open scope: the durable facts above are
15062
- * kept for exactly these (bounded by the scope cap, never by the queue). */
15063
- const scopeOccurrences = /* @__PURE__ */ new Set();
15064
- /** The number of APPENDS this scope's settlements reported per row owner —
15065
- * the exact watermark of how many of the snapshot's newest rows the window
15066
- * owns, even for settlements the bounded queue evicted. */
15067
- const scopeAppends = /* @__PURE__ */ new Map();
15068
- /**
15069
- * The recent successful WRITTEN settlements of the OPEN scope, per row
15070
- * owner, in the writer's true synchronous append order (oldest first). This
15071
- * is the only authority for the cold-seed prefix: `ts` can never reproduce
15072
- * this order. Bounded to {@link INPUT_RECALL_LIMIT} per owner; skips and
15073
- * tokenless writers are included because they are real appends.
15074
- */
15075
- const scopeWritten = /* @__PURE__ */ new Map();
15076
- /**
15077
- * The number of positions the last recall reconcile visited — a
15078
- * HEADLESS-TEST HOOK pinning the frozen plan's O(100) bound (never read by
15079
- * production code).
15080
- */
15081
- let reconcileSteps = 0;
15082
- /** The next occurrence token (monotonic per process/mount; only equality
15083
- * matters). */
15084
- let scopeTokenSeq = 0;
15085
- /**
15086
- * The owner the OPEN scope's entries were accepted for (`undefined` = the
15087
- * sessionless pool). The pool is a real scope: a deferred start and the
15088
- * Remote startup resume both accept input before any hydration reseeds the
15089
- * recall, and the first published owner ADOPTS the pool's entries (that
15090
- * submission is persisted under the new Session, so the snapshot cannot
15091
- * carry it yet).
15092
- */
15093
- let scopeOwner = void 0;
15094
- /** Whether a recall scope is open. Open at construction (the sessionless
15095
- * pool); closed by the owning owner's hydration reseed commit. */
15096
- let scopeOpen = true;
15097
- /** Drop every durable trace of one occurrence the scope no longer holds. */
15098
- const forgetScopeInput = (entry) => {
15099
- scopeOccurrences.delete(entry.token);
15100
- scopeSettled.delete(entry.token);
15101
- };
15102
- /** The number of runs of consecutive identical text in the scope. */
15103
- const countScopeRuns = () => {
15104
- let runs = 0;
15105
- let previous;
15106
- for (const entry of scopeInputs) if (entry.text !== previous) {
15107
- runs += 1;
15108
- previous = entry.text;
15109
- }
15110
- return runs;
15111
- };
15112
- /**
15113
- * APPEND entries (newest first) into the recall snapshot with the SAME
15114
- * semantics the PiTui editor + mirror always used: only CONSECUTIVE
15115
- * duplicates collapse, the cap keeps the newest 100. Non-consecutive
15116
- * repeats like `['a', 'b', 'a']` are legal history and survive.
15117
- */
15118
- const appendSnapshot = (entries) => {
15119
- let last;
15120
- for (const entry of entries) {
15121
- const trimmed = entry.trim();
15122
- if (trimmed === "" || trimmed === last) continue;
15123
- last = trimmed;
15124
- snapshot.push(trimmed);
15125
- }
15126
- if (snapshot.length > 100) snapshot.length = 100;
15127
- };
15128
- const snapshotOf = () => [...snapshot];
15129
- const rememberAccepted = (text) => {
15130
- const trimmed = text.trim();
15131
- if (trimmed === "") return void 0;
15132
- if (snapshot[0] !== trimmed) {
15133
- snapshot.unshift(trimmed);
15134
- if (snapshot.length > 100) snapshot.pop();
15135
- }
15136
- if (!scopeOpen) return void 0;
15137
- scopeTokenSeq += 1;
15138
- const token = scopeTokenSeq;
15139
- const entry = {
15140
- owner: scopeOwner,
15141
- token,
15142
- text: trimmed
15143
- };
15144
- const head = scopeInputs[0];
15145
- if (head !== void 0 && head.text === trimmed) {
15146
- let runStart = scopeInputs.length;
15147
- for (let index = 0; index < scopeInputs.length; index += 1) if (scopeInputs[index].text !== trimmed) {
15148
- runStart = index;
15149
- break;
15150
- }
15151
- const first = scopeInputs[runStart - 1];
15152
- const older = scopeInputs.slice(runStart);
15153
- for (let index = 0; index < runStart - 1; index += 1) forgetScopeInput(scopeInputs[index]);
15154
- scopeInputs.length = 0;
15155
- scopeInputs.push(entry, first, ...older);
15156
- scopeOccurrences.add(token);
15157
- return token;
15158
- }
15159
- scopeInputs.unshift(entry);
15160
- scopeOccurrences.add(token);
15161
- if (countScopeRuns() > 100) {
15162
- const oldest = scopeInputs[scopeInputs.length - 1];
15163
- let runStart = scopeInputs.length - 1;
15164
- while (runStart > 0 && scopeInputs[runStart - 1].text === oldest.text) runStart -= 1;
15165
- for (let index = scopeInputs.length - 1; index >= runStart; index -= 1) forgetScopeInput(scopeInputs[index]);
15166
- scopeInputs.length = runStart;
15167
- }
15168
- return token;
15169
- };
15170
- const seed = (entries) => {
15171
- appendSnapshot(entries);
15172
- };
15173
- /**
15174
- * Record ONE settlement of the OPEN scope, in append order. The input-history
15175
- * owner calls this from the SAME synchronous stack as its append (the detached
15176
- * task's factory is invoked synchronously) and ALSO when its write policy
15177
- * skips a submission, and it carries the submission's occurrence token
15178
- * whenever the settled submission was a scope Enter. That token — not the
15179
- * text — is what attributes the settlement to exactly one occurrence, so
15180
- * repeated identical submissions stay distinguishable, and the ordering of
15181
- * the settled submissions is what places them against every other
15182
- * session-history writer (a steer, a shell line, a sessionless command).
15183
- */
15184
- const settle = (settlement) => {
15185
- if (!scopeOpen) return;
15186
- const appendsBefore = scopeAppends.get(settlement.owner) ?? 0;
15187
- if (settlement.outcome === "written") {
15188
- scopeAppends.set(settlement.owner, appendsBefore + 1);
15189
- const written = scopeWritten.get(settlement.owner) ?? [];
15190
- written.push({
15191
- writeId: settlement.writeId,
15192
- text: settlement.text
15193
- });
15194
- if (written.length > 100) written.shift();
15195
- scopeWritten.set(settlement.owner, written);
15196
- }
15197
- if (settlement.token !== void 0 && scopeOccurrences.has(settlement.token)) scopeSettled.set(settlement.token, {
15198
- owner: settlement.owner,
15199
- outcome: settlement.outcome,
15200
- appendsBefore
15201
- });
15202
- scopeSettlements.push(settlement);
15203
- if (scopeSettlements.length > 100) scopeSettlements.shift();
15204
- };
15205
- /**
15206
- * REPLACE the whole recall projection with the entries of the CURRENT
15207
- * workspace. Session switches must not recall the previous workspace's
15208
- * inputs nor pollute the new workspace's persisted history, so the host
15209
- * resets on every session change. The OPEN scope's occurrences ride along:
15210
- * every successful write keeps its own row once, a policy-skipped occurrence
15211
- * is inserted where its settlement placed it, and a still-unsettled
15212
- * occurrence keeps its rank in the scope's submission order. The commit
15213
- * closes the scope, so ordinary submissions use the plain
15214
- * {@link rememberAccepted} path again.
15215
- * @param entries - the new workspace's persisted entries, newest first.
15216
- * @param owner - the owner whose hydration committed this reseed. The
15217
- * sessionless boot seed passes no owner: it only seeds the recall pool and
15218
- * leaves the scope open (boot is not a published Session).
15219
- */
15220
- const reset = (entries, owner, writeIds) => {
15221
- if (writeIds !== void 0 && writeIds.length !== entries.length) throw new Error("history recall reset: writeIds must stay positionally aligned with entries");
15222
- let seedEntries = entries;
15223
- if (owner !== void 0 && writeIds !== void 0) {
15224
- const written = scopeWritten.get(owner) ?? [];
15225
- const writtenText = /* @__PURE__ */ new Map();
15226
- for (const item of written) {
15227
- if (item.writeId === void 0) throw new Error("history recall reset: a written settlement of the open scope carries no writeId");
15228
- writtenText.set(item.writeId, item.text);
15229
- }
15230
- const baseline = [];
15231
- for (let index = 0; index < entries.length; index += 1) {
15232
- const writeId = writeIds[index];
15233
- if (writeId !== void 0 && writtenText.get(writeId) === entries[index]) continue;
15234
- baseline.push(entries[index]);
15235
- }
15236
- const normalized = [...written].reverse().map((item) => item.text);
15237
- normalized.push(...baseline);
15238
- seedEntries = normalized.slice(0, 100);
15239
- }
15240
- snapshot.length = 0;
15241
- if (owner === void 0) {
15242
- appendSnapshot(seedEntries);
15243
- return;
15244
- }
15245
- const settlements = scopeSettlements.filter((settlement) => settlement.owner === owner);
15246
- const retainedTokens = /* @__PURE__ */ new Set();
15247
- let retainedWrites = 0;
15248
- for (const settlement of settlements) {
15249
- if (settlement.outcome === "written") retainedWrites += 1;
15250
- if (settlement.token !== void 0) retainedTokens.add(settlement.token);
15251
- }
15252
- const covered = Math.min(scopeAppends.get(owner) ?? 0, seedEntries.length);
15253
- const ranks = /* @__PURE__ */ new Map();
15254
- for (let index = 0; index < scopeInputs.length; index += 1) ranks.set(scopeInputs[index].token, index);
15255
- const windowTexts = [];
15256
- const windowRanks = [];
15257
- const windowRows = [];
15258
- let writeSeen = 0;
15259
- for (let index = settlements.length - 1; index >= 0; index -= 1) {
15260
- const settlement = settlements[index];
15261
- const rank = settlement.token === void 0 ? void 0 : ranks.get(settlement.token);
15262
- if (settlement.outcome === "written") {
15263
- writeSeen += 1;
15264
- if (writeSeen > covered) continue;
15265
- windowTexts.push(seedEntries[writeSeen - 1]);
15266
- } else {
15267
- if (rank === void 0) continue;
15268
- windowTexts.push(scopeInputs[rank].text);
15269
- }
15270
- windowRanks.push(rank);
15271
- windowRows.push(settlement.outcome === "written");
15272
- }
15273
- for (let row = retainedWrites; row < covered; row += 1) {
15274
- windowTexts.push(seedEntries[row]);
15275
- windowRanks.push(void 0);
15276
- windowRows.push(true);
15277
- }
15278
- const before = [];
15279
- const after = [];
15280
- for (let index = 0; index < scopeInputs.length; index += 1) {
15281
- const token = scopeInputs[index].token;
15282
- if (retainedTokens.has(token)) continue;
15283
- const settled = scopeSettled.get(token);
15284
- if (settled === void 0) before.push(index);
15285
- else if (settled.outcome === "skipped" && settled.owner === owner) after.push({
15286
- rank: index,
15287
- newerRows: covered - settled.appendsBefore
15288
- });
15289
- }
15290
- after.sort((left, right) => left.newerRows - right.newerRows || left.rank - right.rank);
15291
- reconcileSteps = 0;
15292
- const merged = [];
15293
- let next = 0;
15294
- let rowsSeen = 0;
15295
- let skipped = 0;
15296
- const emitEvictedSkips = (upTo) => {
15297
- while (skipped < after.length && after[skipped].newerRows <= upTo) {
15298
- merged.push(scopeInputs[after[skipped].rank].text);
15299
- skipped += 1;
15300
- }
15301
- };
15302
- for (let index = 0; index < windowTexts.length; index += 1) {
15303
- reconcileSteps += 1;
15304
- const windowRank = windowRanks[index];
15305
- while (next < before.length && (windowRank === void 0 || before[next] < windowRank)) {
15306
- reconcileSteps += 1;
15307
- merged.push(scopeInputs[before[next]].text);
15308
- next += 1;
15309
- }
15310
- emitEvictedSkips(rowsSeen);
15311
- merged.push(windowTexts[index]);
15312
- if (windowRows[index] === true) {
15313
- rowsSeen += 1;
15314
- emitEvictedSkips(rowsSeen);
15315
- }
15316
- }
15317
- while (next < before.length) {
15318
- reconcileSteps += 1;
15319
- merged.push(scopeInputs[before[next]].text);
15320
- next += 1;
15321
- }
15322
- emitEvictedSkips(covered);
15323
- appendSnapshot([...merged, ...seedEntries.slice(covered)]);
15324
- scopeInputs.length = 0;
15325
- scopeSettlements.length = 0;
15326
- scopeSettled.clear();
15327
- scopeOccurrences.clear();
15328
- scopeAppends.clear();
15329
- scopeWritten.clear();
15330
- scopeOpen = false;
15331
- scopeOwner = owner;
15332
- };
15333
- /**
15334
- * Open the RECALL SCOPE of the owner a commit section is publishing (ordinary
15335
- * transition, fork adoption) or creating (the first Session). The owner's
15336
- * hydration reseeds recall from its disk rows afterwards, so inputs accepted
15337
- * in that gap belong to the new owner and must survive the reseed.
15338
- * A REPLACED owner's pending submissions are dropped with the scope — that is
15339
- * what keeps Session A's input out of Session B's recall — while the
15340
- * SESSIONLESS pool's entries are ADOPTED by the first published owner (that
15341
- * submission is persisted under the new Session; there is no outgoing owner
15342
- * to fence).
15343
- */
15344
- const begin = (owner) => {
15345
- if (scopeOwner !== void 0) {
15346
- scopeInputs.length = 0;
15347
- scopeSettlements.length = 0;
15348
- scopeSettled.clear();
15349
- scopeOccurrences.clear();
15350
- scopeAppends.clear();
15351
- scopeWritten.clear();
15352
- }
15353
- snapshot.length = 0;
15354
- appendSnapshot(scopeInputs.filter((entry) => {
15355
- const settled = scopeSettled.get(entry.token);
15356
- return settled === void 0 || settled.owner === owner;
15357
- }).map((entry) => entry.text));
15358
- scopeOwner = owner;
15359
- scopeOpen = true;
15360
- };
15361
- return {
15362
- snapshot: snapshotOf,
15363
- rememberAccepted,
15364
- seed,
15365
- begin,
15366
- reset,
15367
- settle,
15368
- reconcileStepsForTest: () => reconcileSteps,
15369
- scopeFactCountForTest: () => scopeSettled.size
15370
- };
15371
- }
15372
15880
  //#endregion
15373
15881
  //#region src/client/history/reverse-reader.ts
15374
15882
  /**
@@ -16294,29 +16802,378 @@ function shellCommandIsOpen(lines) {
16294
16802
  index += 2;
16295
16803
  continue;
16296
16804
  }
16297
- if (character === "<" && line[index + 1] === "<") {
16298
- const parsed = heredocAt(line, index);
16299
- if (parsed !== void 0) {
16300
- 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;
16301
17018
  index += 2;
16302
17019
  continue;
16303
17020
  }
16304
- }
16305
- if (substitution > 0) {
16306
- if (character === "(") substitution += 1;
16307
- else if (character === ")") substitution -= 1;
17021
+ quote = void 0;
17022
+ closedQuote = true;
16308
17023
  index += 1;
16309
17024
  continue;
16310
17025
  }
16311
- if (brace > 0) {
16312
- if (character === "{") brace += 1;
16313
- else if (character === "}") brace -= 1;
17026
+ if (character === "`" || character === "$" || isPowerShellDoubleQuoteCharacter(character)) {
17027
+ uncertain = true;
17028
+ break;
16314
17029
  }
17030
+ value += character;
17031
+ rawLength += 1;
16315
17032
  index += 1;
17033
+ continue;
16316
17034
  }
16317
- 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;
16318
17081
  }
16319
- 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}`)}'`;
16320
17177
  }
16321
17178
  /** The RAW range a WHOLE-WORD acceptance replaces: the raw word start, and the
16322
17179
  * raw word end. A closing quote the cursor is inside is part of the range (the
@@ -16446,7 +17303,7 @@ async function suggestShellCompletion(context, port, target, options) {
16446
17303
  items: candidates.map((candidate) => {
16447
17304
  const directory = candidate.endsWith("/") || candidate.endsWith("\\");
16448
17305
  return {
16449
- 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,
16450
17307
  label: candidate
16451
17308
  };
16452
17309
  }),
@@ -17147,17 +18004,21 @@ var MentionProvider = class {
17147
18004
  const currentLine = lines[cursorLine] ?? "";
17148
18005
  const textBeforeCursor = currentLine.slice(0, cursorCol);
17149
18006
  const requestScope = this.scopeOf();
17150
- if (this.inputModeSource() !== "prompt" && cursorLine > 0 && shellCommandIsOpen(lines.slice(0, cursorLine))) {
17151
- if (generation === this.requestGeneration) this.requestSnapshot = null;
17152
- 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
+ }
17153
18013
  }
17154
18014
  const shellLine = this.virtualWireShellContext(lines, cursorLine, cursorCol) ?? {
17155
18015
  line: currentLine,
17156
18016
  cursorCol,
17157
18017
  prefixLength: 0
17158
18018
  };
17159
- const shellContext = this.hostShellCompletion === void 0 ? void 0 : shellCompletionContext(shellLine.line, shellLine.cursorCol);
17160
- 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) {
17161
18022
  const port = this.hostShellCompletion;
17162
18023
  if (!(shellContext.kind === "paths" && port.pathAuthority === "client")) {
17163
18024
  const suggestions = await suggestShellCompletion(shellContext, port, shellCompletionTargetOf(requestScope), options);
@@ -17198,7 +18059,7 @@ var MentionProvider = class {
17198
18059
  const literalShellLine = textBeforeCursor.trimStart().startsWith("!");
17199
18060
  if (semantic !== null || literalShellLine) {
17200
18061
  const port = this.hostShellCompletion;
17201
- 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);
17202
18063
  try {
17203
18064
  const result = await this.inner.getSuggestions(lines, cursorLine, cursorCol, options);
17204
18065
  return this.withRequestSnapshot(generation, requestScope, requestMode, requestLocalCwd, lines, cursorLine, cursorCol, result, false);
@@ -17450,7 +18311,8 @@ var MentionProvider = class {
17450
18311
  cursorLine,
17451
18312
  cursorCol
17452
18313
  };
17453
- 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);
17454
18316
  const wholeWordShell = shellContext?.kind === "command" || shellContext?.kind === "subcommand";
17455
18317
  const start = cursorCol - bodyPrefix.length;
17456
18318
  if (!wholeWordShell && (start < 0 || currentLine.slice(start, cursorCol) !== bodyPrefix)) return {
@@ -17483,6 +18345,25 @@ var MentionProvider = class {
17483
18345
  cursorLine,
17484
18346
  cursorCol
17485
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
+ }
17486
18367
  const suffix = shellWordSuffix(shellLine.line, shellLine.cursorCol, shellContext.word?.quote);
17487
18368
  const before = currentLine.slice(0, start);
17488
18369
  const after = currentLine.slice(cursorCol + suffix.length);
@@ -17695,6 +18576,12 @@ function createInstalledAutocompleteProvider(options) {
17695
18576
  /** Find the Assistant entry that owns the structural latest step. A late
17696
18577
  * durable message can append after newer process evidence, so physical array
17697
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
+ */
17698
18585
  function assistantForStep(group, step) {
17699
18586
  for (let index = group.length - 1; index >= 0; index -= 1) {
17700
18587
  const member = group[index];
@@ -18663,13 +19550,15 @@ function clusterAdjacentAmbientContext(messages) {
18663
19550
  *
18664
19551
  * A Work span may CARRY a foldable Context row as a structural part without
18665
19552
  * making it Process: the row keeps its Context semantics, its source bytes and
18666
- * 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
18667
19554
  * narrow forms qualify: a `form:'snapshot'` singleton / snapshot-only raw
18668
- * cluster, a `tool-jobs` Notice, an `agent-message` relay and a
18669
- * `subagent-settled` Notice, each of the last three with durable same-turn
18670
- * `next-step` delivery evidence. A mixed
18671
- * `instructions`/`catalog`/`snapshot` cluster and every other Notice/relay form
18672
- * 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.
18673
19562
  *
18674
19563
  * The projector is a single forward pass plus the linear ambient-clustering
18675
19564
  * pass (O(n)); wrappers are freshly allocated each call, but their
@@ -18694,12 +19583,19 @@ function clusterAdjacentAmbientContext(messages) {
18694
19583
  * {@link isFoldableSnapshotContext} inside {@link projectTranscriptStructure}.
18695
19584
  */
18696
19585
  function isTranscriptWorkMember(message) {
18697
- 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);
18698
19587
  }
18699
19588
  /** Whether one row is a producer-declared Snapshot Context row (the ONE
18700
- * 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. */
18701
19595
  function isSnapshotContext(message) {
18702
- 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);
18703
19599
  }
18704
19600
  /** Per-cluster memo of {@link isSnapshotOnlyCluster}: cluster wrappers are
18705
19601
  * freshly allocated per projection pass but may be queried once per member by
@@ -18734,69 +19630,17 @@ function isFoldableSnapshotContext(message, clusterByMember) {
18734
19630
  const cluster = clusterByMember.get(message);
18735
19631
  return cluster === void 0 || isSnapshotOnlyCluster(cluster);
18736
19632
  }
18737
- /**
18738
- * Whether one row is a Working `tool-jobs` completion Notice with durable
18739
- * same-turn `next-step` delivery evidence.
18740
- *
18741
- * This is a NARROW exception, never a generic notice rule: the producer-declared
18742
- * `sourceKind === 'tool-jobs'` AND `form === 'notice'` are both required, plus
18743
- * the fold's presentation-only `sameTurnNextStep` flag derived from the durable
18744
- * `agent/inbox/spliced` insert/claim identity chain. A `next-turn` wakeup, a
18745
- * foreign/legacy log, a different producer (including `subagent-settled`) or a
18746
- * missing claim carries no flag and therefore stays an independent Context
18747
- * boundary.
18748
- */
18749
- function isWorkingToolJobsNotice(message) {
18750
- if (!isSurfacedContext(message)) return false;
18751
- const presentation = message.contextPresentation;
18752
- return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.form === "notice" && presentation.sourceKind === "tool-jobs";
18753
- }
18754
- /**
18755
- * Whether one row is a same-turn delivered Agent relay (`agent-message` +
18756
- * `relay`) with durable next-step delivery evidence.
18757
- *
18758
- * This is the narrow sibling of {@link isWorkingToolJobsNotice}: the
18759
- * producer-declared `sourceKind === 'agent-message'` AND `form === 'relay'`
18760
- * are both required, plus the fold's presentation-only `sameTurnNextStep`
18761
- * flag derived from the durable `agent/inbox/spliced` insert/claim identity
18762
- * chain. A `next-turn` wakeup, a foreign/legacy log, a crossed source/form
18763
- * pair or a missing claim carries no flag and therefore stays an independent
18764
- * Context boundary.
18765
- */
18766
- function isWorkingAgentRelay(message) {
18767
- if (!isSurfacedContext(message)) return false;
18768
- const presentation = message.contextPresentation;
18769
- return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.sourceKind === "agent-message" && presentation.form === "relay";
18770
- }
18771
- /**
18772
- * Whether one row is a same-turn delivered subagent settlement Notice
18773
- * (`subagent-settled` + `notice`) with durable next-step delivery evidence.
18774
- *
18775
- * This is the narrow sibling of {@link isWorkingToolJobsNotice}: the
18776
- * producer-declared `sourceKind === 'subagent-settled'` AND `form === 'notice'`
18777
- * are both required, plus the fold's presentation-only `sameTurnNextStep` flag
18778
- * derived from the durable `agent/inbox/spliced` insert/claim identity chain.
18779
- * The settlement's textual outcome (`completed` / `error` / `aborted` / …) is
18780
- * deliberately NOT inspected: every settlement that arrived through the same
18781
- * proven delivery is carried the same way, and its raw body is never rewritten.
18782
- * A `next-turn` wakeup, a foreign/legacy log, a crossed source/form pair or a
18783
- * missing claim carries no flag and therefore stays an independent Context
18784
- * boundary.
18785
- */
18786
- function isWorkingSubagentSettledNotice(message) {
18787
- if (!isSurfacedContext(message)) return false;
19633
+ function workContextCarriageOf(message, clusterByMember) {
19634
+ if (!isSurfacedContext(message)) return void 0;
18788
19635
  const presentation = message.contextPresentation;
18789
- return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.sourceKind === "subagent-settled" && presentation.form === "notice";
18790
- }
18791
- /**
18792
- * The complete narrow display-layer eligibility: may this Context row be
18793
- * carried by the same-turn Work/Thought instead of ending it? Only a foldable
18794
- * Snapshot, a proven Working `tool-jobs` Notice, a proven same-turn Agent
18795
- * relay or a proven same-turn subagent settlement Notice qualifies; every
18796
- * other surfaced Context remains a boundary.
18797
- */
18798
- function isFoldableWorkContext(message, clusterByMember) {
18799
- 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";
18800
19644
  }
18801
19645
  /**
18802
19646
  * Segment one raw transcript window into canonical structural blocks.
@@ -18893,9 +19737,28 @@ function projectTranscriptStructure(messages) {
18893
19737
  }], cluster.members, cluster.turn);
18894
19738
  continue;
18895
19739
  }
18896
- if (isFoldableWorkContext(message, clustering.byMember)) {
18897
- if (runMembers.length > 0) {
18898
- 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) {
18899
19762
  runParts.push({
18900
19763
  kind: "message",
18901
19764
  message
@@ -18904,12 +19767,12 @@ function projectTranscriptStructure(messages) {
18904
19767
  continue;
18905
19768
  }
18906
19769
  flush();
19770
+ out.push({
19771
+ kind: "message",
19772
+ message
19773
+ });
19774
+ continue;
18907
19775
  }
18908
- pushPending([{
18909
- kind: "message",
18910
- message
18911
- }], [message], message.turn);
18912
- continue;
18913
19776
  }
18914
19777
  if (isSurfacedInteractionTool(message)) {
18915
19778
  flush();
@@ -18990,16 +19853,22 @@ function clusterByMemberOf(structure) {
18990
19853
  /**
18991
19854
  * Renderer-neutral Focus presentation projection.
18992
19855
  *
18993
- * The Focus projection over one windowed transcript (plan §12/§33): a turn with
18994
- * an initial prompt is grouped as `user(s) -> FocusActivity`; a turn with only
18995
- * same-turn steers starts with `FocusActivity` and keeps those steers in
18996
- * process order. A turn woken by injected-context keeps that LEADING prefix at
18997
- * its original foundation position before the Thought. Collapsed turns HIDE
18998
- * process rows (a committed pre-steer answer is the explicit exception) and
18999
- * expanded turns restore raw chronology with the final assistant held back.
19000
- * A foldable Context row (producer-declared Snapshot, a `tool-jobs` Notice, an
19001
- * `agent-message` relay or a `subagent-settled` Notice with durable same-turn
19002
- * 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
19003
19872
  * cluster with `instructions`/`catalog`: it joins the Thought instead of
19004
19873
  * becoming turn foundation, while a mixed ambient cluster keeps its indivisible
19005
19874
  * foundation position.
@@ -19020,15 +19889,75 @@ function clusterByMemberOf(structure) {
19020
19889
  * collapsed Focus reorder would otherwise lift it above the turn's held-back
19021
19890
  * final and invert the real chronology (`assistant final` → `Context
19022
19891
  * compacted`). Treating turn-less rows as BOUNDARIES makes the projection
19023
- * agree with the fold: `process A -> Thought A`, `command -> standalone`,
19024
- * `process B -> Thought B`. Both runs may still belong to one model turn (the
19025
- * run-owner component cache supports that), and the semantic disclosure
19026
- * 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.
19027
19897
  */
19028
19898
  function focusProjectionTurnOf(message) {
19029
19899
  if (message.kind === "command") return void 0;
19030
19900
  if (message.kind === "compaction" && message.sourceCommand !== void 0) return void 0;
19031
- 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;
19032
19961
  }
19033
19962
  /**
19034
19963
  * The Thought block for one turn: the caller-resolved TURN-LEVEL Action
@@ -19062,25 +19991,102 @@ const EMPTY_ACTION_STATS = {
19062
19991
  types: /* @__PURE__ */ new Map()
19063
19992
  };
19064
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
+ /**
19065
20071
  * One linear pass over the window: each turn's WHOLE-TURN action aggregate
19066
- * (addendum v2 §18). Focus stats describe the turn, not the row run: a
19067
- * turn-less entry can split one turn into separate consecutive runs
19068
- * ({@link consecutiveTurnGroup}), and every Thought block of that turn must
19069
- * still report the same turn-level number — never merely its own run's.
19070
- * A search reveal / disclosure state cannot change it because none of them
19071
- * participate here. O(n) once per projection, never a per-frame rescan of an
19072
- * 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.
19073
20078
  */
19074
20079
  function focusActionStatsByTurn(messages) {
19075
20080
  const accumulators = /* @__PURE__ */ new Map();
19076
20081
  for (const message of messages) {
19077
- if (!("turn" in message)) continue;
20082
+ const turn = transcriptTurnOf(message);
20083
+ if (turn === void 0) continue;
19078
20084
  const source = compactActionSourceOf(message);
19079
20085
  if (source === void 0) continue;
19080
- let accumulator = accumulators.get(message.turn);
20086
+ let accumulator = accumulators.get(turn);
19081
20087
  if (accumulator === void 0) {
19082
20088
  accumulator = newCompactActionStats();
19083
- accumulators.set(message.turn, accumulator);
20089
+ accumulators.set(turn, accumulator);
19084
20090
  }
19085
20091
  addCompactActionStats(accumulator, source);
19086
20092
  }
@@ -19094,8 +20100,8 @@ function focusActionStatsByTurn(messages) {
19094
20100
  * renders an UNQUALIFIED durable mid-turn `form:'notice'` AFTER the Thought
19095
20101
  * (visible process feedback, never inside the hidden Action candidate set),
19096
20102
  * and hides ordinary Process inside the collapsed root. A proven Working
19097
- * `tool-jobs` Notice, same-turn Agent relay or subagent settlement Notice is
19098
- * 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.
19099
20105
  * Expanded Focus restores the exact raw chronology.
19100
20106
  */
19101
20107
  function projectFocus(messages, activities, expandedTurns, focusMode) {
@@ -19104,12 +20110,42 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19104
20110
  message
19105
20111
  }));
19106
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
+ }
19107
20122
  const out = [];
20123
+ const rootedTurns = /* @__PURE__ */ new Set();
19108
20124
  let index = 0;
19109
20125
  while (index < messages.length) {
19110
20126
  const message = messages[index];
19111
20127
  const turn = focusProjectionTurnOf(message);
19112
- 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
+ }
19113
20149
  out.push({
19114
20150
  kind: "message",
19115
20151
  message
@@ -19117,38 +20153,26 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19117
20153
  index += 1;
19118
20154
  continue;
19119
20155
  }
19120
- const group = consecutiveTurnGroup(messages, index, turn);
19121
- index += group.length;
19122
- const activity = activities.get(turn);
19123
- if (activity === void 0) {
19124
- for (const member of group) out.push({
19125
- kind: "message",
19126
- message: member
19127
- });
19128
- continue;
19129
- }
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;
19130
20162
  const actionStats = actionStatsByTurn.get(turn) ?? EMPTY_ACTION_STATS;
19131
20163
  const expanded = expandedTurns.has(turn);
19132
- const final = eligibleFinalAssistant(activity, group);
19133
- const isCommittedAnswer = (member) => activity !== void 0 && assistantCommittedBeforeSteer(activity, member);
19134
- let latestAssistantIndex = -1;
19135
- for (let memberIndex = group.length - 1; memberIndex >= 0; memberIndex -= 1) if (group[memberIndex]?.kind === "assistant") {
19136
- latestAssistantIndex = memberIndex;
19137
- break;
19138
- }
19139
- const latestAssistant = latestAssistantIndex < 0 ? void 0 : group[latestAssistantIndex];
19140
- const laterProcess = latestAssistantIndex < 0 ? false : group.slice(latestAssistantIndex + 1).some((member) => member.kind !== "user" && !isSurfacedContext(member));
19141
- 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);
19142
20166
  if (expanded) {
19143
- const rootOwner = group[0];
19144
- const boundary = focusThoughtLeadBoundary(group);
19145
- 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({
19146
20169
  kind: "message",
19147
20170
  message: member
19148
20171
  });
19149
- 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);
19150
20174
  const emitTailRow = (member) => {
19151
- if (isFocusPersistentInputRow(member)) {
20175
+ if (isFocusPersistentInputRow(member) || isFocusBridgeControlRow(member)) {
19152
20176
  out.push({
19153
20177
  kind: "message",
19154
20178
  message: member,
@@ -19156,7 +20180,7 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19156
20180
  });
19157
20181
  return;
19158
20182
  }
19159
- if (final !== void 0 && member === final.message) return;
20183
+ if (regionFinal !== void 0 && member === regionFinal.message) return;
19160
20184
  if (member === pendingFinalAssistant) return;
19161
20185
  if (isCommittedAnswer(member)) {
19162
20186
  out.push({
@@ -19176,7 +20200,7 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19176
20200
  focusPresentationOwner: rootOwner
19177
20201
  });
19178
20202
  };
19179
- 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({
19180
20204
  kind: "work",
19181
20205
  span: block.span,
19182
20206
  focusOwnerTurn: turn,
@@ -19184,75 +20208,79 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19184
20208
  });
19185
20209
  else if (block.kind === "context-cluster") for (const member of block.cluster.members) emitTailRow(member);
19186
20210
  else emitTailRow(block.message);
19187
- if (final !== void 0) out.push(final.truncated ? {
20211
+ if (regionFinal !== void 0) out.push(regionFinal.truncated ? {
19188
20212
  kind: "message",
19189
- message: final.message,
20213
+ message: regionFinal.message,
19190
20214
  truncated: true
19191
20215
  } : {
19192
20216
  kind: "message",
19193
- message: final.message
20217
+ message: regionFinal.message
19194
20218
  });
19195
20219
  continue;
19196
20220
  }
19197
- const leadBoundary = focusThoughtLeadBoundary(group);
20221
+ const leadBoundary = focusThoughtLeadBoundary(members);
19198
20222
  const foldableSnapshots = {
19199
- clusterByMember: clusterAdjacentAmbientContext(group).byMember,
19200
- workByMember: workByMemberOf(projectTranscriptStructure(group)),
19201
- thoughtOwned: activity !== void 0
20223
+ clusterByMember: clusterAdjacentAmbientContext(members).byMember,
20224
+ workByMember: workByMemberOf(projectTranscriptStructure(members)),
20225
+ thoughtOwned: true
19202
20226
  };
19203
- const firstCommittedIndex = group.findIndex(isCommittedAnswer);
20227
+ const firstCommittedIndex = members.findIndex(isCommittedAnswer);
19204
20228
  const hidden = [];
19205
20229
  const preThought = [];
19206
20230
  const postThought = [];
19207
- if (firstCommittedIndex < 0) {
19208
- for (let index = 0; index < group.length; index += 1) {
19209
- const member = group[index];
19210
- const disposition = collapsedFocusRowDisposition(member, index, leadBoundary, foldableSnapshots);
19211
- if (disposition === "pre-thought" || disposition === "post-thought") (disposition === "pre-thought" ? preThought : postThought).push(member);
19212
- 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;
19213
20237
  }
19214
- out.push(...preThought.map((member) => ({
19215
- kind: "message",
19216
- message: member
19217
- })));
19218
- out.push(...focusActivityBlock(activity, group[0], actionStats, hidden));
19219
- out.push(...postThought.map((member) => ({
19220
- kind: "message",
19221
- message: member
19222
- })));
19223
- for (const member of group) if (member.kind === "compaction") out.push({
19224
- kind: "message",
19225
- message: member
19226
- });
19227
- } else {
19228
- const beforeCommitted = group.slice(0, firstCommittedIndex);
19229
- for (let index = 0; index < beforeCommitted.length; index += 1) {
19230
- const member = beforeCommitted[index];
19231
- const disposition = collapsedFocusRowDisposition(member, index, leadBoundary, foldableSnapshots);
19232
- if (disposition === "pre-thought" || disposition === "post-thought") (disposition === "pre-thought" ? preThought : postThought).push(member);
19233
- 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);
19234
20262
  }
19235
20263
  const postCommittedFoldableSnapshots = {
19236
20264
  ...foldableSnapshots,
19237
20265
  thoughtOwned: false
19238
20266
  };
19239
20267
  const postCommitted = [];
19240
- for (let index = firstCommittedIndex; index < group.length; index += 1) {
19241
- const member = group[index];
19242
- if (final !== void 0 && member === final.message) continue;
19243
- 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);
19244
20272
  else hidden.push(member);
19245
20273
  }
19246
20274
  out.push(...preThought.map((member) => ({
19247
20275
  kind: "message",
19248
20276
  message: member
19249
20277
  })));
19250
- out.push(...focusActivityBlock(activity, group[0], actionStats, hidden));
20278
+ out.push(...focusActivityBlock(activity, rootOwner, actionStats, hidden));
19251
20279
  out.push(...postThought.map((member) => ({
19252
20280
  kind: "message",
19253
20281
  message: member
19254
20282
  })));
19255
- for (const member of beforeCommitted) if (member.kind === "compaction") out.push({
20283
+ for (const member of preCommittedCompactions) out.push({
19256
20284
  kind: "message",
19257
20285
  message: member
19258
20286
  });
@@ -19260,32 +20288,91 @@ function projectFocus(messages, activities, expandedTurns, focusMode) {
19260
20288
  kind: "message",
19261
20289
  message: member
19262
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;
19263
20300
  }
19264
- 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({
19265
20311
  kind: "message",
19266
- message: final.message,
20312
+ message: member
20313
+ });
20314
+ if (regionFinal !== void 0) out.push(regionFinal.truncated ? {
20315
+ kind: "message",
20316
+ message: regionFinal.message,
19267
20317
  truncated: true
19268
20318
  } : {
19269
20319
  kind: "message",
19270
- message: final.message
20320
+ message: regionFinal.message
19271
20321
  });
19272
20322
  }
19273
20323
  return out;
19274
20324
  }
19275
20325
  /**
19276
- * The canonical structural blocks the expanded Focus TAIL consumes: one turn
19277
- * group from its Thought-lead boundary onward. The held-back final is included,
19278
- * so cluster membership is computed from exactly the raw adjacency the window
19279
- * would give. `projectFocus` emits a canonical Work span as a nested `work`
19280
- * 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
19281
20332
  * Work/cluster boundary IDENTITY (owner and member objects) instead of display
19282
20333
  * strings (plan §25).
19283
- * @param group - one turn's consecutive raw messages.
19284
- * @param boundary - the group's Thought-lead boundary ({@link focusThoughtLeadBoundary}).
19285
- * 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.
19286
20338
  */
19287
- function focusExpandedTailStructure(group, boundary) {
19288
- 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;
19289
20376
  }
19290
20377
  /** Rows that remain visible outside the collapsed Thought as persistent
19291
20378
  * input/context boundaries. The semantic class stays Context for injected
@@ -19298,50 +20385,25 @@ function isFocusPersistentInputRow(message) {
19298
20385
  }
19299
20386
  function collapsedFocusRowDisposition(message, index, leadBoundary, foldableSnapshots) {
19300
20387
  if (!isFocusPersistentInputRow(message)) return "hidden";
19301
- 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
+ }
19302
20392
  if (index >= leadBoundary && isNoticeContext(message)) return "post-thought";
19303
20393
  return "pre-thought";
19304
20394
  }
19305
- /**
19306
- * One turn's maximal run of CONSECUTIVE same-turn rows starting at `start`.
19307
- * A turn-less entry (window summary) may SPLIT a turn into separate runs, and
19308
- * the projection folds each run independently — this helper is shared by the
19309
- * projection and the collapsed visibility predicate so their index and
19310
- * `focusThoughtLeadBoundary` math can never diverge on a non-monotonic window.
19311
- * @param messages - the transcript window.
19312
- * @param start - the run's first index.
19313
- * @param turn - the run's turn number.
19314
- */
19315
- /**
19316
- * The consecutive rows of ONE Focus projection turn, starting at `start`.
19317
- *
19318
- * Exported so a caller that needs the Focus disposition of a SINGLE row can
19319
- * project that turn's own group instead of the whole loaded history (the search
19320
- * seat's ancestry probe). It is the SAME segmentation `projectFocus` walks, so
19321
- * the slice and the full projection can never disagree.
19322
- */
19323
- function consecutiveTurnGroup(messages, start, turn) {
19324
- const group = [messages[start]];
19325
- let index = start + 1;
19326
- while (index < messages.length) {
19327
- const next = messages[index];
19328
- if (focusProjectionTurnOf(next) !== turn) break;
19329
- group.push(next);
19330
- index += 1;
19331
- }
19332
- return group;
19333
- }
19334
20395
  /** The Thought-lead boundary of one turn group: the prefix that stays above the
19335
20396
  * Thought. It starts after the FIRST unmarked user row when one exists; a turn
19336
20397
  * with no human user (an inject-woken / next-turn wakeup turn) starts at the
19337
20398
  * group beginning. In both cases the boundary then consumes leading surfaced
19338
- * Context rows that are NOT foldable (the wakeup cause, `instructions`,
19339
- * `catalog`, an unqualified notice or relay). The first FOLDABLE Context row
19340
- * (Snapshot, a proven Working tool-jobs Notice, Agent relay or subagent
19341
- * settlement Notice) ends the
19342
- * foundation and becomes Thought content — so a next-turn wakeup notice stays
19343
- * visible while the Snapshot and same-turn deliveries that arrive during the
19344
- * 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
19345
20407
  * `instructions`/`catalog` + Snapshot cluster keeps its indivisible foundation
19346
20408
  * position. `llm/retry`/max-token orchestration rows are not surfaced Context,
19347
20409
  * so they never enter the prefix. Without steer metadata the first user remains
@@ -19353,7 +20415,8 @@ function focusThoughtLeadBoundary(group) {
19353
20415
  while (true) {
19354
20416
  const member = group[end];
19355
20417
  if (member === void 0 || !isSurfacedContext(member)) break;
19356
- if (isFoldableWorkContext(member, clusterByMember)) break;
20418
+ const carriage = workContextCarriageOf(member, clusterByMember);
20419
+ if (carriage === "thought" || carriage === "work") break;
19357
20420
  end += 1;
19358
20421
  }
19359
20422
  return end;
@@ -19587,7 +20650,7 @@ function summarizeWorkSpan(span) {
19587
20650
  * nothing; an equal-time following row, by contrast, is already visible and
19588
20651
  * closes the Activity from the same instant (a point span hides its duration —
19589
20652
  * a coarse clock must never leave it live). A following block with NO proven
19590
- * 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
19591
20654
  * the live tail without closing it. The lookup is an exact offline 2D
19592
20655
  * dominance-min, so no ordering assumption about the Activities' starts is
19593
20656
  * needed.
@@ -19596,15 +20659,15 @@ function summarizeWorkSpan(span) {
19596
20659
  * end after its turn, so a row of a later turn can never lengthen an
19597
20660
  * already-frozen Activity.
19598
20661
  *
19599
- * KNOWN LIMIT (pinned by `test/activity-clock.test.ts` as a live/cold
19600
- * differential): the canonical Work MEMBERSHIP (which Process rows share one
19601
- * span) is decided by the fold's row ORDER, not by this clock. When cold
19602
- * hydration appends a step's settlement AFTER that step's tool rows while its
19603
- * first visible text preceded them, cold shows ONE Activity where the live fold
19604
- * showed TWO; a raw-adjacent settled-read pair is moreover MERGED by the fold's
19605
- * read grouping before any display rule could act. Converging that belongs to
19606
- * the fold's display-order authority (the `convergeStepLaneOrder` mechanism plus
19607
- * 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.
19608
20671
  * @param structure - the canonical structural blocks for one window.
19609
20672
  * @param turnActivities - the folded turn boundary facts of the SAME snapshot.
19610
20673
  */
@@ -19722,8 +20785,9 @@ function interactionBoundaryOf(span) {
19722
20785
  /** The first ACTUALLY VISIBLE time of one non-Process boundary block: the
19723
20786
  * earliest reliable sidecar start among the row(s) that carry the boundary.
19724
20787
  * `undefined` means the block has no provable first-visible evidence (a
19725
- * synthetic window summary, a command row, a row the fold could not time) —
19726
- * 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. */
19727
20791
  function boundaryTimeOf(block) {
19728
20792
  if (block.kind === "message") return transcriptTimingOf(block.message)?.startedAt;
19729
20793
  if (block.kind === "context-cluster") {
@@ -21341,11 +22405,19 @@ function toolNode(message, key, options) {
21341
22405
  }, ...body.args, ...children, ...body.result);
21342
22406
  }
21343
22407
  /**
21344
- * The safe body of one injected Context row through the existing
21345
- * `systemContextBody` helper (never a raw `<system-reminder>` XML envelope);
21346
- * a body that is not an envelope at all is shown verbatim.
21347
- */
21348
- 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);
21349
22421
  const body = systemContextBody(message.text);
21350
22422
  if (body === void 0) return [ui.md({
21351
22423
  key: "body",
@@ -21357,7 +22429,7 @@ function contextBodyNodes(message) {
21357
22429
  text: sanitizeDisplayText(body.join("\n"))
21358
22430
  })];
21359
22431
  }
21360
- function contextMemberNode(message, key) {
22432
+ function contextMemberNode(message, key, options) {
21361
22433
  const kind = contextPresentationKind(message);
21362
22434
  const head = sanitizedPhysicalLine(message.label ?? contextFormOf(message) ?? "Context");
21363
22435
  return ui.card({
@@ -21366,7 +22438,7 @@ function contextMemberNode(message, key) {
21366
22438
  }, ui.badge({
21367
22439
  key: "kind",
21368
22440
  text: kind ?? "generic"
21369
- }), ...contextBodyNodes(message));
22441
+ }), ...contextBodyNodes(message, options));
21370
22442
  }
21371
22443
  function contextClusterMemberNode(message, key, options) {
21372
22444
  const kind = contextPresentationKind(message);
@@ -21380,14 +22452,14 @@ function contextClusterMemberNode(message, key, options) {
21380
22452
  key: "identity",
21381
22453
  text: head,
21382
22454
  wrap: "none"
21383
- }), ...contextBodyNodes(message));
22455
+ }), ...contextBodyNodes(message, options));
21384
22456
  const expanded = disclosure.expandedContextRowOwners.has(message);
21385
22457
  return ui.section({
21386
22458
  key,
21387
22459
  head,
21388
22460
  collapsible: true,
21389
22461
  collapsed: !expanded
21390
- }, ...expanded ? contextBodyNodes(message) : []);
22462
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21391
22463
  }
21392
22464
  function canCollapseContextRow(message) {
21393
22465
  const kind = contextPresentationKind(message);
@@ -21444,7 +22516,7 @@ function relayContextRowNode(message, key, options, allowDisclosure) {
21444
22516
  if (!allowDisclosure || disclosure === void 0 || !canCollapseContextRow(message)) return ui.card({
21445
22517
  key,
21446
22518
  head: title
21447
- }, ...contextBodyNodes(message));
22519
+ }, ...contextBodyNodes(message, options));
21448
22520
  const expanded = disclosure.expandedContextRowOwners.has(message);
21449
22521
  const preview = relayHeadPreview(sanitizeDisplayText(message.text));
21450
22522
  return ui.section({
@@ -21469,13 +22541,13 @@ function relayContextRowNode(message, key, options, allowDisclosure) {
21469
22541
  })]),
21470
22542
  collapsible: true,
21471
22543
  collapsed: !expanded
21472
- }, ...expanded ? contextBodyNodes(message) : []);
22544
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21473
22545
  }
21474
22546
  function contextRowNode(message, key, options, allowDisclosure = true) {
21475
22547
  const disclosure = options.innerDisclosure;
21476
22548
  const kind = contextPresentationKind(message);
21477
22549
  if (message.context === true && kind === "relay") return relayContextRowNode(message, key, options, allowDisclosure);
21478
- 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);
21479
22551
  const expanded = disclosure.expandedContextRowOwners.has(message);
21480
22552
  if (kind === "notice") {
21481
22553
  const title = message.label === void 0 || message.label === "" ? "Notice" : sanitizedPhysicalLine(message.label);
@@ -21495,7 +22567,7 @@ function contextRowNode(message, key, options, allowDisclosure = true) {
21495
22567
  })]),
21496
22568
  collapsible: true,
21497
22569
  collapsed: !expanded
21498
- }, ...expanded ? contextBodyNodes(message) : []);
22570
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21499
22571
  }
21500
22572
  const identity = kind === "recall" ? message.label === void 0 || message.label === "" ? "Session recall" : `Session recall · ${sanitizedPhysicalLine(message.label)}` : message.label ?? contextFormOf(message) ?? "Context";
21501
22573
  return ui.section({
@@ -21503,7 +22575,7 @@ function contextRowNode(message, key, options, allowDisclosure = true) {
21503
22575
  head: sanitizedPhysicalLine(identity),
21504
22576
  collapsible: true,
21505
22577
  collapsed: !expanded
21506
- }, ...expanded ? contextBodyNodes(message) : []);
22578
+ }, ...expanded ? contextBodyNodes(message, options) : []);
21507
22579
  }
21508
22580
  function systemNode(message, key, options, allowDisclosure = true) {
21509
22581
  if (message.context === true) return contextRowNode(message, key, options, allowDisclosure);
@@ -22151,7 +23223,8 @@ function imageRefIdsOf(message) {
22151
23223
  if (message.displayBlocks !== void 0) {
22152
23224
  for (const display of message.displayBlocks) if (display.kind === "content") pushBlocks([display.block]);
22153
23225
  } else if (message.content !== void 0) pushBlocks(message.content);
22154
- } else if (message.kind === "tool") visitRow(message);
23226
+ } else if (message.kind === "system") pushBlocks(message.content);
23227
+ else if (message.kind === "tool") visitRow(message);
22155
23228
  imageRefIdsCache.set(message, {
22156
23229
  display,
22157
23230
  assistant,
@@ -22259,6 +23332,7 @@ function messageStampOf(message, key, options) {
22259
23332
  break;
22260
23333
  case "system":
22261
23334
  parts.push(disclosureTokenOf(message, key, options));
23335
+ parts.push(imageTokensOf(message, options));
22262
23336
  break;
22263
23337
  case "command":
22264
23338
  case "compaction":
@@ -22340,6 +23414,17 @@ function focusDuration(activity, options) {
22340
23414
  const duration = formatCompactDuration(options.focusElapsedMs?.get(activity));
22341
23415
  return duration === "0s" ? void 0 : duration;
22342
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
+ }
22343
23428
  function focusRootHead(slot, options) {
22344
23429
  const phase = options.focusPhase ?? "working";
22345
23430
  const duration = focusDuration(slot.activity, options);
@@ -22371,10 +23456,7 @@ function focusRootHead(slot, options) {
22371
23456
  index: preview.index,
22372
23457
  ...preview.name === void 0 ? {} : { name: preview.name }
22373
23458
  })));
22374
- const action = slot.action === void 0 ? void 0 : compactActionBody(compactActionPresentation(slot.action, {
22375
- ...options.toolPresenter === void 0 ? {} : { presenter: options.toolPresenter },
22376
- ...options.cwd === void 0 ? {} : { cwd: options.cwd }
22377
- }));
23459
+ const action = focusRootActionBody(slot.action, options);
22378
23460
  if (preparing !== void 0 || action !== void 0) head.push(ui.text({
22379
23461
  key: "action",
22380
23462
  text: sanitizedPhysicalLine(`Action: ${preparing ?? action}`),
@@ -22453,7 +23535,7 @@ function focusNestedWorkDescriptor(span, keys, options, prefix, lifetime, prepar
22453
23535
  materialize: () => focusNestedWorkNode(span, keys, options, prefix, lifetime, preparing)
22454
23536
  };
22455
23537
  }
22456
- function focusMainBlocks(blocks, keys, options, prefix, preparingByRootOwner, preparingByWorkOwner, standalonePreparing, workLifetimes) {
23538
+ function focusMainBlocks(blocks, keys, options, prefix, preparingByRootOwner, preparingByWorkOwner, standalonePreparing, attachedPreparingRootOwner, workLifetimes) {
22457
23539
  const slotsByOwner = /* @__PURE__ */ new Map();
22458
23540
  const rootsWithWorkPreparing = /* @__PURE__ */ new Set();
22459
23541
  const rows = [];
@@ -22494,11 +23576,20 @@ function focusMainBlocks(blocks, keys, options, prefix, preparingByRootOwner, pr
22494
23576
  slot.children.push(focusNestedWorkDescriptor(block.span, keys, options, prefix, workLifetimes.get(block.span.owner), preparingByWorkOwner.get(block.span.owner) ?? []));
22495
23577
  }
22496
23578
  }
23579
+ const deferredStandalone = [];
22497
23580
  for (const slot of slotsByOwner.values()) {
22498
23581
  if (!slot.expanded || slot.preparing.length === 0 || rootsWithWorkPreparing.has(slot.owner)) continue;
22499
- 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);
22500
23587
  }
22501
- 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
+ ];
22502
23593
  }
22503
23594
  /** The ONE Focus Activity root descriptor (canonical occurrence owner). */
22504
23595
  function focusRootDescriptor(slot, keys, options, prefix) {
@@ -22515,6 +23606,9 @@ function focusRootDescriptor(slot, keys, options, prefix) {
22515
23606
  ];
22516
23607
  for (const preview of slot.preparing) stamp.push(...preparingStampOf(preview, options.cwd));
22517
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);
22518
23612
  if (slot.action !== void 0) stamp.push(options.cwd ?? "");
22519
23613
  return {
22520
23614
  key,
@@ -22539,48 +23633,72 @@ function focusRootDescriptor(slot, keys, options, prefix) {
22539
23633
  }
22540
23634
  };
22541
23635
  }
22542
- /** Preparing belongs either to the exact canonical trailing Work owner, to a
22543
- * 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
+ */
22544
23643
  function focusPreparingPlacement(messages, blocks, options) {
22545
23644
  const groups = groupPreparingPreviews(options.preparingPreviews ?? []);
22546
23645
  if (groups.length === 0 || options.window?.hasNewer !== false) return {
22547
23646
  byRootOwner: /* @__PURE__ */ new Map(),
22548
23647
  byWorkOwner: /* @__PURE__ */ new Map(),
22549
- standalone: []
23648
+ standalone: [],
23649
+ attachedRootOwner: void 0
22550
23650
  };
22551
23651
  const activities = options.turnActivities ?? EMPTY_TURN_ACTIVITIES;
22552
23652
  const expandedBlocks = projectFocus(messages, activities, new Set(activities.keys()), true);
22553
23653
  const trailing = projectTranscriptStructure(messages).at(-1);
22554
- let rootOwner;
22555
- 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] ?? [];
22556
23667
  let turn;
23668
+ let workOwner;
23669
+ let attachedRootOwner;
22557
23670
  if (trailing?.kind === "work") {
22558
- turn = trailing.span.turn;
22559
- if (activities.get(turn)?.completed === false) {
22560
- const projected = expandedBlocks.findLast((block) => block.kind === "work" && block.span.owner === trailing.span.owner);
22561
- if (projected?.kind === "work") {
22562
- rootOwner = projected.focusPresentationOwner;
22563
- workOwner = rootOwner === void 0 ? void 0 : trailing.span.owner;
22564
- }
22565
- }
22566
- } else {
22567
- const lastMessage = trailing?.kind === "message" ? trailing.message : trailing?.kind === "context-cluster" ? trailing.cluster.members.at(-1) : void 0;
22568
- if (lastMessage !== void 0 && "turn" in lastMessage && !(lastMessage.kind === "compaction" && lastMessage.sourceCommand !== void 0) && activities.get(lastMessage.turn)?.completed === false) {
22569
- turn = lastMessage.turn;
22570
- const projected = expandedBlocks.findLast((block) => block.kind === "activity" && block.activity.turn === turn);
22571
- rootOwner = projected?.kind === "activity" ? projected.owner : void 0;
22572
- }
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
+ };
22573
23694
  }
22574
- if (rootOwner === void 0 || turn === void 0 || !blocks.some((block) => block.kind === "activity" && block.owner === rootOwner)) return {
22575
- byRootOwner: /* @__PURE__ */ new Map(),
22576
- byWorkOwner: /* @__PURE__ */ new Map(),
22577
- standalone: groups.flatMap(([, previews]) => previews)
22578
- };
22579
- 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);
22580
23697
  return {
22581
- 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]]),
22582
23699
  byWorkOwner: workOwner === void 0 || selected.length === 0 ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map([[workOwner, selected]]),
22583
- standalone: groups.filter(([groupTurn]) => groupTurn !== turn).flatMap(([, previews]) => previews)
23700
+ standalone: groups.filter(([groupTurn]) => groupTurn !== turn).flatMap(([, previews]) => previews),
23701
+ attachedRootOwner
22584
23702
  };
22585
23703
  }
22586
23704
  /** The members whose current transcript body is actually materialized. */
@@ -22752,9 +23870,10 @@ function settledFinalAssistantStats(messages, activities) {
22752
23870
  if (activities === void 0) return EMPTY_ASSISTANT_STATS;
22753
23871
  const rowsByTurn = /* @__PURE__ */ new Map();
22754
23872
  for (const message of messages) {
22755
- if (!("turn" in message)) continue;
22756
- const rows = rowsByTurn.get(message.turn);
22757
- 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]);
22758
23877
  else rows.push(message);
22759
23878
  }
22760
23879
  const result = /* @__PURE__ */ new Map();
@@ -22841,7 +23960,7 @@ function describeTranscriptMainBlocksForPreset(messages, keys, options) {
22841
23960
  const focusBlocks = projectFocus(messages, options.turnActivities ?? EMPTY_TURN_ACTIVITIES, options.expandedFocusTurns ?? EMPTY_TURN_SET, true);
22842
23961
  const workLifetimes = resolveWorkLifetimes(structure, options.turnActivities ?? EMPTY_TURN_ACTIVITIES);
22843
23962
  const preparing = focusPreparingPlacement(messages, focusBlocks, options);
22844
- 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);
22845
23964
  }
22846
23965
  return legacyMainBlocks(structure, keys, renderOptions, prefix, trailing, adopted, standalone);
22847
23966
  }
@@ -22880,4 +23999,4 @@ const EMPTY_TURN_SET = /* @__PURE__ */ new Set();
22880
23999
  const EMPTY_TURN_ACTIVITIES = /* @__PURE__ */ new Map();
22881
24000
  const EMPTY_ASSISTANT_STATS = /* @__PURE__ */ new Map();
22882
24001
  //#endregion
22883
- 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, taskStatusWord 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, markdownTheme as Fr, SESSION_PENDING_LABEL as Ft, compactActionSlotLine as G, historyFilePath as Gi, chooseListedSession as Gn, sanitizeDisplayText as Gr, subagentJobTranscriptId as Gt, formatCompactDuration as H, isAssistantTokenDelta as Hi, sessionBrowserErrorNotice as Hn, singlePhysicalLine as Hr, isTaskItemFailure as Ht, isFoldableWorkContext as I, latestLine as Ii, thinkingPreviewTail as In, selectListTheme 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, setTheme as Lr, buildSessionWorkspaceView as Lt, consecutiveTurnGroup as M, isVisualToolName as Mi, SVG_MAX_RASTER_PIXELS as Mn, HOST_MARKDOWN_OPTIONS as Mr, svgDigest as Mt, focusProjectionTurnOf as N, recentTurnThreshold as Ni, SVG_MAX_RASTER_SIDE as Nn, color 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, editorTheme 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, settingsListTheme 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, sanitizeDisplayLog as Ur, projectTaskItems as Ut, compactActionStatParts as V, StepUsageAccumulator as Vi, sanitizeTerminalText as Vn, sanitizedPhysicalLine as Vr, isTaskItemActive as Vt, compactActionSignature as W, appendHistoryRecord as Wi, canonicalFullSessionId as Wn, sanitizeDisplaySegment 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, taskStatusColor 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 };