mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
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.
464 lines
14 KiB
TypeScript
464 lines
14 KiB
TypeScript
import {
|
|
negotiateProviderCapabilities,
|
|
requireProviderCapabilities,
|
|
type ProviderConfigChanges,
|
|
type ProviderConfigState,
|
|
type ProviderOptionControl,
|
|
type ProviderConnection,
|
|
type ProviderEvent,
|
|
type ProviderInput,
|
|
type ProviderPersistence,
|
|
type ProviderRegistration,
|
|
type ProviderSessionConfig,
|
|
} from "@getpaseo/plugin/server/provider";
|
|
import { randomUUID } from "node:crypto";
|
|
import { providerResultKind } from "../shared/provider-result.js";
|
|
|
|
const CAPABILITIES = [
|
|
"prompt.message",
|
|
"prompt.command",
|
|
"prompt.steer",
|
|
"session.archive",
|
|
"session.configure",
|
|
"session.list",
|
|
"session.metrics",
|
|
"session.persistence",
|
|
"session.subsession",
|
|
"session.unarchive",
|
|
"timeline.plugin",
|
|
] as const;
|
|
|
|
const VOICES = [
|
|
{ value: "calm", label: "Calm" },
|
|
{ value: "direct", label: "Direct" },
|
|
];
|
|
|
|
// Which option keys get a composer control. The control holds no value: Paseo reads it from
|
|
// `providerOptions`, in a draft as well as on a running session.
|
|
const CONTROLS: ProviderOptionControl[] = [
|
|
{ type: "toggle", key: "concise", label: "Concise responses", icon: "Zap" },
|
|
{
|
|
type: "select",
|
|
key: "voice",
|
|
label: "Voice",
|
|
icon: "Mic",
|
|
defaultValue: "calm",
|
|
choices: VOICES,
|
|
},
|
|
];
|
|
|
|
interface ExampleSession {
|
|
config: ProviderSessionConfig;
|
|
/** What the session runs with. A key with no value runs its default. */
|
|
options: { concise?: boolean; voice?: string };
|
|
persistence: ProviderPersistence;
|
|
turn: number;
|
|
activeTurnId: string | null;
|
|
}
|
|
|
|
export function createDirectExampleProvider(): ProviderRegistration {
|
|
return {
|
|
id: "direct-example",
|
|
label: "Direct provider example",
|
|
description: "A complete provider implemented directly against Paseo's provider boundary",
|
|
icon: "icon.svg",
|
|
async connect(request) {
|
|
if (!request.versions.includes(1)) throw new Error("Provider protocol version 1 is required");
|
|
return createConnection(negotiateProviderCapabilities(request.capabilities, CAPABILITIES));
|
|
},
|
|
};
|
|
}
|
|
|
|
function createConnection(capabilities: readonly string[]): ProviderConnection {
|
|
const listeners = new Set<(event: ProviderEvent) => void>();
|
|
const sessions = new Map<string, ExampleSession>();
|
|
const archived = new Set<string>();
|
|
let closed = false;
|
|
const emit = (event: ProviderEvent) => {
|
|
if (closed) return;
|
|
for (const listener of listeners) listener(event);
|
|
};
|
|
|
|
return {
|
|
version: 1,
|
|
capabilities,
|
|
async send(input) {
|
|
if (closed) throw new Error("Provider connection is closed");
|
|
validateAdmission(input, { sessions, capabilities });
|
|
queueMicrotask(() => {
|
|
if (!closed) dispatch(input, { sessions, archived, emit, capabilities });
|
|
});
|
|
},
|
|
onEvent(listener) {
|
|
listeners.add(listener);
|
|
return () => listeners.delete(listener);
|
|
},
|
|
async close() {
|
|
if (closed) return;
|
|
closed = true;
|
|
sessions.clear();
|
|
listeners.clear();
|
|
},
|
|
};
|
|
}
|
|
|
|
function validateAdmission(
|
|
input: ProviderInput,
|
|
state: Pick<ExampleState, "sessions" | "capabilities">,
|
|
): void {
|
|
if (input.type === "session.open") {
|
|
if (state.sessions.has(input.sessionId)) {
|
|
throw new Error(`Session already exists: ${input.sessionId}`);
|
|
}
|
|
requireProviderCapabilities(state.capabilities, input);
|
|
return;
|
|
}
|
|
if (!("sessionId" in input)) {
|
|
requireProviderCapabilities(state.capabilities, input);
|
|
return;
|
|
}
|
|
const session = state.sessions.get(input.sessionId);
|
|
if (!session) throw new Error(`Unknown session: ${input.sessionId}`);
|
|
requireProviderCapabilities(state.capabilities, input);
|
|
}
|
|
|
|
interface ExampleState {
|
|
sessions: Map<string, ExampleSession>;
|
|
archived: Set<string>;
|
|
emit(event: ProviderEvent): void;
|
|
capabilities: readonly string[];
|
|
}
|
|
|
|
function dispatch(input: ProviderInput, state: ExampleState): void {
|
|
switch (input.type) {
|
|
case "catalog":
|
|
state.emit({
|
|
type: "catalog",
|
|
requestId: input.requestId,
|
|
catalog: {
|
|
models: [{ id: "example-1", label: "Example 1" }],
|
|
modes: [{ id: "build", label: "Build" }],
|
|
defaultModel: "example-1",
|
|
defaultMode: "build",
|
|
},
|
|
});
|
|
return;
|
|
case "sessions":
|
|
state.emit({
|
|
type: "sessions",
|
|
requestId: input.requestId,
|
|
sessions: [...state.sessions.values()].map((session) => ({
|
|
persistence: session.persistence,
|
|
cwd: session.config.cwd,
|
|
title: session.config.title,
|
|
})),
|
|
});
|
|
return;
|
|
case "session.open":
|
|
openSession(input, state);
|
|
return;
|
|
case "session.prompt":
|
|
promptSession(input, state);
|
|
return;
|
|
case "session.configure":
|
|
configureSession(input, state);
|
|
return;
|
|
case "session.interrupt":
|
|
state.emit({ type: "request.completed", requestId: input.requestId });
|
|
return;
|
|
case "session.permission":
|
|
state.emit({
|
|
type: "session.permission_resolved",
|
|
sessionId: input.sessionId,
|
|
permissionId: input.permissionId,
|
|
});
|
|
return;
|
|
case "session.revert":
|
|
state.emit({ type: "request.completed", requestId: input.requestId });
|
|
return;
|
|
case "session.archive":
|
|
state.archived.add(persistenceKey(input.persistence));
|
|
state.emit({ type: "request.completed", requestId: input.requestId });
|
|
return;
|
|
case "session.unarchive":
|
|
state.archived.delete(persistenceKey(input.persistence));
|
|
state.emit({ type: "request.completed", requestId: input.requestId });
|
|
return;
|
|
case "session.close":
|
|
state.sessions.delete(input.sessionId);
|
|
state.emit({ type: "session.closed", sessionId: input.sessionId });
|
|
state.emit({ type: "request.completed", requestId: input.requestId });
|
|
}
|
|
}
|
|
|
|
function openSession(
|
|
input: Extract<ProviderInput, { type: "session.open" }>,
|
|
state: ExampleState,
|
|
): void {
|
|
const persistence = input.persistence ?? {
|
|
version: 1,
|
|
data: { nativeSessionId: `example:${input.sessionId}` },
|
|
};
|
|
const { concise, voice } = input.config.providerOptions ?? {};
|
|
const session: ExampleSession = {
|
|
config: input.config,
|
|
options: {
|
|
...(typeof concise === "boolean" ? { concise } : {}),
|
|
...(VOICES.some((candidate) => candidate.value === voice) ? { voice: voice as string } : {}),
|
|
},
|
|
persistence,
|
|
turn: 0,
|
|
activeTurnId: null,
|
|
};
|
|
state.sessions.set(input.sessionId, session);
|
|
state.emit({
|
|
type: "session.opened",
|
|
requestId: input.requestId,
|
|
sessionId: input.sessionId,
|
|
capabilities: state.capabilities,
|
|
restoration: "core",
|
|
persistence,
|
|
title: input.config.title,
|
|
cwd: input.config.cwd,
|
|
});
|
|
state.emit({ type: "session.config", sessionId: input.sessionId, config: configState(session) });
|
|
state.emit({
|
|
type: "session.commands",
|
|
sessionId: input.sessionId,
|
|
commands: [{ name: "reset", description: "Reset the example provider state" }],
|
|
});
|
|
if (input.history === "replay" && input.persistence) {
|
|
state.emit({
|
|
type: "timeline.item",
|
|
sessionId: input.sessionId,
|
|
item: { type: "assistant_message", id: "replayed-1", text: "Restored from persistence" },
|
|
});
|
|
}
|
|
state.emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
|
}
|
|
|
|
function promptSession(
|
|
input: Extract<ProviderInput, { type: "session.prompt" }>,
|
|
state: ExampleState,
|
|
): void {
|
|
const session = requireSession(state, input.sessionId);
|
|
if (input.prompt.delivery === "steer") {
|
|
if (!session.activeTurnId) {
|
|
state.emit({
|
|
type: "session.prompt_result",
|
|
sessionId: input.sessionId,
|
|
clientMessageId: input.prompt.clientMessageId,
|
|
result: { type: "failed", error: { message: "There is no active turn to steer" } },
|
|
});
|
|
return;
|
|
}
|
|
state.emit({
|
|
type: "session.prompt_result",
|
|
sessionId: input.sessionId,
|
|
clientMessageId: input.prompt.clientMessageId,
|
|
result: { type: "steer", turnId: session.activeTurnId },
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (input.prompt.input.type === "command") {
|
|
if (input.prompt.input.name !== "reset") {
|
|
state.emit({
|
|
type: "session.prompt_result",
|
|
sessionId: input.sessionId,
|
|
clientMessageId: input.prompt.clientMessageId,
|
|
result: { type: "failed", error: { message: "Unknown command" } },
|
|
});
|
|
return;
|
|
}
|
|
session.turn = 0;
|
|
state.emit({
|
|
type: "session.notice",
|
|
sessionId: input.sessionId,
|
|
notice: { id: "reset", severity: "info", title: "Example state reset" },
|
|
});
|
|
state.emit({
|
|
type: "session.prompt_result",
|
|
sessionId: input.sessionId,
|
|
clientMessageId: input.prompt.clientMessageId,
|
|
result: { type: "completed" },
|
|
});
|
|
return;
|
|
}
|
|
|
|
session.turn += 1;
|
|
const turnId = `turn-${session.turn}`;
|
|
session.activeTurnId = turnId;
|
|
const text = input.prompt.input.content
|
|
.filter((part) => part.type === "text")
|
|
.map((part) => part.text)
|
|
.join("\n");
|
|
state.emit({
|
|
type: "timeline.item",
|
|
sessionId: input.sessionId,
|
|
item: {
|
|
type: "user_message",
|
|
id: `user-${session.turn}`,
|
|
text,
|
|
clientMessageId: input.prompt.clientMessageId,
|
|
},
|
|
});
|
|
state.emit({
|
|
type: "session.prompt_result",
|
|
sessionId: input.sessionId,
|
|
clientMessageId: input.prompt.clientMessageId,
|
|
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: reply },
|
|
});
|
|
state.emit({
|
|
type: "timeline.item",
|
|
sessionId: input.sessionId,
|
|
item: {
|
|
type: "plugin",
|
|
id: `provider-result-${session.turn}`,
|
|
pluginId: "provider-direct-example",
|
|
kind: providerResultKind,
|
|
version: 1,
|
|
data: { label: "Provider result", detail: `Echoed turn ${session.turn}` },
|
|
},
|
|
});
|
|
publishChild(input.sessionId, session.turn, state);
|
|
session.persistence = {
|
|
version: 1,
|
|
data: { nativeSessionId: `example:${input.sessionId}`, turns: session.turn },
|
|
};
|
|
state.emit({
|
|
type: "session.persistence",
|
|
sessionId: input.sessionId,
|
|
persistence: session.persistence,
|
|
});
|
|
// 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;
|
|
}
|
|
|
|
function publishChild(parentSessionId: string, turn: number, state: ExampleState): void {
|
|
const sessionId = randomUUID();
|
|
state.emit({
|
|
type: "session.opened",
|
|
sessionId,
|
|
parentSessionId,
|
|
capabilities: [],
|
|
restoration: "parent",
|
|
title: "Example child",
|
|
cwd: requireSession(state, parentSessionId).config.cwd,
|
|
});
|
|
state.emit({
|
|
type: "timeline.item",
|
|
sessionId,
|
|
item: {
|
|
type: "plugin",
|
|
id: `child-result-${turn}`,
|
|
pluginId: "provider-direct-example",
|
|
kind: providerResultKind,
|
|
version: 1,
|
|
data: { label: "Child result", detail: "Completed" },
|
|
},
|
|
});
|
|
state.emit({ type: "session.ready", sessionId });
|
|
}
|
|
|
|
function configureSession(
|
|
input: Extract<ProviderInput, { type: "session.configure" }>,
|
|
state: ExampleState,
|
|
): void {
|
|
const session = requireSession(state, input.sessionId);
|
|
const changes = input.changes;
|
|
// Work out everything first, so a refused request changes nothing.
|
|
let options: ExampleSession["options"];
|
|
try {
|
|
options = applyOptions(session.options, changes.providerOptions ?? {});
|
|
} catch (error) {
|
|
state.emit({
|
|
type: "request.failed",
|
|
requestId: input.requestId,
|
|
error: { message: error instanceof Error ? error.message : String(error) },
|
|
});
|
|
return;
|
|
}
|
|
session.options = options;
|
|
session.config = {
|
|
...session.config,
|
|
model: changes.model === null ? undefined : (changes.model ?? session.config.model),
|
|
mode: changes.mode === null ? undefined : (changes.mode ?? session.config.mode),
|
|
thinkingOption:
|
|
changes.thinkingOption === null
|
|
? undefined
|
|
: (changes.thinkingOption ?? session.config.thinkingOption),
|
|
};
|
|
state.emit({ type: "session.config", sessionId: input.sessionId, config: configState(session) });
|
|
state.emit({ type: "request.completed", requestId: input.requestId });
|
|
}
|
|
|
|
/** Apply the whole patch or throw. `null` returns a key to its default. */
|
|
function applyOptions(
|
|
options: ExampleSession["options"],
|
|
patch: NonNullable<ProviderConfigChanges["providerOptions"]>,
|
|
): ExampleSession["options"] {
|
|
const next = { ...options };
|
|
for (const [key, value] of Object.entries(patch)) {
|
|
if (key === "concise" && (value === null || typeof value === "boolean")) {
|
|
if (value === null) delete next.concise;
|
|
else next.concise = value;
|
|
} else if (key === "voice" && (value === null || VOICES.some((v) => v.value === value))) {
|
|
if (value === null) delete next.voice;
|
|
else next.voice = value as string;
|
|
} else {
|
|
throw new Error(`Cannot set ${key} to ${JSON.stringify(value)}`);
|
|
}
|
|
}
|
|
return next;
|
|
}
|
|
|
|
function configState(session: ExampleSession): ProviderConfigState {
|
|
return {
|
|
model: session.config.model ?? "example-1",
|
|
mode: session.config.mode ?? "build",
|
|
thinkingOption: session.config.thinkingOption,
|
|
models: [{ id: "example-1", label: "Example 1" }],
|
|
modes: [{ id: "build", label: "Build" }],
|
|
thinkingOptions: [],
|
|
controls: CONTROLS,
|
|
// What the session ended up with, so Paseo stores what runs.
|
|
providerOptions: { ...session.options },
|
|
};
|
|
}
|
|
|
|
function requireSession(state: ExampleState, sessionId: string): ExampleSession {
|
|
const session = state.sessions.get(sessionId);
|
|
if (!session) throw new Error(`Unknown session: ${sessionId}`);
|
|
return session;
|
|
}
|
|
|
|
function persistenceKey(persistence: ProviderPersistence): string {
|
|
return JSON.stringify(persistence);
|
|
}
|