oc-flight-deck 0.20.3 → 0.20.5

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.
@@ -12,6 +12,19 @@ import { createActiveTime } from "./session-elapsed.js";
12
12
  import { asCount, asRecord, asText, type SessionLike } from "./coerce.js";
13
13
  import { turnKey, type ThroughputSpan } from "./stats.js";
14
14
 
15
+ /**
16
+ * How strong a money figure's claim is: `exact` is a recorded figure the host
17
+ * owns, `bounded` is recorded charges over the history the host still holds,
18
+ * `estimated` needed the model catalog because a charge was not recorded.
19
+ */
20
+ type UsageKind = "exact" | "bounded" | "estimated";
21
+
22
+ /** A money figure with the strength of its claim. */
23
+ interface UsageFigure {
24
+ cost: number;
25
+ kind: UsageKind;
26
+ }
27
+
15
28
  /**
16
29
  * The location the rail reads shell records and VCS from: the host's current
17
30
  * location, or its default when no location is set. A host that cannot resolve
@@ -25,6 +38,14 @@ export function locationOf(context: Plugin.Context) {
25
38
  }
26
39
  }
27
40
 
41
+ /** Token counts, in the shape the host publishes them. */
42
+ interface TokenCounts {
43
+ input: number;
44
+ output: number;
45
+ reasoning: number;
46
+ cache: { read: number; write: number };
47
+ }
48
+
28
49
  export function createSessionReads(context: Plugin.Context) {
29
50
  /** How many trailing messages are inspected for tool parts. */
30
51
  const RECENT_MESSAGES = 4;
@@ -39,81 +60,320 @@ export function createSessionReads(context: Plugin.Context) {
39
60
  }
40
61
  };
41
62
 
42
- // A subagent session is already inside its parent's family total, and the
43
- // host keys `family()` by the family ROOT — so asking from a child returns
44
- // its ancestors and siblings as well. Merging that would report the whole
45
- // tree as this conversation's own, under a label that promises the
46
- // conversation plus *its* subagents. Only a root has a family beneath it.
47
- const isFamilyRoot = (sessionID: string): boolean => {
63
+ // Usage.
64
+ //
65
+ // The host publishes both figures and neither needs reconstructing:
66
+ // `data.session.cost(id)` is the family roll-up (this session plus every
67
+ // descendant) and `session.get().cost` the session's own persisted aggregate.
68
+ // The aggregate spans every model the session ran, and there is no host API
69
+ // for per-model spend, so only `cost` is derived - from the recorded per-step
70
+ // costs of the model currently selected.
71
+ //
72
+ // total - the host roll-up, exact. Zero with no tokens is a real $0.000;
73
+ // zero with tokens on a priced model is a catalog estimate, marked.
74
+ // cost - recorded step costs for the current model over the history the
75
+ // host exposes, marked as a floor when that history is a window,
76
+ // and as an estimate when a step had to be catalog-priced.
77
+
78
+ const emptyTokens = (): TokenCounts => ({
79
+ input: 0,
80
+ output: 0,
81
+ reasoning: 0,
82
+ cache: { read: 0, write: 0 },
83
+ });
84
+
85
+ const readTokens = (source: unknown): TokenCounts => {
86
+ const record = asRecord(source);
87
+ const tokens = emptyTokens();
88
+ if (record === undefined) return tokens;
89
+ tokens.input = asCount(record["input"]) ?? 0;
90
+ tokens.output = asCount(record["output"]) ?? 0;
91
+ tokens.reasoning = asCount(record["reasoning"]) ?? 0;
92
+ const cache = asRecord(record["cache"]);
93
+ tokens.cache.read = asCount(cache?.["read"]) ?? 0;
94
+ tokens.cache.write = asCount(cache?.["write"]) ?? 0;
95
+ return tokens;
96
+ };
97
+
98
+ // Model identity as the host keys it: provider and id. The variant is a
99
+ // setting of the same model, not a different bill, so it is not part of it.
100
+ const modelKeyOf = (model: unknown): string | undefined => {
101
+ const ref = asRecord(model);
102
+ const id = asText(ref?.["id"]) ?? asText(ref?.["modelID"]);
103
+ if (id === undefined) return undefined;
104
+ const provider = asText(ref?.["providerID"]);
105
+ return provider === undefined ? id : `${provider}/${id}`;
106
+ };
107
+
108
+ // Catalog prices, per million tokens, indexed by provider and model id. The
109
+ // catalog array is the cache key: when the host swaps it the index is rebuilt.
110
+ const PRICE_PER_UNIT = 1_000_000;
111
+ let pricedFrom: readonly unknown[] | undefined;
112
+ let priceIndex = new Map<string, readonly { size: number; price: TokenCounts }[]>();
113
+
114
+ const priceKey = (id: string, providerID: string | undefined): string =>
115
+ providerID === undefined ? id : `${providerID}/${id}`;
116
+
117
+ // One catalog row as the four rates it bills, reusing the token shape so a
118
+ // step's tokens multiply rate-for-rate: input at the input rate, generation
119
+ // (output plus reasoning) at the output rate, each cache rung at its own.
120
+ const readPrice = (source: unknown): TokenCounts | undefined => {
121
+ const record = asRecord(source);
122
+ if (record === undefined) return undefined;
123
+ const input = asCount(record["input"]);
124
+ const output = asCount(record["output"]);
125
+ if (input === undefined || output === undefined) return undefined;
126
+ const cache = asRecord(record["cache"]);
127
+ return {
128
+ input,
129
+ output,
130
+ reasoning: output,
131
+ cache: {
132
+ read: asCount(cache?.["read"]) ?? input,
133
+ write: asCount(cache?.["write"]) ?? input,
134
+ },
135
+ };
136
+ };
137
+
138
+ const prices = (): Map<string, readonly { size: number; price: TokenCounts }[]> => {
139
+ let entries: readonly unknown[] = [];
48
140
  try {
49
- return context.data.session.root(sessionID) === sessionID;
141
+ entries = context.data.location.model.list(locationOf(context)) ?? [];
50
142
  } catch {
51
- // A host without `root` keeps the previous behaviour rather than
52
- // silently dropping everyone's subagent total.
53
- return true;
143
+ entries = [];
144
+ }
145
+ if (entries === pricedFrom) return priceIndex;
146
+ pricedFrom = entries;
147
+ priceIndex = new Map();
148
+ for (const entry of entries) {
149
+ const record = asRecord(entry);
150
+ if (record === undefined) continue;
151
+ const id = asText(record["id"]) ?? asText(record["modelID"]);
152
+ if (id === undefined) continue;
153
+ const tiers: { size: number; price: TokenCounts }[] = [];
154
+ const cost = record["cost"];
155
+ const rows = Array.isArray(cost) ? cost : [cost];
156
+ for (const row of rows) {
157
+ const price = readPrice(row);
158
+ if (price === undefined) continue;
159
+ const tier = asRecord(asRecord(row)?.["tier"]);
160
+ tiers.push({ size: asCount(tier?.["size"]) ?? 0, price });
161
+ }
162
+ if (tiers.length === 0) continue;
163
+ tiers.sort((left, right) => left.size - right.size);
164
+ priceIndex.set(priceKey(id, asText(record["providerID"])), tiers);
54
165
  }
166
+ return priceIndex;
55
167
  };
56
168
 
57
- // Subagent sessions are separate sessions, and the parent's `cost` does not
58
- // include them, so a bare `cost` row understates a swarm. Sum the family —
59
- // and the same scope for `tokens`: the money row already shows the family,
60
- // so the token rows beside it must share it, or one row's swarm is another
61
- // row's session. The parent's own tokens come from its session record (its
62
- // own cost arrives via `ownCost`, already in the caller's hand), every
63
- // child's from theirs: `input`, `output`, `reasoning`, and both `cache`
64
- // rungs, so a caller that uses this INSTEAD of the session's own record
65
- // gets the full family figure.
66
- const treeTotals = (sessionID: string, ownCost: unknown) => {
67
- if (!isFamilyRoot(sessionID)) return undefined;
169
+ // What one step costs at catalog prices: the prompt is billed at the input
170
+ // rate, generation (output plus reasoning) at the output rate, and the two
171
+ // cache rungs at their own. A tiered model is priced at the largest tier the
172
+ // prompt reaches. Unknown model, unknown price, or zero rates answer zero - a
173
+ // genuinely free model stays free.
174
+ const catalogCost = (tokens: TokenCounts, model: unknown): number => {
175
+ const ref = asRecord(model);
176
+ const id = asText(ref?.["id"]) ?? asText(ref?.["modelID"]);
177
+ if (id === undefined) return 0;
178
+ const index = prices();
179
+ const tiers = index.get(priceKey(id, asText(ref?.["providerID"]))) ?? index.get(id);
180
+ if (tiers === undefined || tiers.length === 0) return 0;
181
+ const prompt = tokens.input + tokens.cache.read + tokens.cache.write;
182
+ let chosen = tiers[0];
183
+ for (const tier of tiers) if (tier.size <= prompt) chosen = tier;
184
+ const price = chosen?.price;
185
+ if (price === undefined) return 0;
186
+ const micro =
187
+ tokens.input * price.input +
188
+ tokens.output * price.output +
189
+ tokens.reasoning * price.reasoning +
190
+ tokens.cache.read * price.cache.read +
191
+ tokens.cache.write * price.cache.write;
192
+ return micro / PRICE_PER_UNIT;
193
+ };
68
194
 
69
- let ids: readonly string[];
195
+ // The `cost` figure: recorded step costs for the model the session currently
196
+ // runs. The aggregate is deliberately NOT used - it spans every model the
197
+ // session ever ran, so it cannot answer a per-model question.
198
+ //
199
+ // Two guards, both mirroring the host's own accounting:
200
+ // - a fork's copied parent history predates the fork's creation
201
+ // (`stats.ts`: `message.time_created >= session.time_created`), so it is
202
+ // not this session's spend;
203
+ // - the TUI surface exposes no paging (`message.list` only, no `more()`),
204
+ // so the history on hand is a window and the figure is a floor.
205
+ const sessionCost = (
206
+ sessionID: string,
207
+ record: SessionLike | undefined,
208
+ ): UsageFigure | undefined => {
209
+ if (record === undefined) return undefined;
210
+ const messages = messagesOf(sessionID);
211
+ const model = modelKeyOf(record?.model);
212
+ const created = asCount(asRecord(record?.time)?.["created"]) ?? 0;
213
+ let cost = 0;
214
+ let counted = 0;
215
+ let estimated = false;
216
+ for (const entry of messages) {
217
+ const message = asRecord(entry);
218
+ if (message?.["type"] !== "assistant") continue;
219
+ const stamp = asCount(asRecord(message["time"])?.["created"]);
220
+ if (stamp !== undefined && stamp < created) continue;
221
+ if (model !== undefined && modelKeyOf(message["model"]) !== model) continue;
222
+ const recorded = asCount(message["cost"]);
223
+ const stepTokens = asRecord(message["tokens"]);
224
+ if (recorded === undefined && stepTokens === undefined) continue;
225
+ counted += 1;
226
+ if (recorded !== undefined && recorded > 0) {
227
+ cost += recorded;
228
+ } else {
229
+ cost += catalogCost(readTokens(stepTokens), message["model"]);
230
+ estimated = true;
231
+ }
232
+ }
233
+ if (counted === 0) return undefined;
234
+ return { cost, kind: estimated ? "estimated" : "bounded" };
235
+ };
236
+
237
+ // `data.session.cost`, the host's persisted family roll-up. It answers a
238
+ // family figure only for a ROOT id - handed a child it returns that child's
239
+ // own cost - so the caller resolves the root first.
240
+ const hostFamilyCost = (sessionID: string): number | undefined => {
70
241
  try {
71
- ids = context.data.session.family(sessionID) ?? [sessionID];
242
+ const accessor = context.data.session.cost;
243
+ if (typeof accessor !== "function") return undefined;
244
+ return asCount(accessor.call(context.data.session, sessionID));
72
245
  } catch {
73
246
  return undefined;
74
247
  }
248
+ };
75
249
 
76
- let own: SessionLike | undefined;
250
+ // The `total` figure: the host's family roll-up, always resolved from the
251
+ // family ROOT. Nothing is summed for a non-zero figure - the roll-up is the
252
+ // persisted total of per-session aggregates, so it already survives
253
+ // stop/resume, model switches and compaction, and it is exact.
254
+ //
255
+ // A zero roll-up is a real zero when the family spent nothing. Where the
256
+ // family holds tokens on models the catalog prices, a provider-reported zero
257
+ // is a missing charge: every member's messages are priced at the model each
258
+ // message ran, and the figure is marked as an estimate - never exact.
259
+ const treeTotals = (
260
+ sessionID: string,
261
+ ): { cost: number; count: number; tokens: TokenCounts; kind: UsageKind } | undefined => {
262
+ let root = sessionID;
77
263
  try {
78
- own = context.data.session.get(sessionID) as SessionLike | undefined;
264
+ root = context.data.session.root(sessionID) ?? sessionID;
79
265
  } catch {
80
- own = undefined;
266
+ root = sessionID;
81
267
  }
82
- const tokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } };
83
- const addTokens = (source: SessionLike | undefined): void => {
84
- const record = asRecord(source?.tokens);
85
- tokens.input += asCount(record?.["input"]) ?? 0;
86
- tokens.output += asCount(record?.["output"]) ?? 0;
87
- tokens.reasoning += asCount(record?.["reasoning"]) ?? 0;
88
- const cache = asRecord(record?.["cache"]);
89
- tokens.cache.read += asCount(cache?.["read"]) ?? 0;
90
- tokens.cache.write += asCount(cache?.["write"]) ?? 0;
91
- };
92
- addTokens(own);
268
+ let ids: readonly string[];
269
+ try {
270
+ ids = context.data.session.family(root) ?? [root];
271
+ } catch {
272
+ ids = [root];
273
+ }
274
+ const members = ids.includes(root) ? ids : [root, ...ids];
93
275
 
94
- let cost = asCount(ownCost) ?? 0;
95
- let count = 0;
96
- for (const id of ids) {
97
- if (id === sessionID) continue;
98
- let child: SessionLike | undefined;
276
+ const recordOf = (id: string): SessionLike | undefined => {
99
277
  try {
100
- child = context.data.session.get(id) as SessionLike | undefined;
278
+ return context.data.session.get(id) as SessionLike | undefined;
101
279
  } catch {
102
- // One unreadable member must not blank the rest of the tree.
103
- continue;
280
+ return undefined;
104
281
  }
282
+ };
283
+
284
+ const own = recordOf(root);
285
+ // No session record is no figure: the row stays absent (the persist layer's
286
+ // skeleton draws in its place), never a fabricated $0.000.
287
+ if (own === undefined) return undefined;
288
+
289
+ const tokens = emptyTokens();
290
+ const addTokens = (record: SessionLike | undefined): void => {
291
+ const read = readTokens(record?.tokens);
292
+ tokens.input += read.input;
293
+ tokens.output += read.output;
294
+ tokens.reasoning += read.reasoning;
295
+ tokens.cache.read += read.cache.read;
296
+ tokens.cache.write += read.cache.write;
297
+ };
298
+ addTokens(own);
299
+
300
+ let count = 0;
301
+ for (const id of members) {
302
+ if (id === root) continue;
303
+ const child = recordOf(id);
105
304
  if (child === undefined) continue;
106
305
  count += 1;
107
- cost += asCount(child.cost) ?? 0;
108
306
  addTokens(child);
109
307
  }
110
- // The family figure, subagents included. A session that spawned none still
111
- // records one: its own cost against a count of zero, so the `total` row has
112
- // a real number to draw instead of blanking at `$0.000`. `undefined` is now
113
- // reserved for a figure that genuinely cannot be computed — a non-root
114
- // session (its family is its parent's), or a host read that threw.
115
- if (ownCost === undefined && count === 0) return undefined;
116
- return { cost, count, tokens };
308
+
309
+ // Per member: its record, and the recorded assistant charges visible for it
310
+ // with the host's fork guard applied. `visible` is the floor the family can
311
+ // prove from what it holds; `complete` says whether every id the family
312
+ // lists has a record at all.
313
+ let visible = 0;
314
+ let complete = true;
315
+ for (const id of members) {
316
+ const record = recordOf(id);
317
+ if (record === undefined) {
318
+ complete = false;
319
+ continue;
320
+ }
321
+ const created = asCount(asRecord(record.time)?.["created"]) ?? 0;
322
+ let charges = 0;
323
+ for (const entry of messagesOf(id)) {
324
+ const message = asRecord(entry);
325
+ if (message?.["type"] !== "assistant") continue;
326
+ const stamp = asCount(asRecord(message["time"])?.["created"]);
327
+ if (stamp !== undefined && stamp < created) continue;
328
+ charges += asCount(message["cost"]) ?? 0;
329
+ }
330
+ visible += Math.max(asCount(record.cost) ?? 0, charges);
331
+ }
332
+
333
+ let rolled = hostFamilyCost(root);
334
+ if (rolled === undefined) {
335
+ // A host without the accessor: the per-session aggregates are the same
336
+ // persisted numbers, so their sum is still the family figure.
337
+ let total = 0;
338
+ for (const id of members) total += asCount(recordOf(id)?.cost) ?? 0;
339
+ rolled = total;
340
+ }
341
+ // The table, in order. `rolled` is the host's persisted family figure and is
342
+ // never exceeded: a floor above it would claim money the host says was not
343
+ // spent. `exact` is claimed only when the family is complete and the roll-up
344
+ // already covers the charges visible on the message lists.
345
+ if (rolled > 0) {
346
+ return {
347
+ cost: rolled,
348
+ count,
349
+ tokens,
350
+ kind: complete && rolled >= visible ? "exact" : "bounded",
351
+ };
352
+ }
353
+ if (visible > 0) return { cost: visible, count, tokens, kind: "bounded" };
354
+ if (!complete) return { cost: 0, count, tokens, kind: "bounded" };
355
+
356
+ // Zero: price the whole family's messages, each at its own model; a member
357
+ // with no message list on hand still contributes its recorded tokens.
358
+ let priced = 0;
359
+ for (const id of members) {
360
+ const record = recordOf(id);
361
+ if (record === undefined) continue;
362
+ const created = asCount(asRecord(record.time)?.["created"]) ?? 0;
363
+ const listed = messagesOf(id);
364
+ let pricedHere = false;
365
+ for (const entry of listed) {
366
+ const message = asRecord(entry);
367
+ if (message?.["type"] !== "assistant") continue;
368
+ const stamp = asCount(asRecord(message["time"])?.["created"]);
369
+ if (stamp !== undefined && stamp < created) continue;
370
+ priced += catalogCost(readTokens(message["tokens"]), message["model"]);
371
+ pricedHere = true;
372
+ }
373
+ if (!pricedHere) priced += catalogCost(readTokens(record.tokens), record.model);
374
+ }
375
+ if (priced > 0) return { cost: priced, count, tokens, kind: "estimated" };
376
+ return { cost: 0, count, tokens, kind: "exact" };
117
377
  };
118
378
 
119
379
  // A message's own totals are per-request, so the last assistant message's
@@ -340,6 +600,7 @@ export function createSessionReads(context: Plugin.Context) {
340
600
  return {
341
601
  messagesOf,
342
602
  treeTotals,
603
+ sessionCost,
343
604
  contextUsage,
344
605
  sessionElapsed,
345
606
  statusOf,
@@ -6,7 +6,7 @@
6
6
  // through ./coerce.js rather than re-checked here.
7
7
 
8
8
  import { DEFAULT_BAR_WIDTH, formatCost, formatCount, formatDuration, fuelBar } from "./format.js";
9
- import type { DurationStyle } from "./format.js";
9
+ import type { DurationStyle, TimestampFormat } from "./format.js";
10
10
 
11
11
  /** The subset of a session snapshot the rail reads. All fields are untrusted. */
12
12
  export interface StatSource {
@@ -23,6 +23,14 @@ export interface StatSource {
23
23
  readonly agent?: unknown;
24
24
  readonly model?: unknown;
25
25
  readonly cost?: unknown;
26
+ /**
27
+ * How strong the `cost` figure's claim is: `"exact"` (the host's recorded
28
+ * aggregate), `"bounded"` (recorded charges over the history on hand) or
29
+ * `"estimated"` (at least one step priced from the catalog, not charged).
30
+ * The row marks the last two so an estimate never reads as a bill. Untrusted
31
+ * like every other field.
32
+ */
33
+ readonly costKind?: unknown;
26
34
  readonly tokens?: unknown;
27
35
  readonly branch?: unknown;
28
36
  /**
@@ -51,6 +59,13 @@ export interface StatSource {
51
59
  */
52
60
  readonly tps?: unknown;
53
61
  readonly elapsedMs?: unknown;
62
+ /**
63
+ * When the host recorded the session's newest action, as epoch milliseconds:
64
+ * the newest message's `completed`, else `streamed`, else `created` stamp.
65
+ * Untrusted like every other field; the `updated` row formats it through
66
+ * `format.timestamp` and hides when it is absent or not a positive instant.
67
+ */
68
+ readonly lastActionMs?: unknown;
54
69
  readonly turns?: unknown;
55
70
  /** Recent per-turn output sizes, oldest first, for the sparkline. */
56
71
  readonly spark?: unknown;
@@ -81,6 +96,7 @@ export const STAT_FIELDS = [
81
96
  "context",
82
97
  "perms",
83
98
  "elapsed",
99
+ "updated",
84
100
  "tps",
85
101
  "spark",
86
102
  "reasoning",
@@ -163,6 +179,12 @@ export interface LayoutHint {
163
179
  * formatter's own default, `"compact"`, applies.
164
180
  */
165
181
  readonly durationStyle?: DurationStyle;
182
+ /**
183
+ * How the `updated` row writes its timestamp. The rail supplies this from
184
+ * `format.timestamp`, whose defaults are a short date and a time with
185
+ * seconds in the host locale and zone.
186
+ */
187
+ readonly timestamp?: TimestampFormat;
166
188
  /**
167
189
  * True when the rail already draws a `total` row.
168
190
  *
@@ -223,8 +245,11 @@ export const DEFAULT_SPARK_WIDTH = 12;
223
245
  * zero would use, so it is byte-identical to a real zero and the rail keeps
224
246
  * its shape while reading alive rather than reading broken. `caution` has no
225
247
  * skeleton — returning `undefined` keeps the annunciator silent when there is
226
- * nothing to say, and its silence is the design. An unknown name also yields
227
- * `undefined`, so a typo stays skipped rather than drawn.
248
+ * nothing to say, and its silence is the design. `updated` has none either:
249
+ * there is no honest zero timestamp (1970 would be a lie), so a persistent row
250
+ * falls back to `sidebar.placeholder` until the host records an action. An
251
+ * unknown name also yields `undefined`, so a typo stays skipped rather than
252
+ * drawn.
228
253
  */
229
254
  export function skeletonValue(field: string, layout: LayoutHint): string | undefined {
230
255
  switch (canonicalField(field)) {
package/src/tui/stats.ts CHANGED
@@ -14,7 +14,8 @@
14
14
  // rates, and ./rows.js the row rendering. This module re-exports the same
15
15
  // public surface it has always had.
16
16
 
17
- export { clip, formatCost, formatCount, formatDuration, fuelBar, sparkline } from "./format.js";
17
+ export { clip, formatCost, formatCount, formatDuration, formatTimestamp, fuelBar, sparkline } from "./format.js";
18
+ export type { TimestampDateStyle, TimestampFormat, TimestampTimeStyle } from "./format.js";
18
19
  export { statLine, statRows, statSegments } from "./rows.js";
19
20
  export type { StatSegment } from "./rows.js";
20
21
  export { ANIMATED_FIELDS, DEFAULT_PLACEHOLDER, STAT_FIELDS, canonicalField, fieldLabel, isStatField, skeletonValue } from "./stat-fields.js";