oc-flight-deck 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nathwn12
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # ✈ Flight Deck
2
+
3
+ **Live session telemetry for your OpenCode terminal.**
4
+
5
+ Your agent is spending money right now. Most of the time you find out afterwards.
6
+
7
+ Flight Deck puts the numbers where you're already looking — a quiet sidebar that
8
+ shows which model is running, what it's costing, how full the context is, and
9
+ whether your caching is actually working.
10
+
11
+ ```
12
+ ✈ FLIGHT DECK
13
+ ─────────────────
14
+ status ⠹ running
15
+ agent orchestrator
16
+ model deepseek-v4.1-flash · high
17
+ branch main
18
+ cost $0.226
19
+ total $0.247 · 2 subagents
20
+ project $1.48 · 12 sessions
21
+ tokens 533k in · 91k out
22
+ cache 98% hit · 32M read
23
+ context ██░░░░░░░░ 18%
24
+ elapsed 2h 14m
25
+ tps 106 tok/s
26
+ spark ▁▃▂▅█▄▃▂
27
+ ```
28
+
29
+ ## Install
30
+
31
+ ```jsonc
32
+ // opencode.jsonc
33
+ {
34
+ "plugins": ["oc-flight-deck"]
35
+ }
36
+ ```
37
+
38
+ Restart OpenCode. That's the whole setup — no config file, no options, nothing to
39
+ learn. The panel appears beside an open session and starts reading.
40
+
41
+ ## What you're looking at
42
+
43
+ | Row | Why it's there |
44
+ | --- | --- |
45
+ | `status` | A spinner while it works, a circle while it's waiting on you. |
46
+ | `agent` | Which agent you're actually talking to. |
47
+ | `model` | The model *and its variant* — `high` behaves differently. |
48
+ | `branch` | Which branch you're about to commit to. |
49
+ | `cost` | This session, so far. |
50
+ | `total` | **This session plus every subagent it spawned.** |
51
+ | `project` | Every session in this repo. |
52
+ | `tokens` | Input and output, cumulative. |
53
+ | `cache` | Hit rate first, because that's the number that explains the bill. |
54
+ | `context` | A gauge of how full the window is. |
55
+ | `perms` | Appears only when approvals are waiting on you. |
56
+ | `elapsed` | How long you've been at it. |
57
+ | `tps` | Output tokens per second, measured from the last completed turn. |
58
+ | `spark` | Recent turn sizes as a shape — you can see the expensive one. |
59
+
60
+ ### `total` is the row that matters
61
+
62
+ Subagents run as **separate sessions**, and a session's own cost does not include
63
+ them. On the session this was built against, the parent reported `$0.2246` while
64
+ the true spend was `$0.2447` — **9% low on money, and 54% low on input tokens**.
65
+ If you swarm, `total` is the number you actually spent.
66
+
67
+ ### `cache` is the row that surprises people
68
+
69
+ A 98% hit rate is why millions of tokens can cost cents. The moment that number
70
+ drops, your bill doesn't.
71
+
72
+ ## Configuration
73
+
74
+ **You don't need any.** Install it and the panel works. But every knob is
75
+ available in a commented JSONC file.
76
+
77
+ Copy [`flight-deck.example.jsonc`](./flight-deck.example.jsonc) to
78
+ `flight-deck.jsonc` at your project root, or to `.opencode/flight-deck.jsonc`,
79
+ then edit. Comments and trailing commas are fine.
80
+
81
+ ```jsonc
82
+ {
83
+ // Milliseconds between ticks. 0 turns the timer off entirely.
84
+ "refresh": 1000,
85
+
86
+ "sidebar": {
87
+ "enabled": true,
88
+ "lines": ["✈ FLIGHT DECK", "─────────────────"],
89
+ // Any rows, any order. Delete whatever you don't want.
90
+ "rows": [
91
+ "status", "agent", "model", "branch", "cost", "total", "project",
92
+ "tokens", "cache", "context", "perms", "elapsed", "tps", "spark"
93
+ ]
94
+ },
95
+
96
+ "footer": {
97
+ // Off by default — the sidebar already carries the data.
98
+ "enabled": false,
99
+ "text": "Flight Deck"
100
+ }
101
+ }
102
+ ```
103
+
104
+ The example file documents every row and every option inline. A typo is never
105
+ fatal: the bad value is ignored, the default comes back, and you get a one-time
106
+ toast naming the key to fix.
107
+
108
+ ## It reads. It never writes.
109
+
110
+ Flight Deck shows what OpenCode already knows.
111
+
112
+ - **No network calls.** Nothing is fetched, nothing is sent.
113
+ - **No telemetry.** Nothing is collected or phoned home.
114
+ - **No storage.** Nothing is written to disk.
115
+ - **No polling loop** by default — cost, tokens, and permissions update from the
116
+ host's own events. The ticker exists only so clock-derived rows like `elapsed`
117
+ keep moving, and `"refresh": 0` removes it completely.
118
+ - **Theme-native.** Every line uses your active theme's text tokens, so it blends
119
+ with whatever look you already run.
120
+
121
+ Delete the plugin and the stock sidebar is back, exactly as it was.
122
+
123
+ ## Uninstall
124
+
125
+ Remove the entry from `opencode.jsonc`, restart, done. Delete your
126
+ `flight-deck.jsonc` too if you made one.
127
+
128
+ ## Development
129
+
130
+ ```sh
131
+ bun install
132
+ bun run check
133
+ ```
134
+
135
+ `bun run check` typechecks and runs the suite, including headless OpenTUI render
136
+ tests that mount the panel in a real renderer and assert the exact characters
137
+ that come out. A guard test parses the shipped example config and asserts it
138
+ still matches the real defaults, so the documentation can't drift from the code.
139
+
140
+ Built on the official
141
+ [OpenCode V2 CLI plugin API](https://opencode.ai/v2/docs/build/plugins/cli).
142
+
143
+ ## Compatibility
144
+
145
+ The OpenCode plugin API is still in beta. This release targets
146
+ `@opencode/plugin` beta `0.0.0-beta-19425`; pin a host version you've tested.
147
+
148
+ Requires OpenCode V2 (`opencode2`). Building from source needs Bun 1.4+ or
149
+ Node 22+.
150
+
151
+ ## License
152
+
153
+ MIT © 2026 nathwn12 — free to use, modify, and share.
@@ -0,0 +1,95 @@
1
+ {
2
+ // ═════════════════════════════════════════════════════════════════════════
3
+ // ✈ Flight Deck — configuration
4
+ //
5
+ // EVERYTHING HERE IS OPTIONAL. Install the plugin and the panel works with
6
+ // no config file at all. The values below are the defaults, written out so
7
+ // you can see exactly what there is to change. Delete any key and its
8
+ // default comes straight back.
9
+ //
10
+ // TO USE IT: copy this file to `flight-deck.jsonc` at your project root, or
11
+ // to `.opencode/flight-deck.jsonc`. Comments and trailing commas are fine.
12
+ //
13
+ // Flight Deck looks in this order and uses the first file it finds:
14
+ // .opencode/flight-deck.jsonc .opencode/flight-deck.json
15
+ // flight-deck.jsonc flight-deck.json
16
+ //
17
+ // The same values can also be passed as plugin options in opencode.jsonc /
18
+ // cli.json, which take precedence on hosts that forward them.
19
+ // ═════════════════════════════════════════════════════════════════════════
20
+
21
+ // ── Update cadence ───────────────────────────────────────────────────────
22
+ // Milliseconds between refreshes.
23
+ //
24
+ // Cost, tokens, and permissions arrive from the host's own events, so they
25
+ // stay current with no timer at all. Only clock-derived rows need one, and
26
+ // `elapsed` is the reason this exists — without a tick it would sit frozen
27
+ // between turns.
28
+ //
29
+ // 1000 default — a smooth tick, negligible cost
30
+ // 0 no timer; `elapsed` only moves when the session does
31
+ // 5000 calmer, still live enough for a wall-clock row
32
+ "refresh": 1000,
33
+
34
+ // ── Sidebar ──────────────────────────────────────────────────────────────
35
+ "sidebar": {
36
+ // false hides the whole panel.
37
+ "enabled": true,
38
+
39
+ // Fixed lines, rendered above the live rows. This is the only text Flight
40
+ // Deck shows of its own — put your own words here, or a rule.
41
+ // The first line uses your theme's primary text colour; the rest use the
42
+ // subdued colour.
43
+ "lines": ["✈ FLIGHT DECK", "─────────────────"],
44
+
45
+ // The live rows, top to bottom. Every value is read from the open session,
46
+ // so you never type these in. Delete any row you don't want, or reorder
47
+ // them freely — an unknown name is ignored with a one-time warning, so a
48
+ // typo can never break the panel.
49
+ //
50
+ // status running or idle — the glyph animates while it works
51
+ // agent which agent is running (orchestrator, build, plan, ...)
52
+ // model model id, plus the variant when there is one
53
+ // branch current git branch
54
+ // cost what this session has cost so far
55
+ // total this session plus all its subagents (hidden until one runs)
56
+ // project every session in this repo, not just the one on screen
57
+ // tokens this session's input and output tokens
58
+ // cache cache hit rate, then cache reads
59
+ // context a gauge of how full the context window is
60
+ // perms approval requests waiting (only shown when there are some)
61
+ // elapsed wall-clock time since the session started
62
+ // tps output tokens per second on the last completed turn
63
+ // spark recent turn sizes as a sparkline
64
+ // reasoning reasoning tokens, when the model emits them
65
+ // turns number of messages in the session
66
+ "rows": [
67
+ "status",
68
+ "agent",
69
+ "model",
70
+ "branch",
71
+ "cost",
72
+ "total",
73
+ "project",
74
+ "tokens",
75
+ "cache",
76
+ "context",
77
+ "perms",
78
+ "elapsed",
79
+ "tps",
80
+ "spark"
81
+ ]
82
+ },
83
+
84
+ // ── Footer ───────────────────────────────────────────────────────────────
85
+ // Off by default: the sidebar already carries the data, and the prompt
86
+ // footer is high-traffic space, so a line there should earn its place.
87
+ //
88
+ // Writing ANY footer setting turns it on — `"footer": { "text": "hi" }` is
89
+ // enough. Set "enabled": false explicitly to keep it hidden.
90
+ "footer": {
91
+ "enabled": false,
92
+ // Any single line. Empty text is ignored.
93
+ "text": "Flight Deck"
94
+ }
95
+ }
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "oc-flight-deck",
3
+ "version": "0.1.0",
4
+ "description": "Live OpenCode V2 session telemetry — agent, model, branch, cost, tokens, cache hit rate and context usage in your sidebar.",
5
+ "keywords": [
6
+ "opencode",
7
+ "opencode-plugin",
8
+ "opencode-tui",
9
+ "tui",
10
+ "cli",
11
+ "sidebar",
12
+ "telemetry",
13
+ "cost"
14
+ ],
15
+ "license": "MIT",
16
+ "author": "nathwn12",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/nathwn12/oc-flight-deck.git"
20
+ },
21
+ "homepage": "https://github.com/nathwn12/oc-flight-deck#readme",
22
+ "bugs": {
23
+ "url": "https://github.com/nathwn12/oc-flight-deck/issues"
24
+ },
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./src/index.ts",
29
+ "import": "./src/index.ts"
30
+ },
31
+ "./tui": {
32
+ "types": "./src/tui/index.tsx",
33
+ "import": "./src/tui/index.tsx"
34
+ }
35
+ },
36
+ "files": [
37
+ "src",
38
+ "flight-deck.example.jsonc",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "engines": {
43
+ "node": ">=22",
44
+ "bun": ">=1.4.0"
45
+ },
46
+ "scripts": {
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "bun test",
49
+ "check": "bun run typecheck && bun test"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "dependencies": {
55
+ "@opencode/plugin": "0.0.0-beta-19425"
56
+ },
57
+ "devDependencies": {
58
+ "@opentui/core": "0.5.10",
59
+ "@opentui/solid": "0.5.10",
60
+ "@types/bun": "^1.4.2",
61
+ "solid-js": "1.9.15",
62
+ "typescript": "^5.9.0"
63
+ },
64
+ "peerDependencies": {
65
+ "@opentui/core": ">=0.5.10",
66
+ "@opentui/solid": ">=0.5.10",
67
+ "solid-js": ">=1.9.0"
68
+ },
69
+ "peerDependenciesMeta": {
70
+ "@opentui/core": { "optional": true },
71
+ "@opentui/solid": { "optional": true },
72
+ "solid-js": { "optional": true }
73
+ }
74
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+
3
+ // OpenCode loads the package root from opencode.jsonc and discovers the
4
+ // separate ./tui export for the terminal UI. This server-side compatibility
5
+ // entrypoint is deliberately inert: all visible behavior lives in src/tui.
6
+ export default Plugin.define({
7
+ id: "flight-deck.host",
8
+ setup() {},
9
+ });
@@ -0,0 +1,321 @@
1
+ // Configuration model for the cosmetic Flight Deck rail.
2
+ //
3
+ // Options arrive from the host through `context.options` — the `options` object
4
+ // on a plugin entry in `opencode.jsonc` / `cli.json`:
5
+ //
6
+ // { "plugins": [{ "package": "oc-flight-deck", "options": { ... } }] }
7
+ //
8
+ // Everything is optional. Missing or invalid values fall back to the sane
9
+ // defaults below, so the rail always renders and a typo can never break the TUI.
10
+
11
+ import { isStatField, STAT_FIELDS } from "./stats.js";
12
+
13
+ export interface SidebarConfig {
14
+ /** Show the sidebar rail. Default `true`. */
15
+ readonly enabled: boolean;
16
+ /** Fixed lines rendered above the live rows. Default `DEFAULT_SIDEBAR_LINES`. */
17
+ readonly lines: readonly string[];
18
+ /** Live session fields to render, top to bottom. Default `DEFAULT_SIDEBAR_ROWS`. */
19
+ readonly rows: readonly string[];
20
+ }
21
+
22
+ export interface FooterConfig {
23
+ /**
24
+ * Show the prompt-footer rail. Default `false`.
25
+ *
26
+ * Off by default on purpose: the prompt footer is prime real estate and the
27
+ * sidebar already carries the data, so a line that only restates the plugin's
28
+ * name is decoration. Turn it on for a one-line reminder or a custom label.
29
+ */
30
+ readonly enabled: boolean;
31
+ /** Footer text. Default `DEFAULT_FOOTER_TEXT`. */
32
+ readonly text: string;
33
+ }
34
+
35
+ export interface FlightDeckConfig {
36
+ readonly sidebar: SidebarConfig;
37
+ readonly footer: FooterConfig;
38
+ /**
39
+ * Update cadence in milliseconds for time-derived rows.
40
+ *
41
+ * Cost and tokens arrive with events, so they stay current without a timer.
42
+ * Anything derived from the clock — `elapsed` especially — has nothing to
43
+ * react to, so it needs a tick. `0` turns the ticker off entirely.
44
+ */
45
+ readonly refresh: number;
46
+ }
47
+
48
+ /**
49
+ * Fixed lines shown above the live rows — branding only.
50
+ *
51
+ * The rail exists to show session state, so nothing here is filler: there is no
52
+ * placeholder text to delete before it looks finished.
53
+ */
54
+ export const DEFAULT_SIDEBAR_LINES: readonly string[] = [
55
+ "✈ FLIGHT DECK",
56
+ "─────────────────",
57
+ ];
58
+
59
+ /**
60
+ * Live fields shown by default, in reading order.
61
+ *
62
+ * Every one of these is read from the open session at render time, so a fresh
63
+ * install shows real numbers with no configuration file at all.
64
+ */
65
+ export const DEFAULT_SIDEBAR_ROWS: readonly string[] = [
66
+ "status",
67
+ "agent",
68
+ "model",
69
+ "branch",
70
+ "cost",
71
+ "total",
72
+ "project",
73
+ "tokens",
74
+ "cache",
75
+ "context",
76
+ "perms",
77
+ "elapsed",
78
+ "tps",
79
+ "spark",
80
+ ];
81
+
82
+ /** One tick a second: enough for the clock-derived rows, cheap enough to ignore. */
83
+ export const DEFAULT_REFRESH_MS = 1_000;
84
+
85
+ /** A tick slower than once a minute is indistinguishable from no ticker. */
86
+ const MAX_REFRESH_MS = 60_000;
87
+
88
+ export const DEFAULT_FOOTER_TEXT = "Flight Deck";
89
+
90
+ export const DEFAULT_CONFIG: FlightDeckConfig = {
91
+ sidebar: { enabled: true, lines: DEFAULT_SIDEBAR_LINES, rows: DEFAULT_SIDEBAR_ROWS },
92
+ footer: { enabled: false, text: DEFAULT_FOOTER_TEXT },
93
+ refresh: DEFAULT_REFRESH_MS,
94
+ };
95
+
96
+ /** Layout guards: keep a hand-edited config from producing an unusable rail. */
97
+ export const MAX_LINES = 24;
98
+ const MAX_LINE_LENGTH = 120;
99
+
100
+ // Rails render on a single line, so control characters are replaced with
101
+ // spaces rather than being passed to the renderer.
102
+ const CONTROL_CHAR = /[\u0000-\u001F\u007F-\u009F]/;
103
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/g;
104
+
105
+ function normalizeText(value: string, path: string, issues: string[]): string {
106
+ if (!CONTROL_CHAR.test(value)) return value.trim();
107
+ issues.push(`${path} contained control characters; they were replaced with spaces`);
108
+ return value.replace(CONTROL_CHARS, " ").replace(/ {2,}/g, " ").trim();
109
+ }
110
+
111
+ export interface ConfigResolution {
112
+ readonly config: FlightDeckConfig;
113
+ /** Human-readable problems found in the supplied options; empty when clean. */
114
+ readonly issues: readonly string[];
115
+ }
116
+
117
+ function isRecord(value: unknown): value is Record<string, unknown> {
118
+ return typeof value === "object" && value !== null && !Array.isArray(value);
119
+ }
120
+
121
+ function readBoolean(value: unknown, fallback: boolean, path: string, issues: string[]): boolean {
122
+ if (value === undefined) return fallback;
123
+ if (typeof value === "boolean") return value;
124
+ issues.push(`${path} must be true or false; using ${fallback}`);
125
+ return fallback;
126
+ }
127
+
128
+ function readText(value: unknown, fallback: string, path: string, issues: string[]): string {
129
+ if (value === undefined) return fallback;
130
+ if (typeof value !== "string") {
131
+ issues.push(`${path} must be a string; using the default`);
132
+ return fallback;
133
+ }
134
+ const text = normalizeText(value, path, issues);
135
+ if (text.length === 0) {
136
+ issues.push(`${path} must not be empty; using the default`);
137
+ return fallback;
138
+ }
139
+ if (text.length > MAX_LINE_LENGTH) {
140
+ issues.push(`${path} was longer than ${MAX_LINE_LENGTH} characters; it was shortened`);
141
+ return text.slice(0, MAX_LINE_LENGTH);
142
+ }
143
+ return text;
144
+ }
145
+
146
+ function readLines(value: unknown, issues: string[]): readonly string[] {
147
+ if (value === undefined) return DEFAULT_SIDEBAR_LINES;
148
+ if (!Array.isArray(value) || value.length === 0) {
149
+ issues.push("sidebar.lines must be a non-empty array of strings; using the default lines");
150
+ return DEFAULT_SIDEBAR_LINES;
151
+ }
152
+
153
+ const lines: string[] = [];
154
+ value.forEach((entry, index) => {
155
+ const path = `sidebar.lines[${index}]`;
156
+ if (typeof entry !== "string") {
157
+ issues.push(`${path} must be a string; skipping it`);
158
+ return;
159
+ }
160
+ const text = normalizeText(entry, path, issues);
161
+ if (text.length === 0) {
162
+ issues.push(`${path} is empty; skipping it`);
163
+ return;
164
+ }
165
+ if (text.length > MAX_LINE_LENGTH) {
166
+ issues.push(`${path} was longer than ${MAX_LINE_LENGTH} characters; it was shortened`);
167
+ lines.push(text.slice(0, MAX_LINE_LENGTH));
168
+ return;
169
+ }
170
+ lines.push(text);
171
+ });
172
+
173
+ if (lines.length === 0) {
174
+ issues.push("sidebar.lines had no usable entries; using the default lines");
175
+ return DEFAULT_SIDEBAR_LINES;
176
+ }
177
+ if (lines.length > MAX_LINES) {
178
+ issues.push(`sidebar.lines has ${lines.length} entries; keeping the first ${MAX_LINES}`);
179
+ return lines.slice(0, MAX_LINES);
180
+ }
181
+ return lines;
182
+ }
183
+
184
+ /**
185
+ * Read the list of live fields to render.
186
+ *
187
+ * An unknown name is reported rather than silently dropped: otherwise a typo in
188
+ * `sidebar.rows` looks identical to the host simply not having the data yet.
189
+ */
190
+ function readRows(value: unknown, issues: string[]): readonly string[] {
191
+ if (value === undefined) return DEFAULT_SIDEBAR_ROWS;
192
+ if (!Array.isArray(value) || value.length === 0) {
193
+ issues.push("sidebar.rows must be a non-empty array of field names; using the default rows");
194
+ return DEFAULT_SIDEBAR_ROWS;
195
+ }
196
+
197
+ const rows: string[] = [];
198
+ value.forEach((entry, index) => {
199
+ const path = `sidebar.rows[${index}]`;
200
+ if (typeof entry !== "string") {
201
+ issues.push(`${path} must be a string; skipping it`);
202
+ return;
203
+ }
204
+ const name = entry.trim().toLowerCase();
205
+ if (!isStatField(name)) {
206
+ issues.push(`${path} is not a known field (${STAT_FIELDS.join(", ")}); skipping it`);
207
+ return;
208
+ }
209
+ rows.push(name);
210
+ });
211
+
212
+ if (rows.length === 0) {
213
+ issues.push("sidebar.rows had no usable entries; using the default rows");
214
+ return DEFAULT_SIDEBAR_ROWS;
215
+ }
216
+ return rows.slice(0, MAX_LINES);
217
+ }
218
+
219
+ function sectionOf(options: Record<string, unknown>, key: "sidebar" | "footer"): Record<string, unknown> {
220
+ const value = options[key];
221
+ return isRecord(value) ? value : {};
222
+ }
223
+
224
+ /**
225
+ * Read the ticker cadence.
226
+ *
227
+ * `0` is a deliberate value meaning "no ticker", so it must not be treated as a
228
+ * missing setting.
229
+ */
230
+ function readRefresh(value: unknown, issues: string[]): number {
231
+ if (value === undefined) return DEFAULT_REFRESH_MS;
232
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
233
+ issues.push("refresh must be a number of milliseconds; using the default");
234
+ return DEFAULT_REFRESH_MS;
235
+ }
236
+ if (value > MAX_REFRESH_MS) {
237
+ issues.push(`refresh was longer than ${MAX_REFRESH_MS}ms; using ${MAX_REFRESH_MS}`);
238
+ return MAX_REFRESH_MS;
239
+ }
240
+ return value;
241
+ }
242
+
243
+ function mergeSection(file: Record<string, unknown>, host: Record<string, unknown>, key: "sidebar" | "footer"): unknown {
244
+ const fileValue = file[key];
245
+ const hostValue = host[key];
246
+ // A malformed section from either source replaces the other and is reported
247
+ // by resolveConfig, so the problem stays visible instead of being masked by
248
+ // silently preferring the valid side.
249
+ if (hostValue !== undefined && !isRecord(hostValue)) return hostValue;
250
+ if (fileValue !== undefined && !isRecord(fileValue) && hostValue === undefined) return fileValue;
251
+ return { ...sectionOf(file, key), ...sectionOf(host, key) };
252
+ }
253
+
254
+ /**
255
+ * Merge the plugin's own config file with host-supplied options.
256
+ *
257
+ * Precedence is the host's `context.options` over the file, decided key by key,
258
+ * so an installed host can override a single value without restating the rest.
259
+ */
260
+ export function mergeOptions(fileOptions: unknown, hostOptions: unknown): Record<string, unknown> {
261
+ const file = isRecord(fileOptions) ? fileOptions : {};
262
+ const host = isRecord(hostOptions) ? hostOptions : {};
263
+ return {
264
+ ...file,
265
+ ...host,
266
+ sidebar: mergeSection(file, host, "sidebar"),
267
+ footer: mergeSection(file, host, "footer"),
268
+ };
269
+ }
270
+
271
+ /**
272
+ * Turn raw, untrusted `context.options` into a complete config.
273
+ *
274
+ * Unknown keys are ignored (forward compatible), known keys are validated, and
275
+ * any problem is both corrected and reported in `issues` so the plugin can warn
276
+ * once instead of rendering a broken rail.
277
+ */
278
+ export function resolveConfig(options: unknown): ConfigResolution {
279
+ const issues: string[] = [];
280
+
281
+ if (options === undefined || options === null) {
282
+ return { config: DEFAULT_CONFIG, issues };
283
+ }
284
+ if (!isRecord(options)) {
285
+ issues.push("plugin options must be an object; using defaults");
286
+ return { config: DEFAULT_CONFIG, issues };
287
+ }
288
+
289
+ const rawSidebar = options.sidebar;
290
+ const rawFooter = options.footer;
291
+ if (rawSidebar !== undefined && !isRecord(rawSidebar)) {
292
+ issues.push("sidebar must be an object; using defaults");
293
+ }
294
+ if (rawFooter !== undefined && !isRecord(rawFooter)) {
295
+ issues.push("footer must be an object; using defaults");
296
+ }
297
+
298
+ const sidebar = isRecord(rawSidebar) ? rawSidebar : {};
299
+ const footer = isRecord(rawFooter) ? rawFooter : {};
300
+
301
+ // Writing any footer setting counts as asking for the footer, so the rail
302
+ // turns on as soon as you configure it. It is off only when you said nothing
303
+ // about it, and an explicit `enabled` always wins either way.
304
+ const footerConfigured = Object.keys(footer).length > 0;
305
+
306
+ return {
307
+ config: {
308
+ sidebar: {
309
+ enabled: readBoolean(sidebar.enabled, DEFAULT_CONFIG.sidebar.enabled, "sidebar.enabled", issues),
310
+ lines: readLines(sidebar.lines, issues),
311
+ rows: readRows(sidebar.rows, issues),
312
+ },
313
+ footer: {
314
+ enabled: readBoolean(footer.enabled, footerConfigured, "footer.enabled", issues),
315
+ text: readText(footer.text, DEFAULT_CONFIG.footer.text, "footer.text", issues),
316
+ },
317
+ refresh: readRefresh(options.refresh, issues),
318
+ },
319
+ issues,
320
+ };
321
+ }
@@ -0,0 +1,81 @@
1
+ // Reads Flight Deck's own config file.
2
+ //
3
+ // The host's `context.options` is the official configuration channel, but not
4
+ // every host build forwards it (and `cli.json` may not allow comments). So the
5
+ // plugin also reads a small JSONC file from the project, which guarantees
6
+ // inline comments work everywhere. `context.options` still wins when present.
7
+
8
+ import { existsSync, readFileSync, statSync } from "node:fs";
9
+ import { join } from "node:path";
10
+
11
+ /** Searched in order, relative to the project directory; first hit wins. */
12
+ export const CONFIG_FILE_CANDIDATES: readonly string[] = [
13
+ join(".opencode", "flight-deck.jsonc"),
14
+ join(".opencode", "flight-deck.json"),
15
+ "flight-deck.jsonc",
16
+ "flight-deck.json",
17
+ ];
18
+
19
+ /** Refuse to pull an unreasonable file into the TUI at startup. */
20
+ const MAX_CONFIG_BYTES = 64 * 1024;
21
+
22
+ export interface FileConfig {
23
+ /** Parsed file contents, or undefined when no config file was found. */
24
+ readonly options: unknown;
25
+ /** Path of the file that was read, when one was. */
26
+ readonly source?: string;
27
+ /** Set when a file was found but was empty, unreadable, or unusable. */
28
+ readonly issue?: string;
29
+ }
30
+
31
+ export function findConfigFile(directory: string): string | undefined {
32
+ for (const candidate of CONFIG_FILE_CANDIDATES) {
33
+ const path = join(directory, candidate);
34
+ if (existsSync(path)) return path;
35
+ }
36
+ return undefined;
37
+ }
38
+
39
+ export function parseJsonc(text: string): unknown {
40
+ // Bun parses comments and trailing commas. Under a runtime without it we fall
41
+ // back to strict JSON and let the caller report the parse failure.
42
+ const jsonc = (globalThis as { Bun?: { JSONC?: { parse?: (value: string) => unknown } } }).Bun?.JSONC;
43
+ if (typeof jsonc?.parse === "function") return jsonc.parse(text);
44
+ return JSON.parse(text);
45
+ }
46
+
47
+ /**
48
+ * Load the first config file that exists under `directory`.
49
+ *
50
+ * A missing file is normal and silent. A present-but-broken file is reported in
51
+ * `issue` so the caller can warn once, and then behaves as if it were absent.
52
+ * Only regular files under the size cap are read.
53
+ */
54
+ export function loadConfigFile(directory: string): FileConfig {
55
+ const source = findConfigFile(directory);
56
+ if (source === undefined) return { options: undefined };
57
+
58
+ try {
59
+ const stats = statSync(source);
60
+ if (!stats.isFile()) {
61
+ return { options: undefined, source, issue: `${source} is not a regular file; using defaults` };
62
+ }
63
+ if (stats.size > MAX_CONFIG_BYTES) {
64
+ const limit = Math.floor(MAX_CONFIG_BYTES / 1024);
65
+ return { options: undefined, source, issue: `${source} is larger than ${limit} KiB; using defaults` };
66
+ }
67
+
68
+ const text = readFileSync(source, "utf8");
69
+ if (text.trim().length === 0) {
70
+ return { options: undefined, source, issue: `${source} is empty; using defaults` };
71
+ }
72
+ const parsed: unknown = parseJsonc(text);
73
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
74
+ return { options: undefined, source, issue: `${source} must contain a JSON object; using defaults` };
75
+ }
76
+ return { options: parsed, source };
77
+ } catch (error) {
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ return { options: undefined, source, issue: `${source} could not be parsed (${message}); using defaults` };
80
+ }
81
+ }
@@ -0,0 +1,268 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { Plugin } from "@opencode/plugin/tui";
3
+ import { createSignal } from "solid-js";
4
+ import { mergeOptions, resolveConfig } from "./config.js";
5
+ import { loadConfigFile } from "./file-config.js";
6
+ import { footerLine, liveRowOffset, sidebarLines } from "./presentation.js";
7
+ import type { StatSource } from "./stats.js";
8
+
9
+ // Flight Deck is a read-only instrument panel for the OpenCode V2 CLI/TUI. It
10
+ // shows the open session's agent, model, branch, cost, tokens, and cache hit
11
+ // rate in the sidebar. It uses only the official CLI plugin boundary —
12
+ // `@opencode/plugin/tui`, `context.ui.slot`, and theme tokens.
13
+ //
14
+ // Read-only by construction: it never writes, requests, stores, subscribes, or
15
+ // polls. Everything it shows is state the host already holds in memory.
16
+ //
17
+ // Appearance comes from, in order of precedence:
18
+ // 1. `context.options` — the host's plugin options, when the host forwards them
19
+ // 2. `flight-deck.jsonc` (or `.opencode/flight-deck.jsonc`) in the project
20
+ // 3. the sane defaults in ./config.ts
21
+ // See flight-deck.example.jsonc for the commented template.
22
+
23
+ type SessionLike = { cost?: unknown; model?: unknown; time?: unknown };
24
+
25
+ function asCount(value: unknown): number | undefined {
26
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
27
+ }
28
+
29
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
30
+ return typeof value === "object" && value !== null && !Array.isArray(value)
31
+ ? (value as Record<string, unknown>)
32
+ : undefined;
33
+ }
34
+
35
+ export default Plugin.define({
36
+ id: "flight-deck-tui",
37
+ setup(context) {
38
+ const directory = context.location?.directory ?? process.cwd();
39
+ const file = loadConfigFile(directory);
40
+ const { config, issues } = resolveConfig(mergeOptions(file.options, context.options));
41
+
42
+ if (file.issue !== undefined && file.source !== undefined) {
43
+ console.warn(`[flight-deck] ${file.issue}`);
44
+ }
45
+ const problems = file.issue !== undefined ? [file.issue, ...issues] : issues;
46
+ if (problems.length > 0) {
47
+ const extra = problems.length > 1 ? ` (+${problems.length - 1} more)` : "";
48
+ context.ui.toast.show({
49
+ title: "Flight Deck",
50
+ message: `Ignoring invalid config: ${problems[0]}${extra}`,
51
+ variant: "warning",
52
+ });
53
+ }
54
+
55
+ const footer = footerLine(config);
56
+ const releases: Array<() => void> = [];
57
+
58
+ // The host owns these caches; a failure to read one must never break the
59
+ // rail, so every lookup degrades to "no data" instead of throwing.
60
+ const messagesOf = (sessionID: string): readonly unknown[] => {
61
+ try {
62
+ return context.data.session.message.list(sessionID) ?? [];
63
+ } catch {
64
+ return [];
65
+ }
66
+ };
67
+
68
+ // Subagent sessions are separate sessions, and the parent's `cost` does not
69
+ // include them, so a bare `cost` row understates a swarm. Sum the family.
70
+ const treeTotals = (sessionID: string, ownCost: unknown) => {
71
+ let ids: readonly string[];
72
+ try {
73
+ ids = context.data.session.family(sessionID) ?? [sessionID];
74
+ } catch {
75
+ return undefined;
76
+ }
77
+ if (ids.length <= 1) return undefined;
78
+
79
+ let cost = asCount(ownCost) ?? 0;
80
+ let count = 0;
81
+ for (const id of ids) {
82
+ if (id === sessionID) continue;
83
+ const child = context.data.session.get(id) as SessionLike | undefined;
84
+ if (child === undefined) continue;
85
+ count += 1;
86
+ cost += asCount(child.cost) ?? 0;
87
+ }
88
+ return count === 0 ? undefined : { cost, count };
89
+ };
90
+
91
+ // A message's own totals are per-request, so the last assistant message's
92
+ // prompt size *is* the current context occupancy — not a running total.
93
+ const contextUsage = (sessionID: string, model: unknown) => {
94
+ const messages = messagesOf(sessionID);
95
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
96
+ const tokens = asRecord(asRecord(messages[index])?.tokens);
97
+ const input = asCount(tokens?.input);
98
+ if (tokens === undefined || input === undefined) continue;
99
+ const cache = asRecord(tokens.cache);
100
+ const used = input + (asCount(cache?.read) ?? 0) + (asCount(cache?.write) ?? 0);
101
+ if (used === 0) return undefined;
102
+ return { used, limit: contextLimit(model) };
103
+ }
104
+ return undefined;
105
+ };
106
+
107
+ // The window lives at `limit.context` on the catalog entry, and two
108
+ // providers can expose the same model id with different windows — so the
109
+ // provider has to match too, or the gauge would read the wrong ceiling.
110
+ const contextLimit = (model: unknown): number | undefined => {
111
+ const ref = asRecord(model);
112
+ const id = ref?.id;
113
+ const providerID = ref?.providerID;
114
+ if (typeof id !== "string") return undefined;
115
+ try {
116
+ const location = context.location ?? context.data.location.default();
117
+ for (const entry of context.data.location.model.list(location) ?? []) {
118
+ const record = asRecord(entry);
119
+ if (record === undefined || record.id !== id) continue;
120
+ if (typeof providerID === "string" && record.providerID !== providerID) continue;
121
+ const limit = asRecord(record.limit);
122
+ return asCount(limit?.context) ?? asCount(record.context) ?? asCount(record.contextWindow);
123
+ }
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ return undefined;
128
+ };
129
+
130
+ // Measured against the clock rather than the session's last update, so the
131
+ // row keeps moving between events instead of freezing between turns.
132
+ const sessionElapsed = (session: SessionLike | undefined): number | undefined => {
133
+ const created = asCount(asRecord(session?.time)?.created);
134
+ if (created === undefined) return undefined;
135
+ const elapsed = Date.now() - created;
136
+ return elapsed <= 0 ? undefined : elapsed;
137
+ };
138
+
139
+ // Project spend: every session the host knows about here, not just the one
140
+ // on screen. Answers "what has this repo cost me", not "this conversation".
141
+ const projectTotals = () => {
142
+ try {
143
+ const sessions = context.data.session.list() ?? [];
144
+ let cost = 0;
145
+ for (const entry of sessions) cost += asCount(asRecord(entry)?.cost) ?? 0;
146
+ return { cost, count: sessions.length };
147
+ } catch {
148
+ return undefined;
149
+ }
150
+ };
151
+
152
+ const statusOf = (sessionID: string): string | undefined => {
153
+ try {
154
+ return context.data.session.status(sessionID);
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ };
159
+
160
+ const permsOf = (sessionID: string): number | undefined => {
161
+ try {
162
+ return context.data.session.permission.list(sessionID)?.length;
163
+ } catch {
164
+ return undefined;
165
+ }
166
+ };
167
+
168
+ // Throughput of the last completed turn. The host records when streaming
169
+ // finished, so this is measured rather than estimated from wall-clock.
170
+ const lastTps = (sessionID: string): number | undefined => {
171
+ const messages = messagesOf(sessionID);
172
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
173
+ const message = asRecord(messages[index]);
174
+ const tokens = asRecord(message?.tokens);
175
+ const output = asCount(tokens?.output);
176
+ const time = asRecord(message?.time);
177
+ const created = asCount(time?.created);
178
+ const streamed = asCount(time?.streamed);
179
+ if (output === undefined || created === undefined || streamed === undefined) continue;
180
+ const duration = streamed - created;
181
+ if (duration <= 0) continue;
182
+ return output / (duration / 1_000);
183
+ }
184
+ return undefined;
185
+ };
186
+
187
+ // Recent turn sizes, oldest first. Drawn from messages the host already
188
+ // holds, so the sparkline needs no history of our own to accumulate.
189
+ const sparkValues = (sessionID: string): readonly number[] => {
190
+ const sizes: number[] = [];
191
+ for (const entry of messagesOf(sessionID)) {
192
+ const message = asRecord(entry);
193
+ if (message?.type !== "assistant") continue;
194
+ const output = asCount(asRecord(message.tokens)?.output);
195
+ if (output === undefined) continue;
196
+ sizes.push(output);
197
+ }
198
+ return sizes.slice(-12);
199
+ };
200
+
201
+ // A ticker exists only for clock-derived rows; everything else updates from
202
+ // the host's own events. `refresh: 0` opts out of it entirely.
203
+ const [frame, setFrame] = createSignal(0);
204
+ const timer =
205
+ config.refresh > 0 ? setInterval(() => setFrame((value) => value + 1), config.refresh) : undefined;
206
+
207
+ // Read session state inside the render so the rail stays live: cost and
208
+ // tokens climb as the session runs, and the branch appears once VCS
209
+ // resolves. Nothing here writes, requests, or leaves the process.
210
+ const snapshot = (sessionID: string): StatSource => {
211
+ const location = context.location ?? context.data.location.default();
212
+ const session = context.data.session.get(sessionID) as SessionLike | undefined;
213
+ const turns = messagesOf(sessionID).length;
214
+
215
+ return {
216
+ ...session,
217
+ branch: context.data.location.vcs.info(location)?.branch?.current,
218
+ tree: treeTotals(sessionID, session?.cost),
219
+ context: contextUsage(sessionID, session?.model),
220
+ project: projectTotals(),
221
+ status: statusOf(sessionID),
222
+ perms: permsOf(sessionID),
223
+ tps: lastTps(sessionID),
224
+ spark: sparkValues(sessionID),
225
+ elapsedMs: sessionElapsed(session),
226
+ turns,
227
+ // Read the tick so the slot re-runs each frame.
228
+ frame: frame(),
229
+ };
230
+ };
231
+
232
+ if (config.sidebar.enabled) {
233
+ releases.push(
234
+ context.ui.slot({
235
+ append: "sidebar.content",
236
+ render: ({ sessionID }) => {
237
+ const lines = sidebarLines(config, snapshot(sessionID));
238
+ if (lines.length === 0) return null;
239
+ const offset = Math.min(liveRowOffset(config), lines.length);
240
+ return (
241
+ // No padding here: the host already lays out and pads the sidebar,
242
+ // so adding our own would push the rows out of alignment with it.
243
+ <box flexDirection="column">
244
+ {lines.map((line, index) => (
245
+ <text fg={index < offset ? context.theme.text.default : context.theme.text.subdued}>{line}</text>
246
+ ))}
247
+ </box>
248
+ );
249
+ },
250
+ }),
251
+ );
252
+ }
253
+
254
+ if (footer !== undefined) {
255
+ releases.push(
256
+ context.ui.slot({
257
+ append: "prompt.footer.status",
258
+ render: () => <text fg={context.theme.text.subdued}>{footer}</text>,
259
+ }),
260
+ );
261
+ }
262
+
263
+ return () => {
264
+ if (timer !== undefined) clearInterval(timer);
265
+ for (const release of releases) release();
266
+ };
267
+ },
268
+ });
@@ -0,0 +1,32 @@
1
+ // Plain-string views of the Flight Deck rail.
2
+ //
3
+ // Keeping the text layer pure makes it trivial to test, and leaves the JSX in
4
+ // index.tsx to do nothing but wrap these strings in themed <text> elements.
5
+ // The live rows come from ./stats.ts and are read-only: nothing here mutates
6
+ // session state, and nothing leaves the process.
7
+
8
+ import type { FlightDeckConfig } from "./config.js";
9
+ import { MAX_LINES } from "./config.js";
10
+ import { statRows, type StatSource } from "./stats.js";
11
+
12
+ /**
13
+ * Sidebar lines to render, or an empty list when the sidebar rail is disabled.
14
+ *
15
+ * Configured `lines` render first (branding, separators, any fixed text), then
16
+ * the live rows named by `sidebar.rows`, each included only once the host has
17
+ * data for it.
18
+ */
19
+ export function sidebarLines(config: FlightDeckConfig, source: StatSource = {}): readonly string[] {
20
+ if (!config.sidebar.enabled) return [];
21
+ return [...config.sidebar.lines, ...statRows(config.sidebar.rows, source)].slice(0, MAX_LINES);
22
+ }
23
+
24
+ /** Footer text to render, or `undefined` when the footer rail is disabled. */
25
+ export function footerLine(config: FlightDeckConfig): string | undefined {
26
+ return config.footer.enabled ? config.footer.text : undefined;
27
+ }
28
+
29
+ /** Index of the first live row, so the caller can theme branding apart from data. */
30
+ export function liveRowOffset(config: FlightDeckConfig): number {
31
+ return config.sidebar.enabled ? config.sidebar.lines.length : 0;
32
+ }
@@ -0,0 +1,284 @@
1
+ // Live session readouts for the Flight Deck rail.
2
+ //
3
+ // Everything here is derived from state the host already holds in memory and
4
+ // hands to the plugin. There is no network call, no server, and no storage
5
+ // write: this module turns a session snapshot into strings.
6
+ //
7
+ // Kept pure and dependency-free so the formatting is trivial to test.
8
+
9
+ /** A subagent subtree total, relative to the session being displayed. */
10
+ export interface StatTree {
11
+ /** Combined cost of the session plus every subagent session. */
12
+ readonly cost?: unknown;
13
+ /** Number of subagent sessions in the tree. */
14
+ readonly count?: unknown;
15
+ }
16
+
17
+ /** Context-window occupancy for the most recent request. */
18
+ export interface StatContext {
19
+ /** Prompt tokens sent on the last request: input plus cache reads. */
20
+ readonly used?: unknown;
21
+ /** The model's context window, when the catalog knows it. */
22
+ readonly limit?: unknown;
23
+ }
24
+
25
+ /** Whole-project spend, across every session in this repository. */
26
+ export interface StatProject {
27
+ readonly cost?: unknown;
28
+ readonly count?: unknown;
29
+ }
30
+
31
+ /** The subset of a session snapshot the rail reads. All fields are untrusted. */
32
+ export interface StatSource {
33
+ readonly agent?: unknown;
34
+ readonly model?: unknown;
35
+ readonly cost?: unknown;
36
+ readonly tokens?: unknown;
37
+ readonly branch?: unknown;
38
+ readonly tree?: unknown;
39
+ readonly context?: unknown;
40
+ readonly project?: unknown;
41
+ readonly status?: unknown;
42
+ readonly perms?: unknown;
43
+ readonly tps?: unknown;
44
+ readonly elapsedMs?: unknown;
45
+ readonly turns?: unknown;
46
+ /** Recent per-turn output sizes, oldest first, for the sparkline. */
47
+ readonly spark?: unknown;
48
+ /** Animation frame counter, advanced by the ticker. */
49
+ readonly frame?: unknown;
50
+ }
51
+
52
+ /** Fields a user may name in `sidebar.rows`, in the order they are documented. */
53
+ export const STAT_FIELDS = [
54
+ "status",
55
+ "agent",
56
+ "model",
57
+ "branch",
58
+ "cost",
59
+ "total",
60
+ "project",
61
+ "tokens",
62
+ "cache",
63
+ "context",
64
+ "perms",
65
+ "elapsed",
66
+ "tps",
67
+ "spark",
68
+ "reasoning",
69
+ "turns",
70
+ ] as const;
71
+
72
+ export type StatField = (typeof STAT_FIELDS)[number];
73
+
74
+ export function isStatField(value: string): value is StatField {
75
+ return (STAT_FIELDS as readonly string[]).includes(value);
76
+ }
77
+
78
+ const LABEL_WIDTH = 10;
79
+ const BAR_WIDTH = 10;
80
+
81
+ function row(label: string, value: string): string {
82
+ return `${label.padEnd(LABEL_WIDTH)}${value}`;
83
+ }
84
+
85
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
86
+ return typeof value === "object" && value !== null && !Array.isArray(value)
87
+ ? (value as Record<string, unknown>)
88
+ : undefined;
89
+ }
90
+
91
+ function asText(value: unknown): string | undefined {
92
+ if (typeof value !== "string") return undefined;
93
+ const text = value.trim();
94
+ return text.length === 0 ? undefined : text;
95
+ }
96
+
97
+ function asCount(value: unknown): number | undefined {
98
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
99
+ }
100
+
101
+ /** `518k`, `29.2M`, `32M`, `940` — short enough for a narrow rail, precise enough to read. */
102
+ export function formatCount(value: number): string {
103
+ if (value < 1_000) return String(Math.round(value));
104
+ if (value < 1_000_000) return `${Math.round(value / 1_000)}k`;
105
+ const millions = (value / 1_000_000).toFixed(1);
106
+ return `${millions.endsWith(".0") ? millions.slice(0, -2) : millions}M`;
107
+ }
108
+
109
+ /** Sub-dollar sessions keep a third decimal so a cheap run never reads `$0.00`. */
110
+ export function formatCost(value: number): string {
111
+ return `$${value.toFixed(value < 1 ? 3 : 2)}`;
112
+ }
113
+
114
+ /** `45s`, `14m`, `2h 14m`. */
115
+ export function formatDuration(ms: number): string {
116
+ const seconds = Math.floor(ms / 1_000);
117
+ if (seconds < 60) return `${seconds}s`;
118
+ const minutes = Math.floor(seconds / 60);
119
+ if (minutes < 60) return `${minutes}m`;
120
+ const hours = Math.floor(minutes / 60);
121
+ const rest = minutes % 60;
122
+ return rest === 0 ? `${hours}h` : `${hours}h ${rest}m`;
123
+ }
124
+
125
+ /** A ten-cell gauge, so a percentage is readable at a glance rather than parsed. */
126
+ export function fuelBar(ratio: number): string {
127
+ const filled = Math.max(0, Math.min(BAR_WIDTH, Math.round(ratio * BAR_WIDTH)));
128
+ return `${"█".repeat(filled)}${"░".repeat(BAR_WIDTH - filled)}`;
129
+ }
130
+
131
+ const SPARK_LEVELS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"] as const;
132
+
133
+ /** Braille frames, advanced by the ticker, shown only while the session runs. */
134
+ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
135
+
136
+ /**
137
+ * Recent turn sizes as a shape.
138
+ *
139
+ * Scaled against the largest value in the window rather than an absolute scale,
140
+ * so the sparkline stays readable whether turns are tiny or enormous.
141
+ */
142
+ export function sparkline(values: readonly number[]): string {
143
+ if (values.length === 0) return "";
144
+ const max = Math.max(...values);
145
+ if (!Number.isFinite(max) || max <= 0) return SPARK_LEVELS[0].repeat(values.length);
146
+ return values
147
+ .map((value) => {
148
+ const level = Math.floor((Math.max(0, value) / max) * (SPARK_LEVELS.length - 1));
149
+ return SPARK_LEVELS[Math.min(SPARK_LEVELS.length - 1, level)];
150
+ })
151
+ .join("");
152
+ }
153
+
154
+ /**
155
+ * Render one named field, or `undefined` when the host has not supplied it yet.
156
+ *
157
+ * Returning `undefined` rather than a placeholder is deliberate: a rail that
158
+ * shows `branch unknown` before the repo loads looks broken, while a rail
159
+ * that simply grows a row when the data arrives looks alive.
160
+ */
161
+ export function statLine(field: string, source: StatSource): string | undefined {
162
+ switch (field) {
163
+ case "status": {
164
+ const status = asText(source.status);
165
+ if (status === undefined) return undefined;
166
+ // The spinner lives here rather than in a row of its own: an animated
167
+ // glyph beside "running" says the same thing without spending a line.
168
+ if (status !== "running") return row("status", "○ idle");
169
+ const frame = asCount(source.frame) ?? 0;
170
+ return row("status", `${SPINNER[frame % SPINNER.length]} running`);
171
+ }
172
+ case "agent": {
173
+ const agent = asText(source.agent);
174
+ return agent === undefined ? undefined : row("agent", agent);
175
+ }
176
+ case "model": {
177
+ const model = asRecord(source.model);
178
+ const id = asText(model?.id);
179
+ if (id === undefined) return undefined;
180
+ const variant = asText(model?.variant);
181
+ return row("model", variant === undefined ? id : `${id} · ${variant}`);
182
+ }
183
+ case "branch": {
184
+ const branch = asText(source.branch);
185
+ return branch === undefined ? undefined : row("branch", branch);
186
+ }
187
+ case "cost": {
188
+ const cost = asCount(source.cost);
189
+ return cost === undefined ? undefined : row("cost", formatCost(cost));
190
+ }
191
+ case "total": {
192
+ // Only worth a row once a subagent has actually run: subagent sessions are
193
+ // separate, so the parent's `cost` alone understates what was spent.
194
+ const tree = asRecord(source.tree);
195
+ const count = asCount(tree?.count);
196
+ const cost = asCount(tree?.cost);
197
+ if (cost === undefined || count === undefined || count === 0) return undefined;
198
+ const plural = count === 1 ? "subagent" : "subagents";
199
+ return row("total", `${formatCost(cost)} · ${count} ${plural}`);
200
+ }
201
+ case "project": {
202
+ const project = asRecord(source.project);
203
+ const cost = asCount(project?.cost);
204
+ if (cost === undefined) return undefined;
205
+ const count = asCount(project?.count);
206
+ return row("project", `${formatCost(cost)}${count !== undefined && count > 1 ? ` · ${count} sessions` : ""}`);
207
+ }
208
+ case "tokens": {
209
+ const tokens = asRecord(source.tokens);
210
+ const input = asCount(tokens?.input);
211
+ const output = asCount(tokens?.output);
212
+ if (input === undefined && output === undefined) return undefined;
213
+ return row("tokens", `${formatCount(input ?? 0)} in · ${formatCount(output ?? 0)} out`);
214
+ }
215
+ case "cache": {
216
+ const tokens = asRecord(source.tokens);
217
+ const cache = asRecord(tokens?.cache);
218
+ const read = asCount(cache?.read);
219
+ if (read === undefined || read === 0) return undefined;
220
+ const input = asCount(tokens?.input);
221
+ // Hit ratio is the whole point: it explains a cheap bill on a huge token
222
+ // count, and it is the first thing to break when caching stops working.
223
+ const total = input === undefined ? undefined : read + input;
224
+ const value =
225
+ total === undefined || total === 0
226
+ ? `${formatCount(read)} read`
227
+ : `${Math.round((read / total) * 100)}% hit · ${formatCount(read)} read`;
228
+ return row("cache", value);
229
+ }
230
+ case "context": {
231
+ const context = asRecord(source.context);
232
+ const used = asCount(context?.used);
233
+ if (used === undefined || used === 0) return undefined;
234
+ const limit = asCount(context?.limit);
235
+ if (limit === undefined || limit === 0) return row("context", `${formatCount(used)} used`);
236
+ const ratio = used / limit;
237
+ // Show the percentage whenever the host reports it, but never a bar that
238
+ // reads as more than full.
239
+ return row("context", `${fuelBar(ratio)} ${Math.round(Math.min(1, ratio) * 100)}%`);
240
+ }
241
+ case "perms": {
242
+ const perms = asCount(source.perms);
243
+ if (perms === undefined || perms === 0) return undefined;
244
+ return row("perms", perms === 1 ? "1 waiting" : `${perms} waiting`);
245
+ }
246
+ case "elapsed": {
247
+ const ms = asCount(source.elapsedMs);
248
+ if (ms === undefined || ms <= 0) return undefined;
249
+ return row("elapsed", formatDuration(ms));
250
+ }
251
+ case "tps": {
252
+ const tps = asCount(source.tps);
253
+ if (tps === undefined || tps === 0) return undefined;
254
+ return row("tps", `${Math.round(tps)} tok/s`);
255
+ }
256
+ case "spark": {
257
+ const values = Array.isArray(source.spark) ? source.spark.map((value) => asCount(value) ?? 0) : [];
258
+ if (values.length < 2) return undefined;
259
+ return row("spark", sparkline(values));
260
+ }
261
+ case "reasoning": {
262
+ const reasoning = asCount(asRecord(source.tokens)?.reasoning);
263
+ if (reasoning === undefined || reasoning === 0) return undefined;
264
+ return row("reasoning", formatCount(reasoning));
265
+ }
266
+ case "turns": {
267
+ const turns = asCount(source.turns);
268
+ if (turns === undefined || turns === 0) return undefined;
269
+ return row("turns", String(turns));
270
+ }
271
+ default:
272
+ return undefined;
273
+ }
274
+ }
275
+
276
+ /** Render every named field that currently has data, in the given order. */
277
+ export function statRows(fields: readonly string[], source: StatSource): readonly string[] {
278
+ const rows: string[] = [];
279
+ for (const field of fields) {
280
+ const line = statLine(field, source);
281
+ if (line !== undefined) rows.push(line);
282
+ }
283
+ return rows;
284
+ }