oc-flight-deck 0.6.2 → 0.6.6

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.
@@ -0,0 +1,238 @@
1
+ // Everything the host knows about the session on screen.
2
+ //
3
+ // One factory closes over the plugin `context` and returns the read-only
4
+ // lookups the rail needs: the session's messages, family tree, status,
5
+ // activity, shells, permissions, and derived figures (context occupancy,
6
+ // elapsed time, subagent totals, busy). Every lookup degrades to "no data"
7
+ // instead of throwing — the rail must never break because a read failed.
8
+ // Coercion of untrusted values happens through ./coerce.js.
9
+
10
+ import type { Plugin } from "@opencode/plugin/tui";
11
+ import { createActiveElapsed } from "./active-elapsed.js";
12
+ import { asCount, asRecord, asText, type SessionLike } from "./coerce.js";
13
+
14
+ /**
15
+ * The location the rail reads shell records and VCS from: the host's current
16
+ * location, or its default when no location is set. A host that cannot resolve
17
+ * a default degrades to "no location" rather than taking the rail down.
18
+ */
19
+ export function locationOf(context: Plugin.Context) {
20
+ try {
21
+ return context.location ?? context.data.location.default();
22
+ } catch {
23
+ return context.location;
24
+ }
25
+ }
26
+
27
+ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number) {
28
+ /** How many trailing messages are inspected for tool parts. */
29
+ const RECENT_MESSAGES = 4;
30
+
31
+ // The host owns these caches; a failure to read one must never break the
32
+ // rail, so every lookup degrades to "no data" instead of throwing.
33
+ const messagesOf = (sessionID: string): readonly unknown[] => {
34
+ try {
35
+ return context.data.session.message.list(sessionID) ?? [];
36
+ } catch {
37
+ return [];
38
+ }
39
+ };
40
+
41
+ // A subagent session is already inside its parent's family total, and the
42
+ // host keys `family()` by the family ROOT — so asking from a child returns
43
+ // its ancestors and siblings as well. Merging that would report the whole
44
+ // tree as this conversation's own, under a label that promises the
45
+ // conversation plus *its* subagents. Only a root has a family beneath it.
46
+ const isFamilyRoot = (sessionID: string): boolean => {
47
+ try {
48
+ return context.data.session.root(sessionID) === sessionID;
49
+ } catch {
50
+ // A host without `root` keeps the previous behaviour rather than
51
+ // silently dropping everyone's subagent total.
52
+ return true;
53
+ }
54
+ };
55
+
56
+ // Subagent sessions are separate sessions, and the parent's `cost` does not
57
+ // include them, so a bare `cost` row understates a swarm. Sum the family.
58
+ const treeTotals = (sessionID: string, ownCost: unknown) => {
59
+ if (!isFamilyRoot(sessionID)) return undefined;
60
+
61
+ let ids: readonly string[];
62
+ try {
63
+ ids = context.data.session.family(sessionID) ?? [sessionID];
64
+ } catch {
65
+ return undefined;
66
+ }
67
+ if (ids.length <= 1) return undefined;
68
+
69
+ let cost = asCount(ownCost) ?? 0;
70
+ let count = 0;
71
+ for (const id of ids) {
72
+ if (id === sessionID) continue;
73
+ const child = context.data.session.get(id) as SessionLike | undefined;
74
+ if (child === undefined) continue;
75
+ count += 1;
76
+ cost += asCount(child.cost) ?? 0;
77
+ }
78
+ return count === 0 ? undefined : { cost, count };
79
+ };
80
+
81
+ // A message's own totals are per-request, so the last assistant message's
82
+ // prompt size *is* the current context occupancy — not a running total.
83
+ const contextUsage = (sessionID: string, model: unknown) => {
84
+ const messages = messagesOf(sessionID);
85
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
86
+ const tokens = asRecord(asRecord(messages[index])?.tokens);
87
+ const input = asCount(tokens?.input);
88
+ if (tokens === undefined || input === undefined) continue;
89
+ const cache = asRecord(tokens.cache);
90
+ const used = input + (asCount(cache?.read) ?? 0) + (asCount(cache?.write) ?? 0);
91
+ if (used === 0) return undefined;
92
+ return { used, limit: contextLimit(model) };
93
+ }
94
+ return undefined;
95
+ };
96
+
97
+ // The window lives at `limit.context` on the catalog entry, and two
98
+ // providers can expose the same model id with different windows — so the
99
+ // provider has to match too, or the gauge would read the wrong ceiling.
100
+ const contextLimit = (model: unknown): number | undefined => {
101
+ const ref = asRecord(model);
102
+ const id = ref?.id;
103
+ const providerID = ref?.providerID;
104
+ if (typeof id !== "string") return undefined;
105
+ try {
106
+ const location = context.location ?? context.data.location.default();
107
+ for (const entry of context.data.location.model.list(location) ?? []) {
108
+ const record = asRecord(entry);
109
+ if (record === undefined || record.id !== id) continue;
110
+ if (typeof providerID === "string" && record.providerID !== providerID) continue;
111
+ const limit = asRecord(record.limit);
112
+ return asCount(limit?.context) ?? asCount(record.context) ?? asCount(record.contextWindow);
113
+ }
114
+ } catch {
115
+ return undefined;
116
+ }
117
+ return undefined;
118
+ };
119
+
120
+ const statusOf = (sessionID: string): string | undefined => {
121
+ try {
122
+ return context.data.session.status(sessionID);
123
+ } catch {
124
+ return undefined;
125
+ }
126
+ };
127
+
128
+ // Recent tool parts, oldest first. Only the tail is inspected: a loop that is
129
+ // not currently happening is history, and a hang is by definition now.
130
+ const recentParts = (sessionID: string): readonly unknown[] => {
131
+ const parts: unknown[] = [];
132
+ for (const entry of messagesOf(sessionID).slice(-RECENT_MESSAGES)) {
133
+ const content = asRecord(entry)?.["content"];
134
+ if (Array.isArray(content)) parts.push(...content);
135
+ }
136
+ return parts;
137
+ };
138
+
139
+ // The host's own shell records, which outlive the tool call: a backgrounded
140
+ // command returns its result immediately, so its part settles while the
141
+ // process keeps running. This is the only signal that survives that.
142
+ //
143
+ // Shells are listed per LOCATION, not per session, so the session is matched
144
+ // on the record's own `metadata.sessionID` — the documented shape, rather
145
+ // than a session-scoped accessor the published API does not carry.
146
+ const shellsOf = (sessionID: string): readonly unknown[] => {
147
+ try {
148
+ const shells = context.data.shell.list(locationOf(context)) ?? [];
149
+ return shells.filter(
150
+ (entry) => asText(asRecord(asRecord(entry)?.["metadata"])?.["sessionID"]) === sessionID,
151
+ );
152
+ } catch {
153
+ return [];
154
+ }
155
+ };
156
+
157
+ // The newest thing the host recorded for this session that is not a tool
158
+ // part, so the quiet-turn rule is not blind to a model that is streaming.
159
+ const lastActivity = (sessionID: string): number | undefined => {
160
+ const messages = messagesOf(sessionID);
161
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
162
+ const time = asRecord(asRecord(messages[index])?.["time"]);
163
+ const stamp =
164
+ asCount(time?.["completed"]) ?? asCount(time?.["streamed"]) ?? asCount(time?.["created"]);
165
+ if (stamp !== undefined) return stamp;
166
+ }
167
+ return undefined;
168
+ };
169
+
170
+ // What is waiting, not just how many. A bare count tells you to go and look;
171
+ // naming the request tells you whether it is worth looking at.
172
+ const permsOf = (
173
+ sessionID: string,
174
+ ): { count: number; action?: string; resource?: string } | undefined => {
175
+ try {
176
+ const requests = context.data.session.permission.list(sessionID);
177
+ if (requests === undefined || requests.length === 0) return undefined;
178
+ const first = asRecord(requests[0]);
179
+ const action = typeof first?.["action"] === "string" ? first["action"] : undefined;
180
+ const resources = Array.isArray(first?.["resources"]) ? first["resources"] : [];
181
+ const resource = typeof resources[0] === "string" ? resources[0] : undefined;
182
+ return { count: requests.length, action, resource };
183
+ } catch {
184
+ return undefined;
185
+ }
186
+ };
187
+
188
+ // Anything genuinely working keeps the status glyph turning: this session
189
+ // (thinking, streaming, running tools), any subagent in its tree, or a shell
190
+ // command still running. Returns `undefined` when the host has not said
191
+ // either way, so the rail can omit the row rather than invent "idle".
192
+ const busy = (sessionID: string): boolean | undefined => {
193
+ const status = statusOf(sessionID);
194
+ if (status === "running") return true;
195
+
196
+ try {
197
+ for (const id of context.data.session.family(sessionID) ?? []) {
198
+ if (id === sessionID) continue;
199
+ try {
200
+ if (context.data.session.status(id) === "running") return true;
201
+ } catch {
202
+ // One unreadable child must not hide a running sibling.
203
+ }
204
+ }
205
+ } catch {
206
+ // No subagent status on this host; the shell check below still applies.
207
+ }
208
+
209
+ try {
210
+ if (shellsOf(sessionID).some((entry) => asRecord(entry)?.["status"] === "running")) return true;
211
+ } catch {
212
+ // Unreadable shells just mean no shell signal.
213
+ }
214
+
215
+ return status === undefined ? undefined : false;
216
+ };
217
+
218
+ // Accumulated active wall time: the clock runs only while `busy()` says the
219
+ // session, its family, or its shells is working, and freezes otherwise. The
220
+ // `now` parameter keeps the transition observation deterministic for tests.
221
+ const activeElapsed = createActiveElapsed(busy, { maxBankedMs });
222
+ const sessionElapsed = (sessionID: string, now: number = Date.now()): number | undefined =>
223
+ activeElapsed(sessionID, now);
224
+
225
+ return {
226
+ messagesOf,
227
+ isFamilyRoot,
228
+ treeTotals,
229
+ contextUsage,
230
+ sessionElapsed,
231
+ statusOf,
232
+ recentParts,
233
+ shellsOf,
234
+ lastActivity,
235
+ permsOf,
236
+ busy,
237
+ };
238
+ }
@@ -0,0 +1,190 @@
1
+ // Session throughput, measured from the host's own message timestamps and never
2
+ // from a clock this process keeps. A host that stamps its assistant turns gets
3
+ // an active-work average: output tokens divided by the union of the turns' own
4
+ // spans, so idle between turns is not in the denominator and the figure freezes
5
+ // once everything settles. A host proven to expose no message timestamps uses
6
+ // the lifetime average instead.
7
+ //
8
+ // The capability is learned once and remembered for the process. `undefined`
9
+ // means "not yet known": a read that failed, or carried no assistant turns,
10
+ // tells us nothing and must not choose a metric. Once known it is sticky in
11
+ // BOTH directions, so a transient `message.list` failure can never flip a
12
+ // stamped host back to the lifetime average (nor an unstamped host off it) —
13
+ // a failure just hides the row. One value for the whole host, deliberately
14
+ // not keyed by session.
15
+ //
16
+ // The rail re-runs on the fast tick, and walking every family message for
17
+ // every session would repeat the same work fifty times a second, so the
18
+ // result is held briefly. `undefined` is cached too: an idle session must not
19
+ // be re-derived on each tick either.
20
+ //
21
+ // One factory closes over the plugin `context`; `isFamilyRoot` comes from
22
+ // ./session-reads.js so a child session keeps its own figure while a root
23
+ // sums its tree. The math itself lives in ./throughput.js (pure).
24
+ //
25
+ // RESIDUAL RISK, disclosed: the lifetime fallback for an unstamped host still
26
+ // includes idle time and can therefore sag below a peak per-turn rate. There is
27
+ // no timestamp on such a host with which to exclude it.
28
+
29
+ import type { Plugin } from "@opencode/plugin/tui";
30
+ import { asCount, asRecord, type SessionLike } from "./coerce.js";
31
+ import { sessionThroughput, turnKey, turnSpan, unionSpanThroughput, type ThroughputSpan } from "./stats.js";
32
+
33
+ /** What one session's message list contributes to its active-work average. */
34
+ interface TpsScan {
35
+ /** False only when the host refused to list the session's messages. */
36
+ readonly ok: boolean;
37
+ /** Assistant messages seen, whether or not they carried a timestamp. */
38
+ readonly assistant: number;
39
+ /** Assistant turns that carried any usable timestamp, which proves the host stamps. */
40
+ readonly stamped: number;
41
+ /** Spans for turns that carried a usable `created` start. */
42
+ readonly spans: readonly ThroughputSpan[];
43
+ }
44
+
45
+ export function createTpsReader(
46
+ context: Plugin.Context,
47
+ isFamilyRoot: (sessionID: string) => boolean,
48
+ ) {
49
+ const TPS_CACHE_MS = 1_000;
50
+ let hostStamps: boolean | undefined;
51
+ let tpsCache:
52
+ | { readonly sessionID: string; readonly at: number; readonly value: number | undefined }
53
+ | undefined;
54
+
55
+ const scanMessages = (id: string, now: number): TpsScan => {
56
+ let messages: readonly unknown[];
57
+ try {
58
+ messages = context.data.session.message.list(id) ?? [];
59
+ } catch {
60
+ // A refused read is not "this host has no messages".
61
+ return { ok: false, assistant: 0, stamped: 0, spans: [] };
62
+ }
63
+ const spans: ThroughputSpan[] = [];
64
+ let assistant = 0;
65
+ let stamped = 0;
66
+ for (const entry of messages) {
67
+ const message = asRecord(entry);
68
+ if (message?.["type"] !== "assistant") continue;
69
+ assistant += 1;
70
+ const stamp = asRecord(message["time"]);
71
+ const created = asCount(stamp?.["created"]);
72
+ const completed = asCount(stamp?.["completed"]);
73
+ const streamed = asCount(stamp?.["streamed"]);
74
+ // "Stamped" depends only on the timestamps, never on the output count: a
75
+ // batch of zero-output assistant turns still proves the host stamps.
76
+ if (created === undefined && completed === undefined && streamed === undefined) continue;
77
+ stamped += 1;
78
+ // Without `created` there is no start; the turn is skipped, not guessed.
79
+ const span = turnSpan(created, completed, streamed, now);
80
+ if (span === undefined) continue;
81
+ const output = asRecord(message["tokens"])?.["output"];
82
+ spans.push({ key: turnKey(message["id"], created, completed, output), tokens: output, ...span });
83
+ }
84
+ return { ok: true, assistant, stamped, spans };
85
+ };
86
+
87
+ // The lifetime average, the metric of last resort for a host that exposes no
88
+ // per-message timestamps. Measured from the session's own clock
89
+ // (`time.updated`, falling back to now) so a finished session settles on a
90
+ // stable figure instead of decaying as it sits on screen.
91
+ const lifetimeTps = (
92
+ sessionID: string,
93
+ session: SessionLike | undefined,
94
+ created: number,
95
+ time: Record<string, unknown> | undefined,
96
+ ): number | undefined => {
97
+ const updated = asCount(time?.["updated"]);
98
+ const end = updated === undefined ? Date.now() : Math.min(Date.now(), updated);
99
+ const elapsed = end - created;
100
+ if (elapsed <= 0) return undefined;
101
+
102
+ const own = asCount(asRecord(session?.tokens)?.["output"]);
103
+ let output = own;
104
+ // Only a family root owns the tree beneath it; a child asking `family()`
105
+ // gets its ancestors and siblings too, so it keeps its own figure.
106
+ if (isFamilyRoot(sessionID)) {
107
+ try {
108
+ const ids = context.data.session.family(sessionID) ?? [];
109
+ if (ids.length > 1) {
110
+ let total = 0;
111
+ let sawOne = false;
112
+ for (const id of ids) {
113
+ const member = context.data.session.get(id) as SessionLike | undefined;
114
+ const out = asCount(asRecord(member?.tokens)?.["output"]);
115
+ if (out === undefined) continue;
116
+ total += out;
117
+ sawOne = true;
118
+ }
119
+ if (sawOne) output = total;
120
+ }
121
+ } catch {
122
+ // No family on this host: the session's own tokens still stand.
123
+ }
124
+ }
125
+ return sessionThroughput(output, elapsed);
126
+ };
127
+
128
+ const computeTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
129
+ const time = asRecord(session?.time);
130
+ const created = asCount(time?.["created"]);
131
+ if (created === undefined) return undefined;
132
+
133
+ // A host proven unstamped needs no message read at all: its metric is the
134
+ // lifetime average whether or not the read would have succeeded.
135
+ if (hostStamps === false) return lifetimeTps(sessionID, session, created, time);
136
+
137
+ // One `now` for the whole scope, so every in-flight turn ends at the same
138
+ // instant and the union cannot be skewed by the scans drifting apart.
139
+ const now = Date.now();
140
+
141
+ // Timestamped assistant output this session has produced, plus — only from
142
+ // a family root — every subagent session's. A child asking `family()` gets
143
+ // its ancestors and siblings back, so it keeps its own spans.
144
+ const scans: TpsScan[] = [scanMessages(sessionID, now)];
145
+ if (isFamilyRoot(sessionID)) {
146
+ try {
147
+ for (const id of context.data.session.family(sessionID) ?? []) {
148
+ if (id !== sessionID) scans.push(scanMessages(id, now));
149
+ }
150
+ } catch {
151
+ // No family on this host: the session's own turns still stand.
152
+ }
153
+ }
154
+
155
+ const spans: ThroughputSpan[] = [];
156
+ let assistant = 0;
157
+ let stamped = 0;
158
+ let readOk = false;
159
+ for (const scan of scans) {
160
+ spans.push(...scan.spans);
161
+ assistant += scan.assistant;
162
+ stamped += scan.stamped;
163
+ readOk = readOk || scan.ok;
164
+ }
165
+
166
+ if (hostStamps === undefined) {
167
+ // A stamped assistant turn proves the host stamps. Assistant turns with
168
+ // no timestamp prove it does not. Neither, and the capability stays
169
+ // unknown so the row hides rather than guessing a metric.
170
+ if (stamped > 0) hostStamps = true;
171
+ else if (readOk && assistant > 0) hostStamps = false;
172
+ else return undefined;
173
+ }
174
+
175
+ if (hostStamps === true) return unionSpanThroughput(spans);
176
+ return lifetimeTps(sessionID, session, created, time);
177
+ };
178
+
179
+ const sessionTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
180
+ const cached = tpsCache;
181
+ if (cached !== undefined && cached.sessionID === sessionID && Date.now() - cached.at < TPS_CACHE_MS) {
182
+ return cached.value;
183
+ }
184
+ const value = computeTps(sessionID, session);
185
+ tpsCache = { sessionID, at: Date.now(), value };
186
+ return value;
187
+ };
188
+
189
+ return { sessionTps };
190
+ }
@@ -0,0 +1,132 @@
1
+ // The rail's stat vocabulary.
2
+ //
3
+ // `StatSource` is the subset of a session snapshot the rail reads; `STAT_FIELDS`
4
+ // is the set a user may name in `sidebar.rows`; `ANIMATED_FIELDS` drives the
5
+ // ticker; `LayoutHint` carries per-call row geometry. Untrusted values are read
6
+ // through ./coerce.js rather than re-checked here.
7
+
8
+ import type { DurationStyle } from "./format.js";
9
+
10
+ /** The subset of a session snapshot the rail reads. All fields are untrusted. */
11
+ export interface StatSource {
12
+ /**
13
+ * The annunciator line, precomputed by the caller.
14
+ *
15
+ * A plain string on purpose: the rules that decide whether something is wrong
16
+ * live in ./caution.ts and need the clock and the session snapshot, not a
17
+ * formatting function. Severity is already encoded in the glyph.
18
+ */
19
+ readonly caution?: unknown;
20
+ readonly agent?: unknown;
21
+ readonly model?: unknown;
22
+ readonly cost?: unknown;
23
+ readonly tokens?: unknown;
24
+ readonly branch?: unknown;
25
+ readonly tree?: unknown;
26
+ readonly context?: unknown;
27
+ readonly project?: unknown;
28
+ readonly status?: unknown;
29
+ /** True when anything is working: this session, a subagent, or a shell. */
30
+ readonly busy?: unknown;
31
+ readonly perms?: unknown;
32
+ /**
33
+ * Session throughput. On a host that stamps its messages this is an
34
+ * active-work average: output tokens divided by the union of the assistant
35
+ * turns' own spans, subagents summed in, so idle between turns is not
36
+ * counted and the figure freezes when work stops. On a host without message
37
+ * timestamps it falls back to the lifetime average, which can still sag.
38
+ * Either way it is derived from state the host already holds.
39
+ */
40
+ readonly tps?: unknown;
41
+ readonly elapsedMs?: unknown;
42
+ readonly turns?: unknown;
43
+ /** Recent per-turn output sizes, oldest first, for the sparkline. */
44
+ readonly spark?: unknown;
45
+ /** Animation frame counter, advanced by the ticker. */
46
+ readonly frame?: unknown;
47
+ /** Harness status from oc-harness-guard's RPC, via the guard bridge. Untrusted. */
48
+ readonly guard?: unknown;
49
+ }
50
+
51
+ /** Fields a user may name in `sidebar.rows`, in the order they are documented. */
52
+ export const STAT_FIELDS = [
53
+ "caution",
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
+ "guard",
71
+ ] as const;
72
+
73
+ type StatField = (typeof STAT_FIELDS)[number];
74
+
75
+ /**
76
+ * Fields whose value only ever changes on a clock tick.
77
+ *
78
+ * The ticker exists to animate these. When none of them is on screen there is
79
+ * nothing to animate, so the plugin does not start a timer at all.
80
+ *
81
+ * `caution` belongs here for a stronger reason than the others: its whole job is
82
+ * noticing that time has passed without anything happening, so without a tick
83
+ * its thresholds could never be crossed on screen.
84
+ */
85
+ export const ANIMATED_FIELDS = ["caution", "status", "elapsed"] as const;
86
+
87
+ export function isStatField(value: string): value is StatField {
88
+ return STAT_FIELDS.some((field) => field === value);
89
+ }
90
+
91
+ /**
92
+ * Row geometry, overridable per call.
93
+ *
94
+ * A structural type rather than an import of `FlightDeckConfig`: ./config.ts
95
+ * imports this module, so reaching back into it would create a cycle. The
96
+ * shapes are compatible, so the config passes straight through.
97
+ */
98
+ export interface LayoutHint {
99
+ readonly labelWidth?: number;
100
+ readonly barWidth?: number;
101
+ readonly sparkWidth?: number;
102
+ /**
103
+ * How the `elapsed` row joins its duration segments. The rail supplies this
104
+ * from `format.duration` (default `"spaced"`); when the hint is absent the
105
+ * formatter's own default, `"compact"`, applies.
106
+ */
107
+ readonly durationStyle?: DurationStyle;
108
+ /**
109
+ * True when the rail already draws a `total` row.
110
+ *
111
+ * The `cost` row merges the subagent total into itself only when nothing else
112
+ * on the rail already shows it — which makes "do I want one money row or two"
113
+ * a property of `sidebar.rows`, not a separate setting to find.
114
+ */
115
+ readonly hasTotalRow?: boolean;
116
+ /**
117
+ * When true, `statRows` renders one row per named field even when the host
118
+ * has no data for it, using `placeholder` as the value. Default off when
119
+ * calling `statRows` directly; `sidebarLines` turns it on from
120
+ * `config.sidebar.persist`.
121
+ */
122
+ readonly persist?: boolean;
123
+ /** Value shown for a row with no data when `persist` is on. Default `"—"`. */
124
+ readonly placeholder?: string;
125
+ }
126
+
127
+ /** Placeholder value for a persistent row with no data yet. */
128
+ export const DEFAULT_PLACEHOLDER = "—";
129
+
130
+ export const DEFAULT_LABEL_WIDTH = 10;
131
+ export const DEFAULT_SPARK_WIDTH = 12;
132
+