oc-flight-deck 0.6.3 → 0.6.7

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.
@@ -1,16 +1,22 @@
1
- // Session throughput: output tokens per second, as a lifetime average or as a
2
- // trailing-window rate.
1
+ // Session throughput: output tokens per second, measured over the active work
2
+ // the host actually recorded rather than over the wall clock.
3
3
  //
4
4
  // Pure: no clock, no I/O, no rendering. Untrusted sample fields are coerced
5
5
  // through ./coerce.js so a garbage value is skipped rather than guessed at.
6
+ //
7
+ // Two rates live here. `sessionThroughput` is the whole-lifetime average, kept
8
+ // as the metric of last resort for a host that exposes no per-message
9
+ // timestamps. `unionSpanThroughput` is the active-work average: output tokens
10
+ // divided by the union of the assistant turns' own spans, so idle between turns
11
+ // is never in the denominator and the figure freezes once everything settles.
6
12
 
7
- import { asCount } from "./coerce.js";
13
+ import { asCount, asText } from "./coerce.js";
8
14
 
9
15
  /**
10
16
  * Overall session throughput: output tokens over the session's lifetime.
11
17
  *
12
- * Unlike a per-turn rate, this is the whole conversation's average, so it
13
- * includes every subagent and every pause. A just-started session is floored
18
+ * Unlike the active-work average, this is the whole conversation's average, so
19
+ * it includes every subagent and every pause. A just-started session is floored
14
20
  * at one second so it cannot divide by a sliver of time and flash an absurd
15
21
  * rate. Returns `undefined` when there is nothing to divide.
16
22
  */
@@ -22,64 +28,170 @@ export function sessionThroughput(outputTokens: unknown, elapsedMs: unknown): nu
22
28
  return output / (Math.max(elapsed, 1_000) / 1_000);
23
29
  }
24
30
 
25
- /** Length of the trailing window, in milliseconds, that `windowedThroughput` measures. */
26
- export const TPS_WINDOW_MS = 60_000;
27
-
28
31
  /**
29
- * One assistant turn's contribution to a throughput window.
32
+ * One assistant turn's contribution to the active-work average.
30
33
  *
31
- * Both fields are untrusted: `tokens` is the turn's output count and `at` is the
32
- * timestamp it finished at. Anything unusable is skipped rather than guessed at.
34
+ * `key` is the turn's identity (see `turnKey`); `tokens` is its output count;
35
+ * `start` and `end` are its span on the host's epoch clock. Every field is
36
+ * untrusted and coerced before use.
33
37
  */
34
- export interface ThroughputSample {
38
+ export interface ThroughputSpan {
39
+ readonly key?: unknown;
35
40
  readonly tokens?: unknown;
36
- readonly at?: unknown;
41
+ readonly start?: unknown;
42
+ readonly end?: unknown;
37
43
  }
38
44
 
39
45
  /**
40
- * A trailing-window throughput rate: output tokens per second over the last
41
- * `windowMs`, measured from `nowMs`.
46
+ * Resolve one assistant turn's span from its timestamp rungs.
42
47
  *
43
- * The denominator is how much of the window the session has actually lived, so
44
- * a just-started session ramps up against its real age instead of being divided
45
- * by a full minute it has not run — floored at one second, the same floor the
46
- * lifetime average uses, so a sliver of time cannot flash an absurd rate. Once
47
- * the session is older than the window, it settles into a clean rolling minute.
48
+ * `start` is `time.created`. `end` is `time.completed`, else `time.streamed`,
49
+ * else the caller's `nowMs` for a turn still in flight. A clock that steps
50
+ * backwards is clamped to a zero-length span rather than a negative one, so
51
+ * skew can never subtract time from the union. Returns `undefined` when there
52
+ * is no usable start — the turn is skipped, never guessed at.
53
+ */
54
+ export function turnSpan(
55
+ created: unknown,
56
+ completed: unknown,
57
+ streamed: unknown,
58
+ nowMs: unknown,
59
+ ): { readonly start: number; readonly end: number } | undefined {
60
+ const start = asCount(created);
61
+ if (start === undefined) return undefined;
62
+ const ended = asCount(completed) ?? asCount(streamed) ?? asCount(nowMs);
63
+ if (ended === undefined) return undefined;
64
+ return { start, end: Math.max(start, ended) };
65
+ }
66
+
67
+ /**
68
+ * Identity of one assistant turn: the host's own message id when it carries
69
+ * one, otherwise the tuple `(created, completed, output)` that defines the
70
+ * record. Retries, replays and re-sent records share a key, so they contribute
71
+ * their tokens once and their time once.
72
+ */
73
+ export function turnKey(id: unknown, created: unknown, completed: unknown, output: unknown): string {
74
+ const own = asText(id);
75
+ if (own !== undefined) return `id:${own}`;
76
+ return `t:${asCount(created) ?? "?"}:${asCount(completed) ?? "?"}:${asCount(output) ?? "?"}`;
77
+ }
78
+
79
+ /** Output tokens and wall time the accepted turns actually cover. */
80
+ export interface SpanTotals {
81
+ readonly tokens: number;
82
+ readonly unionMs: number;
83
+ }
84
+
85
+ /**
86
+ * The merged length of already-accepted spans.
48
87
  *
49
- * Returns `undefined` — the caller hides the row — unless at least one sample
50
- * carries a usable timestamp inside the window and a positive output count. An
51
- * idle session therefore reports no rate rather than a decaying one. The window
52
- * is inclusive at both ends (`start <= at <= now`) so a boundary sample counts.
88
+ * The shared second half of both unions: it pre-sorts so the result cannot
89
+ * depend on the order the host returned the spans, then merges overlapping and
90
+ * touching spans (`next.start <= openEnd`, so a span that starts exactly when
91
+ * another ends is continuous work) into one. `0` when nothing was accepted.
92
+ */
93
+ function mergedSpanMs(accepted: Array<{ start: number; end: number }>): number {
94
+ // Pre-sort so the merge cannot depend on the order the host returned them.
95
+ accepted.sort((a, b) => a.start - b.start || a.end - b.end);
96
+ const first = accepted[0];
97
+ if (first === undefined) return 0;
98
+
99
+ let unionMs = 0;
100
+ let openStart = first.start;
101
+ let openEnd = first.end;
102
+ for (let index = 1; index < accepted.length; index += 1) {
103
+ const next = accepted[index];
104
+ if (next === undefined) continue;
105
+ // Touching spans (`next.start === openEnd`) merge as well as overlapping
106
+ // ones: a turn that starts exactly when another ends is continuous work.
107
+ if (next.start <= openEnd) {
108
+ if (next.end > openEnd) openEnd = next.end;
109
+ } else {
110
+ unionMs += openEnd - openStart;
111
+ openStart = next.start;
112
+ openEnd = next.end;
113
+ }
114
+ }
115
+ unionMs += openEnd - openStart;
116
+
117
+ return unionMs;
118
+ }
119
+
120
+ /**
121
+ * Sum the tokens of distinct turns and the union length of their spans.
53
122
  *
54
- * Pure: no clock, no I/O, no rendering.
123
+ * De-duplicates by `key` first, so a re-sent record adds its tokens once and
124
+ * enters the union once — a dropped duplicate drops both sides together.
125
+ * Spans are clamped (`end >= start`), then sorted and merged so overlapping
126
+ * and touching turns count once and input order cannot change the result. A
127
+ * turn with no usable token count contributes to neither side: the numerator
128
+ * and the denominator always cover exactly the same turns.
55
129
  */
56
- export function windowedThroughput(
57
- samples: readonly ThroughputSample[],
58
- nowMs: number,
59
- windowMs: number,
60
- sessionCreatedMs: number,
61
- ): number | undefined {
62
- if (!Number.isFinite(nowMs)) return undefined;
63
- if (!Number.isFinite(windowMs) || windowMs <= 0) return undefined;
64
-
65
- // An unusable creation time cannot tell us how long the session has lived, so
66
- // the whole window is assumed available rather than dropping the rate.
67
- const created = Number.isFinite(sessionCreatedMs) ? sessionCreatedMs : undefined;
68
- const alive = created === undefined ? windowMs : nowMs - created;
69
- const denominatorMs = Math.max(1_000, Math.min(windowMs, alive));
70
-
71
- const start = nowMs - windowMs;
72
- let output = 0;
73
- let sawOne = false;
74
- for (const sample of samples) {
75
- const at = asCount(sample.at);
76
- if (at === undefined || at < start || at > nowMs) continue;
77
- const tokens = asCount(sample.tokens);
78
- if (tokens === undefined || tokens <= 0) continue;
79
- output += tokens;
80
- sawOne = true;
130
+ export function unionSpanTotals(spans: readonly ThroughputSpan[]): SpanTotals {
131
+ const seen = new Set<string>();
132
+ const accepted: Array<{ start: number; end: number }> = [];
133
+ let tokens = 0;
134
+
135
+ for (const span of spans) {
136
+ const key = asText(span.key);
137
+ if (key === undefined || seen.has(key)) continue;
138
+
139
+ const start = asCount(span.start);
140
+ const end = asCount(span.end);
141
+ const output = asCount(span.tokens);
142
+ if (start === undefined || end === undefined) continue;
143
+ if (output === undefined || output <= 0) continue;
144
+
145
+ seen.add(key);
146
+ accepted.push({ start, end: Math.max(start, end) });
147
+ tokens += output;
148
+ }
149
+
150
+ return { tokens, unionMs: mergedSpanMs(accepted) };
151
+ }
152
+
153
+ /**
154
+ * The union length of distinct turn spans, with tokens ignored entirely.
155
+ *
156
+ * The same identity rule, clamp, pre-sort and merge as `unionSpanTotals`, but
157
+ * a turn's output count never enters the decision: a zero-output turn still
158
+ * took wall time and still contributes its span. This is what seeds `elapsed`,
159
+ * which must not undercount real work the way a token-gated union would.
160
+ * A missing key is skipped; the first-seen key wins; a span without a usable
161
+ * start and end is skipped; `0` when nothing is usable.
162
+ */
163
+ export function unionSpanMs(spans: readonly ThroughputSpan[]): number {
164
+ const seen = new Set<string>();
165
+ const accepted: Array<{ start: number; end: number }> = [];
166
+
167
+ for (const span of spans) {
168
+ const key = asText(span.key);
169
+ if (key === undefined || seen.has(key)) continue;
170
+
171
+ const start = asCount(span.start);
172
+ const end = asCount(span.end);
173
+ if (start === undefined || end === undefined) continue;
174
+
175
+ seen.add(key);
176
+ accepted.push({ start, end: Math.max(start, end) });
81
177
  }
82
178
 
83
- if (!sawOne) return undefined;
84
- return output / (denominatorMs / 1_000);
179
+ return mergedSpanMs(accepted);
180
+ }
181
+
182
+ /**
183
+ * Active-work throughput: output tokens of the scope divided by the union of
184
+ * its active turn spans. Idle time between turns is not in the denominator, so
185
+ * the figure stops moving once everything settles instead of decaying or
186
+ * hiding. A turn still in flight ends at the caller's `now`, so the value keeps
187
+ * climbing while work happens.
188
+ *
189
+ * Floored at one second, the same floor the lifetime average uses, so a sliver
190
+ * of time cannot flash an absurd rate. Returns `undefined` when there is
191
+ * nothing to divide — no positive output, or no span with positive length.
192
+ */
193
+ export function unionSpanThroughput(spans: readonly ThroughputSpan[]): number | undefined {
194
+ const { tokens, unionMs } = unionSpanTotals(spans);
195
+ if (tokens <= 0 || unionMs <= 0) return undefined;
196
+ return tokens / (Math.max(unionMs, 1_000) / 1_000);
85
197
  }