Files
paseo/packages/plugin/src/server/provider.ts
T
Mohamed Boudra 4d29ee415a Show provider versions and run provider updates from provider settings (#9568)
* feat(providers): show installed version and install link in provider settings

Providers can now declare `installation`: install and update links plus an
`inspect` callback that reports installed state and an opaque version string.
Built-in clients and plugin providers share one contract; plugins receive the
daemon-resolved launch with `resolved: false` when the executable is missing,
so they can report not installed instead of failing.

The daemon calls `inspect` only on the new
`provider.installation.inspect.request` RPC, never from availability probing,
discovery or session creation, so a slow version probe cannot delay agents.
Results are cached per client for 30s, deadlined at 20s, and links survive a
failed probe. The app gates the provider sheet's Installation row on
`server_info.features.providerInstallation`, so older hosts show nothing new.

* feat(providers): show available updates in provider settings

Providers can now declare `installation.checkForUpdates`, returning
`current`, `available` with opaque `versions` and `message`, or `unknown`.
The provider decides what counts as newer; Paseo shows its answer as
written and never parses or compares versions.

The check is its own RPC, `provider.installation.check_updates`, so the
installed version never waits on a network lookup. The daemon caches a
conclusive answer for an hour and an inconclusive one for 30s, shares
in-flight calls, and deadlines the call at 25s, below the plugin RPC
timeout. A throw or timeout comes back as `error`, which the app shows as
inconclusive, never as up to date. The sheet's Refresh bypasses the cache.

Codex and Claude Code read the release source their own updaters use:
the Homebrew cask for cask installs, otherwise the GitHub latest release
for Codex and the configured `autoUpdatesChannel` for Claude Code.
`codex doctor --json` reports the same answer but scans local state and
took close to a minute, so it is not used. Muse compares its build with
the launcher's channel manifest, the same rule the launcher updates by.

The install link now shows whenever the provider declares `installUrl`
and is not reported installed: the Install button for `not_installed`, a
quieter "Install instructions" link when the check failed or the
provider only links to a guide.

* feat(providers): run provider updates from provider settings

Providers can declare `update(context)`, and the Installation section shows an Update
button when an update is available. The daemon owns the operation: one per provider,
joined by later requests, kept in memory past client disconnects, streamed to subscribers
through an owned subscription, and aborted only when the daemon stops. The provider's
answer is the outcome; the daemon adds no verification. After success it drops the cached
inspection and update check and refreshes discovery, without restarting agents.

Codex and Claude run their own `update` subcommand and pass the output through. Muse has
no update subcommand, so it does not declare one.

Updater output is capped at 64 KiB per update so a chatty updater cannot grow daemon memory.
Starting an update requires daemon.manage because it runs commands on the host.

* feat(providers): report installation for the remaining providers

Copilot, OpenCode, Pi, Oh My Pi, Antigravity and Hoplite now show an
install link and the installed version in provider settings. Each one
declares only what its CLI offers:

- Update checks ask the source the CLI's own updater reads: Pi's
  latest-version endpoint, `omp update --check`, and Hoplite's
  latest.json. Copilot and OpenCode resolve their release inside the
  binary, so they declare no check.
- Updates run the CLI's own command: `copilot update`, `opencode
  upgrade`, `pi update --self` (leaves Pi packages alone), `omp update`.
  Antigravity and Hoplite document no self-update.

OpenCode's success message asks for a daemon restart, because all
OpenCode agents share one server that keeps running the old version.

* docs(providers): document the provider installation contract

Plugin authors get the contract in the provider guide, with a worked
example that reports a version, checks for an update and runs the CLI's
own updater, and every field, deadline and cache in the reference.
The internal provider and plugin docs record why the three callbacks are
separate, that versions are opaque, that Paseo adds no verification to
an update, and how the plugin bridge carries and cancels each request.

* chore(protocol): mark provider installation as shipping in v0.17.0

main is on the 0.16 beta series, and a promotion ships the tested beta's
content without pulling from main, so this lands in the next minor.

* fix(app): bound update output and show refresh failures in provider settings

The screen appended every progress chunk with no limit while open, so a
noisy updater grew memory and never showed the truncation note that a
reopened screen shows. Progress now folds with the daemon's 64 KiB limit.

A manual refresh stored its result and failure outside the queries the
screen reads, so a failed refresh brought back the old answer with no
warning. Refresh now runs through those queries. It passes staleTime 0
because the app's default staleTime of Infinity would otherwise answer
from the cache.

The not-connected error uses the translated string the i18n check
requires.

* fix(providers): keep update checks in step with the installed version

A conclusive check is cached for an hour and was not tied to the version
it answered for. After a CLI updated outside Paseo, settings showed the
new version and still offered Update to it. When an inspection reports a
different version, the cached check is dropped. Versions are compared
for equality, so they stay opaque.

The release comparison dropped prerelease suffixes, so Codex
0.200.0-alpha.1 looked current against 0.200.0. A prerelease now comes
before the release with the same numbers. Two different prereleases of
the same release are reported as unknown.

* docs(providers): say when Update instructions shows

* fix(providers): reuse a cached update check only for the version it answered

The previous fix dropped the cached check after an inspection settled
with a new version. On reopen the app sends inspect and check together,
so the check answered from the stale entry before the inspection
settled. A cached check now records the installed version it was
computed against and is reused only when the current inspection, shared
if in flight, reports the same version.

* fix(app): refresh provider version after an update settles while disconnected

The installation and update queries were invalidated only by a live
succeeded progress event. A connection dropped mid-update delivered the
settled operation as a snapshot on reconnect, which left the old version
and Update on screen. A success the view saw running now rereads them
whether it arrives as progress or as a snapshot.

* fix(providers): keep update checks within their own deadline

Tying a cached check to its version made every check wait for a fresh
inspection, which could add the 20 s inspect deadline to the 25 s check
deadline. A check now never starts an inspection. It waits on one only
when the inspection is cached or already running and the check would
reuse a cached answer. When it asks the provider, it records the version
afterwards.

* test(app): assert provider installation states are visible

* fix(providers): share one update check when two clients reopen after a version change

* fix(muse): report the build the update check compares

Paseo reuses a cached update check while inspect reports the same
version string. Muse reported 1.4.18 but compared its build
(1.4.18-R8600.1), so a new build of the same release kept the stale
"Update available" for up to an hour. The contract docs now say to
include everything the check compares in the reported version.

* test(app): scroll custom model rows into view before checking them

The provider sheet now shows an Installation section above the model
lists. At 390x1000 the custom model row sits under the sheet footer
until scrolled. The spec checks that a long model id leaves its Remove
button reachable. It had assumed the row needed no vertical scroll.

* test(app): keep the custom model check sensitive to a Remove button pushed off the sheet

scrollIntoViewIfNeeded on the Remove button scrolled the overflow-hidden model
card sideways too, so the check passed with the long-id layout fix undone.
Scroll only the Custom models heading into view, which moves the sheet
vertically and leaves the card at scrollLeft 0. With the layout fix undone the
spec now fails at 1200px and 390px again.

* feat(app): offer provider updates whether or not an update check answers

Update and Update instructions lived inside the row that appeared only after
checkForUpdates answered, so Copilot and OpenCode, which declare update but no
check, never offered either. A check is a convenience: the Updates row now
shows for an installed provider that offers an update, keeps Update or Update
instructions in place in every check state (none, checking, up to date,
available, couldn't check), and shows what the check knows as a hint beside
it. A provider that offers no update still shows the check's answer once it
has one. The daemon already ran update without a check; a test now says so.

* fix(app): let update output scroll inside the provider sheet on Android

The output box is a ScrollView nested in the sheet's scrolling body. Android hands the drag to the outer ScrollView unless the inner one sets nestedScrollEnabled, so only the last 240px of a long update's output was readable. The tool-call detail views set the same flag.

* fix(app): show one progress indicator per provider update and refresh

While an update ran, the Update button and the update's row each showed a spinner. The button's
spinner also widened it, and the row's leading spinner shifted the title when the update settled.
The update's row now owns progress from the tap until the update settles: it shows the update
starting before the host answers, so the indicator never moves, and the Update button only
disables.

Refresh blanked the Installation rows while the provider was asked again, then moved "Checking…"
from the Version row to the Updates row. The rows now keep their last answers until the new ones
arrive, and the Refresh button shows the refresh until both the models and the installation are
read again.

* fix(app): show a provider update's progress on its Update button

The pressed button carries an action's progress everywhere else in Settings: Button's own
loading state with a present-participle label, as Browser data's Clear and Project settings'
Save do. Update now does the same, reading "Updating..." from the tap until the update settles,
and the update's row holds only the output while it runs, then the result. This replaces the
row-owned spinner from the previous commit, which no other surface uses.

The installation's in-flight labels use three dots like their siblings.

* fix(app): keep a running update's progress visible whatever the inspection reads

Update carries the update's progress, but its row rendered only while the inspection read
"installed". An inspection that ran during the update (on reopen or Refresh) could read loading,
not installed or failed while the binary was replaced, and the sheet then showed nothing about the
running update. The Updates row now stays while an update runs.

* fix(server): show and update the provider CLI its agents launch

The installation contract found the CLI on the daemon's PATH, while agents
spawn the bare command with the provider's environment. A provider whose env
sets PATH could launch one copy and show and update another, so an update
succeeded while new agents kept the old version. The CLI is now resolved with
the provider's environment.

The section test's check-state table now always names the text it expects, so
no case can skip its assertion.

* test(server): name the provider PATH test for what it shows

The availability check that gates a Copilot spawn still looks on the daemon's
PATH, so the copy on the provider's PATH is not always the one agents launch.

* test(antigravity-provider): read the version from the CLI, not its acp subcommand

Antigravity now launches `agy acp --disable-telemetry`, so the launch the
installation receives ends with the ACP subcommand. The version read drops it,
since `agy acp --version` starts the ACP server.

* feat(plugin): pass the inspected version to checkForUpdates

checkForUpdates now receives installedVersion, the version inspect reported, and
the daemon keys the cached answer on it. Before, each provider read its version
a second time and the daemon recorded which version a cached check answered
for, so a check could compare a different version than the one shown, and a
plugin had to put everything its check compared into the reported version.

An update check now waits for the provider's inspection (shared with a
concurrent inspect, refreshed with it), answers Not installed or the
inspection's error without asking the provider, and is asked again once the
inspection reports a different version.

* fix(server): clear a failed provider update when the provider is refreshed

The daemon kept a provider's last update for its whole lifetime, so a failed
update stayed the current update until a later update succeeded or the daemon
restarted, and the provider looked broken after the user fixed it. A refresh
of the provider's installation or update check now drops a failed result. A
running update is never dropped.

* docs(server): say which agents look up the provider CLI on its PATH

* fix(server): tell open provider views when a refresh drops a failed update

A refresh deleted the failed update on the daemon but sent nothing, so a view
already observing the provider's updates, in this client or another one, kept
showing the failure until it observed again. The daemon now pushes
provider.installation.update.cleared with the dropped operation's id to every
subscriber, and the app clears the update it shows when the ids match.
2026-11-19 20:56:00 +07:00

1595 lines
47 KiB
TypeScript

import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { z } from "zod";
export const PROVIDER_PROTOCOL_VERSION = 1 as const;
export const PROVIDER_CAPABILITIES = [
"prompt.message",
"prompt.command",
"prompt.image",
"prompt.output_schema",
"prompt.steer",
"session.can_stop_runtime",
"session.archive",
"session.configure",
"session.list",
"session.persistence",
"session.revert.both",
"session.revert.conversation",
"session.revert.files",
"session.subsession",
"session.unarchive",
"permission",
"permission.tool_policy",
"timeline.plugin",
] as const;
export type ProviderCapability = (typeof PROVIDER_CAPABILITIES)[number];
export interface ProviderRegistration {
/** Activate only while agents.providers contains this provider ID, independently of enabled. */
requiresConfiguration?: boolean;
/** Equal keys share discovery within this provider. Include effective configuration and execution environment. */
getCatalogCacheKey?(options: ProviderCatalogOptions): Promise<string | undefined>;
/** Default executable and arguments; the daemon resolves overrides before status/connect. */
command?: readonly [string, ...string[]];
status?(request: ProviderStatusRequest): Promise<ProviderStatus>;
id: string;
label: string;
description?: string;
/** Plugin-directory-relative path to a self-contained SVG file. */
icon?: string;
/** How users install the provider's CLI and which version they run. Every member is optional. */
installation?: ProviderInstallation;
connect(request: ProviderConnectRequest): Promise<ProviderConnection>;
}
export interface ProviderInstallation {
/** http(s) page that explains how to install the provider. Paseo opens it; it never installs. */
installUrl?: string;
/** http(s) page that explains how to update the provider. */
updateUrl?: string;
/** Report whether the provider is installed and which version. Runs only when a user asks. */
inspect?(context: ProviderInstallationContext): Promise<ProviderInspection>;
/**
* Report whether a newer version than `installedVersion` is available. The provider decides how
* to find out and what counts as newer; Paseo shows the result as written. Return `unknown` when
* it cannot tell. Runs only when a user asks, never before a session, and only after `inspect`
* reports the provider installed. Paseo reuses the answer while `inspect` reports the same
* version.
*/
checkForUpdates?(context: ProviderUpdateCheckContext): Promise<ProviderUpdateCheck>;
/**
* Update the provider, usually by running its CLI's own updater. Paseo shows everything passed
* to `report` while it runs, then the returned message. A throw is a failure with its message.
* Runs only when a user asks. Paseo sets no deadline; `signal` aborts when the daemon stops.
*/
update?(context: ProviderUpdateContext): Promise<ProviderUpdateResult>;
}
export interface ProviderUpdateCheckContext extends ProviderInstallationContext {
/**
* The version `inspect` reported, as written. Absent when `inspect` reported none or the
* provider declares no `inspect`.
*/
installedVersion?: string;
}
export interface ProviderUpdateContext extends ProviderInstallationContext {
/** Shows output to the user as it happens, unchanged and in order. */
report(event: ProviderUpdateReport): void;
}
export const ProviderUpdateReportSchema = z
.object({ type: z.enum(["stdout", "stderr", "message"]), text: z.string() })
.strip();
export type ProviderUpdateReport = z.infer<typeof ProviderUpdateReportSchema>;
export const ProviderUpdateResultSchema = z.discriminatedUnion("status", [
/** `message` is shown as written, such as which version is now installed. */
z.object({ status: z.literal("succeeded"), message: z.string().optional() }).strip(),
z.object({ status: z.literal("failed"), message: z.string() }).strip(),
]);
export type ProviderUpdateResult = z.infer<typeof ProviderUpdateResultSchema>;
export interface ProviderInstallationContext {
/** The launch a session would use. Absent when the provider declares no `command`. */
launch?: ProviderInstallationLaunch;
/** Aborted when Paseo stops waiting for the result. */
signal: AbortSignal;
}
export interface ProviderInstallationLaunch extends ProviderLaunch {
/** False when the executable was not found; `command` is then the configured command as written. */
resolved: boolean;
}
export const ProviderInspectionSchema = z.discriminatedUnion("status", [
/** `version` is shown as written and passed to `checkForUpdates`; Paseo does not parse it. */
z.object({ status: z.literal("installed"), version: z.string().optional() }).strip(),
z.object({ status: z.literal("not_installed") }).strip(),
]);
export type ProviderInspection = z.infer<typeof ProviderInspectionSchema>;
export const ProviderUpdateCheckSchema = z.discriminatedUnion("status", [
z.object({ status: z.literal("current") }).strip(),
/** `versions` and `message` are shown as written; Paseo does not parse, sort or compare them. */
z
.object({
status: z.literal("available"),
versions: z.array(z.string()).optional(),
message: z.string().optional(),
})
.strip(),
z.object({ status: z.literal("unknown"), message: z.string().optional() }).strip(),
]);
export type ProviderUpdateCheck = z.infer<typeof ProviderUpdateCheckSchema>;
export type ProviderCatalogOptions =
| { scope: "global"; force?: boolean; launch?: ProviderLaunch }
| { scope: "workspace"; cwd: string; force?: boolean; launch?: ProviderLaunch };
export const ProviderLaunchSchema = z
.object({
/** Resolved executable path. */
command: z.string().min(1),
args: z.array(z.string()),
/** Complete daemon-owned environment, including overrides and parent-session stripping. */
env: z.record(z.string(), z.string()),
})
.strip();
export type ProviderLaunch = z.infer<typeof ProviderLaunchSchema>;
export interface ProviderStatusRequest {
launch?: ProviderLaunch;
}
export const ProviderStatusSchema = z.discriminatedUnion("available", [
z.object({ available: z.literal(true), diagnostic: z.string().optional() }).strip(),
z.object({ available: z.literal(false), diagnostic: z.string().min(1) }).strip(),
]);
export type ProviderStatus = z.infer<typeof ProviderStatusSchema>;
export interface ProviderConnectRequest {
launch?: ProviderLaunch;
versions: readonly number[];
capabilities: readonly string[];
}
export interface ProviderConnection {
readonly version: number;
readonly capabilities: readonly string[];
send(input: ProviderInput): Promise<void>;
onEvent(listener: (event: ProviderEvent) => void): () => void;
close(): Promise<void>;
}
export interface ProviderPersistence {
version: number;
data: JsonValue;
}
export type ProviderMcpServerConfig =
| {
type: "stdio";
command: string;
args?: string[];
env?: Record<string, string>;
alwaysLoad?: boolean;
}
| {
type: "http" | "sse";
url: string;
headers?: Record<string, string>;
alwaysLoad?: boolean;
};
export interface ProviderToolPolicy {
preapproved: Array<{ kind: "mcp"; server: string; tool: string }>;
}
export interface ProviderSessionConfig {
cwd: string;
env: Readonly<Record<string, string>>;
systemPrompt?: string;
mcpServers: Readonly<Record<string, ProviderMcpServerConfig>>;
toolPolicy?: ProviderToolPolicy;
model?: string;
mode?: string;
thinkingOption?: string;
/** @deprecated The same values as `providerOptions`. */
settings: Readonly<Record<string, JsonValue>>;
/** The agent's options, the provider defaults from `config.json` included. */
providerOptions?: Readonly<Record<string, unknown>>;
title?: string;
persist: boolean;
}
export interface ProviderConfigChanges {
model?: string | null;
mode?: string | null;
thinkingOption?: string | null;
/**
* The option keys to change on the running session, with or without a control. Apply every key
* or fail the whole request, for a key you only read when a session opens. `null` returns the
* key to the provider's own default. The committed values come back in `session.config`.
*/
providerOptions?: Readonly<Record<string, JsonValue>>;
/** @deprecated Sent next to `providerOptions` to a provider that reports `settings`. */
settings?: Readonly<Record<string, JsonValue>>;
}
export interface ProviderPrompt {
clientMessageId: string;
delivery: "auto" | "steer";
input:
| { type: "message"; content: ProviderContent[] }
| { type: "command"; name: string; arguments: string };
outputSchema?: JsonValue;
clearPendingPermissions?: boolean;
}
interface ProviderForgeChangeRequestAttachment {
type: "forge_change_request";
mimeType: "application/paseo-forge-change-request";
forge?: string;
number: number;
title: string;
url: string;
body?: string | null;
projectPath?: string;
baseRefName?: string | null;
headRefName?: string | null;
}
interface ProviderForgeIssueAttachment {
type: "forge_issue";
mimeType: "application/paseo-forge-issue";
forge?: string;
number: number;
title: string;
url: string;
body?: string | null;
projectPath?: string;
}
interface ProviderGitHubPrAttachment {
type: "github_pr";
mimeType: "application/github-pr";
number: number;
title: string;
url: string;
body?: string | null;
baseRefName?: string | null;
headRefName?: string | null;
}
interface ProviderGitHubIssueAttachment {
type: "github_issue";
mimeType: "application/github-issue";
number: number;
title: string;
url: string;
body?: string | null;
}
interface ProviderTextAttachment {
type: "text";
mimeType: "text/plain";
contextKind?: string;
title?: string | null;
text: string;
externalResource?: {
provider: string;
providerLabel: string;
resourceType: string;
id: string;
identifier: string;
title: string;
url: string;
};
}
interface ProviderReviewAttachment {
type: "review";
mimeType: "application/paseo-review";
cwd: string;
mode: "uncommitted" | "base" | "all";
baseRef?: string | null;
comments: Array<{
filePath: string;
side: "old" | "new";
lineNumber: number;
body: string;
context: {
hunkHeader: string;
targetLine: ProviderReviewContextLine;
lines: ProviderReviewContextLine[];
};
}>;
}
interface ProviderReviewContextLine {
oldLineNumber: number | null;
newLineNumber: number | null;
type: "add" | "remove" | "context";
content: string;
}
export type ProviderContent =
| { type: "text"; text: string }
| { type: "image"; data: string; mimeType: string }
| ProviderForgeChangeRequestAttachment
| ProviderForgeIssueAttachment
| ProviderGitHubPrAttachment
| ProviderGitHubIssueAttachment
| ProviderTextAttachment
| ProviderReviewAttachment
| {
type: "uploaded_file";
id: string;
fileName: string;
mimeType: string;
size: number;
path: string;
};
export type ProviderInput =
| { type: "catalog"; requestId: string; cwd?: string }
| { type: "sessions"; requestId: string; query?: string; cwd?: string; limit?: number }
| {
type: "session.open";
requestId: string;
sessionId: string;
config: ProviderSessionConfig;
persistence?: ProviderPersistence;
history: "replay" | "skip";
}
| { type: "session.prompt"; sessionId: string; prompt: ProviderPrompt }
| { type: "session.interrupt"; requestId: string; sessionId: string }
| {
type: "session.permission";
sessionId: string;
permissionId: string;
response: ProviderPermissionResponse;
}
| {
type: "session.configure";
requestId: string;
sessionId: string;
changes: ProviderConfigChanges;
}
| {
type: "session.revert";
requestId: string;
sessionId: string;
token: JsonValue;
scope: "conversation" | "files" | "both";
}
| { type: "session.archive"; requestId: string; persistence: ProviderPersistence }
| { type: "session.unarchive"; requestId: string; persistence: ProviderPersistence }
| { type: "session.can_stop_runtime"; requestId: string; sessionId: string }
| { type: "session.close"; requestId: string; sessionId: string };
export interface ProviderThinkingOption {
id: string;
label: string;
description?: string;
isDefault?: boolean;
metadata?: Readonly<Record<string, JsonValue>>;
}
export interface ProviderModel {
id: string;
aliases?: string[];
isSelectable?: boolean;
label: string;
description?: string;
isDefault?: boolean;
metadata?: Readonly<Record<string, JsonValue>>;
contextWindowMaxTokens?: number;
thinkingOptions?: ProviderThinkingOption[];
defaultThinkingOptionId?: string;
}
export interface ProviderMode {
id: string;
label: string;
description?: string;
icon?: string;
colorTier?: string;
isUnattended?: boolean;
}
/**
* Draws one top-level option key in the composer. The control holds no value: Paseo reads it
* from the agent's options.
*/
export type ProviderOptionControl =
| {
type: "toggle";
key: string;
label: string;
description?: string;
/** A Lucide icon name. */
icon?: string;
/** Shown while the key has no value. */
defaultValue?: boolean;
}
| {
type: "select";
key: string;
label: string;
description?: string;
/** A Lucide icon name. */
icon?: string;
/** The choice shown while the key has no value. */
defaultValue?: string;
choices: ReadonlyArray<{ value: string; label: string; description?: string }>;
};
/** @deprecated Report `controls` and `providerOptions` instead. */
export type ProviderSetting =
| {
type: "toggle";
id: string;
label: string;
description?: string;
value: boolean;
}
| {
type: "select";
id: string;
label: string;
description?: string;
value: string | null;
options: ReadonlyArray<{ label: string; value: string }>;
};
export interface ProviderConfigState {
model?: string;
mode?: string;
thinkingOption?: string;
models: readonly ProviderModel[];
modes: readonly ProviderMode[];
thinkingOptions: readonly ProviderThinkingOption[];
/** The option keys that get a composer control. May change at runtime, for example per model. */
controls?: readonly ProviderOptionControl[];
/** What the session runs with now, for the keys it reports. Publish the committed values. */
providerOptions?: Readonly<Record<string, JsonValue>>;
/** @deprecated Report `controls` and `providerOptions`. Each setting id is an option key. */
settings?: readonly ProviderSetting[];
}
export interface ProviderCatalog {
models: readonly ProviderModel[];
modes: readonly ProviderMode[];
thinkingOptions?: readonly ProviderThinkingOption[];
defaultModel?: string;
defaultMode?: string;
defaultThinkingOption?: string;
}
export interface ProviderSessionSummary {
persistence: ProviderPersistence;
cwd: string;
title?: string;
description?: string;
updatedAt?: string;
}
export interface ProviderCommand {
name: string;
description: string;
argumentHint?: string;
}
export interface ProviderError {
message: string;
code?: string;
diagnostic?: string;
}
export interface ProviderNotice {
id: string;
severity: "info" | "warning" | "error";
title: string;
description?: string;
dismissed?: boolean;
}
export interface ProviderPermissionAction {
id: string;
label: string;
behavior: "allow" | "deny";
variant?: "primary" | "secondary" | "danger";
intent?: "implement" | "implement_resume" | "dismiss";
}
export interface ProviderPermissionRequest {
id: string;
name: string;
kind: "tool" | "plan" | "question" | "mode" | "other";
title?: string;
description?: string;
input?: Readonly<Record<string, JsonValue>>;
detail?: ProviderToolCallDetail;
suggestions?: Array<Record<string, JsonValue>>;
actions?: ProviderPermissionAction[];
metadata?: Readonly<Record<string, JsonValue>>;
}
export type ProviderPermissionResponse =
| {
behavior: "allow";
selectedActionId?: string;
updatedInput?: Record<string, JsonValue>;
updatedPermissions?: Array<Record<string, JsonValue>>;
}
| {
behavior: "deny";
selectedActionId?: string;
message?: string;
interrupt?: boolean;
};
export interface ProviderUsage {
inputTokens?: number;
cachedInputTokens?: number;
outputTokens?: number;
totalCostUsd?: number;
contextWindowMaxTokens?: number;
contextWindowUsedTokens?: number;
}
interface ProviderTimelineIdentity {
id: string;
revertToken?: JsonValue;
}
export type ProviderToolCallDetail =
| { type: "shell"; command: string; cwd?: string; output?: string; exitCode?: number | null }
| { type: "read"; filePath: string; content?: string; offset?: number; limit?: number }
| {
type: "edit";
filePath: string;
oldString?: string;
newString?: string;
unifiedDiff?: string;
}
| { type: "write"; filePath: string; content?: string }
| {
type: "search";
query: string;
toolName?: "search" | "grep" | "glob" | "web_search";
content?: string;
filePaths?: string[];
webResults?: Array<{ title: string; url: string }>;
annotations?: string[];
numFiles?: number;
numMatches?: number;
durationMs?: number;
durationSeconds?: number;
truncated?: boolean;
mode?: "content" | "files_with_matches" | "count";
}
| {
type: "fetch";
url: string;
prompt?: string;
result?: string;
code?: number;
codeText?: string;
bytes?: number;
durationMs?: number;
}
| {
type: "worktree_setup";
worktreePath: string;
branchName: string;
log: string;
commands: Array<{
index: number;
command: string;
cwd: string;
log: string;
status: "running" | "completed" | "failed";
exitCode: number | null;
durationMs?: number;
}>;
truncated?: boolean;
}
| {
type: "sub_agent";
subAgentType?: string;
description?: string;
childSessionId?: string;
log: string;
actions?: Array<{ index: number; toolName: string; summary?: string }>;
}
| {
type: "plain_text";
label?: string;
text?: string;
icon?:
| "wrench"
| "square_terminal"
| "eye"
| "pencil"
| "search"
| "bot"
| "sparkles"
| "brain"
| "mic_vocal";
}
| { type: "plan"; text: string }
| { type: "unknown"; input: JsonValue; output: JsonValue };
type ProviderToolCallItem = ProviderTimelineIdentity & {
type: "tool_call";
callId: string;
name: string;
detail: ProviderToolCallDetail;
metadata?: Readonly<Record<string, JsonValue>>;
} & (
| { status: "running" | "completed" | "canceled"; error: null }
| { status: "failed"; error: JsonValue }
);
export type ProviderTimelineItem =
| (ProviderTimelineIdentity & {
type: "user_message";
text: string;
messageId?: string;
clientMessageId?: string;
})
| (ProviderTimelineIdentity & { type: "assistant_message"; text: string; messageId?: string })
| (ProviderTimelineIdentity & { type: "reasoning"; text: string })
| ProviderToolCallItem
| (ProviderTimelineIdentity & {
type: "todo";
items: Array<{
text: string;
completed: boolean;
id?: string;
status?: "pending" | "in_progress" | "completed";
activeForm?: string;
}>;
})
| (ProviderTimelineIdentity & { type: "error"; message: string })
| (ProviderTimelineIdentity & {
type: "notification";
level: "info" | "warning" | "error";
message: string;
})
| (ProviderTimelineIdentity & {
type: "compaction";
status: "loading" | "completed";
trigger?: "auto" | "manual";
preTokens?: number;
})
| (ProviderTimelineIdentity & {
type: "plugin";
pluginId: string;
kind: string;
version: number;
data: JsonValue;
});
export type ProviderEvent =
| { type: "session.can_stop_runtime"; requestId: string; sessionId: string; canStop: boolean }
| { type: "catalog"; requestId: string; catalog: ProviderCatalog }
| { type: "sessions"; requestId: string; sessions: ProviderSessionSummary[] }
| { type: "request.completed"; requestId: string }
| { type: "request.failed"; requestId: string; error: ProviderError }
| {
type: "session.opened";
requestId?: string;
sessionId: string;
/** Direct parent in the provider session ID namespace. */
parentSessionId?: string;
/** ID of the spawning tool call in the direct parent's timeline. */
toolCallId?: string;
capabilities: readonly string[];
restoration: "core" | "parent";
persistence?: ProviderPersistence;
title?: string;
description?: string;
cwd: string;
}
| { type: "session.ready"; requestId?: string; sessionId: string }
| { type: "session.closed"; sessionId: string; error?: ProviderError }
| { type: "session.runtime_failed"; sessionId: string; error: ProviderError }
| { type: "session.persistence"; sessionId: string; persistence: ProviderPersistence }
| {
type: "session.prompt_result";
sessionId: string;
clientMessageId: string;
result:
| { type: "turn"; turnId: string }
| { type: "steer"; turnId: string }
| { type: "completed" }
| { type: "failed"; error: ProviderError };
}
| {
type: "session.turn";
sessionId: string;
turnId: string;
state: "started" | "completed" | "failed" | "canceled";
error?: ProviderError;
}
| { type: "session.usage"; sessionId: string; turnId?: string; usage: ProviderUsage }
| { type: "session.config"; sessionId: string; config: ProviderConfigState }
| { type: "session.commands"; sessionId: string; commands: ProviderCommand[] }
| { type: "session.permission"; sessionId: string; request: ProviderPermissionRequest }
| { type: "session.permission_resolved"; sessionId: string; permissionId: string }
| { type: "session.notice"; sessionId: string; notice: ProviderNotice }
| { type: "timeline.item"; sessionId: string; item: ProviderTimelineItem; timestamp?: string };
export function negotiateProviderCapabilities(
offered: readonly string[],
supported: readonly string[],
): readonly ProviderCapability[] {
const known = new Set<string>(PROVIDER_CAPABILITIES);
const supportedCapabilities = new Set(supported.filter((capability) => known.has(capability)));
return offered.filter(
(capability, index): capability is ProviderCapability =>
isProviderCapability(capability) &&
supportedCapabilities.has(capability) &&
offered.indexOf(capability) === index,
);
}
export function isProviderCapability(capability: string): capability is ProviderCapability {
return new Set<string>(PROVIDER_CAPABILITIES).has(capability);
}
function requiredPromptCapabilities(prompt: ProviderPrompt): readonly ProviderCapability[] {
const capabilities: ProviderCapability[] = [];
if (prompt.delivery === "steer") capabilities.push("prompt.steer");
if (prompt.input.type === "command") capabilities.push("prompt.command");
else {
capabilities.push("prompt.message");
if (prompt.input.content.some((part) => part.type === "image")) {
capabilities.push("prompt.image");
}
}
if (prompt.outputSchema !== undefined) capabilities.push("prompt.output_schema");
return capabilities;
}
export function requiredProviderCapabilities(input: ProviderInput): readonly ProviderCapability[] {
switch (input.type) {
case "session.can_stop_runtime":
return ["session.can_stop_runtime"];
case "catalog":
case "session.interrupt":
case "session.close":
return [];
case "sessions":
return ["session.list"];
case "session.open": {
const capabilities: ProviderCapability[] = [];
if (input.persistence) capabilities.push("session.persistence");
if (input.config.toolPolicy) capabilities.push("permission.tool_policy");
return capabilities;
}
case "session.prompt":
return requiredPromptCapabilities(input.prompt);
case "session.permission":
return ["permission"];
case "session.configure":
return ["session.configure"];
case "session.revert":
return [`session.revert.${input.scope}`];
case "session.archive":
return ["session.archive"];
case "session.unarchive":
return ["session.unarchive"];
}
}
export function requireProviderCapabilities(
capabilities: readonly string[],
input: ProviderInput,
): void {
for (const capability of requiredProviderCapabilities(input)) {
if (!capabilities.includes(capability)) {
throw new Error(`Provider does not support ${capability}`);
}
}
}
const idSchema = z.string().min(1);
const jsonObjectSchema = z.record(z.string(), z.json());
const providerErrorSchema = z
.object({ message: z.string(), code: z.string().optional(), diagnostic: z.string().optional() })
.strip();
const persistenceSchema = z
.object({ version: z.number().int().nonnegative(), data: z.json() })
.strip();
const mcpServerSchema = z.discriminatedUnion("type", [
z
.object({
type: z.literal("stdio"),
command: z.string(),
args: z.array(z.string()).optional(),
env: z.record(z.string(), z.string()).optional(),
alwaysLoad: z.boolean().optional(),
})
.strict(),
z
.object({
type: z.literal("http"),
url: z.string(),
headers: z.record(z.string(), z.string()).optional(),
alwaysLoad: z.boolean().optional(),
})
.strict(),
z
.object({
type: z.literal("sse"),
url: z.string(),
headers: z.record(z.string(), z.string()).optional(),
alwaysLoad: z.boolean().optional(),
})
.strict(),
]);
const toolPolicySchema = z
.object({
preapproved: z.array(
z.object({ kind: z.literal("mcp"), server: idSchema, tool: idSchema }).strict(),
),
})
.strict();
const providerPermissionResponseSchema: z.ZodType<ProviderPermissionResponse> =
z.discriminatedUnion("behavior", [
z
.object({
behavior: z.literal("allow"),
selectedActionId: z.string().optional(),
updatedInput: jsonObjectSchema.optional(),
updatedPermissions: z.array(jsonObjectSchema).optional(),
})
.strip(),
z
.object({
behavior: z.literal("deny"),
selectedActionId: z.string().optional(),
message: z.string().optional(),
interrupt: z.boolean().optional(),
})
.strip(),
]);
const sessionConfigSchema = z
.object({
cwd: z.string(),
env: z.record(z.string(), z.string()),
systemPrompt: z.string().optional(),
mcpServers: z.record(z.string(), mcpServerSchema),
toolPolicy: toolPolicySchema.optional(),
model: z.string().optional(),
mode: z.string().optional(),
thinkingOption: z.string().optional(),
settings: jsonObjectSchema,
providerOptions: z.record(z.string(), z.unknown()).optional(),
title: z.string().optional(),
persist: z.boolean(),
})
.strict();
const externalResourceSchema = z
.object({
provider: z.string(),
providerLabel: z.string(),
resourceType: z.string(),
id: z.string(),
identifier: z.string(),
title: z.string(),
url: z.string(),
})
.strip();
const reviewContextLineSchema = z
.object({
oldLineNumber: z.number().int().positive().nullable(),
newLineNumber: z.number().int().positive().nullable(),
type: z.enum(["add", "remove", "context"]),
content: z.string(),
})
.strip();
const providerContentSchema: z.ZodType<ProviderContent> = z.union([
z.object({ type: z.literal("text"), text: z.string() }).strict(),
z.object({ type: z.literal("image"), data: z.string(), mimeType: z.string() }).strict(),
z
.object({
type: z.literal("forge_change_request"),
mimeType: z.literal("application/paseo-forge-change-request"),
forge: z.string().optional(),
number: z.number().int().positive(),
title: z.string(),
url: z.string(),
body: z.string().nullable().optional(),
projectPath: z.string().optional(),
baseRefName: z.string().nullable().optional(),
headRefName: z.string().nullable().optional(),
})
.strip(),
z
.object({
type: z.literal("forge_issue"),
mimeType: z.literal("application/paseo-forge-issue"),
forge: z.string().optional(),
number: z.number().int().positive(),
title: z.string(),
url: z.string(),
body: z.string().nullable().optional(),
projectPath: z.string().optional(),
})
.strip(),
z
.object({
type: z.literal("github_pr"),
mimeType: z.literal("application/github-pr"),
number: z.number().int().positive(),
title: z.string(),
url: z.string(),
body: z.string().nullable().optional(),
baseRefName: z.string().nullable().optional(),
headRefName: z.string().nullable().optional(),
})
.strip(),
z
.object({
type: z.literal("github_issue"),
mimeType: z.literal("application/github-issue"),
number: z.number().int().positive(),
title: z.string(),
url: z.string(),
body: z.string().nullable().optional(),
})
.strip(),
z
.object({
type: z.literal("text"),
mimeType: z.literal("text/plain"),
contextKind: z.string().optional(),
title: z.string().nullable().optional(),
text: z.string(),
externalResource: externalResourceSchema.optional(),
})
.strip(),
z
.object({
type: z.literal("review"),
mimeType: z.literal("application/paseo-review"),
cwd: z.string(),
mode: z.enum(["uncommitted", "base", "all"]),
baseRef: z.string().nullable().optional(),
comments: z.array(
z
.object({
filePath: z.string(),
side: z.enum(["old", "new"]),
lineNumber: z.number().int().positive(),
body: z.string(),
context: z
.object({
hunkHeader: z.string(),
targetLine: reviewContextLineSchema,
lines: z.array(reviewContextLineSchema),
})
.strip(),
})
.strip(),
),
})
.strip(),
z
.object({
type: z.literal("uploaded_file"),
id: z.string(),
fileName: z.string(),
mimeType: z.string(),
size: z.number().int().nonnegative(),
path: z.string(),
})
.strip(),
]);
const promptSchema = z
.object({
clientMessageId: idSchema,
delivery: z.enum(["auto", "steer"]),
input: z.union([
z.object({ type: z.literal("message"), content: z.array(providerContentSchema) }).strict(),
z.object({ type: z.literal("command"), name: idSchema, arguments: z.string() }).strict(),
]),
outputSchema: z.json().optional(),
clearPendingPermissions: z.boolean().optional(),
})
.strict();
const configChangesSchema = z
.object({
model: z.string().nullable().optional(),
mode: z.string().nullable().optional(),
thinkingOption: z.string().nullable().optional(),
providerOptions: jsonObjectSchema.optional(),
settings: jsonObjectSchema.optional(),
})
.strict();
export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnion("type", [
z
.object({ type: z.literal("catalog"), requestId: idSchema, cwd: z.string().optional() })
.strict(),
z
.object({
type: z.literal("sessions"),
requestId: idSchema,
query: z.string().optional(),
cwd: z.string().optional(),
limit: z.number().int().positive().optional(),
})
.strict(),
z
.object({
type: z.literal("session.open"),
requestId: idSchema,
sessionId: idSchema,
config: sessionConfigSchema,
persistence: persistenceSchema.optional(),
history: z.enum(["replay", "skip"]),
})
.strict(),
z
.object({ type: z.literal("session.prompt"), sessionId: idSchema, prompt: promptSchema })
.strict(),
z
.object({ type: z.literal("session.interrupt"), requestId: idSchema, sessionId: idSchema })
.strict(),
z
.object({
type: z.literal("session.permission"),
sessionId: idSchema,
permissionId: idSchema,
response: providerPermissionResponseSchema,
})
.strict(),
z
.object({
type: z.literal("session.configure"),
requestId: idSchema,
sessionId: idSchema,
changes: configChangesSchema,
})
.strict(),
z
.object({
type: z.literal("session.revert"),
requestId: idSchema,
sessionId: idSchema,
token: z.json(),
scope: z.enum(["conversation", "files", "both"]),
})
.strict(),
z
.object({
type: z.literal("session.archive"),
requestId: idSchema,
persistence: persistenceSchema,
})
.strict(),
z
.object({
type: z.literal("session.unarchive"),
requestId: idSchema,
persistence: persistenceSchema,
})
.strict(),
z
.object({
type: z.literal("session.can_stop_runtime"),
requestId: idSchema,
sessionId: idSchema,
})
.strict(),
z.object({ type: z.literal("session.close"), requestId: idSchema, sessionId: idSchema }).strict(),
]);
const modeSchema = z
.object({
id: idSchema,
label: z.string(),
description: z.string().optional(),
icon: z.string().optional(),
colorTier: z.string().optional(),
isUnattended: z.boolean().optional(),
})
.strip();
const selectOptionSchema = z
.object({
id: idSchema,
label: z.string(),
description: z.string().optional(),
isDefault: z.boolean().optional(),
metadata: jsonObjectSchema.optional(),
})
.strip();
const modelSchema = z
.object({
id: idSchema,
aliases: z.array(z.string()).optional(),
isSelectable: z.boolean().optional(),
label: z.string(),
description: z.string().optional(),
isDefault: z.boolean().optional(),
metadata: jsonObjectSchema.optional(),
contextWindowMaxTokens: z.number().optional(),
thinkingOptions: z.array(selectOptionSchema).optional(),
defaultThinkingOptionId: z.string().optional(),
})
.strip();
const settingSchema = z.discriminatedUnion("type", [
z
.object({
type: z.literal("toggle"),
id: idSchema,
label: z.string(),
description: z.string().optional(),
value: z.boolean(),
})
.strip(),
z
.object({
type: z.literal("select"),
id: idSchema,
label: z.string(),
description: z.string().optional(),
value: z.string().nullable(),
options: z.array(z.object({ label: z.string(), value: z.string() }).strip()),
})
.strip(),
]);
const controlSchema = z.discriminatedUnion("type", [
z
.object({
type: z.literal("toggle"),
key: idSchema,
label: z.string(),
description: z.string().optional(),
icon: z.string().optional(),
defaultValue: z.boolean().optional(),
})
.strip(),
z
.object({
type: z.literal("select"),
key: idSchema,
label: z.string(),
description: z.string().optional(),
icon: z.string().optional(),
defaultValue: z.string().optional(),
choices: z.array(
z
.object({ value: z.string(), label: z.string(), description: z.string().optional() })
.strip(),
),
})
.strip(),
]);
const configStateSchema = z
.object({
model: z.string().optional(),
mode: z.string().optional(),
thinkingOption: z.string().optional(),
models: z.array(modelSchema),
modes: z.array(modeSchema),
thinkingOptions: z.array(selectOptionSchema),
controls: z.array(controlSchema).optional(),
providerOptions: jsonObjectSchema.optional(),
settings: z.array(settingSchema).optional(),
})
.strip();
const catalogSchema = z
.object({
models: z.array(modelSchema),
modes: z.array(modeSchema),
thinkingOptions: z.array(selectOptionSchema).optional(),
defaultModel: z.string().optional(),
defaultMode: z.string().optional(),
defaultThinkingOption: z.string().optional(),
})
.strip();
const noticeSchema = z
.object({
id: idSchema,
severity: z.enum(["info", "warning", "error"]),
title: z.string(),
description: z.string().optional(),
dismissed: z.boolean().optional(),
})
.strip();
const commandSchema = z
.object({ name: idSchema, description: z.string(), argumentHint: z.string().optional() })
.strip();
const usageSchema = z
.object({
inputTokens: z.number().optional(),
cachedInputTokens: z.number().optional(),
outputTokens: z.number().optional(),
totalCostUsd: z.number().optional(),
contextWindowMaxTokens: z.number().optional(),
contextWindowUsedTokens: z.number().optional(),
})
.strip();
const worktreeCommandSchema = z
.object({
index: z.number().int().positive(),
command: z.string(),
cwd: z.string(),
log: z.string(),
status: z.enum(["running", "completed", "failed"]),
exitCode: z.number().nullable(),
durationMs: z.number().nonnegative().optional(),
})
.strip();
const toolCallDetailSchema: z.ZodType<ProviderToolCallDetail> = z.discriminatedUnion("type", [
z
.object({
type: z.literal("shell"),
command: z.string(),
cwd: z.string().optional(),
output: z.string().optional(),
exitCode: z.number().nullable().optional(),
})
.strip(),
z
.object({
type: z.literal("read"),
filePath: z.string(),
content: z.string().optional(),
offset: z.number().optional(),
limit: z.number().optional(),
})
.strip(),
z
.object({
type: z.literal("edit"),
filePath: z.string(),
oldString: z.string().optional(),
newString: z.string().optional(),
unifiedDiff: z.string().optional(),
})
.strip(),
z
.object({ type: z.literal("write"), filePath: z.string(), content: z.string().optional() })
.strip(),
z
.object({
type: z.literal("search"),
query: z.string(),
toolName: z.enum(["search", "grep", "glob", "web_search"]).optional(),
content: z.string().optional(),
filePaths: z.array(z.string()).optional(),
webResults: z.array(z.object({ title: z.string(), url: z.string() }).strip()).optional(),
annotations: z.array(z.string()).optional(),
numFiles: z.number().optional(),
numMatches: z.number().optional(),
durationMs: z.number().optional(),
durationSeconds: z.number().optional(),
truncated: z.boolean().optional(),
mode: z.enum(["content", "files_with_matches", "count"]).optional(),
})
.strip(),
z
.object({
type: z.literal("fetch"),
url: z.string(),
prompt: z.string().optional(),
result: z.string().optional(),
code: z.number().optional(),
codeText: z.string().optional(),
bytes: z.number().optional(),
durationMs: z.number().optional(),
})
.strip(),
z
.object({
type: z.literal("worktree_setup"),
worktreePath: z.string(),
branchName: z.string(),
log: z.string(),
commands: z.array(worktreeCommandSchema),
truncated: z.boolean().optional(),
})
.strip(),
z
.object({
type: z.literal("sub_agent"),
subAgentType: z.string().optional(),
description: z.string().optional(),
childSessionId: z.string().optional(),
log: z.string(),
actions: z
.array(
z
.object({
index: z.number().int().positive(),
toolName: z.string(),
summary: z.string().optional(),
})
.strip(),
)
.optional(),
})
.strip(),
z
.object({
type: z.literal("plain_text"),
label: z.string().optional(),
text: z.string().optional(),
icon: z
.enum([
"wrench",
"square_terminal",
"eye",
"pencil",
"search",
"bot",
"sparkles",
"brain",
"mic_vocal",
])
.optional(),
})
.strip(),
z.object({ type: z.literal("plan"), text: z.string() }).strip(),
z.object({ type: z.literal("unknown"), input: z.json(), output: z.json() }).strip(),
]);
const timelineIdentityShape = { id: idSchema, revertToken: z.json().optional() };
const toolCallBaseShape = {
...timelineIdentityShape,
type: z.literal("tool_call"),
callId: idSchema,
name: z.string(),
detail: toolCallDetailSchema,
metadata: jsonObjectSchema.optional(),
};
const timelineItemSchema: z.ZodType<ProviderTimelineItem> = z.union([
z
.object({
...timelineIdentityShape,
type: z.literal("user_message"),
text: z.string(),
messageId: z.string().optional(),
clientMessageId: z.string().optional(),
})
.strip(),
z
.object({
...timelineIdentityShape,
type: z.literal("assistant_message"),
text: z.string(),
messageId: z.string().optional(),
})
.strip(),
z.object({ ...timelineIdentityShape, type: z.literal("reasoning"), text: z.string() }).strip(),
z.object({ ...toolCallBaseShape, status: z.literal("running"), error: z.null() }).strip(),
z.object({ ...toolCallBaseShape, status: z.literal("completed"), error: z.null() }).strip(),
z.object({ ...toolCallBaseShape, status: z.literal("failed"), error: z.json() }).strip(),
z.object({ ...toolCallBaseShape, status: z.literal("canceled"), error: z.null() }).strip(),
z
.object({
...timelineIdentityShape,
type: z.literal("todo"),
items: z.array(
z
.object({
text: z.string(),
completed: z.boolean(),
id: z.string().optional(),
status: z.enum(["pending", "in_progress", "completed"]).optional(),
activeForm: z.string().optional(),
})
.strip(),
),
})
.strip(),
z.object({ ...timelineIdentityShape, type: z.literal("error"), message: z.string() }).strip(),
z
.object({
...timelineIdentityShape,
type: z.literal("notification"),
level: z.enum(["info", "warning", "error"]),
message: z.string(),
})
.strip(),
z
.object({
...timelineIdentityShape,
type: z.literal("compaction"),
status: z.enum(["loading", "completed"]),
trigger: z.enum(["auto", "manual"]).optional(),
preTokens: z.number().optional(),
})
.strip(),
z
.object({
...timelineIdentityShape,
type: z.literal("plugin"),
pluginId: idSchema,
kind: z.string(),
version: z.number(),
data: z.json(),
})
.strip(),
]);
const permissionActionSchema = z
.object({
id: idSchema,
label: z.string(),
behavior: z.enum(["allow", "deny"]),
variant: z.enum(["primary", "secondary", "danger"]).optional(),
intent: z.enum(["implement", "implement_resume", "dismiss"]).optional(),
})
.strip();
const providerPermissionRequestSchema: z.ZodType<ProviderPermissionRequest> = z
.object({
id: idSchema,
name: z.string(),
kind: z.enum(["tool", "plan", "question", "mode", "other"]),
title: z.string().optional(),
description: z.string().optional(),
input: jsonObjectSchema.optional(),
detail: toolCallDetailSchema.optional(),
suggestions: z.array(jsonObjectSchema).optional(),
actions: z.array(permissionActionSchema).optional(),
metadata: jsonObjectSchema.optional(),
})
.strip();
export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnion("type", [
z.object({ type: z.literal("catalog"), requestId: idSchema, catalog: catalogSchema }).strip(),
z
.object({
type: z.literal("sessions"),
requestId: idSchema,
sessions: z.array(
z
.object({
persistence: persistenceSchema,
cwd: z.string(),
title: z.string().optional(),
description: z.string().optional(),
updatedAt: z.string().optional(),
})
.strip(),
),
})
.strip(),
z.object({ type: z.literal("request.completed"), requestId: idSchema }).strip(),
z
.object({ type: z.literal("request.failed"), requestId: idSchema, error: providerErrorSchema })
.strip(),
z
.object({
type: z.literal("session.opened"),
requestId: idSchema.optional(),
sessionId: idSchema,
parentSessionId: idSchema.optional(),
toolCallId: idSchema.optional(),
capabilities: z.array(z.string()),
restoration: z.enum(["core", "parent"]),
persistence: persistenceSchema.optional(),
title: z.string().optional(),
description: z.string().optional(),
cwd: z.string(),
})
.strip(),
z
.object({
type: z.literal("session.ready"),
requestId: idSchema.optional(),
sessionId: idSchema,
})
.strip(),
z
.object({
type: z.literal("session.can_stop_runtime"),
requestId: idSchema,
sessionId: idSchema,
canStop: z.boolean(),
})
.strip(),
z
.object({
type: z.literal("session.closed"),
sessionId: idSchema,
error: providerErrorSchema.optional(),
})
.strip(),
z
.object({
type: z.literal("session.runtime_failed"),
sessionId: idSchema,
error: providerErrorSchema,
})
.strip(),
z
.object({
type: z.literal("session.persistence"),
sessionId: idSchema,
persistence: persistenceSchema,
})
.strip(),
z
.object({
type: z.literal("session.prompt_result"),
sessionId: idSchema,
clientMessageId: idSchema,
result: z.union([
z.object({ type: z.literal("turn"), turnId: idSchema }).strip(),
z.object({ type: z.literal("steer"), turnId: idSchema }).strip(),
z.object({ type: z.literal("completed") }).strip(),
z.object({ type: z.literal("failed"), error: providerErrorSchema }).strip(),
]),
})
.strip(),
z
.object({
type: z.literal("session.turn"),
sessionId: idSchema,
turnId: idSchema,
state: z.enum(["started", "completed", "failed", "canceled"]),
error: providerErrorSchema.optional(),
})
.strip(),
z
.object({
type: z.literal("session.usage"),
sessionId: idSchema,
turnId: idSchema.optional(),
usage: usageSchema,
})
.strip(),
z
.object({ type: z.literal("session.config"), sessionId: idSchema, config: configStateSchema })
.strip(),
z
.object({
type: z.literal("session.commands"),
sessionId: idSchema,
commands: z.array(commandSchema),
})
.strip(),
z
.object({
type: z.literal("session.permission"),
sessionId: idSchema,
request: providerPermissionRequestSchema,
})
.strip(),
z
.object({
type: z.literal("session.permission_resolved"),
sessionId: idSchema,
permissionId: idSchema,
})
.strip(),
z
.object({ type: z.literal("session.notice"), sessionId: idSchema, notice: noticeSchema })
.strip(),
z
.object({
type: z.literal("timeline.item"),
sessionId: idSchema,
item: timelineItemSchema,
timestamp: z.string().optional(),
})
.strip(),
]);