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.
This commit is contained in:
Mohamed Boudra
2026-11-22 08:25:42 +01:00
parent 08ad7c7271
commit eda4597aab
33 changed files with 1616 additions and 62 deletions
+19 -1
View File
@@ -219,6 +219,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",
@@ -411,7 +423,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,
@@ -482,6 +483,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(),
@@ -827,6 +834,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"),
@@ -939,6 +947,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({}),
@@ -5134,6 +5143,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,
@@ -645,3 +646,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"');