oc-flight-deck 0.10.3 → 0.11.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.
@@ -5,12 +5,15 @@
5
5
  // Pure: no clock, no I/O, no rendering. Untrusted sample fields are coerced
6
6
  // through ./coerce.js so a garbage value is skipped rather than guessed at.
7
7
  //
8
- // Two rates live here. `sessionThroughput` is the whole-lifetime average, kept
8
+ // Three rates live here. `sessionThroughput` is the whole-lifetime average, kept
9
9
  // as the metric of last resort for a host that exposes no per-message
10
10
  // timestamps. `unionSpanThroughput` is the active-work average: output plus
11
11
  // reasoning tokens divided by the union of the assistant turns' own streaming
12
12
  // spans, so idle and tool-settlement time is never in the denominator and the
13
- // figure freezes once everything settles.
13
+ // figure freezes once everything settles. `createInstantTps` is the live row's
14
+ // tracker: output-only per-poll deltas over generating-time deltas, smoothed
15
+ // with an EWMA and repainted through hysteresis, so the rail shows what the
16
+ // decoder is doing now instead of everything the session ever did.
14
17
 
15
18
  import { asCount, asText } from "./coerce.js";
16
19
 
@@ -94,14 +97,28 @@ export function turnSpan(
94
97
 
95
98
  /**
96
99
  * Identity of one assistant turn: the host's own message id when it carries
97
- * one, otherwise the tuple `(created, completed, output)` that defines the
98
- * record. Retries, replays and re-sent records share a key, so they contribute
99
- * their tokens once and their time once.
100
+ * one, otherwise the tuple `(created, completed)` plus - only once the turn
101
+ * has stopped decoding - its `output` count. A turn with neither end rung yet
102
+ * is still streaming, so its output count is still growing: leaving it out of
103
+ * the key keeps one stable identity across polls instead of re-keying (and
104
+ * re-counting) every snapshot of the same turn. A turn that finished decoding
105
+ * (`streamed` or `completed` recorded) has a final output count, so it stays
106
+ * in the key and two settled turns that share a start stay distinct. Retries,
107
+ * replays and re-sent records share a key, so they contribute their tokens
108
+ * once and their time once.
100
109
  */
101
- export function turnKey(id: unknown, created: unknown, completed: unknown, output: unknown): string {
110
+ export function turnKey(
111
+ id: unknown,
112
+ created: unknown,
113
+ completed: unknown,
114
+ output: unknown,
115
+ streamed?: unknown,
116
+ ): string {
102
117
  const own = asText(id);
103
118
  if (own !== undefined) return `id:${own}`;
104
- return `t:${asCount(created) ?? "?"}:${asCount(completed) ?? "?"}:${asCount(output) ?? "?"}`;
119
+ const stamp = `t:${asCount(created) ?? "?"}:${asCount(completed) ?? "?"}`;
120
+ if (asCount(completed) === undefined && asCount(streamed) === undefined) return stamp;
121
+ return `${stamp}:${asCount(output) ?? "?"}`;
105
122
  }
106
123
 
107
124
  /** Output + reasoning tokens and wall time the accepted turns actually cover. */
@@ -227,3 +244,166 @@ export function unionSpanThroughput(spans: readonly ThroughputSpan[]): number |
227
244
  if (tokens <= 0 || unionMs <= 0) return undefined;
228
245
  return tokens / (Math.max(unionMs, 1_000) / 1_000);
229
246
  }
247
+
248
+ /**
249
+ * Smoothing weight for the instantaneous TPS rate: each new per-poll sample
250
+ * moves the displayed figure 30% of the way toward it. Heavy enough to stop
251
+ * the row flickering on every poll, light enough that a real speedup shows
252
+ * within a few polls rather than sagging behind a lifetime average.
253
+ */
254
+ export const TPS_EWMA_ALPHA = 0.3;
255
+
256
+ /**
257
+ * Minimum generating time (ms) and output tokens before the TPS row draws
258
+ * anything. Below either, a per-poll rate is one lucky sample over a sliver
259
+ * of time - the exact "cheaty" flash the row used to print.
260
+ */
261
+ export const TPS_MIN_GEN_MS = 2_000;
262
+ export const TPS_MIN_TOKENS = 10;
263
+
264
+ /**
265
+ * Hysteresis for the TPS repaint: the held figure moves only when the new
266
+ * smoothed rate differs by at least one whole token/second or by at least
267
+ * ten percent, so sub-token jitter never repaints the row.
268
+ */
269
+ export const TPS_REPAINT_ABS = 1;
270
+ export const TPS_REPAINT_RATIO = 0.1;
271
+
272
+ /**
273
+ * One per-poll instantaneous rate: output-token DELTA over generating-time
274
+ * DELTA, never over idle time. The caller passes only what happened since the
275
+ * previous poll; both deltas exclude idle by construction (the union of
276
+ * streaming spans, or the busy-gated active clock), so a pause can never sag
277
+ * the figure. Returns `undefined` when there is no new generating time to
278
+ * divide by.
279
+ */
280
+ export function instantTpsRate(deltaTokens: unknown, deltaMs: unknown): number | undefined {
281
+ const tokens = asCount(deltaTokens);
282
+ const ms = asCount(deltaMs);
283
+ if (tokens === undefined || ms === undefined || ms <= 0) return undefined;
284
+ return tokens / (ms / 1_000);
285
+ }
286
+
287
+ /**
288
+ * Fold one instantaneous sample into the running rate. The first sample seeds
289
+ * the average directly; every later one moves it `alpha` of the way toward
290
+ * the sample, so a single fast or slow poll bends the figure instead of
291
+ * replacing it.
292
+ */
293
+ export function smoothTpsRate(previous: number | undefined, sample: number, alpha: number = TPS_EWMA_ALPHA): number {
294
+ if (previous === undefined || !Number.isFinite(previous)) return sample;
295
+ if (!Number.isFinite(sample)) return previous;
296
+ return previous + alpha * (sample - previous);
297
+ }
298
+
299
+ /**
300
+ * Whether the held TPS figure should repaint for a new smoothed rate. The
301
+ * first rate always paints; afterwards only a move of at least one tok/s or
302
+ * at least ten percent does, so the row holds steady through noise.
303
+ */
304
+ export function tpsNeedsRepaint(displayed: number | undefined, smoothed: number): boolean {
305
+ if (displayed === undefined || !Number.isFinite(displayed)) return true;
306
+ if (!Number.isFinite(smoothed)) return false;
307
+ if (Math.abs(smoothed - displayed) >= TPS_REPAINT_ABS) return true;
308
+ if (displayed === 0) return smoothed !== 0;
309
+ return Math.abs(smoothed - displayed) / Math.abs(displayed) >= TPS_REPAINT_RATIO;
310
+ }
311
+
312
+ /**
313
+ * Output tokens and generating time for the TPS numerator's twin rule.
314
+ *
315
+ * The same identity rule, clamp, pre-sort and merge as `unionSpanTotals`, but
316
+ * the numerator counts OUTPUT tokens only: reasoning has its own row and no
317
+ * longer inflates the rate. A thinking-heavy turn that emits nothing reads as
318
+ * what it is - time spent with no output yet - rather than as speed.
319
+ */
320
+ export function unionOutputTotals(spans: readonly ThroughputSpan[]): SpanTotals {
321
+ const seen = new Set<string>();
322
+ const accepted: Array<{ start: number; end: number }> = [];
323
+ let tokens = 0;
324
+
325
+ for (const span of spans) {
326
+ const key = asText(span.key);
327
+ if (key === undefined || seen.has(key)) continue;
328
+
329
+ const start = asCount(span.start);
330
+ const end = asCount(span.end);
331
+ if (start === undefined || end === undefined) continue;
332
+ const output = asCount(span.tokens);
333
+
334
+ seen.add(key);
335
+ accepted.push({ start, end: Math.max(start, end) });
336
+ tokens += output ?? 0;
337
+ }
338
+
339
+ return { tokens, unionMs: mergedSpanMs(accepted) };
340
+ }
341
+
342
+ /**
343
+ * Near-instantaneous output rate for one displayed session scope.
344
+ *
345
+ * The caller feeds each poll's cumulative output tokens and cumulative
346
+ * generating milliseconds (streaming-span union, or the busy-gated active
347
+ * clock - both exclude idle by construction) plus whether the scope is busy,
348
+ * and gets back the figure to draw, or `undefined` while there is nothing
349
+ * honest to show yet. Deltas between successive polls are the rate; the
350
+ * EWMA smooths it; hysteresis holds the paint; the minimum sample hides the
351
+ * row until ~2 s of generating time and ~10 tokens are on record; and a
352
+ * non-busy poll freezes on the last figure without touching the baselines, so
353
+ * idle can never dilute the rate - it only holds it.
354
+ */
355
+ export function createInstantTps(alpha: number = TPS_EWMA_ALPHA) {
356
+ let prevTokens: number | undefined;
357
+ let prevGenMs: number | undefined;
358
+ let smoothed: number | undefined;
359
+ let displayed: number | undefined;
360
+
361
+ return function sample(
362
+ totalTokens: unknown,
363
+ totalGenMs: unknown,
364
+ busy: unknown,
365
+ ): number | undefined {
366
+ // Not busy means frozen: hold the last figure, baselines untouched, so
367
+ // the idle stretch contributes nothing to either side of the next delta.
368
+ if (busy === false) return displayed;
369
+
370
+ const tokens = asCount(totalTokens);
371
+ const genMs = asCount(totalGenMs);
372
+ if (tokens === undefined || genMs === undefined) return displayed;
373
+
374
+ // First sight sets the baselines. The cumulative active average seeds the
375
+ // smoother, but only once the minimum sample is on record - before that
376
+ // the row hides rather than flashing a one-sample rate.
377
+ if (prevTokens === undefined || prevGenMs === undefined) {
378
+ prevTokens = tokens;
379
+ prevGenMs = genMs;
380
+ if (tokens < TPS_MIN_TOKENS || genMs < TPS_MIN_GEN_MS) return displayed;
381
+ smoothed = tokens / (genMs / 1_000);
382
+ if (tpsNeedsRepaint(displayed, smoothed)) displayed = smoothed;
383
+ return displayed;
384
+ }
385
+
386
+ const deltaTokens = tokens - prevTokens;
387
+ const deltaMs = genMs - prevGenMs;
388
+ // Counters must not step backwards; a reset rebaselines - baselines and
389
+ // smoother alike, since the pre-reset average belongs to another era -
390
+ // instead of dividing a negative delta into a nonsense rate.
391
+ if (deltaTokens < 0 || deltaMs < 0) {
392
+ prevTokens = tokens;
393
+ prevGenMs = genMs;
394
+ smoothed = undefined;
395
+ return displayed;
396
+ }
397
+ prevTokens = tokens;
398
+ prevGenMs = genMs;
399
+
400
+ if (tokens < TPS_MIN_TOKENS || genMs < TPS_MIN_GEN_MS) return displayed;
401
+ // No new generating time: nothing was produced *in time*, so there is no
402
+ // sample - hold, rather than dividing zero new tokens by zero new time.
403
+ if (deltaMs <= 0) return displayed;
404
+ const instant = deltaTokens / (deltaMs / 1_000);
405
+ smoothed = smoothTpsRate(smoothed, instant, alpha);
406
+ if (tpsNeedsRepaint(displayed, smoothed)) displayed = smoothed;
407
+ return displayed;
408
+ };
409
+ }