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
+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 |
+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",
@@ -549,6 +550,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;
@@ -724,8 +736,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 }
@@ -1232,6 +1255,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(),
@@ -1552,6 +1582,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
@@ -1562,6 +1593,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
@@ -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"');
@@ -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);
+153 -47
View File
@@ -57,6 +57,7 @@ import {
type SteerResult,
type AgentStreamEvent,
type AgentTimelineItem,
type AgentMetric,
type AgentUsage,
type AgentRuntimeInfo,
type ImportedTimelineEntry,
@@ -66,6 +67,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 +512,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 +595,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,
@@ -1788,7 +1823,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:
@@ -1926,6 +1968,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 +2055,7 @@ export class AgentManager {
lastUserMessageAt: existing.lastUserMessageAt,
historyPrimed: rehydrateFromDisk ? false : preservedHistoryPrimed,
lastUsage: preservedLastUsage,
sessionMetrics: preservedSessionMetrics,
lastError: preservedLastError,
attention: preservedAttention,
restoring: true,
@@ -2469,6 +2513,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 +4504,7 @@ export class AgentManager {
persistence?: AgentPersistenceHandle;
historyPrimed?: boolean;
lastUsage?: AgentUsage;
sessionMetrics?: AgentMetric[];
lastError?: string;
attention?: AttentionState;
/**
@@ -4669,6 +4715,7 @@ export class AgentManager {
metadata?: AgentMetadata;
historyPrimed?: boolean;
lastUsage?: AgentUsage;
sessionMetrics?: AgentMetric[];
lastError?: string;
attention?: AttentionState;
persistence?: AgentPersistenceHandle;
@@ -4722,6 +4769,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 +5125,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 +5153,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 +5167,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 +5200,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 +5213,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 +5224,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 +5235,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 +5331,8 @@ export class AgentManager {
);
}
event = this.settleTurnMetrics({ agent, event, options, terminalDisposition });
const flags: StreamEventFlags = { shouldDispatchEvent: true, shouldNotifyWaiters: true };
const dispatchPromise = this.dispatchStreamEventByType({
@@ -5380,6 +5441,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 +5477,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 +5505,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 +5606,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,
@@ -421,8 +423,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;
@@ -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,128 @@ 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("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"],
@@ -1642,6 +1642,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":
@@ -1668,7 +1676,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 {
@@ -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,106 @@
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;
}
@@ -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 }],
@@ -546,6 +548,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 服务器的形式出现在完整的会话配置中。