paseo-turn-speed 1.2.1 → 1.3.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/OVERVIEW.md +5 -4
- package/README.md +40 -8
- package/client/details.tsx +15 -5
- package/client/format.ts +12 -0
- package/client/lifecycle.ts +149 -0
- package/client/meter.ts +173 -11
- package/client/pill.tsx +8 -3
- package/client/settings.tsx +24 -0
- package/client/store.ts +8 -2
- package/index.client.tsx +111 -60
- package/package.json +1 -1
- package/shared/preferences.ts +4 -0
package/OVERVIEW.md
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
A composer pill on every agent that shows how fast the model is decoding: live
|
|
4
4
|
tok/s while a turn runs, final tok/s and token totals after it, and a popover
|
|
5
|
-
with the breakdown — prefill/TTFT, in/
|
|
6
|
-
wait time, and context occupancy.
|
|
5
|
+
with the breakdown — prefill/TTFT, in/out tokens, prompt cache hit rate,
|
|
6
|
+
model-call steps, tool wait time, and context occupancy.
|
|
7
7
|
|
|
8
8
|
Speed is measured over decode windows only: tool waits, long pauses, and prompt
|
|
9
9
|
prefill are separated out, so the number reflects generation speed rather than
|
|
@@ -20,8 +20,9 @@ config that starts including thinking revokes it, so nothing is double-counted.
|
|
|
20
20
|
|
|
21
21
|
Options live under Settings → Plugins → Turn speed: what the pill leads with
|
|
22
22
|
(live estimate, decode-window average, or whole-turn rate, switchable from the
|
|
23
|
-
popover), smoothing window for the live number, token format,
|
|
24
|
-
visibility, and a manual chars/token
|
|
23
|
+
popover), smoothing window for the live number, token format, whether the pill
|
|
24
|
+
carries the cache hit rate, idle-pill visibility, and a manual chars/token
|
|
25
|
+
override. Requires Paseo 0.11 or later;
|
|
25
26
|
see the README for installing from GitHub or npm.
|
|
26
27
|
Turns are observed live; history from before a plugin reload is not
|
|
27
28
|
reconstructed. Subagents keep their own pills, but the parent also knows about
|
package/README.md
CHANGED
|
@@ -3,14 +3,15 @@
|
|
|
3
3
|
A composer pill per agent that shows how fast the model is actually decoding:
|
|
4
4
|
`⚡ 138 tok/s` while a turn runs, `⏸ 43 tok/s` while it waits for your answer,
|
|
5
5
|
`12.4 tok/s · 2 sub` while subagents do the heavy lifting, and the final rate
|
|
6
|
-
once the turn ends — with a popover breakdown (prefill/TTFT, in/
|
|
7
|
-
|
|
8
|
-
Numbers measured from real provider usage are exact; before
|
|
9
|
-
event they are character estimates marked with `≈`. For
|
|
10
|
-
provider subtracts thinking from the reported output
|
|
11
|
-
local models via oMLX), the thinking tokens are
|
|
12
|
-
reasoning text and shown as a separate
|
|
13
|
-
generated tokens instead of only the
|
|
6
|
+
once the turn ends — with a popover breakdown (prefill/TTFT, in/out tokens,
|
|
7
|
+
prompt cache hit rate, steps, tool wait, user wait, per-subagent rates,
|
|
8
|
+
context occupancy). Numbers measured from real provider usage are exact; before
|
|
9
|
+
the first usage event they are character estimates marked with `≈`. For
|
|
10
|
+
reasoning models whose provider subtracts thinking from the reported output
|
|
11
|
+
(measured on OpenCode + local models via oMLX), the thinking tokens are
|
|
12
|
+
estimated from the streamed reasoning text and shown as a separate
|
|
13
|
+
`thinking ≈` line, so rates cover all generated tokens instead of only the
|
|
14
|
+
visible answer.
|
|
14
15
|
|
|
15
16
|
## Install
|
|
16
17
|
|
|
@@ -112,6 +113,26 @@ provider config) — it feeds the `context 34k / 131k` line in the popover.
|
|
|
112
113
|
live rate and tokens plus a `team` total; for provider subagents only the
|
|
113
114
|
running count and delegated time are knowable (see Known limitations).
|
|
114
115
|
Each linked subagent still gets its own pill in its own composer.
|
|
116
|
+
- **Prompt cache hit rate** — `cacheRead / (newInput + cacheWrite + cacheRead)`
|
|
117
|
+
per model call, summed over the turn. The numerator is the prompt the model
|
|
118
|
+
did not have to recompute; the denominator is the whole prompt, so cache
|
|
119
|
+
writes count against the rate — they are tokens the model had to process even
|
|
120
|
+
though they missed the cache. Shown in the popover, and in the pill label
|
|
121
|
+
when enabled in settings.
|
|
122
|
+
|
|
123
|
+
Providers report cache reads in two shapes: OpenAI-compatible ones fold them
|
|
124
|
+
into the prompt counter, Anthropic-style ones report cache reads on top of it.
|
|
125
|
+
The plugin infers the shape per call (a cache read larger than the prompt can
|
|
126
|
+
only mean separate counters) and Settings → Turn speed → Prompt cache can pin
|
|
127
|
+
it explicitly.
|
|
128
|
+
|
|
129
|
+
Paseo's `AgentUsage` exposes only `inputTokens` and `cachedInputTokens`, with
|
|
130
|
+
no cache-write counter, so the `cacheWrite` term is always `0` today and the
|
|
131
|
+
formula collapses to `cacheRead / (newInput + cacheRead)`. For an
|
|
132
|
+
Anthropic-backed model whose TTL cache is being rebuilt mid-turn the reported
|
|
133
|
+
rate will therefore read high by the size of the rebuild. The term is already
|
|
134
|
+
plumbed through (`UsageSnapshot.cacheWrite` → `StepRecord.cacheWriteTokens`),
|
|
135
|
+
so a protocol field is a one-line change to the client's usage mapper.
|
|
115
136
|
- **Live number inside a model call** — real tokens only arrive at the end of a
|
|
116
137
|
call, so the live value estimates tokens from characters over a 1/2/5 s
|
|
117
138
|
smoothing window and is marked `≈` until the call's usage lands.
|
|
@@ -151,6 +172,8 @@ provider config) — it feeds the `context 34k / 131k` line in the popover.
|
|
|
151
172
|
| Show pills for idle agents | off | otherwise pills appear only around observed turns |
|
|
152
173
|
| Speed basis | Live decode | what the pill shows: live estimate, decode-window average, or whole-turn rate |
|
|
153
174
|
| Token format | 1.2k | compact or grouped digits |
|
|
175
|
+
| Cache hit rate in the pill | off | append `· 86% cached` to the pill; the popover always shows the row |
|
|
176
|
+
| Cache read accounting | Auto | whether the provider reports cache reads inside or on top of the prompt counter |
|
|
154
177
|
| Live smoothing window | 2 s | averaging window of the live tok/s |
|
|
155
178
|
| Manual chars per token | off (auto-calibrated) | override the live character estimate |
|
|
156
179
|
| Implausible rate limit | 400 tok/s | steps implying a faster decode are dropped as misattributed usage; no pill ever shows a rate above the limit |
|
|
@@ -193,6 +216,15 @@ check:client` runs the real Hermes syntax check too.
|
|
|
193
216
|
plugin API, so for them the badge, the `delegated` time and the rate
|
|
194
217
|
correction work, but the per-child token breakdown stays empty
|
|
195
218
|
(verified on Paseo 0.12 + OpenCode).
|
|
219
|
+
- The cache hit rate is only as good as the provider's cache counters: without
|
|
220
|
+
`cachedInputTokens` the popover hides the row, and providers that report a
|
|
221
|
+
`cached` counter with a different meaning (some sum cache writes into it)
|
|
222
|
+
will read higher than the true hit rate.
|
|
223
|
+
- Cache **writes** are not reported by Paseo's usage payload at all, so a turn
|
|
224
|
+
that rebuilds an Anthropic TTL cache reads as a higher hit rate than it
|
|
225
|
+
really was: the denominator is missing those tokens. See
|
|
226
|
+
[Prompt cache hit rate](#how-the-numbers-are-computed) for the exact formula
|
|
227
|
+
and the plumbing already in place for when the protocol gains the field.
|
|
196
228
|
- Usage that arrives late from a previous turn (typically after an interrupted
|
|
197
229
|
message) is dropped by the plausibility guard, so that turn's token totals can
|
|
198
230
|
be slightly low; rates stay honest.
|
package/client/details.tsx
CHANGED
|
@@ -3,7 +3,7 @@ import { useEffect, useMemo, useReducer, useSyncExternalStore } from "react";
|
|
|
3
3
|
import { Pressable, Text, View } from "react-native";
|
|
4
4
|
import type { PluginButtonContentProps } from "@getpaseo/plugin/client";
|
|
5
5
|
import { useSettings } from "@getpaseo/plugin/client";
|
|
6
|
-
import { approx, fmtDuration, fmtRate, fmtTokPerSec, fmtTokens } from "./format";
|
|
6
|
+
import { approx, fmtDuration, fmtPercent, fmtRate, fmtTokPerSec, fmtTokens } from "./format";
|
|
7
7
|
import type { AgentSpeedStore } from "./store";
|
|
8
8
|
import { EMPTY_TEAM, type TeamView } from "./team";
|
|
9
9
|
import { preferences, type Preferences } from "../shared/preferences";
|
|
@@ -168,10 +168,10 @@ export function makeSpeedDetails(
|
|
|
168
168
|
<Row
|
|
169
169
|
styles={styles}
|
|
170
170
|
label="tokens"
|
|
171
|
-
value={`in ${fmtTokens(summary.inputTokens, prefs.tokenFormat)}
|
|
172
|
-
summary.
|
|
173
|
-
|
|
174
|
-
)}
|
|
171
|
+
value={`in ${fmtTokens(summary.inputTokens, prefs.tokenFormat)} · out ${approx(
|
|
172
|
+
fmtTokens(summary.estTokens, prefs.tokenFormat),
|
|
173
|
+
summary.approx,
|
|
174
|
+
)}`}
|
|
175
175
|
/>
|
|
176
176
|
{summary.thinkingTokens >= 10 ? (
|
|
177
177
|
<Row
|
|
@@ -180,6 +180,16 @@ export function makeSpeedDetails(
|
|
|
180
180
|
value={`${approx(fmtTokens(summary.thinkingTokens, prefs.tokenFormat), true)} tok (not in reported out)`}
|
|
181
181
|
/>
|
|
182
182
|
) : null}
|
|
183
|
+
{summary.cacheHitRate !== null ? (
|
|
184
|
+
<Row
|
|
185
|
+
styles={styles}
|
|
186
|
+
label="cache hit"
|
|
187
|
+
value={`${fmtPercent(summary.cacheHitRate)} · cached ${fmtTokens(
|
|
188
|
+
summary.cachedTokens,
|
|
189
|
+
prefs.tokenFormat,
|
|
190
|
+
)} / ${fmtTokens(summary.promptTokens, prefs.tokenFormat)}`}
|
|
191
|
+
/>
|
|
192
|
+
) : null}
|
|
183
193
|
{state.ctxUsed !== null && state.ctxMax !== null ? (
|
|
184
194
|
<Row
|
|
185
195
|
styles={styles}
|
package/client/format.ts
CHANGED
|
@@ -22,6 +22,18 @@ function fmtGrouped(n: number): string {
|
|
|
22
22
|
return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, "\u2009");
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/** 0..1 ratio -> 0% / 3.4% / 86% / 100%. Never rounds up to 100% unless
|
|
26
|
+
* the rate is genuinely that high: a 99.86% hit rate reads 99.9%. */
|
|
27
|
+
export function fmtPercent(ratio: number | null): string {
|
|
28
|
+
if (ratio === null || !Number.isFinite(ratio) || ratio < 0) return "—";
|
|
29
|
+
const pct = ratio * 100;
|
|
30
|
+
if (pct >= 99.95) return "100%";
|
|
31
|
+
if (pct >= 99) return `${pct.toFixed(1)}%`;
|
|
32
|
+
if (pct >= 10) return `${Math.round(pct)}%`;
|
|
33
|
+
if (pct < 0.05) return "0%";
|
|
34
|
+
return `${pct.toFixed(1)}%`;
|
|
35
|
+
}
|
|
36
|
+
|
|
25
37
|
/** 640ms / 12.3s / 2m05s */
|
|
26
38
|
export function fmtDuration(ms: number | null): string {
|
|
27
39
|
if (ms === null || !Number.isFinite(ms) || ms < 0) return "—";
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a turn becomes known to the plugin and how it ends.
|
|
3
|
+
*
|
|
4
|
+
* A turn arrives either as a live `turn_started` stream event or as an agent
|
|
5
|
+
* snapshot taken while the plugin attaches mid-turn. Its clock must start at an
|
|
6
|
+
* instant the daemon observed, never at a cached handle field: `ref()`
|
|
7
|
+
* snapshots update on the agent channel while turn events arrive on the
|
|
8
|
+
* timeline channel, so reading `handle.activeTurn` right after `turn_started`
|
|
9
|
+
* can still hold the previous turn's start, charging that whole turn to this
|
|
10
|
+
* one (a 2s turn reported as 63s, `whole turn` collapsing toward 0).
|
|
11
|
+
*
|
|
12
|
+
* It ends either as a terminal stream event (authoritative) or, when that event
|
|
13
|
+
* is lost, as a snapshot that says the agent is no longer working. The snapshot
|
|
14
|
+
* only knows that work stopped: it cannot tell a completed turn from a failed
|
|
15
|
+
* or canceled one, so the end it produces is provisional and a later terminal
|
|
16
|
+
* event for the same turn replaces it.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { reduceMeter, type MeterAction, type MeterState } from "./meter";
|
|
20
|
+
|
|
21
|
+
export type TurnStartSource = "event" | "snapshot" | "arrival";
|
|
22
|
+
|
|
23
|
+
export interface TurnStart {
|
|
24
|
+
/** Epoch milliseconds the meter should count from. */
|
|
25
|
+
at: number;
|
|
26
|
+
/** Where `at` came from; `arrival` means the timestamp was unusable. */
|
|
27
|
+
source: TurnStartSource;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The daemon usually shares the app's clock; allow a little skew before
|
|
31
|
+
* declaring a timestamp unreal. */
|
|
32
|
+
const MAX_CLOCK_SKEW_MS = 5_000;
|
|
33
|
+
|
|
34
|
+
/** The part of an agent snapshot the meter needs, kept structural so the rules
|
|
35
|
+
* stay testable without the SDK. */
|
|
36
|
+
export interface AgentTurnSnapshot {
|
|
37
|
+
status?: string | null;
|
|
38
|
+
activeTurn?: { turnId?: string | null; startedAt?: string | null } | null;
|
|
39
|
+
/** Absent means "no information"; present-and-empty means "nothing open". */
|
|
40
|
+
pendingPermissions?: readonly { id: string | null }[] | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface Reconciliation {
|
|
44
|
+
/** Actions to dispatch, in order. */
|
|
45
|
+
actions: MeterAction[];
|
|
46
|
+
/** Open permission/question ids, or null when the snapshot carries none. */
|
|
47
|
+
pendingWaits: string[] | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function parseTimestamp(value: string | null | undefined): number | null {
|
|
51
|
+
if (!value) return null;
|
|
52
|
+
const parsed = Date.parse(value);
|
|
53
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Anchor a live `turn_started` to the daemon timestamp carried by the stream
|
|
57
|
+
* message, clamped so the clock never starts in the future. Events arrive in
|
|
58
|
+
* order on one subscription, so the timestamp of the latest one is the turn
|
|
59
|
+
* being announced; there is no age limit to guess at. */
|
|
60
|
+
export function turnStartFromEvent(
|
|
61
|
+
timestamp: string | null | undefined,
|
|
62
|
+
arrivedAt: number,
|
|
63
|
+
): TurnStart {
|
|
64
|
+
const parsed = parseTimestamp(timestamp);
|
|
65
|
+
if (parsed === null) return { at: arrivedAt, source: "arrival" };
|
|
66
|
+
if (parsed - arrivedAt > MAX_CLOCK_SKEW_MS) return { at: arrivedAt, source: "arrival" };
|
|
67
|
+
return { at: Math.min(parsed, arrivedAt), source: "event" };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Anchor a turn recovered from an agent snapshot read after the timeline
|
|
71
|
+
* subscription is established. The snapshot's `startedAt` is the daemon's
|
|
72
|
+
* accepted-turn boundary, so it is exact for a mid-turn attach. */
|
|
73
|
+
export function turnStartFromSnapshot(
|
|
74
|
+
startedAt: string | null | undefined,
|
|
75
|
+
observedAt: number,
|
|
76
|
+
): TurnStart {
|
|
77
|
+
const parsed = parseTimestamp(startedAt);
|
|
78
|
+
if (parsed === null) return { at: observedAt, source: "arrival" };
|
|
79
|
+
if (parsed - observedAt > MAX_CLOCK_SKEW_MS) return { at: observedAt, source: "arrival" };
|
|
80
|
+
return { at: Math.min(parsed, observedAt), source: "snapshot" };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Fold one agent snapshot into meter actions, in the order the meter needs.
|
|
85
|
+
*
|
|
86
|
+
* The order is the point: a turn is established before the wait and delegation
|
|
87
|
+
* state that only applies to a running turn, so attaching while the agent is
|
|
88
|
+
* blocked on a permission prompt does not silently charge that wait to the
|
|
89
|
+
* model. Everything is evaluated against the state produced by the previous
|
|
90
|
+
* action, not against the state the caller passed in.
|
|
91
|
+
*/
|
|
92
|
+
export function reconcileSnapshot(
|
|
93
|
+
state: MeterState,
|
|
94
|
+
snapshot: AgentTurnSnapshot,
|
|
95
|
+
now: number,
|
|
96
|
+
options: { seed: boolean },
|
|
97
|
+
): Reconciliation {
|
|
98
|
+
const actions: MeterAction[] = [];
|
|
99
|
+
let current = state;
|
|
100
|
+
const push = (action: MeterAction): void => {
|
|
101
|
+
actions.push(action);
|
|
102
|
+
current = reduceMeter(current, action);
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// 1. A turn that was already running when the plugin attached.
|
|
106
|
+
if (options.seed && current.phase === "idle" && snapshot.status === "running" && snapshot.activeTurn) {
|
|
107
|
+
const start = turnStartFromSnapshot(snapshot.activeTurn.startedAt, now);
|
|
108
|
+
push({
|
|
109
|
+
t: "turn_started",
|
|
110
|
+
at: start.at,
|
|
111
|
+
turnId: snapshot.activeTurn.turnId || null,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 2. Requests the model is blocked on: that interval is not work.
|
|
116
|
+
const pendingPermissions = snapshot.pendingPermissions;
|
|
117
|
+
const pendingWaits = pendingPermissions
|
|
118
|
+
? pendingPermissions
|
|
119
|
+
.map((request) => request.id)
|
|
120
|
+
.filter((id): id is string => typeof id === "string" && id.length > 0)
|
|
121
|
+
: null;
|
|
122
|
+
if (pendingWaits) {
|
|
123
|
+
push({ t: pendingWaits.length > 0 ? "user_wait_started" : "user_wait_ended", at: now });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 3. A turn whose terminal event never arrived: stop the clock, keep the
|
|
127
|
+
// outcome open for the real terminal event.
|
|
128
|
+
if (shouldCloseMissedTurn(current, snapshot)) {
|
|
129
|
+
push({ t: "turn_ended", at: now, kind: "completed", turnId: current.turnId, provisional: true });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return { actions, pendingWaits };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The snapshot is an independent source of truth for "this agent is not
|
|
137
|
+
* working". A snapshot without a status is partial, not idle, and a snapshot
|
|
138
|
+
* that still describes a different turn says nothing about this one.
|
|
139
|
+
*/
|
|
140
|
+
export function shouldCloseMissedTurn(
|
|
141
|
+
state: MeterState,
|
|
142
|
+
snapshot: AgentTurnSnapshot,
|
|
143
|
+
): boolean {
|
|
144
|
+
if (state.phase !== "running") return false;
|
|
145
|
+
const status = snapshot.status;
|
|
146
|
+
if (typeof status !== "string" || status === "" || status === "running") return false;
|
|
147
|
+
const turnId = snapshot.activeTurn?.turnId || null;
|
|
148
|
+
return turnId === null || state.turnId === null || turnId === state.turnId;
|
|
149
|
+
}
|
package/client/meter.ts
CHANGED
|
@@ -83,7 +83,18 @@ export const INCLUSION_EVIDENCE_STEPS = 3;
|
|
|
83
83
|
|
|
84
84
|
export interface UsageSnapshot {
|
|
85
85
|
input?: number | null;
|
|
86
|
+
/** Prompt tokens served from the provider's cache (cache reads). */
|
|
86
87
|
cached?: number | null;
|
|
88
|
+
/**
|
|
89
|
+
* Prompt tokens written into the provider's cache (Anthropic's
|
|
90
|
+
* `cache_creation_input_tokens`). Part of the prompt the model had to
|
|
91
|
+
* process, so it belongs in the cache-hit denominator.
|
|
92
|
+
*
|
|
93
|
+
* Paseo's AgentUsage carries no such field today (see the note on
|
|
94
|
+
* `PromptTotals`), so the client always sends 0; the slot exists so a
|
|
95
|
+
* provider that starts reporting it changes one mapper, not the formula.
|
|
96
|
+
*/
|
|
97
|
+
cacheWrite?: number | null;
|
|
87
98
|
output?: number | null;
|
|
88
99
|
ctxMax?: number | null;
|
|
89
100
|
ctxUsed?: number | null;
|
|
@@ -107,6 +118,8 @@ export interface StepRecord {
|
|
|
107
118
|
* window never saw. Their tokens count in turn totals but not in the
|
|
108
119
|
* decode-window rate. */
|
|
109
120
|
thinkingLateChars: number;
|
|
121
|
+
/** Prompt tokens this call wrote into the cache; 0 when unreported. */
|
|
122
|
+
cacheWriteTokens: number;
|
|
110
123
|
/** Prefill/TTFT measured on the first step only, else 0. */
|
|
111
124
|
prefillMs: number;
|
|
112
125
|
}
|
|
@@ -150,6 +163,7 @@ export interface MeterState {
|
|
|
150
163
|
prevUsageOut: number;
|
|
151
164
|
prevUsageIn: number;
|
|
152
165
|
prevUsageCached: number;
|
|
166
|
+
prevUsageCacheWrite: number;
|
|
153
167
|
steps: readonly StepRecord[];
|
|
154
168
|
/** Characters streamed since the last step boundary (live estimate). */
|
|
155
169
|
liveChars: number;
|
|
@@ -189,6 +203,10 @@ export interface MeterState {
|
|
|
189
203
|
calibInput: { chars: number; tokens: number } | null;
|
|
190
204
|
endedAt: number | null;
|
|
191
205
|
endNote: string | null;
|
|
206
|
+
/** Ended from an agent snapshot rather than a terminal event: the clock is
|
|
207
|
+
* stopped, but the outcome (completed / failed / canceled) is still open and
|
|
208
|
+
* the real terminal event for this turn may replace it. */
|
|
209
|
+
provisional: boolean;
|
|
192
210
|
}
|
|
193
211
|
|
|
194
212
|
export type MeterAction =
|
|
@@ -204,7 +222,7 @@ export type MeterAction =
|
|
|
204
222
|
| { t: "delegated_started"; at: number }
|
|
205
223
|
/** All subagents finished: the agent works alone again. */
|
|
206
224
|
| { t: "delegated_ended"; at: number }
|
|
207
|
-
| { t: "turn_ended"; at: number; kind: "completed" | "failed" | "canceled"; usage?: UsageSnapshot; maxTokPerSec?: number; note?: string | null }
|
|
225
|
+
| { t: "turn_ended"; at: number; kind: "completed" | "failed" | "canceled"; usage?: UsageSnapshot; maxTokPerSec?: number; note?: string | null; turnId?: string | null; provisional?: boolean }
|
|
208
226
|
/** The agent switched model (or its identity just became known): a
|
|
209
227
|
* thinking-exclusion verdict learned on another model must not carry. */
|
|
210
228
|
| { t: "model_changed"; model: string | null }
|
|
@@ -232,6 +250,7 @@ export function initialMeterState(): MeterState {
|
|
|
232
250
|
prevUsageOut: 0,
|
|
233
251
|
prevUsageIn: 0,
|
|
234
252
|
prevUsageCached: 0,
|
|
253
|
+
prevUsageCacheWrite: 0,
|
|
235
254
|
steps: [],
|
|
236
255
|
liveChars: 0,
|
|
237
256
|
totalChars: 0,
|
|
@@ -250,6 +269,7 @@ export function initialMeterState(): MeterState {
|
|
|
250
269
|
calibInput: null,
|
|
251
270
|
endedAt: null,
|
|
252
271
|
endNote: null,
|
|
272
|
+
provisional: false,
|
|
253
273
|
};
|
|
254
274
|
}
|
|
255
275
|
|
|
@@ -402,6 +422,7 @@ function applyUsage(
|
|
|
402
422
|
const out = num(usage.output);
|
|
403
423
|
const inp = num(usage.input);
|
|
404
424
|
const cached = num(usage.cached);
|
|
425
|
+
const cacheWrite = num(usage.cacheWrite);
|
|
405
426
|
const counters = {
|
|
406
427
|
usageOut: out ?? state.usageOut,
|
|
407
428
|
usageIn: inp ?? state.usageIn,
|
|
@@ -412,12 +433,14 @@ function applyUsage(
|
|
|
412
433
|
const outDelta = delta(out, state.prevUsageOut);
|
|
413
434
|
const inDelta = delta(inp, state.prevUsageIn);
|
|
414
435
|
const cachedDelta = delta(cached, state.prevUsageCached);
|
|
436
|
+
const cacheWriteDelta = delta(cacheWrite, state.prevUsageCacheWrite);
|
|
415
437
|
const withCounters: MeterState = {
|
|
416
438
|
...state,
|
|
417
439
|
...counters,
|
|
418
440
|
prevUsageOut: outDelta.next,
|
|
419
441
|
prevUsageIn: inDelta.next,
|
|
420
442
|
prevUsageCached: cachedDelta.next,
|
|
443
|
+
prevUsageCacheWrite: cacheWriteDelta.next,
|
|
421
444
|
};
|
|
422
445
|
if (state.phase !== "running") return { ...withCounters };
|
|
423
446
|
if (outDelta.amount <= 0) {
|
|
@@ -470,6 +493,7 @@ function applyUsage(
|
|
|
470
493
|
cachedTokens: cachedDelta.amount,
|
|
471
494
|
thinkingChars: state.liveReasoningChars,
|
|
472
495
|
thinkingLateChars: reasoningLate ? state.liveReasoningChars : 0,
|
|
496
|
+
cacheWriteTokens: cacheWriteDelta.amount,
|
|
473
497
|
prefillMs,
|
|
474
498
|
};
|
|
475
499
|
// More streamed reasoning characters than this step's output tokens could
|
|
@@ -511,6 +535,25 @@ function applyUsage(
|
|
|
511
535
|
};
|
|
512
536
|
}
|
|
513
537
|
|
|
538
|
+
/** A provisional end stopped the clock, but the step it froze still belongs
|
|
539
|
+
* to this turn: usage that arrives afterwards must still close that step, or
|
|
540
|
+
* the terminal payload's tokens never reach the turn's totals. */
|
|
541
|
+
function usageAccountingBase(state: MeterState): MeterState {
|
|
542
|
+
return state.provisional ? { ...state, phase: "running" } : state;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Keep the stopped clock when only the accounting was updated. */
|
|
546
|
+
function keepProvisionalEnd(state: MeterState, next: MeterState): MeterState {
|
|
547
|
+
if (!state.provisional) return next;
|
|
548
|
+
return {
|
|
549
|
+
...next,
|
|
550
|
+
phase: state.phase,
|
|
551
|
+
endedAt: state.endedAt,
|
|
552
|
+
endNote: state.endNote,
|
|
553
|
+
provisional: true,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
514
557
|
function endTurn(
|
|
515
558
|
state: MeterState,
|
|
516
559
|
at: number,
|
|
@@ -518,17 +561,40 @@ function endTurn(
|
|
|
518
561
|
usage: UsageSnapshot | undefined,
|
|
519
562
|
maxTokPerSec: number | undefined,
|
|
520
563
|
note: string | null,
|
|
564
|
+
turnId: string | null | undefined,
|
|
565
|
+
provisional: boolean,
|
|
521
566
|
): MeterState {
|
|
567
|
+
// A terminal event for another turn describes a turn this meter never
|
|
568
|
+
// followed: it must not close this one, and it must not advance this turn's
|
|
569
|
+
// usage baseline either. An empty id is no id, not another turn.
|
|
570
|
+
const id = turnId || null;
|
|
571
|
+
if (id !== null && state.turnId !== null && id !== state.turnId) return state;
|
|
522
572
|
// A repeated cumulative payload contributes no delta and opens no step.
|
|
523
|
-
const withUsage = usage
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
573
|
+
const withUsage = usage
|
|
574
|
+
? applyUsage(usageAccountingBase(state), at, usage, maxTokPerSec)
|
|
575
|
+
: state;
|
|
576
|
+
if (withUsage.phase === "running") {
|
|
577
|
+
// A turn that ends while a question is still open closes the wait there;
|
|
578
|
+
// same for an ongoing delegation.
|
|
579
|
+
return {
|
|
580
|
+
...closeDelegated(closeWait(withUsage, at), at),
|
|
581
|
+
phase: kind,
|
|
582
|
+
endedAt: at,
|
|
583
|
+
endNote: note,
|
|
584
|
+
provisional,
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
// A provisional end only knows that the agent stopped working: an idle
|
|
588
|
+
// snapshot cannot tell a completed turn from a failed or canceled one. The
|
|
589
|
+
// real terminal event is authoritative for the same turn, so it replaces the
|
|
590
|
+
// guess together with the outcome and the usage it carries.
|
|
591
|
+
if (!withUsage.provisional) return state;
|
|
527
592
|
return {
|
|
528
|
-
...
|
|
593
|
+
...withUsage,
|
|
529
594
|
phase: kind,
|
|
530
595
|
endedAt: at,
|
|
531
596
|
endNote: note,
|
|
597
|
+
provisional: false,
|
|
532
598
|
};
|
|
533
599
|
}
|
|
534
600
|
|
|
@@ -541,7 +607,7 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
|
|
|
541
607
|
return {
|
|
542
608
|
...initialMeterState(),
|
|
543
609
|
phase: "running",
|
|
544
|
-
turnId: action.turnId,
|
|
610
|
+
turnId: action.turnId || null,
|
|
545
611
|
startedAt: action.at,
|
|
546
612
|
ctxMax: state.ctxMax,
|
|
547
613
|
ctxUsed: state.ctxUsed,
|
|
@@ -550,6 +616,7 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
|
|
|
550
616
|
prevUsageOut: state.prevUsageOut,
|
|
551
617
|
prevUsageIn: state.prevUsageIn,
|
|
552
618
|
prevUsageCached: state.prevUsageCached,
|
|
619
|
+
prevUsageCacheWrite: state.prevUsageCacheWrite,
|
|
553
620
|
// A provider-level property: survives turns like the usage baseline
|
|
554
621
|
// — but only when it has a known owner. A verdict that never got a
|
|
555
622
|
// model identity cannot tell an unchanged provider from an invisible
|
|
@@ -570,8 +637,15 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
|
|
|
570
637
|
// Backwards compatibility with callers using the legacy key scheme.
|
|
571
638
|
(action.kind === undefined && action.key.startsWith("reasoning")),
|
|
572
639
|
);
|
|
573
|
-
case "usage":
|
|
574
|
-
|
|
640
|
+
case "usage": {
|
|
641
|
+
const next = applyUsage(
|
|
642
|
+
usageAccountingBase(state),
|
|
643
|
+
action.at,
|
|
644
|
+
action.usage,
|
|
645
|
+
action.maxTokPerSec,
|
|
646
|
+
);
|
|
647
|
+
return keepProvisionalEnd(state, next);
|
|
648
|
+
}
|
|
575
649
|
case "compaction":
|
|
576
650
|
// Context was rewritten; streamed chars since the last step no longer
|
|
577
651
|
// map to answer tokens. Drop the live window, keep step history.
|
|
@@ -593,7 +667,16 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
|
|
|
593
667
|
// An end for a delegation we never saw is a no-op.
|
|
594
668
|
return state.delegatedAt === null ? state : closeDelegated(state, action.at);
|
|
595
669
|
case "turn_ended":
|
|
596
|
-
return endTurn(
|
|
670
|
+
return endTurn(
|
|
671
|
+
state,
|
|
672
|
+
action.at,
|
|
673
|
+
action.kind,
|
|
674
|
+
action.usage,
|
|
675
|
+
action.maxTokPerSec,
|
|
676
|
+
action.note ?? null,
|
|
677
|
+
action.turnId,
|
|
678
|
+
action.provisional === true,
|
|
679
|
+
);
|
|
597
680
|
case "reset":
|
|
598
681
|
// Keep the observed usage baseline: the provider's counters outlive the
|
|
599
682
|
// locally observed turn, so deltas must stay continuous.
|
|
@@ -605,6 +688,7 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
|
|
|
605
688
|
prevUsageOut: state.prevUsageOut,
|
|
606
689
|
prevUsageIn: state.prevUsageIn,
|
|
607
690
|
prevUsageCached: state.prevUsageCached,
|
|
691
|
+
prevUsageCacheWrite: state.prevUsageCacheWrite,
|
|
608
692
|
thinkingExcluded: state.thinkingExcluded,
|
|
609
693
|
thinkingExcludedModel: state.thinkingExcludedModel,
|
|
610
694
|
inclusionStreak: state.inclusionStreak,
|
|
@@ -666,6 +750,12 @@ export interface TurnSummary {
|
|
|
666
750
|
inputTokens: number;
|
|
667
751
|
/** Cached prompt tokens across the turn's calls. */
|
|
668
752
|
cachedTokens: number;
|
|
753
|
+
/** Prompt tokens written to the cache; 0 for providers that do not report it. */
|
|
754
|
+
cacheWriteTokens: number;
|
|
755
|
+
/** All prompt tokens across the turn's calls: input + writes + reads. */
|
|
756
|
+
promptTokens: number;
|
|
757
|
+
/** Cached share of `promptTokens` (0..1); null without prompt data. */
|
|
758
|
+
cacheHitRate: number | null;
|
|
669
759
|
/** Prompt tokens of the first step, for the prefill rate. */
|
|
670
760
|
firstStepPromptTokens: number | null;
|
|
671
761
|
/** Cached prompt tokens of the first step: with a warm cache the prompt
|
|
@@ -678,10 +768,69 @@ export interface TurnSummary {
|
|
|
678
768
|
unattributedTokens: number;
|
|
679
769
|
}
|
|
680
770
|
|
|
681
|
-
|
|
771
|
+
/**
|
|
772
|
+
* How a provider reports prompt cache reads. The two common shapes cannot be
|
|
773
|
+
* told apart from the numbers alone, hence the explicit override.
|
|
774
|
+
*
|
|
775
|
+
* - `inclusive` (OpenAI-style): the prompt counter already contains the cached
|
|
776
|
+
* tokens, so the prompt total is `inputTokens`.
|
|
777
|
+
* - `separate` (Anthropic-style): `inputTokens` is only the uncached part and
|
|
778
|
+
* cache reads are reported on top, so the total is their sum.
|
|
779
|
+
* - `auto`: infer per turn — cache reads larger than the prompt can only mean
|
|
780
|
+
* separate counters; otherwise assume the prompt already includes them.
|
|
781
|
+
*/
|
|
782
|
+
export type CacheCountingMode = "auto" | "inclusive" | "separate";
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* Prompt totals for one model call.
|
|
786
|
+
*
|
|
787
|
+
* The hit rate is the share of the prompt that was served without being
|
|
788
|
+
* recomputed, so the denominator is the whole prompt:
|
|
789
|
+
*
|
|
790
|
+
* hitRate = cacheRead / (newInput + cacheWrite + cacheRead)
|
|
791
|
+
*
|
|
792
|
+
* The `cacheWrite` term is Anthropic's `cache_creation_input_tokens`: those
|
|
793
|
+
* tokens were part of the prompt even though they missed the cache, and
|
|
794
|
+
* leaving them out inflates the rate whenever a TTL cache is being rebuilt.
|
|
795
|
+
* Paseo's `AgentUsage` exposes only `inputTokens` and `cachedInputTokens`, so
|
|
796
|
+
* the term is always 0 today and the formula collapses to
|
|
797
|
+
* `cacheRead / (newInput + cacheRead)` — identical to the pre-cache-write
|
|
798
|
+
* behaviour for every provider that does report 0.
|
|
799
|
+
*
|
|
800
|
+
* `hitRate` never exceeds 1: some providers fold cache writes into the same
|
|
801
|
+
* counter they report as cache reads, and the clamp keeps that from printing
|
|
802
|
+
* above 100%.
|
|
803
|
+
*/
|
|
804
|
+
export function cacheStats(
|
|
805
|
+
inputTokens: number,
|
|
806
|
+
cachedTokens: number,
|
|
807
|
+
mode: CacheCountingMode = "auto",
|
|
808
|
+
cacheWriteTokens = 0,
|
|
809
|
+
): { promptTokens: number; cachedTokens: number; hitRate: number | null } {
|
|
810
|
+
const cached = Number.isFinite(cachedTokens) && cachedTokens > 0 ? cachedTokens : 0;
|
|
811
|
+
const input = Number.isFinite(inputTokens) && inputTokens > 0 ? inputTokens : 0;
|
|
812
|
+
const cacheWrite =
|
|
813
|
+
Number.isFinite(cacheWriteTokens) && cacheWriteTokens > 0 ? cacheWriteTokens : 0;
|
|
814
|
+
const separate = mode === "separate" || (mode === "auto" && cached > input);
|
|
815
|
+
const promptTokens = separate ? input + cacheWrite + cached : input + cacheWrite;
|
|
816
|
+
if (promptTokens <= 0) return { promptTokens: 0, cachedTokens: 0, hitRate: null };
|
|
817
|
+
return {
|
|
818
|
+
promptTokens,
|
|
819
|
+
cachedTokens: cached,
|
|
820
|
+
hitRate: Math.min(1, cached / promptTokens),
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
export function summarizeTurn(
|
|
825
|
+
state: MeterState,
|
|
826
|
+
charsPerToken: number,
|
|
827
|
+
now: number,
|
|
828
|
+
cacheCounting: CacheCountingMode = "auto",
|
|
829
|
+
): TurnSummary {
|
|
682
830
|
const realOut = state.steps.reduce((sum, s) => sum + s.outTokens, 0);
|
|
683
831
|
const inputTokens = state.steps.reduce((sum, s) => sum + s.inputTokens, 0);
|
|
684
832
|
const cachedTokens = state.steps.reduce((sum, s) => sum + s.cachedTokens, 0);
|
|
833
|
+
const cacheWriteTokens = state.steps.reduce((sum, s) => sum + s.cacheWriteTokens, 0);
|
|
685
834
|
const waitMs = state.steps.reduce((sum, s) => sum + s.waitMs, 0);
|
|
686
835
|
const hasReal = state.sawUsage && realOut > 0;
|
|
687
836
|
// Without any usage step there is no anchored window; the span of streamed
|
|
@@ -775,6 +924,16 @@ export function summarizeTurn(state: MeterState, charsPerToken: number, now: num
|
|
|
775
924
|
decodeMs > 0 && decodeTokens > 0 ? decodeTokens / (decodeMs / 1000) : null;
|
|
776
925
|
const tokPerSecTurn =
|
|
777
926
|
activeMs !== null && activeMs > 0 && estTokens > 0 ? estTokens / (activeMs / 1000) : null;
|
|
927
|
+
// Each call is normalised on its own, then summed: a turn can mix providers'
|
|
928
|
+
// shapes, and a per-call decision is far more reliable than a merged one.
|
|
929
|
+
let promptTokens = 0;
|
|
930
|
+
let hitTokens = 0;
|
|
931
|
+
for (const step of state.steps) {
|
|
932
|
+
const stepCache = cacheStats(step.inputTokens, step.cachedTokens, cacheCounting, step.cacheWriteTokens);
|
|
933
|
+
promptTokens += stepCache.promptTokens;
|
|
934
|
+
hitTokens += stepCache.cachedTokens;
|
|
935
|
+
}
|
|
936
|
+
const cacheHitRate = promptTokens > 0 ? Math.min(1, hitTokens / promptTokens) : null;
|
|
778
937
|
return {
|
|
779
938
|
outTokens,
|
|
780
939
|
estTokens,
|
|
@@ -792,6 +951,9 @@ export function summarizeTurn(state: MeterState, charsPerToken: number, now: num
|
|
|
792
951
|
steps: state.steps.length,
|
|
793
952
|
inputTokens,
|
|
794
953
|
cachedTokens,
|
|
954
|
+
cacheWriteTokens,
|
|
955
|
+
promptTokens,
|
|
956
|
+
cacheHitRate,
|
|
795
957
|
firstStepPromptTokens: state.steps.length > 0 && state.steps[0].inputTokens > 0 ? state.steps[0].inputTokens : null,
|
|
796
958
|
firstStepCachedTokens: state.steps.length > 0 && state.steps[0].cachedTokens > 0 ? state.steps[0].cachedTokens : null,
|
|
797
959
|
thinkingTokens,
|
package/client/pill.tsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { PluginButton, PluginButtonRegistration } from "@getpaseo/plugin/client";
|
|
2
|
-
import { approx, fmtDuration, fmtRate, fmtTokens } from "./format";
|
|
2
|
+
import { approx, fmtDuration, fmtPercent, fmtRate, fmtTokens } from "./format";
|
|
3
3
|
import type { AgentSpeedStore } from "./store";
|
|
4
4
|
import type { TeamView } from "./team";
|
|
5
5
|
import type { Preferences } from "../shared/preferences";
|
|
@@ -52,11 +52,15 @@ export function computePillView(
|
|
|
52
52
|
const running = phase === "running";
|
|
53
53
|
const waiting = summary.waiting;
|
|
54
54
|
const teamRunning = team && phase === "running" && team.running > 0 ? team : null;
|
|
55
|
-
// The composer track is narrow: the pill carries the decode rate
|
|
56
|
-
//
|
|
55
|
+
// The composer track is narrow: the pill carries the decode rate plus the
|
|
56
|
+
// turn's cache hit rate (when enabled) and the subagent count (when the work
|
|
57
|
+
// is delegated); turn state (live vs waiting) is shown by the leading icon.
|
|
57
58
|
// Tokens, prefill and wait time live in the popover; the full picture goes
|
|
58
59
|
// into the accessible title.
|
|
59
60
|
const labelParts: string[] = [rateText];
|
|
61
|
+
if (prefs.showCacheInPill && summary.cacheHitRate !== null) {
|
|
62
|
+
labelParts.push(`\u00b7 ${fmtPercent(summary.cacheHitRate)} cached`);
|
|
63
|
+
}
|
|
60
64
|
if (teamRunning) labelParts.push(`\u00b7 ${teamRunning.running} sub`);
|
|
61
65
|
if (phase === "failed") labelParts.push("\u00b7 failed");
|
|
62
66
|
if (phase === "canceled") labelParts.push("\u00b7 canceled");
|
|
@@ -76,6 +80,7 @@ export function computePillView(
|
|
|
76
80
|
titleParts.push(`${approx(fmtTokens(summary.estTokens, prefs.tokenFormat), isApprox)} tok`);
|
|
77
81
|
}
|
|
78
82
|
if (summary.prefillMs !== null) titleParts.push(`TTFT ${fmtDuration(summary.prefillMs)}`);
|
|
83
|
+
if (summary.cacheHitRate !== null) titleParts.push(`cache ${fmtPercent(summary.cacheHitRate)}`);
|
|
79
84
|
return {
|
|
80
85
|
label: labelParts.join(" "),
|
|
81
86
|
icon: waiting ? "Pause" : running ? "Zap" : "Activity",
|
package/client/settings.tsx
CHANGED
|
@@ -72,6 +72,12 @@ export function makeSettingsScreen(onSaved: () => void): ComponentType<PluginSur
|
|
|
72
72
|
]}
|
|
73
73
|
onValueChange={(v) => save({ numerator: v })}
|
|
74
74
|
/>
|
|
75
|
+
<SettingsSwitch
|
|
76
|
+
label="Show cache hit rate in the pill"
|
|
77
|
+
hint="Appends the turn's prompt cache hit rate to the composer pill. The popover always shows it."
|
|
78
|
+
value={values.showCacheInPill}
|
|
79
|
+
onValueChange={(v) => save({ showCacheInPill: v })}
|
|
80
|
+
/>
|
|
75
81
|
<SettingsSelect
|
|
76
82
|
label="Token format"
|
|
77
83
|
value={values.tokenFormat}
|
|
@@ -148,6 +154,24 @@ export function makeSettingsScreen(onSaved: () => void): ComponentType<PluginSur
|
|
|
148
154
|
{settings.saveError ? <Text style={error}>{settings.saveError}</Text> : null}
|
|
149
155
|
</SettingsCard>
|
|
150
156
|
</SettingsSection>
|
|
157
|
+
<SettingsSection
|
|
158
|
+
title="Prompt cache"
|
|
159
|
+
info="Hit rate = cache reads / (new input + cache writes + cache reads), summed over the turn's model calls. Paseo does not report cache writes, so that term is currently always 0."
|
|
160
|
+
>
|
|
161
|
+
<SettingsCard>
|
|
162
|
+
<SettingsSelect
|
|
163
|
+
label="How cache reads are reported"
|
|
164
|
+
hint="Auto infers from the numbers (cache reads larger than the prompt can only mean separate counters). Claude reports cache reads on top of the prompt; most OpenAI-compatible providers fold them in."
|
|
165
|
+
value={values.cacheCounting}
|
|
166
|
+
options={[
|
|
167
|
+
{ label: "Auto (default)", value: "auto" },
|
|
168
|
+
{ label: "Included in prompt (OpenAI-style)", value: "inclusive" },
|
|
169
|
+
{ label: "Separate from prompt (Anthropic-style)", value: "separate" },
|
|
170
|
+
]}
|
|
171
|
+
onValueChange={(v) => save({ cacheCounting: v })}
|
|
172
|
+
/>
|
|
173
|
+
</SettingsCard>
|
|
174
|
+
</SettingsSection>
|
|
151
175
|
<SettingsSection title="Calibration" info="Learned per model from real usage: chars per output token, blended 0.7/0.3 and clamped to 2..8.">
|
|
152
176
|
<SettingsCard>
|
|
153
177
|
{calibration.length === 0 ? (
|
package/client/store.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
+
cacheStats,
|
|
2
3
|
calibrate,
|
|
3
4
|
initialMeterState,
|
|
4
5
|
reduceMeter,
|
|
5
6
|
summarizeTurn,
|
|
6
7
|
DEFAULT_CHARS_PER_TOKEN,
|
|
7
8
|
REASONING_CHARS_PER_TOKEN,
|
|
9
|
+
type CacheCountingMode,
|
|
8
10
|
type MeterAction,
|
|
9
11
|
type MeterState,
|
|
10
12
|
type TurnSummary,
|
|
@@ -26,6 +28,8 @@ export interface AgentSpeedStoreDeps {
|
|
|
26
28
|
learnedCharsPerToken(model: string): number | undefined;
|
|
27
29
|
/** Called when a step produced a new chars/token measurement to persist. */
|
|
28
30
|
onCalibration(model: string, charsPerToken: number): void;
|
|
31
|
+
/** How the provider reports prompt cache reads (see `cacheStats`). */
|
|
32
|
+
cacheCounting(): CacheCountingMode;
|
|
29
33
|
now(): number;
|
|
30
34
|
}
|
|
31
35
|
|
|
@@ -75,7 +79,7 @@ export function createAgentSpeedStore(deps: AgentSpeedStoreDeps): AgentSpeedStor
|
|
|
75
79
|
};
|
|
76
80
|
|
|
77
81
|
const summary = (at?: number): TurnSummary =>
|
|
78
|
-
summarizeTurn(state, deps.charsPerToken(model), at ?? now());
|
|
82
|
+
summarizeTurn(state, deps.charsPerToken(model), at ?? now(), deps.cacheCounting());
|
|
79
83
|
|
|
80
84
|
const pushSample = () => {
|
|
81
85
|
if (state.phase !== "running") {
|
|
@@ -157,9 +161,11 @@ export function createAgentSpeedStore(deps: AgentSpeedStoreDeps): AgentSpeedStor
|
|
|
157
161
|
step.decodeMs > 0 ? ((step.outTokens + thinking) / (step.decodeMs / 1000)).toFixed(1) : "inf";
|
|
158
162
|
const thinkPart =
|
|
159
163
|
step.thinkingChars > 0 ? ` thinkChars=${step.thinkingChars} think~${Math.round(thinking)}` : "";
|
|
164
|
+
const stepCache = cacheStats(step.inputTokens, step.cachedTokens, deps.cacheCounting());
|
|
165
|
+
const hit = stepCache.hitRate === null ? "n/a" : `${Math.round(stepCache.hitRate * 100)}%`;
|
|
160
166
|
console.log(
|
|
161
167
|
`turn-speed: step ok [${deps.agentId.slice(0, 8)}] out=${step.outTokens}${thinkPart} in=${step.inputTokens}` +
|
|
162
|
-
` cached=${step.cachedTokens} decodeMs=${Math.round(step.decodeMs)} waitMs=${Math.round(step.waitMs)}` +
|
|
168
|
+
` cached=${step.cachedTokens} (${hit}) decodeMs=${Math.round(step.decodeMs)} waitMs=${Math.round(step.waitMs)}` +
|
|
163
169
|
` rate=${rate} verdict=${next.thinkingExcluded ? "excluded" : "off"}`,
|
|
164
170
|
);
|
|
165
171
|
}
|
package/index.client.tsx
CHANGED
|
@@ -4,6 +4,10 @@ import { createAgentSpeedStore, type AgentSpeedStore } from "./client/store";
|
|
|
4
4
|
import { bindPill } from "./client/pill";
|
|
5
5
|
import { makeSpeedDetails } from "./client/details";
|
|
6
6
|
import { parentAgentIdOf } from "./client/links";
|
|
7
|
+
import {
|
|
8
|
+
reconcileSnapshot,
|
|
9
|
+
turnStartFromEvent,
|
|
10
|
+
} from "./client/lifecycle";
|
|
7
11
|
import { summarizeTeam, type TeamMemberInput } from "./client/team";
|
|
8
12
|
import { makeSettingsScreen } from "./client/settings";
|
|
9
13
|
import {
|
|
@@ -62,6 +66,19 @@ export default function contribute(client: PluginClientContext) {
|
|
|
62
66
|
const logError = (...args: unknown[]) => {
|
|
63
67
|
if (!aborted()) console.error("turn-speed:", ...args);
|
|
64
68
|
};
|
|
69
|
+
/** A terminal event for a turn this meter never followed (its start was
|
|
70
|
+
* lost) must not close the current turn, replace its outcome, or clear the
|
|
71
|
+
* waits and tool calls that belong to it. An empty id is no id: the reducer
|
|
72
|
+
* treats it the same way. */
|
|
73
|
+
const belongsToCurrentTurn = (
|
|
74
|
+
store: AgentSpeedStore,
|
|
75
|
+
turnId: string | null | undefined,
|
|
76
|
+
): boolean => {
|
|
77
|
+
const id = turnId || null;
|
|
78
|
+
if (id === null) return true;
|
|
79
|
+
const current = store.state.turnId;
|
|
80
|
+
return current === null || current === id;
|
|
81
|
+
};
|
|
65
82
|
|
|
66
83
|
const notifyTeam = (parentId: string): void => {
|
|
67
84
|
for (const listener of teamWatchers.get(parentId) ?? []) {
|
|
@@ -231,8 +248,8 @@ export default function contribute(client: PluginClientContext) {
|
|
|
231
248
|
|
|
232
249
|
function onStreamEvent(
|
|
233
250
|
store: AgentSpeedStore,
|
|
234
|
-
handle: AgentHandle,
|
|
235
251
|
event: StreamEvent,
|
|
252
|
+
eventTimestamp: string | null | undefined,
|
|
236
253
|
reseed: () => void,
|
|
237
254
|
waits: Set<string>,
|
|
238
255
|
agentId: string,
|
|
@@ -244,23 +261,27 @@ export default function contribute(client: PluginClientContext) {
|
|
|
244
261
|
case "turn_started": {
|
|
245
262
|
waits.clear();
|
|
246
263
|
subCalls.clear();
|
|
247
|
-
|
|
248
|
-
|
|
264
|
+
// Anchor to the daemon's timestamp from this very message: a ref()
|
|
265
|
+
// snapshot updates on another channel and can still hold the previous
|
|
266
|
+
// turn's start, which would charge that whole turn to this one.
|
|
267
|
+
const start = turnStartFromEvent(eventTimestamp, at);
|
|
249
268
|
store.dispatch({
|
|
250
269
|
t: "turn_started",
|
|
251
|
-
at:
|
|
252
|
-
turnId: event.turnId
|
|
270
|
+
at: start.at,
|
|
271
|
+
turnId: event.turnId || null,
|
|
253
272
|
});
|
|
254
273
|
onSubChange();
|
|
255
274
|
break;
|
|
256
275
|
}
|
|
257
276
|
case "turn_completed":
|
|
277
|
+
if (!belongsToCurrentTurn(store, event.turnId)) break;
|
|
258
278
|
waits.clear();
|
|
259
279
|
subCalls.clear();
|
|
260
280
|
store.dispatch({
|
|
261
281
|
t: "turn_ended",
|
|
262
282
|
at,
|
|
263
283
|
kind: "completed",
|
|
284
|
+
turnId: event.turnId || null,
|
|
264
285
|
usage: event.usage ? mapUsage(event.usage) : undefined,
|
|
265
286
|
maxTokPerSec: prefs.maxPlausibleTokPerSec,
|
|
266
287
|
});
|
|
@@ -268,15 +289,29 @@ export default function contribute(client: PluginClientContext) {
|
|
|
268
289
|
void refreshPrefs();
|
|
269
290
|
break;
|
|
270
291
|
case "turn_failed":
|
|
292
|
+
if (!belongsToCurrentTurn(store, event.turnId)) break;
|
|
271
293
|
waits.clear();
|
|
272
294
|
subCalls.clear();
|
|
273
|
-
store.dispatch({
|
|
295
|
+
store.dispatch({
|
|
296
|
+
t: "turn_ended",
|
|
297
|
+
at,
|
|
298
|
+
kind: "failed",
|
|
299
|
+
turnId: event.turnId || null,
|
|
300
|
+
note: event.error,
|
|
301
|
+
});
|
|
274
302
|
onSubChange();
|
|
275
303
|
break;
|
|
276
304
|
case "turn_canceled":
|
|
305
|
+
if (!belongsToCurrentTurn(store, event.turnId)) break;
|
|
277
306
|
waits.clear();
|
|
278
307
|
subCalls.clear();
|
|
279
|
-
store.dispatch({
|
|
308
|
+
store.dispatch({
|
|
309
|
+
t: "turn_ended",
|
|
310
|
+
at,
|
|
311
|
+
kind: "canceled",
|
|
312
|
+
turnId: event.turnId || null,
|
|
313
|
+
note: event.reason,
|
|
314
|
+
});
|
|
280
315
|
onSubChange();
|
|
281
316
|
break;
|
|
282
317
|
case "permission_requested":
|
|
@@ -366,6 +401,7 @@ export default function contribute(client: PluginClientContext) {
|
|
|
366
401
|
charsPerToken: (model) => effectiveCpt(model),
|
|
367
402
|
learnedCharsPerToken: (model) => calibration.get(model),
|
|
368
403
|
onCalibration,
|
|
404
|
+
cacheCounting: () => prefs.cacheCounting,
|
|
369
405
|
now: () => Date.now(),
|
|
370
406
|
});
|
|
371
407
|
store.setIdentity(agent.provider, agent.model ?? null);
|
|
@@ -391,56 +427,15 @@ export default function contribute(client: PluginClientContext) {
|
|
|
391
427
|
// triggered the attach, then from the handle when it is populated.
|
|
392
428
|
observeUsage(agent.lastUsage ?? null);
|
|
393
429
|
observeUsage(handle.lastUsage);
|
|
394
|
-
// Open permission/question requests
|
|
395
|
-
//
|
|
430
|
+
// Open permission/question requests, tracked so stream events do not
|
|
431
|
+
// dispatch the same transition twice.
|
|
396
432
|
const pendingWaits = new Set<string>();
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
for (const request of pending) pendingWaits.add(request.id);
|
|
404
|
-
store.dispatch({
|
|
405
|
-
t: pendingWaits.size > 0 ? "user_wait_started" : "user_wait_ended",
|
|
406
|
-
at: Date.now(),
|
|
407
|
-
});
|
|
408
|
-
};
|
|
409
|
-
syncWaits(agent);
|
|
410
|
-
// Attaching mid-turn (agent created before the plugin loaded, or a fresh
|
|
411
|
-
// agent whose turn_started raced the subscription): start the meter from
|
|
412
|
-
// the snapshot so the pill exists for the rest of that turn.
|
|
413
|
-
const seedTurn = (snapshot: {
|
|
414
|
-
status?: string | null;
|
|
415
|
-
activeTurn?: { turnId?: string | null; startedAt?: string | null } | null;
|
|
416
|
-
}): void => {
|
|
417
|
-
if (store.state.phase !== "idle" || snapshot.status !== "running" || !snapshot.activeTurn) return;
|
|
418
|
-
const raw = snapshot.activeTurn.startedAt;
|
|
419
|
-
const parsed = raw ? Date.parse(raw) : Number.NaN;
|
|
420
|
-
store.dispatch({
|
|
421
|
-
t: "turn_started",
|
|
422
|
-
at: Number.isFinite(parsed) ? parsed : Date.now(),
|
|
423
|
-
turnId: snapshot.activeTurn.turnId ?? null,
|
|
424
|
-
});
|
|
425
|
-
};
|
|
426
|
-
seedTurn(agent);
|
|
427
|
-
// A ref() handle starts empty: without a real snapshot, the first usage
|
|
428
|
-
// event after a reload would count the session-cumulative counters as
|
|
429
|
-
// one giant step. Fetch the truth for that case.
|
|
430
|
-
const reseed = (): void => {
|
|
431
|
-
void handle
|
|
432
|
-
.refresh()
|
|
433
|
-
.then((result) => {
|
|
434
|
-
const snapshot = result?.agent;
|
|
435
|
-
if (!snapshot || attached.get(agent.id)?.store !== store) return;
|
|
436
|
-
store.setIdentity(snapshot.provider, snapshot.model ?? null);
|
|
437
|
-
observeUsage(snapshot.lastUsage ?? null);
|
|
438
|
-
syncWaits(snapshot);
|
|
439
|
-
seedTurn(snapshot);
|
|
440
|
-
})
|
|
441
|
-
.catch((error) => logError(`usage reseed failed for ${agent.id}`, error));
|
|
442
|
-
};
|
|
443
|
-
reseed();
|
|
433
|
+
// Live events are only delivered after the timeline subscription is
|
|
434
|
+
// established, and the daemon keeps no replay: anything that happens
|
|
435
|
+
// before `ready` is invisible. Seeding a turn before then is what leaves
|
|
436
|
+
// a turn that ends inside that window running forever, so seeding waits
|
|
437
|
+
// for `ready` and takes its snapshot afterwards.
|
|
438
|
+
let listening = false;
|
|
444
439
|
|
|
445
440
|
// Delegation: open sub_agent tool calls (or linked children that are
|
|
446
441
|
// running) mean the agent's own model is idle while subagents work, so
|
|
@@ -469,6 +464,45 @@ export default function contribute(client: PluginClientContext) {
|
|
|
469
464
|
console.log(`turn-speed: delegation ${should ? "on" : "off"} [${agent.id.slice(0, 8)}]`);
|
|
470
465
|
store.dispatch({ t: should ? "delegated_started" : "delegated_ended", at: Date.now() });
|
|
471
466
|
};
|
|
467
|
+
// One snapshot, one ordered set of actions: identify the turn, restore the
|
|
468
|
+
// waits that belong to it, then end a turn whose terminal event was lost.
|
|
469
|
+
// The last step is provisional, so a real terminal event still decides the
|
|
470
|
+
// outcome.
|
|
471
|
+
function reconcile(snapshot: AgentSnapshot): void {
|
|
472
|
+
const result = reconcileSnapshot(store.state, snapshot, Date.now(), { seed: listening });
|
|
473
|
+
if (result.pendingWaits) {
|
|
474
|
+
pendingWaits.clear();
|
|
475
|
+
for (const requestId of result.pendingWaits) pendingWaits.add(requestId);
|
|
476
|
+
}
|
|
477
|
+
for (const action of result.actions) {
|
|
478
|
+
store.dispatch(action);
|
|
479
|
+
if (action.t === "turn_ended" && action.provisional) {
|
|
480
|
+
subCalls.clear();
|
|
481
|
+
void refreshPrefs();
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
// Re-evaluate the delegation after the snapshot: it may have just
|
|
485
|
+
// established the turn, and children that are already running must park
|
|
486
|
+
// that time instead of charging it to the parent. Without this, a parent
|
|
487
|
+
// that attaches after its children would count their work as its own
|
|
488
|
+
// until the next child event.
|
|
489
|
+
syncDelegated();
|
|
490
|
+
}
|
|
491
|
+
// A ref() handle starts empty: without a real snapshot, the first usage
|
|
492
|
+
// event after a reload would count the session-cumulative counters as
|
|
493
|
+
// one giant step. Fetch the truth for that case.
|
|
494
|
+
function reseed(): void {
|
|
495
|
+
void handle
|
|
496
|
+
.refresh()
|
|
497
|
+
.then((result) => {
|
|
498
|
+
const snapshot = result?.agent;
|
|
499
|
+
if (!snapshot || attached.get(agent.id)?.store !== store) return;
|
|
500
|
+
store.setIdentity(snapshot.provider, snapshot.model ?? null);
|
|
501
|
+
observeUsage(snapshot.lastUsage ?? null);
|
|
502
|
+
reconcile(snapshot);
|
|
503
|
+
})
|
|
504
|
+
.catch((error) => logError(`usage reseed failed for ${agent.id}`, error));
|
|
505
|
+
}
|
|
472
506
|
const team = () => {
|
|
473
507
|
const view = summarizeTeam(
|
|
474
508
|
teamMembers(agent.id),
|
|
@@ -524,19 +558,36 @@ export default function contribute(client: PluginClientContext) {
|
|
|
524
558
|
remember(snapshot);
|
|
525
559
|
store.setIdentity(snapshot.provider, snapshot.model ?? null);
|
|
526
560
|
observeUsage(snapshot.lastUsage ?? null);
|
|
527
|
-
|
|
528
|
-
seedTurn(snapshot);
|
|
561
|
+
reconcile(snapshot);
|
|
529
562
|
if (snapshot.archivedAt || snapshot.status === "closed") detach(agent.id);
|
|
530
563
|
});
|
|
531
564
|
|
|
532
565
|
const timelineSub = handle.timeline.subscribe((event) => {
|
|
533
566
|
try {
|
|
534
|
-
onStreamEvent(
|
|
567
|
+
onStreamEvent(
|
|
568
|
+
store,
|
|
569
|
+
event.event,
|
|
570
|
+
"timestamp" in event ? event.timestamp : null,
|
|
571
|
+
reseed,
|
|
572
|
+
pendingWaits,
|
|
573
|
+
agent.id,
|
|
574
|
+
subCalls,
|
|
575
|
+
syncDelegated,
|
|
576
|
+
);
|
|
535
577
|
} catch (error) {
|
|
536
578
|
logError(`timeline event failed for ${agent.id}`, error);
|
|
537
579
|
}
|
|
538
580
|
});
|
|
539
|
-
void timelineSub.ready
|
|
581
|
+
void timelineSub.ready
|
|
582
|
+
.then(() => {
|
|
583
|
+
if (aborted() || attached.get(agent.id)?.store !== store) return;
|
|
584
|
+
listening = true;
|
|
585
|
+
// Live delivery is guaranteed from here on, and a fresh snapshot
|
|
586
|
+
// recovers whatever happened before it: start and terminal events can
|
|
587
|
+
// no longer fall into an uncovered window.
|
|
588
|
+
reseed();
|
|
589
|
+
})
|
|
590
|
+
.catch((error) => logError(`timeline subscribe failed for ${agent.id}`, error));
|
|
540
591
|
|
|
541
592
|
attached.set(agent.id, {
|
|
542
593
|
store,
|
package/package.json
CHANGED
package/shared/preferences.ts
CHANGED
|
@@ -17,6 +17,10 @@ export const preferences = defineSettings({
|
|
|
17
17
|
manualCharsPerToken: z.number().min(1).max(12).nullable().default(null),
|
|
18
18
|
/** Token count rendering: 1.2k or 1 240. */
|
|
19
19
|
tokenFormat: z.enum(["compact", "plain"]).default("compact"),
|
|
20
|
+
/** Append the turn's prompt cache hit rate to the pill label. */
|
|
21
|
+
showCacheInPill: z.boolean().default(false),
|
|
22
|
+
/** How the provider reports cache reads relative to the prompt counter. */
|
|
23
|
+
cacheCounting: z.enum(["auto", "inclusive", "separate"]).default("auto"),
|
|
20
24
|
/** Usage steps implying a faster decode than this are misattributed
|
|
21
25
|
* (late usage from a previous message) and get dropped from the turn. */
|
|
22
26
|
maxPlausibleTokPerSec: z.number().int().min(50).max(100000).default(400),
|