pantheon-opencode 1.7.0 → 2.0.0-beta.1

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 (168) hide show
  1. package/AGENTS.global.md +2 -2
  2. package/AGENTS.md +3 -3
  3. package/CHANGELOG.md +64 -60
  4. package/README.md +52 -45
  5. package/README.pt-BR.md +19 -19
  6. package/bin/pantheon-init.mjs +11 -48
  7. package/package.json +9 -13
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +7 -6
  11. package/scripts/{check-plugin-v2-coverage.mjs → check-plugin-coverage.mjs} +7 -7
  12. package/scripts/{decision-router-v2-budget.mjs → decision-router-budget-gates.mjs} +1 -1
  13. package/scripts/{decision-router-v2-egress.mjs → decision-router-egress.mjs} +1 -1
  14. package/scripts/decision-router.mjs +2 -2
  15. package/scripts/docs-media.mjs +1 -1
  16. package/scripts/doctor.mjs +225 -136
  17. package/scripts/install/behavior-overrides.bundle.mjs +123 -0
  18. package/scripts/install/{v2-capabilities.mjs → capabilities.mjs} +7 -7
  19. package/scripts/install/config-migration.mjs +60 -253
  20. package/scripts/install/file-inventory.mjs +6 -4
  21. package/scripts/install/interactive.mjs +1 -1
  22. package/scripts/install/opencode-state.mjs +13 -12
  23. package/scripts/install/opencode-version.mjs +97 -162
  24. package/scripts/install/opencode.mjs +271 -428
  25. package/scripts/install/plan.mjs +1 -9
  26. package/scripts/install/plugin.mjs +19 -35
  27. package/scripts/install/shared.mjs +40 -1
  28. package/scripts/package-evidence.mjs +1 -4
  29. package/scripts/probe-pantheon-cost.mjs +1 -1
  30. package/scripts/reconcile.mjs +5 -7
  31. package/scripts/release-gates.mjs +22 -61
  32. package/scripts/setup-v2-config.mjs +10 -8
  33. package/scripts/setup.mjs +12 -22
  34. package/scripts/sync-tui.mjs +9 -17
  35. package/scripts/{test-opencode-v2-sandbox.sh → test-opencode-sandbox.sh} +9 -9
  36. package/scripts/update-skills-lock.mjs +24 -12
  37. package/scripts/update.mjs +17 -1
  38. package/scripts/validate-routing.mjs +79 -4
  39. package/scripts/validate-sandbox-install.mjs +3 -3
  40. package/skills-lock.json +25 -8
  41. package/src/agents/zeus.md +1 -0
  42. package/src/pantheon/behavior-overrides.ts +191 -0
  43. package/src/pantheon/{v2-bounded-read.ts → bounded-read.ts} +1 -1
  44. package/src/pantheon/cost-command.ts +1 -1
  45. package/src/pantheon/{v2-decision-contracts.ts → decision-contracts.ts} +3 -3
  46. package/src/pantheon/{v2-decision-points → decision-points}/p1-agent.ts +3 -3
  47. package/src/pantheon/{v2-decision-points → decision-points}/p10-claims.ts +2 -2
  48. package/src/pantheon/{v2-decision-points → decision-points}/p11-catalog.ts +2 -2
  49. package/src/pantheon/{v2-decision-points → decision-points}/p2-skill.ts +3 -3
  50. package/src/pantheon/{v2-decision-points → decision-points}/p3-complexity.ts +6 -6
  51. package/src/pantheon/{v2-decision-points → decision-points}/p4-memory.ts +2 -2
  52. package/src/pantheon/{v2-decision-points → decision-points}/p5-themis-verify.ts +2 -2
  53. package/src/pantheon/{v2-decision-points → decision-points}/p6-council.ts +3 -3
  54. package/src/pantheon/{v2-decision-points → decision-points}/p7-loop.ts +5 -5
  55. package/src/pantheon/{v2-decision-points → decision-points}/p8-guardrail.ts +2 -2
  56. package/src/pantheon/{v2-decision-points → decision-points}/p9-memory-compaction.ts +2 -2
  57. package/src/pantheon/{v2-decision-points.ts → decision-points.ts} +5 -5
  58. package/src/pantheon/{v2-decision-policy.ts → decision-policy.ts} +2 -2
  59. package/src/pantheon/{v2-decision-prompt-surface.ts → decision-prompt-surface.ts} +3 -3
  60. package/src/pantheon/{v2-decision-registry.ts → decision-registry.ts} +10 -13
  61. package/src/pantheon/{v2-decision-resource-ids.ts → decision-resource-ids.ts} +1 -1
  62. package/src/pantheon/{v2-decision-shadow.ts → decision-shadow.ts} +1 -1
  63. package/src/pantheon/{v2-decision-telemetry.ts → decision-telemetry.ts} +1 -1
  64. package/src/pantheon/{v2-execute-after.ts → execute-after.ts} +4 -4
  65. package/src/pantheon/goal-store.ts +7 -0
  66. package/src/pantheon/{v2-hook-engine.ts → hook-engine.ts} +3 -3
  67. package/src/pantheon/jev-decision-tool.ts +3 -3
  68. package/src/pantheon/jev-decisions.ts +12 -6
  69. package/src/pantheon/jev-escalation.ts +6 -6
  70. package/src/pantheon/jev-quality-score.ts +2 -2
  71. package/src/pantheon/jev-rank-verify.ts +2 -2
  72. package/src/pantheon/jev-risk-gate.ts +4 -4
  73. package/src/pantheon/local-decision-agents.ts +1 -1
  74. package/src/pantheon/local-decision-router.ts +1 -1
  75. package/src/pantheon/local-decision-tool.ts +2 -2
  76. package/src/pantheon/local-orchestration.ts +1 -1
  77. package/src/pantheon/model-command.ts +1 -1
  78. package/src/pantheon/{v2-vision.ts → native-vision.ts} +12 -15
  79. package/src/pantheon/pantheon-decision-catalog.ts +12 -0
  80. package/src/pantheon/{v2-shell-hooks.ts → shell-hooks.ts} +4 -4
  81. package/src/pantheon/{v2-tools.ts → tools.ts} +4 -4
  82. package/src/pantheon/{v2-unsupported.d.mts → unsupported.d.mts} +3 -3
  83. package/src/pantheon/{v2-unsupported.mjs → unsupported.mjs} +8 -8
  84. package/src/pantheon/update-notifier.ts +101 -0
  85. package/src/pantheon/vision-local.ts +12 -3
  86. package/src/pantheon/vision.ts +120 -2
  87. package/src/{plugin-v2 → plugin}/index.ts +7 -7
  88. package/src/plugin.ts +2875 -500
  89. package/src/plugins/hook-runner.ts +3 -3
  90. package/src/plugins/tui/dist/server.d.ts +23 -9
  91. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  92. package/src/plugins/tui/dist/server.js +25 -12
  93. package/src/plugins/tui/dist/server.js.map +1 -1
  94. package/src/plugins/tui/dist/tui.d.ts +1023 -494
  95. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  96. package/src/plugins/tui/dist/tui.js +4841 -2066
  97. package/src/plugins/tui/dist/tui.js.map +1 -1
  98. package/src/plugins/tui/{index-v2.ts → index.ts} +1 -1
  99. package/src/plugins/tui/package-lock.json +2 -42
  100. package/src/plugins/tui/package.json +4 -10
  101. package/src/plugins/tui/src/cost-data.ts +1 -1
  102. package/src/plugins/tui/src/index.tsx +4222 -2822
  103. package/src/plugins/tui/src/pantheon-settings-state.ts +111 -0
  104. package/src/plugins/tui/src/pantheon-settings.tsx +236 -0
  105. package/src/plugins/tui/src/server.ts +23 -10
  106. package/src/plugins/tui/src/update-notice.ts +86 -0
  107. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  108. package/src/plugins/tui/tsdown.config.ts +3 -5
  109. package/src/plugins/tui/tui.ts +1 -2
  110. package/src/routing.yml +36 -0
  111. package/src/skills/README.md +16 -1
  112. package/src/skills/artifact-management/SKILL.md +10 -67
  113. package/src/skills/artifact-management/references/artifact-templates.md +71 -0
  114. package/src/skills/auto-continue/SKILL.md +10 -0
  115. package/src/skills/code-review-checklist/SKILL.md +11 -44
  116. package/src/skills/code-review-checklist/references/review-checklists.md +54 -0
  117. package/src/skills/instruction-forge/SKILL.md +57 -0
  118. package/src/skills/instruction-forge/references/agents-md-doctrine.md +50 -0
  119. package/src/skills/instruction-forge/references/eval-doctrine.md +37 -0
  120. package/src/skills/instruction-forge/references/skill-doctrine.md +62 -0
  121. package/src/skills/memory-bank/SKILL.md +11 -90
  122. package/src/skills/memory-bank/references/anti-patterns.md +33 -0
  123. package/src/skills/memory-bank/references/product-adoption.md +19 -0
  124. package/src/skills/memory-bank/references/storage-model.md +21 -0
  125. package/src/skills/memory-bank/references/structure-and-frequency.md +44 -0
  126. package/src/skills/reflect/SKILL.md +1 -0
  127. package/src/skills/session-goal/SKILL.md +7 -54
  128. package/src/skills/session-goal/references/goal-format.md +26 -0
  129. package/src/skills/session-goal/references/session-reuse.md +44 -0
  130. package/src/skills/tdd-with-agents/SKILL.md +11 -101
  131. package/src/skills/tdd-with-agents/references/advanced-testing-patterns.md +58 -0
  132. package/src/skills/tdd-with-agents/references/testing-by-layer.md +60 -0
  133. package/src/skills/visual-review-pipeline/SKILL.md +11 -120
  134. package/src/skills/visual-review-pipeline/references/findings-schema.md +49 -0
  135. package/src/skills/visual-review-pipeline/references/workflow-steps.md +111 -0
  136. package/scripts/hooks/log-session-start.sh +0 -48
  137. package/scripts/hooks/validate-post-conditions.sh +0 -21
  138. package/scripts/hooks/validate-talos-scope.sh +0 -50
  139. package/scripts/hooks/validate-tool-safety.sh +0 -49
  140. package/src/pantheon/goal-loop.ts +0 -314
  141. package/src/pantheon/idle-continuation.ts +0 -52
  142. package/src/pantheon/todo-preserve.ts +0 -301
  143. package/src/pantheon/tool-ceiling.ts +0 -159
  144. package/src/pantheon/v2-bridge.ts +0 -153
  145. package/src/plugin-v2.ts +0 -2954
  146. package/src/plugins/pantheon-hooks.ts +0 -1433
  147. package/src/plugins/tui/dist/server-v2.d.ts +0 -30
  148. package/src/plugins/tui/dist/server-v2.d.ts.map +0 -1
  149. package/src/plugins/tui/dist/server-v2.js +0 -33
  150. package/src/plugins/tui/dist/server-v2.js.map +0 -1
  151. package/src/plugins/tui/dist/tui-v2.d.ts +0 -1039
  152. package/src/plugins/tui/dist/tui-v2.d.ts.map +0 -1
  153. package/src/plugins/tui/dist/tui-v2.js +0 -4597
  154. package/src/plugins/tui/dist/tui-v2.js.map +0 -1
  155. package/src/plugins/tui/src/index-v2.tsx +0 -4496
  156. package/src/plugins/tui/src/server-v2.ts +0 -28
  157. package/src/plugins/tui/tui-v2.ts +0 -2
  158. /package/src/pantheon/{v2-decision-budget.ts → decision-budget.ts} +0 -0
  159. /package/src/pantheon/{v2-decision-egress.ts → decision-egress.ts} +0 -0
  160. /package/src/pantheon/{v2-decision-events.ts → decision-events.ts} +0 -0
  161. /package/src/pantheon/{v2-decision-heuristic.ts → decision-heuristic.ts} +0 -0
  162. /package/src/pantheon/{v2-decision-premises.ts → decision-premises.ts} +0 -0
  163. /package/src/pantheon/{v2-decision-rank.ts → decision-rank.ts} +0 -0
  164. /package/src/pantheon/{v2-decision-verify.ts → decision-verify.ts} +0 -0
  165. /package/src/pantheon/{v2-delegation-enforce.ts → delegation-policy.ts} +0 -0
  166. /package/src/pantheon/{v2-model-overrides.ts → model-overrides.ts} +0 -0
  167. /package/src/pantheon/{v2-native-decisions.ts → native-decisions.ts} +0 -0
  168. /package/src/plugins/tui/src/{opencode-v2.d.ts → opencode.d.ts} +0 -0
@@ -1,4597 +0,0 @@
1
- import { createComponent, createElement, createTextNode, effect, insert, insertNode, memo, setProp } from "@opentui/solid";
2
- import { mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
3
- import { homedir } from "node:os";
4
- import { dirname, join } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { For, Show, createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js";
7
- import { execFile } from "node:child_process";
8
- import { Plugin } from "@opencode/plugin/tui";
9
- //#region src/context-gauge.ts
10
- const CONTEXT_BAR_CELLS = 12;
11
- const CONTEXT_BAR_FILLED_CELL = "▰";
12
- const CONTEXT_BAR_EMPTY_CELL = "▱";
13
- function numberOrNull$1(value) {
14
- return typeof value === "number" && Number.isFinite(value) ? value : null;
15
- }
16
- function contextUsageTone(percent) {
17
- if (percent > 90) return "error";
18
- if (percent > 50) return "warning";
19
- if (percent > 25) return "success";
20
- return "info";
21
- }
22
- function formatTokenCount(tokens) {
23
- const value = numberOrNull$1(tokens);
24
- if (value === null || value < 0) return null;
25
- return Math.round(value).toLocaleString("en-US");
26
- }
27
- function formatContextWindow(limit) {
28
- const value = numberOrNull$1(limit);
29
- if (value === null || value <= 0) return null;
30
- if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
31
- if (value >= 1e3) return `${Math.floor(value / 1e3)}K`;
32
- return `${Math.floor(value)}`;
33
- }
34
- function contextBarFilled(percent, cells = 12) {
35
- const total = Math.max(1, Math.floor(cells));
36
- const filled = Math.round(percent / 100 * total);
37
- if (!Number.isFinite(filled)) return 0;
38
- return Math.min(total, Math.max(0, filled));
39
- }
40
- function contextBar(percent, cells = 12) {
41
- const value = numberOrNull$1(percent);
42
- if (value === null) return null;
43
- const total = Math.max(1, Math.floor(cells));
44
- const filled = contextBarFilled(value, total);
45
- return {
46
- filled: "▰".repeat(filled),
47
- empty: "▱".repeat(total - filled)
48
- };
49
- }
50
- function formatSpent(cost) {
51
- const value = numberOrNull$1(cost);
52
- if (value === null || value < 0) return null;
53
- return `$${value.toFixed(2)}`;
54
- }
55
- //#endregion
56
- //#region src/model-usage-limits.ts
57
- /** Shared bounds for cached recent model-usage aggregation. */
58
- const MODEL_USAGE_VISIBLE_CEILING = 3;
59
- const MODEL_USAGE_MESSAGE_LIMIT = 400;
60
- const MODEL_USAGE_SESSION_LIMIT = 8;
61
- //#endregion
62
- //#region src/sidebar-width.ts
63
- const GRAPHEMES = new Intl.Segmenter(void 0, { granularity: "grapheme" });
64
- /** A grapheme the host draws two cells wide: emoji presentation, an extended
65
- * pictograph (a bare `❤` counts too, exactly as the host's `emoji-regex`
66
- * does) and a regional-indicator pair (a flag). */
67
- const EMOJI_GLYPH = /\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{Regional_Indicator}/u;
68
- /** VS16 asks for emoji presentation; without it `1` is one cell, with it the
69
- * keycap sequence is drawn as one two-cell glyph. */
70
- const EMOJI_PRESENTATION_SELECTOR = "️";
71
- /** Unicode default-ignorable code points carry no width of their own. */
72
- const IGNORABLE_GLYPH = /^\p{Default_Ignorable_Code_Point}$/u;
73
- /** East Asian Wide/Fullwidth ranges — two cells, never the ambiguous width
74
- * (the host measures ambiguous as narrow, so `▸`/`✓`/`—` stay one cell).
75
- * Generated from the host's own measurement (`string-width` over every code
76
- * point, emoji excluded), so this table can be regenerated verbatim when the
77
- * host upgrades its Unicode data instead of being hand-edited. */
78
- const CELL_WIDE_RANGES = [
79
- [4352, 4446],
80
- [9001, 9002],
81
- [9776, 9783],
82
- [9866, 9871],
83
- [11904, 11929],
84
- [11931, 12019],
85
- [12032, 12245],
86
- [12272, 12335],
87
- [12337, 12348],
88
- [12350, 12350],
89
- [12353, 12438],
90
- [12441, 12543],
91
- [12549, 12591],
92
- [12593, 12643],
93
- [12645, 12686],
94
- [12688, 12773],
95
- [12783, 12830],
96
- [12832, 12871],
97
- [12880, 12950],
98
- [12952, 12952],
99
- [12954, 42124],
100
- [42128, 42182],
101
- [43360, 43388],
102
- [44032, 55203],
103
- [63744, 64255],
104
- [65040, 65049],
105
- [65072, 65106],
106
- [65108, 65126],
107
- [65128, 65131],
108
- [65281, 65376],
109
- [65504, 65510],
110
- [94176, 94180],
111
- [94192, 94198],
112
- [94208, 101594],
113
- [101631, 101664],
114
- [101760, 101874],
115
- [101888, 102801],
116
- [102816, 102866],
117
- [110576, 110579],
118
- [110581, 110587],
119
- [110589, 110590],
120
- [110592, 110888],
121
- [110898, 110898],
122
- [110928, 110930],
123
- [110933, 110933],
124
- [110948, 110952],
125
- [110960, 111355],
126
- [119552, 119638],
127
- [119648, 119670],
128
- [127488, 127488],
129
- [127504, 127513],
130
- [127515, 127534],
131
- [127536, 127537],
132
- [127547, 127547],
133
- [127552, 127560],
134
- [127584, 127589],
135
- [131072, 196605],
136
- [196608, 262141]
137
- ];
138
- /** One code point the terminal draws no cell for: control characters, the
139
- * zero-width joiners/marks, combining marks and variation selectors. */
140
- function isZeroWidthCodePoint(code, glyph) {
141
- if (code <= 31 || code >= 127 && code <= 159) return true;
142
- if (code >= 8203 && code <= 8207) return true;
143
- if (code === 65279) return true;
144
- if (code >= 768 && code <= 879) return true;
145
- if (code >= 6832 && code <= 6911) return true;
146
- if (code >= 7616 && code <= 7679) return true;
147
- if (code >= 8400 && code <= 8447) return true;
148
- if (code >= 65024 && code <= 65039) return true;
149
- if (code >= 65056 && code <= 65071) return true;
150
- if (code >= 917760 && code <= 917999) return true;
151
- if (code >= 55296 && code <= 57343) return true;
152
- return IGNORABLE_GLYPH.test(glyph);
153
- }
154
- function isWideCodePoint(code) {
155
- for (const [low, high] of CELL_WIDE_RANGES) {
156
- if (code < low) return false;
157
- if (code <= high) return true;
158
- }
159
- return false;
160
- }
161
- /** Cells one grapheme occupies. */
162
- function graphemeWidth(segment) {
163
- if (EMOJI_GLYPH.test(segment)) return 2;
164
- if (segment.length > 1 && segment.includes(EMOJI_PRESENTATION_SELECTOR)) return 2;
165
- let width = 0;
166
- for (const glyph of segment) {
167
- const code = glyph.codePointAt(0) ?? 0;
168
- if (isZeroWidthCodePoint(code, glyph)) continue;
169
- width += isWideCodePoint(code) ? 2 : 1;
170
- }
171
- return width;
172
- }
173
- /** Terminal cells `value` occupies — the unit every column in this plugin is
174
- * measured in. Mirrors the host (that is how `@opentui/core` sizes a text
175
- * run): emoji count as two cells, East Asian Wide/Fullwidth as two, East
176
- * Asian Ambiguous as one, combining marks and variation selectors as none.
177
- * Pure. */
178
- function cellWidth(value) {
179
- let width = 0;
180
- for (const { segment } of GRAPHEMES.segment(value)) width += graphemeWidth(segment);
181
- return width;
182
- }
183
- /** Prefix of the "+N more" line appended when the bullet budget is exceeded. */
184
- const WHATS_NEW_MORE_PREFIX = "… +";
185
- const EMPTY_HIGHLIGHTS = {
186
- version: null,
187
- found: false,
188
- groups: [],
189
- totalItems: 0,
190
- truncated: false
191
- };
192
- /** Escape regex metacharacters so a version like 1.0.0 matches literally. */
193
- function escapeRegExp(text) {
194
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
195
- }
196
- /**
197
- * Extract the body of a version section from changelog text — inline replica
198
- * of scripts/changelog-extract.mjs `extractSection` (see that file for the
199
- * full contract: `## [<version>] - YYYY-MM-DD`, leading `v` and the date
200
- * optional, `## [Unreleased]` never matched).
201
- */
202
- function extractSection(changelogText, version) {
203
- const normalized = String(version).trim().replace(/^v/i, "");
204
- if (!normalized || /^unreleased$/i.test(normalized)) return {
205
- found: false,
206
- body: null
207
- };
208
- const escaped = escapeRegExp(normalized);
209
- const match = new RegExp(`^##[ \\t]+\\[v?${escaped}\\](?:[ \\t]*-[ \\t]*\\d{4}-\\d{2}-\\d{2})?(?=[ \\t]|$)`, "m").exec(changelogText);
210
- if (!match) return {
211
- found: false,
212
- body: null
213
- };
214
- const newline = changelogText.indexOf("\n", match.index);
215
- const start = newline === -1 ? changelogText.length : newline + 1;
216
- const nextHeading = /^##[ \t]+\[/m.exec(changelogText.slice(start));
217
- const end = nextHeading ? start + nextHeading.index : changelogText.length;
218
- return {
219
- found: true,
220
- body: changelogText.slice(start, end).trim()
221
- };
222
- }
223
- /**
224
- * Reduce one markdown line to plain text: links keep their label, emphasis
225
- * and inline-code markers are dropped, HTML comment fragments are removed,
226
- * and whitespace collapses. Deliberately simple — the input is our own
227
- * CHANGELOG (lint-capped at 200 chars per bullet), not hostile input.
228
- */
229
- function stripMarkdown(text) {
230
- return text.replace(/<!--[\s\S]*?-->/g, " ").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/(\*\*|__)/g, "").replace(/`/g, "").replace(/\s+/g, " ").trim();
231
- }
232
- /** Strip the leading H3 marker (`### Added` → `Added`). */
233
- function stripHeading(text) {
234
- return text.replace(/^#{1,6}[ \t]+/, "").trim();
235
- }
236
- /**
237
- * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)
238
- * from a section body: its bullets only, each truncated to
239
- * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when
240
- * the section carries no summary block (the full-section fallback applies).
241
- */
242
- function extractWhatsNewSummary(body) {
243
- const lines = body.split("\n");
244
- const start = lines.findIndex((line) => /^#{2,3}[ \t]+.*What'?s New/i.test(line.trim()));
245
- if (start === -1) return null;
246
- const items = [];
247
- for (const rawLine of lines.slice(start + 1)) {
248
- const line = rawLine.trim();
249
- if (line === "" || line.startsWith("<!--")) continue;
250
- if (/^#{1,6}[ \t]/.test(line)) break;
251
- if (!/^[-*][ \t]/.test(line)) continue;
252
- if (items.length >= 6) break;
253
- const content = stripMarkdown(line.replace(/^[-*][ \t]+/, ""));
254
- if (content === "") continue;
255
- items.push(content.length > 140 ? `${content.slice(0, 139)}…` : content);
256
- }
257
- return items.length > 0 ? items : null;
258
- }
259
- /**
260
- * Extract the release highlights for `version`. When the section carries a
261
- * curated `🆕 What's New` summary block, THE WINDOW SHOWS ONLY THAT (the
262
- * full Added/Changed/Fixed walls are for the CHANGELOG readers, not the
263
- * dialog); otherwise it falls back to the H3-group extraction bounded to
264
- * WHATS_NEW_MAX_ITEMS bullets. A missing section, a bullet-less section or a
265
- * blank changelog all return EMPTY_HIGHLIGHTS (no window).
266
- */
267
- function extractHighlights(changelogText, version) {
268
- const { found, body } = extractSection(changelogText ?? "", version ?? "");
269
- if (!found || !body) return { ...EMPTY_HIGHLIGHTS };
270
- const summary = extractWhatsNewSummary(body);
271
- if (summary !== null) return {
272
- version: String(version).trim().replace(/^v/i, ""),
273
- found: true,
274
- groups: [{
275
- heading: null,
276
- items: summary
277
- }],
278
- totalItems: summary.length,
279
- truncated: false
280
- };
281
- const groups = [];
282
- let totalItems = 0;
283
- let truncated = false;
284
- for (const rawLine of body.split("\n")) {
285
- const line = rawLine.trim();
286
- if (line === "" || line.startsWith("<!--")) continue;
287
- if (/^#{1,6}[ \t]/.test(line)) {
288
- const heading = stripMarkdown(stripHeading(line));
289
- if (heading === "") continue;
290
- if (groups.at(-1)?.items.length === 0) groups.pop();
291
- groups.push({
292
- heading,
293
- items: []
294
- });
295
- continue;
296
- }
297
- if (totalItems >= 12) {
298
- if (/^[-*][ \t]/.test(line)) totalItems += 1;
299
- continue;
300
- }
301
- const isBullet = /^[-*][ \t]/.test(line);
302
- const continuation = (groups.at(-1)?.items.length ?? 0) > 0;
303
- if (!isBullet && !continuation) continue;
304
- const content = stripMarkdown(isBullet ? line.replace(/^[-*][ \t]+/, "") : line);
305
- if (content === "") continue;
306
- const bounded = content.length > 140 ? `${content.slice(0, 139)}…` : content;
307
- const group = groups.at(-1);
308
- if (group === void 0) groups.push({
309
- heading: null,
310
- items: [bounded]
311
- });
312
- else if (isBullet || group.items.length === 0) group.items.push(bounded);
313
- else group.items[group.items.length - 1] = `${group.items.at(-1)} ${bounded}`.trim();
314
- if (isBullet) totalItems += 1;
315
- }
316
- const kept = groups.filter((group) => group.items.length > 0);
317
- truncated = totalItems > 12;
318
- return {
319
- version: found ? String(version).trim().replace(/^v/i, "") : null,
320
- found,
321
- groups: kept,
322
- totalItems,
323
- truncated
324
- };
325
- }
326
- /** Window title — mirrors the sidebar's `Pantheon v<version>` convention. */
327
- function whatsNewTitle(version) {
328
- return `O que há de novo — Pantheon v${String(version).trim().replace(/^v/i, "")}`;
329
- }
330
- /** Flat display lines for the window: group headings, `• ` bullets, `+N more`. */
331
- function whatsNewLines(highlights) {
332
- const lines = [];
333
- for (const group of highlights.groups) {
334
- if (group.heading !== null) lines.push(group.heading);
335
- for (const item of group.items) lines.push(`• ${item}`);
336
- }
337
- if (highlights.truncated) {
338
- const hidden = Math.max(0, highlights.totalItems - 12);
339
- if (hidden > 0) lines.push(`${WHATS_NEW_MORE_PREFIX}${hidden} mais`);
340
- }
341
- return lines;
342
- }
343
- /**
344
- * Candidate CHANGELOG.md locations for a bundle, first readable wins:
345
- * 1. the plugin copy root (`<configDir>/plugins/pantheon-tui/CHANGELOG.md`,
346
- * shipped by both installers next to package.json);
347
- * 2. the package root (dev checkout; also an npm-package install when the
348
- * bundle runs from `<pkg>/src/plugins/tui/dist/`).
349
- */
350
- function changelogCandidates(bundlePath) {
351
- const dist = dirname(bundlePath);
352
- const copyRoot = dirname(dist);
353
- const packageRoot = dirname(dirname(dirname(copyRoot)));
354
- return [join(copyRoot, "CHANGELOG.md"), join(packageRoot, "CHANGELOG.md")];
355
- }
356
- /** Read the first existing candidate; null when none is readable (no window). */
357
- async function readChangelogForBundle(bundleUrl) {
358
- try {
359
- const bundlePath = fileURLToPath(bundleUrl);
360
- for (const candidate of changelogCandidates(bundlePath)) try {
361
- return await readFile(candidate, "utf8");
362
- } catch {}
363
- return null;
364
- } catch {
365
- return null;
366
- }
367
- }
368
- /** The ambient build-time version, or null outside a tsdown build. */
369
- function embeddedVersion() {
370
- return "1.7.0";
371
- }
372
- /**
373
- * Resolve the running Pantheon version for the what's-new window: the plugin
374
- * copy's own package.json first (the copy root two levels above the bundle,
375
- * then the package root four levels above — the same legs as the V1 sidebar's
376
- * detectVersion try 0a/0b), falling back to the tsdown build embed. Null when
377
- * nothing resolves → no window (fail-open).
378
- */
379
- async function resolveRunningVersion(bundleUrl, embedded = embeddedVersion()) {
380
- try {
381
- const bundlePath = fileURLToPath(bundleUrl);
382
- const dist = dirname(bundlePath);
383
- for (const root of [dirname(dist), dirname(dirname(dirname(dist)))]) try {
384
- const raw = await readFile(join(root, "package.json"), "utf8");
385
- const parsed = JSON.parse(raw);
386
- if (typeof parsed.version === "string" && parsed.version.trim() !== "") return parsed.version;
387
- } catch {}
388
- } catch {}
389
- return embedded;
390
- }
391
- //#endregion
392
- //#region src/whats-new-state.ts
393
- /**
394
- * whats-new-state.ts — last-seen version for the one-time "What's new" window.
395
- *
396
- * The TUI shows a dismissable release-highlights dialog once per Pantheon
397
- * version. Whether a version was already seen is persisted next to the other
398
- * opencode-level Pantheon state: `<configDir>/.pantheon/whats-new.json`, the
399
- * same directory that already holds `install-state.json` (scripts/install/
400
- * state.mjs) and the active-preset file the sidebar reads. There is no
401
- * established persistent TUI KV store (the host `api.kv` is per-process), so
402
- * the plugin owns one small JSON file with the atomic-write discipline used
403
- * across the repo (unique tmp + rename, mirrors scripts/install/verify.mjs).
404
- *
405
- * Fail-open everywhere: a missing or corrupt file reads as "never seen" (the
406
- * window may show), a failed write is silent (the window may show again) —
407
- * neither can ever block TUI startup.
408
- */
409
- /** State file name, kept next to `install-state.json` in `<configDir>/.pantheon/`. */
410
- const WHATS_NEW_STATE_FILENAME = "whats-new.json";
411
- /** Parse a state file body; null when unreadable as the expected shape. */
412
- function parseWhatsNewState(raw) {
413
- try {
414
- const parsed = JSON.parse(raw);
415
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
416
- const record = parsed;
417
- const seen = record.seenVersion;
418
- if (typeof seen !== "string" && seen !== null) return null;
419
- return {
420
- seenVersion: seen,
421
- updatedAt: String(record.updatedAt ?? "")
422
- };
423
- } catch {
424
- return null;
425
- }
426
- }
427
- /** Read the persisted state; null when missing or corrupt (never throws). */
428
- async function readWhatsNewState(statePath) {
429
- try {
430
- return parseWhatsNewState(await readFile(statePath, "utf8"));
431
- } catch {
432
- return null;
433
- }
434
- }
435
- /**
436
- * Whether the one-time window should show for `version`: any version change
437
- * since the last dismissal (including downgrades). A falsy version — the
438
- * resolver failed — never shows.
439
- */
440
- async function shouldShowWhatsNew(version, statePath) {
441
- if (typeof version !== "string" || version.trim() === "") return false;
442
- return (await readWhatsNewState(statePath))?.seenVersion !== version;
443
- }
444
- /**
445
- * Persist `version` as seen (atomic tmp + rename, 0o600). Never throws: a
446
- * failed write leaves the state untouched and the window may show again —
447
- * the same fail-open contract as the rest of the plugin.
448
- */
449
- async function markSeenWhatsNew(version, statePath) {
450
- if (typeof version !== "string" || version.trim() === "") return false;
451
- const previous = await readWhatsNewState(statePath);
452
- const next = {
453
- seenVersion: version,
454
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
455
- };
456
- const tmpPath = `${statePath}.tmp-${process.pid}`;
457
- try {
458
- await mkdir(dirname(statePath), { recursive: true });
459
- await writeFile(tmpPath, `${JSON.stringify({
460
- ...previous,
461
- ...next
462
- }, null, 2)}\n`, {
463
- encoding: "utf8",
464
- mode: 384
465
- });
466
- await rename(tmpPath, statePath);
467
- return true;
468
- } catch {
469
- try {
470
- await unlink(tmpPath);
471
- } catch {}
472
- return false;
473
- }
474
- }
475
- /** `stat`-based existence probe (async I/O discipline). */
476
- async function pathExists(path) {
477
- try {
478
- await stat(path);
479
- return true;
480
- } catch {
481
- return false;
482
- }
483
- }
484
- /**
485
- * Default state path: `<configDir>/.pantheon/whats-new.json`, resolving the
486
- * OpenCode config directory exactly like src/pantheon/tui-version-check.ts
487
- * (`$XDG_CONFIG_HOME/opencode` → `~/.opencode`), defaulting to the XDG
488
- * location `init` creates when neither exists yet.
489
- */
490
- async function defaultWhatsNewStatePath(env = process.env, home = homedir()) {
491
- const xdgConfig = env.XDG_CONFIG_HOME || join(home, ".config");
492
- const primary = join(xdgConfig, "opencode");
493
- if (await pathExists(primary)) return join(primary, ".pantheon", WHATS_NEW_STATE_FILENAME);
494
- const legacy = join(home, ".opencode");
495
- if (await pathExists(legacy)) return join(legacy, ".pantheon", WHATS_NEW_STATE_FILENAME);
496
- return join(primary, ".pantheon", WHATS_NEW_STATE_FILENAME);
497
- }
498
- //#endregion
499
- //#region src/whats-new-open.ts
500
- /**
501
- * whats-new-open.ts — the show-once decision for the "What's new" window.
502
- *
503
- * Plain data in, plain data out: the entrypoints (index.tsx / index-v2.tsx)
504
- * resolve the running version and the shipped CHANGELOG.md, then hand this
505
- * module a `show` callback that renders the view data through the host's
506
- * dialog API. Keeping the decision JSX-free makes the whole one-time flow
507
- * testable offline (node strips the types natively) — the Solid glue lives in
508
- * whats-new.tsx.
509
- *
510
- * Contract (pinned by tests/tui-whats-new.test.mjs):
511
- * - shows at most once per version: dismissal marks the version seen;
512
- * - nothing to show (no version, missing CHANGELOG, empty section) → no
513
- * window AND no pin — the next start may still show it;
514
- * - never throws on its own inputs; I/O failures inside the state module
515
- * are fail-open there.
516
- */
517
- /** Muted footer hint teaching the dismiss bind (Portuguese, like the sidebar). */
518
- const WHATS_NEW_CLOSE_HINT = "esc/q fechar";
519
- /** Hint variant when the highlights span more than one page. */
520
- const WHATS_NEW_PAGES_HINT = "esc/q fechar · n próxima · p volta";
521
- /** Hard-wrap one display line into rows of at most `width` columns (>= 10). */
522
- function wrapWhatsNewLine(line, width) {
523
- const bounded = Number.isInteger(width) && width > 10 ? width : 76;
524
- const text = String(line);
525
- if (text.length <= bounded) return [text];
526
- const rows = [];
527
- let rest = text;
528
- while (rest.length > bounded) {
529
- rows.push(rest.slice(0, bounded));
530
- rest = rest.slice(bounded);
531
- }
532
- if (rest.length > 0) rows.push(rest);
533
- return rows;
534
- }
535
- /** Slice display lines into fixed-size pages (>= 1 page, empty-safe). */
536
- function paginateWhatsNewLines(lines, pageSize = 14) {
537
- const size = Number.isInteger(pageSize) && pageSize > 0 ? pageSize : 14;
538
- if (lines.length === 0) return [[]];
539
- const pages = [];
540
- for (let i = 0; i < lines.length; i += size) pages.push(lines.slice(i, i + size));
541
- return pages;
542
- }
543
- /**
544
- * Open the one-time window when the version changed and highlights exist.
545
- * Returns true when the window was shown; the caller's `onClose` callback
546
- * (both host-initiated and local close binds) must funnel into marking seen.
547
- */
548
- async function openWhatsNew(input) {
549
- const { version, statePath, changelogText, show } = input;
550
- if (typeof version !== "string" || version.trim() === "") return false;
551
- if (!await shouldShowWhatsNew(version, statePath)) return false;
552
- const lines = whatsNewLines(changelogText ? extractHighlights(changelogText, version) : { ...EMPTY_HIGHLIGHTS });
553
- if (lines.length === 0) return false;
554
- const pages = paginateWhatsNewLines(lines);
555
- const data = {
556
- version,
557
- title: whatsNewTitle(version),
558
- lines,
559
- pages,
560
- hint: pages.length > 1 ? WHATS_NEW_PAGES_HINT : WHATS_NEW_CLOSE_HINT
561
- };
562
- show(() => data, () => {
563
- markSeenWhatsNew(version, statePath);
564
- });
565
- return true;
566
- }
567
- //#endregion
568
- //#region src/whats-new.tsx
569
- /** @jsxImportSource @opentui/solid */
570
- /**
571
- * whats-new.tsx — the one-time "What's new" window (per Pantheon version).
572
- *
573
- * When the running Pantheon version changed since the last TUI start, the V2
574
- * entrypoint fires {@link maybeShowWhatsNewV2} (fire-and-forget, never
575
- * awaited — startup must never block). The decision lives in
576
- * whats-new-open.ts; this file is only the host glue + view:
577
- * `context.ui.dialog.show` plus a keymap layer gated on the open signal so
578
- * `escape`/`q` dismiss and `n`/`p` flip pages while (and only while) the
579
- * window is up — the same gated-layer pattern as the dispatch panel.
580
- *
581
- * The window shows the curated 🆕 What's New summary (whats-new-highlights
582
- * prefers it), hard-wrapped to the window width and sliced into fixed-size
583
- * pages — a big changelog can never overflow the terminal; the footer points
584
- * at the complete CHANGELOG.md.
585
- *
586
- * Deliberately V2-only: the two dist entries are self-contained (the V1
587
- * sidebar mirrors the preset resolver rather than importing it) because any
588
- * module shared by both entries becomes a content-hashed chunk in dist/,
589
- * changing the artifact shape the byte-reproducible-dist gate pins. The V1
590
- * generation (OpenCode 1.x, legacy) does not show the window; the pure
591
- * modules here are generation-agnostic, so a V1 mirror can follow the
592
- * documented inline-replica precedent if it is ever wanted.
593
- *
594
- * Dismissal always funnels into `markSeenWhatsNew` (idempotent), so the window
595
- * is shown exactly once per version. Every failure path is silent: missing
596
- * CHANGELOG.md, unreadable state, a host API that throws — the window simply
597
- * does not show (fail-open, like the rest of the plugin).
598
- */
599
- /** Window body: title, rule, the current page (wrapped), footer hint. */
600
- function WhatsNewContent(props) {
601
- const rows = () => {
602
- const current = props.data.pages[Math.min(props.page(), props.pageCount() - 1)] ?? [];
603
- const wrapped = [];
604
- for (const line of current) wrapped.push(...wrapWhatsNewLine(line, 76));
605
- return wrapped;
606
- };
607
- return (() => {
608
- var _el$ = createElement("box"), _el$2 = createElement("text"), _el$3 = createElement("text"), _el$5 = createElement("box"), _el$6 = createElement("text");
609
- insertNode(_el$, _el$2);
610
- insertNode(_el$, _el$3);
611
- insertNode(_el$, _el$5);
612
- insertNode(_el$, _el$6);
613
- setProp(_el$, "flexDirection", "column");
614
- setProp(_el$, "paddingLeft", 1);
615
- setProp(_el$, "paddingRight", 1);
616
- setProp(_el$, "paddingTop", 1);
617
- setProp(_el$2, "attributes", 1);
618
- insert(_el$2, () => props.data.title);
619
- insertNode(_el$3, createTextNode(`──────────────────────────────────────`));
620
- insert(_el$, createComponent(For, {
621
- get each() {
622
- return rows();
623
- },
624
- children: (line) => (() => {
625
- var _el$7 = createElement("text");
626
- insert(_el$7, line);
627
- effect((_$p) => setProp(_el$7, "fg", line.startsWith("• ") ? props.fg : props.muted, _$p));
628
- return _el$7;
629
- })()
630
- }), _el$5);
631
- setProp(_el$5, "height", 1);
632
- insert(_el$6, (() => {
633
- var _c$ = memo(() => props.pageCount() > 1);
634
- return () => _c$() ? `${props.page() + 1}/${props.pageCount()} · ` : "";
635
- })(), null);
636
- insert(_el$6, () => props.data.hint, null);
637
- effect((_p$) => {
638
- var _v$ = props.fg, _v$2 = props.muted, _v$3 = props.muted;
639
- _v$ !== _p$.e && (_p$.e = setProp(_el$2, "fg", _v$, _p$.e));
640
- _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "fg", _v$2, _p$.t));
641
- _v$3 !== _p$.a && (_p$.a = setProp(_el$6, "fg", _v$3, _p$.a));
642
- return _p$;
643
- }, {
644
- e: void 0,
645
- t: void 0,
646
- a: void 0
647
- });
648
- return _el$;
649
- })();
650
- }
651
- /**
652
- * Entry glue: resolve version + shipped CHANGELOG.md, then show the window
653
- * through the host dialog stack once. Never throws.
654
- */
655
- async function maybeShowWhatsNewV2(context) {
656
- try {
657
- const version = await resolveRunningVersion(import.meta.url);
658
- if (!version) return;
659
- const statePath = await defaultWhatsNewStatePath();
660
- const changelogText = await readChangelogForBundle(import.meta.url);
661
- const [open, setOpen] = createSignal(false);
662
- const [page, setPage] = createSignal(0);
663
- let viewData;
664
- const pageCount = () => Math.max(1, Math.ceil(viewData?.pages.length ?? 1));
665
- let dismiss = () => {};
666
- try {
667
- context.keymap.layer(() => ({
668
- mode: "global",
669
- enabled: () => open(),
670
- commands: [
671
- {
672
- id: "pantheon.whats-new.close",
673
- title: "Fechar o que há de novo",
674
- bind: "escape,q",
675
- run: () => {
676
- if (!open()) return false;
677
- dismiss();
678
- }
679
- },
680
- {
681
- id: "pantheon.whats-new.next",
682
- title: "Próxima página",
683
- bind: "n,right",
684
- run: () => {
685
- if (!open()) return false;
686
- setPage((current) => Math.min(current + 1, pageCount() - 1));
687
- }
688
- },
689
- {
690
- id: "pantheon.whats-new.prev",
691
- title: "Página anterior",
692
- bind: "p,left",
693
- run: () => {
694
- if (!open()) return false;
695
- setPage((current) => Math.max(current - 1, 0));
696
- }
697
- }
698
- ]
699
- }));
700
- } catch {}
701
- await openWhatsNew({
702
- version,
703
- statePath,
704
- changelogText,
705
- show: (render, onClose) => {
706
- const close = () => {
707
- setOpen(false);
708
- onClose();
709
- };
710
- dismiss = () => {
711
- try {
712
- context.ui.dialog.clear();
713
- } catch {}
714
- close();
715
- };
716
- viewData = render();
717
- setPage(0);
718
- setOpen(true);
719
- try {
720
- const theme = context.theme?.text ?? {};
721
- context.ui.dialog.show(() => createComponent(WhatsNewContent, {
722
- data: viewData,
723
- page,
724
- pageCount,
725
- get fg() {
726
- return theme.base;
727
- },
728
- get muted() {
729
- return theme.muted;
730
- }
731
- }), close);
732
- } catch {}
733
- }
734
- });
735
- } catch {}
736
- }
737
- //#endregion
738
- //#region src/index-v2.tsx
739
- /** @jsxImportSource @opentui/solid */
740
- const SINGLETON = Symbol.for("pantheon.tui.v2.loaded");
741
- /** How often the sidebar re-reads .pantheon/active-preset.json (V1 parity) so
742
- * `set-tier` changes made while opencode is open show up within ~30s. */
743
- const PRESET_REFRESH_MS = 3e4;
744
- /** Running-row spinner cadence — matches V1's animation tick. */
745
- const SPINNER_INTERVAL_MS = 80;
746
- /** Bounded warm-up: sync at most this many sessions at plugin load. */
747
- const WARMUP_SESSION_LIMIT = 24;
748
- /** Sidebar body shown while the host has not published a session yet. */
749
- const SIDEBAR_WAITING_LABEL = "Aguardando sessão…";
750
- /** Delegate-completion toast title. */
751
- const TOAST_TITLE = "Pantheon";
752
- /** Marker before the preset label (fixed header, home status, prompt footer).
753
- * `▸` U+25B8 is one cell; the previous bolt (U+26A1) carries
754
- * Emoji_Presentation and is measured as two cells, which misaligned the line. */
755
- const PRESET_MARKER = "▸";
756
- /** Git ahead / behind arrows (U+2191 / U+2193), one cell each — the glyphs the
757
- * reference sidebars use for `↑ahead ↓behind`. */
758
- const GIT_ARROW_UP = "↑";
759
- const GIT_ARROW_DOWN = "↓";
760
- /** One event name the host publishes on `data.on` — the OpenCode V2 union. */
761
- /** V2 events that refresh the sidebar. V1 also listened to `session.updated`,
762
- * but that name is absent from the OpenCode V2 event union (verified against
763
- * `@opencode/client`'s `OpenCodeEvent`), so the valid events that carry the
764
- * same state changes are used instead: `session.renamed` /
765
- * `session.metadata.updated` / `session.moved` (the mutations `session.updated`
766
- * used to stand for) and `session.idle` (a child finishing). `satisfies` keeps
767
- * the literals while making a name outside the union a type error (surfaced by
768
- * `tsc -p tsconfig.build.json`), and the sidebar test asserts the same names
769
- * against the installed union at runtime. */
770
- const SIDEBAR_REFRESH_EVENTS = [
771
- "session.created",
772
- "session.renamed",
773
- "session.metadata.updated",
774
- "session.moved",
775
- "session.idle",
776
- "session.status",
777
- "session.deleted"
778
- ];
779
- /** One `overrides.agents[<agent>]` entry from active-preset.json. */
780
- /** The override map the CLI wrote into active-preset.json. */
781
- /** A preset plus the explicit overrides stored next to it. */
782
- function emptyOverrides() {
783
- return { agents: {} };
784
- }
785
- /** Keep only well-formed per-agent overrides: unknown keys are ignored and a
786
- * non-string model/variant is dropped instead of leaking into the render. */
787
- function parsePresetOverrides(value) {
788
- const overrides = emptyOverrides();
789
- if (!value || typeof value !== "object") return overrides;
790
- const agents = value.agents;
791
- if (!agents || typeof agents !== "object") return overrides;
792
- for (const [agent, entry] of Object.entries(agents)) {
793
- if (agent === "" || !entry || typeof entry !== "object") continue;
794
- const model = entry.model;
795
- const variant = entry.variant;
796
- const override = {};
797
- if (typeof model === "string" && model !== "") override.model = model;
798
- if (typeof variant === "string" && variant !== "") override.variant = variant;
799
- if (override.model !== void 0 || override.variant !== void 0) overrides.agents[agent] = override;
800
- }
801
- return overrides;
802
- }
803
- /** Read .pantheon/active-preset.json — first existing candidate wins; malformed
804
- * JSON or a `preset` that is missing, empty or "none" → null (no fall-through
805
- * to lower candidates). The explicit per-agent overrides stored in the same
806
- * file come along so the sidebar can mark them with `*`. */
807
- async function readActivePresetDetail(cwd) {
808
- const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
809
- const candidates = [
810
- join(cwd, ".pantheon", "active-preset.json"),
811
- join(xdgConfig, "opencode", ".pantheon", "active-preset.json"),
812
- join(homedir(), ".opencode", ".pantheon", "active-preset.json")
813
- ];
814
- for (const candidate of candidates) {
815
- let raw;
816
- try {
817
- raw = await readFile(candidate, "utf8");
818
- } catch {
819
- continue;
820
- }
821
- try {
822
- const parsed = JSON.parse(raw);
823
- const name = parsed && typeof parsed === "object" ? parsed.preset : void 0;
824
- if (typeof name !== "string" || name.length === 0 || name === "none") return null;
825
- return {
826
- info: {
827
- name,
828
- source: "file"
829
- },
830
- overrides: parsePresetOverrides(parsed.overrides)
831
- };
832
- } catch {
833
- return null;
834
- }
835
- }
836
- return null;
837
- }
838
- /** Env leg of resolution: PANTHEON_MODEL_PRESET set and !== 'none' wins. */
839
- function presetFromEnv(env) {
840
- const name = env.PANTHEON_MODEL_PRESET;
841
- if (name !== void 0 && name !== "" && name !== "none") return {
842
- name,
843
- source: "env"
844
- };
845
- return {
846
- name: null,
847
- source: null
848
- };
849
- }
850
- /** Resolve the active preset plus its per-agent overrides: env > file > default.
851
- * An env-selected preset has no file overrides by construction. */
852
- async function resolveActivePresetForTui(env, cwd) {
853
- const envPreset = presetFromEnv(env);
854
- if (envPreset.source === "env") return {
855
- info: envPreset,
856
- overrides: emptyOverrides()
857
- };
858
- return await readActivePresetDetail(cwd) ?? {
859
- info: {
860
- name: null,
861
- source: null
862
- },
863
- overrides: emptyOverrides()
864
- };
865
- }
866
- /** `SessionInfo.id` is always a `ses…` handle. Guarded so a placeholder or a
867
- * foreign id never reaches the status/navigate APIs. */
868
- function isValidSessionID(id) {
869
- return typeof id === "string" && id.startsWith("ses");
870
- }
871
- function numberOrNull(value) {
872
- return typeof value === "number" && Number.isFinite(value) ? value : null;
873
- }
874
- /** Model reference shapes the host publishes: `ModelRef` objects, bare ids, or
875
- * `provider/model` strings. Returns the id part, never throws. */
876
- function modelRefID(ref) {
877
- if (typeof ref === "string") return ref === "" ? null : ref;
878
- if (ref && typeof ref === "object") {
879
- const id = ref.id;
880
- if (typeof id === "string" && id !== "") return id;
881
- }
882
- return null;
883
- }
884
- /** Short display id: the segment after the last `/` (`opencode-go/kimi-k3` →
885
- * `kimi-k3`), truncated so a long id never wraps the sidebar. */
886
- function shortModelID(ref, max = 24) {
887
- const id = modelRefID(ref);
888
- if (id === null) return null;
889
- const segment = id.slice(id.lastIndexOf("/") + 1);
890
- if (segment === "") return null;
891
- return segment.length > max ? `${segment.slice(0, Math.max(1, max - 1))}…` : segment;
892
- }
893
- /** `providerID` of a model reference, trimmed; null when absent/blank. Derived
894
- * only from what the host already published — never a lookup table. */
895
- function providerIDFromRef(ref) {
896
- if (ref === null || typeof ref !== "object") return null;
897
- const providerID = ref.providerID;
898
- return typeof providerID === "string" && providerID.trim() !== "" ? providerID.trim() : null;
899
- }
900
- /** Provider for a bare-string model reference: match its id (or bare segment)
901
- * in the host model list. Null when the list cannot answer. */
902
- function providerIDFromModels(models, ref) {
903
- if (!Array.isArray(models)) return null;
904
- const id = modelRefID(ref);
905
- if (id === null) return null;
906
- const segment = id.slice(id.lastIndexOf("/") + 1);
907
- for (const model of models) {
908
- if (!model || typeof model !== "object") continue;
909
- const modelID = typeof model.modelID === "string" ? model.modelID : "";
910
- const rowID = typeof model.id === "string" ? model.id : "";
911
- if (modelID !== id && rowID !== id && modelID !== segment && rowID !== segment) continue;
912
- const providerID = providerIDFromRef(model);
913
- if (providerID !== null) return providerID;
914
- }
915
- return null;
916
- }
917
- /** Resolve `model.limit.context` for a model reference. Match order: the
918
- * provider-qualified id, then the bare id (the host's `id`/`modelID` fields).
919
- * Absent/ambiguous models degrade to null so the gauge is simply omitted. */
920
- function resolveContextLimit(models, ref) {
921
- const id = modelRefID(ref);
922
- if (id === null) return null;
923
- const providerID = ref && typeof ref === "object" ? ref.providerID : void 0;
924
- const segment = id.slice(id.lastIndexOf("/") + 1);
925
- const matches = models.filter((model) => {
926
- if (!model || typeof model !== "object") return false;
927
- const modelID = typeof model.modelID === "string" ? model.modelID : "";
928
- const rowID = typeof model.id === "string" ? model.id : "";
929
- if (!(modelID === id || rowID === id || modelID === segment || rowID === segment)) return false;
930
- if (typeof providerID !== "string" || providerID === "") return true;
931
- return model.providerID === providerID;
932
- });
933
- const candidates = matches.length > 0 ? matches : models.filter((model) => {
934
- const modelID = typeof model?.modelID === "string" ? model.modelID : "";
935
- const rowID = typeof model?.id === "string" ? model.id : "";
936
- return modelID === segment || rowID === segment;
937
- });
938
- for (const model of candidates) {
939
- const limit = model?.limit?.context;
940
- if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) return limit;
941
- }
942
- return null;
943
- }
944
- function asRecord(value) {
945
- return typeof value === "object" && value !== null ? value : void 0;
946
- }
947
- function modelID(ref) {
948
- const record = asRecord(ref);
949
- const id = typeof ref === "string" ? ref : record?.id ?? record?.modelID;
950
- return typeof id === "string" && id.trim() !== "" ? id : null;
951
- }
952
- function messageModelRef(message) {
953
- return message.model ?? message;
954
- }
955
- function modelProvider(ref, models) {
956
- const direct = asRecord(ref)?.providerID;
957
- if (typeof direct === "string" && direct.trim() !== "") return direct.trim();
958
- const id = modelID(ref);
959
- if (id === null) return null;
960
- const segment = id.slice(id.lastIndexOf("/") + 1);
961
- const providers = /* @__PURE__ */ new Set();
962
- for (const candidate of models) {
963
- const item = asRecord(candidate);
964
- if (!item) continue;
965
- if (item.id !== id && item.modelID !== id && item.id !== segment && item.modelID !== segment) continue;
966
- if (typeof item.providerID === "string" && item.providerID.trim() !== "") providers.add(item.providerID.trim());
967
- }
968
- const explicitProvider = id.includes("/") ? id.slice(0, id.indexOf("/")) : null;
969
- if (explicitProvider && providers.has(explicitProvider)) return explicitProvider;
970
- return providers.size === 1 ? [...providers][0] ?? null : null;
971
- }
972
- function modelIdentity(ref, models) {
973
- const id = modelID(ref);
974
- if (id === null) return null;
975
- const providerID = modelProvider(ref, models);
976
- const segment = id.slice(id.lastIndexOf("/") + 1);
977
- return {
978
- key: `${providerID ?? ""}\u0000${id}`,
979
- id,
980
- providerID,
981
- label: segment || id
982
- };
983
- }
984
- function tokenCount(message) {
985
- const tokens = asRecord(message.tokens);
986
- if (!tokens) return null;
987
- const cache = asRecord(tokens.cache);
988
- const reported = [
989
- tokens.input,
990
- tokens.output,
991
- tokens.reasoning,
992
- cache?.read,
993
- cache?.write
994
- ].filter((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
995
- return reported.length === 0 ? null : reported.reduce((sum, value) => sum + value, 0);
996
- }
997
- function contextLimit(ref, models) {
998
- const id = modelID(ref);
999
- if (id === null) return null;
1000
- const providerID = modelProvider(ref, models);
1001
- if (providerID === null) return null;
1002
- const segment = id.slice(id.lastIndexOf("/") + 1);
1003
- const matches = models.filter((value) => {
1004
- const model = asRecord(value);
1005
- if (!model) return false;
1006
- return (model.id === id || model.modelID === id || model.id === segment || model.modelID === segment) && model.providerID === providerID;
1007
- });
1008
- const limits = /* @__PURE__ */ new Set();
1009
- for (const candidate of matches) {
1010
- const limit = asRecord(asRecord(candidate)?.limit)?.context;
1011
- if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) limits.add(limit);
1012
- }
1013
- return limits.size === 1 ? [...limits][0] ?? null : null;
1014
- }
1015
- function liveTranscriptWindow(messages, revertMessageID) {
1016
- let end = messages.length;
1017
- if (revertMessageID) {
1018
- const boundary = messages.findIndex((message) => asRecord(message)?.id === revertMessageID);
1019
- if (boundary >= 0) end = boundary;
1020
- }
1021
- let start = 0;
1022
- for (let index = end - 1; index >= 0; index -= 1) if (asRecord(messages[index])?.type === "compaction") {
1023
- start = index + 1;
1024
- break;
1025
- }
1026
- return {
1027
- start,
1028
- end
1029
- };
1030
- }
1031
- function latestContext(messages, modelRef, models, revertMessageID) {
1032
- const target = modelIdentity(modelRef, models);
1033
- if (target === null || target.providerID === null) return null;
1034
- const limit = contextLimit(modelRef, models);
1035
- if (limit === null || limit <= 0) return null;
1036
- const { start, end } = liveTranscriptWindow(messages, revertMessageID);
1037
- for (let index = end - 1; index >= start; index -= 1) {
1038
- const message = asRecord(messages[index]);
1039
- if (message?.type !== "assistant") continue;
1040
- const identity = modelIdentity(messageModelRef(message), models);
1041
- if (identity?.id !== target.id || identity.providerID !== target.providerID) continue;
1042
- const tokens = tokenCount(message);
1043
- if (tokens === null || tokens <= 0) continue;
1044
- return {
1045
- tokens,
1046
- percent: Math.round(tokens / limit * 100),
1047
- limit
1048
- };
1049
- }
1050
- return null;
1051
- }
1052
- /** Snapshot for one exact model identity in the bounded active transcript. */
1053
- function resolveModelContextSnapshot(messages, modelRef, models, revertMessageID) {
1054
- return latestContext(messages.slice(-400), modelRef, models, revertMessageID);
1055
- }
1056
- /** Select the pinned chat model before transcript or configured-agent fallbacks. */
1057
- function resolveActiveModelRef(sessionModel, activeMessages, fallbackModel = null) {
1058
- if (modelID(sessionModel) !== null) return sessionModel;
1059
- const firstMessage = Math.max(0, activeMessages.length - 400);
1060
- for (let index = activeMessages.length - 1; index >= firstMessage; index -= 1) {
1061
- const message = asRecord(activeMessages[index]);
1062
- if (message?.type !== "assistant") continue;
1063
- const ref = messageModelRef(message);
1064
- if (modelID(ref) !== null) return ref;
1065
- }
1066
- return modelID(fallbackModel) === null ? null : fallbackModel;
1067
- }
1068
- /** Native token total: input + output + reasoning + cache read + cache write. */
1069
- function messageTokensTotal(tokens) {
1070
- const cacheRead = numberOrNull(tokens?.cache?.read) ?? 0;
1071
- const cacheWrite = numberOrNull(tokens?.cache?.write) ?? 0;
1072
- return (numberOrNull(tokens?.input) ?? 0) + (numberOrNull(tokens?.output) ?? 0) + (numberOrNull(tokens?.reasoning) ?? 0) + cacheRead + cacheWrite;
1073
- }
1074
- /** The part of a transcript that still counts: everything before the revert
1075
- * boundary (when a revert is active), then after the last compaction. Both
1076
- * derived numbers that read "the last assistant with usage" — the context
1077
- * gauge and the cache hit rate — share this window, so a reverted-away or
1078
- * compacted-away message can never feed either one. Pure. */
1079
- function transcriptWindow(messages, revertMessageID) {
1080
- let end = messages.length;
1081
- if (typeof revertMessageID === "string" && revertMessageID !== "") {
1082
- const boundary = messages.findIndex((message) => message?.id === revertMessageID);
1083
- if (boundary >= 0) end = boundary;
1084
- }
1085
- let start = 0;
1086
- for (let index = end - 1; index >= 0; index--) if (messages[index]?.type === "compaction") {
1087
- start = index + 1;
1088
- break;
1089
- }
1090
- return {
1091
- start,
1092
- end
1093
- };
1094
- }
1095
- /** Context usage for a message list. Scope: the live window (see
1096
- * `transcriptWindow`). The last assistant message carrying `tokens` in that
1097
- * window wins. Null when there is no limit or no such message — the caller
1098
- * then omits the block. */
1099
- function computeContextUsage(messages, contextLimit, revertMessageID) {
1100
- const limit = numberOrNull(contextLimit);
1101
- if (limit === null || limit <= 0) return null;
1102
- if (!Array.isArray(messages) || messages.length === 0) return null;
1103
- const { start, end } = transcriptWindow(messages, revertMessageID);
1104
- for (let index = end - 1; index >= start; index--) {
1105
- const message = messages[index];
1106
- if (message?.type !== "assistant" || !message.tokens) continue;
1107
- const tokens = messageTokensTotal(message.tokens);
1108
- if (!Number.isFinite(tokens) || tokens <= 0) continue;
1109
- return {
1110
- tokens,
1111
- percent: Math.round(tokens / limit * 100),
1112
- limit
1113
- };
1114
- }
1115
- return null;
1116
- }
1117
- /** Color for one gauge stage. Filled cells and the percent value both come from
1118
- * this one call, so the bar and its number can never disagree. `theme` is the
1119
- * host's resolved theme (loosely typed at runtime); a missing token falls back
1120
- * to the theme's base text instead of an unstyled cell. Pure. */
1121
- function contextProgressColor(stage, theme) {
1122
- return theme?.text?.feedback?.[stage]?.base ?? theme?.text?.base;
1123
- }
1124
- /** The muted extra line under the gauge: `cache 92% · 42.3 tok/s`. Either half
1125
- * may be missing (no cache read, no measurable turn); no data at all yields
1126
- * null so no empty line is rendered. The speed keeps the host's own one
1127
- * decimal and `tok/s` label. Pure. */
1128
- function contextPerformanceLine(performance) {
1129
- if (!performance) return null;
1130
- const parts = [];
1131
- const cacheHit = numberOrNull(performance.cacheHit);
1132
- if (cacheHit !== null) parts.push(`cache ${Math.round(cacheHit)}%`);
1133
- const tokensPerSecond = numberOrNull(performance.tokensPerSecond);
1134
- if (tokensPerSecond !== null) parts.push(`${tokensPerSecond.toFixed(1)} tok/s`);
1135
- return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR);
1136
- }
1137
- /** Cache hit rate of one message: `cache.read / (input + cache.read)` as a
1138
- * percentage. The denominator must be > 0, otherwise the ratio is meaningless
1139
- * (a message that only wrote to the cache has no input to hit). Null when the
1140
- * numbers are absent. Pure. */
1141
- function cacheHitPercent(tokens) {
1142
- const read = numberOrNull(tokens?.cache?.read);
1143
- const input = numberOrNull(tokens?.input);
1144
- if (read === null || input === null) return null;
1145
- const denominator = input + read;
1146
- if (!(denominator > 0)) return null;
1147
- return read / denominator * 100;
1148
- }
1149
- /** The message the cache hit rate comes from: the last assistant of the live
1150
- * window (see `transcriptWindow`) that actually carries `tokens`. Later
1151
- * messages without usage — a streaming placeholder that the host publishes
1152
- * before any step completes, a step that reports no usage — are skipped
1153
- * instead of blanking a ratio the previous message already measured. Null
1154
- * when nothing in the window has usage. Pure. */
1155
- function lastAssistantWithTokens(messages, revertMessageID) {
1156
- if (!Array.isArray(messages) || messages.length === 0) return null;
1157
- const { start, end } = transcriptWindow(messages, revertMessageID);
1158
- for (let index = end - 1; index >= start; index--) {
1159
- const message = messages[index];
1160
- if (message?.type !== "assistant" || !message.tokens) continue;
1161
- return message;
1162
- }
1163
- return null;
1164
- }
1165
- /** Tokens per second of the current turn. Mirrors the host's
1166
- * `turnTokensPerSecond` (anomalyco/opencode v2.0.30,
1167
- * `packages/tui/src/routes/session/rows.ts`) so the sidebar and the native
1168
- * session footer can never disagree: the numerator is `output + reasoning`
1169
- * summed over every assistant step of the turn and the denominator is the
1170
- * summed active streaming time `max(0, time.streamed - time.created)`, so the
1171
- * division happens once, after aggregating — each step weighs by its own
1172
- * duration instead of each step voting equally. `completed` is never used; a
1173
- * turn with a step that has no `time.streamed` has no measurable speed. The
1174
- * turn starts after the last `user` message; with no user message only the
1175
- * last assistant step counts (degraded: there is no boundary to group by).
1176
- * Pure and fail-open. */
1177
- function turnTokensPerSecond(messages, position) {
1178
- if (!Array.isArray(messages) || messages.length === 0) return null;
1179
- let anchor = -1;
1180
- if (typeof position === "number" && Number.isInteger(position) && position >= 0 && position < messages.length) anchor = position;
1181
- else for (let index = messages.length - 1; index >= 0; index--) if (messages[index]?.type === "assistant") {
1182
- anchor = index;
1183
- break;
1184
- }
1185
- if (anchor === -1 || messages[anchor]?.type !== "assistant") return null;
1186
- let start = -1;
1187
- for (let index = anchor - 1; index >= 0; index--) if (messages[index]?.type === "user") {
1188
- start = index;
1189
- break;
1190
- }
1191
- const steps = start === -1 ? [messages[anchor]] : messages.slice(start + 1, anchor + 1).filter((item) => item?.type === "assistant");
1192
- if (steps.length === 0) return null;
1193
- let output = 0;
1194
- let duration = 0;
1195
- for (const step of steps) {
1196
- output += (numberOrNull(step?.tokens?.output) ?? 0) + (numberOrNull(step?.tokens?.reasoning) ?? 0);
1197
- const created = numberOrNull(step?.time?.created);
1198
- const streamed = numberOrNull(step?.time?.streamed);
1199
- if (created === null || streamed === null) return null;
1200
- duration += Math.max(0, streamed - created);
1201
- }
1202
- if (output <= 0 || duration <= 0) return null;
1203
- const rate = output / (duration / 1e3);
1204
- return Number.isFinite(rate) && rate > 0 ? rate : null;
1205
- }
1206
- /** Last-message telemetry the Context block renders in muted text. Both halves
1207
- * are optional; the block renders no line when neither is available. */
1208
- /** One rendered context row. `lead` and `tail` carry the gauge bar when the row
1209
- * has one (`lead` is toned with the value, `tail` is muted), so the 12 cells
1210
- * stay contiguous while the empty half still reads as background. */
1211
- /** The `Context` block's data rows; null rows are not rendered. */
1212
- /** Rows for the `Context` block:
1213
- * `<tokens> tokens` / `▰▰▰▰▰▱▱▱▱▱▱▱ <percent>% of <window>` /
1214
- * `$<spent> spent`. The percentage row carries the only semantic tone, the
1215
- * gauge bar (12 cells) and is omitted entirely when the percentage is
1216
- * unavailable (never `undefined%`). A block with neither tokens nor cost
1217
- * yields null. Pure. */
1218
- function contextBlockRows(usage, cost) {
1219
- const spentValue = formatSpent(cost);
1220
- const spent = spentValue === null ? null : {
1221
- lead: null,
1222
- value: spentValue,
1223
- tail: null,
1224
- suffix: " gasto na sessão",
1225
- tone: null
1226
- };
1227
- if (usage === null) return spent === null ? null : {
1228
- tokens: null,
1229
- percent: null,
1230
- spent
1231
- };
1232
- const tokensValue = formatTokenCount(usage.tokens);
1233
- const tokens = tokensValue === null ? null : {
1234
- lead: null,
1235
- value: tokensValue,
1236
- tail: null,
1237
- suffix: " tokens",
1238
- tone: null
1239
- };
1240
- const percentValue = numberOrNull(usage.percent);
1241
- const window = formatContextWindow(usage.limit);
1242
- const bar = contextBar(percentValue);
1243
- const percent = bar === null || percentValue === null ? null : {
1244
- lead: bar.filled,
1245
- value: ` ${Math.round(percentValue)}%`,
1246
- tail: bar.empty,
1247
- suffix: window === null ? null : ` of ${window}`,
1248
- tone: contextUsageTone(percentValue)
1249
- };
1250
- if (tokens === null && percent === null && spent === null) return null;
1251
- return {
1252
- tokens,
1253
- percent,
1254
- spent
1255
- };
1256
- }
1257
- /** Column widths for one model row (labels are muted, numbers right-aligned). */
1258
- const MODEL_USAGE_MODEL_WIDTH = 12;
1259
- const MODEL_USAGE_TOKEN_WIDTH = 6;
1260
- const MODEL_USAGE_COST_WIDTH = 8;
1261
- /** Session events arrive in bursts; model rows are recomputed at most once
1262
- * per window (same cadence as the git-count revalidation). */
1263
- const MODEL_USAGE_DEBOUNCE_MS = 400;
1264
- /** Real usage for one model, summed across the assistant messages that used it. */
1265
- /** Totals per model from assistant messages: sums `cost` and `tokens`, drops
1266
- * models whose real cost is 0/absent, and orders by cost (then tokens, then
1267
- * name). `providerID` participates in the key so two providers exposing the
1268
- * same bare id are not merged. Pure. */
1269
- function collectModelUsage(messages) {
1270
- if (!Array.isArray(messages)) return [];
1271
- const totals = /* @__PURE__ */ new Map();
1272
- for (const message of messages) {
1273
- if (message?.type !== "assistant") continue;
1274
- const id = modelRefID(message.model);
1275
- const model = shortModelID(message.model, 12);
1276
- if (id === null || model === null) continue;
1277
- const key = `${typeof message.model?.providerID === "string" ? message.model.providerID : ""}\u0000${id}`;
1278
- const tokensTotal = message.tokens ? messageTokensTotal(message.tokens) : 0;
1279
- const cost = numberOrNull(message.cost) ?? 0;
1280
- const current = totals.get(key);
1281
- if (current) {
1282
- current.tokens += Math.max(0, tokensTotal);
1283
- current.cost += Math.max(0, cost);
1284
- } else totals.set(key, {
1285
- model,
1286
- tokens: Math.max(0, tokensTotal),
1287
- cost: Math.max(0, cost)
1288
- });
1289
- }
1290
- return [...totals.values()].filter((row) => row.cost > 0).sort((a, b) => b.cost - a.cost || b.tokens - a.tokens || a.model.localeCompare(b.model));
1291
- }
1292
- /** Visible rows plus the aggregate of the models that did not fit. Pure. */
1293
- /** Cap the model list at `maxVisible`; the rest is aggregated (still real
1294
- * totals) for the `… +N` line. Pure. */
1295
- function ceilingModelUsage(rows, maxVisible = 3) {
1296
- const limit = Math.max(0, maxVisible);
1297
- const visible = rows.slice(0, limit);
1298
- const rest = rows.slice(visible.length);
1299
- return {
1300
- visible,
1301
- hidden: rest.length,
1302
- hiddenCost: rest.reduce((sum, row) => sum + row.cost, 0),
1303
- hiddenTokens: rest.reduce((sum, row) => sum + row.tokens, 0)
1304
- };
1305
- }
1306
- /** Compact tokens for a model row (`80,000` → `80K`); `0` stays explicit. Pure. */
1307
- function formatUsageTokens(tokens) {
1308
- const value = numberOrNull(tokens);
1309
- if (value === null || value <= 0) return "0";
1310
- return formatContextWindow(value) ?? String(Math.round(value));
1311
- }
1312
- /** Real per-model cost with adaptive precision: cents for `>= $0.01`, up to
1313
- * four decimals below that (a real `$0.0031` must not render as `$0.00`), and
1314
- * an explicit `< $0.0001` for the remainder. Pure. */
1315
- function formatUsageCost(cost) {
1316
- const value = numberOrNull(cost);
1317
- if (value === null || value < 0) return null;
1318
- if (value === 0) return "$0.00";
1319
- if (value >= .01) return `$${value.toFixed(2)}`;
1320
- if (value >= 1e-4) return `$${value.toFixed(4).replace(/0+$/, "").replace(/\.$/, "")}`;
1321
- return "<$0.0001";
1322
- }
1323
- /** One formatted model row: truncated label + compact tokens + real cost. */
1324
- /** Format the visible model rows for rendering. Labels are already short ids
1325
- * (12 chars); the second truncation only guards host drift. Pure. */
1326
- function modelUsageRows(rows) {
1327
- return rows.map((row) => ({
1328
- model: truncateLabel(row.model, 12),
1329
- tokens: formatUsageTokens(row.tokens),
1330
- cost: formatUsageCost(row.cost) ?? "$0.00"
1331
- }));
1332
- }
1333
- /** Exact single-line text of a model row, with numbers right-aligned. Pure. */
1334
- function modelUsageRowText(row) {
1335
- return `${row.model.padEnd(12)} ${row.tokens.padStart(6)} ${row.cost.padStart(8)}`;
1336
- }
1337
- /** Wrap on grapheme boundaries, measuring terminal cells rather than code units.
1338
- * (Body moved verbatim from the removed quota module's `quotaTextLines`.) */
1339
- function wrapTextLines(text, width, indent) {
1340
- const max = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
1341
- if (max < 1) return [];
1342
- const padding = " ".repeat(Math.min(Math.max(0, indent), Math.max(0, max - 2)));
1343
- const lines = [];
1344
- let line = padding;
1345
- const segmenter = new Intl.Segmenter();
1346
- for (const word of text.trim().split(/\s+/)) {
1347
- if (!word) continue;
1348
- if (line.trim() && cellWidth(line) + 1 + cellWidth(word) > max) {
1349
- lines.push(line.trimEnd());
1350
- line = padding;
1351
- }
1352
- if (line.trim()) line += " ";
1353
- for (const { segment } of segmenter.segment(word)) {
1354
- const glyphWidth = cellWidth(segment);
1355
- if (glyphWidth > max) continue;
1356
- if (cellWidth(line) + glyphWidth > max) {
1357
- if (line.trim()) lines.push(line.trimEnd());
1358
- line = glyphWidth + cellWidth(padding) <= max ? padding : "";
1359
- }
1360
- line += segment;
1361
- }
1362
- }
1363
- if (line.trim()) lines.push(line.trimEnd());
1364
- return lines;
1365
- }
1366
- /** Wrap sidebar text by terminal cells, preserving the complete values. */
1367
- function sidebarTextLines(value) {
1368
- return wrapTextLines(value, 34, 0);
1369
- }
1370
- /** Align a monetary value when it fits, otherwise preserve it on a new line. */
1371
- function sidebarMoneyLines(label, value) {
1372
- const gap = 34 - cellWidth(label) - cellWidth(value);
1373
- return gap >= 1 ? [`${label}${" ".repeat(gap)}${value}`] : [...sidebarTextLines(label), ...sidebarTextLines(value)];
1374
- }
1375
- /** Keep the existing OpenCode periods together when possible. */
1376
- function contextSpendLines(value) {
1377
- const match = /^(.*\S)\s+(<?\$\S+)$/.exec(value);
1378
- return match?.[1] && match[2] && cellWidth(value) <= 34 ? sidebarMoneyLines(match[1], match[2]) : sidebarTextLines(value);
1379
- }
1380
- /** Keep ordinary rows aligned; give oversized values their own lines. */
1381
- function modelUsageRowLines(row) {
1382
- const single = modelUsageRowText(row);
1383
- if (cellWidth(single) <= 34) return [single];
1384
- return [
1385
- ...sidebarTextLines(row.model),
1386
- ...sidebarTextLines(`Tokens ${row.tokens}`),
1387
- ...sidebarTextLines(`USD ${row.cost}`)
1388
- ];
1389
- }
1390
- /** Muted aggregate line for the models beyond the cap (`… +2 $0.03`). Null
1391
- * when every model fits. Pure. */
1392
- function hiddenModelUsageText(hidden, hiddenCost) {
1393
- if (!Number.isFinite(hidden) || hidden <= 0) return null;
1394
- const cost = formatUsageCost(hiddenCost);
1395
- return cost === null ? `… +${hidden}` : `… +${hidden} ${cost}`;
1396
- }
1397
- /** Bucket for a session the host published without an agent id. */
1398
- const UNKNOWN_AGENT = "?";
1399
- /** Agent key of a session or message: the trimmed id when it is a non-empty
1400
- * string, else the `?` bucket — never `undefined`. Pure. */
1401
- function agentKey(value) {
1402
- if (typeof value !== "string") return "?";
1403
- const text = value.trim();
1404
- return text === "" ? "?" : text;
1405
- }
1406
- /** One rendered todo row. `priority` is carried by the tool but not rendered:
1407
- * the reference block uses a single marker column. */
1408
- /** Rows rendered before the `… +N` line. */
1409
- const TODO_VISIBLE_CEILING = 6;
1410
- /** Content width before the ellipsis — the block has ~30-34 usable columns. */
1411
- const TODO_TEXT_WIDTH = 28;
1412
- /** Row markers (`•` in progress, `−` cancelled with U+2212, as in the git row). */
1413
- const TODO_MARKERS = {
1414
- in_progress: "[•]",
1415
- pending: "[ ]",
1416
- completed: "[x]",
1417
- cancelled: "[−]"
1418
- };
1419
- /** Group order: live work first, then open, then closed. */
1420
- const TODO_STATUS_ORDER = [
1421
- "in_progress",
1422
- "pending",
1423
- "completed",
1424
- "cancelled"
1425
- ];
1426
- /** Narrow a loose `status` value to the tool's four states. */
1427
- function isTodoStatus(value) {
1428
- return value === "in_progress" || value === "pending" || value === "completed" || value === "cancelled";
1429
- }
1430
- /** Items from a `todowrite` `input` payload. A missing/malformed `input`,
1431
- * absent `todos`, an unknown `status` or an empty/missing `content` drops the
1432
- * entry instead of throwing; a list with nothing readable yields `[]`. Pure. */
1433
- function parseTodoItems(input) {
1434
- const raw = input?.todos;
1435
- if (!Array.isArray(raw)) return [];
1436
- const items = [];
1437
- for (const entry of raw) {
1438
- const content = entry?.content;
1439
- const status = entry?.status;
1440
- if (typeof content !== "string" || content.trim() === "") continue;
1441
- if (!isTodoStatus(status)) continue;
1442
- items.push({
1443
- content: content.trim(),
1444
- status
1445
- });
1446
- }
1447
- return items;
1448
- }
1449
- /** Newest completed `todowrite` in a transcript. The tool replaces the list
1450
- * wholesale, so the last write wins; a write with `todos: []` returns null
1451
- * (the block disappears rather than showing the previous list) and a
1452
- * not-yet-completed write is ignored. Null when the transcript carries no
1453
- * such part, so the block never renders a guess. Pure. */
1454
- function latestTodoItems(messages) {
1455
- if (!Array.isArray(messages)) return null;
1456
- for (let index = messages.length - 1; index >= 0; index--) {
1457
- const message = messages[index];
1458
- if (message?.type !== "assistant" || !Array.isArray(message.content)) continue;
1459
- const parts = message.content;
1460
- for (let position = parts.length - 1; position >= 0; position--) {
1461
- const part = parts[position];
1462
- if (part?.type !== "tool" || part?.name !== "todowrite") continue;
1463
- if (part?.state?.status !== "completed") continue;
1464
- const items = parseTodoItems(part.state.input);
1465
- return items.length === 0 ? null : items;
1466
- }
1467
- }
1468
- return null;
1469
- }
1470
- /** Stable group order (in_progress → pending → completed → cancelled); within a
1471
- * group the transcript order is preserved. Pure. */
1472
- function orderTodoItems(items) {
1473
- return [...items].sort((a, b) => TODO_STATUS_ORDER.indexOf(a.status) - TODO_STATUS_ORDER.indexOf(b.status));
1474
- }
1475
- /** Row color channel: `accent` for live work, `muted` for closed items, base
1476
- * for pending. Kept separate from the theme so it is testable. Pure. */
1477
- /** Tone for one status — no rainbow, a single accent. Pure. */
1478
- function todoTone(status) {
1479
- if (status === "in_progress") return "accent";
1480
- if (status === "completed" || status === "cancelled") return "muted";
1481
- return "base";
1482
- }
1483
- /** Exact rendered text of one row: `[•] <content truncated to 28>`. Pure. */
1484
- function todoRowText(item) {
1485
- return `${TODO_MARKERS[item.status]} ${truncateLabel(item.content, 28)}`;
1486
- }
1487
- /** Ordered rows capped for the sidebar, plus how many did not fit. Pure. */
1488
- /** Order then cap the list at `maxVisible`. Pure. */
1489
- function ceilingTodoItems(items, maxVisible = 6) {
1490
- const ordered = orderTodoItems(items);
1491
- const visible = ordered.slice(0, Math.max(0, maxVisible));
1492
- return {
1493
- visible,
1494
- hidden: Math.max(0, ordered.length - visible.length)
1495
- };
1496
- }
1497
- /** Overflow line (`… +3`); null when every item fits. Pure. */
1498
- function hiddenTodoText(hidden) {
1499
- if (!Number.isFinite(hidden) || hidden <= 0) return null;
1500
- return `… +${Math.round(hidden)}`;
1501
- }
1502
- /** Narrow a `VcsFileStatus["status"]` value read off a loose payload. */
1503
- function isGitChangeStatus(value) {
1504
- return value === "added" || value === "modified" || value === "deleted";
1505
- }
1506
- /** Files per status from a `VcsFileStatus[]` payload. Unknown statuses and
1507
- * malformed entries are ignored. Pure. */
1508
- function countGitChanges(files) {
1509
- const counts = {
1510
- added: 0,
1511
- modified: 0,
1512
- deleted: 0
1513
- };
1514
- if (!Array.isArray(files)) return counts;
1515
- for (const entry of files) {
1516
- const status = entry?.status;
1517
- if (isGitChangeStatus(status)) counts[status] += 1;
1518
- }
1519
- return counts;
1520
- }
1521
- /** `+1 ±2 −3` for the file counts; each zero term is omitted, and an empty
1522
- * change set returns null so the row is not rendered at all. Pure. */
1523
- function formatGitChanges(files) {
1524
- const { added, modified, deleted } = countGitChanges(files);
1525
- const parts = [];
1526
- if (added > 0) parts.push(`+${added}`);
1527
- if (modified > 0) parts.push(`±${modified}`);
1528
- if (deleted > 0) parts.push(`\u2212${deleted}`);
1529
- return parts.length === 0 ? null : parts.join(" ");
1530
- }
1531
- /** Wall-clock ceiling for one git call. A stuck git (index lock, network
1532
- * filesystem) is killed instead of holding the row forever. */
1533
- const GIT_CLI_TIMEOUT_MS = 2e3;
1534
- /** Session events arrive in bursts; a git probe is scheduled at most once per
1535
- * window instead of once per event. */
1536
- const GIT_CLI_DEBOUNCE_MS = 1e3;
1537
- /** Minimum spacing between two probe starts. Five seconds keeps a chatty event
1538
- * stream from spawning a git process per step while staying fresh enough to
1539
- * show a file appearing mid-turn. */
1540
- const GIT_CLI_MIN_INTERVAL_MS = 5e3;
1541
- /** Stdout ceiling for one git call. `status --porcelain=v1 -uall` lists every
1542
- * untracked file, so a large worktree easily passes the 1 MB `execFile`
1543
- * default — which would reject and silently hand the row back to the
1544
- * `vcs.status` fallback. 4 MB is far above a realistic porcelain listing. */
1545
- const GIT_CLI_MAX_BUFFER = 4194304;
1546
- /** One `execFile` call: `(file, args, options) → { stdout }`. Injectable so the
1547
- * parsing/gating logic is testable without spawning processes. */
1548
- /** Default runner: the promisified `node:child_process.execFile`. A non-zero
1549
- * exit (no repository, no upstream) rejects and the caller decides. */
1550
- const defaultGitExec = (file, args, options) => new Promise((resolve, reject) => {
1551
- execFile(file, [...args], {
1552
- cwd: options.cwd,
1553
- timeout: options.timeout,
1554
- windowsHide: options.windowsHide,
1555
- maxBuffer: options.maxBuffer
1556
- }, (error, stdout) => {
1557
- if (error) reject(error);
1558
- else resolve({ stdout: typeof stdout === "string" ? stdout : String(stdout ?? "") });
1559
- });
1560
- });
1561
- /** Files per status from `git status --porcelain=v1 -uall`, including the two
1562
- * columns the protocol cannot report. Each line starts with `XY` (index and
1563
- * worktree state); a rename prints `R old -> new`, and `??` / `!!` are
1564
- * untracked / ignored. Precedence per file: deleted > added > modified, so
1565
- * `AM` counts once as added and `AD` once as deleted. Renames, copies and
1566
- * unmerged entries count as modified. Pure. */
1567
- /** Parse porcelain v1 output into file counts. Empty/malformed output yields
1568
- * zero counts (a clean tree), never a throw. Pure. */
1569
- function parseGitStatusPorcelain(output) {
1570
- const counts = {
1571
- added: 0,
1572
- modified: 0,
1573
- deleted: 0,
1574
- untracked: 0
1575
- };
1576
- if (typeof output !== "string" || output === "") return counts;
1577
- for (const line of output.split("\n")) {
1578
- if (line.length < 2) continue;
1579
- const index = line[0];
1580
- const worktree = line[1];
1581
- if (index === "!" && worktree === "!") continue;
1582
- if (index === "?" && worktree === "?") {
1583
- counts.untracked += 1;
1584
- continue;
1585
- }
1586
- if (index === " " && worktree === " ") continue;
1587
- if (index === "D" || worktree === "D") counts.deleted += 1;
1588
- else if (index === "A" || worktree === "A") counts.added += 1;
1589
- else counts.modified += 1;
1590
- }
1591
- return counts;
1592
- }
1593
- /** `git rev-list --count --left-right @{upstream}...HEAD` prints two numbers:
1594
- * commits only on the upstream (behind) then commits only on HEAD (ahead).
1595
- * Null when the output is not that pair — e.g. the command failed because the
1596
- * branch has no upstream, in which case the arrows are simply omitted. Pure. */
1597
- function parseGitAheadBehind(output) {
1598
- if (typeof output !== "string") return null;
1599
- const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(output);
1600
- if (match === null) return null;
1601
- const behind = Number(match[1]);
1602
- const ahead = Number(match[2]);
1603
- if (!Number.isFinite(ahead) || !Number.isFinite(behind)) return null;
1604
- return {
1605
- ahead,
1606
- behind
1607
- };
1608
- }
1609
- /** One git observation: file counts plus the upstream distance (either arrow
1610
- * may be unknown when the branch has no upstream). */
1611
- /** One probe: `git status --porcelain=v1 -uall` for the counts, then
1612
- * `git rev-list --count --left-right @{upstream}...HEAD` for the arrows (a
1613
- * failure there only drops the arrows). A status failure rejects — the caller
1614
- * then falls back to `client.vcs.status`. */
1615
- async function readGitSnapshot(directory, exec = defaultGitExec) {
1616
- const options = {
1617
- cwd: directory,
1618
- timeout: GIT_CLI_TIMEOUT_MS,
1619
- windowsHide: true,
1620
- maxBuffer: GIT_CLI_MAX_BUFFER
1621
- };
1622
- const changes = parseGitStatusPorcelain((await exec("git", [
1623
- "status",
1624
- "--porcelain=v1",
1625
- "-uall"
1626
- ], options))?.stdout);
1627
- let ahead = null;
1628
- let behind = null;
1629
- try {
1630
- const parsed = parseGitAheadBehind((await exec("git", [
1631
- "rev-list",
1632
- "--count",
1633
- "--left-right",
1634
- "@{upstream}...HEAD"
1635
- ], options))?.stdout);
1636
- if (parsed !== null) {
1637
- ahead = parsed.ahead;
1638
- behind = parsed.behind;
1639
- }
1640
- } catch {}
1641
- return {
1642
- changes,
1643
- ahead,
1644
- behind
1645
- };
1646
- }
1647
- /** Rendered git row: `+1 ±2 −1 ?2 ↑3 ↓1`, zero terms omitted. Null when the
1648
- * tree is clean and in sync, so the block keeps only its branch line. Pure. */
1649
- function formatGitSnapshot(snapshot) {
1650
- if (!snapshot?.changes) return null;
1651
- const { added, modified, deleted, untracked } = snapshot.changes;
1652
- const parts = [];
1653
- if (added > 0) parts.push(`+${added}`);
1654
- if (modified > 0) parts.push(`±${modified}`);
1655
- if (deleted > 0) parts.push(`\u2212${deleted}`);
1656
- if (untracked > 0) parts.push(`?${untracked}`);
1657
- if ((snapshot.ahead ?? 0) > 0) parts.push(`↑${snapshot.ahead}`);
1658
- if ((snapshot.behind ?? 0) > 0) parts.push(`↓${snapshot.behind}`);
1659
- return parts.length === 0 ? null : parts.join(" ");
1660
- }
1661
- /** Whether a new probe may start. An in-flight probe always wins (no queue), and
1662
- * the previous start must be older than the cooldown. Pure. */
1663
- function gitProbeAllowed(state, cooldownMs = GIT_CLI_MIN_INTERVAL_MS) {
1664
- if (state.inFlight) return false;
1665
- if (state.lastRunAt === null) return true;
1666
- const elapsed = state.now - state.lastRunAt;
1667
- return !Number.isFinite(elapsed) || elapsed >= cooldownMs;
1668
- }
1669
- /** Spend window labels, in render order. */
1670
- const SPEND_TODAY_LABEL = "hoje";
1671
- const SPEND_30D_LABEL = "30d";
1672
- /** Separator between the two windows on the Context footer line. */
1673
- const SPEND_LINE_SEPARATOR = " · ";
1674
- /** `30d` window: 30 × 24 h, measured back from "now". */
1675
- const SPEND_30D_MS = 2592e6;
1676
- /** Probe window: one hour, narrow enough that a unit mix-up cannot line up. */
1677
- const SPEND_PROBE_WINDOW_MS = 36e5;
1678
- /** The echoed `range` may be rounded server-side; 120 s absorbs that. */
1679
- const SPEND_PROBE_TOLERANCE_MS = 12e4;
1680
- /** Session events arrive in bursts — same 400 ms window as the other blocks. */
1681
- const SPEND_REFRESH_DEBOUNCE_MS = 400;
1682
- /** Spend per window in USD. Either side may be unknown (kept `null`). */
1683
- /** `from`/`to` unit accepted by the route. `SessionStatsInput` declares both as
1684
- * bare `number` and does not say which unit, so it is measured once per
1685
- * process (`ms` unless the server echoes seconds) instead of guessed. */
1686
- /** Resolved unit for this process; `null` until the mount probe answers. */
1687
- let spendUnit = null;
1688
- /** In-flight probe, so two refreshes cannot each burn the 2-call budget. */
1689
- let spendProbe = null;
1690
- /** Test-only: forget the process-wide unit resolution. Never called at runtime. */
1691
- function resetSpendUnit() {
1692
- spendUnit = null;
1693
- spendProbe = null;
1694
- }
1695
- /** Resolved unit (`ms` / `s` / `unavailable`) or null while still unknown. */
1696
- function resolvedSpendUnit() {
1697
- return spendUnit;
1698
- }
1699
- /** Local midnight for `now`: `new Date()` with the clock fields zeroed in the
1700
- * current timezone (DST-safe, unlike subtracting hours). Pure. */
1701
- function startOfLocalDay(now) {
1702
- const date = new Date(now);
1703
- date.setHours(0, 0, 0, 0);
1704
- return date.getTime();
1705
- }
1706
- /** The two windows the block shows: `hoje` (local midnight → now) and `30d`
1707
- * (now − 30 days → now). Pure. */
1708
- function spendWindows(now) {
1709
- return {
1710
- today: {
1711
- from: startOfLocalDay(now),
1712
- to: now
1713
- },
1714
- thirtyDays: {
1715
- from: now - SPEND_30D_MS,
1716
- to: now
1717
- }
1718
- };
1719
- }
1720
- /** USD with two decimals (`$0.42`), four for a positive sub-cent amount
1721
- * (`$0.0031`), and `<$0.0001` when even four decimals would read `$0.0000`.
1722
- * `0` prints `$0.00`. Null for a missing/negative/non-finite value. Pure. */
1723
- function formatSpendUSD(cost) {
1724
- const value = numberOrNull(cost);
1725
- if (value === null || value < 0) return null;
1726
- if (value === 0) return "$0.00";
1727
- if (value >= .01) return `$${value.toFixed(2)}`;
1728
- const cents = value.toFixed(2);
1729
- if (cents !== "0.00") return `$${cents}`;
1730
- const cents4 = value.toFixed(4);
1731
- return cents4 === "0.0000" ? "<$0.0001" : `$${cents4}`;
1732
- }
1733
- /** `cost` off a `SessionStatsInfo` (`MoneyUSD` = number) or null when the
1734
- * payload is malformed/negative, so a bad value never reaches a row. Pure. */
1735
- function statsCost(result) {
1736
- const cost = numberOrNull(result?.cost);
1737
- return cost !== null && cost >= 0 ? cost : null;
1738
- }
1739
- /** True when the server echoed the window we sent, within 120 s. `scale` is how
1740
- * many milliseconds one unit of the sent window is worth (`1` for `ms`, `1000`
1741
- * for `s`). The echo is accepted either as the same numbers we sent (the route
1742
- * keeps the caller's unit) or converted to millisecond epoch (`DateTime.Utc`),
1743
- * so the probe pins the unit without assuming which of the two it gets. Pure. */
1744
- function statsRangeMatches(range, sent, scale) {
1745
- const from = numberOrNull(range?.from);
1746
- const to = numberOrNull(range?.to);
1747
- if (from === null || to === null) return false;
1748
- const tolerance = SPEND_PROBE_TOLERANCE_MS / scale;
1749
- const sameUnit = Math.abs(from - sent.from) <= tolerance && Math.abs(to - sent.to) <= tolerance;
1750
- const asMilliseconds = Math.abs(from - sent.from * scale) <= 12e4 && Math.abs(to - sent.to * scale) <= 12e4;
1751
- return sameUnit || asMilliseconds;
1752
- }
1753
- /** The `Context` block's last line: OpenCode stats source and both spend windows
1754
- * on one muted row (`OpenCode · hoje $0.42 · 30d $9.80`). A window without a
1755
- * usable amount is omitted, and no usable window at all yields null so the
1756
- * line (and not the block) is dropped. Pure. */
1757
- function contextSpendLine(totals) {
1758
- if (totals === null) return null;
1759
- const parts = [];
1760
- const today = formatSpendUSD(totals.today);
1761
- if (today !== null) parts.push(`${SPEND_TODAY_LABEL} ${today}`);
1762
- const thirtyDays = formatSpendUSD(totals.thirtyDays);
1763
- if (thirtyDays !== null) parts.push(`30d ${thirtyDays}`);
1764
- return parts.length === 0 ? null : `OpenCode${SPEND_LINE_SEPARATOR}${parts.join(SPEND_LINE_SEPARATOR)}`;
1765
- }
1766
- /** Grapheme iterator: a cut never splits a surrogate pair, a combining mark
1767
- * from its base or a ZWJ emoji sequence, so truncation stays cell-exact. */
1768
- /** Clamp a free-form label to `max` terminal cells without wrapping. The width
1769
- * is measured in display cells, never in UTF-16 code units: a CJK or emoji
1770
- * label used to overflow the column it was cut for (`計画の移行` is 5 code
1771
- * units but 10 cells, `🚀` is 2 units and 2 cells). Pure. */
1772
- function truncateLabel(value, max = 28) {
1773
- const text = value.trim();
1774
- const budget = Math.max(1, Math.floor(numberOrNull(max) ?? 1));
1775
- if (cellWidth(text) <= budget) return text;
1776
- const ellipsis = "…";
1777
- const room = budget - cellWidth(ellipsis);
1778
- let cut = "";
1779
- let used = 0;
1780
- for (const { segment } of GRAPHEMES.segment(text)) {
1781
- const width = cellWidth(segment);
1782
- if (used + width > room) break;
1783
- cut += segment;
1784
- used += width;
1785
- }
1786
- return `${cut.replace(/\s+$/, "")}${ellipsis}`;
1787
- }
1788
- /** Right-pad `value` with spaces to exactly `cells` display columns (a wider
1789
- * value is truncated first). `padEnd` counts code units, so it under-pads a
1790
- * CJK/emoji cell and the next column drifts. Pure. */
1791
- function padCell(value, cells) {
1792
- const width = Math.max(0, Math.floor(numberOrNull(cells) ?? 0));
1793
- if (width === 0) return "";
1794
- const text = truncateLabel(value, width);
1795
- return `${text}${" ".repeat(Math.max(0, width - cellWidth(text)))}`;
1796
- }
1797
- /** Columns the fixed header may use before it would wrap the sidebar. */
1798
- const HEADER_MAX_WIDTH = 34;
1799
- /** Preset row of the fixed header: `▸ <preset> · <provider>`. The provider is
1800
- * cut first when the row overflows, so the preset name is never the casualty;
1801
- * a missing provider leaves the preset alone (no `unknown` placeholder). */
1802
- function presetHeaderLine(presetName, providerID) {
1803
- const base = `▸ ${presetName.trim() === "" ? "default" : presetName.trim()}`;
1804
- const provider = providerID === null ? "" : providerID.trim();
1805
- if (provider === "") return truncateLabel(base, HEADER_MAX_WIDTH);
1806
- const room = HEADER_MAX_WIDTH - `${base} · `.length;
1807
- if (room < 2) return truncateLabel(base, HEADER_MAX_WIDTH);
1808
- return `${base} · ${truncateLabel(provider, room)}`;
1809
- }
1810
- /** One classification plus the evidence that produced it. */
1811
- /** Bracketed description prefix → short label (`[council]` → `coun`). */
1812
- const DISPATCH_PREFIX_KINDS = [
1813
- ["council", "coun"],
1814
- ["discovery", "disc"],
1815
- ["hotfix", "hot"],
1816
- ["plan", "plan"],
1817
- ["review", "revw"]
1818
- ];
1819
- /** Agent → kind, consulted only when the description declares no prefix.
1820
- * `council` is deliberately absent — see the section comment. */
1821
- const DISPATCH_AGENT_KINDS = {
1822
- apollo: "disc",
1823
- athena: "plan",
1824
- talos: "hot",
1825
- themis: "revw"
1826
- };
1827
- /** Kind declared by a leading `[prefix]` on the description: case-insensitive
1828
- * and tolerant of spaces inside the brackets. Null when none is declared. */
1829
- function dispatchKindFromPrefix(description) {
1830
- if (typeof description !== "string") return null;
1831
- const match = /^\s*\[\s*([a-z]+)\s*\]/i.exec(description);
1832
- if (match === null) return null;
1833
- const token = (match[1] ?? "").toLowerCase();
1834
- for (const [word, kind] of DISPATCH_PREFIX_KINDS) if (word === token) return kind;
1835
- return null;
1836
- }
1837
- /** Kind implied by the child's agent, null for an agent that implies none. */
1838
- function dispatchKindFromAgent(agent) {
1839
- if (typeof agent !== "string") return null;
1840
- return DISPATCH_AGENT_KINDS[agent.trim().toLowerCase()] ?? null;
1841
- }
1842
- /** Classify one dispatch. The description prefix always wins over the agent;
1843
- * otherwise the agent decides, and anything else is `oth` (a real dispatch we
1844
- * simply cannot name). A missing call is the only `unavailable` outcome. Pure. */
1845
- function classifyDispatchKind(call) {
1846
- if (call === null || call === void 0) return {
1847
- kind: null,
1848
- origin: "unavailable"
1849
- };
1850
- const fromPrefix = dispatchKindFromPrefix(call.description);
1851
- if (fromPrefix !== null) return {
1852
- kind: fromPrefix,
1853
- origin: "prefix"
1854
- };
1855
- return {
1856
- kind: dispatchKindFromAgent(call.agent) ?? "oth",
1857
- origin: "agent"
1858
- };
1859
- }
1860
- /** A `subagent` tool call the parent made, as its own transcript records it. */
1861
- /** Host tool that spawns a child (V2 name; it is not `task`). */
1862
- const SUBAGENT_TOOL = "subagent";
1863
- /** The tool result also names its child: `<subagent sessionID="ses_…" …>`. */
1864
- const SUBAGENT_SESSION_PATTERN = /sessionID="([^"]+)"/;
1865
- /** Text of a tool `content` payload, joined; tolerant of the string form. */
1866
- function toolContentText(content) {
1867
- if (typeof content === "string") return content;
1868
- if (!Array.isArray(content)) return "";
1869
- const chunks = [];
1870
- for (const part of content) {
1871
- const text = part?.text;
1872
- if (typeof text === "string") chunks.push(text);
1873
- }
1874
- return chunks.join("\n");
1875
- }
1876
- /** Child session id of one `subagent` call: the exact `metadata.sessionID`
1877
- * first, then an `output`/`result` id, then the `<subagent sessionID="…">` tag
1878
- * in the result text. Null when the call has not produced a child yet. */
1879
- function subagentSessionID(state) {
1880
- const direct = [
1881
- state?.metadata?.sessionID,
1882
- state?.output?.sessionID,
1883
- state?.result?.sessionID
1884
- ];
1885
- for (const candidate of direct) if (typeof candidate === "string" && candidate !== "") return candidate;
1886
- return SUBAGENT_SESSION_PATTERN.exec(toolContentText(state?.content))?.[1] ?? null;
1887
- }
1888
- /** Correlate the parent transcript's `subagent` calls with the children they
1889
- * spawned: child session id → `{ agent, description, background }`. One pass
1890
- * over the list the sidebar already holds — no request, no `message.sync` on
1891
- * the child. `streaming`/`pending` states carry their input as *partial JSON
1892
- * text*, so they are skipped rather than parsed. Fail-open: a malformed part
1893
- * contributes nothing. Pure. */
1894
- function collectSubagentCalls(messages) {
1895
- const calls = /* @__PURE__ */ new Map();
1896
- if (!Array.isArray(messages)) return calls;
1897
- for (const message of messages) {
1898
- if (message?.type !== "assistant" || !Array.isArray(message.content)) continue;
1899
- for (const part of message.content) {
1900
- if (part?.type !== "tool" || part?.name !== SUBAGENT_TOOL) continue;
1901
- const state = part.state;
1902
- if (state === null || typeof state !== "object") continue;
1903
- if (state.status === "streaming" || state.status === "pending") continue;
1904
- const sessionID = subagentSessionID(state);
1905
- if (!isValidSessionID(sessionID)) continue;
1906
- const input = state.input !== null && typeof state.input === "object" ? state.input : {};
1907
- const agent = typeof input.agent === "string" ? input.agent : "";
1908
- const description = typeof input.description === "string" ? input.description : "";
1909
- calls.set(sessionID, {
1910
- sessionID,
1911
- agent,
1912
- description,
1913
- background: input.background === true
1914
- });
1915
- }
1916
- }
1917
- return calls;
1918
- }
1919
- /** Grace window for a child that has not started yet. V2's `session.status()`
1920
- * returns `idle` both for "created but not started" and for "finished", so an
1921
- * idle/unknown/absent child whose own last activity (`time.updated`, falling
1922
- * back to `time.created`) is this recent still reads as running — otherwise a
1923
- * just-spawned child renders a premature ✓. Trade-off (V1 parity: it had the
1924
- * same window for its absent statuses): a child that finished within the window
1925
- * and reports no `outcome` reads as running until the window closes, at which
1926
- * point it turns terminal and its completion toast fires. A child that reports
1927
- * a terminal `outcome` is never held back by the window. */
1928
- const DELEGATION_CHILD_STATUS_GRACE_MS = 6e4;
1929
- /** One delegated child job as the sidebar renders it. */
1930
- /** Map the host's live session status to a display state. V2 exposes only
1931
- * `"idle" | "running"` through the TUI context (the client union adds `retry`
1932
- * and `busy`); `error`/`failed` are handled defensively for host drift.
1933
- * `idle`, `retry` and unknown/absent statuses are terminal only once the
1934
- * child's own activity is older than the grace window — within it the child
1935
- * reads as running (see `DELEGATION_CHILD_STATUS_GRACE_MS`). An interruption is
1936
- * not part of this union: it arrives as a terminal `outcome`. Pure. */
1937
- function delegationStateFromStatus(status, time, now = Date.now(), graceMs = DELEGATION_CHILD_STATUS_GRACE_MS) {
1938
- switch (status) {
1939
- case "running":
1940
- case "busy": return "running";
1941
- case "error":
1942
- case "failed": return "failed";
1943
- default: {
1944
- const lastActivity = Math.max(time?.updated ?? 0, time?.created ?? 0);
1945
- if (lastActivity > 0 && now - lastActivity < graceMs) return "running";
1946
- return "completed";
1947
- }
1948
- }
1949
- }
1950
- /** Map a V2 child `outcome` to a display state. `interrupted` (user abort,
1951
- * shutdown, superseded, inactivity) is distinct from both success and failure,
1952
- * so an aborted child never renders the ✓ of a completed one. Returns null for
1953
- * an absent/unrecognised outcome so the live status decides. Pure. */
1954
- function delegationStateFromOutcome(outcome) {
1955
- switch (outcome) {
1956
- case "succeeded": return "completed";
1957
- case "failed": return "failed";
1958
- case "interrupted": return "interrupted";
1959
- default: return null;
1960
- }
1961
- }
1962
- /** Build a delegation row from a child session + its live status, plus the
1963
- * `subagent` call that spawned it (when the parent transcript had one). A
1964
- * terminal `outcome` wins when present (the only V2 primitive that surfaces a
1965
- * delegation failure/interruption once the status is back to idle); otherwise
1966
- * the live status decides, with the absent/idle grace window applied. The
1967
- * `call` only ever *adds* the purpose and the background flag — an absent one
1968
- * leaves the row fully renderable. Pure. */
1969
- function toDelegationView(child, status, now = Date.now(), call) {
1970
- const id = typeof child?.id === "string" ? child.id : "";
1971
- const title = typeof child?.title === "string" && child.title !== "" ? child.title : "";
1972
- const agent = typeof child?.agent === "string" && child.agent !== "" ? child.agent : "";
1973
- const label = title !== "" ? title : agent !== "" ? agent : id.slice(0, 8);
1974
- const state = delegationStateFromOutcome(child?.outcome) ?? delegationStateFromStatus(status, child?.time, now);
1975
- const classification = classifyDispatchKind(call);
1976
- return {
1977
- id,
1978
- label,
1979
- state,
1980
- startedAt: numberOrNull(child?.time?.created),
1981
- updatedAt: numberOrNull(child?.time?.updated),
1982
- agent: agent !== "" ? agent : null,
1983
- model: shortModelID(child?.model),
1984
- cost: numberOrNull(child?.cost),
1985
- kind: classification.kind,
1986
- kindOrigin: classification.origin,
1987
- background: call?.background === true
1988
- };
1989
- }
1990
- const SPINNER_FRAMES = [
1991
- "⠋",
1992
- "⠙",
1993
- "⠹",
1994
- "⠸",
1995
- "⠼",
1996
- "⠴",
1997
- "⠦",
1998
- "⠧",
1999
- "⠇",
2000
- "⠏"
2001
- ];
2002
- /** Spinner glyph for a frame counter (incremented every ~80ms while any job is
2003
- * running). Pure. */
2004
- function spinnerFrame(frame) {
2005
- const index = Math.abs(Math.floor(frame)) % SPINNER_FRAMES.length;
2006
- return SPINNER_FRAMES[index] ?? SPINNER_FRAMES[0];
2007
- }
2008
- /** Shared order: live work first, then most recent activity. One comparator for
2009
- * every consumer of the dispatch tree (sidebar block and panel list), so the
2010
- * two views can never disagree about which child comes first. Pure. */
2011
- function compareDelegations(a, b) {
2012
- const activeA = a.state === "running" ? 1 : 0;
2013
- const activeB = b.state === "running" ? 1 : 0;
2014
- if (activeA !== activeB) return activeB - activeA;
2015
- return (b.updatedAt ?? 0) - (a.updatedAt ?? 0);
2016
- }
2017
- /** Token totals published on `SessionInfo.tokens`, one entry per counter. */
2018
- /** One child of the dispatch tree: the delegation row plus the fields only the
2019
- * panel's detail view needs (`SessionInfo.title`/`parentID`/`tokens` and the
2020
- * spawning call's description). */
2021
- /** Optional inputs of `collectDispatch`: a fixed clock (tests/render ticks) and
2022
- * an already-computed `agent` map, so a caller that walked the parent
2023
- * transcript anyway never pays for a second walk. */
2024
- /** `message.list` of one session, degrades to an empty list. The host's list is
2025
- * a cached directory read, not a request. */
2026
- function readSessionMessages(context, sessionID) {
2027
- try {
2028
- const result = context?.data?.session?.message?.list?.(sessionID);
2029
- return Array.isArray(result) ? result : [];
2030
- } catch {
2031
- return [];
2032
- }
2033
- }
2034
- /** Token counters of a child, null when the host published none of them. Pure. */
2035
- function dispatchTokens(tokens) {
2036
- if (tokens === null || typeof tokens !== "object") return null;
2037
- const source = tokens;
2038
- const cache = source.cache !== null && typeof source.cache === "object" ? source.cache : {};
2039
- const totals = {
2040
- input: numberOrNull(source.input),
2041
- output: numberOrNull(source.output),
2042
- reasoning: numberOrNull(source.reasoning),
2043
- cacheRead: numberOrNull(cache.read),
2044
- cacheWrite: numberOrNull(cache.write)
2045
- };
2046
- return [
2047
- totals.input,
2048
- totals.output,
2049
- totals.reasoning,
2050
- totals.cacheRead,
2051
- totals.cacheWrite
2052
- ].every((value) => value === null) ? null : totals;
2053
- }
2054
- /** One child `SessionInfo` + its live status → `DispatchEntry`. The call only
2055
- * ever adds the kind and the description; an absent one leaves the entry fully
2056
- * renderable. Pure. */
2057
- function toDispatchEntry(child, status, now = Date.now(), call) {
2058
- const title = typeof child?.title === "string" && child.title !== "" ? child.title : null;
2059
- const parentID = typeof child?.parentID === "string" && child.parentID !== "" ? child.parentID : null;
2060
- const description = typeof call?.description === "string" && call.description !== "" ? call.description : null;
2061
- return {
2062
- view: toDelegationView(child, status, now, call),
2063
- title,
2064
- description,
2065
- parentID,
2066
- tokens: dispatchTokens(child?.tokens)
2067
- };
2068
- }
2069
- /** The delegation tree of `sessionID` — every child `session.family` returns,
2070
- * root excluded, each enriched from `session.get`/`session.status` and the
2071
- * parent's `subagent` calls. Empty when the family API is unavailable or the
2072
- * session id is not a real handle (never falls back to the root). Ordered by
2073
- * the shared `compareDelegations`, so callers render the same list in the same
2074
- * order. A family that repeats an id yields one row per child: the id is
2075
- * deduplicated before the walk, so a duplicate can never double a row or its
2076
- * cost. */
2077
- function collectDispatch(context, sessionID, options = {}) {
2078
- if (!isValidSessionID(sessionID)) return [];
2079
- let family = [];
2080
- try {
2081
- const result = context?.data?.session?.family?.(sessionID);
2082
- if (Array.isArray(result)) family = result;
2083
- } catch {
2084
- return [];
2085
- }
2086
- const now = numberOrNull(options.now) ?? Date.now();
2087
- const calls = options.calls ?? collectSubagentCalls(readSessionMessages(context, sessionID));
2088
- const entries = [];
2089
- const seen = /* @__PURE__ */ new Set();
2090
- for (const childID of family) {
2091
- if (childID === sessionID || !isValidSessionID(childID)) continue;
2092
- if (seen.has(childID)) continue;
2093
- seen.add(childID);
2094
- let child;
2095
- try {
2096
- child = context.data.session.get(childID);
2097
- } catch {
2098
- continue;
2099
- }
2100
- if (!child) continue;
2101
- entries.push(toDispatchEntry(child, sessionStatusOf(context, childID), now, calls.get(childID) ?? null));
2102
- }
2103
- return entries.sort((a, b) => compareDelegations(a.view, b.view));
2104
- }
2105
- /** Sidebar blocks in render order. Spacing is derived from this list instead of
2106
- * from the view, so a hidden block can never leave an empty gap behind. */
2107
- /** One rendered block: its key, and whether a blank line precedes it. */
2108
- /** Header glyph per block — one codepoint each, rendered muted before the bold
2109
- * label. The fixed header (version/preset/session) takes none.
2110
- * Measured as one terminal cell by the host (`@opentui/core` counts
2111
- * `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), ▾ U+25BE (N),
2112
- * ◈ U+25C8 (A). `☑` U+2611 was rejected for the Todo header because it matches
2113
- * `emoji-regex` and would occupy two cells; `⌁` U+2301 (the old Dispatch glyph)
2114
- * was replaced by the host's own Notice glyph. */
2115
- const BLOCK_ICONS = {
2116
- context: "▤",
2117
- git: "◆",
2118
- todo: "▾",
2119
- dispatch: "◈"
2120
- };
2121
- /** Tag every block that has content with its spacer: never before the first
2122
- * (the view puts a single blank line after the fixed header instead), one
2123
- * blank line before every later block. A repeated key collapses instead of
2124
- * stacking spacers, so an absent optional block can never leave a double gap.
2125
- * Pure. */
2126
- function withBlockSpacers(keys) {
2127
- const seen = /* @__PURE__ */ new Set();
2128
- const blocks = [];
2129
- for (const key of keys) {
2130
- if (seen.has(key)) continue;
2131
- seen.add(key);
2132
- blocks.push({
2133
- key,
2134
- spacer: blocks.length > 0
2135
- });
2136
- }
2137
- return blocks;
2138
- }
2139
- /** Live children rendered one row each; the rest collapse into `… +N rodando`. */
2140
- const DISPATCH_RUNNING_CEILING = 3;
2141
- /** Agent rollup rows rendered before the `… +K $<soma>` line. */
2142
- const DISPATCH_AGENT_CEILING = 3;
2143
- /** Hard cap on the block's rendered rows, header included. The sidebar is
2144
- * short; live work is served first, then the finished rollup. */
2145
- const DISPATCH_MAX_LINES = 8;
2146
- /** Marker of the aggregated "finished" section. */
2147
- const DISPATCH_DONE_MARKER = "✓";
2148
- /** Column width of the agent (or of its title/id fallback). */
2149
- const DISPATCH_AGENT_WIDTH = 12;
2150
- /** Narrowest agent column a row may fall back to before the cost is kept whole
2151
- * and the label truncates further. */
2152
- const DISPATCH_MIN_AGENT_WIDTH = 8;
2153
- /** Column width of the short model id — the model is dropped before the agent
2154
- * or the cost so a row always fits. */
2155
- const DISPATCH_MODEL_WIDTH = 7;
2156
- /** Column width of the per-dispatch cost (`$0.04`; a sub-cent cost widens it). */
2157
- const DISPATCH_COST_WIDTH = 5;
2158
- /** Column width of the duration (`12.7s` / `1m04s` / `820ms`). */
2159
- const DISPATCH_DURATION_WIDTH = 5;
2160
- /** Column width of the `×<count>` cell of an agent rollup row. */
2161
- const DISPATCH_COUNT_WIDTH = 3;
2162
- /** Column width of an agent rollup cost (`$0.0051` still fits). */
2163
- const DISPATCH_GROUP_COST_WIDTH = 7;
2164
- /** Hard column budget for one row — a Dispatch line never wraps:
2165
- * marker(2) + agent(12) + model(7) + cost(5) + duration(5) + 3 spaces = 34.
2166
- * The kind suffix (`·disc`, `·disc~`) is wider evidence than the model, so a
2167
- * classified row spends the model's columns first: marker(2) + agent(≤12) +
2168
- * suffix(≤6) + cost(5) + duration(5) + 2 spaces ≤ 32, still inside 34. */
2169
- const DISPATCH_MAX_WIDTH = 34;
2170
- /** Middle dot used between a label and its kind (`apollo·disc`). */
2171
- const DISPATCH_KIND_SEPARATOR = "·";
2172
- /** Background marker: the parent asked the child to run in the background. */
2173
- const DISPATCH_BACKGROUND_MARKER = "~";
2174
- /** Kind suffix glued to a row's label: `·disc`, `·disc~` for a background run,
2175
- * and empty when the child could not be classified (the row then reads exactly
2176
- * as before). Pure. */
2177
- function dispatchKindSuffix(kind, background) {
2178
- if (kind === null || kind === void 0) return "";
2179
- const text = `${DISPATCH_KIND_SEPARATOR}${kind}`;
2180
- return background === true ? `${text}${DISPATCH_BACKGROUND_MARKER}` : text;
2181
- }
2182
- /** Header summary: `2 rodando · $3.49`. The live count is omitted when nothing
2183
- * runs, and the total spend is always printed (the header only renders while
2184
- * the tree has children, so `$0.00` is a real answer). Pure. */
2185
- function dispatchHeaderSummary(running, cost) {
2186
- const parts = [];
2187
- const live = numberOrNull(running) ?? 0;
2188
- if (live > 0) parts.push(`${Math.round(live)} rodando`);
2189
- const formatted = formatSpendUSD(numberOrNull(cost) ?? 0);
2190
- if (formatted !== null) parts.push(formatted);
2191
- return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR);
2192
- }
2193
- /** Compact duration without an internal space: `820` → `820ms`, `12_400` →
2194
- * `12.4s`, `64_000` → `1m04s`, `3_780_000` → `1h03m`, `172_800_000` → `2d`.
2195
- * An absent or negative value renders an em dash, never `NaN`s. Pure. */
2196
- function formatDispatchDuration(ms) {
2197
- const value = numberOrNull(ms);
2198
- if (value === null || value < 0) return "—";
2199
- if (value < 1e3) return `${Math.round(value)}ms`;
2200
- const seconds = value / 1e3;
2201
- if (seconds < 59.95) return `${seconds.toFixed(1)}s`;
2202
- const total = Math.round(seconds);
2203
- const hours = Math.floor(total / 3600);
2204
- const minutes = Math.floor(total % 3600 / 60);
2205
- if (hours >= 24) return `${Math.floor(hours / 24)}d`;
2206
- if (hours > 0) return `${hours}h${String(minutes).padStart(2, "0")}m`;
2207
- return `${minutes}m${String(total % 60).padStart(2, "0")}s`;
2208
- }
2209
- /** Elapsed label for one row: a live child measures `now - created`, a finished
2210
- * one freezes at `updated - created` (em dash when a timestamp is missing).
2211
- * Pure. */
2212
- function dispatchElapsed(view, now = Date.now()) {
2213
- if (view.startedAt === null) return "—";
2214
- if (view.state === "running") return formatDispatchDuration(now - view.startedAt);
2215
- if (view.updatedAt === null) return "—";
2216
- return formatDispatchDuration(view.updatedAt - view.startedAt);
2217
- }
2218
- /** Name column: the agent when the host published one, else the child title,
2219
- * else the short id — never `undefined`. Truncated to the column width. Pure. */
2220
- function dispatchAgentText(view, max = 12) {
2221
- const agent = typeof view.agent === "string" ? view.agent.trim() : "";
2222
- const label = typeof view.label === "string" ? view.label.trim() : "";
2223
- const id = typeof view.id === "string" ? view.id.trim() : "";
2224
- const name = agent !== "" ? agent : label !== "" ? label : id;
2225
- return name === "" ? "—" : truncateLabel(name, max);
2226
- }
2227
- /** Model column, empty when the host published none. Pure. */
2228
- function dispatchModelText(view) {
2229
- const model = typeof view.model === "string" ? view.model.trim() : "";
2230
- return model === "" ? "" : truncateLabel(model, 7);
2231
- }
2232
- /** Cost column: the child's real `SessionInfo.cost` with two decimals (up to
2233
- * four below a cent, so `$0.0031` never collapses to `$0.00`), `$0.00` for a
2234
- * zero cost, and an em dash when the host published no numeric cost. Pure. */
2235
- function formatDispatchCost(cost) {
2236
- return formatUsageCost(cost) ?? "—";
2237
- }
2238
- /** Total spend of every child (live + finished), `0` when none published a
2239
- * numeric cost. Pure. */
2240
- function dispatchTotalCost(views) {
2241
- let total = 0;
2242
- for (const view of views ?? []) {
2243
- const cost = numberOrNull(view?.cost);
2244
- if (cost !== null && cost >= 0) total += cost;
2245
- }
2246
- return total;
2247
- }
2248
- /** One live child: `⠸ <agent 12>·<kind> <custo> <duração>`, with the model as a
2249
- * fourth column only when the row still fits and the child is unclassified —
2250
- * the kind is the stronger evidence at this width, so it takes the model's
2251
- * columns. The kind rides glued to the label (never a column of its own) and
2252
- * disappears with the label's truncation; then the agent column shrinks (never
2253
- * below `DISPATCH_MIN_AGENT_WIDTH`); the cost is always present — `$0.00` for a
2254
- * zero cost, an em dash for a missing one. Pure. */
2255
- function runningChildRowText(view, now = Date.now(), frame = 0, max = 34) {
2256
- const marker = `${spinnerFrame(frame)} `;
2257
- const duration = dispatchElapsed(view, now).padStart(5);
2258
- const cost = formatDispatchCost(view.cost).padStart(5);
2259
- const model = dispatchModelText(view);
2260
- const suffix = dispatchKindSuffix(view.kind, view.background);
2261
- const limit = Math.max(1, max);
2262
- const row = (agentWidth, withModel, withSuffix = true) => {
2263
- const kind = withSuffix ? suffix : "";
2264
- const name = dispatchAgentText(view, agentWidth);
2265
- const cell = kind === "" ? name.padEnd(agentWidth) : `${name}${kind}`;
2266
- const tail = withModel ? `${model.padEnd(7)} ${cost} ${duration}` : `${cost} ${duration}`;
2267
- return `${marker}${cell} ${tail}`;
2268
- };
2269
- if (model !== "" && suffix === "") {
2270
- const withModel = row(12, true);
2271
- if (withModel.length <= limit) return withModel;
2272
- }
2273
- const full = row(12, false);
2274
- if (full.length <= limit) return full;
2275
- for (let width = 11; width >= 8; width -= 1) {
2276
- const narrowed = row(width, false);
2277
- if (narrowed.length <= limit) return narrowed;
2278
- }
2279
- if (suffix !== "") return row(8, false, false);
2280
- return row(8, false);
2281
- }
2282
- /** Sessions and spend attributed to one agent in the finished section. `kind`
2283
- * is only set when every finished session of the group agrees on it — a mixed
2284
- * group carries no single purpose, so the row omits it rather than picking one.
2285
- * `background` follows the same rule (all of them background). */
2286
- /** Rollup of the finished children by agent: `×count` sessions and the summed
2287
- * `SessionInfo.cost`. Failed and interrupted children are included (they are
2288
- * finished); running ones are not. The group's kind survives only when the
2289
- * whole group agrees, so an aggregate row never claims a purpose it cannot
2290
- * prove. Ordered by cost, then count, then name. Pure. */
2291
- function collectChildAgentUsage(views) {
2292
- const totals = /* @__PURE__ */ new Map();
2293
- for (const view of views ?? []) {
2294
- if (!view || view.state === "running") continue;
2295
- const agent = agentKey(view.agent);
2296
- const current = totals.get(agent) ?? {
2297
- agent,
2298
- count: 0,
2299
- cost: 0,
2300
- kinds: /* @__PURE__ */ new Set(),
2301
- background: true
2302
- };
2303
- current.count += 1;
2304
- current.kinds.add(view.kind ?? null);
2305
- if (view.background !== true) current.background = false;
2306
- const cost = numberOrNull(view.cost);
2307
- if (cost !== null && cost >= 0) current.cost += cost;
2308
- totals.set(agent, current);
2309
- }
2310
- return [...totals.values()].map((entry) => {
2311
- const shared = entry.kinds.size === 1 ? [...entry.kinds][0] ?? null : null;
2312
- return {
2313
- agent: entry.agent,
2314
- count: entry.count,
2315
- cost: entry.cost,
2316
- kind: shared,
2317
- background: entry.background
2318
- };
2319
- }).sort((a, b) => b.cost - a.cost || b.count - a.count || a.agent.localeCompare(b.agent));
2320
- }
2321
- /** One agent rollup row: `<agent 12> ×<count 3>·<kind> <custo 7>`. The kind is
2322
- * glued to the count (the row's only label) and omitted for a mixed group; the
2323
- * agent column shrinks (never below the minimum) before the cost, which is
2324
- * what the row is for. Pure. */
2325
- function childAgentRowText(row, max = 34) {
2326
- const suffix = dispatchKindSuffix(row?.kind, row?.background);
2327
- const count = `\u00D7${String(Math.max(0, Math.round(numberOrNull(row?.count) ?? 0))).padStart(3)}`;
2328
- const cost = formatDispatchCost(row?.cost).padStart(7);
2329
- const limit = Math.max(1, max);
2330
- const text = (agentWidth, withSuffix = true) => {
2331
- const kind = withSuffix ? suffix : "";
2332
- return `${truncateLabel(agentKey(row?.agent), agentWidth).padEnd(agentWidth)} ${count}${kind} ${cost}`;
2333
- };
2334
- const full = text(12);
2335
- if (full.length <= limit) return full;
2336
- for (let width = 11; width >= 8; width -= 1) {
2337
- const narrowed = text(width);
2338
- if (narrowed.length <= limit) return narrowed;
2339
- }
2340
- if (suffix !== "") return text(8, false);
2341
- return text(8);
2342
- }
2343
- /** The `… +K $<soma>` line for agents beyond the rollup cap. Null when every
2344
- * agent fits. Pure. */
2345
- function hiddenChildAgentsText(hidden, hiddenCost) {
2346
- const count = numberOrNull(hidden) ?? 0;
2347
- if (count <= 0) return null;
2348
- const cost = formatSpendUSD(numberOrNull(hiddenCost) ?? 0);
2349
- return cost === null ? `\u2026 +${Math.round(count)}` : `\u2026 +${Math.round(count)} ${cost}`;
2350
- }
2351
- /** Summary of the finished section: `✓ 70 · $3.40 · 9 agentes`. `· $<soma>` is
2352
- * omitted when nothing was spent and `· 1 agente` when a single agent owns
2353
- * every finished child; `✓ <total>` always prints. Null when nothing finished.
2354
- * Pure. */
2355
- function completedSummaryText(completed, cost, agents) {
2356
- const total = numberOrNull(completed) ?? 0;
2357
- if (total <= 0) return null;
2358
- const parts = [`✓ ${Math.round(total)}`];
2359
- const spend = numberOrNull(cost) ?? 0;
2360
- if (spend > 0) {
2361
- const formatted = formatSpendUSD(spend);
2362
- if (formatted !== null) parts.push(formatted);
2363
- }
2364
- const groups = Math.round(numberOrNull(agents) ?? 0);
2365
- if (groups > 1) parts.push(`${groups} agentes`);
2366
- return parts.join(SPEND_LINE_SEPARATOR);
2367
- }
2368
- /** The `· <F> falhas` suffix of the finished summary, null when nothing failed.
2369
- * Pure. */
2370
- function failedSuffixText(failures) {
2371
- const count = numberOrNull(failures) ?? 0;
2372
- if (count <= 0) return null;
2373
- const rounded = Math.round(count);
2374
- return `${rounded} ${rounded === 1 ? "falha" : "falhas"}`;
2375
- }
2376
- /** One rendered live row: its text plus the session it navigates to. */
2377
- /** Everything the `Dispatch` block renders, already joined and capped. */
2378
- /** Newest activity first, so the live rows that just moved lead the section.
2379
- * Pure. */
2380
- function lastActivity(view) {
2381
- return Math.max(numberOrNull(view?.updatedAt) ?? 0, numberOrNull(view?.startedAt) ?? 0);
2382
- }
2383
- /** Build the whole block from the child set. Null when there is no child, so
2384
- * the block (and its spacer) never renders empty. Live work is capped at
2385
- * `DISPATCH_RUNNING_CEILING` and the finished rollup at
2386
- * `DISPATCH_AGENT_CEILING`, with the rollup giving up rows first to keep the
2387
- * block inside `DISPATCH_MAX_LINES`. Pure. */
2388
- function buildDispatchBlock(views, now = Date.now(), frame = 0, max = 34) {
2389
- const list = Array.isArray(views) ? views.filter((view) => view && typeof view.id === "string") : [];
2390
- if (list.length === 0) return null;
2391
- const running = list.filter((view) => view.state === "running").sort((a, b) => lastActivity(b) - lastActivity(a));
2392
- const finished = list.filter((view) => view.state !== "running");
2393
- const groups = collectChildAgentUsage(finished);
2394
- const finishedCost = groups.reduce((sum, group) => sum + group.cost, 0);
2395
- const failures = finished.filter((view) => view.state === "failed").length;
2396
- const totalCost = dispatchTotalCost(list);
2397
- const runningSlots = Math.min(3, running.length);
2398
- const runningHidden = running.length - runningSlots;
2399
- const runningLines = running.map((view) => ({
2400
- id: view.id,
2401
- text: runningChildRowText(view, now, frame, max)
2402
- }));
2403
- const summary = completedSummaryText(finished.length, finishedCost, groups.length);
2404
- const runningRows = runningSlots + (runningHidden > 0 ? 1 : 0);
2405
- const room = Math.max(0, 7 - runningRows - (summary === null ? 0 : 1));
2406
- const wanted = Math.min(3, groups.length);
2407
- const agentSlots = groups.length > wanted ? Math.min(wanted, Math.max(0, room - 1)) : Math.min(wanted, room);
2408
- const visibleAgents = groups.slice(0, agentSlots);
2409
- const hiddenAgents = groups.slice(agentSlots);
2410
- return {
2411
- runningCount: running.length,
2412
- completedCount: finished.length,
2413
- agentCount: groups.length,
2414
- failures,
2415
- totalCost,
2416
- running: runningLines.slice(0, runningSlots),
2417
- runningHidden,
2418
- summary,
2419
- agents: visibleAgents,
2420
- agentsHidden: hiddenAgents.length,
2421
- agentsHiddenCost: hiddenAgents.reduce((sum, group) => sum + group.cost, 0)
2422
- };
2423
- }
2424
- /** Panel content name, registered by the `session.panel` claim and passed to
2425
- * `ui.panel.open`. */
2426
- const DISPATCH_PANEL_NAME = "pantheon.dispatch";
2427
- /** Toast shown when `ui.panel.open` refuses (no session route is active). The
2428
- * panel only exists inside a session, so there is no alternative route. */
2429
- const DISPATCH_PANEL_TOAST = "Abra uma sessão para ver o Dispatch";
2430
- /** Panel title marker — the same glyph the sidebar block header uses. */
2431
- const DISPATCH_PANEL_HEADER_MARKER = "◈";
2432
- /** Selected-row gutter marker (`▸`, one cell). */
2433
- const DISPATCH_PANEL_SELECTION_MARKER = "▸";
2434
- /** Cells the selection gutter occupies before a row's own text. */
2435
- const DISPATCH_PANEL_SELECTION_GUTTER = 2;
2436
- /** Column of the horizontal rule under the header. */
2437
- const DISPATCH_PANEL_RULE_CHAR = "─";
2438
- /** Em dash for any datum the host did not publish. */
2439
- const DISPATCH_PANEL_DASH = "—";
2440
- /** Body of an empty panel (the claim still renders, the list is just empty). */
2441
- const DISPATCH_PANEL_EMPTY_TEXT = "Nenhuma sessão delegada";
2442
- /** Width at or above which the list and the detail sit side by side. */
2443
- const DISPATCH_PANEL_WIDE_MIN_WIDTH = 72;
2444
- /** Rows the viewport holds; pageup/pagedown move by exactly this many rows. */
2445
- const DISPATCH_PANEL_PAGE_SIZE = 10;
2446
- /** Panel row columns: marker(2) + agent(12) + kind(4) + cost(≥7) + duration(8).
2447
- * The cost column is at least this wide; a sub-cent cost widens it per row. */
2448
- const DISPATCH_PANEL_AGENT_WIDTH = 12;
2449
- const DISPATCH_PANEL_MIN_AGENT_WIDTH = 6;
2450
- const DISPATCH_PANEL_KIND_WIDTH = 4;
2451
- const DISPATCH_PANEL_COST_WIDTH = 7;
2452
- const DISPATCH_PANEL_DURATION_WIDTH = 8;
2453
- /** Title column budget (`◈ Dispatch — <sessão>`). */
2454
- const DISPATCH_PANEL_TITLE_WIDTH = 44;
2455
- /** Badge appended to the title while the host presents the panel full screen. */
2456
- const DISPATCH_PANEL_FULLSCREEN_BADGE = "[fullscreen]";
2457
- /** Columns a row spends before the agent cell, cost column excluded
2458
- * (2 marker + 1 + 4 kind + 1 + 8 duration). The cost is measured per row
2459
- * because `<$0.0001` is one cell wider than `DISPATCH_PANEL_COST_WIDTH`. */
2460
- const DISPATCH_PANEL_ROW_FIXED_WIDTH = 16;
2461
- /** Human labels of a kind's evidence, as the detail line prints them. */
2462
- const DISPATCH_KIND_ORIGIN_LABELS = {
2463
- prefix: "prefixo",
2464
- agent: "agente",
2465
- unavailable: "indisponível"
2466
- };
2467
- /** Entries in row order: live work first, then most recent activity — the same
2468
- * comparator the sidebar block uses. Pure. */
2469
- function orderDispatchEntries(entries) {
2470
- return [...entries].sort((a, b) => compareDelegations(a.view, b.view));
2471
- }
2472
- /** `◈ Dispatch — <sessão>`, with the session title truncated (never wrapped),
2473
- * plus the `[fullscreen]` badge while the host presents the panel full screen.
2474
- * An absent title leaves the marker and the name alone. Pure. */
2475
- function dispatchPanelTitle(sessionTitle, max = 44, presentation) {
2476
- const base = `◈ Dispatch`;
2477
- const badge = presentation === "fullscreen" ? ` ${DISPATCH_PANEL_FULLSCREEN_BADGE}` : "";
2478
- const title = typeof sessionTitle === "string" ? sessionTitle.trim() : "";
2479
- if (title === "") return `${base}${badge}`;
2480
- return `${base} — ${truncateLabel(title, Math.max(4, max))}${badge}`;
2481
- }
2482
- /** Header counters: `2 rodando · 70 concluídos · 1 falha · $3.59`. A zero
2483
- * counter is omitted (never `0 rodando`); the total spend is printed whenever
2484
- * the tree has a child, because `$0.00` is then a real answer. Null for an
2485
- * empty tree, so the header renders no counter line at all. Pure. */
2486
- function dispatchPanelHeader(entries) {
2487
- const list = Array.isArray(entries) ? entries.filter((entry) => entry?.view) : [];
2488
- if (list.length === 0) return null;
2489
- let running = 0;
2490
- let completed = 0;
2491
- let failed = 0;
2492
- for (const entry of list) switch (entry.view.state) {
2493
- case "running":
2494
- running += 1;
2495
- break;
2496
- case "completed":
2497
- completed += 1;
2498
- break;
2499
- case "failed": failed += 1;
2500
- }
2501
- const parts = [];
2502
- if (running > 0) parts.push(`${running} rodando`);
2503
- if (completed > 0) parts.push(`${completed} ${completed === 1 ? "concluído" : "concluídos"}`);
2504
- if (failed > 0) parts.push(`${failed} ${failed === 1 ? "falha" : "falhas"}`);
2505
- const cost = formatSpendUSD(dispatchTotalCost(list.map((entry) => entry.view)));
2506
- if (cost !== null) parts.push(cost);
2507
- return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR);
2508
- }
2509
- /** Horizontal rule under the header, clamped to the panel's own width. Pure. */
2510
- function dispatchPanelRule(width, max = 200) {
2511
- const columns = Math.max(0, Math.min(max, Math.floor(numberOrNull(width) ?? 0)));
2512
- return "─".repeat(columns);
2513
- }
2514
- /** Row marker: animated spinner while running, `✓` done, `✗` failed, `○`
2515
- * cancelled/interrupted, `?` for a state the host never publishes. Every glyph
2516
- * is one cell wide and `?` is the only fallback, so an unknown state is visible
2517
- * instead of silently rendering as success. Pure. */
2518
- function dispatchPanelMarker(state, frame = 0) {
2519
- switch (state) {
2520
- case "running": return `${spinnerFrame(frame)} `;
2521
- case "completed": return "✓ ";
2522
- case "failed": return "✗ ";
2523
- case "interrupted": return "○ ";
2524
- default: return "? ";
2525
- }
2526
- }
2527
- /** One padded, truncated cell: an absent/blank value becomes the em dash, and
2528
- * the value is cut to the cell's own width (never to the line's length, so one
2529
- * long cell cannot squeeze its neighbours out of alignment). Pure. */
2530
- function dispatchPanelCell(value, width) {
2531
- const cells = Math.max(1, Math.floor(numberOrNull(width) ?? 1));
2532
- const text = typeof value === "string" ? value.trim() : "";
2533
- return padCell(text === "" ? "—" : text, cells);
2534
- }
2535
- /** One list row: `⠋ prometheus plan $0.09 14m34s`. The agent cell absorbs
2536
- * the width difference (down to `DISPATCH_PANEL_MIN_AGENT_WIDTH`), so a narrow
2537
- * panel truncates the label rather than the numbers; the cost column grows by
2538
- * itself for a sub-cent value so the row never spends more than its budget.
2539
- * Pure. */
2540
- function dispatchPanelRowText(entry, options = {}) {
2541
- const view = entry?.view;
2542
- if (!view) return "";
2543
- const now = numberOrNull(options.now) ?? Date.now();
2544
- const frame = numberOrNull(options.frame) ?? 0;
2545
- const width = Math.floor(numberOrNull(options.max) ?? 35);
2546
- const costText = formatDispatchCost(view.cost);
2547
- const costWidth = Math.max(7, cellWidth(costText));
2548
- const agentWidth = Math.max(6, Math.min(12, width - (DISPATCH_PANEL_ROW_FIXED_WIDTH + costWidth)));
2549
- return `${dispatchPanelMarker(view.state, frame)}${dispatchPanelCell(dispatchAgentText(view, 12), agentWidth)} ${dispatchPanelCell(view.kind, 4)} ${costText.padStart(costWidth)}${truncateLabel(dispatchElapsed(view, now), 8).padStart(8)}`;
2550
- }
2551
- /** `ses_ab12cd`, short enough for a detail line. Full id when it already fits. */
2552
- function shortSessionID(id, max = 10) {
2553
- const text = typeof id === "string" ? id.trim() : "";
2554
- if (text === "") return "—";
2555
- return text.length <= max ? text : `${text.slice(0, Math.max(1, max - 1))}\u2026`;
2556
- }
2557
- /** Token counters of one child on a single line (`in 1.2K · out 430 · r 120 ·
2558
- * cache 8K/1K`), or `tokens —` when the host published none. Pure. */
2559
- function dispatchTokenLine(tokens) {
2560
- if (!tokens) return `tokens —`;
2561
- const value = (token) => token === null ? "—" : formatContextWindow(token) ?? String(token);
2562
- return [
2563
- `in ${value(tokens.input)}`,
2564
- `out ${value(tokens.output)}`,
2565
- `r ${value(tokens.reasoning)}`,
2566
- `cache ${value(tokens.cacheRead)}/${value(tokens.cacheWrite)}`
2567
- ].join(SPEND_LINE_SEPARATOR);
2568
- }
2569
- /** Detail lines of the selected child: heading (title, else the spawning
2570
- * description, else the row label), short id + model, token counters, and the
2571
- * kind plus its evidence and the parent id. Two to four lines; `expanded:
2572
- * false` keeps only the heading. Every missing datum prints `—`. Pure. */
2573
- function dispatchPanelDetail(entry, options = {}) {
2574
- if (!entry?.view) return ["—"];
2575
- const max = Math.max(8, Math.floor(numberOrNull(options.max) ?? 60));
2576
- const view = entry.view;
2577
- const lines = [truncateLabel(entry.title ?? entry.description ?? (typeof view.label === "string" && view.label !== "" ? view.label : null) ?? view.id, max)];
2578
- if (options.expanded === false) return lines;
2579
- lines.push(truncateLabel(`${shortSessionID(view.id)}${SPEND_LINE_SEPARATOR}${view.model ?? "—"}`, max));
2580
- lines.push(truncateLabel(dispatchTokenLine(entry.tokens), max));
2581
- const origin = DISPATCH_KIND_ORIGIN_LABELS[view.kindOrigin] ?? DISPATCH_KIND_ORIGIN_LABELS.unavailable;
2582
- lines.push(truncateLabel(`kind ${view.kind ?? "—"} (${origin})${SPEND_LINE_SEPARATOR}parent ${entry.parentID ?? "—"}`, max));
2583
- return lines;
2584
- }
2585
- /** Panel geometry for its input width: wide (≥72) puts the detail in a second
2586
- * column, narrow stacks it under the list. `rowWidth` is what a list row may
2587
- * spend after the selection gutter. Pure. */
2588
- function dispatchPanelLayout(width) {
2589
- const columns = Math.max(20, Math.floor(numberOrNull(width) ?? 0));
2590
- if (columns >= 72) {
2591
- const listWidth = Math.max(40, Math.min(64, columns - 26));
2592
- return {
2593
- mode: "wide",
2594
- listWidth,
2595
- detailWidth: Math.max(24, columns - listWidth - 2),
2596
- rowWidth: listWidth - 2
2597
- };
2598
- }
2599
- return {
2600
- mode: "narrow",
2601
- listWidth: columns,
2602
- detailWidth: columns,
2603
- rowWidth: columns - 2
2604
- };
2605
- }
2606
- /** Viewport of the list: the page holding the selection, scrolled so the
2607
- * selected row stays visible with its predecessors. Bounded, so a 71-child
2608
- * tree renders ten rows, never all of them. Pure. */
2609
- function dispatchPanelWindow(total, selectedIndex, pageSize = 10) {
2610
- const count = Math.max(0, Math.floor(numberOrNull(total) ?? 0));
2611
- const size = Math.max(1, Math.floor(numberOrNull(pageSize) ?? 10));
2612
- if (count === 0) return {
2613
- start: 0,
2614
- end: 0,
2615
- size
2616
- };
2617
- const index = Math.min(count - 1, Math.max(0, Math.floor(numberOrNull(selectedIndex) ?? 0)));
2618
- const start = Math.min(Math.max(0, index - size + 1), Math.max(0, count - size));
2619
- return {
2620
- start,
2621
- end: Math.min(count, start + size),
2622
- size
2623
- };
2624
- }
2625
- /** `1-10 de 71` while the list is longer than one page; null when everything
2626
- * fits (and for an empty list), so the footer never pads itself. Pure. */
2627
- function dispatchPanelRangeText(start, end, total) {
2628
- const count = Math.max(0, Math.floor(numberOrNull(total) ?? 0));
2629
- const first = Math.max(0, Math.floor(numberOrNull(start) ?? 0));
2630
- const last = Math.min(count, Math.floor(numberOrNull(end) ?? 0));
2631
- if (count === 0 || first === 0 && last >= count) return null;
2632
- return `${first + 1}-${last} de ${count}`;
2633
- }
2634
- /** One rendered list row, selection resolved by the view against the model's
2635
- * selected id. */
2636
- /** Every entry as a row, ordered by the shared comparator. Pure. */
2637
- function dispatchPanelRows(entries, options = {}) {
2638
- return orderDispatchEntries(Array.isArray(entries) ? entries.filter((entry) => entry?.view && typeof entry.view.id === "string") : []).map((entry) => ({
2639
- id: entry.view.id,
2640
- state: entry.view.state,
2641
- text: dispatchPanelRowText(entry, options)
2642
- }));
2643
- }
2644
- /** Panel action, one per command. */
2645
- /** One namespaced command: stable id, explicit binding, and the action it runs. */
2646
- /** The panel's whole keymap, in table order. `bind` is explicit for every
2647
- * command (no auto-binding), and every id is namespaced, so a `k`/`q`/`f`
2648
- * binding can never collide with the host's own keys. */
2649
- const DISPATCH_PANEL_COMMANDS = [
2650
- {
2651
- action: "up",
2652
- id: "pantheon.dispatch.up",
2653
- title: "Dispatch: selecionar anterior",
2654
- bind: "k,up"
2655
- },
2656
- {
2657
- action: "down",
2658
- id: "pantheon.dispatch.down",
2659
- title: "Dispatch: selecionar próxima",
2660
- bind: "j,down"
2661
- },
2662
- {
2663
- action: "home",
2664
- id: "pantheon.dispatch.home",
2665
- title: "Dispatch: primeira",
2666
- bind: "home"
2667
- },
2668
- {
2669
- action: "end",
2670
- id: "pantheon.dispatch.end",
2671
- title: "Dispatch: última",
2672
- bind: "end"
2673
- },
2674
- {
2675
- action: "pageup",
2676
- id: "pantheon.dispatch.pageup",
2677
- title: "Dispatch: página acima",
2678
- bind: "pageup"
2679
- },
2680
- {
2681
- action: "pagedown",
2682
- id: "pantheon.dispatch.pagedown",
2683
- title: "Dispatch: página abaixo",
2684
- bind: "pagedown"
2685
- },
2686
- {
2687
- action: "toggle",
2688
- id: "pantheon.dispatch.toggle",
2689
- title: "Dispatch: expandir detalhe",
2690
- bind: "enter"
2691
- },
2692
- {
2693
- action: "fullscreen",
2694
- id: "pantheon.dispatch.fullscreen",
2695
- title: "Dispatch: tela cheia",
2696
- bind: "f"
2697
- },
2698
- {
2699
- action: "close",
2700
- id: "pantheon.dispatch.close",
2701
- title: "Dispatch: fechar",
2702
- bind: "escape,q"
2703
- }
2704
- ];
2705
- /** Run one action against the model and the host-owned panel input. Kept apart
2706
- * from the keymap so the whole command surface is testable without a renderer.
2707
- */
2708
- function performDispatchPanelAction(action, model, panel) {
2709
- switch (action) {
2710
- case "up":
2711
- model.move(-1);
2712
- return;
2713
- case "down":
2714
- model.move(1);
2715
- return;
2716
- case "home":
2717
- model.first();
2718
- return;
2719
- case "end":
2720
- model.last();
2721
- return;
2722
- case "pageup":
2723
- model.pageUp();
2724
- return;
2725
- case "pagedown":
2726
- model.pageDown();
2727
- return;
2728
- case "toggle":
2729
- model.toggle();
2730
- return;
2731
- case "fullscreen":
2732
- panel.toggleFullscreen();
2733
- return;
2734
- case "close":
2735
- panel.close();
2736
- return;
2737
- default: return;
2738
- }
2739
- }
2740
- /** Footer: the keys the host reports for each command (`keymap.shortcuts`) with
2741
- * an em dash whenever a command has no binding, so the hint can never advertise
2742
- * a key that does nothing. Pure. */
2743
- function dispatchPanelFooter(shortcutsOf) {
2744
- const keys = (id) => {
2745
- let list = [];
2746
- try {
2747
- const result = shortcutsOf(id);
2748
- list = Array.isArray(result) ? result : [];
2749
- } catch {
2750
- list = [];
2751
- }
2752
- const text = list.map((key) => String(key ?? "").trim()).filter((key) => key !== "").join("/");
2753
- return text === "" ? "—" : text;
2754
- };
2755
- return [
2756
- `${keys("pantheon.dispatch.up")} ${keys("pantheon.dispatch.down")} mover`,
2757
- `${keys("pantheon.dispatch.toggle")} detalhe`,
2758
- `${keys("pantheon.dispatch.fullscreen")} fullscreen`,
2759
- `${keys("pantheon.dispatch.close")} fechar`
2760
- ].join(SPEND_LINE_SEPARATOR);
2761
- }
2762
- /** The subset of `PanelInput` the model reads, so tests can drive it with a
2763
- * plain object. */
2764
- /** `keymap.shortcuts` of one command; empty when the keymap is unavailable. */
2765
- function keymapShortcuts(context, id) {
2766
- try {
2767
- const list = context?.keymap?.shortcuts?.(id);
2768
- return Array.isArray(list) ? list : [];
2769
- } catch {
2770
- return [];
2771
- }
2772
- }
2773
- /** Open the panel from the command palette / slash command. `ui.panel.open`
2774
- * only accepts a `session` route, so a refusal (no session open) is answered
2775
- * with a toast — never a fallback route, never a silent no-op. Returns whether
2776
- * the panel opened. */
2777
- function openDispatchPanel(context) {
2778
- let opened = false;
2779
- try {
2780
- opened = context?.ui?.panel?.open?.(DISPATCH_PANEL_NAME) === true;
2781
- } catch {
2782
- opened = false;
2783
- }
2784
- if (opened) return true;
2785
- try {
2786
- context?.ui?.toast?.show?.({
2787
- message: DISPATCH_PANEL_TOAST,
2788
- variant: "warning"
2789
- });
2790
- } catch {}
2791
- return false;
2792
- }
2793
- /** Reactive state the panel view renders. Selection is held by session id, so
2794
- * it survives list updates; the index is derived (and falls back to the first
2795
- * row when the selected child disappears). */
2796
- /** Model behind the panel. Mounted only while the panel claim renders (the
2797
- * `Show` in `session.panel`), so the 80 ms tick it arms exists exactly while
2798
- * the panel is open; it also stops on `isOpen()` going false and on dispose.
2799
- * It performs no `message.sync`, writes no `session.metadata` and makes no
2800
- * request: `collectDispatch` reads only host-cached state. */
2801
- function createDispatchPanelModel(context, panel) {
2802
- const [revision, setRevision] = createSignal(0);
2803
- const [frame, setFrame] = createSignal(0);
2804
- const [expanded, setExpanded] = createSignal(true);
2805
- const [selectedID, setSelectedID] = createSignal(null);
2806
- const isOpen = () => panel().name === DISPATCH_PANEL_NAME;
2807
- const activeSessionID = () => {
2808
- const id = panel().sessionID;
2809
- return isValidSessionID(id) ? id : "";
2810
- };
2811
- const entries = createMemo(() => {
2812
- revision();
2813
- if (!isOpen()) return [];
2814
- return collectDispatch(context, activeSessionID());
2815
- });
2816
- const layout = createMemo(() => dispatchPanelLayout(panel().width));
2817
- const rows = createMemo(() => {
2818
- const mode = layout();
2819
- return dispatchPanelRows(entries(), {
2820
- now: Date.now(),
2821
- frame: frame(),
2822
- max: mode.rowWidth
2823
- });
2824
- });
2825
- const selectedIndex = createMemo(() => {
2826
- const list = rows();
2827
- if (list.length === 0) return 0;
2828
- const id = selectedID();
2829
- if (id === null) return 0;
2830
- const index = list.findIndex((row) => row.id === id);
2831
- return index === -1 ? 0 : index;
2832
- });
2833
- const selectedIDAccessor = createMemo(() => rows()[selectedIndex()]?.id ?? null);
2834
- const selectedEntry = createMemo(() => entries()[selectedIndex()] ?? null);
2835
- const session = createMemo(() => {
2836
- revision();
2837
- const id = activeSessionID();
2838
- if (id === "") return void 0;
2839
- try {
2840
- return context.data.session.get(id);
2841
- } catch {
2842
- return;
2843
- }
2844
- });
2845
- const title = createMemo(() => dispatchPanelTitle(session()?.title, 44, panel().presentation));
2846
- const header = createMemo(() => dispatchPanelHeader(entries()));
2847
- const detail = createMemo(() => dispatchPanelDetail(selectedEntry(), {
2848
- expanded: expanded(),
2849
- max: layout().detailWidth
2850
- }));
2851
- const visible = createMemo(() => {
2852
- const list = rows();
2853
- const window = dispatchPanelWindow(list.length, selectedIndex());
2854
- return {
2855
- start: window.start,
2856
- rows: list.slice(window.start, window.end)
2857
- };
2858
- });
2859
- const hasRunning = createMemo(() => rows().some((row) => row.state === "running"));
2860
- const footer = createMemo(() => {
2861
- const list = rows();
2862
- const window = dispatchPanelWindow(list.length, selectedIndex());
2863
- const range = dispatchPanelRangeText(window.start, window.end, list.length);
2864
- const hints = dispatchPanelFooter((id) => keymapShortcuts(context, id));
2865
- return range === null ? hints : `${range}${SPEND_LINE_SEPARATOR}${hints}`;
2866
- });
2867
- const select = (index) => {
2868
- const list = rows();
2869
- if (list.length === 0) return;
2870
- const clamped = Math.min(list.length - 1, Math.max(0, Math.round(index)));
2871
- setSelectedID(list[clamped]?.id ?? null);
2872
- };
2873
- onMount(() => {
2874
- onCleanup(subscribeSidebarRefresh(context, () => setRevision((value) => value + 1)));
2875
- });
2876
- createEffect(() => {
2877
- if (!isOpen() || !hasRunning()) return;
2878
- const spinner = setInterval(() => setFrame((value) => value + 1), SPINNER_INTERVAL_MS);
2879
- onCleanup(() => clearInterval(spinner));
2880
- });
2881
- return {
2882
- entries,
2883
- rows,
2884
- title,
2885
- header,
2886
- detail,
2887
- layout,
2888
- visible,
2889
- selectedID: selectedIDAccessor,
2890
- selectedIndex,
2891
- expanded,
2892
- hasRunning,
2893
- frame,
2894
- footer,
2895
- move: (delta) => select(selectedIndex() + (numberOrNull(delta) ?? 0)),
2896
- first: () => select(0),
2897
- last: () => select(rows().length - 1),
2898
- pageUp: () => select(selectedIndex() - 10),
2899
- pageDown: () => select(selectedIndex() + 10),
2900
- toggle: () => setExpanded((value) => !value)
2901
- };
2902
- }
2903
- /** Session ids to eagerly sync at load (deduped, bounded). Pure. */
2904
- function collectWarmupTargets(sessions, limit = WARMUP_SESSION_LIMIT) {
2905
- const ids = [];
2906
- for (const session of sessions) {
2907
- if (!isValidSessionID(session?.id) || ids.includes(session.id)) continue;
2908
- ids.push(session.id);
2909
- if (ids.length >= limit) break;
2910
- }
2911
- return ids;
2912
- }
2913
- /** Body a sidebar instance renders when the host has not published a real
2914
- * session id yet. OpenCode V2 scopes the `sidebar.content` slot to a session
2915
- * (`SlotMap["sidebar.content"] = { sessionID: string }`), so before the first
2916
- * prompt the slot may not mount at all — see the `home.footer.status`
2917
- * contribution for the pre-prompt degradation. Pure. */
2918
- function sidebarPlaceholder(sessionID) {
2919
- return isValidSessionID(sessionID) ? null : SIDEBAR_WAITING_LABEL;
2920
- }
2921
- /** Navigate to a session through the V2 router. Fail-open: an absent router or
2922
- * a removed session must never break the sidebar. Returns whether a valid
2923
- * navigation was dispatched. Pure. */
2924
- function navigateToSession(router, sessionID) {
2925
- if (typeof router?.navigate !== "function" || !isValidSessionID(sessionID)) return false;
2926
- try {
2927
- router.navigate({
2928
- type: "session",
2929
- sessionID
2930
- });
2931
- return true;
2932
- } catch {
2933
- return false;
2934
- }
2935
- }
2936
- /** Diff two delegation observations: entries that were `running` and are no
2937
- * longer running count as completions, fired once per transition. Returns the
2938
- * next snapshot so callers can keep a single tracker. First observation never
2939
- * reports a completion (no toast spam on mount). Pure. */
2940
- function detectDelegationCompletions(previous, current) {
2941
- const snapshot = /* @__PURE__ */ new Map();
2942
- const completed = [];
2943
- for (const entry of current) {
2944
- snapshot.set(entry.id, entry.state);
2945
- if (previous.get(entry.id) === "running" && entry.state !== "running") completed.push(entry);
2946
- }
2947
- return {
2948
- completed,
2949
- snapshot
2950
- };
2951
- }
2952
- function resolveLocation(context) {
2953
- try {
2954
- return context?.location ?? context?.data?.location?.default();
2955
- } catch {
2956
- return;
2957
- }
2958
- }
2959
- function resolveSidebarCwd(context) {
2960
- const location = resolveLocation(context);
2961
- if (location && typeof location.directory === "string" && location.directory !== "") return location.directory;
2962
- return process.cwd();
2963
- }
2964
- function sessionStatusOf(context, sessionID) {
2965
- try {
2966
- const status = context?.data?.session?.status?.(sessionID);
2967
- return typeof status === "string" ? status : void 0;
2968
- } catch {
2969
- return;
2970
- }
2971
- }
2972
- /** Subscribe `refresh` to every V2 event that can change sidebar state. Returns
2973
- * a disposer that releases exactly the subscriptions the host handed out. The
2974
- * event names come from the V2 union; the cast turns an unknown name into a
2975
- * compile error instead of a silent no-op subscription. */
2976
- function subscribeSidebarRefresh(context, refresh) {
2977
- const stop = [];
2978
- const data = context?.data;
2979
- if (typeof data?.on === "function") for (const type of SIDEBAR_REFRESH_EVENTS) try {
2980
- const unsubscribe = data.on(type, refresh);
2981
- if (typeof unsubscribe === "function") stop.push(unsubscribe);
2982
- } catch {}
2983
- return () => {
2984
- for (const unsubscribe of stop) if (typeof unsubscribe === "function") unsubscribe();
2985
- };
2986
- }
2987
- /** Populate the cached data at load so the sidebar has content before the first
2988
- * prompt (Known Issue guard). Fire-and-forget: a missing API or a failed sync
2989
- * degrades silently and the sidebar still renders its static header. */
2990
- function warmUpSidebarData(context, location) {
2991
- try {
2992
- Promise.resolve(context?.data?.location?.vcs?.sync?.(location)).catch(() => {});
2993
- } catch {}
2994
- let listed = [];
2995
- try {
2996
- const result = context?.data?.session?.list?.();
2997
- if (Array.isArray(result)) listed = result;
2998
- } catch {}
2999
- for (const id of collectWarmupTargets(listed)) try {
3000
- Promise.resolve(context?.data?.session?.sync?.(id)).catch(() => {});
3001
- } catch {}
3002
- }
3003
- function showDelegationToast(context, done) {
3004
- const variant = done.state === "failed" ? "error" : done.state === "interrupted" ? "warning" : "success";
3005
- const verb = done.state === "failed" ? "falhou" : done.state === "interrupted" ? "interrompida" : "concluída";
3006
- try {
3007
- context?.ui?.toast?.show?.({
3008
- title: TOAST_TITLE,
3009
- message: `${done.label} ${verb}`,
3010
- variant,
3011
- sessionID: done.id
3012
- });
3013
- } catch {}
3014
- }
3015
- /** Active preset signal with mount + 30s refresh. Shared by the sidebar and the
3016
- * home-screen status contribution. */
3017
- function useActivePreset(context) {
3018
- const [preset, setPreset] = createSignal(presetFromEnv(process.env));
3019
- const [overrides, setOverrides] = createSignal(emptyOverrides());
3020
- onMount(() => {
3021
- const cwd = resolveSidebarCwd(context);
3022
- let cancelled = false;
3023
- const refresh = async () => {
3024
- try {
3025
- const detail = await resolveActivePresetForTui(process.env, cwd);
3026
- if (!cancelled) {
3027
- setPreset(detail.info);
3028
- setOverrides(detail.overrides);
3029
- }
3030
- } catch {}
3031
- };
3032
- refresh();
3033
- const timer = setInterval(() => void refresh(), PRESET_REFRESH_MS);
3034
- onCleanup(() => {
3035
- cancelled = true;
3036
- clearInterval(timer);
3037
- });
3038
- });
3039
- return {
3040
- preset,
3041
- overrides
3042
- };
3043
- }
3044
- /** Debounce for the git file-count revalidation. `vcs.status` is an HTTP call;
3045
- * session events arrive in bursts, so the row is refreshed at most once per
3046
- * window instead of on every event. */
3047
- const GIT_CHANGES_DEBOUNCE_MS = 400;
3048
- /** `context.client.vcs.status(input?, requestOptions?)` →
3049
- * `Promise<{ data: VcsFileStatus[] }>` (`GET /api/vcs/status`). Returns the
3050
- * callable or null when the host does not expose it, so callers degrade to
3051
- * the branch-only row instead of throwing. */
3052
- function vcsStatusCall(context) {
3053
- const status = context?.client?.vcs?.status;
3054
- return typeof status === "function" ? status.bind(context.client.vcs) : null;
3055
- }
3056
- /** `context.client.session.stats(input?, requestOptions?)` →
3057
- * `Promise<SessionStatsInfo>` (`GET /api/experimental/session/stats`), served
3058
- * by the local process. Returns the callable or null when the host does not
3059
- * expose it, so the Context spend line simply does not render. */
3060
- function statsCall(context) {
3061
- const stats = context?.client?.session?.stats;
3062
- return typeof stats === "function" ? stats.bind(context.client.session) : null;
3063
- }
3064
- /** Local IANA zone for the stats call (`America/Sao_Paulo`); omitted when the
3065
- * runtime cannot resolve one. */
3066
- function localTimezone() {
3067
- try {
3068
- const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
3069
- return typeof zone === "string" && zone !== "" ? zone : void 0;
3070
- } catch {
3071
- return;
3072
- }
3073
- }
3074
- /** Fields every stats call sends. `tools: 'none'` skips the tool aggregation
3075
- * the block never renders; `project` is omitted (no cheap id in hand) rather
3076
- * than guessed. */
3077
- function statsInput() {
3078
- const timezone = localTimezone();
3079
- return timezone === void 0 ? { tools: "none" } : {
3080
- tools: "none",
3081
- timezone
3082
- };
3083
- }
3084
- /** Convert a millisecond instant to the unit the route accepted. */
3085
- function spendInstant(ms, unit) {
3086
- return unit === "s" ? Math.floor(ms / 1e3) : ms;
3087
- }
3088
- /** Measure the `from`/`to` unit once: millisecond epoch first, then a single
3089
- * seconds attempt. Bounded to two calls and never throws; anything the route
3090
- * rejects (mismatch, throw, malformed echo) ends as `unavailable`, which hides
3091
- * the block for the rest of the process instead of retrying forever. */
3092
- async function probeSpendUnit(call) {
3093
- const now = Date.now();
3094
- const fromMs = now - SPEND_PROBE_WINDOW_MS;
3095
- const attempts = [{
3096
- sent: {
3097
- from: fromMs,
3098
- to: now
3099
- },
3100
- scale: 1,
3101
- unit: "ms"
3102
- }, {
3103
- sent: {
3104
- from: Math.floor(fromMs / 1e3),
3105
- to: Math.floor(now / 1e3)
3106
- },
3107
- scale: 1e3,
3108
- unit: "s"
3109
- }];
3110
- for (const attempt of attempts) try {
3111
- if (statsRangeMatches((await call({
3112
- ...statsInput(),
3113
- ...attempt.sent
3114
- }))?.range, attempt.sent, attempt.scale)) return attempt.unit;
3115
- } catch {}
3116
- return "unavailable";
3117
- }
3118
- /** Resolve (and cache) the unit for this process. Concurrent callers share one
3119
- * probe, so a burst of refreshes cannot spend more than two calls on it. */
3120
- function ensureSpendUnit(call) {
3121
- if (spendUnit !== null) return Promise.resolve(spendUnit);
3122
- if (spendProbe === null) spendProbe = probeSpendUnit(call).then((unit) => {
3123
- spendUnit = unit;
3124
- spendProbe = null;
3125
- return unit;
3126
- }, () => {
3127
- spendUnit = "unavailable";
3128
- spendProbe = null;
3129
- return "unavailable";
3130
- });
3131
- return spendProbe;
3132
- }
3133
- /** Reactive state the sidebar view renders. Accessors keep the view reactive
3134
- * while the model itself stays free of JSX, so its effects are exercisable
3135
- * without a TUI renderer. */
3136
- /** Reactive wiring behind the sidebar: refresh subscription, warm syncs, the
3137
- * running-only spinner and the completion-toast effect. `context` stays loosely
3138
- * typed (the host API only exists at runtime) but the refresh event names are
3139
- * narrowed to the V2 union at the subscription site. */
3140
- function createSidebarModel(context, sessionID, gitExec = defaultGitExec) {
3141
- const [revision, setRevision] = createSignal(0);
3142
- const [metricsRevision, setMetricsRevision] = createSignal(0);
3143
- const [frame, setFrame] = createSignal(0);
3144
- const location = resolveLocation(context);
3145
- const activePreset = useActivePreset(context);
3146
- const preset = activePreset.preset;
3147
- const presetOverrides = activePreset.overrides;
3148
- let observedStates = /* @__PURE__ */ new Map();
3149
- let metricsDebounce;
3150
- const scheduleMetrics = () => {
3151
- if (metricsDebounce !== void 0) clearTimeout(metricsDebounce);
3152
- metricsDebounce = setTimeout(() => {
3153
- metricsDebounce = void 0;
3154
- setMetricsRevision((value) => value + 1);
3155
- }, 400);
3156
- };
3157
- const refresh = () => {
3158
- setRevision((value) => value + 1);
3159
- scheduleMetrics();
3160
- };
3161
- const activeSessionID = () => {
3162
- const id = sessionID();
3163
- return isValidSessionID(id) ? id : "";
3164
- };
3165
- const session = createMemo(() => {
3166
- revision();
3167
- const id = activeSessionID();
3168
- if (id === "") return void 0;
3169
- try {
3170
- return context.data.session.get(id);
3171
- } catch {
3172
- return;
3173
- }
3174
- });
3175
- const branch = createMemo(() => {
3176
- revision();
3177
- try {
3178
- return context.data.location.vcs.info(location)?.branch?.current ?? null;
3179
- } catch {
3180
- return null;
3181
- }
3182
- });
3183
- const [gitChangesRead, setGitChangesRead] = createSignal({
3184
- session: activeSessionID(),
3185
- text: null
3186
- });
3187
- const [gitCliRead, setGitCliRead] = createSignal({
3188
- session: activeSessionID(),
3189
- snapshot: null
3190
- });
3191
- const gitChanges = createMemo(() => {
3192
- const read = gitChangesRead();
3193
- return read.session === activeSessionID() ? read.text : null;
3194
- });
3195
- const gitCli = createMemo(() => {
3196
- const read = gitCliRead();
3197
- return read.session === activeSessionID() ? read.snapshot : null;
3198
- });
3199
- let gitRequest = 0;
3200
- let gitDebounce;
3201
- let gitProbeDebounce;
3202
- let gitProbeSessionID = activeSessionID();
3203
- let gitProbeStartedAt = null;
3204
- let gitProbeInFlight = false;
3205
- let disposed = false;
3206
- const loadGitChanges = async () => {
3207
- const status = vcsStatusCall(context);
3208
- if (status === null) return;
3209
- const session = activeSessionID();
3210
- const request = ++gitRequest;
3211
- try {
3212
- const result = await status({ location: { directory: resolveSidebarCwd(context) } });
3213
- if (request !== gitRequest || session !== activeSessionID()) return;
3214
- const files = Array.isArray(result?.data) ? result.data : Array.isArray(result) ? result : [];
3215
- setGitChangesRead({
3216
- session,
3217
- text: formatGitChanges(files)
3218
- });
3219
- } catch {}
3220
- };
3221
- const runGitProbe = async () => {
3222
- const session = activeSessionID();
3223
- if (session !== gitProbeSessionID) {
3224
- gitProbeSessionID = session;
3225
- gitProbeStartedAt = null;
3226
- gitProbeInFlight = false;
3227
- }
3228
- if (!gitProbeAllowed({
3229
- now: Date.now(),
3230
- lastRunAt: gitProbeStartedAt,
3231
- inFlight: gitProbeInFlight
3232
- })) return;
3233
- gitProbeInFlight = true;
3234
- gitProbeStartedAt = Date.now();
3235
- try {
3236
- const snapshot = await readGitSnapshot(resolveSidebarCwd(context), gitExec);
3237
- if (!disposed && session === activeSessionID()) setGitCliRead({
3238
- session,
3239
- snapshot
3240
- });
3241
- } catch {} finally {
3242
- if (session === gitProbeSessionID) gitProbeInFlight = false;
3243
- }
3244
- };
3245
- const scheduleGitChanges = () => {
3246
- if (vcsStatusCall(context) === null) return;
3247
- if (gitCli() !== null) return;
3248
- if (gitDebounce !== void 0) clearTimeout(gitDebounce);
3249
- gitDebounce = setTimeout(() => {
3250
- gitDebounce = void 0;
3251
- loadGitChanges();
3252
- }, 400);
3253
- };
3254
- const scheduleGitProbe = () => {
3255
- if (gitProbeDebounce !== void 0) clearTimeout(gitProbeDebounce);
3256
- gitProbeDebounce = setTimeout(() => {
3257
- gitProbeDebounce = void 0;
3258
- runGitProbe();
3259
- }, GIT_CLI_DEBOUNCE_MS);
3260
- };
3261
- const gitLine = createMemo(() => {
3262
- const snapshot = gitCli();
3263
- if (snapshot !== null) return formatGitSnapshot(snapshot);
3264
- return gitChanges();
3265
- });
3266
- createEffect(on(activeSessionID, (id) => {
3267
- if (disposed || id === "") return;
3268
- runGitProbe();
3269
- loadGitChanges();
3270
- }, { defer: true }));
3271
- const [spend, setSpend] = createSignal(null);
3272
- let spendTotals = {
3273
- today: null,
3274
- thirtyDays: null
3275
- };
3276
- let spendRequest = 0;
3277
- let spendDebounce;
3278
- const loadSpend = async () => {
3279
- const stats = statsCall(context);
3280
- if (stats === null) return;
3281
- try {
3282
- const unit = await ensureSpendUnit(stats);
3283
- if (unit === "unavailable") return;
3284
- const request = ++spendRequest;
3285
- const windows = spendWindows(Date.now());
3286
- const settled = await Promise.allSettled([stats({
3287
- ...statsInput(),
3288
- from: spendInstant(windows.today.from, unit),
3289
- to: spendInstant(windows.today.to, unit)
3290
- }), stats({
3291
- ...statsInput(),
3292
- from: spendInstant(windows.thirtyDays.from, unit),
3293
- to: spendInstant(windows.thirtyDays.to, unit)
3294
- })]);
3295
- if (request !== spendRequest) return;
3296
- const next = { ...spendTotals };
3297
- for (const [index, key] of ["today", "thirtyDays"].entries()) {
3298
- const result = settled[index];
3299
- if (result === void 0 || result.status !== "fulfilled") continue;
3300
- const cost = statsCost(result.value);
3301
- if (cost === null) continue;
3302
- next[key] = cost;
3303
- }
3304
- spendTotals = next;
3305
- setSpend(next);
3306
- } catch {}
3307
- };
3308
- const scheduleSpend = () => {
3309
- if (statsCall(context) === null) return;
3310
- if (spendDebounce !== void 0) clearTimeout(spendDebounce);
3311
- spendDebounce = setTimeout(() => {
3312
- spendDebounce = void 0;
3313
- loadSpend();
3314
- }, 400);
3315
- };
3316
- const messages = createMemo(() => {
3317
- revision();
3318
- const id = activeSessionID();
3319
- if (id === "") return [];
3320
- try {
3321
- const result = context.data.session.message?.list?.(id);
3322
- return Array.isArray(result) ? result : [];
3323
- } catch {
3324
- return [];
3325
- }
3326
- });
3327
- const familySessionIDs = createMemo(() => {
3328
- revision();
3329
- const id = activeSessionID();
3330
- if (id === "") return [];
3331
- const ids = [id];
3332
- try {
3333
- const result = context.data.session.family?.(id);
3334
- if (Array.isArray(result)) for (const childID of result) {
3335
- if (!isValidSessionID(childID) || ids.includes(childID)) continue;
3336
- ids.push(childID);
3337
- if (ids.length >= 8) break;
3338
- }
3339
- } catch {}
3340
- return ids;
3341
- });
3342
- const transcript = createMemo(() => {
3343
- metricsRevision();
3344
- const rootID = activeSessionID();
3345
- const collected = [];
3346
- let todo = [];
3347
- for (const id of familySessionIDs()) {
3348
- let list = [];
3349
- try {
3350
- const result = context.data.session.message?.list?.(id);
3351
- if (Array.isArray(result)) list = result;
3352
- } catch {}
3353
- collected.push(...list.slice(-400));
3354
- if (id === rootID) todo = latestTodoItems(list) ?? [];
3355
- }
3356
- return {
3357
- messages: collected,
3358
- todo
3359
- };
3360
- });
3361
- const usageMessages = createMemo(() => transcript().messages);
3362
- const todo = createMemo(() => ceilingTodoItems(transcript().todo, 6));
3363
- const messageCostTotal = createMemo(() => {
3364
- let total = 0;
3365
- for (const message of usageMessages()) {
3366
- if (message?.type !== "assistant") continue;
3367
- const cost = numberOrNull(message.cost);
3368
- if (cost !== null && cost > 0) total += cost;
3369
- }
3370
- return total;
3371
- });
3372
- const cost = createMemo(() => {
3373
- revision();
3374
- const ids = familySessionIDs();
3375
- if (ids.length === 0) return null;
3376
- let total = 0;
3377
- let found = false;
3378
- for (const id of ids) {
3379
- let value;
3380
- try {
3381
- value = context.data.session.cost?.(id);
3382
- } catch {
3383
- value = void 0;
3384
- }
3385
- let resolved = numberOrNull(value);
3386
- if (resolved === null) try {
3387
- resolved = numberOrNull(context.data.session.get(id)?.cost);
3388
- } catch {
3389
- resolved = null;
3390
- }
3391
- if (resolved !== null && resolved >= 0) {
3392
- total += resolved;
3393
- found = true;
3394
- }
3395
- }
3396
- if (found) return Math.max(total, messageCostTotal());
3397
- const fallback = messageCostTotal();
3398
- return fallback > 0 ? fallback : null;
3399
- });
3400
- const modelUsage = createMemo(() => {
3401
- metricsRevision();
3402
- return ceilingModelUsage(collectModelUsage(usageMessages()), 3);
3403
- });
3404
- const modelRefs = createMemo(() => {
3405
- revision();
3406
- const current = session();
3407
- const agent = typeof current?.agent === "string" && current.agent !== "" ? current.agent : "";
3408
- let agentRef;
3409
- if (agent !== "") try {
3410
- const agents = context.data.location?.agent?.list?.(location);
3411
- if (Array.isArray(agents)) agentRef = agents.find((entry) => entry?.id === agent)?.model;
3412
- } catch {}
3413
- const override = agent === "" ? void 0 : presetOverrides().agents[agent]?.model;
3414
- return {
3415
- agent,
3416
- sessionRef: current?.model,
3417
- agentRef,
3418
- override: typeof override === "string" && override !== "" ? override : null
3419
- };
3420
- });
3421
- const agentModel = createMemo(() => {
3422
- const { agent, sessionRef, agentRef, override } = modelRefs();
3423
- const model = shortModelID(override) ?? shortModelID(sessionRef) ?? shortModelID(agentRef);
3424
- if (model === null) return null;
3425
- return {
3426
- agent,
3427
- model,
3428
- overridden: override !== null
3429
- };
3430
- });
3431
- const provider = createMemo(() => {
3432
- revision();
3433
- const fromSession = providerIDFromRef(session()?.model);
3434
- if (fromSession !== null) return fromSession;
3435
- const list = messages();
3436
- for (let index = list.length - 1; index >= 0; index -= 1) {
3437
- const message = list[index];
3438
- if (message?.type !== "assistant") continue;
3439
- const fromMessage = providerIDFromRef(message.model);
3440
- if (fromMessage !== null) return fromMessage;
3441
- }
3442
- const { agentRef } = modelRefs();
3443
- const fromAgent = providerIDFromRef(agentRef);
3444
- if (fromAgent !== null) return fromAgent;
3445
- try {
3446
- return providerIDFromModels(context.data.location?.model?.list?.(location), agentRef);
3447
- } catch {
3448
- return null;
3449
- }
3450
- });
3451
- const contextUsage = createMemo(() => {
3452
- const list = messages().slice(-400);
3453
- if (list.length === 0) return null;
3454
- const refs = modelRefs();
3455
- const ref = resolveActiveModelRef(refs.sessionRef, list, refs.agentRef);
3456
- if (ref === null) return null;
3457
- let models = [];
3458
- try {
3459
- const result = context.data.location?.model?.list?.(location);
3460
- if (Array.isArray(result)) models = result;
3461
- } catch {}
3462
- return resolveModelContextSnapshot(list, ref, models, session()?.revert?.messageID);
3463
- });
3464
- const cachePerformance = createMemo(() => {
3465
- const message = lastAssistantWithTokens(messages(), session()?.revert?.messageID);
3466
- return message === null ? null : cacheHitPercent(message.tokens);
3467
- });
3468
- const turnPerformance = createMemo(() => {
3469
- const list = messages();
3470
- let anchor = -1;
3471
- for (let index = list.length - 1; index >= 0; index--) if (list[index]?.type === "assistant") {
3472
- anchor = index;
3473
- break;
3474
- }
3475
- return anchor === -1 ? null : turnTokensPerSecond(list, anchor);
3476
- });
3477
- const performance = createMemo(() => {
3478
- const cacheHit = cachePerformance();
3479
- const tokensPerSecond = turnPerformance();
3480
- if (cacheHit === null && tokensPerSecond === null) return null;
3481
- return {
3482
- cacheHit,
3483
- tokensPerSecond
3484
- };
3485
- });
3486
- const subagentCalls = createMemo(() => collectSubagentCalls(messages()));
3487
- const dispatchEntries = createMemo(() => {
3488
- revision();
3489
- const id = activeSessionID();
3490
- if (id === "") return [];
3491
- return collectDispatch(context, id, {
3492
- now: Date.now(),
3493
- calls: subagentCalls()
3494
- });
3495
- });
3496
- /** What the sidebar block renders: the collector's rows, nothing else. */
3497
- const allDelegations = createMemo(() => dispatchEntries().map((entry) => entry.view));
3498
- const hasRunning = createMemo(() => allDelegations().some((view) => view.state === "running"));
3499
- const dispatch = createMemo(() => {
3500
- frame();
3501
- return buildDispatchBlock(allDelegations(), Date.now(), frame());
3502
- });
3503
- const blocks = createMemo(() => {
3504
- const present = [];
3505
- if (contextBlockRows(contextUsage(), cost()) !== null || contextSpendLine(spend()) !== null) present.push("context");
3506
- if (branch() !== null || gitLine() !== null) present.push("git");
3507
- if (todo().visible.length > 0) present.push("todo");
3508
- if (dispatch() !== null) present.push("dispatch");
3509
- return withBlockSpacers(present);
3510
- });
3511
- onMount(() => {
3512
- const unsubscribeAll = subscribeSidebarRefresh(context, () => {
3513
- refresh();
3514
- scheduleGitChanges();
3515
- scheduleGitProbe();
3516
- scheduleSpend();
3517
- });
3518
- const id = activeSessionID();
3519
- if (id !== "") {
3520
- try {
3521
- Promise.resolve(context.data.session.sync(id)).then(refresh);
3522
- } catch {}
3523
- try {
3524
- Promise.resolve(context.data.session.message?.sync?.(id)).then(refresh);
3525
- } catch {}
3526
- }
3527
- try {
3528
- Promise.resolve(context.data.location.vcs.sync(location)).then(refresh);
3529
- } catch {}
3530
- loadGitChanges();
3531
- runGitProbe();
3532
- loadSpend();
3533
- createEffect(() => {
3534
- if (!hasRunning()) return;
3535
- const spinner = setInterval(() => setFrame((value) => value + 1), SPINNER_INTERVAL_MS);
3536
- onCleanup(() => clearInterval(spinner));
3537
- });
3538
- onCleanup(() => {
3539
- disposed = true;
3540
- if (gitDebounce !== void 0) clearTimeout(gitDebounce);
3541
- if (gitProbeDebounce !== void 0) clearTimeout(gitProbeDebounce);
3542
- if (spendDebounce !== void 0) clearTimeout(spendDebounce);
3543
- if (metricsDebounce !== void 0) clearTimeout(metricsDebounce);
3544
- });
3545
- onCleanup(unsubscribeAll);
3546
- });
3547
- let observedSessionID = activeSessionID();
3548
- createEffect(() => {
3549
- const id = activeSessionID();
3550
- const views = allDelegations();
3551
- if (id !== observedSessionID) {
3552
- observedSessionID = id;
3553
- observedStates = /* @__PURE__ */ new Map();
3554
- }
3555
- if (id === "") {
3556
- observedStates = /* @__PURE__ */ new Map();
3557
- return;
3558
- }
3559
- const { completed, snapshot } = detectDelegationCompletions(observedStates, views.map((view) => ({
3560
- id: view.id,
3561
- label: view.label,
3562
- state: view.state
3563
- })));
3564
- observedStates = snapshot;
3565
- for (const done of completed) showDelegationToast(context, done);
3566
- });
3567
- return {
3568
- activeSessionID,
3569
- session,
3570
- branch,
3571
- gitChanges,
3572
- gitLine,
3573
- gitCli,
3574
- performance,
3575
- dispatch,
3576
- blocks,
3577
- hasRunning,
3578
- frame,
3579
- preset,
3580
- provider,
3581
- presetOverrides,
3582
- cost,
3583
- modelUsage,
3584
- todo,
3585
- spend,
3586
- contextUsage,
3587
- agentModel
3588
- };
3589
- }
3590
- /** One `Context` row: an optional toned lead segment (the gauge's filled
3591
- * cells), the value, the muted gauge tail (empty cells) and the muted unit
3592
- * suffix (`tokens` / `of 200K` / `spent`). */
3593
- function ContextRowView(props) {
3594
- const fullWidth = () => cellWidth(`${props.row.lead ?? ""}${props.row.tail ?? ""}${props.row.value}${props.row.suffix ?? ""}`);
3595
- return createComponent(Show, {
3596
- get when() {
3597
- return props.row.suffix !== " gasto na sessão";
3598
- },
3599
- get fallback() {
3600
- return (() => {
3601
- var _el$3 = createElement("box");
3602
- setProp(_el$3, "flexDirection", "column");
3603
- insert(_el$3, createComponent(For, {
3604
- get each() {
3605
- return sidebarMoneyLines("gasto na sessão", props.row.value);
3606
- },
3607
- children: (line) => (() => {
3608
- var _el$4 = createElement("text");
3609
- insert(_el$4, line);
3610
- effect((_$p) => setProp(_el$4, "fg", props.fg, _$p));
3611
- return _el$4;
3612
- })()
3613
- }));
3614
- return _el$3;
3615
- })();
3616
- },
3617
- get children() {
3618
- return createComponent(Show, {
3619
- get when() {
3620
- return fullWidth() <= 34;
3621
- },
3622
- get fallback() {
3623
- return (() => {
3624
- var _el$5 = createElement("box");
3625
- setProp(_el$5, "flexDirection", "column");
3626
- insert(_el$5, createComponent(For, {
3627
- get each() {
3628
- return sidebarTextLines(`${props.row.value.trim()}${props.row.suffix ?? ""}`);
3629
- },
3630
- children: (line) => (() => {
3631
- var _el$6 = createElement("text");
3632
- insert(_el$6, line);
3633
- effect((_$p) => setProp(_el$6, "fg", props.fg, _$p));
3634
- return _el$6;
3635
- })()
3636
- }));
3637
- return _el$5;
3638
- })();
3639
- },
3640
- get children() {
3641
- var _el$ = createElement("box"), _el$2 = createElement("text");
3642
- insertNode(_el$, _el$2);
3643
- setProp(_el$, "flexDirection", "row");
3644
- insert(_el$, createComponent(Show, {
3645
- get when() {
3646
- return props.row.lead;
3647
- },
3648
- children: (lead) => (() => {
3649
- var _el$7 = createElement("text");
3650
- insert(_el$7, lead);
3651
- effect((_$p) => setProp(_el$7, "fg", props.fg, _$p));
3652
- return _el$7;
3653
- })()
3654
- }), _el$2);
3655
- insert(_el$, createComponent(Show, {
3656
- get when() {
3657
- return props.row.tail;
3658
- },
3659
- children: (tail) => (() => {
3660
- var _el$8 = createElement("text");
3661
- insert(_el$8, tail);
3662
- effect((_$p) => setProp(_el$8, "fg", props.muted, _$p));
3663
- return _el$8;
3664
- })()
3665
- }), _el$2);
3666
- insert(_el$2, () => props.row.value);
3667
- insert(_el$, createComponent(Show, {
3668
- get when() {
3669
- return props.row.suffix;
3670
- },
3671
- children: (suffix) => (() => {
3672
- var _el$9 = createElement("text");
3673
- insert(_el$9, suffix);
3674
- effect((_$p) => setProp(_el$9, "fg", props.muted, _$p));
3675
- return _el$9;
3676
- })()
3677
- }), null);
3678
- effect((_$p) => setProp(_el$2, "fg", props.fg, _$p));
3679
- return _el$;
3680
- }
3681
- });
3682
- }
3683
- });
3684
- }
3685
- /** Block title: a muted single-width glyph, then the bold label. The fixed
3686
- * header at the top of the sidebar deliberately renders no icon. `summary` is
3687
- * the muted tail some blocks carry (`· 2 rodando · $0.47`), so the header
3688
- * stays one line. */
3689
- function BlockHeader(props) {
3690
- return (() => {
3691
- var _el$0 = createElement("box"), _el$1 = createElement("text"), _el$10 = createElement("text");
3692
- insertNode(_el$0, _el$1);
3693
- insertNode(_el$0, _el$10);
3694
- setProp(_el$0, "flexDirection", "row");
3695
- insert(_el$1, () => `${props.icon} `);
3696
- setProp(_el$10, "attributes", 1);
3697
- insert(_el$10, () => props.label);
3698
- insert(_el$0, createComponent(Show, {
3699
- get when() {
3700
- return props.summary;
3701
- },
3702
- children: (summary) => (() => {
3703
- var _el$11 = createElement("text");
3704
- insert(_el$11, () => `${SPEND_LINE_SEPARATOR}${summary()}`);
3705
- effect((_$p) => setProp(_el$11, "fg", props.muted, _$p));
3706
- return _el$11;
3707
- })()
3708
- }), null);
3709
- effect((_p$) => {
3710
- var _v$ = props.muted, _v$2 = props.fg;
3711
- _v$ !== _p$.e && (_p$.e = setProp(_el$1, "fg", _v$, _p$.e));
3712
- _v$2 !== _p$.t && (_p$.t = setProp(_el$10, "fg", _v$2, _p$.t));
3713
- return _p$;
3714
- }, {
3715
- e: void 0,
3716
- t: void 0
3717
- });
3718
- return _el$0;
3719
- })();
3720
- }
3721
- function Sidebar(props) {
3722
- const { context } = props;
3723
- const model = createSidebarModel(context, () => props.sessionID);
3724
- const text = () => context.theme.text?.base;
3725
- const muted = () => context.theme.text?.muted ?? text();
3726
- const tone = (value) => context.theme?.text?.feedback?.[value]?.base ?? text();
3727
- const todoFg = (status) => {
3728
- const rowTone = todoTone(status);
3729
- if (rowTone === "accent") return tone("warning");
3730
- return rowTone === "muted" ? muted() : text();
3731
- };
3732
- const open = (sessionID) => () => navigateToSession(context.ui?.router, sessionID);
3733
- const block = (key) => model.blocks().find((entry) => entry.key === key);
3734
- const spacer = (key) => block(key)?.spacer === true;
3735
- const usageRows = () => modelUsageRows(model.modelUsage().visible);
3736
- const usageHidden = () => hiddenModelUsageText(model.modelUsage().hidden, model.modelUsage().hiddenCost);
3737
- const contextRows = () => contextBlockRows(model.contextUsage(), model.cost());
3738
- const spendLine = () => contextSpendLine(model.spend());
3739
- const performanceLine = () => contextPerformanceLine(model.performance());
3740
- const gaugeFg = (row) => contextProgressColor(row.tone ?? "warning", context.theme);
3741
- const dispatchView = () => model.dispatch();
3742
- const dispatchSummary = () => {
3743
- const view = dispatchView();
3744
- return view === null ? null : dispatchHeaderSummary(view.runningCount, view.totalCost);
3745
- };
3746
- const failedSuffix = () => failedSuffixText(dispatchView()?.failures);
3747
- return (() => {
3748
- var _el$12 = createElement("box"), _el$13 = createElement("text"), _el$14 = createElement("text");
3749
- insertNode(_el$12, _el$13);
3750
- insertNode(_el$12, _el$14);
3751
- setProp(_el$12, "flexDirection", "column");
3752
- setProp(_el$12, "width", "100%");
3753
- setProp(_el$12, "padding", 1);
3754
- setProp(_el$13, "attributes", 1);
3755
- insert(_el$13, `Pantheon v1.7.0`);
3756
- insert(_el$14, () => presetHeaderLine(model.preset().name ?? "", model.provider()));
3757
- insert(_el$12, createComponent(Show, {
3758
- get when() {
3759
- return memo(() => model.activeSessionID() !== "")() && model.session();
3760
- },
3761
- get fallback() {
3762
- return (() => {
3763
- var _el$25 = createElement("text");
3764
- insert(_el$25, () => sidebarPlaceholder(props.sessionID));
3765
- effect((_$p) => setProp(_el$25, "fg", muted(), _$p));
3766
- return _el$25;
3767
- })();
3768
- },
3769
- children: (current) => (() => {
3770
- var _el$26 = createElement("text");
3771
- insert(_el$26, () => `Sessão: ${truncateLabel(current().title || current().id)}`);
3772
- effect((_$p) => setProp(_el$26, "fg", text(), _$p));
3773
- return _el$26;
3774
- })()
3775
- }), null);
3776
- insert(_el$12, createComponent(Show, {
3777
- get when() {
3778
- return model.blocks().length > 0;
3779
- },
3780
- get children() {
3781
- var _el$15 = createElement("box");
3782
- setProp(_el$15, "height", 1);
3783
- return _el$15;
3784
- }
3785
- }), null);
3786
- insert(_el$12, createComponent(Show, {
3787
- get when() {
3788
- return block("context");
3789
- },
3790
- get children() {
3791
- var _el$16 = createElement("box");
3792
- setProp(_el$16, "flexDirection", "column");
3793
- insert(_el$16, createComponent(Show, {
3794
- get when() {
3795
- return spacer("context");
3796
- },
3797
- get children() {
3798
- var _el$17 = createElement("box");
3799
- setProp(_el$17, "height", 1);
3800
- return _el$17;
3801
- }
3802
- }), null);
3803
- insert(_el$16, createComponent(BlockHeader, {
3804
- get icon() {
3805
- return BLOCK_ICONS.context;
3806
- },
3807
- label: "Context",
3808
- get fg() {
3809
- return text();
3810
- },
3811
- get muted() {
3812
- return muted();
3813
- }
3814
- }), null);
3815
- insert(_el$16, createComponent(Show, {
3816
- get when() {
3817
- return contextRows();
3818
- },
3819
- children: (rows) => (() => {
3820
- var _el$27 = createElement("box");
3821
- setProp(_el$27, "flexDirection", "column");
3822
- insert(_el$27, createComponent(Show, {
3823
- get when() {
3824
- return rows().tokens;
3825
- },
3826
- children: (row) => createComponent(ContextRowView, {
3827
- get row() {
3828
- return row();
3829
- },
3830
- get fg() {
3831
- return text();
3832
- },
3833
- get muted() {
3834
- return muted();
3835
- }
3836
- })
3837
- }), null);
3838
- insert(_el$27, createComponent(Show, {
3839
- get when() {
3840
- return rows().percent;
3841
- },
3842
- children: (row) => createComponent(ContextRowView, {
3843
- get row() {
3844
- return row();
3845
- },
3846
- get fg() {
3847
- return gaugeFg(row());
3848
- },
3849
- get muted() {
3850
- return muted();
3851
- }
3852
- })
3853
- }), null);
3854
- insert(_el$27, createComponent(Show, {
3855
- get when() {
3856
- return rows().spent;
3857
- },
3858
- children: (row) => createComponent(ContextRowView, {
3859
- get row() {
3860
- return row();
3861
- },
3862
- get fg() {
3863
- return text();
3864
- },
3865
- get muted() {
3866
- return muted();
3867
- }
3868
- })
3869
- }), null);
3870
- insert(_el$27, createComponent(Show, {
3871
- get when() {
3872
- return usageRows().length > 0;
3873
- },
3874
- get children() {
3875
- return [(() => {
3876
- var _el$28 = createElement("text");
3877
- insertNode(_el$28, createTextNode(`Sessão · custo reportado`));
3878
- effect((_$p) => setProp(_el$28, "fg", muted(), _$p));
3879
- return _el$28;
3880
- })(), (() => {
3881
- var _el$30 = createElement("text");
3882
- insertNode(_el$30, createTextNode(`Modelo Tokens USD`));
3883
- effect((_$p) => setProp(_el$30, "fg", muted(), _$p));
3884
- return _el$30;
3885
- })()];
3886
- }
3887
- }), null);
3888
- insert(_el$27, createComponent(For, {
3889
- get each() {
3890
- return usageRows();
3891
- },
3892
- children: (row) => (() => {
3893
- var _el$32 = createElement("box");
3894
- setProp(_el$32, "flexDirection", "column");
3895
- insert(_el$32, createComponent(For, {
3896
- get each() {
3897
- return modelUsageRowLines(row);
3898
- },
3899
- children: (line) => (() => {
3900
- var _el$33 = createElement("text");
3901
- insert(_el$33, line);
3902
- effect((_$p) => setProp(_el$33, "fg", text(), _$p));
3903
- return _el$33;
3904
- })()
3905
- }));
3906
- return _el$32;
3907
- })()
3908
- }), null);
3909
- insert(_el$27, createComponent(Show, {
3910
- get when() {
3911
- return usageHidden();
3912
- },
3913
- children: (line) => createComponent(For, {
3914
- get each() {
3915
- return sidebarTextLines(line());
3916
- },
3917
- children: (part) => (() => {
3918
- var _el$34 = createElement("text");
3919
- insert(_el$34, part);
3920
- effect((_$p) => setProp(_el$34, "fg", muted(), _$p));
3921
- return _el$34;
3922
- })()
3923
- })
3924
- }), null);
3925
- return _el$27;
3926
- })()
3927
- }), null);
3928
- insert(_el$16, createComponent(Show, {
3929
- get when() {
3930
- return performanceLine();
3931
- },
3932
- children: (line) => (() => {
3933
- var _el$35 = createElement("text");
3934
- insert(_el$35, line);
3935
- effect((_$p) => setProp(_el$35, "fg", muted(), _$p));
3936
- return _el$35;
3937
- })()
3938
- }), null);
3939
- insert(_el$16, createComponent(Show, {
3940
- get when() {
3941
- return spendLine();
3942
- },
3943
- children: (line) => createComponent(For, {
3944
- get each() {
3945
- return contextSpendLines(line());
3946
- },
3947
- children: (part) => (() => {
3948
- var _el$36 = createElement("text");
3949
- insert(_el$36, part);
3950
- effect((_$p) => setProp(_el$36, "fg", muted(), _$p));
3951
- return _el$36;
3952
- })()
3953
- })
3954
- }), null);
3955
- return _el$16;
3956
- }
3957
- }), null);
3958
- insert(_el$12, createComponent(Show, {
3959
- get when() {
3960
- return block("git");
3961
- },
3962
- get children() {
3963
- var _el$18 = createElement("box");
3964
- setProp(_el$18, "flexDirection", "column");
3965
- insert(_el$18, createComponent(Show, {
3966
- get when() {
3967
- return spacer("git");
3968
- },
3969
- get children() {
3970
- var _el$19 = createElement("box");
3971
- setProp(_el$19, "height", 1);
3972
- return _el$19;
3973
- }
3974
- }), null);
3975
- insert(_el$18, createComponent(BlockHeader, {
3976
- get icon() {
3977
- return BLOCK_ICONS.git;
3978
- },
3979
- label: "Git status",
3980
- get fg() {
3981
- return text();
3982
- },
3983
- get muted() {
3984
- return muted();
3985
- }
3986
- }), null);
3987
- insert(_el$18, createComponent(Show, {
3988
- get when() {
3989
- return model.branch();
3990
- },
3991
- children: (value) => (() => {
3992
- var _el$37 = createElement("box"), _el$38 = createElement("text"), _el$40 = createElement("text");
3993
- insertNode(_el$37, _el$38);
3994
- insertNode(_el$37, _el$40);
3995
- setProp(_el$37, "flexDirection", "row");
3996
- insertNode(_el$38, createTextNode(`⎇ `));
3997
- insert(_el$40, () => truncateLabel(value(), 32));
3998
- effect((_p$) => {
3999
- var _v$5 = muted(), _v$6 = text();
4000
- _v$5 !== _p$.e && (_p$.e = setProp(_el$38, "fg", _v$5, _p$.e));
4001
- _v$6 !== _p$.t && (_p$.t = setProp(_el$40, "fg", _v$6, _p$.t));
4002
- return _p$;
4003
- }, {
4004
- e: void 0,
4005
- t: void 0
4006
- });
4007
- return _el$37;
4008
- })()
4009
- }), null);
4010
- insert(_el$18, createComponent(Show, {
4011
- get when() {
4012
- return model.gitLine();
4013
- },
4014
- children: (line) => (() => {
4015
- var _el$41 = createElement("text");
4016
- insert(_el$41, line);
4017
- effect((_$p) => setProp(_el$41, "fg", text(), _$p));
4018
- return _el$41;
4019
- })()
4020
- }), null);
4021
- return _el$18;
4022
- }
4023
- }), null);
4024
- insert(_el$12, createComponent(Show, {
4025
- get when() {
4026
- return block("todo");
4027
- },
4028
- get children() {
4029
- var _el$20 = createElement("box");
4030
- setProp(_el$20, "flexDirection", "column");
4031
- insert(_el$20, createComponent(Show, {
4032
- get when() {
4033
- return spacer("todo");
4034
- },
4035
- get children() {
4036
- var _el$21 = createElement("box");
4037
- setProp(_el$21, "height", 1);
4038
- return _el$21;
4039
- }
4040
- }), null);
4041
- insert(_el$20, createComponent(Show, {
4042
- get when() {
4043
- return model.todo().visible.length > 0;
4044
- },
4045
- get children() {
4046
- var _el$22 = createElement("box");
4047
- setProp(_el$22, "flexDirection", "column");
4048
- insert(_el$22, createComponent(BlockHeader, {
4049
- get icon() {
4050
- return BLOCK_ICONS.todo;
4051
- },
4052
- label: "Todo",
4053
- get fg() {
4054
- return tone("warning");
4055
- },
4056
- get muted() {
4057
- return muted();
4058
- }
4059
- }), null);
4060
- insert(_el$22, createComponent(For, {
4061
- get each() {
4062
- return model.todo().visible;
4063
- },
4064
- children: (item) => (() => {
4065
- var _el$42 = createElement("text");
4066
- insert(_el$42, () => todoRowText(item));
4067
- effect((_$p) => setProp(_el$42, "fg", todoFg(item.status), _$p));
4068
- return _el$42;
4069
- })()
4070
- }), null);
4071
- insert(_el$22, createComponent(Show, {
4072
- get when() {
4073
- return hiddenTodoText(model.todo().hidden);
4074
- },
4075
- children: (line) => (() => {
4076
- var _el$43 = createElement("text");
4077
- insert(_el$43, line);
4078
- effect((_$p) => setProp(_el$43, "fg", muted(), _$p));
4079
- return _el$43;
4080
- })()
4081
- }), null);
4082
- return _el$22;
4083
- }
4084
- }), null);
4085
- return _el$20;
4086
- }
4087
- }), null);
4088
- insert(_el$12, createComponent(Show, {
4089
- get when() {
4090
- return block("dispatch");
4091
- },
4092
- get children() {
4093
- var _el$23 = createElement("box");
4094
- setProp(_el$23, "flexDirection", "column");
4095
- insert(_el$23, createComponent(Show, {
4096
- get when() {
4097
- return spacer("dispatch");
4098
- },
4099
- get children() {
4100
- var _el$24 = createElement("box");
4101
- setProp(_el$24, "height", 1);
4102
- return _el$24;
4103
- }
4104
- }), null);
4105
- insert(_el$23, createComponent(Show, {
4106
- get when() {
4107
- return dispatchView();
4108
- },
4109
- children: (view) => (() => {
4110
- var _el$44 = createElement("box");
4111
- setProp(_el$44, "flexDirection", "column");
4112
- insert(_el$44, createComponent(BlockHeader, {
4113
- get icon() {
4114
- return BLOCK_ICONS.dispatch;
4115
- },
4116
- label: "Dispatch",
4117
- get fg() {
4118
- return memo(() => view().runningCount > 0)() ? tone("success") : muted();
4119
- },
4120
- get muted() {
4121
- return muted();
4122
- },
4123
- get summary() {
4124
- return dispatchSummary();
4125
- }
4126
- }), null);
4127
- insert(_el$44, createComponent(For, {
4128
- get each() {
4129
- return view().running;
4130
- },
4131
- children: (row) => (() => {
4132
- var _el$46 = createElement("box"), _el$47 = createElement("text");
4133
- insertNode(_el$46, _el$47);
4134
- setProp(_el$46, "flexShrink", 0);
4135
- insert(_el$47, () => row.text);
4136
- effect((_p$) => {
4137
- var _v$7 = open(row.id), _v$8 = tone("success");
4138
- _v$7 !== _p$.e && (_p$.e = setProp(_el$46, "onMouseDown", _v$7, _p$.e));
4139
- _v$8 !== _p$.t && (_p$.t = setProp(_el$47, "fg", _v$8, _p$.t));
4140
- return _p$;
4141
- }, {
4142
- e: void 0,
4143
- t: void 0
4144
- });
4145
- return _el$46;
4146
- })()
4147
- }), null);
4148
- insert(_el$44, createComponent(Show, {
4149
- get when() {
4150
- return view().runningHidden > 0;
4151
- },
4152
- get children() {
4153
- var _el$45 = createElement("text");
4154
- insert(_el$45, () => `\u2026 +${view().runningHidden} rodando`);
4155
- effect((_$p) => setProp(_el$45, "fg", muted(), _$p));
4156
- return _el$45;
4157
- }
4158
- }), null);
4159
- insert(_el$44, createComponent(Show, {
4160
- get when() {
4161
- return view().summary;
4162
- },
4163
- children: (line) => (() => {
4164
- var _el$48 = createElement("box"), _el$49 = createElement("text");
4165
- insertNode(_el$48, _el$49);
4166
- setProp(_el$48, "flexDirection", "row");
4167
- setProp(_el$48, "flexShrink", 0);
4168
- insert(_el$49, line);
4169
- insert(_el$48, createComponent(Show, {
4170
- get when() {
4171
- return failedSuffix();
4172
- },
4173
- children: (suffix) => (() => {
4174
- var _el$50 = createElement("text");
4175
- insert(_el$50, () => `${SPEND_LINE_SEPARATOR}${suffix()}`);
4176
- effect((_$p) => setProp(_el$50, "fg", tone("error"), _$p));
4177
- return _el$50;
4178
- })()
4179
- }), null);
4180
- effect((_$p) => setProp(_el$49, "fg", muted(), _$p));
4181
- return _el$48;
4182
- })()
4183
- }), null);
4184
- insert(_el$44, createComponent(For, {
4185
- get each() {
4186
- return view().agents;
4187
- },
4188
- children: (row) => (() => {
4189
- var _el$51 = createElement("text");
4190
- insert(_el$51, () => childAgentRowText(row));
4191
- effect((_$p) => setProp(_el$51, "fg", muted(), _$p));
4192
- return _el$51;
4193
- })()
4194
- }), null);
4195
- insert(_el$44, createComponent(Show, {
4196
- get when() {
4197
- return hiddenChildAgentsText(view().agentsHidden, view().agentsHiddenCost);
4198
- },
4199
- children: (line) => (() => {
4200
- var _el$52 = createElement("text");
4201
- insert(_el$52, line);
4202
- effect((_$p) => setProp(_el$52, "fg", muted(), _$p));
4203
- return _el$52;
4204
- })()
4205
- }), null);
4206
- return _el$44;
4207
- })()
4208
- }), null);
4209
- return _el$23;
4210
- }
4211
- }), null);
4212
- effect((_p$) => {
4213
- var _v$3 = text(), _v$4 = muted();
4214
- _v$3 !== _p$.e && (_p$.e = setProp(_el$13, "fg", _v$3, _p$.e));
4215
- _v$4 !== _p$.t && (_p$.t = setProp(_el$14, "fg", _v$4, _p$.t));
4216
- return _p$;
4217
- }, {
4218
- e: void 0,
4219
- t: void 0
4220
- });
4221
- return _el$12;
4222
- })();
4223
- }
4224
- /** Panel actions that only make sense with a row selected. A panel over an
4225
- * empty tree still owns `f`/`escape`, but the navigation keys fall through
4226
- * instead of being swallowed by a no-op. */
4227
- const DISPATCH_PANEL_ROW_ACTIONS = /* @__PURE__ */ new Set([
4228
- "up",
4229
- "down",
4230
- "home",
4231
- "end",
4232
- "pageup",
4233
- "pagedown",
4234
- "toggle"
4235
- ]);
4236
- /** One command: runs only while the panel owns the keyboard, and reports
4237
- * `false` (the host keeps the key) when it cannot act. `undefined` means the
4238
- * key was consumed. */
4239
- function runDispatchPanelCommand(action, panel, model) {
4240
- if (panel.focused !== true) return false;
4241
- if (DISPATCH_PANEL_ROW_ACTIONS.has(action) && model.rows().length === 0) return false;
4242
- performDispatchPanelAction(action, model, panel);
4243
- }
4244
- /** Keymap layer of the panel, as data. It is registered inside the
4245
- * `session.panel` claim, but the host mounts the effects of *every* panel
4246
- * contribution, so the layer itself is not proof of focus: without `enabled`
4247
- * the `j/k/f/q/enter/escape` bindings were consumed while the panel was not
4248
- * focused and the composer lost its keys. `enabled` (the documented gate) makes
4249
- * the whole layer inert until `panel.focused` is true. Pure. */
4250
- function dispatchPanelKeymapLayer(panel, model) {
4251
- const focused = () => panel.focused === true;
4252
- return {
4253
- mode: "global",
4254
- enabled: focused,
4255
- commands: DISPATCH_PANEL_COMMANDS.map((spec) => ({
4256
- id: spec.id,
4257
- title: spec.title,
4258
- bind: spec.bind,
4259
- run: () => focused() ? runDispatchPanelCommand(spec.action, panel, model) : false
4260
- }))
4261
- };
4262
- }
4263
- /** Keymap layer of the panel. Created inside the `session.panel` claim, so the
4264
- * host removes it with the panel; it renders nothing. */
4265
- function DispatchPanelKeymap(props) {
4266
- props.context.keymap.layer(() => dispatchPanelKeymapLayer(props.panel, props.model));
4267
- return null;
4268
- }
4269
- /** The full-width dispatch panel: header counters, one row per child session,
4270
- * the detail of the selected child and the key hints. Wide panels put the
4271
- * detail beside the list; narrow ones stack it under the list and every cell is
4272
- * truncated to its own column instead of wrapping. */
4273
- function DispatchPanel(props) {
4274
- const model = createDispatchPanelModel(props.context, () => props.panel);
4275
- const text = () => props.context.theme.text?.base;
4276
- const muted = () => props.context.theme.text?.muted ?? text();
4277
- const tone = (value) => props.context.theme?.text?.feedback?.[value]?.base ?? text();
4278
- const rowFg = (state) => {
4279
- if (state === "failed") return tone("error");
4280
- if (state === "running") return tone("success");
4281
- if (state === "interrupted") return tone("warning");
4282
- return text();
4283
- };
4284
- const selected = (id) => id === model.selectedID();
4285
- const rows = () => createComponent(For, {
4286
- get each() {
4287
- return model.visible().rows;
4288
- },
4289
- children: (row) => (() => {
4290
- var _el$53 = createElement("box"), _el$54 = createElement("text"), _el$55 = createElement("text");
4291
- insertNode(_el$53, _el$54);
4292
- insertNode(_el$53, _el$55);
4293
- setProp(_el$53, "flexDirection", "row");
4294
- setProp(_el$53, "flexShrink", 0);
4295
- insert(_el$54, () => selected(row.id) ? `▸ ` : " ");
4296
- insert(_el$55, () => row.text);
4297
- effect((_p$) => {
4298
- var _v$9 = selected(row.id) ? text() : muted(), _v$0 = rowFg(row.state), _v$1 = selected(row.id) ? 1 : 0;
4299
- _v$9 !== _p$.e && (_p$.e = setProp(_el$54, "fg", _v$9, _p$.e));
4300
- _v$0 !== _p$.t && (_p$.t = setProp(_el$55, "fg", _v$0, _p$.t));
4301
- _v$1 !== _p$.a && (_p$.a = setProp(_el$55, "attributes", _v$1, _p$.a));
4302
- return _p$;
4303
- }, {
4304
- e: void 0,
4305
- t: void 0,
4306
- a: void 0
4307
- });
4308
- return _el$53;
4309
- })()
4310
- });
4311
- const detail = () => createComponent(For, {
4312
- get each() {
4313
- return model.detail();
4314
- },
4315
- children: (line, index) => (() => {
4316
- var _el$56 = createElement("text");
4317
- insert(_el$56, line);
4318
- effect((_$p) => setProp(_el$56, "fg", index() === 0 ? text() : muted(), _$p));
4319
- return _el$56;
4320
- })()
4321
- });
4322
- const empty = () => (() => {
4323
- var _el$57 = createElement("text");
4324
- insertNode(_el$57, createTextNode(`Nenhuma sessão delegada`));
4325
- effect((_$p) => setProp(_el$57, "fg", muted(), _$p));
4326
- return _el$57;
4327
- })();
4328
- return (() => {
4329
- var _el$59 = createElement("box"), _el$60 = createElement("text"), _el$61 = createElement("text"), _el$65 = createElement("box"), _el$66 = createElement("text");
4330
- insertNode(_el$59, _el$60);
4331
- insertNode(_el$59, _el$61);
4332
- insertNode(_el$59, _el$65);
4333
- insertNode(_el$59, _el$66);
4334
- setProp(_el$59, "flexDirection", "column");
4335
- setProp(_el$59, "width", "100%");
4336
- setProp(_el$59, "padding", 1);
4337
- insert(_el$59, createComponent(DispatchPanelKeymap, {
4338
- get context() {
4339
- return props.context;
4340
- },
4341
- get panel() {
4342
- return props.panel;
4343
- },
4344
- model
4345
- }), _el$60);
4346
- setProp(_el$60, "attributes", 1);
4347
- insert(_el$60, () => model.title());
4348
- insert(_el$59, createComponent(Show, {
4349
- get when() {
4350
- return model.header();
4351
- },
4352
- children: (line) => (() => {
4353
- var _el$67 = createElement("text");
4354
- insert(_el$67, line);
4355
- effect((_$p) => setProp(_el$67, "fg", muted(), _$p));
4356
- return _el$67;
4357
- })()
4358
- }), _el$61);
4359
- insert(_el$61, () => dispatchPanelRule(props.panel.width - 2));
4360
- insert(_el$59, createComponent(Show, {
4361
- get when() {
4362
- return model.layout().mode === "wide";
4363
- },
4364
- get fallback() {
4365
- return (() => {
4366
- var _el$68 = createElement("box");
4367
- setProp(_el$68, "flexDirection", "column");
4368
- insert(_el$68, createComponent(Show, {
4369
- get when() {
4370
- return model.rows().length > 0;
4371
- },
4372
- get fallback() {
4373
- return empty();
4374
- },
4375
- get children() {
4376
- var _el$69 = createElement("box");
4377
- setProp(_el$69, "flexDirection", "column");
4378
- insert(_el$69, rows);
4379
- return _el$69;
4380
- }
4381
- }), null);
4382
- insert(_el$68, createComponent(Show, {
4383
- get when() {
4384
- return model.selectedID();
4385
- },
4386
- get children() {
4387
- var _el$70 = createElement("box"), _el$71 = createElement("box");
4388
- insertNode(_el$70, _el$71);
4389
- setProp(_el$70, "flexDirection", "column");
4390
- setProp(_el$71, "height", 1);
4391
- insert(_el$70, detail, null);
4392
- return _el$70;
4393
- }
4394
- }), null);
4395
- return _el$68;
4396
- })();
4397
- },
4398
- get children() {
4399
- var _el$62 = createElement("box"), _el$63 = createElement("box");
4400
- insertNode(_el$62, _el$63);
4401
- setProp(_el$62, "flexDirection", "row");
4402
- setProp(_el$63, "flexDirection", "column");
4403
- insert(_el$63, createComponent(Show, {
4404
- get when() {
4405
- return model.rows().length > 0;
4406
- },
4407
- get fallback() {
4408
- return empty();
4409
- },
4410
- get children() {
4411
- return rows();
4412
- }
4413
- }));
4414
- insert(_el$62, createComponent(Show, {
4415
- get when() {
4416
- return model.selectedID();
4417
- },
4418
- get children() {
4419
- var _el$64 = createElement("box");
4420
- setProp(_el$64, "flexDirection", "column");
4421
- insert(_el$64, detail);
4422
- effect((_$p) => setProp(_el$64, "width", model.layout().detailWidth, _$p));
4423
- return _el$64;
4424
- }
4425
- }), null);
4426
- effect((_$p) => setProp(_el$63, "width", model.layout().listWidth, _$p));
4427
- return _el$62;
4428
- }
4429
- }), _el$65);
4430
- setProp(_el$65, "height", 1);
4431
- insert(_el$66, () => model.footer());
4432
- effect((_p$) => {
4433
- var _v$10 = text(), _v$11 = muted(), _v$12 = muted();
4434
- _v$10 !== _p$.e && (_p$.e = setProp(_el$60, "fg", _v$10, _p$.e));
4435
- _v$11 !== _p$.t && (_p$.t = setProp(_el$61, "fg", _v$11, _p$.t));
4436
- _v$12 !== _p$.a && (_p$.a = setProp(_el$66, "fg", _v$12, _p$.a));
4437
- return _p$;
4438
- }, {
4439
- e: void 0,
4440
- t: void 0,
4441
- a: void 0
4442
- });
4443
- return _el$59;
4444
- })();
4445
- }
4446
- /** App-level command claim: the only way into the panel. It registers the
4447
- * `pantheon.dispatch.open` command (palette + `/dispatch`) and renders nothing;
4448
- * the panel itself lives behind its own `session.panel` claim. */
4449
- function DispatchCommandLayer(props) {
4450
- props.context.keymap.layer(() => ({
4451
- mode: "global",
4452
- commands: [{
4453
- id: "pantheon.dispatch.open",
4454
- title: "Pantheon: Dispatch",
4455
- group: "Pantheon",
4456
- palette: true,
4457
- slash: {
4458
- name: "dispatch",
4459
- aliases: ["pantheon-dispatch"]
4460
- },
4461
- run: () => {
4462
- openDispatchPanel(props.context);
4463
- }
4464
- }]
4465
- }));
4466
- return null;
4467
- }
4468
- /** Home-screen status contribution. The sidebar slot is session-scoped, so
4469
- * before the first prompt the sidebar may not mount at all (Known Issue) —
4470
- * this keeps a compact Pantheon line visible on the home footer meanwhile. */
4471
- function HomeStatus(props) {
4472
- const preset = useActivePreset(props.context).preset;
4473
- const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base;
4474
- return (() => {
4475
- var _el$72 = createElement("text");
4476
- insert(_el$72, () => `Pantheon v1.7.0${preset().name ? ` ▸ ${preset().name}` : ""}`);
4477
- effect((_$p) => setProp(_el$72, "fg", muted(), _$p));
4478
- return _el$72;
4479
- })();
4480
- }
4481
- /** Lean footer model: only the preset label and the live delegation count. It
4482
- * deliberately does not reuse `createSidebarModel` — that model owns the
4483
- * completion toasts and the spinner, and a second instance would double-toast.
4484
- * No session id in the slot input is a graceful no-op (count 0). */
4485
- function createFooterModel(context, sessionID) {
4486
- const [revision, setRevision] = createSignal(0);
4487
- const preset = useActivePreset(context).preset;
4488
- const activeSessionID = () => {
4489
- const id = sessionID();
4490
- return isValidSessionID(id) ? id : "";
4491
- };
4492
- const running = createMemo(() => {
4493
- revision();
4494
- const id = activeSessionID();
4495
- if (id === "") return 0;
4496
- let family = [];
4497
- try {
4498
- const result = context.data.session.family?.(id);
4499
- if (Array.isArray(result)) family = result;
4500
- } catch {
4501
- return 0;
4502
- }
4503
- const now = Date.now();
4504
- let count = 0;
4505
- for (const childID of family) {
4506
- if (childID === id || !isValidSessionID(childID)) continue;
4507
- try {
4508
- const child = context.data.session.get(childID);
4509
- if (child?.parentID !== id) continue;
4510
- if (toDelegationView(child, sessionStatusOf(context, childID), now).state === "running") count += 1;
4511
- } catch {}
4512
- }
4513
- return count;
4514
- });
4515
- onMount(() => {
4516
- onCleanup(subscribeSidebarRefresh(context, () => setRevision((value) => value + 1)));
4517
- });
4518
- return {
4519
- preset,
4520
- running
4521
- };
4522
- }
4523
- /** Prompt-footer contribution: `▸<preset> · ✦<n> ativos`, appended next to the
4524
- * native line (never replacing it) and only while a delegation is running. */
4525
- function PromptFooter(props) {
4526
- const model = createFooterModel(props.context, () => props.sessionID);
4527
- const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base;
4528
- return createComponent(Show, {
4529
- get when() {
4530
- return model.running() > 0;
4531
- },
4532
- get children() {
4533
- var _el$73 = createElement("text");
4534
- insert(_el$73, () => `▸${model.preset().name ?? "default"} · ✦${model.running()} ativos`);
4535
- effect((_$p) => setProp(_el$73, "fg", muted(), _$p));
4536
- return _el$73;
4537
- }
4538
- });
4539
- }
4540
- const plugin = Plugin.define({
4541
- id: "pantheon.tui",
4542
- setup(context) {
4543
- const globalState = globalThis;
4544
- if (globalState[SINGLETON]) return;
4545
- globalState[SINGLETON] = true;
4546
- warmUpSidebarData(context, resolveLocation(context));
4547
- const unregisterSidebar = context.ui.slot({
4548
- append: "sidebar.content",
4549
- render: ({ sessionID }) => createComponent(Sidebar, {
4550
- context,
4551
- sessionID
4552
- })
4553
- });
4554
- const unregisterHome = context.ui.slot({
4555
- append: "home.footer.status",
4556
- render: () => createComponent(HomeStatus, { context })
4557
- });
4558
- const unregisterPromptFooter = context.ui.slot({
4559
- append: "prompt.footer",
4560
- render: ({ sessionID }) => createComponent(PromptFooter, {
4561
- context,
4562
- sessionID
4563
- })
4564
- });
4565
- const unregisterPanel = context.ui.slot({
4566
- append: "session.panel",
4567
- render: (panel) => createComponent(Show, {
4568
- get when() {
4569
- return panel.name === DISPATCH_PANEL_NAME;
4570
- },
4571
- get children() {
4572
- return createComponent(DispatchPanel, {
4573
- context,
4574
- panel
4575
- });
4576
- }
4577
- })
4578
- });
4579
- const unregisterCommands = context.ui.slot({
4580
- append: "app",
4581
- render: () => createComponent(DispatchCommandLayer, { context })
4582
- });
4583
- maybeShowWhatsNewV2(context);
4584
- return () => {
4585
- if (typeof unregisterSidebar === "function") unregisterSidebar();
4586
- if (typeof unregisterHome === "function") unregisterHome();
4587
- if (typeof unregisterPromptFooter === "function") unregisterPromptFooter();
4588
- if (typeof unregisterPanel === "function") unregisterPanel();
4589
- if (typeof unregisterCommands === "function") unregisterCommands();
4590
- delete globalState[SINGLETON];
4591
- };
4592
- }
4593
- });
4594
- //#endregion
4595
- export { BLOCK_ICONS, CONTEXT_BAR_CELLS, CONTEXT_BAR_EMPTY_CELL, CONTEXT_BAR_FILLED_CELL, DELEGATION_CHILD_STATUS_GRACE_MS, DISPATCH_AGENT_CEILING, DISPATCH_AGENT_WIDTH, DISPATCH_COST_WIDTH, DISPATCH_COUNT_WIDTH, DISPATCH_DONE_MARKER, DISPATCH_DURATION_WIDTH, DISPATCH_GROUP_COST_WIDTH, DISPATCH_KIND_ORIGIN_LABELS, DISPATCH_MAX_LINES, DISPATCH_MAX_WIDTH, DISPATCH_MIN_AGENT_WIDTH, DISPATCH_MODEL_WIDTH, DISPATCH_PANEL_AGENT_WIDTH, DISPATCH_PANEL_COMMANDS, DISPATCH_PANEL_COST_WIDTH, DISPATCH_PANEL_DASH, DISPATCH_PANEL_DURATION_WIDTH, DISPATCH_PANEL_EMPTY_TEXT, DISPATCH_PANEL_FULLSCREEN_BADGE, DISPATCH_PANEL_HEADER_MARKER, DISPATCH_PANEL_KIND_WIDTH, DISPATCH_PANEL_MIN_AGENT_WIDTH, DISPATCH_PANEL_NAME, DISPATCH_PANEL_PAGE_SIZE, DISPATCH_PANEL_RULE_CHAR, DISPATCH_PANEL_SELECTION_GUTTER, DISPATCH_PANEL_SELECTION_MARKER, DISPATCH_PANEL_TITLE_WIDTH, DISPATCH_PANEL_TOAST, DISPATCH_PANEL_WIDE_MIN_WIDTH, DISPATCH_RUNNING_CEILING, GIT_ARROW_DOWN, GIT_ARROW_UP, GIT_CHANGES_DEBOUNCE_MS, GIT_CLI_DEBOUNCE_MS, GIT_CLI_MAX_BUFFER, GIT_CLI_MIN_INTERVAL_MS, GIT_CLI_TIMEOUT_MS, HEADER_MAX_WIDTH, MODEL_USAGE_COST_WIDTH, MODEL_USAGE_DEBOUNCE_MS, MODEL_USAGE_MESSAGE_LIMIT, MODEL_USAGE_MODEL_WIDTH, MODEL_USAGE_SESSION_LIMIT, MODEL_USAGE_TOKEN_WIDTH, MODEL_USAGE_VISIBLE_CEILING, PRESET_MARKER, SIDEBAR_REFRESH_EVENTS, SIDEBAR_WAITING_LABEL, SPEND_30D_LABEL, SPEND_30D_MS, SPEND_LINE_SEPARATOR, SPEND_PROBE_TOLERANCE_MS, SPEND_PROBE_WINDOW_MS, SPEND_REFRESH_DEBOUNCE_MS, SPEND_TODAY_LABEL, TODO_TEXT_WIDTH, TODO_VISIBLE_CEILING, UNKNOWN_AGENT, agentKey, buildDispatchBlock, cacheHitPercent, ceilingModelUsage, ceilingTodoItems, cellWidth, childAgentRowText, classifyDispatchKind, collectChildAgentUsage, collectDispatch, collectModelUsage, collectSubagentCalls, collectWarmupTargets, completedSummaryText, computeContextUsage, contextBar, contextBarFilled, contextBlockRows, contextPerformanceLine, contextProgressColor, contextSpendLine, contextSpendLines, contextUsageTone, countGitChanges, createDispatchPanelModel, createFooterModel, createSidebarModel, plugin as default, defaultGitExec, delegationStateFromOutcome, delegationStateFromStatus, detectDelegationCompletions, dispatchAgentText, dispatchElapsed, dispatchHeaderSummary, dispatchKindFromAgent, dispatchKindFromPrefix, dispatchKindSuffix, dispatchModelText, dispatchPanelCell, dispatchPanelDetail, dispatchPanelFooter, dispatchPanelHeader, dispatchPanelKeymapLayer, dispatchPanelLayout, dispatchPanelMarker, dispatchPanelRangeText, dispatchPanelRowText, dispatchPanelRows, dispatchPanelRule, dispatchPanelTitle, dispatchPanelWindow, dispatchTokenLine, dispatchTokens, dispatchTotalCost, failedSuffixText, formatContextWindow, formatDispatchCost, formatDispatchDuration, formatGitChanges, formatGitSnapshot, formatSpendUSD, formatSpent, formatTokenCount, formatUsageCost, formatUsageTokens, gitProbeAllowed, hiddenChildAgentsText, hiddenModelUsageText, hiddenTodoText, isTodoStatus, isValidSessionID, lastAssistantWithTokens, latestTodoItems, messageTokensTotal, modelRefID, modelUsageRowLines, modelUsageRowText, modelUsageRows, navigateToSession, openDispatchPanel, orderDispatchEntries, orderTodoItems, padCell, parseGitAheadBehind, parseGitStatusPorcelain, parsePresetOverrides, parseTodoItems, performDispatchPanelAction, presetFromEnv, presetHeaderLine, providerIDFromModels, providerIDFromRef, readGitSnapshot, resetSpendUnit, resolveActiveModelRef, resolveActivePresetForTui, resolveContextLimit, resolveModelContextSnapshot, resolvedSpendUnit, runDispatchPanelCommand, runningChildRowText, shortModelID, shortSessionID, sidebarMoneyLines, sidebarPlaceholder, sidebarTextLines, spendWindows, spinnerFrame, startOfLocalDay, statsCost, statsRangeMatches, toDelegationView, toDispatchEntry, todoRowText, todoTone, transcriptWindow, truncateLabel, turnTokensPerSecond, withBlockSpacers };
4596
-
4597
- //# sourceMappingURL=tui-v2.js.map