feat(providers): report session and turn metrics from OpenCode, OMP, Pi and Claude

Each provider now attaches metrics to turn_completed and emits
session_metrics_updated, live and when history is replayed.

- Live turns end on the adapter's clock. A provider's message timestamps
  can come from another clock.
- Tool time merges overlapping runs, so parallel tools count once.
- A total that is missing any part is hidden, so a partial total is
  never shown.
- Replayed history reports metrics only for turns that finished, which
  matches live, where failed and interrupted turns report none.
- Claude reports cost as a running total for each query(). A resumed
  query starts that total from a saved one, so a turn's cost is the
  change since the previous result of the same query. The first turn of
  a query shows no cost.
- Claude transcripts do not record result messages, so replayed Claude
  history has no turn metrics.
- Session metrics come from each provider's own cumulative counters. The
  cache hit is the last reply's or the last turn's, because a session-wide
  figure blends prompts from before and after compactions.
This commit is contained in:
Mohamed Boudra
2026-11-22 08:25:42 +01:00
parent eda4597aab
commit 43db5e2ca0
25 changed files with 2592 additions and 47 deletions
@@ -1,4 +1,5 @@
import { setImmediate } from "node:timers/promises";
import { ClaudeResultMeter } from "./metrics.js";
import { ClaudeRuntimeSafety } from "./runtime-safety.js";
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
import { applyProviderOptionsPatch } from "../../option-controls.js";
@@ -124,6 +125,7 @@ import {
type AgentOptionControl,
type AgentLaunchContext,
type AgentMetadata,
type AgentMetric,
type AgentMode,
type AgentModelDefinition,
type AgentPermissionRequest,
@@ -2539,6 +2541,7 @@ class ClaudeAgentSession implements AgentSession {
private cachedRuntimeInfo: AgentRuntimeInfo | null = null;
private lastOptionsModel: string | null = null;
private lastRuntimeModel: string | null = null;
private readonly resultMeter = new ClaudeResultMeter();
private compacting = false;
private compactionMarkerOpen = false;
private queryPumpPromise: Promise<void> | null = null;
@@ -3859,6 +3862,7 @@ class ClaudeAgentSession implements AgentSession {
this.dispatchEvents([{ type: "background_work", provider: "claude", items: null }]);
// A fresh Claude process has no turn of its own in flight.
this.mainTurnInFlight = false;
this.resultMeter.queryStarted();
this.query = claudeQuery(
{ prompt: input.iterable, options },
{
@@ -5370,6 +5374,25 @@ class ClaudeAgentSession implements AgentSession {
private appendResultEvents(
message: Extract<SDKMessage, { type: "result" }>,
events: AgentStreamEvent[],
): void {
const metrics = this.resultMeter.observe(
message,
this.lastRuntimeModel ?? this.config.model ?? null,
);
this.appendTurnOutcomeEvents(message, metrics.turn, events);
if (metrics.session?.length) {
events.push({
type: "session_metrics_updated",
provider: "claude",
metrics: metrics.session,
});
}
}
private appendTurnOutcomeEvents(
message: Extract<SDKMessage, { type: "result" }>,
turnMetrics: AgentMetric[],
events: AgentStreamEvent[],
): void {
const usage = this.convertUsage(message);
// Claude Code reports a turn that stopped on an API error (a usage limit, an overloaded or
@@ -5414,7 +5437,7 @@ class ClaudeAgentSession implements AgentSession {
},
});
}
events.push({ type: "turn_completed", provider: "claude", usage });
events.push({ type: "turn_completed", provider: "claude", usage, metrics: turnMetrics });
return;
}
const errorMessage =
@@ -0,0 +1,172 @@
import type { SDKResultMessage } from "@anthropic-ai/claude-agent-sdk";
import { describe, expect, test } from "vitest";
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
import { collectSessionTurnEvents } from "../test-utils/session-stream-adapter.js";
import { ClaudeAgentClient } from "./agent.js";
import { ClaudeResultMeter } from "./metrics.js";
import type { ClaudeQueryFactory } from "./query.js";
function result(fields: Record<string, unknown> = {}): SDKResultMessage {
return {
type: "result",
subtype: "success",
session_id: "metrics-session",
duration_ms: 9_000,
duration_api_ms: 6_000,
ttft_ms: 800,
is_error: false,
num_turns: 3,
result: "done",
stop_reason: "end_turn",
total_cost_usd: 0.05,
usage: {
input_tokens: 1_000,
output_tokens: 600,
cache_read_input_tokens: 3_000,
cache_creation_input_tokens: 0,
},
modelUsage: {
"claude-sonnet-4-6": { inputTokens: 1_000, outputTokens: 600 },
"claude-haiku-4-5": { inputTokens: 500, outputTokens: 100 },
},
permission_denials: [],
uuid: "result-1",
...fields,
} as unknown as SDKResultMessage;
}
describe("Claude result metrics", () => {
test("a turn reports its model, timing, steps, tokens and cache, and the session its totals", () => {
const meter = new ClaudeResultMeter();
meter.queryStarted();
expect(meter.observe(result(), "claude-sonnet-4-6")).toEqual({
turn: [
{ label: "Model", value: "claude-sonnet-4-6" },
{ label: "Elapsed", value: "9.0s" },
{ label: "Model time", value: "6.0s" },
{ label: "TTFT", value: "0.8s" },
{ label: "Steps", value: "3" },
{ label: "Tokens", value: "1.0K ↑ · 600 ↓" },
{ label: "Cache", value: "75%", tone: "ok" },
// The first result of a query carries earlier spend too, so its own cost is unknown.
],
session: [
// Every model the session called, the haiku side calls included.
{ label: "Tokens", value: "1.5K ↑ · 700 ↓" },
{ label: "Cache (last turn)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.050" },
],
});
});
test("a turn's cost is the change in the query's running total", () => {
const meter = new ClaudeResultMeter();
meter.queryStarted();
meter.observe(result({ total_cost_usd: 0.05 }), null);
const cost = (fields: Record<string, unknown>) =>
meter.observe(result(fields), null).turn.find((metric) => metric.label === "Cost")?.value;
expect(cost({ total_cost_usd: 0.08 })).toBe("$0.030");
// A crashed run zeroes the total; the next turn counts from the last real total.
expect(cost({ subtype: "error_during_execution", total_cost_usd: 0 })).toBeUndefined();
expect(cost({ total_cost_usd: 0.1 })).toBe("$0.020");
// A cleared session restarts the total.
expect(cost({ total_cost_usd: 0.01 })).toBeUndefined();
expect(cost({ total_cost_usd: 0.015 })).toBe("$0.005");
meter.queryStarted();
expect(cost({ total_cost_usd: 0.2 })).toBeUndefined();
});
test("an error result does not replace the session's totals", () => {
const meter = new ClaudeResultMeter();
expect(
meter.observe(result({ subtype: "error_during_execution", total_cost_usd: 0 }), null).session,
).toBeNull();
});
test("missing or malformed values hide only their metrics", () => {
const meter = new ClaudeResultMeter();
expect(
meter.observe(
result({
duration_api_ms: -1,
ttft_ms: undefined,
num_turns: 1,
usage: { output_tokens: 5 },
modelUsage: { broken: {} },
total_cost_usd: Number.NaN,
}),
null,
),
).toEqual({ turn: [{ label: "Elapsed", value: "9.0s" }], session: [] });
});
});
// A query that answers each prompt with init and a result, the way Claude Code does.
function resultQuery(results: Array<Record<string, unknown>>): ClaudeQueryFactory {
return ({ prompt }) => {
let turn = 0;
const messages = (async function* () {
if (typeof prompt === "string") throw new Error("Expected streaming input");
for await (const _message of prompt) {
yield {
type: "system",
subtype: "init",
session_id: "metrics-session",
permissionMode: "default",
model: "claude-sonnet-4-6",
};
yield result({ uuid: `result-${turn}`, ...results[turn] });
turn += 1;
}
})();
return Object.assign(messages, {
close: () => {
void messages.return();
},
interrupt: async () => undefined,
setModel: async () => undefined,
setPermissionMode: async () => undefined,
supportedModels: async () => [],
supportedCommands: async () => [],
}) as ReturnType<ClaudeQueryFactory>;
};
}
test("completed Claude turns carry their metrics and update the session's", async () => {
const client = new ClaudeAgentClient({
logger: createTestLogger(),
resolveBinary: async () => process.execPath,
queryFactory: resultQuery([{ total_cost_usd: 0.05 }, { total_cost_usd: 0.09 }]),
});
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
try {
await collectSessionTurnEvents(session, "first turn");
const second = await collectSessionTurnEvents(session, "second turn");
const completed = second.find((event) => event.type === "turn_completed");
expect(completed?.type === "turn_completed" ? completed.metrics : undefined).toEqual([
{ label: "Model", value: "claude-sonnet-4-6" },
{ label: "Elapsed", value: "9.0s" },
{ label: "Model time", value: "6.0s" },
{ label: "TTFT", value: "0.8s" },
{ label: "Steps", value: "3" },
{ label: "Tokens", value: "1.0K ↑ · 600 ↓" },
{ label: "Cache", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.040" },
]);
// Session totals follow the turn's outcome.
await expect
.poll(() => events.filter((event) => event.type === "session_metrics_updated").at(1))
.toMatchObject({
metrics: [
{ label: "Tokens", value: "1.5K ↑ · 700 ↓" },
{ label: "Cache (last turn)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.090" },
],
});
} finally {
await session.close();
}
});
@@ -0,0 +1,95 @@
import type { SDKResultMessage } from "@anthropic-ai/claude-agent-sdk";
import type { AgentMetric } from "../../agent-sdk-types.js";
import { formatMetricDuration } from "../metrics.js";
import { cacheMetric, costMetric, type MeasuredTokens, tokensMetric } from "../turn-metrics.js";
/**
* Turn and session metrics from Claude Code's result message, which ends every turn.
* Transcripts do not record results, so replayed history has no turn metrics.
*/
function amount(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
}
function duration(label: string, ms: number | null): AgentMetric[] {
const value = ms === null ? null : formatMetricDuration(ms);
return value ? [{ label, value }] : [];
}
/** The main loop's tokens for the turn; subagents and side calls are not included. */
function turnTokens(result: SDKResultMessage): MeasuredTokens | null {
const usage = result.usage;
const input = amount(usage?.input_tokens);
const output = amount(usage?.output_tokens);
if (input === null || output === null) return null;
return {
input,
output,
cacheRead: amount(usage.cache_read_input_tokens) ?? 0,
cacheWrite: amount(usage.cache_creation_input_tokens) ?? 0,
};
}
/** Every model the session called, subagents included, since the SDK started counting. */
function sessionTokens(result: SDKResultMessage): { input: number; output: number } | null {
let input = 0;
let output = 0;
for (const usage of Object.values(result.modelUsage ?? {})) {
const modelInput = amount(usage?.inputTokens);
const modelOutput = amount(usage?.outputTokens);
if (modelInput === null || modelOutput === null) return null;
input += modelInput;
output += modelOutput;
}
return { input, output };
}
export interface ClaudeResultMetrics {
turn: AgentMetric[];
/** Null for a result whose totals are not the session's: Claude zeroes them on a crash. */
session: AgentMetric[] | null;
}
/**
* Reads results in the order one query() reports them. The SDK reports cost as a
* running total for the query, so a turn's cost is the change since the last result.
*/
export class ClaudeResultMeter {
private totalCostUsd: number | null = null;
/** A new query() may start its running total from a saved one, so no change is known yet. */
queryStarted(): void {
this.totalCostUsd = null;
}
observe(result: SDKResultMessage, model: string | null): ClaudeResultMetrics {
const total = amount(result.total_cost_usd);
const previous = this.totalCostUsd;
// A crashed run reports zero; keep counting from the last real total.
if (total !== null && total > 0) this.totalCostUsd = total;
const turnCost =
total !== null && previous !== null && total >= previous ? total - previous : null;
const tokens = turnTokens(result);
const steps = amount(result.num_turns);
const turn = [
...(model ? [{ label: "Model", value: model }] : []),
...duration("Elapsed", amount(result.duration_ms)),
...duration("Model time", amount(result.duration_api_ms)),
...duration("TTFT", "ttft_ms" in result ? amount(result.ttft_ms) : null),
...(steps !== null && steps > 1 ? [{ label: "Steps", value: String(steps) }] : []),
...(tokens ? [...tokensMetric(tokens), ...cacheMetric(tokens, "Cache")] : []),
...costMetric(turnCost),
];
if (result.subtype !== "success") return { turn, session: null };
const totals = sessionTokens(result);
return {
turn,
session: [
...(totals ? tokensMetric(totals) : []),
...(tokens ? cacheMetric(tokens, "Cache (last turn)") : []),
...costMetric(total),
],
};
}
}
@@ -104,3 +104,20 @@ export function mergeTimeIntervals(intervals: readonly TimeInterval[]): [number,
}
return merged;
}
/**
* Reports session metrics only when they change, for providers that recompute
* them after every event.
*/
export function createSessionMetricsReporter(
report: (metrics: AgentMetric[]) => void,
): (metrics: AgentMetric[]) => void {
// A session starts with nothing reported, so an empty first report is not news.
let reported = "[]";
return (metrics) => {
const key = JSON.stringify(metrics);
if (key === reported) return;
reported = key;
report(metrics);
};
}
@@ -112,6 +112,9 @@ import { OmpSubagentIndex } from "./subagent-index.js";
import { OmpQuestionUi } from "./question-ui.js";
import { mapOmpToolDetail } from "./tool-call-mapper.js";
import { OmpUsagePoller, type OmpUsagePollScheduler } from "./usage-poller.js";
import { ompReplyStep, ompSessionMetrics } from "./metrics.js";
import { type MeasuredStep, measuredTurnMetrics, TurnMeter } from "../turn-metrics.js";
import { createSessionMetricsReporter } from "../metrics.js";
import {
buildOmpRpcUiPermissionResponse,
mapOmpRpcUiPermissionRequest,
@@ -704,6 +707,11 @@ export class OmpAgentSession implements AgentSession {
private readonly providerIdleDeadlineMs: number;
private readonly noTurnScheduler: OmpNoTurnScheduler;
private readonly usagePoller: OmpUsagePoller;
private readonly turnMeter = new TurnMeter();
private lastReply: MeasuredStep | null = null;
private readonly reportSessionMetrics = createSessionMetricsReporter((metrics) =>
this.emit({ type: "session_metrics_updated", provider: this.provider, metrics }),
);
private closed = false;
private live: boolean;
private readonly emittedUserMessageIds = new Set<string>();
@@ -740,13 +748,14 @@ export class OmpAgentSession implements AgentSession {
this.usagePoller = new OmpUsagePoller({
scheduler: options.usagePollScheduler,
readStats: () => this.runtimeSession.getSessionStats(),
onUsage: (usage, turnId) => {
onUsage: (usage, turnId, stats) => {
this.emit({
type: "usage_updated",
provider: this.provider,
usage,
...(turnId === undefined ? {} : { turnId }),
});
this.reportSessionMetrics(ompSessionMetrics(stats, this.lastReply));
},
onPollError: (error) => {
this.logger.debug({ err: error }, "OMP context usage poll failed");
@@ -878,6 +887,7 @@ export class OmpAgentSession implements AgentSession {
const turnId = randomUUID();
this.live = true;
this.activeTurnId = turnId;
this.turnMeter.begin(Date.now());
this.activeAssistantMessageId = null;
this.activeTurnTerminalAssistantMessage = null;
this.activeTurnStarted = false;
@@ -1010,12 +1020,24 @@ export class OmpAgentSession implements AgentSession {
}
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
yield* streamOmpHistory({
const replay = yield* streamOmpHistory({
sessionFile: this.state.sessionFile,
runtimeSession: this.runtimeSession,
provider: this.provider,
bridgedTools: this.hostTools?.bridge?.toolIdentities(),
});
this.lastReply ??= replay.lastReply;
const stats = await this.runtimeSession.getSessionStats().catch((error: unknown) => {
this.logger.debug({ err: error }, "OMP session stats unavailable for history");
return null;
});
if (stats) {
yield {
type: "session_metrics_updated",
provider: this.provider,
metrics: ompSessionMetrics(stats, this.lastReply),
};
}
for (const item of mapOmpTodoState(this.state)) {
yield {
type: "timeline",
@@ -1250,6 +1272,7 @@ export class OmpAgentSession implements AgentSession {
this.outOfBandTurnStartAnnounced = false;
this.activeTurnHasUserMessage = false;
this.pendingClientMessages.length = 0;
this.turnMeter.reset();
this.clearNoTurnBuffers();
}
@@ -1904,6 +1927,7 @@ export class OmpAgentSession implements AgentSession {
this.handleMessageUpdate(event, turnId);
return;
case "tool_execution_start": {
this.turnMeter.toolStarted(event.toolCallId, Date.now());
const toolCall = parseToolArgs(event.toolName, event.args);
this.activeToolCalls.set(event.toolCallId, toolCall);
this.questionUi.start(event.toolName, event.args);
@@ -1921,6 +1945,7 @@ export class OmpAgentSession implements AgentSession {
return;
}
case "tool_execution_end": {
this.turnMeter.toolEnded(event.toolCallId, Date.now());
this.handleToolExecutionEnd(event, turnId);
return;
}
@@ -2043,6 +2068,13 @@ export class OmpAgentSession implements AgentSession {
}
}
private observeReply(message: OmpAgentMessage): void {
const step = ompReplyStep(message);
if (!step) return;
this.turnMeter.step(step, Date.now());
this.lastReply = step;
}
private handleMessageEnd(
event: Extract<OmpAgentSessionEvent, { type: "message_end" }>,
turnId: string | undefined,
@@ -2050,6 +2082,7 @@ export class OmpAgentSession implements AgentSession {
if (event.message.role === "assistant") {
this.activeAssistantMessageId = null;
this.questionUi.observeMessage(event.message);
this.observeReply(event.message);
if (turnId) {
this.activeTurnTerminalAssistantMessage = event.message;
}
@@ -2216,11 +2249,13 @@ export class OmpAgentSession implements AgentSession {
return;
}
const finalUsage = this.usagePoller.completeTurn(turnId);
const metrics = measuredTurnMetrics(this.turnMeter.finish(Date.now()));
this.resetActiveTurn({ terminalizeWork: false });
this.emit({
type: "turn_completed",
provider: this.provider,
turnId,
metrics,
});
void this.refreshAfterTurn(finalUsage);
}
@@ -878,7 +878,7 @@ describe("OMP history mapper", () => {
const events: AgentStreamEvent[] = [];
for await (const event of streamOmpHistory({ sessionFile, provider: "omp" })) {
events.push(event);
if (event.type === "timeline") events.push(event);
}
expect(events.map((event) => event.item)).toEqual([
{ type: "assistant_message", text: "Before.", messageId: "resp-1" },
@@ -1,7 +1,14 @@
import { open, type FileHandle } from "node:fs/promises";
import { setImmediate } from "node:timers/promises";
import { basename, extname, join } from "node:path";
import type { AgentProvider, AgentStreamEvent, AgentTimelineItem } from "../../agent-sdk-types.js";
import type {
AgentMetric,
AgentProvider,
AgentStreamEvent,
AgentTimelineItem,
} from "../../agent-sdk-types.js";
import type { MeasuredStep } from "../turn-metrics.js";
import { ompReplayedTurns } from "./metrics.js";
import { normalizeProviderReplayTimestamp } from "../../provider-history-timestamps.js";
import { OmpHistoryMapper, type OmpCapturedUserMessageEntry } from "./message-history.js";
import type { OmpAgentMessage } from "./rpc-types.js";
@@ -67,19 +74,25 @@ function buildOmpModelId(provider: unknown, model: unknown): string | null {
return normalizedProvider && normalizedModel ? `${normalizedProvider}/${normalizedModel}` : null;
}
/** What a replay learned that the live session reports from later. */
export interface OmpHistoryReplay {
lastReply: MeasuredStep | null;
}
export async function* streamOmpHistory(input: {
sessionFile?: string;
runtimeSession?: OmpRuntimeSession;
provider: AgentProvider;
bridgedTools?: ReadonlyMap<string, OmpBridgedToolIdentity>;
visitedSessionFiles?: Set<string>;
}): AsyncGenerator<AgentStreamEvent> {
}): AsyncGenerator<AgentStreamEvent, OmpHistoryReplay> {
const replay: OmpHistoryReplay = { lastReply: null };
if (!input.sessionFile) {
return;
return replay;
}
const visitedSessionFiles = input.visitedSessionFiles ?? new Set<string>();
if (visitedSessionFiles.has(input.sessionFile)) {
return;
return replay;
}
visitedSessionFiles.add(input.sessionFile);
let entries: OmpSessionEntry[];
@@ -90,7 +103,7 @@ export async function* streamOmpHistory(input: {
);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return;
return replay;
}
throw error;
}
@@ -118,6 +131,9 @@ export async function* streamOmpHistory(input: {
OMP_HISTORY_MAPPER_HOOKS,
input.bridgedTools,
);
const turns = ompReplayedTurns();
const turnCompleted = (metrics: AgentMetric[]): AgentStreamEvent[] =>
metrics.length ? [{ type: "turn_completed", provider: input.provider, metrics }] : [];
let replayed = 0;
for (const replayEntry of replayEntries) {
if (++replayed % 32 === 0) await setImmediate();
@@ -125,14 +141,20 @@ export async function* streamOmpHistory(input: {
const events: AgentStreamEvent[] =
"item" in replayEntry
? [{ type: "timeline", provider: input.provider, item: replayEntry.item }]
: mapper.mapMessages([replayEntry.message]);
: [
...turnCompleted(turns.observe(replayEntry.message)),
...mapper.mapMessages([replayEntry.message]),
];
for (const event of events) {
yield timestamp && event.type === "timeline" ? { ...event, timestamp } : event;
}
}
yield* turnCompleted(turns.end());
replay.lastReply = turns.lastReply;
for (const transcript of readSubagentTranscripts(messages, input.sessionFile)) {
yield* replaySubagentTranscript(transcript, input.provider, visitedSessionFiles);
}
return replay;
}
async function* replaySubagentTranscript(
@@ -0,0 +1,280 @@
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, onTestFinished, test } from "vitest";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
import type { AgentPersistenceHandle, AgentStreamEvent } from "../../agent-sdk-types.js";
import { OmpAgentClient } from "./agent.js";
import { ompReplyStep, ompSessionMetrics } from "./metrics.js";
import type { OmpAgentMessage } from "./rpc-types.js";
import { FakeOmp } from "./test-utils/fake-omp.js";
// The fields OMP records on an assistant message, which Paseo's message schema leaves untyped.
function reply(fields: Record<string, unknown> = {}): OmpAgentMessage {
return {
role: "assistant",
content: [{ type: "text", text: "done" }],
provider: "anthropic",
model: "claude-sonnet",
stopReason: "stop",
usage: {
input: 1_000,
output: 600,
cacheRead: 3_000,
cacheWrite: 0,
cost: { total: 0.012 },
},
timestamp: 10_000,
duration: 3_000,
ttft: 500,
completedAt: 13_100,
...fields,
} as OmpAgentMessage;
}
function metric(metrics: { label: string; value: string }[] | undefined, label: string) {
return metrics?.find((entry) => entry.label === label)?.value;
}
type StreamEvent<T extends AgentStreamEvent["type"]> = Extract<AgentStreamEvent, { type: T }>;
function firstEvent<T extends AgentStreamEvent["type"]>(events: AgentStreamEvent[], type: T) {
return events.find((event): event is StreamEvent<T> => event.type === type);
}
function lastEvent<T extends AgentStreamEvent["type"]>(events: AgentStreamEvent[], type: T) {
return events.findLast((event): event is StreamEvent<T> => event.type === type);
}
describe("OMP reply steps", () => {
test("reads the served model, usage and timing", () => {
expect(ompReplyStep(reply({ upstreamModel: "claude-sonnet-4-6" }))).toEqual({
model: "claude-sonnet-4-6",
tokens: { input: 1_000, output: 600, cacheRead: 3_000, cacheWrite: 0 },
costUsd: 0.012,
durationMs: 3_000,
ttftMs: 500,
endedAt: 13_100,
});
});
test("a malformed field costs only that field", () => {
expect(
ompReplyStep(reply({ ttft: "fast", usage: { input: 1 }, completedAt: undefined })),
).toEqual({
model: "claude-sonnet",
tokens: null,
costUsd: null,
durationMs: 3_000,
ttftMs: null,
// Without OMP's completion stamp the response ended when the request did.
endedAt: 13_000,
});
});
test("other messages are not steps", () => {
expect(ompReplyStep({ role: "user", content: "hi" })).toBeNull();
});
});
describe("OMP session metrics", () => {
test("reports OMP's cumulative totals and the last reply's cache hit", () => {
expect(
ompSessionMetrics(
{
tokens: { input: 50_000, output: 4_000, cacheRead: 200_000, cacheWrite: 0 },
cost: 2.5,
toolCalls: 12,
premiumRequests: 3,
},
ompReplyStep(reply()),
),
).toEqual([
{ label: "Tokens", value: "50.0K ↑ · 4.0K ↓" },
{ label: "Cache (last reply)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$2.50" },
{ label: "Tool calls", value: "12" },
{ label: "Premium requests", value: "3" },
]);
});
test("a new session reports nothing", () => {
expect(ompSessionMetrics({}, null)).toEqual([]);
});
});
describe("OMP metrics through the session", () => {
test("a completed turn carries its metrics and the session reports its totals", async () => {
const runtime = new FakeOmp();
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
const session = await client.createSession({ provider: "omp", cwd: process.cwd() });
onTestFinished(() => session.close());
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await session.startTurn("fix the build");
const omp = runtime.latestSession();
omp.beginTurn();
omp.acceptPrompt("fix the build");
const plan = reply({
stopReason: "toolUse",
duration: 1_000,
ttft: 300,
completedAt: undefined,
});
omp.emit({ type: "message_end", message: plan });
omp.emit({ type: "tool_execution_start", toolCallId: "call-1", toolName: "bash", args: {} });
omp.emit({ type: "tool_execution_end", toolCallId: "call-1", toolName: "bash", result: {} });
const answer = reply({ upstreamModel: "claude-sonnet-4-6", ttft: 700 });
omp.emit({ type: "message_end", message: answer });
omp.stats = {
tokens: { input: 2_000, output: 1_200, cacheRead: 6_000, cacheWrite: 0 },
cost: 0.024,
};
omp.finishTurn(answer);
await expect.poll(() => firstEvent(events, "turn_completed")).toBeDefined();
const completed = firstEvent(events, "turn_completed");
const metrics = completed?.metrics;
expect(metric(metrics, "Model")).toBe("claude-sonnet-4-6");
// 1,200 output tokens over 4s of requests.
expect(metric(metrics, "Speed")).toBe("~300 tok/s");
expect(metric(metrics, "Model time")).toBe("4.0s");
expect(metric(metrics, "Average TTFT")).toBe("0.5s");
expect(metric(metrics, "Steps")).toBe("2");
expect(metric(metrics, "Tokens")).toBe("2.0K ↑ · 1.2K ↓");
expect(metric(metrics, "Cost")).toBe("$0.024");
expect(metrics?.some((entry) => entry.label === "Elapsed")).toBe(true);
await expect
.poll(() => lastEvent(events, "session_metrics_updated"))
.toMatchObject({
metrics: [
{ label: "Tokens", value: "2.0K ↑ · 1.2K ↓" },
{ label: "Cache (last reply)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.024" },
],
});
});
test("a failed turn reports no metrics and the next turn starts its own", async () => {
const runtime = new FakeOmp();
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
const session = await client.createSession({ provider: "omp", cwd: process.cwd() });
onTestFinished(() => session.close());
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await session.startTurn("first");
const omp = runtime.latestSession();
omp.beginTurn();
omp.acceptPrompt("first");
const failed = reply({ stopReason: "error", errorMessage: "overloaded" });
omp.emit({ type: "message_end", message: failed });
omp.finishTurn(failed);
await expect.poll(() => firstEvent(events, "turn_failed") !== undefined).toBe(true);
await session.startTurn("second");
omp.beginTurn();
omp.acceptPrompt("second", "omp-user-2");
const answer = reply({ duration: 2_000, ttft: 100 });
omp.emit({ type: "message_end", message: answer });
omp.finishTurn(answer);
await expect.poll(() => firstEvent(events, "turn_completed")).toBeDefined();
const completed = firstEvent(events, "turn_completed");
const metrics = completed?.metrics;
expect(metric(metrics, "Steps")).toBeUndefined();
expect(metric(metrics, "TTFT")).toBe("0.1s");
});
});
describe("OMP history metrics", () => {
async function sessionFile(messages: Record<string, unknown>[]) {
const directory = await mkdtemp(join(tmpdir(), "paseo-omp-metrics-"));
const file = join(directory, "session.jsonl");
const entries = [
{ type: "session", id: "root", parentId: null },
...messages.map((message, index) => ({
type: "message",
id: `entry-${index}`,
parentId: index === 0 ? "root" : `entry-${index - 1}`,
message,
})),
];
await writeFile(file, entries.map((entry) => JSON.stringify(entry)).join("\n"));
return file;
}
test("replays each finished turn's metrics after its rows", async () => {
const file = await sessionFile([
{ role: "user", content: "first", timestamp: 9_000 },
reply({ completedAt: 13_000 }),
{ role: "user", content: "second", timestamp: 20_000 },
reply({ stopReason: "aborted", errorMessage: "Interrupted" }),
{ role: "user", content: "third", timestamp: 30_000 },
reply({ stopReason: "toolUse" }),
]);
const handle: AgentPersistenceHandle = {
provider: "omp",
sessionId: "history-1",
nativeHandle: file,
metadata: { cwd: process.cwd() },
};
const client = new OmpAgentClient({ logger: createTestLogger(), runtime: new FakeOmp() });
const session = await client.resumeSession(handle, undefined, undefined, {
purpose: "history",
});
const events: AgentStreamEvent[] = [];
try {
for await (const event of session.streamHistory()) events.push(event);
} finally {
await session.close();
}
const sequence = events.map((event) =>
event.type === "timeline" ? event.item.type : event.type,
);
expect(sequence.slice(0, 4)).toEqual([
"user_message",
"assistant_message",
"turn_completed",
"user_message",
]);
expect(sequence.filter((type) => type === "turn_completed")).toHaveLength(1);
const completed = firstEvent(events, "turn_completed");
const metrics = completed?.metrics;
expect(metric(metrics, "Elapsed")).toBe("4.0s");
expect(metric(metrics, "Speed")).toBe("~200 tok/s");
// OMP does not record how long tools ran.
expect(metric(metrics, "Tool time")).toBeUndefined();
});
test("a live session restores its session metrics from history", async () => {
const file = await sessionFile([{ role: "user", content: "first", timestamp: 9_000 }, reply()]);
const runtime = new FakeOmp();
runtime.queueSessionSetup((omp) => {
omp.stats = {
tokens: { input: 1_000, output: 600, cacheRead: 3_000, cacheWrite: 0 },
cost: 0.012,
};
});
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
const session = await client.resumeSession({
provider: "omp",
sessionId: "omp-session-1",
nativeHandle: file,
metadata: { cwd: process.cwd() },
});
onTestFinished(() => session.close());
const events: AgentStreamEvent[] = [];
for await (const event of session.streamHistory()) events.push(event);
expect(lastEvent(events, "session_metrics_updated")).toMatchObject({
metrics: [
{ label: "Tokens", value: "1.0K ↑ · 600 ↓" },
{ label: "Cache (last reply)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.012" },
],
});
});
});
@@ -0,0 +1,108 @@
import { z } from "zod";
import type { AgentMetric } from "../../agent-sdk-types.js";
import {
type MeasuredStep,
ReplayedTurns,
sessionTotalsMetrics,
type TurnMessageReader,
} from "../turn-metrics.js";
import type { OmpAgentMessage, OmpSessionStats } from "./rpc-types.js";
// Fields OMP records on a message that only metrics read. Each one falls back on its
// own: transcripts are read without validation, and a value of an unexpected shape
// should cost that metric, not the message.
const count = z.number().nonnegative().optional().catch(undefined);
const label = z.string().min(1).optional().catch(undefined);
const OmpUsageSchema = z.object({
input: z.number().nonnegative(),
/** Reasoning included. */
output: z.number().nonnegative(),
cacheRead: z.number().nonnegative(),
cacheWrite: z.number().nonnegative(),
cost: z.object({ total: z.number().nonnegative() }).optional().catch(undefined),
});
const OmpReplyMetricsSchema = z.object({
model: label,
/** The model a router or gateway actually served. */
upstreamModel: label,
usage: OmpUsageSchema.optional().catch(undefined),
/** When the request was sent. */
timestamp: count,
duration: count,
ttft: count,
/** Local time OMP finished streaming the response. */
completedAt: count,
stopReason: label,
errorMessage: z.string().nullable().optional().catch(undefined),
});
const OmpPromptMetricsSchema = z.object({ timestamp: count });
const UNFINISHED_STOP_REASONS = new Set(["toolUse", "error", "aborted"]);
export function ompReplyStep(message: OmpAgentMessage): MeasuredStep | null {
if (message.role !== "assistant") return null;
const reply = OmpReplyMetricsSchema.parse(message);
const usage = reply.usage;
const endedAt =
reply.completedAt ??
(reply.timestamp !== undefined && reply.duration !== undefined
? reply.timestamp + reply.duration
: undefined);
return {
model: reply.upstreamModel ?? reply.model ?? null,
tokens: usage
? {
input: usage.input,
output: usage.output,
cacheRead: usage.cacheRead,
cacheWrite: usage.cacheWrite,
}
: null,
costUsd: usage?.cost?.total ?? null,
durationMs: reply.duration ?? null,
ttftMs: reply.ttft ?? null,
endedAt: endedAt ?? null,
};
}
function isFinalReply(message: OmpAgentMessage): boolean {
if (message.role !== "assistant" || message.errorMessage) return false;
return !UNFINISHED_STOP_REASONS.has(message.stopReason ?? "");
}
const reader: TurnMessageReader<OmpAgentMessage> = {
prompt: (message) =>
message.role === "user"
? { startedAt: OmpPromptMetricsSchema.parse(message).timestamp ?? null }
: null,
reply: (message) => {
const step = ompReplyStep(message);
return step ? { step, final: isFinalReply(message) } : null;
},
};
/** Replays an OMP transcript's turns. OMP does not record how long tools ran. */
export function ompReplayedTurns(): ReplayedTurns<OmpAgentMessage> {
return new ReplayedTurns(reader);
}
export function ompSessionMetrics(
stats: OmpSessionStats,
lastReply: MeasuredStep | null,
): AgentMetric[] {
const metrics = sessionTotalsMetrics(
{
input: stats.tokens?.input ?? 0,
output: stats.tokens?.output ?? 0,
costUsd: stats.cost ?? null,
},
lastReply,
);
if (stats.toolCalls) metrics.push({ label: "Tool calls", value: String(stats.toolCalls) });
if (stats.premiumRequests)
metrics.push({ label: "Premium requests", value: String(stats.premiumRequests) });
return metrics;
}
@@ -180,6 +180,9 @@ export const OmpSessionStatsSchema = z
.passthrough()
.optional(),
cost: z.number().optional(),
toolCalls: z.number().optional(),
// Copilot bills by request rather than by token.
premiumRequests: z.number().optional(),
contextUsage: OmpContextUsageSchema.optional(),
})
.passthrough();
@@ -7,7 +7,8 @@ export interface OmpUsagePollScheduler {
interface OmpUsagePollerOptions {
readStats(): Promise<OmpSessionStats>;
onUsage(usage: AgentUsage, turnId?: string): void;
/** Called when usage changes, with the stats it was read from. */
onUsage(usage: AgentUsage, turnId: string | undefined, stats: OmpSessionStats): void;
onPollError(error: unknown): void;
scheduler?: OmpUsagePollScheduler;
}
@@ -93,27 +94,27 @@ export class OmpUsagePoller {
}
this.active = false;
const completionGeneration = this.invalidatePendingWork();
let usage: AgentUsage | undefined;
let stats: OmpSessionStats;
try {
usage = toAgentUsage(await this.options.readStats());
stats = await this.options.readStats();
} catch {
return;
}
if (this.closed || this.generation !== completionGeneration) {
return;
}
this.publishUsage(usage, turnId);
this.publishUsage(stats, turnId);
}
async refresh(): Promise<void> {
let usage: AgentUsage | undefined;
let stats: OmpSessionStats;
try {
usage = toAgentUsage(await this.options.readStats());
stats = await this.options.readStats();
} catch (error) {
if (!this.closed) this.options.onPollError(error);
return;
}
if (!this.closed) this.publishUsage(usage);
if (!this.closed) this.publishUsage(stats);
}
close(): void {
@@ -137,9 +138,9 @@ export class OmpUsagePoller {
}
private async poll(generation: number): Promise<void> {
let usage: AgentUsage | undefined;
let stats: OmpSessionStats;
try {
usage = toAgentUsage(await this.options.readStats());
stats = await this.options.readStats();
} catch (error) {
try {
if (this.active && !this.closed && this.generation === generation) {
@@ -154,7 +155,7 @@ export class OmpUsagePoller {
}
try {
if (this.active && !this.closed && this.generation === generation) {
this.publishUsage(usage);
this.publishUsage(stats);
}
} finally {
if (this.active && !this.closed && this.generation === generation) {
@@ -171,10 +172,10 @@ export class OmpUsagePoller {
return usage;
}
private publishUsage(usage: AgentUsage | undefined, turnId?: string): void {
const changedUsage = this.takeChangedUsage(usage);
private publishUsage(stats: OmpSessionStats, turnId?: string): void {
const changedUsage = this.takeChangedUsage(toAgentUsage(stats));
if (changedUsage) {
this.options.onUsage(changedUsage, turnId);
this.options.onUsage(changedUsage, turnId, stats);
}
}
}
@@ -33,6 +33,7 @@ export class V2Harness {
active = false;
activeReads = 0;
autoComplete = true;
sessionGetError: Error | null = null;
constructor(private sequence = 0) {}
private executions: SessionLogItem[] = [];
startExecution() {
@@ -142,7 +143,10 @@ export class V2Harness {
this.creates.push(input);
return this.info;
},
get: async () => this.info,
get: async () => {
if (this.sessionGetError) throw this.sessionGetError;
return this.info;
},
list: async () => ({ data: [], cursor: {} }),
active: async () => {
this.activeReads += 1;
@@ -0,0 +1,399 @@
import type { SessionInfo, SessionMessageInfo, TokenUsageInfo } from "@opencode/client";
import { describe, expect, test } from "vitest";
import { createTestLogger } from "../../../../../test-utils/test-logger.js";
import type { AgentMetric, AgentStreamEvent } from "../../../agent-sdk-types.js";
import { V2Harness } from "../test-utils/v2-harness.js";
import { OpenCodeV2AgentClient } from "./agent.js";
import { latestTurnMetrics, replayedTurnMetrics, sessionMetrics } from "./metrics.js";
type Assistant = Extract<SessionMessageInfo, { type: "assistant" }>;
type Content = Assistant["content"][number];
function tokens(
input: number,
output: number,
{ reasoning = 0, read = 0, write = 0 } = {},
): TokenUsageInfo {
return { input, output, reasoning, cache: { read, write } };
}
function user(id: string, created: number): SessionMessageInfo {
return { id, type: "user", text: id, time: { created } };
}
function idle(
id: string,
created: number,
outcome: "succeeded" | "failed" = "succeeded",
): SessionMessageInfo {
return { id, type: "idle", outcome, time: { created } };
}
function step(
id: string,
time: { created: number; firstToken?: number; streamed?: number; completed?: number },
options: {
tokens?: TokenUsageInfo;
cost?: number;
content?: Content[];
model?: Assistant["model"];
error?: Assistant["error"];
} = {},
): SessionMessageInfo {
return {
id,
type: "assistant",
agent: "build",
model: options.model ?? { providerID: "anthropic", id: "claude-sonnet" },
// The bundled client predates `firstToken`; newer servers send it.
time: time as Assistant["time"],
content: options.content ?? [{ type: "text", text: "answer" }],
tokens: options.tokens ?? tokens(0, 0),
...(options.cost === undefined ? {} : { cost: options.cost }),
...(options.error ? { error: options.error } : {}),
};
}
function tool(id: string, time: { created: number; ran?: number; completed?: number }): Content {
return {
type: "tool",
id,
name: "bash",
time,
state: { status: "completed", input: {}, content: [{ type: "text", text: "ok" }] },
};
}
function metric(metrics: AgentMetric[], label: string) {
return metrics.find((entry) => entry.label === label);
}
describe("OpenCode v2 turn metrics", () => {
test("a single reply reports its model, speed, timing, tokens, cache and cost", () => {
const metrics = latestTurnMetrics([
user("prompt", 1_000),
step(
"reply",
{ created: 1_200, firstToken: 1_700, streamed: 3_700, completed: 3_800 },
{
tokens: tokens(2_000, 900, { reasoning: 100, read: 6_000, write: 2_000 }),
cost: 0.0123,
model: { providerID: "anthropic", id: "claude-sonnet", variant: "high" },
},
),
]);
expect(metrics).toEqual([
{ label: "Model", value: "anthropic/claude-sonnet (high)" },
// 1,000 generated tokens over the 2s between the first token and the end of the stream.
{ label: "Response", value: "~500 tok/s" },
// The same tokens over the 2.6s the model ran.
{ label: "Whole turn", value: "~385 tok/s" },
{ label: "Elapsed", value: "2.8s" },
{ label: "Model time", value: "2.6s" },
{ label: "TTFT", value: "0.5s" },
{ label: "Tokens", value: "2.0K ↑ · 1.0K ↓" },
{ label: "Cache", value: "60%", tone: "ok" },
{ label: "Cost", value: "$0.012" },
]);
});
test("a multi-step turn sums its steps and leaves parallel tool time out of model time", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step(
"plan",
{ created: 100, firstToken: 300, streamed: 1_100, completed: 4_100 },
{
tokens: tokens(1_000, 400, { read: 3_000 }),
cost: 0.01,
content: [
// Two tools run side by side over 1.1s–4.1s; together they took 3s, not 5s.
tool("a", { created: 900, ran: 1_100, completed: 4_100 }),
tool("b", { created: 1_000, ran: 2_100, completed: 4_100 }),
],
},
),
step(
"answer",
{ created: 4_200, firstToken: 4_600, streamed: 5_200, completed: 5_200 },
{ tokens: tokens(500, 600, { read: 4_500 }), cost: 0.02 },
),
]);
expect(metric(metrics, "Steps")).toEqual({ label: "Steps", value: "2" });
expect(metric(metrics, "Elapsed")?.value).toBe("5.2s");
// (4.0s - 3.0s tools) + 1.0s.
expect(metric(metrics, "Model time")?.value).toBe("2.0s");
expect(metric(metrics, "Tool time")?.value).toBe("3.0s");
// 1,000 generated tokens over 2s of model time.
expect(metric(metrics, "Whole turn")?.value).toBe("~500 tok/s");
// The final reply streamed 600 tokens in 0.6s.
expect(metric(metrics, "Response")?.value).toBe("~1000 tok/s");
expect(metric(metrics, "Average TTFT")?.value).toBe("0.3s");
expect(metric(metrics, "Tokens")?.value).toBe("1.5K ↑ · 1.0K ↓");
expect(metric(metrics, "Cache")).toEqual({ label: "Cache", value: "83%", tone: "ok" });
expect(metric(metrics, "Cost")?.value).toBe("$0.030");
});
test("a final step that called tools reports no response speed", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step(
"reply",
{ created: 0, firstToken: 100, streamed: 500, completed: 1_000 },
{
tokens: tokens(10, 100),
content: [tool("a", { created: 400, ran: 500, completed: 1_000 })],
},
),
]);
expect(metric(metrics, "Response")).toBeUndefined();
expect(metric(metrics, "Whole turn")?.value).toBe("~200 tok/s");
expect(metric(metrics, "Tool time")?.value).toBe("0.5s");
});
test("an error reply reports no response speed", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step(
"reply",
{ created: 0, firstToken: 100, streamed: 500, completed: 500 },
{ tokens: tokens(10, 100), error: { type: "api", message: "overloaded" } },
),
]);
expect(metric(metrics, "Response")).toBeUndefined();
});
test("one step with a bad timestamp hides turn timing instead of showing a partial total", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step("first", { created: 100, completed: 1_100 }, { tokens: tokens(10, 100) }),
// A tool that ends after its step ended is not a believable interval.
step(
"second",
{ created: 1_200, completed: 2_200 },
{
tokens: tokens(10, 100),
content: [tool("a", { created: 1_300, ran: 1_400, completed: 9_000 })],
},
),
]);
expect(metric(metrics, "Model time")).toBeUndefined();
expect(metric(metrics, "Tool time")).toBeUndefined();
expect(metric(metrics, "Whole turn")).toBeUndefined();
// Elapsed and token totals do not depend on the bad interval.
expect(metric(metrics, "Elapsed")?.value).toBe("2.2s");
expect(metric(metrics, "Tokens")?.value).toBe("20 ↑ · 200 ↓");
});
test("servers without first-token stamps report no TTFT or response speed", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step("reply", { created: 0, streamed: 900, completed: 1_000 }, { tokens: tokens(10, 100) }),
]);
expect(metric(metrics, "TTFT")).toBeUndefined();
expect(metric(metrics, "Response")).toBeUndefined();
expect(metric(metrics, "Whole turn")?.value).toBe("~100 tok/s");
});
test("an implausible rate is hidden", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step(
"reply",
{ created: 0, firstToken: 1, streamed: 2, completed: 2 },
{ tokens: tokens(10, 100_000) },
),
]);
expect(metric(metrics, "Response")).toBeUndefined();
expect(metric(metrics, "Whole turn")).toBeUndefined();
});
test("a turn still running reports nothing", () => {
expect(
latestTurnMetrics([
user("prompt", 0),
step("reply", { created: 0 }, { tokens: tokens(1, 1) }),
]),
).toEqual([]);
});
test("a turn without tokens or cost leaves those metrics out", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step("reply", { created: 0, completed: 1_000 }),
]);
expect(metrics.map((entry) => entry.label)).toEqual(["Model", "Elapsed", "Model time"]);
});
test("a steered prompt stays in the turn the idle marker closes", () => {
const metrics = latestTurnMetrics([
user("prompt", 0),
step("first", { created: 100, completed: 1_000 }, { tokens: tokens(10, 100) }),
user("steer", 500),
step("second", { created: 1_100, completed: 2_000 }, { tokens: tokens(10, 100) }),
idle("idle", 2_000),
]);
expect(metric(metrics, "Steps")?.value).toBe("2");
expect(metric(metrics, "Elapsed")?.value).toBe("2.0s");
});
});
describe("OpenCode v2 replayed turn metrics", () => {
test("keys each successful turn by the message its metrics follow", () => {
const replayed = replayedTurnMetrics([
user("first", 0),
step("first-reply", { created: 100, completed: 1_000 }, { tokens: tokens(10, 100) }),
idle("first-idle", 1_000),
user("second", 2_000),
step("second-reply", { created: 2_100, completed: 2_500 }, { tokens: tokens(10, 100) }),
idle("second-idle", 2_500, "failed"),
user("third", 3_000),
step("third-reply", { created: 3_100 }),
]);
expect([...replayed.keys()]).toEqual(["first-idle"]);
expect(metric(replayed.get("first-idle")!, "Elapsed")?.value).toBe("1.0s");
});
test("sessions without idle markers end a turn at the next prompt", () => {
const replayed = replayedTurnMetrics([
user("first", 0),
step("first-reply", { created: 100, completed: 1_000 }, { tokens: tokens(10, 100) }),
user("second", 2_000),
step("second-reply", { created: 2_100, completed: 2_500 }, { tokens: tokens(10, 100) }),
]);
expect([...replayed.keys()]).toEqual(["first-reply", "second-reply"]);
});
});
describe("OpenCode v2 session metrics", () => {
const info: Pick<SessionInfo, "tokens" | "cost"> = {
tokens: tokens(40_000, 3_000, { reasoning: 500, read: 90_000 }),
cost: 1.234,
};
test("reports cumulative session totals and the cache hit of the last reply", () => {
expect(
sessionMetrics(info, [
user("prompt", 0),
step("old", { created: 1, completed: 2 }, { tokens: tokens(1_000, 10, { read: 0 }) }),
step("last", { created: 3, completed: 4 }, { tokens: tokens(100, 10, { read: 900 }) }),
step("running", { created: 5 }),
]),
).toEqual([
{ label: "Tokens", value: "40.0K ↑ · 3.5K ↓" },
{ label: "Cache (last reply)", value: "90%", tone: "ok" },
{ label: "Cost", value: "$1.23" },
]);
});
test("a new session reports nothing", () => {
expect(sessionMetrics({ tokens: tokens(0, 0), cost: 0 }, [])).toEqual([]);
});
});
describe("OpenCode v2 metrics through the session", () => {
function answeredHarness() {
const harness = new V2Harness();
harness.info.tokens = tokens(2_000, 1_000, { read: 8_000 });
harness.info.cost = 0.5;
harness.prompt = async (input) => {
harness.prompts.push(input.text);
harness.history.push(
user("prompt", 1_000),
step(
"reply",
{ created: 1_000, firstToken: 1_500, streamed: 2_500, completed: 3_000 },
{ tokens: tokens(2_000, 1_000, { read: 8_000 }), cost: 0.5 },
),
idle("idle", 3_000),
);
};
return harness;
}
test("a completed turn carries its metrics and the session reports its totals", async () => {
const harness = answeredHarness();
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
try {
await session.run("answer");
const completed = events.find((event) => event.type === "turn_completed");
expect(completed).toMatchObject({
metrics: expect.arrayContaining([
{ label: "Model", value: "anthropic/claude-sonnet" },
{ label: "Elapsed", value: "2.0s" },
{ label: "Response", value: "~1000 tok/s" },
]),
});
const sessionUpdates = events.filter((event) => event.type === "session_metrics_updated");
expect(sessionUpdates.at(-1)).toMatchObject({
metrics: [
{ label: "Tokens", value: "2.0K ↑ · 1.0K ↓" },
{ label: "Cache (last reply)", value: "80%", tone: "ok" },
{ label: "Cost", value: "$0.500" },
],
});
// Reconciling unchanged state does not repeat the same session metrics.
expect(new Set(sessionUpdates.map((event) => JSON.stringify(event))).size).toBe(
sessionUpdates.length,
);
} finally {
await session.close();
}
});
test("history replays each turn's metrics after its rows, then the session metrics", async () => {
const harness = answeredHarness();
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
try {
await session.run("answer");
const history: AgentStreamEvent[] = [];
for await (const event of session.streamHistory!()) history.push(event);
expect(history.map((event) => event.type)).toEqual([
"timeline",
"timeline",
"turn_completed",
"session_metrics_updated",
]);
expect(history[2]).toMatchObject({
metrics: expect.arrayContaining([{ label: "Elapsed", value: "2.0s" }]),
});
expect(history[3]).toMatchObject({
metrics: expect.arrayContaining([{ label: "Cost", value: "$0.500" }]),
});
} finally {
await session.close();
}
});
test("history replays without session metrics when the session info is unavailable", async () => {
const harness = answeredHarness();
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
try {
await session.run("answer");
harness.sessionGetError = new Error("session lookup failed");
const history: AgentStreamEvent[] = [];
for await (const event of session.streamHistory!()) history.push(event);
expect(history.map((event) => event.type)).toEqual([
"timeline",
"timeline",
"turn_completed",
]);
} finally {
await session.close();
}
});
});
@@ -0,0 +1,262 @@
import type { SessionInfo, SessionMessageInfo, TokenUsageInfo } from "@opencode/client";
import type { AgentMetric } from "../../../agent-sdk-types.js";
import {
formatMetricDuration,
formatMetricRate,
mergeTimeIntervals,
type TimeInterval,
} from "../../metrics.js";
import { cacheMetric, costMetric, type MeasuredTokens, tokensMetric } from "../../turn-metrics.js";
type Step = Extract<SessionMessageInfo, { type: "assistant" }>;
/** Newer OpenCode servers stamp `firstToken`; steps recorded before it existed leave it unset. */
interface StepTime {
readonly created: number;
readonly firstToken?: number;
/** When the response body ended, before tools settled. */
readonly streamed?: number;
readonly completed?: number;
}
/**
* One prompt and the steps that answered it. Sessions with idle markers end a turn
* at the marker, so a prompt steered into a running turn stays part of it; older
* sessions end a turn at the next prompt.
*/
interface Turn {
input: SessionMessageInfo | undefined;
steps: Step[];
/** The message whose replayed rows the turn's metrics follow. */
lastMessageId: string | undefined;
outcome: "succeeded" | "failed" | "interrupted" | undefined;
}
interface StepStats {
/** Step wall time less the time its tools ran; null when any interval is unbelievable. */
modelMs: number | null;
toolMs: number | null;
ttftMs: number | null;
}
function isInput(message: SessionMessageInfo) {
return message.type === "user" || message.type === "synthetic";
}
function sessionTurns(messages: readonly SessionMessageInfo[]): Turn[] {
const legacy = !messages.some((message) => message.type === "idle");
const turns: Turn[] = [];
let current: Turn | null = null;
for (const message of messages) {
if (isInput(message) && (legacy || !current)) {
current = { input: message, steps: [], lastMessageId: undefined, outcome: undefined };
turns.push(current);
continue;
}
if (!current) continue;
if (message.type === "assistant") {
current.steps.push(message);
current.lastMessageId = message.id;
} else if (message.type === "idle") {
current.outcome = message.outcome;
current.lastMessageId = message.id;
current = null;
}
}
return turns;
}
function isCompleted(turn: Turn) {
return turn.steps.length > 0 && turn.steps.every((step) => step.time.completed !== undefined);
}
function stepTime(step: Step): StepTime {
return step.time;
}
function isWithin(value: number | undefined, start: number, end: number): value is number {
return value !== undefined && Number.isFinite(value) && value >= start && value <= end;
}
function totalDuration(intervals: readonly TimeInterval[]) {
return mergeTimeIntervals(intervals).reduce((sum, [start, end]) => sum + (end - start), 0);
}
function stepStats(step: Step): StepStats {
const { created, firstToken, completed } = stepTime(step);
if (
completed === undefined ||
!Number.isFinite(created) ||
!isWithin(completed, created, completed)
)
return { modelMs: null, toolMs: null, ttftMs: null };
const intervals: TimeInterval[] = [];
let toolsValid = true;
for (const part of step.content) {
if (part.type !== "tool") continue;
// A tool that failed while its input streamed never ran.
if (part.state.status === "error" && part.time.ran === undefined) continue;
const ran = part.time.ran;
const ended = part.time.completed;
if (
(part.state.status !== "completed" && part.state.status !== "error") ||
!isWithin(ran, created, completed) ||
!isWithin(ended, ran, completed)
) {
toolsValid = false;
continue;
}
intervals.push([ran, ended]);
}
const toolMs = toolsValid ? totalDuration(intervals) : null;
return {
toolMs,
modelMs: toolMs === null ? null : completed - created - toolMs,
ttftMs:
isWithin(firstToken, created, completed) && firstToken > created
? firstToken - created
: null,
};
}
/** Sums the values, or null when any is missing so a partial total is never shown. */
function sumAll(values: readonly (number | null | undefined)[]): number | null {
let total = 0;
for (const value of values) {
if (value === null || value === undefined || !Number.isFinite(value) || value < 0) return null;
total += value;
}
return total;
}
function generated(tokens: TokenUsageInfo) {
return tokens.output + tokens.reasoning;
}
function rate(tokens: number, ms: number) {
return ms > 0 ? formatMetricRate(tokens / (ms / 1000)) : null;
}
/** The final reply's speed while it streamed, which a step that ran tools does not have. */
function responseRate(step: Step): string | null {
if (step.error || !step.tokens || step.content.some((part) => part.type === "tool")) return null;
const { created, firstToken, streamed, completed } = stepTime(step);
if (completed === undefined || !isWithin(firstToken, created, completed)) return null;
if (!isWithin(streamed, firstToken, completed)) return null;
return rate(generated(step.tokens), streamed - firstToken);
}
function modelName(model: Step["model"]) {
const name = `${model.providerID}/${model.id}`;
return model.variant ? `${name} (${model.variant})` : name;
}
function durationMetric(label: string, ms: number | null): AgentMetric[] {
const value = ms === null ? null : formatMetricDuration(ms);
return value ? [{ label, value }] : [];
}
function measured(tokens: TokenUsageInfo): MeasuredTokens {
return {
input: tokens.input,
output: generated(tokens),
cacheRead: tokens.cache.read,
cacheWrite: tokens.cache.write,
};
}
function tokenMetrics(tokens: TokenUsageInfo, cacheLabel: string): AgentMetric[] {
return [...tokensMetric(measured(tokens)), ...cacheMetric(measured(tokens), cacheLabel)];
}
function turnTokens(steps: readonly Step[]): TokenUsageInfo | null {
const pick = (read: (tokens: TokenUsageInfo) => number) =>
sumAll(steps.map((step) => (step.tokens ? read(step.tokens) : null)));
const input = pick((tokens) => tokens.input);
const output = pick((tokens) => tokens.output);
const reasoning = pick((tokens) => tokens.reasoning);
const read = pick((tokens) => tokens.cache.read);
const write = pick((tokens) => tokens.cache.write);
if (input === null || output === null || reasoning === null || read === null || write === null)
return null;
return { input, output, reasoning, cache: { read, write } };
}
function turnMetrics(turn: Turn): AgentMetric[] {
const last = turn.steps.at(-1);
if (!last || !isCompleted(turn)) return [];
const stats = turn.steps.map(stepStats);
const modelMs = sumAll(stats.map((step) => step.modelMs));
const toolMs = sumAll(stats.map((step) => step.toolMs));
const ttfts = stats.map((step) => step.ttftMs);
const ttftTotal = sumAll(ttfts);
const tokens = turnTokens(turn.steps);
const ranTools = turn.steps.some((step) => step.content.some((part) => part.type === "tool"));
const inputCreated = turn.input?.time.created;
const lastCompleted = stepTime(last).completed;
const elapsedMs =
inputCreated !== undefined && lastCompleted !== undefined && lastCompleted >= inputCreated
? lastCompleted - inputCreated
: null;
const response = responseRate(last);
const wholeTurn = tokens && modelMs !== null ? rate(generated(tokens), modelMs) : null;
return [
{ label: "Model", value: modelName(last.model) },
...(response ? [{ label: "Response", value: response }] : []),
...(wholeTurn ? [{ label: "Whole turn", value: wholeTurn }] : []),
...durationMetric("Elapsed", elapsedMs),
...durationMetric("Model time", modelMs),
...(ranTools ? durationMetric("Tool time", toolMs) : []),
...durationMetric(
turn.steps.length === 1 ? "TTFT" : "Average TTFT",
ttftTotal === null ? null : ttftTotal / ttfts.length,
),
...(turn.steps.length > 1 ? [{ label: "Steps", value: String(turn.steps.length) }] : []),
...(tokens ? tokenMetrics(tokens, "Cache") : []),
...costMetric(sumAll(turn.steps.map((step) => step.cost))),
];
}
/** The metrics of the turn that just finished, read from the history after it settled. */
export function latestTurnMetrics(messages: readonly SessionMessageInfo[]): AgentMetric[] {
const turn = sessionTurns(messages).at(-1);
return turn ? turnMetrics(turn) : [];
}
/**
* Each successful turn's metrics, keyed by the message they follow when the
* history is replayed. Only successful turns: a live turn that failed or was
* interrupted reports none either.
*/
export function replayedTurnMetrics(
messages: readonly SessionMessageInfo[],
): Map<string, AgentMetric[]> {
const legacy = !messages.some((message) => message.type === "idle");
const replayed = new Map<string, AgentMetric[]>();
for (const turn of sessionTurns(messages)) {
if (!turn.lastMessageId || (!legacy && turn.outcome !== "succeeded")) continue;
const metrics = turnMetrics(turn);
if (metrics.length > 0) replayed.set(turn.lastMessageId, metrics);
}
return replayed;
}
/**
* Session totals come from OpenCode's own cumulative counters: the loaded history
* can be a compacted tail. The cache hit is the last reply's, since a session-wide
* figure blends prompts from before and after compactions.
*/
export function sessionMetrics(
info: Pick<SessionInfo, "tokens" | "cost">,
messages: readonly SessionMessageInfo[],
): AgentMetric[] {
const lastReply = messages.findLast(
(message): message is Step =>
message.type === "assistant" && message.time.completed !== undefined && !!message.tokens,
);
return [
...tokensMetric(measured(info.tokens)),
...(lastReply?.tokens ? cacheMetric(measured(lastReply.tokens), "Cache (last reply)") : []),
...costMetric(info.cost),
];
}
@@ -41,6 +41,8 @@ import { commands } from "./commands.js";
import { messages } from "./history.js";
import { SessionPermissions } from "./permissions.js";
import { SessionUsage } from "./usage.js";
import { createSessionMetricsReporter } from "../../metrics.js";
import { replayedTurnMetrics, sessionMetrics } from "./metrics.js";
export class OpenCodeV2Session implements AgentSession {
readonly provider = "opencode";
@@ -64,6 +66,10 @@ export class OpenCodeV2Session implements AgentSession {
private history: SessionMessageInfo[] = [];
private readonly background: OpenCodeBackgroundInventory;
private modes: AgentMode[] = [];
// Reconciliation runs after nearly every event; report only what changed.
private readonly reportSessionMetrics = createSessionMetricsReporter((metrics) =>
this.emit({ type: "session_metrics_updated", provider: "opencode", metrics }),
);
constructor(
private connection: V2Connection,
private info: SessionInfo,
@@ -304,9 +310,32 @@ export class OpenCodeV2Session implements AgentSession {
await this.reconnectIfExited();
const history = new V2Timeline(false);
const events: AgentStreamEvent[] = [];
await history.messages(await messages(this.client, this.id), (event) => {
events.push(event);
});
const [info, list] = await Promise.all([
// Session totals are extra; history replays without them.
this.client.session.get({ sessionID: this.id }).catch((error: unknown) => {
this.logger.debug({ err: error }, "OpenCode session info unavailable for history");
return null;
}),
messages(this.client, this.id),
]);
const turnMetrics = replayedTurnMetrics(list);
await history.messages(
list,
(event) => {
events.push(event);
},
(message) => {
const metrics = turnMetrics.get(message.id);
if (metrics) events.push({ type: "turn_completed", provider: "opencode", metrics });
},
);
if (info) {
events.push({
type: "session_metrics_updated",
provider: "opencode",
metrics: sessionMetrics(info, list),
});
}
yield* events;
}
async getRuntimeInfo() {
@@ -488,6 +517,7 @@ export class OpenCodeV2Session implements AgentSession {
this.info = info;
this.history = history;
await this.timeline.messages(history, (event) => this.emitTimeline(event));
this.reportSessionMetrics(sessionMetrics(this.info, this.history));
await this.permissions.reconcile(this.id);
}
private async reconcile() {
@@ -59,11 +59,16 @@ export class V2Timeline {
// Publish each cursor advance in the same synchronous step. Buffering snapshot
// events until image IO finishes lets live deltas overtake already committed text.
// `published` runs once a message's items are out, so a caller can place its own
// events between messages.
messages(
messages: SessionMessageInfo[],
publish: (event: AgentStreamEvent) => void,
published?: (message: SessionMessageInfo) => void,
): Promise<void> {
const result = this.pendingMessages.then(() => this.publishMessages(messages, publish));
const result = this.pendingMessages.then(() =>
this.publishMessages(messages, publish, published),
);
this.pendingMessages = result.catch(() => {});
return result;
}
@@ -71,6 +76,7 @@ export class V2Timeline {
private async publishMessages(
messages: SessionMessageInfo[],
publish: (event: AgentStreamEvent) => void,
published?: (message: SessionMessageInfo) => void,
): Promise<void> {
const state: TimelineState = { structured: false, accepted: false };
for (const message of messages) {
@@ -80,6 +86,7 @@ export class V2Timeline {
if (message.type === "user") this.userMessage(message, state, push);
else if (message.type === "assistant") await this.assistantMessage(message, state, push);
else if (message.type === "compaction") this.compactionMessage(message, push);
published?.(message);
}
}
@@ -16,6 +16,7 @@ import { toDiagnosticErrorMessage } from "../../diagnostic-utils.js";
import { renderPromptAttachmentAsText } from "../../../prompt-attachments.js";
import { usageFromV2 } from "./mapping.js";
import { latestTurnMetrics } from "./metrics.js";
import { commands } from "./commands.js";
@@ -304,6 +305,7 @@ export class SessionTurns {
provider: "opencode",
turnId: turn.id,
usage: usageFromV2(info),
metrics: latestTurnMetrics(history),
});
}
private async readExecution(): Promise<ExecutionEvent | null> {
@@ -104,6 +104,9 @@ import type {
PiThinkingLevel,
} from "./rpc-types.js";
import { PiUsagePoller, type PiUsagePollScheduler } from "./usage-poller.js";
import { PiFirstTokenTimer, piReplyStep, piSessionMetrics } from "./metrics.js";
import { type MeasuredStep, measuredTurnMetrics, TurnMeter } from "../turn-metrics.js";
import { createSessionMetricsReporter } from "../metrics.js";
import {
mapToolDetail,
parseToolArgs,
@@ -1208,6 +1211,12 @@ export class PiRpcAgentSession implements AgentSession {
private readonly currentModeId: string | null;
private readonly logger: Logger;
private readonly usagePoller: PiUsagePoller;
private readonly turnMeter = new TurnMeter();
private readonly firstToken = new PiFirstTokenTimer();
private lastReply: MeasuredStep | null = null;
private readonly reportSessionMetrics = createSessionMetricsReporter((metrics) =>
this.emit({ type: "session_metrics_updated", provider: this.provider, metrics }),
);
private closed = false;
private runtimeDead = false;
private readonly closeController = new AbortController();
@@ -1250,13 +1259,14 @@ export class PiRpcAgentSession implements AgentSession {
this.usagePoller = new PiUsagePoller({
scheduler: options.usagePollScheduler,
readStats: () => this.runtimeSession.getSessionStats(),
onUsage: (usage, turnId) => {
onUsage: (usage, turnId, stats) => {
this.emit({
type: "usage_updated",
provider: this.provider,
usage,
...(turnId === undefined ? {} : { turnId }),
});
this.reportSessionMetrics(piSessionMetrics(stats, this.lastReply));
},
onPollError: (error) => {
this.logger.debug({ err: error }, "Pi context usage poll failed");
@@ -1301,6 +1311,7 @@ export class PiRpcAgentSession implements AgentSession {
const turnId = randomUUID();
this.activeTurnId = turnId;
this.turnMeter.begin(Date.now());
this.usagePoller.startTurn();
this.activeClientMessageId = options?.clientMessageId ?? null;
this.activeAssistantMessageId = null;
@@ -1447,7 +1458,7 @@ export class PiRpcAgentSession implements AgentSession {
try {
await this.requestEntryCapture("history");
const history = await this.runtimeSession.getHistory();
yield* streamPiHistory(
const replay = yield* streamPiHistory(
this.provider,
history.messages,
history.userEntries,
@@ -1456,6 +1467,18 @@ export class PiRpcAgentSession implements AgentSession {
createPiExtensionHost(this.logger, undefined, 16 * 1024 * 1024),
this.closeController.signal,
);
this.lastReply ??= replay.lastReply;
const stats = await this.runtimeSession.getSessionStats().catch((error: unknown) => {
this.logger.debug({ err: error }, "Pi session stats unavailable for history");
return null;
});
if (stats && !this.closeController.signal.aborted) {
yield {
type: "session_metrics_updated",
provider: this.provider,
metrics: piSessionMetrics(stats, this.lastReply),
};
}
} finally {
if (this.closeAfterHistory) await this.close();
}
@@ -2252,6 +2275,7 @@ export class PiRpcAgentSession implements AgentSession {
this.handleMessageUpdate(event, turnId);
return;
case "tool_execution_start": {
this.turnMeter.toolStarted(event.toolCallId, Date.now());
const toolCall = parseToolArgs(event.toolName, event.args);
this.activeToolCalls.set(event.toolCallId, toolCall);
const request = this.extensionHost.onToolStart(
@@ -2287,6 +2311,7 @@ export class PiRpcAgentSession implements AgentSession {
return;
}
case "tool_execution_end": {
this.turnMeter.toolEnded(event.toolCallId, Date.now());
this.handleToolExecutionEnd(event);
return;
}
@@ -2434,6 +2459,7 @@ export class PiRpcAgentSession implements AgentSession {
if (event.message && event.message.role !== "assistant") {
return;
}
this.firstToken.replyUpdated(event.assistantMessageEvent, Date.now());
if (event.assistantMessageEvent.type === "text_delta") {
// Pi-compatible runtimes may emit updates without a preceding message_start.
this.activeAssistantMessageId ??= event.message?.responseId || randomUUID();
@@ -2465,6 +2491,7 @@ export class PiRpcAgentSession implements AgentSession {
private handleMessageStart(event: Extract<PiAgentSessionEvent, { type: "message_start" }>): void {
if (event.message.role === "assistant") {
this.activeAssistantMessageId = event.message.responseId || null;
this.firstToken.replyStarted(Date.now());
}
}
@@ -2474,6 +2501,11 @@ export class PiRpcAgentSession implements AgentSession {
): void {
if (event.message.role === "assistant") {
this.activeAssistantMessageId = null;
const step = piReplyStep(event.message, this.firstToken.replyEnded());
if (step) {
this.turnMeter.step(step, Date.now());
this.lastReply = step;
}
return;
}
if (event.message.role === "custom") {
@@ -2555,6 +2587,8 @@ export class PiRpcAgentSession implements AgentSession {
this.pendingSettledMessages = null;
this.pendingSteerSubmissions.length = 0;
this.clearNoTurnBuffers();
const measured = this.turnMeter.finish(Date.now());
this.turnMeter.reset();
if (typeof errorMessage === "string" && errorMessage.length > 0) {
this.usagePoller.stopTurn();
this.emit({
@@ -2570,6 +2604,7 @@ export class PiRpcAgentSession implements AgentSession {
type: "turn_completed",
provider: this.provider,
turnId,
metrics: measuredTurnMetrics(measured),
});
void this.refreshAfterTurn(finalUsage);
}
@@ -1,5 +1,12 @@
import { mapCustomMessageToToolCall } from "../custom-message.js";
import type { AgentStreamEvent, AgentTimelineItem, ToolCallDetail } from "../../agent-sdk-types.js";
import type {
AgentMetric,
AgentStreamEvent,
AgentTimelineItem,
ToolCallDetail,
} from "../../agent-sdk-types.js";
import type { MeasuredStep } from "../turn-metrics.js";
import { piReplayedTurns } from "./metrics.js";
import {
materializeProviderImage,
renderProviderImageOutputAsAssistantMarkdown,
@@ -312,19 +319,36 @@ export async function* streamPiHistory(
// At most eight 2 MiB child files per replay; remaining cards keep their summaries.
extensionHost: PiExtensionHost = createPiExtensionHost(undefined, undefined, 16 * 1024 * 1024),
signal?: AbortSignal,
): AsyncGenerator<AgentStreamEvent> {
): AsyncGenerator<AgentStreamEvent, PiHistoryReplay> {
const mapper = new PiHistoryMapper(provider, userEntries, hooks, extensionHost);
const turns = piReplayedTurns();
const replay: PiHistoryReplay = { lastReply: null };
// Each finished turn's metrics follow its rows, as they do live.
const turnCompleted = (metrics: AgentMetric[]): AgentStreamEvent[] =>
metrics.length ? [{ type: "turn_completed", provider, metrics }] : [];
for (const message of messages) {
if (signal?.aborted) return;
for (const event of await mapper.mapMessages([message])) {
if (signal?.aborted) return;
if (signal?.aborted) return replay;
const events = [
...turnCompleted(turns.observe(message)),
...(await mapper.mapMessages([message])),
];
for (const event of events) {
if (signal?.aborted) return replay;
yield event;
}
}
yield* turnCompleted(turns.end());
replay.lastReply = turns.lastReply;
for (const event of await mapper.hydrate()) {
if (signal?.aborted) return;
if (signal?.aborted) return replay;
yield event;
}
return replay;
}
export interface PiHistoryReplay {
/** The most recent reply replayed, for the session's metrics. */
lastReply: MeasuredStep | null;
}
function toToolResultTimelineItem(input: {
@@ -0,0 +1,353 @@
import { tmpdir } from "node:os";
import pino from "pino";
import { afterEach, describe, expect, onTestFinished, test, vi } from "vitest";
import type { AgentMetric, AgentStreamEvent } from "../../agent-sdk-types.js";
import { PiRpcAgentClient } from "./agent.js";
import { PiFirstTokenTimer, piReplyStep, piSessionMetrics } from "./metrics.js";
import type { PiAgentMessage } from "./rpc-types.js";
import { FakePi } from "./test-utils/fake-pi.js";
// The fields Pi records on an assistant message, which Paseo's message type leaves out.
function reply(fields: Record<string, unknown> = {}): PiAgentMessage {
return {
role: "assistant",
content: [{ type: "text", text: "done" }],
provider: "anthropic",
model: "claude-sonnet",
stopReason: "stop",
usage: {
input: 1_000,
// Reasoning is part of output.
output: 600,
reasoning: 200,
cacheRead: 3_000,
cacheWrite: 0,
cost: { total: 0.012 },
},
timestamp: 10_000,
durationMs: 3_000,
...fields,
} as PiAgentMessage;
}
function user(text: string, timestamp: number): PiAgentMessage {
return { role: "user", content: text, timestamp } as PiAgentMessage;
}
function toolResult(id: string, fields: Record<string, unknown>): PiAgentMessage {
return {
role: "toolResult",
toolCallId: id,
toolName: "bash",
content: [{ type: "text", text: "ok" }],
isError: false,
...fields,
} as PiAgentMessage;
}
function value(metrics: AgentMetric[] | undefined, label: string) {
return metrics?.find((metric) => metric.label === label)?.value;
}
function createClient(pi: FakePi) {
return new PiRpcAgentClient({ logger: pino({ level: "silent" }), runtime: pi });
}
type StreamEvent<T extends AgentStreamEvent["type"]> = Extract<AgentStreamEvent, { type: T }>;
function firstEvent<T extends AgentStreamEvent["type"]>(events: AgentStreamEvent[], type: T) {
return events.find((event): event is StreamEvent<T> => event.type === type);
}
function lastEvent<T extends AgentStreamEvent["type"]>(events: AgentStreamEvent[], type: T) {
return events.findLast((event): event is StreamEvent<T> => event.type === type);
}
describe("Pi reply steps", () => {
test("names the served model and thinking level, and ends when the response did", () => {
expect(
piReplyStep(reply({ responseModel: "claude-sonnet-4-6", thinkingLevel: "high" }), 400),
).toEqual({
model: "claude-sonnet-4-6 (high)",
tokens: { input: 1_000, output: 600, cacheRead: 3_000, cacheWrite: 0 },
costUsd: 0.012,
durationMs: 3_000,
ttftMs: 400,
endedAt: 13_000,
});
});
test("a malformed field costs only that field", () => {
expect(
piReplyStep(reply({ thinkingLevel: "off", usage: { input: -1 }, durationMs: "slow" })),
).toEqual({
model: "claude-sonnet",
tokens: null,
costUsd: null,
durationMs: null,
ttftMs: null,
endedAt: null,
});
});
test("other messages are not steps", () => {
expect(piReplyStep(user("hi", 1))).toBeNull();
});
});
describe("Pi first token timer", () => {
test("times the first content of each reply", () => {
const timer = new PiFirstTokenTimer();
timer.replyStarted(1_000);
timer.replyUpdated({ type: "start" }, 1_100);
// An empty delta is not a token.
timer.replyUpdated({ type: "text_delta", delta: "" }, 1_200);
timer.replyUpdated({ type: "toolcall_start" }, 1_300);
timer.replyUpdated({ type: "text_delta", delta: "late" }, 1_400);
expect(timer.replyEnded()).toBe(300);
timer.replyStarted(2_000);
timer.replyUpdated({ type: "thinking_delta", delta: "hmm" }, 2_050);
expect(timer.replyEnded()).toBe(50);
// A reply whose start was not seen, or that never produced content, is not timed.
timer.replyUpdated({ type: "text_start" }, 3_000);
expect(timer.replyEnded()).toBeNull();
timer.replyStarted(4_000);
expect(timer.replyEnded()).toBeNull();
});
});
describe("Pi session metrics", () => {
test("reports Pi's cumulative totals, the last reply's cache hit and tool calls", () => {
expect(
piSessionMetrics(
{
tokens: { input: 50_000, output: 4_000, cacheRead: 200_000, cacheWrite: 0 },
cost: 2.5,
toolCalls: 12,
},
piReplyStep(reply()),
),
).toEqual([
{ label: "Tokens", value: "50.0K ↑ · 4.0K ↓" },
{ label: "Cache (last reply)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$2.50" },
{ label: "Tool calls", value: "12" },
]);
});
test("a new session reports nothing", () => {
expect(piSessionMetrics({ toolCalls: 0 }, null)).toEqual([]);
});
});
describe("Pi metrics through the session", () => {
afterEach(() => {
vi.useRealTimers();
});
test("a completed turn carries its metrics and the session reports its totals", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: 100_000 });
const pi = new FakePi();
const session = await createClient(pi).createSession({ provider: "pi", cwd: tmpdir() });
onTestFinished(() => session.close());
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
const runtime = pi.latestSession();
await session.startTurn("fix the build");
runtime.emit({ type: "agent_start" });
runtime.emit({ type: "turn_start" });
// The first reply calls two tools that run in parallel.
vi.setSystemTime(100_500);
runtime.emit({ type: "message_start", message: reply({ content: [] }) });
vi.setSystemTime(100_800);
runtime.emit({
type: "message_update",
assistantMessageEvent: { type: "toolcall_start" },
});
vi.setSystemTime(101_500);
runtime.emit({
type: "message_end",
message: reply({ stopReason: "toolUse", durationMs: 1_000 }),
});
runtime.emit({ type: "tool_execution_start", toolCallId: "a", toolName: "bash", args: {} });
vi.setSystemTime(102_000);
runtime.emit({ type: "tool_execution_start", toolCallId: "b", toolName: "bash", args: {} });
vi.setSystemTime(103_000);
runtime.emit({ type: "tool_execution_end", toolCallId: "a", toolName: "bash", result: {} });
vi.setSystemTime(104_000);
runtime.emit({ type: "tool_execution_end", toolCallId: "b", toolName: "bash", result: {} });
// The final reply.
runtime.emit({ type: "message_start", message: reply({ content: [] }) });
vi.setSystemTime(104_100);
runtime.emit({
type: "message_update",
assistantMessageEvent: { type: "text_delta", delta: "d" },
});
vi.setSystemTime(107_000);
const answer = reply({ responseModel: "claude-sonnet-4-6", thinkingLevel: "high" });
runtime.emit({ type: "message_end", message: answer });
runtime.stats = {
tokens: { input: 2_000, output: 1_200, cacheRead: 6_000, cacheWrite: 0 },
cost: 0.024,
toolCalls: 2,
};
runtime.finishTurn(answer);
await expect.poll(() => firstEvent(events, "turn_completed") !== undefined).toBe(true);
const completed = firstEvent(events, "turn_completed");
expect(completed?.metrics).toEqual([
{ label: "Model", value: "claude-sonnet-4-6 (high)" },
// 1,200 output tokens over 4s of requests.
{ label: "Speed", value: "~300 tok/s" },
{ label: "Elapsed", value: "7.0s" },
{ label: "Model time", value: "4.0s" },
// Tools ran from 101.5s to 104s.
{ label: "Tool time", value: "2.5s" },
{ label: "Average TTFT", value: "0.2s" },
{ label: "Steps", value: "2" },
{ label: "Tokens", value: "2.0K ↑ · 1.2K ↓" },
{ label: "Cache", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.024" },
]);
await expect
.poll(() => lastEvent(events, "session_metrics_updated"))
.toMatchObject({
metrics: [
{ label: "Tokens", value: "2.0K ↑ · 1.2K ↓" },
{ label: "Cache (last reply)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.024" },
{ label: "Tool calls", value: "2" },
],
});
});
test("a failed turn reports no metrics and leaves none to the next turn", async () => {
const pi = new FakePi();
const session = await createClient(pi).createSession({ provider: "pi", cwd: tmpdir() });
onTestFinished(() => session.close());
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
const runtime = pi.latestSession();
await session.startTurn("first");
const failed = reply({ stopReason: "error", errorMessage: "overloaded" });
runtime.emit({ type: "message_end", message: failed });
runtime.finishTurn(failed);
await expect.poll(() => firstEvent(events, "turn_failed") !== undefined).toBe(true);
await session.startTurn("second");
const answer = reply();
runtime.emit({ type: "message_end", message: answer });
runtime.finishTurn(answer);
await expect.poll(() => firstEvent(events, "turn_completed") !== undefined).toBe(true);
const completed = firstEvent(events, "turn_completed");
const metrics = completed?.metrics;
expect(value(metrics, "Steps")).toBeUndefined();
expect(value(metrics, "Tokens")).toBe("1.0K ↑ · 600 ↓");
});
});
describe("Pi history metrics", () => {
test("replays each finished turn's metrics after its rows", async () => {
const pi = new FakePi();
pi.queueSessionSetup((runtime) => {
runtime.messages = [
user("first", 9_000),
reply({
stopReason: "toolUse",
durationMs: 1_000,
content: [
{ type: "toolCall", id: "a", name: "bash", arguments: {} },
{ type: "toolCall", id: "b", name: "bash", arguments: {} },
],
}),
// Parallel runs, 11s–13s and 12s–14s: 3s of tool time.
toolResult("a", { timestamp: 13_000, durationMs: 2_000 }),
toolResult("b", { timestamp: 14_000, durationMs: 2_000 }),
reply({ timestamp: 14_500, durationMs: 1_500 }),
user("second", 20_000),
reply({ stopReason: "aborted", errorMessage: "Request was aborted" }),
];
runtime.stats = {
tokens: { input: 3_000, output: 1_800, cacheRead: 9_000, cacheWrite: 0 },
cost: 0.036,
toolCalls: 2,
};
});
const session = await createClient(pi).resumeSession(
{
provider: "pi",
sessionId: "pi-session-1",
nativeHandle: "/tmp/native-pi-session",
metadata: { cwd: tmpdir() },
},
{},
undefined,
{ purpose: "history" },
);
onTestFinished(() => session.close());
const events: AgentStreamEvent[] = [];
for await (const event of session.streamHistory()) events.push(event);
const sequence = events.map((event) =>
event.type === "timeline" ? event.item.type : event.type,
);
const completedAt = sequence.indexOf("turn_completed");
expect(sequence.slice(completedAt - 1, completedAt + 2)).toEqual([
"assistant_message",
"turn_completed",
"user_message",
]);
expect(sequence.filter((type) => type === "turn_completed")).toHaveLength(1);
const completed = firstEvent(events, "turn_completed");
const metrics = completed?.metrics;
expect(value(metrics, "Elapsed")).toBe("7.0s");
expect(value(metrics, "Model time")).toBe("2.5s");
expect(value(metrics, "Tool time")).toBe("3.0s");
// Pi does not record time to first token.
expect(value(metrics, "Average TTFT")).toBeUndefined();
expect(events.at(-1)).toMatchObject({
type: "session_metrics_updated",
metrics: [
{ label: "Tokens", value: "3.0K ↑ · 1.8K ↓" },
{ label: "Cache (last reply)", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.036" },
{ label: "Tool calls", value: "2" },
],
});
});
test("a tool result without a recorded duration hides the turn's tool time", async () => {
const pi = new FakePi();
pi.queueSessionSetup((runtime) => {
runtime.messages = [
user("first", 9_000),
reply({ stopReason: "toolUse" }),
toolResult("a", { timestamp: 13_000 }),
reply({ timestamp: 14_000 }),
];
});
const session = await createClient(pi).resumeSession(
{
provider: "pi",
sessionId: "pi-session-1",
nativeHandle: "/tmp/native-pi-session",
metadata: { cwd: tmpdir() },
},
{},
undefined,
{ purpose: "history" },
);
onTestFinished(() => session.close());
const events: AgentStreamEvent[] = [];
for await (const event of session.streamHistory()) events.push(event);
const completed = firstEvent(events, "turn_completed");
const metrics = completed?.metrics;
expect(value(metrics, "Steps")).toBe("2");
expect(value(metrics, "Tool time")).toBeUndefined();
});
});
@@ -0,0 +1,152 @@
import { z } from "zod";
import type { AgentMetric } from "../../agent-sdk-types.js";
import {
type MeasuredStep,
ReplayedTurns,
sessionTotalsMetrics,
type TurnMessageReader,
} from "../turn-metrics.js";
import type { PiAgentMessage, PiSessionStats } from "./rpc-types.js";
// Fields Pi records on a message that only metrics read. Each one falls back on its
// own: a value of an unexpected shape should cost that metric, not the message.
const count = z.number().nonnegative().optional().catch(undefined);
const label = z.string().min(1).optional().catch(undefined);
const PiUsageSchema = z.object({
input: z.number().nonnegative(),
/** Reasoning included: Pi reports reasoning as a part of output. */
output: z.number().nonnegative(),
cacheRead: z.number().nonnegative(),
cacheWrite: z.number().nonnegative(),
cost: z.object({ total: z.number().nonnegative() }).optional().catch(undefined),
});
const PiReplyMetricsSchema = z.object({
model: label,
/** The model the provider reports it served. */
responseModel: label,
thinkingLevel: label,
usage: PiUsageSchema.optional().catch(undefined),
/** When the request was sent. */
timestamp: count,
/** From `timestamp` to the end of the response. */
durationMs: count,
stopReason: label,
errorMessage: z.string().nullable().optional().catch(undefined),
});
const PiTimedMessageSchema = z.object({ timestamp: count, durationMs: count });
const UNFINISHED_STOP_REASONS = new Set(["toolUse", "error", "aborted"]);
function modelName(reply: z.infer<typeof PiReplyMetricsSchema>): string | null {
const model = reply.responseModel ?? reply.model;
if (!model) return null;
const level = reply.thinkingLevel;
return level && level !== "off" ? `${model} (${level})` : model;
}
/** A reply as a step. Pi does not record time to first token; live turns time it. */
export function piReplyStep(
message: PiAgentMessage,
ttftMs: number | null = null,
): MeasuredStep | null {
if (message.role !== "assistant") return null;
const reply = PiReplyMetricsSchema.parse(message);
const usage = reply.usage;
return {
model: modelName(reply),
tokens: usage
? {
input: usage.input,
output: usage.output,
cacheRead: usage.cacheRead,
cacheWrite: usage.cacheWrite,
}
: null,
costUsd: usage?.cost?.total ?? null,
durationMs: reply.durationMs ?? null,
ttftMs,
endedAt:
reply.timestamp !== undefined && reply.durationMs !== undefined
? reply.timestamp + reply.durationMs
: null,
};
}
function isFinalReply(message: PiAgentMessage): boolean {
if (message.role !== "assistant" || message.errorMessage) return false;
return !UNFINISHED_STOP_REASONS.has(message.stopReason ?? "");
}
const reader: TurnMessageReader<PiAgentMessage> = {
prompt: (message) =>
message.role === "user"
? { startedAt: PiTimedMessageSchema.parse(message).timestamp ?? null }
: null,
reply: (message) => {
const step = piReplyStep(message);
return step ? { step, final: isFinalReply(message) } : null;
},
// A tool result is stamped when the tool finished.
toolRun: (message) => {
if (message.role !== "toolResult") return undefined;
const { timestamp, durationMs } = PiTimedMessageSchema.parse(message);
if (timestamp === undefined || durationMs === undefined || durationMs > timestamp) return null;
return [timestamp - durationMs, timestamp];
},
};
export function piReplayedTurns(): ReplayedTurns<PiAgentMessage> {
return new ReplayedTurns(reader);
}
export function piSessionMetrics(
stats: PiSessionStats,
lastReply: MeasuredStep | null,
): AgentMetric[] {
const metrics = sessionTotalsMetrics(
{
input: stats.tokens?.input ?? 0,
output: stats.tokens?.output ?? 0,
costUsd: stats.cost ?? null,
},
lastReply,
);
if (stats.toolCalls) metrics.push({ label: "Tool calls", value: String(stats.toolCalls) });
return metrics;
}
const CONTENT_START_EVENTS = new Set(["text_start", "thinking_start", "toolcall_start"]);
/**
* Times a live reply's first token: from the reply's start to its first content,
* on the adapter's clock.
*/
export class PiFirstTokenTimer {
private startedAt: number | null = null;
private firstTokenAt: number | null = null;
replyStarted(now: number): void {
this.startedAt = now;
this.firstTokenAt = null;
}
replyUpdated(event: { type: string; delta?: unknown }, now: number): void {
if (this.startedAt === null || this.firstTokenAt !== null) return;
const delta = typeof event.delta === "string" && event.delta.length > 0;
if (CONTENT_START_EVENTS.has(event.type) || delta) this.firstTokenAt = now;
}
/** The reply's time to first token, once it ended; null when unseen. */
replyEnded(): number | null {
const ttft =
this.startedAt !== null && this.firstTokenAt !== null
? this.firstTokenAt - this.startedAt
: null;
this.startedAt = null;
this.firstTokenAt = null;
return ttft;
}
}
@@ -115,6 +115,7 @@ export interface PiSessionStats {
total?: number;
};
cost?: number;
toolCalls?: number;
contextUsage?: {
tokens?: number | null;
contextWindow?: number | null;
@@ -157,7 +158,18 @@ export interface PiRpcResponse {
export type PiAssistantMessageEvent =
| { type: "text_delta"; delta?: string }
| { type: "thinking_delta"; delta?: string }
| { type: "start" | "text_start" | "text_end" | "thinking_start" | "thinking_end" | "done" };
| { type: "toolcall_delta"; delta?: string }
| {
type:
| "start"
| "text_start"
| "text_end"
| "thinking_start"
| "thinking_end"
| "toolcall_start"
| "toolcall_end"
| "done";
};
export type PiAgentSessionEvent =
| { type: "thinking_level_changed"; level: PiThinkingLevel }
@@ -7,7 +7,8 @@ export interface PiUsagePollScheduler {
interface PiUsagePollerOptions {
readStats(): Promise<PiSessionStats>;
onUsage(usage: AgentUsage, turnId?: string): void;
/** Called when usage changes, with the stats it was read from. */
onUsage(usage: AgentUsage, turnId: string | undefined, stats: PiSessionStats): void;
onPollError(error: unknown): void;
scheduler?: PiUsagePollScheduler;
}
@@ -93,16 +94,16 @@ export class PiUsagePoller {
}
this.active = false;
const completionGeneration = this.invalidatePendingWork();
let usage: AgentUsage | undefined;
let stats: PiSessionStats;
try {
usage = toAgentUsage(await this.options.readStats());
stats = await this.options.readStats();
} catch {
return;
}
if (this.closed || this.generation !== completionGeneration) {
return;
}
this.publishUsage(usage, turnId);
this.publishUsage(stats, turnId);
}
close(): void {
@@ -126,9 +127,9 @@ export class PiUsagePoller {
}
private async poll(generation: number): Promise<void> {
let usage: AgentUsage | undefined;
let stats: PiSessionStats;
try {
usage = toAgentUsage(await this.options.readStats());
stats = await this.options.readStats();
} catch (error) {
try {
if (this.active && !this.closed && this.generation === generation) {
@@ -143,7 +144,7 @@ export class PiUsagePoller {
}
try {
if (this.active && !this.closed && this.generation === generation) {
this.publishUsage(usage);
this.publishUsage(stats);
}
} finally {
if (this.active && !this.closed && this.generation === generation) {
@@ -160,10 +161,10 @@ export class PiUsagePoller {
return usage;
}
private publishUsage(usage: AgentUsage | undefined, turnId?: string): void {
const changedUsage = this.takeChangedUsage(usage);
private publishUsage(stats: PiSessionStats, turnId?: string): void {
const changedUsage = this.takeChangedUsage(toAgentUsage(stats));
if (changedUsage) {
this.options.onUsage(changedUsage, turnId);
this.options.onUsage(changedUsage, turnId, stats);
}
}
}
@@ -0,0 +1,227 @@
import { describe, expect, test } from "vitest";
import { createSessionMetricsReporter } from "./metrics.js";
import {
type MeasuredStep,
measuredTurnMetrics,
ReplayedTurns,
type TurnMessageReader,
TurnMeter,
} from "./turn-metrics.js";
function step(overrides: Partial<MeasuredStep> = {}): MeasuredStep {
return {
model: "claude-sonnet",
tokens: { input: 1_000, output: 500, cacheRead: 3_000, cacheWrite: 0 },
costUsd: 0.01,
durationMs: 2_000,
ttftMs: 400,
endedAt: null,
...overrides,
};
}
describe("measured turn metrics", () => {
test("a single step reports model, speed, timing, tokens, cache and cost", () => {
expect(
measuredTurnMetrics({ steps: [step()], startedAt: 1_000, endedAt: 3_500, toolMs: null }),
).toEqual([
{ label: "Model", value: "claude-sonnet" },
{ label: "Speed", value: "~250 tok/s" },
{ label: "Elapsed", value: "2.5s" },
{ label: "Model time", value: "2.0s" },
{ label: "TTFT", value: "0.4s" },
{ label: "Tokens", value: "1.0K ↑ · 500 ↓" },
{ label: "Cache", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.010" },
]);
});
test("several steps sum, average TTFT, count steps and name the last model", () => {
const metrics = measuredTurnMetrics({
steps: [
step({ model: "first", ttftMs: 200 }),
step({ model: "second", durationMs: 3_000, ttftMs: 600, costUsd: 0.02 }),
],
startedAt: 0,
endedAt: 9_000,
toolMs: 3_500,
});
expect(metrics).toEqual([
{ label: "Model", value: "second" },
// 1,000 output tokens over 5s of requests.
{ label: "Speed", value: "~200 tok/s" },
{ label: "Elapsed", value: "9.0s" },
{ label: "Model time", value: "5.0s" },
{ label: "Tool time", value: "3.5s" },
{ label: "Average TTFT", value: "0.4s" },
{ label: "Steps", value: "2" },
{ label: "Tokens", value: "2.0K ↑ · 1.0K ↓" },
{ label: "Cache", value: "75%", tone: "ok" },
{ label: "Cost", value: "$0.030" },
]);
});
test("a step missing a value hides the totals that need it", () => {
const metrics = measuredTurnMetrics({
steps: [step(), step({ durationMs: null, ttftMs: null, costUsd: null, tokens: null })],
startedAt: null,
endedAt: 5_000,
toolMs: null,
});
expect(metrics).toEqual([
{ label: "Model", value: "claude-sonnet" },
{ label: "Steps", value: "2" },
]);
});
test("requests shorter than 100ms report no speed", () => {
const metrics = measuredTurnMetrics({
steps: [
step({ durationMs: 99, tokens: { input: 1, output: 10, cacheRead: 0, cacheWrite: 0 } }),
],
startedAt: null,
endedAt: null,
toolMs: null,
});
expect(metrics.find((metric) => metric.label === "Speed")).toBeUndefined();
});
test("a turn without steps reports nothing", () => {
expect(measuredTurnMetrics({ steps: [], startedAt: 0, endedAt: 1, toolMs: 0 })).toEqual([]);
});
});
describe("turn meter", () => {
test("counts parallel tool runs once", () => {
const meter = new TurnMeter();
meter.begin(1_000);
meter.toolStarted("a", 2_000);
meter.toolStarted("b", 2_500);
meter.toolEnded("a", 4_000);
meter.toolEnded("b", 3_000);
// A tool whose start was never seen adds nothing.
meter.toolEnded("unknown", 4_500);
meter.step(step({ endedAt: 6_000 }), 6_000);
expect(meter.finish(7_000)).toEqual({
steps: [step({ endedAt: 6_000 })],
startedAt: 1_000,
endedAt: 7_000,
toolMs: 2_000,
});
});
test("a turn begun again starts empty, and one it never saw begin starts at its first event", () => {
const meter = new TurnMeter();
meter.begin(0);
meter.step(step(), 5);
meter.begin(10);
expect(meter.finish(20)).toEqual({ steps: [], startedAt: 10, endedAt: 20, toolMs: null });
meter.reset();
meter.toolStarted("a", 30);
meter.toolEnded("a", 40);
meter.step(step(), 45);
expect(meter.finish(50)).toMatchObject({ startedAt: 30, endedAt: 50, toolMs: 10 });
});
});
type Message =
| { role: "user"; at: number }
| { role: "assistant"; step: MeasuredStep; final: boolean }
| { role: "tool"; run: [number, number] | null }
| { role: "note" };
const reader: TurnMessageReader<Message> = {
prompt: (message) => (message.role === "user" ? { startedAt: message.at } : null),
reply: (message) =>
message.role === "assistant" ? { step: message.step, final: message.final } : null,
toolRun: (message) => (message.role === "tool" ? message.run : undefined),
};
function replay(messages: Message[]) {
const turns = new ReplayedTurns(reader);
const out: Array<{ before: number; values: string[]; labels?: string[] }> = [];
messages.forEach((message, index) => {
const metrics = turns.observe(message);
if (metrics.length) out.push({ before: index, values: metrics.map((m) => m.value) });
});
const last = turns.end();
if (last.length)
out.push({
before: messages.length,
values: last.map((m) => m.value),
labels: last.map((m) => m.label),
});
return { out, lastReply: turns.lastReply };
}
describe("replayed turns", () => {
test("each finished turn's metrics come before the prompt that follows it", () => {
const first = step({ endedAt: 3_000, model: "first" });
const second = step({ endedAt: 12_000, model: "second", ttftMs: null, costUsd: null });
const { out, lastReply } = replay([
{ role: "user", at: 1_000 },
{ role: "assistant", step: step({ endedAt: 2_000 }), final: false },
// Parallel runs, 2.0s–2.5s and 2.25s–3.0s: 1.0s of tool time, not 1.25s.
{ role: "tool", run: [2_000, 2_500] },
{ role: "tool", run: [2_250, 3_000] },
{ role: "note" },
{ role: "assistant", step: first, final: true },
{ role: "user", at: 10_000 },
{ role: "assistant", step: second, final: true },
]);
expect(out).toEqual([
{
before: 6,
values: [
"first",
"~250 tok/s",
"2.0s",
"4.0s",
"1.0s",
"0.4s",
"2",
"2.0K ↑ · 1.0K ↓",
"75%",
"$0.020",
],
},
{
before: 8,
values: ["second", "~250 tok/s", "2.0s", "2.0s", "1.0K ↑ · 500 ↓", "75%"],
labels: ["Model", "Speed", "Elapsed", "Model time", "Tokens", "Cache"],
},
]);
expect(lastReply).toBe(second);
});
test("a turn that did not finish, or whose tool time was not recorded, says so", () => {
const { out } = replay([
{ role: "user", at: 0 },
{ role: "assistant", step: step({ endedAt: 1_000 }), final: false },
{ role: "user", at: 2_000 },
{ role: "assistant", step: step({ endedAt: 4_000 }), final: false },
{ role: "tool", run: null },
{ role: "assistant", step: step({ endedAt: 5_000 }), final: true },
]);
expect(out).toHaveLength(1);
expect(out[0]!.labels).not.toContain("Tool time");
expect(out[0]!.values[out[0]!.labels!.indexOf("Elapsed")]).toBe("3.0s");
});
});
describe("session metrics reporter", () => {
test("reports only changes, starting from nothing reported", () => {
const reported: unknown[] = [];
const report = createSessionMetricsReporter((metrics) => reported.push(metrics));
report([]);
report([{ label: "Cost", value: "$1.00" }]);
report([{ label: "Cost", value: "$1.00" }]);
report([]);
report([{ label: "Cost", value: "$1.00" }]);
expect(reported).toEqual([
[{ label: "Cost", value: "$1.00" }],
[],
[{ label: "Cost", value: "$1.00" }],
]);
});
});
@@ -0,0 +1,281 @@
import type { AgentMetric } from "../agent-sdk-types.js";
import {
cacheHitTone,
computeCacheHitPercent,
formatMetricCost,
formatMetricDuration,
formatMetricRate,
formatTokenPair,
mergeTimeIntervals,
type TimeInterval,
} from "./metrics.js";
/**
* Turn metrics for providers that report each model request of a turn as its own
* message with usage and timing, as Pi and OMP do. The provider maps its messages
* to steps; this module decides what the turn shows.
*/
const MIN_SPEED_DURATION_MS = 100;
export interface MeasuredTokens {
/** Uncached prompt tokens. */
input: number;
/** Generated tokens, reasoning included. */
output: number;
cacheRead: number;
cacheWrite: number;
}
/** One model request. A null field is one the provider did not report. */
export interface MeasuredStep {
model: string | null;
tokens: MeasuredTokens | null;
costUsd: number | null;
/** From sending the request to the end of the response. */
durationMs: number | null;
ttftMs: number | null;
/** Wall-clock time the response ended. */
endedAt: number | null;
}
export interface MeasuredTurn {
steps: MeasuredStep[];
/** Wall-clock time the prompt was sent. */
startedAt: number | null;
endedAt: number | null;
/** Wall time tools ran, overlapping runs counted once. */
toolMs: number | null;
}
/** The sum, or null when any value is missing so a partial total is never shown. */
function sumAll(values: readonly (number | null)[]): number | null {
let total = 0;
for (const value of values) {
if (value === null || !Number.isFinite(value) || value < 0) return null;
total += value;
}
return total;
}
function sumTokens(steps: readonly MeasuredStep[]): MeasuredTokens | null {
const pick = (read: (tokens: MeasuredTokens) => number) =>
sumAll(steps.map((step) => (step.tokens ? read(step.tokens) : null)));
const input = pick((tokens) => tokens.input);
const output = pick((tokens) => tokens.output);
const cacheRead = pick((tokens) => tokens.cacheRead);
const cacheWrite = pick((tokens) => tokens.cacheWrite);
if (input === null || output === null || cacheRead === null || cacheWrite === null) return null;
return { input, output, cacheRead, cacheWrite };
}
/** Wall time the runs cover, overlapping runs counted once. */
function totalDuration(runs: readonly TimeInterval[]): number {
return mergeTimeIntervals(runs).reduce((sum, [start, end]) => sum + (end - start), 0);
}
function metric(label: string, value: string | null): AgentMetric[] {
return value ? [{ label, value }] : [];
}
function duration(label: string, ms: number | null): AgentMetric[] {
return metric(label, ms === null ? null : formatMetricDuration(ms));
}
function speed(tokens: MeasuredTokens | null, modelMs: number | null): string | null {
if (!tokens || modelMs === null || modelMs < MIN_SPEED_DURATION_MS) return null;
return formatMetricRate(tokens.output / (modelMs / 1000));
}
export function tokensMetric(tokens: { input: number; output: number }): AgentMetric[] {
if (tokens.input + tokens.output <= 0) return [];
return [{ label: "Tokens", value: formatTokenPair(tokens.input, tokens.output) }];
}
export function cacheMetric(tokens: MeasuredTokens, label: string): AgentMetric[] {
const percent = computeCacheHitPercent({
input: tokens.input,
cacheRead: tokens.cacheRead,
cacheWrite: tokens.cacheWrite,
});
if (percent === null) return [];
const tone = cacheHitTone(percent);
return [{ label, value: `${percent}%`, ...(tone ? { tone } : {}) }];
}
export function costMetric(usd: number | null): AgentMetric[] {
return metric("Cost", usd === null ? null : formatMetricCost(usd));
}
/**
* Totals from the provider's own session counters, which survive compactions the
* transcript does not. The cache hit is the last reply's: a session-wide figure
* blends prompts from before and after compactions.
*/
export function sessionTotalsMetrics(
totals: { input: number; output: number; costUsd: number | null },
lastReply: MeasuredStep | null,
): AgentMetric[] {
return [
...tokensMetric(totals),
...(lastReply?.tokens ? cacheMetric(lastReply.tokens, "Cache (last reply)") : []),
...costMetric(totals.costUsd),
];
}
export function measuredTurnMetrics(turn: MeasuredTurn): AgentMetric[] {
const { steps } = turn;
const last = steps.at(-1);
if (!last) return [];
const tokens = sumTokens(steps);
const modelMs = sumAll(steps.map((step) => step.durationMs));
const ttftTotal = sumAll(steps.map((step) => step.ttftMs));
const elapsedMs =
turn.startedAt !== null && turn.endedAt !== null && turn.endedAt >= turn.startedAt
? turn.endedAt - turn.startedAt
: null;
return [
...metric("Model", last.model),
...metric("Speed", speed(tokens, modelMs)),
...duration("Elapsed", elapsedMs),
...duration("Model time", modelMs),
...(turn.toolMs !== null && turn.toolMs > 0 ? duration("Tool time", turn.toolMs) : []),
...duration(
steps.length === 1 ? "TTFT" : "Average TTFT",
ttftTotal === null ? null : ttftTotal / steps.length,
),
...(steps.length > 1 ? [{ label: "Steps", value: String(steps.length) }] : []),
...(tokens ? [...tokensMetric(tokens), ...cacheMetric(tokens, "Cache")] : []),
...costMetric(sumAll(steps.map((step) => step.costUsd))),
];
}
/**
* Measures a live turn: its replies, and when its tools ran, which providers do
* not record. Times are wall-clock milliseconds the caller passes in; the turn runs
* from begin() to finish().
*/
export class TurnMeter {
private startedAt: number | null = null;
private steps: MeasuredStep[] = [];
private running = new Map<string, number>();
private toolRuns: TimeInterval[] = [];
begin(now: number): void {
this.reset();
this.startedAt = now;
}
reset(): void {
this.startedAt = null;
this.steps = [];
this.running = new Map();
this.toolRuns = [];
}
step(step: MeasuredStep, now: number): void {
this.startedAt ??= now;
this.steps.push(step);
}
toolStarted(id: string, now: number): void {
this.startedAt ??= now;
this.running.set(id, now);
}
toolEnded(id: string, now: number): void {
const started = this.running.get(id);
if (started === undefined) return;
this.running.delete(id);
this.toolRuns.push([started, now]);
}
finish(now: number): MeasuredTurn {
const toolMs = this.toolRuns.length === 0 ? null : totalDuration(this.toolRuns);
return {
steps: [...this.steps],
startedAt: this.startedAt,
// The adapter's clock on both ends: a provider's timestamps can come from another clock.
endedAt: now,
toolMs,
};
}
}
/** How a provider's transcript messages read as turns. */
export interface TurnMessageReader<Message> {
/** When the message is a prompt, the time it was sent; null when it is not a prompt. */
prompt(message: Message): { startedAt: number | null } | null;
/** When the message is a model reply, its step and whether the turn ended with it. */
reply(message: Message): { step: MeasuredStep; final: boolean } | null;
/**
* When the tool behind a tool result ran: undefined for other messages, null when
* unrecorded. Readers whose transcripts never record it leave this out.
*/
toolRun?(message: Message): TimeInterval | null | undefined;
}
interface ReplayedTurn {
startedAt: number | null;
steps: MeasuredStep[];
/** Null once any run is unrecorded, so a partial tool time is never shown. */
toolRuns: TimeInterval[] | null;
final: boolean;
}
/**
* Replays a transcript as turns, each running from a prompt to the reply before
* the next prompt. Only turns that finished report metrics: one that failed or was
* stopped reports none live either.
*/
export class ReplayedTurns<Message> {
private turn: ReplayedTurn | null = null;
private latestReply: MeasuredStep | null = null;
constructor(private readonly reader: TurnMessageReader<Message>) {}
/** The most recent reply replayed, for session metrics that describe it. */
get lastReply(): MeasuredStep | null {
return this.latestReply;
}
/** Metrics of the turn this message closes; replay them before the message's own rows. */
observe(message: Message): AgentMetric[] {
const prompt = this.reader.prompt(message);
if (prompt) {
const closed = this.end();
this.turn = this.open(prompt.startedAt);
return closed;
}
const reply = this.reader.reply(message);
if (reply) {
this.turn ??= this.open(null);
this.turn.steps.push(reply.step);
this.turn.final = reply.final;
this.latestReply = reply.step;
return [];
}
const run = this.reader.toolRun?.(message);
if (run !== undefined && this.turn?.toolRuns) {
this.turn.toolRuns = run === null ? null : [...this.turn.toolRuns, run];
}
return [];
}
/** Metrics of the open turn, once the transcript ends. */
end(): AgentMetric[] {
const turn = this.turn;
this.turn = null;
if (!turn?.final) return [];
return measuredTurnMetrics({
steps: turn.steps,
startedAt: turn.startedAt,
endedAt: turn.steps.at(-1)?.endedAt ?? null,
toolMs: turn.toolRuns ? totalDuration(turn.toolRuns) : null,
});
}
private open(startedAt: number | null): ReplayedTurn {
return { startedAt, steps: [], toolRuns: this.reader.toolRun ? [] : null, final: false };
}
}