paseo-turn-speed 1.0.1 → 1.2.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/client/meter.ts CHANGED
@@ -16,7 +16,29 @@
16
16
  * Whenever the provider reports the model is blocked on the user (a question
17
17
  * or permission request), that interval is tracked separately: it is removed
18
18
  * from step decode/wait windows and from the whole-turn rate, while the turn
19
- * clock itself keeps running in wall time.
19
+ * clock itself keeps running in wall time. While the agent's work runs in
20
+ * subagents (a delegated interval), that time is likewise removed from the
21
+ * whole-turn rate — the subagents' own pills carry their speed — but it stays
22
+ * inside decode/wait windows, because a delegated call is just another tool
23
+ * run between the agent's model calls.
24
+ *
25
+ * Thinking tokens: some providers (measured on OpenCode + local reasoning
26
+ * models) report `output` with the reasoning tokens subtracted while the
27
+ * thinking itself streams as reasoning text and its decode time sits in the
28
+ * step window. Counting only `output` then under-reports rates by the whole
29
+ * thinking share. When a closed step shows far more reasoning characters
30
+ * than its output tokens could pay for, the meter marks the turn as
31
+ * `thinkingExcluded` and credits an estimate of the thinking tokens (reasoning
32
+ * characters divided by the reasoning-specific chars/token ratio, measured
33
+ * well above the visible-text one), marked approximate: reasoning that streamed
34
+ * from the step start covers its own window time and enters the decode rate;
35
+ * reasoning delivered as a late bulk (after the step's visible text began)
36
+ * has no measured time, so it only enters turn totals and the whole-turn
37
+ * rate. Providers that report thinking inside `output` never trigger this.
38
+ *
39
+ * Usage deltas the plausibility guard rejects are not dropped: they land in
40
+ * `unattributedTokens`, counted in token totals and the whole-turn rate
41
+ * without a decode window of their own.
20
42
  */
21
43
 
22
44
  /** A live-window text gap longer than this is treated as a stall. */
@@ -32,6 +54,32 @@ const MAX_TEXT_KEYS = 32;
32
54
  export const CAL_MIN = 2;
33
55
  export const CAL_MAX = 8;
34
56
  export const CAL_MIN_CHARS = 40;
57
+ /** A closed step whose reasoning characters exceed its output tokens by this
58
+ * much cannot be reporting thinking inside `output`: mark the turn as one
59
+ * where the provider excludes reasoning tokens from the reported numbers. */
60
+ export const EXCLUDED_EVIDENCE_RATIO = 8;
61
+ /** Below this many reasoning characters the evidence above is too noisy. */
62
+ export const EXCLUDED_MIN_CHARS = 200;
63
+ /** Reasoning prose encodes more characters per token than visible answers,
64
+ * and the calibrated visible ratio is additionally biased low: usage
65
+ * `output` counts tool-call arguments, which never stream as text. Measured
66
+ * across ~41k reasoning tokens of real OpenCode + local reasoning sessions:
67
+ * streamed reasoning text runs ~3.7 characters per reasoning token, so the
68
+ * thinking estimate uses this dedicated ratio instead of the model's
69
+ * visible-text calibration. */
70
+ export const REASONING_CHARS_PER_TOKEN = 3.7;
71
+ /** A closed step whose reported output tokens already pay for its streamed
72
+ * reasoning characters — at most 1.4× the reasoning ratio, headroom for
73
+ * token-dense prose — says thinking is inside `output`: excluded heavy
74
+ * thinking could not be this cheap to report. Between this and
75
+ * EXCLUDED_EVIDENCE_RATIO sits a neutral band that concludes nothing. A
76
+ * single such step can also be a tool-heavy fluke on an excluding provider,
77
+ * so a streak of them is needed to revoke the verdict — e.g. after the
78
+ * provider config started including usage differently. One excluding-style
79
+ * step re-arms it, so a wrong revocation costs at most a step of
80
+ * undercounting; without revocation a wrong verdict double-counts forever. */
81
+ export const INCLUSION_EVIDENCE_RATIO = REASONING_CHARS_PER_TOKEN * 1.4;
82
+ export const INCLUSION_EVIDENCE_STEPS = 3;
35
83
 
36
84
  export interface UsageSnapshot {
37
85
  input?: number | null;
@@ -52,6 +100,13 @@ export interface StepRecord {
52
100
  inputTokens: number;
53
101
  /** Cached prompt tokens this call reported. */
54
102
  cachedTokens: number;
103
+ /** Reasoning characters streamed during this step (thinking estimate). */
104
+ thinkingChars: number;
105
+ /** The subset that arrived late (after the step's visible text started):
106
+ * a bulk delivery of the reasoning block, whose generation time the step
107
+ * window never saw. Their tokens count in turn totals but not in the
108
+ * decode-window rate. */
109
+ thinkingLateChars: number;
55
110
  /** Prefill/TTFT measured on the first step only, else 0. */
56
111
  prefillMs: number;
57
112
  }
@@ -74,6 +129,11 @@ export interface MeterState {
74
129
  lastTextAt: number | null;
75
130
  /** First text since the last step boundary (null = re-anchored). */
76
131
  stepFirstTextAt: number | null;
132
+ /** First visible-text and first reasoning growth since the step boundary.
133
+ * Their order tells streamed thinking (window-covering) from a late bulk
134
+ * delivery of a reasoning block (whose generation time the window misses). */
135
+ stepFirstVisibleAt: number | null;
136
+ stepFirstReasoningAt: number | null;
77
137
  /** Usage arrival of the last completed step. */
78
138
  prevStepEndAt: number | null;
79
139
  /** Per-message observed text length (snapshot vs delta normalised). */
@@ -95,10 +155,32 @@ export interface MeterState {
95
155
  liveChars: number;
96
156
  /** All characters streamed this turn (fallback estimate). */
97
157
  totalChars: number;
158
+ /** Reasoning-only characters since the last step boundary (⊆ liveChars). */
159
+ liveReasoningChars: number;
160
+ /** Reasoning-only characters streamed this turn (⊆ totalChars). */
161
+ totalReasoningChars: number;
162
+ /** Usage tokens the plausibility guard rejected, kept for whole-turn totals. */
163
+ unattributedTokens: number;
164
+ /** Set once a step showed reasoning characters no `output` figure could
165
+ * pay for: this provider excludes thinking from its reported output, so
166
+ * rates add an estimate from the streamed reasoning text. */
167
+ thinkingExcluded: boolean;
168
+ /** Model id (`model_changed`) the verdict belongs to: an exclusion is a
169
+ * provider-model property, so switching to a model that reports thinking
170
+ * inside `output` must not double-count it. Null while the identity was
171
+ * not yet known when the verdict was learned. */
172
+ thinkingExcludedModel: string | null;
173
+ /** Consecutive closed steps whose `output` already paid for the streamed
174
+ * reasoning characters; enough of them revoke a stale verdict. */
175
+ inclusionStreak: number;
98
176
  /** Completed user-wait intervals inside this turn. */
99
177
  userWaits: readonly UserWaitInterval[];
100
178
  /** Start of the open user-wait interval, null when the model is live. */
101
179
  pausedAt: number | null;
180
+ /** Completed intervals where the agent's work ran in subagents. */
181
+ delegatedWaits: readonly UserWaitInterval[];
182
+ /** Start of the open delegation interval, null while the agent runs alone. */
183
+ delegatedAt: number | null;
102
184
  /** True once any real usage step landed during this turn. */
103
185
  sawUsage: boolean;
104
186
  /** Set when a usage delta was dropped as physically impossible. */
@@ -111,14 +193,21 @@ export interface MeterState {
111
193
 
112
194
  export type MeterAction =
113
195
  | { t: "turn_started"; at: number; turnId: string | null }
114
- | { t: "text"; at: number; key: string; text: string }
196
+ | { t: "text"; at: number; key: string; text: string; kind?: "text" | "reasoning" }
115
197
  | { t: "usage"; at: number; usage: UsageSnapshot; maxTokPerSec?: number }
116
198
  | { t: "compaction"; at: number }
117
199
  /** The model blocked on the user (question asked, permission pending). */
118
200
  | { t: "user_wait_started"; at: number }
119
201
  /** The user answered: the model woke up. */
120
202
  | { t: "user_wait_ended"; at: number }
203
+ /** Subagents of this agent started running: the model is delegated. */
204
+ | { t: "delegated_started"; at: number }
205
+ /** All subagents finished: the agent works alone again. */
206
+ | { t: "delegated_ended"; at: number }
121
207
  | { t: "turn_ended"; at: number; kind: "completed" | "failed" | "canceled"; usage?: UsageSnapshot; maxTokPerSec?: number; note?: string | null }
208
+ /** The agent switched model (or its identity just became known): a
209
+ * thinking-exclusion verdict learned on another model must not carry. */
210
+ | { t: "model_changed"; model: string | null }
122
211
  /** Drop the locally observed turn (epoch replacement, reconnect, reload). */
123
212
  | { t: "reset" };
124
213
 
@@ -130,6 +219,8 @@ export function initialMeterState(): MeterState {
130
219
  firstTextAt: null,
131
220
  lastTextAt: null,
132
221
  stepFirstTextAt: null,
222
+ stepFirstVisibleAt: null,
223
+ stepFirstReasoningAt: null,
133
224
  prevStepEndAt: null,
134
225
  textLens: {},
135
226
  textTails: {},
@@ -144,8 +235,16 @@ export function initialMeterState(): MeterState {
144
235
  steps: [],
145
236
  liveChars: 0,
146
237
  totalChars: 0,
238
+ liveReasoningChars: 0,
239
+ totalReasoningChars: 0,
240
+ unattributedTokens: 0,
241
+ thinkingExcluded: false,
242
+ thinkingExcludedModel: null,
243
+ inclusionStreak: 0,
147
244
  userWaits: [],
148
245
  pausedAt: null,
246
+ delegatedWaits: [],
247
+ delegatedAt: null,
149
248
  sawUsage: false,
150
249
  stepRejected: null,
151
250
  calibInput: null,
@@ -193,7 +292,13 @@ function growText(
193
292
  return { lens, tails, growth };
194
293
  }
195
294
 
196
- function applyText(state: MeterState, at: number, key: string, text: string): MeterState {
295
+ function applyText(
296
+ state: MeterState,
297
+ at: number,
298
+ key: string,
299
+ text: string,
300
+ isReasoning: boolean,
301
+ ): MeterState {
197
302
  if (state.phase !== "running" || text.length === 0) return state;
198
303
  const { lens, tails, growth } = growText(state, key, text);
199
304
  if (growth <= 0) return state;
@@ -203,9 +308,15 @@ function applyText(state: MeterState, at: number, key: string, text: string): Me
203
308
  textTails: tails,
204
309
  firstTextAt: state.firstTextAt === null ? at : state.firstTextAt,
205
310
  stepFirstTextAt: state.stepFirstTextAt === null ? at : state.stepFirstTextAt,
311
+ stepFirstVisibleAt:
312
+ !isReasoning && state.stepFirstVisibleAt === null ? at : state.stepFirstVisibleAt,
313
+ stepFirstReasoningAt:
314
+ isReasoning && state.stepFirstReasoningAt === null ? at : state.stepFirstReasoningAt,
206
315
  lastTextAt: at,
207
316
  liveChars: state.liveChars + growth,
208
317
  totalChars: state.totalChars + growth,
318
+ liveReasoningChars: isReasoning ? state.liveReasoningChars + growth : state.liveReasoningChars,
319
+ totalReasoningChars: isReasoning ? state.totalReasoningChars + growth : state.totalReasoningChars,
209
320
  };
210
321
  }
211
322
 
@@ -243,6 +354,45 @@ function closeWait(state: MeterState, at: number): MeterState {
243
354
  };
244
355
  }
245
356
 
357
+ /** Move the open delegation interval into the completed list. */
358
+ function closeDelegated(state: MeterState, at: number): MeterState {
359
+ return state.delegatedAt === null
360
+ ? state
361
+ : {
362
+ ...state,
363
+ delegatedAt: null,
364
+ delegatedWaits: [
365
+ ...state.delegatedWaits,
366
+ { start: state.delegatedAt, end: Math.max(at, state.delegatedAt) },
367
+ ],
368
+ };
369
+ }
370
+
371
+ /** Milliseconds inside [from, to] covered by at least one interval, counting
372
+ * overlapping intervals once (a user wait during a delegation is one pause,
373
+ * not two). */
374
+ function unionOverlapMs(intervals: readonly UserWaitInterval[], from: number, to: number): number {
375
+ if (to <= from) return 0;
376
+ const clipped = intervals
377
+ .map((wait) => [Math.max(wait.start, from), Math.min(wait.end, to)] as const)
378
+ .filter(([start, end]) => end > start)
379
+ .sort((a, b) => a[0] - b[0]);
380
+ let total = 0;
381
+ let runStart = Number.NEGATIVE_INFINITY;
382
+ let runEnd = Number.NEGATIVE_INFINITY;
383
+ for (const [start, end] of clipped) {
384
+ if (start > runEnd) {
385
+ if (runEnd > runStart) total += runEnd - runStart;
386
+ runStart = start;
387
+ runEnd = end;
388
+ } else if (end > runEnd) {
389
+ runEnd = end;
390
+ }
391
+ }
392
+ if (runEnd > runStart) total += runEnd - runStart;
393
+ return total;
394
+ }
395
+
246
396
  function applyUsage(
247
397
  state: MeterState,
248
398
  at: number,
@@ -295,6 +445,9 @@ function applyUsage(
295
445
  return {
296
446
  ...withCounters,
297
447
  calibInput: null,
448
+ // Real tokens with no trustworthy window of their own: keep them in
449
+ // the turn totals instead of letting them vanish from every rate.
450
+ unattributedTokens: state.unattributedTokens + outDelta.amount,
298
451
  stepRejected: { tokens: outDelta.amount, windowMs: stepDecodeMs },
299
452
  };
300
453
  }
@@ -302,23 +455,59 @@ function applyUsage(
302
455
  state.steps.length === 0 && state.firstTextAt !== null && state.startedAt !== null
303
456
  ? Math.max(0, state.firstTextAt - state.startedAt)
304
457
  : 0;
458
+ // Reasoning that showed up only after this step's visible text was already
459
+ // streaming is a bulk delivery of the finished block: the window missed
460
+ // its generation. Reasoning that led (or carried) the window covered it.
461
+ const reasoningLate =
462
+ state.liveReasoningChars > 0 &&
463
+ state.stepFirstVisibleAt !== null &&
464
+ (state.stepFirstReasoningAt === null || state.stepFirstReasoningAt > state.stepFirstVisibleAt);
305
465
  const step: StepRecord = {
306
466
  outTokens: outDelta.amount,
307
467
  decodeMs: stepDecodeMs,
308
468
  waitMs: stepWaitMs,
309
469
  inputTokens: inDelta.amount,
310
470
  cachedTokens: cachedDelta.amount,
471
+ thinkingChars: state.liveReasoningChars,
472
+ thinkingLateChars: reasoningLate ? state.liveReasoningChars : 0,
311
473
  prefillMs,
312
474
  };
475
+ // More streamed reasoning characters than this step's output tokens could
476
+ // possibly contain: the provider subtracts thinking from `output`.
477
+ const thinkingEvidence =
478
+ state.liveReasoningChars >= EXCLUDED_MIN_CHARS &&
479
+ state.liveReasoningChars > outDelta.amount * EXCLUDED_EVIDENCE_RATIO;
480
+ // The opposite signal: this step streamed meaningful reasoning yet its
481
+ // reported output tokens alone already pay for those characters, meaning
482
+ // the thinking is inside `output`. A single such step can also be a
483
+ // tool-heavy step on an excluding provider, so a streak of them is needed
484
+ // to revoke the verdict; one excluding-style step re-arms it.
485
+ const inclusionEvidence =
486
+ state.thinkingExcluded &&
487
+ !thinkingEvidence &&
488
+ state.liveReasoningChars >= EXCLUDED_MIN_CHARS &&
489
+ state.liveReasoningChars <= outDelta.amount * INCLUSION_EVIDENCE_RATIO;
490
+ const inclusionStreak = inclusionEvidence ? state.inclusionStreak + 1 : 0;
491
+ const revoked = inclusionStreak >= INCLUSION_EVIDENCE_STEPS;
313
492
  return {
314
493
  ...withCounters,
315
494
  steps: [...state.steps, step],
316
495
  stepFirstTextAt: null,
496
+ stepFirstVisibleAt: null,
497
+ stepFirstReasoningAt: null,
317
498
  prevStepEndAt: at,
318
499
  liveChars: 0,
500
+ liveReasoningChars: 0,
319
501
  sawUsage: true,
502
+ thinkingExcluded: revoked ? false : state.thinkingExcluded || thinkingEvidence,
503
+ inclusionStreak: revoked ? 0 : inclusionStreak,
320
504
  stepRejected: null,
321
- calibInput: { chars: state.liveChars, tokens: outDelta.amount },
505
+ // Calibration pairs visible characters with visible tokens: reasoning
506
+ // text must not enter it, or the ratio saturates against excluded output.
507
+ calibInput: {
508
+ chars: state.liveChars - state.liveReasoningChars,
509
+ tokens: outDelta.amount,
510
+ },
322
511
  };
323
512
  }
324
513
 
@@ -333,8 +522,14 @@ function endTurn(
333
522
  // A repeated cumulative payload contributes no delta and opens no step.
334
523
  const withUsage = usage ? applyUsage(state, at, usage, maxTokPerSec) : state;
335
524
  if (withUsage.phase !== "running") return state;
336
- // A turn that ends while a question is still open closes the wait there.
337
- return { ...closeWait(withUsage, at), phase: kind, endedAt: at, endNote: note };
525
+ // A turn that ends while a question is still open closes the wait there;
526
+ // same for an ongoing delegation.
527
+ return {
528
+ ...closeDelegated(closeWait(withUsage, at), at),
529
+ phase: kind,
530
+ endedAt: at,
531
+ endNote: note,
532
+ };
338
533
  }
339
534
 
340
535
  export function reduceMeter(state: MeterState, action: MeterAction): MeterState {
@@ -355,16 +550,34 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
355
550
  prevUsageOut: state.prevUsageOut,
356
551
  prevUsageIn: state.prevUsageIn,
357
552
  prevUsageCached: state.prevUsageCached,
553
+ // A provider-level property: survives turns like the usage baseline
554
+ // — but only when it has a known owner. A verdict that never got a
555
+ // model identity cannot tell an unchanged provider from an invisible
556
+ // model switch, so each new turn re-derives it from fresh evidence.
557
+ thinkingExcluded:
558
+ state.thinkingExcludedModel === null ? false : state.thinkingExcluded,
559
+ thinkingExcludedModel: state.thinkingExcludedModel,
560
+ inclusionStreak: state.thinkingExcludedModel === null ? 0 : state.inclusionStreak,
358
561
  };
359
562
  }
360
563
  case "text":
361
- return applyText(state, action.at, action.key, action.text);
564
+ return applyText(
565
+ state,
566
+ action.at,
567
+ action.key,
568
+ action.text,
569
+ action.kind === "reasoning" ||
570
+ // Backwards compatibility with callers using the legacy key scheme.
571
+ (action.kind === undefined && action.key.startsWith("reasoning")),
572
+ );
362
573
  case "usage":
363
574
  return applyUsage(state, action.at, action.usage, action.maxTokPerSec);
364
575
  case "compaction":
365
576
  // Context was rewritten; streamed chars since the last step no longer
366
577
  // map to answer tokens. Drop the live window, keep step history.
367
- return state.phase === "running" ? { ...state, liveChars: 0 } : state;
578
+ return state.phase === "running"
579
+ ? { ...state, liveChars: 0, liveReasoningChars: 0 }
580
+ : state;
368
581
  case "user_wait_started":
369
582
  return state.phase === "running" && state.pausedAt === null
370
583
  ? { ...state, pausedAt: action.at }
@@ -372,6 +585,13 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
372
585
  case "user_wait_ended":
373
586
  // An end for a wait we never saw (resolved before attach) is a no-op.
374
587
  return state.pausedAt === null ? state : closeWait(state, action.at);
588
+ case "delegated_started":
589
+ return state.phase === "running" && state.delegatedAt === null
590
+ ? { ...state, delegatedAt: action.at }
591
+ : state;
592
+ case "delegated_ended":
593
+ // An end for a delegation we never saw is a no-op.
594
+ return state.delegatedAt === null ? state : closeDelegated(state, action.at);
375
595
  case "turn_ended":
376
596
  return endTurn(state, action.at, action.kind, action.usage, action.maxTokPerSec, action.note ?? null);
377
597
  case "reset":
@@ -385,7 +605,29 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
385
605
  prevUsageOut: state.prevUsageOut,
386
606
  prevUsageIn: state.prevUsageIn,
387
607
  prevUsageCached: state.prevUsageCached,
608
+ thinkingExcluded: state.thinkingExcluded,
609
+ thinkingExcludedModel: state.thinkingExcludedModel,
610
+ inclusionStreak: state.inclusionStreak,
611
+ };
612
+ case "model_changed": {
613
+ const model = action.model;
614
+ // An unknown identity must never clear a learned verdict: the model
615
+ // simply is not on record yet.
616
+ if (model === null || model === state.thinkingExcludedModel) return state;
617
+ // A verdict learned before identity was known belongs to it: adopt
618
+ // rather than revoke, the first concrete model is what we observed.
619
+ if (state.thinkingExcluded && state.thinkingExcludedModel === null) {
620
+ return { ...state, thinkingExcludedModel: model };
621
+ }
622
+ // Another model: the exclusion verdict was its property, not this
623
+ // model's. Steps of the current turn stay; only the verdict resets.
624
+ return {
625
+ ...state,
626
+ thinkingExcluded: false,
627
+ thinkingExcludedModel: model,
628
+ inclusionStreak: 0,
388
629
  };
630
+ }
389
631
  default:
390
632
  return state;
391
633
  }
@@ -412,6 +654,10 @@ export interface TurnSummary {
412
654
  userWaitMs: number;
413
655
  /** True while an open user-wait interval is running. */
414
656
  waiting: boolean;
657
+ /** Wall milliseconds this turn's work ran inside subagents. */
658
+ delegatedMs: number;
659
+ /** True while at least one subagent is running right now. */
660
+ delegated: boolean;
415
661
  tokPerSecDecode: number | null;
416
662
  /** Tokens per second over turn time minus user waits. */
417
663
  tokPerSecTurn: number | null;
@@ -422,6 +668,14 @@ export interface TurnSummary {
422
668
  cachedTokens: number;
423
669
  /** Prompt tokens of the first step, for the prefill rate. */
424
670
  firstStepPromptTokens: number | null;
671
+ /** Cached prompt tokens of the first step: with a warm cache the prompt
672
+ * was restored, not prefilled, so the prefill rate is hidden then. */
673
+ firstStepCachedTokens: number | null;
674
+ /** Thinking tokens estimated from streamed reasoning characters (0 when
675
+ * the provider reports thinking inside `output` or none was streamed). */
676
+ thinkingTokens: number;
677
+ /** Tokens from rejected usage bursts, counted in totals without a window. */
678
+ unattributedTokens: number;
425
679
  }
426
680
 
427
681
  export function summarizeTurn(state: MeterState, charsPerToken: number, now: number): TurnSummary {
@@ -429,24 +683,64 @@ export function summarizeTurn(state: MeterState, charsPerToken: number, now: num
429
683
  const inputTokens = state.steps.reduce((sum, s) => sum + s.inputTokens, 0);
430
684
  const cachedTokens = state.steps.reduce((sum, s) => sum + s.cachedTokens, 0);
431
685
  const waitMs = state.steps.reduce((sum, s) => sum + s.waitMs, 0);
686
+ const hasReal = state.sawUsage && realOut > 0;
432
687
  // Without any usage step there is no anchored window; the span of streamed
433
688
  // text stands in for it so estimate-only providers still get a decode rate.
689
+ // While a step is open, its streamed characters already sit in `estTokens`
690
+ // (as the tail estimate), so the running window from its first text counts
691
+ // in the decode denominator too: freezing it at the closed steps would
692
+ // divide a growing token count by stale windows and print a burst rate.
693
+ const openWindowMs =
694
+ state.phase === "running" && state.stepFirstTextAt !== null && state.liveChars > 0
695
+ ? Math.max(
696
+ 0,
697
+ now - state.stepFirstTextAt - waitOverlap(state, state.stepFirstTextAt, now),
698
+ )
699
+ : 0;
434
700
  const decodeMs =
435
701
  state.steps.length > 0
436
- ? state.steps.reduce((sum, s) => sum + s.decodeMs, 0)
702
+ ? state.steps.reduce((sum, s) => sum + s.decodeMs, 0) + openWindowMs
437
703
  : state.firstTextAt !== null && state.lastTextAt !== null
438
704
  ? Math.max(0, state.lastTextAt - state.firstTextAt)
439
705
  : 0;
440
- const hasReal = state.sawUsage && realOut > 0;
441
- const tailEst = state.liveChars / charsPerToken;
442
- const wholeEst = state.totalChars / charsPerToken;
706
+ // Thinking estimate for providers detected as excluding reasoning from
707
+ // `output`: reasoning characters converted with the reasoning-specific
708
+ // chars/token ratio (visible-text calibration is biased by tool args).
709
+ // Early thinking (reasoning led the step window) both adds tokens and was
710
+ // paid for by window time; late bulks add tokens only, so they may count
711
+ // in turn totals but never in the decode-window rate.
712
+ const stepThinkingChars = state.steps.reduce((sum, s) => sum + s.thinkingChars, 0);
713
+ const earlyThinking = state.thinkingExcluded
714
+ ? state.steps.reduce((sum, s) => sum + (s.thinkingChars - s.thinkingLateChars), 0) /
715
+ REASONING_CHARS_PER_TOKEN
716
+ : 0;
717
+ const lateThinking = state.thinkingExcluded
718
+ ? state.steps.reduce((sum, s) => sum + s.thinkingLateChars, 0) / REASONING_CHARS_PER_TOKEN
719
+ : 0;
720
+ // Live reasoning characters enter the tail estimate only while reasoning
721
+ // leads the open step (its arrival was paced with generation). A trailing
722
+ // bulk of a finished reasoning block would fake a token burst.
723
+ const liveReasoningEarly =
724
+ state.stepFirstReasoningAt !== null &&
725
+ (state.stepFirstVisibleAt === null || state.stepFirstReasoningAt <= state.stepFirstVisibleAt);
726
+ const thinkingTokens = state.thinkingExcluded && hasReal
727
+ ? (stepThinkingChars + (liveReasoningEarly ? state.liveReasoningChars : 0)) /
728
+ REASONING_CHARS_PER_TOKEN
729
+ : 0;
730
+ const tailEst =
731
+ (state.liveChars - state.liveReasoningChars) / charsPerToken +
732
+ (liveReasoningEarly ? state.liveReasoningChars / REASONING_CHARS_PER_TOKEN : 0);
733
+ const wholeEst =
734
+ (state.totalChars - state.totalReasoningChars) / charsPerToken +
735
+ (state.totalReasoningChars - (liveReasoningEarly ? 0 : state.liveReasoningChars)) /
736
+ REASONING_CHARS_PER_TOKEN;
443
737
  let outTokens: number | null = null;
444
738
  let estTokens: number;
445
739
  let approx: boolean;
446
740
  if (hasReal) {
447
741
  outTokens = realOut;
448
- estTokens = realOut + tailEst;
449
- approx = state.liveChars > 0;
742
+ estTokens = realOut + earlyThinking + lateThinking + tailEst + state.unattributedTokens;
743
+ approx = state.liveChars > 0 || earlyThinking + lateThinking > 0 || state.unattributedTokens > 0;
450
744
  } else {
451
745
  estTokens = wholeEst;
452
746
  approx = true;
@@ -460,13 +754,27 @@ export function summarizeTurn(state: MeterState, charsPerToken: number, now: num
460
754
  let userWaitMs = 0;
461
755
  for (const wait of state.userWaits) userWaitMs += Math.max(0, wait.end - wait.start);
462
756
  if (state.pausedAt !== null && end !== null) userWaitMs += Math.max(0, end - state.pausedAt);
757
+ let delegatedMs = 0;
758
+ for (const wait of state.delegatedWaits) delegatedMs += Math.max(0, wait.end - wait.start);
759
+ if (state.delegatedAt !== null && end !== null) delegatedMs += Math.max(0, end - state.delegatedAt);
463
760
  // The turn's productive time: wall clock minus the stretches where the
464
- // model was asleep waiting for the user.
465
- const activeMs = totalMs !== null ? Math.max(0, totalMs - userWaitMs) : null;
761
+ // agent produced nothing itself — blocked on the user or delegated to
762
+ // subagents. Overlapping stretches count once.
763
+ const asleep: UserWaitInterval[] = [...state.userWaits, ...state.delegatedWaits];
764
+ if (state.pausedAt !== null && end !== null) asleep.push({ start: state.pausedAt, end });
765
+ if (state.delegatedAt !== null && end !== null) asleep.push({ start: state.delegatedAt, end });
766
+ const activeMs =
767
+ totalMs !== null && state.startedAt !== null && end !== null
768
+ ? Math.max(0, totalMs - unionOverlapMs(asleep, state.startedAt, end))
769
+ : null;
770
+ // Rejected bursts and late thinking bulks have no decode window of their
771
+ // own, so they count in the whole-turn totals but never inflate the
772
+ // decode-window rate.
773
+ const decodeTokens = hasReal ? estTokens - state.unattributedTokens - lateThinking : estTokens;
466
774
  const tokPerSecDecode =
467
- decodeMs > 0 && estTokens > 0 ? (outTokens ?? estTokens) / (decodeMs / 1000) : null;
775
+ decodeMs > 0 && decodeTokens > 0 ? decodeTokens / (decodeMs / 1000) : null;
468
776
  const tokPerSecTurn =
469
- activeMs !== null && activeMs > 0 && estTokens > 0 ? (outTokens ?? estTokens) / (activeMs / 1000) : null;
777
+ activeMs !== null && activeMs > 0 && estTokens > 0 ? estTokens / (activeMs / 1000) : null;
470
778
  return {
471
779
  outTokens,
472
780
  estTokens,
@@ -477,12 +785,17 @@ export function summarizeTurn(state: MeterState, charsPerToken: number, now: num
477
785
  totalMs,
478
786
  userWaitMs,
479
787
  waiting: state.pausedAt !== null && state.phase === "running",
788
+ delegatedMs,
789
+ delegated: state.delegatedAt !== null && state.phase === "running",
480
790
  tokPerSecDecode,
481
791
  tokPerSecTurn,
482
792
  steps: state.steps.length,
483
793
  inputTokens,
484
794
  cachedTokens,
485
795
  firstStepPromptTokens: state.steps.length > 0 && state.steps[0].inputTokens > 0 ? state.steps[0].inputTokens : null,
796
+ firstStepCachedTokens: state.steps.length > 0 && state.steps[0].cachedTokens > 0 ? state.steps[0].cachedTokens : null,
797
+ thinkingTokens,
798
+ unattributedTokens: state.unattributedTokens,
486
799
  };
487
800
  }
488
801
 
@@ -497,7 +810,12 @@ export function calibrate(
497
810
  ): number | null {
498
811
  if (!(tokens > 0) || !(chars >= minChars)) return null;
499
812
  const observed = chars / tokens;
500
- if (!Number.isFinite(observed) || observed < 1) return null;
813
+ // Below 1.5 char/token the sample is dominated by tool-call arguments
814
+ // (counted in `output` but never streamed as text), not this model's text
815
+ // ratio; above 12 it is usage bookkeeping noise (misattributed deltas).
816
+ // Either end poisons the EMA toward the clamps (a single 20+ sample used to
817
+ // pin the blend at CAL_MAX).
818
+ if (!Number.isFinite(observed) || observed < 1.5 || observed > 12) return null;
501
819
  const base = typeof prev === "number" && Number.isFinite(prev) ? prev : DEFAULT_CHARS_PER_TOKEN;
502
820
  const next = 0.7 * base + 0.3 * observed;
503
821
  return Math.min(CAL_MAX, Math.max(CAL_MIN, next));
package/client/pill.tsx CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { PluginButton, PluginButtonRegistration } from "@getpaseo/plugin/client";
2
2
  import { approx, fmtDuration, fmtRate, fmtTokens } from "./format";
3
3
  import type { AgentSpeedStore } from "./store";
4
+ import type { TeamView } from "./team";
4
5
  import type { Preferences } from "../shared/preferences";
5
6
 
6
7
  const PILL_REFRESH_MS = 500;
@@ -12,18 +13,28 @@ export interface PillView {
12
13
  title: string;
13
14
  }
14
15
 
15
- /** Number the pill leads with, per the speed-basis preference. */
16
+ /** Number the pill leads with, per the speed-basis preference. Rates above
17
+ * the plausibility limit are bookkeeping artifacts, not speed: show nothing
18
+ * rather than a fabricated burst. */
16
19
  function headlineTokPerSec(store: AgentSpeedStore, prefs: Preferences, now: number): number | null {
17
20
  const summary = store.summary(now);
21
+ const plausible = (rate: number | null): number | null =>
22
+ rate !== null && rate > prefs.maxPlausibleTokPerSec ? null : rate;
18
23
  if (store.isRunning() && prefs.numerator === "live") {
19
- const live = store.liveTokPerSec(prefs.liveWindowSec);
24
+ const live = store.liveTokPerSec(prefs.liveWindowSec, prefs.maxPlausibleTokPerSec);
20
25
  if (live !== null) return live;
21
26
  }
22
- if (prefs.numerator === "turn") return summary.tokPerSecTurn ?? summary.tokPerSecDecode;
23
- return summary.tokPerSecDecode ?? summary.tokPerSecTurn;
27
+ if (prefs.numerator === "turn")
28
+ return plausible(summary.tokPerSecTurn ?? summary.tokPerSecDecode);
29
+ return plausible(summary.tokPerSecDecode ?? summary.tokPerSecTurn);
24
30
  }
25
31
 
26
- export function computePillView(store: AgentSpeedStore, prefs: Preferences, now: number): PillView {
32
+ export function computePillView(
33
+ store: AgentSpeedStore,
34
+ prefs: Preferences,
35
+ now: number,
36
+ team?: TeamView | null,
37
+ ): PillView {
27
38
  const state = store.state;
28
39
  const phase = state.phase;
29
40
  if (phase === "idle") {
@@ -40,15 +51,27 @@ export function computePillView(store: AgentSpeedStore, prefs: Preferences, now:
40
51
  const rateText = rate === null ? "\u2014" : `${approx(fmtRate(rate), isApprox)} tok/s`;
41
52
  const running = phase === "running";
42
53
  const waiting = summary.waiting;
54
+ const teamRunning = team && phase === "running" && team.running > 0 ? team : null;
43
55
  // The composer track is narrow: the pill carries the decode rate only, and
44
56
  // the turn state (live vs waiting) is shown solely by the leading icon.
45
57
  // Tokens, prefill and wait time live in the popover; the full picture goes
46
58
  // into the accessible title.
47
59
  const labelParts: string[] = [rateText];
60
+ if (teamRunning) labelParts.push(`\u00b7 ${teamRunning.running} sub`);
48
61
  if (phase === "failed") labelParts.push("\u00b7 failed");
49
62
  if (phase === "canceled") labelParts.push("\u00b7 canceled");
50
63
  const titleParts = [`Turn speed ${rateText} decode`];
51
- if (waiting) titleParts.push("waiting for you");
64
+ if (waiting) titleParts.push("waiting");
65
+ if (teamRunning) {
66
+ // Keep the sheet title on one phone line: the short `N sub` form matches
67
+ // the pill label; the full breakdown is in the popover body.
68
+ const teamLabel = `${teamRunning.running} sub`;
69
+ titleParts.push(
70
+ teamRunning.liveTokPerSec === null
71
+ ? teamLabel
72
+ : `${teamLabel} @ ${approx(fmtRate(teamRunning.liveTokPerSec), teamRunning.approx)} tok/s`,
73
+ );
74
+ }
52
75
  if (summary.estTokens > 0) {
53
76
  titleParts.push(`${approx(fmtTokens(summary.estTokens, prefs.tokenFormat), isApprox)} tok`);
54
77
  }
@@ -76,8 +99,10 @@ export function bindPill(
76
99
  store: AgentSpeedStore,
77
100
  getPrefs: () => Preferences,
78
101
  now: () => number,
102
+ getTeam?: () => TeamView | null,
79
103
  ): PillRegistrationHandle {
80
- const first = computePillView(store, getPrefs(), now());
104
+ const view = (t: number) => computePillView(store, getPrefs(), t, getTeam ? getTeam() : null);
105
+ const first = view(now());
81
106
  let registration = register({ ...buttonBase, ...first });
82
107
  let lastPaint = 0;
83
108
  let pendingTimer: ReturnType<typeof setTimeout> | null = null;
@@ -94,8 +119,13 @@ export function bindPill(
94
119
  return;
95
120
  }
96
121
  lastPaint = t;
97
- const view = computePillView(store, getPrefs(), t);
98
- registration.update({ label: view.label, icon: view.icon, visible: view.visible, title: view.title });
122
+ const viewNow = view(t);
123
+ registration.update({
124
+ label: viewNow.label,
125
+ icon: viewNow.icon,
126
+ visible: viewNow.visible,
127
+ title: viewNow.title,
128
+ });
99
129
  };
100
130
 
101
131
  const unsubscribe = store.subscribe(() => paint(false));