Path: blob/main/src/vs/platform/agentHost/common/state/protocol/state.ts
13405 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45// allow-any-unicode-comment-file6// DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts78// ─── Type Aliases ────────────────────────────────────────────────────────────910/** A URI string (e.g. `agenthost:/root` or `copilot:/<uuid>`). */11export type URI = string;1213/**14* A string that may optionally be rendered as Markdown.15*16* - A plain `string` is rendered as-is (no Markdown processing).17* - An object with `{ markdown: string }` is rendered with Markdown formatting.18*/19export type StringOrMarkdown = string | { markdown: string };2021// ─── Icon ────────────────────────────────────────────────────────────────────2223/**24* An optionally-sized icon that can be displayed in a user interface.25*26* @category Common Types27*/28export interface Icon {29/**30* A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a31* `data:` URI with Base64-encoded image data.32*33* Consumers SHOULD take steps to ensure URLs serving icons are from the34* same domain as the client/server or a trusted domain.35*36* Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain37* executable JavaScript.38*/39src: URI;4041/**42* Optional MIME type override if the source MIME type is missing or generic.43* For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`.44*/45contentType?: string;4647/**48* Optional array of strings that specify sizes at which the icon can be used.49* Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.50*51* If not provided, the client should assume that the icon can be used at any size.52*/53sizes?: string[];5455/**56* Optional specifier for the theme this icon is designed for. `"light"` indicates57* the icon is designed to be used with a light background, and `"dark"` indicates58* the icon is designed to be used with a dark background.59*60* If not provided, the client should assume the icon can be used with any theme.61*/62theme?: 'light' | 'dark';63}6465// ─── Protected Resource Metadata (RFC 9728) ─────────────────────────────────6667/**68* Describes a protected resource's authentication requirements using69* [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) (OAuth 2.070* Protected Resource Metadata) semantics.71*72* Field names use snake_case to match the RFC 9728 JSON format.73*74* @category Authentication75* @see {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728}76*/77export interface ProtectedResourceMetadata {78/**79* REQUIRED. The protected resource's resource identifier, a URL using the80* `https` scheme with no fragment component (e.g. `"https://api.github.com"`).81*/82resource: string;8384/** OPTIONAL. Human-readable name of the protected resource. */85resource_name?: string;8687/** OPTIONAL. JSON array of OAuth authorization server identifier URLs. */88authorization_servers?: string[];8990/** OPTIONAL. URL of the protected resource's JWK Set document. */91jwks_uri?: string;9293/** RECOMMENDED. JSON array of OAuth 2.0 scope values used in authorization requests. */94scopes_supported?: string[];9596/** OPTIONAL. JSON array of Bearer Token presentation methods supported. */97bearer_methods_supported?: string[];9899/** OPTIONAL. JSON array of JWS signing algorithms supported. */100resource_signing_alg_values_supported?: string[];101102/** OPTIONAL. JSON array of JWE encryption algorithms (alg) supported. */103resource_encryption_alg_values_supported?: string[];104105/** OPTIONAL. JSON array of JWE encryption algorithms (enc) supported. */106resource_encryption_enc_values_supported?: string[];107108/** OPTIONAL. URL of human-readable documentation for the resource. */109resource_documentation?: string;110111/** OPTIONAL. URL of the resource's data-usage policy. */112resource_policy_uri?: string;113114/** OPTIONAL. URL of the resource's terms of service. */115resource_tos_uri?: string;116117/**118* AHP extension. Whether authentication is required for this resource.119*120* - `true` (default) — the agent cannot be used without a valid token.121* The server SHOULD return `AuthRequired` (`-32007`) if the client122* attempts to use the agent without authenticating.123* - `false` — the agent works without authentication but MAY offer124* enhanced capabilities when a token is provided.125*126* Clients SHOULD treat an absent field the same as `true`.127*/128required?: boolean;129}130131// ─── Root State ──────────────────────────────────────────────────────────────132133/**134* Policy configuration state for a model.135*136* @category Root State137*/138export const enum PolicyState {139Enabled = 'enabled',140Disabled = 'disabled',141Unconfigured = 'unconfigured',142}143144/**145* Global state shared with every client subscribed to `agenthost:/root`.146*147* @category Root State148*/149export interface RootState {150/** Available agent backends and their models */151agents: AgentInfo[];152/** Number of active (non-disposed) sessions on the server */153activeSessions?: number;154/** Known terminals on the server. Subscribe to individual terminal URIs for full state. */155terminals?: TerminalInfo[];156/** Agent host configuration schema and current values */157config?: RootConfigState;158}159160/**161* @category Root State162*/163export interface AgentInfo {164/** Agent provider ID (e.g. `'copilot'`) */165provider: string;166/** Human-readable name */167displayName: string;168/** Description string */169description: string;170/** Available models for this agent */171models: SessionModelInfo[];172/**173* Protected resources this agent requires authentication for.174*175* Each entry describes an OAuth 2.0 protected resource using176* [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) semantics.177* Clients should obtain tokens from the declared `authorization_servers`178* and push them via the `authenticate` command before creating sessions179* with this agent.180*181* @see {@link /specification/authentication | Authentication}182*/183protectedResources?: ProtectedResourceMetadata[];184/**185* Customizations (Open Plugins) associated with this agent.186*187* Each entry is a reference to an [Open Plugins](https://open-plugins.com/)188* plugin that the agent host can activate for sessions using this agent.189*/190customizations?: CustomizationRef[];191}192193/**194* @category Root State195*/196export interface SessionModelInfo {197/** Model identifier */198id: string;199/** Provider this model belongs to */200provider: string;201/** Human-readable model name */202name: string;203/** Maximum context window size */204maxContextWindow?: number;205/** Whether the model supports vision */206supportsVision?: boolean;207/** Policy configuration state */208policyState?: PolicyState;209/**210* Configuration schema describing model-specific options (e.g. thinking211* level). Clients present this as a form and pass the resolved values in212* {@link ModelSelection.config} when creating or changing sessions.213*/214configSchema?: ConfigSchema;215}216217/**218* A model selection: the chosen model ID together with any model-specific219* configuration values whose keys correspond to the model's220* {@link SessionModelInfo.configSchema}.221*222* @category Root State223*/224export interface ModelSelection {225/** Model identifier */226id: string;227/** Model-specific configuration values */228config?: Record<string, string>;229}230231// ─── Pending Message Types ───────────────────────────────────────────────────232233/**234* Discriminant for pending message kinds.235*236* @category Pending Message Types237*/238export const enum PendingMessageKind {239/** Injected into the current turn at a convenient point */240Steering = 'steering',241/** Sent automatically as a new turn after the current turn finishes */242Queued = 'queued',243}244245/**246* A message queued for future delivery to the agent.247*248* Steering messages are injected into the current turn mid-flight.249* Queued messages are automatically started as new turns after the250* current turn naturally finishes.251*252* @category Pending Message Types253*/254export interface PendingMessage {255/** Unique identifier for this pending message */256id: string;257/** The message content */258userMessage: UserMessage;259}260261// ─── Session State ───────────────────────────────────────────────────────────262263/**264* Session initialization state.265*266* @category Session State267*/268export const enum SessionLifecycle {269Creating = 'creating',270Ready = 'ready',271CreationFailed = 'creationFailed',272}273274/**275* Bitset of summary-level session status flags.276*277* Use bitwise checks instead of equality for non-terminal activity. For example,278* `status & SessionStatus.InProgress` matches both ordinary in-progress turns279* and turns that are paused waiting for input.280*281* @category Session State282*/283export const enum SessionStatus {284/** Session is idle — no turn is active. */285Idle = 1,286/** Session ended with an error. */287Error = 1 << 1,288/** A turn is actively streaming. */289InProgress = 1 << 3,290/** A turn is in progress but blocked waiting for user input or tool confirmation. */291InputNeeded = (1 << 3) | (1 << 4),292/** The client has viewed this session since its last modification. */293IsRead = 1 << 5,294/** The session has been archived by the client. */295IsArchived = 1 << 6,296}297298/**299* Full state for a single session, loaded when a client subscribes to the session's URI.300*301* @category Session State302*/303export interface SessionState {304/** Lightweight session metadata */305summary: SessionSummary;306/** Session initialization state */307lifecycle: SessionLifecycle;308/** Error details if creation failed */309creationError?: ErrorInfo;310/** Tools provided by the server (agent host) for this session */311serverTools?: ToolDefinition[];312/** The client currently providing tools and interactive capabilities to this session */313activeClient?: SessionActiveClient;314/** Completed turns */315turns: Turn[];316/** Currently in-progress turn */317activeTurn?: ActiveTurn;318/** Message to inject into the current turn at a convenient point */319steeringMessage?: PendingMessage;320/** Messages to send automatically as new turns after the current turn finishes */321queuedMessages?: PendingMessage[];322/** Requests for user input that are currently blocking or informing session progress */323inputRequests?: SessionInputRequest[];324/** Session configuration schema and current values */325config?: SessionConfigState;326/**327* Server-provided customizations active in this session.328*329* Client-provided customizations are available on330* {@link SessionActiveClient.customizations | activeClient.customizations}.331*/332customizations?: SessionCustomization[];333/**334* Additional provider-specific metadata for this session.335*336* Clients MAY look for well-known keys here to provide enhanced UI.337* For example, a `git` key may provide extra git metadata about the session's338* workingDirectory.339*/340_meta?: Record<string, unknown>;341}342343/**344* The client currently providing tools and interactive capabilities to a session.345*346* Only one client may be active per session at a time. The server SHOULD347* automatically unset the active client if that client disconnects.348*349* @category Session State350*/351export interface SessionActiveClient {352/** Client identifier (matches `clientId` from `initialize`) */353clientId: string;354/** Human-readable client name (e.g. `"VS Code"`) */355displayName?: string;356/** Tools this client provides to the session */357tools: ToolDefinition[];358/** Customizations this client contributes to the session */359customizations?: CustomizationRef[];360}361362/**363* Server-owned project metadata for a session.364*365* @category Session State366*/367export interface ProjectInfo {368/** Project URI */369uri: URI;370/** Human-readable project name */371displayName: string;372}373374/**375* @category Session State376*/377export interface SessionSummary {378/** Session URI */379resource: URI;380/** Agent provider ID */381provider: string;382/** Session title */383title: string;384/** Current session status */385status: SessionStatus;386/** Human-readable description of what the session is currently doing */387activity?: string;388/** Creation timestamp */389createdAt: number;390/** Last modification timestamp */391modifiedAt: number;392/** Server-owned project for this session */393project?: ProjectInfo;394/** Currently selected model */395model?: ModelSelection;396/** The working directory URI for this session */397workingDirectory?: URI;398/** Files changed during this session with diff statistics */399diffs?: FileEdit[];400}401402// ─── Config Schema Types ─────────────────────────────────────────────────────403404/**405* A JSON Schema-compatible property descriptor with display extensions.406*407* Standard JSON Schema fields (`type`, `title`, `description`, `default`,408* `enum`) allow validators to process the schema. Display extensions409* (`enumLabels`, `enumDescriptions`) are parallel arrays that provide UI410* metadata for each `enum` value.411*412* This is the generic base type. See {@link SessionConfigPropertySchema} for413* session-specific extensions.414*415* @category Config Schema Types416*/417export interface ConfigPropertySchema {418/** JSON Schema: property type */419type: 'string' | 'number' | 'boolean' | 'array' | 'object';420/** JSON Schema: human-readable label for the property */421title: string;422/** JSON Schema: description / tooltip */423description?: string;424/** JSON Schema: default value */425default?: unknown;426/** JSON Schema: allowed values (typically used with `string` type) */427enum?: string[];428/** Display extension: human-readable label per enum value (parallel array) */429enumLabels?: string[];430/** Display extension: description per enum value (parallel array) */431enumDescriptions?: string[];432/** JSON Schema: when `true`, the property is displayed but cannot be modified by the user */433readOnly?: boolean;434/** JSON Schema: schema for array items (used when `type` is `'array'`) */435items?: ConfigPropertySchema;436/** JSON Schema: property descriptors for object properties (used when `type` is `'object'`) */437properties?: Record<string, ConfigPropertySchema>;438/** JSON Schema: list of required property ids (used when `type` is `'object'`) */439required?: string[];440}441442/**443* A JSON Schema object describing available configuration properties.444*445* This is the generic base type. See {@link SessionConfigSchema} for446* session-specific usage.447*448* @category Config Schema Types449*/450export interface ConfigSchema {451/** JSON Schema: always `'object'` */452type: 'object';453/** JSON Schema: property descriptors keyed by property id */454properties: Record<string, ConfigPropertySchema>;455/** JSON Schema: list of required property ids */456required?: string[];457}458459// ─── Root Config Types ───────────────────────────────────────────────────────460461/**462* Live agent-host configuration metadata.463*464* The schema describes the available configuration properties and the values465* contain the current value for each resolved property.466*467* @category Root State468*/469export interface RootConfigState {470/** JSON Schema describing available configuration properties */471schema: ConfigSchema;472/** Current configuration values */473values: Record<string, unknown>;474}475476// ─── Session Config Types ────────────────────────────────────────────────────477478/**479* A session configuration property descriptor.480*481* Extends the generic {@link ConfigPropertySchema} with session-specific482* display extensions.483*484* @category Session Config Types485*/486export interface SessionConfigPropertySchema extends ConfigPropertySchema {487/**488* Display extension: when `true`, the full set of allowed values is too large489* to enumerate statically. The client SHOULD use `sessionConfigCompletions`490* to fetch matching values based on user input. Any values in `enum` are491* seed/recent values for initial display.492*/493enumDynamic?: boolean;494/** When `true`, the user may change this property after session creation */495sessionMutable?: boolean;496}497498/**499* A JSON Schema object describing available session configuration metadata.500*501* @category Session Config Types502*/503export interface SessionConfigSchema {504/** JSON Schema: always `'object'` */505type: 'object';506/** JSON Schema: property descriptors keyed by property id */507properties: Record<string, SessionConfigPropertySchema>;508/** JSON Schema: list of required property ids */509required?: string[];510}511512/**513* Live session configuration metadata.514*515* The schema describes the available configuration properties and the values516* contain the current value for each resolved property.517*518* @category Session Config Types519*/520export interface SessionConfigState {521/** JSON Schema describing available configuration properties */522schema: SessionConfigSchema;523/** Current configuration values */524values: Record<string, unknown>;525}526527// ─── Session Input Types ────────────────────────────────────────────────────528529/**530* How a client completed an input request.531*532* @category Session Input Types533*/534export const enum SessionInputResponseKind {535Accept = 'accept',536Decline = 'decline',537Cancel = 'cancel',538}539540/**541* Question/input control kind.542*543* @category Session Input Types544*/545export const enum SessionInputQuestionKind {546Text = 'text',547Number = 'number',548Integer = 'integer',549Boolean = 'boolean',550SingleSelect = 'single-select',551MultiSelect = 'multi-select',552}553554/**555* A choice in a select-style question.556*557* @category Session Input Types558*/559export interface SessionInputOption {560/** Stable option identifier; for MCP enum values this is the enum string */561id: string;562/** Display label */563label: string;564/** Optional secondary text */565description?: string;566/** Whether this option is the recommended/default choice */567recommended?: boolean;568}569570interface SessionInputQuestionBase {571/** Stable question identifier used as the key in `answers` */572id: string;573/** Short display title */574title?: string;575/** Prompt shown to the user */576message: string;577/** Whether the user must answer this question to accept the request */578required?: boolean;579}580581/** Text question within a session input request. */582export interface SessionInputTextQuestion extends SessionInputQuestionBase {583kind: SessionInputQuestionKind.Text;584/** Format hint for text questions, such as `email`, `uri`, `date`, or `date-time` */585format?: string;586/** Minimum string length */587min?: number;588/** Maximum string length */589max?: number;590/** Default text */591defaultValue?: string;592}593594/** Numeric question within a session input request. */595export interface SessionInputNumberQuestion extends SessionInputQuestionBase {596kind: SessionInputQuestionKind.Number | SessionInputQuestionKind.Integer;597/**598* Minimum value599* @format float600*/601min?: number;602/**603* Maximum value604* @format float605*/606max?: number;607/**608* Default numeric value609* @format float610*/611defaultValue?: number;612}613614/** Boolean question within a session input request. */615export interface SessionInputBooleanQuestion extends SessionInputQuestionBase {616kind: SessionInputQuestionKind.Boolean;617/** Default boolean value */618defaultValue?: boolean;619}620621/** Single-select question within a session input request. */622export interface SessionInputSingleSelectQuestion extends SessionInputQuestionBase {623kind: SessionInputQuestionKind.SingleSelect;624/** Options the user may select from */625options: SessionInputOption[];626/** Whether the user may enter text instead of selecting an option */627allowFreeformInput?: boolean;628}629630/** Multi-select question within a session input request. */631export interface SessionInputMultiSelectQuestion extends SessionInputQuestionBase {632kind: SessionInputQuestionKind.MultiSelect;633/** Options the user may select from */634options: SessionInputOption[];635/** Whether the user may enter text in addition to selecting options */636allowFreeformInput?: boolean;637/** Minimum selected item count */638min?: number;639/** Maximum selected item count */640max?: number;641}642643/**644* One question within a session input request.645*646* @category Session Input Types647*/648export type SessionInputQuestion = SessionInputTextQuestion649| SessionInputNumberQuestion650| SessionInputBooleanQuestion651| SessionInputSingleSelectQuestion652| SessionInputMultiSelectQuestion;653654/**655* A live request for user input.656*657* The server creates or replaces requests with `session/inputRequested`.658* Clients sync drafts with `session/inputAnswerChanged` and complete requests659* with `session/inputCompleted`.660*661* @category Session Input Types662*/663export interface SessionInputRequest {664/** Stable request identifier */665id: string;666/** Display message for the request as a whole */667message?: string;668/** URL the user should review or open, for URL-style elicitations */669url?: URI;670/** Ordered questions to ask the user */671questions?: SessionInputQuestion[];672/** Current draft or submitted answers, keyed by question ID */673answers?: Record<string, SessionInputAnswer>;674}675676/**677* Answer value kind.678*679* @category Session Input Types680*/681export const enum SessionInputAnswerValueKind {682Text = 'text',683Number = 'number',684Boolean = 'boolean',685Selected = 'selected',686SelectedMany = 'selected-many',687}688689/**690* Value captured for one answer.691*692* @category Session Input Types693*/694export interface SessionInputTextAnswerValue {695kind: SessionInputAnswerValueKind.Text;696value: string;697}698699export interface SessionInputNumberAnswerValue {700kind: SessionInputAnswerValueKind.Number;701/** @format float */702value: number;703}704705export interface SessionInputBooleanAnswerValue {706kind: SessionInputAnswerValueKind.Boolean;707value: boolean;708}709710export interface SessionInputSelectedAnswerValue {711kind: SessionInputAnswerValueKind.Selected;712value: string;713/** Free-form text entered instead of selecting an option */714freeformValues?: string[];715}716717export interface SessionInputSelectedManyAnswerValue {718kind: SessionInputAnswerValueKind.SelectedMany;719value: string[];720/** Free-form text entered in addition to selected options */721freeformValues?: string[];722}723724export type SessionInputAnswerValue = SessionInputTextAnswerValue725| SessionInputNumberAnswerValue726| SessionInputBooleanAnswerValue727| SessionInputSelectedAnswerValue728| SessionInputSelectedManyAnswerValue;729730export interface SessionInputAnswered {731/** Answer state */732state: SessionInputAnswerState.Draft | SessionInputAnswerState.Submitted;733/** Answer value */734value: SessionInputAnswerValue;735}736737export interface SessionInputSkipped {738/** Answer state */739state: SessionInputAnswerState.Skipped;740/** Free-form reason or value captured while skipping, if any */741freeformValues?: string[];742}743744/**745* Answer lifecycle state.746*747* @category Session Input Types748*/749export const enum SessionInputAnswerState {750Draft = 'draft',751Submitted = 'submitted',752Skipped = 'skipped',753}754755/**756* Draft, submitted, or skipped answer for one question.757*758* @category Session Input Types759*/760export type SessionInputAnswer = SessionInputAnswered | SessionInputSkipped;761762// ─── Turn Types ──────────────────────────────────────────────────────────────763764/**765* How a turn ended.766*767* @category Turn Types768*/769export const enum TurnState {770Complete = 'complete',771Cancelled = 'cancelled',772Error = 'error',773}774775/**776* Type of a message attachment.777*778* @category Turn Types779*/780export const enum AttachmentType {781File = 'file',782Directory = 'directory',783Selection = 'selection',784}785786/**787* A completed request/response cycle.788*789* @category Turn Types790*/791export interface Turn {792/** Turn identifier */793id: string;794/** The user's input */795userMessage: UserMessage;796/**797* All response content in stream order: text, tool calls, reasoning, and content refs.798*799* Consumers should derive display text by concatenating markdown parts,800* and find tool calls by filtering for `ToolCall` parts.801*/802responseParts: ResponsePart[];803/** Token usage info */804usage: UsageInfo | undefined;805/** How the turn ended */806state: TurnState;807/** Error details if state is `'error'` */808error?: ErrorInfo;809}810811/**812* An in-progress turn — the assistant is actively streaming.813*814* @category Turn Types815*/816export interface ActiveTurn {817/** Turn identifier */818id: string;819/** The user's input */820userMessage: UserMessage;821/**822* All response content in stream order: text, tool calls, reasoning, and content refs.823*824* Tool call parts include `pendingPermissions` when permissions are awaiting user approval.825*/826responseParts: ResponsePart[];827/** Token usage info */828usage: UsageInfo | undefined;829}830831/**832* @category Turn Types833*/834export interface UserMessage {835/** Message text */836text: string;837/** File/selection attachments */838attachments?: MessageAttachment[];839}840841/**842* @category Turn Types843*/844export interface MessageAttachment {845/** Attachment type */846type: AttachmentType;847/** File/directory URI */848uri: URI;849/** Display name */850displayName?: string;851}852853// ─── Response Parts ──────────────────────────────────────────────────────────854855/**856* Discriminant for response part types.857*858* @category Response Parts859*/860export const enum ResponsePartKind {861Markdown = 'markdown',862ContentRef = 'contentRef',863ToolCall = 'toolCall',864Reasoning = 'reasoning',865}866867/**868* @category Response Parts869*/870export interface MarkdownResponsePart {871/** Discriminant */872kind: ResponsePartKind.Markdown;873/** Part identifier, used by `session/delta` to target this part for content appends */874id: string;875/** Markdown content */876content: string;877}878879/**880* A reference to large content stored outside the state tree.881*/882export interface ContentRef {883/** Content URI */884uri: URI;885/** Approximate size in bytes */886sizeHint?: number;887/** Content MIME type */888contentType?: string;889}890891/**892* A content part that's a reference to large content stored outside the state tree.893*894* @category Response Parts895*/896export interface ResourceReponsePart extends ContentRef {897/** Discriminant */898kind: ResponsePartKind.ContentRef;899}900901/**902* A tool call represented as a response part.903*904* Tool calls are part of the response stream, interleaved with text and905* reasoning. The `toolCall.toolCallId` serves as the part identifier for906* actions that target this part.907*908* @category Response Parts909*/910export interface ToolCallResponsePart {911/** Discriminant */912kind: ResponsePartKind.ToolCall;913/** Full tool call lifecycle state */914toolCall: ToolCallState;915}916917/**918* Reasoning/thinking content from the model.919*920* @category Response Parts921*/922export interface ReasoningResponsePart {923/** Discriminant */924kind: ResponsePartKind.Reasoning;925/** Part identifier, used by `session/reasoning` to target this part for content appends */926id: string;927/** Accumulated reasoning text */928content: string;929}930931/**932* @category Response Parts933*/934export type ResponsePart = MarkdownResponsePart | ResourceReponsePart | ToolCallResponsePart | ReasoningResponsePart;935936// ─── Tool Call Types ─────────────────────────────────────────────────────────937938/**939* Status of a tool call in the lifecycle state machine.940*941* @category Tool Call Types942*/943export const enum ToolCallStatus {944Streaming = 'streaming',945PendingConfirmation = 'pending-confirmation',946Running = 'running',947PendingResultConfirmation = 'pending-result-confirmation',948Completed = 'completed',949Cancelled = 'cancelled',950}951952/**953* How a tool call was confirmed for execution.954*955* - `NotNeeded` — No confirmation required (auto-approved)956* - `UserAction` — User explicitly approved957* - `Setting` — Approved by a persistent user setting958*959* @category Tool Call Types960*/961export const enum ToolCallConfirmationReason {962NotNeeded = 'not-needed',963UserAction = 'user-action',964Setting = 'setting',965}966967/**968* Why a tool call was cancelled.969*970* @category Tool Call Types971*/972export const enum ToolCallCancellationReason {973Denied = 'denied',974Skipped = 'skipped',975ResultDenied = 'result-denied',976}977978/**979* Whether a confirmation option represents an approval or denial action.980*981* @category Tool Call Types982*/983export const enum ConfirmationOptionKind {984Approve = 'approve',985Deny = 'deny',986}987988/**989* A confirmation option that the server offers for a tool call awaiting990* approval. Allows richer choices beyond simple approve/deny — for example,991* "Approve in this Session" or "Deny with reason."992*993* @category Tool Call Types994*/995export interface ConfirmationOption {996/** Unique identifier for the option, returned in the confirmed action */997id: string;998/** Human-readable label displayed to the user */999label: string;1000/** Whether this option represents an approval or denial */1001kind: ConfirmationOptionKind;1002/**1003* Logical group number for visual categorisation.1004*1005* Clients SHOULD display options in the order they are defined and MAY1006* use differing group numbers to insert dividers between logical clusters1007* of options.1008*/1009group?: number;1010}10111012/**1013* Metadata common to all tool call states.1014*1015* @category Tool Call Types1016* @remarks1017* Fields like `toolName` carry agent-specific identifiers on the wire despite the1018* agent-agnostic design principle. These exist for debugging and logging purposes.1019* A future version may move these to a separate diagnostic channel or namespace them1020* more clearly.1021*/1022interface ToolCallBase {1023/** Unique tool call identifier */1024toolCallId: string;1025/** Internal tool name (for debugging/logging) */1026toolName: string;1027/** Human-readable tool name */1028displayName: string;1029/**1030* If this tool is provided by a client, the `clientId` of the owning client.1031* Absent for server-side tools.1032*1033* When set, the identified client is responsible for executing the tool and1034* dispatching `session/toolCallComplete` with the result.1035*/1036toolClientId?: string;1037/**1038* Additional provider-specific metadata for this tool call.1039*1040* Clients MAY look for well-known keys here to provide enhanced UI.1041* For example, a `ptyTerminal` key with `{ input: string; output: string }`1042* indicates the tool operated on a terminal (both `input` and `output` may1043* contain escape sequences).1044*/1045_meta?: Record<string, unknown>;1046}10471048/**1049* Properties available once tool call parameters are fully received.1050*1051* @category Tool Call Types1052*/1053interface ToolCallParameterFields {1054/** Message describing what the tool will do */1055invocationMessage: StringOrMarkdown;1056/** Raw tool input */1057toolInput?: string;1058}10591060/**1061* Tool execution result details, available after execution completes.1062*1063* @category Tool Call Types1064*/1065export interface ToolCallResult {1066/** Whether the tool succeeded */1067success: boolean;1068/** Past-tense description of what the tool did */1069pastTenseMessage: StringOrMarkdown;1070/**1071* Unstructured result content blocks.1072*1073* This mirrors the `content` field of MCP `CallToolResult`.1074*/1075content?: ToolResultContent[];1076/**1077* Optional structured result object.1078*1079* This mirrors the `structuredContent` field of MCP `CallToolResult`.1080*/1081structuredContent?: Record<string, unknown>;1082/** Error details if the tool failed */1083error?: { message: string; code?: string };1084}10851086/**1087* LM is streaming the tool call parameters.1088*1089* @category Tool Call Types1090*/1091export interface ToolCallStreamingState extends ToolCallBase {1092status: ToolCallStatus.Streaming;1093/** Partial parameters accumulated so far */1094partialInput?: string;1095/** Progress message shown while parameters are streaming */1096invocationMessage?: StringOrMarkdown;1097}10981099/**1100* Parameters are complete, or a running tool requires re-confirmation1101* (e.g. a mid-execution permission check).1102*1103* @category Tool Call Types1104*/1105export interface ToolCallPendingConfirmationState extends ToolCallBase, ToolCallParameterFields {1106status: ToolCallStatus.PendingConfirmation;1107/** Short title for the confirmation prompt (e.g. `"Run in terminal"`, `"Write file"`) */1108confirmationTitle?: StringOrMarkdown;1109/** File edits that this tool call will perform, for preview before confirmation */1110edits?: { items: FileEdit[] };1111/** Whether the agent host allows the client to edit the tool's input parameters before confirming */1112editable?: boolean;1113/**1114* Options the server offers for this confirmation. When present, the client1115* SHOULD render these instead of a plain approve/deny UI. Each option1116* belongs to a {@link ConfirmationOptionGroup} so the client can still1117* categorise the choices.1118*/1119options?: ConfirmationOption[];1120}11211122/**1123* Tool is actively executing.1124*1125* @category Tool Call Types1126*/1127export interface ToolCallRunningState extends ToolCallBase, ToolCallParameterFields {1128status: ToolCallStatus.Running;1129/** How the tool was confirmed for execution */1130confirmed: ToolCallConfirmationReason;1131/** The confirmation option the user selected, if confirmation options were provided */1132selectedOption?: ConfirmationOption;1133/**1134* Partial content produced while the tool is still executing.1135*1136* For example, a terminal content block lets clients subscribe to live1137* output before the tool completes.1138*/1139content?: ToolResultContent[];1140}11411142/**1143* Tool finished executing, waiting for client to approve the result.1144*1145* @category Tool Call Types1146*/1147export interface ToolCallPendingResultConfirmationState extends ToolCallBase, ToolCallParameterFields, ToolCallResult {1148status: ToolCallStatus.PendingResultConfirmation;1149/** How the tool was confirmed for execution */1150confirmed: ToolCallConfirmationReason;1151/** The confirmation option the user selected, if confirmation options were provided */1152selectedOption?: ConfirmationOption;1153}11541155/**1156* Tool completed successfully or with an error.1157*1158* @category Tool Call Types1159*/1160export interface ToolCallCompletedState extends ToolCallBase, ToolCallParameterFields, ToolCallResult {1161status: ToolCallStatus.Completed;1162/** How the tool was confirmed for execution */1163confirmed: ToolCallConfirmationReason;1164/** The confirmation option the user selected, if confirmation options were provided */1165selectedOption?: ConfirmationOption;1166}11671168/**1169* Tool call was cancelled before execution.1170*1171* @category Tool Call Types1172*/1173export interface ToolCallCancelledState extends ToolCallBase, ToolCallParameterFields {1174status: ToolCallStatus.Cancelled;1175/** Why the tool was cancelled */1176reason: ToolCallCancellationReason;1177/** Optional message explaining the cancellation */1178reasonMessage?: StringOrMarkdown;1179/** What the user suggested doing instead */1180userSuggestion?: UserMessage;1181/** The confirmation option the user selected, if confirmation options were provided */1182selectedOption?: ConfirmationOption;1183}11841185/**1186* Discriminated union of all tool call lifecycle states.1187*1188* See the [state model guide](/guide/state-model.html#tool-call-lifecycle)1189* for the full state machine diagram.1190*1191* @category Tool Call Types1192*/1193export type ToolCallState =1194| ToolCallStreamingState1195| ToolCallPendingConfirmationState1196| ToolCallRunningState1197| ToolCallPendingResultConfirmationState1198| ToolCallCompletedState1199| ToolCallCancelledState;12001201// ─── Tool Definition Types ───────────────────────────────────────────────────12021203/**1204* Describes a tool available in a session, provided by either the server or the active client.1205*1206* @category Tool Definition Types1207*/1208export interface ToolDefinition {1209/** Unique tool identifier */1210name: string;1211/** Human-readable display name */1212title?: string;1213/** Description of what the tool does */1214description?: string;1215/**1216* JSON Schema defining the expected input parameters.1217*1218* Optional because client-provided tools may not have formal schemas.1219* Mirrors MCP `Tool.inputSchema`.1220*/1221inputSchema?: {1222type: 'object';1223properties?: Record<string, object>;1224required?: string[];1225};1226/**1227* JSON Schema defining the structure of the tool's output.1228*1229* Mirrors MCP `Tool.outputSchema`.1230*/1231outputSchema?: {1232type: 'object';1233properties?: Record<string, object>;1234required?: string[];1235};1236/** Behavioral hints about the tool. All properties are advisory. */1237annotations?: ToolAnnotations;1238/**1239* Additional provider-specific metadata.1240*1241* Mirrors the MCP `_meta` convention.1242*/1243_meta?: Record<string, unknown>;1244}12451246/**1247* Behavioral hints about a tool. All properties are advisory and not1248* guaranteed to faithfully describe tool behavior.1249*1250* Mirrors MCP `ToolAnnotations` from the Model Context Protocol specification.1251*1252* @category Tool Definition Types1253*/1254export interface ToolAnnotations {1255/** Alternate human-readable title */1256title?: string;1257/** Tool does not modify its environment (default: false) */1258readOnlyHint?: boolean;1259/** Tool may perform destructive updates (default: true) */1260destructiveHint?: boolean;1261/** Repeated calls with the same arguments have no additional effect (default: false) */1262idempotentHint?: boolean;1263/** Tool may interact with external entities (default: true) */1264openWorldHint?: boolean;1265}12661267// ─── Tool Result Content ─────────────────────────────────────────────────────12681269/**1270* Discriminant for tool result content types.1271*1272* @category Tool Result Content1273*/1274export const enum ToolResultContentType {1275Text = 'text',1276EmbeddedResource = 'embeddedResource',1277Resource = 'resource',1278FileEdit = 'fileEdit',1279Terminal = 'terminal',1280Subagent = 'subagent',1281}12821283/**1284* Text content in a tool result.1285*1286* Mirrors MCP `TextContent`.1287*1288* @category Tool Result Content1289*/1290export interface ToolResultTextContent {1291type: ToolResultContentType.Text;1292/** The text content */1293text: string;1294}12951296/**1297* Base64-encoded binary content embedded in a tool result.1298*1299* Mirrors MCP `EmbeddedResource` for inline binary data.1300*1301* @category Tool Result Content1302*/1303export interface ToolResultEmbeddedResourceContent {1304type: ToolResultContentType.EmbeddedResource;1305/** Base64-encoded data */1306data: string;1307/** Content type (e.g. `"image/png"`, `"application/pdf"`) */1308contentType: string;1309}13101311/**1312* A reference to a resource stored outside the tool result.1313*1314* Wraps {@link ContentRef} for lazy-loading large results.1315*1316* @category Tool Result Content1317*/1318export interface ToolResultResourceContent extends ContentRef {1319type: ToolResultContentType.Resource;1320}13211322/**1323* Describes a file modification with before/after state and diff metadata.1324*1325* Supports creates (only `after`), deletes (only `before`), renames/moves1326* (different `uri` in `before` and `after`), and edits (same `uri`, different content).1327*1328* @category Tool Result Content1329*/1330export interface FileEdit {1331/** The file state before the edit. Absent for file creations or for in-place file edits. */1332before?: {1333/** URI of the file before the edit */1334uri: URI;1335/** Reference to the file content before the edit */1336content: ContentRef;1337};1338/** The file state after the edit. Absent for file deletions. */1339after?: {1340/** URI of the file after the edit */1341uri: URI;1342/** Reference to the file content after the edit */1343content: ContentRef;1344};1345/** Optional diff display metadata */1346diff?: {1347/** Number of items added (e.g., lines for text files, cells for notebooks) */1348added?: number;1349/** Number of items removed (e.g., lines for text files, cells for notebooks) */1350removed?: number;1351};1352}13531354/**1355* Describes a file modification performed by a tool.1356*1357* @category Tool Result Content1358*/1359export interface ToolResultFileEditContent extends FileEdit {1360type: ToolResultContentType.FileEdit;1361}13621363/**1364* A reference to a terminal whose output is relevant to this tool result.1365*1366* Clients can subscribe to the terminal's URI to stream its output in real1367* time, providing live feedback while a tool is executing.1368*1369* @category Tool Result Content1370*/1371export interface ToolResultTerminalContent {1372type: ToolResultContentType.Terminal;1373/** Terminal URI (subscribable for full terminal state) */1374resource: URI;1375/** Display title for the terminal content */1376title: string;1377}13781379/**1380* A reference to a subagent session spawned by a tool.1381*1382* Clients can subscribe to the subagent's session URI to stream its1383* progress in real time, including inner tool calls and responses.1384*1385* @category Tool Result Content1386*/1387export interface ToolResultSubagentContent {1388type: ToolResultContentType.Subagent;1389/** Subagent session URI (subscribable for full session state) */1390resource: URI;1391/** Display title for the subagent */1392title: string;1393/** Internal agent name */1394agentName?: string;1395/** Human-readable description of the subagent's task */1396description?: string;1397}13981399/**1400* Content block in a tool result.1401*1402* Mirrors the content blocks in MCP `CallToolResult.content`, plus1403* `ToolResultResourceContent` for lazy-loading large results,1404* `ToolResultFileEditContent` for file edit diffs,1405* `ToolResultTerminalContent` for live terminal output, and1406* `ToolResultSubagentContent` for subagent sessions (AHP extensions).1407*1408* @category Tool Result Content1409*/1410export type ToolResultContent =1411| ToolResultTextContent1412| ToolResultEmbeddedResourceContent1413| ToolResultResourceContent1414| ToolResultFileEditContent1415| ToolResultTerminalContent1416| ToolResultSubagentContent;14171418// ─── Customization Types ─────────────────────────────────────────────────────14191420/**1421* A reference to an [Open Plugins](https://open-plugins.com/) plugin.1422*1423* This is intentionally thin — AHP specifies plugin identity and metadata1424* but not implementation details, which are defined by the Open Plugins spec.1425*1426* @category Customization Types1427*/1428export interface CustomizationRef {1429/** Plugin URI (e.g. an HTTPS URL or marketplace identifier) */1430uri: URI;1431/** Human-readable name */1432displayName: string;1433/** Description of what the plugin provides */1434description?: string;1435/** Icons for the plugin */1436icons?: Icon[];1437/**1438* Opaque version token for this customization.1439*1440* Clients SHOULD include a nonce with every customization they provide.1441* Consumers can compare nonces to detect whether a customization has1442* changed since it was last seen, avoiding redundant reloads or copies.1443*/1444nonce?: string;1445}14461447/**1448* Loading status for a server-managed customization.1449*1450* @category Customization Types1451*/1452export const enum CustomizationStatus {1453/** Plugin is being loaded */1454Loading = 'loading',1455/** Plugin is fully operational */1456Loaded = 'loaded',1457/** Plugin partially loaded but has warnings */1458Degraded = 'degraded',1459/** Plugin was unable to load */1460Error = 'error',1461}14621463/**1464* A customization active in a session.1465*1466* @category Customization Types1467*/1468export interface SessionCustomization {1469/** The plugin this customization refers to */1470customization: CustomizationRef;1471/** Whether this customization is currently enabled */1472enabled: boolean;1473/**1474* The `clientId` of the client that contributed this customization.1475* Absent for host-provided customizations.1476*/1477clientId?: string;1478/** Server-reported loading status */1479status?: CustomizationStatus;1480/**1481* Human-readable status detail (e.g. error message or degradation warning).1482*/1483statusMessage?: string;1484}14851486// ─── Terminal Types ──────────────────────────────────────────────────────────14871488/**1489* Lightweight terminal metadata exposed on the root state.1490*1491* @category Terminal Types1492*/1493export interface TerminalInfo {1494/** Terminal URI (subscribable for full terminal state) */1495resource: URI;1496/** Human-readable terminal title */1497title: string;1498/** Who currently holds this terminal */1499claim: TerminalClaim;1500/** Process exit code, if the terminal process has exited */1501exitCode?: number;1502}15031504/**1505* Discriminant for terminal claim kinds.1506*1507* @category Terminal Types1508*/1509export const enum TerminalClaimKind {1510Client = 'client',1511Session = 'session',1512}15131514/**1515* A terminal claimed by a connected client.1516*1517* @category Terminal Types1518*/1519export interface TerminalClientClaim {1520/** Discriminant */1521kind: TerminalClaimKind.Client;1522/** The `clientId` of the claiming client */1523clientId: string;1524}15251526/**1527* A terminal claimed by a session, optionally scoped to a specific turn or tool call.1528*1529* @category Terminal Types1530*/1531export interface TerminalSessionClaim {1532/** Discriminant */1533kind: TerminalClaimKind.Session;1534/** Session URI that claimed the terminal */1535session: URI;1536/** Optional turn identifier within the session */1537turnId?: string;1538/** Optional tool call identifier within the turn */1539toolCallId?: string;1540}15411542/**1543* Describes who currently holds a terminal. A terminal may be claimed by1544* either a connected client or a session (e.g. during a tool call).1545*1546* @category Terminal Types1547*/1548export type TerminalClaim = TerminalClientClaim | TerminalSessionClaim;15491550/**1551* Full state for a single terminal, loaded when a client subscribes to the terminal's URI.1552*1553* @category Terminal Types1554*/1555export interface TerminalState {1556/** Human-readable terminal title */1557title: string;1558/** Current working directory of the terminal process */1559cwd?: URI;1560/** Terminal width in columns */1561cols?: number;1562/** Terminal height in rows */1563rows?: number;1564/**1565* Typed content parts, replacing the flat `content: string`.1566*1567* Naive consumers that only need the raw VT stream can reconstruct it with:1568* `content.map(p => p.type === 'command' ? p.output : p.value).join('')`1569*1570* Consumers that need command boundaries can filter by part type.1571*/1572content: TerminalContentPart[];1573/** Process exit code, set when the terminal process exits */1574exitCode?: number;1575/** Who currently holds this terminal */1576claim: TerminalClaim;1577/**1578* Whether this terminal emits `terminal/commandExecuted` and1579* `terminal/commandFinished` actions and populates `command`-typed parts.1580*1581* Clients MUST check this flag before relying on command detection.1582* Do NOT use the presence of a `command` part as a feature flag — parts1583* are absent in the normal idle state.1584*/1585supportsCommandDetection?: boolean;1586}15871588// ─── Terminal Content Parts ──────────────────────────────────────────────────15891590/**1591* A content part within terminal output.1592*1593* @category Terminal Types1594*/1595export type TerminalContentPart =1596| TerminalUnclassifiedPart1597| TerminalCommandPart;15981599/**1600* Unstructured terminal output — content before, between, or after commands,1601* or from terminals that do not support command detection.1602*1603* @category Terminal Types1604*/1605export interface TerminalUnclassifiedPart {1606type: 'unclassified';1607/** Accumulated VT output. Appended to by `terminal/data` when no command is executing. */1608value: string;1609}16101611/**1612* A single command: its command line and the output it produced.1613*1614* While `isComplete` is false the command is still executing; `output` grows1615* as `terminal/data` actions arrive. At `terminal/commandFinished` the part1616* is mutated in-place with `isComplete: true` and the completion metadata.1617*1618* @category Terminal Types1619*/1620export interface TerminalCommandPart {1621type: 'command';1622/**1623* Stable id matching the `commandId` on the corresponding1624* `terminal/commandExecuted` and `terminal/commandFinished` actions.1625*/1626commandId: string;1627/** The command line submitted to the shell. */1628commandLine: string;1629/**1630* Accumulated VT output. Appended to by `terminal/data` while `isComplete`1631* is false. Shell integration escape sequences are stripped by the server.1632*/1633output: string;1634/** Unix timestamp (ms) when execution started, as reported by the server. */1635timestamp: number;1636/** Whether the command has finished. */1637isComplete: boolean;1638/** Shell exit code. Set at completion. `undefined` if unknown. */1639exitCode?: number;1640/** Wall-clock duration in milliseconds. Set at completion. */1641durationMs?: number;1642}16431644// ─── Common Types ────────────────────────────────────────────────────────────16451646/**1647* @category Common Types1648*/1649export interface UsageInfo {1650/** Input tokens consumed */1651inputTokens?: number;1652/** Output tokens generated */1653outputTokens?: number;1654/** Model used */1655model?: string;1656/** Tokens read from cache */1657cacheReadTokens?: number;1658}16591660/**1661* @category Common Types1662*/1663export interface ErrorInfo {1664/** Error type identifier */1665errorType: string;1666/** Human-readable error message */1667message: string;1668/** Stack trace */1669stack?: string;1670}16711672/**1673* A point-in-time snapshot of a subscribed resource's state, returned by1674* `initialize`, `reconnect`, and `subscribe`.1675*1676* @category Common Types1677*/1678export interface Snapshot {1679/** The subscribed resource URI (e.g. `agenthost:/root` or `copilot:/<uuid>`) */1680resource: URI;1681/** The current state of the resource */1682state: RootState | SessionState | TerminalState;1683/** The `serverSeq` at which this snapshot was taken. Subsequent actions will have `serverSeq > fromSeq`. */1684fromSeq: number;1685}168616871688