mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +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. * feat(providers): report session and turn metrics from OpenCode, OMP, Pi and Claude Each provider now attaches metrics to turn_completed and emits session_metrics_updated, live and when history is replayed. - Live turns end on the adapter's clock. A provider's message timestamps can come from another clock. - Tool time merges overlapping runs, so parallel tools count once. - A total that is missing any part is hidden, so a partial total is never shown. - Replayed history reports metrics only for turns that finished, which matches live, where failed and interrupted turns report none. - Claude reports cost as a running total for each query(). A resumed query starts that total from a saved one, so a turn's cost is the change since the previous result of the same query. The first turn of a query shows no cost. - Claude transcripts do not record result messages, so replayed Claude history has no turn metrics. - Session metrics come from each provider's own cumulative counters. The cache hit is the last reply's or the last turn's, because a session-wide figure blends prompts from before and after compactions. * feat(app): show provider session and turn metrics Session metrics appear in the context window details, between the context summary and the account usage cards. A provider-reported Cost row replaces the app's own session cost line. Each completed turn with metrics gets a stats button in its footer: a hover card on web, a press-opened tooltip on native wide screens, and a sheet on compact screens. The context window sheet becomes a shared DetailsSheet so both use the same content-sized sheet. Metrics ride on the row that hosts the turn's footer (the turn's last assistant message, else its last tool call), the same row the daemon stamps. Live turn_completed events and timeline pages both stamp that row, so a refetch agrees with what the live event showed. The daemon updates session metrics without bumping updatedAt, like usage, so a stale buffered upsert may still carry the newest metrics and is accepted for that field. * fix(app): keep a turn's stats after the cached timeline reloads The local timeline cache dropped turnMetrics when it saved a turn's footer row. After a page reload the cached rows painted without the stats icon, and the catch-up fetch had no new entries to stamp them from. * fix(providers): keep imported session stats and never count a steered turn short Importing a Pi, Oh My Pi or OpenCode v2 session dropped the stats the provider returned with its history, so imported chats showed none until a forced replay. Import now carries them the way replay does. Replaying a Pi or Oh My Pi transcript read a prompt that steered a running turn as the start of a new turn, so the steered turn's stats counted only the steps after the steer. A turn that follows one ending on tools now reports no total, because the transcript reads the same as a stop and a new prompt. * fix(providers): keep stats through merged messages and plugin imports, start Pi first-token timing at the request A message the timeline merges from several chunks keeps the stats stamped on its last chunk. Plugin session imports carry the stats the plugin replayed, through the same history reader the other providers use. Steers queued together after an unclear turn stay unclear instead of attributing the final reply to the wrong turn. Pi measures time to first token from the request, not the first reply header. * fix(providers): carry a turn's stats onto the message the timeline merges from text chunks The previous change put the carry-over in the reasoning merge. The assistant message merge dropped the stats of its last chunk, so an imported reply of two text blocks lost its Turn stats button. * fix(providers): carry a turn's stats onto the tool card the timeline merges from updates An imported turn that ends on a tool call stamps the stats on the tool's last update. The tool merge kept the first update's fields, so the stats were lost. * fix(opencode): replay no session stats for a session that has none An empty OpenCode session replayed a session stats event with no metrics, which broke the empty-history check in the versioned runtime test.
2280 lines
78 KiB
TypeScript
2280 lines
78 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { isDeepStrictEqual } from "node:util";
|
|
import { PluginSessionHistory } from "./plugin-session-history.js";
|
|
import { resolve as resolvePath } from "node:path";
|
|
import type { Logger } from "pino";
|
|
import type { JsonValue, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
|
import type { ProviderInstallationInspection } from "@getpaseo/protocol/messages";
|
|
import { z } from "zod";
|
|
import {
|
|
PROVIDER_CAPABILITIES,
|
|
PROVIDER_PROTOCOL_VERSION,
|
|
ProviderEventSchema,
|
|
ProviderInputSchema,
|
|
ProviderStatusSchema,
|
|
type ProviderStatus,
|
|
type ProviderInspection,
|
|
type ProviderUpdateCheck,
|
|
type ProviderUpdateResult,
|
|
type ProviderInstallationLaunch,
|
|
type ProviderLaunch,
|
|
requireProviderCapabilities,
|
|
type ProviderCapability,
|
|
type ProviderCommand,
|
|
type ProviderConfigChanges,
|
|
type ProviderConfigState,
|
|
type ProviderConnection,
|
|
type ProviderError,
|
|
type ProviderEvent,
|
|
type ProviderInput,
|
|
type ProviderPersistence,
|
|
type ProviderPrompt,
|
|
type ProviderRegistration,
|
|
type ProviderSessionConfig,
|
|
type ProviderContent,
|
|
type ProviderTimelineItem,
|
|
} from "@getpaseo/plugin/server/provider";
|
|
import type {
|
|
AgentCapabilityFlags,
|
|
AgentClient,
|
|
AgentClientInstallation,
|
|
AgentClientUpdateCheckContext,
|
|
AgentClientUpdateContext,
|
|
AgentCreateSessionOptions,
|
|
AgentLaunchContext,
|
|
AgentMode,
|
|
AgentModelDefinition,
|
|
AgentOptionControl,
|
|
AgentPermissionRequest,
|
|
AgentPermissionResponse,
|
|
AgentPersistenceHandle,
|
|
AgentPromptInput,
|
|
AgentRunOptions,
|
|
AgentRunResult,
|
|
AgentSession,
|
|
AgentSessionConfig,
|
|
AgentSlashCommand,
|
|
AgentStreamEvent,
|
|
AgentTimelineItem,
|
|
FetchCatalogOptions,
|
|
ImportableProviderSession,
|
|
ImportedProviderSession,
|
|
ImportProviderSessionContext,
|
|
ImportProviderSessionInput,
|
|
ListImportableSessionsOptions,
|
|
ProviderCatalog,
|
|
ProviderRefreshContext,
|
|
SteerActiveTurnOptions,
|
|
SteerResult,
|
|
AgentClientDiagnosticContext,
|
|
} from "./agent-sdk-types.js";
|
|
import {
|
|
resolveProviderLaunch,
|
|
checkProviderLaunchAvailable,
|
|
createProviderEnv,
|
|
type ProviderRuntimeSettings,
|
|
} from "./provider-launch-config.js";
|
|
import { ImportedHistory } from "./provider-session-import.js";
|
|
import { readPluginOptionState } from "./plugin-provider-options.js";
|
|
import {
|
|
buildCommandResolutionDiagnosticRows,
|
|
formatProviderDiagnostic,
|
|
type DiagnosticEntry,
|
|
} from "./providers/diagnostic-utils.js";
|
|
import type { RegisteredProviderDefinition } from "./provider-registry.js";
|
|
import { runProviderTurn } from "./providers/provider-runner.js";
|
|
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
|
|
|
|
interface Deferred<Value> {
|
|
promise: Promise<Value>;
|
|
resolve(value: Value): void;
|
|
reject(error: Error): void;
|
|
}
|
|
|
|
interface PendingRequest {
|
|
kind: ProviderInput["type"];
|
|
sessionId?: string;
|
|
resolve(event: ProviderEvent): void;
|
|
reject(error: Error): void;
|
|
}
|
|
|
|
interface PendingOpenDescendantState {
|
|
readonly providerSessionIds: Set<string>;
|
|
readonly events: ProviderEvent[];
|
|
}
|
|
|
|
interface OpenProviderSessionInput {
|
|
sessionId: string;
|
|
config: ProviderSessionConfig;
|
|
persistence?: ProviderPersistence;
|
|
history: "replay" | "skip";
|
|
}
|
|
|
|
function deferred<Value>(): Deferred<Value> {
|
|
let resolve!: (value: Value) => void;
|
|
let reject!: (error: Error) => void;
|
|
const promise = new Promise<Value>((onResolve, onReject) => {
|
|
resolve = onResolve;
|
|
reject = onReject;
|
|
});
|
|
// Provider events can reject before send() settles and the caller awaits this promise.
|
|
// Observe that interval without replacing the rejecting promise returned to the caller.
|
|
void promise.catch(() => undefined);
|
|
return { promise, resolve, reject };
|
|
}
|
|
|
|
function providerError(error: ProviderError): Error {
|
|
return Object.assign(new Error(error.message), {
|
|
code: error.code,
|
|
diagnostic: error.diagnostic,
|
|
});
|
|
}
|
|
|
|
function isProviderRequestReply(
|
|
event: ProviderEvent,
|
|
): event is Extract<
|
|
ProviderEvent,
|
|
{ type: "request.completed" | "catalog" | "sessions" | "session.can_stop_runtime" }
|
|
> {
|
|
return (
|
|
event.type === "request.completed" ||
|
|
event.type === "catalog" ||
|
|
event.type === "sessions" ||
|
|
event.type === "session.can_stop_runtime"
|
|
);
|
|
}
|
|
|
|
function describeVersion(inspection: ProviderInstallationInspection): string {
|
|
if (inspection.status === "not_installed") return "not installed";
|
|
if (inspection.status === "error") return `error: ${inspection.message}`;
|
|
return inspection.version?.trim() || "unknown";
|
|
}
|
|
|
|
class ProviderRuntime {
|
|
private connection: ProviderConnection | null = null;
|
|
connectedLaunch: ProviderLaunch | undefined;
|
|
private connecting: Promise<ProviderConnection> | null = null;
|
|
private closed = false;
|
|
private generation = 0;
|
|
private closePromise: Promise<void> | null = null;
|
|
private unsubscribe: (() => void) | null = null;
|
|
private readonly sessions = new Map<string, ProviderRuntimeSession>();
|
|
private readonly providerSessions = new Map<string, ProviderRuntimeSession>();
|
|
private readonly sessionListeners = new Set<
|
|
(
|
|
session: ProviderRuntimeSession,
|
|
event: Extract<ProviderEvent, { type: "session.opened" }>,
|
|
) => void
|
|
>();
|
|
private readonly requests = new Map<string, PendingRequest>();
|
|
private readonly sessionRequests = new Map<string, string>();
|
|
private readonly pendingOpenDescendants = new Map<string, PendingOpenDescendantState>();
|
|
private readonly pendingOpenDescendantsByRoot = new Map<
|
|
ProviderRuntimeSession,
|
|
PendingOpenDescendantState
|
|
>();
|
|
|
|
constructor(
|
|
private readonly registration: ProviderRegistration,
|
|
private readonly runtimeSettings?: ProviderRuntimeSettings,
|
|
) {}
|
|
|
|
/** The launch after overrides, and where its executable resolves. */
|
|
private async resolveConfiguredLaunch() {
|
|
const command = this.registration.command;
|
|
if (!command) return undefined;
|
|
const launch = await resolveProviderLaunch({
|
|
commandConfig: this.runtimeSettings?.command,
|
|
defaultBinary: command[0],
|
|
});
|
|
if (launch.source !== "override") launch.args.unshift(...command.slice(1));
|
|
const env = createProviderEnv({ runtimeSettings: this.runtimeSettings });
|
|
launch.env = env;
|
|
return { launch, env, availability: await checkProviderLaunchAvailable(launch) };
|
|
}
|
|
|
|
/** The effective launch, including when its executable does not resolve. */
|
|
private async resolveEffectiveLaunch(): Promise<ProviderInstallationLaunch | undefined> {
|
|
const configured = await this.resolveConfiguredLaunch();
|
|
if (!configured) return undefined;
|
|
const { launch, env, availability } = configured;
|
|
if (!availability.resolvedPath)
|
|
return { command: launch.command, args: launch.args, env, resolved: false };
|
|
return {
|
|
command: resolvePath(availability.resolvedPath),
|
|
args: launch.args,
|
|
env,
|
|
resolved: true,
|
|
};
|
|
}
|
|
|
|
private async resolveLaunch(): Promise<ProviderLaunch | undefined> {
|
|
const launch = await this.resolveEffectiveLaunch();
|
|
if (!launch) return undefined;
|
|
if (!launch.resolved) throw new Error(`${launch.command} not found on PATH`);
|
|
return { command: launch.command, args: launch.args, env: launch.env };
|
|
}
|
|
|
|
async resolveUsageLaunch(): Promise<ProviderLaunch | undefined> {
|
|
const launch = await this.resolveEffectiveLaunch();
|
|
if (!launch?.resolved) return undefined;
|
|
return { command: launch.command, args: launch.args, env: launch.env };
|
|
}
|
|
|
|
async inspectInstallation(signal: AbortSignal): Promise<ProviderInspection> {
|
|
const inspect = this.registration.installation?.inspect;
|
|
if (!inspect) throw new Error("Provider does not report its installation");
|
|
const launch = await this.resolveEffectiveLaunch();
|
|
signal.throwIfAborted();
|
|
return await inspect.call(this.registration.installation, { launch, signal });
|
|
}
|
|
|
|
async checkForUpdates(context: AgentClientUpdateCheckContext): Promise<ProviderUpdateCheck> {
|
|
const checkForUpdates = this.registration.installation?.checkForUpdates;
|
|
if (!checkForUpdates) throw new Error("Provider does not check for updates");
|
|
const launch = await this.resolveEffectiveLaunch();
|
|
context.signal.throwIfAborted();
|
|
return await checkForUpdates.call(this.registration.installation, { ...context, launch });
|
|
}
|
|
|
|
async update(context: AgentClientUpdateContext): Promise<ProviderUpdateResult> {
|
|
const update = this.registration.installation?.update;
|
|
if (!update) throw new Error("Provider does not update itself");
|
|
const launch = await this.resolveEffectiveLaunch();
|
|
context.signal.throwIfAborted();
|
|
return await update.call(this.registration.installation, { ...context, launch });
|
|
}
|
|
|
|
/** What the daemon launches, where it found the executable and which version it runs. */
|
|
async launchDiagnosticRows(context: AgentClientDiagnosticContext): Promise<DiagnosticEntry[]> {
|
|
const configured = await this.resolveConfiguredLaunch();
|
|
if (!configured) return [];
|
|
const { launch, env, availability } = configured;
|
|
const rows = [
|
|
...(await buildCommandResolutionDiagnosticRows(launch, {
|
|
knownBinaryNames: [launch.command],
|
|
pathValue: env.PATH,
|
|
})),
|
|
{ label: "Resolved path", value: availability.resolvedPath ?? "not found" },
|
|
];
|
|
if (!availability.resolvedPath) return rows;
|
|
const inspection = await context.inspectInstallation();
|
|
if (inspection) rows.push({ label: "Version", value: describeVersion(inspection) });
|
|
return rows;
|
|
}
|
|
|
|
async status(): Promise<ProviderStatus> {
|
|
try {
|
|
const launch = await this.resolveLaunch();
|
|
if (this.registration.status)
|
|
return ProviderStatusSchema.parse(await this.registration.status({ launch }));
|
|
if (!this.registration.command) await this.getConnection();
|
|
return { available: true };
|
|
} catch (error) {
|
|
return {
|
|
available: false,
|
|
diagnostic: error instanceof Error ? error.message : String(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
async catalogCacheKey(options: FetchCatalogOptions): Promise<string | undefined> {
|
|
const callback = this.registration.getCatalogCacheKey;
|
|
if (!callback) return undefined;
|
|
return callback({ ...options, launch: await this.resolveLaunch() });
|
|
}
|
|
|
|
get negotiatedCapabilities(): readonly string[] {
|
|
return this.connection?.capabilities ?? [];
|
|
}
|
|
|
|
get isClosed(): boolean {
|
|
return this.closed;
|
|
}
|
|
|
|
async isAvailable(): Promise<boolean> {
|
|
return (await this.status()).available;
|
|
}
|
|
|
|
async catalog(
|
|
cwd?: string,
|
|
signal?: AbortSignal,
|
|
): Promise<Extract<ProviderEvent, { type: "catalog" }>["catalog"]> {
|
|
const event = await this.complete({ type: "catalog", requestId: randomUUID(), cwd }, signal);
|
|
if (event.type !== "catalog") throw new Error("Provider returned an invalid catalog response");
|
|
return event.catalog;
|
|
}
|
|
|
|
async listSessions(
|
|
input: {
|
|
query?: string;
|
|
cwd?: string;
|
|
limit?: number;
|
|
} = {},
|
|
): Promise<Extract<ProviderEvent, { type: "sessions" }>["sessions"]> {
|
|
const connection = await this.getConnection();
|
|
if (!connection.capabilities.includes("session.list")) return [];
|
|
const event = await this.complete({ type: "sessions", requestId: randomUUID(), ...input });
|
|
if (event.type !== "sessions")
|
|
throw new Error("Provider returned an invalid sessions response");
|
|
return event.sessions;
|
|
}
|
|
|
|
onSessionOpened(
|
|
listener: (
|
|
session: ProviderRuntimeSession,
|
|
event: Extract<ProviderEvent, { type: "session.opened" }>,
|
|
) => void,
|
|
): () => void {
|
|
this.sessionListeners.add(listener);
|
|
return () => this.sessionListeners.delete(listener);
|
|
}
|
|
|
|
async openSession(input: OpenProviderSessionInput): Promise<ProviderRuntimeSession> {
|
|
if (this.sessions.has(input.sessionId)) {
|
|
throw new Error(`Provider session already exists: ${input.sessionId}`);
|
|
}
|
|
const connection = await this.getConnection();
|
|
requireProviderCapabilities(connection.capabilities, {
|
|
type: "session.open",
|
|
requestId: "capability-check",
|
|
...input,
|
|
});
|
|
const session = new ProviderRuntimeSession(
|
|
this,
|
|
connection,
|
|
input.sessionId,
|
|
input.sessionId,
|
|
"core",
|
|
);
|
|
this.sessions.set(input.sessionId, session);
|
|
this.providerSessions.set(input.sessionId, session);
|
|
const requestId = randomUUID();
|
|
const ready = session.beginOpen(requestId);
|
|
this.sessionRequests.set(requestId, input.sessionId);
|
|
try {
|
|
await connection.send({
|
|
type: "session.open",
|
|
requestId,
|
|
sessionId: input.sessionId,
|
|
config: input.config,
|
|
persistence: input.persistence,
|
|
history: input.history,
|
|
});
|
|
await ready;
|
|
return session;
|
|
} catch (error) {
|
|
this.sessionRequests.delete(requestId);
|
|
this.discardPendingOpenDescendants(session);
|
|
this.sessions.delete(input.sessionId);
|
|
this.providerSessions.delete(input.sessionId);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async archive(persistence: ProviderPersistence): Promise<void> {
|
|
const connection = await this.getConnection();
|
|
if (!connection.capabilities.includes("session.archive")) return;
|
|
await this.complete({ type: "session.archive", requestId: randomUUID(), persistence });
|
|
}
|
|
|
|
async unarchive(persistence: ProviderPersistence): Promise<void> {
|
|
const connection = await this.getConnection();
|
|
if (!connection.capabilities.includes("session.unarchive")) return;
|
|
await this.complete({ type: "session.unarchive", requestId: randomUUID(), persistence });
|
|
}
|
|
|
|
close(): Promise<void> {
|
|
if (this.closePromise) return this.closePromise;
|
|
this.closed = true;
|
|
this.generation += 1;
|
|
const connection = this.connection;
|
|
const connecting = connection ? null : this.connecting;
|
|
this.connection = null;
|
|
this.unsubscribe?.();
|
|
this.unsubscribe = null;
|
|
for (const session of this.sessions.values()) session.connectionClosed();
|
|
this.sessions.clear();
|
|
this.providerSessions.clear();
|
|
this.pendingOpenDescendants.clear();
|
|
this.pendingOpenDescendantsByRoot.clear();
|
|
this.sessionListeners.clear();
|
|
for (const request of this.requests.values()) request.reject(new Error("Provider closed"));
|
|
this.requests.clear();
|
|
this.closePromise = Promise.all([
|
|
connection?.close(),
|
|
connecting?.then(
|
|
() => undefined,
|
|
() => undefined,
|
|
),
|
|
]).then(() => undefined);
|
|
return this.closePromise;
|
|
}
|
|
|
|
async complete(
|
|
input: ProviderInput & { requestId: string },
|
|
signal?: AbortSignal,
|
|
): Promise<ProviderEvent> {
|
|
signal?.throwIfAborted();
|
|
const connection = await this.getConnection();
|
|
signal?.throwIfAborted();
|
|
const pending = deferred<ProviderEvent>();
|
|
this.requests.set(input.requestId, {
|
|
kind: input.type,
|
|
sessionId:
|
|
"sessionId" in input
|
|
? (this.providerSessions.get(input.sessionId)?.id ?? input.sessionId)
|
|
: undefined,
|
|
resolve: pending.resolve,
|
|
reject: pending.reject,
|
|
});
|
|
const abort = () => {
|
|
if (!this.requests.delete(input.requestId)) return;
|
|
pending.reject(
|
|
signal?.reason instanceof Error ? signal.reason : new Error("Provider request aborted"),
|
|
);
|
|
};
|
|
signal?.addEventListener("abort", abort, { once: true });
|
|
try {
|
|
await connection.send(input);
|
|
return await pending.promise;
|
|
} catch (error) {
|
|
this.requests.delete(input.requestId);
|
|
throw error;
|
|
} finally {
|
|
signal?.removeEventListener("abort", abort);
|
|
}
|
|
}
|
|
|
|
removeSession(sessionId: string, providerSessionId: string): void {
|
|
this.sessions.delete(sessionId);
|
|
this.providerSessions.delete(providerSessionId);
|
|
}
|
|
|
|
private getConnection(): Promise<ProviderConnection> {
|
|
if (this.closed) return Promise.reject(new Error("Provider runtime is closed"));
|
|
if (this.connection) return Promise.resolve(this.connection);
|
|
if (this.connecting) return this.connecting;
|
|
const generation = this.generation;
|
|
const connecting = this.establishConnection(generation);
|
|
this.connecting = connecting;
|
|
connecting.then(
|
|
() => {
|
|
if (this.connecting === connecting) this.connecting = null;
|
|
return undefined;
|
|
},
|
|
() => {
|
|
if (this.connecting === connecting) this.connecting = null;
|
|
return undefined;
|
|
},
|
|
);
|
|
return connecting;
|
|
}
|
|
|
|
private async establishConnection(generation: number): Promise<ProviderConnection> {
|
|
const launch = await this.resolveLaunch();
|
|
const rawConnection = await this.registration.connect({
|
|
launch,
|
|
versions: [PROVIDER_PROTOCOL_VERSION],
|
|
capabilities: PROVIDER_CAPABILITIES,
|
|
});
|
|
if (this.closed || generation !== this.generation) {
|
|
await rawConnection.close().catch(() => undefined);
|
|
throw new Error("Provider runtime is closed");
|
|
}
|
|
try {
|
|
this.validateConnection(rawConnection);
|
|
} catch (error) {
|
|
await rawConnection.close().catch(() => undefined);
|
|
throw error;
|
|
}
|
|
this.connectedLaunch = launch;
|
|
const connection = normalizeConnection(rawConnection);
|
|
const unsubscribe = connection.onEvent((event) => this.accept(event));
|
|
if (this.closed || generation !== this.generation) {
|
|
unsubscribe();
|
|
await connection.close().catch(() => undefined);
|
|
throw new Error("Provider runtime is closed");
|
|
}
|
|
this.unsubscribe = unsubscribe;
|
|
this.connection = connection;
|
|
return connection;
|
|
}
|
|
|
|
private validateConnection(connection: ProviderConnection): void {
|
|
if (connection.version !== PROVIDER_PROTOCOL_VERSION) {
|
|
throw new Error(`Provider selected unsupported version ${connection.version}`);
|
|
}
|
|
}
|
|
|
|
private accept(event: ProviderEvent): void {
|
|
if (event.type === "request.failed") {
|
|
this.failRequest(event);
|
|
return;
|
|
}
|
|
if (isProviderRequestReply(event)) {
|
|
this.finishRequest(event);
|
|
return;
|
|
}
|
|
this.finishSessionReadyRequest(event);
|
|
if (this.holdPendingOpenDescendant(event)) return;
|
|
if (this.acceptProviderChild(event)) return;
|
|
if ("sessionId" in event) {
|
|
const session = this.providerSessions.get(event.sessionId);
|
|
if (!session) return;
|
|
event = {
|
|
...event,
|
|
sessionId: session.id,
|
|
...(event.type === "session.opened" && event.parentSessionId
|
|
? { parentSessionId: this.providerSessions.get(event.parentSessionId)?.id }
|
|
: {}),
|
|
} as ProviderEvent;
|
|
}
|
|
if (event.type === "session.runtime_failed") {
|
|
this.failSessionRequests(event.sessionId, providerError(event.error));
|
|
} else if (event.type === "session.closed") {
|
|
this.settleClosedSessionRequests(
|
|
event.sessionId,
|
|
new Error(event.error?.message ?? `Provider session ${event.sessionId} closed`),
|
|
event,
|
|
);
|
|
}
|
|
if ("sessionId" in event) {
|
|
const session = this.sessions.get(event.sessionId);
|
|
session?.accept(event);
|
|
if (event.type === "session.closed" && session) {
|
|
this.removeSession(session.id, session.providerId);
|
|
}
|
|
}
|
|
}
|
|
|
|
private finishSessionReadyRequest(event: ProviderEvent): void {
|
|
if (event.type !== "session.ready" || !event.requestId) return;
|
|
this.sessionRequests.delete(event.requestId);
|
|
const request = this.requests.get(event.requestId);
|
|
if (!request) return;
|
|
this.requests.delete(event.requestId);
|
|
request.resolve(event);
|
|
}
|
|
|
|
private acceptProviderChild(event: ProviderEvent): boolean {
|
|
if (event.type !== "session.opened" || this.providerSessions.has(event.sessionId)) return false;
|
|
const parent = event.parentSessionId
|
|
? this.providerSessions.get(event.parentSessionId)
|
|
: undefined;
|
|
if (!parent) return true;
|
|
const sessionId = randomUUID();
|
|
const session = new ProviderRuntimeSession(
|
|
this,
|
|
this.connection!,
|
|
sessionId,
|
|
event.sessionId,
|
|
event.restoration,
|
|
);
|
|
this.sessions.set(sessionId, session);
|
|
this.providerSessions.set(event.sessionId, session);
|
|
const mappedEvent = { ...event, sessionId, parentSessionId: parent.id };
|
|
session.accept(mappedEvent);
|
|
for (const listener of this.sessionListeners) listener(session, mappedEvent);
|
|
return true;
|
|
}
|
|
|
|
private holdPendingOpenDescendant(event: ProviderEvent): boolean {
|
|
if (!("sessionId" in event)) return false;
|
|
let state = this.pendingOpenDescendants.get(event.sessionId);
|
|
if (event.type === "session.opened" && event.parentSessionId) {
|
|
const parent = this.providerSessions.get(event.parentSessionId);
|
|
state =
|
|
this.pendingOpenDescendants.get(event.parentSessionId) ??
|
|
(parent?.hasPendingOpen() ? this.pendingOpenDescendantStateFor(parent) : undefined);
|
|
if (state) {
|
|
state.providerSessionIds.add(event.sessionId);
|
|
this.pendingOpenDescendants.set(event.sessionId, state);
|
|
}
|
|
}
|
|
if (!state) return false;
|
|
state.events.push(event);
|
|
return true;
|
|
}
|
|
|
|
private pendingOpenDescendantStateFor(root: ProviderRuntimeSession): PendingOpenDescendantState {
|
|
const existing = this.pendingOpenDescendantsByRoot.get(root);
|
|
if (existing) return existing;
|
|
const state: PendingOpenDescendantState = { providerSessionIds: new Set(), events: [] };
|
|
this.pendingOpenDescendantsByRoot.set(root, state);
|
|
return state;
|
|
}
|
|
|
|
releasePendingOpenDescendants(root: ProviderRuntimeSession): void {
|
|
const state = this.takePendingOpenDescendants(root);
|
|
if (!state) return;
|
|
for (const event of state.events) this.accept(event);
|
|
}
|
|
|
|
discardPendingOpenDescendants(root: ProviderRuntimeSession): void {
|
|
this.takePendingOpenDescendants(root);
|
|
}
|
|
|
|
private takePendingOpenDescendants(
|
|
root: ProviderRuntimeSession,
|
|
): PendingOpenDescendantState | undefined {
|
|
const state = this.pendingOpenDescendantsByRoot.get(root);
|
|
if (!state) return undefined;
|
|
this.pendingOpenDescendantsByRoot.delete(root);
|
|
for (const providerSessionId of state.providerSessionIds) {
|
|
if (this.pendingOpenDescendants.get(providerSessionId) === state) {
|
|
this.pendingOpenDescendants.delete(providerSessionId);
|
|
}
|
|
}
|
|
return state;
|
|
}
|
|
|
|
private failSessionRequests(sessionId: string, error: Error): void {
|
|
for (const [requestId, request] of this.requests) {
|
|
if (request.sessionId !== sessionId) continue;
|
|
this.requests.delete(requestId);
|
|
request.reject(error);
|
|
}
|
|
for (const [requestId, pendingSessionId] of this.sessionRequests) {
|
|
if (pendingSessionId === sessionId) this.sessionRequests.delete(requestId);
|
|
}
|
|
}
|
|
|
|
private settleClosedSessionRequests(
|
|
sessionId: string,
|
|
error: Error,
|
|
event: Extract<ProviderEvent, { type: "session.closed" }>,
|
|
): void {
|
|
for (const [requestId, request] of this.requests) {
|
|
if (request.sessionId !== sessionId) continue;
|
|
this.requests.delete(requestId);
|
|
if (request.kind === "session.close") request.resolve(event);
|
|
else request.reject(error);
|
|
}
|
|
}
|
|
|
|
private failRequest(event: Extract<ProviderEvent, { type: "request.failed" }>): void {
|
|
const request = this.requests.get(event.requestId);
|
|
if (request) {
|
|
this.requests.delete(event.requestId);
|
|
request.reject(providerError(event.error));
|
|
}
|
|
if (request?.sessionId) this.sessions.get(request.sessionId)?.requestFailed(event);
|
|
const sessionId = this.sessionRequests.get(event.requestId);
|
|
if (!sessionId) return;
|
|
this.sessionRequests.delete(event.requestId);
|
|
this.sessions.get(sessionId)?.requestFailed(event);
|
|
}
|
|
|
|
private finishRequest(
|
|
event: Extract<
|
|
ProviderEvent,
|
|
{ type: "request.completed" | "catalog" | "sessions" | "session.can_stop_runtime" }
|
|
>,
|
|
): void {
|
|
const request = this.requests.get(event.requestId);
|
|
if (!request) return;
|
|
if (
|
|
event.type === "session.can_stop_runtime" &&
|
|
this.providerSessions.get(event.sessionId)?.id !== request.sessionId
|
|
) {
|
|
this.requests.delete(event.requestId);
|
|
request.reject(new Error("Runtime safety response belongs to another session"));
|
|
return;
|
|
}
|
|
this.requests.delete(event.requestId);
|
|
request.resolve(event);
|
|
}
|
|
}
|
|
|
|
class ProviderRuntimeSession {
|
|
readonly history: ProviderEvent[] = [];
|
|
private historyClaimed = false;
|
|
private readonly listeners = new Set<(event: ProviderEvent) => void>();
|
|
private capabilities: readonly string[] = [];
|
|
private openRequest: { requestId: string; deferred: Deferred<void> } | null = null;
|
|
private readonly prompts = new Map<
|
|
string,
|
|
Deferred<Extract<ProviderEvent, { type: "session.prompt_result" }>>
|
|
>();
|
|
private readonly activeTurnIds = new Set<string>();
|
|
private terminal = false;
|
|
// The provider ended this session with session.closed, so it has nothing left to close.
|
|
private closedByProvider = false;
|
|
private closePromise: Promise<void> | null = null;
|
|
config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [] };
|
|
commands: ProviderCommand[] = [];
|
|
persistence: ProviderPersistence | null = null;
|
|
|
|
constructor(
|
|
private readonly runtime: ProviderRuntime,
|
|
private readonly connection: ProviderConnection,
|
|
readonly id: string,
|
|
private readonly providerSessionId: string,
|
|
readonly restoration: "core" | "parent",
|
|
) {}
|
|
|
|
get providerId(): string {
|
|
return this.providerSessionId;
|
|
}
|
|
|
|
get negotiatedCapabilities(): readonly string[] {
|
|
return this.capabilities;
|
|
}
|
|
|
|
onEvent(listener: (event: ProviderEvent) => void): () => void {
|
|
// This buffer bridges session.open and adapter attachment. Once replayed,
|
|
// the adapter owns history; retaining live cumulative snapshots is quadratic.
|
|
this.historyClaimed = true;
|
|
this.history.length = 0;
|
|
this.listeners.add(listener);
|
|
return () => this.listeners.delete(listener);
|
|
}
|
|
|
|
async prompt(
|
|
prompt: ProviderPrompt,
|
|
): Promise<Extract<ProviderEvent, { type: "session.prompt_result" }>["result"]> {
|
|
requireProviderCapabilities(this.capabilities, {
|
|
type: "session.prompt",
|
|
sessionId: this.providerSessionId,
|
|
prompt,
|
|
});
|
|
if (this.terminal) throw new StaleProviderSessionError(this.id);
|
|
const pending = deferred<Extract<ProviderEvent, { type: "session.prompt_result" }>>();
|
|
this.prompts.set(prompt.clientMessageId, pending);
|
|
try {
|
|
await this.connection.send({
|
|
type: "session.prompt",
|
|
sessionId: this.providerSessionId,
|
|
prompt,
|
|
});
|
|
return (await pending.promise).result;
|
|
} catch (error) {
|
|
if (this.terminal || this.runtime.isClosed) throw new StaleProviderSessionError(this.id);
|
|
throw error;
|
|
} finally {
|
|
this.prompts.delete(prompt.clientMessageId);
|
|
}
|
|
}
|
|
|
|
async canStopRuntime(): Promise<boolean> {
|
|
if (
|
|
this.terminal ||
|
|
this.prompts.size ||
|
|
this.activeTurnIds.size ||
|
|
!this.capabilities.includes("session.can_stop_runtime")
|
|
)
|
|
return false;
|
|
const event = await this.runtime.complete(
|
|
{
|
|
type: "session.can_stop_runtime",
|
|
requestId: randomUUID(),
|
|
sessionId: this.providerSessionId,
|
|
},
|
|
AbortSignal.timeout(10_000),
|
|
);
|
|
if (event.type !== "session.can_stop_runtime")
|
|
throw new Error("Invalid runtime safety response");
|
|
return event.canStop;
|
|
}
|
|
|
|
async configure(changes: ProviderConfigChanges): Promise<void> {
|
|
if (this.terminal) throw new StaleProviderSessionError(this.id);
|
|
const input: Extract<ProviderInput, { type: "session.configure" }> = {
|
|
type: "session.configure",
|
|
requestId: randomUUID(),
|
|
sessionId: this.providerSessionId,
|
|
changes,
|
|
};
|
|
requireProviderCapabilities(this.capabilities, input);
|
|
await this.runtime.complete(input);
|
|
}
|
|
|
|
async respondToPermission(
|
|
permissionId: string,
|
|
response: Extract<ProviderInput, { type: "session.permission" }>["response"],
|
|
): Promise<void> {
|
|
const input: Extract<ProviderInput, { type: "session.permission" }> = {
|
|
type: "session.permission",
|
|
sessionId: this.providerSessionId,
|
|
permissionId,
|
|
response,
|
|
};
|
|
requireProviderCapabilities(this.capabilities, input);
|
|
await this.connection.send(input);
|
|
}
|
|
|
|
async revert(token: ProviderInput & { type: "session.revert" }): Promise<void> {
|
|
const input = { ...token, sessionId: this.providerSessionId };
|
|
requireProviderCapabilities(this.capabilities, input);
|
|
await this.runtime.complete(input);
|
|
}
|
|
|
|
async interrupt(): Promise<void> {
|
|
await this.runtime.complete({
|
|
type: "session.interrupt",
|
|
requestId: randomUUID(),
|
|
sessionId: this.providerSessionId,
|
|
});
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
this.history.length = 0;
|
|
if (this.restoration === "parent" || this.closedByProvider) {
|
|
this.runtime.removeSession(this.id, this.providerSessionId);
|
|
return;
|
|
}
|
|
this.closePromise ??= this.closeNativeSession().catch((error) => {
|
|
this.closePromise = null;
|
|
throw error;
|
|
});
|
|
await this.closePromise;
|
|
}
|
|
|
|
private async closeNativeSession(): Promise<void> {
|
|
try {
|
|
await this.runtime.complete({
|
|
type: "session.close",
|
|
requestId: randomUUID(),
|
|
sessionId: this.providerSessionId,
|
|
});
|
|
} catch (error) {
|
|
if (!this.runtime.isClosed) throw error;
|
|
}
|
|
// A failed close still needs its routing for a subsequent session.closed ack.
|
|
this.runtime.removeSession(this.id, this.providerSessionId);
|
|
}
|
|
|
|
beginOpen(requestId: string): Promise<void> {
|
|
const pending = deferred<void>();
|
|
this.openRequest = { requestId, deferred: pending };
|
|
return pending.promise;
|
|
}
|
|
|
|
requestFailed(event: Extract<ProviderEvent, { type: "request.failed" }>): void {
|
|
if (this.openRequest?.requestId === event.requestId) {
|
|
this.openRequest.deferred.reject(providerError(event.error));
|
|
this.openRequest = null;
|
|
this.runtime.discardPendingOpenDescendants(this);
|
|
}
|
|
}
|
|
|
|
accept(event: ProviderEvent): void {
|
|
if (event.type === "session.opened") {
|
|
event = { ...event, capabilities: this.normalizeSessionCapabilities(event.capabilities) };
|
|
}
|
|
if (event.type === "session.opened") {
|
|
this.capabilities = [...event.capabilities];
|
|
this.persistence = this.restoration === "core" ? (event.persistence ?? null) : null;
|
|
return;
|
|
}
|
|
const openRequest = this.openRequest;
|
|
if (
|
|
event.type === "session.ready" &&
|
|
openRequest &&
|
|
openRequest.requestId === event.requestId
|
|
) {
|
|
this.openRequest = null;
|
|
this.runtime.releasePendingOpenDescendants(this);
|
|
openRequest.deferred.resolve();
|
|
return;
|
|
}
|
|
if (event.type === "session.prompt_result") {
|
|
if (event.result.type === "turn") this.activeTurnIds.add(event.result.turnId);
|
|
this.prompts.get(event.clientMessageId)?.resolve(event);
|
|
return;
|
|
}
|
|
if (event.type === "session.runtime_failed" || event.type === "session.closed") {
|
|
if (event.type === "session.closed") this.closedByProvider = true;
|
|
if (this.terminal) return;
|
|
this.terminal = true;
|
|
this.publish(event);
|
|
this.rejectPending(new Error(event.error?.message ?? `Provider session ${this.id} closed`));
|
|
return;
|
|
}
|
|
this.publish(event);
|
|
}
|
|
|
|
hasPendingOpen(): boolean {
|
|
return this.openRequest !== null;
|
|
}
|
|
|
|
connectionClosed(error = new Error("Provider connection closed")): void {
|
|
// Closing fails only an interrupted turn. An idle session goes stale, and its next prompt
|
|
// reopens it from persistence.
|
|
if (!this.terminal && this.activeTurnIds.size > 0) {
|
|
this.publish({
|
|
type: "session.runtime_failed",
|
|
sessionId: this.id,
|
|
error: { message: error.message },
|
|
});
|
|
}
|
|
this.terminal = true;
|
|
this.rejectPending(error);
|
|
}
|
|
|
|
private rejectPending(error: Error): void {
|
|
const openRequest = this.openRequest;
|
|
this.openRequest = null;
|
|
openRequest?.deferred.reject(error);
|
|
this.runtime.discardPendingOpenDescendants(this);
|
|
for (const prompt of this.prompts.values()) prompt.reject(error);
|
|
this.prompts.clear();
|
|
}
|
|
|
|
private normalizeSessionCapabilities(capabilities: readonly string[]): ProviderCapability[] {
|
|
const known = PROVIDER_CAPABILITIES.filter((capability) => capabilities.includes(capability));
|
|
for (const capability of known) {
|
|
if (!this.connection.capabilities.includes(capability)) {
|
|
throw new Error(`Provider session selected unoffered capability ${capability}`);
|
|
}
|
|
}
|
|
return known;
|
|
}
|
|
|
|
private publish(event: ProviderEvent): void {
|
|
if (event.type === "session.turn") {
|
|
if (event.state === "started") this.activeTurnIds.add(event.turnId);
|
|
else this.activeTurnIds.delete(event.turnId);
|
|
}
|
|
if (event.type === "session.config") this.config = event.config;
|
|
if (event.type === "session.commands") this.commands = [...event.commands];
|
|
if (event.type === "session.persistence" && this.restoration === "core") {
|
|
this.persistence = event.persistence;
|
|
}
|
|
if (!this.historyClaimed) this.history.push(event);
|
|
for (const listener of this.listeners) listener(event);
|
|
}
|
|
}
|
|
|
|
function normalizeConnection(connection: ProviderConnection): ProviderConnection {
|
|
const capabilities = PROVIDER_CAPABILITIES.filter((capability) =>
|
|
connection.capabilities.includes(capability),
|
|
);
|
|
return {
|
|
version: connection.version,
|
|
capabilities,
|
|
send: (input) => connection.send(ProviderInputSchema.parse(input)),
|
|
onEvent: (listener) =>
|
|
connection.onEvent((event) => listener(ProviderEventSchema.parse(event))),
|
|
close: () => connection.close(),
|
|
};
|
|
}
|
|
|
|
interface AdaptedPluginProvider {
|
|
registration: ProviderRegistration;
|
|
client: PluginAgentClient;
|
|
definition: RegisteredProviderDefinition;
|
|
clients: Set<PluginAgentClient>;
|
|
}
|
|
|
|
/** Owns the complete plugin-provider adaptation behind the existing core provider boundary. */
|
|
export class PluginAgentClientRegistry {
|
|
private readonly providers = new Map<string, AdaptedPluginProvider>();
|
|
|
|
constructor(private readonly logger: Logger) {}
|
|
|
|
replace(registrations: readonly ProviderRegistration[]): void {
|
|
const incoming = new Map<string, ProviderRegistration>();
|
|
for (const registration of registrations) {
|
|
if (incoming.has(registration.id)) {
|
|
throw new Error(`Duplicate plugin provider ID: ${registration.id}`);
|
|
}
|
|
incoming.set(registration.id, registration);
|
|
}
|
|
|
|
for (const [id, adapted] of this.providers) {
|
|
if (incoming.get(id) === adapted.registration) continue;
|
|
this.providers.delete(id);
|
|
void Promise.all([...adapted.clients].map((client) => client.shutdown())).catch((error) => {
|
|
this.logger.warn({ err: error, provider: id }, "Failed to stop plugin provider");
|
|
});
|
|
}
|
|
|
|
for (const [id, registration] of incoming) {
|
|
if (this.providers.has(id)) continue;
|
|
const client = new PluginAgentClient(registration);
|
|
const clients = new Set([client]);
|
|
const definition = createPluginProviderDefinition(
|
|
registration,
|
|
(_logger, runtimeSettings) => {
|
|
const configuredClient = new PluginAgentClient(registration, runtimeSettings);
|
|
clients.add(configuredClient);
|
|
return configuredClient;
|
|
},
|
|
);
|
|
this.providers.set(id, { registration, client, definition, clients });
|
|
}
|
|
}
|
|
|
|
definitions(): Record<string, RegisteredProviderDefinition> {
|
|
return Object.fromEntries(
|
|
[...this.providers].map(([id, provider]) => [id, provider.definition]),
|
|
);
|
|
}
|
|
|
|
clients(): Record<string, AgentClient> {
|
|
return Object.fromEntries([...this.providers].map(([id, provider]) => [id, provider.client]));
|
|
}
|
|
|
|
has(provider: string): boolean {
|
|
return this.providers.has(provider);
|
|
}
|
|
|
|
async shutdown(): Promise<void> {
|
|
const providers = [...this.providers.values()];
|
|
this.providers.clear();
|
|
await Promise.all(
|
|
providers.flatMap(({ clients }) => [...clients].map((client) => client.shutdown())),
|
|
);
|
|
}
|
|
}
|
|
|
|
function createPluginProviderDefinition(
|
|
registration: ProviderRegistration,
|
|
createClient: RegisteredProviderDefinition["createClient"],
|
|
): RegisteredProviderDefinition {
|
|
return {
|
|
id: registration.id,
|
|
label: registration.label,
|
|
description: registration.description ?? `Plugin provider ${registration.label}`,
|
|
iconSvg: registration.icon,
|
|
docsUrl: registration.docsUrl,
|
|
requiresConfiguration: registration.requiresConfiguration,
|
|
defaultModeId: null,
|
|
modes: [],
|
|
supportsExactMcpPreapproval: true,
|
|
createClient,
|
|
};
|
|
}
|
|
|
|
interface PendingChild {
|
|
session: ProviderRuntimeSession;
|
|
opened: Extract<ProviderEvent, { type: "session.opened" }>;
|
|
}
|
|
|
|
class PluginAgentClient implements AgentClient {
|
|
readonly provider: string;
|
|
private readonly label: string;
|
|
private readonly runtime: ProviderRuntime;
|
|
private readonly rootsBySession = new Map<string, PluginAgentSession>();
|
|
private readonly pendingChildren: PendingChild[] = [];
|
|
|
|
readonly getCatalogCacheKey?: AgentClient["getCatalogCacheKey"];
|
|
readonly installation?: AgentClientInstallation;
|
|
|
|
constructor(registration: ProviderRegistration, runtimeSettings?: ProviderRuntimeSettings) {
|
|
this.provider = registration.id;
|
|
this.label = registration.label;
|
|
this.runtime = new ProviderRuntime(registration, runtimeSettings);
|
|
if (registration.getCatalogCacheKey)
|
|
this.getCatalogCacheKey = (options) => this.runtime.catalogCacheKey(options);
|
|
const installation = registration.installation;
|
|
if (installation)
|
|
this.installation = {
|
|
installUrl: installation.installUrl,
|
|
updateUrl: installation.updateUrl,
|
|
inspect: installation.inspect
|
|
? ({ signal }) => this.runtime.inspectInstallation(signal)
|
|
: undefined,
|
|
checkForUpdates: installation.checkForUpdates
|
|
? (context) => this.runtime.checkForUpdates(context)
|
|
: undefined,
|
|
update: installation.update ? (context) => this.runtime.update(context) : undefined,
|
|
};
|
|
this.runtime.onSessionOpened((session, opened) => this.acceptChild(session, opened));
|
|
}
|
|
|
|
resolveUsageLaunch() {
|
|
return this.runtime.resolveUsageLaunch();
|
|
}
|
|
|
|
get capabilities(): AgentCapabilityFlags {
|
|
return agentCapabilities(this.runtime.negotiatedCapabilities);
|
|
}
|
|
|
|
async createSession(
|
|
config: AgentSessionConfig,
|
|
launchContext?: AgentLaunchContext,
|
|
options?: AgentCreateSessionOptions,
|
|
): Promise<AgentSession> {
|
|
return await this.openSession({
|
|
config,
|
|
launchContext,
|
|
history: "skip",
|
|
persist: options?.persistSession !== false,
|
|
});
|
|
}
|
|
|
|
async resumeSession(
|
|
handle: AgentPersistenceHandle,
|
|
overrides?: Partial<AgentSessionConfig>,
|
|
launchContext?: AgentLaunchContext,
|
|
): Promise<AgentSession> {
|
|
if (!overrides?.cwd) {
|
|
throw new Error(`Plugin provider '${this.provider}' requires cwd to resume a session`);
|
|
}
|
|
return await this.openSession({
|
|
config: { ...overrides, provider: this.provider, cwd: overrides.cwd },
|
|
launchContext,
|
|
persistence: decodePersistence(handle),
|
|
history: "replay",
|
|
persist: true,
|
|
});
|
|
}
|
|
|
|
async fetchCatalog(
|
|
options: FetchCatalogOptions,
|
|
context?: ProviderRefreshContext,
|
|
): Promise<ProviderCatalog> {
|
|
const catalog = await this.runtime.catalog(
|
|
options.scope === "workspace" ? options.cwd : undefined,
|
|
context?.signal,
|
|
);
|
|
return {
|
|
models: catalog.models.map((model) =>
|
|
mapModel(
|
|
this.provider,
|
|
model,
|
|
catalog.defaultModel,
|
|
catalog.thinkingOptions,
|
|
catalog.defaultThinkingOption,
|
|
),
|
|
),
|
|
modes: catalog.modes.map((mode) => ({ ...mode })),
|
|
defaultModeId: catalog.defaultMode,
|
|
};
|
|
}
|
|
|
|
async isAvailable(signal?: AbortSignal): Promise<boolean> {
|
|
signal?.throwIfAborted();
|
|
return await this.runtime.isAvailable();
|
|
}
|
|
|
|
async getDiagnostic(context: AgentClientDiagnosticContext): Promise<{ diagnostic: string }> {
|
|
const [rows, status] = await Promise.all([
|
|
this.runtime.launchDiagnosticRows(context),
|
|
this.runtime.status(),
|
|
]);
|
|
const report = [formatProviderDiagnostic(this.label, rows)];
|
|
if (!status.available) report.push(` Error: ${status.diagnostic}`);
|
|
// An available provider adds its own rows, one per line.
|
|
else if (status.diagnostic) {
|
|
for (const line of status.diagnostic.split("\n")) {
|
|
if (line.trim()) report.push(` ${line.trim()}`);
|
|
}
|
|
}
|
|
return { diagnostic: report.join("\n") };
|
|
}
|
|
|
|
async listImportableSessions(
|
|
options: ListImportableSessionsOptions = {},
|
|
): Promise<ImportableProviderSession[]> {
|
|
const sessions = await this.runtime.listSessions({
|
|
query: options.query,
|
|
cwd: options.cwd,
|
|
limit: options.limit,
|
|
});
|
|
return sessions.map((session) => ({
|
|
providerHandleId: encodePersistence(session.persistence),
|
|
cwd: session.cwd,
|
|
title: session.title ?? null,
|
|
firstPromptPreview: null,
|
|
lastPromptPreview: session.description ?? null,
|
|
lastActivityAt: parseProviderDate(session.updatedAt),
|
|
}));
|
|
}
|
|
|
|
async importSession(
|
|
input: ImportProviderSessionInput,
|
|
context: ImportProviderSessionContext,
|
|
): Promise<ImportedProviderSession> {
|
|
const session = await this.openSession({
|
|
config: { ...context.config, provider: this.provider, cwd: input.cwd },
|
|
launchContext: context.launchContext,
|
|
persistence: decodePersistenceId(input.providerHandleId),
|
|
history: "replay",
|
|
persist: true,
|
|
});
|
|
const persistence = session.describePersistence();
|
|
if (!persistence) throw new Error(`Plugin provider '${this.provider}' did not persist import`);
|
|
return {
|
|
session,
|
|
config: { ...context.storedConfig, provider: this.provider, cwd: input.cwd },
|
|
persistence,
|
|
...session.importedHistory(),
|
|
};
|
|
}
|
|
|
|
async archiveNativeSession(handle: AgentPersistenceHandle): Promise<void> {
|
|
await this.runtime.archive(decodePersistence(handle));
|
|
}
|
|
|
|
async unarchiveNativeSession(handle: AgentPersistenceHandle): Promise<void> {
|
|
await this.runtime.unarchive(decodePersistence(handle));
|
|
}
|
|
|
|
async shutdown(): Promise<void> {
|
|
await this.runtime.close();
|
|
}
|
|
|
|
private async openSession(input: {
|
|
config: AgentSessionConfig;
|
|
launchContext?: AgentLaunchContext;
|
|
persistence?: ProviderPersistence;
|
|
history: "replay" | "skip";
|
|
persist: boolean;
|
|
}): Promise<PluginAgentSession> {
|
|
const sessionId = randomUUID();
|
|
const bridge = await this.runtime.openSession({
|
|
sessionId,
|
|
config: mapSessionConfig(input.config, input.launchContext, input.persist),
|
|
persistence: input.persistence,
|
|
history: input.history,
|
|
});
|
|
const forget = () => {
|
|
for (const [id, owner] of this.rootsBySession) {
|
|
if (owner === session) this.rootsBySession.delete(id);
|
|
}
|
|
};
|
|
const bind = (next: ProviderRuntimeSession) => {
|
|
this.rootsBySession.set(next.id, session);
|
|
this.attachPendingChildren();
|
|
};
|
|
const config = mapSessionConfig(input.config, input.launchContext, input.persist);
|
|
const session = new PluginAgentSession(
|
|
this.provider,
|
|
bridge,
|
|
forget,
|
|
async (persistence, state, options) => {
|
|
forget();
|
|
return await this.runtime.openSession({
|
|
sessionId: randomUUID(),
|
|
config: {
|
|
...config,
|
|
model: state.model,
|
|
mode: state.mode,
|
|
thinkingOption: state.thinkingOption,
|
|
settings: options,
|
|
providerOptions: options,
|
|
},
|
|
persistence,
|
|
history: "replay",
|
|
});
|
|
},
|
|
bind,
|
|
config.settings,
|
|
this.runtime.connectedLaunch
|
|
? {
|
|
...this.runtime.connectedLaunch,
|
|
env: { ...this.runtime.connectedLaunch.env, ...config.env },
|
|
}
|
|
: undefined,
|
|
);
|
|
bind(bridge);
|
|
return session;
|
|
}
|
|
|
|
private acceptChild(
|
|
session: ProviderRuntimeSession,
|
|
opened: Extract<ProviderEvent, { type: "session.opened" }>,
|
|
): void {
|
|
const root = opened.parentSessionId
|
|
? this.rootsBySession.get(opened.parentSessionId)
|
|
: undefined;
|
|
if (!root) {
|
|
this.pendingChildren.push({ session, opened });
|
|
return;
|
|
}
|
|
root.attachChild(session, opened);
|
|
this.rootsBySession.set(session.id, root);
|
|
this.attachPendingChildren();
|
|
}
|
|
|
|
private attachPendingChildren(): void {
|
|
let attached = true;
|
|
while (attached) {
|
|
attached = false;
|
|
for (let index = this.pendingChildren.length - 1; index >= 0; index -= 1) {
|
|
const pending = this.pendingChildren[index];
|
|
const root = pending.opened.parentSessionId
|
|
? this.rootsBySession.get(pending.opened.parentSessionId)
|
|
: undefined;
|
|
if (!root) continue;
|
|
this.pendingChildren.splice(index, 1);
|
|
root.attachChild(pending.session, pending.opened);
|
|
this.rootsBySession.set(pending.session.id, root);
|
|
attached = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
interface TimelineTextSnapshot {
|
|
type: "assistant_message" | "reasoning" | "user_message";
|
|
text: string;
|
|
}
|
|
|
|
function isTextSnapshotItem(
|
|
item: ProviderTimelineItem,
|
|
): item is Extract<ProviderTimelineItem, { type: TimelineTextSnapshot["type"] }> {
|
|
return (
|
|
item.type === "assistant_message" || item.type === "reasoning" || item.type === "user_message"
|
|
);
|
|
}
|
|
|
|
class PluginAgentSession implements AgentSession {
|
|
readonly initialTimeline: ImportedProviderSession["timeline"];
|
|
private readonly listeners = new Set<(event: AgentStreamEvent) => void>();
|
|
private readonly history = new PluginSessionHistory();
|
|
private readonly pendingPermissions = new Map<string, AgentPermissionRequest>();
|
|
private readonly permissionResponses = new Map<string, AgentPermissionResponse>();
|
|
private readonly revertTokens = new Map<string, ProviderTimelineItem["revertToken"]>();
|
|
private readonly timelineSnapshots = new Map<string, TimelineTextSnapshot>();
|
|
private readonly subagentIdsBySession = new Map<string, string | null>();
|
|
private readonly children = new Map<
|
|
string,
|
|
{ session: ProviderRuntimeSession; unsubscribe: () => void }
|
|
>();
|
|
private readonly childSnapshots = new Map<string, Map<string, TimelineTextSnapshot>>();
|
|
// Outcome of each child's latest finished turn, so a plain close does not report it as completed.
|
|
private readonly childTurnOutcomes = new Map<string, "completed" | "canceled" | "failed">();
|
|
private unsubscribe: (() => void) | null = null;
|
|
/** How the opened session differs from the options it was given. */
|
|
readonly openOptionsPatch: Record<string, JsonValue>;
|
|
private knownOptions: Record<string, JsonValue> = {};
|
|
// The options a reopened session starts with: what it launched with, then every value the
|
|
// plugin reported or was given, minus every key that was reset.
|
|
private readonly committedOptions: Record<string, JsonValue>;
|
|
/** While `applyOptions` waits on the plugin, its `session.config` answers that call. */
|
|
private applyingOptions = false;
|
|
private currentTurnId: string | null = null;
|
|
private closed = false;
|
|
private replay: {
|
|
persistence: ProviderPersistence;
|
|
config: ProviderConfigState;
|
|
messageId: string;
|
|
scope: "conversation" | "both";
|
|
closed: boolean;
|
|
} | null = null;
|
|
private replaying: Promise<void> | null = null;
|
|
|
|
constructor(
|
|
readonly provider: string,
|
|
private bridge: ProviderRuntimeSession,
|
|
private readonly onClose: () => void,
|
|
private readonly reopen: (
|
|
persistence: ProviderPersistence,
|
|
state: ProviderConfigState,
|
|
options: Readonly<Record<string, JsonValue>>,
|
|
) => Promise<ProviderRuntimeSession>,
|
|
private readonly onBind: (bridge: ProviderRuntimeSession) => void,
|
|
givenOptions: Readonly<Record<string, JsonValue>>,
|
|
private readonly usageLaunch: ProviderLaunch | undefined,
|
|
) {
|
|
this.subagentIdsBySession.set(bridge.id, null);
|
|
// Every setting the session opened with that was not given, including ones nobody set.
|
|
this.committedOptions = { ...givenOptions };
|
|
this.openOptionsPatch = this.optionDifferences(givenOptions);
|
|
this.commitOptions();
|
|
for (const event of bridge.history) this.accept(event, false);
|
|
// Opening notices arrive before the manager subscribes to the session.
|
|
// Commit them on registration and replay the same timestamps from history.
|
|
this.initialTimeline = this.timelineHistory().filter(
|
|
(entry) => entry.item.type === "notification",
|
|
);
|
|
this.unsubscribe = bridge.onEvent((event) => this.accept(event, true));
|
|
}
|
|
|
|
usageSession() {
|
|
if (this.closed || !this.usageLaunch) return null;
|
|
return {
|
|
provider: this.provider,
|
|
model: this.bridge.config.model,
|
|
env: this.usageLaunch.env,
|
|
launch: this.usageLaunch,
|
|
sessionKey: this.bridge.id,
|
|
};
|
|
}
|
|
|
|
get id(): string {
|
|
return this.describePersistence()?.sessionId ?? this.bridge.id;
|
|
}
|
|
|
|
get capabilities(): AgentCapabilityFlags {
|
|
const capabilities = agentCapabilities(this.bridge.negotiatedCapabilities);
|
|
const resumable = this.canReplayHistory;
|
|
return {
|
|
...capabilities,
|
|
supportsRewindConversation: capabilities.supportsRewindConversation && resumable,
|
|
supportsRewindBoth: capabilities.supportsRewindBoth && resumable,
|
|
};
|
|
}
|
|
|
|
get controls(): AgentOptionControl[] {
|
|
return readPluginOptionState(this.bridge.config).controls;
|
|
}
|
|
|
|
async run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult> {
|
|
return await runProviderTurn({
|
|
prompt,
|
|
runOptions: options,
|
|
startTurn: (nextPrompt, nextOptions) => this.startTurn(nextPrompt, nextOptions),
|
|
subscribe: (callback) => this.subscribe(callback),
|
|
getSessionId: () => this.id,
|
|
});
|
|
}
|
|
|
|
async startTurn(
|
|
prompt: AgentPromptInput,
|
|
options: AgentRunOptions = {},
|
|
): Promise<{ turnId: string }> {
|
|
this.assertReplayComplete();
|
|
const clientMessageId = options.clientMessageId ?? randomUUID();
|
|
const result = await this.bridge.prompt({
|
|
clientMessageId,
|
|
delivery: "auto",
|
|
input: mapPromptInput(prompt, this.bridge.commands),
|
|
...(options.outputSchema === undefined
|
|
? {}
|
|
: { outputSchema: toJsonValue(options.outputSchema, "output schema") }),
|
|
});
|
|
if (result.type === "failed") throw providerError(result.error);
|
|
if (result.type === "turn" || result.type === "steer") return { turnId: result.turnId };
|
|
|
|
const turnId = `command-${clientMessageId}`;
|
|
this.publish({ type: "turn_started", provider: this.provider, turnId });
|
|
this.publish({ type: "turn_completed", provider: this.provider, turnId });
|
|
return { turnId };
|
|
}
|
|
|
|
/** Offered only when the provider negotiated prompt.steer, so callers can ask before steering. */
|
|
get steerActiveTurn():
|
|
| ((prompt: AgentPromptInput, options: SteerActiveTurnOptions) => Promise<SteerResult>)
|
|
| undefined {
|
|
if (!this.bridge.negotiatedCapabilities.includes("prompt.steer")) return undefined;
|
|
return (prompt, options) => this.steer(prompt, options);
|
|
}
|
|
|
|
private async steer(
|
|
prompt: AgentPromptInput,
|
|
options: SteerActiveTurnOptions,
|
|
): Promise<SteerResult> {
|
|
this.assertReplayComplete();
|
|
const result = await this.bridge.prompt({
|
|
clientMessageId: options.clientMessageId ?? randomUUID(),
|
|
delivery: "steer",
|
|
input: { type: "message", content: mapPromptContent(prompt) },
|
|
...(options.outputSchema === undefined
|
|
? {}
|
|
: { outputSchema: toJsonValue(options.outputSchema, "output schema") }),
|
|
clearPendingPermissions: options.clearPendingPermissions,
|
|
});
|
|
return result.type === "steer" && result.turnId === options.expectedTurnId
|
|
? { status: "accepted" }
|
|
: { status: "unavailable" };
|
|
}
|
|
|
|
subscribe(callback: (event: AgentStreamEvent) => void): () => void {
|
|
this.listeners.add(callback);
|
|
return () => this.listeners.delete(callback);
|
|
}
|
|
|
|
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
|
|
await this.ensureReplay();
|
|
for (const event of this.history.read(this.provider)) yield event;
|
|
}
|
|
|
|
get canStopRuntime(): (() => Promise<boolean>) | undefined {
|
|
if (!this.bridge.negotiatedCapabilities.includes("session.can_stop_runtime")) return undefined;
|
|
return () => this.bridge.canStopRuntime();
|
|
}
|
|
|
|
async getRuntimeInfo() {
|
|
return {
|
|
provider: this.provider,
|
|
sessionId: this.id,
|
|
model: this.bridge.config.model ?? null,
|
|
modeId: this.bridge.config.mode ?? null,
|
|
thinkingOptionId: this.bridge.config.thinkingOption ?? null,
|
|
};
|
|
}
|
|
|
|
async getAvailableModes(): Promise<AgentMode[]> {
|
|
return this.bridge.config.modes.map((mode) => ({ ...mode }));
|
|
}
|
|
|
|
async getCurrentMode(): Promise<string | null> {
|
|
return this.bridge.config.mode ?? null;
|
|
}
|
|
|
|
async setMode(modeId: string): Promise<void> {
|
|
this.assertReplayComplete();
|
|
await this.bridge.configure({ mode: modeId });
|
|
}
|
|
|
|
getPendingPermissions(): AgentPermissionRequest[] {
|
|
return [...this.pendingPermissions.values()];
|
|
}
|
|
|
|
async respondToPermission(requestId: string, response: AgentPermissionResponse): Promise<void> {
|
|
this.permissionResponses.set(requestId, response);
|
|
try {
|
|
await this.bridge.respondToPermission(
|
|
requestId,
|
|
toJsonValue(response, "permission response") as Extract<
|
|
ProviderInput,
|
|
{ type: "session.permission" }
|
|
>["response"],
|
|
);
|
|
} catch (error) {
|
|
this.permissionResponses.delete(requestId);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
describePersistence(): AgentPersistenceHandle | null {
|
|
return this.bridge.persistence
|
|
? persistenceHandle(this.provider, this.bridge.persistence)
|
|
: null;
|
|
}
|
|
|
|
async interrupt(): Promise<void> {
|
|
await this.bridge.interrupt();
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
if (this.closed) return;
|
|
this.closed = true;
|
|
this.listeners.clear();
|
|
await this.replaying?.catch(() => undefined);
|
|
await this.clearBinding();
|
|
this.replay = null;
|
|
this.listeners.clear();
|
|
this.onClose();
|
|
await this.bridge.close();
|
|
}
|
|
|
|
async listCommands(): Promise<AgentSlashCommand[]> {
|
|
return this.bridge.commands.map((command) => ({
|
|
...command,
|
|
argumentHint: command.argumentHint ?? "",
|
|
kind: command.kind ?? "command",
|
|
}));
|
|
}
|
|
|
|
async setModel(modelId: string | null): Promise<{ model: string | null }> {
|
|
this.assertReplayComplete();
|
|
await this.bridge.configure({ model: modelId });
|
|
return { model: this.bridge.config.model ?? null };
|
|
}
|
|
|
|
async setThinkingOption(thinkingOptionId: string | null): Promise<void> {
|
|
this.assertReplayComplete();
|
|
await this.bridge.configure({ thinkingOption: thinkingOptionId });
|
|
}
|
|
|
|
/** The agent manager sends one apply at a time per session. */
|
|
async applyOptions(options: ProviderOptions): Promise<Record<string, JsonValue>> {
|
|
this.assertReplayComplete();
|
|
const before = this.currentOptions();
|
|
const { legacySettings } = readPluginOptionState(this.bridge.config);
|
|
// The plugin applies every key it is given or rejects the whole request.
|
|
const settings: Record<string, JsonValue> = {};
|
|
for (const [id, value] of Object.entries(options)) {
|
|
settings[id] = toJsonValue(value, `option '${id}'`);
|
|
}
|
|
if (Object.keys(settings).length === 0) return {};
|
|
this.applyingOptions = true;
|
|
try {
|
|
// COMPAT(plugin-provider-settings): added in v0.15.0, remove after 2027-05-01. A plugin
|
|
// reporting `settings` is sent the same keys under that name.
|
|
await this.bridge.configure({
|
|
providerOptions: settings,
|
|
...(legacySettings ? { settings } : {}),
|
|
});
|
|
} catch (error) {
|
|
// Nothing is stored for a refused patch, so what the plugin moved is reported once the
|
|
// call has ended.
|
|
this.applyingOptions = false;
|
|
for (const event of this.reportOptionChanges()) this.publish(event);
|
|
throw error;
|
|
} finally {
|
|
this.applyingOptions = false;
|
|
}
|
|
// A requested key is a request, not a report: only a key the plugin reported before can be
|
|
// one it has now dropped.
|
|
const ended = this.optionChanges({ ...before, ...settings }, before);
|
|
this.commitOptions(settings);
|
|
return ended;
|
|
}
|
|
|
|
async revertConversation(input: { messageId: string }): Promise<void> {
|
|
await this.revert(input.messageId, "conversation");
|
|
}
|
|
|
|
async revertFiles(input: { messageId: string }): Promise<void> {
|
|
await this.revert(input.messageId, "files");
|
|
}
|
|
|
|
async revertBoth(input: { messageId: string }): Promise<void> {
|
|
await this.revert(input.messageId, "both");
|
|
}
|
|
|
|
timelineHistory(): ImportedProviderSession["timeline"] {
|
|
return this.history
|
|
.read(this.provider)
|
|
.flatMap((event) =>
|
|
event.type === "timeline" ? [{ item: event.item, timestamp: event.timestamp }] : [],
|
|
);
|
|
}
|
|
|
|
importedHistory(): ReturnType<ImportedHistory["result"]> {
|
|
const history = new ImportedHistory();
|
|
for (const event of this.history.read(this.provider)) history.add(event);
|
|
return history.result();
|
|
}
|
|
|
|
attachChild(
|
|
child: ProviderRuntimeSession,
|
|
opened: Extract<ProviderEvent, { type: "session.opened" }>,
|
|
): void {
|
|
const parentSubagentId = opened.parentSessionId
|
|
? this.subagentIdsBySession.get(opened.parentSessionId)
|
|
: undefined;
|
|
if (parentSubagentId === undefined) {
|
|
throw new Error(`Missing plugin child parent ${opened.parentSessionId}`);
|
|
}
|
|
const childId = child.providerId;
|
|
this.subagentIdsBySession.set(child.id, childId);
|
|
this.publish({
|
|
type: "provider_subagent",
|
|
provider: this.provider,
|
|
event: {
|
|
type: "upsert",
|
|
id: childId,
|
|
parentSubagentId,
|
|
toolCallId: opened.toolCallId ?? null,
|
|
title: opened.title ?? null,
|
|
description: opened.description ?? null,
|
|
status: "running",
|
|
cwd: opened.cwd,
|
|
},
|
|
});
|
|
const snapshots = new Map<string, TimelineTextSnapshot>();
|
|
this.childSnapshots.set(childId, snapshots);
|
|
for (const event of child.history) this.acceptChildEvent(childId, event, snapshots);
|
|
this.children.set(child.id, {
|
|
session: child,
|
|
unsubscribe: child.onEvent((event) => this.acceptChildEvent(childId, event, snapshots)),
|
|
});
|
|
}
|
|
|
|
private accept(event: ProviderEvent, live: boolean): void {
|
|
const translated = this.translate(event);
|
|
for (const next of translated) {
|
|
this.history.push(next);
|
|
if (live) this.emit(next);
|
|
}
|
|
}
|
|
|
|
private translate(event: ProviderEvent): AgentStreamEvent[] {
|
|
switch (event.type) {
|
|
case "session.turn":
|
|
return [this.translateTurn(event)];
|
|
case "session.usage":
|
|
return [
|
|
{
|
|
type: "usage_updated",
|
|
provider: this.provider,
|
|
usage: { ...event.usage },
|
|
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":
|
|
return [this.translatePermission(event)];
|
|
case "session.permission_resolved":
|
|
return [this.translatePermissionResolution(event)];
|
|
case "session.config":
|
|
return this.translateConfig(event);
|
|
case "session.notice":
|
|
return this.translateNotice(event);
|
|
case "session.runtime_failed":
|
|
return [this.translateFailure(event.error)];
|
|
case "session.closed":
|
|
return event.error ? [this.translateFailure(event.error)] : [];
|
|
default:
|
|
return [];
|
|
}
|
|
}
|
|
|
|
private translateTurn(event: Extract<ProviderEvent, { type: "session.turn" }>): AgentStreamEvent {
|
|
if (event.state === "started") {
|
|
this.currentTurnId = event.turnId;
|
|
return { type: "turn_started", provider: this.provider, turnId: event.turnId };
|
|
}
|
|
if (this.currentTurnId === event.turnId) this.currentTurnId = null;
|
|
if (event.state === "completed") {
|
|
return {
|
|
type: "turn_completed",
|
|
provider: this.provider,
|
|
turnId: event.turnId,
|
|
...(event.metrics ? { metrics: event.metrics.map((metric) => ({ ...metric })) } : {}),
|
|
};
|
|
}
|
|
if (event.state === "canceled") {
|
|
return {
|
|
type: "turn_canceled",
|
|
provider: this.provider,
|
|
turnId: event.turnId,
|
|
reason: event.error?.message ?? "Canceled by provider",
|
|
};
|
|
}
|
|
return {
|
|
type: "turn_failed",
|
|
provider: this.provider,
|
|
turnId: event.turnId,
|
|
error: event.error?.message ?? "Provider turn failed",
|
|
code: event.error?.code,
|
|
diagnostic: event.error?.diagnostic,
|
|
};
|
|
}
|
|
|
|
private translateTimeline(
|
|
event: Extract<ProviderEvent, { type: "timeline.item" }>,
|
|
): AgentStreamEvent[] {
|
|
const item = mapTimelineItem(event.item, this.timelineSnapshots, this.revertTokens);
|
|
return item
|
|
? [
|
|
{
|
|
type: "timeline",
|
|
provider: this.provider,
|
|
item,
|
|
turnId: this.currentTurnId ?? undefined,
|
|
timestamp: event.timestamp,
|
|
},
|
|
]
|
|
: [];
|
|
}
|
|
|
|
private translatePermission(
|
|
event: Extract<ProviderEvent, { type: "session.permission" }>,
|
|
): AgentStreamEvent {
|
|
const request: AgentPermissionRequest = { ...event.request, provider: this.provider };
|
|
this.pendingPermissions.set(request.id, request);
|
|
return {
|
|
type: "permission_requested",
|
|
provider: this.provider,
|
|
request,
|
|
turnId: this.currentTurnId ?? undefined,
|
|
};
|
|
}
|
|
|
|
private translatePermissionResolution(
|
|
event: Extract<ProviderEvent, { type: "session.permission_resolved" }>,
|
|
): AgentStreamEvent {
|
|
this.pendingPermissions.delete(event.permissionId);
|
|
const resolution = this.permissionResponses.get(event.permissionId) ?? {
|
|
behavior: "deny" as const,
|
|
message: "Resolved by provider",
|
|
};
|
|
this.permissionResponses.delete(event.permissionId);
|
|
return {
|
|
type: "permission_resolved",
|
|
provider: this.provider,
|
|
requestId: event.permissionId,
|
|
resolution,
|
|
turnId: this.currentTurnId ?? undefined,
|
|
};
|
|
}
|
|
|
|
private currentOptions(): Record<string, JsonValue> {
|
|
return readPluginOptionState(this.bridge.config).options;
|
|
}
|
|
|
|
/** Options whose value differs from `known`: the plugin's own change or its opening state. */
|
|
private optionDifferences(known: Readonly<Record<string, JsonValue>>): Record<string, JsonValue> {
|
|
const patch: Record<string, JsonValue> = {};
|
|
for (const [id, value] of Object.entries(this.currentOptions())) {
|
|
if (!isDeepStrictEqual(known[id], value)) patch[id] = value;
|
|
}
|
|
return patch;
|
|
}
|
|
|
|
/**
|
|
* Settle the options a reopened session starts with: what is committed, then the request the
|
|
* plugin accepted, then what it reported back. A key it reported before and no longer reports
|
|
* was reset.
|
|
*/
|
|
private commitOptions(accepted: Readonly<Record<string, JsonValue>> = {}): void {
|
|
for (const [id, value] of Object.entries(accepted)) {
|
|
if (value === null) delete this.committedOptions[id];
|
|
else this.committedOptions[id] = value;
|
|
}
|
|
const current = this.currentOptions();
|
|
for (const id of Object.keys(this.knownOptions)) {
|
|
if (!(id in current)) delete this.committedOptions[id];
|
|
}
|
|
Object.assign(this.committedOptions, current);
|
|
this.knownOptions = current;
|
|
}
|
|
|
|
/**
|
|
* What changed against the options `known` to be set: values that differ, and `null` for a key
|
|
* in `reported` that the plugin no longer reports, which went back to its default.
|
|
*/
|
|
private optionChanges(
|
|
known: Readonly<Record<string, JsonValue>>,
|
|
reported: Readonly<Record<string, JsonValue>>,
|
|
): Record<string, JsonValue> {
|
|
const patch = this.optionDifferences(known);
|
|
const current = this.currentOptions();
|
|
for (const id of Object.keys(reported)) {
|
|
if (known[id] !== null && !(id in current)) patch[id] = null;
|
|
}
|
|
return patch;
|
|
}
|
|
|
|
private reportOptionChanges(): AgentStreamEvent[] {
|
|
if (this.applyingOptions) return [];
|
|
const patch = this.optionChanges(this.knownOptions, this.knownOptions);
|
|
if (Object.keys(patch).length === 0) return [];
|
|
this.commitOptions();
|
|
return [{ type: "options_changed", provider: this.provider, patch }];
|
|
}
|
|
|
|
private translateConfig(
|
|
event: Extract<ProviderEvent, { type: "session.config" }>,
|
|
): AgentStreamEvent[] {
|
|
return [
|
|
...this.reportOptionChanges(),
|
|
{
|
|
type: "mode_changed",
|
|
provider: this.provider,
|
|
currentModeId: event.config.mode ?? null,
|
|
availableModes: event.config.modes.map((mode) => ({ ...mode })),
|
|
},
|
|
{
|
|
type: "model_changed",
|
|
provider: this.provider,
|
|
runtimeInfo: {
|
|
provider: this.provider,
|
|
sessionId: this.id,
|
|
model: event.config.model ?? null,
|
|
modeId: event.config.mode ?? null,
|
|
thinkingOptionId: event.config.thinkingOption ?? null,
|
|
},
|
|
},
|
|
{
|
|
type: "thinking_option_changed",
|
|
provider: this.provider,
|
|
thinkingOptionId: event.config.thinkingOption ?? null,
|
|
},
|
|
];
|
|
}
|
|
|
|
private translateNotice(
|
|
event: Extract<ProviderEvent, { type: "session.notice" }>,
|
|
): AgentStreamEvent[] {
|
|
if (event.notice.dismissed) return [];
|
|
return [
|
|
{
|
|
type: "timeline",
|
|
provider: this.provider,
|
|
timestamp: new Date().toISOString(),
|
|
item: {
|
|
type: "notification",
|
|
level: event.notice.severity,
|
|
message: [event.notice.title, event.notice.description].filter(Boolean).join("\n"),
|
|
},
|
|
turnId: this.currentTurnId ?? undefined,
|
|
},
|
|
];
|
|
}
|
|
|
|
private translateFailure(error: ProviderError): AgentStreamEvent {
|
|
return {
|
|
type: "turn_failed",
|
|
provider: this.provider,
|
|
turnId: this.currentTurnId ?? undefined,
|
|
error: error.message,
|
|
code: error.code,
|
|
diagnostic: error.diagnostic,
|
|
};
|
|
}
|
|
|
|
private acceptChildEvent(
|
|
childId: string,
|
|
event: ProviderEvent,
|
|
snapshots: Map<string, TimelineTextSnapshot>,
|
|
): void {
|
|
if (event.type === "timeline.item") {
|
|
const item = mapTimelineItem(event.item, snapshots);
|
|
if (item) {
|
|
this.publish({
|
|
type: "provider_subagent",
|
|
provider: this.provider,
|
|
event: { type: "timeline", id: childId, item, timestamp: event.timestamp },
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
if (event.type === "session.turn") {
|
|
if (event.state === "started") {
|
|
this.childTurnOutcomes.delete(childId);
|
|
} else {
|
|
this.childTurnOutcomes.set(childId, event.state);
|
|
}
|
|
this.publish({
|
|
type: "provider_subagent",
|
|
provider: this.provider,
|
|
event: {
|
|
type: "upsert",
|
|
id: childId,
|
|
status: event.state === "started" ? "running" : event.state,
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
if (event.type === "session.runtime_failed" || event.type === "session.closed") {
|
|
this.publish({
|
|
type: "provider_subagent",
|
|
provider: this.provider,
|
|
event: {
|
|
type: "upsert",
|
|
id: childId,
|
|
status:
|
|
event.type === "session.runtime_failed" || event.error
|
|
? "failed"
|
|
: (this.childTurnOutcomes.get(childId) ?? "completed"),
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
private async clearBinding(): Promise<void> {
|
|
this.unsubscribe?.();
|
|
this.unsubscribe = null;
|
|
for (const child of this.children.values()) {
|
|
child.unsubscribe();
|
|
await child.session.close();
|
|
}
|
|
this.children.clear();
|
|
this.subagentIdsBySession.clear();
|
|
this.history.clear();
|
|
this.timelineSnapshots.clear();
|
|
this.childSnapshots.clear();
|
|
this.childTurnOutcomes.clear();
|
|
this.revertTokens.clear();
|
|
this.pendingPermissions.clear();
|
|
this.permissionResponses.clear();
|
|
this.currentTurnId = null;
|
|
}
|
|
|
|
private assertReplayComplete(): void {
|
|
if (this.replay) {
|
|
throw new Error(
|
|
"Plugin rewind history refresh is incomplete. Retry the rewind or reload the agent before continuing.",
|
|
);
|
|
}
|
|
}
|
|
|
|
// A native rewind has already committed. Until replay succeeds, neither history
|
|
// nor a new prompt may use the retired binding. Keep its latest handle for retry.
|
|
private async ensureReplay(): Promise<void> {
|
|
if (!this.replay) return;
|
|
if (this.closed) throw new StaleProviderSessionError(this.id);
|
|
if (!this.replaying) {
|
|
this.replaying = this.replayBinding().finally(() => {
|
|
this.replaying = null;
|
|
});
|
|
}
|
|
await this.replaying;
|
|
}
|
|
|
|
private async replayBinding(): Promise<void> {
|
|
const replay = this.replay!;
|
|
if (!replay.closed) {
|
|
for (const request of this.pendingPermissions.values()) {
|
|
await this.respondToPermission(request.id, {
|
|
behavior: "deny",
|
|
message: "Session replaced after rewind",
|
|
});
|
|
this.pendingPermissions.delete(request.id);
|
|
this.permissionResponses.delete(request.id);
|
|
}
|
|
await this.clearBinding();
|
|
await this.bridge.close();
|
|
replay.closed = true;
|
|
}
|
|
const bridge = await this.reopen(replay.persistence, replay.config, this.committedOptions);
|
|
this.bridge = bridge;
|
|
this.subagentIdsBySession.set(bridge.id, null);
|
|
for (const event of bridge.history) this.accept(event, false);
|
|
this.unsubscribe = bridge.onEvent((event) => this.accept(event, true));
|
|
this.onBind(bridge);
|
|
this.replay = null;
|
|
}
|
|
|
|
private get canReplayHistory(): boolean {
|
|
return (
|
|
this.bridge.restoration === "core" &&
|
|
this.bridge.persistence !== null &&
|
|
this.bridge.negotiatedCapabilities.includes("session.persistence")
|
|
);
|
|
}
|
|
|
|
private async revert(messageId: string, scope: "conversation" | "files" | "both") {
|
|
const pending = this.replay;
|
|
await this.ensureReplay();
|
|
if (pending?.messageId === messageId && pending.scope === scope) return;
|
|
if (scope !== "files" && !this.canReplayHistory) {
|
|
throw new Error("Plugin conversation rewind requires session persistence for history replay");
|
|
}
|
|
const token = this.revertTokens.get(messageId);
|
|
if (token === undefined) throw new Error(`No provider revert token for message ${messageId}`);
|
|
await this.bridge.revert({
|
|
type: "session.revert",
|
|
requestId: randomUUID(),
|
|
sessionId: this.bridge.providerId,
|
|
token,
|
|
scope,
|
|
});
|
|
if (scope !== "files") {
|
|
const persistence = this.bridge.persistence;
|
|
if (!persistence) throw new Error("Plugin rewind removed session persistence");
|
|
this.replay = { persistence, config: this.bridge.config, messageId, scope, closed: false };
|
|
await this.ensureReplay();
|
|
}
|
|
}
|
|
|
|
private publish(event: AgentStreamEvent): void {
|
|
this.history.push(event);
|
|
this.emit(event);
|
|
}
|
|
|
|
private emit(event: AgentStreamEvent): void {
|
|
for (const listener of this.listeners) listener(event);
|
|
}
|
|
}
|
|
|
|
function agentCapabilities(capabilities: readonly string[]): AgentCapabilityFlags {
|
|
const supports = (capability: ProviderCapability) => capabilities.includes(capability);
|
|
return {
|
|
supportsStreaming: true,
|
|
supportsSessionPersistence: supports("session.persistence"),
|
|
supportsSessionListing: supports("session.list"),
|
|
supportsDynamicModes: supports("session.configure"),
|
|
supportsMcpServers: true,
|
|
supportsNativePaseoTools: false,
|
|
supportsReasoningStream: true,
|
|
supportsToolInvocations: true,
|
|
supportsRewindConversation: supports("session.revert.conversation"),
|
|
supportsRewindFiles: supports("session.revert.files"),
|
|
supportsRewindBoth: supports("session.revert.both"),
|
|
};
|
|
}
|
|
|
|
function mapModel(
|
|
provider: string,
|
|
model: Extract<ProviderEvent, { type: "catalog" }>["catalog"]["models"][number],
|
|
defaultModel: string | undefined,
|
|
catalogThinkingOptions: Extract<ProviderEvent, { type: "catalog" }>["catalog"]["thinkingOptions"],
|
|
catalogDefaultThinkingOption: string | undefined,
|
|
): AgentModelDefinition {
|
|
const thinkingOptions = model.thinkingOptions ?? catalogThinkingOptions;
|
|
return {
|
|
...model,
|
|
provider,
|
|
isDefault: model.isDefault ?? model.id === defaultModel,
|
|
metadata: model.metadata ? { ...model.metadata } : undefined,
|
|
thinkingOptions: thinkingOptions?.map((option) => Object.assign({}, option)),
|
|
defaultThinkingOptionId: model.defaultThinkingOptionId ?? catalogDefaultThinkingOption,
|
|
};
|
|
}
|
|
|
|
function mapSessionConfig(
|
|
config: AgentSessionConfig,
|
|
launchContext: AgentLaunchContext | undefined,
|
|
persist: boolean,
|
|
): ProviderSessionConfig {
|
|
return {
|
|
cwd: config.cwd,
|
|
env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }),
|
|
systemPrompt: combineSystemPrompts(
|
|
config.systemPrompt,
|
|
config.daemonAppendSystemPrompt,
|
|
...(config.pluginAppendSystemPrompt ?? []),
|
|
),
|
|
mcpServers: { ...config.mcpServers },
|
|
toolPolicy: config.toolPolicy
|
|
? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) }
|
|
: undefined,
|
|
model: config.model,
|
|
mode: config.modeId,
|
|
thinkingOption: config.thinkingOptionId,
|
|
// The plugin SDK reads composer values from `settings`; they are options here.
|
|
settings: toJsonObject(config.providerOptions ?? {}, "provider settings"),
|
|
providerOptions: config.providerOptions,
|
|
title: config.title ?? undefined,
|
|
persist,
|
|
};
|
|
}
|
|
|
|
function combineSystemPrompts(
|
|
systemPrompt: string | undefined,
|
|
daemonPrompt: string | undefined,
|
|
...pluginPrompts: string[]
|
|
): string | undefined {
|
|
const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter(
|
|
(value): value is string => typeof value === "string" && value.trim().length > 0,
|
|
);
|
|
return parts.length > 0 ? parts.join("\n\n") : undefined;
|
|
}
|
|
|
|
function mapPromptInput(
|
|
prompt: AgentPromptInput,
|
|
commands: readonly { name: string }[],
|
|
): ProviderPrompt["input"] {
|
|
if (typeof prompt === "string" && prompt.startsWith("/")) {
|
|
const separator = prompt.indexOf(" ");
|
|
const name = prompt.slice(1, separator === -1 ? undefined : separator);
|
|
if (commands.some((command) => command.name === name)) {
|
|
return {
|
|
type: "command",
|
|
name,
|
|
arguments: separator === -1 ? "" : prompt.slice(separator + 1),
|
|
};
|
|
}
|
|
}
|
|
return { type: "message", content: mapPromptContent(prompt) };
|
|
}
|
|
|
|
function mapPromptContent(prompt: AgentPromptInput): ProviderContent[] {
|
|
const content = typeof prompt === "string" ? [{ type: "text" as const, text: prompt }] : prompt;
|
|
return toJsonValue(content, "prompt content") as ProviderContent[];
|
|
}
|
|
|
|
function mapTimelineItem(
|
|
item: ProviderTimelineItem,
|
|
snapshots: Map<string, TimelineTextSnapshot>,
|
|
revertTokens?: Map<string, ProviderTimelineItem["revertToken"]>,
|
|
): AgentTimelineItem | null {
|
|
const previous = snapshots.get(item.id);
|
|
if (isTextSnapshotItem(item)) {
|
|
snapshots.set(item.id, { type: item.type, text: item.text });
|
|
}
|
|
const { id, revertToken: _revertToken, ...withoutIdentity } = item;
|
|
rememberRevertToken(item, revertTokens);
|
|
|
|
if (item.type === "assistant_message" || item.type === "reasoning") {
|
|
const previousText = previous?.type === item.type ? previous.text : "";
|
|
const suffix = item.text.startsWith(previousText)
|
|
? item.text.slice(previousText.length)
|
|
: item.text;
|
|
// Match OpenCode's detachedSuffix: a sliced delta otherwise keeps its entire
|
|
// cumulative IPC snapshot alive in the projected timeline. Preserve split surrogates.
|
|
const text = Buffer.from(suffix, "utf16le").toString("utf16le");
|
|
if (text.length === 0) return null;
|
|
return item.type === "assistant_message"
|
|
? { type: "assistant_message", text, messageId: item.messageId ?? id }
|
|
: { type: "reasoning", text };
|
|
}
|
|
if (item.type === "user_message") {
|
|
if (previous?.type === "user_message" && previous.text === item.text) return null;
|
|
return {
|
|
type: "user_message",
|
|
text: item.text,
|
|
messageId: item.messageId ?? id,
|
|
clientMessageId: item.clientMessageId,
|
|
};
|
|
}
|
|
if (item.type === "plugin") {
|
|
return {
|
|
type: "plugin",
|
|
id,
|
|
pluginId: item.pluginId,
|
|
kind: item.kind,
|
|
version: item.version,
|
|
data: item.data,
|
|
};
|
|
}
|
|
return withoutIdentity as AgentTimelineItem;
|
|
}
|
|
|
|
function rememberRevertToken(
|
|
item: ProviderTimelineItem,
|
|
tokens?: Map<string, ProviderTimelineItem["revertToken"]>,
|
|
): void {
|
|
if (item.revertToken === undefined || !tokens) return;
|
|
tokens.set(item.id, item.revertToken);
|
|
if (item.type === "user_message" || item.type === "assistant_message") {
|
|
tokens.set(item.messageId ?? item.id, item.revertToken);
|
|
}
|
|
}
|
|
|
|
function persistenceHandle(
|
|
provider: string,
|
|
persistence: ProviderPersistence,
|
|
): AgentPersistenceHandle {
|
|
return {
|
|
provider,
|
|
sessionId: encodePersistence(persistence),
|
|
metadata: { pluginProviderPersistence: persistence },
|
|
};
|
|
}
|
|
|
|
function encodePersistence(persistence: ProviderPersistence): string {
|
|
return `plugin:${JSON.stringify(persistence)}`;
|
|
}
|
|
|
|
function decodePersistence(handle: AgentPersistenceHandle): ProviderPersistence {
|
|
const fromMetadata = handle.metadata?.pluginProviderPersistence;
|
|
if (fromMetadata !== undefined) {
|
|
return ProviderPersistenceSchema.parse(fromMetadata);
|
|
}
|
|
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated.
|
|
if (handle.provider === "goose" && !handle.sessionId.startsWith("plugin:")) {
|
|
return { version: 1, data: { sessionId: handle.sessionId } };
|
|
}
|
|
return decodePersistenceId(handle.sessionId);
|
|
}
|
|
|
|
const ProviderPersistenceSchema: z.ZodType<ProviderPersistence> = z
|
|
.object({ version: z.number().int().nonnegative(), data: z.json() })
|
|
.strict();
|
|
|
|
function decodePersistenceId(id: string): ProviderPersistence {
|
|
if (!id.startsWith("plugin:")) throw new Error("Invalid plugin provider persistence handle");
|
|
return ProviderPersistenceSchema.parse(JSON.parse(id.slice("plugin:".length)));
|
|
}
|
|
|
|
function parseProviderDate(value: string | undefined): Date {
|
|
const timestamp = value ? Date.parse(value) : Number.NaN;
|
|
return new Date(Number.isFinite(timestamp) ? timestamp : 0);
|
|
}
|
|
|
|
function toJsonObject(value: unknown, label: string): Record<string, JsonValue> {
|
|
const encoded = toJsonValue(value, label);
|
|
if (typeof encoded !== "object" || encoded === null || Array.isArray(encoded)) {
|
|
throw new Error(`${label} must be a JSON object`);
|
|
}
|
|
return encoded as Record<string, JsonValue>;
|
|
}
|
|
|
|
function toJsonValue(value: unknown, label: string): JsonValue {
|
|
const encoded = JSON.stringify(value);
|
|
if (encoded === undefined) throw new Error(`${label} must be JSON-serializable`);
|
|
return JSON.parse(encoded) as JsonValue;
|
|
}
|