mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 09:46:05 +00:00
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:
@@ -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);
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user