Show provider session and turn metrics (#10496)

* feat(providers): let providers report session and turn metrics

Providers know things about a session and a turn that Paseo cannot derive:
timing, token flow, cache use, cost, the model that answered. They can now
report them as label/value rows that Paseo carries to clients unchanged, so
each provider decides which metrics make sense and how they read.

Session metrics live on the agent record and snapshot. Turn metrics are
stamped on the turn's footer row (last assistant message, else last tool
call) so they survive reload, pagination and a daemon restart, and so the
live turn_completed event and a later timeline fetch agree. Provider history
replay restores both.

Metrics are sanitized once where they enter the agent manager. The wire
schemas validate whole messages, so one malformed row from a provider would
otherwise make clients drop an entire snapshot, turn event or timeline page.

A live completed turn with no Model metric gets the agent's model, so every
provider shows model attribution before it is instrumented. Replayed turns do
not: they may have run on a different model than the agent has now.

Plugin providers publish session metrics behind a negotiated
`session.metrics` capability because an older daemon closes a connection
that sends an event type it does not know. Turn metrics ride an existing
event that older daemons strip, so they need no gate.

The wire additions are optional fields on existing schemas only.

* 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.

* feat(app): show provider session and turn metrics

Session metrics appear in the context window details, between the context summary and the
account usage cards. A provider-reported Cost row replaces the app's own session cost line.

Each completed turn with metrics gets a stats button in its footer: a hover card on web, a
press-opened tooltip on native wide screens, and a sheet on compact screens. The context window
sheet becomes a shared DetailsSheet so both use the same content-sized sheet.

Metrics ride on the row that hosts the turn's footer (the turn's last assistant message, else its
last tool call), the same row the daemon stamps. Live turn_completed events and timeline pages
both stamp that row, so a refetch agrees with what the live event showed.

The daemon updates session metrics without bumping updatedAt, like usage, so a stale buffered
upsert may still carry the newest metrics and is accepted for that field.

* fix(app): keep a turn's stats after the cached timeline reloads

The local timeline cache dropped turnMetrics when it saved a turn's footer row. After a page
reload the cached rows painted without the stats icon, and the catch-up fetch had no new
entries to stamp them from.

* fix(providers): keep imported session stats and never count a steered turn short

Importing a Pi, Oh My Pi or OpenCode v2 session dropped the stats the provider returned with its
history, so imported chats showed none until a forced replay. Import now carries them the way
replay does.

Replaying a Pi or Oh My Pi transcript read a prompt that steered a running turn as the start of a
new turn, so the steered turn's stats counted only the steps after the steer. A turn that follows
one ending on tools now reports no total, because the transcript reads the same as a stop and a
new prompt.

* fix(providers): keep stats through merged messages and plugin imports, start Pi first-token timing at the request

A message the timeline merges from several chunks keeps the stats stamped on its last chunk. Plugin session imports carry the stats the plugin replayed, through the same history reader the other providers use. Steers queued together after an unclear turn stay unclear instead of attributing the final reply to the wrong turn. Pi measures time to first token from the request, not the first reply header.

* fix(providers): carry a turn's stats onto the message the timeline merges from text chunks

The previous change put the carry-over in the reasoning merge. The assistant message merge dropped the stats of its last chunk, so an imported reply of two text blocks lost its Turn stats button.

* fix(providers): carry a turn's stats onto the tool card the timeline merges from updates

An imported turn that ends on a tool call stamps the stats on the tool's last update. The tool merge kept the first update's fields, so the stats were lost.

* fix(opencode): replay no session stats for a session that has none

An empty OpenCode session replayed a session stats event with no metrics, which broke the empty-history check in the versioned runtime test.
This commit is contained in:
Mohamed Boudra
2026-11-22 16:43:56 +07:00
committed by GitHub
parent 52377f595a
commit 2d09c47672
94 changed files with 5500 additions and 170 deletions
+1
View File
@@ -102,6 +102,7 @@ Each agent is stored as a separate JSON file, grouped by project directory.
| `config` | `SerializableConfig?` | Agent session configuration (see below) |
| `runtimeInfo` | `RuntimeInfo?` | Live runtime state (see below) |
| `features` | `AgentFeature[]?` | Provider-reported features (toggles/selects) |
| `sessionMetrics` | `AgentMetric[]?` | Provider-reported session metrics, already formatted for display; the latest report replaces the list |
| `persistence` | `PersistenceHandle?` | Handle for resuming sessions |
| `lastError` | `string?` (nullable) | Last error message, if any |
| `requiresAttention` | `boolean?` | Whether the agent needs user attention |
@@ -393,6 +393,39 @@ describe("layoutStream", () => {
expect(findLayoutItem(layout, thinking.id).toolSequence).toBe("last");
});
it.each(["web", "android"] as const)(
"carries turn metrics from the footer's source row on %s",
(platform) => {
const metrics = [{ label: "Model", value: "opus" }];
const earlier = { ...assistantMessage("a1", 2), turnMetrics: metrics };
const latest = { ...toolCall("tool-2", 5), turnMetrics: [{ label: "Steps", value: "2" }] };
const layout = layoutFor({
platform,
tail: [userMessage("u1", 1), earlier, toolCall("tool-1", 3), userMessage("u2", 4), latest],
});
expect(findLayoutItem(layout, "tool-1").completedFooter?.turnMetrics).toBe(metrics);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(latest.turnMetrics);
},
);
it("lays out the footer again when its source row gains turn metrics", () => {
const assistant = assistantMessage("a1", 2);
const trailing = toolCall("tool-2", 4);
const tail = [userMessage("u1", 1), assistant, toolCall("tool-1", 3), trailing];
const next = userMessage("u2", 5);
const before = layoutFor({ platform: "android", tail: [...tail, next] });
const metrics = [{ label: "Model", value: "opus" }];
const stamped = [...tail];
stamped[1] = { ...assistant, turnMetrics: metrics };
const after = layoutFor({ platform: "android", tail: [...stamped, next] });
expect(findLayoutItem(before, trailing.id).completedFooter?.turnMetrics).toBeUndefined();
expect(findLayoutItem(after, trailing.id).completedFooter?.turnMetrics).toBe(metrics);
expect(findLayoutItem(after, next.id)).toBe(findLayoutItem(before, next.id));
});
it("keeps bottom and inline footer ownership mutually exclusive", () => {
const assistant = assistantMessage("a1", 2);
const layout = layoutFor({
+8
View File
@@ -1,3 +1,4 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing";
@@ -10,6 +11,7 @@ export interface TurnFooterHost {
itemId: string;
items: StreamItem[];
timing?: TurnTiming;
turnMetrics?: AgentMetric[];
startIndex: number;
}
@@ -69,10 +71,15 @@ function createTurnFooterHost(input: {
index: number;
timingByItemId: Map<string, TurnTiming>;
}): TurnFooterHost {
const turnMetrics =
input.item.kind === "assistant_message" || input.item.kind === "tool_call"
? input.item.turnMetrics
: undefined;
return {
itemId: input.item.id,
items: input.items,
timing: input.timingByItemId.get(input.item.id),
...(turnMetrics ? { turnMetrics } : {}),
startIndex: input.index,
};
}
@@ -247,6 +254,7 @@ function areTurnFooterHostsEqual(
return (
left.itemId === right.itemId &&
left.timing === right.timing &&
left.turnMetrics === right.turnMetrics &&
left.startIndex === right.startIndex &&
left.items === right.items
);
@@ -1,6 +1,10 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { PortalProvider } from "@gorhom/portal";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { FloatingPanelPortalHost } from "@/components/ui/floating-panel-portal";
import { i18n } from "@/i18n/i18next";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
@@ -92,3 +96,57 @@ it.each([
"Friday 11:11 PM": 1,
});
});
const COMPLETED_TIMING: TurnTiming = { completedAt: FRIDAY_NIGHT, durationMs: 26_000 };
describe("turn stats", () => {
const metrics: AgentMetric[] = [
{ label: "Model", value: "opus" },
{ label: "Cost", value: "$0.42", tone: "warning" },
];
function renderFooterWithMetrics(turnMetrics?: AgentMetric[]): void {
act(() =>
root.render(
<PortalProvider>
<CompletedTurnFooterRow
strategy={createNativeStreamStrategy()}
items={[reply]}
timing={COMPLETED_TIMING}
startIndex={0}
supportsTimelineCursor={false}
turnMetrics={turnMetrics}
/>
<FloatingPanelPortalHost />
</PortalProvider>,
),
);
}
it("has no trigger when the provider reported nothing for the turn", () => {
renderFooterWithMetrics(undefined);
expect(page.getByRole("button", { name: "Turn stats" }).elements()).toHaveLength(0);
});
it("shows the turn's metrics while the pointer is on the trigger", async () => {
renderFooterWithMetrics(metrics);
await page.getByRole("button", { name: "Turn stats" }).hover();
const card = page.getByRole("dialog", { name: "Turn stats" });
await expect.element(card).toBeVisible();
await expect.element(card.getByText("Model")).toBeVisible();
await expect.element(card.getByText("opus")).toBeVisible();
await expect.element(card.getByText("$0.42")).toBeVisible();
});
it("keeps the footer's height when the trigger appears", () => {
renderFooterWithMetrics(undefined);
const without = host.getBoundingClientRect().height;
renderFooterWithMetrics(metrics);
expect(host.getBoundingClientRect().height).toBe(without);
});
});
@@ -1,3 +1,4 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import React, { memo, useCallback, useMemo, type ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -81,6 +82,7 @@ export const TurnFooter = memo(function TurnFooter({
items={host.items}
timing={host.timing}
startIndex={host.startIndex}
turnMetrics={host.turnMetrics}
supportsTimelineCursor={supportsTimelineCursor}
onForkAssistantTurn={onForkAssistantTurn}
/>
@@ -92,6 +94,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({
items,
timing,
startIndex,
turnMetrics,
supportsTimelineCursor,
onForkAssistantTurn,
}: {
@@ -99,6 +102,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({
items: StreamItem[];
timing?: TurnTiming;
startIndex: number;
turnMetrics?: AgentMetric[];
supportsTimelineCursor: boolean;
onForkAssistantTurn?: AssistantTurnForkHandler;
}) {
@@ -109,6 +113,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({
items={items}
timing={timing}
startIndex={startIndex}
turnMetrics={turnMetrics}
supportsTimelineCursor={supportsTimelineCursor}
onForkAssistantTurn={onForkAssistantTurn}
/>
@@ -165,6 +170,7 @@ function CompletedTurnFooter({
items,
timing,
startIndex,
turnMetrics,
supportsTimelineCursor,
onForkAssistantTurn,
}: {
@@ -172,6 +178,7 @@ function CompletedTurnFooter({
items: StreamItem[];
timing?: TurnTiming;
startIndex: number;
turnMetrics?: AgentMetric[];
supportsTimelineCursor: boolean;
onForkAssistantTurn?: AssistantTurnForkHandler;
}) {
@@ -205,6 +212,7 @@ function CompletedTurnFooter({
completedAt={timing?.completedAt}
durationMs={timing?.durationMs}
onFork={boundary && onForkAssistantTurn ? handleFork : undefined}
metrics={turnMetrics}
/>
</View>
);
+1
View File
@@ -188,6 +188,7 @@ function renderStreamItemWithTurnFooter(input: {
items={footerHost.items}
timing={footerHost.timing}
startIndex={footerHost.startIndex}
turnMetrics={footerHost.turnMetrics}
supportsTimelineCursor={input.supportsTimelineCursor}
onForkAssistantTurn={input.onForkAssistantTurn}
/>
@@ -0,0 +1,65 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { i18n } from "@/i18n/i18next";
import { ContextWindowDetails } from "./context-window-details";
const CONTEXT = { percentage: 40, usedTokens: 80_000, maxTokens: 200_000 };
let root: Root;
let host: HTMLDivElement;
beforeEach(async () => {
await i18n.changeLanguage("en");
vi.stubGlobal("React", React);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(() => {
act(() => root.unmount());
host.remove();
vi.unstubAllGlobals();
});
function renderDetails(sessionMetrics: AgentMetric[]): void {
act(() =>
root.render(
<QueryClientProvider client={new QueryClient()}>
<ContextWindowDetails
serverId="server"
agentId="agent"
context={CONTEXT}
sessionCost="$1.20"
sessionMetrics={sessionMetrics}
showTitle
refreshable={false}
/>
</QueryClientProvider>,
),
);
}
it("shows what the provider reports about the session", async () => {
renderDetails([
{ label: "Model", value: "opus" },
{ label: "Requests", value: "12" },
]);
await expect.element(page.getByText("Model")).toBeVisible();
await expect.element(page.getByText("opus")).toBeVisible();
await expect.element(page.getByText("Requests")).toBeVisible();
await expect.element(page.getByText("Session cost $1.20")).toBeVisible();
});
it("leaves the cost to the provider when it reports one", async () => {
renderDetails([{ label: "Cost", value: "$1.25" }]);
await expect.element(page.getByText("$1.25")).toBeVisible();
expect(page.getByText("Session cost $1.20").elements()).toHaveLength(0);
});
@@ -1,8 +1,10 @@
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { AgentUsage } from "@/usage";
import { formatTokenCount } from "./context-window-meter.utils";
import { MetricsList } from "./metrics-list";
interface ContextWindowDetailsProps {
serverId: string;
@@ -13,6 +15,8 @@ interface ContextWindowDetailsProps {
maxTokens: number;
} | null;
sessionCost: string | null;
/** What the provider reports about the session. A reported cost replaces `sessionCost`. */
sessionMetrics: AgentMetric[];
/** The hover card and tooltip title themselves; the sheet's header carries the title instead. */
showTitle: boolean;
/** Whether the usage cards have a Refresh button; without one they show their freshness. */
@@ -20,18 +24,22 @@ interface ContextWindowDetailsProps {
}
/**
* What the context window meter opens: how full the window is, then the usage of the agent's
* account. The desktop hover card, the native wide tooltip, and the compact sheet all render it.
* What the context window meter opens: how full the window is, what the provider reports about the
* session, then the usage of the agent's account. The desktop hover card, the native wide tooltip, and the compact sheet all render it.
*/
export function ContextWindowDetails({
serverId,
agentId,
context,
sessionCost,
sessionMetrics,
showTitle,
refreshable,
}: ContextWindowDetailsProps) {
const { t } = useTranslation();
const providerReportsCost = sessionMetrics.some(
(metric) => metric.label.toLowerCase() === "cost",
);
return (
<>
<View style={styles.summary}>
@@ -51,10 +59,11 @@ export function ContextWindowDetails({
) : (
<Text style={styles.detail}>{t("contextWindow.noData")}</Text>
)}
{sessionCost ? (
{sessionCost && !providerReportsCost ? (
<Text style={styles.detail}>{t("contextWindow.sessionCost", { cost: sessionCost })}</Text>
) : null}
</View>
{sessionMetrics.length > 0 ? <MetricsList metrics={sessionMetrics} /> : null}
<AgentUsage serverId={serverId} agentId={agentId} refreshable={refreshable} />
</>
);
@@ -13,11 +13,12 @@ import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/h
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { useHostReportsUsage } from "@/usage";
import type { Theme } from "@/styles/theme";
import { TOOLBAR_DISC_SIZE, type ToolbarRing } from "@/components/ui/control-geometry";
import { ContextWindowDetails } from "./context-window-details";
import { ContextWindowSheet } from "./context-window-sheet";
import { DetailsSheet } from "./details-sheet";
import { formatContextPercentage } from "./context-window-meter.utils";
interface ContextWindowMeterProps {
@@ -26,11 +27,14 @@ interface ContextWindowMeterProps {
maxTokens: number | null;
usedTokens: number | null;
totalCostUsd?: number | null;
/** What the provider reports about the session, shown in the details. */
sessionMetrics?: AgentMetric[];
showPercentage?: boolean;
/** The ring's box and stroke when it sits in an icon toolbar. */
toolbarRing?: ToolbarRing;
}
const EMPTY_METRICS: AgentMetric[] = [];
const SVG_SIZE = 14;
const USAGE_POPOVER_WIDTH = 300;
const COMPACT_SVG_SIZE = 12;
@@ -156,13 +160,16 @@ export function ContextWindowMeter({
maxTokens,
usedTokens,
totalCostUsd,
sessionMetrics = EMPTY_METRICS,
showPercentage = false,
toolbarRing,
}: ContextWindowMeterProps) {
const { t, i18n } = useTranslation();
const { width } = useWindowDimensions();
// Usage cards need a wider popover; without them it keeps the plain tooltip shape.
// Usage cards and session metrics need a wider popover; without them it keeps the plain tooltip
// shape.
const showsUsage = useHostReportsUsage(serverId);
const isWide = showsUsage || sessionMetrics.length > 0;
const popoverWidth = Math.min(USAGE_POPOVER_WIDTH, width - 24);
// Compact screens open the details in a sheet, which can hold a pressable Refresh.
const isCompact = useIsCompactFormFactor();
@@ -226,21 +233,22 @@ export function ContextWindowMeter({
{ring}
{percentageLabel}
</Pressable>
<ContextWindowSheet open={isSheetOpen} onClose={closeSheet}>
<DetailsSheet open={isSheetOpen} onClose={closeSheet} title={t("contextWindow.title")}>
<ContextWindowDetails
serverId={serverId}
agentId={agentId}
context={context}
sessionCost={formattedSessionCost}
sessionMetrics={sessionMetrics}
showTitle={false}
refreshable
/>
</ContextWindowSheet>
</DetailsSheet>
</>
);
}
const popoverStyle = showsUsage
const popoverStyle = isWide
? [styles.usagePopover, { width: popoverWidth }]
: styles.plainPopover;
@@ -264,7 +272,7 @@ export function ContextWindowMeter({
side="top"
align="center"
offset={8}
maxWidth={showsUsage ? popoverWidth : undefined}
maxWidth={isWide ? popoverWidth : undefined}
style={popoverStyle}
testID="context-window-meter-tooltip"
>
@@ -273,6 +281,7 @@ export function ContextWindowMeter({
agentId={agentId}
context={context}
sessionCost={formattedSessionCost}
sessionMetrics={sessionMetrics}
showTitle
refreshable={false}
/>
@@ -307,6 +316,7 @@ export function ContextWindowMeter({
agentId={agentId}
context={context}
sessionCost={formattedSessionCost}
sessionMetrics={sessionMetrics}
showTitle
refreshable
/>
@@ -1,7 +1,6 @@
import { useMemo, type ReactNode } from "react";
import { View, useWindowDimensions } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { BottomSheetScrollView } from "@gorhom/bottom-sheet";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SheetHeaderView, SHEET_HORIZONTAL_PADDING_SCALE } from "@/components/adaptive-modal-sheet";
@@ -23,23 +22,24 @@ const ThemedBottomSheetModal = withUnistyles(IsolatedBottomSheetModal, (theme) =
}));
/**
* The context window meter's details on compact screens, in a sheet as tall as its content.
* Gorhom mounts the content only while the sheet is presented, so whatever it fetches stops once
* the sheet closes.
* What a hover card or tooltip shows on wide screens, shown on compact screens in a sheet as tall
* as its content. Gorhom mounts the content only while the sheet is presented, so whatever it
* fetches stops once the sheet closes.
*/
export function ContextWindowSheet({
export function DetailsSheet({
open,
onClose,
title,
children,
}: {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
}) {
const { t } = useTranslation();
const { height } = useWindowDimensions();
const insets = useSafeAreaInsets();
const header = useMemo(() => ({ title: t("contextWindow.title") }), [t]);
const header = useMemo(() => ({ title }), [title]);
const scrollContentStyle = useMemo(() => ({ paddingBottom: insets.bottom }), [insets.bottom]);
const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({
visible: open,
@@ -50,7 +50,8 @@ export function ContextWindowSheet({
<ThemedBottomSheetModal
ref={sheetRef}
contextBridge={null}
// Content-sized rather than fixed snap points: the usage cards stream in one at a time.
// Content-sized rather than fixed snap points: a few rows of details, or usage cards that
// stream in one at a time.
enableDynamicSizing
maxDynamicContentSize={height * 0.8}
onChange={handleSheetChange}
+12 -2
View File
@@ -3,6 +3,7 @@ import { MessagePreview, MessageSender } from "@/components/user-message";
import { useStableEvent } from "@/hooks/use-stable-event";
import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content";
import { AssistantForkMenu, type AssistantForkTarget } from "@/components/assistant-fork-menu";
import { TurnMetricsButton } from "@/components/turn-metrics";
import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox";
import {
AttachmentFrame,
@@ -36,7 +37,11 @@ import { useToolCallExpanded } from "@/tool-calls/expansion-context";
import { useTargetAgentTitle } from "@/tool-calls/use-target-agent-title";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type { AgentCapabilityFlags, ToolCallDetail } from "@getpaseo/protocol/agent-types";
import type {
AgentCapabilityFlags,
AgentMetric,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import MaskedView from "@react-native-masked-view/masked-view";
import {
@@ -560,6 +565,8 @@ interface AssistantTurnFooterProps {
completedAt?: Date;
durationMs?: number | null;
onFork?: (target: AssistantForkTarget) => Promise<void> | void;
/** What the provider reported about the turn. Without any, the footer has no stats button. */
metrics?: AgentMetric[];
}
const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({
@@ -617,6 +624,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
completedAt,
durationMs,
onFork,
metrics,
}: AssistantTurnFooterProps) {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
@@ -666,10 +674,11 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
[onFork],
);
const canFork = Boolean(onFork);
const hasMetrics = metrics !== undefined && metrics.length > 0;
return (
<View style={assistantTurnFooterStylesheet.container}>
{getContent || canFork ? (
{getContent || canFork || hasMetrics ? (
<View style={assistantTurnFooterStylesheet.actions}>
{getContent ? (
<TurnCopyButton
@@ -678,6 +687,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
/>
) : null}
{canFork ? <AssistantForkMenu onFork={handleFork} /> : null}
{hasMetrics ? <TurnMetricsButton metrics={metrics} /> : null}
</View>
) : null}
{primaryLabel ? (
@@ -0,0 +1,72 @@
import { memo } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
/**
* Label and value rows a provider reports for a session or a turn. The provider owns the words and
* the tone; the list only lines them up.
*/
export const MetricsList = memo(function MetricsList({
metrics,
testID,
}: {
metrics: AgentMetric[];
testID?: string;
}) {
return (
<View style={styles.list} testID={testID}>
{metrics.map((metric) => (
<View key={metric.label} style={styles.row}>
<Text style={styles.label} numberOfLines={1}>
{metric.label}
</Text>
<Text style={[styles.value, toneStyle(metric.tone)]} numberOfLines={1}>
{metric.value}
</Text>
</View>
))}
</View>
);
});
function toneStyle(tone: AgentMetric["tone"]) {
switch (tone) {
case "ok":
return styles.ok;
case "warning":
return styles.warning;
case "danger":
return styles.danger;
default:
return null;
}
}
const styles = StyleSheet.create((theme) => ({
list: {
gap: theme.spacing[1.5],
},
row: {
flexDirection: "row",
alignItems: "baseline",
gap: theme.spacing[6],
},
label: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
lineHeight: theme.fontSize.sm * 1.4,
},
value: {
flex: 1,
textAlign: "right",
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
lineHeight: theme.fontSize.sm * 1.4,
fontVariant: ["tabular-nums"],
},
ok: { color: theme.colors.statusSuccess },
warning: { color: theme.colors.statusWarning },
danger: { color: theme.colors.statusDanger },
}));
@@ -0,0 +1,148 @@
import { memo, useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { ChartNoAxesColumn } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
useHoverCardOpen,
} from "@/components/ui/hover-card";
import { PressHighlight } from "@/components/ui/press-highlight";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { DetailsSheet } from "./details-sheet";
import { MetricsList } from "./metrics-list";
const ThemedChart = withUnistyles(ChartNoAxesColumn);
const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
/**
* The turn footer's stats button: what the provider reported about this turn, in a hover card on
* web, a tooltip opened by press on native wide screens, and a sheet on compact screens.
*/
export const TurnMetricsButton = memo(function TurnMetricsButton({
metrics,
}: {
metrics: AgentMetric[];
}) {
const isCompact = useIsCompactFormFactor();
if (isCompact) return <TurnMetricsSheetButton metrics={metrics} />;
if (isNative) return <TurnMetricsTooltipButton metrics={metrics} />;
return <TurnMetricsHoverCardButton metrics={metrics} />;
});
function TurnMetricsSheetButton({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const openSheet = useCallback(() => setOpen(true), []);
const closeSheet = useCallback(() => setOpen(false), []);
return (
<>
<PressHighlight
style={styles.trigger}
accessibilityRole="button"
accessibilityLabel={t("message.actions.turnStats")}
onPress={openSheet}
testID="turn-metrics-trigger"
>
{({ hovered }) => <TurnMetricsIcon active={open || Boolean(hovered)} />}
</PressHighlight>
<DetailsSheet open={open} onClose={closeSheet} title={t("message.actions.turnStats")}>
<MetricsList metrics={metrics} />
</DetailsSheet>
</>
);
}
function TurnMetricsTooltipButton({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
return (
<Tooltip open={open} onOpenChange={setOpen} delayDuration={0} enabledOnDesktop enabledOnMobile>
<TooltipTrigger asChild triggerRefProp="ref">
<PressHighlight
style={styles.trigger}
accessibilityRole="button"
accessibilityLabel={t("message.actions.turnStats")}
testID="turn-metrics-trigger"
>
{({ hovered }) => <TurnMetricsIcon active={open || Boolean(hovered)} />}
</PressHighlight>
</TooltipTrigger>
<TooltipContent side="top" align="start" offset={8} style={styles.popover}>
<TurnMetricsDetails metrics={metrics} />
</TooltipContent>
</Tooltip>
);
}
function TurnMetricsHoverCardButton({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
return (
<HoverCard>
<HoverCardTrigger focusable accessibilityLabel={t("message.actions.turnStats")}>
<View style={styles.trigger} testID="turn-metrics-trigger">
<HoverCardTurnMetricsIcon />
</View>
</HoverCardTrigger>
<HoverCardContent
placement="top"
alignment="start"
offset={8}
role="dialog"
accessibilityLabel={t("message.actions.turnStats")}
testID="turn-metrics-details"
style={styles.popover}
>
<TurnMetricsDetails metrics={metrics} />
</HoverCardContent>
</HoverCard>
);
}
function HoverCardTurnMetricsIcon() {
return <TurnMetricsIcon active={useHoverCardOpen()} />;
}
function TurnMetricsIcon({ active }: { active: boolean }) {
return (
<ThemedChart
size={ICON_SIZE.sm}
uniProps={active ? foregroundColorMapping : foregroundMutedColorMapping}
/>
);
}
function TurnMetricsDetails({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
return (
<>
<Text style={styles.title}>{t("message.actions.turnStats")}</Text>
<MetricsList metrics={metrics} />
</>
);
}
const styles = StyleSheet.create((theme) => ({
// Matches the Copy and Fork buttons beside it, so the glyphs share one row and one spacing.
trigger: {
alignSelf: "center",
padding: theme.spacing[1],
borderRadius: theme.borderRadius.md,
},
popover: {
minWidth: 220,
padding: theme.spacing[3],
gap: theme.spacing[2],
},
title: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
}));
@@ -267,6 +267,11 @@ function WebHoverCard({
);
}
/** Whether the enclosing card is open, so its trigger can look active while it is. */
export function useHoverCardOpen(): boolean {
return useContext(HoverCardContext)?.open ?? false;
}
export function HoverCardTrigger({
children,
focusable = false,
+6
View File
@@ -147,6 +147,7 @@ import { RenderProfile } from "@/utils/render-profiler";
import { AfterPaintPublication } from "@/composer/after-paint-publication";
import { isWeb, isNative } from "@/constants/platform";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import type {
AttachmentMetadata,
ComposerAttachment,
@@ -295,6 +296,8 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
);
}
const EMPTY_METRICS: AgentMetric[] = [];
function buildAgentStateSelector(serverId: string, agentId: string) {
return (state: ReturnType<typeof useSessionStore.getState>) => {
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
@@ -303,6 +306,7 @@ function buildAgentStateSelector(serverId: string, agentId: string) {
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
model: agent?.model ?? null,
};
};
@@ -2225,6 +2229,7 @@ function ComposerContentImpl({
maxTokens={agentState.contextWindowMaxTokens}
usedTokens={agentState.contextWindowUsedTokens}
totalCostUsd={agentState.totalCostUsd}
sessionMetrics={agentState.sessionMetrics}
toolbarRing={TOOLBAR_RINGS[controlSizing]}
/>
</View>
@@ -2236,6 +2241,7 @@ function ComposerContentImpl({
agentState.contextWindowMaxTokens,
agentState.contextWindowUsedTokens,
agentState.totalCostUsd,
agentState.sessionMetrics,
controlSizing,
],
);
+1
View File
@@ -349,6 +349,7 @@ export const ar: TranslationResources = {
copyTurn: "نسخ بدوره",
copyMessage: "انسخ الرسالة",
forkMenu: "تفريع الرسالة",
turnStats: "إحصاءات الدور",
forkInNewTab: "تفريع في تبويب جديد",
forkInNewWorkspace: "تفريع في مساحة عمل جديدة",
forkUnavailable: "حدّث المضيف لاستخدام هذا.",
+1
View File
@@ -348,6 +348,7 @@ export const en = {
copyTurn: "Copy turn",
copyMessage: "Copy message",
forkMenu: "Fork chat from here",
turnStats: "Turn stats",
forkInNewTab: "Fork in a new tab",
forkInNewWorkspace: "Fork in a new workspace",
forkUnavailable: "Update the host to use this.",
+1
View File
@@ -354,6 +354,7 @@ export const es: TranslationResources = {
copyTurn: "Copiar turno",
copyMessage: "Copiar mensaje",
forkMenu: "Bifurcar mensaje",
turnStats: "Estadísticas del turno",
forkInNewTab: "Bifurcar en una pestaña nueva",
forkInNewWorkspace: "Bifurcar en un espacio de trabajo nuevo",
forkUnavailable: "Actualiza el host para usar esto.",
+1
View File
@@ -354,6 +354,7 @@ export const fr: TranslationResources = {
copyTurn: "Copier l’échange",
copyMessage: "Copier le message",
forkMenu: "Forker la conversation à partir d’ici",
turnStats: "Statistiques de l’échange",
forkInNewTab: "Forker dans un nouvel onglet",
forkInNewWorkspace: "Forker dans un nouvel espace de travail",
forkUnavailable: "Mettez à jour l’hôte pour utiliser cette fonction.",
+1
View File
@@ -354,6 +354,7 @@ export const ja: TranslationResources = {
copyTurn: "ターンをコピー",
copyMessage: "メッセージをコピー",
forkMenu: "メッセージをフォーク",
turnStats: "ターンの統計",
forkInNewTab: "新しいタブにフォーク",
forkInNewWorkspace: "新しいワークスペースにフォーク",
forkUnavailable: "これを使用するにはホストを更新してください。",
+1
View File
@@ -350,6 +350,7 @@ export const ko: TranslationResources = {
copyTurn: "턴 복사",
copyMessage: "메시지 복사",
forkMenu: "여기에서 채팅 분기",
turnStats: "턴 통계",
forkInNewTab: "새 탭으로 분기",
forkInNewWorkspace: "새 워크스페이스로 분기",
forkUnavailable: "이를 사용하려면 호스트를 업데이트하세요.",
+1
View File
@@ -353,6 +353,7 @@ export const ptBR: TranslationResources = {
copyTurn: "Copiar turno",
copyMessage: "Copiar mensagem",
forkMenu: "Bifurcar mensagem",
turnStats: "Estatísticas do turno",
forkInNewTab: "Bifurcar em uma nova aba",
forkInNewWorkspace: "Bifurcar em um novo workspace",
forkUnavailable: "Atualize o host para usar isto.",
+1
View File
@@ -353,6 +353,7 @@ export const ru: TranslationResources = {
copyTurn: "Скопировать ответ",
copyMessage: "Копировать сообщение",
forkMenu: "Форкнуть чат отсюда",
turnStats: "Статистика ответа",
forkInNewTab: "Создать форк в новой вкладке",
forkInNewWorkspace: "Создать форк в новом рабочем пространстве",
forkUnavailable: "Обновите хост, чтобы использовать эту функцию.",
+1
View File
@@ -349,6 +349,7 @@ export const zhCN: TranslationResources = {
copyTurn: "复制回合",
copyMessage: "复制消息",
forkMenu: "分叉消息",
turnStats: "回合统计",
forkInNewTab: "分叉到新标签页",
forkInNewWorkspace: "分叉到新工作区",
forkUnavailable: "请更新主机以使用此功能。",
@@ -806,6 +806,28 @@ describe("ReplicaCache", () => {
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([timelineItem("New")]);
});
it("keeps a turn's stats on its footer row across cache reopen", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const answer: StreamItem = {
...(timelineItem("Done") as Extract<StreamItem, { kind: "assistant_message" }>),
turnMetrics: [
{ label: "Model", value: "gemini-3.6-flash" },
{ label: "Cache", value: "64%", tone: "ok" },
],
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
items: [answer],
range: { epoch: "epoch-1", startSeq: 12, endSeq: 12 },
hasOlder: false,
});
await writer.flush();
const reader = createCache(storage);
expect((await reader.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([answer]);
});
it("round-trips plugin timeline items", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -2,6 +2,7 @@ import { findMountedWindowStart } from "@/agent-stream/history-window";
import { z } from "zod";
import {
AgentBackgroundWorkSummarySchema,
AgentMetricSchema,
AgentStatusSchema,
AgentTimelineItemPayloadSchema,
ForgeWebSchema,
@@ -129,6 +130,7 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [
...TimelineItemBaseShape,
kind: z.literal("assistant_message"),
messageId: z.string().optional(),
turnMetrics: z.array(AgentMetricSchema).optional(),
text: z.string(),
// Reject old caches containing display fragments; refetch the complete source text.
}),
@@ -163,6 +165,7 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [
...TimelineItemBaseShape,
kind: z.literal("tool_call"),
provider: AgentProviderSchema,
turnMetrics: z.array(AgentMetricSchema).optional(),
item: AgentTimelineItemPayloadSchema.refine((item) => item.type === "tool_call"),
}),
z.strictObject({
@@ -482,6 +485,7 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
...base,
kind: item.kind,
...(item.messageId ? { messageId: item.messageId } : {}),
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
text: item.text,
};
case "thought":
@@ -516,6 +520,7 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
...base,
kind: item.kind,
provider: item.payload.data.provider,
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
item: serializeAgentToolCall(item.payload.data),
};
case "plugin":
@@ -575,6 +580,7 @@ function deserializeBuiltinTimelineItem(
...base,
kind: item.kind,
...(item.messageId ? { messageId: item.messageId } : {}),
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
text: item.text,
};
case "thought":
@@ -611,6 +617,7 @@ function deserializeBuiltinTimelineItem(
return {
...base,
kind: item.kind,
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
payload: {
source: "agent",
data: {
+3
View File
@@ -33,6 +33,7 @@ import type {
AgentMode,
AgentCapabilityFlags,
AgentUsage,
AgentMetric,
AgentPersistenceHandle,
} from "@getpaseo/protocol/agent-types";
import type {
@@ -93,6 +94,8 @@ export interface Agent {
runtimeInfo?: AgentRuntimeInfo;
usageScopeKey?: string;
lastUsage?: AgentUsage;
/** What the provider reports about the session, as label and value rows. */
sessionMetrics?: AgentMetric[];
lastError?: string | null;
title: string | null;
cwd: string;
@@ -4558,3 +4558,262 @@ describe("createAgentStreamReducerQueue", () => {
expect(scheduler.size).toBe(0);
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "opus" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
function liveTurn(events: AgentStreamEventPayload[]) {
let seq = 0;
return processAgentStreamEvents({
events: events.map((event) =>
event.type === "timeline"
? makeStreamReducerEvent(event, ++seq)
: { event, seq: undefined, epoch: undefined, timestamp: new Date(1000 + seq) },
),
currentTail: [],
currentHead: [],
currentCursor: undefined,
});
}
function inTurn(event: AgentStreamEventPayload, turnId: string): AgentStreamEventPayload {
return { ...event, turnId } as AgentStreamEventPayload;
}
function turnCompleted(turnId?: string, turnMetrics = metrics): AgentStreamEventPayload {
return {
type: "turn_completed",
provider: "claude",
...(turnId ? { turnId } : {}),
metrics: turnMetrics,
};
}
function metricsByKind(items: StreamItem[]) {
return items.map((item) => ({
kind: item.kind,
turnMetrics: "turnMetrics" in item ? item.turnMetrics : undefined,
}));
}
it("puts a live turn's metrics on its last assistant message", () => {
const result = liveTurn([
inTurn(makeTimelineEvent("question", "user_message"), "turn-1"),
inTurn(makeAssistantTimelineEvent("Looking."), "turn-1"),
inTurn(makeToolCallTimelineEvent("read-1"), "turn-1"),
inTurn(makeAssistantTimelineEvent("Done."), "turn-1"),
turnCompleted("turn-1"),
]);
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
it("puts a live tool-only turn's metrics on its last tool call", () => {
const result = liveTurn([
inTurn(makeTimelineEvent("question", "user_message"), "turn-1"),
inTurn(makeToolCallTimelineEvent("read-1"), "turn-1"),
inTurn(makeToolCallTimelineEvent("read-2"), "turn-1"),
turnCompleted("turn-1"),
]);
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: metrics },
]);
});
it("does not put a turn's metrics on an earlier turn's reply", () => {
const result = liveTurn([
inTurn(makeTimelineEvent("first", "user_message"), "turn-1"),
inTurn(makeAssistantTimelineEvent("First reply."), "turn-1"),
turnCompleted("turn-1", [{ label: "Model", value: "first" }]),
inTurn(makeTimelineEvent("second", "user_message"), "turn-2"),
inTurn(makeToolCallTimelineEvent("read-1"), "turn-2"),
inTurn(makeTimelineEvent("thinking", "reasoning"), "turn-2"),
turnCompleted("turn-2"),
]);
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: [{ label: "Model", value: "first" }] },
{ kind: "user_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: undefined },
{ kind: "thought", turnMetrics: undefined },
]);
});
it("leaves the timeline untouched when a turn completes without metrics", () => {
const before = liveTurn([
inTurn(makeTimelineEvent("question", "user_message"), "turn-1"),
inTurn(makeAssistantTimelineEvent("Done."), "turn-1"),
turnCompleted("turn-1", []),
]);
const after = processAgentStreamEvent({
...baseStreamInput,
event: { type: "turn_completed", provider: "claude", turnId: "turn-1" },
currentTail: before.tail,
currentHead: before.head,
});
expect(after.tail).toBe(before.tail);
expect(metricsByKind(after.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: undefined },
]);
});
it("hydrates turn metrics from a replaced history page", () => {
const result = processTimelineResponse({
...baseTimelineInput,
payload: {
...baseTimelineInput.payload,
reset: true,
startCursor: { seq: 1 },
endCursor: { seq: 4 },
entries: [
makeTimelineEntry(1, "question", "user_message"),
{ ...makeTimelineEntry(2, "Reply."), turnMetrics: metrics },
makeTimelineEntry(3, "next question", "user_message"),
{
...makeToolCallTimelineEntry(4, "read-1", "completed", {
type: "read",
filePath: "/tmp/a.ts",
}),
turnMetrics: [{ label: "Model", value: "sonnet" }],
},
],
},
});
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
{ kind: "user_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: [{ label: "Model", value: "sonnet" }] },
]);
});
it("hydrates turn metrics from an older history page", () => {
const currentTail: StreamItem[] = [
{ kind: "user_message", id: "current-3", text: "current-3", timestamp: new Date(3000) },
];
const result = processTimelineResponse({
...baseTimelineInput,
currentTail,
currentCursor: { epoch: "epoch-1", startSeq: 3, endSeq: 3 },
payload: {
...baseTimelineInput.payload,
direction: "before",
startCursor: { seq: 1 },
endCursor: { seq: 2 },
entries: [
makeTimelineEntry(1, "older question", "user_message"),
{ ...makeTimelineEntry(2, "Older reply."), turnMetrics: metrics },
],
},
});
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
{ kind: "user_message", turnMetrics: undefined },
]);
});
it("hydrates turn metrics on a projected reply that replaces the live one", () => {
const live = processAgentStreamEvents({
events: [makeStreamReducerEvent(makeAssistantTimelineEvent("Partial"), 2)],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 1 },
});
const result = processTimelineResponse({
...baseTimelineInput,
currentTail: live.tail,
currentHead: live.head,
currentCursor: live.cursor ?? undefined,
payload: {
...baseTimelineInput.payload,
startCursor: { seq: 3 },
endCursor: { seq: 3 },
entries: [
{
...makeTimelineEntry(2, "Partial reply.", "assistant_message", 3),
sourceSeqRanges: [{ startSeq: 2, endSeq: 3 }],
turnMetrics: metrics,
},
],
},
});
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
it("keeps live turn metrics when canonical history replaces the timeline", () => {
const live = liveTurn([
makeTimelineEvent("question", "user_message"),
makeAssistantTimelineEvent("Done."),
turnCompleted(),
]);
const result = processTimelineResponse({
...baseTimelineInput,
currentTail: live.tail,
currentHead: live.head,
currentCursor: live.cursor ?? undefined,
payload: {
...baseTimelineInput.payload,
reset: true,
startCursor: { seq: 1 },
endCursor: { seq: 2 },
entries: [
makeTimelineEntry(1, "question", "user_message"),
{ ...makeTimelineEntry(2, "Done."), turnMetrics: metrics },
],
},
});
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
it("keeps row identity when a page repeats metrics the row already has", () => {
const first = processTimelineResponse({
...baseTimelineInput,
payload: {
...baseTimelineInput.payload,
reset: true,
startCursor: { seq: 1 },
endCursor: { seq: 1 },
entries: [{ ...makeTimelineEntry(1, "Reply."), turnMetrics: metrics }],
},
});
const repeated = processTimelineResponse({
...baseTimelineInput,
currentTail: first.tail,
currentCursor: first.cursor ?? undefined,
payload: {
...baseTimelineInput.payload,
startCursor: { seq: 1 },
endCursor: { seq: 1 },
entries: [{ ...makeTimelineEntry(1, "Reply."), turnMetrics: [...metrics] }],
},
});
expect(repeated.tail).toBe(first.tail);
});
});
@@ -1,8 +1,9 @@
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
import {
applyStreamEvent,
flushHeadToTail,
@@ -133,6 +134,7 @@ interface TimelineResponseEntry {
turnId?: string;
item: AgentTimelineItem;
timestamp: string;
turnMetrics?: AgentMetric[];
}
export interface ProcessTimelineResponseInput {
@@ -1268,7 +1270,8 @@ export function processTimelineResponse(
// ------------------------------------------------------------------
// Convert entries to timeline units
// ------------------------------------------------------------------
const timelineUnits = selectEntriesOwnedByTimelinePage(payload).map((entry) => ({
const pageEntries = selectEntriesOwnedByTimelinePage(payload);
const timelineUnits = pageEntries.map((entry) => ({
seq: entry.seqStart,
seqEnd: entry.seqEnd,
sourceSeqRanges:
@@ -1379,8 +1382,8 @@ export function processTimelineResponse(
});
}
const nextTail = timelineResult.tail;
const nextHead = timelineResult.head;
const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries);
const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries);
const nextCursor = timelineResult.cursor;
const cursorChanged = timelineResult.cursorChanged;
sideEffects.push(...timelineResult.sideEffects);
+101
View File
@@ -0,0 +1,101 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { continuesResponse } from "@/agent-stream/turn-membership";
import type { StreamItem, TimelinePosition } from "@/types/stream";
type TurnFooterAnchor = Extract<StreamItem, { kind: "assistant_message" | "tool_call" }>;
/**
* Puts a completed turn's metrics on the row its footer hangs on: the turn's last assistant
* message, else its last row when that row is a tool call. The daemon stamps the same row, so a
* later timeline fetch agrees with what the live event showed.
*/
export function stampCompletedTurnMetrics(
items: StreamItem[],
metrics: AgentMetric[] | undefined,
turnId: string | undefined,
): StreamItem[] {
if (!metrics || metrics.length === 0) return items;
const index = findTurnFooterAnchorIndex(items, turnId);
if (index === null) return items;
return replaceAt(items, index, metrics);
}
/**
* Puts the metrics a timeline page carries on the rows it wrote. Every reducer path leaves a row
* with the cursor of the last entry that wrote it, which is the entry the daemon stamped.
*/
export function stampTimelineTurnMetrics(
items: StreamItem[],
epoch: string,
entries: ReadonlyArray<{ seqEnd: number; turnMetrics?: AgentMetric[] }>,
): StreamItem[] {
const metricsBySeq = new Map<number, AgentMetric[]>();
for (const entry of entries) {
if (entry.turnMetrics && entry.turnMetrics.length > 0) {
metricsBySeq.set(entry.seqEnd, entry.turnMetrics);
}
}
if (metricsBySeq.size === 0) return items;
let next = items;
items.forEach((item, index) => {
const metrics = isTurnFooterAnchor(item)
? metricsBySeq.get(cursorSeqIn(item.timelineCursor, epoch) ?? -1)
: undefined;
if (metrics) next = replaceAt(next, index, metrics);
});
return next;
}
function findTurnFooterAnchorIndex(items: StreamItem[], turnId: string | undefined): number | null {
const last = lastIndexOfTurn(items, turnId);
if (last === null) return null;
for (let index = last; index >= 0; index--) {
if (index < last && !continuesResponse(items[index], items[index + 1])) break;
if (items[index].kind === "assistant_message") return index;
}
return items[last].kind === "tool_call" ? last : null;
}
function lastIndexOfTurn(items: StreamItem[], turnId: string | undefined): number | null {
const tail = items.length - 1;
if (tail < 0) return null;
if (turnId === undefined) return tail;
const index = items.findLastIndex((item) => item.turnId === turnId);
if (index >= 0) return index;
// Rows from daemons without turn ids belong to the trailing turn. A tail owned by another
// turn means this turn wrote no rows.
return items[tail].turnId === undefined ? tail : null;
}
function isTurnFooterAnchor(item: StreamItem): item is TurnFooterAnchor {
return item.kind === "assistant_message" || item.kind === "tool_call";
}
function cursorSeqIn(cursor: TimelinePosition | undefined, epoch: string): number | null {
return cursor?.epoch === epoch ? cursor.seq : null;
}
/** Returns `items` itself when the row already shows these metrics, so unchanged rows keep identity. */
function replaceAt(items: StreamItem[], index: number, metrics: AgentMetric[]): StreamItem[] {
const item = items[index];
if (!item || !isTurnFooterAnchor(item) || areMetricsEqual(item.turnMetrics, metrics)) {
return items;
}
const next = [...items];
next[index] = { ...item, turnMetrics: metrics };
return next;
}
function areMetricsEqual(left: AgentMetric[] | undefined, right: AgentMetric[]): boolean {
return (
left !== undefined &&
left.length === right.length &&
left.every(
(metric, index) =>
metric.label === right[index].label &&
metric.value === right[index].value &&
metric.tone === right[index].tone,
)
);
}
+8 -1
View File
@@ -1,5 +1,6 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type {
AgentMetric,
AgentProvider,
AgentTimelineItem,
JsonValue,
@@ -9,6 +10,7 @@ import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
import type { AgentAttachment, AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type { AttachmentMetadata } from "@/attachments/types";
import type { OverviewSummary } from "@/tool-calls/detail-level/overview/model";
import { stampCompletedTurnMetrics } from "@/timeline/turn-metrics";
import { extractTaskEntriesFromToolCall } from "../utils/tool-call-parsers";
/**
@@ -715,6 +717,8 @@ export interface AssistantMessageItem {
timelineCursor?: TimelinePosition;
text: string;
timestamp: Date;
/** Set when this message carries its turn's footer. */
turnMetrics?: AgentMetric[];
/** Display-only fields, assigned after source-item plugin transforms. */
}
@@ -769,6 +773,8 @@ export interface ToolCallItem {
turnId?: string;
timestamp: Date;
payload: ToolCallPayload;
/** Set when this call carries its turn's footer. */
turnMetrics?: AgentMetric[];
}
export type AgentToolCallItem = ToolCallItem & {
@@ -1630,9 +1636,10 @@ export function reduceStreamUpdate(
);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
case "thread_started":
case "turn_started":
case "turn_completed":
case "turn_failed":
case "turn_canceled":
case "permission_requested":
@@ -199,6 +199,44 @@ describe("agent directory reconciliation", () => {
});
});
it("accepts session metrics from a stale buffered upsert without regressing metadata", () => {
const result = reconcileAgentDirectory({
snapshot: [
{
...entry("agent", "idle"),
agent: {
...snapshot("agent", "idle"),
title: "newer page",
updatedAt: "2026-07-12T12:00:00.000Z",
sessionMetrics: [{ label: "Cost", value: "$0.10" }],
},
},
],
deltas: [
{
kind: "upsert",
agent: {
...snapshot("agent", "running"),
title: "stale live",
updatedAt: "2026-07-12T11:00:00.000Z",
sessionMetrics: [{ label: "Cost", value: "$0.42" }],
},
project: entry("agent", "idle").project,
},
],
});
expect({
title: result[0]?.agent.title,
status: result[0]?.agent.status,
sessionMetrics: result[0]?.agent.sessionMetrics,
}).toEqual({
title: "newer page",
status: "idle",
sessionMetrics: [{ label: "Cost", value: "$0.42" }],
});
});
it("preserves usage when a stale buffered upsert omits it", () => {
const result = reconcileAgentDirectory({
snapshot: [
@@ -1,11 +1,16 @@
import equal from "fast-deep-equal";
import type { AgentUsage } from "@getpaseo/protocol/agent-types";
import type { AgentMetric, AgentUsage } from "@getpaseo/protocol/agent-types";
interface AgentUpdateValue {
updatedAt: Date | string;
lastUsage?: AgentUsage;
sessionMetrics?: AgentMetric[];
}
// The daemon reports these without bumping `updatedAt`, so a stale upsert can still carry the
// newest value.
const FIELDS_UPDATED_IN_PLACE = ["lastUsage", "sessionMetrics"] as const;
function timestamp(value: Date | string): number {
return value instanceof Date ? value.getTime() : Date.parse(value);
}
@@ -15,7 +20,9 @@ export function acceptAgentDirectoryUpdate<T extends AgentUpdateValue>(
incoming: T,
): T {
if (!current || timestamp(incoming.updatedAt) >= timestamp(current.updatedAt)) return incoming;
if (incoming.lastUsage === undefined) return current;
if (equal(incoming.lastUsage, current.lastUsage)) return current;
return { ...current, lastUsage: incoming.lastUsage };
const newer = FIELDS_UPDATED_IN_PLACE.filter(
(field) => incoming[field] !== undefined && !equal(incoming[field], current[field]),
);
if (newer.length === 0) return current;
return { ...current, ...Object.fromEntries(newer.map((field) => [field, incoming[field]])) };
}
@@ -35,6 +35,7 @@ function createSnapshot(
labels: (input.labels ?? {}) as AgentSnapshotPayload["labels"],
...(input.controls ? { controls: input.controls } : {}),
...(input.options ? { options: input.options } : {}),
...(input.sessionMetrics ? { sessionMetrics: input.sessionMetrics } : {}),
};
}
@@ -78,6 +79,15 @@ describe("normalizeAgentSnapshot", () => {
});
});
it("round-trips session metrics through the canonical snapshot boundary", () => {
const sessionMetrics = [{ label: "Cost", value: "$0.42", tone: "warning" as const }];
const agent = normalizeAgentSnapshot(createSnapshot({ sessionMetrics }), "server-1");
expect(agent.sessionMetrics).toEqual(sessionMetrics);
expect(projectAgentSnapshot(agent).sessionMetrics).toEqual(sessionMetrics);
});
it("normalizes identified and legacy active turns at the snapshot boundary", () => {
const startedAt = "2026-07-31T12:00:00.000Z";
expect(
@@ -81,6 +81,7 @@ export function projectAgentSnapshot(agent: Agent): AgentSnapshotPayload {
...(agent.runtimeInfo ? { runtimeInfo: agent.runtimeInfo } : {}),
...(agent.usageScopeKey ? { usageScopeKey: agent.usageScopeKey } : {}),
...(agent.lastUsage ? { lastUsage: agent.lastUsage } : {}),
...(agent.sessionMetrics ? { sessionMetrics: agent.sessionMetrics } : {}),
...(agent.lastError ? { lastError: agent.lastError } : {}),
title: agent.title,
labels: agent.labels,
@@ -129,6 +130,7 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId:
runtimeInfo: snapshot.runtimeInfo,
usageScopeKey: snapshot.usageScopeKey,
lastUsage: snapshot.lastUsage,
sessionMetrics: snapshot.sessionMetrics,
lastError: snapshot.lastError ?? null,
title: snapshot.title ?? null,
cwd: snapshot.cwd,
@@ -22,6 +22,7 @@ export const AudioLines = StubIcon;
export const Blocks = StubIcon;
export const Bot = StubIcon;
export const Brain = StubIcon;
export const ChartNoAxesColumn = StubIcon;
export const Check = StubIcon;
export const CheckCircle = StubIcon;
export const CheckCircle2 = StubIcon;
@@ -140,3 +141,5 @@ export const Ellipsis = StubIcon;
export const Maximize = StubIcon;
export const Minimize = StubIcon;
export const Rows2 = StubIcon;
export const Gauge = StubIcon;
export const GripVertical = StubIcon;
+62 -1
View File
@@ -1,5 +1,12 @@
import { describe, expect, it } from "vitest";
import { ProviderInputSchema, type ProviderInput } from "./provider.js";
import {
ProviderEventSchema,
ProviderInputSchema,
negotiateProviderCapabilities,
type ProviderEvent,
type ProviderInput,
type ProviderMetric,
} from "./provider.js";
type ReviewMode = "uncommitted" | "base" | "all";
type Delivery = "auto" | "steer";
@@ -64,3 +71,57 @@ describe("Provider review attachments", () => {
},
);
});
describe("Provider metrics", () => {
const metrics: ProviderMetric[] = [
{ label: "Model", value: "agent-large" },
{ label: "Cache", value: "82%", tone: "ok" },
];
it("publishes the session's metrics as one replaceable list", () => {
const event: ProviderEvent = { type: "session.metrics", sessionId: "session-1", metrics };
expect(ProviderEventSchema.parse(event)).toEqual(event);
});
it("attaches metrics to the turn they describe when it completes", () => {
const event: ProviderEvent = {
type: "session.turn",
sessionId: "session-1",
turnId: "turn-1",
state: "completed",
metrics,
};
expect(ProviderEventSchema.parse(event)).toEqual(event);
});
it("keeps completing turns without metrics", () => {
const event: ProviderEvent = {
type: "session.turn",
sessionId: "session-1",
turnId: "turn-1",
state: "completed",
};
expect(ProviderEventSchema.parse(event)).toEqual(event);
});
it("tells a provider whether this Paseo shows session metrics", () => {
const supported = ["prompt.message", "session.metrics"] as const;
expect(
negotiateProviderCapabilities(["prompt.message", "session.metrics"], supported),
).toContain("session.metrics");
// A Paseo from before session metrics never offers them.
expect(negotiateProviderCapabilities(["prompt.message"], supported)).toEqual([
"prompt.message",
]);
});
it("refuses a metric whose value is not text Paseo can show as given", () => {
expect(
ProviderEventSchema.safeParse({
type: "session.metrics",
sessionId: "session-1",
metrics: [{ label: "Cost", value: 1.23 }],
}).success,
).toBe(false);
});
});
+38
View File
@@ -13,6 +13,7 @@ export const PROVIDER_CAPABILITIES = [
"session.archive",
"session.configure",
"session.list",
"session.metrics",
"session.persistence",
"session.revert.both",
"session.revert.conversation",
@@ -551,6 +552,17 @@ export interface ProviderUsage {
contextWindowUsedTokens?: number;
}
/**
* One row of provider-owned detail about a session or a turn. Format `value` for
* reading: Paseo shows it as given.
*/
export interface ProviderMetric {
label: string;
value: string;
/** Colors the value. Omit it for an ordinary value. */
tone?: "default" | "ok" | "warning" | "danger";
}
interface ProviderTimelineIdentity {
id: string;
revertToken?: JsonValue;
@@ -726,8 +738,19 @@ export type ProviderEvent =
turnId: string;
state: "started" | "completed" | "failed" | "canceled";
error?: ProviderError;
/** Shown on the turn's footer. Read when `state` is `"completed"`. */
metrics?: readonly ProviderMetric[];
}
| { type: "session.usage"; sessionId: string; turnId?: string; usage: ProviderUsage }
| {
type: "session.metrics";
sessionId: string;
/**
* Replaces the metrics shown for the session. An empty list clears them. Publish only when
* `session.metrics` was negotiated: a Paseo that does not offer it rejects this event.
*/
metrics: readonly ProviderMetric[];
}
| { type: "session.config"; sessionId: string; config: ProviderConfigState }
| { type: "session.commands"; sessionId: string; commands: ProviderCommand[] }
| { type: "session.permission"; sessionId: string; request: ProviderPermissionRequest }
@@ -1234,6 +1257,13 @@ const usageSchema = z
contextWindowUsedTokens: z.number().optional(),
})
.strip();
const metricSchema = z
.object({
label: z.string(),
value: z.string(),
tone: z.enum(["default", "ok", "warning", "danger"]).optional(),
})
.strip();
const worktreeCommandSchema = z
.object({
index: z.number().int().positive(),
@@ -1554,6 +1584,7 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
turnId: idSchema,
state: z.enum(["started", "completed", "failed", "canceled"]),
error: providerErrorSchema.optional(),
metrics: z.array(metricSchema).optional(),
})
.strip(),
z
@@ -1564,6 +1595,13 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
usage: usageSchema,
})
.strip(),
z
.object({
type: z.literal("session.metrics"),
sessionId: idSchema,
metrics: z.array(metricSchema),
})
.strip(),
z
.object({ type: z.literal("session.config"), sessionId: idSchema, config: configStateSchema })
.strip(),
+19 -1
View File
@@ -221,6 +221,18 @@ export interface AgentUsage {
contextWindowUsedTokens?: number;
}
export type AgentMetricTone = "default" | "ok" | "warning" | "danger";
/**
* One provider-owned label/value row. The provider formats `value`; Paseo renders
* it as given and never interprets it.
*/
export interface AgentMetric {
label: string;
value: string;
tone?: AgentMetricTone;
}
export const TOOL_CALL_ICON_NAMES = [
"wrench",
"square_terminal",
@@ -413,7 +425,13 @@ export type AgentTimelineItem =
export type AgentStreamEvent =
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
| { type: "turn_started"; provider: AgentProvider; turnId?: string }
| { type: "turn_completed"; provider: AgentProvider; usage?: AgentUsage; turnId?: string }
| {
type: "turn_completed";
provider: AgentProvider;
usage?: AgentUsage;
turnId?: string;
metrics?: AgentMetric[];
}
| { type: "usage_updated"; provider: AgentProvider; usage: AgentUsage; turnId?: string }
| {
type: "mode_changed";
+11
View File
@@ -290,6 +290,7 @@ export type MutableDaemonConfig = z.infer<typeof MutableDaemonConfigSchema>;
export type MutableDaemonConfigPatch = z.infer<typeof MutableDaemonConfigPatchSchema>;
import type {
AgentCapabilityFlags,
AgentMetric,
AgentModelDefinition,
AgentMode,
AgentPermissionRequest,
@@ -483,6 +484,12 @@ const AgentUsageSchema: z.ZodType<AgentUsage> = z.object({
contextWindowUsedTokens: z.number().optional(),
});
export const AgentMetricSchema: z.ZodType<AgentMetric> = z.object({
label: z.string(),
value: z.string(),
tone: z.enum(["default", "ok", "warning", "danger"]).optional(),
});
const McpStdioServerConfigSchema = z.object({
type: z.literal("stdio"),
command: z.string(),
@@ -828,6 +835,7 @@ export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [
provider: AgentProviderSchema,
turnId: z.string().optional(),
usage: AgentUsageSchema.optional(),
metrics: z.array(AgentMetricSchema).optional(),
}),
z.object({
type: z.literal("turn_failed"),
@@ -940,6 +948,7 @@ export const AgentSnapshotPayloadSchema = z.object({
/** Opaque. Changes whenever the accounts this agent reports usage for can change. */
usageScopeKey: z.string().optional(),
lastUsage: AgentUsageSchema.optional(),
sessionMetrics: z.array(AgentMetricSchema).optional(),
lastError: z.string().optional(),
title: z.string().nullable(),
labels: z.record(z.string(), z.string()).default({}),
@@ -5135,6 +5144,8 @@ export const AgentTimelineEntryPayloadSchema = z.object({
seqEnd: z.number().int().nonnegative(),
sourceSeqRanges: z.array(AgentTimelineSeqRangeSchema),
collapsed: z.array(z.enum(["assistant_merge", "reasoning_merge", "tool_lifecycle", "identity"])),
/** Set on the row that carries the turn footer: the turn's last assistant message, else its last tool call. */
turnMetrics: z.array(AgentMetricSchema).optional(),
});
export const FetchAgentTimelineResponseMessageSchema = z.object({
@@ -5,6 +5,7 @@ import {
MutableDaemonConfigPatchSchema,
UsageReportEntrySchema,
AgentSnapshotPayloadSchema,
AgentStreamEventPayloadSchema,
AgentTimelineItemPayloadSchema,
ServerInfoStatusPayloadSchema,
SessionOutboundMessageSchema,
@@ -648,3 +649,91 @@ test("speech config reads remain compatible with clients before features and fut
}).features?.voiceMode?.stt,
).toEqual({ provider: "future", region: "eu" });
});
describe("provider metrics", () => {
const metrics = [
{ label: "Model", value: "gpt-5.5" },
{ label: "Cache", value: "82%", tone: "ok" },
];
const snapshot = {
id: "agent-1",
provider: "codex",
cwd: "/tmp/project",
model: null,
thinkingOptionId: null,
effectiveThinkingOptionId: null,
createdAt: "2026-11-22T00:00:00.000Z",
updatedAt: "2026-11-22T00:00:00.000Z",
lastUserMessageAt: null,
status: "idle",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: null,
labels: {},
};
const turnCompleted = { type: "turn_completed", provider: "codex", turnId: "turn-1" };
const entry = {
provider: "codex",
item: { type: "assistant_message", text: "Done" },
timestamp: "2026-11-22T00:00:00.000Z",
seqStart: 1,
seqEnd: 1,
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
collapsed: [],
};
test("new apps read session, turn and timeline metrics from a new daemon", () => {
expect(
AgentSnapshotPayloadSchema.parse({ ...snapshot, sessionMetrics: metrics }).sessionMetrics,
).toEqual(metrics);
expect(AgentStreamEventPayloadSchema.parse({ ...turnCompleted, metrics })).toEqual({
...turnCompleted,
metrics,
});
expect(AgentTimelineEntryPayloadSchema.parse({ ...entry, turnMetrics: metrics })).toEqual({
...entry,
turnMetrics: metrics,
});
});
test("new apps accept payloads from daemons that send no metrics", () => {
expect(AgentSnapshotPayloadSchema.parse(snapshot).sessionMetrics).toBeUndefined();
expect(AgentStreamEventPayloadSchema.parse(turnCompleted)).toEqual(turnCompleted);
expect(AgentTimelineEntryPayloadSchema.parse(entry)).toEqual(entry);
});
test("apps released before metrics drop the fields they do not know", () => {
const legacySnapshot = AgentSnapshotPayloadSchema.omit({ sessionMetrics: true });
const legacyTurnCompleted = z.object({
type: z.literal("turn_completed"),
provider: z.string(),
turnId: z.string().optional(),
});
const legacyEntry = AgentTimelineEntryPayloadSchema.omit({ turnMetrics: true });
expect(legacySnapshot.parse({ ...snapshot, sessionMetrics: metrics })).not.toHaveProperty(
"sessionMetrics",
);
expect(legacyTurnCompleted.parse({ ...turnCompleted, metrics })).toEqual(turnCompleted);
expect(legacyEntry.parse({ ...entry, turnMetrics: metrics })).toEqual(entry);
});
test("metric tone is a closed set, so a new tone needs a capability gate", () => {
expect(
AgentTimelineEntryPayloadSchema.safeParse({
...entry,
turnMetrics: [{ label: "Cache", value: "82%", tone: "sparkly" }],
}).success,
).toBe(false);
});
});
@@ -260,6 +260,62 @@ const SourceSchema = z.object({
});
});
it("preserves turn metrics on a completed turn and on its timeline row", () => {
const metrics = [
{ label: "Model", value: "gpt-5.5" },
{ label: "Cache", value: "82%", tone: "ok" },
];
const completed = {
type: "session",
message: {
type: "agent_stream",
payload: {
agentId: "agent-1",
event: { type: "turn_completed", provider: "codex", turnId: "turn-1", metrics },
timestamp: "2026-11-22T00:00:00.000Z",
},
},
};
const timeline = {
type: "session",
message: {
type: "fetch_agent_timeline_response",
payload: {
requestId: "timeline",
agentId: "agent-1",
agent: null,
direction: "tail",
projection: "projected",
epoch: "epoch-1",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 1, maxSeq: 1, nextSeq: 2 },
startCursor: null,
endCursor: null,
hasOlder: false,
hasNewer: false,
entries: [
{
provider: "codex",
item: { type: "assistant_message", text: "Done" },
timestamp: "2026-11-22T00:00:00.000Z",
seqStart: 1,
seqEnd: 1,
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
collapsed: [],
turnMetrics: metrics,
},
],
error: null,
},
},
};
expect(validateWSOutboundMessage(completed)).toEqual({ success: true, data: completed });
expect(validateWSOutboundMessage(timeline)).toEqual({ success: true, data: timeline });
});
it("emits runtime imports with .js extensions", async () => {
const generated = await readFile(generatedWSOutboundPath, "utf8");
expect(generated).toContain('from "./ws-outbound-schema-metadata.js"');
@@ -47,6 +47,7 @@ import type {
AgentDraftControls,
AgentOptionControl,
AgentLaunchContext,
AgentMetric,
AgentPromptInput,
AgentProvider,
AgentPersistenceHandle,
@@ -2136,6 +2137,10 @@ class StreamingAssistantClient implements AgentClient {
interface FakeCodexEmitterArgs {
turnItems?: AgentTimelineItem[];
historyItems?: AgentTimelineItem[];
/** Metrics the provider attaches to the turn it completes. */
turnMetrics?: AgentMetric[];
/** A raw replay, for history that is more than timeline items. */
history?: AgentStreamEvent[];
}
function fakeCodexEmitting(args: FakeCodexEmitterArgs): AgentClient {
@@ -2150,12 +2155,18 @@ function fakeCodexEmitting(args: FakeCodexEmitterArgs): AgentClient {
for (const item of turnItems) {
this.pushEvent({ type: "timeline", provider: this.provider, item, turnId });
}
this.pushEvent({ type: "turn_completed", provider: this.provider, turnId });
this.pushEvent({
type: "turn_completed",
provider: this.provider,
turnId,
...(args.turnMetrics ? { metrics: args.turnMetrics } : {}),
});
}, 0);
return { turnId };
}
override async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
yield* args.history ?? [];
for (const item of historyItems) {
yield { type: "timeline", provider: this.provider, item };
}
@@ -2171,8 +2182,8 @@ function fakeCodexEmitting(args: FakeCodexEmitterArgs): AgentClient {
async createSession(config: AgentSessionConfig) {
return new FakeCodexSession(config);
},
async resumeSession() {
throw new Error("unused");
async resumeSession(_handle, config) {
return new FakeCodexSession({ provider: "codex", cwd: config?.cwd ?? process.cwd() });
},
};
}
@@ -13696,6 +13707,257 @@ test("system-injected prompts appear as trigger tools during history replay", as
expect(userMessages[0].text).toBe("real user message");
});
function completedTurns(events: AgentManagerEvent[]) {
return events.flatMap((event) =>
event.type === "agent_stream" && event.event.type === "turn_completed" ? [event.event] : [],
);
}
test("a completed turn's metrics go out with the turn and stay on its footer row", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-turn-metrics-"));
const store = new RecordingTimelineStore();
const metrics: AgentMetric[] = [
{ label: "Model", value: "GPT-5.4" },
{ label: "Cache", value: "82%", tone: "ok" },
];
const manager = new AgentManager({
clients: {
codex: fakeCodexEmitting({
turnItems: [
{ type: "assistant_message", text: "Working" },
{
type: "tool_call",
callId: "call-1",
name: "shell",
status: "completed",
error: null,
detail: { type: "unknown", input: null, output: null },
},
{ type: "assistant_message", text: "Done" },
],
turnMetrics: metrics,
}),
},
durableTimelineStore: store,
logger,
});
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false });
await manager.runAgent(agent.id, { text: "go" });
await manager.flush();
expect(completedTurns(events)).toEqual([
{ type: "turn_completed", provider: "codex", turnId: "turn-fake-codex", metrics },
]);
const stamped = { item: { type: "assistant_message", text: "Done" }, turnMetrics: metrics };
expect(manager.fetchTimeline(agent.id).rows.filter((row) => row.turnMetrics)).toEqual([
expect.objectContaining(stamped),
]);
expect((await manager.getTimelineRows(agent.id)).filter((row) => row.turnMetrics)).toEqual([
expect.objectContaining(stamped),
]);
await manager.closeAgent(agent.id);
});
test.each<{
name: string;
model?: string;
turnMetrics?: AgentMetric[];
expected: AgentMetric[] | undefined;
}>([
{
name: "leads with the agent's model when the provider names none",
model: "gpt-5.4",
turnMetrics: [{ label: "Elapsed", value: "1.2s" }],
expected: [
{ label: "Model", value: "gpt-5.4" },
{ label: "Elapsed", value: "1.2s" },
],
},
{
name: "shows the agent's model for a provider that reports no metrics",
model: "gpt-5.4",
expected: [{ label: "Model", value: "gpt-5.4" }],
},
{
name: "keeps the provider's own model row",
model: "gpt-5.4",
turnMetrics: [{ label: "MODEL", value: "GPT-5.4 (fast)" }],
expected: [{ label: "MODEL", value: "GPT-5.4 (fast)" }],
},
{
name: "sends no metrics when neither the provider nor the agent names a model",
expected: undefined,
},
])("a live turn $name", async ({ model, turnMetrics, expected }) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-turn-model-"));
const manager = new AgentManager({
clients: {
codex: fakeCodexEmitting({
turnItems: [{ type: "assistant_message", text: "Done" }],
turnMetrics,
}),
},
logger,
});
const agent = await manager.createAgent({ provider: "codex", cwd: workdir, model }, undefined, {
workspaceId: undefined,
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false });
await manager.runAgent(agent.id, { text: "go" });
expect(completedTurns(events).map((event) => event.metrics)).toEqual([expected]);
expect(manager.fetchTimeline(agent.id).rows.at(-1)?.turnMetrics).toEqual(expected);
await manager.closeAgent(agent.id);
});
test.each(["first load", "forced refresh"])(
"turn metrics in provider history return to their footer rows on %s",
async (path) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-history-metrics-"));
const first: AgentMetric[] = [{ label: "Model", value: "GPT-5.4" }];
const second: AgentMetric[] = [{ label: "Elapsed", value: "4.0s" }];
const tool: AgentTimelineItem = {
type: "tool_call",
callId: "call-1",
name: "shell",
status: "completed",
error: null,
detail: { type: "unknown", input: null, output: null },
};
const history: AgentStreamEvent[] = [
{ type: "timeline", provider: "codex", item: { type: "user_message", text: "one" } },
{ type: "timeline", provider: "codex", item: { type: "assistant_message", text: "A1" } },
{ type: "turn_completed", provider: "codex", turnId: "old-1", metrics: first },
{ type: "timeline", provider: "codex", item: { type: "user_message", text: "two" } },
{ type: "timeline", provider: "codex", item: tool },
{ type: "turn_completed", provider: "codex", turnId: "old-2", metrics: second },
{ type: "timeline", provider: "codex", item: { type: "user_message", text: "three" } },
{ type: "timeline", provider: "codex", item: { type: "assistant_message", text: "A3" } },
{ type: "turn_completed", provider: "codex", turnId: "old-3" },
];
const manager = new AgentManager({
clients: { codex: fakeCodexEmitting({ history }) },
logger,
});
// The agent's model is known, but a replayed turn may have run on another one.
const agent = await manager.createAgent(
{ provider: "codex", cwd: workdir, model: "gpt-5.4" },
undefined,
{ workspaceId: undefined },
);
if (path === "forced refresh") {
await manager.hydrateTimelineFromProvider(agent.id, { force: true });
} else {
await manager.reloadAgentSession(agent.id, undefined, { rehydrateFromDisk: true });
await manager.hydrateTimelineFromProvider(agent.id);
}
expect(manager.fetchTimeline(agent.id).rows.map((row) => row.turnMetrics ?? null)).toEqual([
null,
first,
null,
second,
null,
null,
]);
await manager.closeAgent(agent.id);
},
);
test.each(["first load", "forced refresh"])(
"session metrics in provider history show the provider's latest totals on %s",
async (path) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-history-session-metrics-"));
const latest: AgentMetric[] = [{ label: "Cost", value: "$0.42" }];
const history: AgentStreamEvent[] = [
{
type: "session_metrics_updated",
provider: "codex",
metrics: [{ label: "Cost", value: "$0.10" }],
},
{ type: "timeline", provider: "codex", item: { type: "user_message", text: "one" } },
{ type: "session_metrics_updated", provider: "codex", metrics: latest },
];
const manager = new AgentManager({
clients: { codex: fakeCodexEmitting({ history }) },
logger,
});
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false });
if (path === "forced refresh") {
await manager.hydrateTimelineFromProvider(agent.id, { force: true });
} else {
await manager.reloadAgentSession(agent.id, undefined, { rehydrateFromDisk: true });
await manager.hydrateTimelineFromProvider(agent.id);
}
expect(events).toContainEqual(
expect.objectContaining({
type: "agent_state",
agent: expect.objectContaining({ sessionMetrics: latest }),
}),
);
expect(manager.getAgent(agent.id)?.sessionMetrics).toEqual(latest);
await manager.closeAgent(agent.id);
},
);
test("session metrics reach the agent snapshot, stay off the stream, and survive a restart", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-session-metrics-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new SessionRecordingAgentClient();
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false });
const metrics: AgentMetric[] = [
{ label: "Cost", value: "$1.23" },
{ label: "Cache", value: "82%", tone: "ok" },
];
client.sessions[0].pushEvent({ type: "session_metrics_updated", provider: "codex", metrics });
await manager.flush();
expect(toAgentPayload(manager.getAgent(agent.id)!).sessionMetrics).toEqual(metrics);
expect(events.filter((event) => event.type === "agent_stream")).toEqual([]);
expect(events).toContainEqual(
expect.objectContaining({
type: "agent_state",
agent: expect.objectContaining({ sessionMetrics: metrics }),
}),
);
await manager.reloadAgentSession(agent.id);
expect(manager.getAgent(agent.id)?.sessionMetrics).toEqual(metrics);
await manager.closeAgent(agent.id);
await manager.flush();
const restarted = new AgentManager({ clients: { codex: client }, registry: storage, logger });
const record = await storage.get(agent.id);
expect(record?.sessionMetrics).toEqual(metrics);
const resumed = await restarted.resumeAgentFromPersistence(
record!.persistence!,
{ cwd: workdir },
agent.id,
);
expect(toAgentPayload(resumed).sessionMetrics).toEqual(metrics);
await restarted.closeAgent(agent.id);
});
test("commandMayHaveChangedExternalState matches remote-state commands", () => {
// GitHub PR operations (remote, no local file changes)
expect(commandMayHaveChangedExternalState("gh pr merge 123")).toBe(true);
@@ -15945,3 +16207,55 @@ function dispatchStarted(dispatch: Awaited<ReturnType<typeof startAgentRun>>): P
void dispatch.started.catch(() => undefined);
return dispatch.started;
}
test("importProviderSession keeps the stats the provider reported with its history", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-import-metrics-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const session = new TestAgentSession({ provider: "codex", cwd: workdir });
const turnMetrics = [{ label: "Elapsed", value: "1.2s" }];
const sessionMetrics = [{ label: "Cost", value: "$0.011" }];
class ImportClient extends TestAgentClient {
async importSession(input: ImportProviderSessionInput) {
return {
session,
config: { provider: "codex" as const, cwd: workdir },
persistence: {
provider: "codex" as const,
sessionId: input.providerHandleId,
nativeHandle: input.providerHandleId,
metadata: { provider: "codex", cwd: workdir },
},
timeline: [
{ item: { type: "user_message" as const, text: "Hi" } },
{ item: { type: "assistant_message" as const, text: "Done" }, turnMetrics },
{ item: { type: "user_message" as const, text: "Again" } },
{ item: { type: "assistant_message" as const, text: "Done again" } },
],
sessionMetrics,
};
}
}
const manager = new AgentManager({
clients: { codex: new ImportClient() },
registry: storage,
logger,
});
const imported = await manager.importProviderSession({
provider: "codex",
providerHandleId: "thread-selected",
cwd: workdir,
workspaceId: "ws-imported",
});
expect(imported.sessionMetrics).toEqual(sessionMetrics);
expect(
manager.fetchTimeline(imported.id).rows.map((row) => [row.item.type, row.turnMetrics ?? null]),
).toEqual([
["user_message", null],
["assistant_message", turnMetrics],
["user_message", null],
["assistant_message", null],
]);
});
+170 -50
View File
@@ -4,7 +4,11 @@ import type { AgentToolResult } from "@getpaseo/plugin/server";
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js";
import { AgentTurnChangedError } from "./agent-prompt.js";
import { continuesAssistantMessage, projectTimelineRows } from "./timeline-projection.js";
import {
continuesAssistantMessage,
projectTimelineRows,
TimelineProjection,
} from "./timeline-projection.js";
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js";
import { applyRecordPatch } from "../record-patch.js";
@@ -57,6 +61,7 @@ import {
type SteerResult,
type AgentStreamEvent,
type AgentTimelineItem,
type AgentMetric,
type AgentUsage,
type AgentRuntimeInfo,
type ImportedTimelineEntry,
@@ -66,6 +71,7 @@ import {
import { buildArchivedAgentRecord, type ArchivedStoredAgentRecord } from "./agent-archive.js";
import type { JsonValue, ProviderOptions } from "@getpaseo/protocol/agent-types";
import { toStoredAgentRecord } from "./agent-projections.js";
import { sanitizeAgentMetrics, withModelMetric } from "./agent-metrics.js";
import {
applyProviderOptionsPatch,
exposeFeatureValuesToHook,
@@ -510,6 +516,8 @@ interface ManagedAgentBase {
activeTurnId: string | null;
activeTurnStartedAt: Date | null;
lastUsage?: AgentUsage;
/** Provider-owned session metrics, replaced whole on every provider update. */
sessionMetrics?: AgentMetric[];
lastError?: string;
attention: AttentionState;
foregroundTurnWaiters: Set<ForegroundTurnWaiter>;
@@ -591,6 +599,37 @@ type LiveManagedAgent = ActiveManagedAgent;
type AgentLabelPatch = Record<string, string | null>;
type AgentMetadata = Record<string, JsonValue>;
/**
* What a provider replay contributes: timeline rows, the metrics of the turn that
* wrote the rows before them, and the session's metrics as they stood at that point.
*/
type ProviderHistoryEntry =
| { type: "row"; event: Extract<AgentStreamEvent, { type: "timeline" }> }
| { type: "turn_metrics"; metrics: AgentMetric[] }
| { type: "session_metrics"; metrics: AgentMetric[] };
interface ReplayedTimelineRow {
event: Extract<AgentStreamEvent, { type: "timeline" }>;
row: AgentTimelineRow;
}
function providerHistoryEntries(event: AgentStreamEvent): ProviderHistoryEntry[] {
if (event.type === "timeline") {
return projectAgentMessages(event.item).map((item) => ({
type: "row",
event: { ...event, item },
}));
}
if (event.type === "turn_completed") {
const metrics = sanitizeAgentMetrics(event.metrics);
return metrics.length > 0 ? [{ type: "turn_metrics", metrics }] : [];
}
if (event.type === "session_metrics_updated") {
return [{ type: "session_metrics", metrics: sanitizeAgentMetrics(event.metrics) }];
}
return [];
}
function attachManagedTurnIdentity(
agent: ActiveManagedAgent,
event: AgentStreamEvent,
@@ -774,13 +813,22 @@ function buildExplicitTimelineSeedForRegister(
function buildImportedTimelineRows(entries: readonly ImportedTimelineEntry[]): AgentTimelineRow[] {
const rows: AgentTimelineRow[] = [];
// Finds the footer row a turn's stats belong on, by the same rule live turns use.
const projection = new TimelineProjection();
for (const entry of entries) {
for (const item of projectAgentMessages(entry.item)) {
rows.push({
const row: AgentTimelineRow = {
seq: rows.length + 1,
timestamp: entry.timestamp ?? new Date().toISOString(),
item: limitAgentTimelineItemContent(item),
});
};
rows.push(row);
projection.append(row);
}
if (entry.turnMetrics) {
const footer = projection.stampTurnMetrics(entry.turnMetrics);
if (footer)
rows[footer.seq - 1] = { ...rows[footer.seq - 1], turnMetrics: entry.turnMetrics };
}
}
return rows;
@@ -1788,7 +1836,14 @@ export class AgentManager {
...options,
// The caller read its metadata and attention before this turn in the lane; a setMetadata
// or attention clear queued ahead of it has saved a newer record, the one the open hooks saw.
...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}),
...(record
? {
metadata: record.metadata,
attention: extractAttention(record),
// Shown until the reopened session reports its own.
sessionMetrics: record.sessionMetrics,
}
: {}),
workspaceId,
launchEnv,
persistence:
@@ -1877,6 +1932,7 @@ export class AgentManager {
workspaceId: input.workspaceId,
timelineRows,
timelineNextSeq: timelineRows.length + 1,
sessionMetrics: imported.sessionMetrics,
persistence: imported.persistence,
historyPrimed: true,
initialTitle,
@@ -1926,6 +1982,7 @@ export class AgentManager {
const rehydrateFromDisk = options?.rehydrateFromDisk ?? false;
const preservedHistoryPrimed = existing.historyPrimed;
const preservedLastUsage = existing.lastUsage;
const preservedSessionMetrics = existing.sessionMetrics;
const preservedLastError = existing.lastError;
const preservedAttention = existing.attention;
const handle = existing.persistence;
@@ -2012,6 +2069,7 @@ export class AgentManager {
lastUserMessageAt: existing.lastUserMessageAt,
historyPrimed: rehydrateFromDisk ? false : preservedHistoryPrimed,
lastUsage: preservedLastUsage,
sessionMetrics: preservedSessionMetrics,
lastError: preservedLastError,
attention: preservedAttention,
restoring: true,
@@ -2469,6 +2527,7 @@ export class AgentManager {
historyPrimed: true,
lastUserMessageAt: record.lastUserMessageAt ? new Date(record.lastUserMessageAt) : null,
lastUsage: undefined,
sessionMetrics: record.sessionMetrics,
lastError: record.lastError ?? undefined,
attention,
internal: record.internal,
@@ -4459,6 +4518,7 @@ export class AgentManager {
persistence?: AgentPersistenceHandle;
historyPrimed?: boolean;
lastUsage?: AgentUsage;
sessionMetrics?: AgentMetric[];
lastError?: string;
attention?: AttentionState;
/**
@@ -4669,6 +4729,7 @@ export class AgentManager {
metadata?: AgentMetadata;
historyPrimed?: boolean;
lastUsage?: AgentUsage;
sessionMetrics?: AgentMetric[];
lastError?: string;
attention?: AttentionState;
persistence?: AgentPersistenceHandle;
@@ -4722,6 +4783,7 @@ export class AgentManager {
historyPrimed: options?.historyPrimed ?? durableTimelineHasRows,
lastUserMessageAt: options?.lastUserMessageAt ?? null,
lastUsage: options?.lastUsage,
sessionMetrics: options?.sessionMetrics,
lastError: options?.lastError,
attention: resolveInitialAttention(options?.attention),
internal: config.internal ?? false,
@@ -5077,16 +5139,14 @@ export class AgentManager {
broadcast: boolean,
broadcastTimeline: boolean,
): Promise<void> {
const historyEvents: Extract<AgentStreamEvent, { type: "timeline" }>[] = [];
const historyEntries: ProviderHistoryEntry[] = [];
const providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] = [];
for await (const rawEvent of agent.session.streamHistory()) {
const event = limitAgentStreamEventContent(rawEvent);
if (event.type === "timeline") {
for (const item of projectAgentMessages(event.item)) {
historyEvents.push({ ...event, item });
}
} else if (event.type === "provider_subagent") {
if (event.type === "provider_subagent") {
providerSubagentEvents.push(event);
} else {
historyEntries.push(...providerHistoryEntries(event));
}
}
@@ -5107,17 +5167,13 @@ export class AgentManager {
this.dispatch({ type: "provider_subagent", event: update });
}
}
for (const event of historyEvents) {
const row = this.recordTimeline(
agent.id,
event.item,
event.timestamp ? { timestamp: event.timestamp } : undefined,
);
if (broadcastTimeline) {
this.dispatchStream(agent.id, event, {
seq: row.seq,
for (const entry of historyEntries) {
const replayed = this.replayProviderHistoryEntry(agent, entry);
if (replayed && broadcastTimeline) {
this.dispatchStream(agent.id, replayed.event, {
seq: replayed.row.seq,
epoch: this.timelineStore.getEpoch(agent.id),
timestamp: row.timestamp,
timestamp: replayed.row.timestamp,
});
}
}
@@ -5125,6 +5181,31 @@ export class AgentManager {
this.emitState(agent);
}
/**
* Returns the row a replayed timeline event wrote. Metrics write no row: turn
* metrics land on one already written, session metrics on the agent.
*/
private replayProviderHistoryEntry(
agent: ActiveManagedAgent,
entry: ProviderHistoryEntry,
): ReplayedTimelineRow | null {
if (entry.type === "turn_metrics") {
this.stampTurnMetrics(agent.id, entry.metrics);
return null;
}
if (entry.type === "session_metrics") {
agent.sessionMetrics = entry.metrics;
return null;
}
const { event } = entry;
const row = this.recordTimeline(
agent.id,
event.item,
event.timestamp ? { timestamp: event.timestamp } : undefined,
);
return { event, row };
}
private async primeTimelineFromLegacyProviderHistory(
agent: ActiveManagedAgent,
broadcast: boolean | (() => boolean),
@@ -5133,7 +5214,7 @@ export class AgentManager {
| Iterable<AgentStreamEvent> = agent.session.streamHistory(),
): Promise<void> {
const deferredBroadcast = typeof broadcast === "function";
const historyEvents: Extract<AgentStreamEvent, { type: "timeline" }>[] = [];
const historyEntries: ProviderHistoryEntry[] = [];
const historySubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] = [];
agent.historyPrimed = false;
try {
@@ -5146,12 +5227,7 @@ export class AgentManager {
historySubagentEvents.push(event);
continue;
}
if (event.type !== "timeline") {
continue;
}
for (const item of projectAgentMessages(event.item)) {
historyEvents.push({ ...event, item });
}
historyEntries.push(...providerHistoryEntries(event));
}
} catch (error) {
this.logger.warn({ err: error, agentId: agent.id }, "Failed to hydrate provider history");
@@ -5162,10 +5238,7 @@ export class AgentManager {
// Keeping them would leave getTimelineRows reading one copy per hydration.
await this.deleteCommittedTimeline(agent.id);
const timelineEvents: Array<{
event: Extract<AgentStreamEvent, { type: "timeline" }>;
row: AgentTimelineRow;
}> = [];
const timelineEvents: ReplayedTimelineRow[] = [];
const providerSubagentEvents: AgentManagerEvent[] = [];
for (const event of historySubagentEvents) {
const update = this.providerSubagents.apply(agent.id, event.provider, event.event);
@@ -5176,23 +5249,23 @@ export class AgentManager {
this.dispatch(managerEvent);
}
}
for (const event of historyEvents) {
const row = this.recordTimeline(
agent.id,
event.item,
event.timestamp ? { timestamp: event.timestamp } : undefined,
);
for (const entry of historyEntries) {
const replayed = this.replayProviderHistoryEntry(agent, entry);
if (!replayed) continue;
if (deferredBroadcast) {
timelineEvents.push({ event, row });
timelineEvents.push(replayed);
} else if (broadcast) {
this.dispatchStream(agent.id, event, {
seq: row.seq,
this.dispatchStream(agent.id, replayed.event, {
seq: replayed.row.seq,
epoch: this.timelineStore.getEpoch(agent.id),
timestamp: row.timestamp,
timestamp: replayed.row.timestamp,
});
}
}
agent.historyPrimed = true;
if (historyEntries.some((entry) => entry.type === "session_metrics")) {
this.emitState(agent);
}
if (typeof broadcast !== "function" || !broadcast()) {
return;
@@ -5272,6 +5345,8 @@ export class AgentManager {
);
}
event = this.settleTurnMetrics({ agent, event, options, terminalDisposition });
const flags: StreamEventFlags = { shouldDispatchEvent: true, shouldNotifyWaiters: true };
const dispatchPromise = this.dispatchStreamEventByType({
@@ -5380,6 +5455,23 @@ export class AgentManager {
this.emitState(agent);
}
private onStreamThinkingOptionChanged(params: {
agent: ActiveManagedAgent;
event: Extract<AgentStreamEvent, { type: "thinking_option_changed" }>;
flags: StreamEventFlags;
}): void {
const { agent, event, flags } = params;
agent.config.thinkingOptionId = event.thinkingOptionId ?? undefined;
if (agent.runtimeInfo) {
agent.runtimeInfo = {
...agent.runtimeInfo,
thinkingOptionId: event.thinkingOptionId,
};
}
flags.shouldDispatchEvent = false;
this.emitState(agent);
}
private dispatchStreamEventByType(params: {
agent: ActiveManagedAgent;
event: AgentStreamEvent;
@@ -5399,6 +5491,12 @@ export class AgentManager {
agent.lastUsage = event.usage;
this.emitState(agent);
return undefined;
case "session_metrics_updated":
// Clients read these from the agent snapshot; the event itself is not on the wire.
agent.sessionMetrics = sanitizeAgentMetrics(event.metrics);
flags.shouldDispatchEvent = false;
this.emitState(agent);
return undefined;
case "mode_changed":
this.applyObservedMode(agent, event.currentModeId);
agent.availableModes = event.availableModes;
@@ -5421,15 +5519,7 @@ export class AgentManager {
this.emitState(agent);
return undefined;
case "thinking_option_changed":
agent.config.thinkingOptionId = event.thinkingOptionId ?? undefined;
if (agent.runtimeInfo) {
agent.runtimeInfo = {
...agent.runtimeInfo,
thinkingOptionId: event.thinkingOptionId,
};
}
flags.shouldDispatchEvent = false;
this.emitState(agent);
this.onStreamThinkingOptionChanged({ agent, event, flags });
return undefined;
case "options_changed":
this.onStreamOptionsChanged({ agent, patch: event.patch, flags });
@@ -5530,6 +5620,36 @@ export class AgentManager {
}
}
/**
* Decides what a completed turn shows and records it on the turn's footer row, so
* the live event and a later timeline fetch agree.
*/
private settleTurnMetrics(params: {
agent: ActiveManagedAgent;
event: AgentStreamEvent;
options: HandleStreamEventOptions | undefined;
terminalDisposition: ActiveTurnTerminalDisposition;
}): AgentStreamEvent {
if (params.event.type !== "turn_completed") return params.event;
const { agent } = params;
const { metrics: reported, ...event } = params.event;
// A replayed turn may have run on another model than the agent has now.
const model = params.options?.fromHistory
? null
: (agent.runtimeInfo?.model ?? agent.config.model);
const metrics = withModelMetric(sanitizeAgentMetrics(reported), model);
if (metrics.length === 0) return event;
if (params.terminalDisposition !== "stale") {
this.stampTurnMetrics(agent.id, metrics, event.turnId);
}
return { ...event, metrics };
}
private stampTurnMetrics(agentId: string, metrics: AgentMetric[], turnId?: string): void {
const row = this.timelineStore.stampTurnMetrics(agentId, metrics, { turnId });
if (row) this.enqueueDurableTimelineUpdate(agentId, row);
}
private onStreamTurnCompleted(params: {
agent: ActiveManagedAgent;
event: Extract<AgentStreamEvent, { type: "turn_completed" }>;
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import { sanitizeAgentMetrics, withModelMetric } from "./agent-metrics.js";
describe("sanitizeAgentMetrics", () => {
it("keeps well-formed metrics in the provider's order", () => {
const metrics = [
{ label: "Model", value: "GPT-5.4" },
{ label: "Cache", value: "82%", tone: "ok" },
];
expect(sanitizeAgentMetrics(metrics)).toEqual(metrics);
});
it("drops rows a client could not render and keeps the rest", () => {
expect(
sanitizeAgentMetrics([
{ label: "Cost", value: 1.23 },
"junk",
null,
{ label: "", value: "empty label" },
{ value: "no label" },
{ label: "Elapsed", value: "1.2s", extra: true },
]),
).toEqual([{ label: "Elapsed", value: "1.2s" }]);
});
it("drops a tone clients do not know and keeps the row", () => {
expect(sanitizeAgentMetrics([{ label: "Cache", value: "82%", tone: "sparkly" }])).toEqual([
{ label: "Cache", value: "82%" },
]);
});
it("treats anything that is not a list as no metrics", () => {
expect(sanitizeAgentMetrics(undefined)).toEqual([]);
expect(sanitizeAgentMetrics({ label: "Model", value: "GPT-5.4" })).toEqual([]);
});
it("bounds what one provider can put on every snapshot", () => {
const flood = Array.from({ length: 500 }, (_, index) => ({
label: `Metric ${index}`,
value: "x".repeat(10_000),
}));
const sanitized = sanitizeAgentMetrics(flood);
expect(sanitized).toHaveLength(32);
expect(sanitized[0].value).toHaveLength(256);
});
});
describe("withModelMetric", () => {
it("leads with the model when no row names one", () => {
expect(withModelMetric([{ label: "Elapsed", value: "1.2s" }], "gpt-5.4")).toEqual([
{ label: "Model", value: "gpt-5.4" },
{ label: "Elapsed", value: "1.2s" },
]);
});
it("leaves a provider's own model row alone, whatever its case", () => {
const metrics = [{ label: "model", value: "GPT-5.4 (fast)" }];
expect(withModelMetric(metrics, "gpt-5.4")).toEqual(metrics);
});
it("adds nothing when the model is unknown", () => {
expect(withModelMetric([], null)).toEqual([]);
expect(withModelMetric([], undefined)).toEqual([]);
});
});
@@ -0,0 +1,45 @@
import type { AgentMetric } from "./agent-sdk-types.js";
const MAX_METRICS = 32;
const MAX_TEXT_LENGTH = 256;
const TONES: ReadonlySet<unknown> = new Set(["default", "ok", "warning", "danger"]);
function isTone(value: unknown): value is NonNullable<AgentMetric["tone"]> {
return TONES.has(value);
}
function sanitizeMetric(value: unknown): AgentMetric | null {
if (typeof value !== "object" || value === null) return null;
const { label, value: text, tone } = value as Record<string, unknown>;
if (typeof label !== "string" || label.length === 0 || typeof text !== "string") return null;
return {
label: label.slice(0, MAX_TEXT_LENGTH),
value: text.slice(0, MAX_TEXT_LENGTH),
...(isTone(tone) ? { tone } : {}),
};
}
/**
* The one place provider metrics are checked. Providers build them from SDK and
* process output Paseo does not control, and one malformed row would make a
* client reject the whole snapshot, turn event, or timeline page that carries it.
*/
export function sanitizeAgentMetrics(value: unknown): AgentMetric[] {
if (!Array.isArray(value)) return [];
const metrics: AgentMetric[] = [];
for (const entry of value) {
const metric = sanitizeMetric(entry);
if (metric) metrics.push(metric);
if (metrics.length === MAX_METRICS) break;
}
return metrics;
}
/** Every completed turn can say which model ran it, even for providers that report nothing. */
export function withModelMetric(
metrics: AgentMetric[],
model: string | null | undefined,
): AgentMetric[] {
if (!model || metrics.some((metric) => metric.label.toLowerCase() === "model")) return metrics;
return [{ label: "Model", value: model }, ...metrics];
}
@@ -496,6 +496,38 @@ describe("toAgentPayload", () => {
).not.toHaveProperty("lastError");
});
it("shows session metrics on a live agent and on the same agent once it is closed", () => {
const sessionMetrics = [
{ label: "Cost", value: "$1.23" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
const agent = createManagedAgent({
provider: "codex",
config: { provider: "codex" },
sessionMetrics,
});
const record = toStoredAgentRecord(agent);
expect(toAgentPayload(agent).sessionMetrics).toEqual(sessionMetrics);
expect(record.sessionMetrics).toEqual(sessionMetrics);
expect(buildStoredAgentPayload(record, ["codex"], ownOptionsOnly).sessionMetrics).toEqual(
sessionMetrics,
);
});
it("omits session metrics for an agent whose provider reports none", () => {
const agent = createManagedAgent({ provider: "codex", config: { provider: "codex" } });
const record = toStoredAgentRecord(agent);
expect(toAgentPayload(agent)).not.toHaveProperty("sessionMetrics");
expect(record).not.toHaveProperty("sessionMetrics");
expect(buildStoredAgentPayload(record, ["codex"], ownOptionsOnly)).not.toHaveProperty(
"sessionMetrics",
);
expect(toAgentPayload({ ...agent, sessionMetrics: [] })).not.toHaveProperty("sessionMetrics");
});
it("omits lastUsage when not available", () => {
const agent = createManagedAgent({ lastUsage: undefined });
const payload = toAgentPayload(agent);
@@ -9,6 +9,7 @@ import type {
AgentCapabilityFlags,
AgentOptionControl,
AgentMetadata,
AgentMetric,
AgentMode,
AgentPermissionRequest,
AgentPersistenceHandle,
@@ -102,6 +103,7 @@ export function toStoredAgentRecord(
runtimeInfo,
controls: normalizeControls(agent.controls),
persistence,
...projectSessionMetrics(agent.sessionMetrics),
lastError: agent.lastError ?? undefined,
requiresAttention: agent.attention.requiresAttention,
attentionReason: agent.attention.requiresAttention ? agent.attention.attentionReason : null,
@@ -166,6 +168,7 @@ export function toAgentPayload(
metadata: agent.metadata,
archivedAt: options?.archivedAt ?? null,
...visibilityFlags(agent),
...projectSessionMetrics(agent.sessionMetrics),
};
const usageScopeKey = projectUsageScopeKey(agent);
@@ -328,6 +331,7 @@ export function buildStoredAgentPayload(
labels: normalizeLabels(record.labels),
metadata: record.metadata,
...(typeof record.lastError === "string" ? { lastError: record.lastError } : {}),
...projectSessionMetrics(record.sessionMetrics),
...(providerAvailable ? {} : { providerUnavailable: true }),
};
}
@@ -586,6 +590,13 @@ function sanitizeMetadataArray(value: unknown): AgentMetadata[] | undefined {
return sanitized.length > 0 ? sanitized : undefined;
}
/** A session with no metrics carries no field, on the wire and on disk. */
function projectSessionMetrics(metrics: AgentMetric[] | undefined): {
sessionMetrics?: AgentMetric[];
} {
return metrics?.length ? { sessionMetrics: metrics.map((metric) => ({ ...metric })) } : {};
}
type UsageNumericField = Exclude<keyof AgentUsage, never>;
function assignFiniteNumber(
@@ -1,4 +1,5 @@
import type {
AgentMetric,
AgentOptionControl,
AgentOptionSelectControl,
AgentOptionToggleControl,
@@ -19,6 +20,7 @@ import type {
import type { PaseoToolCatalog } from "./tools/types.js";
export type {
AgentMetric,
AgentOptionControl,
AgentOptionSelectControl,
AgentOptionToggleControl,
@@ -423,8 +425,17 @@ export type AgentTimelineItem =
export type AgentStreamEvent =
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
| { type: "turn_started"; provider: AgentProvider; turnId?: string }
| { type: "turn_completed"; provider: AgentProvider; usage?: AgentUsage; turnId?: string }
| {
type: "turn_completed";
provider: AgentProvider;
usage?: AgentUsage;
turnId?: string;
/** Shown on the completed turn's footer. */
metrics?: AgentMetric[];
}
| { type: "usage_updated"; provider: AgentProvider; usage: AgentUsage; turnId?: string }
/** Full replacement of the metrics shown for the session. An empty list clears them. */
| { type: "session_metrics_updated"; provider: AgentProvider; metrics: AgentMetric[] }
| {
type: "mode_changed";
provider: AgentProvider;
@@ -614,6 +625,8 @@ export interface ImportProviderSessionContext {
export interface ImportedTimelineEntry {
item: AgentTimelineItem;
timestamp?: string;
/** Set on the last entry of a turn the provider reported stats for. */
turnMetrics?: AgentMetric[];
}
export interface ImportedProviderSession {
@@ -621,6 +634,7 @@ export interface ImportedProviderSession {
config: AgentSessionConfig;
persistence: AgentPersistenceHandle;
timeline: ImportedTimelineEntry[];
sessionMetrics?: AgentMetric[];
providerSubagentEvents?: Extract<AgentStreamEvent, { type: "provider_subagent" }>[];
}
@@ -127,6 +127,7 @@ function createManagedAgent(overrides: ManagedAgentOverrides = {}): ManagedAgent
historyPrimed: overrides.historyPrimed ?? true,
lastUserMessageAt: overrides.lastUserMessageAt ?? core.now,
lastUsage: overrides.lastUsage,
sessionMetrics: overrides.sessionMetrics,
lastError: overrides.lastError,
};
}
@@ -315,6 +316,21 @@ describe("AgentStorage", () => {
});
});
test("session metrics survive a daemon restart and follow the latest snapshot", async () => {
const sessionMetrics = [
{ label: "Cost", value: "$1.23" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
await storage.applySnapshot(createManagedAgent({ id: "agent-metrics", sessionMetrics }));
const reloaded = new AgentStorage(storagePath, createTestLogger());
expect((await reloaded.get("agent-metrics"))?.sessionMetrics).toEqual(sessionMetrics);
await reloaded.applySnapshot(createManagedAgent({ id: "agent-metrics" }));
const cleared = new AgentStorage(storagePath, createTestLogger());
expect(await cleared.get("agent-metrics")).not.toHaveProperty("sessionMetrics");
});
test("a record stored with featureValues loads them in providerOptions", async () => {
await storage.applySnapshot(createManagedAgent({ id: "agent-legacy" }));
const file = findRecordFile(storagePath, "agent-legacy");
@@ -5,7 +5,12 @@ import type { Logger } from "pino";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { writeJsonFileAtomic } from "../atomic-file.js";
import { AgentFeatureSchema, AgentOptionControlSchema, AgentStatusSchema } from "../messages.js";
import {
AgentFeatureSchema,
AgentMetricSchema,
AgentOptionControlSchema,
AgentStatusSchema,
} from "../messages.js";
import { toStoredAgentRecord } from "./agent-projections.js";
import type { ManagedAgent } from "./agent-manager.js";
import type { AgentSessionConfig } from "./agent-sdk-types.js";
@@ -77,6 +82,7 @@ const RAW_STORED_AGENT_SCHEMA = z.object({
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. Read-only; becomes controls.
features: z.array(AgentFeatureSchema).optional(),
persistence: PERSISTENCE_HANDLE_SCHEMA,
sessionMetrics: z.array(AgentMetricSchema).optional(),
lastError: z.string().nullable().optional(),
requiresAttention: z.boolean().optional(),
attentionReason: z.enum(["finished", "error", "permission"]).nullable().optional(),
@@ -1,5 +1,5 @@
import type { ProjectedTimelineRow } from "./timeline-projection.js";
import type { AgentTimelineItem } from "./agent-sdk-types.js";
import type { AgentMetric, AgentTimelineItem } from "./agent-sdk-types.js";
export interface AgentTimelineRow {
seq: number;
@@ -7,6 +7,8 @@ export interface AgentTimelineRow {
item: AgentTimelineItem;
readonly turnId?: string;
readonly providerMessageId?: string;
/** Metrics of the turn this row carries the footer for. */
readonly turnMetrics?: AgentMetric[];
}
export interface AgentTimelineCursor {
@@ -245,6 +245,167 @@ describe("projected sequence ownership", () => {
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "gpt-5.5" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
const tool = {
type: "tool_call" as const,
callId: "t",
name: "shell",
error: null,
detail: { type: "plain_text" as const, label: "work" },
};
function turnMetricsByRow(store: InMemoryAgentTimelineStore, agentId: string) {
return store.fetch(agentId).rows.map((row) => row.turnMetrics ?? null);
}
it("puts a turn's metrics on its last assistant message, where its footer shows", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "go" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "First" }, { turnId: "turn-1" });
store.append("a", { ...tool, status: "completed" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "Done" }, { turnId: "turn-1" });
store.append("a", { type: "reasoning", text: "wrap up" }, { turnId: "turn-1" });
const stamped = store.stampTurnMetrics("a", metrics, { turnId: "turn-1" });
expect(stamped).toMatchObject({ seq: 4, item: { text: "Done" }, turnMetrics: metrics });
expect(turnMetricsByRow(store, "a")).toEqual([null, null, null, metrics, null]);
});
it("falls back to the turn's last row when it is a tool call and no message was written", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "go" });
store.append("a", { type: "reasoning", text: "thinking" });
store.append("a", { ...tool, status: "completed" });
store.stampTurnMetrics("a", metrics);
expect(turnMetricsByRow(store, "a")).toEqual([null, null, metrics]);
});
it("leaves the previous turn alone when the completed turn has no footer row", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "one" });
store.append("a", { type: "assistant_message", text: "Answer one" });
store.append("a", { type: "user_message", text: "two" });
store.append("a", { type: "reasoning", text: "thinking" });
expect(store.stampTurnMetrics("a", metrics)).toBeNull();
expect(turnMetricsByRow(store, "a")).toEqual([null, null, null, null]);
});
it("finds the completed turn by id when a newer turn already has rows", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "one" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "Answer one" }, { turnId: "turn-1" });
store.append("a", { type: "user_message", text: "two" }, { turnId: "turn-2" });
store.append("a", { type: "assistant_message", text: "Answer two" }, { turnId: "turn-2" });
store.stampTurnMetrics("a", metrics, { turnId: "turn-1" });
expect(turnMetricsByRow(store, "a")).toEqual([null, metrics, null, null]);
});
it("stamps nothing for a turn that wrote no rows instead of the turn before it", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "one" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "Answer one" }, { turnId: "turn-1" });
expect(store.stampTurnMetrics("a", metrics, { turnId: "turn-2" })).toBeNull();
expect(turnMetricsByRow(store, "a")).toEqual([null, null]);
});
it("keeps the metrics when a late update lands on the stamped row", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "go" }, { turnId: "turn-1" });
store.append("a", { ...tool, status: "running" }, { turnId: "turn-1" });
store.stampTurnMetrics("a", metrics, { turnId: "turn-1" });
store.append("a", { ...tool, status: "completed" }, { turnId: "turn-1" });
expect(store.fetch("a").rows[1]).toMatchObject({
item: { status: "completed" },
turnMetrics: metrics,
});
});
it("keeps the stats on a message whose chunks the projection merges", () => {
const store = new InMemoryAgentTimelineStore();
const at = "2026-11-22T00:00:00.000Z";
store.initialize("a", {
rows: [
{ seq: 1, timestamp: at, item: { type: "user_message", text: "go" } },
{ seq: 2, timestamp: at, item: { type: "assistant_message", text: "Do" } },
{
seq: 3,
timestamp: at,
item: { type: "assistant_message", text: "ne" },
turnMetrics: metrics,
},
],
});
const rows = store.fetch("a").rows;
expect(rows).toHaveLength(2);
expect(rows[1]).toMatchObject({ item: { text: "Done" }, turnMetrics: metrics });
});
it("keeps the stats on a tool card whose updates the projection merges", () => {
const store = new InMemoryAgentTimelineStore();
const at = "2026-11-22T00:00:00.000Z";
store.initialize("a", {
rows: [
{ seq: 1, timestamp: at, item: { type: "user_message", text: "go" } },
{ seq: 2, timestamp: at, item: { ...tool, status: "running" } },
{ seq: 3, timestamp: at, item: { ...tool, status: "completed" }, turnMetrics: metrics },
],
});
const rows = store.fetch("a").rows;
expect(rows).toHaveLength(2);
expect(rows[1]).toMatchObject({ item: { status: "completed" }, turnMetrics: metrics });
});
it("restores stamped rows when a timeline is seeded from stored rows", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("live");
store.append("live", { type: "user_message", text: "go" });
store.append("live", { type: "assistant_message", text: "Done" });
store.stampTurnMetrics("live", metrics);
store.initialize("projected", { rows: store.getRows("live") });
store.initialize("canonical", {
rows: [
{
seq: 1,
timestamp: "2026-11-22T00:00:00.000Z",
item: { type: "user_message", text: "go" },
},
{
seq: 2,
timestamp: "2026-11-22T00:00:01.000Z",
item: { type: "assistant_message", text: "Done" },
turnMetrics: metrics,
},
],
});
expect(turnMetricsByRow(store, "projected")).toEqual([null, metrics]);
expect(turnMetricsByRow(store, "canonical")).toEqual([null, metrics]);
});
});
it("includes transitive tool updates in a contiguous projected tail", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { TimelineProjection, type ProjectedTimelineRow } from "./timeline-projection.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import type { AgentTimelineItem } from "./agent-sdk-types.js";
import type { AgentMetric, AgentTimelineItem } from "./agent-sdk-types.js";
import type {
AgentTimelineFetchOptions,
AgentTimelineFetchResult,
@@ -85,6 +85,15 @@ export class InMemoryAgentTimelineStore {
);
}
/** Records a completed turn's metrics on its footer row. Null when the turn has none. */
stampTurnMetrics(
agentId: string,
metrics: AgentMetric[],
options?: { turnId?: string },
): AgentTimelineRow | null {
return this.requireState(agentId).projection.stampTurnMetrics(metrics, options?.turnId);
}
getEpoch(agentId: string): string {
return this.requireState(agentId).epoch;
}
@@ -2219,6 +2219,73 @@ describe("PluginAgentClientRegistry", () => {
expect(harness.inputs.map((input) => input.type)).toContain("session.close");
});
test("carries a plugin's session and turn metrics into the agent stream", async () => {
const turnMetrics = [
{ label: "Model", value: "plugin-model" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
const sessionMetrics = [{ label: "Cost", value: "$1.23" }];
const harness = createProviderHarness({
handleInput: async (input, emit) => {
if (input.type !== "session.prompt") return false;
emit({
type: "session.prompt_result",
sessionId: input.sessionId,
clientMessageId: input.prompt.clientMessageId,
result: { type: "turn", turnId: "turn-1" },
});
emit({
type: "session.turn",
sessionId: input.sessionId,
turnId: "turn-1",
state: "started",
});
emit({
type: "session.turn",
sessionId: input.sessionId,
turnId: "turn-1",
state: "completed",
metrics: turnMetrics,
});
emit({ type: "session.metrics", sessionId: input.sessionId, metrics: sessionMetrics });
return true;
},
});
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([harness.registration]);
const client = registry.clients()[harness.registration.id]!;
const session = await client.createSession({ provider: harness.registration.id, cwd: "/tmp" });
const events: AgentStreamEvent[] = [];
const unsubscribe = session.subscribe((event) => events.push(event));
try {
await session.startTurn("hello", { clientMessageId: "client-message" });
expect(eventsOfType(events, "turn_completed")).toEqual([
{
type: "turn_completed",
provider: "plugin-direct",
turnId: "turn-1",
metrics: turnMetrics,
},
]);
expect(eventsOfType(events, "session_metrics_updated")).toEqual([
{ type: "session_metrics_updated", provider: "plugin-direct", metrics: sessionMetrics },
]);
const history: AgentStreamEvent[] = [];
for await (const event of session.streamHistory()) history.push(event);
expect(eventsOfType(history, "turn_completed")).toContainEqual({
type: "turn_completed",
provider: "plugin-direct",
turnId: "turn-1",
metrics: turnMetrics,
});
} finally {
unsubscribe();
await session.close();
registry.replace([]);
}
});
test("delivers a supported steer to the active turn", async () => {
const harness = createProviderHarness({
capabilities: [...CAPABILITIES, "prompt.steer"],
@@ -2879,6 +2946,63 @@ test("plugin provider import launches with runtime MCP servers and returns only
}
});
test("plugin provider import keeps the stats the plugin reported with its history", async () => {
const turnMetrics = [{ label: "Model", value: "plugin-model" }];
const sessionMetrics = [{ label: "Cost", value: "$1.23" }];
const harness = createProviderHarness({
handleInput: async (input, emit) => {
if (input.type !== "session.open" || input.history !== "replay") return false;
emit({
type: "session.opened",
requestId: input.requestId,
sessionId: input.sessionId,
capabilities: CAPABILITIES,
restoration: "core",
persistence: input.persistence ?? { version: 1, data: { token: "root" } },
cwd: input.config.cwd,
});
emit({
type: "timeline.item",
sessionId: input.sessionId,
item: { type: "user_message", id: "user-1", text: "go" },
});
emit({
type: "timeline.item",
sessionId: input.sessionId,
item: { type: "assistant_message", id: "answer-1", text: "Done" },
});
emit({
type: "session.turn",
sessionId: input.sessionId,
turnId: "turn-1",
state: "completed",
metrics: turnMetrics,
});
emit({ type: "session.metrics", sessionId: input.sessionId, metrics: sessionMetrics });
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
return true;
},
});
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([harness.registration]);
const client = registry.clients()[harness.registration.id]!;
const storedConfig = { provider: harness.registration.id, cwd: "/project" };
try {
const imported = await client.importSession!(
{ providerHandleId: 'plugin:{"version":1,"data":{"token":"root"}}', cwd: "/project" },
{ config: storedConfig, storedConfig },
);
expect(imported.sessionMetrics).toEqual(sessionMetrics);
expect(imported.timeline.map((entry) => entry.turnMetrics ?? null)).toEqual([
null,
turnMetrics,
]);
await imported.session.close();
} finally {
await registry.shutdown();
}
});
test("resumes a goose session saved by the generic ACP provider", async () => {
const logger = createTestLogger();
const harness = createProviderHarness();
@@ -74,6 +74,7 @@ import {
createProviderEnv,
type ProviderRuntimeSettings,
} from "./provider-launch-config.js";
import { ImportedHistory } from "./provider-session-import.js";
import { readPluginOptionState } from "./plugin-provider-options.js";
import {
buildCommandResolutionDiagnosticRows,
@@ -1201,8 +1202,7 @@ class PluginAgentClient implements AgentClient {
session,
config: { ...context.storedConfig, provider: this.provider, cwd: input.cwd },
persistence,
timeline: session.timelineHistory(),
providerSubagentEvents: session.subagentHistory(),
...session.importedHistory(),
};
}
@@ -1629,13 +1629,10 @@ class PluginAgentSession implements AgentSession {
);
}
subagentHistory(): NonNullable<ImportedProviderSession["providerSubagentEvents"]> {
return this.history
.read(this.provider)
.filter(
(event): event is Extract<AgentStreamEvent, { type: "provider_subagent" }> =>
event.type === "provider_subagent",
);
importedHistory(): ReturnType<ImportedHistory["result"]> {
const history = new ImportedHistory();
for (const event of this.history.read(this.provider)) history.add(event);
return history.result();
}
attachChild(
@@ -1694,6 +1691,14 @@ class PluginAgentSession implements AgentSession {
turnId: event.turnId,
},
];
case "session.metrics":
return [
{
type: "session_metrics_updated",
provider: this.provider,
metrics: event.metrics.map((metric) => ({ ...metric })),
},
];
case "timeline.item":
return this.translateTimeline(event);
case "session.permission":
@@ -1720,7 +1725,12 @@ class PluginAgentSession implements AgentSession {
}
if (this.currentTurnId === event.turnId) this.currentTurnId = null;
if (event.state === "completed") {
return { type: "turn_completed", provider: this.provider, turnId: event.turnId };
return {
type: "turn_completed",
provider: this.provider,
turnId: event.turnId,
...(event.metrics ? { metrics: event.metrics.map((metric) => ({ ...metric })) } : {}),
};
}
if (event.state === "canceled") {
return {
@@ -64,4 +64,41 @@ describe("importSessionFromPersistence", () => {
nativeHandle: SESSION_FILE,
});
});
it("keeps the stats the provider reports in its history", async () => {
const cwd = "/Users/dev/code/project";
const imported = await importSessionFromPersistence({
provider: "omp",
request: { providerHandleId: SESSION_FILE, cwd },
context: context(cwd),
resumeSession: async () =>
({
async *streamHistory() {
yield { type: "timeline", provider: "omp", item: { type: "user_message", text: "Hi" } };
yield {
type: "timeline",
provider: "omp",
item: { type: "assistant_message", text: "Done" },
};
yield {
type: "turn_completed",
provider: "omp",
metrics: [{ label: "Elapsed", value: "1.2s" }],
};
yield {
type: "session_metrics_updated",
provider: "omp",
metrics: [{ label: "Cost", value: "$0.011" }],
};
},
describePersistence: () => null,
}) as unknown as AgentSession,
});
expect(imported.timeline.map((entry) => entry.turnMetrics ?? null)).toEqual([
null,
[{ label: "Elapsed", value: "1.2s" }],
]);
expect(imported.sessionMetrics).toEqual([{ label: "Cost", value: "$0.011" }]);
});
});
@@ -1,5 +1,7 @@
import { sanitizeAgentMetrics } from "./agent-metrics.js";
import type {
AgentClient,
AgentMetric,
AgentPersistenceHandle,
AgentProvider,
AgentSessionConfig,
@@ -39,8 +41,7 @@ export async function importSessionFromPersistence(input: {
session,
config: storedConfig,
persistence: canonicalImportPersistence(persistence, session),
timeline: history.timeline,
providerSubagentEvents: history.providerSubagentEvents,
...history,
};
}
@@ -81,24 +82,51 @@ function buildImportPersistenceHandle(
};
}
async function collectImportedHistory(events: AsyncGenerator<AgentStreamEvent>): Promise<{
timeline: ImportedTimelineEntry[];
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[];
}> {
const timeline: ImportedTimelineEntry[] = [];
const providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] = [];
for await (const event of events) {
if (event.type === "provider_subagent") {
providerSubagentEvents.push(event);
continue;
/** What an import keeps of a provider's replayed history, whichever way the events arrive. */
export class ImportedHistory {
readonly timeline: ImportedTimelineEntry[] = [];
readonly providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] = [];
sessionMetrics: AgentMetric[] | undefined;
add(event: AgentStreamEvent): void {
switch (event.type) {
case "provider_subagent":
this.providerSubagentEvents.push(event);
return;
case "session_metrics_updated":
this.sessionMetrics = sanitizeAgentMetrics(event.metrics);
return;
case "turn_completed": {
const metrics = sanitizeAgentMetrics(event.metrics);
const last = this.timeline.at(-1);
if (last && metrics.length > 0) last.turnMetrics = metrics;
return;
}
case "timeline":
this.timeline.push({
item: event.item,
...(event.timestamp ? { timestamp: event.timestamp } : {}),
});
return;
default:
return;
}
if (event.type !== "timeline") {
continue;
}
timeline.push({
item: event.item,
...(event.timestamp ? { timestamp: event.timestamp } : {}),
});
}
return { timeline, providerSubagentEvents };
result(): Pick<
ImportedProviderSession,
"timeline" | "sessionMetrics" | "providerSubagentEvents"
> {
return {
timeline: this.timeline,
...(this.sessionMetrics ? { sessionMetrics: this.sessionMetrics } : {}),
providerSubagentEvents: this.providerSubagentEvents,
};
}
}
async function collectImportedHistory(events: AsyncGenerator<AgentStreamEvent>) {
const history = new ImportedHistory();
for await (const event of events) history.add(event);
return history.result();
}
@@ -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,
@@ -2542,6 +2544,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;
@@ -3862,6 +3865,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 },
{
@@ -5373,6 +5377,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
@@ -5417,7 +5440,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),
],
};
}
}
@@ -0,0 +1,173 @@
import { describe, expect, it } from "vitest";
import {
cacheHitTone,
computeCacheHitPercent,
formatMetricCost,
formatMetricDuration,
formatMetricRate,
formatMetricTokens,
formatTokenPair,
mergeTimeIntervals,
} from "./metrics.js";
describe("formatMetricDuration", () => {
it.each([
[1, "<0.1s"],
[49, "<0.1s"],
[50, "0.1s"],
[0, "0.0s"],
[1_240, "1.2s"],
[12_350, "12.4s"],
[59_940, "59.9s"],
[59_960, "1m 0s"],
[60_000, "1m 0s"],
[125_400, "2m 5s"],
[3_725_000, "62m 5s"],
])("shows %dms as %s", (ms, expected) => {
expect(formatMetricDuration(ms)).toBe(expected);
});
it.each([-1, Number.NaN, Number.POSITIVE_INFINITY])("has nothing to show for %d", (ms) => {
expect(formatMetricDuration(ms)).toBeNull();
});
});
describe("formatMetricTokens", () => {
it.each([
[0, "0"],
[7, "7"],
[999, "999"],
[999.6, "1.0K"],
[1_000, "1.0K"],
[1_234, "1.2K"],
[18_900, "18.9K"],
[999_949, "999.9K"],
[999_950, "1.0M"],
[1_234_567, "1.2M"],
[2_500_000_000, "2500.0M"],
])("shows %d as %s", (tokens, expected) => {
expect(formatMetricTokens(tokens)).toBe(expected);
});
it.each([-5, Number.NaN, Number.POSITIVE_INFINITY])("counts %d as no tokens", (tokens) => {
expect(formatMetricTokens(tokens)).toBe("0");
});
});
describe("formatTokenPair", () => {
it("shows input going up and output coming down", () => {
expect(formatTokenPair(18_900, 2_300)).toBe("18.9K ↑ · 2.3K ↓");
expect(formatTokenPair(120, 0)).toBe("120 ↑ · 0 ↓");
});
});
describe("formatMetricRate", () => {
it.each([
[163.4, "~163 tok/s"],
[1, "~1 tok/s"],
[5_000, "~5000 tok/s"],
])("shows %d as %s", (rate, expected) => {
expect(formatMetricRate(rate)).toBe(expected);
});
it.each([0, -3, 0.2, 5_000.1, Number.NaN, Number.POSITIVE_INFINITY])(
"has no believable rate for %d",
(rate) => {
expect(formatMetricRate(rate)).toBeNull();
},
);
});
describe("formatMetricCost", () => {
it.each([
[0.042, "$0.042"],
[0.0421, "$0.042"],
[0.5, "$0.500"],
[0.0004, "<$0.001"],
[0.9996, "$1.00"],
[1.234, "$1.23"],
[1234.5, "$1234.50"],
])("shows %d as %s", (usd, expected) => {
expect(formatMetricCost(usd)).toBe(expected);
});
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])("has no cost for %d", (usd) => {
expect(formatMetricCost(usd)).toBeNull();
});
});
describe("computeCacheHitPercent", () => {
it("is the share of prompt tokens read from cache", () => {
expect(computeCacheHitPercent({ input: 100, cacheRead: 820, cacheWrite: 80 })).toBe(82);
expect(computeCacheHitPercent({ input: 2, cacheRead: 1, cacheWrite: 0 })).toBe(33);
expect(computeCacheHitPercent({ input: 100, cacheRead: 0, cacheWrite: 0 })).toBe(0);
expect(computeCacheHitPercent({ input: 0, cacheRead: 500, cacheWrite: 0 })).toBe(100);
});
it("is unknown when the turn sent no prompt tokens", () => {
expect(computeCacheHitPercent({ input: 0, cacheRead: 0, cacheWrite: 0 })).toBeNull();
});
it("is unknown when a count is not a usable number", () => {
expect(computeCacheHitPercent({ input: Number.NaN, cacheRead: 10, cacheWrite: 0 })).toBeNull();
expect(computeCacheHitPercent({ input: 10, cacheRead: -4, cacheWrite: 0 })).toBeNull();
});
it("marks a cache that served at least half the prompt as good", () => {
expect(cacheHitTone(50)).toBe("ok");
expect(cacheHitTone(82)).toBe("ok");
expect(cacheHitTone(49)).toBeUndefined();
});
});
describe("mergeTimeIntervals", () => {
it("unions overlapping and touching intervals so shared time counts once", () => {
expect(
mergeTimeIntervals([
[50, 80],
[0, 10],
[5, 20],
[20, 30],
[60, 70],
]),
).toEqual([
[0, 30],
[50, 80],
]);
});
it("keeps separate intervals apart", () => {
expect(
mergeTimeIntervals([
[0, 1],
[2, 3],
]),
).toEqual([
[0, 1],
[2, 3],
]);
expect(mergeTimeIntervals([])).toEqual([]);
});
it("drops intervals that never ran forward", () => {
expect(
mergeTimeIntervals([
[10, 5],
[Number.NaN, 4],
[1, 2],
]),
).toEqual([[1, 2]]);
});
it("leaves the caller's intervals untouched", () => {
const intervals: [number, number][] = [
[5, 9],
[0, 6],
];
mergeTimeIntervals(intervals);
expect(intervals).toEqual([
[5, 9],
[0, 6],
]);
});
});
@@ -0,0 +1,123 @@
import type { AgentMetric } from "../agent-sdk-types.js";
/**
* Formatting shared by providers that report session and turn metrics, so the
* same quantity reads the same way whichever provider measured it.
*
* Formatters return `null` when there is nothing believable to show; the caller
* leaves that metric out.
*/
export type TimeInterval = readonly [start: number, end: number];
const MAX_PLAUSIBLE_TOKENS_PER_SECOND = 5000;
const CACHE_HIT_OK_PERCENT = 50;
export function formatMetricDuration(ms: number): string | null {
if (!Number.isFinite(ms) || ms < 0) {
return null;
}
if (ms > 0 && ms < 50) {
return "<0.1s";
}
const tenths = Math.round(ms / 100);
if (tenths < 600) {
return `${(tenths / 10).toFixed(1)}s`;
}
const seconds = Math.round(ms / 1000);
return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
}
export function formatMetricTokens(tokens: number): string {
if (!Number.isFinite(tokens) || tokens <= 0) {
return "0";
}
const count = Math.round(tokens);
if (count < 1000) {
return String(count);
}
const tenthsOfThousands = Math.round(count / 100);
if (tenthsOfThousands < 10_000) {
return `${(tenthsOfThousands / 10).toFixed(1)}K`;
}
return `${(Math.round(count / 100_000) / 10).toFixed(1)}M`;
}
export function formatTokenPair(input: number, output: number): string {
return `${formatMetricTokens(input)} ↑ · ${formatMetricTokens(output)} ↓`;
}
/** Rates above the plausibility cap come from a bad timestamp, not a fast model. */
export function formatMetricRate(tokensPerSecond: number): string | null {
if (!Number.isFinite(tokensPerSecond) || tokensPerSecond > MAX_PLAUSIBLE_TOKENS_PER_SECOND) {
return null;
}
const rounded = Math.round(tokensPerSecond);
return rounded > 0 ? `~${rounded} tok/s` : null;
}
export function formatMetricCost(usd: number): string | null {
if (!Number.isFinite(usd) || usd <= 0) {
return null;
}
if (usd < 0.0005) {
return "<$0.001";
}
// 0.9995 is where three decimals would round up to "$1.000".
return usd < 0.9995 ? `$${usd.toFixed(3)}` : `$${usd.toFixed(2)}`;
}
/** The share of prompt tokens served from cache, as a whole percent. */
export function computeCacheHitPercent(tokens: {
input: number;
cacheRead: number;
cacheWrite: number;
}): number | null {
const counts = [tokens.input, tokens.cacheRead, tokens.cacheWrite];
if (counts.some((count) => !Number.isFinite(count) || count < 0)) {
return null;
}
const prompt = tokens.input + tokens.cacheRead + tokens.cacheWrite;
return prompt > 0 ? Math.round((tokens.cacheRead / prompt) * 100) : null;
}
export function cacheHitTone(percent: number): AgentMetric["tone"] {
return percent >= CACHE_HIT_OK_PERCENT ? "ok" : undefined;
}
/**
* Unions overlapping or touching intervals, so time shared by parallel work
* (tool calls running side by side) counts once.
*/
export function mergeTimeIntervals(intervals: readonly TimeInterval[]): [number, number][] {
const ordered = intervals
.filter(([start, end]) => Number.isFinite(start) && Number.isFinite(end) && end >= start)
.toSorted((a, b) => a[0] - b[0]);
const merged: [number, number][] = [];
for (const [start, end] of ordered) {
const current = merged.at(-1);
if (current && start <= current[1]) {
current[1] = Math.max(current[1], end);
} else {
merged.push([start, end]);
}
}
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,114 @@
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),
endedOnTools: message.role === "assistant" && message.stopReason === "toolUse",
}
: 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,415 @@
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 of a session with no turns replays nothing", async () => {
const harness = new V2Harness();
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
try {
const history: AgentStreamEvent[] = [];
for await (const event of session.streamHistory!()) history.push(event);
expect(history).toEqual([]);
} 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,29 @@ 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 });
},
);
const metrics = info ? sessionMetrics(info, list) : [];
if (metrics.length > 0) {
events.push({ type: "session_metrics_updated", provider: "opencode", metrics });
}
yield* events;
}
async getRuntimeInfo() {
@@ -488,6 +514,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();
}
@@ -2230,6 +2253,7 @@ export class PiRpcAgentSession implements AgentSession {
});
return;
case "turn_start":
this.firstToken.requestSent(Date.now());
this.activeTurnStarted = true;
this.clearNoTurnBuffers();
if (this.activeTurnStartedEmitted) {
@@ -2252,6 +2276,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 +2312,7 @@ export class PiRpcAgentSession implements AgentSession {
return;
}
case "tool_execution_end": {
this.turnMeter.toolEnded(event.toolCallId, Date.now());
this.handleToolExecutionEnd(event);
return;
}
@@ -2434,6 +2460,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 +2492,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 +2502,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 +2588,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 +2605,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,362 @@
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);
// The request going out starts the clock; the reply's start arrives later, with the headers.
timer.requestSent(5_000);
timer.replyStarted(8_000);
timer.replyUpdated({ type: "text_start" }, 8_050);
expect(timer.replyEnded()).toBe(3_050);
// 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" },
// The first reply's clock starts when the request went out (turn_start, 100.0s), before its
// headers arrived: 0.8s. The second has no turn_start, so it starts at its message_start:
// 0.1s.
{ label: "Average TTFT", value: "0.5s" },
{ 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,163 @@
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),
endedOnTools: message.role === "assistant" && message.stopReason === "toolUse",
}
: 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, on the adapter's clock: from when the request went out
* (`turn_start`) to the reply's first content. A reply's `message_start` only arrives once
* the response headers have, so it stands in for the request only when no `turn_start` came.
*/
export class PiFirstTokenTimer {
private startedAt: number | null = null;
private firstTokenAt: number | null = null;
requestSent(now: number): void {
this.startedAt = now;
this.firstTokenAt = null;
}
replyStarted(now: number): void {
if (this.startedAt === null) this.requestSent(now);
}
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,262 @@
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; endedOnTools?: 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, endedOnTools: message.endedOnTools }
: 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("replayed turns after a turn that ended on tools", () => {
test("claims no total for a turn the transcript cannot tell from a steered one, and none for the turn before it", () => {
const { out } = replay([
{ role: "user", at: 0 },
{ role: "assistant", step: step({ endedAt: 1_000 }), final: false, endedOnTools: true },
{ role: "tool", run: [1_000, 1_500] },
// Live, this prompt steered the turn above, so one turn spans both replies. After a
// stop it would have begun another. The transcript reads the same either way.
{ role: "user", at: 2_000 },
{ role: "assistant", step: step({ endedAt: 3_000 }), final: true },
{ role: "user", at: 4_000 },
{ role: "assistant", step: step({ endedAt: 5_000 }), final: true },
]);
expect(out).toHaveLength(1);
expect(out[0]!.before).toBe(7);
expect(out[0]!.labels).toContain("Elapsed");
});
});
describe("replayed turns after steers queued together", () => {
test("every prompt queued behind a turn that ended on tools shares its doubt", () => {
const { out } = replay([
{ role: "user", at: 0 },
{ role: "assistant", step: step({ endedAt: 1_000 }), final: false, endedOnTools: true },
{ role: "tool", run: [1_000, 1_500] },
{ role: "user", at: 2_000 },
{ role: "user", at: 2_100 },
{ role: "assistant", step: step({ endedAt: 3_000 }), final: true },
]);
expect(out).toEqual([]);
});
});
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,302 @@
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; endedOnTools?: 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;
/** The last reply asked for tools, so the turn may have gone on or been cut off there. */
endedOnTools: boolean;
/**
* A prompt followed a turn that ended on tools. The transcript cannot say whether that
* prompt steered the turn (live, one turn spanning both) or began another after a stop
* (live, only the later steps), so no total is claimed for it.
*/
unclear: 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) {
// Prompts queued behind one another, with no reply between, share the first one's doubt.
const unclear =
this.turn !== null &&
(this.turn.endedOnTools || (this.turn.unclear && this.turn.steps.length === 0));
const closed = this.end();
this.turn = this.open(prompt.startedAt);
this.turn.unclear = unclear;
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.turn.endedOnTools = reply.endedOnTools === true;
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 || turn.unclear) 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,
endedOnTools: false,
unclear: false,
};
}
}
@@ -1,5 +1,5 @@
import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn";
import type { AgentTimelineItem, ToolCallDetail } from "./agent-sdk-types.js";
import type { AgentMetric, AgentTimelineItem, ToolCallDetail } from "./agent-sdk-types.js";
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
@@ -22,6 +22,7 @@ export interface TimelineProjectionEntry {
item: AgentTimelineItem;
turnId?: string;
providerMessageId?: string;
turnMetrics?: AgentMetric[];
timestamp: string;
seqStart: number;
seqEnd: number;
@@ -125,6 +126,7 @@ function makeCanonicalEntries(rows: readonly AgentTimelineRow[]): WorkingEntry[]
timestamp: row.timestamp,
...(row.turnId ? { turnId: row.turnId } : {}),
...(row.providerMessageId ? { providerMessageId: row.providerMessageId } : {}),
...(row.turnMetrics ? { turnMetrics: row.turnMetrics } : {}),
seqStart: row.seq,
seqEnd: row.seq,
sourceSeqRanges: [{ startSeq: row.seq, endSeq: row.seq }],
@@ -155,6 +157,7 @@ function mergeIdentityEntries(existing: WorkingEntry, entry: WorkingEntry): Work
item: mergeToolCallItems(existing.item, entry.item),
timestamp: entry.timestamp,
seqEnd: Math.max(existing.seqEnd, entry.seqEnd),
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
...mergeIdentityMetadata(existing, entry, "tool_lifecycle"),
};
case "plugin":
@@ -295,6 +298,8 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
seqEnd: entry.seqEnd,
sourceSeqRanges: mergeSeqRanges(previous.sourceSeqRanges, entry.sourceSeqRanges),
collapsed: Array.from(collapsedKinds),
// The turn's stats ride on its last row, which is the later chunk of a merged message.
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
};
}
@@ -546,6 +551,40 @@ export class TimelineProjection {
this.rows[index] = { ...this.rows[index], providerMessageId };
return { ...this.rows[index] };
}
/**
* Puts a completed turn's metrics on the row the app hangs that turn's footer on.
* Returns null when the turn has no such row.
*/
stampTurnMetrics(metrics: AgentMetric[], turnId?: string): ProjectedTimelineRow | null {
const index = this.turnFooterRowIndex(turnId);
if (index === null) return null;
this.rows[index] = { ...this.rows[index], turnMetrics: metrics };
return { ...this.rows[index] };
}
// Mirrors the app's footer anchor: the turn's last assistant message, else its
// last row when that row is a tool call.
private turnFooterRowIndex(turnId: string | undefined): number | null {
const last = this.lastRowIndexOfTurn(turnId);
if (last === null) return null;
for (let index = last; index >= 0; index--) {
if (index < last && !continuesProjectedTurn(this.rows[index], this.rows[index + 1])) break;
if (this.rows[index].item.type === "assistant_message") return index;
}
return this.rows[last].item.type === "tool_call" ? last : null;
}
private lastRowIndexOfTurn(turnId: string | undefined): number | null {
const tail = this.rows.length - 1;
if (tail < 0) return null;
if (turnId === undefined) return tail;
const index = this.rows.findLastIndex((row) => row.turnId === turnId);
if (index >= 0) return index;
// Rows replayed from provider history carry no turn id, so the turn is the
// trailing one. A tail owned by another turn means this turn wrote no rows.
return this.rows[tail].turnId === undefined ? tail : null;
}
}
export function projectTimelineRows(input: {
+1
View File
@@ -8677,6 +8677,7 @@ export class Session {
seqStart: entry.seqStart,
seqEnd: entry.seqEnd,
sourceSeqRanges: entry.sourceSeqRanges,
turnMetrics: entry.turnMetrics,
turnId: undefined as string | undefined,
collapsed: (
source
@@ -481,6 +481,42 @@ describe("wire compatibility", () => {
);
});
test("returns turn metrics on the turn's footer row while legacy schemas ignore them", async () => {
const turnMetrics = [
{ label: "Model", value: "GPT-5.4" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
const response = await emitTimelineResponse({
rows: [
{
seq: 1,
timestamp: "2026-05-02T00:00:00.000Z",
item: { type: "user_message", text: "prompt" },
},
{
seq: 2,
timestamp: "2026-05-02T00:00:01.000Z",
item: { type: "assistant_message", text: "done" },
turnMetrics,
},
],
});
expect(
FetchAgentTimelineResponseMessageSchema.parse(response).payload.entries.map(
(entry) => entry.turnMetrics ?? null,
),
).toEqual([null, turnMetrics]);
// A row without metrics sends no field at all.
expect(JSON.parse(JSON.stringify(response)).payload.entries[0]).not.toHaveProperty(
"turnMetrics",
);
expect(LegacyFetchAgentTimelineResponseMessageSchema.parse(response).payload.entries).toEqual([
expect.not.objectContaining({ turnMetrics: expect.anything() }),
expect.not.objectContaining({ turnMetrics: expect.anything() }),
]);
});
test("legacy worktree request shape normalizes to the same internal input as the new shape", async () => {
const workflow = new InMemoryWorktreeWorkflow();
+1 -1
View File
@@ -3,7 +3,7 @@
This plugin implements `ProviderRegistration` directly. It demonstrates connection negotiation,
catalog and session listing, session creation, prompt and command disposition, option controls
with icons (`controls` and `providerOptions`),
persistence and replay, archive actions, and an ordinary child session.
persistence and replay, archive actions, turn and session metrics, and an ordinary child session.
The provider emits versioned `provider-result` timeline items for its root and child sessions.
`index.client.tsx` registers the Zod schema and React Native renderer for those items. The server
@@ -47,6 +47,7 @@ describe("direct provider example", () => {
"prompt.message",
"prompt.command",
"session.configure",
"session.metrics",
"session.persistence",
"session.subsession",
"timeline.plugin",
@@ -165,6 +166,54 @@ describe("direct provider example", () => {
}),
);
expect(events).toContainEqual(expect.objectContaining({ type: "session.persistence" }));
expect(events).toContainEqual({
type: "session.turn",
sessionId: "session-complete",
turnId: "turn-1",
state: "completed",
metrics: [
{ label: "Model", value: "example-1" },
{ label: "Reply", value: "11 characters" },
],
});
expect(events).toContainEqual({
type: "session.metrics",
sessionId: "session-complete",
metrics: [{ label: "Turns", value: "1" }],
});
await connection.close();
});
it("keeps session metrics from a Paseo that does not offer them", async () => {
const connection = await createDirectExampleProvider().connect({
versions: [1],
capabilities: ["prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
await connection.send({
type: "session.open",
requestId: "open-older",
sessionId: "session-older",
config: { cwd: "/repo", env: {}, mcpServers: {}, settings: {}, persist: false },
history: "skip",
});
await connection.send({
type: "session.prompt",
sessionId: "session-older",
prompt: {
clientMessageId: "message-older",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "hello" }] },
},
});
await new Promise<void>((resolve) => queueMicrotask(resolve));
expect(events).toContainEqual(
expect.objectContaining({ type: "session.turn", state: "completed" }),
);
expect(events.filter((event) => event.type === "session.metrics")).toEqual([]);
await connection.close();
});
@@ -21,6 +21,7 @@ const CAPABILITIES = [
"session.archive",
"session.configure",
"session.list",
"session.metrics",
"session.persistence",
"session.subsession",
"session.unarchive",
@@ -309,10 +310,11 @@ function promptSession(
result: { type: "turn", turnId },
});
state.emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" });
const reply = `Echo: ${text}`;
state.emit({
type: "timeline.item",
sessionId: input.sessionId,
item: { type: "assistant_message", id: `assistant-${session.turn}`, text: `Echo: ${text}` },
item: { type: "assistant_message", id: `assistant-${session.turn}`, text: reply },
});
state.emit({
type: "timeline.item",
@@ -336,7 +338,25 @@ function promptSession(
sessionId: input.sessionId,
persistence: session.persistence,
});
state.emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" });
// Values are formatted here: Paseo shows each one as given.
state.emit({
type: "session.turn",
sessionId: input.sessionId,
turnId,
state: "completed",
metrics: [
{ label: "Model", value: session.config.model ?? "example-1" },
{ label: "Reply", value: `${reply.length} characters` },
],
});
// An older Paseo does not offer session metrics and rejects the event.
if (state.capabilities.includes("session.metrics")) {
state.emit({
type: "session.metrics",
sessionId: input.sessionId,
metrics: [{ label: "Turns", value: String(session.turn) }],
});
}
session.activeTurnId = null;
}
+48
View File
@@ -427,6 +427,54 @@ export default function contribute(client: PluginClientContext) {
The same renderer can display items emitted by a provider, a client timeline transformer, or a
daemon timeline append. A renderer does not require a provider implementation.
## Report metrics
Report what your provider measured as `label` and `value` pairs. Paseo shows each value as given,
so format it for reading: `12.4s`, not `12431`. You choose which metrics make sense for your agent.
Add `metrics` to the `completed` turn event. Paseo shows them from the footer of that turn:
```ts
emit({
type: "session.turn",
sessionId,
turnId,
state: "completed",
metrics: [
{ label: "Model", value: "example-1" },
{ label: "Elapsed", value: "12.4s" },
{ label: "Tokens", value: "18.9K ↑ · 2.3K ↓" },
{ label: "Cache", value: "82%", tone: "ok" },
],
});
```
Publish `session.metrics` for totals that cover the whole session. Paseo shows them in the context
window details. Each event replaces the previous list, and an empty list clears it. Add
`session.metrics` to your supported capabilities and publish the event only when it was negotiated:
```ts
if (capabilities.includes("session.metrics")) {
emit({
type: "session.metrics",
sessionId,
metrics: [
{ label: "Turns", value: "7" },
{ label: "Cost", value: "$0.42" },
],
});
}
```
A Paseo from before session metrics does not offer the capability and closes a connection that
sends the event. It ignores `metrics` on a turn, so turn metrics need no check.
Set `tone` to `"ok"`, `"warning"`, or `"danger"` to color a value. When a completed turn has no
`Model` metric, Paseo adds the session's model.
When `history` is `"replay"`, publish each old turn's `completed` event after that turn's items.
Paseo puts the metrics back on the turn's footer.
## Report installation and updates
Add `installation` to your registration and the provider's settings show an **Installation**
+42
View File
@@ -351,6 +351,48 @@ export default function contribute(client: PluginClientContext) {
同一个渲染器可以显示由 Provider、客户端时间线转换器或 daemon 时间线追加发出的条目。渲染器并不需要 Provider 实现。
## 报告指标 {#report-metrics}
把 Provider 测量到的数据以 `label` 和 `value` 的形式报告。Paseo 会原样显示每个值,所以请把它格式化成便于阅读的形式:写 `12.4s`,不要写 `12431`。哪些指标适合你的 Agent,由你决定。
在 `completed` 轮次事件中添加 `metrics`。Paseo 会在该轮次的页脚显示它们:
```ts
emit({
type: "session.turn",
sessionId,
turnId,
state: "completed",
metrics: [
{ label: "Model", value: "example-1" },
{ label: "Elapsed", value: "12.4s" },
{ label: "Tokens", value: "18.9K ↑ · 2.3K ↓" },
{ label: "Cache", value: "82%", tone: "ok" },
],
});
```
对于覆盖整个会话的总计,发布 `session.metrics`。Paseo 会在上下文窗口详情中显示它们。每个事件都会替换之前的列表,空列表会清除它。把 `session.metrics` 加入你支持的能力,并且只在协商成功时发布该事件:
```ts
if (capabilities.includes("session.metrics")) {
emit({
type: "session.metrics",
sessionId,
metrics: [
{ label: "Turns", value: "7" },
{ label: "Cost", value: "$0.42" },
],
});
}
```
不支持会话指标的旧版 Paseo 不会提供这项能力,并且会关闭发送该事件的连接。它会忽略轮次上的 `metrics`,所以轮次指标不需要检查。
把 `tone` 设为 `"ok"`、`"warning"` 或 `"danger"`,可以给值着色。如果已完成的轮次没有 `Model` 指标,Paseo 会添加会话的模型。
当 `history` 为 `"replay"` 时,请在每个旧轮次的条目之后发布该轮次的 `completed` 事件。Paseo 会把指标放回该轮次的页脚。
## 报告安装与更新 {#report-installation-and-updates}
在注册中添加 `installation`,Provider 的设置中就会出现 **安装** 部分。用户可以看到你的 CLI 是否已安装、是哪个版本、是否有可用更新,以及一个 **更新** 按钮,它会运行你的更新程序并显示其输出。每个成员都是可选的,只声明你的 CLI 支持的部分:
+2
View File
@@ -419,6 +419,8 @@ configuration, persistence, permissions, and failures are events.
Use the single `session.prompt` input for messages, structured commands, steering, and command side
effects. Repeat `clientMessageId` on the live user timeline item and publish exactly one matching
`session.prompt_result`. Publish provider-created children as sessions with `parentSessionId`.
Report measurements as `metrics` on a completed `session.turn` and through `session.metrics`. See
[Report metrics](/docs/plugins/providers#report-metrics).
Provider options are one record, `ProviderSessionConfig.providerOptions` on `session.open`. It
includes configured defaults and per-agent overrides; validate and apply it in your provider. Report
+1 -1
View File
@@ -357,7 +357,7 @@ Paseo 为服务端代码提供 `@getpaseo/plugin`、`@getpaseo/plugin/server`、
使用来自 `@getpaseo/plugin/server/provider` 的 `ProviderRegistration` 调用 `server.registerProvider()`。它的连接通过 `send()` 接收输入,并通过 `onEvent()` 发出完整的状态快照。`send()` 只报告是否接受;提示词的处理结果、轮次、配置、持久化、权限和失败都是事件。
消息、结构化命令、引导和命令副作用都使用同一个 `session.prompt` 输入。在实时的用户时间线条目上重复 `clientMessageId`,并恰好发布一个与之匹配的 `session.prompt_result`。把 Provider 创建的子会话发布为带有 `parentSessionId` 的会话。
消息、结构化命令、引导和命令副作用都使用同一个 `session.prompt` 输入。在实时的用户时间线条目上重复 `clientMessageId`,并恰好发布一个与之匹配的 `session.prompt_result`。把 Provider 创建的子会话发布为带有 `parentSessionId` 的会话。通过已完成的 `session.turn` 上的 `metrics` 和 `session.metrics` 报告测量数据,见[报告指标](/docs/plugins/providers#report-metrics)。
Provider 选项是一个记录,即 `session.open` 中的 `ProviderSessionConfig.providerOptions`。它包含配置的默认值和针对单个 Agent 的覆盖值;请在你的 Provider 中校验并应用它。在 `session.config` 中为需要在 Composer 里显示开关或选择器的顶层键报告 `controls`,并在 `providerOptions` 下报告会话正在使用的值。运行中会话的修改会以 `session.configure` 的形式到达,内容在 `changes.providerOptions` 中。配置和合并语义见 [Provider 选项](/docs/sdk/provider-options)。宿主工具以 MCP 服务器的形式出现在完整的会话配置中。