diff --git a/package-lock.json b/package-lock.json index e9275a8f..0c77cbd6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "@types/ws": "^8.5.13", "@typescript-eslint/eslint-plugin": "^8.65.0", "@typescript-eslint/parser": "^8.65.0", + "esbuild": "^0.28.2", "eslint": "^10.6.0", "eslint-config-prettier": "^10.1.8", "globals": "^17.7.0", diff --git a/package.json b/package.json index 6ce61678..b3d3e1a6 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "!dist/**/*.spec.*", "!dist/examples", "!dist/test-support", + "!dist/v[12]/**/zod.gen.d.ts", "schema/v1/schema.json", "schema/v1/schema.unstable.json", "schema/v2/schema.json", @@ -29,6 +30,7 @@ "LICENSE" ], "type": "module", + "sideEffects": false, "main": "dist/v1/stable/acp.js", "types": "dist/v1/stable/acp.d.ts", "exports": { @@ -100,7 +102,7 @@ "snapshot:nes": "node scripts/snapshot-nes.js", "typecheck": "tsc --noEmit", "build": "npm run clean && tsc --project tsconfig.build.json", - "package:check": "node scripts/check-package.js", + "package:check": "node scripts/check-package.js && node scripts/check-bundles.js", "format": "prettier --write .", "format:check": "prettier --check .", "lint": "eslint", @@ -134,6 +136,7 @@ "@types/ws": "^8.5.13", "@typescript-eslint/eslint-plugin": "^8.65.0", "@typescript-eslint/parser": "^8.65.0", + "esbuild": "^0.28.2", "eslint": "^10.6.0", "eslint-config-prettier": "^10.1.8", "globals": "^17.7.0", diff --git a/scripts/check-bundles.js b/scripts/check-bundles.js new file mode 100644 index 00000000..5dd79564 --- /dev/null +++ b/scripts/check-bundles.js @@ -0,0 +1,60 @@ +import { gzipSync } from "node:zlib"; +import { build } from "esbuild"; + +// Bundle public package imports, including dependencies, as a browser app would. +// Re-export the symbol so minification cannot discard the consumer itself. +for (const [entry, schema] of [ + ["@agentclientprotocol/sdk", "dist/v1/schema"], + ["@agentclientprotocol/sdk/unstable", "dist/v1/unstable/schema"], + ["@agentclientprotocol/sdk/experimental/v2", "dist/v2/schema"], + [ + "@agentclientprotocol/sdk/experimental/v2/unstable", + "dist/v2/unstable/schema", + ], +]) { + for (const name of [ + "PROTOCOL_VERSION", + "methods", + "ndJsonStream", + "client", + ]) { + const { outputFiles, metafile } = await build({ + stdin: { + contents: `export { ${name} } from "${entry}";`, + resolveDir: process.cwd(), + }, + bundle: true, + platform: "browser", + format: "esm", + target: "es2022", + minify: true, + write: false, + metafile: true, + }); + const { contents } = outputFiles[0]; + console.log( + `${entry} ${name}: ${contents.length} bytes minified, ${gzipSync(contents).length} gzip`, + ); + + // Count modules that contributed bytes, not everything esbuild parsed + // while resolving re-exports. A client needs its own validators, not the + // other protocol versions reached via the optional v2 router. + const inputs = Object.values(metafile.outputs)[0].inputs; + const unexpected = Object.entries(inputs) + .filter(([, { bytesInOutput }]) => bytesInOutput > 0) + .map(([path]) => path) + .filter((path) => + name === "client" + ? path.endsWith("/zod.gen.js") && path !== `${schema}/zod.gen.js` + : path.endsWith("/zod.gen.js") || path.includes("node_modules/zod/"), + ); + if (unexpected.length) { + throw new Error(`${entry} ${name} pulled in ${unexpected.join(", ")}`); + } + // Leave room for the helpers to grow without silently bundling the SDK. + const budget = name === "PROTOCOL_VERSION" ? 256 : 8 * 1024; + if (name !== "client" && contents.length > budget) { + throw new Error(`${entry} ${name} exceeded its ${budget}-byte budget`); + } + } +} diff --git a/scripts/check-package.js b/scripts/check-package.js index 211dba97..5ddca274 100644 --- a/scripts/check-package.js +++ b/scripts/check-package.js @@ -56,6 +56,9 @@ const unexpected = [...files].filter( file.startsWith("dist/") && /\.(?:js|js\.map|d\.ts)$/.test(file) && !/(?:^|\/)(?:examples|test-support)\//.test(file) && + // Several MB of inferred validator types, not public in v1 or v2. + // NES does expose its validators; its declarations must stay reachable. + !/^dist\/v[12]\/.*\/zod\.gen\.d\.ts$/.test(file) && !/\.(?:test|spec)\./.test(file) ), ); diff --git a/scripts/generate-bindings.js b/scripts/generate-bindings.js index 9186c79e..21b9f873 100644 --- a/scripts/generate-bindings.js +++ b/scripts/generate-bindings.js @@ -1,5 +1,8 @@ import { posix as path } from "node:path"; +// References between projected modules must stay within the same protocol lane. +export const bindingModules = ["acp", "bindings", "methods"]; + const SPEC_TABLES = new Set([ "agentRequestSpecs", "agentNotificationSpecs", @@ -178,6 +181,8 @@ export function generateBindings(ts, template, definitions, metadata, config) { // Each binding uses its own generated schema, but the same JSON-RPC engine, // streams and deserialization helpers. Never route through the other API. if (!specifier.startsWith(".")) return specifier; + if (bindingModules.some((name) => specifier === `./${name}.js`)) + return specifier; const schemaPrefix = "./unstable/schema/"; const target = specifier.startsWith(schemaPrefix) ? path.join(config.outputDir, specifier.slice(schemaPrefix.length)) diff --git a/scripts/generate.js b/scripts/generate.js index 53e2eb83..c58d0918 100644 --- a/scripts/generate.js +++ b/scripts/generate.js @@ -10,7 +10,7 @@ import * as fs from "fs/promises"; import { dirname } from "path"; import * as prettier from "prettier"; import ts from "typescript"; -import { generateBindings } from "./generate-bindings.js"; +import { bindingModules, generateBindings } from "./generate-bindings.js"; const CURRENT_V1_SCHEMA_RELEASE = "schema-v1.32.0"; const CURRENT_V2_SCHEMA_RELEASE = "schema-v2.0.0-alpha.16"; @@ -104,8 +104,7 @@ const SCHEMA_CONFIGS = [ expectedExtensibleUnions: V1_EXTENSIBLE_UNIONS, openApiVersion: "1.0.0", releaseTag: CURRENT_V1_SCHEMA_RELEASE, - bindingsSource: "./src/v1/acp.ts", - bindingsPath: "./src/v1/stable/acp.ts", + bindingsDir: "./src/v1", }, { name: "v1-unstable", @@ -132,8 +131,7 @@ const SCHEMA_CONFIGS = [ brandUnknownVariants: true, openApiVersion: "2.0.0", releaseTag: CURRENT_V2_SCHEMA_RELEASE, - bindingsSource: "./src/v2/acp.ts", - bindingsPath: "./src/v2/stable/acp.ts", + bindingsDir: "./src/v2", }, { name: "v2-unstable", @@ -195,22 +193,30 @@ async function main() { await generateSchema(config, CHECK_GENERATED); } - for (const config of SCHEMA_CONFIGS.filter((lane) => lane.bindingsPath)) { - const template = await fs.readFile(config.bindingsSource, "utf8"); + for (const config of SCHEMA_CONFIGS.filter((lane) => lane.bindingsDir)) { const schema = JSON.parse(await fs.readFile(config.schemaPath, "utf8")); const metadata = JSON.parse(await fs.readFile(config.metadataPath, "utf8")); - const bindings = await formatStable( - generateBindings(ts, template, schema.$defs, metadata, config), - ); - if (CHECK_GENERATED) { - if ((await fs.readFile(config.bindingsPath, "utf8")) !== bindings) { - throw new Error( - `[${config.name}] ${config.bindingsPath} is stale. Run npm run generate.`, - ); + for (const name of bindingModules) { + const bindingsSource = `${config.bindingsDir}/${name}.ts`; + const bindingsPath = `${config.bindingsDir}/stable/${name}.ts`; + const template = await fs.readFile(bindingsSource, "utf8"); + const bindings = await formatStable( + generateBindings(ts, template, schema.$defs, metadata, { + ...config, + bindingsSource, + bindingsPath, + }), + ); + if (CHECK_GENERATED) { + if ((await fs.readFile(bindingsPath, "utf8")) !== bindings) { + throw new Error( + `[${config.name}] ${bindingsPath} is stale. Run npm run generate.`, + ); + } + } else { + await fs.mkdir(dirname(bindingsPath), { recursive: true }); + await fs.writeFile(bindingsPath, bindings); } - } else { - await fs.mkdir(dirname(config.bindingsPath), { recursive: true }); - await fs.writeFile(config.bindingsPath, bindings); } } } diff --git a/src/v1/acp.ts b/src/v1/acp.ts index 71a02be9..079f05d2 100644 --- a/src/v1/acp.ts +++ b/src/v1/acp.ts @@ -1,16 +1,14 @@ -// V1 binding implementation, specialized against stable schemas by generate.js. -import * as schema from "./unstable/schema/index.js"; -import * as validate from "./unstable/schema/zod.gen.js"; import type { AnyMessage } from "../core/jsonrpc.js"; import { ndJsonStream as createJsonStream } from "../core/stream.js"; +import type { NdJsonStreamOptions } from "../core/stream.js"; + +// Keep module initialization behind re-exports so a consumer pays only for +// the bindings, method table, or guards it actually uses. +export * from "./bindings.js"; +export { methods } from "./methods.js"; export type * from "./unstable/schema/types.gen.js"; -// Runtime narrowing helpers for extensible unions, exposed as companion values -// that merge (declaration merging) with the like-named types — e.g. -// `CreateElicitationResponse.isAccept(response)`. See schema/guards.gen.ts. -// -// Listed explicitly (not `export *`) so each value+type pair merges rather than -// colliding with the `export type *` above. The guards.gen re-export test -// asserts this list stays in sync as new extensible unions are added. +// List guards explicitly so their value/type pairs merge rather than colliding +// with the type exports above. The guards.gen re-export test checks this list. export { CreateElicitationRequest, CreateElicitationResponse, @@ -25,6 +23,7 @@ export { PROTOCOL_METHODS, PROTOCOL_VERSION, } from "./unstable/schema/index.js"; + /** * Stream interface for stable ACP v1 connections. * @@ -62,6 +61,7 @@ export { MessageTooLargeError, } from "../core/stream-limits.js"; export type { NdJsonStreamOptions } from "../core/stream.js"; +export type { ParamsParser } from "../core/app-handlers.js"; export type { AgentConnectOptions, AgentConnectionLifecycle, @@ -78,2573 +78,3 @@ export type { Result, SendRequestOptions, } from "../core/jsonrpc.js"; - -import type { NdJsonStreamOptions } from "../core/stream.js"; -import { - parseParams, - registerAppNotification, - registerAppRequest, -} from "../core/app-handlers.js"; -import type { ParamsParser } from "../core/app-handlers.js"; -export type { ParamsParser } from "../core/app-handlers.js"; -import { connectionContextOf } from "../core/connection-access.js"; -import { - Connection, - Handled, - HandlerRegistration, - RequestError, - RequestResponder, - treatSessionNotFoundAsSuccess, -} from "../core/jsonrpc.js"; -import type { - ConnectionBuilder, - ConnectionContext, - HandleResult, - IncomingMessage, - JsonRpcId, - JsonRpcHandler, - MaybePromise, - SendRequestOptions, -} from "../core/jsonrpc.js"; - -const initializedConnections = new WeakSet(); - -/** - * Rejects requests other than `initialize` with `-32600` until an `initialize` - * request has been answered successfully. `initialize` itself may be sent - * again at any time, as before. - */ -function agentInitializationGate(enabled: () => boolean): JsonRpcHandler { - return { - handleMessage(message, cx) { - if ( - message.kind !== "request" || - !enabled() || - initializedConnections.has(cx) - ) { - return Handled.no(message); - } - if (message.method !== schema.AGENT_METHODS.initialize) { - return message.responder - .respondWithError( - RequestError.invalidRequest( - undefined, - `ACP connection must be initialized before '${message.method}'`, - ), - ) - .then(() => Handled.yes()); - } - - const { responder } = message; - return Handled.no({ - ...message, - responder: new RequestResponder( - responder.id, - (result) => { - // Record success before the response goes out, so the client's - // next request is never rejected. - if ("result" in result) { - initializedConnections.add(cx); - } - return responder.respondWithResult(result); - }, - responder.signal, - ), - }); - }, - describe: () => "agent-initialization", - }; -} - -function emptyObjectResponse(response: T | null | undefined | void): T { - return response ?? ({} as T); -} - -function isStream(value: unknown): value is Stream { - return ( - typeof value === "object" && - value !== null && - "readable" in value && - "writable" in value - ); -} - -function memoryStreamPair(): [Stream, Stream] { - const leftToRight = new TransformStream(); - const rightToLeft = new TransformStream(); - return [ - { - readable: rightToLeft.readable, - writable: leftToRight.writable, - }, - { - readable: leftToRight.readable, - writable: rightToLeft.writable, - }, - ]; -} - -/** - * ACP method-name constants. - * - * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and - * `notify(...)` when you want literal-string type inference without spelling - * protocol strings inline. - */ -export const methods = { - agent: { - initialize: schema.AGENT_METHODS.initialize, - authenticate: schema.AGENT_METHODS.authenticate, - logout: schema.AGENT_METHODS.logout, - auth: { - status: schema.AGENT_METHODS.auth_status, - }, - providers: { - list: schema.AGENT_METHODS.providers_list, - set: schema.AGENT_METHODS.providers_set, - disable: schema.AGENT_METHODS.providers_disable, - }, - session: { - new: schema.AGENT_METHODS.session_new, - load: schema.AGENT_METHODS.session_load, - list: schema.AGENT_METHODS.session_list, - delete: schema.AGENT_METHODS.session_delete, - fork: schema.AGENT_METHODS.session_fork, - archive: schema.AGENT_METHODS.session_archive, - unarchive: schema.AGENT_METHODS.session_unarchive, - status: schema.AGENT_METHODS.session_status, - options: schema.AGENT_METHODS.session_options, - setTitle: schema.AGENT_METHODS.session_set_title, - resume: schema.AGENT_METHODS.session_resume, - close: schema.AGENT_METHODS.session_close, - setMode: schema.AGENT_METHODS.session_set_mode, - setConfigOption: schema.AGENT_METHODS.session_set_config_option, - prompt: schema.AGENT_METHODS.session_prompt, - cancel: schema.AGENT_METHODS.session_cancel, - }, - mcp: { - message: schema.AGENT_METHODS.mcp_message, - }, - }, - client: { - session: { - requestPermission: schema.CLIENT_METHODS.session_request_permission, - update: schema.CLIENT_METHODS.session_update, - }, - fs: { - writeTextFile: schema.CLIENT_METHODS.fs_write_text_file, - readTextFile: schema.CLIENT_METHODS.fs_read_text_file, - }, - terminal: { - create: schema.CLIENT_METHODS.terminal_create, - output: schema.CLIENT_METHODS.terminal_output, - release: schema.CLIENT_METHODS.terminal_release, - waitForExit: schema.CLIENT_METHODS.terminal_wait_for_exit, - kill: schema.CLIENT_METHODS.terminal_kill, - }, - mcp: { - message: schema.CLIENT_METHODS.mcp_message, - }, - elicitation: { - create: schema.CLIENT_METHODS.elicitation_create, - complete: schema.CLIENT_METHODS.elicitation_complete, - }, - auth: { - statusUpdate: schema.CLIENT_METHODS.auth_status_update, - }, - }, - protocol: { - cancelRequest: schema.PROTOCOL_METHODS.cancel_request, - }, -} as const; - -const startActiveSession = Symbol("startActiveSession"); - -/** - * Active ACP connection returned by `AgentApp.connect(...)` and - * `ClientApp.connect(...)`. - * - * Use this handle when you need a connection to stay open independently of a - * single `connectWith(...)` operation. - */ -export interface AcpConnection { - /** - * AbortSignal that aborts when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after the signal aborts. - */ - readonly signal: AbortSignal; - - /** - * Promise that resolves when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after this resolves. - */ - readonly closed: Promise; - - /** - * Closes the connection and rejects pending requests. Messages received but - * not yet dispatched are dropped. Does nothing once the connection is closed. - */ - close(error?: unknown): void; -} - -/** - * Agent-side connection returned by `AgentApp.connect(...)`. - * - * Use `client` to call client-side ACP methods for the lifetime of the - * connection. - */ -export interface AgentConnection extends AcpConnection { - /** - * Context for calling client-side ACP methods. - */ - readonly client: AgentContext; -} - -/** - * Client-side connection returned by `ClientApp.connect(...)`. - * - * Use `agent` to call agent-side ACP methods and session helpers for the - * lifetime of the connection. - */ -export interface ClientConnection extends AcpConnection { - /** - * Context for calling agent-side ACP methods. - */ - readonly agent: ClientContext; -} - -class AcpContext { - /** @internal */ - constructor( - private readonly cx: ConnectionContext, - private readonly currentRequestId?: JsonRpcId, - ) {} - - /** - * JSON-RPC id of the request currently being handled. - * - * This is `undefined` for notification handlers and for contexts created - * outside an inbound request, such as `connect(...)` and `connectWith(...)`. - */ - get requestId(): JsonRpcId | undefined { - return this.currentRequestId; - } - - /** @internal */ - protected get connectionContext(): ConnectionContext { - return this.cx; - } - - /** @hidden SDK helpers use this to identify the connection. */ - [connectionContextOf](): ConnectionContext { - return this.cx; - } - - /** @internal */ - protected sendRequest( - method: string, - params?: Req, - mapResponse?: (response: Resp) => Output, - options?: SendRequestOptions, - ): Promise { - return this.cx.sendRequest(method, params, mapResponse, options); - } - - /** @internal */ - protected sendNotification(method: string, params?: N): Promise { - return this.cx.sendNotification(method, params); - } - - /** @internal */ - protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { - return this.cx.addDynamicHandler(handler); - } -} - -/** - * Context passed to agent-side handlers. - * - * Agents use this context to call client-side ACP methods while handling - * requests such as `session/prompt`. - */ -export class AgentContext extends AcpContext { - private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { - super(cx, requestId); - } - - /** @internal */ - static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { - return new AgentContext(cx, requestId); - } - - /** - * Executes a command in a new client terminal. - * - * Returns a handle for reading output, waiting for exit, killing the command, - * and releasing the terminal. Check the client's terminal capability first. - * Use `await using` or call `release()` when finished. - */ - async createTerminal( - params: schema.CreateTerminalRequest, - options?: SendRequestOptions, - ): Promise { - const response = await this.request( - schema.CLIENT_METHODS.terminal_create, - params, - options, - ); - return TerminalHandle.create( - response.terminalId, - params.sessionId, - this.connectionContext, - ); - } - - /** - * Sends a request to the client by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - */ - request( - method: Method, - params: ClientRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - const spec = clientRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - return this.sendRequest(method, params, spec?.mapResponse, options); - } - - /** - * Sends a notification to the client by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: ClientNotificationParamsByMethod[Method], - ): Promise; - notify(method: string, params?: Params): Promise; - notify(method: string, params?: unknown): Promise { - return this.sendNotification(method, params); - } -} - -/** - * Context used by clients to call agent-side ACP methods. - * - * `connectWith` passes a `ClientContext` to the callback. Client handlers also - * receive one as `ctx.agent` when they need to call back into the agent. - */ -export class ClientContext extends AcpContext { - private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { - super(cx, requestId); - } - - /** @internal */ - static create(cx: ConnectionContext, requestId?: JsonRpcId): ClientContext { - return new ClientContext(cx, requestId); - } - - /** @internal */ - [startActiveSession]( - params: schema.NewSessionRequest, - options?: SendRequestOptions, - ): Promise { - return this.sendRequest< - schema.NewSessionRequest, - schema.NewSessionResponse, - ActiveSession - >( - schema.AGENT_METHODS.session_new, - params, - (response) => this.attachSession(response), - options, - ); - } - - /** - * Creates a builder for starting and observing an ACP session. - * - * Pass a string for the common case where only `cwd` is needed, or pass a - * full `NewSessionRequest` when you need MCP servers, `_meta`, or additional - * session fields. - */ - buildSession(cwd: string): SessionBuilder; - buildSession(request: schema.NewSessionRequest): SessionBuilder; - buildSession( - cwdOrRequest: string | schema.NewSessionRequest, - ): SessionBuilder { - if (typeof cwdOrRequest === "string") { - return SessionBuilder.create(this, { - cwd: cwdOrRequest, - mcpServers: [], - }); - } - - return SessionBuilder.create(this, cwdOrRequest); - } - - /** - * Builds active-session helpers around a `session/new` response. - */ - private attachSession(response: schema.NewSessionResponse): ActiveSession { - const updates = new AsyncQueue(); - const closeSignal = this.connectionContext.signal; - const failUpdatesOnClose = () => { - updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); - }; - if (closeSignal.aborted) { - failUpdatesOnClose(); - } else { - closeSignal.addEventListener("abort", failUpdatesOnClose); - } - const sessionRegistration = sessionUpdateRouter( - this.connectionContext, - ).attach(response, updates); - const closeRegistration = new HandlerRegistration(() => { - closeSignal.removeEventListener("abort", failUpdatesOnClose); - }); - - return ActiveSession.create(this, response, updates, [ - sessionRegistration, - closeRegistration, - ]); - } - - /** - * Sends a request to the agent by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - * - * Closing or deleting a session is idempotent: a `-32002` (Resource not - * found) response to `session/close` or `session/delete` resolves with an - * empty result instead of rejecting. - */ - request( - method: Method, - params: AgentRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - const spec = agentRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - return treatSessionNotFoundAsSuccess( - method, - this.sendRequest(method, params, spec?.mapResponse, options), - () => (spec?.mapResponse ? spec.mapResponse({}) : {}), - ); - } - - /** - * Sends a notification to the agent by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: AgentNotificationParamsByMethod[Method], - ): Promise; - notify(method: string, params?: Params): Promise; - notify(method: string, params?: unknown): Promise { - return this.sendNotification(method, params); - } -} - -class AcpConnectionHandle implements AcpConnection { - constructor(private readonly connection: Connection) {} - - get signal(): AbortSignal { - return this.connection.signal; - } - - get closed(): Promise { - return this.connection.closed; - } - - close(error?: unknown): void { - this.connection.close(error); - } -} - -class AgentConnectionHandle - extends AcpConnectionHandle - implements AgentConnection -{ - readonly client: AgentContext; - private didStartConnectHandlers = false; - - constructor( - connection: Connection, - private readonly connectHandlers: readonly AgentConnectHandler[] = [], - ) { - super(connection); - this.client = AgentContext.create(connection.getContext()); - } - - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} - -class ClientConnectionHandle - extends AcpConnectionHandle - implements ClientConnection -{ - readonly agent: ClientContext; - private didStartConnectHandlers = false; - - constructor( - connection: Connection, - private readonly connectHandlers: readonly ClientConnectHandler[] = [], - ) { - super(connection); - this.agent = ClientContext.create(connection.getContext()); - } - - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} - -function agentConnection( - connection: Connection, - connectHandlers: readonly AgentConnectHandler[] = [], -): AgentConnection { - return new AgentConnectionHandle(connection, connectHandlers); -} - -function clientConnection( - connection: Connection, - connectHandlers: readonly ClientConnectHandler[] = [], -): ClientConnection { - return new ClientConnectionHandle(connection, connectHandlers); -} - -type AsyncQueueEntry = - | { - kind: "value"; - value: T; - } - | { - kind: "error"; - error: unknown; - }; - -class AsyncQueue { - private values: Array> = []; - private waiters: Array<{ - resolve: (value: T) => void; - reject: (error: unknown) => void; - }> = []; - private failed = false; - private failure: unknown; - - enqueue(value: T): void { - if (this.failed) { - return; - } - - const waiter = this.waiters.shift(); - if (waiter) { - waiter.resolve(value); - } else { - this.values.push({ kind: "value", value }); - } - } - - reject(error: unknown): void { - if (this.failed) { - return; - } - - if (this.waiters.length > 0) { - for (const waiter of this.waiters.splice(0)) { - waiter.reject(error); - } - return; - } - - this.values.push({ kind: "error", error }); - } - - clearErrors(): void { - this.values = this.values.filter((entry) => entry.kind === "value"); - } - - fail(error: unknown): void { - if (this.failed) { - return; - } - - this.failed = true; - this.failure = error; - for (const waiter of this.waiters.splice(0)) { - waiter.reject(error); - } - } - - next(): Promise { - if (this.values.length > 0) { - const entry = this.values.shift() as AsyncQueueEntry; - if (entry.kind === "error") { - return Promise.reject(entry.error); - } - - return Promise.resolve(entry.value); - } - - if (this.failed) { - return Promise.reject(this.failure); - } - - return new Promise((resolve, reject) => { - this.waiters.push({ resolve, reject }); - }); - } -} - -function cloneNewSessionRequest( - request: schema.NewSessionRequest, -): schema.NewSessionRequest { - return { - ...request, - additionalDirectories: request.additionalDirectories - ? [...request.additionalDirectories] - : undefined, - mcpServers: [...request.mcpServers], - }; -} - -/** - * Message produced by an `ActiveSession`. - * - * `session_update` messages expose the typed `session/update` notification and - * `stop` messages report the final `session/prompt` response. A prompt turn is - * complete once a `stop` message is returned. - */ -export type ActiveSessionMessage = - | { - /** - * Indicates that this message came from a `session/update` notification. - */ - kind: "session_update"; - /** - * Full notification sent by the agent. - */ - notification: schema.SessionNotification; - /** - * Convenience alias for `notification.update`. - */ - update: schema.SessionUpdate; - } - | { - /** - * Indicates that the prompt turn has completed. - */ - kind: "stop"; - /** - * Final response from `session/prompt`. - */ - response: schema.PromptResponse; - /** - * Convenience alias for `response.stopReason`. - */ - stopReason: schema.StopReason; - }; - -/** - * Builder for creating an `ActiveSession`. - * - * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or - * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session - * needs MCP servers, `_meta`, or additional request fields. All paths in ACP - * payloads should be absolute. - */ -export class SessionBuilder { - private request: schema.NewSessionRequest; - - private constructor( - private cx: ClientContext, - request: schema.NewSessionRequest, - ) { - this.request = cloneNewSessionRequest(request); - } - - /** @internal */ - static create( - cx: ClientContext, - request: schema.NewSessionRequest, - ): SessionBuilder { - return new SessionBuilder(cx, request); - } - - /** - * Returns the `session/new` request that will be sent. - * - * The returned object is a defensive copy, so mutating it does not change the - * builder. - */ - toRequest(): schema.NewSessionRequest { - return cloneNewSessionRequest(this.request); - } - - /** - * Replaces the additional workspace roots for this session. - * - * `additionalDirectories` expand the session's file-system scope without - * changing `cwd`. Each path should be absolute. - */ - withAdditionalDirectories(additionalDirectories: string[]): this { - this.request = { - ...this.request, - additionalDirectories: [...additionalDirectories], - }; - return this; - } - - /** - * Adds one MCP server to the `session/new` request. - */ - withMcpServer(mcpServer: schema.McpServer): this { - this.request = { - ...this.request, - mcpServers: [...this.request.mcpServers, mcpServer], - }; - return this; - } - - /** - * Starts the session and returns an `ActiveSession` for prompting and reading - * updates. - * - * Call `dispose()` on the returned session when you no longer need update - * routing, or use `withSession(...)` to scope disposal automatically. - */ - async start(options?: SendRequestOptions): Promise { - return this.cx[startActiveSession](this.toRequest(), options); - } - - /** - * Starts the session, runs `op`, and disposes the active-session update - * routing when `op` finishes or throws. - */ - async withSession( - op: (session: ActiveSession) => MaybePromise, - ): Promise { - const session = await this.start(); - try { - return await op(session); - } finally { - session.dispose(); - } - } -} - -/** - * Convenience wrapper for an active ACP session. - * - * An active session routes `session/update` notifications for one session ID - * into an async queue. Use `prompt(...)` to send user content, then read updates - * with `nextUpdate()` until a `stop` message is returned. - */ -export class ActiveSession { - private constructor( - private cx: ClientContext, - private sessionResponse: schema.NewSessionResponse, - private updates: { - enqueue(value: ActiveSessionMessage): void; - reject(error: unknown): void; - clearErrors(): void; - fail(error: unknown): void; - next(): Promise; - }, - private registrations: HandlerRegistration[], - ) {} - - /** @internal */ - static create( - cx: ClientContext, - sessionResponse: schema.NewSessionResponse, - updates: { - enqueue(value: ActiveSessionMessage): void; - reject(error: unknown): void; - clearErrors(): void; - fail(error: unknown): void; - next(): Promise; - }, - registrations: HandlerRegistration[], - ): ActiveSession { - return new ActiveSession(cx, sessionResponse, updates, registrations); - } - - /** - * Session ID returned by `session/new`. - */ - get sessionId(): schema.SessionId { - return this.sessionResponse.sessionId; - } - - /** - * Mode state returned when the session was created, if the agent provided it. - */ - get modes(): schema.SessionModeState | null | undefined { - return this.sessionResponse.modes; - } - - /** - * Metadata returned when the session was created. - */ - get meta(): { [key: string]: unknown } | null | undefined { - return this.sessionResponse._meta; - } - - /** - * Full response returned by `session/new`. - */ - get newSessionResponse(): schema.NewSessionResponse { - return this.sessionResponse; - } - - /** - * Sends a prompt to this session. - * - * Strings are converted to one text content block. A single content block is - * wrapped in an array. The returned promise resolves with the final - * `PromptResponse`, and the same completion is also queued as a `stop` - * message for `nextUpdate()`. - */ - prompt( - prompt: string | schema.ContentBlock | Array, - options?: SendRequestOptions, - ): Promise { - this.updates.clearErrors(); - const response = this.cx.request( - schema.AGENT_METHODS.session_prompt, - { - sessionId: this.sessionId, - prompt: this.promptBlocks(prompt), - }, - options, - ); - void response.then( - (value) => { - this.updates.enqueue({ - kind: "stop", - response: value, - stopReason: value.stopReason, - }); - }, - (error) => { - this.updates.reject(error); - }, - ); - return response; - } - - /** - * Reads the next update or stop message for this session. - */ - nextUpdate(): Promise { - return this.updates.next(); - } - - /** - * Reads text chunks until the current prompt turn stops. - * - * Only `agent_message_chunk` updates with text content are appended. Other - * update types are ignored by this helper; use `nextUpdate()` when you need - * tool calls, plans, or the final `PromptResponse`. - */ - async readText(): Promise { - let output = ""; - for (;;) { - const message = await this.nextUpdate(); - if (message.kind === "stop") { - return output; - } - - const { update } = message; - if ( - update.sessionUpdate === "agent_message_chunk" && - update.content.type === "text" - ) { - output += update.content.text; - } - } - } - - /** - * Stops routing updates to this active-session helper. - * - * This does not close the ACP session on the agent. Use `ClientContext` - * session lifecycle methods when the protocol session itself should be closed - * or deleted. - */ - dispose(): void { - for (const registration of this.registrations.splice(0)) { - registration.dispose(); - } - this.updates.fail(new Error("Active session disposed")); - } - - /** - * Supports explicit resource management with `using`. - */ - [Symbol.dispose](): void { - this.dispose(); - } - - private promptBlocks( - prompt: string | schema.ContentBlock | Array, - ): Array { - if (typeof prompt === "string") { - return [{ type: "text", text: prompt }]; - } - - if (Array.isArray(prompt)) { - return prompt; - } - - return [prompt]; - } -} - -/** - * Options used when creating an ACP app. - */ -export type AppOptions = { - /** - * Human-readable name used in JSON-RPC handler descriptions and diagnostics. - */ - name?: string; -}; - -/** - * Common context passed to agent-side handlers. - */ -export type AgentHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed client context for calling client-side ACP methods. - */ - client: AgentContext; -}; - -/** - * Context passed to agent-side request handlers. - */ -export type AgentRequestContext = AgentHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; - -/** - * Context passed to agent-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type AgentNotificationContext = AgentHandlerContext; - -/** - * Common context passed to client-side handlers. - */ -export type ClientHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed agent context for calling agent-side ACP methods. - */ - agent: ClientContext; -}; - -/** - * Context passed to client-side request handlers. - */ -export type ClientRequestContext = ClientHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; - -/** - * Context passed to client-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type ClientNotificationContext = ClientHandlerContext; - -/** - * Request handler registered on an `AgentApp`. - */ -export type AgentRequestHandler = ( - context: AgentRequestContext, -) => MaybePromise; - -/** - * Notification handler registered on an `AgentApp`. - */ -export type AgentNotificationHandler = ( - context: AgentNotificationContext, -) => MaybePromise; - -/** - * Request handler registered on a `ClientApp`. - */ -export type ClientRequestHandler = ( - context: ClientRequestContext, -) => MaybePromise; - -/** - * Notification handler registered on a `ClientApp`. - */ -export type ClientNotificationHandler = ( - context: ClientNotificationContext, -) => MaybePromise; - -/** - * Handler called when an `AgentApp` opens a connection. - */ -export type AgentConnectHandler = ( - connection: AgentConnection, -) => MaybePromise; - -/** - * Handler called when a `ClientApp` opens a connection. - */ -export type ClientConnectHandler = ( - connection: ClientConnection, -) => MaybePromise; - -type AcpRequestSpec = { - method: string; - params?: ParamsParser; - mapResponse?: (response: Response) => WireResponse; -}; - -type AcpNotificationSpec = { - method: string; - params?: ParamsParser; -}; - -function requestSpec( - method: string, - params: ParamsParser, - mapResponse?: (response: Response) => WireResponse, -): AcpRequestSpec { - return { - method, - // Match Rust's empty-payload handling without bypassing required fields. - params: (value) => parseParams(params, value ?? {}), - mapResponse, - }; -} - -function notificationSpec( - method: string, - params: ParamsParser, -): AcpNotificationSpec { - return { method, params }; -} - -function specsByMethod>( - specs: T, -): Record { - const byMethod: Record = {}; - for (const spec of Object.values(specs) as Array) { - byMethod[spec.method] = spec; - } - return byMethod; -} - -const agentRequestSpecs = { - initialize: requestSpec( - schema.AGENT_METHODS.initialize, - validate.zInitializeRequest, - ), - newSession: requestSpec( - schema.AGENT_METHODS.session_new, - validate.zNewSessionRequest, - ), - loadSession: requestSpec< - schema.LoadSessionRequest, - schema.LoadSessionResponse | void, - schema.LoadSessionResponse - >( - schema.AGENT_METHODS.session_load, - validate.zLoadSessionRequest, - emptyObjectResponse, - ), - unstable_forkSession: requestSpec< - schema.ForkSessionRequest, - schema.ForkSessionResponse - >(schema.AGENT_METHODS.session_fork, validate.zForkSessionRequest), - listSessions: requestSpec< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >(schema.AGENT_METHODS.session_list, validate.zListSessionsRequest), - deleteSession: requestSpec< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void, - schema.DeleteSessionResponse - >( - schema.AGENT_METHODS.session_delete, - validate.zDeleteSessionRequest, - emptyObjectResponse, - ), - unstable_archiveSession: requestSpec< - schema.ArchiveSessionRequest, - schema.ArchiveSessionResponse | void, - schema.ArchiveSessionResponse - >( - schema.AGENT_METHODS.session_archive, - validate.zArchiveSessionRequest, - emptyObjectResponse, - ), - unstable_unarchiveSession: requestSpec< - schema.UnarchiveSessionRequest, - schema.UnarchiveSessionResponse | void, - schema.UnarchiveSessionResponse - >( - schema.AGENT_METHODS.session_unarchive, - validate.zUnarchiveSessionRequest, - emptyObjectResponse, - ), - unstable_sessionStatus: requestSpec< - schema.SessionStatusRequest, - schema.SessionStatusResponse - >(schema.AGENT_METHODS.session_status, validate.zSessionStatusRequest), - unstable_sessionOptions: requestSpec< - schema.SessionOptionsRequest, - schema.SessionOptionsResponse - >(schema.AGENT_METHODS.session_options, validate.zSessionOptionsRequest), - unstable_setSessionTitle: requestSpec< - schema.SetSessionTitleRequest, - schema.SetSessionTitleResponse - >(schema.AGENT_METHODS.session_set_title, validate.zSetSessionTitleRequest), - resumeSession: requestSpec< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >(schema.AGENT_METHODS.session_resume, validate.zResumeSessionRequest), - closeSession: requestSpec< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void, - schema.CloseSessionResponse - >( - schema.AGENT_METHODS.session_close, - validate.zCloseSessionRequest, - emptyObjectResponse, - ), - setSessionMode: requestSpec< - schema.SetSessionModeRequest, - schema.SetSessionModeResponse | void, - schema.SetSessionModeResponse - >( - schema.AGENT_METHODS.session_set_mode, - validate.zSetSessionModeRequest, - emptyObjectResponse, - ), - setSessionConfigOption: requestSpec< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >( - schema.AGENT_METHODS.session_set_config_option, - validate.zSetSessionConfigOptionRequest, - ), - authenticate: requestSpec< - schema.AuthenticateRequest, - schema.AuthenticateResponse | void, - schema.AuthenticateResponse - >( - schema.AGENT_METHODS.authenticate, - validate.zAuthenticateRequest, - emptyObjectResponse, - ), - unstable_listProviders: requestSpec< - schema.ListProvidersRequest, - schema.ListProvidersResponse - >(schema.AGENT_METHODS.providers_list, validate.zListProvidersRequest), - unstable_setProvider: requestSpec< - schema.SetProviderRequest, - schema.SetProviderResponse | void, - schema.SetProviderResponse - >( - schema.AGENT_METHODS.providers_set, - validate.zSetProviderRequest, - emptyObjectResponse, - ), - unstable_disableProvider: requestSpec< - schema.DisableProviderRequest, - schema.DisableProviderResponse | void, - schema.DisableProviderResponse - >( - schema.AGENT_METHODS.providers_disable, - validate.zDisableProviderRequest, - emptyObjectResponse, - ), - logout: requestSpec< - schema.LogoutRequest, - schema.LogoutResponse | void, - schema.LogoutResponse - >(schema.AGENT_METHODS.logout, validate.zLogoutRequest, emptyObjectResponse), - unstable_authStatus: requestSpec< - schema.AuthStatusRequest, - schema.AuthStatusResponse - >(schema.AGENT_METHODS.auth_status, validate.zAuthStatusRequest), - prompt: requestSpec( - schema.AGENT_METHODS.session_prompt, - validate.zPromptRequest, - ), -}; - -const agentNotificationSpecs = { - cancel: notificationSpec( - schema.AGENT_METHODS.session_cancel, - validate.zCancelNotification, - ), - unstable_messageMcp: notificationSpec( - schema.AGENT_METHODS.mcp_message, - validate.zMessageMcpNotification, - ), -}; - -const clientRequestSpecs = { - requestPermission: requestSpec< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >( - schema.CLIENT_METHODS.session_request_permission, - validate.zRequestPermissionRequest, - ), - writeTextFile: requestSpec< - schema.WriteTextFileRequest, - schema.WriteTextFileResponse | void, - schema.WriteTextFileResponse - >( - schema.CLIENT_METHODS.fs_write_text_file, - validate.zWriteTextFileRequest, - emptyObjectResponse, - ), - readTextFile: requestSpec< - schema.ReadTextFileRequest, - schema.ReadTextFileResponse - >(schema.CLIENT_METHODS.fs_read_text_file, validate.zReadTextFileRequest), - createTerminal: requestSpec< - schema.CreateTerminalRequest, - schema.CreateTerminalResponse - >(schema.CLIENT_METHODS.terminal_create, validate.zCreateTerminalRequest), - terminalOutput: requestSpec< - schema.TerminalOutputRequest, - schema.TerminalOutputResponse - >(schema.CLIENT_METHODS.terminal_output, validate.zTerminalOutputRequest), - releaseTerminal: requestSpec< - schema.ReleaseTerminalRequest, - schema.ReleaseTerminalResponse | void, - schema.ReleaseTerminalResponse - >( - schema.CLIENT_METHODS.terminal_release, - validate.zReleaseTerminalRequest, - emptyObjectResponse, - ), - waitForTerminalExit: requestSpec< - schema.WaitForTerminalExitRequest, - schema.WaitForTerminalExitResponse - >( - schema.CLIENT_METHODS.terminal_wait_for_exit, - validate.zWaitForTerminalExitRequest, - ), - killTerminal: requestSpec< - schema.KillTerminalRequest, - schema.KillTerminalResponse | void, - schema.KillTerminalResponse - >( - schema.CLIENT_METHODS.terminal_kill, - validate.zKillTerminalRequest, - emptyObjectResponse, - ), - createElicitation: requestSpec< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >( - schema.CLIENT_METHODS.elicitation_create, - validate.zCreateElicitationRequest, - ), - unstable_messageMcp: requestSpec< - schema.MessageMcpRequest, - schema.MessageMcpResponse - >(schema.CLIENT_METHODS.mcp_message, validate.zMessageMcpRequest), -}; - -const clientNotificationSpecs = { - sessionUpdate: notificationSpec( - schema.CLIENT_METHODS.session_update, - validate.zSessionNotification, - ), - completeElicitation: notificationSpec( - schema.CLIENT_METHODS.elicitation_complete, - validate.zCompleteElicitationNotification, - ), - unstable_authStatusUpdate: - notificationSpec( - schema.CLIENT_METHODS.auth_status_update, - validate.zAuthStatusUpdateNotification, - ), -}; - -const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); -const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); -const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); -const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); - -/** - * Agent request handlers keyed by ACP protocol method name. - */ -export type AgentRequestHandlersByMethod = { - /** - * Handles `initialize`. - * - * Registering this handler makes the app reject other requests with - * `-32600` until an `initialize` request has been answered successfully. - */ - [schema.AGENT_METHODS.initialize]: AgentRequestHandler< - schema.InitializeRequest, - schema.InitializeResponse - >; - [schema.AGENT_METHODS.session_new]: AgentRequestHandler< - schema.NewSessionRequest, - schema.NewSessionResponse - >; - [schema.AGENT_METHODS.session_load]: AgentRequestHandler< - schema.LoadSessionRequest, - schema.LoadSessionResponse | void - >; - [schema.AGENT_METHODS.session_fork]: AgentRequestHandler< - schema.ForkSessionRequest, - schema.ForkSessionResponse - >; - [schema.AGENT_METHODS.session_list]: AgentRequestHandler< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >; - [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void - >; - /** - * Handles `session/archive`. Archiving an active or loaded session first - * cancels its work and frees its resources as `session/close` would. - * Archiving an archived session succeeds. An unknown session gets `-32002`. - */ - [schema.AGENT_METHODS.session_archive]: AgentRequestHandler< - schema.ArchiveSessionRequest, - schema.ArchiveSessionResponse | void - >; - /** - * Handles `session/unarchive`. It does not load or resume the session. - * Unarchiving a session that is not archived succeeds. An unknown session - * gets `-32002`. - */ - [schema.AGENT_METHODS.session_unarchive]: AgentRequestHandler< - schema.UnarchiveSessionRequest, - schema.UnarchiveSessionResponse | void - >; - /** - * Handles `session/status`. It must not load, resume, create, close, or - * change the session. An unknown session gets `-32002`. - */ - [schema.AGENT_METHODS.session_status]: AgentRequestHandler< - schema.SessionStatusRequest, - schema.SessionStatusResponse - >; - /** - * Handles `session/options`. Respond with the modes and config options a - * session would start with. With `sessionId`, respond with what - * `session/load` or `session/resume` would return for that session. - * Clients send `sessionId` only when the agent supports `session/load`, - * `session/resume`, or `session/fork`. Before a fork, it is the source - * session's ID. It must not create, load, resume, or change a session, - * send `session/update` notifications, or add an entry to `session/list`. - * The agent may start its runtime to resolve the options, and these rules - * still hold for it. An unknown session gets `-32002`. - */ - [schema.AGENT_METHODS.session_options]: AgentRequestHandler< - schema.SessionOptionsRequest, - schema.SessionOptionsResponse - >; - /** - * Handles `session/set_title`. Respond with the stored title after storing - * it. A title that is invalid after normalization gets `-32602`, and an - * unknown session gets `-32002`. - */ - [schema.AGENT_METHODS.session_set_title]: AgentRequestHandler< - schema.SetSessionTitleRequest, - schema.SetSessionTitleResponse - >; - [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >; - [schema.AGENT_METHODS.session_close]: AgentRequestHandler< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void - >; - [schema.AGENT_METHODS.session_set_mode]: AgentRequestHandler< - schema.SetSessionModeRequest, - schema.SetSessionModeResponse | void - >; - [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >; - [schema.AGENT_METHODS.authenticate]: AgentRequestHandler< - schema.AuthenticateRequest, - schema.AuthenticateResponse | void - >; - [schema.AGENT_METHODS.providers_list]: AgentRequestHandler< - schema.ListProvidersRequest, - schema.ListProvidersResponse - >; - [schema.AGENT_METHODS.providers_set]: AgentRequestHandler< - schema.SetProviderRequest, - schema.SetProviderResponse | void - >; - [schema.AGENT_METHODS.providers_disable]: AgentRequestHandler< - schema.DisableProviderRequest, - schema.DisableProviderResponse | void - >; - [schema.AGENT_METHODS.logout]: AgentRequestHandler< - schema.LogoutRequest, - schema.LogoutResponse | void - >; - /** - * Handles `auth/status`. It must not change any agent state, and it must - * not fail with `auth_required` (`-32000`). - */ - [schema.AGENT_METHODS.auth_status]: AgentRequestHandler< - schema.AuthStatusRequest, - schema.AuthStatusResponse - >; - [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< - schema.PromptRequest, - schema.PromptResponse - >; -}; - -/** - * ACP request methods that can be handled by an `AgentApp`. - */ -export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; - -/** - * Agent notification handlers keyed by ACP protocol method name. - */ -export type AgentNotificationHandlersByMethod = { - [schema.AGENT_METHODS - .session_cancel]: AgentNotificationHandler; - [schema.AGENT_METHODS - .mcp_message]: AgentNotificationHandler; -}; - -/** - * ACP notification methods that can be handled by an `AgentApp`. - */ -export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & - string; - -/** - * Client request handlers keyed by ACP protocol method name. - */ -export type ClientRequestHandlersByMethod = { - [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >; - [schema.CLIENT_METHODS.fs_write_text_file]: ClientRequestHandler< - schema.WriteTextFileRequest, - schema.WriteTextFileResponse | void - >; - [schema.CLIENT_METHODS.fs_read_text_file]: ClientRequestHandler< - schema.ReadTextFileRequest, - schema.ReadTextFileResponse - >; - [schema.CLIENT_METHODS.terminal_create]: ClientRequestHandler< - schema.CreateTerminalRequest, - schema.CreateTerminalResponse - >; - [schema.CLIENT_METHODS.terminal_output]: ClientRequestHandler< - schema.TerminalOutputRequest, - schema.TerminalOutputResponse - >; - [schema.CLIENT_METHODS.terminal_release]: ClientRequestHandler< - schema.ReleaseTerminalRequest, - schema.ReleaseTerminalResponse | void - >; - [schema.CLIENT_METHODS.terminal_wait_for_exit]: ClientRequestHandler< - schema.WaitForTerminalExitRequest, - schema.WaitForTerminalExitResponse - >; - [schema.CLIENT_METHODS.terminal_kill]: ClientRequestHandler< - schema.KillTerminalRequest, - schema.KillTerminalResponse | void - >; - [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >; - [schema.CLIENT_METHODS.mcp_message]: ClientRequestHandler< - schema.MessageMcpRequest, - schema.MessageMcpResponse - >; -}; - -/** - * ACP request methods that can be handled by a `ClientApp`. - */ -export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; - -/** - * Client notification handlers keyed by ACP protocol method name. - */ -export type ClientNotificationHandlersByMethod = { - [schema.CLIENT_METHODS - .session_update]: ClientNotificationHandler; - [schema.CLIENT_METHODS - .elicitation_complete]: ClientNotificationHandler; - [schema.CLIENT_METHODS - .auth_status_update]: ClientNotificationHandler; -}; - -/** - * ACP notification methods that can be handled by a `ClientApp`. - */ -export type ClientNotificationMethod = - keyof ClientNotificationHandlersByMethod & string; - -/** - * Agent request params keyed by ACP protocol method name. - */ -export type AgentRequestParamsByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -/** - * Agent request responses keyed by ACP protocol method name. - */ -export type AgentRequestResponsesByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; - -/** - * Agent notification params keyed by ACP protocol method name. - */ -export type AgentNotificationParamsByMethod = { - [ - Method in AgentNotificationMethod - ]: AgentNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -/** - * Client request params keyed by ACP protocol method name. - */ -export type ClientRequestParamsByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -/** - * Client request responses keyed by ACP protocol method name. - */ -export type ClientRequestResponsesByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; - -/** - * Client notification params keyed by ACP protocol method name. - */ -export type ClientNotificationParamsByMethod = { - [ - Method in ClientNotificationMethod - ]: ClientNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -function agentRequestContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): AgentRequestContext { - return { - method, - params, - requestId, - signal, - client, - }; -} - -function agentNotificationContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - method: string, -): AgentNotificationContext { - return { - method, - params, - signal, - client, - }; -} - -function clientRequestContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): ClientRequestContext { - return { - method, - params, - requestId, - signal, - agent, - }; -} - -function clientNotificationContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - method: string, -): ClientNotificationContext { - return { - method, - params, - signal, - agent, - }; -} - -type ActiveSessionUpdateQueue = { - enqueue(value: ActiveSessionMessage): void; -}; - -class SessionUpdateRouter { - private readonly activeSessions = new Map< - string, - Set - >(); - - handleMessage(message: IncomingMessage): HandleResult { - if ( - message.kind !== "notification" || - message.method !== schema.CLIENT_METHODS.session_update - ) { - return Handled.no(message); - } - - const notification = validate.zSessionNotification.parse(message.params); - const update = { - kind: "session_update", - notification, - update: notification.update, - } satisfies ActiveSessionMessage; - const activeSessions = this.activeSessions.get(notification.sessionId); - if (activeSessions && activeSessions.size > 0) { - for (const session of activeSessions) { - session.enqueue(update); - } - } - - return Handled.no(message); - } - - attach( - response: schema.NewSessionResponse, - updates: ActiveSessionUpdateQueue, - ): HandlerRegistration { - const sessions = - this.activeSessions.get(response.sessionId) ?? - new Set(); - sessions.add(updates); - this.activeSessions.set(response.sessionId, sessions); - - return new HandlerRegistration(() => { - sessions.delete(updates); - if (sessions.size === 0) { - this.activeSessions.delete(response.sessionId); - } - }); - } -} - -const sessionUpdateRouters = new WeakMap< - ConnectionContext, - SessionUpdateRouter ->(); - -function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { - let router = sessionUpdateRouters.get(cx); - if (!router) { - router = new SessionUpdateRouter(); - sessionUpdateRouters.set(cx, router); - } - return router; -} - -function runConnectHandlers( - connection: ConnectionHandle, - handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, -): void { - for (const handler of handlers) { - let result: MaybePromise; - try { - result = handler(connection); - } catch (error) { - connection.close(error); - throw error; - } - - void Promise.resolve(result).catch((error) => { - connection.close(error); - }); - } -} - -const appBuilder = Symbol("appBuilder"); -const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); -const runClientConnectHandlers = Symbol("runClientConnectHandlers"); - -type AppConnectOptions = { - readonly deferConnectHandlers?: boolean; -}; - -type AgentConnectionState = { - rawConnection: Connection; - connection: AgentConnection; -}; - -type ClientConnectionState = { - rawConnection: Connection; - connection: ClientConnection; -}; - -/** - * Creates an agent-side app. - * - * Register request and notification handlers by ACP method name, then call - * `connect(stream)` to serve an ACP client. - */ -export function agent(options?: AppOptions): AgentApp { - return new AgentApp(options); -} - -/** - * Agent-side app builder. - * - * Methods on this class register typed request or notification handlers and - * return `this`, so apps can be built with a fluent chain. Handler params are - * parsed with the generated ACP schemas before your handler runs, and thrown - * errors are converted to JSON-RPC errors by the connection layer. - */ -export class AgentApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: AgentConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - private hasInitializeHandler = false; - - constructor(options: AppOptions = {}) { - this.builder.withHandler( - agentInitializationGate(() => this.hasInitializeHandler), - ); - if (options.name) { - this.builder.name(options.name); - } - } - - /** @internal */ - [appBuilder](): ConnectionBuilder { - return this.builder; - } - - /** @internal */ - [runAgentConnectHandlers](connection: AgentConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - - /** - * Connects this agent app to a transport stream. - */ - connect(stream: Stream): AgentConnection; - /** @internal */ - connect(stream: Stream, options: AppConnectOptions): AgentConnection; - /** - * Connects this agent app directly to a client app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(client: ClientApp): AgentConnection; - connect( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnection { - return this.connectConnection(target, options).connection; - } - - /** - * Connects this agent app to a stream or client app for the lifetime of `op`. - * - * The callback receives an `AgentContext` for calling client-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | ClientApp, - op: (context: AgentContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.client)); - } - - /** - * Registers a handler that runs when this agent app opens a connection. - * - * Use this for connection-scoped work that needs to call client-side ACP - * methods outside an inbound request handler, or to set up per-connection - * state that the request handlers use. - * - * Handlers are called synchronously in registration order and are not - * awaited. A handler that throws or rejects closes the connection. When they - * are called depends on who opens the connection: - * - * - `connect(...)` and `connectWith(...)` call them before the connection - * handles its first inbound message, and so does the experimental - * `AgentProtocolRouter`'s `connect(...)` when it routes to this app. Only - * the work a handler does before its first `await` is guaranteed to come - * first. - * - The experimental `AcpServer` calls them after the client has completed - * `initialize`, so messages they send cannot replace the initialize - * response. Request handlers, including `initialize`, can run before them. - */ - onConnect(handler: AgentConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - - /** - * Registers a request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: AgentRequestHandler): this; - onRequest( - method: Method, - handler: AgentRequestHandlersByMethod[Method], - ): this; - onRequest( - method: string, - params: ParamsParser, - handler: AgentRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | AgentRequestHandlersByMethod[AgentRequestMethod] - | AgentRequestHandler - | ParamsParser, - handler?: AgentRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as AgentRequestHandler, - ); - } - if (handler) { - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = agentRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - - if (method === schema.AGENT_METHODS.initialize) { - this.hasInitializeHandler = true; - } - return this.request( - spec as AcpRequestSpec, - handlerOrParams as AgentRequestHandler, - ); - } - - /** - * Registers a notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. Serialize work yourself - * when its effects must be applied in order. - */ - onNotification(method: "*", handler: AgentNotificationHandler): this; - onNotification( - method: Method, - handler: AgentNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: string, - params: ParamsParser, - handler: AgentNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | AgentNotificationHandlersByMethod[AgentNotificationMethod] - | AgentNotificationHandler - | ParamsParser, - handler?: AgentNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as AgentNotificationHandler, - ); - } - if (handler) { - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = agentNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as AgentNotificationHandler, - ); - } - - private request( - spec: AcpRequestSpec, - handler: AgentRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - agentRequestContext( - params, - AgentContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.mapResponse, - ); - return this; - } - - private notification( - spec: AcpNotificationSpec, - handler: AgentNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - agentNotificationContext( - params, - AgentContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - - private connectConnection( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnectionState { - if (isStream(target)) { - const state = this.openStreamConnection(target); - if (!options.deferConnectHandlers) { - this[runAgentConnectHandlers](state.connection); - } - return state; - } - - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = clientConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => - peerRawConnection.closeFromPeer(), - ); - void peerRawConnection.closed.then(() => - state.rawConnection.closeFromPeer(), - ); - try { - target[runClientConnectHandlers](peerConnection); - this[runAgentConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - - private openStreamConnection(stream: Stream): AgentConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: agentConnection(rawConnection, this.connectHandlers), - }; - } -} - -/** - * Creates a client-side app. - * - * Register request and notification handlers by ACP method name, then use - * `connectWith(...)` to run the workflow that calls agent-side methods. - */ -export function client(options?: AppOptions): ClientApp { - return new ClientApp(options); -} - -/** - * Client-side app builder. - * - * Methods on this class register typed client handlers and return `this`, so - * apps can be built with a fluent chain. `connectWith(...)` is the usual entry - * point for clients because it provides a `ClientContext` for calling - * agent-side requests and session helpers. - */ -export class ClientApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: ClientConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - - constructor(options: AppOptions = {}) { - if (options.name) { - this.builder.name(options.name); - } - this.builder.withHandler({ - handleMessage: (message, cx) => - sessionUpdateRouter(cx).handleMessage(message), - describe: () => "client-session-update-router", - }); - } - - /** @internal */ - [appBuilder](): ConnectionBuilder { - return this.builder; - } - - /** @internal */ - [runClientConnectHandlers](connection: ClientConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - - /** - * Connects this client app to a transport stream. - */ - connect(stream: Stream): ClientConnection; - /** - * Connects this client app directly to an agent app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(agent: AgentApp): ClientConnection; - connect(target: Stream | AgentApp): ClientConnection { - return this.connectConnection(target).connection; - } - - /** - * Connects this client app to a stream or agent app for the lifetime of `op`. - * - * The callback receives a `ClientContext` for calling agent-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | AgentApp, - op: (context: ClientContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.agent)); - } - - /** - * Registers a handler that runs when this client app opens a connection. - * - * Use this for connection-scoped work that needs to call agent-side ACP - * methods outside an inbound request handler. - */ - onConnect(handler: ClientConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - - /** - * Registers a client request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: ClientRequestHandler): this; - onRequest( - method: Method, - handler: ClientRequestHandlersByMethod[Method], - ): this; - onRequest( - method: string, - params: ParamsParser, - handler: ClientRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | ClientRequestHandlersByMethod[ClientRequestMethod] - | ClientRequestHandler - | ParamsParser, - handler?: ClientRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as ClientRequestHandler, - ); - } - if (handler) { - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = clientRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - - return this.request( - spec as AcpRequestSpec, - handlerOrParams as ClientRequestHandler, - ); - } - - /** - * Registers a client notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. To apply a session's - * `session/update` notifications in the order they are received, a handler - * that awaits before applying an update must serialize that work itself, for - * example by chaining it onto a per-session promise. {@link ActiveSession} - * already queues updates in arrival order. - */ - onNotification( - method: "*", - handler: ClientNotificationHandler, - ): this; - onNotification( - method: Method, - handler: ClientNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: string, - params: ParamsParser, - handler: ClientNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | ClientNotificationHandlersByMethod[ClientNotificationMethod] - | ClientNotificationHandler - | ParamsParser, - handler?: ClientNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as ClientNotificationHandler, - ); - } - if (handler) { - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = clientNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as ClientNotificationHandler, - ); - } - - private request( - spec: AcpRequestSpec, - handler: ClientRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - clientRequestContext( - params, - ClientContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.mapResponse, - ); - return this; - } - - private notification( - spec: AcpNotificationSpec, - handler: ClientNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - clientNotificationContext( - params, - ClientContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - - private connectConnection(target: Stream | AgentApp): ClientConnectionState { - if (isStream(target)) { - const state = this.openStreamConnection(target); - this[runClientConnectHandlers](state.connection); - return state; - } - - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = agentConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => - peerRawConnection.closeFromPeer(), - ); - void peerRawConnection.closed.then(() => - state.rawConnection.closeFromPeer(), - ); - try { - target[runAgentConnectHandlers](peerConnection); - this[runClientConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - - private openStreamConnection(stream: Stream): ClientConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: clientConnection(rawConnection, this.connectHandlers), - }; - } -} - -/** - * Handle for controlling and monitoring a terminal created via `createTerminal`. - * - * Provides methods to: - * - Get current output without waiting - * - Wait for command completion - * - Kill the running command - * - Release terminal resources - * - * **Important:** Always call `release()` when done with the terminal to free resources. - - * The terminal supports async disposal via `Symbol.asyncDispose` for automatic cleanup. - - * You can use `await using` to ensure the terminal is automatically released when it - * goes out of scope. - */ -export class TerminalHandle { - /** - * Terminal identifier returned by `terminal/create`. - */ - public id: string; - private sessionId: string; - private connection: Pick; - - private constructor( - id: string, - sessionId: string, - conn: Pick, - ) { - this.id = id; - this.sessionId = sessionId; - this.connection = conn; - } - - /** @internal */ - static create( - id: string, - sessionId: string, - conn: Pick, - ): TerminalHandle { - return new TerminalHandle(id, sessionId, conn); - } - - /** - * Gets the current terminal output without waiting for the command to exit. - */ - currentOutput(): Promise { - return this.connection.sendRequest(schema.CLIENT_METHODS.terminal_output, { - sessionId: this.sessionId, - terminalId: this.id, - }); - } - - /** - * Waits for the terminal command to complete and returns its exit status. - */ - waitForExit(): Promise { - return this.connection.sendRequest( - schema.CLIENT_METHODS.terminal_wait_for_exit, - { - sessionId: this.sessionId, - terminalId: this.id, - }, - ); - } - - /** - * Kills the terminal command without releasing the terminal. - * - * The terminal remains valid after killing, allowing you to: - * - Get the final output with `currentOutput()` - * - Check the exit status - * - Release the terminal when done - * - * Useful for implementing timeouts or cancellation. - */ - kill(): Promise { - return this.connection.sendRequest< - schema.KillTerminalRequest, - schema.KillTerminalResponse - >( - schema.CLIENT_METHODS.terminal_kill, - { - sessionId: this.sessionId, - terminalId: this.id, - }, - emptyObjectResponse, - ); - } - - /** - * Releases the terminal and frees all associated resources. - * - * If the command is still running, it will be killed. - * After release, the terminal ID becomes invalid and cannot be used - * with other terminal methods. - * - * Tool calls that already reference this terminal will continue to - * display its output. - * - * **Important:** Always call this method when done with the terminal. - */ - release(): Promise { - return this.connection.sendRequest< - schema.ReleaseTerminalRequest, - schema.ReleaseTerminalResponse | void - >( - schema.CLIENT_METHODS.terminal_release, - { - sessionId: this.sessionId, - terminalId: this.id, - }, - emptyObjectResponse, - ); - } - - /** - * Releases the terminal when used with `await using`. - */ - async [Symbol.asyncDispose](): Promise { - await this.release(); - } -} diff --git a/src/v1/bindings.ts b/src/v1/bindings.ts new file mode 100644 index 00000000..75e7c5c6 --- /dev/null +++ b/src/v1/bindings.ts @@ -0,0 +1,2498 @@ +// V1 binding implementation, specialized against stable schemas by generate.js. +import * as schema from "./unstable/schema/index.js"; +import * as validate from "./unstable/schema/zod.gen.js"; +import type { Stream } from "./acp.js"; +import { + parseParams, + registerAppNotification, + registerAppRequest, +} from "../core/app-handlers.js"; +import type { ParamsParser } from "../core/app-handlers.js"; +import { connectionContextOf } from "../core/connection-access.js"; +import { + Connection, + Handled, + HandlerRegistration, + RequestError, + RequestResponder, + treatSessionNotFoundAsSuccess, +} from "../core/jsonrpc.js"; +import type { + AnyMessage, + ConnectionBuilder, + ConnectionContext, + HandleResult, + IncomingMessage, + JsonRpcId, + JsonRpcHandler, + MaybePromise, + SendRequestOptions, +} from "../core/jsonrpc.js"; + +const initializedConnections = new WeakSet(); + +/** + * Rejects requests other than `initialize` with `-32600` until an `initialize` + * request has been answered successfully. `initialize` itself may be sent + * again at any time, as before. + */ +function agentInitializationGate(enabled: () => boolean): JsonRpcHandler { + return { + handleMessage(message, cx) { + if ( + message.kind !== "request" || + !enabled() || + initializedConnections.has(cx) + ) { + return Handled.no(message); + } + if (message.method !== schema.AGENT_METHODS.initialize) { + return message.responder + .respondWithError( + RequestError.invalidRequest( + undefined, + `ACP connection must be initialized before '${message.method}'`, + ), + ) + .then(() => Handled.yes()); + } + + const { responder } = message; + return Handled.no({ + ...message, + responder: new RequestResponder( + responder.id, + (result) => { + // Record success before the response goes out, so the client's + // next request is never rejected. + if ("result" in result) { + initializedConnections.add(cx); + } + return responder.respondWithResult(result); + }, + responder.signal, + ), + }); + }, + describe: () => "agent-initialization", + }; +} + +function emptyObjectResponse(response: T | null | undefined | void): T { + return response ?? ({} as T); +} + +function isStream(value: unknown): value is Stream { + return ( + typeof value === "object" && + value !== null && + "readable" in value && + "writable" in value + ); +} + +function memoryStreamPair(): [Stream, Stream] { + const leftToRight = new TransformStream(); + const rightToLeft = new TransformStream(); + return [ + { + readable: rightToLeft.readable, + writable: leftToRight.writable, + }, + { + readable: leftToRight.readable, + writable: rightToLeft.writable, + }, + ]; +} + +const startActiveSession = Symbol("startActiveSession"); + +/** + * Active ACP connection returned by `AgentApp.connect(...)` and + * `ClientApp.connect(...)`. + * + * Use this handle when you need a connection to stay open independently of a + * single `connectWith(...)` operation. + */ +export interface AcpConnection { + /** + * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. + */ + readonly signal: AbortSignal; + + /** + * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. + */ + readonly closed: Promise; + + /** + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. + */ + close(error?: unknown): void; +} + +/** + * Agent-side connection returned by `AgentApp.connect(...)`. + * + * Use `client` to call client-side ACP methods for the lifetime of the + * connection. + */ +export interface AgentConnection extends AcpConnection { + /** + * Context for calling client-side ACP methods. + */ + readonly client: AgentContext; +} + +/** + * Client-side connection returned by `ClientApp.connect(...)`. + * + * Use `agent` to call agent-side ACP methods and session helpers for the + * lifetime of the connection. + */ +export interface ClientConnection extends AcpConnection { + /** + * Context for calling agent-side ACP methods. + */ + readonly agent: ClientContext; +} + +class AcpContext { + /** @internal */ + constructor( + private readonly cx: ConnectionContext, + private readonly currentRequestId?: JsonRpcId, + ) {} + + /** + * JSON-RPC id of the request currently being handled. + * + * This is `undefined` for notification handlers and for contexts created + * outside an inbound request, such as `connect(...)` and `connectWith(...)`. + */ + get requestId(): JsonRpcId | undefined { + return this.currentRequestId; + } + + /** @internal */ + protected get connectionContext(): ConnectionContext { + return this.cx; + } + + /** @hidden SDK helpers use this to identify the connection. */ + [connectionContextOf](): ConnectionContext { + return this.cx; + } + + /** @internal */ + protected sendRequest( + method: string, + params?: Req, + mapResponse?: (response: Resp) => Output, + options?: SendRequestOptions, + ): Promise { + return this.cx.sendRequest(method, params, mapResponse, options); + } + + /** @internal */ + protected sendNotification(method: string, params?: N): Promise { + return this.cx.sendNotification(method, params); + } + + /** @internal */ + protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { + return this.cx.addDynamicHandler(handler); + } +} + +/** + * Context passed to agent-side handlers. + * + * Agents use this context to call client-side ACP methods while handling + * requests such as `session/prompt`. + */ +export class AgentContext extends AcpContext { + private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { + super(cx, requestId); + } + + /** @internal */ + static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { + return new AgentContext(cx, requestId); + } + + /** + * Executes a command in a new client terminal. + * + * Returns a handle for reading output, waiting for exit, killing the command, + * and releasing the terminal. Check the client's terminal capability first. + * Use `await using` or call `release()` when finished. + */ + async createTerminal( + params: schema.CreateTerminalRequest, + options?: SendRequestOptions, + ): Promise { + const response = await this.request( + schema.CLIENT_METHODS.terminal_create, + params, + options, + ); + return TerminalHandle.create( + response.terminalId, + params.sessionId, + this.connectionContext, + ); + } + + /** + * Sends a request to the client by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + */ + request( + method: Method, + params: ClientRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + const spec = clientRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + return this.sendRequest(method, params, spec?.mapResponse, options); + } + + /** + * Sends a notification to the client by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: ClientNotificationParamsByMethod[Method], + ): Promise; + notify(method: string, params?: Params): Promise; + notify(method: string, params?: unknown): Promise { + return this.sendNotification(method, params); + } +} + +/** + * Context used by clients to call agent-side ACP methods. + * + * `connectWith` passes a `ClientContext` to the callback. Client handlers also + * receive one as `ctx.agent` when they need to call back into the agent. + */ +export class ClientContext extends AcpContext { + private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { + super(cx, requestId); + } + + /** @internal */ + static create(cx: ConnectionContext, requestId?: JsonRpcId): ClientContext { + return new ClientContext(cx, requestId); + } + + /** @internal */ + [startActiveSession]( + params: schema.NewSessionRequest, + options?: SendRequestOptions, + ): Promise { + return this.sendRequest< + schema.NewSessionRequest, + schema.NewSessionResponse, + ActiveSession + >( + schema.AGENT_METHODS.session_new, + params, + (response) => this.attachSession(response), + options, + ); + } + + /** + * Creates a builder for starting and observing an ACP session. + * + * Pass a string for the common case where only `cwd` is needed, or pass a + * full `NewSessionRequest` when you need MCP servers, `_meta`, or additional + * session fields. + */ + buildSession(cwd: string): SessionBuilder; + buildSession(request: schema.NewSessionRequest): SessionBuilder; + buildSession( + cwdOrRequest: string | schema.NewSessionRequest, + ): SessionBuilder { + if (typeof cwdOrRequest === "string") { + return SessionBuilder.create(this, { + cwd: cwdOrRequest, + mcpServers: [], + }); + } + + return SessionBuilder.create(this, cwdOrRequest); + } + + /** + * Builds active-session helpers around a `session/new` response. + */ + private attachSession(response: schema.NewSessionResponse): ActiveSession { + const updates = new AsyncQueue(); + const closeSignal = this.connectionContext.signal; + const failUpdatesOnClose = () => { + updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); + }; + if (closeSignal.aborted) { + failUpdatesOnClose(); + } else { + closeSignal.addEventListener("abort", failUpdatesOnClose); + } + const sessionRegistration = sessionUpdateRouter( + this.connectionContext, + ).attach(response, updates); + const closeRegistration = new HandlerRegistration(() => { + closeSignal.removeEventListener("abort", failUpdatesOnClose); + }); + + return ActiveSession.create(this, response, updates, [ + sessionRegistration, + closeRegistration, + ]); + } + + /** + * Sends a request to the agent by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + * + * Closing or deleting a session is idempotent: a `-32002` (Resource not + * found) response to `session/close` or `session/delete` resolves with an + * empty result instead of rejecting. + */ + request( + method: Method, + params: AgentRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + const spec = agentRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + return treatSessionNotFoundAsSuccess( + method, + this.sendRequest(method, params, spec?.mapResponse, options), + () => (spec?.mapResponse ? spec.mapResponse({}) : {}), + ); + } + + /** + * Sends a notification to the agent by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: AgentNotificationParamsByMethod[Method], + ): Promise; + notify(method: string, params?: Params): Promise; + notify(method: string, params?: unknown): Promise { + return this.sendNotification(method, params); + } +} + +class AcpConnectionHandle implements AcpConnection { + constructor(private readonly connection: Connection) {} + + get signal(): AbortSignal { + return this.connection.signal; + } + + get closed(): Promise { + return this.connection.closed; + } + + close(error?: unknown): void { + this.connection.close(error); + } +} + +class AgentConnectionHandle + extends AcpConnectionHandle + implements AgentConnection +{ + readonly client: AgentContext; + private didStartConnectHandlers = false; + + constructor( + connection: Connection, + private readonly connectHandlers: readonly AgentConnectHandler[] = [], + ) { + super(connection); + this.client = AgentContext.create(connection.getContext()); + } + + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} + +class ClientConnectionHandle + extends AcpConnectionHandle + implements ClientConnection +{ + readonly agent: ClientContext; + private didStartConnectHandlers = false; + + constructor( + connection: Connection, + private readonly connectHandlers: readonly ClientConnectHandler[] = [], + ) { + super(connection); + this.agent = ClientContext.create(connection.getContext()); + } + + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} + +function agentConnection( + connection: Connection, + connectHandlers: readonly AgentConnectHandler[] = [], +): AgentConnection { + return new AgentConnectionHandle(connection, connectHandlers); +} + +function clientConnection( + connection: Connection, + connectHandlers: readonly ClientConnectHandler[] = [], +): ClientConnection { + return new ClientConnectionHandle(connection, connectHandlers); +} + +type AsyncQueueEntry = + | { + kind: "value"; + value: T; + } + | { + kind: "error"; + error: unknown; + }; + +class AsyncQueue { + private values: Array> = []; + private waiters: Array<{ + resolve: (value: T) => void; + reject: (error: unknown) => void; + }> = []; + private failed = false; + private failure: unknown; + + enqueue(value: T): void { + if (this.failed) { + return; + } + + const waiter = this.waiters.shift(); + if (waiter) { + waiter.resolve(value); + } else { + this.values.push({ kind: "value", value }); + } + } + + reject(error: unknown): void { + if (this.failed) { + return; + } + + if (this.waiters.length > 0) { + for (const waiter of this.waiters.splice(0)) { + waiter.reject(error); + } + return; + } + + this.values.push({ kind: "error", error }); + } + + clearErrors(): void { + this.values = this.values.filter((entry) => entry.kind === "value"); + } + + fail(error: unknown): void { + if (this.failed) { + return; + } + + this.failed = true; + this.failure = error; + for (const waiter of this.waiters.splice(0)) { + waiter.reject(error); + } + } + + next(): Promise { + if (this.values.length > 0) { + const entry = this.values.shift() as AsyncQueueEntry; + if (entry.kind === "error") { + return Promise.reject(entry.error); + } + + return Promise.resolve(entry.value); + } + + if (this.failed) { + return Promise.reject(this.failure); + } + + return new Promise((resolve, reject) => { + this.waiters.push({ resolve, reject }); + }); + } +} + +function cloneNewSessionRequest( + request: schema.NewSessionRequest, +): schema.NewSessionRequest { + return { + ...request, + additionalDirectories: request.additionalDirectories + ? [...request.additionalDirectories] + : undefined, + mcpServers: [...request.mcpServers], + }; +} + +/** + * Message produced by an `ActiveSession`. + * + * `session_update` messages expose the typed `session/update` notification and + * `stop` messages report the final `session/prompt` response. A prompt turn is + * complete once a `stop` message is returned. + */ +export type ActiveSessionMessage = + | { + /** + * Indicates that this message came from a `session/update` notification. + */ + kind: "session_update"; + /** + * Full notification sent by the agent. + */ + notification: schema.SessionNotification; + /** + * Convenience alias for `notification.update`. + */ + update: schema.SessionUpdate; + } + | { + /** + * Indicates that the prompt turn has completed. + */ + kind: "stop"; + /** + * Final response from `session/prompt`. + */ + response: schema.PromptResponse; + /** + * Convenience alias for `response.stopReason`. + */ + stopReason: schema.StopReason; + }; + +/** + * Builder for creating an `ActiveSession`. + * + * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or + * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session + * needs MCP servers, `_meta`, or additional request fields. All paths in ACP + * payloads should be absolute. + */ +export class SessionBuilder { + private request: schema.NewSessionRequest; + + private constructor( + private cx: ClientContext, + request: schema.NewSessionRequest, + ) { + this.request = cloneNewSessionRequest(request); + } + + /** @internal */ + static create( + cx: ClientContext, + request: schema.NewSessionRequest, + ): SessionBuilder { + return new SessionBuilder(cx, request); + } + + /** + * Returns the `session/new` request that will be sent. + * + * The returned object is a defensive copy, so mutating it does not change the + * builder. + */ + toRequest(): schema.NewSessionRequest { + return cloneNewSessionRequest(this.request); + } + + /** + * Replaces the additional workspace roots for this session. + * + * `additionalDirectories` expand the session's file-system scope without + * changing `cwd`. Each path should be absolute. + */ + withAdditionalDirectories(additionalDirectories: string[]): this { + this.request = { + ...this.request, + additionalDirectories: [...additionalDirectories], + }; + return this; + } + + /** + * Adds one MCP server to the `session/new` request. + */ + withMcpServer(mcpServer: schema.McpServer): this { + this.request = { + ...this.request, + mcpServers: [...this.request.mcpServers, mcpServer], + }; + return this; + } + + /** + * Starts the session and returns an `ActiveSession` for prompting and reading + * updates. + * + * Call `dispose()` on the returned session when you no longer need update + * routing, or use `withSession(...)` to scope disposal automatically. + */ + async start(options?: SendRequestOptions): Promise { + return this.cx[startActiveSession](this.toRequest(), options); + } + + /** + * Starts the session, runs `op`, and disposes the active-session update + * routing when `op` finishes or throws. + */ + async withSession( + op: (session: ActiveSession) => MaybePromise, + ): Promise { + const session = await this.start(); + try { + return await op(session); + } finally { + session.dispose(); + } + } +} + +/** + * Convenience wrapper for an active ACP session. + * + * An active session routes `session/update` notifications for one session ID + * into an async queue. Use `prompt(...)` to send user content, then read updates + * with `nextUpdate()` until a `stop` message is returned. + */ +export class ActiveSession { + private constructor( + private cx: ClientContext, + private sessionResponse: schema.NewSessionResponse, + private updates: { + enqueue(value: ActiveSessionMessage): void; + reject(error: unknown): void; + clearErrors(): void; + fail(error: unknown): void; + next(): Promise; + }, + private registrations: HandlerRegistration[], + ) {} + + /** @internal */ + static create( + cx: ClientContext, + sessionResponse: schema.NewSessionResponse, + updates: { + enqueue(value: ActiveSessionMessage): void; + reject(error: unknown): void; + clearErrors(): void; + fail(error: unknown): void; + next(): Promise; + }, + registrations: HandlerRegistration[], + ): ActiveSession { + return new ActiveSession(cx, sessionResponse, updates, registrations); + } + + /** + * Session ID returned by `session/new`. + */ + get sessionId(): schema.SessionId { + return this.sessionResponse.sessionId; + } + + /** + * Mode state returned when the session was created, if the agent provided it. + */ + get modes(): schema.SessionModeState | null | undefined { + return this.sessionResponse.modes; + } + + /** + * Metadata returned when the session was created. + */ + get meta(): { [key: string]: unknown } | null | undefined { + return this.sessionResponse._meta; + } + + /** + * Full response returned by `session/new`. + */ + get newSessionResponse(): schema.NewSessionResponse { + return this.sessionResponse; + } + + /** + * Sends a prompt to this session. + * + * Strings are converted to one text content block. A single content block is + * wrapped in an array. The returned promise resolves with the final + * `PromptResponse`, and the same completion is also queued as a `stop` + * message for `nextUpdate()`. + */ + prompt( + prompt: string | schema.ContentBlock | Array, + options?: SendRequestOptions, + ): Promise { + this.updates.clearErrors(); + const response = this.cx.request( + schema.AGENT_METHODS.session_prompt, + { + sessionId: this.sessionId, + prompt: this.promptBlocks(prompt), + }, + options, + ); + void response.then( + (value) => { + this.updates.enqueue({ + kind: "stop", + response: value, + stopReason: value.stopReason, + }); + }, + (error) => { + this.updates.reject(error); + }, + ); + return response; + } + + /** + * Reads the next update or stop message for this session. + */ + nextUpdate(): Promise { + return this.updates.next(); + } + + /** + * Reads text chunks until the current prompt turn stops. + * + * Only `agent_message_chunk` updates with text content are appended. Other + * update types are ignored by this helper; use `nextUpdate()` when you need + * tool calls, plans, or the final `PromptResponse`. + */ + async readText(): Promise { + let output = ""; + for (;;) { + const message = await this.nextUpdate(); + if (message.kind === "stop") { + return output; + } + + const { update } = message; + if ( + update.sessionUpdate === "agent_message_chunk" && + update.content.type === "text" + ) { + output += update.content.text; + } + } + } + + /** + * Stops routing updates to this active-session helper. + * + * This does not close the ACP session on the agent. Use `ClientContext` + * session lifecycle methods when the protocol session itself should be closed + * or deleted. + */ + dispose(): void { + for (const registration of this.registrations.splice(0)) { + registration.dispose(); + } + this.updates.fail(new Error("Active session disposed")); + } + + /** + * Supports explicit resource management with `using`. + */ + [Symbol.dispose](): void { + this.dispose(); + } + + private promptBlocks( + prompt: string | schema.ContentBlock | Array, + ): Array { + if (typeof prompt === "string") { + return [{ type: "text", text: prompt }]; + } + + if (Array.isArray(prompt)) { + return prompt; + } + + return [prompt]; + } +} + +/** + * Options used when creating an ACP app. + */ +export type AppOptions = { + /** + * Human-readable name used in JSON-RPC handler descriptions and diagnostics. + */ + name?: string; +}; + +/** + * Common context passed to agent-side handlers. + */ +export type AgentHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed client context for calling client-side ACP methods. + */ + client: AgentContext; +}; + +/** + * Context passed to agent-side request handlers. + */ +export type AgentRequestContext = AgentHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; + +/** + * Context passed to agent-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type AgentNotificationContext = AgentHandlerContext; + +/** + * Common context passed to client-side handlers. + */ +export type ClientHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed agent context for calling agent-side ACP methods. + */ + agent: ClientContext; +}; + +/** + * Context passed to client-side request handlers. + */ +export type ClientRequestContext = ClientHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; + +/** + * Context passed to client-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type ClientNotificationContext = ClientHandlerContext; + +/** + * Request handler registered on an `AgentApp`. + */ +export type AgentRequestHandler = ( + context: AgentRequestContext, +) => MaybePromise; + +/** + * Notification handler registered on an `AgentApp`. + */ +export type AgentNotificationHandler = ( + context: AgentNotificationContext, +) => MaybePromise; + +/** + * Request handler registered on a `ClientApp`. + */ +export type ClientRequestHandler = ( + context: ClientRequestContext, +) => MaybePromise; + +/** + * Notification handler registered on a `ClientApp`. + */ +export type ClientNotificationHandler = ( + context: ClientNotificationContext, +) => MaybePromise; + +/** + * Handler called when an `AgentApp` opens a connection. + */ +export type AgentConnectHandler = ( + connection: AgentConnection, +) => MaybePromise; + +/** + * Handler called when a `ClientApp` opens a connection. + */ +export type ClientConnectHandler = ( + connection: ClientConnection, +) => MaybePromise; + +type AcpRequestSpec = { + method: string; + params?: ParamsParser; + mapResponse?: (response: Response) => WireResponse; +}; + +type AcpNotificationSpec = { + method: string; + params?: ParamsParser; +}; + +function requestSpec( + method: string, + params: ParamsParser, + mapResponse?: (response: Response) => WireResponse, +): AcpRequestSpec { + return { + method, + // Match Rust's empty-payload handling without bypassing required fields. + params: (value) => parseParams(params, value ?? {}), + mapResponse, + }; +} + +function notificationSpec( + method: string, + params: ParamsParser, +): AcpNotificationSpec { + return { method, params }; +} + +function specsByMethod>( + specs: T, +): Record { + const byMethod: Record = {}; + for (const spec of Object.values(specs) as Array) { + byMethod[spec.method] = spec; + } + return byMethod; +} + +const agentRequestSpecs = { + initialize: requestSpec( + schema.AGENT_METHODS.initialize, + validate.zInitializeRequest, + ), + newSession: requestSpec( + schema.AGENT_METHODS.session_new, + validate.zNewSessionRequest, + ), + loadSession: requestSpec< + schema.LoadSessionRequest, + schema.LoadSessionResponse | void, + schema.LoadSessionResponse + >( + schema.AGENT_METHODS.session_load, + validate.zLoadSessionRequest, + emptyObjectResponse, + ), + unstable_forkSession: requestSpec< + schema.ForkSessionRequest, + schema.ForkSessionResponse + >(schema.AGENT_METHODS.session_fork, validate.zForkSessionRequest), + listSessions: requestSpec< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >(schema.AGENT_METHODS.session_list, validate.zListSessionsRequest), + deleteSession: requestSpec< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void, + schema.DeleteSessionResponse + >( + schema.AGENT_METHODS.session_delete, + validate.zDeleteSessionRequest, + emptyObjectResponse, + ), + unstable_archiveSession: requestSpec< + schema.ArchiveSessionRequest, + schema.ArchiveSessionResponse | void, + schema.ArchiveSessionResponse + >( + schema.AGENT_METHODS.session_archive, + validate.zArchiveSessionRequest, + emptyObjectResponse, + ), + unstable_unarchiveSession: requestSpec< + schema.UnarchiveSessionRequest, + schema.UnarchiveSessionResponse | void, + schema.UnarchiveSessionResponse + >( + schema.AGENT_METHODS.session_unarchive, + validate.zUnarchiveSessionRequest, + emptyObjectResponse, + ), + unstable_sessionStatus: requestSpec< + schema.SessionStatusRequest, + schema.SessionStatusResponse + >(schema.AGENT_METHODS.session_status, validate.zSessionStatusRequest), + unstable_sessionOptions: requestSpec< + schema.SessionOptionsRequest, + schema.SessionOptionsResponse + >(schema.AGENT_METHODS.session_options, validate.zSessionOptionsRequest), + unstable_setSessionTitle: requestSpec< + schema.SetSessionTitleRequest, + schema.SetSessionTitleResponse + >(schema.AGENT_METHODS.session_set_title, validate.zSetSessionTitleRequest), + resumeSession: requestSpec< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >(schema.AGENT_METHODS.session_resume, validate.zResumeSessionRequest), + closeSession: requestSpec< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void, + schema.CloseSessionResponse + >( + schema.AGENT_METHODS.session_close, + validate.zCloseSessionRequest, + emptyObjectResponse, + ), + setSessionMode: requestSpec< + schema.SetSessionModeRequest, + schema.SetSessionModeResponse | void, + schema.SetSessionModeResponse + >( + schema.AGENT_METHODS.session_set_mode, + validate.zSetSessionModeRequest, + emptyObjectResponse, + ), + setSessionConfigOption: requestSpec< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >( + schema.AGENT_METHODS.session_set_config_option, + validate.zSetSessionConfigOptionRequest, + ), + authenticate: requestSpec< + schema.AuthenticateRequest, + schema.AuthenticateResponse | void, + schema.AuthenticateResponse + >( + schema.AGENT_METHODS.authenticate, + validate.zAuthenticateRequest, + emptyObjectResponse, + ), + unstable_listProviders: requestSpec< + schema.ListProvidersRequest, + schema.ListProvidersResponse + >(schema.AGENT_METHODS.providers_list, validate.zListProvidersRequest), + unstable_setProvider: requestSpec< + schema.SetProviderRequest, + schema.SetProviderResponse | void, + schema.SetProviderResponse + >( + schema.AGENT_METHODS.providers_set, + validate.zSetProviderRequest, + emptyObjectResponse, + ), + unstable_disableProvider: requestSpec< + schema.DisableProviderRequest, + schema.DisableProviderResponse | void, + schema.DisableProviderResponse + >( + schema.AGENT_METHODS.providers_disable, + validate.zDisableProviderRequest, + emptyObjectResponse, + ), + logout: requestSpec< + schema.LogoutRequest, + schema.LogoutResponse | void, + schema.LogoutResponse + >(schema.AGENT_METHODS.logout, validate.zLogoutRequest, emptyObjectResponse), + unstable_authStatus: requestSpec< + schema.AuthStatusRequest, + schema.AuthStatusResponse + >(schema.AGENT_METHODS.auth_status, validate.zAuthStatusRequest), + prompt: requestSpec( + schema.AGENT_METHODS.session_prompt, + validate.zPromptRequest, + ), +}; + +const agentNotificationSpecs = { + cancel: notificationSpec( + schema.AGENT_METHODS.session_cancel, + validate.zCancelNotification, + ), + unstable_messageMcp: notificationSpec( + schema.AGENT_METHODS.mcp_message, + validate.zMessageMcpNotification, + ), +}; + +const clientRequestSpecs = { + requestPermission: requestSpec< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >( + schema.CLIENT_METHODS.session_request_permission, + validate.zRequestPermissionRequest, + ), + writeTextFile: requestSpec< + schema.WriteTextFileRequest, + schema.WriteTextFileResponse | void, + schema.WriteTextFileResponse + >( + schema.CLIENT_METHODS.fs_write_text_file, + validate.zWriteTextFileRequest, + emptyObjectResponse, + ), + readTextFile: requestSpec< + schema.ReadTextFileRequest, + schema.ReadTextFileResponse + >(schema.CLIENT_METHODS.fs_read_text_file, validate.zReadTextFileRequest), + createTerminal: requestSpec< + schema.CreateTerminalRequest, + schema.CreateTerminalResponse + >(schema.CLIENT_METHODS.terminal_create, validate.zCreateTerminalRequest), + terminalOutput: requestSpec< + schema.TerminalOutputRequest, + schema.TerminalOutputResponse + >(schema.CLIENT_METHODS.terminal_output, validate.zTerminalOutputRequest), + releaseTerminal: requestSpec< + schema.ReleaseTerminalRequest, + schema.ReleaseTerminalResponse | void, + schema.ReleaseTerminalResponse + >( + schema.CLIENT_METHODS.terminal_release, + validate.zReleaseTerminalRequest, + emptyObjectResponse, + ), + waitForTerminalExit: requestSpec< + schema.WaitForTerminalExitRequest, + schema.WaitForTerminalExitResponse + >( + schema.CLIENT_METHODS.terminal_wait_for_exit, + validate.zWaitForTerminalExitRequest, + ), + killTerminal: requestSpec< + schema.KillTerminalRequest, + schema.KillTerminalResponse | void, + schema.KillTerminalResponse + >( + schema.CLIENT_METHODS.terminal_kill, + validate.zKillTerminalRequest, + emptyObjectResponse, + ), + createElicitation: requestSpec< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >( + schema.CLIENT_METHODS.elicitation_create, + validate.zCreateElicitationRequest, + ), + unstable_messageMcp: requestSpec< + schema.MessageMcpRequest, + schema.MessageMcpResponse + >(schema.CLIENT_METHODS.mcp_message, validate.zMessageMcpRequest), +}; + +const clientNotificationSpecs = { + sessionUpdate: notificationSpec( + schema.CLIENT_METHODS.session_update, + validate.zSessionNotification, + ), + completeElicitation: notificationSpec( + schema.CLIENT_METHODS.elicitation_complete, + validate.zCompleteElicitationNotification, + ), + unstable_authStatusUpdate: + notificationSpec( + schema.CLIENT_METHODS.auth_status_update, + validate.zAuthStatusUpdateNotification, + ), +}; + +const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); +const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); +const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); +const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); + +/** + * Agent request handlers keyed by ACP protocol method name. + */ +export type AgentRequestHandlersByMethod = { + /** + * Handles `initialize`. + * + * Registering this handler makes the app reject other requests with + * `-32600` until an `initialize` request has been answered successfully. + */ + [schema.AGENT_METHODS.initialize]: AgentRequestHandler< + schema.InitializeRequest, + schema.InitializeResponse + >; + [schema.AGENT_METHODS.session_new]: AgentRequestHandler< + schema.NewSessionRequest, + schema.NewSessionResponse + >; + [schema.AGENT_METHODS.session_load]: AgentRequestHandler< + schema.LoadSessionRequest, + schema.LoadSessionResponse | void + >; + [schema.AGENT_METHODS.session_fork]: AgentRequestHandler< + schema.ForkSessionRequest, + schema.ForkSessionResponse + >; + [schema.AGENT_METHODS.session_list]: AgentRequestHandler< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >; + [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void + >; + /** + * Handles `session/archive`. Archiving an active or loaded session first + * cancels its work and frees its resources as `session/close` would. + * Archiving an archived session succeeds. An unknown session gets `-32002`. + */ + [schema.AGENT_METHODS.session_archive]: AgentRequestHandler< + schema.ArchiveSessionRequest, + schema.ArchiveSessionResponse | void + >; + /** + * Handles `session/unarchive`. It does not load or resume the session. + * Unarchiving a session that is not archived succeeds. An unknown session + * gets `-32002`. + */ + [schema.AGENT_METHODS.session_unarchive]: AgentRequestHandler< + schema.UnarchiveSessionRequest, + schema.UnarchiveSessionResponse | void + >; + /** + * Handles `session/status`. It must not load, resume, create, close, or + * change the session. An unknown session gets `-32002`. + */ + [schema.AGENT_METHODS.session_status]: AgentRequestHandler< + schema.SessionStatusRequest, + schema.SessionStatusResponse + >; + /** + * Handles `session/options`. Respond with the modes and config options a + * session would start with. With `sessionId`, respond with what + * `session/load` or `session/resume` would return for that session. + * Clients send `sessionId` only when the agent supports `session/load`, + * `session/resume`, or `session/fork`. Before a fork, it is the source + * session's ID. It must not create, load, resume, or change a session, + * send `session/update` notifications, or add an entry to `session/list`. + * The agent may start its runtime to resolve the options, and these rules + * still hold for it. An unknown session gets `-32002`. + */ + [schema.AGENT_METHODS.session_options]: AgentRequestHandler< + schema.SessionOptionsRequest, + schema.SessionOptionsResponse + >; + /** + * Handles `session/set_title`. Respond with the stored title after storing + * it. A title that is invalid after normalization gets `-32602`, and an + * unknown session gets `-32002`. + */ + [schema.AGENT_METHODS.session_set_title]: AgentRequestHandler< + schema.SetSessionTitleRequest, + schema.SetSessionTitleResponse + >; + [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >; + [schema.AGENT_METHODS.session_close]: AgentRequestHandler< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void + >; + [schema.AGENT_METHODS.session_set_mode]: AgentRequestHandler< + schema.SetSessionModeRequest, + schema.SetSessionModeResponse | void + >; + [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >; + [schema.AGENT_METHODS.authenticate]: AgentRequestHandler< + schema.AuthenticateRequest, + schema.AuthenticateResponse | void + >; + [schema.AGENT_METHODS.providers_list]: AgentRequestHandler< + schema.ListProvidersRequest, + schema.ListProvidersResponse + >; + [schema.AGENT_METHODS.providers_set]: AgentRequestHandler< + schema.SetProviderRequest, + schema.SetProviderResponse | void + >; + [schema.AGENT_METHODS.providers_disable]: AgentRequestHandler< + schema.DisableProviderRequest, + schema.DisableProviderResponse | void + >; + [schema.AGENT_METHODS.logout]: AgentRequestHandler< + schema.LogoutRequest, + schema.LogoutResponse | void + >; + /** + * Handles `auth/status`. It must not change any agent state, and it must + * not fail with `auth_required` (`-32000`). + */ + [schema.AGENT_METHODS.auth_status]: AgentRequestHandler< + schema.AuthStatusRequest, + schema.AuthStatusResponse + >; + [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< + schema.PromptRequest, + schema.PromptResponse + >; +}; + +/** + * ACP request methods that can be handled by an `AgentApp`. + */ +export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; + +/** + * Agent notification handlers keyed by ACP protocol method name. + */ +export type AgentNotificationHandlersByMethod = { + [schema.AGENT_METHODS + .session_cancel]: AgentNotificationHandler; + [schema.AGENT_METHODS + .mcp_message]: AgentNotificationHandler; +}; + +/** + * ACP notification methods that can be handled by an `AgentApp`. + */ +export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & + string; + +/** + * Client request handlers keyed by ACP protocol method name. + */ +export type ClientRequestHandlersByMethod = { + [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >; + [schema.CLIENT_METHODS.fs_write_text_file]: ClientRequestHandler< + schema.WriteTextFileRequest, + schema.WriteTextFileResponse | void + >; + [schema.CLIENT_METHODS.fs_read_text_file]: ClientRequestHandler< + schema.ReadTextFileRequest, + schema.ReadTextFileResponse + >; + [schema.CLIENT_METHODS.terminal_create]: ClientRequestHandler< + schema.CreateTerminalRequest, + schema.CreateTerminalResponse + >; + [schema.CLIENT_METHODS.terminal_output]: ClientRequestHandler< + schema.TerminalOutputRequest, + schema.TerminalOutputResponse + >; + [schema.CLIENT_METHODS.terminal_release]: ClientRequestHandler< + schema.ReleaseTerminalRequest, + schema.ReleaseTerminalResponse | void + >; + [schema.CLIENT_METHODS.terminal_wait_for_exit]: ClientRequestHandler< + schema.WaitForTerminalExitRequest, + schema.WaitForTerminalExitResponse + >; + [schema.CLIENT_METHODS.terminal_kill]: ClientRequestHandler< + schema.KillTerminalRequest, + schema.KillTerminalResponse | void + >; + [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >; + [schema.CLIENT_METHODS.mcp_message]: ClientRequestHandler< + schema.MessageMcpRequest, + schema.MessageMcpResponse + >; +}; + +/** + * ACP request methods that can be handled by a `ClientApp`. + */ +export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; + +/** + * Client notification handlers keyed by ACP protocol method name. + */ +export type ClientNotificationHandlersByMethod = { + [schema.CLIENT_METHODS + .session_update]: ClientNotificationHandler; + [schema.CLIENT_METHODS + .elicitation_complete]: ClientNotificationHandler; + [schema.CLIENT_METHODS + .auth_status_update]: ClientNotificationHandler; +}; + +/** + * ACP notification methods that can be handled by a `ClientApp`. + */ +export type ClientNotificationMethod = + keyof ClientNotificationHandlersByMethod & string; + +/** + * Agent request params keyed by ACP protocol method name. + */ +export type AgentRequestParamsByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +/** + * Agent request responses keyed by ACP protocol method name. + */ +export type AgentRequestResponsesByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; + +/** + * Agent notification params keyed by ACP protocol method name. + */ +export type AgentNotificationParamsByMethod = { + [ + Method in AgentNotificationMethod + ]: AgentNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +/** + * Client request params keyed by ACP protocol method name. + */ +export type ClientRequestParamsByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +/** + * Client request responses keyed by ACP protocol method name. + */ +export type ClientRequestResponsesByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; + +/** + * Client notification params keyed by ACP protocol method name. + */ +export type ClientNotificationParamsByMethod = { + [ + Method in ClientNotificationMethod + ]: ClientNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +function agentRequestContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): AgentRequestContext { + return { + method, + params, + requestId, + signal, + client, + }; +} + +function agentNotificationContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + method: string, +): AgentNotificationContext { + return { + method, + params, + signal, + client, + }; +} + +function clientRequestContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): ClientRequestContext { + return { + method, + params, + requestId, + signal, + agent, + }; +} + +function clientNotificationContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + method: string, +): ClientNotificationContext { + return { + method, + params, + signal, + agent, + }; +} + +type ActiveSessionUpdateQueue = { + enqueue(value: ActiveSessionMessage): void; +}; + +class SessionUpdateRouter { + private readonly activeSessions = new Map< + string, + Set + >(); + + handleMessage(message: IncomingMessage): HandleResult { + if ( + message.kind !== "notification" || + message.method !== schema.CLIENT_METHODS.session_update + ) { + return Handled.no(message); + } + + const notification = validate.zSessionNotification.parse(message.params); + const update = { + kind: "session_update", + notification, + update: notification.update, + } satisfies ActiveSessionMessage; + const activeSessions = this.activeSessions.get(notification.sessionId); + if (activeSessions && activeSessions.size > 0) { + for (const session of activeSessions) { + session.enqueue(update); + } + } + + return Handled.no(message); + } + + attach( + response: schema.NewSessionResponse, + updates: ActiveSessionUpdateQueue, + ): HandlerRegistration { + const sessions = + this.activeSessions.get(response.sessionId) ?? + new Set(); + sessions.add(updates); + this.activeSessions.set(response.sessionId, sessions); + + return new HandlerRegistration(() => { + sessions.delete(updates); + if (sessions.size === 0) { + this.activeSessions.delete(response.sessionId); + } + }); + } +} + +const sessionUpdateRouters = new WeakMap< + ConnectionContext, + SessionUpdateRouter +>(); + +function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { + let router = sessionUpdateRouters.get(cx); + if (!router) { + router = new SessionUpdateRouter(); + sessionUpdateRouters.set(cx, router); + } + return router; +} + +function runConnectHandlers( + connection: ConnectionHandle, + handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, +): void { + for (const handler of handlers) { + let result: MaybePromise; + try { + result = handler(connection); + } catch (error) { + connection.close(error); + throw error; + } + + void Promise.resolve(result).catch((error) => { + connection.close(error); + }); + } +} + +const appBuilder = Symbol("appBuilder"); +const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); +const runClientConnectHandlers = Symbol("runClientConnectHandlers"); + +type AppConnectOptions = { + readonly deferConnectHandlers?: boolean; +}; + +type AgentConnectionState = { + rawConnection: Connection; + connection: AgentConnection; +}; + +type ClientConnectionState = { + rawConnection: Connection; + connection: ClientConnection; +}; + +/** + * Creates an agent-side app. + * + * Register request and notification handlers by ACP method name, then call + * `connect(stream)` to serve an ACP client. + */ +export function agent(options?: AppOptions): AgentApp { + return new AgentApp(options); +} + +/** + * Agent-side app builder. + * + * Methods on this class register typed request or notification handlers and + * return `this`, so apps can be built with a fluent chain. Handler params are + * parsed with the generated ACP schemas before your handler runs, and thrown + * errors are converted to JSON-RPC errors by the connection layer. + */ +export class AgentApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: AgentConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + private hasInitializeHandler = false; + + constructor(options: AppOptions = {}) { + this.builder.withHandler( + agentInitializationGate(() => this.hasInitializeHandler), + ); + if (options.name) { + this.builder.name(options.name); + } + } + + /** @internal */ + [appBuilder](): ConnectionBuilder { + return this.builder; + } + + /** @internal */ + [runAgentConnectHandlers](connection: AgentConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + + /** + * Connects this agent app to a transport stream. + */ + connect(stream: Stream): AgentConnection; + /** @internal */ + connect(stream: Stream, options: AppConnectOptions): AgentConnection; + /** + * Connects this agent app directly to a client app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(client: ClientApp): AgentConnection; + connect( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnection { + return this.connectConnection(target, options).connection; + } + + /** + * Connects this agent app to a stream or client app for the lifetime of `op`. + * + * The callback receives an `AgentContext` for calling client-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | ClientApp, + op: (context: AgentContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.client)); + } + + /** + * Registers a handler that runs when this agent app opens a connection. + * + * Use this for connection-scoped work that needs to call client-side ACP + * methods outside an inbound request handler, or to set up per-connection + * state that the request handlers use. + * + * Handlers are called synchronously in registration order and are not + * awaited. A handler that throws or rejects closes the connection. When they + * are called depends on who opens the connection: + * + * - `connect(...)` and `connectWith(...)` call them before the connection + * handles its first inbound message, and so does the experimental + * `AgentProtocolRouter`'s `connect(...)` when it routes to this app. Only + * the work a handler does before its first `await` is guaranteed to come + * first. + * - The experimental `AcpServer` calls them after the client has completed + * `initialize`, so messages they send cannot replace the initialize + * response. Request handlers, including `initialize`, can run before them. + */ + onConnect(handler: AgentConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + + /** + * Registers a request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: AgentRequestHandler): this; + onRequest( + method: Method, + handler: AgentRequestHandlersByMethod[Method], + ): this; + onRequest( + method: string, + params: ParamsParser, + handler: AgentRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | AgentRequestHandlersByMethod[AgentRequestMethod] + | AgentRequestHandler + | ParamsParser, + handler?: AgentRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as AgentRequestHandler, + ); + } + if (handler) { + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = agentRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + + if (method === schema.AGENT_METHODS.initialize) { + this.hasInitializeHandler = true; + } + return this.request( + spec as AcpRequestSpec, + handlerOrParams as AgentRequestHandler, + ); + } + + /** + * Registers a notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. Serialize work yourself + * when its effects must be applied in order. + */ + onNotification(method: "*", handler: AgentNotificationHandler): this; + onNotification( + method: Method, + handler: AgentNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: string, + params: ParamsParser, + handler: AgentNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | AgentNotificationHandlersByMethod[AgentNotificationMethod] + | AgentNotificationHandler + | ParamsParser, + handler?: AgentNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as AgentNotificationHandler, + ); + } + if (handler) { + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = agentNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as AgentNotificationHandler, + ); + } + + private request( + spec: AcpRequestSpec, + handler: AgentRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + agentRequestContext( + params, + AgentContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.mapResponse, + ); + return this; + } + + private notification( + spec: AcpNotificationSpec, + handler: AgentNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + agentNotificationContext( + params, + AgentContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + + private connectConnection( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnectionState { + if (isStream(target)) { + const state = this.openStreamConnection(target); + if (!options.deferConnectHandlers) { + this[runAgentConnectHandlers](state.connection); + } + return state; + } + + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = clientConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); + try { + target[runClientConnectHandlers](peerConnection); + this[runAgentConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + + private openStreamConnection(stream: Stream): AgentConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: agentConnection(rawConnection, this.connectHandlers), + }; + } +} + +/** + * Creates a client-side app. + * + * Register request and notification handlers by ACP method name, then use + * `connectWith(...)` to run the workflow that calls agent-side methods. + */ +export function client(options?: AppOptions): ClientApp { + return new ClientApp(options); +} + +/** + * Client-side app builder. + * + * Methods on this class register typed client handlers and return `this`, so + * apps can be built with a fluent chain. `connectWith(...)` is the usual entry + * point for clients because it provides a `ClientContext` for calling + * agent-side requests and session helpers. + */ +export class ClientApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: ClientConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + + constructor(options: AppOptions = {}) { + if (options.name) { + this.builder.name(options.name); + } + this.builder.withHandler({ + handleMessage: (message, cx) => + sessionUpdateRouter(cx).handleMessage(message), + describe: () => "client-session-update-router", + }); + } + + /** @internal */ + [appBuilder](): ConnectionBuilder { + return this.builder; + } + + /** @internal */ + [runClientConnectHandlers](connection: ClientConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + + /** + * Connects this client app to a transport stream. + */ + connect(stream: Stream): ClientConnection; + /** + * Connects this client app directly to an agent app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(agent: AgentApp): ClientConnection; + connect(target: Stream | AgentApp): ClientConnection { + return this.connectConnection(target).connection; + } + + /** + * Connects this client app to a stream or agent app for the lifetime of `op`. + * + * The callback receives a `ClientContext` for calling agent-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | AgentApp, + op: (context: ClientContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.agent)); + } + + /** + * Registers a handler that runs when this client app opens a connection. + * + * Use this for connection-scoped work that needs to call agent-side ACP + * methods outside an inbound request handler. + */ + onConnect(handler: ClientConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + + /** + * Registers a client request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: ClientRequestHandler): this; + onRequest( + method: Method, + handler: ClientRequestHandlersByMethod[Method], + ): this; + onRequest( + method: string, + params: ParamsParser, + handler: ClientRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | ClientRequestHandlersByMethod[ClientRequestMethod] + | ClientRequestHandler + | ParamsParser, + handler?: ClientRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as ClientRequestHandler, + ); + } + if (handler) { + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = clientRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + + return this.request( + spec as AcpRequestSpec, + handlerOrParams as ClientRequestHandler, + ); + } + + /** + * Registers a client notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. To apply a session's + * `session/update` notifications in the order they are received, a handler + * that awaits before applying an update must serialize that work itself, for + * example by chaining it onto a per-session promise. {@link ActiveSession} + * already queues updates in arrival order. + */ + onNotification( + method: "*", + handler: ClientNotificationHandler, + ): this; + onNotification( + method: Method, + handler: ClientNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: string, + params: ParamsParser, + handler: ClientNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | ClientNotificationHandlersByMethod[ClientNotificationMethod] + | ClientNotificationHandler + | ParamsParser, + handler?: ClientNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as ClientNotificationHandler, + ); + } + if (handler) { + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = clientNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as ClientNotificationHandler, + ); + } + + private request( + spec: AcpRequestSpec, + handler: ClientRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + clientRequestContext( + params, + ClientContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.mapResponse, + ); + return this; + } + + private notification( + spec: AcpNotificationSpec, + handler: ClientNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + clientNotificationContext( + params, + ClientContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + + private connectConnection(target: Stream | AgentApp): ClientConnectionState { + if (isStream(target)) { + const state = this.openStreamConnection(target); + this[runClientConnectHandlers](state.connection); + return state; + } + + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = agentConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); + try { + target[runAgentConnectHandlers](peerConnection); + this[runClientConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + + private openStreamConnection(stream: Stream): ClientConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: clientConnection(rawConnection, this.connectHandlers), + }; + } +} + +/** + * Handle for controlling and monitoring a terminal created via `createTerminal`. + * + * Provides methods to: + * - Get current output without waiting + * - Wait for command completion + * - Kill the running command + * - Release terminal resources + * + * **Important:** Always call `release()` when done with the terminal to free resources. + + * The terminal supports async disposal via `Symbol.asyncDispose` for automatic cleanup. + + * You can use `await using` to ensure the terminal is automatically released when it + * goes out of scope. + */ +export class TerminalHandle { + /** + * Terminal identifier returned by `terminal/create`. + */ + public id: string; + private sessionId: string; + private connection: Pick; + + private constructor( + id: string, + sessionId: string, + conn: Pick, + ) { + this.id = id; + this.sessionId = sessionId; + this.connection = conn; + } + + /** @internal */ + static create( + id: string, + sessionId: string, + conn: Pick, + ): TerminalHandle { + return new TerminalHandle(id, sessionId, conn); + } + + /** + * Gets the current terminal output without waiting for the command to exit. + */ + currentOutput(): Promise { + return this.connection.sendRequest(schema.CLIENT_METHODS.terminal_output, { + sessionId: this.sessionId, + terminalId: this.id, + }); + } + + /** + * Waits for the terminal command to complete and returns its exit status. + */ + waitForExit(): Promise { + return this.connection.sendRequest( + schema.CLIENT_METHODS.terminal_wait_for_exit, + { + sessionId: this.sessionId, + terminalId: this.id, + }, + ); + } + + /** + * Kills the terminal command without releasing the terminal. + * + * The terminal remains valid after killing, allowing you to: + * - Get the final output with `currentOutput()` + * - Check the exit status + * - Release the terminal when done + * + * Useful for implementing timeouts or cancellation. + */ + kill(): Promise { + return this.connection.sendRequest< + schema.KillTerminalRequest, + schema.KillTerminalResponse + >( + schema.CLIENT_METHODS.terminal_kill, + { + sessionId: this.sessionId, + terminalId: this.id, + }, + emptyObjectResponse, + ); + } + + /** + * Releases the terminal and frees all associated resources. + * + * If the command is still running, it will be killed. + * After release, the terminal ID becomes invalid and cannot be used + * with other terminal methods. + * + * Tool calls that already reference this terminal will continue to + * display its output. + * + * **Important:** Always call this method when done with the terminal. + */ + release(): Promise { + return this.connection.sendRequest< + schema.ReleaseTerminalRequest, + schema.ReleaseTerminalResponse | void + >( + schema.CLIENT_METHODS.terminal_release, + { + sessionId: this.sessionId, + terminalId: this.id, + }, + emptyObjectResponse, + ); + } + + /** + * Releases the terminal when used with `await using`. + */ + async [Symbol.asyncDispose](): Promise { + await this.release(); + } +} diff --git a/src/v1/methods.ts b/src/v1/methods.ts new file mode 100644 index 00000000..43b7ccd1 --- /dev/null +++ b/src/v1/methods.ts @@ -0,0 +1,75 @@ +import * as schema from "./unstable/schema/index.js"; + +/** + * ACP method-name constants. + * + * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and + * `notify(...)` when you want literal-string type inference without spelling + * protocol strings inline. + */ +export const methods = { + agent: { + initialize: schema.AGENT_METHODS.initialize, + authenticate: schema.AGENT_METHODS.authenticate, + logout: schema.AGENT_METHODS.logout, + auth: { + status: schema.AGENT_METHODS.auth_status, + }, + providers: { + list: schema.AGENT_METHODS.providers_list, + set: schema.AGENT_METHODS.providers_set, + disable: schema.AGENT_METHODS.providers_disable, + }, + session: { + new: schema.AGENT_METHODS.session_new, + load: schema.AGENT_METHODS.session_load, + list: schema.AGENT_METHODS.session_list, + delete: schema.AGENT_METHODS.session_delete, + fork: schema.AGENT_METHODS.session_fork, + archive: schema.AGENT_METHODS.session_archive, + unarchive: schema.AGENT_METHODS.session_unarchive, + status: schema.AGENT_METHODS.session_status, + options: schema.AGENT_METHODS.session_options, + setTitle: schema.AGENT_METHODS.session_set_title, + resume: schema.AGENT_METHODS.session_resume, + close: schema.AGENT_METHODS.session_close, + setMode: schema.AGENT_METHODS.session_set_mode, + setConfigOption: schema.AGENT_METHODS.session_set_config_option, + prompt: schema.AGENT_METHODS.session_prompt, + cancel: schema.AGENT_METHODS.session_cancel, + }, + mcp: { + message: schema.AGENT_METHODS.mcp_message, + }, + }, + client: { + session: { + requestPermission: schema.CLIENT_METHODS.session_request_permission, + update: schema.CLIENT_METHODS.session_update, + }, + fs: { + writeTextFile: schema.CLIENT_METHODS.fs_write_text_file, + readTextFile: schema.CLIENT_METHODS.fs_read_text_file, + }, + terminal: { + create: schema.CLIENT_METHODS.terminal_create, + output: schema.CLIENT_METHODS.terminal_output, + release: schema.CLIENT_METHODS.terminal_release, + waitForExit: schema.CLIENT_METHODS.terminal_wait_for_exit, + kill: schema.CLIENT_METHODS.terminal_kill, + }, + mcp: { + message: schema.CLIENT_METHODS.mcp_message, + }, + elicitation: { + create: schema.CLIENT_METHODS.elicitation_create, + complete: schema.CLIENT_METHODS.elicitation_complete, + }, + auth: { + statusUpdate: schema.CLIENT_METHODS.auth_status_update, + }, + }, + protocol: { + cancelRequest: schema.PROTOCOL_METHODS.cancel_request, + }, +} as const; diff --git a/src/v1/stable/acp.ts b/src/v1/stable/acp.ts index 266dab60..ea64d1a8 100644 --- a/src/v1/stable/acp.ts +++ b/src/v1/stable/acp.ts @@ -1,17 +1,14 @@ // Generated from src/v1/acp.ts. Do not edit directly. -// V1 binding implementation, specialized against stable schemas by generate.js. -import * as schema from "../schema/index.js"; -import * as validate from "../schema/zod.gen.js"; import type { AnyMessage } from "../../core/jsonrpc.js"; import { ndJsonStream as createJsonStream } from "../../core/stream.js"; +import type { NdJsonStreamOptions } from "../../core/stream.js"; +// Keep module initialization behind re-exports so a consumer pays only for +// the bindings, method table, or guards it actually uses. +export * from "./bindings.js"; +export { methods } from "./methods.js"; export type * from "../schema/types.gen.js"; -// Runtime narrowing helpers for extensible unions, exposed as companion values -// that merge (declaration merging) with the like-named types — e.g. -// `CreateElicitationResponse.isAccept(response)`. See schema/guards.gen.ts. -// -// Listed explicitly (not `export *`) so each value+type pair merges rather than -// colliding with the `export type *` above. The guards.gen re-export test -// asserts this list stays in sync as new extensible unions are added. +// List guards explicitly so their value/type pairs merge rather than colliding +// with the type exports above. The guards.gen re-export test checks this list. export { CreateElicitationRequest, CreateElicitationResponse, @@ -59,6 +56,7 @@ export { MessageTooLargeError, } from "../../core/stream-limits.js"; export type { NdJsonStreamOptions } from "../../core/stream.js"; +export type { ParamsParser } from "../../core/app-handlers.js"; export type { AgentConnectOptions, AgentConnectionLifecycle, @@ -75,2223 +73,3 @@ export type { Result, SendRequestOptions, } from "../../core/jsonrpc.js"; -import type { NdJsonStreamOptions } from "../../core/stream.js"; -import { - parseParams, - registerAppNotification, - registerAppRequest, -} from "../../core/app-handlers.js"; -import type { ParamsParser } from "../../core/app-handlers.js"; -export type { ParamsParser } from "../../core/app-handlers.js"; -import { connectionContextOf } from "../../core/connection-access.js"; -import { - Connection, - Handled, - HandlerRegistration, - RequestError, - RequestResponder, - treatSessionNotFoundAsSuccess, -} from "../../core/jsonrpc.js"; -import type { - ConnectionBuilder, - ConnectionContext, - HandleResult, - IncomingMessage, - JsonRpcId, - JsonRpcHandler, - MaybePromise, - SendRequestOptions, -} from "../../core/jsonrpc.js"; -const initializedConnections = new WeakSet(); -/** - * Rejects requests other than `initialize` with `-32600` until an `initialize` - * request has been answered successfully. `initialize` itself may be sent - * again at any time, as before. - */ -function agentInitializationGate(enabled: () => boolean): JsonRpcHandler { - return { - handleMessage(message, cx) { - if ( - message.kind !== "request" || - !enabled() || - initializedConnections.has(cx) - ) { - return Handled.no(message); - } - if (message.method !== schema.AGENT_METHODS.initialize) { - return message.responder - .respondWithError( - RequestError.invalidRequest( - undefined, - `ACP connection must be initialized before '${message.method}'`, - ), - ) - .then(() => Handled.yes()); - } - const { responder } = message; - return Handled.no({ - ...message, - responder: new RequestResponder( - responder.id, - (result) => { - // Record success before the response goes out, so the client's - // next request is never rejected. - if ("result" in result) { - initializedConnections.add(cx); - } - return responder.respondWithResult(result); - }, - responder.signal, - ), - }); - }, - describe: () => "agent-initialization", - }; -} -function emptyObjectResponse(response: T | null | undefined | void): T { - return response ?? ({} as T); -} -function isStream(value: unknown): value is Stream { - return ( - typeof value === "object" && - value !== null && - "readable" in value && - "writable" in value - ); -} -function memoryStreamPair(): [Stream, Stream] { - const leftToRight = new TransformStream(); - const rightToLeft = new TransformStream(); - return [ - { - readable: rightToLeft.readable, - writable: leftToRight.writable, - }, - { - readable: leftToRight.readable, - writable: rightToLeft.writable, - }, - ]; -} -/** - * ACP method-name constants. - * - * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and - * `notify(...)` when you want literal-string type inference without spelling - * protocol strings inline. - */ -export const methods = { - agent: { - initialize: schema.AGENT_METHODS.initialize, - authenticate: schema.AGENT_METHODS.authenticate, - logout: schema.AGENT_METHODS.logout, - session: { - new: schema.AGENT_METHODS.session_new, - load: schema.AGENT_METHODS.session_load, - list: schema.AGENT_METHODS.session_list, - delete: schema.AGENT_METHODS.session_delete, - resume: schema.AGENT_METHODS.session_resume, - close: schema.AGENT_METHODS.session_close, - setMode: schema.AGENT_METHODS.session_set_mode, - setConfigOption: schema.AGENT_METHODS.session_set_config_option, - prompt: schema.AGENT_METHODS.session_prompt, - cancel: schema.AGENT_METHODS.session_cancel, - }, - }, - client: { - session: { - requestPermission: schema.CLIENT_METHODS.session_request_permission, - update: schema.CLIENT_METHODS.session_update, - }, - fs: { - writeTextFile: schema.CLIENT_METHODS.fs_write_text_file, - readTextFile: schema.CLIENT_METHODS.fs_read_text_file, - }, - terminal: { - create: schema.CLIENT_METHODS.terminal_create, - output: schema.CLIENT_METHODS.terminal_output, - release: schema.CLIENT_METHODS.terminal_release, - waitForExit: schema.CLIENT_METHODS.terminal_wait_for_exit, - kill: schema.CLIENT_METHODS.terminal_kill, - }, - elicitation: { - create: schema.CLIENT_METHODS.elicitation_create, - complete: schema.CLIENT_METHODS.elicitation_complete, - }, - }, - protocol: { - cancelRequest: schema.PROTOCOL_METHODS.cancel_request, - }, -} as const; -const startActiveSession = Symbol("startActiveSession"); -/** - * Active ACP connection returned by `AgentApp.connect(...)` and - * `ClientApp.connect(...)`. - * - * Use this handle when you need a connection to stay open independently of a - * single `connectWith(...)` operation. - */ -export interface AcpConnection { - /** - * AbortSignal that aborts when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after the signal aborts. - */ - readonly signal: AbortSignal; - /** - * Promise that resolves when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after this resolves. - */ - readonly closed: Promise; - /** - * Closes the connection and rejects pending requests. Messages received but - * not yet dispatched are dropped. Does nothing once the connection is closed. - */ - close(error?: unknown): void; -} -/** - * Agent-side connection returned by `AgentApp.connect(...)`. - * - * Use `client` to call client-side ACP methods for the lifetime of the - * connection. - */ -export interface AgentConnection extends AcpConnection { - /** - * Context for calling client-side ACP methods. - */ - readonly client: AgentContext; -} -/** - * Client-side connection returned by `ClientApp.connect(...)`. - * - * Use `agent` to call agent-side ACP methods and session helpers for the - * lifetime of the connection. - */ -export interface ClientConnection extends AcpConnection { - /** - * Context for calling agent-side ACP methods. - */ - readonly agent: ClientContext; -} -class AcpContext { - /** @internal */ - constructor( - private readonly cx: ConnectionContext, - private readonly currentRequestId?: JsonRpcId, - ) {} - /** - * JSON-RPC id of the request currently being handled. - * - * This is `undefined` for notification handlers and for contexts created - * outside an inbound request, such as `connect(...)` and `connectWith(...)`. - */ - get requestId(): JsonRpcId | undefined { - return this.currentRequestId; - } - /** @internal */ - protected get connectionContext(): ConnectionContext { - return this.cx; - } - /** @hidden SDK helpers use this to identify the connection. */ - [connectionContextOf](): ConnectionContext { - return this.cx; - } - /** @internal */ - protected sendRequest( - method: string, - params?: Req, - mapResponse?: (response: Resp) => Output, - options?: SendRequestOptions, - ): Promise { - return this.cx.sendRequest(method, params, mapResponse, options); - } - /** @internal */ - protected sendNotification(method: string, params?: N): Promise { - return this.cx.sendNotification(method, params); - } - /** @internal */ - protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { - return this.cx.addDynamicHandler(handler); - } -} -/** - * Context passed to agent-side handlers. - * - * Agents use this context to call client-side ACP methods while handling - * requests such as `session/prompt`. - */ -export class AgentContext extends AcpContext { - private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { - super(cx, requestId); - } - /** @internal */ - static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { - return new AgentContext(cx, requestId); - } - /** - * Executes a command in a new client terminal. - * - * Returns a handle for reading output, waiting for exit, killing the command, - * and releasing the terminal. Check the client's terminal capability first. - * Use `await using` or call `release()` when finished. - */ - async createTerminal( - params: schema.CreateTerminalRequest, - options?: SendRequestOptions, - ): Promise { - const response = await this.request( - schema.CLIENT_METHODS.terminal_create, - params, - options, - ); - return TerminalHandle.create( - response.terminalId, - params.sessionId, - this.connectionContext, - ); - } - /** - * Sends a request to the client by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - */ - request( - method: Method, - params: ClientRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - const spec = clientRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - return this.sendRequest(method, params, spec?.mapResponse, options); - } - /** - * Sends a notification to the client by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: ClientNotificationParamsByMethod[Method], - ): Promise; - notify(method: string, params?: Params): Promise; - notify(method: string, params?: unknown): Promise { - return this.sendNotification(method, params); - } -} -/** - * Context used by clients to call agent-side ACP methods. - * - * `connectWith` passes a `ClientContext` to the callback. Client handlers also - * receive one as `ctx.agent` when they need to call back into the agent. - */ -export class ClientContext extends AcpContext { - private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { - super(cx, requestId); - } - /** @internal */ - static create(cx: ConnectionContext, requestId?: JsonRpcId): ClientContext { - return new ClientContext(cx, requestId); - } - /** @internal */ - [startActiveSession]( - params: schema.NewSessionRequest, - options?: SendRequestOptions, - ): Promise { - return this.sendRequest< - schema.NewSessionRequest, - schema.NewSessionResponse, - ActiveSession - >( - schema.AGENT_METHODS.session_new, - params, - (response) => this.attachSession(response), - options, - ); - } - /** - * Creates a builder for starting and observing an ACP session. - * - * Pass a string for the common case where only `cwd` is needed, or pass a - * full `NewSessionRequest` when you need MCP servers, `_meta`, or additional - * session fields. - */ - buildSession(cwd: string): SessionBuilder; - buildSession(request: schema.NewSessionRequest): SessionBuilder; - buildSession( - cwdOrRequest: string | schema.NewSessionRequest, - ): SessionBuilder { - if (typeof cwdOrRequest === "string") { - return SessionBuilder.create(this, { - cwd: cwdOrRequest, - mcpServers: [], - }); - } - return SessionBuilder.create(this, cwdOrRequest); - } - /** - * Builds active-session helpers around a `session/new` response. - */ - private attachSession(response: schema.NewSessionResponse): ActiveSession { - const updates = new AsyncQueue(); - const closeSignal = this.connectionContext.signal; - const failUpdatesOnClose = () => { - updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); - }; - if (closeSignal.aborted) { - failUpdatesOnClose(); - } else { - closeSignal.addEventListener("abort", failUpdatesOnClose); - } - const sessionRegistration = sessionUpdateRouter( - this.connectionContext, - ).attach(response, updates); - const closeRegistration = new HandlerRegistration(() => { - closeSignal.removeEventListener("abort", failUpdatesOnClose); - }); - return ActiveSession.create(this, response, updates, [ - sessionRegistration, - closeRegistration, - ]); - } - /** - * Sends a request to the agent by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - * - * Closing or deleting a session is idempotent: a `-32002` (Resource not - * found) response to `session/close` or `session/delete` resolves with an - * empty result instead of rejecting. - */ - request( - method: Method, - params: AgentRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - const spec = agentRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - return treatSessionNotFoundAsSuccess( - method, - this.sendRequest(method, params, spec?.mapResponse, options), - () => (spec?.mapResponse ? spec.mapResponse({}) : {}), - ); - } - /** - * Sends a notification to the agent by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: AgentNotificationParamsByMethod[Method], - ): Promise; - notify(method: string, params?: Params): Promise; - notify(method: string, params?: unknown): Promise { - return this.sendNotification(method, params); - } -} -class AcpConnectionHandle implements AcpConnection { - constructor(private readonly connection: Connection) {} - get signal(): AbortSignal { - return this.connection.signal; - } - get closed(): Promise { - return this.connection.closed; - } - close(error?: unknown): void { - this.connection.close(error); - } -} -class AgentConnectionHandle - extends AcpConnectionHandle - implements AgentConnection -{ - readonly client: AgentContext; - private didStartConnectHandlers = false; - constructor( - connection: Connection, - private readonly connectHandlers: readonly AgentConnectHandler[] = [], - ) { - super(connection); - this.client = AgentContext.create(connection.getContext()); - } - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} -class ClientConnectionHandle - extends AcpConnectionHandle - implements ClientConnection -{ - readonly agent: ClientContext; - private didStartConnectHandlers = false; - constructor( - connection: Connection, - private readonly connectHandlers: readonly ClientConnectHandler[] = [], - ) { - super(connection); - this.agent = ClientContext.create(connection.getContext()); - } - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} -function agentConnection( - connection: Connection, - connectHandlers: readonly AgentConnectHandler[] = [], -): AgentConnection { - return new AgentConnectionHandle(connection, connectHandlers); -} -function clientConnection( - connection: Connection, - connectHandlers: readonly ClientConnectHandler[] = [], -): ClientConnection { - return new ClientConnectionHandle(connection, connectHandlers); -} -type AsyncQueueEntry = - | { - kind: "value"; - value: T; - } - | { - kind: "error"; - error: unknown; - }; -class AsyncQueue { - private values: Array> = []; - private waiters: Array<{ - resolve: (value: T) => void; - reject: (error: unknown) => void; - }> = []; - private failed = false; - private failure: unknown; - enqueue(value: T): void { - if (this.failed) { - return; - } - const waiter = this.waiters.shift(); - if (waiter) { - waiter.resolve(value); - } else { - this.values.push({ kind: "value", value }); - } - } - reject(error: unknown): void { - if (this.failed) { - return; - } - if (this.waiters.length > 0) { - for (const waiter of this.waiters.splice(0)) { - waiter.reject(error); - } - return; - } - this.values.push({ kind: "error", error }); - } - clearErrors(): void { - this.values = this.values.filter((entry) => entry.kind === "value"); - } - fail(error: unknown): void { - if (this.failed) { - return; - } - this.failed = true; - this.failure = error; - for (const waiter of this.waiters.splice(0)) { - waiter.reject(error); - } - } - next(): Promise { - if (this.values.length > 0) { - const entry = this.values.shift() as AsyncQueueEntry; - if (entry.kind === "error") { - return Promise.reject(entry.error); - } - return Promise.resolve(entry.value); - } - if (this.failed) { - return Promise.reject(this.failure); - } - return new Promise((resolve, reject) => { - this.waiters.push({ resolve, reject }); - }); - } -} -function cloneNewSessionRequest( - request: schema.NewSessionRequest, -): schema.NewSessionRequest { - return { - ...request, - additionalDirectories: request.additionalDirectories - ? [...request.additionalDirectories] - : undefined, - mcpServers: [...request.mcpServers], - }; -} -/** - * Message produced by an `ActiveSession`. - * - * `session_update` messages expose the typed `session/update` notification and - * `stop` messages report the final `session/prompt` response. A prompt turn is - * complete once a `stop` message is returned. - */ -export type ActiveSessionMessage = - | { - /** - * Indicates that this message came from a `session/update` notification. - */ - kind: "session_update"; - /** - * Full notification sent by the agent. - */ - notification: schema.SessionNotification; - /** - * Convenience alias for `notification.update`. - */ - update: schema.SessionUpdate; - } - | { - /** - * Indicates that the prompt turn has completed. - */ - kind: "stop"; - /** - * Final response from `session/prompt`. - */ - response: schema.PromptResponse; - /** - * Convenience alias for `response.stopReason`. - */ - stopReason: schema.StopReason; - }; -/** - * Builder for creating an `ActiveSession`. - * - * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or - * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session - * needs MCP servers, `_meta`, or additional request fields. All paths in ACP - * payloads should be absolute. - */ -export class SessionBuilder { - private request: schema.NewSessionRequest; - private constructor( - private cx: ClientContext, - request: schema.NewSessionRequest, - ) { - this.request = cloneNewSessionRequest(request); - } - /** @internal */ - static create( - cx: ClientContext, - request: schema.NewSessionRequest, - ): SessionBuilder { - return new SessionBuilder(cx, request); - } - /** - * Returns the `session/new` request that will be sent. - * - * The returned object is a defensive copy, so mutating it does not change the - * builder. - */ - toRequest(): schema.NewSessionRequest { - return cloneNewSessionRequest(this.request); - } - /** - * Replaces the additional workspace roots for this session. - * - * `additionalDirectories` expand the session's file-system scope without - * changing `cwd`. Each path should be absolute. - */ - withAdditionalDirectories(additionalDirectories: string[]): this { - this.request = { - ...this.request, - additionalDirectories: [...additionalDirectories], - }; - return this; - } - /** - * Adds one MCP server to the `session/new` request. - */ - withMcpServer(mcpServer: schema.McpServer): this { - this.request = { - ...this.request, - mcpServers: [...this.request.mcpServers, mcpServer], - }; - return this; - } - /** - * Starts the session and returns an `ActiveSession` for prompting and reading - * updates. - * - * Call `dispose()` on the returned session when you no longer need update - * routing, or use `withSession(...)` to scope disposal automatically. - */ - async start(options?: SendRequestOptions): Promise { - return this.cx[startActiveSession](this.toRequest(), options); - } - /** - * Starts the session, runs `op`, and disposes the active-session update - * routing when `op` finishes or throws. - */ - async withSession( - op: (session: ActiveSession) => MaybePromise, - ): Promise { - const session = await this.start(); - try { - return await op(session); - } finally { - session.dispose(); - } - } -} -/** - * Convenience wrapper for an active ACP session. - * - * An active session routes `session/update` notifications for one session ID - * into an async queue. Use `prompt(...)` to send user content, then read updates - * with `nextUpdate()` until a `stop` message is returned. - */ -export class ActiveSession { - private constructor( - private cx: ClientContext, - private sessionResponse: schema.NewSessionResponse, - private updates: { - enqueue(value: ActiveSessionMessage): void; - reject(error: unknown): void; - clearErrors(): void; - fail(error: unknown): void; - next(): Promise; - }, - private registrations: HandlerRegistration[], - ) {} - /** @internal */ - static create( - cx: ClientContext, - sessionResponse: schema.NewSessionResponse, - updates: { - enqueue(value: ActiveSessionMessage): void; - reject(error: unknown): void; - clearErrors(): void; - fail(error: unknown): void; - next(): Promise; - }, - registrations: HandlerRegistration[], - ): ActiveSession { - return new ActiveSession(cx, sessionResponse, updates, registrations); - } - /** - * Session ID returned by `session/new`. - */ - get sessionId(): schema.SessionId { - return this.sessionResponse.sessionId; - } - /** - * Mode state returned when the session was created, if the agent provided it. - */ - get modes(): schema.SessionModeState | null | undefined { - return this.sessionResponse.modes; - } - /** - * Metadata returned when the session was created. - */ - get meta(): - | { - [key: string]: unknown; - } - | null - | undefined { - return this.sessionResponse._meta; - } - /** - * Full response returned by `session/new`. - */ - get newSessionResponse(): schema.NewSessionResponse { - return this.sessionResponse; - } - /** - * Sends a prompt to this session. - * - * Strings are converted to one text content block. A single content block is - * wrapped in an array. The returned promise resolves with the final - * `PromptResponse`, and the same completion is also queued as a `stop` - * message for `nextUpdate()`. - */ - prompt( - prompt: string | schema.ContentBlock | Array, - options?: SendRequestOptions, - ): Promise { - this.updates.clearErrors(); - const response = this.cx.request( - schema.AGENT_METHODS.session_prompt, - { - sessionId: this.sessionId, - prompt: this.promptBlocks(prompt), - }, - options, - ); - void response.then( - (value) => { - this.updates.enqueue({ - kind: "stop", - response: value, - stopReason: value.stopReason, - }); - }, - (error) => { - this.updates.reject(error); - }, - ); - return response; - } - /** - * Reads the next update or stop message for this session. - */ - nextUpdate(): Promise { - return this.updates.next(); - } - /** - * Reads text chunks until the current prompt turn stops. - * - * Only `agent_message_chunk` updates with text content are appended. Other - * update types are ignored by this helper; use `nextUpdate()` when you need - * tool calls, plans, or the final `PromptResponse`. - */ - async readText(): Promise { - let output = ""; - for (;;) { - const message = await this.nextUpdate(); - if (message.kind === "stop") { - return output; - } - const { update } = message; - if ( - update.sessionUpdate === "agent_message_chunk" && - update.content.type === "text" - ) { - output += update.content.text; - } - } - } - /** - * Stops routing updates to this active-session helper. - * - * This does not close the ACP session on the agent. Use `ClientContext` - * session lifecycle methods when the protocol session itself should be closed - * or deleted. - */ - dispose(): void { - for (const registration of this.registrations.splice(0)) { - registration.dispose(); - } - this.updates.fail(new Error("Active session disposed")); - } - /** - * Supports explicit resource management with `using`. - */ - [Symbol.dispose](): void { - this.dispose(); - } - private promptBlocks( - prompt: string | schema.ContentBlock | Array, - ): Array { - if (typeof prompt === "string") { - return [{ type: "text", text: prompt }]; - } - if (Array.isArray(prompt)) { - return prompt; - } - return [prompt]; - } -} -/** - * Options used when creating an ACP app. - */ -export type AppOptions = { - /** - * Human-readable name used in JSON-RPC handler descriptions and diagnostics. - */ - name?: string; -}; -/** - * Common context passed to agent-side handlers. - */ -export type AgentHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed client context for calling client-side ACP methods. - */ - client: AgentContext; -}; -/** - * Context passed to agent-side request handlers. - */ -export type AgentRequestContext = AgentHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; -/** - * Context passed to agent-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type AgentNotificationContext = AgentHandlerContext; -/** - * Common context passed to client-side handlers. - */ -export type ClientHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed agent context for calling agent-side ACP methods. - */ - agent: ClientContext; -}; -/** - * Context passed to client-side request handlers. - */ -export type ClientRequestContext = ClientHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; -/** - * Context passed to client-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type ClientNotificationContext = ClientHandlerContext; -/** - * Request handler registered on an `AgentApp`. - */ -export type AgentRequestHandler = ( - context: AgentRequestContext, -) => MaybePromise; -/** - * Notification handler registered on an `AgentApp`. - */ -export type AgentNotificationHandler = ( - context: AgentNotificationContext, -) => MaybePromise; -/** - * Request handler registered on a `ClientApp`. - */ -export type ClientRequestHandler = ( - context: ClientRequestContext, -) => MaybePromise; -/** - * Notification handler registered on a `ClientApp`. - */ -export type ClientNotificationHandler = ( - context: ClientNotificationContext, -) => MaybePromise; -/** - * Handler called when an `AgentApp` opens a connection. - */ -export type AgentConnectHandler = ( - connection: AgentConnection, -) => MaybePromise; -/** - * Handler called when a `ClientApp` opens a connection. - */ -export type ClientConnectHandler = ( - connection: ClientConnection, -) => MaybePromise; -type AcpRequestSpec = { - method: string; - params?: ParamsParser; - mapResponse?: (response: Response) => WireResponse; -}; -type AcpNotificationSpec = { - method: string; - params?: ParamsParser; -}; -function requestSpec( - method: string, - params: ParamsParser, - mapResponse?: (response: Response) => WireResponse, -): AcpRequestSpec { - return { - method, - // Match Rust's empty-payload handling without bypassing required fields. - params: (value) => parseParams(params, value ?? {}), - mapResponse, - }; -} -function notificationSpec( - method: string, - params: ParamsParser, -): AcpNotificationSpec { - return { method, params }; -} -function specsByMethod< - T extends Record< - string, - { - method: string; - } - >, ->(specs: T): Record { - const byMethod: Record = {}; - for (const spec of Object.values(specs) as Array) { - byMethod[spec.method] = spec; - } - return byMethod; -} -const agentRequestSpecs = { - initialize: requestSpec( - schema.AGENT_METHODS.initialize, - validate.zInitializeRequest, - ), - newSession: requestSpec( - schema.AGENT_METHODS.session_new, - validate.zNewSessionRequest, - ), - loadSession: requestSpec< - schema.LoadSessionRequest, - schema.LoadSessionResponse | void, - schema.LoadSessionResponse - >( - schema.AGENT_METHODS.session_load, - validate.zLoadSessionRequest, - emptyObjectResponse, - ), - listSessions: requestSpec< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >(schema.AGENT_METHODS.session_list, validate.zListSessionsRequest), - deleteSession: requestSpec< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void, - schema.DeleteSessionResponse - >( - schema.AGENT_METHODS.session_delete, - validate.zDeleteSessionRequest, - emptyObjectResponse, - ), - resumeSession: requestSpec< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >(schema.AGENT_METHODS.session_resume, validate.zResumeSessionRequest), - closeSession: requestSpec< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void, - schema.CloseSessionResponse - >( - schema.AGENT_METHODS.session_close, - validate.zCloseSessionRequest, - emptyObjectResponse, - ), - setSessionMode: requestSpec< - schema.SetSessionModeRequest, - schema.SetSessionModeResponse | void, - schema.SetSessionModeResponse - >( - schema.AGENT_METHODS.session_set_mode, - validate.zSetSessionModeRequest, - emptyObjectResponse, - ), - setSessionConfigOption: requestSpec< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >( - schema.AGENT_METHODS.session_set_config_option, - validate.zSetSessionConfigOptionRequest, - ), - authenticate: requestSpec< - schema.AuthenticateRequest, - schema.AuthenticateResponse | void, - schema.AuthenticateResponse - >( - schema.AGENT_METHODS.authenticate, - validate.zAuthenticateRequest, - emptyObjectResponse, - ), - logout: requestSpec< - schema.LogoutRequest, - schema.LogoutResponse | void, - schema.LogoutResponse - >(schema.AGENT_METHODS.logout, validate.zLogoutRequest, emptyObjectResponse), - prompt: requestSpec( - schema.AGENT_METHODS.session_prompt, - validate.zPromptRequest, - ), -}; -const agentNotificationSpecs = { - cancel: notificationSpec( - schema.AGENT_METHODS.session_cancel, - validate.zCancelNotification, - ), -}; -const clientRequestSpecs = { - requestPermission: requestSpec< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >( - schema.CLIENT_METHODS.session_request_permission, - validate.zRequestPermissionRequest, - ), - writeTextFile: requestSpec< - schema.WriteTextFileRequest, - schema.WriteTextFileResponse | void, - schema.WriteTextFileResponse - >( - schema.CLIENT_METHODS.fs_write_text_file, - validate.zWriteTextFileRequest, - emptyObjectResponse, - ), - readTextFile: requestSpec< - schema.ReadTextFileRequest, - schema.ReadTextFileResponse - >(schema.CLIENT_METHODS.fs_read_text_file, validate.zReadTextFileRequest), - createTerminal: requestSpec< - schema.CreateTerminalRequest, - schema.CreateTerminalResponse - >(schema.CLIENT_METHODS.terminal_create, validate.zCreateTerminalRequest), - terminalOutput: requestSpec< - schema.TerminalOutputRequest, - schema.TerminalOutputResponse - >(schema.CLIENT_METHODS.terminal_output, validate.zTerminalOutputRequest), - releaseTerminal: requestSpec< - schema.ReleaseTerminalRequest, - schema.ReleaseTerminalResponse | void, - schema.ReleaseTerminalResponse - >( - schema.CLIENT_METHODS.terminal_release, - validate.zReleaseTerminalRequest, - emptyObjectResponse, - ), - waitForTerminalExit: requestSpec< - schema.WaitForTerminalExitRequest, - schema.WaitForTerminalExitResponse - >( - schema.CLIENT_METHODS.terminal_wait_for_exit, - validate.zWaitForTerminalExitRequest, - ), - killTerminal: requestSpec< - schema.KillTerminalRequest, - schema.KillTerminalResponse | void, - schema.KillTerminalResponse - >( - schema.CLIENT_METHODS.terminal_kill, - validate.zKillTerminalRequest, - emptyObjectResponse, - ), - createElicitation: requestSpec< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >( - schema.CLIENT_METHODS.elicitation_create, - validate.zCreateElicitationRequest, - ), -}; -const clientNotificationSpecs = { - sessionUpdate: notificationSpec( - schema.CLIENT_METHODS.session_update, - validate.zSessionNotification, - ), - completeElicitation: notificationSpec( - schema.CLIENT_METHODS.elicitation_complete, - validate.zCompleteElicitationNotification, - ), -}; -const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); -const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); -const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); -const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); -/** - * Agent request handlers keyed by ACP protocol method name. - */ -export type AgentRequestHandlersByMethod = { - /** - * Handles `initialize`. - * - * Registering this handler makes the app reject other requests with - * `-32600` until an `initialize` request has been answered successfully. - */ - [schema.AGENT_METHODS.initialize]: AgentRequestHandler< - schema.InitializeRequest, - schema.InitializeResponse - >; - [schema.AGENT_METHODS.session_new]: AgentRequestHandler< - schema.NewSessionRequest, - schema.NewSessionResponse - >; - [schema.AGENT_METHODS.session_load]: AgentRequestHandler< - schema.LoadSessionRequest, - schema.LoadSessionResponse | void - >; - [schema.AGENT_METHODS.session_list]: AgentRequestHandler< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >; - [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void - >; - [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >; - [schema.AGENT_METHODS.session_close]: AgentRequestHandler< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void - >; - [schema.AGENT_METHODS.session_set_mode]: AgentRequestHandler< - schema.SetSessionModeRequest, - schema.SetSessionModeResponse | void - >; - [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >; - [schema.AGENT_METHODS.authenticate]: AgentRequestHandler< - schema.AuthenticateRequest, - schema.AuthenticateResponse | void - >; - [schema.AGENT_METHODS.logout]: AgentRequestHandler< - schema.LogoutRequest, - schema.LogoutResponse | void - >; - [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< - schema.PromptRequest, - schema.PromptResponse - >; -}; -/** - * ACP request methods that can be handled by an `AgentApp`. - */ -export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; -/** - * Agent notification handlers keyed by ACP protocol method name. - */ -export type AgentNotificationHandlersByMethod = { - [schema.AGENT_METHODS - .session_cancel]: AgentNotificationHandler; -}; -/** - * ACP notification methods that can be handled by an `AgentApp`. - */ -export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & - string; -/** - * Client request handlers keyed by ACP protocol method name. - */ -export type ClientRequestHandlersByMethod = { - [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >; - [schema.CLIENT_METHODS.fs_write_text_file]: ClientRequestHandler< - schema.WriteTextFileRequest, - schema.WriteTextFileResponse | void - >; - [schema.CLIENT_METHODS.fs_read_text_file]: ClientRequestHandler< - schema.ReadTextFileRequest, - schema.ReadTextFileResponse - >; - [schema.CLIENT_METHODS.terminal_create]: ClientRequestHandler< - schema.CreateTerminalRequest, - schema.CreateTerminalResponse - >; - [schema.CLIENT_METHODS.terminal_output]: ClientRequestHandler< - schema.TerminalOutputRequest, - schema.TerminalOutputResponse - >; - [schema.CLIENT_METHODS.terminal_release]: ClientRequestHandler< - schema.ReleaseTerminalRequest, - schema.ReleaseTerminalResponse | void - >; - [schema.CLIENT_METHODS.terminal_wait_for_exit]: ClientRequestHandler< - schema.WaitForTerminalExitRequest, - schema.WaitForTerminalExitResponse - >; - [schema.CLIENT_METHODS.terminal_kill]: ClientRequestHandler< - schema.KillTerminalRequest, - schema.KillTerminalResponse | void - >; - [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >; -}; -/** - * ACP request methods that can be handled by a `ClientApp`. - */ -export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; -/** - * Client notification handlers keyed by ACP protocol method name. - */ -export type ClientNotificationHandlersByMethod = { - [schema.CLIENT_METHODS - .session_update]: ClientNotificationHandler; - [schema.CLIENT_METHODS - .elicitation_complete]: ClientNotificationHandler; -}; -/** - * ACP notification methods that can be handled by a `ClientApp`. - */ -export type ClientNotificationMethod = - keyof ClientNotificationHandlersByMethod & string; -/** - * Agent request params keyed by ACP protocol method name. - */ -export type AgentRequestParamsByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -/** - * Agent request responses keyed by ACP protocol method name. - */ -export type AgentRequestResponsesByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; -/** - * Agent notification params keyed by ACP protocol method name. - */ -export type AgentNotificationParamsByMethod = { - [ - Method in AgentNotificationMethod - ]: AgentNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -/** - * Client request params keyed by ACP protocol method name. - */ -export type ClientRequestParamsByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -/** - * Client request responses keyed by ACP protocol method name. - */ -export type ClientRequestResponsesByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; -/** - * Client notification params keyed by ACP protocol method name. - */ -export type ClientNotificationParamsByMethod = { - [ - Method in ClientNotificationMethod - ]: ClientNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -function agentRequestContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): AgentRequestContext { - return { - method, - params, - requestId, - signal, - client, - }; -} -function agentNotificationContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - method: string, -): AgentNotificationContext { - return { - method, - params, - signal, - client, - }; -} -function clientRequestContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): ClientRequestContext { - return { - method, - params, - requestId, - signal, - agent, - }; -} -function clientNotificationContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - method: string, -): ClientNotificationContext { - return { - method, - params, - signal, - agent, - }; -} -type ActiveSessionUpdateQueue = { - enqueue(value: ActiveSessionMessage): void; -}; -class SessionUpdateRouter { - private readonly activeSessions = new Map< - string, - Set - >(); - handleMessage(message: IncomingMessage): HandleResult { - if ( - message.kind !== "notification" || - message.method !== schema.CLIENT_METHODS.session_update - ) { - return Handled.no(message); - } - const notification = validate.zSessionNotification.parse(message.params); - const update = { - kind: "session_update", - notification, - update: notification.update, - } satisfies ActiveSessionMessage; - const activeSessions = this.activeSessions.get(notification.sessionId); - if (activeSessions && activeSessions.size > 0) { - for (const session of activeSessions) { - session.enqueue(update); - } - } - return Handled.no(message); - } - attach( - response: schema.NewSessionResponse, - updates: ActiveSessionUpdateQueue, - ): HandlerRegistration { - const sessions = - this.activeSessions.get(response.sessionId) ?? - new Set(); - sessions.add(updates); - this.activeSessions.set(response.sessionId, sessions); - return new HandlerRegistration(() => { - sessions.delete(updates); - if (sessions.size === 0) { - this.activeSessions.delete(response.sessionId); - } - }); - } -} -const sessionUpdateRouters = new WeakMap< - ConnectionContext, - SessionUpdateRouter ->(); -function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { - let router = sessionUpdateRouters.get(cx); - if (!router) { - router = new SessionUpdateRouter(); - sessionUpdateRouters.set(cx, router); - } - return router; -} -function runConnectHandlers( - connection: ConnectionHandle, - handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, -): void { - for (const handler of handlers) { - let result: MaybePromise; - try { - result = handler(connection); - } catch (error) { - connection.close(error); - throw error; - } - void Promise.resolve(result).catch((error) => { - connection.close(error); - }); - } -} -const appBuilder = Symbol("appBuilder"); -const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); -const runClientConnectHandlers = Symbol("runClientConnectHandlers"); -type AppConnectOptions = { - readonly deferConnectHandlers?: boolean; -}; -type AgentConnectionState = { - rawConnection: Connection; - connection: AgentConnection; -}; -type ClientConnectionState = { - rawConnection: Connection; - connection: ClientConnection; -}; -/** - * Creates an agent-side app. - * - * Register request and notification handlers by ACP method name, then call - * `connect(stream)` to serve an ACP client. - */ -export function agent(options?: AppOptions): AgentApp { - return new AgentApp(options); -} -/** - * Agent-side app builder. - * - * Methods on this class register typed request or notification handlers and - * return `this`, so apps can be built with a fluent chain. Handler params are - * parsed with the generated ACP schemas before your handler runs, and thrown - * errors are converted to JSON-RPC errors by the connection layer. - */ -export class AgentApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: AgentConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - private hasInitializeHandler = false; - constructor(options: AppOptions = {}) { - this.builder.withHandler( - agentInitializationGate(() => this.hasInitializeHandler), - ); - if (options.name) { - this.builder.name(options.name); - } - } - /** @internal */ - [appBuilder](): ConnectionBuilder { - return this.builder; - } - /** @internal */ - [runAgentConnectHandlers](connection: AgentConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - /** - * Connects this agent app to a transport stream. - */ - connect(stream: Stream): AgentConnection; - /** @internal */ - connect(stream: Stream, options: AppConnectOptions): AgentConnection; - /** - * Connects this agent app directly to a client app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(client: ClientApp): AgentConnection; - connect( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnection { - return this.connectConnection(target, options).connection; - } - /** - * Connects this agent app to a stream or client app for the lifetime of `op`. - * - * The callback receives an `AgentContext` for calling client-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | ClientApp, - op: (context: AgentContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.client)); - } - /** - * Registers a handler that runs when this agent app opens a connection. - * - * Use this for connection-scoped work that needs to call client-side ACP - * methods outside an inbound request handler, or to set up per-connection - * state that the request handlers use. - * - * Handlers are called synchronously in registration order and are not - * awaited. A handler that throws or rejects closes the connection. When they - * are called depends on who opens the connection: - * - * - `connect(...)` and `connectWith(...)` call them before the connection - * handles its first inbound message, and so does the experimental - * `AgentProtocolRouter`'s `connect(...)` when it routes to this app. Only - * the work a handler does before its first `await` is guaranteed to come - * first. - * - The experimental `AcpServer` calls them after the client has completed - * `initialize`, so messages they send cannot replace the initialize - * response. Request handlers, including `initialize`, can run before them. - */ - onConnect(handler: AgentConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - /** - * Registers a request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: AgentRequestHandler): this; - onRequest( - method: Method, - handler: AgentRequestHandlersByMethod[Method], - ): this; - onRequest( - method: string, - params: ParamsParser, - handler: AgentRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | AgentRequestHandlersByMethod[AgentRequestMethod] - | AgentRequestHandler - | ParamsParser, - handler?: AgentRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as AgentRequestHandler, - ); - } - if (handler) { - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = agentRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - if (method === schema.AGENT_METHODS.initialize) { - this.hasInitializeHandler = true; - } - return this.request( - spec as AcpRequestSpec, - handlerOrParams as AgentRequestHandler, - ); - } - /** - * Registers a notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. Serialize work yourself - * when its effects must be applied in order. - */ - onNotification(method: "*", handler: AgentNotificationHandler): this; - onNotification( - method: Method, - handler: AgentNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: string, - params: ParamsParser, - handler: AgentNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | AgentNotificationHandlersByMethod[AgentNotificationMethod] - | AgentNotificationHandler - | ParamsParser, - handler?: AgentNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as AgentNotificationHandler, - ); - } - if (handler) { - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = agentNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as AgentNotificationHandler, - ); - } - private request( - spec: AcpRequestSpec, - handler: AgentRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - agentRequestContext( - params, - AgentContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.mapResponse, - ); - return this; - } - private notification( - spec: AcpNotificationSpec, - handler: AgentNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - agentNotificationContext( - params, - AgentContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - private connectConnection( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnectionState { - if (isStream(target)) { - const state = this.openStreamConnection(target); - if (!options.deferConnectHandlers) { - this[runAgentConnectHandlers](state.connection); - } - return state; - } - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = clientConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => - peerRawConnection.closeFromPeer(), - ); - void peerRawConnection.closed.then(() => - state.rawConnection.closeFromPeer(), - ); - try { - target[runClientConnectHandlers](peerConnection); - this[runAgentConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - private openStreamConnection(stream: Stream): AgentConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: agentConnection(rawConnection, this.connectHandlers), - }; - } -} -/** - * Creates a client-side app. - * - * Register request and notification handlers by ACP method name, then use - * `connectWith(...)` to run the workflow that calls agent-side methods. - */ -export function client(options?: AppOptions): ClientApp { - return new ClientApp(options); -} -/** - * Client-side app builder. - * - * Methods on this class register typed client handlers and return `this`, so - * apps can be built with a fluent chain. `connectWith(...)` is the usual entry - * point for clients because it provides a `ClientContext` for calling - * agent-side requests and session helpers. - */ -export class ClientApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: ClientConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - constructor(options: AppOptions = {}) { - if (options.name) { - this.builder.name(options.name); - } - this.builder.withHandler({ - handleMessage: (message, cx) => - sessionUpdateRouter(cx).handleMessage(message), - describe: () => "client-session-update-router", - }); - } - /** @internal */ - [appBuilder](): ConnectionBuilder { - return this.builder; - } - /** @internal */ - [runClientConnectHandlers](connection: ClientConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - /** - * Connects this client app to a transport stream. - */ - connect(stream: Stream): ClientConnection; - /** - * Connects this client app directly to an agent app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(agent: AgentApp): ClientConnection; - connect(target: Stream | AgentApp): ClientConnection { - return this.connectConnection(target).connection; - } - /** - * Connects this client app to a stream or agent app for the lifetime of `op`. - * - * The callback receives a `ClientContext` for calling agent-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | AgentApp, - op: (context: ClientContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.agent)); - } - /** - * Registers a handler that runs when this client app opens a connection. - * - * Use this for connection-scoped work that needs to call agent-side ACP - * methods outside an inbound request handler. - */ - onConnect(handler: ClientConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - /** - * Registers a client request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: ClientRequestHandler): this; - onRequest( - method: Method, - handler: ClientRequestHandlersByMethod[Method], - ): this; - onRequest( - method: string, - params: ParamsParser, - handler: ClientRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | ClientRequestHandlersByMethod[ClientRequestMethod] - | ClientRequestHandler - | ParamsParser, - handler?: ClientRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as ClientRequestHandler, - ); - } - if (handler) { - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = clientRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - return this.request( - spec as AcpRequestSpec, - handlerOrParams as ClientRequestHandler, - ); - } - /** - * Registers a client notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. To apply a session's - * `session/update` notifications in the order they are received, a handler - * that awaits before applying an update must serialize that work itself, for - * example by chaining it onto a per-session promise. {@link ActiveSession} - * already queues updates in arrival order. - */ - onNotification( - method: "*", - handler: ClientNotificationHandler, - ): this; - onNotification( - method: Method, - handler: ClientNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: string, - params: ParamsParser, - handler: ClientNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | ClientNotificationHandlersByMethod[ClientNotificationMethod] - | ClientNotificationHandler - | ParamsParser, - handler?: ClientNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as ClientNotificationHandler, - ); - } - if (handler) { - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = clientNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as ClientNotificationHandler, - ); - } - private request( - spec: AcpRequestSpec, - handler: ClientRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - clientRequestContext( - params, - ClientContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.mapResponse, - ); - return this; - } - private notification( - spec: AcpNotificationSpec, - handler: ClientNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - clientNotificationContext( - params, - ClientContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - private connectConnection(target: Stream | AgentApp): ClientConnectionState { - if (isStream(target)) { - const state = this.openStreamConnection(target); - this[runClientConnectHandlers](state.connection); - return state; - } - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = agentConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => - peerRawConnection.closeFromPeer(), - ); - void peerRawConnection.closed.then(() => - state.rawConnection.closeFromPeer(), - ); - try { - target[runAgentConnectHandlers](peerConnection); - this[runClientConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - private openStreamConnection(stream: Stream): ClientConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: clientConnection(rawConnection, this.connectHandlers), - }; - } -} -/** - * Handle for controlling and monitoring a terminal created via `createTerminal`. - * - * Provides methods to: - * - Get current output without waiting - * - Wait for command completion - * - Kill the running command - * - Release terminal resources - * - * **Important:** Always call `release()` when done with the terminal to free resources. - - * The terminal supports async disposal via `Symbol.asyncDispose` for automatic cleanup. - - * You can use `await using` to ensure the terminal is automatically released when it - * goes out of scope. - */ -export class TerminalHandle { - /** - * Terminal identifier returned by `terminal/create`. - */ - public id: string; - private sessionId: string; - private connection: Pick; - private constructor( - id: string, - sessionId: string, - conn: Pick, - ) { - this.id = id; - this.sessionId = sessionId; - this.connection = conn; - } - /** @internal */ - static create( - id: string, - sessionId: string, - conn: Pick, - ): TerminalHandle { - return new TerminalHandle(id, sessionId, conn); - } - /** - * Gets the current terminal output without waiting for the command to exit. - */ - currentOutput(): Promise { - return this.connection.sendRequest(schema.CLIENT_METHODS.terminal_output, { - sessionId: this.sessionId, - terminalId: this.id, - }); - } - /** - * Waits for the terminal command to complete and returns its exit status. - */ - waitForExit(): Promise { - return this.connection.sendRequest( - schema.CLIENT_METHODS.terminal_wait_for_exit, - { - sessionId: this.sessionId, - terminalId: this.id, - }, - ); - } - /** - * Kills the terminal command without releasing the terminal. - * - * The terminal remains valid after killing, allowing you to: - * - Get the final output with `currentOutput()` - * - Check the exit status - * - Release the terminal when done - * - * Useful for implementing timeouts or cancellation. - */ - kill(): Promise { - return this.connection.sendRequest< - schema.KillTerminalRequest, - schema.KillTerminalResponse - >( - schema.CLIENT_METHODS.terminal_kill, - { - sessionId: this.sessionId, - terminalId: this.id, - }, - emptyObjectResponse, - ); - } - /** - * Releases the terminal and frees all associated resources. - * - * If the command is still running, it will be killed. - * After release, the terminal ID becomes invalid and cannot be used - * with other terminal methods. - * - * Tool calls that already reference this terminal will continue to - * display its output. - * - * **Important:** Always call this method when done with the terminal. - */ - release(): Promise { - return this.connection.sendRequest< - schema.ReleaseTerminalRequest, - schema.ReleaseTerminalResponse | void - >( - schema.CLIENT_METHODS.terminal_release, - { - sessionId: this.sessionId, - terminalId: this.id, - }, - emptyObjectResponse, - ); - } - /** - * Releases the terminal when used with `await using`. - */ - async [Symbol.asyncDispose](): Promise { - await this.release(); - } -} diff --git a/src/v1/stable/bindings.ts b/src/v1/stable/bindings.ts new file mode 100644 index 00000000..4d7d7c2c --- /dev/null +++ b/src/v1/stable/bindings.ts @@ -0,0 +1,2174 @@ +// Generated from src/v1/bindings.ts. Do not edit directly. +// V1 binding implementation, specialized against stable schemas by generate.js. +import * as schema from "../schema/index.js"; +import * as validate from "../schema/zod.gen.js"; +import type { Stream } from "./acp.js"; +import { + parseParams, + registerAppNotification, + registerAppRequest, +} from "../../core/app-handlers.js"; +import type { ParamsParser } from "../../core/app-handlers.js"; +import { connectionContextOf } from "../../core/connection-access.js"; +import { + Connection, + Handled, + HandlerRegistration, + RequestError, + RequestResponder, + treatSessionNotFoundAsSuccess, +} from "../../core/jsonrpc.js"; +import type { + AnyMessage, + ConnectionBuilder, + ConnectionContext, + HandleResult, + IncomingMessage, + JsonRpcId, + JsonRpcHandler, + MaybePromise, + SendRequestOptions, +} from "../../core/jsonrpc.js"; +const initializedConnections = new WeakSet(); +/** + * Rejects requests other than `initialize` with `-32600` until an `initialize` + * request has been answered successfully. `initialize` itself may be sent + * again at any time, as before. + */ +function agentInitializationGate(enabled: () => boolean): JsonRpcHandler { + return { + handleMessage(message, cx) { + if ( + message.kind !== "request" || + !enabled() || + initializedConnections.has(cx) + ) { + return Handled.no(message); + } + if (message.method !== schema.AGENT_METHODS.initialize) { + return message.responder + .respondWithError( + RequestError.invalidRequest( + undefined, + `ACP connection must be initialized before '${message.method}'`, + ), + ) + .then(() => Handled.yes()); + } + const { responder } = message; + return Handled.no({ + ...message, + responder: new RequestResponder( + responder.id, + (result) => { + // Record success before the response goes out, so the client's + // next request is never rejected. + if ("result" in result) { + initializedConnections.add(cx); + } + return responder.respondWithResult(result); + }, + responder.signal, + ), + }); + }, + describe: () => "agent-initialization", + }; +} +function emptyObjectResponse(response: T | null | undefined | void): T { + return response ?? ({} as T); +} +function isStream(value: unknown): value is Stream { + return ( + typeof value === "object" && + value !== null && + "readable" in value && + "writable" in value + ); +} +function memoryStreamPair(): [Stream, Stream] { + const leftToRight = new TransformStream(); + const rightToLeft = new TransformStream(); + return [ + { + readable: rightToLeft.readable, + writable: leftToRight.writable, + }, + { + readable: leftToRight.readable, + writable: rightToLeft.writable, + }, + ]; +} +const startActiveSession = Symbol("startActiveSession"); +/** + * Active ACP connection returned by `AgentApp.connect(...)` and + * `ClientApp.connect(...)`. + * + * Use this handle when you need a connection to stay open independently of a + * single `connectWith(...)` operation. + */ +export interface AcpConnection { + /** + * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. + */ + readonly signal: AbortSignal; + /** + * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. + */ + readonly closed: Promise; + /** + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. + */ + close(error?: unknown): void; +} +/** + * Agent-side connection returned by `AgentApp.connect(...)`. + * + * Use `client` to call client-side ACP methods for the lifetime of the + * connection. + */ +export interface AgentConnection extends AcpConnection { + /** + * Context for calling client-side ACP methods. + */ + readonly client: AgentContext; +} +/** + * Client-side connection returned by `ClientApp.connect(...)`. + * + * Use `agent` to call agent-side ACP methods and session helpers for the + * lifetime of the connection. + */ +export interface ClientConnection extends AcpConnection { + /** + * Context for calling agent-side ACP methods. + */ + readonly agent: ClientContext; +} +class AcpContext { + /** @internal */ + constructor( + private readonly cx: ConnectionContext, + private readonly currentRequestId?: JsonRpcId, + ) {} + /** + * JSON-RPC id of the request currently being handled. + * + * This is `undefined` for notification handlers and for contexts created + * outside an inbound request, such as `connect(...)` and `connectWith(...)`. + */ + get requestId(): JsonRpcId | undefined { + return this.currentRequestId; + } + /** @internal */ + protected get connectionContext(): ConnectionContext { + return this.cx; + } + /** @hidden SDK helpers use this to identify the connection. */ + [connectionContextOf](): ConnectionContext { + return this.cx; + } + /** @internal */ + protected sendRequest( + method: string, + params?: Req, + mapResponse?: (response: Resp) => Output, + options?: SendRequestOptions, + ): Promise { + return this.cx.sendRequest(method, params, mapResponse, options); + } + /** @internal */ + protected sendNotification(method: string, params?: N): Promise { + return this.cx.sendNotification(method, params); + } + /** @internal */ + protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { + return this.cx.addDynamicHandler(handler); + } +} +/** + * Context passed to agent-side handlers. + * + * Agents use this context to call client-side ACP methods while handling + * requests such as `session/prompt`. + */ +export class AgentContext extends AcpContext { + private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { + super(cx, requestId); + } + /** @internal */ + static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { + return new AgentContext(cx, requestId); + } + /** + * Executes a command in a new client terminal. + * + * Returns a handle for reading output, waiting for exit, killing the command, + * and releasing the terminal. Check the client's terminal capability first. + * Use `await using` or call `release()` when finished. + */ + async createTerminal( + params: schema.CreateTerminalRequest, + options?: SendRequestOptions, + ): Promise { + const response = await this.request( + schema.CLIENT_METHODS.terminal_create, + params, + options, + ); + return TerminalHandle.create( + response.terminalId, + params.sessionId, + this.connectionContext, + ); + } + /** + * Sends a request to the client by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + */ + request( + method: Method, + params: ClientRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + const spec = clientRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + return this.sendRequest(method, params, spec?.mapResponse, options); + } + /** + * Sends a notification to the client by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: ClientNotificationParamsByMethod[Method], + ): Promise; + notify(method: string, params?: Params): Promise; + notify(method: string, params?: unknown): Promise { + return this.sendNotification(method, params); + } +} +/** + * Context used by clients to call agent-side ACP methods. + * + * `connectWith` passes a `ClientContext` to the callback. Client handlers also + * receive one as `ctx.agent` when they need to call back into the agent. + */ +export class ClientContext extends AcpContext { + private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { + super(cx, requestId); + } + /** @internal */ + static create(cx: ConnectionContext, requestId?: JsonRpcId): ClientContext { + return new ClientContext(cx, requestId); + } + /** @internal */ + [startActiveSession]( + params: schema.NewSessionRequest, + options?: SendRequestOptions, + ): Promise { + return this.sendRequest< + schema.NewSessionRequest, + schema.NewSessionResponse, + ActiveSession + >( + schema.AGENT_METHODS.session_new, + params, + (response) => this.attachSession(response), + options, + ); + } + /** + * Creates a builder for starting and observing an ACP session. + * + * Pass a string for the common case where only `cwd` is needed, or pass a + * full `NewSessionRequest` when you need MCP servers, `_meta`, or additional + * session fields. + */ + buildSession(cwd: string): SessionBuilder; + buildSession(request: schema.NewSessionRequest): SessionBuilder; + buildSession( + cwdOrRequest: string | schema.NewSessionRequest, + ): SessionBuilder { + if (typeof cwdOrRequest === "string") { + return SessionBuilder.create(this, { + cwd: cwdOrRequest, + mcpServers: [], + }); + } + return SessionBuilder.create(this, cwdOrRequest); + } + /** + * Builds active-session helpers around a `session/new` response. + */ + private attachSession(response: schema.NewSessionResponse): ActiveSession { + const updates = new AsyncQueue(); + const closeSignal = this.connectionContext.signal; + const failUpdatesOnClose = () => { + updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); + }; + if (closeSignal.aborted) { + failUpdatesOnClose(); + } else { + closeSignal.addEventListener("abort", failUpdatesOnClose); + } + const sessionRegistration = sessionUpdateRouter( + this.connectionContext, + ).attach(response, updates); + const closeRegistration = new HandlerRegistration(() => { + closeSignal.removeEventListener("abort", failUpdatesOnClose); + }); + return ActiveSession.create(this, response, updates, [ + sessionRegistration, + closeRegistration, + ]); + } + /** + * Sends a request to the agent by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + * + * Closing or deleting a session is idempotent: a `-32002` (Resource not + * found) response to `session/close` or `session/delete` resolves with an + * empty result instead of rejecting. + */ + request( + method: Method, + params: AgentRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + const spec = agentRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + return treatSessionNotFoundAsSuccess( + method, + this.sendRequest(method, params, spec?.mapResponse, options), + () => (spec?.mapResponse ? spec.mapResponse({}) : {}), + ); + } + /** + * Sends a notification to the agent by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: AgentNotificationParamsByMethod[Method], + ): Promise; + notify(method: string, params?: Params): Promise; + notify(method: string, params?: unknown): Promise { + return this.sendNotification(method, params); + } +} +class AcpConnectionHandle implements AcpConnection { + constructor(private readonly connection: Connection) {} + get signal(): AbortSignal { + return this.connection.signal; + } + get closed(): Promise { + return this.connection.closed; + } + close(error?: unknown): void { + this.connection.close(error); + } +} +class AgentConnectionHandle + extends AcpConnectionHandle + implements AgentConnection +{ + readonly client: AgentContext; + private didStartConnectHandlers = false; + constructor( + connection: Connection, + private readonly connectHandlers: readonly AgentConnectHandler[] = [], + ) { + super(connection); + this.client = AgentContext.create(connection.getContext()); + } + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} +class ClientConnectionHandle + extends AcpConnectionHandle + implements ClientConnection +{ + readonly agent: ClientContext; + private didStartConnectHandlers = false; + constructor( + connection: Connection, + private readonly connectHandlers: readonly ClientConnectHandler[] = [], + ) { + super(connection); + this.agent = ClientContext.create(connection.getContext()); + } + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} +function agentConnection( + connection: Connection, + connectHandlers: readonly AgentConnectHandler[] = [], +): AgentConnection { + return new AgentConnectionHandle(connection, connectHandlers); +} +function clientConnection( + connection: Connection, + connectHandlers: readonly ClientConnectHandler[] = [], +): ClientConnection { + return new ClientConnectionHandle(connection, connectHandlers); +} +type AsyncQueueEntry = + | { + kind: "value"; + value: T; + } + | { + kind: "error"; + error: unknown; + }; +class AsyncQueue { + private values: Array> = []; + private waiters: Array<{ + resolve: (value: T) => void; + reject: (error: unknown) => void; + }> = []; + private failed = false; + private failure: unknown; + enqueue(value: T): void { + if (this.failed) { + return; + } + const waiter = this.waiters.shift(); + if (waiter) { + waiter.resolve(value); + } else { + this.values.push({ kind: "value", value }); + } + } + reject(error: unknown): void { + if (this.failed) { + return; + } + if (this.waiters.length > 0) { + for (const waiter of this.waiters.splice(0)) { + waiter.reject(error); + } + return; + } + this.values.push({ kind: "error", error }); + } + clearErrors(): void { + this.values = this.values.filter((entry) => entry.kind === "value"); + } + fail(error: unknown): void { + if (this.failed) { + return; + } + this.failed = true; + this.failure = error; + for (const waiter of this.waiters.splice(0)) { + waiter.reject(error); + } + } + next(): Promise { + if (this.values.length > 0) { + const entry = this.values.shift() as AsyncQueueEntry; + if (entry.kind === "error") { + return Promise.reject(entry.error); + } + return Promise.resolve(entry.value); + } + if (this.failed) { + return Promise.reject(this.failure); + } + return new Promise((resolve, reject) => { + this.waiters.push({ resolve, reject }); + }); + } +} +function cloneNewSessionRequest( + request: schema.NewSessionRequest, +): schema.NewSessionRequest { + return { + ...request, + additionalDirectories: request.additionalDirectories + ? [...request.additionalDirectories] + : undefined, + mcpServers: [...request.mcpServers], + }; +} +/** + * Message produced by an `ActiveSession`. + * + * `session_update` messages expose the typed `session/update` notification and + * `stop` messages report the final `session/prompt` response. A prompt turn is + * complete once a `stop` message is returned. + */ +export type ActiveSessionMessage = + | { + /** + * Indicates that this message came from a `session/update` notification. + */ + kind: "session_update"; + /** + * Full notification sent by the agent. + */ + notification: schema.SessionNotification; + /** + * Convenience alias for `notification.update`. + */ + update: schema.SessionUpdate; + } + | { + /** + * Indicates that the prompt turn has completed. + */ + kind: "stop"; + /** + * Final response from `session/prompt`. + */ + response: schema.PromptResponse; + /** + * Convenience alias for `response.stopReason`. + */ + stopReason: schema.StopReason; + }; +/** + * Builder for creating an `ActiveSession`. + * + * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or + * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session + * needs MCP servers, `_meta`, or additional request fields. All paths in ACP + * payloads should be absolute. + */ +export class SessionBuilder { + private request: schema.NewSessionRequest; + private constructor( + private cx: ClientContext, + request: schema.NewSessionRequest, + ) { + this.request = cloneNewSessionRequest(request); + } + /** @internal */ + static create( + cx: ClientContext, + request: schema.NewSessionRequest, + ): SessionBuilder { + return new SessionBuilder(cx, request); + } + /** + * Returns the `session/new` request that will be sent. + * + * The returned object is a defensive copy, so mutating it does not change the + * builder. + */ + toRequest(): schema.NewSessionRequest { + return cloneNewSessionRequest(this.request); + } + /** + * Replaces the additional workspace roots for this session. + * + * `additionalDirectories` expand the session's file-system scope without + * changing `cwd`. Each path should be absolute. + */ + withAdditionalDirectories(additionalDirectories: string[]): this { + this.request = { + ...this.request, + additionalDirectories: [...additionalDirectories], + }; + return this; + } + /** + * Adds one MCP server to the `session/new` request. + */ + withMcpServer(mcpServer: schema.McpServer): this { + this.request = { + ...this.request, + mcpServers: [...this.request.mcpServers, mcpServer], + }; + return this; + } + /** + * Starts the session and returns an `ActiveSession` for prompting and reading + * updates. + * + * Call `dispose()` on the returned session when you no longer need update + * routing, or use `withSession(...)` to scope disposal automatically. + */ + async start(options?: SendRequestOptions): Promise { + return this.cx[startActiveSession](this.toRequest(), options); + } + /** + * Starts the session, runs `op`, and disposes the active-session update + * routing when `op` finishes or throws. + */ + async withSession( + op: (session: ActiveSession) => MaybePromise, + ): Promise { + const session = await this.start(); + try { + return await op(session); + } finally { + session.dispose(); + } + } +} +/** + * Convenience wrapper for an active ACP session. + * + * An active session routes `session/update` notifications for one session ID + * into an async queue. Use `prompt(...)` to send user content, then read updates + * with `nextUpdate()` until a `stop` message is returned. + */ +export class ActiveSession { + private constructor( + private cx: ClientContext, + private sessionResponse: schema.NewSessionResponse, + private updates: { + enqueue(value: ActiveSessionMessage): void; + reject(error: unknown): void; + clearErrors(): void; + fail(error: unknown): void; + next(): Promise; + }, + private registrations: HandlerRegistration[], + ) {} + /** @internal */ + static create( + cx: ClientContext, + sessionResponse: schema.NewSessionResponse, + updates: { + enqueue(value: ActiveSessionMessage): void; + reject(error: unknown): void; + clearErrors(): void; + fail(error: unknown): void; + next(): Promise; + }, + registrations: HandlerRegistration[], + ): ActiveSession { + return new ActiveSession(cx, sessionResponse, updates, registrations); + } + /** + * Session ID returned by `session/new`. + */ + get sessionId(): schema.SessionId { + return this.sessionResponse.sessionId; + } + /** + * Mode state returned when the session was created, if the agent provided it. + */ + get modes(): schema.SessionModeState | null | undefined { + return this.sessionResponse.modes; + } + /** + * Metadata returned when the session was created. + */ + get meta(): + | { + [key: string]: unknown; + } + | null + | undefined { + return this.sessionResponse._meta; + } + /** + * Full response returned by `session/new`. + */ + get newSessionResponse(): schema.NewSessionResponse { + return this.sessionResponse; + } + /** + * Sends a prompt to this session. + * + * Strings are converted to one text content block. A single content block is + * wrapped in an array. The returned promise resolves with the final + * `PromptResponse`, and the same completion is also queued as a `stop` + * message for `nextUpdate()`. + */ + prompt( + prompt: string | schema.ContentBlock | Array, + options?: SendRequestOptions, + ): Promise { + this.updates.clearErrors(); + const response = this.cx.request( + schema.AGENT_METHODS.session_prompt, + { + sessionId: this.sessionId, + prompt: this.promptBlocks(prompt), + }, + options, + ); + void response.then( + (value) => { + this.updates.enqueue({ + kind: "stop", + response: value, + stopReason: value.stopReason, + }); + }, + (error) => { + this.updates.reject(error); + }, + ); + return response; + } + /** + * Reads the next update or stop message for this session. + */ + nextUpdate(): Promise { + return this.updates.next(); + } + /** + * Reads text chunks until the current prompt turn stops. + * + * Only `agent_message_chunk` updates with text content are appended. Other + * update types are ignored by this helper; use `nextUpdate()` when you need + * tool calls, plans, or the final `PromptResponse`. + */ + async readText(): Promise { + let output = ""; + for (;;) { + const message = await this.nextUpdate(); + if (message.kind === "stop") { + return output; + } + const { update } = message; + if ( + update.sessionUpdate === "agent_message_chunk" && + update.content.type === "text" + ) { + output += update.content.text; + } + } + } + /** + * Stops routing updates to this active-session helper. + * + * This does not close the ACP session on the agent. Use `ClientContext` + * session lifecycle methods when the protocol session itself should be closed + * or deleted. + */ + dispose(): void { + for (const registration of this.registrations.splice(0)) { + registration.dispose(); + } + this.updates.fail(new Error("Active session disposed")); + } + /** + * Supports explicit resource management with `using`. + */ + [Symbol.dispose](): void { + this.dispose(); + } + private promptBlocks( + prompt: string | schema.ContentBlock | Array, + ): Array { + if (typeof prompt === "string") { + return [{ type: "text", text: prompt }]; + } + if (Array.isArray(prompt)) { + return prompt; + } + return [prompt]; + } +} +/** + * Options used when creating an ACP app. + */ +export type AppOptions = { + /** + * Human-readable name used in JSON-RPC handler descriptions and diagnostics. + */ + name?: string; +}; +/** + * Common context passed to agent-side handlers. + */ +export type AgentHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed client context for calling client-side ACP methods. + */ + client: AgentContext; +}; +/** + * Context passed to agent-side request handlers. + */ +export type AgentRequestContext = AgentHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; +/** + * Context passed to agent-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type AgentNotificationContext = AgentHandlerContext; +/** + * Common context passed to client-side handlers. + */ +export type ClientHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed agent context for calling agent-side ACP methods. + */ + agent: ClientContext; +}; +/** + * Context passed to client-side request handlers. + */ +export type ClientRequestContext = ClientHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; +/** + * Context passed to client-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type ClientNotificationContext = ClientHandlerContext; +/** + * Request handler registered on an `AgentApp`. + */ +export type AgentRequestHandler = ( + context: AgentRequestContext, +) => MaybePromise; +/** + * Notification handler registered on an `AgentApp`. + */ +export type AgentNotificationHandler = ( + context: AgentNotificationContext, +) => MaybePromise; +/** + * Request handler registered on a `ClientApp`. + */ +export type ClientRequestHandler = ( + context: ClientRequestContext, +) => MaybePromise; +/** + * Notification handler registered on a `ClientApp`. + */ +export type ClientNotificationHandler = ( + context: ClientNotificationContext, +) => MaybePromise; +/** + * Handler called when an `AgentApp` opens a connection. + */ +export type AgentConnectHandler = ( + connection: AgentConnection, +) => MaybePromise; +/** + * Handler called when a `ClientApp` opens a connection. + */ +export type ClientConnectHandler = ( + connection: ClientConnection, +) => MaybePromise; +type AcpRequestSpec = { + method: string; + params?: ParamsParser; + mapResponse?: (response: Response) => WireResponse; +}; +type AcpNotificationSpec = { + method: string; + params?: ParamsParser; +}; +function requestSpec( + method: string, + params: ParamsParser, + mapResponse?: (response: Response) => WireResponse, +): AcpRequestSpec { + return { + method, + // Match Rust's empty-payload handling without bypassing required fields. + params: (value) => parseParams(params, value ?? {}), + mapResponse, + }; +} +function notificationSpec( + method: string, + params: ParamsParser, +): AcpNotificationSpec { + return { method, params }; +} +function specsByMethod< + T extends Record< + string, + { + method: string; + } + >, +>(specs: T): Record { + const byMethod: Record = {}; + for (const spec of Object.values(specs) as Array) { + byMethod[spec.method] = spec; + } + return byMethod; +} +const agentRequestSpecs = { + initialize: requestSpec( + schema.AGENT_METHODS.initialize, + validate.zInitializeRequest, + ), + newSession: requestSpec( + schema.AGENT_METHODS.session_new, + validate.zNewSessionRequest, + ), + loadSession: requestSpec< + schema.LoadSessionRequest, + schema.LoadSessionResponse | void, + schema.LoadSessionResponse + >( + schema.AGENT_METHODS.session_load, + validate.zLoadSessionRequest, + emptyObjectResponse, + ), + listSessions: requestSpec< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >(schema.AGENT_METHODS.session_list, validate.zListSessionsRequest), + deleteSession: requestSpec< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void, + schema.DeleteSessionResponse + >( + schema.AGENT_METHODS.session_delete, + validate.zDeleteSessionRequest, + emptyObjectResponse, + ), + resumeSession: requestSpec< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >(schema.AGENT_METHODS.session_resume, validate.zResumeSessionRequest), + closeSession: requestSpec< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void, + schema.CloseSessionResponse + >( + schema.AGENT_METHODS.session_close, + validate.zCloseSessionRequest, + emptyObjectResponse, + ), + setSessionMode: requestSpec< + schema.SetSessionModeRequest, + schema.SetSessionModeResponse | void, + schema.SetSessionModeResponse + >( + schema.AGENT_METHODS.session_set_mode, + validate.zSetSessionModeRequest, + emptyObjectResponse, + ), + setSessionConfigOption: requestSpec< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >( + schema.AGENT_METHODS.session_set_config_option, + validate.zSetSessionConfigOptionRequest, + ), + authenticate: requestSpec< + schema.AuthenticateRequest, + schema.AuthenticateResponse | void, + schema.AuthenticateResponse + >( + schema.AGENT_METHODS.authenticate, + validate.zAuthenticateRequest, + emptyObjectResponse, + ), + logout: requestSpec< + schema.LogoutRequest, + schema.LogoutResponse | void, + schema.LogoutResponse + >(schema.AGENT_METHODS.logout, validate.zLogoutRequest, emptyObjectResponse), + prompt: requestSpec( + schema.AGENT_METHODS.session_prompt, + validate.zPromptRequest, + ), +}; +const agentNotificationSpecs = { + cancel: notificationSpec( + schema.AGENT_METHODS.session_cancel, + validate.zCancelNotification, + ), +}; +const clientRequestSpecs = { + requestPermission: requestSpec< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >( + schema.CLIENT_METHODS.session_request_permission, + validate.zRequestPermissionRequest, + ), + writeTextFile: requestSpec< + schema.WriteTextFileRequest, + schema.WriteTextFileResponse | void, + schema.WriteTextFileResponse + >( + schema.CLIENT_METHODS.fs_write_text_file, + validate.zWriteTextFileRequest, + emptyObjectResponse, + ), + readTextFile: requestSpec< + schema.ReadTextFileRequest, + schema.ReadTextFileResponse + >(schema.CLIENT_METHODS.fs_read_text_file, validate.zReadTextFileRequest), + createTerminal: requestSpec< + schema.CreateTerminalRequest, + schema.CreateTerminalResponse + >(schema.CLIENT_METHODS.terminal_create, validate.zCreateTerminalRequest), + terminalOutput: requestSpec< + schema.TerminalOutputRequest, + schema.TerminalOutputResponse + >(schema.CLIENT_METHODS.terminal_output, validate.zTerminalOutputRequest), + releaseTerminal: requestSpec< + schema.ReleaseTerminalRequest, + schema.ReleaseTerminalResponse | void, + schema.ReleaseTerminalResponse + >( + schema.CLIENT_METHODS.terminal_release, + validate.zReleaseTerminalRequest, + emptyObjectResponse, + ), + waitForTerminalExit: requestSpec< + schema.WaitForTerminalExitRequest, + schema.WaitForTerminalExitResponse + >( + schema.CLIENT_METHODS.terminal_wait_for_exit, + validate.zWaitForTerminalExitRequest, + ), + killTerminal: requestSpec< + schema.KillTerminalRequest, + schema.KillTerminalResponse | void, + schema.KillTerminalResponse + >( + schema.CLIENT_METHODS.terminal_kill, + validate.zKillTerminalRequest, + emptyObjectResponse, + ), + createElicitation: requestSpec< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >( + schema.CLIENT_METHODS.elicitation_create, + validate.zCreateElicitationRequest, + ), +}; +const clientNotificationSpecs = { + sessionUpdate: notificationSpec( + schema.CLIENT_METHODS.session_update, + validate.zSessionNotification, + ), + completeElicitation: notificationSpec( + schema.CLIENT_METHODS.elicitation_complete, + validate.zCompleteElicitationNotification, + ), +}; +const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); +const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); +const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); +const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); +/** + * Agent request handlers keyed by ACP protocol method name. + */ +export type AgentRequestHandlersByMethod = { + /** + * Handles `initialize`. + * + * Registering this handler makes the app reject other requests with + * `-32600` until an `initialize` request has been answered successfully. + */ + [schema.AGENT_METHODS.initialize]: AgentRequestHandler< + schema.InitializeRequest, + schema.InitializeResponse + >; + [schema.AGENT_METHODS.session_new]: AgentRequestHandler< + schema.NewSessionRequest, + schema.NewSessionResponse + >; + [schema.AGENT_METHODS.session_load]: AgentRequestHandler< + schema.LoadSessionRequest, + schema.LoadSessionResponse | void + >; + [schema.AGENT_METHODS.session_list]: AgentRequestHandler< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >; + [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void + >; + [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >; + [schema.AGENT_METHODS.session_close]: AgentRequestHandler< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void + >; + [schema.AGENT_METHODS.session_set_mode]: AgentRequestHandler< + schema.SetSessionModeRequest, + schema.SetSessionModeResponse | void + >; + [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >; + [schema.AGENT_METHODS.authenticate]: AgentRequestHandler< + schema.AuthenticateRequest, + schema.AuthenticateResponse | void + >; + [schema.AGENT_METHODS.logout]: AgentRequestHandler< + schema.LogoutRequest, + schema.LogoutResponse | void + >; + [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< + schema.PromptRequest, + schema.PromptResponse + >; +}; +/** + * ACP request methods that can be handled by an `AgentApp`. + */ +export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; +/** + * Agent notification handlers keyed by ACP protocol method name. + */ +export type AgentNotificationHandlersByMethod = { + [schema.AGENT_METHODS + .session_cancel]: AgentNotificationHandler; +}; +/** + * ACP notification methods that can be handled by an `AgentApp`. + */ +export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & + string; +/** + * Client request handlers keyed by ACP protocol method name. + */ +export type ClientRequestHandlersByMethod = { + [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >; + [schema.CLIENT_METHODS.fs_write_text_file]: ClientRequestHandler< + schema.WriteTextFileRequest, + schema.WriteTextFileResponse | void + >; + [schema.CLIENT_METHODS.fs_read_text_file]: ClientRequestHandler< + schema.ReadTextFileRequest, + schema.ReadTextFileResponse + >; + [schema.CLIENT_METHODS.terminal_create]: ClientRequestHandler< + schema.CreateTerminalRequest, + schema.CreateTerminalResponse + >; + [schema.CLIENT_METHODS.terminal_output]: ClientRequestHandler< + schema.TerminalOutputRequest, + schema.TerminalOutputResponse + >; + [schema.CLIENT_METHODS.terminal_release]: ClientRequestHandler< + schema.ReleaseTerminalRequest, + schema.ReleaseTerminalResponse | void + >; + [schema.CLIENT_METHODS.terminal_wait_for_exit]: ClientRequestHandler< + schema.WaitForTerminalExitRequest, + schema.WaitForTerminalExitResponse + >; + [schema.CLIENT_METHODS.terminal_kill]: ClientRequestHandler< + schema.KillTerminalRequest, + schema.KillTerminalResponse | void + >; + [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >; +}; +/** + * ACP request methods that can be handled by a `ClientApp`. + */ +export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; +/** + * Client notification handlers keyed by ACP protocol method name. + */ +export type ClientNotificationHandlersByMethod = { + [schema.CLIENT_METHODS + .session_update]: ClientNotificationHandler; + [schema.CLIENT_METHODS + .elicitation_complete]: ClientNotificationHandler; +}; +/** + * ACP notification methods that can be handled by a `ClientApp`. + */ +export type ClientNotificationMethod = + keyof ClientNotificationHandlersByMethod & string; +/** + * Agent request params keyed by ACP protocol method name. + */ +export type AgentRequestParamsByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +/** + * Agent request responses keyed by ACP protocol method name. + */ +export type AgentRequestResponsesByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; +/** + * Agent notification params keyed by ACP protocol method name. + */ +export type AgentNotificationParamsByMethod = { + [ + Method in AgentNotificationMethod + ]: AgentNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +/** + * Client request params keyed by ACP protocol method name. + */ +export type ClientRequestParamsByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +/** + * Client request responses keyed by ACP protocol method name. + */ +export type ClientRequestResponsesByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; +/** + * Client notification params keyed by ACP protocol method name. + */ +export type ClientNotificationParamsByMethod = { + [ + Method in ClientNotificationMethod + ]: ClientNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +function agentRequestContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): AgentRequestContext { + return { + method, + params, + requestId, + signal, + client, + }; +} +function agentNotificationContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + method: string, +): AgentNotificationContext { + return { + method, + params, + signal, + client, + }; +} +function clientRequestContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): ClientRequestContext { + return { + method, + params, + requestId, + signal, + agent, + }; +} +function clientNotificationContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + method: string, +): ClientNotificationContext { + return { + method, + params, + signal, + agent, + }; +} +type ActiveSessionUpdateQueue = { + enqueue(value: ActiveSessionMessage): void; +}; +class SessionUpdateRouter { + private readonly activeSessions = new Map< + string, + Set + >(); + handleMessage(message: IncomingMessage): HandleResult { + if ( + message.kind !== "notification" || + message.method !== schema.CLIENT_METHODS.session_update + ) { + return Handled.no(message); + } + const notification = validate.zSessionNotification.parse(message.params); + const update = { + kind: "session_update", + notification, + update: notification.update, + } satisfies ActiveSessionMessage; + const activeSessions = this.activeSessions.get(notification.sessionId); + if (activeSessions && activeSessions.size > 0) { + for (const session of activeSessions) { + session.enqueue(update); + } + } + return Handled.no(message); + } + attach( + response: schema.NewSessionResponse, + updates: ActiveSessionUpdateQueue, + ): HandlerRegistration { + const sessions = + this.activeSessions.get(response.sessionId) ?? + new Set(); + sessions.add(updates); + this.activeSessions.set(response.sessionId, sessions); + return new HandlerRegistration(() => { + sessions.delete(updates); + if (sessions.size === 0) { + this.activeSessions.delete(response.sessionId); + } + }); + } +} +const sessionUpdateRouters = new WeakMap< + ConnectionContext, + SessionUpdateRouter +>(); +function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { + let router = sessionUpdateRouters.get(cx); + if (!router) { + router = new SessionUpdateRouter(); + sessionUpdateRouters.set(cx, router); + } + return router; +} +function runConnectHandlers( + connection: ConnectionHandle, + handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, +): void { + for (const handler of handlers) { + let result: MaybePromise; + try { + result = handler(connection); + } catch (error) { + connection.close(error); + throw error; + } + void Promise.resolve(result).catch((error) => { + connection.close(error); + }); + } +} +const appBuilder = Symbol("appBuilder"); +const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); +const runClientConnectHandlers = Symbol("runClientConnectHandlers"); +type AppConnectOptions = { + readonly deferConnectHandlers?: boolean; +}; +type AgentConnectionState = { + rawConnection: Connection; + connection: AgentConnection; +}; +type ClientConnectionState = { + rawConnection: Connection; + connection: ClientConnection; +}; +/** + * Creates an agent-side app. + * + * Register request and notification handlers by ACP method name, then call + * `connect(stream)` to serve an ACP client. + */ +export function agent(options?: AppOptions): AgentApp { + return new AgentApp(options); +} +/** + * Agent-side app builder. + * + * Methods on this class register typed request or notification handlers and + * return `this`, so apps can be built with a fluent chain. Handler params are + * parsed with the generated ACP schemas before your handler runs, and thrown + * errors are converted to JSON-RPC errors by the connection layer. + */ +export class AgentApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: AgentConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + private hasInitializeHandler = false; + constructor(options: AppOptions = {}) { + this.builder.withHandler( + agentInitializationGate(() => this.hasInitializeHandler), + ); + if (options.name) { + this.builder.name(options.name); + } + } + /** @internal */ + [appBuilder](): ConnectionBuilder { + return this.builder; + } + /** @internal */ + [runAgentConnectHandlers](connection: AgentConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + /** + * Connects this agent app to a transport stream. + */ + connect(stream: Stream): AgentConnection; + /** @internal */ + connect(stream: Stream, options: AppConnectOptions): AgentConnection; + /** + * Connects this agent app directly to a client app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(client: ClientApp): AgentConnection; + connect( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnection { + return this.connectConnection(target, options).connection; + } + /** + * Connects this agent app to a stream or client app for the lifetime of `op`. + * + * The callback receives an `AgentContext` for calling client-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | ClientApp, + op: (context: AgentContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.client)); + } + /** + * Registers a handler that runs when this agent app opens a connection. + * + * Use this for connection-scoped work that needs to call client-side ACP + * methods outside an inbound request handler, or to set up per-connection + * state that the request handlers use. + * + * Handlers are called synchronously in registration order and are not + * awaited. A handler that throws or rejects closes the connection. When they + * are called depends on who opens the connection: + * + * - `connect(...)` and `connectWith(...)` call them before the connection + * handles its first inbound message, and so does the experimental + * `AgentProtocolRouter`'s `connect(...)` when it routes to this app. Only + * the work a handler does before its first `await` is guaranteed to come + * first. + * - The experimental `AcpServer` calls them after the client has completed + * `initialize`, so messages they send cannot replace the initialize + * response. Request handlers, including `initialize`, can run before them. + */ + onConnect(handler: AgentConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + /** + * Registers a request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: AgentRequestHandler): this; + onRequest( + method: Method, + handler: AgentRequestHandlersByMethod[Method], + ): this; + onRequest( + method: string, + params: ParamsParser, + handler: AgentRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | AgentRequestHandlersByMethod[AgentRequestMethod] + | AgentRequestHandler + | ParamsParser, + handler?: AgentRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as AgentRequestHandler, + ); + } + if (handler) { + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = agentRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + if (method === schema.AGENT_METHODS.initialize) { + this.hasInitializeHandler = true; + } + return this.request( + spec as AcpRequestSpec, + handlerOrParams as AgentRequestHandler, + ); + } + /** + * Registers a notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. Serialize work yourself + * when its effects must be applied in order. + */ + onNotification(method: "*", handler: AgentNotificationHandler): this; + onNotification( + method: Method, + handler: AgentNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: string, + params: ParamsParser, + handler: AgentNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | AgentNotificationHandlersByMethod[AgentNotificationMethod] + | AgentNotificationHandler + | ParamsParser, + handler?: AgentNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as AgentNotificationHandler, + ); + } + if (handler) { + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = agentNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as AgentNotificationHandler, + ); + } + private request( + spec: AcpRequestSpec, + handler: AgentRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + agentRequestContext( + params, + AgentContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.mapResponse, + ); + return this; + } + private notification( + spec: AcpNotificationSpec, + handler: AgentNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + agentNotificationContext( + params, + AgentContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + private connectConnection( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnectionState { + if (isStream(target)) { + const state = this.openStreamConnection(target); + if (!options.deferConnectHandlers) { + this[runAgentConnectHandlers](state.connection); + } + return state; + } + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = clientConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); + try { + target[runClientConnectHandlers](peerConnection); + this[runAgentConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + private openStreamConnection(stream: Stream): AgentConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: agentConnection(rawConnection, this.connectHandlers), + }; + } +} +/** + * Creates a client-side app. + * + * Register request and notification handlers by ACP method name, then use + * `connectWith(...)` to run the workflow that calls agent-side methods. + */ +export function client(options?: AppOptions): ClientApp { + return new ClientApp(options); +} +/** + * Client-side app builder. + * + * Methods on this class register typed client handlers and return `this`, so + * apps can be built with a fluent chain. `connectWith(...)` is the usual entry + * point for clients because it provides a `ClientContext` for calling + * agent-side requests and session helpers. + */ +export class ClientApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: ClientConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + constructor(options: AppOptions = {}) { + if (options.name) { + this.builder.name(options.name); + } + this.builder.withHandler({ + handleMessage: (message, cx) => + sessionUpdateRouter(cx).handleMessage(message), + describe: () => "client-session-update-router", + }); + } + /** @internal */ + [appBuilder](): ConnectionBuilder { + return this.builder; + } + /** @internal */ + [runClientConnectHandlers](connection: ClientConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + /** + * Connects this client app to a transport stream. + */ + connect(stream: Stream): ClientConnection; + /** + * Connects this client app directly to an agent app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(agent: AgentApp): ClientConnection; + connect(target: Stream | AgentApp): ClientConnection { + return this.connectConnection(target).connection; + } + /** + * Connects this client app to a stream or agent app for the lifetime of `op`. + * + * The callback receives a `ClientContext` for calling agent-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | AgentApp, + op: (context: ClientContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.agent)); + } + /** + * Registers a handler that runs when this client app opens a connection. + * + * Use this for connection-scoped work that needs to call agent-side ACP + * methods outside an inbound request handler. + */ + onConnect(handler: ClientConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + /** + * Registers a client request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: ClientRequestHandler): this; + onRequest( + method: Method, + handler: ClientRequestHandlersByMethod[Method], + ): this; + onRequest( + method: string, + params: ParamsParser, + handler: ClientRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | ClientRequestHandlersByMethod[ClientRequestMethod] + | ClientRequestHandler + | ParamsParser, + handler?: ClientRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as ClientRequestHandler, + ); + } + if (handler) { + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = clientRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + return this.request( + spec as AcpRequestSpec, + handlerOrParams as ClientRequestHandler, + ); + } + /** + * Registers a client notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. To apply a session's + * `session/update` notifications in the order they are received, a handler + * that awaits before applying an update must serialize that work itself, for + * example by chaining it onto a per-session promise. {@link ActiveSession} + * already queues updates in arrival order. + */ + onNotification( + method: "*", + handler: ClientNotificationHandler, + ): this; + onNotification( + method: Method, + handler: ClientNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: string, + params: ParamsParser, + handler: ClientNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | ClientNotificationHandlersByMethod[ClientNotificationMethod] + | ClientNotificationHandler + | ParamsParser, + handler?: ClientNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as ClientNotificationHandler, + ); + } + if (handler) { + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = clientNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as ClientNotificationHandler, + ); + } + private request( + spec: AcpRequestSpec, + handler: ClientRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + clientRequestContext( + params, + ClientContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.mapResponse, + ); + return this; + } + private notification( + spec: AcpNotificationSpec, + handler: ClientNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + clientNotificationContext( + params, + ClientContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + private connectConnection(target: Stream | AgentApp): ClientConnectionState { + if (isStream(target)) { + const state = this.openStreamConnection(target); + this[runClientConnectHandlers](state.connection); + return state; + } + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = agentConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); + try { + target[runAgentConnectHandlers](peerConnection); + this[runClientConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + private openStreamConnection(stream: Stream): ClientConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: clientConnection(rawConnection, this.connectHandlers), + }; + } +} +/** + * Handle for controlling and monitoring a terminal created via `createTerminal`. + * + * Provides methods to: + * - Get current output without waiting + * - Wait for command completion + * - Kill the running command + * - Release terminal resources + * + * **Important:** Always call `release()` when done with the terminal to free resources. + + * The terminal supports async disposal via `Symbol.asyncDispose` for automatic cleanup. + + * You can use `await using` to ensure the terminal is automatically released when it + * goes out of scope. + */ +export class TerminalHandle { + /** + * Terminal identifier returned by `terminal/create`. + */ + public id: string; + private sessionId: string; + private connection: Pick; + private constructor( + id: string, + sessionId: string, + conn: Pick, + ) { + this.id = id; + this.sessionId = sessionId; + this.connection = conn; + } + /** @internal */ + static create( + id: string, + sessionId: string, + conn: Pick, + ): TerminalHandle { + return new TerminalHandle(id, sessionId, conn); + } + /** + * Gets the current terminal output without waiting for the command to exit. + */ + currentOutput(): Promise { + return this.connection.sendRequest(schema.CLIENT_METHODS.terminal_output, { + sessionId: this.sessionId, + terminalId: this.id, + }); + } + /** + * Waits for the terminal command to complete and returns its exit status. + */ + waitForExit(): Promise { + return this.connection.sendRequest( + schema.CLIENT_METHODS.terminal_wait_for_exit, + { + sessionId: this.sessionId, + terminalId: this.id, + }, + ); + } + /** + * Kills the terminal command without releasing the terminal. + * + * The terminal remains valid after killing, allowing you to: + * - Get the final output with `currentOutput()` + * - Check the exit status + * - Release the terminal when done + * + * Useful for implementing timeouts or cancellation. + */ + kill(): Promise { + return this.connection.sendRequest< + schema.KillTerminalRequest, + schema.KillTerminalResponse + >( + schema.CLIENT_METHODS.terminal_kill, + { + sessionId: this.sessionId, + terminalId: this.id, + }, + emptyObjectResponse, + ); + } + /** + * Releases the terminal and frees all associated resources. + * + * If the command is still running, it will be killed. + * After release, the terminal ID becomes invalid and cannot be used + * with other terminal methods. + * + * Tool calls that already reference this terminal will continue to + * display its output. + * + * **Important:** Always call this method when done with the terminal. + */ + release(): Promise { + return this.connection.sendRequest< + schema.ReleaseTerminalRequest, + schema.ReleaseTerminalResponse | void + >( + schema.CLIENT_METHODS.terminal_release, + { + sessionId: this.sessionId, + terminalId: this.id, + }, + emptyObjectResponse, + ); + } + /** + * Releases the terminal when used with `await using`. + */ + async [Symbol.asyncDispose](): Promise { + await this.release(); + } +} diff --git a/src/v1/stable/methods.ts b/src/v1/stable/methods.ts new file mode 100644 index 00000000..e616d012 --- /dev/null +++ b/src/v1/stable/methods.ts @@ -0,0 +1,52 @@ +// Generated from src/v1/methods.ts. Do not edit directly. +import * as schema from "../schema/index.js"; +/** + * ACP method-name constants. + * + * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and + * `notify(...)` when you want literal-string type inference without spelling + * protocol strings inline. + */ +export const methods = { + agent: { + initialize: schema.AGENT_METHODS.initialize, + authenticate: schema.AGENT_METHODS.authenticate, + logout: schema.AGENT_METHODS.logout, + session: { + new: schema.AGENT_METHODS.session_new, + load: schema.AGENT_METHODS.session_load, + list: schema.AGENT_METHODS.session_list, + delete: schema.AGENT_METHODS.session_delete, + resume: schema.AGENT_METHODS.session_resume, + close: schema.AGENT_METHODS.session_close, + setMode: schema.AGENT_METHODS.session_set_mode, + setConfigOption: schema.AGENT_METHODS.session_set_config_option, + prompt: schema.AGENT_METHODS.session_prompt, + cancel: schema.AGENT_METHODS.session_cancel, + }, + }, + client: { + session: { + requestPermission: schema.CLIENT_METHODS.session_request_permission, + update: schema.CLIENT_METHODS.session_update, + }, + fs: { + writeTextFile: schema.CLIENT_METHODS.fs_write_text_file, + readTextFile: schema.CLIENT_METHODS.fs_read_text_file, + }, + terminal: { + create: schema.CLIENT_METHODS.terminal_create, + output: schema.CLIENT_METHODS.terminal_output, + release: schema.CLIENT_METHODS.terminal_release, + waitForExit: schema.CLIENT_METHODS.terminal_wait_for_exit, + kill: schema.CLIENT_METHODS.terminal_kill, + }, + elicitation: { + create: schema.CLIENT_METHODS.elicitation_create, + complete: schema.CLIENT_METHODS.elicitation_complete, + }, + }, + protocol: { + cancelRequest: schema.PROTOCOL_METHODS.cancel_request, + }, +} as const; diff --git a/src/v2/acp.ts b/src/v2/acp.ts index 62130dd3..47985ed3 100644 --- a/src/v2/acp.ts +++ b/src/v2/acp.ts @@ -42,26 +42,15 @@ * @experimental */ -import * as schema from "./unstable/schema/index.js"; -import * as validate from "./unstable/schema/zod.gen.js"; -import * as guards from "./unstable/schema/guards.gen.js"; +import type { AnyMessage } from "../core/jsonrpc.js"; import { ndJsonStream as createJsonStream } from "../core/stream.js"; import type { NdJsonStreamOptions } from "../core/stream.js"; -import { - parseParams, - registerAppNotification, - registerAppRequest, -} from "../core/app-handlers.js"; -import type { ParamsParser } from "../core/app-handlers.js"; -export type { ParamsParser } from "../core/app-handlers.js"; + +export * from "./bindings.js"; +export { methods } from "./methods.js"; export type * from "./unstable/schema/types.gen.js"; -// Runtime narrowing helpers for extensible unions, exposed as companion values -// that merge (declaration merging) with the like-named types — e.g. -// `CreateElicitationResponse.isAccept(response)`. See schema/guards.gen.ts. -// -// Listed explicitly (not `export *`) so each value+type pair merges rather than -// colliding with the `export type *` above. The guards.gen re-export test -// asserts this list stays in sync as new extensible unions are added. +// List guards explicitly so their value/type pairs merge rather than colliding +// with the type exports above. The guards.gen re-export test checks this list. export { AuthMethod, AvailableCommand, @@ -127,6 +116,7 @@ export { MessageTooLargeError, } from "../core/stream-limits.js"; export type { NdJsonStreamOptions } from "../core/stream.js"; +export type { ParamsParser } from "../core/app-handlers.js"; export { AgentProtocolRouter, agentProtocolRouter, @@ -147,3605 +137,3 @@ export type { Result, SendRequestOptions, } from "../core/jsonrpc.js"; - -import { - Connection, - Handled, - HandlerRegistration, - isRecord, - isV2RequestId, - RequestError, - respondWithNullId, - treatSessionNotFoundAsSuccess, -} from "../core/jsonrpc.js"; -import { connectionContextOf } from "../core/connection-access.js"; -import type { - AnyMessage, - ConnectionBuilder, - ConnectionContext, - HandleResult, - IncomingMessage, - JsonRpcId, - JsonRpcHandler, - MaybePromise, - SendRequestOptions, -} from "../core/jsonrpc.js"; - -/** - * ACP v2 extension method name. - * - * New custom methods should begin with `_` so they cannot collide with present - * or future protocol methods. - * - * @experimental - */ -export type ExtensionMethod = `_${string}`; - -/** - * A method name that is not part of the current ACP v2 draft. - * - * This compatibility type permits methods from older or newer unstable ACP - * revisions while preventing current built-in method literals from falling - * through the untyped overloads. Prefer {@link ExtensionMethod} for new custom - * methods. - * - * @experimental - */ -export type UnrecognizedMethod = string extends Method - ? Method - : Method extends - | AgentRequestMethod - | AgentNotificationMethod - | ClientRequestMethod - | ClientNotificationMethod - | typeof schema.PROTOCOL_METHODS.cancel_request - ? never - : Method; - -function emptyObjectResponse(response: T | null | undefined | void): T { - return response ?? ({} as T); -} - -const knownProtocolMethods = new Set([ - ...Object.values(schema.AGENT_METHODS), - ...Object.values(schema.CLIENT_METHODS), - ...Object.values(schema.PROTOCOL_METHODS), -]); - -function assertV2MethodDirection( - method: string, - builtIns: Record, - kind: "request" | "notification", - allowProtocolNotification = false, -): void { - if ( - Object.hasOwn(builtIns, method) || - (allowProtocolNotification && - method === schema.PROTOCOL_METHODS.cancel_request) - ) { - return; - } - if (knownProtocolMethods.has(method)) { - throw new TypeError( - `ACP v2 ${kind} method '${method}' is not valid in this direction`, - ); - } -} - -function assertUnrecognizedV2Method( - method: string, - kind: "request" | "notification", -): void { - if (knownProtocolMethods.has(method)) { - throw new TypeError( - `Cannot replace the built-in ACP v2 ${kind} parser for '${method}'`, - ); - } -} - -/** - * Client info substituted when an `initialize` request written for a newer - * protocol version has a missing or malformed `info`. - */ -const UNKNOWN_IMPLEMENTATION: schema.Implementation = { - name: "unknown", - version: "unknown", -}; - -function readInitializeProtocolVersion( - params: unknown, -): schema.ProtocolVersion { - return received(validate.zProtocolVersion).parse( - isPlainObject(params) ? params["protocolVersion"] : undefined, - ); -} - -function parseV2InitializeRequest(params: unknown): schema.InitializeRequest { - const protocolVersion = readInitializeProtocolVersion(params); - if (protocolVersion < schema.PROTOCOL_VERSION) { - throw RequestError.unsupportedProtocolVersion(protocolVersion, [ - schema.PROTOCOL_VERSION, - ]); - } - // A request for a newer version was written for a schema this endpoint does - // not know, so keep whatever parses under v2 instead of rejecting it. - // Capabilities and `_meta` already drop malformed values field by field; - // only the required `info` needs a substitute. - const lenient = - protocolVersion > schema.PROTOCOL_VERSION && isPlainObject(params); - const request = received( - validate.zInitializeRequest, - ).parse( - lenient && !validate.zImplementation.safeParse(params["info"]).success - ? { ...params, info: UNKNOWN_IMPLEMENTATION } - : params, - ); - return structuredClone({ - ...request, - protocolVersion: schema.PROTOCOL_VERSION, - }); -} - -function isPlainObject(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function normalizeOutgoingV2InitializeRequest(params: unknown): { - wire: schema.InitializeRequest; - parsed: schema.InitializeRequest; -} { - const request = - typeof params === "object" && params !== null && !Array.isArray(params) - ? (params as Record) - : {}; - const outgoing = { - ...request, - protocolVersion: schema.PROTOCOL_VERSION, - }; - // Parsing supplies a validated local view, not the payload to transmit. - // In particular, Zod strips future capability fields from that view. - const parsed = parseV2InitializeRequest(outgoing); - return { - wire: structuredClone(outgoing) as schema.InitializeRequest, - parsed, - }; -} - -function mapV2InitializeResponse(response: unknown): schema.InitializeResponse { - const parsed = received( - validate.zInitializeResponse, - ).parse(response); - if (parsed.protocolVersion !== schema.PROTOCOL_VERSION) { - throw RequestError.invalidRequest( - { - expectedProtocolVersion: schema.PROTOCOL_VERSION, - receivedProtocolVersion: parsed.protocolVersion, - }, - `The v2 API only supports protocol version ${schema.PROTOCOL_VERSION}`, - ); - } - return structuredClone(parsed); -} - -function serializeV2InitializeResponse( - response: schema.InitializeResponse, -): schema.InitializeResponse { - // Keep validation separate from serialization, as for outgoing requests. - mapV2InitializeResponse(response); - return structuredClone(response); -} - -/** - * Validated initialize request and response for one ACP v2 connection. - * - * The snapshot becomes available only after the initialize response has been - * validated and sent or received successfully. When the Client repeats - * `initialize`, the latest successful exchange replaces the snapshot. - * - * @experimental - */ -export type InitializationSnapshot = Readonly<{ - request: schema.InitializeRequest; - response: schema.InitializeResponse; -}>; - -type InitializationPhase = - "uninitialized" | "initializing" | "initialized" | "failed"; - -function cloneInitialization( - initialization: InitializationSnapshot, -): InitializationSnapshot { - return structuredClone(initialization); -} - -function deferred(): { - promise: Promise; - resolve(value: T | PromiseLike): void; - reject(reason?: unknown): void; -} { - let resolve!: (value: T | PromiseLike) => void; - let reject!: (reason?: unknown) => void; - const promise = new Promise((resolvePromise, rejectPromise) => { - resolve = resolvePromise; - reject = rejectPromise; - }); - return { promise, resolve, reject }; -} - -/** - * Initialization lifecycle of one ACP v2 connection side. - * - * The Client may repeat `initialize` after a previous one completed, as long - * as it has not sent any other request. A repeat that fails leaves the - * previous initialization in effect. A first `initialize` that fails leaves - * the connection uninitialized, so the Client may send `initialize` again. - */ -class InitializationState { - private phase: InitializationPhase = "uninitialized"; - private request?: schema.InitializeRequest; - private snapshot?: InitializationSnapshot; - private otherRequestSeen = false; - private attempt = deferred(); - private readonly barrier = deferred(); - - constructor() { - void this.barrier.promise.catch(() => {}); - this.attempt.resolve(); - } - - get status(): InitializationPhase { - return this.phase; - } - - get initialized(): Promise { - return this.barrier.promise - .then(() => this.attempt.promise) - .then(() => cloneInitialization(this.snapshot!)); - } - - /** - * Returns why `initialize` cannot start now, or `undefined` if it can. - */ - beginError(): RequestError | undefined { - if (this.phase === "initializing") { - return RequestError.invalidRequest( - "ACP v2 initialize is already in progress", - ); - } - if (this.phase === "failed") { - return RequestError.invalidRequest( - "ACP v2 connection initialization failed", - ); - } - if (this.phase === "initialized" && this.otherRequestSeen) { - return RequestError.invalidRequest( - "ACP v2 initialize must not be repeated after other requests", - ); - } - return undefined; - } - - begin(request: schema.InitializeRequest): void { - const error = this.beginError(); - if (error) { - throw error; - } - - const requestSnapshot = structuredClone(request); - this.request = requestSnapshot; - this.phase = "initializing"; - this.attempt = deferred(); - } - - complete(response: schema.InitializeResponse): void { - if (this.phase !== "initializing" || !this.request) { - throw RequestError.invalidRequest( - "ACP v2 initialization is not in progress", - ); - } - - const initialization = { - request: structuredClone(this.request), - response: structuredClone(response), - }; - this.snapshot = initialization; - this.request = undefined; - this.phase = "initialized"; - this.barrier.resolve(initialization); - this.attempt.resolve(); - } - - /** - * Whether an `initialize` exchange has completed, including while a repeat - * is in progress. - */ - get hasInitialized(): boolean { - return this.snapshot !== undefined && this.phase !== "failed"; - } - - /** - * Fails the initialize attempt in progress. A failed repeat keeps the - * previous initialization; a failed first attempt leaves the connection - * uninitialized so `initialize` can be sent again. - */ - failAttempt(): void { - if (this.phase !== "initializing") { - return; - } - this.phase = this.snapshot ? "initialized" : "uninitialized"; - this.request = undefined; - this.attempt.resolve(); - } - - /** - * Fails initialization for good, such as when the connection closes before - * it was initialized. A failed repeat keeps the previous initialization. - */ - fail(error?: unknown): void { - if (this.phase === "initializing" && this.snapshot) { - this.failAttempt(); - return; - } - if (this.phase === "uninitialized" || this.phase === "initializing") { - this.phase = "failed"; - this.request = undefined; - this.barrier.reject( - error ?? - RequestError.invalidRequest( - "ACP v2 connection initialization failed", - ), - ); - this.attempt.resolve(); - } - } - - /** - * Records a request other than `initialize`, after which `initialize` may - * no longer be repeated. - */ - noteRequest(): void { - if (this.phase === "initializing" || this.phase === "initialized") { - this.otherRequestSeen = true; - } - } - - waitUntilInitialized(method: string): Promise { - if (this.phase === "initialized") { - return Promise.resolve(); - } - if (this.phase === "initializing") { - // Settles with the attempt: a failed first attempt rejects, since the - // connection is uninitialized again. - return this.attempt.promise.then(() => this.waitUntilInitialized(method)); - } - if (this.phase === "failed") { - return this.barrier.promise.then(() => {}); - } - return Promise.reject(initializationUnavailable(method)); - } -} - -const initializationStates = new WeakMap< - ConnectionContext, - InitializationState ->(); - -function initializationState(cx: ConnectionContext): InitializationState { - let state = initializationStates.get(cx); - if (!state) { - state = new InitializationState(); - initializationStates.set(cx, state); - if (cx.signal.aborted) { - state.fail(cx.signal.reason); - } else { - cx.signal.addEventListener("abort", () => state?.fail(cx.signal.reason), { - once: true, - }); - } - } - return state; -} - -function initializationUnavailable(method: string): RequestError { - return RequestError.invalidRequest( - `ACP v2 connection must be initialized before '${method}'`, - ); -} - -/** - * Rejects a request received before initialization with `-32600` and ignores - * a notification. Neither changes the initialization state, so the peer can - * still initialize the connection. - */ -async function blockUninitializedIncoming( - message: IncomingMessage, -): Promise { - return rejectIncoming(message, initializationUnavailable(message.method)); -} - -async function rejectIncoming( - message: IncomingMessage, - error: RequestError, -): Promise { - if (message.kind === "request") { - await message.responder.respondWithError(error); - } - return Handled.yes(); -} - -/** - * Rejects requests whose ID is `null` or a non-integer number, which ACP v2 - * does not allow. The error response uses `id: null` because the request ID - * is unusable. - */ -async function rejectInvalidRequestId( - message: IncomingMessage, -): Promise { - if (message.kind !== "request" || isV2RequestId(message.raw.id)) { - return undefined; - } - await respondWithNullId( - message.responder, - RequestError.invalidRequest( - undefined, - "ACP v2 request IDs must be strings or integers", - ), - ); - return Handled.yes(); -} - -async function waitUntilInitializedIncoming( - message: IncomingMessage, - state: InitializationState, -): Promise { - if (state.status === "initialized") { - return Handled.no(message); - } - if (state.status === "initializing") { - try { - await state.waitUntilInitialized(message.method); - } catch { - return blockUninitializedIncoming(message); - } - return Handled.no(message); - } - return blockUninitializedIncoming(message); -} - -/** - * Answers `tool_call/cancel` and `terminal/cancel` with `-32602` when the app - * has no handler for them. Neither method has an initialize-time capability: - * an Agent that never advertises `capabilities.cancel` on a tool call or - * terminal has nothing to cancel, and the spec answers a request for an - * unknown or non-cancellable entity with `-32602`, not `-32601`. - */ -function defaultEntityCancelHandler( - handles: (method: string) => boolean, -): JsonRpcHandler { - const entities: Record = { - [schema.AGENT_METHODS.tool_call_cancel]: { - key: "toolCallId", - label: "tool call", - }, - [schema.AGENT_METHODS.terminal_cancel]: { - key: "terminalId", - label: "terminal", - }, - }; - return { - async handleMessage(message) { - const entity = Object.hasOwn(entities, message.method) - ? entities[message.method] - : undefined; - if (message.kind !== "request" || !entity || handles(message.method)) { - return Handled.no(message); - } - const id = isRecord(message.params) - ? message.params[entity.key] - : undefined; - return rejectIncoming( - message, - RequestError.invalidParams( - typeof id === "string" ? { [entity.key]: id } : undefined, - `the ${entity.label} is unknown or not cancellable`, - ), - ); - }, - describe: () => "default-entity-cancel", - }; -} - -function agentInitializationGuard(): JsonRpcHandler { - return { - async handleMessage(message, cx) { - const invalidId = await rejectInvalidRequestId(message); - if (invalidId) { - return invalidId; - } - - const state = initializationState(cx); - if (message.kind === "notification") { - // The connection already applied `$/cancel_request`. Agents ignore - // other notifications that arrive before initialization completes. - if ( - message.method === schema.PROTOCOL_METHODS.cancel_request || - !state.hasInitialized - ) { - return Handled.yes(); - } - return waitUntilInitializedIncoming(message, state); - } - - if (message.method === schema.AGENT_METHODS.initialize) { - // The Client may repeat initialize after the previous one completed - // and before any other request. A repeat that fails leaves the - // previous initialization in effect. - const beginError = state.beginError(); - if (beginError) { - return rejectIncoming(message, beginError); - } - - // A malformed initialize throws before `begin`, so it leaves the - // connection as it was: uninitialized, or with the previous - // initialization in effect. - if ( - state.status === "initialized" && - readInitializeProtocolVersion(message.params) < - schema.PROTOCOL_VERSION - ) { - // A repeat must use the version the previous response selected. - return rejectIncoming( - message, - RequestError.invalidRequest( - undefined, - `a repeated initialize must request protocol version ${schema.PROTOCOL_VERSION} or later`, - ), - ); - } - state.begin(parseV2InitializeRequest(message.params)); - return Handled.no(message); - } - - // Requests other than initialize must not wait for an in-flight - // initialize: the spec requires rejecting them until it completes. - if (state.status === "initialized") { - state.noteRequest(); - return Handled.no(message); - } - return blockUninitializedIncoming(message); - }, - describe: () => "agent-initialization", - }; -} - -function clientInitializationGuard(): JsonRpcHandler { - return { - async handleMessage(message, cx) { - const invalidId = await rejectInvalidRequestId(message); - if (invalidId) { - return invalidId; - } - - const state = initializationState(cx); - if ( - message.kind === "notification" && - message.method === schema.PROTOCOL_METHODS.cancel_request - ) { - // The connection already applied it. - return Handled.yes(); - } - return waitUntilInitializedIncoming(message, state); - }, - describe: () => "client-initialization", - }; -} - -function parseRequestResponse( - spec: { response?: ParamsParser }, - response: unknown, -): unknown { - return parseParams(spec.response, response); -} - -function isStream(value: unknown): value is Stream { - return ( - typeof value === "object" && - value !== null && - "readable" in value && - "writable" in value - ); -} - -function memoryStreamPair(): [Stream, Stream] { - const leftToRight = new TransformStream(); - const rightToLeft = new TransformStream(); - return [ - { - readable: rightToLeft.readable, - writable: leftToRight.writable, - }, - { - readable: leftToRight.readable, - writable: rightToLeft.writable, - }, - ]; -} - -type McpTransportCapability = Exclude; - -// Transport keys of `session.mcp`: `stdio` and `http`, plus `acp` with the -// unstable schema. Read from the schema so each entrypoint checks only the -// transports its own `McpCapabilities` type can advertise. -const MCP_TRANSPORT_CAPABILITIES: ReadonlyArray = Object.keys( - validate.zMcpCapabilities.shape, -).filter((key) => key !== "_meta"); - -/** - * Throws `-32602` (Invalid params) for the first MCP server the agent cannot - * accept: one whose `name` repeats an earlier server's, or whose transport the - * agent did not advertise in `session.mcp`. - * - * Call it from `session/new`, `session/resume`, or `session/fork` handlers with - * the `capabilities.session.mcp` value the agent sent in its `initialize` - * response. Each server `name` must be unique within the list; a duplicate is - * rejected with error data `{ name }`. A server is accepted only when its - * `type` is a transport key in that object with a non-null value, for example - * `stdio` with `{ stdio: {} }`. Everything else is rejected, including v1's - * `sse`, unknown types, and custom `_`-prefixed types; agents that support a - * custom transport should handle those servers before calling this. The error - * data for a transport is `{ type }` with the rejected server's transport. - * - * @experimental - */ -export function assertSupportedMcpServers( - mcpServers: ReadonlyArray | null | undefined, - capabilities: schema.McpCapabilities | null | undefined, -): void { - const names = new Set(); - for (const server of mcpServers ?? []) { - const { name, type } = server; - if (typeof name === "string") { - if (names.has(name)) { - throw RequestError.invalidParams( - { name }, - `Duplicate MCP server name ${name}`, - ); - } - names.add(name); - } - if ( - !MCP_TRANSPORT_CAPABILITIES.includes(type) || - capabilities?.[type as McpTransportCapability] == null - ) { - throw RequestError.invalidParams( - { type }, - `Unsupported MCP server transport ${type}`, - ); - } - } -} - -/** - * ACP method-name constants for the experimental draft v2 API. - * - * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and - * `notify(...)` when you want literal-string type inference without spelling - * protocol strings inline. - * - * @experimental - */ -export const methods = { - agent: { - initialize: schema.AGENT_METHODS.initialize, - auth: { - login: schema.AGENT_METHODS.auth_login, - logout: schema.AGENT_METHODS.auth_logout, - status: schema.AGENT_METHODS.auth_status, - }, - providers: { - list: schema.AGENT_METHODS.providers_list, - set: schema.AGENT_METHODS.providers_set, - disable: schema.AGENT_METHODS.providers_disable, - }, - session: { - new: schema.AGENT_METHODS.session_new, - list: schema.AGENT_METHODS.session_list, - delete: schema.AGENT_METHODS.session_delete, - fork: schema.AGENT_METHODS.session_fork, - archive: schema.AGENT_METHODS.session_archive, - unarchive: schema.AGENT_METHODS.session_unarchive, - status: schema.AGENT_METHODS.session_status, - options: schema.AGENT_METHODS.session_options, - setTitle: schema.AGENT_METHODS.session_set_title, - resume: schema.AGENT_METHODS.session_resume, - close: schema.AGENT_METHODS.session_close, - setConfigOption: schema.AGENT_METHODS.session_set_config_option, - prompt: schema.AGENT_METHODS.session_prompt, - cancel: schema.AGENT_METHODS.session_cancel, - }, - toolCall: { - cancel: schema.AGENT_METHODS.tool_call_cancel, - }, - terminal: { - cancel: schema.AGENT_METHODS.terminal_cancel, - }, - mcp: { - message: schema.AGENT_METHODS.mcp_message, - }, - }, - client: { - session: { - requestPermission: schema.CLIENT_METHODS.session_request_permission, - update: schema.CLIENT_METHODS.session_update, - }, - mcp: { - message: schema.CLIENT_METHODS.mcp_message, - }, - elicitation: { - create: schema.CLIENT_METHODS.elicitation_create, - complete: schema.CLIENT_METHODS.elicitation_complete, - }, - auth: { - statusUpdate: schema.CLIENT_METHODS.auth_status_update, - }, - }, - protocol: { - cancelRequest: schema.PROTOCOL_METHODS.cancel_request, - }, -} as const; - -const startActiveSession = Symbol("startActiveSession"); -const routeActiveSessionUpdate = Symbol("routeActiveSessionUpdate"); - -/** - * Experimental draft ACP v2 connection returned by `AgentApp.connect(...)` and - * `ClientApp.connect(...)`. - * - * Use this handle when you need a connection to stay open independently of a - * single `connectWith(...)` operation. - * - * @experimental - */ -export interface AcpConnection { - /** - * Resolves with the validated initialize exchange once initialization - * succeeds, or rejects if initialization or the connection fails. - * - * After a repeated `initialize` completes, reading this again resolves with - * the latest exchange. - */ - readonly initialized: Promise; - - /** - * AbortSignal that aborts when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after the signal aborts. - */ - readonly signal: AbortSignal; - - /** - * Promise that resolves when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after this resolves. - */ - readonly closed: Promise; - - /** - * Closes the connection and rejects pending requests. Messages received but - * not yet dispatched are dropped. Does nothing once the connection is closed. - */ - close(error?: unknown): void; -} - -/** - * Experimental draft ACP v2 agent-side connection returned by - * `AgentApp.connect(...)`. - * - * Use `client` to call client-side ACP methods for the lifetime of the - * connection. - * - * @experimental - */ -export interface AgentConnection extends AcpConnection { - /** - * Context for calling client-side ACP methods. - */ - readonly client: AgentContext; -} - -/** - * Experimental draft ACP v2 client-side connection returned by - * `ClientApp.connect(...)`. - * - * Use `agent` to call agent-side ACP methods and session helpers for the - * lifetime of the connection. - * - * @experimental - */ -export interface ClientConnection extends AcpConnection { - /** - * Context for calling agent-side ACP methods. - */ - readonly agent: ClientContext; -} - -class AcpContext { - /** @internal */ - constructor( - private readonly cx: ConnectionContext, - private readonly currentRequestId?: JsonRpcId, - ) {} - - /** - * Validated initialize exchange, once this connection is initialized. - */ - get initialized(): Promise { - return initializationState(this.cx).initialized; - } - - /** @internal */ - protected get initializationLifecycle(): InitializationState { - return initializationState(this.cx); - } - - /** - * JSON-RPC id of the request currently being handled. - * - * This is `undefined` for notification handlers and for contexts created - * outside an inbound request, such as `connect(...)` and `connectWith(...)`. - */ - get requestId(): JsonRpcId | undefined { - return this.currentRequestId; - } - - /** @internal */ - protected get connectionContext(): ConnectionContext { - return this.cx; - } - - /** @hidden SDK helpers use this to identify the connection. */ - [connectionContextOf](): ConnectionContext { - return this.cx; - } - - /** @internal */ - protected sendRequest( - method: string, - params?: Req, - mapResponse?: (response: Resp) => Output, - options?: SendRequestOptions, - ): Promise { - return this.cx.sendRequest(method, params, mapResponse, options); - } - - /** @internal */ - protected sendNotification(method: string, params?: N): Promise { - return this.cx.sendNotification(method, params); - } - - /** @internal */ - protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { - return this.cx.addDynamicHandler(handler); - } -} - -/** - * Experimental draft ACP v2 context passed to agent-side handlers. - * - * Agents use this context to call client-side ACP methods while handling - * requests such as `session/prompt`. - * - * @experimental - */ -export class AgentContext extends AcpContext { - private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { - super(cx, requestId); - } - - /** @internal */ - static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { - return new AgentContext(cx, requestId); - } - - /** - * Sends a request to the client by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - */ - request( - method: Method, - params: ClientRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: ExtensionMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request< - Response = unknown, - Params = unknown, - const Method extends string = never, - >( - method: UnrecognizedMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - assertV2MethodDirection(method, clientRequestSpecsByMethod, "request"); - const spec = clientRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - return this.initializationLifecycle - .waitUntilInitialized(method) - .then(() => - this.sendRequest( - method, - params, - spec ? (response) => parseRequestResponse(spec, response) : undefined, - options, - ), - ); - } - - /** - * Sends a notification to the client by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: ClientNotificationParamsByMethod[Method], - ): Promise; - notify( - method: typeof schema.PROTOCOL_METHODS.cancel_request, - params: schema.CancelRequestNotification, - ): Promise; - notify( - method: ExtensionMethod, - params?: Params, - ): Promise; - notify( - method: UnrecognizedMethod, - params?: Params, - ): Promise; - notify(method: string, params?: unknown): Promise { - assertV2MethodDirection( - method, - clientNotificationSpecsByMethod, - "notification", - true, - ); - return this.initializationLifecycle - .waitUntilInitialized(method) - .then(() => this.sendNotification(method, params)); - } -} - -/** - * Experimental draft ACP v2 context used by clients to call agent-side ACP - * methods. - * - * `connectWith` passes a `ClientContext` to the callback. Client handlers also - * receive one as `ctx.agent` when they need to call back into the agent. - * - * @experimental - */ -export class ClientContext extends AcpContext { - private constructor( - cx: ConnectionContext, - requestId?: JsonRpcId, - private readonly closeOnInitializationFailure?: (error: unknown) => void, - ) { - super(cx, requestId); - } - - /** @internal */ - static create( - cx: ConnectionContext, - requestId?: JsonRpcId, - closeOnInitializationFailure?: (error: unknown) => void, - ): ClientContext { - return new ClientContext(cx, requestId, closeOnInitializationFailure); - } - - /** @internal */ - [startActiveSession]( - params: schema.NewSessionRequest, - options?: SendRequestOptions, - ): Promise { - return this.request(schema.AGENT_METHODS.session_new, params, options).then( - (response) => this.attachSession(response), - ); - } - - /** - * Creates a builder for starting and observing an ACP session. - * - * Pass an absolute path for the common case where only `cwd` is needed, or - * pass a full `NewSessionRequest` when you need MCP servers, `_meta`, or - * additional session fields. - */ - buildSession(cwd: schema.AbsolutePath): SessionBuilder; - buildSession(request: schema.NewSessionRequest): SessionBuilder; - buildSession( - cwdOrRequest: schema.AbsolutePath | schema.NewSessionRequest, - ): SessionBuilder { - if (typeof cwdOrRequest === "string") { - return SessionBuilder.create(this, { - cwd: cwdOrRequest, - mcpServers: [], - }); - } - - return SessionBuilder.create(this, cwdOrRequest); - } - - /** - * Builds active-session helpers around a `session/new` response. - */ - private attachSession(response: schema.NewSessionResponse): ActiveSession { - const updates = new AsyncQueue(); - const closeSignal = this.connectionContext.signal; - const failUpdatesOnClose = () => { - updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); - }; - if (closeSignal.aborted) { - failUpdatesOnClose(); - } else { - closeSignal.addEventListener("abort", failUpdatesOnClose); - } - const registrations: HandlerRegistration[] = []; - const session = ActiveSession.create( - this, - response, - updates, - registrations, - ); - registrations.push( - sessionUpdateRouter(this.connectionContext).attach(response, { - enqueue: (message) => session[routeActiveSessionUpdate](message), - }), - new HandlerRegistration(() => { - closeSignal.removeEventListener("abort", failUpdatesOnClose); - }), - ); - - return session; - } - - /** - * Sends a request to the agent by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - * - * Other requests wait until `initialize` has completed. `initialize` may be - * repeated once the previous one completed and before any other request has - * been sent; otherwise it throws `-32600` synchronously. A repeat that fails - * leaves the previous initialization in effect, and a first `initialize` - * that gets an error response leaves the connection uninitialized, so it can - * be sent again. - * - * Closing or deleting a session is idempotent: a `-32002` (Resource not - * found) response to `session/close` or `session/delete` resolves with an - * empty result instead of rejecting. - */ - request( - method: Method, - params: AgentRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: ExtensionMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request< - Response = unknown, - Params = unknown, - const Method extends string = never, - >( - method: UnrecognizedMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - assertV2MethodDirection(method, agentRequestSpecsByMethod, "request"); - const spec = agentRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - const state = this.initializationLifecycle; - if (method === schema.AGENT_METHODS.initialize) { - const { wire: request, parsed } = - normalizeOutgoingV2InitializeRequest(params); - state.begin(parsed); - - let response: Promise; - // Set when the agent answered with a response this client cannot use, - // as opposed to an error response. - let unusableResponse = false; - try { - response = this.sendRequest( - method, - request, - (value) => { - try { - const parsed = parseRequestResponse(spec!, value); - state.complete(parsed as schema.InitializeResponse); - return parsed; - } catch (error) { - unusableResponse = true; - throw error; - } - }, - options, - ); - } catch (error) { - this.failInitialization(error); - throw error; - } - void response.catch((error) => { - if (state.status === "initializing") { - if (unusableResponse) { - this.failInitialization(error); - } else { - // An error response leaves the connection as it was, so the - // client may send initialize again. - state.failAttempt(); - } - } - }); - return response; - } - - state.noteRequest(); - const mapResponse = spec - ? (response: unknown) => parseRequestResponse(spec, response) - : undefined; - return state - .waitUntilInitialized(method) - .then(() => - treatSessionNotFoundAsSuccess( - method, - this.sendRequest(method, params, mapResponse, options), - () => (mapResponse ? mapResponse({}) : {}), - ), - ); - } - - /** - * Fails an initialize attempt. Closes the connection unless a previous - * initialization remains in effect. - */ - private failInitialization(error: unknown): void { - const state = this.initializationLifecycle; - state.fail(error); - if (state.status === "failed") { - this.closeOnInitializationFailure?.(error); - } - } - - /** - * Sends a notification to the agent by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: AgentNotificationParamsByMethod[Method], - ): Promise; - notify( - method: typeof schema.PROTOCOL_METHODS.cancel_request, - params: schema.CancelRequestNotification, - ): Promise; - notify( - method: ExtensionMethod, - params?: Params, - ): Promise; - notify( - method: UnrecognizedMethod, - params?: Params, - ): Promise; - notify(method: string, params?: unknown): Promise { - assertV2MethodDirection( - method, - agentNotificationSpecsByMethod, - "notification", - true, - ); - return this.initializationLifecycle - .waitUntilInitialized(method) - .then(() => this.sendNotification(method, params)); - } -} - -class AcpConnectionHandle implements AcpConnection { - constructor(private readonly connection: Connection) {} - - get initialized(): Promise { - return initializationState(this.connection.getContext()).initialized; - } - - get signal(): AbortSignal { - return this.connection.signal; - } - - get closed(): Promise { - return this.connection.closed; - } - - close(error?: unknown): void { - this.connection.close(error); - } -} - -class AgentConnectionHandle - extends AcpConnectionHandle - implements AgentConnection -{ - readonly client: AgentContext; - private didStartConnectHandlers = false; - - constructor( - connection: Connection, - private readonly connectHandlers: readonly AgentConnectHandler[] = [], - ) { - super(connection); - this.client = AgentContext.create(connection.getContext()); - } - - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} - -class ClientConnectionHandle - extends AcpConnectionHandle - implements ClientConnection -{ - readonly agent: ClientContext; - private didStartConnectHandlers = false; - - constructor( - connection: Connection, - private readonly connectHandlers: readonly ClientConnectHandler[] = [], - ) { - super(connection); - this.agent = ClientContext.create( - connection.getContext(), - undefined, - (error) => connection.close(error), - ); - } - - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} - -function agentConnection( - connection: Connection, - connectHandlers: readonly AgentConnectHandler[] = [], -): AgentConnection { - return new AgentConnectionHandle(connection, connectHandlers); -} - -function clientConnection( - connection: Connection, - connectHandlers: readonly ClientConnectHandler[] = [], -): ClientConnection { - return new ClientConnectionHandle(connection, connectHandlers); -} - -class AsyncQueue { - private values: Array = []; - private waiters: Array<{ - resolve: (value: T) => void; - reject: (error: unknown) => void; - }> = []; - private failed = false; - private failure: unknown; - - enqueue(value: T): void { - if (this.failed) { - return; - } - - const waiter = this.waiters.shift(); - if (waiter) { - waiter.resolve(value); - } else { - this.values.push(value); - } - } - - fail(error: unknown): void { - if (this.failed) { - return; - } - - this.failed = true; - this.failure = error; - for (const waiter of this.waiters.splice(0)) { - waiter.reject(error); - } - } - - next(signal?: AbortSignal): Promise { - if (signal?.aborted) { - return Promise.reject(signal.reason); - } - - if (this.values.length > 0) { - return Promise.resolve(this.values.shift() as T); - } - - if (this.failed) { - return Promise.reject(this.failure); - } - - return new Promise((resolve, reject) => { - const cleanup = (): void => { - signal?.removeEventListener("abort", onAbort); - }; - const waiter = { - resolve: (value: T): void => { - cleanup(); - resolve(value); - }, - reject: (error: unknown): void => { - cleanup(); - reject(error); - }, - }; - const onAbort = (): void => { - const index = this.waiters.indexOf(waiter); - if (index >= 0) { - this.waiters.splice(index, 1); - } - waiter.reject(signal?.reason); - }; - - this.waiters.push(waiter); - signal?.addEventListener("abort", onAbort, { once: true }); - if (signal?.aborted) { - onAbort(); - } - }); - } -} - -/** - * Applies a `capabilities` patch from a `tool_call_update` or - * `terminal_update`: omission leaves it unchanged, `null` clears it, and an - * object replaces it, so `cancel` is supported only when the latest object - * carries a non-null `cancel`. - */ -function applyCancelCapability( - cancellable: Set, - id: Id, - capabilities: { cancel?: unknown } | null | undefined, -): void { - if (capabilities === undefined) { - return; - } - if (capabilities?.cancel != null) { - cancellable.add(id); - } else { - cancellable.delete(id); - } -} - -function cloneNewSessionRequest( - request: schema.NewSessionRequest, -): schema.NewSessionRequest { - return structuredClone(request); -} - -/** - * Experimental draft ACP v2 `session/set_config_option` params for - * `ActiveSession.setConfigOption(...)`; the session ID is filled in. - * - * @experimental - */ -export type ActiveSessionSetConfigOptionRequest = - schema.SetSessionConfigOptionRequest extends infer Request - ? Request extends unknown - ? { - [ - Key in keyof Request as Key extends "sessionId" ? never : Key - ]: Request[Key]; - } - : never - : never; - -type ActiveSessionQueue = Pick< - AsyncQueue, - "enqueue" | "fail" | "next" ->; - -/** - * Experimental draft ACP v2 message produced by an `ActiveSession`. - * - * `session_update` messages expose the typed `session/update` notification and - * `stop` messages report an idle `state_update`. Both are session-scoped: - * a `stop` message does not acknowledge processing or completion of any prompt. - * - * @experimental - */ -export type ActiveSessionMessage = - | { - /** - * Indicates that this message came from a `session/update` notification. - */ - kind: "session_update"; - /** - * Full notification sent by the agent. - */ - notification: schema.UpdateSessionNotification; - /** - * Convenience alias for `notification.update`. - */ - update: schema.SessionUpdate; - } - | { - /** - * Indicates an idle foreground snapshot, not necessarily a new completion. - */ - kind: "stop"; - /** - * Full notification containing the idle state update. - */ - notification: schema.UpdateSessionNotification; - /** - * Convenience alias for `notification.update`. - */ - update: schema.SessionUpdate; - /** - * Stop reason reported by the idle state, when provided. - */ - stopReason: schema.IdleStateUpdate["stopReason"]; - }; - -/** - * Experimental draft ACP v2 builder for creating an `ActiveSession`. - * - * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or - * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session - * needs MCP servers, `_meta`, or additional request fields. All paths in ACP - * payloads should be absolute. - * - * @experimental - */ -export class SessionBuilder { - private request: schema.NewSessionRequest; - - private constructor( - private cx: ClientContext, - request: schema.NewSessionRequest, - ) { - this.request = cloneNewSessionRequest(request); - } - - /** @internal */ - static create( - cx: ClientContext, - request: schema.NewSessionRequest, - ): SessionBuilder { - return new SessionBuilder(cx, request); - } - - /** - * Returns the `session/new` request that will be sent. - * - * The returned object is a defensive copy, so mutating it does not change the - * builder. - */ - toRequest(): schema.NewSessionRequest { - return cloneNewSessionRequest(this.request); - } - - /** - * Replaces the additional workspace roots for this session. - * - * `additionalDirectories` expand the session's file-system scope without - * changing `cwd`. Each path should be absolute. - */ - withAdditionalDirectories( - additionalDirectories: schema.AbsolutePath[], - ): this { - this.request = { - ...this.request, - additionalDirectories: [...additionalDirectories], - }; - return this; - } - - /** - * Adds one MCP server to the `session/new` request. - */ - withMcpServer(mcpServer: schema.McpServer): this { - this.request = { - ...this.request, - mcpServers: [ - ...(this.request.mcpServers ?? []), - structuredClone(mcpServer), - ], - }; - return this; - } - - /** - * Starts the session and returns an `ActiveSession` for prompting and reading - * updates. - * - * Call `dispose()` on the returned session when you no longer need update - * routing, or use `withSession(...)` to scope disposal automatically. - */ - async start(options?: SendRequestOptions): Promise { - return this.cx[startActiveSession](this.toRequest(), options); - } - - /** - * Starts the session, runs `op`, and disposes the active-session update - * routing when `op` finishes or throws. - */ - async withSession( - op: (session: ActiveSession) => MaybePromise, - ): Promise { - const session = await this.start(); - try { - return await op(session); - } finally { - session.dispose(); - } - } -} - -/** - * Experimental draft ACP v2 convenience wrapper for an active session. - * - * An active session routes `session/update` notifications for one session ID - * into an async queue. Use `prompt(...)` to submit user content and - * `nextUpdate()` to observe the session independently of prompt requests. - * A `stop` message reports idle foreground work, not per-prompt completion. - * - * @experimental - */ -export class ActiveSession { - private currentConfigOptions: Array | undefined; - private latestBackground: Array | undefined; - private readonly cancellableToolCalls = new Set(); - private readonly cancellableTerminals = new Set(); - - private constructor( - private cx: ClientContext, - private sessionResponse: schema.NewSessionResponse, - private updates: ActiveSessionQueue, - private registrations: HandlerRegistration[], - ) { - this.currentConfigOptions = sessionResponse.configOptions ?? undefined; - } - - /** @internal */ - static create( - cx: ClientContext, - sessionResponse: schema.NewSessionResponse, - updates: ActiveSessionQueue, - registrations: HandlerRegistration[], - ): ActiveSession { - return new ActiveSession(cx, sessionResponse, updates, registrations); - } - - /** - * Session ID returned by `session/new`. - */ - get sessionId(): schema.SessionId { - return this.sessionResponse.sessionId; - } - - /** - * Current configuration options for this session, if the agent provided any. - * - * Starts with the `configOptions` from `session/new`. It is replaced with the - * full list from each `config_option_update` routed to this session (applied - * when the notification arrives, before it is read with `nextUpdate()`) and - * from each `setConfigOption(...)` response. Updates stop after `dispose()`. - * `newSessionResponse.configOptions` keeps the original `session/new` value. - */ - get configOptions(): Array | undefined { - return this.currentConfigOptions; - } - - /** - * Metadata returned when the session was created. - */ - get meta(): { [key: string]: unknown } | null | undefined { - return this.sessionResponse._meta; - } - - /** - * The `background` list from the latest `state_update` routed to this - * session, or `undefined` while background work is not reported. - * - * Each `state_update` replaces it, applied when the notification arrives, - * before it is read with `nextUpdate()`. `[]` means no background work is - * running. A snapshot that omits the list, carries `null` or a malformed - * list, or reports a state this SDK does not know resets it to `undefined`: - * background work is unknown until a list arrives, and nothing should be - * treated as abandoned. Updates stop after `dispose()`. - */ - get background(): ReadonlyArray | undefined { - return this.latestBackground; - } - - /** - * Whether `request`'s `subject` references work in the latest `background` - * list: a listed tool call (by the subject's `toolCall.toolCallId`, or a - * command subject's `toolCallId`) or a listed terminal (by a command - * subject's `terminalId`). - * - * `session/cancel` does not cover listed work, so permission requests for - * it stay open. For the cancelled foreground work, the Agent stops waiting - * on its permission requests and cancels them with `$/cancel_request`, and - * the Client answers each cancelled request with the `cancelled` outcome. - * A Client may also answer a request with `cancelled` right after sending - * `session/cancel`, without waiting for `$/cancel_request`, but only when - * it knows the request belongs to the cancelled work. A `false` result - * alone does not establish that: it is also returned for requests without - * a `subject`, custom subjects, and any request while `background` is not - * reported. On `session/close`, the Agent cancels every pending permission - * request in the session with `$/cancel_request`. When an Agent sends a - * permission request with `cancellationSignal` and - * `stopWaitingOnCancel: true`, aborting the signal sends - * `$/cancel_request` and stops waiting for the answer. - */ - isForBackgroundWork(request: schema.RequestPermissionRequest): boolean { - const background = this.latestBackground; - const subject = request.subject; - if (!background || !subject) { - return false; - } - let toolCallId: schema.ToolCallId | null | undefined; - let terminalId: schema.TerminalId | null | undefined; - if (guards.RequestPermissionSubject.isToolCall(subject)) { - toolCallId = subject.toolCall.toolCallId; - } else if (guards.RequestPermissionSubject.isCommand(subject)) { - toolCallId = subject.toolCallId; - terminalId = subject.terminalId; - } - return background.some( - (work) => - (toolCallId != null && - guards.BackgroundWork.isToolCall(work) && - work.toolCallId === toolCallId) || - (terminalId != null && - guards.BackgroundWork.isTerminal(work) && - work.terminalId === terminalId), - ); - } - - /** - * Whether the tool call currently advertises `capabilities.cancel`, from - * the `tool_call_update` patches routed to this session. - */ - canCancelToolCall(toolCallId: schema.ToolCallId): boolean { - return this.cancellableToolCalls.has(toolCallId); - } - - /** - * Whether the terminal currently advertises `capabilities.cancel`, from the - * `terminal_update` patches routed to this session. - */ - canCancelTerminal(terminalId: schema.TerminalId): boolean { - return this.cancellableTerminals.has(terminalId); - } - - /** - * Cancels one tool call with `tool_call/cancel`. - * - * Rejects with a `TypeError`, without sending the request, unless the tool - * call currently advertises `capabilities.cancel` (see - * `canCancelToolCall`). The response means the Agent accepted the - * cancellation, not that the work stopped. The Agent confirms it with a - * `tool_call_update` to a final status. - * - * This only covers tool calls reported in this session. A subagent's tool - * call is reported in its child session, so send - * `methods.agent.toolCall.cancel` through `ClientContext.request` with the - * child's `sessionId`. The tool call's own `capabilities.cancel` enables - * that even when the child session doesn't advertise `cancel`. - * - * The Agent answers `-32602` once the tool call has a final status. This - * includes a request sent again after the first one was accepted. The - * `tool_call_update` with that status reports the outcome. - */ - cancelToolCall( - toolCallId: schema.ToolCallId, - options?: SendRequestOptions, - ): Promise { - if (!this.canCancelToolCall(toolCallId)) { - return Promise.reject( - new TypeError( - `Tool call ${JSON.stringify(toolCallId)} does not advertise cancel`, - ), - ); - } - return this.cx.request( - schema.AGENT_METHODS.tool_call_cancel, - { sessionId: this.sessionId, toolCallId }, - options, - ); - } - - /** - * Stops a terminal's process with `terminal/cancel`. - * - * Rejects with a `TypeError`, without sending the request, unless the - * terminal currently advertises `capabilities.cancel` (see - * `canCancelTerminal`). The response means the Agent accepted the - * cancellation, not that the process stopped. The Agent confirms it with a - * `terminal_update` that sets `exitStatus`. The terminal is not released. - * - * This only covers terminals reported in this session. A subagent's - * terminal is reported in its child session, so send - * `methods.agent.terminal.cancel` through `ClientContext.request` with the - * child's `sessionId`. The terminal's own `capabilities.cancel` enables - * that even when the child session doesn't advertise `cancel`. - * - * The Agent answers `-32602` once the process has exited. This includes a - * request sent again after the first one was accepted. The - * `terminal_update` that sets `exitStatus` reports the outcome. - */ - cancelTerminal( - terminalId: schema.TerminalId, - options?: SendRequestOptions, - ): Promise { - if (!this.canCancelTerminal(terminalId)) { - return Promise.reject( - new TypeError( - `Terminal ${JSON.stringify(terminalId)} does not advertise cancel`, - ), - ); - } - return this.cx.request( - schema.AGENT_METHODS.terminal_cancel, - { sessionId: this.sessionId, terminalId }, - options, - ); - } - - /** - * Full response returned by `session/new`. - */ - get newSessionResponse(): schema.NewSessionResponse { - return this.sessionResponse; - } - - /** - * Sends a prompt to this session. - * - * Strings are converted to one text content block. A single content block is - * wrapped in an array. A prompt must contain at least one block. The returned - * promise resolves with the inserted user message's ID once the agent - * inserts it into the ACP conversation, not when processing finishes. - * - * A prompt may be sent while the agent is working. The agent inserts it - * right away or holds it and inserts it later, in the order received; the - * promise stays pending until then. Aborting `options.cancellationSignal` - * withdraws a held prompt, and `session/cancel` or `session/close` answer - * held prompts with `-32800`. `session/cancel` does not affect a prompt sent - * after it. - * - * Session updates remain independent of this request and have no fixed - * order relative to its response; an idle `state_update` does not establish - * that this message was processed. Rejection is reported only by this - * promise, not by the session update queue. - */ - prompt( - prompt: string | schema.ContentBlock | Array, - options?: SendRequestOptions, - ): Promise { - const blocks = this.promptBlocks(prompt); - if (blocks.length === 0) { - // Clients must not send an empty prompt. - return Promise.reject( - new TypeError("A prompt must contain at least one content block"), - ); - } - return this.cx.request( - schema.AGENT_METHODS.session_prompt, - { - sessionId: this.sessionId, - prompt: blocks, - }, - options, - ); - } - - /** - * Sets a configuration option for this session with - * `session/set_config_option`. - * - * The response carries the agent's complete `configOptions` list, which - * replaces `configOptions` on this session. For example, - * `session.setConfigOption({ configId: "model", type: "id", value: "fast" })`. - */ - async setConfigOption( - request: ActiveSessionSetConfigOptionRequest, - options?: SendRequestOptions, - ): Promise { - const response = await this.cx.request( - schema.AGENT_METHODS.session_set_config_option, - { ...request, sessionId: this.sessionId }, - options, - ); - this.currentConfigOptions = response.configOptions; - return response; - } - - /** - * Reads the next update or stop message for this session. - * - * Idle updates are always returned as `stop` messages, whether or not a prompt - * is pending. Queued updates are consumed in arrival order. An abort signal - * cancels this read without cancelling session work or discarding updates. - */ - nextUpdate(signal?: AbortSignal): Promise { - return this.updates.next(signal); - } - - /** - * Collects agent text from the session queue until the next idle update. - * - * This consumes the same queue as `nextUpdate()`, including already queued - * updates. It does not associate output or idle with any submitted prompt, - * skip updates when a prompt is sent, or wait for a prompt to be inserted. - * Use one reader at a time to avoid splitting the session's updates. - * An abort signal cancels the read without cancelling session work. - * - * Full `agent_message` updates replace content for their `messageId`, while - * `agent_message_chunk` updates append to it. Non-text content and other - * update types are ignored; use `nextUpdate()` when you need them. - */ - async readTextUntilIdle(signal?: AbortSignal): Promise { - const messageOrder: schema.MessageId[] = []; - const messageContent = new Map< - schema.MessageId, - Array - >(); - const ensureMessage = ( - messageId: schema.MessageId, - ): Array => { - let content = messageContent.get(messageId); - if (!content) { - content = []; - messageOrder.push(messageId); - messageContent.set(messageId, content); - } - return content; - }; - - for (;;) { - const message = await this.nextUpdate(signal); - if (message.kind === "stop") { - return messageOrder - .flatMap((messageId) => messageContent.get(messageId) ?? []) - .filter(guards.ContentBlock.isText) - .map((content) => content.text) - .join(""); - } - - const { update } = message; - if (guards.SessionUpdate.isAgentMessage(update)) { - ensureMessage(update.messageId); - if (update.content !== undefined) { - messageContent.set(update.messageId, update.content ?? []); - } - } else if (guards.SessionUpdate.isAgentMessageChunk(update)) { - ensureMessage(update.messageId).push(update.content); - } - } - } - - /** @internal */ - [routeActiveSessionUpdate](message: ActiveSessionMessage): void { - const { update } = message; - if (guards.SessionUpdate.isConfigOptionUpdate(update)) { - this.currentConfigOptions = update.configOptions; - } else if (guards.SessionUpdate.isStateUpdate(update)) { - this.latestBackground = - !guards.StateUpdate.isCustom(update) && Array.isArray(update.background) - ? update.background - : undefined; - } else if (guards.SessionUpdate.isToolCallUpdate(update)) { - applyCancelCapability( - this.cancellableToolCalls, - update.toolCallId, - update.capabilities, - ); - } else if (guards.SessionUpdate.isTerminalUpdate(update)) { - applyCancelCapability( - this.cancellableTerminals, - update.terminalId, - update.capabilities, - ); - } - this.updates.enqueue(message); - } - - /** - * Stops routing updates to this active-session helper. - * - * This does not close the ACP session on the agent. Use `ClientContext` - * session lifecycle methods when the protocol session itself should be closed - * or deleted. - */ - dispose(): void { - for (const registration of this.registrations.splice(0)) { - registration.dispose(); - } - this.updates.fail(new Error("Active session disposed")); - } - - /** - * Supports explicit resource management with `using`. - */ - [Symbol.dispose](): void { - this.dispose(); - } - - private promptBlocks( - prompt: string | schema.ContentBlock | Array, - ): Array { - if (typeof prompt === "string") { - return [{ type: "text", text: prompt }]; - } - - if (Array.isArray(prompt)) { - return prompt; - } - - return [prompt]; - } -} - -/** - * Options used when creating an ACP app. - */ -export type AppOptions = { - /** - * Human-readable name used in JSON-RPC handler descriptions and diagnostics. - */ - name?: string; -}; - -/** - * Common context passed to agent-side handlers. - */ -export type AgentHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed client context for calling client-side ACP methods. - */ - client: AgentContext; -}; - -/** - * Context passed to agent-side request handlers. - */ -export type AgentRequestContext = AgentHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; - -/** - * Context passed to agent-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type AgentNotificationContext = AgentHandlerContext; - -/** - * Common context passed to client-side handlers. - */ -export type ClientHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed agent context for calling agent-side ACP methods. - */ - agent: ClientContext; -}; - -/** - * Context passed to client-side request handlers. - */ -export type ClientRequestContext = ClientHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; - -/** - * Context passed to client-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type ClientNotificationContext = ClientHandlerContext; - -/** - * Request handler registered on an `AgentApp`. - */ -export type AgentRequestHandler = ( - context: AgentRequestContext, -) => MaybePromise; - -/** - * Notification handler registered on an `AgentApp`. - */ -export type AgentNotificationHandler = ( - context: AgentNotificationContext, -) => MaybePromise; - -/** - * Request handler registered on a `ClientApp`. - */ -export type ClientRequestHandler = ( - context: ClientRequestContext, -) => MaybePromise; - -/** - * Notification handler registered on a `ClientApp`. - */ -export type ClientNotificationHandler = ( - context: ClientNotificationContext, -) => MaybePromise; - -/** - * Handler called when an `AgentApp` opens a connection. - */ -export type AgentConnectHandler = ( - connection: AgentConnection, -) => MaybePromise; - -/** - * Handler called when a `ClientApp` opens a connection. - */ -export type ClientConnectHandler = ( - connection: ClientConnection, -) => MaybePromise; - -type AcpRequestSpec = { - method: string; - params?: ParamsParser; - response?: ParamsParser; - serializeResponse?: (response: HandlerResponse) => Response; -}; - -type AcpNotificationSpec = { - method: string; - params?: ParamsParser; -}; - -/** - * A generated validator as the parser of received values. - * - * The validators type the tag of an unknown variant as a plain string, while - * the protocol types brand it as an `UnknownVariant`, which only received - * values have. Everything a validator parses is received, so its output has - * the protocol type. - */ -function received(validator: { parse(value: unknown): unknown }): { - parse(value: unknown): T; -} { - return validator as { parse(value: unknown): T }; -} - -function requestSpec( - method: string, - params: ParamsParser, - response: ParamsParser, - serializeResponse?: (response: HandlerResponse) => Response, -): AcpRequestSpec { - return { - method, - // Match Rust's empty-payload handling without bypassing required fields. - params: (value) => parseParams(params, value ?? {}), - response, - serializeResponse, - }; -} - -function notificationSpec( - method: string, - params: ParamsParser, -): AcpNotificationSpec { - return { method, params }; -} - -function specsByMethod>( - specs: T, -): Record { - const byMethod = Object.create(null) as Record; - for (const spec of Object.values(specs) as Array) { - byMethod[spec.method] = spec; - } - return byMethod; -} - -const agentRequestSpecs = { - initialize: requestSpec( - schema.AGENT_METHODS.initialize, - parseV2InitializeRequest, - mapV2InitializeResponse, - serializeV2InitializeResponse, - ), - loginAuth: requestSpec< - schema.LoginAuthRequest, - schema.LoginAuthResponse | void, - schema.LoginAuthResponse - >( - schema.AGENT_METHODS.auth_login, - validate.zLoginAuthRequest, - validate.zLoginAuthResponse, - emptyObjectResponse, - ), - unstable_listProviders: requestSpec< - schema.ListProvidersRequest, - schema.ListProvidersResponse - >( - schema.AGENT_METHODS.providers_list, - validate.zListProvidersRequest, - validate.zListProvidersResponse, - ), - unstable_setProvider: requestSpec< - schema.SetProviderRequest, - schema.SetProviderResponse | void, - schema.SetProviderResponse - >( - schema.AGENT_METHODS.providers_set, - validate.zSetProviderRequest, - validate.zSetProviderResponse, - emptyObjectResponse, - ), - unstable_disableProvider: requestSpec< - schema.DisableProviderRequest, - schema.DisableProviderResponse | void, - schema.DisableProviderResponse - >( - schema.AGENT_METHODS.providers_disable, - validate.zDisableProviderRequest, - validate.zDisableProviderResponse, - emptyObjectResponse, - ), - newSession: requestSpec( - schema.AGENT_METHODS.session_new, - received(validate.zNewSessionRequest), - received(validate.zNewSessionResponse), - ), - setSessionConfigOption: requestSpec< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >( - schema.AGENT_METHODS.session_set_config_option, - received(validate.zSetSessionConfigOptionRequest), - received(validate.zSetSessionConfigOptionResponse), - ), - prompt: requestSpec( - schema.AGENT_METHODS.session_prompt, - received(validate.zPromptRequest), - received(validate.zPromptResponse), - ), - listSessions: requestSpec< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >( - schema.AGENT_METHODS.session_list, - validate.zListSessionsRequest, - validate.zListSessionsResponse, - ), - deleteSession: requestSpec< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void, - schema.DeleteSessionResponse - >( - schema.AGENT_METHODS.session_delete, - validate.zDeleteSessionRequest, - validate.zDeleteSessionResponse, - emptyObjectResponse, - ), - unstable_forkSession: requestSpec< - schema.ForkSessionRequest, - schema.ForkSessionResponse - >( - schema.AGENT_METHODS.session_fork, - received(validate.zForkSessionRequest), - received(validate.zForkSessionResponse), - ), - unstable_archiveSession: requestSpec< - schema.ArchiveSessionRequest, - schema.ArchiveSessionResponse | void, - schema.ArchiveSessionResponse - >( - schema.AGENT_METHODS.session_archive, - validate.zArchiveSessionRequest, - validate.zArchiveSessionResponse, - emptyObjectResponse, - ), - unstable_unarchiveSession: requestSpec< - schema.UnarchiveSessionRequest, - schema.UnarchiveSessionResponse | void, - schema.UnarchiveSessionResponse - >( - schema.AGENT_METHODS.session_unarchive, - validate.zUnarchiveSessionRequest, - validate.zUnarchiveSessionResponse, - emptyObjectResponse, - ), - unstable_sessionStatus: requestSpec< - schema.SessionStatusRequest, - schema.SessionStatusResponse - >( - schema.AGENT_METHODS.session_status, - validate.zSessionStatusRequest, - received(validate.zSessionStatusResponse), - ), - unstable_sessionOptions: requestSpec< - schema.SessionOptionsRequest, - schema.SessionOptionsResponse - >( - schema.AGENT_METHODS.session_options, - validate.zSessionOptionsRequest, - received(validate.zSessionOptionsResponse), - ), - unstable_setSessionTitle: requestSpec< - schema.SetSessionTitleRequest, - schema.SetSessionTitleResponse - >( - schema.AGENT_METHODS.session_set_title, - validate.zSetSessionTitleRequest, - validate.zSetSessionTitleResponse, - ), - resumeSession: requestSpec< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >( - schema.AGENT_METHODS.session_resume, - received(validate.zResumeSessionRequest), - received(validate.zResumeSessionResponse), - ), - closeSession: requestSpec< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void, - schema.CloseSessionResponse - >( - schema.AGENT_METHODS.session_close, - validate.zCloseSessionRequest, - validate.zCloseSessionResponse, - emptyObjectResponse, - ), - cancelToolCall: requestSpec< - schema.CancelToolCallRequest, - schema.CancelToolCallResponse | void, - schema.CancelToolCallResponse - >( - schema.AGENT_METHODS.tool_call_cancel, - validate.zCancelToolCallRequest, - validate.zCancelToolCallResponse, - emptyObjectResponse, - ), - cancelTerminal: requestSpec< - schema.CancelTerminalRequest, - schema.CancelTerminalResponse | void, - schema.CancelTerminalResponse - >( - schema.AGENT_METHODS.terminal_cancel, - validate.zCancelTerminalRequest, - validate.zCancelTerminalResponse, - emptyObjectResponse, - ), - logoutAuth: requestSpec< - schema.LogoutAuthRequest, - schema.LogoutAuthResponse | void, - schema.LogoutAuthResponse - >( - schema.AGENT_METHODS.auth_logout, - validate.zLogoutAuthRequest, - validate.zLogoutAuthResponse, - emptyObjectResponse, - ), - unstable_authStatus: requestSpec< - schema.AuthStatusRequest, - schema.AuthStatusResponse - >( - schema.AGENT_METHODS.auth_status, - validate.zAuthStatusRequest, - validate.zAuthStatusResponse, - ), -}; - -const agentNotificationSpecs = { - cancelSession: notificationSpec( - schema.AGENT_METHODS.session_cancel, - validate.zCancelSessionNotification, - ), - unstable_messageMcp: notificationSpec( - schema.AGENT_METHODS.mcp_message, - validate.zMessageMcpNotification, - ), -}; - -const clientRequestSpecs = { - requestPermission: requestSpec< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >( - schema.CLIENT_METHODS.session_request_permission, - received(validate.zRequestPermissionRequest), - received(validate.zRequestPermissionResponse), - ), - unstable_messageMcp: requestSpec< - schema.MessageMcpRequest, - schema.MessageMcpResponse - >( - schema.CLIENT_METHODS.mcp_message, - validate.zMessageMcpRequest, - validate.zMessageMcpResponse, - ), - createElicitation: requestSpec< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >( - schema.CLIENT_METHODS.elicitation_create, - received(validate.zCreateElicitationRequest), - received(validate.zCreateElicitationResponse), - ), -}; - -const clientNotificationSpecs = { - sessionUpdate: notificationSpec( - schema.CLIENT_METHODS.session_update, - received(validate.zUpdateSessionNotification), - ), - completeElicitation: notificationSpec( - schema.CLIENT_METHODS.elicitation_complete, - validate.zCompleteElicitationNotification, - ), - unstable_authStatusUpdate: - notificationSpec( - schema.CLIENT_METHODS.auth_status_update, - validate.zAuthStatusUpdateNotification, - ), -}; - -const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); -const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); -const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); -const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); - -/** - * Agent request handlers keyed by ACP protocol method name. - */ -export type AgentRequestHandlersByMethod = { - /** - * Handles `initialize`. - * - * Runs again for each repeated `initialize`, which the Client may send after - * a previous one completed and before any other request; the latest - * successful exchange is authoritative. Other requests that arrive while - * `initialize` is in flight are rejected with `-32600`. - * - * When the Client requests a newer protocol version than v2, params that do - * not parse under v2 are dropped instead of rejected, and a missing or - * malformed `info` is replaced with `{ name: "unknown", version: "unknown" }`. - */ - [schema.AGENT_METHODS.initialize]: AgentRequestHandler< - schema.InitializeRequest, - schema.InitializeResponse - >; - [schema.AGENT_METHODS.auth_login]: AgentRequestHandler< - schema.LoginAuthRequest, - schema.LoginAuthResponse | void - >; - [schema.AGENT_METHODS.providers_list]: AgentRequestHandler< - schema.ListProvidersRequest, - schema.ListProvidersResponse - >; - [schema.AGENT_METHODS.providers_set]: AgentRequestHandler< - schema.SetProviderRequest, - schema.SetProviderResponse | void - >; - [schema.AGENT_METHODS.providers_disable]: AgentRequestHandler< - schema.DisableProviderRequest, - schema.DisableProviderResponse | void - >; - [schema.AGENT_METHODS.session_new]: AgentRequestHandler< - schema.NewSessionRequest, - schema.NewSessionResponse - >; - [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >; - [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< - schema.PromptRequest, - schema.PromptResponse - >; - [schema.AGENT_METHODS.session_list]: AgentRequestHandler< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >; - [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void - >; - [schema.AGENT_METHODS.session_fork]: AgentRequestHandler< - schema.ForkSessionRequest, - schema.ForkSessionResponse - >; - /** - * Handles `session/archive`. Archiving an active or loaded session first - * cancels its work and frees its resources as `session/close` would. - * Archiving an archived session succeeds. An unknown session gets `-32002`. - */ - [schema.AGENT_METHODS.session_archive]: AgentRequestHandler< - schema.ArchiveSessionRequest, - schema.ArchiveSessionResponse | void - >; - /** - * Handles `session/unarchive`. It does not resume the session. Unarchiving - * a session that is not archived succeeds. An unknown session gets - * `-32002`. - */ - [schema.AGENT_METHODS.session_unarchive]: AgentRequestHandler< - schema.UnarchiveSessionRequest, - schema.UnarchiveSessionResponse | void - >; - /** - * Handles `session/status`. It must not resume, create, close, or change - * the session. An unknown session gets `-32002`. Include the current - * `state` snapshot when the session is `open`. - */ - [schema.AGENT_METHODS.session_status]: AgentRequestHandler< - schema.SessionStatusRequest, - schema.SessionStatusResponse - >; - /** - * Handles `session/options`. Respond with the config options and commands - * a session would start with. With `sessionId`, respond with what - * `session/resume` would return for that session. Clients also send the - * source session's `sessionId` to show the options before a - * `session/fork`. It must not create, resume, or change a session, send - * `session/update` notifications, or add an entry to `session/list`. The - * agent may start its runtime to resolve the options, and these rules - * still hold for it. An unknown session gets `-32002`. - */ - [schema.AGENT_METHODS.session_options]: AgentRequestHandler< - schema.SessionOptionsRequest, - schema.SessionOptionsResponse - >; - /** - * Handles `session/set_title`. Respond with the stored title after storing - * it. A title that is invalid after normalization gets `-32602`, and an - * unknown session gets `-32002`. - */ - [schema.AGENT_METHODS.session_set_title]: AgentRequestHandler< - schema.SetSessionTitleRequest, - schema.SetSessionTitleResponse - >; - /** - * Handles `session/resume`. - * - * With a `replayFrom` cursor, replay the history as `session/update` - * notifications, then send `replay_complete` exactly once, also when the - * history is empty. Until then, send only replayed history for the - * session and hold its other updates. Requests such as - * `session/request_permission` should wait too. Do not send - * `replay_complete` when `replayFrom` is omitted or `null`, or when the - * replay cannot be finished. Throw `-32602` for an unsupported cursor, - * without replaying anything. - * - * For every successful resume, send the current `state_update` before - * responding, after `replay_complete` when a replay was requested. - */ - [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >; - /** - * Handles `session/close`. Before responding, cancel every pending - * `session/request_permission` request and elicitation in the session with - * `$/cancel_request`, for example by aborting the `cancellationSignal` - * passed to `AgentContext.request`. Pass `stopWaitingOnCancel: true` with - * it so the pending request promise rejects with `-32800` right away - * instead of waiting for the Client's answer. Closing also stops the - * session's background work. - */ - [schema.AGENT_METHODS.session_close]: AgentRequestHandler< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void - >; - /** - * Handles `tool_call/cancel`. - * - * Respond once the cancellation is accepted, then confirm it with a - * `tool_call_update` to a final status. Throw `-32602` for a tool call - * that is unknown, already final, or not cancellable. This includes a - * request the Client sends again after the first one was accepted and the - * tool call has since reached a final status. Without this handler (and - * without a `"*"` request fallback), the app answers every - * `tool_call/cancel` with `-32602`. - */ - [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< - schema.CancelToolCallRequest, - schema.CancelToolCallResponse | void - >; - /** - * Handles `terminal/cancel`. - * - * Respond once the cancellation is accepted, then confirm it with a - * `terminal_update` that sets `exitStatus`. Cancelling does not release the - * terminal. Throw `-32602` for a terminal that is unknown, has already - * exited, or is not cancellable. This includes a request the Client sends - * again after the first one was accepted and the process has since exited. - * Without this handler (and without a `"*"` request fallback), the app - * answers every `terminal/cancel` with `-32602`. - */ - [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< - schema.CancelTerminalRequest, - schema.CancelTerminalResponse | void - >; - /** - * Handles `auth/logout`. Logging out is idempotent: respond with the same - * empty result when there is no authenticated state to end, for example - * because the Client already logged out. - */ - [schema.AGENT_METHODS.auth_logout]: AgentRequestHandler< - schema.LogoutAuthRequest, - schema.LogoutAuthResponse | void - >; - /** - * Handles `auth/status`. It must not change any agent state, and it must - * not fail with `auth_required` (`-32000`). - */ - [schema.AGENT_METHODS.auth_status]: AgentRequestHandler< - schema.AuthStatusRequest, - schema.AuthStatusResponse - >; -}; - -/** - * ACP request methods that can be handled by an `AgentApp`. - */ -export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; - -/** - * Agent notification handlers keyed by ACP protocol method name. - */ -export type AgentNotificationHandlersByMethod = { - /** - * Handles `session/cancel`. Stop waiting on the pending - * `session/request_permission` requests of the cancelled foreground work, - * treat them as not approved, and cancel each with `$/cancel_request`, for - * example by aborting the `cancellationSignal` passed to - * `AgentContext.request`. With `stopWaitingOnCancel: true`, aborting the - * signal does both: it sends `$/cancel_request` and rejects the request - * promise with `-32800` without waiting for the Client's answer. Work in - * the latest `background` list keeps running. - */ - [schema.AGENT_METHODS - .session_cancel]: AgentNotificationHandler; - [schema.AGENT_METHODS - .mcp_message]: AgentNotificationHandler; -}; - -/** - * ACP notification methods that can be handled by an `AgentApp`. - */ -export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & - string; - -/** - * Client request handlers keyed by ACP protocol method name. - */ -export type ClientRequestHandlersByMethod = { - [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >; - [schema.CLIENT_METHODS.mcp_message]: ClientRequestHandler< - schema.MessageMcpRequest, - schema.MessageMcpResponse - >; - [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >; -}; - -/** - * ACP request methods that can be handled by a `ClientApp`. - */ -export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; - -/** - * Client notification handlers keyed by ACP protocol method name. - */ -export type ClientNotificationHandlersByMethod = { - [schema.CLIENT_METHODS - .session_update]: ClientNotificationHandler; - [schema.CLIENT_METHODS - .elicitation_complete]: ClientNotificationHandler; - [schema.CLIENT_METHODS - .auth_status_update]: ClientNotificationHandler; -}; - -/** - * ACP notification methods that can be handled by a `ClientApp`. - */ -export type ClientNotificationMethod = - keyof ClientNotificationHandlersByMethod & string; - -/** - * Agent request params keyed by ACP protocol method name. - */ -export type AgentRequestParamsByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -/** - * Agent request responses keyed by ACP protocol method name. - */ -export type AgentRequestResponsesByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; - -/** - * Agent notification params keyed by ACP protocol method name. - */ -export type AgentNotificationParamsByMethod = { - [ - Method in AgentNotificationMethod - ]: AgentNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -/** - * Client request params keyed by ACP protocol method name. - */ -export type ClientRequestParamsByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -/** - * Client request responses keyed by ACP protocol method name. - */ -export type ClientRequestResponsesByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; - -/** - * Client notification params keyed by ACP protocol method name. - */ -export type ClientNotificationParamsByMethod = { - [ - Method in ClientNotificationMethod - ]: ClientNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { params: infer Params } - ? Params - : never - : never; -}; - -function agentRequestContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): AgentRequestContext { - return { - method, - params, - requestId, - signal, - client, - }; -} - -function agentNotificationContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - method: string, -): AgentNotificationContext { - return { - method, - params, - signal, - client, - }; -} - -function clientRequestContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): ClientRequestContext { - return { - method, - params, - requestId, - signal, - agent, - }; -} - -function clientNotificationContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - method: string, -): ClientNotificationContext { - return { - method, - params, - signal, - agent, - }; -} - -type ActiveSessionUpdateQueue = Pick; - -class SessionUpdateRouter { - private readonly activeSessions = new Map< - string, - Set - >(); - - handleMessage(message: IncomingMessage): HandleResult { - if ( - message.kind !== "notification" || - message.method !== schema.CLIENT_METHODS.session_update - ) { - return Handled.no(message); - } - - const notification = received( - validate.zUpdateSessionNotification, - ).parse(message.params); - const { update } = notification; - const isIdle = - guards.SessionUpdate.isStateUpdate(update) && - guards.StateUpdate.isIdle(update); - const activeSessions = this.activeSessions.get(notification.sessionId); - if (activeSessions && activeSessions.size > 0) { - for (const session of activeSessions) { - if (isIdle) { - session.enqueue({ - kind: "stop", - notification, - update, - stopReason: update.stopReason, - }); - } else { - session.enqueue({ - kind: "session_update", - notification, - update, - }); - } - } - } - - return Handled.no(message); - } - - attach( - response: schema.NewSessionResponse, - updates: ActiveSessionUpdateQueue, - ): HandlerRegistration { - const sessions = - this.activeSessions.get(response.sessionId) ?? - new Set(); - sessions.add(updates); - this.activeSessions.set(response.sessionId, sessions); - - return new HandlerRegistration(() => { - sessions.delete(updates); - if (sessions.size === 0) { - this.activeSessions.delete(response.sessionId); - } - }); - } -} - -const sessionUpdateRouters = new WeakMap< - ConnectionContext, - SessionUpdateRouter ->(); - -function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { - let router = sessionUpdateRouters.get(cx); - if (!router) { - router = new SessionUpdateRouter(); - sessionUpdateRouters.set(cx, router); - } - return router; -} - -function runConnectHandlers( - connection: ConnectionHandle, - handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, -): void { - for (const handler of handlers) { - let result: MaybePromise; - try { - result = handler(connection); - } catch (error) { - connection.close(error); - throw error; - } - - void Promise.resolve(result).catch((error) => { - connection.close(error); - }); - } -} - -const appBuilder = Symbol("appBuilder"); -const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); -const runClientConnectHandlers = Symbol("runClientConnectHandlers"); - -type AppConnectOptions = { - readonly deferConnectHandlers?: boolean; -}; - -type AgentConnectionState = { - rawConnection: Connection; - connection: AgentConnection; -}; - -type ClientConnectionState = { - rawConnection: Connection; - connection: ClientConnection; -}; - -function bridgeConnectionClose(source: Connection, peer: Connection): void { - void source.closed.then(async () => { - if (initializationState(source.getContext()).status === "initialized") { - await initializationState(peer.getContext()).initialized.catch(() => {}); - } - peer.closeFromPeer(source.signal.reason); - }); -} - -/** - * Creates an agent-side app for the experimental draft ACP v2 API. - * - * Register request and notification handlers by ACP method name, then call - * `connect(stream)` to serve an ACP client. - * - * @experimental - */ -export function agent(options?: AppOptions): AgentApp { - return new AgentApp(options); -} - -/** - * Agent-side app builder for the experimental draft ACP v2 API. - * - * Methods on this class register typed request or notification handlers and - * return `this`, so apps can be built with a fluent chain. Handler params are - * parsed with the generated ACP schemas before your handler runs, and thrown - * errors are converted to JSON-RPC errors by the connection layer. - * - * @experimental - */ -export class AgentApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: AgentConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - private readonly requestMethods = new Set(); - private hasInitializeHandler = false; - - constructor(options: AppOptions = {}) { - this.builder.withHandler(agentInitializationGuard()); - this.builder.withHandler( - defaultEntityCancelHandler( - (method) => - this.requestMethods.has(method) || this.fallbackKinds.has("request"), - ), - ); - if (options.name) { - this.builder.name(options.name); - } - } - - /** @internal */ - [appBuilder](): ConnectionBuilder { - this.assertInitializeHandler(); - return this.builder; - } - - /** @internal */ - [runAgentConnectHandlers](connection: AgentConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - - /** - * Connects this agent app to a transport stream. - */ - connect(stream: Stream): AgentConnection; - /** @internal */ - connect(stream: Stream, options: AppConnectOptions): AgentConnection; - /** - * Connects this agent app directly to a client app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(client: ClientApp): AgentConnection; - connect( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnection { - return this.connectConnection(target, options).connection; - } - - /** - * Connects this agent app to a stream or client app for the lifetime of `op`. - * - * The callback receives an `AgentContext` for calling client-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | ClientApp, - op: (context: AgentContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.client)); - } - - /** - * Registers a handler that runs when this agent app opens a connection. - * - * Use this for connection-scoped work that needs to call client-side ACP - * methods outside an inbound request handler, or to set up per-connection - * state that the request handlers use. Requests and notifications sent - * through `connection.client` wait until `initialize` has completed. - * - * Handlers are called synchronously in registration order and are not - * awaited. A handler that throws or rejects closes the connection. When they - * are called depends on who opens the connection: - * - * - `connect(...)` and `connectWith(...)` call them before the connection - * handles its first inbound message, and so does - * {@link AgentProtocolRouter.connect} when it routes to this app. Only the - * work a handler does before its first `await` is guaranteed to come first. - * - The experimental `AcpServer` calls them after the client has completed - * `initialize`. Request handlers, including `initialize`, can run before - * them. - */ - onConnect(handler: AgentConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - - /** - * Registers a request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: AgentRequestHandler): this; - onRequest( - method: Method, - handler: AgentRequestHandlersByMethod[Method], - ): this; - onRequest( - method: ExtensionMethod, - params: ParamsParser, - handler: AgentRequestHandler, - ): this; - onRequest( - method: UnrecognizedMethod, - params: ParamsParser, - handler: AgentRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | AgentRequestHandlersByMethod[AgentRequestMethod] - | AgentRequestHandler - | ParamsParser, - handler?: AgentRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as AgentRequestHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "request"); - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = agentRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - - if (method === schema.AGENT_METHODS.initialize) { - this.hasInitializeHandler = true; - } - this.requestMethods.add(method); - return this.request( - spec as AcpRequestSpec, - handlerOrParams as AgentRequestHandler, - ); - } - - /** - * Registers a notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. Serialize work yourself - * when its effects must be applied in order. - */ - onNotification(method: "*", handler: AgentNotificationHandler): this; - onNotification( - method: Method, - handler: AgentNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: ExtensionMethod, - params: ParamsParser, - handler: AgentNotificationHandler, - ): this; - onNotification( - method: UnrecognizedMethod, - params: ParamsParser, - handler: AgentNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | AgentNotificationHandlersByMethod[AgentNotificationMethod] - | AgentNotificationHandler - | ParamsParser, - handler?: AgentNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as AgentNotificationHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "notification"); - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = agentNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as AgentNotificationHandler, - ); - } - - private request( - spec: AcpRequestSpec, - handler: AgentRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - agentRequestContext( - params, - AgentContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.serializeResponse, - spec.method === schema.AGENT_METHODS.initialize - ? { - beforeResponse: (_params, response, cx) => { - initializationState(cx).complete( - mapV2InitializeResponse(response), - ); - }, - onError: (cx) => initializationState(cx).failAttempt(), - } - : undefined, - ); - return this; - } - - private notification( - spec: AcpNotificationSpec, - handler: AgentNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - agentNotificationContext( - params, - AgentContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - - private connectConnection( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnectionState { - this.assertInitializeHandler(); - if (isStream(target)) { - const state = this.openStreamConnection(target); - if (!options.deferConnectHandlers) { - this[runAgentConnectHandlers](state.connection); - } - return state; - } - - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = clientConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerRawConnection); - bridgeConnectionClose(peerRawConnection, state.rawConnection); - try { - target[runClientConnectHandlers](peerConnection); - this[runAgentConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - - private openStreamConnection(stream: Stream): AgentConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: agentConnection(rawConnection, this.connectHandlers), - }; - } - - private assertInitializeHandler(): void { - if (!this.hasInitializeHandler) { - throw new Error( - "AgentApp requires an initialize request handler before connecting", - ); - } - } -} - -/** - * Creates a client-side app for the experimental draft ACP v2 API. - * - * Register request and notification handlers by ACP method name, then use - * `connectWith(...)` to run the workflow that calls agent-side methods. - * - * @experimental - */ -export function client(options?: AppOptions): ClientApp { - return new ClientApp(options); -} - -/** - * Client-side app builder for the experimental draft ACP v2 API. - * - * Methods on this class register typed client handlers and return `this`, so - * apps can be built with a fluent chain. `connectWith(...)` is the usual entry - * point for clients because it provides a `ClientContext` for calling - * agent-side requests and session helpers. - * - * @experimental - */ -export class ClientApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: ClientConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - - constructor(options: AppOptions = {}) { - if (options.name) { - this.builder.name(options.name); - } - this.builder.withHandler(clientInitializationGuard()); - this.builder.withHandler({ - handleMessage: (message, cx) => - sessionUpdateRouter(cx).handleMessage(message), - describe: () => "client-session-update-router", - }); - } - - /** @internal */ - [appBuilder](): ConnectionBuilder { - return this.builder; - } - - /** @internal */ - [runClientConnectHandlers](connection: ClientConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - - /** - * Connects this client app to a transport stream. - */ - connect(stream: Stream): ClientConnection; - /** - * Connects this client app directly to an agent app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(agent: AgentApp): ClientConnection; - connect(target: Stream | AgentApp): ClientConnection { - return this.connectConnection(target).connection; - } - - /** - * Connects this client app to a stream or agent app for the lifetime of `op`. - * - * The callback receives a `ClientContext` for calling agent-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | AgentApp, - op: (context: ClientContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.agent)); - } - - /** - * Registers a handler that runs when this client app opens a connection. - * - * Use this for connection-scoped work that needs to call agent-side ACP - * methods outside an inbound request handler. - */ - onConnect(handler: ClientConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - - /** - * Registers a client request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: ClientRequestHandler): this; - onRequest( - method: Method, - handler: ClientRequestHandlersByMethod[Method], - ): this; - onRequest( - method: ExtensionMethod, - params: ParamsParser, - handler: ClientRequestHandler, - ): this; - onRequest( - method: UnrecognizedMethod, - params: ParamsParser, - handler: ClientRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | ClientRequestHandlersByMethod[ClientRequestMethod] - | ClientRequestHandler - | ParamsParser, - handler?: ClientRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as ClientRequestHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "request"); - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = clientRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - - return this.request( - spec as AcpRequestSpec, - handlerOrParams as ClientRequestHandler, - ); - } - - /** - * Registers a client notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. ACP requires a session's - * `session/update` notifications to be applied in the order they are - * received, so a `session/update` handler that awaits before applying an - * update must serialize that work itself, for example by chaining it onto a - * per-session promise. {@link ActiveSession} already queues updates in - * arrival order. - */ - onNotification( - method: "*", - handler: ClientNotificationHandler, - ): this; - onNotification( - method: Method, - handler: ClientNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: ExtensionMethod, - params: ParamsParser, - handler: ClientNotificationHandler, - ): this; - onNotification( - method: UnrecognizedMethod, - params: ParamsParser, - handler: ClientNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | ClientNotificationHandlersByMethod[ClientNotificationMethod] - | ClientNotificationHandler - | ParamsParser, - handler?: ClientNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as ClientNotificationHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "notification"); - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - - const spec = clientNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as ClientNotificationHandler, - ); - } - - private request( - spec: AcpRequestSpec, - handler: ClientRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - clientRequestContext( - params, - ClientContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.serializeResponse, - ); - return this; - } - - private notification( - spec: AcpNotificationSpec, - handler: ClientNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - clientNotificationContext( - params, - ClientContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - - private connectConnection(target: Stream | AgentApp): ClientConnectionState { - if (isStream(target)) { - const state = this.openStreamConnection(target); - this[runClientConnectHandlers](state.connection); - return state; - } - - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = agentConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerRawConnection); - bridgeConnectionClose(peerRawConnection, state.rawConnection); - try { - target[runAgentConnectHandlers](peerConnection); - this[runClientConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - - private openStreamConnection(stream: Stream): ClientConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: clientConnection(rawConnection, this.connectHandlers), - }; - } -} diff --git a/src/v2/bindings.ts b/src/v2/bindings.ts new file mode 100644 index 00000000..c3d25916 --- /dev/null +++ b/src/v2/bindings.ts @@ -0,0 +1,3542 @@ +import * as schema from "./unstable/schema/index.js"; +import * as validate from "./unstable/schema/zod.gen.js"; +import * as guards from "./unstable/schema/guards.gen.js"; +import type { Stream } from "./acp.js"; +import { + parseParams, + registerAppNotification, + registerAppRequest, +} from "../core/app-handlers.js"; +import type { ParamsParser } from "../core/app-handlers.js"; +import { + Connection, + Handled, + HandlerRegistration, + isRecord, + isV2RequestId, + RequestError, + respondWithNullId, + treatSessionNotFoundAsSuccess, +} from "../core/jsonrpc.js"; +import { connectionContextOf } from "../core/connection-access.js"; +import type { + AnyMessage, + ConnectionBuilder, + ConnectionContext, + HandleResult, + IncomingMessage, + JsonRpcId, + JsonRpcHandler, + MaybePromise, + SendRequestOptions, +} from "../core/jsonrpc.js"; + +/** + * ACP v2 extension method name. + * + * New custom methods should begin with `_` so they cannot collide with present + * or future protocol methods. + * + * @experimental + */ +export type ExtensionMethod = `_${string}`; + +/** + * A method name that is not part of the current ACP v2 draft. + * + * This compatibility type permits methods from older or newer unstable ACP + * revisions while preventing current built-in method literals from falling + * through the untyped overloads. Prefer {@link ExtensionMethod} for new custom + * methods. + * + * @experimental + */ +export type UnrecognizedMethod = string extends Method + ? Method + : Method extends + | AgentRequestMethod + | AgentNotificationMethod + | ClientRequestMethod + | ClientNotificationMethod + | typeof schema.PROTOCOL_METHODS.cancel_request + ? never + : Method; + +function emptyObjectResponse(response: T | null | undefined | void): T { + return response ?? ({} as T); +} + +const knownProtocolMethods = new Set([ + ...Object.values(schema.AGENT_METHODS), + ...Object.values(schema.CLIENT_METHODS), + ...Object.values(schema.PROTOCOL_METHODS), +]); + +function assertV2MethodDirection( + method: string, + builtIns: Record, + kind: "request" | "notification", + allowProtocolNotification = false, +): void { + if ( + Object.hasOwn(builtIns, method) || + (allowProtocolNotification && + method === schema.PROTOCOL_METHODS.cancel_request) + ) { + return; + } + if (knownProtocolMethods.has(method)) { + throw new TypeError( + `ACP v2 ${kind} method '${method}' is not valid in this direction`, + ); + } +} + +function assertUnrecognizedV2Method( + method: string, + kind: "request" | "notification", +): void { + if (knownProtocolMethods.has(method)) { + throw new TypeError( + `Cannot replace the built-in ACP v2 ${kind} parser for '${method}'`, + ); + } +} + +/** + * Client info substituted when an `initialize` request written for a newer + * protocol version has a missing or malformed `info`. + */ +const UNKNOWN_IMPLEMENTATION: schema.Implementation = { + name: "unknown", + version: "unknown", +}; + +function readInitializeProtocolVersion( + params: unknown, +): schema.ProtocolVersion { + return received(validate.zProtocolVersion).parse( + isPlainObject(params) ? params["protocolVersion"] : undefined, + ); +} + +function parseV2InitializeRequest(params: unknown): schema.InitializeRequest { + const protocolVersion = readInitializeProtocolVersion(params); + if (protocolVersion < schema.PROTOCOL_VERSION) { + throw RequestError.unsupportedProtocolVersion(protocolVersion, [ + schema.PROTOCOL_VERSION, + ]); + } + // A request for a newer version was written for a schema this endpoint does + // not know, so keep whatever parses under v2 instead of rejecting it. + // Capabilities and `_meta` already drop malformed values field by field; + // only the required `info` needs a substitute. + const lenient = + protocolVersion > schema.PROTOCOL_VERSION && isPlainObject(params); + const request = received( + validate.zInitializeRequest, + ).parse( + lenient && !validate.zImplementation.safeParse(params["info"]).success + ? { ...params, info: UNKNOWN_IMPLEMENTATION } + : params, + ); + return structuredClone({ + ...request, + protocolVersion: schema.PROTOCOL_VERSION, + }); +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function normalizeOutgoingV2InitializeRequest(params: unknown): { + wire: schema.InitializeRequest; + parsed: schema.InitializeRequest; +} { + const request = + typeof params === "object" && params !== null && !Array.isArray(params) + ? (params as Record) + : {}; + const outgoing = { + ...request, + protocolVersion: schema.PROTOCOL_VERSION, + }; + // Parsing supplies a validated local view, not the payload to transmit. + // In particular, Zod strips future capability fields from that view. + const parsed = parseV2InitializeRequest(outgoing); + return { + wire: structuredClone(outgoing) as schema.InitializeRequest, + parsed, + }; +} + +function mapV2InitializeResponse(response: unknown): schema.InitializeResponse { + const parsed = received( + validate.zInitializeResponse, + ).parse(response); + if (parsed.protocolVersion !== schema.PROTOCOL_VERSION) { + throw RequestError.invalidRequest( + { + expectedProtocolVersion: schema.PROTOCOL_VERSION, + receivedProtocolVersion: parsed.protocolVersion, + }, + `The v2 API only supports protocol version ${schema.PROTOCOL_VERSION}`, + ); + } + return structuredClone(parsed); +} + +function serializeV2InitializeResponse( + response: schema.InitializeResponse, +): schema.InitializeResponse { + // Keep validation separate from serialization, as for outgoing requests. + mapV2InitializeResponse(response); + return structuredClone(response); +} + +/** + * Validated initialize request and response for one ACP v2 connection. + * + * The snapshot becomes available only after the initialize response has been + * validated and sent or received successfully. When the Client repeats + * `initialize`, the latest successful exchange replaces the snapshot. + * + * @experimental + */ +export type InitializationSnapshot = Readonly<{ + request: schema.InitializeRequest; + response: schema.InitializeResponse; +}>; + +type InitializationPhase = + "uninitialized" | "initializing" | "initialized" | "failed"; + +function cloneInitialization( + initialization: InitializationSnapshot, +): InitializationSnapshot { + return structuredClone(initialization); +} + +function deferred(): { + promise: Promise; + resolve(value: T | PromiseLike): void; + reject(reason?: unknown): void; +} { + let resolve!: (value: T | PromiseLike) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise; + reject = rejectPromise; + }); + return { promise, resolve, reject }; +} + +/** + * Initialization lifecycle of one ACP v2 connection side. + * + * The Client may repeat `initialize` after a previous one completed, as long + * as it has not sent any other request. A repeat that fails leaves the + * previous initialization in effect. A first `initialize` that fails leaves + * the connection uninitialized, so the Client may send `initialize` again. + */ +class InitializationState { + private phase: InitializationPhase = "uninitialized"; + private request?: schema.InitializeRequest; + private snapshot?: InitializationSnapshot; + private otherRequestSeen = false; + private attempt = deferred(); + private readonly barrier = deferred(); + + constructor() { + void this.barrier.promise.catch(() => {}); + this.attempt.resolve(); + } + + get status(): InitializationPhase { + return this.phase; + } + + get initialized(): Promise { + return this.barrier.promise + .then(() => this.attempt.promise) + .then(() => cloneInitialization(this.snapshot!)); + } + + /** + * Returns why `initialize` cannot start now, or `undefined` if it can. + */ + beginError(): RequestError | undefined { + if (this.phase === "initializing") { + return RequestError.invalidRequest( + "ACP v2 initialize is already in progress", + ); + } + if (this.phase === "failed") { + return RequestError.invalidRequest( + "ACP v2 connection initialization failed", + ); + } + if (this.phase === "initialized" && this.otherRequestSeen) { + return RequestError.invalidRequest( + "ACP v2 initialize must not be repeated after other requests", + ); + } + return undefined; + } + + begin(request: schema.InitializeRequest): void { + const error = this.beginError(); + if (error) { + throw error; + } + + const requestSnapshot = structuredClone(request); + this.request = requestSnapshot; + this.phase = "initializing"; + this.attempt = deferred(); + } + + complete(response: schema.InitializeResponse): void { + if (this.phase !== "initializing" || !this.request) { + throw RequestError.invalidRequest( + "ACP v2 initialization is not in progress", + ); + } + + const initialization = { + request: structuredClone(this.request), + response: structuredClone(response), + }; + this.snapshot = initialization; + this.request = undefined; + this.phase = "initialized"; + this.barrier.resolve(initialization); + this.attempt.resolve(); + } + + /** + * Whether an `initialize` exchange has completed, including while a repeat + * is in progress. + */ + get hasInitialized(): boolean { + return this.snapshot !== undefined && this.phase !== "failed"; + } + + /** + * Fails the initialize attempt in progress. A failed repeat keeps the + * previous initialization; a failed first attempt leaves the connection + * uninitialized so `initialize` can be sent again. + */ + failAttempt(): void { + if (this.phase !== "initializing") { + return; + } + this.phase = this.snapshot ? "initialized" : "uninitialized"; + this.request = undefined; + this.attempt.resolve(); + } + + /** + * Fails initialization for good, such as when the connection closes before + * it was initialized. A failed repeat keeps the previous initialization. + */ + fail(error?: unknown): void { + if (this.phase === "initializing" && this.snapshot) { + this.failAttempt(); + return; + } + if (this.phase === "uninitialized" || this.phase === "initializing") { + this.phase = "failed"; + this.request = undefined; + this.barrier.reject( + error ?? + RequestError.invalidRequest( + "ACP v2 connection initialization failed", + ), + ); + this.attempt.resolve(); + } + } + + /** + * Records a request other than `initialize`, after which `initialize` may + * no longer be repeated. + */ + noteRequest(): void { + if (this.phase === "initializing" || this.phase === "initialized") { + this.otherRequestSeen = true; + } + } + + waitUntilInitialized(method: string): Promise { + if (this.phase === "initialized") { + return Promise.resolve(); + } + if (this.phase === "initializing") { + // Settles with the attempt: a failed first attempt rejects, since the + // connection is uninitialized again. + return this.attempt.promise.then(() => this.waitUntilInitialized(method)); + } + if (this.phase === "failed") { + return this.barrier.promise.then(() => {}); + } + return Promise.reject(initializationUnavailable(method)); + } +} + +const initializationStates = new WeakMap< + ConnectionContext, + InitializationState +>(); + +function initializationState(cx: ConnectionContext): InitializationState { + let state = initializationStates.get(cx); + if (!state) { + state = new InitializationState(); + initializationStates.set(cx, state); + if (cx.signal.aborted) { + state.fail(cx.signal.reason); + } else { + cx.signal.addEventListener("abort", () => state?.fail(cx.signal.reason), { + once: true, + }); + } + } + return state; +} + +function initializationUnavailable(method: string): RequestError { + return RequestError.invalidRequest( + `ACP v2 connection must be initialized before '${method}'`, + ); +} + +/** + * Rejects a request received before initialization with `-32600` and ignores + * a notification. Neither changes the initialization state, so the peer can + * still initialize the connection. + */ +async function blockUninitializedIncoming( + message: IncomingMessage, +): Promise { + return rejectIncoming(message, initializationUnavailable(message.method)); +} + +async function rejectIncoming( + message: IncomingMessage, + error: RequestError, +): Promise { + if (message.kind === "request") { + await message.responder.respondWithError(error); + } + return Handled.yes(); +} + +/** + * Rejects requests whose ID is `null` or a non-integer number, which ACP v2 + * does not allow. The error response uses `id: null` because the request ID + * is unusable. + */ +async function rejectInvalidRequestId( + message: IncomingMessage, +): Promise { + if (message.kind !== "request" || isV2RequestId(message.raw.id)) { + return undefined; + } + await respondWithNullId( + message.responder, + RequestError.invalidRequest( + undefined, + "ACP v2 request IDs must be strings or integers", + ), + ); + return Handled.yes(); +} + +async function waitUntilInitializedIncoming( + message: IncomingMessage, + state: InitializationState, +): Promise { + if (state.status === "initialized") { + return Handled.no(message); + } + if (state.status === "initializing") { + try { + await state.waitUntilInitialized(message.method); + } catch { + return blockUninitializedIncoming(message); + } + return Handled.no(message); + } + return blockUninitializedIncoming(message); +} + +/** + * Answers `tool_call/cancel` and `terminal/cancel` with `-32602` when the app + * has no handler for them. Neither method has an initialize-time capability: + * an Agent that never advertises `capabilities.cancel` on a tool call or + * terminal has nothing to cancel, and the spec answers a request for an + * unknown or non-cancellable entity with `-32602`, not `-32601`. + */ +function defaultEntityCancelHandler( + handles: (method: string) => boolean, +): JsonRpcHandler { + const entities: Record = { + [schema.AGENT_METHODS.tool_call_cancel]: { + key: "toolCallId", + label: "tool call", + }, + [schema.AGENT_METHODS.terminal_cancel]: { + key: "terminalId", + label: "terminal", + }, + }; + return { + async handleMessage(message) { + const entity = Object.hasOwn(entities, message.method) + ? entities[message.method] + : undefined; + if (message.kind !== "request" || !entity || handles(message.method)) { + return Handled.no(message); + } + const id = isRecord(message.params) + ? message.params[entity.key] + : undefined; + return rejectIncoming( + message, + RequestError.invalidParams( + typeof id === "string" ? { [entity.key]: id } : undefined, + `the ${entity.label} is unknown or not cancellable`, + ), + ); + }, + describe: () => "default-entity-cancel", + }; +} + +function agentInitializationGuard(): JsonRpcHandler { + return { + async handleMessage(message, cx) { + const invalidId = await rejectInvalidRequestId(message); + if (invalidId) { + return invalidId; + } + + const state = initializationState(cx); + if (message.kind === "notification") { + // The connection already applied `$/cancel_request`. Agents ignore + // other notifications that arrive before initialization completes. + if ( + message.method === schema.PROTOCOL_METHODS.cancel_request || + !state.hasInitialized + ) { + return Handled.yes(); + } + return waitUntilInitializedIncoming(message, state); + } + + if (message.method === schema.AGENT_METHODS.initialize) { + // The Client may repeat initialize after the previous one completed + // and before any other request. A repeat that fails leaves the + // previous initialization in effect. + const beginError = state.beginError(); + if (beginError) { + return rejectIncoming(message, beginError); + } + + // A malformed initialize throws before `begin`, so it leaves the + // connection as it was: uninitialized, or with the previous + // initialization in effect. + if ( + state.status === "initialized" && + readInitializeProtocolVersion(message.params) < + schema.PROTOCOL_VERSION + ) { + // A repeat must use the version the previous response selected. + return rejectIncoming( + message, + RequestError.invalidRequest( + undefined, + `a repeated initialize must request protocol version ${schema.PROTOCOL_VERSION} or later`, + ), + ); + } + state.begin(parseV2InitializeRequest(message.params)); + return Handled.no(message); + } + + // Requests other than initialize must not wait for an in-flight + // initialize: the spec requires rejecting them until it completes. + if (state.status === "initialized") { + state.noteRequest(); + return Handled.no(message); + } + return blockUninitializedIncoming(message); + }, + describe: () => "agent-initialization", + }; +} + +function clientInitializationGuard(): JsonRpcHandler { + return { + async handleMessage(message, cx) { + const invalidId = await rejectInvalidRequestId(message); + if (invalidId) { + return invalidId; + } + + const state = initializationState(cx); + if ( + message.kind === "notification" && + message.method === schema.PROTOCOL_METHODS.cancel_request + ) { + // The connection already applied it. + return Handled.yes(); + } + return waitUntilInitializedIncoming(message, state); + }, + describe: () => "client-initialization", + }; +} + +function parseRequestResponse( + spec: { response?: ParamsParser }, + response: unknown, +): unknown { + return parseParams(spec.response, response); +} + +function isStream(value: unknown): value is Stream { + return ( + typeof value === "object" && + value !== null && + "readable" in value && + "writable" in value + ); +} + +function memoryStreamPair(): [Stream, Stream] { + const leftToRight = new TransformStream(); + const rightToLeft = new TransformStream(); + return [ + { + readable: rightToLeft.readable, + writable: leftToRight.writable, + }, + { + readable: leftToRight.readable, + writable: rightToLeft.writable, + }, + ]; +} + +type McpTransportCapability = Exclude; + +// Transport keys of `session.mcp`: `stdio` and `http`, plus `acp` with the +// unstable schema. Read from the schema so each entrypoint checks only the +// transports its own `McpCapabilities` type can advertise. +const MCP_TRANSPORT_CAPABILITIES: ReadonlyArray = Object.keys( + validate.zMcpCapabilities.shape, +).filter((key) => key !== "_meta"); + +/** + * Throws `-32602` (Invalid params) for the first MCP server the agent cannot + * accept: one whose `name` repeats an earlier server's, or whose transport the + * agent did not advertise in `session.mcp`. + * + * Call it from `session/new`, `session/resume`, or `session/fork` handlers with + * the `capabilities.session.mcp` value the agent sent in its `initialize` + * response. Each server `name` must be unique within the list; a duplicate is + * rejected with error data `{ name }`. A server is accepted only when its + * `type` is a transport key in that object with a non-null value, for example + * `stdio` with `{ stdio: {} }`. Everything else is rejected, including v1's + * `sse`, unknown types, and custom `_`-prefixed types; agents that support a + * custom transport should handle those servers before calling this. The error + * data for a transport is `{ type }` with the rejected server's transport. + * + * @experimental + */ +export function assertSupportedMcpServers( + mcpServers: ReadonlyArray | null | undefined, + capabilities: schema.McpCapabilities | null | undefined, +): void { + const names = new Set(); + for (const server of mcpServers ?? []) { + const { name, type } = server; + if (typeof name === "string") { + if (names.has(name)) { + throw RequestError.invalidParams( + { name }, + `Duplicate MCP server name ${name}`, + ); + } + names.add(name); + } + if ( + !MCP_TRANSPORT_CAPABILITIES.includes(type) || + capabilities?.[type as McpTransportCapability] == null + ) { + throw RequestError.invalidParams( + { type }, + `Unsupported MCP server transport ${type}`, + ); + } + } +} + +const startActiveSession = Symbol("startActiveSession"); +const routeActiveSessionUpdate = Symbol("routeActiveSessionUpdate"); + +/** + * Experimental draft ACP v2 connection returned by `AgentApp.connect(...)` and + * `ClientApp.connect(...)`. + * + * Use this handle when you need a connection to stay open independently of a + * single `connectWith(...)` operation. + * + * @experimental + */ +export interface AcpConnection { + /** + * Resolves with the validated initialize exchange once initialization + * succeeds, or rejects if initialization or the connection fails. + * + * After a repeated `initialize` completes, reading this again resolves with + * the latest exchange. + */ + readonly initialized: Promise; + + /** + * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. + */ + readonly signal: AbortSignal; + + /** + * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. + */ + readonly closed: Promise; + + /** + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. + */ + close(error?: unknown): void; +} + +/** + * Experimental draft ACP v2 agent-side connection returned by + * `AgentApp.connect(...)`. + * + * Use `client` to call client-side ACP methods for the lifetime of the + * connection. + * + * @experimental + */ +export interface AgentConnection extends AcpConnection { + /** + * Context for calling client-side ACP methods. + */ + readonly client: AgentContext; +} + +/** + * Experimental draft ACP v2 client-side connection returned by + * `ClientApp.connect(...)`. + * + * Use `agent` to call agent-side ACP methods and session helpers for the + * lifetime of the connection. + * + * @experimental + */ +export interface ClientConnection extends AcpConnection { + /** + * Context for calling agent-side ACP methods. + */ + readonly agent: ClientContext; +} + +class AcpContext { + /** @internal */ + constructor( + private readonly cx: ConnectionContext, + private readonly currentRequestId?: JsonRpcId, + ) {} + + /** + * Validated initialize exchange, once this connection is initialized. + */ + get initialized(): Promise { + return initializationState(this.cx).initialized; + } + + /** @internal */ + protected get initializationLifecycle(): InitializationState { + return initializationState(this.cx); + } + + /** + * JSON-RPC id of the request currently being handled. + * + * This is `undefined` for notification handlers and for contexts created + * outside an inbound request, such as `connect(...)` and `connectWith(...)`. + */ + get requestId(): JsonRpcId | undefined { + return this.currentRequestId; + } + + /** @internal */ + protected get connectionContext(): ConnectionContext { + return this.cx; + } + + /** @hidden SDK helpers use this to identify the connection. */ + [connectionContextOf](): ConnectionContext { + return this.cx; + } + + /** @internal */ + protected sendRequest( + method: string, + params?: Req, + mapResponse?: (response: Resp) => Output, + options?: SendRequestOptions, + ): Promise { + return this.cx.sendRequest(method, params, mapResponse, options); + } + + /** @internal */ + protected sendNotification(method: string, params?: N): Promise { + return this.cx.sendNotification(method, params); + } + + /** @internal */ + protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { + return this.cx.addDynamicHandler(handler); + } +} + +/** + * Experimental draft ACP v2 context passed to agent-side handlers. + * + * Agents use this context to call client-side ACP methods while handling + * requests such as `session/prompt`. + * + * @experimental + */ +export class AgentContext extends AcpContext { + private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { + super(cx, requestId); + } + + /** @internal */ + static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { + return new AgentContext(cx, requestId); + } + + /** + * Sends a request to the client by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + */ + request( + method: Method, + params: ClientRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: ExtensionMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request< + Response = unknown, + Params = unknown, + const Method extends string = never, + >( + method: UnrecognizedMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + assertV2MethodDirection(method, clientRequestSpecsByMethod, "request"); + const spec = clientRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + return this.initializationLifecycle + .waitUntilInitialized(method) + .then(() => + this.sendRequest( + method, + params, + spec ? (response) => parseRequestResponse(spec, response) : undefined, + options, + ), + ); + } + + /** + * Sends a notification to the client by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: ClientNotificationParamsByMethod[Method], + ): Promise; + notify( + method: typeof schema.PROTOCOL_METHODS.cancel_request, + params: schema.CancelRequestNotification, + ): Promise; + notify( + method: ExtensionMethod, + params?: Params, + ): Promise; + notify( + method: UnrecognizedMethod, + params?: Params, + ): Promise; + notify(method: string, params?: unknown): Promise { + assertV2MethodDirection( + method, + clientNotificationSpecsByMethod, + "notification", + true, + ); + return this.initializationLifecycle + .waitUntilInitialized(method) + .then(() => this.sendNotification(method, params)); + } +} + +/** + * Experimental draft ACP v2 context used by clients to call agent-side ACP + * methods. + * + * `connectWith` passes a `ClientContext` to the callback. Client handlers also + * receive one as `ctx.agent` when they need to call back into the agent. + * + * @experimental + */ +export class ClientContext extends AcpContext { + private constructor( + cx: ConnectionContext, + requestId?: JsonRpcId, + private readonly closeOnInitializationFailure?: (error: unknown) => void, + ) { + super(cx, requestId); + } + + /** @internal */ + static create( + cx: ConnectionContext, + requestId?: JsonRpcId, + closeOnInitializationFailure?: (error: unknown) => void, + ): ClientContext { + return new ClientContext(cx, requestId, closeOnInitializationFailure); + } + + /** @internal */ + [startActiveSession]( + params: schema.NewSessionRequest, + options?: SendRequestOptions, + ): Promise { + return this.request(schema.AGENT_METHODS.session_new, params, options).then( + (response) => this.attachSession(response), + ); + } + + /** + * Creates a builder for starting and observing an ACP session. + * + * Pass an absolute path for the common case where only `cwd` is needed, or + * pass a full `NewSessionRequest` when you need MCP servers, `_meta`, or + * additional session fields. + */ + buildSession(cwd: schema.AbsolutePath): SessionBuilder; + buildSession(request: schema.NewSessionRequest): SessionBuilder; + buildSession( + cwdOrRequest: schema.AbsolutePath | schema.NewSessionRequest, + ): SessionBuilder { + if (typeof cwdOrRequest === "string") { + return SessionBuilder.create(this, { + cwd: cwdOrRequest, + mcpServers: [], + }); + } + + return SessionBuilder.create(this, cwdOrRequest); + } + + /** + * Builds active-session helpers around a `session/new` response. + */ + private attachSession(response: schema.NewSessionResponse): ActiveSession { + const updates = new AsyncQueue(); + const closeSignal = this.connectionContext.signal; + const failUpdatesOnClose = () => { + updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); + }; + if (closeSignal.aborted) { + failUpdatesOnClose(); + } else { + closeSignal.addEventListener("abort", failUpdatesOnClose); + } + const registrations: HandlerRegistration[] = []; + const session = ActiveSession.create( + this, + response, + updates, + registrations, + ); + registrations.push( + sessionUpdateRouter(this.connectionContext).attach(response, { + enqueue: (message) => session[routeActiveSessionUpdate](message), + }), + new HandlerRegistration(() => { + closeSignal.removeEventListener("abort", failUpdatesOnClose); + }), + ); + + return session; + } + + /** + * Sends a request to the agent by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + * + * Other requests wait until `initialize` has completed. `initialize` may be + * repeated once the previous one completed and before any other request has + * been sent; otherwise it throws `-32600` synchronously. A repeat that fails + * leaves the previous initialization in effect, and a first `initialize` + * that gets an error response leaves the connection uninitialized, so it can + * be sent again. + * + * Closing or deleting a session is idempotent: a `-32002` (Resource not + * found) response to `session/close` or `session/delete` resolves with an + * empty result instead of rejecting. + */ + request( + method: Method, + params: AgentRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: ExtensionMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request< + Response = unknown, + Params = unknown, + const Method extends string = never, + >( + method: UnrecognizedMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + assertV2MethodDirection(method, agentRequestSpecsByMethod, "request"); + const spec = agentRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + const state = this.initializationLifecycle; + if (method === schema.AGENT_METHODS.initialize) { + const { wire: request, parsed } = + normalizeOutgoingV2InitializeRequest(params); + state.begin(parsed); + + let response: Promise; + // Set when the agent answered with a response this client cannot use, + // as opposed to an error response. + let unusableResponse = false; + try { + response = this.sendRequest( + method, + request, + (value) => { + try { + const parsed = parseRequestResponse(spec!, value); + state.complete(parsed as schema.InitializeResponse); + return parsed; + } catch (error) { + unusableResponse = true; + throw error; + } + }, + options, + ); + } catch (error) { + this.failInitialization(error); + throw error; + } + void response.catch((error) => { + if (state.status === "initializing") { + if (unusableResponse) { + this.failInitialization(error); + } else { + // An error response leaves the connection as it was, so the + // client may send initialize again. + state.failAttempt(); + } + } + }); + return response; + } + + state.noteRequest(); + const mapResponse = spec + ? (response: unknown) => parseRequestResponse(spec, response) + : undefined; + return state + .waitUntilInitialized(method) + .then(() => + treatSessionNotFoundAsSuccess( + method, + this.sendRequest(method, params, mapResponse, options), + () => (mapResponse ? mapResponse({}) : {}), + ), + ); + } + + /** + * Fails an initialize attempt. Closes the connection unless a previous + * initialization remains in effect. + */ + private failInitialization(error: unknown): void { + const state = this.initializationLifecycle; + state.fail(error); + if (state.status === "failed") { + this.closeOnInitializationFailure?.(error); + } + } + + /** + * Sends a notification to the agent by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: AgentNotificationParamsByMethod[Method], + ): Promise; + notify( + method: typeof schema.PROTOCOL_METHODS.cancel_request, + params: schema.CancelRequestNotification, + ): Promise; + notify( + method: ExtensionMethod, + params?: Params, + ): Promise; + notify( + method: UnrecognizedMethod, + params?: Params, + ): Promise; + notify(method: string, params?: unknown): Promise { + assertV2MethodDirection( + method, + agentNotificationSpecsByMethod, + "notification", + true, + ); + return this.initializationLifecycle + .waitUntilInitialized(method) + .then(() => this.sendNotification(method, params)); + } +} + +class AcpConnectionHandle implements AcpConnection { + constructor(private readonly connection: Connection) {} + + get initialized(): Promise { + return initializationState(this.connection.getContext()).initialized; + } + + get signal(): AbortSignal { + return this.connection.signal; + } + + get closed(): Promise { + return this.connection.closed; + } + + close(error?: unknown): void { + this.connection.close(error); + } +} + +class AgentConnectionHandle + extends AcpConnectionHandle + implements AgentConnection +{ + readonly client: AgentContext; + private didStartConnectHandlers = false; + + constructor( + connection: Connection, + private readonly connectHandlers: readonly AgentConnectHandler[] = [], + ) { + super(connection); + this.client = AgentContext.create(connection.getContext()); + } + + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} + +class ClientConnectionHandle + extends AcpConnectionHandle + implements ClientConnection +{ + readonly agent: ClientContext; + private didStartConnectHandlers = false; + + constructor( + connection: Connection, + private readonly connectHandlers: readonly ClientConnectHandler[] = [], + ) { + super(connection); + this.agent = ClientContext.create( + connection.getContext(), + undefined, + (error) => connection.close(error), + ); + } + + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} + +function agentConnection( + connection: Connection, + connectHandlers: readonly AgentConnectHandler[] = [], +): AgentConnection { + return new AgentConnectionHandle(connection, connectHandlers); +} + +function clientConnection( + connection: Connection, + connectHandlers: readonly ClientConnectHandler[] = [], +): ClientConnection { + return new ClientConnectionHandle(connection, connectHandlers); +} + +class AsyncQueue { + private values: Array = []; + private waiters: Array<{ + resolve: (value: T) => void; + reject: (error: unknown) => void; + }> = []; + private failed = false; + private failure: unknown; + + enqueue(value: T): void { + if (this.failed) { + return; + } + + const waiter = this.waiters.shift(); + if (waiter) { + waiter.resolve(value); + } else { + this.values.push(value); + } + } + + fail(error: unknown): void { + if (this.failed) { + return; + } + + this.failed = true; + this.failure = error; + for (const waiter of this.waiters.splice(0)) { + waiter.reject(error); + } + } + + next(signal?: AbortSignal): Promise { + if (signal?.aborted) { + return Promise.reject(signal.reason); + } + + if (this.values.length > 0) { + return Promise.resolve(this.values.shift() as T); + } + + if (this.failed) { + return Promise.reject(this.failure); + } + + return new Promise((resolve, reject) => { + const cleanup = (): void => { + signal?.removeEventListener("abort", onAbort); + }; + const waiter = { + resolve: (value: T): void => { + cleanup(); + resolve(value); + }, + reject: (error: unknown): void => { + cleanup(); + reject(error); + }, + }; + const onAbort = (): void => { + const index = this.waiters.indexOf(waiter); + if (index >= 0) { + this.waiters.splice(index, 1); + } + waiter.reject(signal?.reason); + }; + + this.waiters.push(waiter); + signal?.addEventListener("abort", onAbort, { once: true }); + if (signal?.aborted) { + onAbort(); + } + }); + } +} + +/** + * Applies a `capabilities` patch from a `tool_call_update` or + * `terminal_update`: omission leaves it unchanged, `null` clears it, and an + * object replaces it, so `cancel` is supported only when the latest object + * carries a non-null `cancel`. + */ +function applyCancelCapability( + cancellable: Set, + id: Id, + capabilities: { cancel?: unknown } | null | undefined, +): void { + if (capabilities === undefined) { + return; + } + if (capabilities?.cancel != null) { + cancellable.add(id); + } else { + cancellable.delete(id); + } +} + +function cloneNewSessionRequest( + request: schema.NewSessionRequest, +): schema.NewSessionRequest { + return structuredClone(request); +} + +/** + * Experimental draft ACP v2 `session/set_config_option` params for + * `ActiveSession.setConfigOption(...)`; the session ID is filled in. + * + * @experimental + */ +export type ActiveSessionSetConfigOptionRequest = + schema.SetSessionConfigOptionRequest extends infer Request + ? Request extends unknown + ? { + [ + Key in keyof Request as Key extends "sessionId" ? never : Key + ]: Request[Key]; + } + : never + : never; + +type ActiveSessionQueue = Pick< + AsyncQueue, + "enqueue" | "fail" | "next" +>; + +/** + * Experimental draft ACP v2 message produced by an `ActiveSession`. + * + * `session_update` messages expose the typed `session/update` notification and + * `stop` messages report an idle `state_update`. Both are session-scoped: + * a `stop` message does not acknowledge processing or completion of any prompt. + * + * @experimental + */ +export type ActiveSessionMessage = + | { + /** + * Indicates that this message came from a `session/update` notification. + */ + kind: "session_update"; + /** + * Full notification sent by the agent. + */ + notification: schema.UpdateSessionNotification; + /** + * Convenience alias for `notification.update`. + */ + update: schema.SessionUpdate; + } + | { + /** + * Indicates an idle foreground snapshot, not necessarily a new completion. + */ + kind: "stop"; + /** + * Full notification containing the idle state update. + */ + notification: schema.UpdateSessionNotification; + /** + * Convenience alias for `notification.update`. + */ + update: schema.SessionUpdate; + /** + * Stop reason reported by the idle state, when provided. + */ + stopReason: schema.IdleStateUpdate["stopReason"]; + }; + +/** + * Experimental draft ACP v2 builder for creating an `ActiveSession`. + * + * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or + * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session + * needs MCP servers, `_meta`, or additional request fields. All paths in ACP + * payloads should be absolute. + * + * @experimental + */ +export class SessionBuilder { + private request: schema.NewSessionRequest; + + private constructor( + private cx: ClientContext, + request: schema.NewSessionRequest, + ) { + this.request = cloneNewSessionRequest(request); + } + + /** @internal */ + static create( + cx: ClientContext, + request: schema.NewSessionRequest, + ): SessionBuilder { + return new SessionBuilder(cx, request); + } + + /** + * Returns the `session/new` request that will be sent. + * + * The returned object is a defensive copy, so mutating it does not change the + * builder. + */ + toRequest(): schema.NewSessionRequest { + return cloneNewSessionRequest(this.request); + } + + /** + * Replaces the additional workspace roots for this session. + * + * `additionalDirectories` expand the session's file-system scope without + * changing `cwd`. Each path should be absolute. + */ + withAdditionalDirectories( + additionalDirectories: schema.AbsolutePath[], + ): this { + this.request = { + ...this.request, + additionalDirectories: [...additionalDirectories], + }; + return this; + } + + /** + * Adds one MCP server to the `session/new` request. + */ + withMcpServer(mcpServer: schema.McpServer): this { + this.request = { + ...this.request, + mcpServers: [ + ...(this.request.mcpServers ?? []), + structuredClone(mcpServer), + ], + }; + return this; + } + + /** + * Starts the session and returns an `ActiveSession` for prompting and reading + * updates. + * + * Call `dispose()` on the returned session when you no longer need update + * routing, or use `withSession(...)` to scope disposal automatically. + */ + async start(options?: SendRequestOptions): Promise { + return this.cx[startActiveSession](this.toRequest(), options); + } + + /** + * Starts the session, runs `op`, and disposes the active-session update + * routing when `op` finishes or throws. + */ + async withSession( + op: (session: ActiveSession) => MaybePromise, + ): Promise { + const session = await this.start(); + try { + return await op(session); + } finally { + session.dispose(); + } + } +} + +/** + * Experimental draft ACP v2 convenience wrapper for an active session. + * + * An active session routes `session/update` notifications for one session ID + * into an async queue. Use `prompt(...)` to submit user content and + * `nextUpdate()` to observe the session independently of prompt requests. + * A `stop` message reports idle foreground work, not per-prompt completion. + * + * @experimental + */ +export class ActiveSession { + private currentConfigOptions: Array | undefined; + private latestBackground: Array | undefined; + private readonly cancellableToolCalls = new Set(); + private readonly cancellableTerminals = new Set(); + + private constructor( + private cx: ClientContext, + private sessionResponse: schema.NewSessionResponse, + private updates: ActiveSessionQueue, + private registrations: HandlerRegistration[], + ) { + this.currentConfigOptions = sessionResponse.configOptions ?? undefined; + } + + /** @internal */ + static create( + cx: ClientContext, + sessionResponse: schema.NewSessionResponse, + updates: ActiveSessionQueue, + registrations: HandlerRegistration[], + ): ActiveSession { + return new ActiveSession(cx, sessionResponse, updates, registrations); + } + + /** + * Session ID returned by `session/new`. + */ + get sessionId(): schema.SessionId { + return this.sessionResponse.sessionId; + } + + /** + * Current configuration options for this session, if the agent provided any. + * + * Starts with the `configOptions` from `session/new`. It is replaced with the + * full list from each `config_option_update` routed to this session (applied + * when the notification arrives, before it is read with `nextUpdate()`) and + * from each `setConfigOption(...)` response. Updates stop after `dispose()`. + * `newSessionResponse.configOptions` keeps the original `session/new` value. + */ + get configOptions(): Array | undefined { + return this.currentConfigOptions; + } + + /** + * Metadata returned when the session was created. + */ + get meta(): { [key: string]: unknown } | null | undefined { + return this.sessionResponse._meta; + } + + /** + * The `background` list from the latest `state_update` routed to this + * session, or `undefined` while background work is not reported. + * + * Each `state_update` replaces it, applied when the notification arrives, + * before it is read with `nextUpdate()`. `[]` means no background work is + * running. A snapshot that omits the list, carries `null` or a malformed + * list, or reports a state this SDK does not know resets it to `undefined`: + * background work is unknown until a list arrives, and nothing should be + * treated as abandoned. Updates stop after `dispose()`. + */ + get background(): ReadonlyArray | undefined { + return this.latestBackground; + } + + /** + * Whether `request`'s `subject` references work in the latest `background` + * list: a listed tool call (by the subject's `toolCall.toolCallId`, or a + * command subject's `toolCallId`) or a listed terminal (by a command + * subject's `terminalId`). + * + * `session/cancel` does not cover listed work, so permission requests for + * it stay open. For the cancelled foreground work, the Agent stops waiting + * on its permission requests and cancels them with `$/cancel_request`, and + * the Client answers each cancelled request with the `cancelled` outcome. + * A Client may also answer a request with `cancelled` right after sending + * `session/cancel`, without waiting for `$/cancel_request`, but only when + * it knows the request belongs to the cancelled work. A `false` result + * alone does not establish that: it is also returned for requests without + * a `subject`, custom subjects, and any request while `background` is not + * reported. On `session/close`, the Agent cancels every pending permission + * request in the session with `$/cancel_request`. When an Agent sends a + * permission request with `cancellationSignal` and + * `stopWaitingOnCancel: true`, aborting the signal sends + * `$/cancel_request` and stops waiting for the answer. + */ + isForBackgroundWork(request: schema.RequestPermissionRequest): boolean { + const background = this.latestBackground; + const subject = request.subject; + if (!background || !subject) { + return false; + } + let toolCallId: schema.ToolCallId | null | undefined; + let terminalId: schema.TerminalId | null | undefined; + if (guards.RequestPermissionSubject.isToolCall(subject)) { + toolCallId = subject.toolCall.toolCallId; + } else if (guards.RequestPermissionSubject.isCommand(subject)) { + toolCallId = subject.toolCallId; + terminalId = subject.terminalId; + } + return background.some( + (work) => + (toolCallId != null && + guards.BackgroundWork.isToolCall(work) && + work.toolCallId === toolCallId) || + (terminalId != null && + guards.BackgroundWork.isTerminal(work) && + work.terminalId === terminalId), + ); + } + + /** + * Whether the tool call currently advertises `capabilities.cancel`, from + * the `tool_call_update` patches routed to this session. + */ + canCancelToolCall(toolCallId: schema.ToolCallId): boolean { + return this.cancellableToolCalls.has(toolCallId); + } + + /** + * Whether the terminal currently advertises `capabilities.cancel`, from the + * `terminal_update` patches routed to this session. + */ + canCancelTerminal(terminalId: schema.TerminalId): boolean { + return this.cancellableTerminals.has(terminalId); + } + + /** + * Cancels one tool call with `tool_call/cancel`. + * + * Rejects with a `TypeError`, without sending the request, unless the tool + * call currently advertises `capabilities.cancel` (see + * `canCancelToolCall`). The response means the Agent accepted the + * cancellation, not that the work stopped. The Agent confirms it with a + * `tool_call_update` to a final status. + * + * This only covers tool calls reported in this session. A subagent's tool + * call is reported in its child session, so send + * `methods.agent.toolCall.cancel` through `ClientContext.request` with the + * child's `sessionId`. The tool call's own `capabilities.cancel` enables + * that even when the child session doesn't advertise `cancel`. + * + * The Agent answers `-32602` once the tool call has a final status. This + * includes a request sent again after the first one was accepted. The + * `tool_call_update` with that status reports the outcome. + */ + cancelToolCall( + toolCallId: schema.ToolCallId, + options?: SendRequestOptions, + ): Promise { + if (!this.canCancelToolCall(toolCallId)) { + return Promise.reject( + new TypeError( + `Tool call ${JSON.stringify(toolCallId)} does not advertise cancel`, + ), + ); + } + return this.cx.request( + schema.AGENT_METHODS.tool_call_cancel, + { sessionId: this.sessionId, toolCallId }, + options, + ); + } + + /** + * Stops a terminal's process with `terminal/cancel`. + * + * Rejects with a `TypeError`, without sending the request, unless the + * terminal currently advertises `capabilities.cancel` (see + * `canCancelTerminal`). The response means the Agent accepted the + * cancellation, not that the process stopped. The Agent confirms it with a + * `terminal_update` that sets `exitStatus`. The terminal is not released. + * + * This only covers terminals reported in this session. A subagent's + * terminal is reported in its child session, so send + * `methods.agent.terminal.cancel` through `ClientContext.request` with the + * child's `sessionId`. The terminal's own `capabilities.cancel` enables + * that even when the child session doesn't advertise `cancel`. + * + * The Agent answers `-32602` once the process has exited. This includes a + * request sent again after the first one was accepted. The + * `terminal_update` that sets `exitStatus` reports the outcome. + */ + cancelTerminal( + terminalId: schema.TerminalId, + options?: SendRequestOptions, + ): Promise { + if (!this.canCancelTerminal(terminalId)) { + return Promise.reject( + new TypeError( + `Terminal ${JSON.stringify(terminalId)} does not advertise cancel`, + ), + ); + } + return this.cx.request( + schema.AGENT_METHODS.terminal_cancel, + { sessionId: this.sessionId, terminalId }, + options, + ); + } + + /** + * Full response returned by `session/new`. + */ + get newSessionResponse(): schema.NewSessionResponse { + return this.sessionResponse; + } + + /** + * Sends a prompt to this session. + * + * Strings are converted to one text content block. A single content block is + * wrapped in an array. A prompt must contain at least one block. The returned + * promise resolves with the inserted user message's ID once the agent + * inserts it into the ACP conversation, not when processing finishes. + * + * A prompt may be sent while the agent is working. The agent inserts it + * right away or holds it and inserts it later, in the order received; the + * promise stays pending until then. Aborting `options.cancellationSignal` + * withdraws a held prompt, and `session/cancel` or `session/close` answer + * held prompts with `-32800`. `session/cancel` does not affect a prompt sent + * after it. + * + * Session updates remain independent of this request and have no fixed + * order relative to its response; an idle `state_update` does not establish + * that this message was processed. Rejection is reported only by this + * promise, not by the session update queue. + */ + prompt( + prompt: string | schema.ContentBlock | Array, + options?: SendRequestOptions, + ): Promise { + const blocks = this.promptBlocks(prompt); + if (blocks.length === 0) { + // Clients must not send an empty prompt. + return Promise.reject( + new TypeError("A prompt must contain at least one content block"), + ); + } + return this.cx.request( + schema.AGENT_METHODS.session_prompt, + { + sessionId: this.sessionId, + prompt: blocks, + }, + options, + ); + } + + /** + * Sets a configuration option for this session with + * `session/set_config_option`. + * + * The response carries the agent's complete `configOptions` list, which + * replaces `configOptions` on this session. For example, + * `session.setConfigOption({ configId: "model", type: "id", value: "fast" })`. + */ + async setConfigOption( + request: ActiveSessionSetConfigOptionRequest, + options?: SendRequestOptions, + ): Promise { + const response = await this.cx.request( + schema.AGENT_METHODS.session_set_config_option, + { ...request, sessionId: this.sessionId }, + options, + ); + this.currentConfigOptions = response.configOptions; + return response; + } + + /** + * Reads the next update or stop message for this session. + * + * Idle updates are always returned as `stop` messages, whether or not a prompt + * is pending. Queued updates are consumed in arrival order. An abort signal + * cancels this read without cancelling session work or discarding updates. + */ + nextUpdate(signal?: AbortSignal): Promise { + return this.updates.next(signal); + } + + /** + * Collects agent text from the session queue until the next idle update. + * + * This consumes the same queue as `nextUpdate()`, including already queued + * updates. It does not associate output or idle with any submitted prompt, + * skip updates when a prompt is sent, or wait for a prompt to be inserted. + * Use one reader at a time to avoid splitting the session's updates. + * An abort signal cancels the read without cancelling session work. + * + * Full `agent_message` updates replace content for their `messageId`, while + * `agent_message_chunk` updates append to it. Non-text content and other + * update types are ignored; use `nextUpdate()` when you need them. + */ + async readTextUntilIdle(signal?: AbortSignal): Promise { + const messageOrder: schema.MessageId[] = []; + const messageContent = new Map< + schema.MessageId, + Array + >(); + const ensureMessage = ( + messageId: schema.MessageId, + ): Array => { + let content = messageContent.get(messageId); + if (!content) { + content = []; + messageOrder.push(messageId); + messageContent.set(messageId, content); + } + return content; + }; + + for (;;) { + const message = await this.nextUpdate(signal); + if (message.kind === "stop") { + return messageOrder + .flatMap((messageId) => messageContent.get(messageId) ?? []) + .filter(guards.ContentBlock.isText) + .map((content) => content.text) + .join(""); + } + + const { update } = message; + if (guards.SessionUpdate.isAgentMessage(update)) { + ensureMessage(update.messageId); + if (update.content !== undefined) { + messageContent.set(update.messageId, update.content ?? []); + } + } else if (guards.SessionUpdate.isAgentMessageChunk(update)) { + ensureMessage(update.messageId).push(update.content); + } + } + } + + /** @internal */ + [routeActiveSessionUpdate](message: ActiveSessionMessage): void { + const { update } = message; + if (guards.SessionUpdate.isConfigOptionUpdate(update)) { + this.currentConfigOptions = update.configOptions; + } else if (guards.SessionUpdate.isStateUpdate(update)) { + this.latestBackground = + !guards.StateUpdate.isCustom(update) && Array.isArray(update.background) + ? update.background + : undefined; + } else if (guards.SessionUpdate.isToolCallUpdate(update)) { + applyCancelCapability( + this.cancellableToolCalls, + update.toolCallId, + update.capabilities, + ); + } else if (guards.SessionUpdate.isTerminalUpdate(update)) { + applyCancelCapability( + this.cancellableTerminals, + update.terminalId, + update.capabilities, + ); + } + this.updates.enqueue(message); + } + + /** + * Stops routing updates to this active-session helper. + * + * This does not close the ACP session on the agent. Use `ClientContext` + * session lifecycle methods when the protocol session itself should be closed + * or deleted. + */ + dispose(): void { + for (const registration of this.registrations.splice(0)) { + registration.dispose(); + } + this.updates.fail(new Error("Active session disposed")); + } + + /** + * Supports explicit resource management with `using`. + */ + [Symbol.dispose](): void { + this.dispose(); + } + + private promptBlocks( + prompt: string | schema.ContentBlock | Array, + ): Array { + if (typeof prompt === "string") { + return [{ type: "text", text: prompt }]; + } + + if (Array.isArray(prompt)) { + return prompt; + } + + return [prompt]; + } +} + +/** + * Options used when creating an ACP app. + */ +export type AppOptions = { + /** + * Human-readable name used in JSON-RPC handler descriptions and diagnostics. + */ + name?: string; +}; + +/** + * Common context passed to agent-side handlers. + */ +export type AgentHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed client context for calling client-side ACP methods. + */ + client: AgentContext; +}; + +/** + * Context passed to agent-side request handlers. + */ +export type AgentRequestContext = AgentHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; + +/** + * Context passed to agent-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type AgentNotificationContext = AgentHandlerContext; + +/** + * Common context passed to client-side handlers. + */ +export type ClientHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed agent context for calling agent-side ACP methods. + */ + agent: ClientContext; +}; + +/** + * Context passed to client-side request handlers. + */ +export type ClientRequestContext = ClientHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; + +/** + * Context passed to client-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type ClientNotificationContext = ClientHandlerContext; + +/** + * Request handler registered on an `AgentApp`. + */ +export type AgentRequestHandler = ( + context: AgentRequestContext, +) => MaybePromise; + +/** + * Notification handler registered on an `AgentApp`. + */ +export type AgentNotificationHandler = ( + context: AgentNotificationContext, +) => MaybePromise; + +/** + * Request handler registered on a `ClientApp`. + */ +export type ClientRequestHandler = ( + context: ClientRequestContext, +) => MaybePromise; + +/** + * Notification handler registered on a `ClientApp`. + */ +export type ClientNotificationHandler = ( + context: ClientNotificationContext, +) => MaybePromise; + +/** + * Handler called when an `AgentApp` opens a connection. + */ +export type AgentConnectHandler = ( + connection: AgentConnection, +) => MaybePromise; + +/** + * Handler called when a `ClientApp` opens a connection. + */ +export type ClientConnectHandler = ( + connection: ClientConnection, +) => MaybePromise; + +type AcpRequestSpec = { + method: string; + params?: ParamsParser; + response?: ParamsParser; + serializeResponse?: (response: HandlerResponse) => Response; +}; + +type AcpNotificationSpec = { + method: string; + params?: ParamsParser; +}; + +/** + * A generated validator as the parser of received values. + * + * The validators type the tag of an unknown variant as a plain string, while + * the protocol types brand it as an `UnknownVariant`, which only received + * values have. Everything a validator parses is received, so its output has + * the protocol type. + */ +function received(validator: { parse(value: unknown): unknown }): { + parse(value: unknown): T; +} { + return validator as { parse(value: unknown): T }; +} + +function requestSpec( + method: string, + params: ParamsParser, + response: ParamsParser, + serializeResponse?: (response: HandlerResponse) => Response, +): AcpRequestSpec { + return { + method, + // Match Rust's empty-payload handling without bypassing required fields. + params: (value) => parseParams(params, value ?? {}), + response, + serializeResponse, + }; +} + +function notificationSpec( + method: string, + params: ParamsParser, +): AcpNotificationSpec { + return { method, params }; +} + +function specsByMethod>( + specs: T, +): Record { + const byMethod = Object.create(null) as Record; + for (const spec of Object.values(specs) as Array) { + byMethod[spec.method] = spec; + } + return byMethod; +} + +const agentRequestSpecs = { + initialize: requestSpec( + schema.AGENT_METHODS.initialize, + parseV2InitializeRequest, + mapV2InitializeResponse, + serializeV2InitializeResponse, + ), + loginAuth: requestSpec< + schema.LoginAuthRequest, + schema.LoginAuthResponse | void, + schema.LoginAuthResponse + >( + schema.AGENT_METHODS.auth_login, + validate.zLoginAuthRequest, + validate.zLoginAuthResponse, + emptyObjectResponse, + ), + unstable_listProviders: requestSpec< + schema.ListProvidersRequest, + schema.ListProvidersResponse + >( + schema.AGENT_METHODS.providers_list, + validate.zListProvidersRequest, + validate.zListProvidersResponse, + ), + unstable_setProvider: requestSpec< + schema.SetProviderRequest, + schema.SetProviderResponse | void, + schema.SetProviderResponse + >( + schema.AGENT_METHODS.providers_set, + validate.zSetProviderRequest, + validate.zSetProviderResponse, + emptyObjectResponse, + ), + unstable_disableProvider: requestSpec< + schema.DisableProviderRequest, + schema.DisableProviderResponse | void, + schema.DisableProviderResponse + >( + schema.AGENT_METHODS.providers_disable, + validate.zDisableProviderRequest, + validate.zDisableProviderResponse, + emptyObjectResponse, + ), + newSession: requestSpec( + schema.AGENT_METHODS.session_new, + received(validate.zNewSessionRequest), + received(validate.zNewSessionResponse), + ), + setSessionConfigOption: requestSpec< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >( + schema.AGENT_METHODS.session_set_config_option, + received(validate.zSetSessionConfigOptionRequest), + received(validate.zSetSessionConfigOptionResponse), + ), + prompt: requestSpec( + schema.AGENT_METHODS.session_prompt, + received(validate.zPromptRequest), + received(validate.zPromptResponse), + ), + listSessions: requestSpec< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >( + schema.AGENT_METHODS.session_list, + validate.zListSessionsRequest, + validate.zListSessionsResponse, + ), + deleteSession: requestSpec< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void, + schema.DeleteSessionResponse + >( + schema.AGENT_METHODS.session_delete, + validate.zDeleteSessionRequest, + validate.zDeleteSessionResponse, + emptyObjectResponse, + ), + unstable_forkSession: requestSpec< + schema.ForkSessionRequest, + schema.ForkSessionResponse + >( + schema.AGENT_METHODS.session_fork, + received(validate.zForkSessionRequest), + received(validate.zForkSessionResponse), + ), + unstable_archiveSession: requestSpec< + schema.ArchiveSessionRequest, + schema.ArchiveSessionResponse | void, + schema.ArchiveSessionResponse + >( + schema.AGENT_METHODS.session_archive, + validate.zArchiveSessionRequest, + validate.zArchiveSessionResponse, + emptyObjectResponse, + ), + unstable_unarchiveSession: requestSpec< + schema.UnarchiveSessionRequest, + schema.UnarchiveSessionResponse | void, + schema.UnarchiveSessionResponse + >( + schema.AGENT_METHODS.session_unarchive, + validate.zUnarchiveSessionRequest, + validate.zUnarchiveSessionResponse, + emptyObjectResponse, + ), + unstable_sessionStatus: requestSpec< + schema.SessionStatusRequest, + schema.SessionStatusResponse + >( + schema.AGENT_METHODS.session_status, + validate.zSessionStatusRequest, + received(validate.zSessionStatusResponse), + ), + unstable_sessionOptions: requestSpec< + schema.SessionOptionsRequest, + schema.SessionOptionsResponse + >( + schema.AGENT_METHODS.session_options, + validate.zSessionOptionsRequest, + received(validate.zSessionOptionsResponse), + ), + unstable_setSessionTitle: requestSpec< + schema.SetSessionTitleRequest, + schema.SetSessionTitleResponse + >( + schema.AGENT_METHODS.session_set_title, + validate.zSetSessionTitleRequest, + validate.zSetSessionTitleResponse, + ), + resumeSession: requestSpec< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >( + schema.AGENT_METHODS.session_resume, + received(validate.zResumeSessionRequest), + received(validate.zResumeSessionResponse), + ), + closeSession: requestSpec< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void, + schema.CloseSessionResponse + >( + schema.AGENT_METHODS.session_close, + validate.zCloseSessionRequest, + validate.zCloseSessionResponse, + emptyObjectResponse, + ), + cancelToolCall: requestSpec< + schema.CancelToolCallRequest, + schema.CancelToolCallResponse | void, + schema.CancelToolCallResponse + >( + schema.AGENT_METHODS.tool_call_cancel, + validate.zCancelToolCallRequest, + validate.zCancelToolCallResponse, + emptyObjectResponse, + ), + cancelTerminal: requestSpec< + schema.CancelTerminalRequest, + schema.CancelTerminalResponse | void, + schema.CancelTerminalResponse + >( + schema.AGENT_METHODS.terminal_cancel, + validate.zCancelTerminalRequest, + validate.zCancelTerminalResponse, + emptyObjectResponse, + ), + logoutAuth: requestSpec< + schema.LogoutAuthRequest, + schema.LogoutAuthResponse | void, + schema.LogoutAuthResponse + >( + schema.AGENT_METHODS.auth_logout, + validate.zLogoutAuthRequest, + validate.zLogoutAuthResponse, + emptyObjectResponse, + ), + unstable_authStatus: requestSpec< + schema.AuthStatusRequest, + schema.AuthStatusResponse + >( + schema.AGENT_METHODS.auth_status, + validate.zAuthStatusRequest, + validate.zAuthStatusResponse, + ), +}; + +const agentNotificationSpecs = { + cancelSession: notificationSpec( + schema.AGENT_METHODS.session_cancel, + validate.zCancelSessionNotification, + ), + unstable_messageMcp: notificationSpec( + schema.AGENT_METHODS.mcp_message, + validate.zMessageMcpNotification, + ), +}; + +const clientRequestSpecs = { + requestPermission: requestSpec< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >( + schema.CLIENT_METHODS.session_request_permission, + received(validate.zRequestPermissionRequest), + received(validate.zRequestPermissionResponse), + ), + unstable_messageMcp: requestSpec< + schema.MessageMcpRequest, + schema.MessageMcpResponse + >( + schema.CLIENT_METHODS.mcp_message, + validate.zMessageMcpRequest, + validate.zMessageMcpResponse, + ), + createElicitation: requestSpec< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >( + schema.CLIENT_METHODS.elicitation_create, + received(validate.zCreateElicitationRequest), + received(validate.zCreateElicitationResponse), + ), +}; + +const clientNotificationSpecs = { + sessionUpdate: notificationSpec( + schema.CLIENT_METHODS.session_update, + received(validate.zUpdateSessionNotification), + ), + completeElicitation: notificationSpec( + schema.CLIENT_METHODS.elicitation_complete, + validate.zCompleteElicitationNotification, + ), + unstable_authStatusUpdate: + notificationSpec( + schema.CLIENT_METHODS.auth_status_update, + validate.zAuthStatusUpdateNotification, + ), +}; + +const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); +const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); +const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); +const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); + +/** + * Agent request handlers keyed by ACP protocol method name. + */ +export type AgentRequestHandlersByMethod = { + /** + * Handles `initialize`. + * + * Runs again for each repeated `initialize`, which the Client may send after + * a previous one completed and before any other request; the latest + * successful exchange is authoritative. Other requests that arrive while + * `initialize` is in flight are rejected with `-32600`. + * + * When the Client requests a newer protocol version than v2, params that do + * not parse under v2 are dropped instead of rejected, and a missing or + * malformed `info` is replaced with `{ name: "unknown", version: "unknown" }`. + */ + [schema.AGENT_METHODS.initialize]: AgentRequestHandler< + schema.InitializeRequest, + schema.InitializeResponse + >; + [schema.AGENT_METHODS.auth_login]: AgentRequestHandler< + schema.LoginAuthRequest, + schema.LoginAuthResponse | void + >; + [schema.AGENT_METHODS.providers_list]: AgentRequestHandler< + schema.ListProvidersRequest, + schema.ListProvidersResponse + >; + [schema.AGENT_METHODS.providers_set]: AgentRequestHandler< + schema.SetProviderRequest, + schema.SetProviderResponse | void + >; + [schema.AGENT_METHODS.providers_disable]: AgentRequestHandler< + schema.DisableProviderRequest, + schema.DisableProviderResponse | void + >; + [schema.AGENT_METHODS.session_new]: AgentRequestHandler< + schema.NewSessionRequest, + schema.NewSessionResponse + >; + [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >; + [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< + schema.PromptRequest, + schema.PromptResponse + >; + [schema.AGENT_METHODS.session_list]: AgentRequestHandler< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >; + [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void + >; + [schema.AGENT_METHODS.session_fork]: AgentRequestHandler< + schema.ForkSessionRequest, + schema.ForkSessionResponse + >; + /** + * Handles `session/archive`. Archiving an active or loaded session first + * cancels its work and frees its resources as `session/close` would. + * Archiving an archived session succeeds. An unknown session gets `-32002`. + */ + [schema.AGENT_METHODS.session_archive]: AgentRequestHandler< + schema.ArchiveSessionRequest, + schema.ArchiveSessionResponse | void + >; + /** + * Handles `session/unarchive`. It does not resume the session. Unarchiving + * a session that is not archived succeeds. An unknown session gets + * `-32002`. + */ + [schema.AGENT_METHODS.session_unarchive]: AgentRequestHandler< + schema.UnarchiveSessionRequest, + schema.UnarchiveSessionResponse | void + >; + /** + * Handles `session/status`. It must not resume, create, close, or change + * the session. An unknown session gets `-32002`. Include the current + * `state` snapshot when the session is `open`. + */ + [schema.AGENT_METHODS.session_status]: AgentRequestHandler< + schema.SessionStatusRequest, + schema.SessionStatusResponse + >; + /** + * Handles `session/options`. Respond with the config options and commands + * a session would start with. With `sessionId`, respond with what + * `session/resume` would return for that session. Clients also send the + * source session's `sessionId` to show the options before a + * `session/fork`. It must not create, resume, or change a session, send + * `session/update` notifications, or add an entry to `session/list`. The + * agent may start its runtime to resolve the options, and these rules + * still hold for it. An unknown session gets `-32002`. + */ + [schema.AGENT_METHODS.session_options]: AgentRequestHandler< + schema.SessionOptionsRequest, + schema.SessionOptionsResponse + >; + /** + * Handles `session/set_title`. Respond with the stored title after storing + * it. A title that is invalid after normalization gets `-32602`, and an + * unknown session gets `-32002`. + */ + [schema.AGENT_METHODS.session_set_title]: AgentRequestHandler< + schema.SetSessionTitleRequest, + schema.SetSessionTitleResponse + >; + /** + * Handles `session/resume`. + * + * With a `replayFrom` cursor, replay the history as `session/update` + * notifications, then send `replay_complete` exactly once, also when the + * history is empty. Until then, send only replayed history for the + * session and hold its other updates. Requests such as + * `session/request_permission` should wait too. Do not send + * `replay_complete` when `replayFrom` is omitted or `null`, or when the + * replay cannot be finished. Throw `-32602` for an unsupported cursor, + * without replaying anything. + * + * For every successful resume, send the current `state_update` before + * responding, after `replay_complete` when a replay was requested. + */ + [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >; + /** + * Handles `session/close`. Before responding, cancel every pending + * `session/request_permission` request and elicitation in the session with + * `$/cancel_request`, for example by aborting the `cancellationSignal` + * passed to `AgentContext.request`. Pass `stopWaitingOnCancel: true` with + * it so the pending request promise rejects with `-32800` right away + * instead of waiting for the Client's answer. Closing also stops the + * session's background work. + */ + [schema.AGENT_METHODS.session_close]: AgentRequestHandler< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void + >; + /** + * Handles `tool_call/cancel`. + * + * Respond once the cancellation is accepted, then confirm it with a + * `tool_call_update` to a final status. Throw `-32602` for a tool call + * that is unknown, already final, or not cancellable. This includes a + * request the Client sends again after the first one was accepted and the + * tool call has since reached a final status. Without this handler (and + * without a `"*"` request fallback), the app answers every + * `tool_call/cancel` with `-32602`. + */ + [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< + schema.CancelToolCallRequest, + schema.CancelToolCallResponse | void + >; + /** + * Handles `terminal/cancel`. + * + * Respond once the cancellation is accepted, then confirm it with a + * `terminal_update` that sets `exitStatus`. Cancelling does not release the + * terminal. Throw `-32602` for a terminal that is unknown, has already + * exited, or is not cancellable. This includes a request the Client sends + * again after the first one was accepted and the process has since exited. + * Without this handler (and without a `"*"` request fallback), the app + * answers every `terminal/cancel` with `-32602`. + */ + [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< + schema.CancelTerminalRequest, + schema.CancelTerminalResponse | void + >; + /** + * Handles `auth/logout`. Logging out is idempotent: respond with the same + * empty result when there is no authenticated state to end, for example + * because the Client already logged out. + */ + [schema.AGENT_METHODS.auth_logout]: AgentRequestHandler< + schema.LogoutAuthRequest, + schema.LogoutAuthResponse | void + >; + /** + * Handles `auth/status`. It must not change any agent state, and it must + * not fail with `auth_required` (`-32000`). + */ + [schema.AGENT_METHODS.auth_status]: AgentRequestHandler< + schema.AuthStatusRequest, + schema.AuthStatusResponse + >; +}; + +/** + * ACP request methods that can be handled by an `AgentApp`. + */ +export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; + +/** + * Agent notification handlers keyed by ACP protocol method name. + */ +export type AgentNotificationHandlersByMethod = { + /** + * Handles `session/cancel`. Stop waiting on the pending + * `session/request_permission` requests of the cancelled foreground work, + * treat them as not approved, and cancel each with `$/cancel_request`, for + * example by aborting the `cancellationSignal` passed to + * `AgentContext.request`. With `stopWaitingOnCancel: true`, aborting the + * signal does both: it sends `$/cancel_request` and rejects the request + * promise with `-32800` without waiting for the Client's answer. Work in + * the latest `background` list keeps running. + */ + [schema.AGENT_METHODS + .session_cancel]: AgentNotificationHandler; + [schema.AGENT_METHODS + .mcp_message]: AgentNotificationHandler; +}; + +/** + * ACP notification methods that can be handled by an `AgentApp`. + */ +export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & + string; + +/** + * Client request handlers keyed by ACP protocol method name. + */ +export type ClientRequestHandlersByMethod = { + [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >; + [schema.CLIENT_METHODS.mcp_message]: ClientRequestHandler< + schema.MessageMcpRequest, + schema.MessageMcpResponse + >; + [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >; +}; + +/** + * ACP request methods that can be handled by a `ClientApp`. + */ +export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; + +/** + * Client notification handlers keyed by ACP protocol method name. + */ +export type ClientNotificationHandlersByMethod = { + [schema.CLIENT_METHODS + .session_update]: ClientNotificationHandler; + [schema.CLIENT_METHODS + .elicitation_complete]: ClientNotificationHandler; + [schema.CLIENT_METHODS + .auth_status_update]: ClientNotificationHandler; +}; + +/** + * ACP notification methods that can be handled by a `ClientApp`. + */ +export type ClientNotificationMethod = + keyof ClientNotificationHandlersByMethod & string; + +/** + * Agent request params keyed by ACP protocol method name. + */ +export type AgentRequestParamsByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +/** + * Agent request responses keyed by ACP protocol method name. + */ +export type AgentRequestResponsesByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; + +/** + * Agent notification params keyed by ACP protocol method name. + */ +export type AgentNotificationParamsByMethod = { + [ + Method in AgentNotificationMethod + ]: AgentNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +/** + * Client request params keyed by ACP protocol method name. + */ +export type ClientRequestParamsByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +/** + * Client request responses keyed by ACP protocol method name. + */ +export type ClientRequestResponsesByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; + +/** + * Client notification params keyed by ACP protocol method name. + */ +export type ClientNotificationParamsByMethod = { + [ + Method in ClientNotificationMethod + ]: ClientNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { params: infer Params } + ? Params + : never + : never; +}; + +function agentRequestContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): AgentRequestContext { + return { + method, + params, + requestId, + signal, + client, + }; +} + +function agentNotificationContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + method: string, +): AgentNotificationContext { + return { + method, + params, + signal, + client, + }; +} + +function clientRequestContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): ClientRequestContext { + return { + method, + params, + requestId, + signal, + agent, + }; +} + +function clientNotificationContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + method: string, +): ClientNotificationContext { + return { + method, + params, + signal, + agent, + }; +} + +type ActiveSessionUpdateQueue = Pick; + +class SessionUpdateRouter { + private readonly activeSessions = new Map< + string, + Set + >(); + + handleMessage(message: IncomingMessage): HandleResult { + if ( + message.kind !== "notification" || + message.method !== schema.CLIENT_METHODS.session_update + ) { + return Handled.no(message); + } + + const notification = received( + validate.zUpdateSessionNotification, + ).parse(message.params); + const { update } = notification; + const isIdle = + guards.SessionUpdate.isStateUpdate(update) && + guards.StateUpdate.isIdle(update); + const activeSessions = this.activeSessions.get(notification.sessionId); + if (activeSessions && activeSessions.size > 0) { + for (const session of activeSessions) { + if (isIdle) { + session.enqueue({ + kind: "stop", + notification, + update, + stopReason: update.stopReason, + }); + } else { + session.enqueue({ + kind: "session_update", + notification, + update, + }); + } + } + } + + return Handled.no(message); + } + + attach( + response: schema.NewSessionResponse, + updates: ActiveSessionUpdateQueue, + ): HandlerRegistration { + const sessions = + this.activeSessions.get(response.sessionId) ?? + new Set(); + sessions.add(updates); + this.activeSessions.set(response.sessionId, sessions); + + return new HandlerRegistration(() => { + sessions.delete(updates); + if (sessions.size === 0) { + this.activeSessions.delete(response.sessionId); + } + }); + } +} + +const sessionUpdateRouters = new WeakMap< + ConnectionContext, + SessionUpdateRouter +>(); + +function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { + let router = sessionUpdateRouters.get(cx); + if (!router) { + router = new SessionUpdateRouter(); + sessionUpdateRouters.set(cx, router); + } + return router; +} + +function runConnectHandlers( + connection: ConnectionHandle, + handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, +): void { + for (const handler of handlers) { + let result: MaybePromise; + try { + result = handler(connection); + } catch (error) { + connection.close(error); + throw error; + } + + void Promise.resolve(result).catch((error) => { + connection.close(error); + }); + } +} + +const appBuilder = Symbol("appBuilder"); +const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); +const runClientConnectHandlers = Symbol("runClientConnectHandlers"); + +type AppConnectOptions = { + readonly deferConnectHandlers?: boolean; +}; + +type AgentConnectionState = { + rawConnection: Connection; + connection: AgentConnection; +}; + +type ClientConnectionState = { + rawConnection: Connection; + connection: ClientConnection; +}; + +function bridgeConnectionClose(source: Connection, peer: Connection): void { + void source.closed.then(async () => { + if (initializationState(source.getContext()).status === "initialized") { + await initializationState(peer.getContext()).initialized.catch(() => {}); + } + peer.closeFromPeer(source.signal.reason); + }); +} + +/** + * Creates an agent-side app for the experimental draft ACP v2 API. + * + * Register request and notification handlers by ACP method name, then call + * `connect(stream)` to serve an ACP client. + * + * @experimental + */ +export function agent(options?: AppOptions): AgentApp { + return new AgentApp(options); +} + +/** + * Agent-side app builder for the experimental draft ACP v2 API. + * + * Methods on this class register typed request or notification handlers and + * return `this`, so apps can be built with a fluent chain. Handler params are + * parsed with the generated ACP schemas before your handler runs, and thrown + * errors are converted to JSON-RPC errors by the connection layer. + * + * @experimental + */ +export class AgentApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: AgentConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + private readonly requestMethods = new Set(); + private hasInitializeHandler = false; + + constructor(options: AppOptions = {}) { + this.builder.withHandler(agentInitializationGuard()); + this.builder.withHandler( + defaultEntityCancelHandler( + (method) => + this.requestMethods.has(method) || this.fallbackKinds.has("request"), + ), + ); + if (options.name) { + this.builder.name(options.name); + } + } + + /** @internal */ + [appBuilder](): ConnectionBuilder { + this.assertInitializeHandler(); + return this.builder; + } + + /** @internal */ + [runAgentConnectHandlers](connection: AgentConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + + /** + * Connects this agent app to a transport stream. + */ + connect(stream: Stream): AgentConnection; + /** @internal */ + connect(stream: Stream, options: AppConnectOptions): AgentConnection; + /** + * Connects this agent app directly to a client app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(client: ClientApp): AgentConnection; + connect( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnection { + return this.connectConnection(target, options).connection; + } + + /** + * Connects this agent app to a stream or client app for the lifetime of `op`. + * + * The callback receives an `AgentContext` for calling client-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | ClientApp, + op: (context: AgentContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.client)); + } + + /** + * Registers a handler that runs when this agent app opens a connection. + * + * Use this for connection-scoped work that needs to call client-side ACP + * methods outside an inbound request handler, or to set up per-connection + * state that the request handlers use. Requests and notifications sent + * through `connection.client` wait until `initialize` has completed. + * + * Handlers are called synchronously in registration order and are not + * awaited. A handler that throws or rejects closes the connection. When they + * are called depends on who opens the connection: + * + * - `connect(...)` and `connectWith(...)` call them before the connection + * handles its first inbound message, and so does + * {@link AgentProtocolRouter.connect} when it routes to this app. Only the + * work a handler does before its first `await` is guaranteed to come first. + * - The experimental `AcpServer` calls them after the client has completed + * `initialize`. Request handlers, including `initialize`, can run before + * them. + */ + onConnect(handler: AgentConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + + /** + * Registers a request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: AgentRequestHandler): this; + onRequest( + method: Method, + handler: AgentRequestHandlersByMethod[Method], + ): this; + onRequest( + method: ExtensionMethod, + params: ParamsParser, + handler: AgentRequestHandler, + ): this; + onRequest( + method: UnrecognizedMethod, + params: ParamsParser, + handler: AgentRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | AgentRequestHandlersByMethod[AgentRequestMethod] + | AgentRequestHandler + | ParamsParser, + handler?: AgentRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as AgentRequestHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "request"); + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = agentRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + + if (method === schema.AGENT_METHODS.initialize) { + this.hasInitializeHandler = true; + } + this.requestMethods.add(method); + return this.request( + spec as AcpRequestSpec, + handlerOrParams as AgentRequestHandler, + ); + } + + /** + * Registers a notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. Serialize work yourself + * when its effects must be applied in order. + */ + onNotification(method: "*", handler: AgentNotificationHandler): this; + onNotification( + method: Method, + handler: AgentNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: ExtensionMethod, + params: ParamsParser, + handler: AgentNotificationHandler, + ): this; + onNotification( + method: UnrecognizedMethod, + params: ParamsParser, + handler: AgentNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | AgentNotificationHandlersByMethod[AgentNotificationMethod] + | AgentNotificationHandler + | ParamsParser, + handler?: AgentNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as AgentNotificationHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "notification"); + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = agentNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as AgentNotificationHandler, + ); + } + + private request( + spec: AcpRequestSpec, + handler: AgentRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + agentRequestContext( + params, + AgentContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.serializeResponse, + spec.method === schema.AGENT_METHODS.initialize + ? { + beforeResponse: (_params, response, cx) => { + initializationState(cx).complete( + mapV2InitializeResponse(response), + ); + }, + onError: (cx) => initializationState(cx).failAttempt(), + } + : undefined, + ); + return this; + } + + private notification( + spec: AcpNotificationSpec, + handler: AgentNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + agentNotificationContext( + params, + AgentContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + + private connectConnection( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnectionState { + this.assertInitializeHandler(); + if (isStream(target)) { + const state = this.openStreamConnection(target); + if (!options.deferConnectHandlers) { + this[runAgentConnectHandlers](state.connection); + } + return state; + } + + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = clientConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); + try { + target[runClientConnectHandlers](peerConnection); + this[runAgentConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + + private openStreamConnection(stream: Stream): AgentConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: agentConnection(rawConnection, this.connectHandlers), + }; + } + + private assertInitializeHandler(): void { + if (!this.hasInitializeHandler) { + throw new Error( + "AgentApp requires an initialize request handler before connecting", + ); + } + } +} + +/** + * Creates a client-side app for the experimental draft ACP v2 API. + * + * Register request and notification handlers by ACP method name, then use + * `connectWith(...)` to run the workflow that calls agent-side methods. + * + * @experimental + */ +export function client(options?: AppOptions): ClientApp { + return new ClientApp(options); +} + +/** + * Client-side app builder for the experimental draft ACP v2 API. + * + * Methods on this class register typed client handlers and return `this`, so + * apps can be built with a fluent chain. `connectWith(...)` is the usual entry + * point for clients because it provides a `ClientContext` for calling + * agent-side requests and session helpers. + * + * @experimental + */ +export class ClientApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: ClientConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + + constructor(options: AppOptions = {}) { + if (options.name) { + this.builder.name(options.name); + } + this.builder.withHandler(clientInitializationGuard()); + this.builder.withHandler({ + handleMessage: (message, cx) => + sessionUpdateRouter(cx).handleMessage(message), + describe: () => "client-session-update-router", + }); + } + + /** @internal */ + [appBuilder](): ConnectionBuilder { + return this.builder; + } + + /** @internal */ + [runClientConnectHandlers](connection: ClientConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + + /** + * Connects this client app to a transport stream. + */ + connect(stream: Stream): ClientConnection; + /** + * Connects this client app directly to an agent app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(agent: AgentApp): ClientConnection; + connect(target: Stream | AgentApp): ClientConnection { + return this.connectConnection(target).connection; + } + + /** + * Connects this client app to a stream or agent app for the lifetime of `op`. + * + * The callback receives a `ClientContext` for calling agent-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | AgentApp, + op: (context: ClientContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.agent)); + } + + /** + * Registers a handler that runs when this client app opens a connection. + * + * Use this for connection-scoped work that needs to call agent-side ACP + * methods outside an inbound request handler. + */ + onConnect(handler: ClientConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + + /** + * Registers a client request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: ClientRequestHandler): this; + onRequest( + method: Method, + handler: ClientRequestHandlersByMethod[Method], + ): this; + onRequest( + method: ExtensionMethod, + params: ParamsParser, + handler: ClientRequestHandler, + ): this; + onRequest( + method: UnrecognizedMethod, + params: ParamsParser, + handler: ClientRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | ClientRequestHandlersByMethod[ClientRequestMethod] + | ClientRequestHandler + | ParamsParser, + handler?: ClientRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as ClientRequestHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "request"); + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = clientRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + + return this.request( + spec as AcpRequestSpec, + handlerOrParams as ClientRequestHandler, + ); + } + + /** + * Registers a client notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. ACP requires a session's + * `session/update` notifications to be applied in the order they are + * received, so a `session/update` handler that awaits before applying an + * update must serialize that work itself, for example by chaining it onto a + * per-session promise. {@link ActiveSession} already queues updates in + * arrival order. + */ + onNotification( + method: "*", + handler: ClientNotificationHandler, + ): this; + onNotification( + method: Method, + handler: ClientNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: ExtensionMethod, + params: ParamsParser, + handler: ClientNotificationHandler, + ): this; + onNotification( + method: UnrecognizedMethod, + params: ParamsParser, + handler: ClientNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | ClientNotificationHandlersByMethod[ClientNotificationMethod] + | ClientNotificationHandler + | ParamsParser, + handler?: ClientNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as ClientNotificationHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "notification"); + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + + const spec = clientNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as ClientNotificationHandler, + ); + } + + private request( + spec: AcpRequestSpec, + handler: ClientRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + clientRequestContext( + params, + ClientContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.serializeResponse, + ); + return this; + } + + private notification( + spec: AcpNotificationSpec, + handler: ClientNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + clientNotificationContext( + params, + ClientContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + + private connectConnection(target: Stream | AgentApp): ClientConnectionState { + if (isStream(target)) { + const state = this.openStreamConnection(target); + this[runClientConnectHandlers](state.connection); + return state; + } + + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = agentConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); + try { + target[runAgentConnectHandlers](peerConnection); + this[runClientConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + + private openStreamConnection(stream: Stream): ClientConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: clientConnection(rawConnection, this.connectHandlers), + }; + } +} diff --git a/src/v2/methods.ts b/src/v2/methods.ts new file mode 100644 index 00000000..3979e81e --- /dev/null +++ b/src/v2/methods.ts @@ -0,0 +1,70 @@ +import * as schema from "./unstable/schema/index.js"; + +/** + * ACP method-name constants for the experimental draft v2 API. + * + * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and + * `notify(...)` when you want literal-string type inference without spelling + * protocol strings inline. + * + * @experimental + */ +export const methods = { + agent: { + initialize: schema.AGENT_METHODS.initialize, + auth: { + login: schema.AGENT_METHODS.auth_login, + logout: schema.AGENT_METHODS.auth_logout, + status: schema.AGENT_METHODS.auth_status, + }, + providers: { + list: schema.AGENT_METHODS.providers_list, + set: schema.AGENT_METHODS.providers_set, + disable: schema.AGENT_METHODS.providers_disable, + }, + session: { + new: schema.AGENT_METHODS.session_new, + list: schema.AGENT_METHODS.session_list, + delete: schema.AGENT_METHODS.session_delete, + fork: schema.AGENT_METHODS.session_fork, + archive: schema.AGENT_METHODS.session_archive, + unarchive: schema.AGENT_METHODS.session_unarchive, + status: schema.AGENT_METHODS.session_status, + options: schema.AGENT_METHODS.session_options, + setTitle: schema.AGENT_METHODS.session_set_title, + resume: schema.AGENT_METHODS.session_resume, + close: schema.AGENT_METHODS.session_close, + setConfigOption: schema.AGENT_METHODS.session_set_config_option, + prompt: schema.AGENT_METHODS.session_prompt, + cancel: schema.AGENT_METHODS.session_cancel, + }, + toolCall: { + cancel: schema.AGENT_METHODS.tool_call_cancel, + }, + terminal: { + cancel: schema.AGENT_METHODS.terminal_cancel, + }, + mcp: { + message: schema.AGENT_METHODS.mcp_message, + }, + }, + client: { + session: { + requestPermission: schema.CLIENT_METHODS.session_request_permission, + update: schema.CLIENT_METHODS.session_update, + }, + mcp: { + message: schema.CLIENT_METHODS.mcp_message, + }, + elicitation: { + create: schema.CLIENT_METHODS.elicitation_create, + complete: schema.CLIENT_METHODS.elicitation_complete, + }, + auth: { + statusUpdate: schema.CLIENT_METHODS.auth_status_update, + }, + }, + protocol: { + cancelRequest: schema.PROTOCOL_METHODS.cancel_request, + }, +} as const; diff --git a/src/v2/stable/acp.ts b/src/v2/stable/acp.ts index 4be29fd9..148af9e7 100644 --- a/src/v2/stable/acp.ts +++ b/src/v2/stable/acp.ts @@ -42,26 +42,14 @@ * @packageDocumentation * @experimental */ -import * as schema from "../schema/index.js"; -import * as validate from "../schema/zod.gen.js"; -import * as guards from "../schema/guards.gen.js"; +import type { AnyMessage } from "../../core/jsonrpc.js"; import { ndJsonStream as createJsonStream } from "../../core/stream.js"; import type { NdJsonStreamOptions } from "../../core/stream.js"; -import { - parseParams, - registerAppNotification, - registerAppRequest, -} from "../../core/app-handlers.js"; -import type { ParamsParser } from "../../core/app-handlers.js"; -export type { ParamsParser } from "../../core/app-handlers.js"; +export * from "./bindings.js"; +export { methods } from "./methods.js"; export type * from "../schema/types.gen.js"; -// Runtime narrowing helpers for extensible unions, exposed as companion values -// that merge (declaration merging) with the like-named types — e.g. -// `CreateElicitationResponse.isAccept(response)`. See schema/guards.gen.ts. -// -// Listed explicitly (not `export *`) so each value+type pair merges rather than -// colliding with the `export type *` above. The guards.gen re-export test -// asserts this list stays in sync as new extensible unions are added. +// List guards explicitly so their value/type pairs merge rather than colliding +// with the type exports above. The guards.gen re-export test checks this list. export { AuthMethod, AvailableCommand, @@ -123,6 +111,7 @@ export { MessageTooLargeError, } from "../../core/stream-limits.js"; export type { NdJsonStreamOptions } from "../../core/stream.js"; +export type { ParamsParser } from "../../core/app-handlers.js"; export { AgentProtocolRouter, agentProtocolRouter, @@ -143,3184 +132,3 @@ export type { Result, SendRequestOptions, } from "../../core/jsonrpc.js"; -import { - Connection, - Handled, - HandlerRegistration, - isRecord, - isV2RequestId, - RequestError, - respondWithNullId, - treatSessionNotFoundAsSuccess, -} from "../../core/jsonrpc.js"; -import { connectionContextOf } from "../../core/connection-access.js"; -import type { - AnyMessage, - ConnectionBuilder, - ConnectionContext, - HandleResult, - IncomingMessage, - JsonRpcId, - JsonRpcHandler, - MaybePromise, - SendRequestOptions, -} from "../../core/jsonrpc.js"; -/** - * ACP v2 extension method name. - * - * New custom methods should begin with `_` so they cannot collide with present - * or future protocol methods. - * - * @experimental - */ -export type ExtensionMethod = `_${string}`; -/** - * A method name that is not part of the current ACP v2 draft. - * - * This compatibility type permits methods from older or newer unstable ACP - * revisions while preventing current built-in method literals from falling - * through the untyped overloads. Prefer {@link ExtensionMethod} for new custom - * methods. - * - * @experimental - */ -export type UnrecognizedMethod = string extends Method - ? Method - : Method extends - | AgentRequestMethod - | AgentNotificationMethod - | ClientRequestMethod - | ClientNotificationMethod - | typeof schema.PROTOCOL_METHODS.cancel_request - ? never - : Method; -function emptyObjectResponse(response: T | null | undefined | void): T { - return response ?? ({} as T); -} -const knownProtocolMethods = new Set([ - ...Object.values(schema.AGENT_METHODS), - ...Object.values(schema.CLIENT_METHODS), - ...Object.values(schema.PROTOCOL_METHODS), -]); -function assertV2MethodDirection( - method: string, - builtIns: Record, - kind: "request" | "notification", - allowProtocolNotification = false, -): void { - if ( - Object.hasOwn(builtIns, method) || - (allowProtocolNotification && - method === schema.PROTOCOL_METHODS.cancel_request) - ) { - return; - } - if (knownProtocolMethods.has(method)) { - throw new TypeError( - `ACP v2 ${kind} method '${method}' is not valid in this direction`, - ); - } -} -function assertUnrecognizedV2Method( - method: string, - kind: "request" | "notification", -): void { - if (knownProtocolMethods.has(method)) { - throw new TypeError( - `Cannot replace the built-in ACP v2 ${kind} parser for '${method}'`, - ); - } -} -/** - * Client info substituted when an `initialize` request written for a newer - * protocol version has a missing or malformed `info`. - */ -const UNKNOWN_IMPLEMENTATION: schema.Implementation = { - name: "unknown", - version: "unknown", -}; -function readInitializeProtocolVersion( - params: unknown, -): schema.ProtocolVersion { - return received(validate.zProtocolVersion).parse( - isPlainObject(params) ? params["protocolVersion"] : undefined, - ); -} -function parseV2InitializeRequest(params: unknown): schema.InitializeRequest { - const protocolVersion = readInitializeProtocolVersion(params); - if (protocolVersion < schema.PROTOCOL_VERSION) { - throw RequestError.unsupportedProtocolVersion(protocolVersion, [ - schema.PROTOCOL_VERSION, - ]); - } - // A request for a newer version was written for a schema this endpoint does - // not know, so keep whatever parses under v2 instead of rejecting it. - // Capabilities and `_meta` already drop malformed values field by field; - // only the required `info` needs a substitute. - const lenient = - protocolVersion > schema.PROTOCOL_VERSION && isPlainObject(params); - const request = received( - validate.zInitializeRequest, - ).parse( - lenient && !validate.zImplementation.safeParse(params["info"]).success - ? { ...params, info: UNKNOWN_IMPLEMENTATION } - : params, - ); - return structuredClone({ - ...request, - protocolVersion: schema.PROTOCOL_VERSION, - }); -} -function isPlainObject(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function normalizeOutgoingV2InitializeRequest(params: unknown): { - wire: schema.InitializeRequest; - parsed: schema.InitializeRequest; -} { - const request = - typeof params === "object" && params !== null && !Array.isArray(params) - ? (params as Record) - : {}; - const outgoing = { - ...request, - protocolVersion: schema.PROTOCOL_VERSION, - }; - // Parsing supplies a validated local view, not the payload to transmit. - // In particular, Zod strips future capability fields from that view. - const parsed = parseV2InitializeRequest(outgoing); - return { - wire: structuredClone(outgoing) as schema.InitializeRequest, - parsed, - }; -} -function mapV2InitializeResponse(response: unknown): schema.InitializeResponse { - const parsed = received( - validate.zInitializeResponse, - ).parse(response); - if (parsed.protocolVersion !== schema.PROTOCOL_VERSION) { - throw RequestError.invalidRequest( - { - expectedProtocolVersion: schema.PROTOCOL_VERSION, - receivedProtocolVersion: parsed.protocolVersion, - }, - `The v2 API only supports protocol version ${schema.PROTOCOL_VERSION}`, - ); - } - return structuredClone(parsed); -} -function serializeV2InitializeResponse( - response: schema.InitializeResponse, -): schema.InitializeResponse { - // Keep validation separate from serialization, as for outgoing requests. - mapV2InitializeResponse(response); - return structuredClone(response); -} -/** - * Validated initialize request and response for one ACP v2 connection. - * - * The snapshot becomes available only after the initialize response has been - * validated and sent or received successfully. When the Client repeats - * `initialize`, the latest successful exchange replaces the snapshot. - * - * @experimental - */ -export type InitializationSnapshot = Readonly<{ - request: schema.InitializeRequest; - response: schema.InitializeResponse; -}>; -type InitializationPhase = - "uninitialized" | "initializing" | "initialized" | "failed"; -function cloneInitialization( - initialization: InitializationSnapshot, -): InitializationSnapshot { - return structuredClone(initialization); -} -function deferred(): { - promise: Promise; - resolve(value: T | PromiseLike): void; - reject(reason?: unknown): void; -} { - let resolve!: (value: T | PromiseLike) => void; - let reject!: (reason?: unknown) => void; - const promise = new Promise((resolvePromise, rejectPromise) => { - resolve = resolvePromise; - reject = rejectPromise; - }); - return { promise, resolve, reject }; -} -/** - * Initialization lifecycle of one ACP v2 connection side. - * - * The Client may repeat `initialize` after a previous one completed, as long - * as it has not sent any other request. A repeat that fails leaves the - * previous initialization in effect. A first `initialize` that fails leaves - * the connection uninitialized, so the Client may send `initialize` again. - */ -class InitializationState { - private phase: InitializationPhase = "uninitialized"; - private request?: schema.InitializeRequest; - private snapshot?: InitializationSnapshot; - private otherRequestSeen = false; - private attempt = deferred(); - private readonly barrier = deferred(); - constructor() { - void this.barrier.promise.catch(() => {}); - this.attempt.resolve(); - } - get status(): InitializationPhase { - return this.phase; - } - get initialized(): Promise { - return this.barrier.promise - .then(() => this.attempt.promise) - .then(() => cloneInitialization(this.snapshot!)); - } - /** - * Returns why `initialize` cannot start now, or `undefined` if it can. - */ - beginError(): RequestError | undefined { - if (this.phase === "initializing") { - return RequestError.invalidRequest( - "ACP v2 initialize is already in progress", - ); - } - if (this.phase === "failed") { - return RequestError.invalidRequest( - "ACP v2 connection initialization failed", - ); - } - if (this.phase === "initialized" && this.otherRequestSeen) { - return RequestError.invalidRequest( - "ACP v2 initialize must not be repeated after other requests", - ); - } - return undefined; - } - begin(request: schema.InitializeRequest): void { - const error = this.beginError(); - if (error) { - throw error; - } - const requestSnapshot = structuredClone(request); - this.request = requestSnapshot; - this.phase = "initializing"; - this.attempt = deferred(); - } - complete(response: schema.InitializeResponse): void { - if (this.phase !== "initializing" || !this.request) { - throw RequestError.invalidRequest( - "ACP v2 initialization is not in progress", - ); - } - const initialization = { - request: structuredClone(this.request), - response: structuredClone(response), - }; - this.snapshot = initialization; - this.request = undefined; - this.phase = "initialized"; - this.barrier.resolve(initialization); - this.attempt.resolve(); - } - /** - * Whether an `initialize` exchange has completed, including while a repeat - * is in progress. - */ - get hasInitialized(): boolean { - return this.snapshot !== undefined && this.phase !== "failed"; - } - /** - * Fails the initialize attempt in progress. A failed repeat keeps the - * previous initialization; a failed first attempt leaves the connection - * uninitialized so `initialize` can be sent again. - */ - failAttempt(): void { - if (this.phase !== "initializing") { - return; - } - this.phase = this.snapshot ? "initialized" : "uninitialized"; - this.request = undefined; - this.attempt.resolve(); - } - /** - * Fails initialization for good, such as when the connection closes before - * it was initialized. A failed repeat keeps the previous initialization. - */ - fail(error?: unknown): void { - if (this.phase === "initializing" && this.snapshot) { - this.failAttempt(); - return; - } - if (this.phase === "uninitialized" || this.phase === "initializing") { - this.phase = "failed"; - this.request = undefined; - this.barrier.reject( - error ?? - RequestError.invalidRequest( - "ACP v2 connection initialization failed", - ), - ); - this.attempt.resolve(); - } - } - /** - * Records a request other than `initialize`, after which `initialize` may - * no longer be repeated. - */ - noteRequest(): void { - if (this.phase === "initializing" || this.phase === "initialized") { - this.otherRequestSeen = true; - } - } - waitUntilInitialized(method: string): Promise { - if (this.phase === "initialized") { - return Promise.resolve(); - } - if (this.phase === "initializing") { - // Settles with the attempt: a failed first attempt rejects, since the - // connection is uninitialized again. - return this.attempt.promise.then(() => this.waitUntilInitialized(method)); - } - if (this.phase === "failed") { - return this.barrier.promise.then(() => {}); - } - return Promise.reject(initializationUnavailable(method)); - } -} -const initializationStates = new WeakMap< - ConnectionContext, - InitializationState ->(); -function initializationState(cx: ConnectionContext): InitializationState { - let state = initializationStates.get(cx); - if (!state) { - state = new InitializationState(); - initializationStates.set(cx, state); - if (cx.signal.aborted) { - state.fail(cx.signal.reason); - } else { - cx.signal.addEventListener("abort", () => state?.fail(cx.signal.reason), { - once: true, - }); - } - } - return state; -} -function initializationUnavailable(method: string): RequestError { - return RequestError.invalidRequest( - `ACP v2 connection must be initialized before '${method}'`, - ); -} -/** - * Rejects a request received before initialization with `-32600` and ignores - * a notification. Neither changes the initialization state, so the peer can - * still initialize the connection. - */ -async function blockUninitializedIncoming( - message: IncomingMessage, -): Promise { - return rejectIncoming(message, initializationUnavailable(message.method)); -} -async function rejectIncoming( - message: IncomingMessage, - error: RequestError, -): Promise { - if (message.kind === "request") { - await message.responder.respondWithError(error); - } - return Handled.yes(); -} -/** - * Rejects requests whose ID is `null` or a non-integer number, which ACP v2 - * does not allow. The error response uses `id: null` because the request ID - * is unusable. - */ -async function rejectInvalidRequestId( - message: IncomingMessage, -): Promise { - if (message.kind !== "request" || isV2RequestId(message.raw.id)) { - return undefined; - } - await respondWithNullId( - message.responder, - RequestError.invalidRequest( - undefined, - "ACP v2 request IDs must be strings or integers", - ), - ); - return Handled.yes(); -} -async function waitUntilInitializedIncoming( - message: IncomingMessage, - state: InitializationState, -): Promise { - if (state.status === "initialized") { - return Handled.no(message); - } - if (state.status === "initializing") { - try { - await state.waitUntilInitialized(message.method); - } catch { - return blockUninitializedIncoming(message); - } - return Handled.no(message); - } - return blockUninitializedIncoming(message); -} -/** - * Answers `tool_call/cancel` and `terminal/cancel` with `-32602` when the app - * has no handler for them. Neither method has an initialize-time capability: - * an Agent that never advertises `capabilities.cancel` on a tool call or - * terminal has nothing to cancel, and the spec answers a request for an - * unknown or non-cancellable entity with `-32602`, not `-32601`. - */ -function defaultEntityCancelHandler( - handles: (method: string) => boolean, -): JsonRpcHandler { - const entities: Record< - string, - { - key: string; - label: string; - } - > = { - [schema.AGENT_METHODS.tool_call_cancel]: { - key: "toolCallId", - label: "tool call", - }, - [schema.AGENT_METHODS.terminal_cancel]: { - key: "terminalId", - label: "terminal", - }, - }; - return { - async handleMessage(message) { - const entity = Object.hasOwn(entities, message.method) - ? entities[message.method] - : undefined; - if (message.kind !== "request" || !entity || handles(message.method)) { - return Handled.no(message); - } - const id = isRecord(message.params) - ? message.params[entity.key] - : undefined; - return rejectIncoming( - message, - RequestError.invalidParams( - typeof id === "string" ? { [entity.key]: id } : undefined, - `the ${entity.label} is unknown or not cancellable`, - ), - ); - }, - describe: () => "default-entity-cancel", - }; -} -function agentInitializationGuard(): JsonRpcHandler { - return { - async handleMessage(message, cx) { - const invalidId = await rejectInvalidRequestId(message); - if (invalidId) { - return invalidId; - } - const state = initializationState(cx); - if (message.kind === "notification") { - // The connection already applied `$/cancel_request`. Agents ignore - // other notifications that arrive before initialization completes. - if ( - message.method === schema.PROTOCOL_METHODS.cancel_request || - !state.hasInitialized - ) { - return Handled.yes(); - } - return waitUntilInitializedIncoming(message, state); - } - if (message.method === schema.AGENT_METHODS.initialize) { - // The Client may repeat initialize after the previous one completed - // and before any other request. A repeat that fails leaves the - // previous initialization in effect. - const beginError = state.beginError(); - if (beginError) { - return rejectIncoming(message, beginError); - } - // A malformed initialize throws before `begin`, so it leaves the - // connection as it was: uninitialized, or with the previous - // initialization in effect. - if ( - state.status === "initialized" && - readInitializeProtocolVersion(message.params) < - schema.PROTOCOL_VERSION - ) { - // A repeat must use the version the previous response selected. - return rejectIncoming( - message, - RequestError.invalidRequest( - undefined, - `a repeated initialize must request protocol version ${schema.PROTOCOL_VERSION} or later`, - ), - ); - } - state.begin(parseV2InitializeRequest(message.params)); - return Handled.no(message); - } - // Requests other than initialize must not wait for an in-flight - // initialize: the spec requires rejecting them until it completes. - if (state.status === "initialized") { - state.noteRequest(); - return Handled.no(message); - } - return blockUninitializedIncoming(message); - }, - describe: () => "agent-initialization", - }; -} -function clientInitializationGuard(): JsonRpcHandler { - return { - async handleMessage(message, cx) { - const invalidId = await rejectInvalidRequestId(message); - if (invalidId) { - return invalidId; - } - const state = initializationState(cx); - if ( - message.kind === "notification" && - message.method === schema.PROTOCOL_METHODS.cancel_request - ) { - // The connection already applied it. - return Handled.yes(); - } - return waitUntilInitializedIncoming(message, state); - }, - describe: () => "client-initialization", - }; -} -function parseRequestResponse( - spec: { - response?: ParamsParser; - }, - response: unknown, -): unknown { - return parseParams(spec.response, response); -} -function isStream(value: unknown): value is Stream { - return ( - typeof value === "object" && - value !== null && - "readable" in value && - "writable" in value - ); -} -function memoryStreamPair(): [Stream, Stream] { - const leftToRight = new TransformStream(); - const rightToLeft = new TransformStream(); - return [ - { - readable: rightToLeft.readable, - writable: leftToRight.writable, - }, - { - readable: leftToRight.readable, - writable: rightToLeft.writable, - }, - ]; -} -type McpTransportCapability = Exclude; -// Transport keys of `session.mcp`: `stdio` and `http`, plus `acp` with the -// unstable schema. Read from the schema so each entrypoint checks only the -// transports its own `McpCapabilities` type can advertise. -const MCP_TRANSPORT_CAPABILITIES: ReadonlyArray = Object.keys( - validate.zMcpCapabilities.shape, -).filter((key) => key !== "_meta"); -/** - * Throws `-32602` (Invalid params) for the first MCP server the agent cannot - * accept: one whose `name` repeats an earlier server's, or whose transport the - * agent did not advertise in `session.mcp`. - * - * Call it from `session/new`, `session/resume`, or `session/fork` handlers with - * the `capabilities.session.mcp` value the agent sent in its `initialize` - * response. Each server `name` must be unique within the list; a duplicate is - * rejected with error data `{ name }`. A server is accepted only when its - * `type` is a transport key in that object with a non-null value, for example - * `stdio` with `{ stdio: {} }`. Everything else is rejected, including v1's - * `sse`, unknown types, and custom `_`-prefixed types; agents that support a - * custom transport should handle those servers before calling this. The error - * data for a transport is `{ type }` with the rejected server's transport. - * - * @experimental - */ -export function assertSupportedMcpServers( - mcpServers: ReadonlyArray | null | undefined, - capabilities: schema.McpCapabilities | null | undefined, -): void { - const names = new Set(); - for (const server of mcpServers ?? []) { - const { name, type } = server; - if (typeof name === "string") { - if (names.has(name)) { - throw RequestError.invalidParams( - { name }, - `Duplicate MCP server name ${name}`, - ); - } - names.add(name); - } - if ( - !MCP_TRANSPORT_CAPABILITIES.includes(type) || - capabilities?.[type as McpTransportCapability] == null - ) { - throw RequestError.invalidParams( - { type }, - `Unsupported MCP server transport ${type}`, - ); - } - } -} -/** - * ACP method-name constants for the experimental draft v2 API. - * - * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and - * `notify(...)` when you want literal-string type inference without spelling - * protocol strings inline. - * - * @experimental - */ -export const methods = { - agent: { - initialize: schema.AGENT_METHODS.initialize, - auth: { - login: schema.AGENT_METHODS.auth_login, - logout: schema.AGENT_METHODS.auth_logout, - }, - session: { - new: schema.AGENT_METHODS.session_new, - list: schema.AGENT_METHODS.session_list, - delete: schema.AGENT_METHODS.session_delete, - resume: schema.AGENT_METHODS.session_resume, - close: schema.AGENT_METHODS.session_close, - setConfigOption: schema.AGENT_METHODS.session_set_config_option, - prompt: schema.AGENT_METHODS.session_prompt, - cancel: schema.AGENT_METHODS.session_cancel, - }, - toolCall: { - cancel: schema.AGENT_METHODS.tool_call_cancel, - }, - terminal: { - cancel: schema.AGENT_METHODS.terminal_cancel, - }, - }, - client: { - session: { - requestPermission: schema.CLIENT_METHODS.session_request_permission, - update: schema.CLIENT_METHODS.session_update, - }, - elicitation: { - create: schema.CLIENT_METHODS.elicitation_create, - complete: schema.CLIENT_METHODS.elicitation_complete, - }, - }, - protocol: { - cancelRequest: schema.PROTOCOL_METHODS.cancel_request, - }, -} as const; -const startActiveSession = Symbol("startActiveSession"); -const routeActiveSessionUpdate = Symbol("routeActiveSessionUpdate"); -/** - * Experimental draft ACP v2 connection returned by `AgentApp.connect(...)` and - * `ClientApp.connect(...)`. - * - * Use this handle when you need a connection to stay open independently of a - * single `connectWith(...)` operation. - * - * @experimental - */ -export interface AcpConnection { - /** - * Resolves with the validated initialize exchange once initialization - * succeeds, or rejects if initialization or the connection fails. - * - * After a repeated `initialize` completes, reading this again resolves with - * the latest exchange. - */ - readonly initialized: Promise; - /** - * AbortSignal that aborts when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after the signal aborts. - */ - readonly signal: AbortSignal; - /** - * Promise that resolves when the connection closes. - * - * Unless `close()` closed the connection, notifications received before it - * closed can still reach their handlers after this resolves. - */ - readonly closed: Promise; - /** - * Closes the connection and rejects pending requests. Messages received but - * not yet dispatched are dropped. Does nothing once the connection is closed. - */ - close(error?: unknown): void; -} -/** - * Experimental draft ACP v2 agent-side connection returned by - * `AgentApp.connect(...)`. - * - * Use `client` to call client-side ACP methods for the lifetime of the - * connection. - * - * @experimental - */ -export interface AgentConnection extends AcpConnection { - /** - * Context for calling client-side ACP methods. - */ - readonly client: AgentContext; -} -/** - * Experimental draft ACP v2 client-side connection returned by - * `ClientApp.connect(...)`. - * - * Use `agent` to call agent-side ACP methods and session helpers for the - * lifetime of the connection. - * - * @experimental - */ -export interface ClientConnection extends AcpConnection { - /** - * Context for calling agent-side ACP methods. - */ - readonly agent: ClientContext; -} -class AcpContext { - /** @internal */ - constructor( - private readonly cx: ConnectionContext, - private readonly currentRequestId?: JsonRpcId, - ) {} - /** - * Validated initialize exchange, once this connection is initialized. - */ - get initialized(): Promise { - return initializationState(this.cx).initialized; - } - /** @internal */ - protected get initializationLifecycle(): InitializationState { - return initializationState(this.cx); - } - /** - * JSON-RPC id of the request currently being handled. - * - * This is `undefined` for notification handlers and for contexts created - * outside an inbound request, such as `connect(...)` and `connectWith(...)`. - */ - get requestId(): JsonRpcId | undefined { - return this.currentRequestId; - } - /** @internal */ - protected get connectionContext(): ConnectionContext { - return this.cx; - } - /** @hidden SDK helpers use this to identify the connection. */ - [connectionContextOf](): ConnectionContext { - return this.cx; - } - /** @internal */ - protected sendRequest( - method: string, - params?: Req, - mapResponse?: (response: Resp) => Output, - options?: SendRequestOptions, - ): Promise { - return this.cx.sendRequest(method, params, mapResponse, options); - } - /** @internal */ - protected sendNotification(method: string, params?: N): Promise { - return this.cx.sendNotification(method, params); - } - /** @internal */ - protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { - return this.cx.addDynamicHandler(handler); - } -} -/** - * Experimental draft ACP v2 context passed to agent-side handlers. - * - * Agents use this context to call client-side ACP methods while handling - * requests such as `session/prompt`. - * - * @experimental - */ -export class AgentContext extends AcpContext { - private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { - super(cx, requestId); - } - /** @internal */ - static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { - return new AgentContext(cx, requestId); - } - /** - * Sends a request to the client by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - */ - request( - method: Method, - params: ClientRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: ExtensionMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request< - Response = unknown, - Params = unknown, - const Method extends string = never, - >( - method: UnrecognizedMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - assertV2MethodDirection(method, clientRequestSpecsByMethod, "request"); - const spec = clientRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - return this.initializationLifecycle - .waitUntilInitialized(method) - .then(() => - this.sendRequest( - method, - params, - spec ? (response) => parseRequestResponse(spec, response) : undefined, - options, - ), - ); - } - /** - * Sends a notification to the client by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: ClientNotificationParamsByMethod[Method], - ): Promise; - notify( - method: typeof schema.PROTOCOL_METHODS.cancel_request, - params: schema.CancelRequestNotification, - ): Promise; - notify( - method: ExtensionMethod, - params?: Params, - ): Promise; - notify( - method: UnrecognizedMethod, - params?: Params, - ): Promise; - notify(method: string, params?: unknown): Promise { - assertV2MethodDirection( - method, - clientNotificationSpecsByMethod, - "notification", - true, - ); - return this.initializationLifecycle - .waitUntilInitialized(method) - .then(() => this.sendNotification(method, params)); - } -} -/** - * Experimental draft ACP v2 context used by clients to call agent-side ACP - * methods. - * - * `connectWith` passes a `ClientContext` to the callback. Client handlers also - * receive one as `ctx.agent` when they need to call back into the agent. - * - * @experimental - */ -export class ClientContext extends AcpContext { - private constructor( - cx: ConnectionContext, - requestId?: JsonRpcId, - private readonly closeOnInitializationFailure?: (error: unknown) => void, - ) { - super(cx, requestId); - } - /** @internal */ - static create( - cx: ConnectionContext, - requestId?: JsonRpcId, - closeOnInitializationFailure?: (error: unknown) => void, - ): ClientContext { - return new ClientContext(cx, requestId, closeOnInitializationFailure); - } - /** @internal */ - [startActiveSession]( - params: schema.NewSessionRequest, - options?: SendRequestOptions, - ): Promise { - return this.request(schema.AGENT_METHODS.session_new, params, options).then( - (response) => this.attachSession(response), - ); - } - /** - * Creates a builder for starting and observing an ACP session. - * - * Pass an absolute path for the common case where only `cwd` is needed, or - * pass a full `NewSessionRequest` when you need MCP servers, `_meta`, or - * additional session fields. - */ - buildSession(cwd: schema.AbsolutePath): SessionBuilder; - buildSession(request: schema.NewSessionRequest): SessionBuilder; - buildSession( - cwdOrRequest: schema.AbsolutePath | schema.NewSessionRequest, - ): SessionBuilder { - if (typeof cwdOrRequest === "string") { - return SessionBuilder.create(this, { - cwd: cwdOrRequest, - mcpServers: [], - }); - } - return SessionBuilder.create(this, cwdOrRequest); - } - /** - * Builds active-session helpers around a `session/new` response. - */ - private attachSession(response: schema.NewSessionResponse): ActiveSession { - const updates = new AsyncQueue(); - const closeSignal = this.connectionContext.signal; - const failUpdatesOnClose = () => { - updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); - }; - if (closeSignal.aborted) { - failUpdatesOnClose(); - } else { - closeSignal.addEventListener("abort", failUpdatesOnClose); - } - const registrations: HandlerRegistration[] = []; - const session = ActiveSession.create( - this, - response, - updates, - registrations, - ); - registrations.push( - sessionUpdateRouter(this.connectionContext).attach(response, { - enqueue: (message) => session[routeActiveSessionUpdate](message), - }), - new HandlerRegistration(() => { - closeSignal.removeEventListener("abort", failUpdatesOnClose); - }), - ); - return session; - } - /** - * Sends a request to the agent by ACP method name. - * - * Built-in method literals infer their params and response types. Custom - * methods can specify their response and params types with generics. - * - * Other requests wait until `initialize` has completed. `initialize` may be - * repeated once the previous one completed and before any other request has - * been sent; otherwise it throws `-32600` synchronously. A repeat that fails - * leaves the previous initialization in effect, and a first `initialize` - * that gets an error response leaves the connection uninitialized, so it can - * be sent again. - * - * Closing or deleting a session is idempotent: a `-32002` (Resource not - * found) response to `session/close` or `session/delete` resolves with an - * empty result instead of rejecting. - */ - request( - method: Method, - params: AgentRequestParamsByMethod[Method], - options?: SendRequestOptions, - ): Promise; - request( - method: ExtensionMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request< - Response = unknown, - Params = unknown, - const Method extends string = never, - >( - method: UnrecognizedMethod, - params?: Params, - options?: SendRequestOptions, - ): Promise; - request( - method: string, - params?: unknown, - options?: SendRequestOptions, - ): Promise { - assertV2MethodDirection(method, agentRequestSpecsByMethod, "request"); - const spec = agentRequestSpecsByMethod[method] as - AcpRequestSpec | undefined; - const state = this.initializationLifecycle; - if (method === schema.AGENT_METHODS.initialize) { - const { wire: request, parsed } = - normalizeOutgoingV2InitializeRequest(params); - state.begin(parsed); - let response: Promise; - // Set when the agent answered with a response this client cannot use, - // as opposed to an error response. - let unusableResponse = false; - try { - response = this.sendRequest( - method, - request, - (value) => { - try { - const parsed = parseRequestResponse(spec!, value); - state.complete(parsed as schema.InitializeResponse); - return parsed; - } catch (error) { - unusableResponse = true; - throw error; - } - }, - options, - ); - } catch (error) { - this.failInitialization(error); - throw error; - } - void response.catch((error) => { - if (state.status === "initializing") { - if (unusableResponse) { - this.failInitialization(error); - } else { - // An error response leaves the connection as it was, so the - // client may send initialize again. - state.failAttempt(); - } - } - }); - return response; - } - state.noteRequest(); - const mapResponse = spec - ? (response: unknown) => parseRequestResponse(spec, response) - : undefined; - return state - .waitUntilInitialized(method) - .then(() => - treatSessionNotFoundAsSuccess( - method, - this.sendRequest(method, params, mapResponse, options), - () => (mapResponse ? mapResponse({}) : {}), - ), - ); - } - /** - * Fails an initialize attempt. Closes the connection unless a previous - * initialization remains in effect. - */ - private failInitialization(error: unknown): void { - const state = this.initializationLifecycle; - state.fail(error); - if (state.status === "failed") { - this.closeOnInitializationFailure?.(error); - } - } - /** - * Sends a notification to the agent by ACP method name. - * - * Built-in method literals infer their params type. Custom notifications can - * specify their params type with a generic. - */ - notify( - method: Method, - params: AgentNotificationParamsByMethod[Method], - ): Promise; - notify( - method: typeof schema.PROTOCOL_METHODS.cancel_request, - params: schema.CancelRequestNotification, - ): Promise; - notify( - method: ExtensionMethod, - params?: Params, - ): Promise; - notify( - method: UnrecognizedMethod, - params?: Params, - ): Promise; - notify(method: string, params?: unknown): Promise { - assertV2MethodDirection( - method, - agentNotificationSpecsByMethod, - "notification", - true, - ); - return this.initializationLifecycle - .waitUntilInitialized(method) - .then(() => this.sendNotification(method, params)); - } -} -class AcpConnectionHandle implements AcpConnection { - constructor(private readonly connection: Connection) {} - get initialized(): Promise { - return initializationState(this.connection.getContext()).initialized; - } - get signal(): AbortSignal { - return this.connection.signal; - } - get closed(): Promise { - return this.connection.closed; - } - close(error?: unknown): void { - this.connection.close(error); - } -} -class AgentConnectionHandle - extends AcpConnectionHandle - implements AgentConnection -{ - readonly client: AgentContext; - private didStartConnectHandlers = false; - constructor( - connection: Connection, - private readonly connectHandlers: readonly AgentConnectHandler[] = [], - ) { - super(connection); - this.client = AgentContext.create(connection.getContext()); - } - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} -class ClientConnectionHandle - extends AcpConnectionHandle - implements ClientConnection -{ - readonly agent: ClientContext; - private didStartConnectHandlers = false; - constructor( - connection: Connection, - private readonly connectHandlers: readonly ClientConnectHandler[] = [], - ) { - super(connection); - this.agent = ClientContext.create( - connection.getContext(), - undefined, - (error) => connection.close(error), - ); - } - /** @internal */ - startConnectHandlers(): void { - if (this.didStartConnectHandlers) { - return; - } - this.didStartConnectHandlers = true; - runConnectHandlers(this, this.connectHandlers); - } -} -function agentConnection( - connection: Connection, - connectHandlers: readonly AgentConnectHandler[] = [], -): AgentConnection { - return new AgentConnectionHandle(connection, connectHandlers); -} -function clientConnection( - connection: Connection, - connectHandlers: readonly ClientConnectHandler[] = [], -): ClientConnection { - return new ClientConnectionHandle(connection, connectHandlers); -} -class AsyncQueue { - private values: Array = []; - private waiters: Array<{ - resolve: (value: T) => void; - reject: (error: unknown) => void; - }> = []; - private failed = false; - private failure: unknown; - enqueue(value: T): void { - if (this.failed) { - return; - } - const waiter = this.waiters.shift(); - if (waiter) { - waiter.resolve(value); - } else { - this.values.push(value); - } - } - fail(error: unknown): void { - if (this.failed) { - return; - } - this.failed = true; - this.failure = error; - for (const waiter of this.waiters.splice(0)) { - waiter.reject(error); - } - } - next(signal?: AbortSignal): Promise { - if (signal?.aborted) { - return Promise.reject(signal.reason); - } - if (this.values.length > 0) { - return Promise.resolve(this.values.shift() as T); - } - if (this.failed) { - return Promise.reject(this.failure); - } - return new Promise((resolve, reject) => { - const cleanup = (): void => { - signal?.removeEventListener("abort", onAbort); - }; - const waiter = { - resolve: (value: T): void => { - cleanup(); - resolve(value); - }, - reject: (error: unknown): void => { - cleanup(); - reject(error); - }, - }; - const onAbort = (): void => { - const index = this.waiters.indexOf(waiter); - if (index >= 0) { - this.waiters.splice(index, 1); - } - waiter.reject(signal?.reason); - }; - this.waiters.push(waiter); - signal?.addEventListener("abort", onAbort, { once: true }); - if (signal?.aborted) { - onAbort(); - } - }); - } -} -/** - * Applies a `capabilities` patch from a `tool_call_update` or - * `terminal_update`: omission leaves it unchanged, `null` clears it, and an - * object replaces it, so `cancel` is supported only when the latest object - * carries a non-null `cancel`. - */ -function applyCancelCapability( - cancellable: Set, - id: Id, - capabilities: - | { - cancel?: unknown; - } - | null - | undefined, -): void { - if (capabilities === undefined) { - return; - } - if (capabilities?.cancel != null) { - cancellable.add(id); - } else { - cancellable.delete(id); - } -} -function cloneNewSessionRequest( - request: schema.NewSessionRequest, -): schema.NewSessionRequest { - return structuredClone(request); -} -/** - * Experimental draft ACP v2 `session/set_config_option` params for - * `ActiveSession.setConfigOption(...)`; the session ID is filled in. - * - * @experimental - */ -export type ActiveSessionSetConfigOptionRequest = - schema.SetSessionConfigOptionRequest extends infer Request - ? Request extends unknown - ? { - [ - Key in keyof Request as Key extends "sessionId" ? never : Key - ]: Request[Key]; - } - : never - : never; -type ActiveSessionQueue = Pick< - AsyncQueue, - "enqueue" | "fail" | "next" ->; -/** - * Experimental draft ACP v2 message produced by an `ActiveSession`. - * - * `session_update` messages expose the typed `session/update` notification and - * `stop` messages report an idle `state_update`. Both are session-scoped: - * a `stop` message does not acknowledge processing or completion of any prompt. - * - * @experimental - */ -export type ActiveSessionMessage = - | { - /** - * Indicates that this message came from a `session/update` notification. - */ - kind: "session_update"; - /** - * Full notification sent by the agent. - */ - notification: schema.UpdateSessionNotification; - /** - * Convenience alias for `notification.update`. - */ - update: schema.SessionUpdate; - } - | { - /** - * Indicates an idle foreground snapshot, not necessarily a new completion. - */ - kind: "stop"; - /** - * Full notification containing the idle state update. - */ - notification: schema.UpdateSessionNotification; - /** - * Convenience alias for `notification.update`. - */ - update: schema.SessionUpdate; - /** - * Stop reason reported by the idle state, when provided. - */ - stopReason: schema.IdleStateUpdate["stopReason"]; - }; -/** - * Experimental draft ACP v2 builder for creating an `ActiveSession`. - * - * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or - * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session - * needs MCP servers, `_meta`, or additional request fields. All paths in ACP - * payloads should be absolute. - * - * @experimental - */ -export class SessionBuilder { - private request: schema.NewSessionRequest; - private constructor( - private cx: ClientContext, - request: schema.NewSessionRequest, - ) { - this.request = cloneNewSessionRequest(request); - } - /** @internal */ - static create( - cx: ClientContext, - request: schema.NewSessionRequest, - ): SessionBuilder { - return new SessionBuilder(cx, request); - } - /** - * Returns the `session/new` request that will be sent. - * - * The returned object is a defensive copy, so mutating it does not change the - * builder. - */ - toRequest(): schema.NewSessionRequest { - return cloneNewSessionRequest(this.request); - } - /** - * Replaces the additional workspace roots for this session. - * - * `additionalDirectories` expand the session's file-system scope without - * changing `cwd`. Each path should be absolute. - */ - withAdditionalDirectories( - additionalDirectories: schema.AbsolutePath[], - ): this { - this.request = { - ...this.request, - additionalDirectories: [...additionalDirectories], - }; - return this; - } - /** - * Adds one MCP server to the `session/new` request. - */ - withMcpServer(mcpServer: schema.McpServer): this { - this.request = { - ...this.request, - mcpServers: [ - ...(this.request.mcpServers ?? []), - structuredClone(mcpServer), - ], - }; - return this; - } - /** - * Starts the session and returns an `ActiveSession` for prompting and reading - * updates. - * - * Call `dispose()` on the returned session when you no longer need update - * routing, or use `withSession(...)` to scope disposal automatically. - */ - async start(options?: SendRequestOptions): Promise { - return this.cx[startActiveSession](this.toRequest(), options); - } - /** - * Starts the session, runs `op`, and disposes the active-session update - * routing when `op` finishes or throws. - */ - async withSession( - op: (session: ActiveSession) => MaybePromise, - ): Promise { - const session = await this.start(); - try { - return await op(session); - } finally { - session.dispose(); - } - } -} -/** - * Experimental draft ACP v2 convenience wrapper for an active session. - * - * An active session routes `session/update` notifications for one session ID - * into an async queue. Use `prompt(...)` to submit user content and - * `nextUpdate()` to observe the session independently of prompt requests. - * A `stop` message reports idle foreground work, not per-prompt completion. - * - * @experimental - */ -export class ActiveSession { - private currentConfigOptions: Array | undefined; - private latestBackground: Array | undefined; - private readonly cancellableToolCalls = new Set(); - private readonly cancellableTerminals = new Set(); - private constructor( - private cx: ClientContext, - private sessionResponse: schema.NewSessionResponse, - private updates: ActiveSessionQueue, - private registrations: HandlerRegistration[], - ) { - this.currentConfigOptions = sessionResponse.configOptions ?? undefined; - } - /** @internal */ - static create( - cx: ClientContext, - sessionResponse: schema.NewSessionResponse, - updates: ActiveSessionQueue, - registrations: HandlerRegistration[], - ): ActiveSession { - return new ActiveSession(cx, sessionResponse, updates, registrations); - } - /** - * Session ID returned by `session/new`. - */ - get sessionId(): schema.SessionId { - return this.sessionResponse.sessionId; - } - /** - * Current configuration options for this session, if the agent provided any. - * - * Starts with the `configOptions` from `session/new`. It is replaced with the - * full list from each `config_option_update` routed to this session (applied - * when the notification arrives, before it is read with `nextUpdate()`) and - * from each `setConfigOption(...)` response. Updates stop after `dispose()`. - * `newSessionResponse.configOptions` keeps the original `session/new` value. - */ - get configOptions(): Array | undefined { - return this.currentConfigOptions; - } - /** - * Metadata returned when the session was created. - */ - get meta(): - | { - [key: string]: unknown; - } - | null - | undefined { - return this.sessionResponse._meta; - } - /** - * The `background` list from the latest `state_update` routed to this - * session, or `undefined` while background work is not reported. - * - * Each `state_update` replaces it, applied when the notification arrives, - * before it is read with `nextUpdate()`. `[]` means no background work is - * running. A snapshot that omits the list, carries `null` or a malformed - * list, or reports a state this SDK does not know resets it to `undefined`: - * background work is unknown until a list arrives, and nothing should be - * treated as abandoned. Updates stop after `dispose()`. - */ - get background(): ReadonlyArray | undefined { - return this.latestBackground; - } - /** - * Whether `request`'s `subject` references work in the latest `background` - * list: a listed tool call (by the subject's `toolCall.toolCallId`, or a - * command subject's `toolCallId`) or a listed terminal (by a command - * subject's `terminalId`). - * - * `session/cancel` does not cover listed work, so permission requests for - * it stay open. For the cancelled foreground work, the Agent stops waiting - * on its permission requests and cancels them with `$/cancel_request`, and - * the Client answers each cancelled request with the `cancelled` outcome. - * A Client may also answer a request with `cancelled` right after sending - * `session/cancel`, without waiting for `$/cancel_request`, but only when - * it knows the request belongs to the cancelled work. A `false` result - * alone does not establish that: it is also returned for requests without - * a `subject`, custom subjects, and any request while `background` is not - * reported. On `session/close`, the Agent cancels every pending permission - * request in the session with `$/cancel_request`. When an Agent sends a - * permission request with `cancellationSignal` and - * `stopWaitingOnCancel: true`, aborting the signal sends - * `$/cancel_request` and stops waiting for the answer. - */ - isForBackgroundWork(request: schema.RequestPermissionRequest): boolean { - const background = this.latestBackground; - const subject = request.subject; - if (!background || !subject) { - return false; - } - let toolCallId: schema.ToolCallId | null | undefined; - let terminalId: schema.TerminalId | null | undefined; - if (guards.RequestPermissionSubject.isToolCall(subject)) { - toolCallId = subject.toolCall.toolCallId; - } else if (guards.RequestPermissionSubject.isCommand(subject)) { - toolCallId = subject.toolCallId; - terminalId = subject.terminalId; - } - return background.some( - (work) => - (toolCallId != null && - guards.BackgroundWork.isToolCall(work) && - work.toolCallId === toolCallId) || - (terminalId != null && - guards.BackgroundWork.isTerminal(work) && - work.terminalId === terminalId), - ); - } - /** - * Whether the tool call currently advertises `capabilities.cancel`, from - * the `tool_call_update` patches routed to this session. - */ - canCancelToolCall(toolCallId: schema.ToolCallId): boolean { - return this.cancellableToolCalls.has(toolCallId); - } - /** - * Whether the terminal currently advertises `capabilities.cancel`, from the - * `terminal_update` patches routed to this session. - */ - canCancelTerminal(terminalId: schema.TerminalId): boolean { - return this.cancellableTerminals.has(terminalId); - } - /** - * Cancels one tool call with `tool_call/cancel`. - * - * Rejects with a `TypeError`, without sending the request, unless the tool - * call currently advertises `capabilities.cancel` (see - * `canCancelToolCall`). The response means the Agent accepted the - * cancellation, not that the work stopped. The Agent confirms it with a - * `tool_call_update` to a final status. - * - * This only covers tool calls reported in this session. A subagent's tool - * call is reported in its child session, so send - * `methods.agent.toolCall.cancel` through `ClientContext.request` with the - * child's `sessionId`. The tool call's own `capabilities.cancel` enables - * that even when the child session doesn't advertise `cancel`. - * - * The Agent answers `-32602` once the tool call has a final status. This - * includes a request sent again after the first one was accepted. The - * `tool_call_update` with that status reports the outcome. - */ - cancelToolCall( - toolCallId: schema.ToolCallId, - options?: SendRequestOptions, - ): Promise { - if (!this.canCancelToolCall(toolCallId)) { - return Promise.reject( - new TypeError( - `Tool call ${JSON.stringify(toolCallId)} does not advertise cancel`, - ), - ); - } - return this.cx.request( - schema.AGENT_METHODS.tool_call_cancel, - { sessionId: this.sessionId, toolCallId }, - options, - ); - } - /** - * Stops a terminal's process with `terminal/cancel`. - * - * Rejects with a `TypeError`, without sending the request, unless the - * terminal currently advertises `capabilities.cancel` (see - * `canCancelTerminal`). The response means the Agent accepted the - * cancellation, not that the process stopped. The Agent confirms it with a - * `terminal_update` that sets `exitStatus`. The terminal is not released. - * - * This only covers terminals reported in this session. A subagent's - * terminal is reported in its child session, so send - * `methods.agent.terminal.cancel` through `ClientContext.request` with the - * child's `sessionId`. The terminal's own `capabilities.cancel` enables - * that even when the child session doesn't advertise `cancel`. - * - * The Agent answers `-32602` once the process has exited. This includes a - * request sent again after the first one was accepted. The - * `terminal_update` that sets `exitStatus` reports the outcome. - */ - cancelTerminal( - terminalId: schema.TerminalId, - options?: SendRequestOptions, - ): Promise { - if (!this.canCancelTerminal(terminalId)) { - return Promise.reject( - new TypeError( - `Terminal ${JSON.stringify(terminalId)} does not advertise cancel`, - ), - ); - } - return this.cx.request( - schema.AGENT_METHODS.terminal_cancel, - { sessionId: this.sessionId, terminalId }, - options, - ); - } - /** - * Full response returned by `session/new`. - */ - get newSessionResponse(): schema.NewSessionResponse { - return this.sessionResponse; - } - /** - * Sends a prompt to this session. - * - * Strings are converted to one text content block. A single content block is - * wrapped in an array. A prompt must contain at least one block. The returned - * promise resolves with the inserted user message's ID once the agent - * inserts it into the ACP conversation, not when processing finishes. - * - * A prompt may be sent while the agent is working. The agent inserts it - * right away or holds it and inserts it later, in the order received; the - * promise stays pending until then. Aborting `options.cancellationSignal` - * withdraws a held prompt, and `session/cancel` or `session/close` answer - * held prompts with `-32800`. `session/cancel` does not affect a prompt sent - * after it. - * - * Session updates remain independent of this request and have no fixed - * order relative to its response; an idle `state_update` does not establish - * that this message was processed. Rejection is reported only by this - * promise, not by the session update queue. - */ - prompt( - prompt: string | schema.ContentBlock | Array, - options?: SendRequestOptions, - ): Promise { - const blocks = this.promptBlocks(prompt); - if (blocks.length === 0) { - // Clients must not send an empty prompt. - return Promise.reject( - new TypeError("A prompt must contain at least one content block"), - ); - } - return this.cx.request( - schema.AGENT_METHODS.session_prompt, - { - sessionId: this.sessionId, - prompt: blocks, - }, - options, - ); - } - /** - * Sets a configuration option for this session with - * `session/set_config_option`. - * - * The response carries the agent's complete `configOptions` list, which - * replaces `configOptions` on this session. For example, - * `session.setConfigOption({ configId: "model", type: "id", value: "fast" })`. - */ - async setConfigOption( - request: ActiveSessionSetConfigOptionRequest, - options?: SendRequestOptions, - ): Promise { - const response = await this.cx.request( - schema.AGENT_METHODS.session_set_config_option, - { ...request, sessionId: this.sessionId }, - options, - ); - this.currentConfigOptions = response.configOptions; - return response; - } - /** - * Reads the next update or stop message for this session. - * - * Idle updates are always returned as `stop` messages, whether or not a prompt - * is pending. Queued updates are consumed in arrival order. An abort signal - * cancels this read without cancelling session work or discarding updates. - */ - nextUpdate(signal?: AbortSignal): Promise { - return this.updates.next(signal); - } - /** - * Collects agent text from the session queue until the next idle update. - * - * This consumes the same queue as `nextUpdate()`, including already queued - * updates. It does not associate output or idle with any submitted prompt, - * skip updates when a prompt is sent, or wait for a prompt to be inserted. - * Use one reader at a time to avoid splitting the session's updates. - * An abort signal cancels the read without cancelling session work. - * - * Full `agent_message` updates replace content for their `messageId`, while - * `agent_message_chunk` updates append to it. Non-text content and other - * update types are ignored; use `nextUpdate()` when you need them. - */ - async readTextUntilIdle(signal?: AbortSignal): Promise { - const messageOrder: schema.MessageId[] = []; - const messageContent = new Map< - schema.MessageId, - Array - >(); - const ensureMessage = ( - messageId: schema.MessageId, - ): Array => { - let content = messageContent.get(messageId); - if (!content) { - content = []; - messageOrder.push(messageId); - messageContent.set(messageId, content); - } - return content; - }; - for (;;) { - const message = await this.nextUpdate(signal); - if (message.kind === "stop") { - return messageOrder - .flatMap((messageId) => messageContent.get(messageId) ?? []) - .filter(guards.ContentBlock.isText) - .map((content) => content.text) - .join(""); - } - const { update } = message; - if (guards.SessionUpdate.isAgentMessage(update)) { - ensureMessage(update.messageId); - if (update.content !== undefined) { - messageContent.set(update.messageId, update.content ?? []); - } - } else if (guards.SessionUpdate.isAgentMessageChunk(update)) { - ensureMessage(update.messageId).push(update.content); - } - } - } - /** @internal */ - [routeActiveSessionUpdate](message: ActiveSessionMessage): void { - const { update } = message; - if (guards.SessionUpdate.isConfigOptionUpdate(update)) { - this.currentConfigOptions = update.configOptions; - } else if (guards.SessionUpdate.isStateUpdate(update)) { - this.latestBackground = - !guards.StateUpdate.isCustom(update) && Array.isArray(update.background) - ? update.background - : undefined; - } else if (guards.SessionUpdate.isToolCallUpdate(update)) { - applyCancelCapability( - this.cancellableToolCalls, - update.toolCallId, - update.capabilities, - ); - } else if (guards.SessionUpdate.isTerminalUpdate(update)) { - applyCancelCapability( - this.cancellableTerminals, - update.terminalId, - update.capabilities, - ); - } - this.updates.enqueue(message); - } - /** - * Stops routing updates to this active-session helper. - * - * This does not close the ACP session on the agent. Use `ClientContext` - * session lifecycle methods when the protocol session itself should be closed - * or deleted. - */ - dispose(): void { - for (const registration of this.registrations.splice(0)) { - registration.dispose(); - } - this.updates.fail(new Error("Active session disposed")); - } - /** - * Supports explicit resource management with `using`. - */ - [Symbol.dispose](): void { - this.dispose(); - } - private promptBlocks( - prompt: string | schema.ContentBlock | Array, - ): Array { - if (typeof prompt === "string") { - return [{ type: "text", text: prompt }]; - } - if (Array.isArray(prompt)) { - return prompt; - } - return [prompt]; - } -} -/** - * Options used when creating an ACP app. - */ -export type AppOptions = { - /** - * Human-readable name used in JSON-RPC handler descriptions and diagnostics. - */ - name?: string; -}; -/** - * Common context passed to agent-side handlers. - */ -export type AgentHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed client context for calling client-side ACP methods. - */ - client: AgentContext; -}; -/** - * Context passed to agent-side request handlers. - */ -export type AgentRequestContext = AgentHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; -/** - * Context passed to agent-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type AgentNotificationContext = AgentHandlerContext; -/** - * Common context passed to client-side handlers. - */ -export type ClientHandlerContext = { - /** The method being handled, including the actual name in fallback handlers. */ - method: string; - /** - * Parsed request or notification params. - */ - params: Params; - /** - * AbortSignal for the current request, or the connection signal for - * notifications. - */ - signal: AbortSignal; - /** - * Typed agent context for calling agent-side ACP methods. - */ - agent: ClientContext; -}; -/** - * Context passed to client-side request handlers. - */ -export type ClientRequestContext = ClientHandlerContext & { - /** - * JSON-RPC id of the request currently being handled. - */ - requestId: JsonRpcId; -}; -/** - * Context passed to client-side notification handlers. - * - * Notifications do not have JSON-RPC request ids. - */ -export type ClientNotificationContext = ClientHandlerContext; -/** - * Request handler registered on an `AgentApp`. - */ -export type AgentRequestHandler = ( - context: AgentRequestContext, -) => MaybePromise; -/** - * Notification handler registered on an `AgentApp`. - */ -export type AgentNotificationHandler = ( - context: AgentNotificationContext, -) => MaybePromise; -/** - * Request handler registered on a `ClientApp`. - */ -export type ClientRequestHandler = ( - context: ClientRequestContext, -) => MaybePromise; -/** - * Notification handler registered on a `ClientApp`. - */ -export type ClientNotificationHandler = ( - context: ClientNotificationContext, -) => MaybePromise; -/** - * Handler called when an `AgentApp` opens a connection. - */ -export type AgentConnectHandler = ( - connection: AgentConnection, -) => MaybePromise; -/** - * Handler called when a `ClientApp` opens a connection. - */ -export type ClientConnectHandler = ( - connection: ClientConnection, -) => MaybePromise; -type AcpRequestSpec = { - method: string; - params?: ParamsParser; - response?: ParamsParser; - serializeResponse?: (response: HandlerResponse) => Response; -}; -type AcpNotificationSpec = { - method: string; - params?: ParamsParser; -}; -/** - * A generated validator as the parser of received values. - * - * The validators type the tag of an unknown variant as a plain string, while - * the protocol types brand it as an `UnknownVariant`, which only received - * values have. Everything a validator parses is received, so its output has - * the protocol type. - */ -function received(validator: { parse(value: unknown): unknown }): { - parse(value: unknown): T; -} { - return validator as { - parse(value: unknown): T; - }; -} -function requestSpec( - method: string, - params: ParamsParser, - response: ParamsParser, - serializeResponse?: (response: HandlerResponse) => Response, -): AcpRequestSpec { - return { - method, - // Match Rust's empty-payload handling without bypassing required fields. - params: (value) => parseParams(params, value ?? {}), - response, - serializeResponse, - }; -} -function notificationSpec( - method: string, - params: ParamsParser, -): AcpNotificationSpec { - return { method, params }; -} -function specsByMethod< - T extends Record< - string, - { - method: string; - } - >, ->(specs: T): Record { - const byMethod = Object.create(null) as Record; - for (const spec of Object.values(specs) as Array) { - byMethod[spec.method] = spec; - } - return byMethod; -} -const agentRequestSpecs = { - initialize: requestSpec( - schema.AGENT_METHODS.initialize, - parseV2InitializeRequest, - mapV2InitializeResponse, - serializeV2InitializeResponse, - ), - loginAuth: requestSpec< - schema.LoginAuthRequest, - schema.LoginAuthResponse | void, - schema.LoginAuthResponse - >( - schema.AGENT_METHODS.auth_login, - validate.zLoginAuthRequest, - validate.zLoginAuthResponse, - emptyObjectResponse, - ), - newSession: requestSpec( - schema.AGENT_METHODS.session_new, - received(validate.zNewSessionRequest), - received(validate.zNewSessionResponse), - ), - setSessionConfigOption: requestSpec< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >( - schema.AGENT_METHODS.session_set_config_option, - received(validate.zSetSessionConfigOptionRequest), - received(validate.zSetSessionConfigOptionResponse), - ), - prompt: requestSpec( - schema.AGENT_METHODS.session_prompt, - received(validate.zPromptRequest), - received(validate.zPromptResponse), - ), - listSessions: requestSpec< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >( - schema.AGENT_METHODS.session_list, - validate.zListSessionsRequest, - validate.zListSessionsResponse, - ), - deleteSession: requestSpec< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void, - schema.DeleteSessionResponse - >( - schema.AGENT_METHODS.session_delete, - validate.zDeleteSessionRequest, - validate.zDeleteSessionResponse, - emptyObjectResponse, - ), - resumeSession: requestSpec< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >( - schema.AGENT_METHODS.session_resume, - received(validate.zResumeSessionRequest), - received(validate.zResumeSessionResponse), - ), - closeSession: requestSpec< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void, - schema.CloseSessionResponse - >( - schema.AGENT_METHODS.session_close, - validate.zCloseSessionRequest, - validate.zCloseSessionResponse, - emptyObjectResponse, - ), - cancelToolCall: requestSpec< - schema.CancelToolCallRequest, - schema.CancelToolCallResponse | void, - schema.CancelToolCallResponse - >( - schema.AGENT_METHODS.tool_call_cancel, - validate.zCancelToolCallRequest, - validate.zCancelToolCallResponse, - emptyObjectResponse, - ), - cancelTerminal: requestSpec< - schema.CancelTerminalRequest, - schema.CancelTerminalResponse | void, - schema.CancelTerminalResponse - >( - schema.AGENT_METHODS.terminal_cancel, - validate.zCancelTerminalRequest, - validate.zCancelTerminalResponse, - emptyObjectResponse, - ), - logoutAuth: requestSpec< - schema.LogoutAuthRequest, - schema.LogoutAuthResponse | void, - schema.LogoutAuthResponse - >( - schema.AGENT_METHODS.auth_logout, - validate.zLogoutAuthRequest, - validate.zLogoutAuthResponse, - emptyObjectResponse, - ), -}; -const agentNotificationSpecs = { - cancelSession: notificationSpec( - schema.AGENT_METHODS.session_cancel, - validate.zCancelSessionNotification, - ), -}; -const clientRequestSpecs = { - requestPermission: requestSpec< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >( - schema.CLIENT_METHODS.session_request_permission, - received(validate.zRequestPermissionRequest), - received(validate.zRequestPermissionResponse), - ), - createElicitation: requestSpec< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >( - schema.CLIENT_METHODS.elicitation_create, - received(validate.zCreateElicitationRequest), - received(validate.zCreateElicitationResponse), - ), -}; -const clientNotificationSpecs = { - sessionUpdate: notificationSpec( - schema.CLIENT_METHODS.session_update, - received(validate.zUpdateSessionNotification), - ), - completeElicitation: notificationSpec( - schema.CLIENT_METHODS.elicitation_complete, - validate.zCompleteElicitationNotification, - ), -}; -const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); -const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); -const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); -const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); -/** - * Agent request handlers keyed by ACP protocol method name. - */ -export type AgentRequestHandlersByMethod = { - /** - * Handles `initialize`. - * - * Runs again for each repeated `initialize`, which the Client may send after - * a previous one completed and before any other request; the latest - * successful exchange is authoritative. Other requests that arrive while - * `initialize` is in flight are rejected with `-32600`. - * - * When the Client requests a newer protocol version than v2, params that do - * not parse under v2 are dropped instead of rejected, and a missing or - * malformed `info` is replaced with `{ name: "unknown", version: "unknown" }`. - */ - [schema.AGENT_METHODS.initialize]: AgentRequestHandler< - schema.InitializeRequest, - schema.InitializeResponse - >; - [schema.AGENT_METHODS.auth_login]: AgentRequestHandler< - schema.LoginAuthRequest, - schema.LoginAuthResponse | void - >; - [schema.AGENT_METHODS.session_new]: AgentRequestHandler< - schema.NewSessionRequest, - schema.NewSessionResponse - >; - [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< - schema.SetSessionConfigOptionRequest, - schema.SetSessionConfigOptionResponse - >; - [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< - schema.PromptRequest, - schema.PromptResponse - >; - [schema.AGENT_METHODS.session_list]: AgentRequestHandler< - schema.ListSessionsRequest, - schema.ListSessionsResponse - >; - [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< - schema.DeleteSessionRequest, - schema.DeleteSessionResponse | void - >; - /** - * Handles `session/resume`. - * - * With a `replayFrom` cursor, replay the history as `session/update` - * notifications, then send `replay_complete` exactly once, also when the - * history is empty. Until then, send only replayed history for the - * session and hold its other updates. Requests such as - * `session/request_permission` should wait too. Do not send - * `replay_complete` when `replayFrom` is omitted or `null`, or when the - * replay cannot be finished. Throw `-32602` for an unsupported cursor, - * without replaying anything. - * - * For every successful resume, send the current `state_update` before - * responding, after `replay_complete` when a replay was requested. - */ - [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< - schema.ResumeSessionRequest, - schema.ResumeSessionResponse - >; - /** - * Handles `session/close`. Before responding, cancel every pending - * `session/request_permission` request and elicitation in the session with - * `$/cancel_request`, for example by aborting the `cancellationSignal` - * passed to `AgentContext.request`. Pass `stopWaitingOnCancel: true` with - * it so the pending request promise rejects with `-32800` right away - * instead of waiting for the Client's answer. Closing also stops the - * session's background work. - */ - [schema.AGENT_METHODS.session_close]: AgentRequestHandler< - schema.CloseSessionRequest, - schema.CloseSessionResponse | void - >; - /** - * Handles `tool_call/cancel`. - * - * Respond once the cancellation is accepted, then confirm it with a - * `tool_call_update` to a final status. Throw `-32602` for a tool call - * that is unknown, already final, or not cancellable. This includes a - * request the Client sends again after the first one was accepted and the - * tool call has since reached a final status. Without this handler (and - * without a `"*"` request fallback), the app answers every - * `tool_call/cancel` with `-32602`. - */ - [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< - schema.CancelToolCallRequest, - schema.CancelToolCallResponse | void - >; - /** - * Handles `terminal/cancel`. - * - * Respond once the cancellation is accepted, then confirm it with a - * `terminal_update` that sets `exitStatus`. Cancelling does not release the - * terminal. Throw `-32602` for a terminal that is unknown, has already - * exited, or is not cancellable. This includes a request the Client sends - * again after the first one was accepted and the process has since exited. - * Without this handler (and without a `"*"` request fallback), the app - * answers every `terminal/cancel` with `-32602`. - */ - [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< - schema.CancelTerminalRequest, - schema.CancelTerminalResponse | void - >; - /** - * Handles `auth/logout`. Logging out is idempotent: respond with the same - * empty result when there is no authenticated state to end, for example - * because the Client already logged out. - */ - [schema.AGENT_METHODS.auth_logout]: AgentRequestHandler< - schema.LogoutAuthRequest, - schema.LogoutAuthResponse | void - >; -}; -/** - * ACP request methods that can be handled by an `AgentApp`. - */ -export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; -/** - * Agent notification handlers keyed by ACP protocol method name. - */ -export type AgentNotificationHandlersByMethod = { - /** - * Handles `session/cancel`. Stop waiting on the pending - * `session/request_permission` requests of the cancelled foreground work, - * treat them as not approved, and cancel each with `$/cancel_request`, for - * example by aborting the `cancellationSignal` passed to - * `AgentContext.request`. With `stopWaitingOnCancel: true`, aborting the - * signal does both: it sends `$/cancel_request` and rejects the request - * promise with `-32800` without waiting for the Client's answer. Work in - * the latest `background` list keeps running. - */ - [schema.AGENT_METHODS - .session_cancel]: AgentNotificationHandler; -}; -/** - * ACP notification methods that can be handled by an `AgentApp`. - */ -export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & - string; -/** - * Client request handlers keyed by ACP protocol method name. - */ -export type ClientRequestHandlersByMethod = { - [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< - schema.RequestPermissionRequest, - schema.RequestPermissionResponse - >; - [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< - schema.CreateElicitationRequest, - schema.CreateElicitationResponse - >; -}; -/** - * ACP request methods that can be handled by a `ClientApp`. - */ -export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; -/** - * Client notification handlers keyed by ACP protocol method name. - */ -export type ClientNotificationHandlersByMethod = { - [schema.CLIENT_METHODS - .session_update]: ClientNotificationHandler; - [schema.CLIENT_METHODS - .elicitation_complete]: ClientNotificationHandler; -}; -/** - * ACP notification methods that can be handled by a `ClientApp`. - */ -export type ClientNotificationMethod = - keyof ClientNotificationHandlersByMethod & string; -/** - * Agent request params keyed by ACP protocol method name. - */ -export type AgentRequestParamsByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -/** - * Agent request responses keyed by ACP protocol method name. - */ -export type AgentRequestResponsesByMethod = { - [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; -/** - * Agent notification params keyed by ACP protocol method name. - */ -export type AgentNotificationParamsByMethod = { - [ - Method in AgentNotificationMethod - ]: AgentNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -/** - * Client request params keyed by ACP protocol method name. - */ -export type ClientRequestParamsByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -/** - * Client request responses keyed by ACP protocol method name. - */ -export type ClientRequestResponsesByMethod = { - [ - Method in ClientRequestMethod - ]: ClientRequestHandlersByMethod[Method] extends ( - context: infer _Context, - ) => MaybePromise - ? Exclude - : never; -}; -/** - * Client notification params keyed by ACP protocol method name. - */ -export type ClientNotificationParamsByMethod = { - [ - Method in ClientNotificationMethod - ]: ClientNotificationHandlersByMethod[Method] extends ( - context: infer Context, - ) => MaybePromise - ? Context extends { - params: infer Params; - } - ? Params - : never - : never; -}; -function agentRequestContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): AgentRequestContext { - return { - method, - params, - requestId, - signal, - client, - }; -} -function agentNotificationContext( - params: Params, - client: AgentContext, - signal: AbortSignal, - method: string, -): AgentNotificationContext { - return { - method, - params, - signal, - client, - }; -} -function clientRequestContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - requestId: JsonRpcId, - method: string, -): ClientRequestContext { - return { - method, - params, - requestId, - signal, - agent, - }; -} -function clientNotificationContext( - params: Params, - agent: ClientContext, - signal: AbortSignal, - method: string, -): ClientNotificationContext { - return { - method, - params, - signal, - agent, - }; -} -type ActiveSessionUpdateQueue = Pick; -class SessionUpdateRouter { - private readonly activeSessions = new Map< - string, - Set - >(); - handleMessage(message: IncomingMessage): HandleResult { - if ( - message.kind !== "notification" || - message.method !== schema.CLIENT_METHODS.session_update - ) { - return Handled.no(message); - } - const notification = received( - validate.zUpdateSessionNotification, - ).parse(message.params); - const { update } = notification; - const isIdle = - guards.SessionUpdate.isStateUpdate(update) && - guards.StateUpdate.isIdle(update); - const activeSessions = this.activeSessions.get(notification.sessionId); - if (activeSessions && activeSessions.size > 0) { - for (const session of activeSessions) { - if (isIdle) { - session.enqueue({ - kind: "stop", - notification, - update, - stopReason: update.stopReason, - }); - } else { - session.enqueue({ - kind: "session_update", - notification, - update, - }); - } - } - } - return Handled.no(message); - } - attach( - response: schema.NewSessionResponse, - updates: ActiveSessionUpdateQueue, - ): HandlerRegistration { - const sessions = - this.activeSessions.get(response.sessionId) ?? - new Set(); - sessions.add(updates); - this.activeSessions.set(response.sessionId, sessions); - return new HandlerRegistration(() => { - sessions.delete(updates); - if (sessions.size === 0) { - this.activeSessions.delete(response.sessionId); - } - }); - } -} -const sessionUpdateRouters = new WeakMap< - ConnectionContext, - SessionUpdateRouter ->(); -function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { - let router = sessionUpdateRouters.get(cx); - if (!router) { - router = new SessionUpdateRouter(); - sessionUpdateRouters.set(cx, router); - } - return router; -} -function runConnectHandlers( - connection: ConnectionHandle, - handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, -): void { - for (const handler of handlers) { - let result: MaybePromise; - try { - result = handler(connection); - } catch (error) { - connection.close(error); - throw error; - } - void Promise.resolve(result).catch((error) => { - connection.close(error); - }); - } -} -const appBuilder = Symbol("appBuilder"); -const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); -const runClientConnectHandlers = Symbol("runClientConnectHandlers"); -type AppConnectOptions = { - readonly deferConnectHandlers?: boolean; -}; -type AgentConnectionState = { - rawConnection: Connection; - connection: AgentConnection; -}; -type ClientConnectionState = { - rawConnection: Connection; - connection: ClientConnection; -}; -function bridgeConnectionClose(source: Connection, peer: Connection): void { - void source.closed.then(async () => { - if (initializationState(source.getContext()).status === "initialized") { - await initializationState(peer.getContext()).initialized.catch(() => {}); - } - peer.closeFromPeer(source.signal.reason); - }); -} -/** - * Creates an agent-side app for the experimental draft ACP v2 API. - * - * Register request and notification handlers by ACP method name, then call - * `connect(stream)` to serve an ACP client. - * - * @experimental - */ -export function agent(options?: AppOptions): AgentApp { - return new AgentApp(options); -} -/** - * Agent-side app builder for the experimental draft ACP v2 API. - * - * Methods on this class register typed request or notification handlers and - * return `this`, so apps can be built with a fluent chain. Handler params are - * parsed with the generated ACP schemas before your handler runs, and thrown - * errors are converted to JSON-RPC errors by the connection layer. - * - * @experimental - */ -export class AgentApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: AgentConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - private readonly requestMethods = new Set(); - private hasInitializeHandler = false; - constructor(options: AppOptions = {}) { - this.builder.withHandler(agentInitializationGuard()); - this.builder.withHandler( - defaultEntityCancelHandler( - (method) => - this.requestMethods.has(method) || this.fallbackKinds.has("request"), - ), - ); - if (options.name) { - this.builder.name(options.name); - } - } - /** @internal */ - [appBuilder](): ConnectionBuilder { - this.assertInitializeHandler(); - return this.builder; - } - /** @internal */ - [runAgentConnectHandlers](connection: AgentConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - /** - * Connects this agent app to a transport stream. - */ - connect(stream: Stream): AgentConnection; - /** @internal */ - connect(stream: Stream, options: AppConnectOptions): AgentConnection; - /** - * Connects this agent app directly to a client app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(client: ClientApp): AgentConnection; - connect( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnection { - return this.connectConnection(target, options).connection; - } - /** - * Connects this agent app to a stream or client app for the lifetime of `op`. - * - * The callback receives an `AgentContext` for calling client-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | ClientApp, - op: (context: AgentContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.client)); - } - /** - * Registers a handler that runs when this agent app opens a connection. - * - * Use this for connection-scoped work that needs to call client-side ACP - * methods outside an inbound request handler, or to set up per-connection - * state that the request handlers use. Requests and notifications sent - * through `connection.client` wait until `initialize` has completed. - * - * Handlers are called synchronously in registration order and are not - * awaited. A handler that throws or rejects closes the connection. When they - * are called depends on who opens the connection: - * - * - `connect(...)` and `connectWith(...)` call them before the connection - * handles its first inbound message, and so does - * {@link AgentProtocolRouter.connect} when it routes to this app. Only the - * work a handler does before its first `await` is guaranteed to come first. - * - The experimental `AcpServer` calls them after the client has completed - * `initialize`. Request handlers, including `initialize`, can run before - * them. - */ - onConnect(handler: AgentConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - /** - * Registers a request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: AgentRequestHandler): this; - onRequest( - method: Method, - handler: AgentRequestHandlersByMethod[Method], - ): this; - onRequest( - method: ExtensionMethod, - params: ParamsParser, - handler: AgentRequestHandler, - ): this; - onRequest( - method: UnrecognizedMethod, - params: ParamsParser, - handler: AgentRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | AgentRequestHandlersByMethod[AgentRequestMethod] - | AgentRequestHandler - | ParamsParser, - handler?: AgentRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as AgentRequestHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "request"); - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = agentRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - if (method === schema.AGENT_METHODS.initialize) { - this.hasInitializeHandler = true; - } - this.requestMethods.add(method); - return this.request( - spec as AcpRequestSpec, - handlerOrParams as AgentRequestHandler, - ); - } - /** - * Registers a notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. Serialize work yourself - * when its effects must be applied in order. - */ - onNotification(method: "*", handler: AgentNotificationHandler): this; - onNotification( - method: Method, - handler: AgentNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: ExtensionMethod, - params: ParamsParser, - handler: AgentNotificationHandler, - ): this; - onNotification( - method: UnrecognizedMethod, - params: ParamsParser, - handler: AgentNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | AgentNotificationHandlersByMethod[AgentNotificationMethod] - | AgentNotificationHandler - | ParamsParser, - handler?: AgentNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as AgentNotificationHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "notification"); - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = agentNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as AgentNotificationHandler, - ); - } - private request( - spec: AcpRequestSpec, - handler: AgentRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - agentRequestContext( - params, - AgentContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.serializeResponse, - spec.method === schema.AGENT_METHODS.initialize - ? { - beforeResponse: (_params, response, cx) => { - initializationState(cx).complete( - mapV2InitializeResponse(response), - ); - }, - onError: (cx) => initializationState(cx).failAttempt(), - } - : undefined, - ); - return this; - } - private notification( - spec: AcpNotificationSpec, - handler: AgentNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - agentNotificationContext( - params, - AgentContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - private connectConnection( - target: Stream | ClientApp, - options: AppConnectOptions = {}, - ): AgentConnectionState { - this.assertInitializeHandler(); - if (isStream(target)) { - const state = this.openStreamConnection(target); - if (!options.deferConnectHandlers) { - this[runAgentConnectHandlers](state.connection); - } - return state; - } - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = clientConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerRawConnection); - bridgeConnectionClose(peerRawConnection, state.rawConnection); - try { - target[runClientConnectHandlers](peerConnection); - this[runAgentConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - private openStreamConnection(stream: Stream): AgentConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: agentConnection(rawConnection, this.connectHandlers), - }; - } - private assertInitializeHandler(): void { - if (!this.hasInitializeHandler) { - throw new Error( - "AgentApp requires an initialize request handler before connecting", - ); - } - } -} -/** - * Creates a client-side app for the experimental draft ACP v2 API. - * - * Register request and notification handlers by ACP method name, then use - * `connectWith(...)` to run the workflow that calls agent-side methods. - * - * @experimental - */ -export function client(options?: AppOptions): ClientApp { - return new ClientApp(options); -} -/** - * Client-side app builder for the experimental draft ACP v2 API. - * - * Methods on this class register typed client handlers and return `this`, so - * apps can be built with a fluent chain. `connectWith(...)` is the usual entry - * point for clients because it provides a `ClientContext` for calling - * agent-side requests and session helpers. - * - * @experimental - */ -export class ClientApp { - private readonly builder = Connection.builder(); - private readonly connectHandlers: ClientConnectHandler[] = []; - private readonly fallbackKinds = new Set<"request" | "notification">(); - constructor(options: AppOptions = {}) { - if (options.name) { - this.builder.name(options.name); - } - this.builder.withHandler(clientInitializationGuard()); - this.builder.withHandler({ - handleMessage: (message, cx) => - sessionUpdateRouter(cx).handleMessage(message), - describe: () => "client-session-update-router", - }); - } - /** @internal */ - [appBuilder](): ConnectionBuilder { - return this.builder; - } - /** @internal */ - [runClientConnectHandlers](connection: ClientConnection): void { - runConnectHandlers(connection, this.connectHandlers); - } - /** - * Connects this client app to a transport stream. - */ - connect(stream: Stream): ClientConnection; - /** - * Connects this client app directly to an agent app. - * - * This is useful for tests and in-process examples that do not need a - * transport. - */ - connect(agent: AgentApp): ClientConnection; - connect(target: Stream | AgentApp): ClientConnection { - return this.connectConnection(target).connection; - } - /** - * Connects this client app to a stream or agent app for the lifetime of `op`. - * - * The callback receives a `ClientContext` for calling agent-side methods. - * When `op` resolves or rejects, the connection is closed. - */ - connectWith( - target: Stream | AgentApp, - op: (context: ClientContext) => MaybePromise, - ): Promise { - const { rawConnection, connection } = this.connectConnection(target); - return rawConnection.runUntil(() => op(connection.agent)); - } - /** - * Registers a handler that runs when this client app opens a connection. - * - * Use this for connection-scoped work that needs to call agent-side ACP - * methods outside an inbound request handler. - */ - onConnect(handler: ClientConnectHandler): this { - this.connectHandlers.push(handler); - return this; - } - /** - * Registers a client request handler by ACP method name. - * - * Built-in method literals infer their params and response types from - * `method`. Pass a parser as the second argument to register custom extension - * methods. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - */ - onRequest(method: "*", handler: ClientRequestHandler): this; - onRequest( - method: Method, - handler: ClientRequestHandlersByMethod[Method], - ): this; - onRequest( - method: ExtensionMethod, - params: ParamsParser, - handler: ClientRequestHandler, - ): this; - onRequest( - method: UnrecognizedMethod, - params: ParamsParser, - handler: ClientRequestHandler, - ): this; - onRequest( - method: string, - handlerOrParams: - | ClientRequestHandlersByMethod[ClientRequestMethod] - | ClientRequestHandler - | ParamsParser, - handler?: ClientRequestHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("request")) - throw new Error("A request fallback is already registered."); - this.fallbackKinds.add("request"); - return this.request( - { method }, - handlerOrParams as ClientRequestHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "request"); - return this.request( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = clientRequestSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, - ); - } - return this.request( - spec as AcpRequestSpec, - handlerOrParams as ClientRequestHandler, - ); - } - /** - * Registers a client notification handler by ACP method name. - * - * Built-in method literals infer their params type from `method`. Pass a - * parser as the second argument to register custom extension notifications. - * Use `"*"` without a parser for a raw fallback after normal dispatch. - * - * Handlers start in the order notifications arrive, but the connection does - * not wait for an async handler to settle before dispatching the next - * message, so async handlers can run concurrently. ACP requires a session's - * `session/update` notifications to be applied in the order they are - * received, so a `session/update` handler that awaits before applying an - * update must serialize that work itself, for example by chaining it onto a - * per-session promise. {@link ActiveSession} already queues updates in - * arrival order. - */ - onNotification( - method: "*", - handler: ClientNotificationHandler, - ): this; - onNotification( - method: Method, - handler: ClientNotificationHandlersByMethod[Method], - ): this; - onNotification( - method: ExtensionMethod, - params: ParamsParser, - handler: ClientNotificationHandler, - ): this; - onNotification( - method: UnrecognizedMethod, - params: ParamsParser, - handler: ClientNotificationHandler, - ): this; - onNotification( - method: string, - handlerOrParams: - | ClientNotificationHandlersByMethod[ClientNotificationMethod] - | ClientNotificationHandler - | ParamsParser, - handler?: ClientNotificationHandler, - ): this { - if (method === "*") { - if (handler) - throw new Error( - "Wildcard handlers receive raw params; omit the parser.", - ); - if (this.fallbackKinds.has("notification")) - throw new Error("A notification fallback is already registered."); - this.fallbackKinds.add("notification"); - return this.notification( - { method }, - handlerOrParams as ClientNotificationHandler, - ); - } - if (handler) { - assertUnrecognizedV2Method(method, "notification"); - return this.notification( - { method, params: handlerOrParams as ParamsParser }, - handler, - ); - } - const spec = clientNotificationSpecsByMethod[method]; - if (!spec) { - throw new Error( - `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, - ); - } - return this.notification( - spec as AcpNotificationSpec, - handlerOrParams as ClientNotificationHandler, - ); - } - private request( - spec: AcpRequestSpec, - handler: ClientRequestHandler, - ): this { - registerAppRequest( - this.builder, - spec, - (params, cx, signal, requestId, method) => - clientRequestContext( - params, - ClientContext.create(cx, requestId), - signal, - requestId, - method, - ), - handler, - spec.serializeResponse, - ); - return this; - } - private notification( - spec: AcpNotificationSpec, - handler: ClientNotificationHandler, - ): this { - registerAppNotification( - this.builder, - spec, - (params, cx, signal, method) => - clientNotificationContext( - params, - ClientContext.create(cx), - signal, - method, - ), - handler, - ); - return this; - } - private connectConnection(target: Stream | AgentApp): ClientConnectionState { - if (isStream(target)) { - const state = this.openStreamConnection(target); - this[runClientConnectHandlers](state.connection); - return state; - } - const [thisStream, peerStream] = memoryStreamPair(); - const peerRawConnection = target[appBuilder]().connect(peerStream); - const peerConnection = agentConnection(peerRawConnection); - const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerRawConnection); - bridgeConnectionClose(peerRawConnection, state.rawConnection); - try { - target[runAgentConnectHandlers](peerConnection); - this[runClientConnectHandlers](state.connection); - } catch (error) { - peerConnection.close(error); - state.connection.close(error); - throw error; - } - return state; - } - private openStreamConnection(stream: Stream): ClientConnectionState { - const rawConnection = this.builder.connect(stream); - return { - rawConnection, - connection: clientConnection(rawConnection, this.connectHandlers), - }; - } -} diff --git a/src/v2/stable/bindings.ts b/src/v2/stable/bindings.ts new file mode 100644 index 00000000..9fd308f6 --- /dev/null +++ b/src/v2/stable/bindings.ts @@ -0,0 +1,3145 @@ +// Generated from src/v2/bindings.ts. Do not edit directly. +import * as schema from "../schema/index.js"; +import * as validate from "../schema/zod.gen.js"; +import * as guards from "../schema/guards.gen.js"; +import type { Stream } from "./acp.js"; +import { + parseParams, + registerAppNotification, + registerAppRequest, +} from "../../core/app-handlers.js"; +import type { ParamsParser } from "../../core/app-handlers.js"; +import { + Connection, + Handled, + HandlerRegistration, + isRecord, + isV2RequestId, + RequestError, + respondWithNullId, + treatSessionNotFoundAsSuccess, +} from "../../core/jsonrpc.js"; +import { connectionContextOf } from "../../core/connection-access.js"; +import type { + AnyMessage, + ConnectionBuilder, + ConnectionContext, + HandleResult, + IncomingMessage, + JsonRpcId, + JsonRpcHandler, + MaybePromise, + SendRequestOptions, +} from "../../core/jsonrpc.js"; +/** + * ACP v2 extension method name. + * + * New custom methods should begin with `_` so they cannot collide with present + * or future protocol methods. + * + * @experimental + */ +export type ExtensionMethod = `_${string}`; +/** + * A method name that is not part of the current ACP v2 draft. + * + * This compatibility type permits methods from older or newer unstable ACP + * revisions while preventing current built-in method literals from falling + * through the untyped overloads. Prefer {@link ExtensionMethod} for new custom + * methods. + * + * @experimental + */ +export type UnrecognizedMethod = string extends Method + ? Method + : Method extends + | AgentRequestMethod + | AgentNotificationMethod + | ClientRequestMethod + | ClientNotificationMethod + | typeof schema.PROTOCOL_METHODS.cancel_request + ? never + : Method; +function emptyObjectResponse(response: T | null | undefined | void): T { + return response ?? ({} as T); +} +const knownProtocolMethods = new Set([ + ...Object.values(schema.AGENT_METHODS), + ...Object.values(schema.CLIENT_METHODS), + ...Object.values(schema.PROTOCOL_METHODS), +]); +function assertV2MethodDirection( + method: string, + builtIns: Record, + kind: "request" | "notification", + allowProtocolNotification = false, +): void { + if ( + Object.hasOwn(builtIns, method) || + (allowProtocolNotification && + method === schema.PROTOCOL_METHODS.cancel_request) + ) { + return; + } + if (knownProtocolMethods.has(method)) { + throw new TypeError( + `ACP v2 ${kind} method '${method}' is not valid in this direction`, + ); + } +} +function assertUnrecognizedV2Method( + method: string, + kind: "request" | "notification", +): void { + if (knownProtocolMethods.has(method)) { + throw new TypeError( + `Cannot replace the built-in ACP v2 ${kind} parser for '${method}'`, + ); + } +} +/** + * Client info substituted when an `initialize` request written for a newer + * protocol version has a missing or malformed `info`. + */ +const UNKNOWN_IMPLEMENTATION: schema.Implementation = { + name: "unknown", + version: "unknown", +}; +function readInitializeProtocolVersion( + params: unknown, +): schema.ProtocolVersion { + return received(validate.zProtocolVersion).parse( + isPlainObject(params) ? params["protocolVersion"] : undefined, + ); +} +function parseV2InitializeRequest(params: unknown): schema.InitializeRequest { + const protocolVersion = readInitializeProtocolVersion(params); + if (protocolVersion < schema.PROTOCOL_VERSION) { + throw RequestError.unsupportedProtocolVersion(protocolVersion, [ + schema.PROTOCOL_VERSION, + ]); + } + // A request for a newer version was written for a schema this endpoint does + // not know, so keep whatever parses under v2 instead of rejecting it. + // Capabilities and `_meta` already drop malformed values field by field; + // only the required `info` needs a substitute. + const lenient = + protocolVersion > schema.PROTOCOL_VERSION && isPlainObject(params); + const request = received( + validate.zInitializeRequest, + ).parse( + lenient && !validate.zImplementation.safeParse(params["info"]).success + ? { ...params, info: UNKNOWN_IMPLEMENTATION } + : params, + ); + return structuredClone({ + ...request, + protocolVersion: schema.PROTOCOL_VERSION, + }); +} +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function normalizeOutgoingV2InitializeRequest(params: unknown): { + wire: schema.InitializeRequest; + parsed: schema.InitializeRequest; +} { + const request = + typeof params === "object" && params !== null && !Array.isArray(params) + ? (params as Record) + : {}; + const outgoing = { + ...request, + protocolVersion: schema.PROTOCOL_VERSION, + }; + // Parsing supplies a validated local view, not the payload to transmit. + // In particular, Zod strips future capability fields from that view. + const parsed = parseV2InitializeRequest(outgoing); + return { + wire: structuredClone(outgoing) as schema.InitializeRequest, + parsed, + }; +} +function mapV2InitializeResponse(response: unknown): schema.InitializeResponse { + const parsed = received( + validate.zInitializeResponse, + ).parse(response); + if (parsed.protocolVersion !== schema.PROTOCOL_VERSION) { + throw RequestError.invalidRequest( + { + expectedProtocolVersion: schema.PROTOCOL_VERSION, + receivedProtocolVersion: parsed.protocolVersion, + }, + `The v2 API only supports protocol version ${schema.PROTOCOL_VERSION}`, + ); + } + return structuredClone(parsed); +} +function serializeV2InitializeResponse( + response: schema.InitializeResponse, +): schema.InitializeResponse { + // Keep validation separate from serialization, as for outgoing requests. + mapV2InitializeResponse(response); + return structuredClone(response); +} +/** + * Validated initialize request and response for one ACP v2 connection. + * + * The snapshot becomes available only after the initialize response has been + * validated and sent or received successfully. When the Client repeats + * `initialize`, the latest successful exchange replaces the snapshot. + * + * @experimental + */ +export type InitializationSnapshot = Readonly<{ + request: schema.InitializeRequest; + response: schema.InitializeResponse; +}>; +type InitializationPhase = + "uninitialized" | "initializing" | "initialized" | "failed"; +function cloneInitialization( + initialization: InitializationSnapshot, +): InitializationSnapshot { + return structuredClone(initialization); +} +function deferred(): { + promise: Promise; + resolve(value: T | PromiseLike): void; + reject(reason?: unknown): void; +} { + let resolve!: (value: T | PromiseLike) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise; + reject = rejectPromise; + }); + return { promise, resolve, reject }; +} +/** + * Initialization lifecycle of one ACP v2 connection side. + * + * The Client may repeat `initialize` after a previous one completed, as long + * as it has not sent any other request. A repeat that fails leaves the + * previous initialization in effect. A first `initialize` that fails leaves + * the connection uninitialized, so the Client may send `initialize` again. + */ +class InitializationState { + private phase: InitializationPhase = "uninitialized"; + private request?: schema.InitializeRequest; + private snapshot?: InitializationSnapshot; + private otherRequestSeen = false; + private attempt = deferred(); + private readonly barrier = deferred(); + constructor() { + void this.barrier.promise.catch(() => {}); + this.attempt.resolve(); + } + get status(): InitializationPhase { + return this.phase; + } + get initialized(): Promise { + return this.barrier.promise + .then(() => this.attempt.promise) + .then(() => cloneInitialization(this.snapshot!)); + } + /** + * Returns why `initialize` cannot start now, or `undefined` if it can. + */ + beginError(): RequestError | undefined { + if (this.phase === "initializing") { + return RequestError.invalidRequest( + "ACP v2 initialize is already in progress", + ); + } + if (this.phase === "failed") { + return RequestError.invalidRequest( + "ACP v2 connection initialization failed", + ); + } + if (this.phase === "initialized" && this.otherRequestSeen) { + return RequestError.invalidRequest( + "ACP v2 initialize must not be repeated after other requests", + ); + } + return undefined; + } + begin(request: schema.InitializeRequest): void { + const error = this.beginError(); + if (error) { + throw error; + } + const requestSnapshot = structuredClone(request); + this.request = requestSnapshot; + this.phase = "initializing"; + this.attempt = deferred(); + } + complete(response: schema.InitializeResponse): void { + if (this.phase !== "initializing" || !this.request) { + throw RequestError.invalidRequest( + "ACP v2 initialization is not in progress", + ); + } + const initialization = { + request: structuredClone(this.request), + response: structuredClone(response), + }; + this.snapshot = initialization; + this.request = undefined; + this.phase = "initialized"; + this.barrier.resolve(initialization); + this.attempt.resolve(); + } + /** + * Whether an `initialize` exchange has completed, including while a repeat + * is in progress. + */ + get hasInitialized(): boolean { + return this.snapshot !== undefined && this.phase !== "failed"; + } + /** + * Fails the initialize attempt in progress. A failed repeat keeps the + * previous initialization; a failed first attempt leaves the connection + * uninitialized so `initialize` can be sent again. + */ + failAttempt(): void { + if (this.phase !== "initializing") { + return; + } + this.phase = this.snapshot ? "initialized" : "uninitialized"; + this.request = undefined; + this.attempt.resolve(); + } + /** + * Fails initialization for good, such as when the connection closes before + * it was initialized. A failed repeat keeps the previous initialization. + */ + fail(error?: unknown): void { + if (this.phase === "initializing" && this.snapshot) { + this.failAttempt(); + return; + } + if (this.phase === "uninitialized" || this.phase === "initializing") { + this.phase = "failed"; + this.request = undefined; + this.barrier.reject( + error ?? + RequestError.invalidRequest( + "ACP v2 connection initialization failed", + ), + ); + this.attempt.resolve(); + } + } + /** + * Records a request other than `initialize`, after which `initialize` may + * no longer be repeated. + */ + noteRequest(): void { + if (this.phase === "initializing" || this.phase === "initialized") { + this.otherRequestSeen = true; + } + } + waitUntilInitialized(method: string): Promise { + if (this.phase === "initialized") { + return Promise.resolve(); + } + if (this.phase === "initializing") { + // Settles with the attempt: a failed first attempt rejects, since the + // connection is uninitialized again. + return this.attempt.promise.then(() => this.waitUntilInitialized(method)); + } + if (this.phase === "failed") { + return this.barrier.promise.then(() => {}); + } + return Promise.reject(initializationUnavailable(method)); + } +} +const initializationStates = new WeakMap< + ConnectionContext, + InitializationState +>(); +function initializationState(cx: ConnectionContext): InitializationState { + let state = initializationStates.get(cx); + if (!state) { + state = new InitializationState(); + initializationStates.set(cx, state); + if (cx.signal.aborted) { + state.fail(cx.signal.reason); + } else { + cx.signal.addEventListener("abort", () => state?.fail(cx.signal.reason), { + once: true, + }); + } + } + return state; +} +function initializationUnavailable(method: string): RequestError { + return RequestError.invalidRequest( + `ACP v2 connection must be initialized before '${method}'`, + ); +} +/** + * Rejects a request received before initialization with `-32600` and ignores + * a notification. Neither changes the initialization state, so the peer can + * still initialize the connection. + */ +async function blockUninitializedIncoming( + message: IncomingMessage, +): Promise { + return rejectIncoming(message, initializationUnavailable(message.method)); +} +async function rejectIncoming( + message: IncomingMessage, + error: RequestError, +): Promise { + if (message.kind === "request") { + await message.responder.respondWithError(error); + } + return Handled.yes(); +} +/** + * Rejects requests whose ID is `null` or a non-integer number, which ACP v2 + * does not allow. The error response uses `id: null` because the request ID + * is unusable. + */ +async function rejectInvalidRequestId( + message: IncomingMessage, +): Promise { + if (message.kind !== "request" || isV2RequestId(message.raw.id)) { + return undefined; + } + await respondWithNullId( + message.responder, + RequestError.invalidRequest( + undefined, + "ACP v2 request IDs must be strings or integers", + ), + ); + return Handled.yes(); +} +async function waitUntilInitializedIncoming( + message: IncomingMessage, + state: InitializationState, +): Promise { + if (state.status === "initialized") { + return Handled.no(message); + } + if (state.status === "initializing") { + try { + await state.waitUntilInitialized(message.method); + } catch { + return blockUninitializedIncoming(message); + } + return Handled.no(message); + } + return blockUninitializedIncoming(message); +} +/** + * Answers `tool_call/cancel` and `terminal/cancel` with `-32602` when the app + * has no handler for them. Neither method has an initialize-time capability: + * an Agent that never advertises `capabilities.cancel` on a tool call or + * terminal has nothing to cancel, and the spec answers a request for an + * unknown or non-cancellable entity with `-32602`, not `-32601`. + */ +function defaultEntityCancelHandler( + handles: (method: string) => boolean, +): JsonRpcHandler { + const entities: Record< + string, + { + key: string; + label: string; + } + > = { + [schema.AGENT_METHODS.tool_call_cancel]: { + key: "toolCallId", + label: "tool call", + }, + [schema.AGENT_METHODS.terminal_cancel]: { + key: "terminalId", + label: "terminal", + }, + }; + return { + async handleMessage(message) { + const entity = Object.hasOwn(entities, message.method) + ? entities[message.method] + : undefined; + if (message.kind !== "request" || !entity || handles(message.method)) { + return Handled.no(message); + } + const id = isRecord(message.params) + ? message.params[entity.key] + : undefined; + return rejectIncoming( + message, + RequestError.invalidParams( + typeof id === "string" ? { [entity.key]: id } : undefined, + `the ${entity.label} is unknown or not cancellable`, + ), + ); + }, + describe: () => "default-entity-cancel", + }; +} +function agentInitializationGuard(): JsonRpcHandler { + return { + async handleMessage(message, cx) { + const invalidId = await rejectInvalidRequestId(message); + if (invalidId) { + return invalidId; + } + const state = initializationState(cx); + if (message.kind === "notification") { + // The connection already applied `$/cancel_request`. Agents ignore + // other notifications that arrive before initialization completes. + if ( + message.method === schema.PROTOCOL_METHODS.cancel_request || + !state.hasInitialized + ) { + return Handled.yes(); + } + return waitUntilInitializedIncoming(message, state); + } + if (message.method === schema.AGENT_METHODS.initialize) { + // The Client may repeat initialize after the previous one completed + // and before any other request. A repeat that fails leaves the + // previous initialization in effect. + const beginError = state.beginError(); + if (beginError) { + return rejectIncoming(message, beginError); + } + // A malformed initialize throws before `begin`, so it leaves the + // connection as it was: uninitialized, or with the previous + // initialization in effect. + if ( + state.status === "initialized" && + readInitializeProtocolVersion(message.params) < + schema.PROTOCOL_VERSION + ) { + // A repeat must use the version the previous response selected. + return rejectIncoming( + message, + RequestError.invalidRequest( + undefined, + `a repeated initialize must request protocol version ${schema.PROTOCOL_VERSION} or later`, + ), + ); + } + state.begin(parseV2InitializeRequest(message.params)); + return Handled.no(message); + } + // Requests other than initialize must not wait for an in-flight + // initialize: the spec requires rejecting them until it completes. + if (state.status === "initialized") { + state.noteRequest(); + return Handled.no(message); + } + return blockUninitializedIncoming(message); + }, + describe: () => "agent-initialization", + }; +} +function clientInitializationGuard(): JsonRpcHandler { + return { + async handleMessage(message, cx) { + const invalidId = await rejectInvalidRequestId(message); + if (invalidId) { + return invalidId; + } + const state = initializationState(cx); + if ( + message.kind === "notification" && + message.method === schema.PROTOCOL_METHODS.cancel_request + ) { + // The connection already applied it. + return Handled.yes(); + } + return waitUntilInitializedIncoming(message, state); + }, + describe: () => "client-initialization", + }; +} +function parseRequestResponse( + spec: { + response?: ParamsParser; + }, + response: unknown, +): unknown { + return parseParams(spec.response, response); +} +function isStream(value: unknown): value is Stream { + return ( + typeof value === "object" && + value !== null && + "readable" in value && + "writable" in value + ); +} +function memoryStreamPair(): [Stream, Stream] { + const leftToRight = new TransformStream(); + const rightToLeft = new TransformStream(); + return [ + { + readable: rightToLeft.readable, + writable: leftToRight.writable, + }, + { + readable: leftToRight.readable, + writable: rightToLeft.writable, + }, + ]; +} +type McpTransportCapability = Exclude; +// Transport keys of `session.mcp`: `stdio` and `http`, plus `acp` with the +// unstable schema. Read from the schema so each entrypoint checks only the +// transports its own `McpCapabilities` type can advertise. +const MCP_TRANSPORT_CAPABILITIES: ReadonlyArray = Object.keys( + validate.zMcpCapabilities.shape, +).filter((key) => key !== "_meta"); +/** + * Throws `-32602` (Invalid params) for the first MCP server the agent cannot + * accept: one whose `name` repeats an earlier server's, or whose transport the + * agent did not advertise in `session.mcp`. + * + * Call it from `session/new`, `session/resume`, or `session/fork` handlers with + * the `capabilities.session.mcp` value the agent sent in its `initialize` + * response. Each server `name` must be unique within the list; a duplicate is + * rejected with error data `{ name }`. A server is accepted only when its + * `type` is a transport key in that object with a non-null value, for example + * `stdio` with `{ stdio: {} }`. Everything else is rejected, including v1's + * `sse`, unknown types, and custom `_`-prefixed types; agents that support a + * custom transport should handle those servers before calling this. The error + * data for a transport is `{ type }` with the rejected server's transport. + * + * @experimental + */ +export function assertSupportedMcpServers( + mcpServers: ReadonlyArray | null | undefined, + capabilities: schema.McpCapabilities | null | undefined, +): void { + const names = new Set(); + for (const server of mcpServers ?? []) { + const { name, type } = server; + if (typeof name === "string") { + if (names.has(name)) { + throw RequestError.invalidParams( + { name }, + `Duplicate MCP server name ${name}`, + ); + } + names.add(name); + } + if ( + !MCP_TRANSPORT_CAPABILITIES.includes(type) || + capabilities?.[type as McpTransportCapability] == null + ) { + throw RequestError.invalidParams( + { type }, + `Unsupported MCP server transport ${type}`, + ); + } + } +} +const startActiveSession = Symbol("startActiveSession"); +const routeActiveSessionUpdate = Symbol("routeActiveSessionUpdate"); +/** + * Experimental draft ACP v2 connection returned by `AgentApp.connect(...)` and + * `ClientApp.connect(...)`. + * + * Use this handle when you need a connection to stay open independently of a + * single `connectWith(...)` operation. + * + * @experimental + */ +export interface AcpConnection { + /** + * Resolves with the validated initialize exchange once initialization + * succeeds, or rejects if initialization or the connection fails. + * + * After a repeated `initialize` completes, reading this again resolves with + * the latest exchange. + */ + readonly initialized: Promise; + /** + * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. + */ + readonly signal: AbortSignal; + /** + * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. + */ + readonly closed: Promise; + /** + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. + */ + close(error?: unknown): void; +} +/** + * Experimental draft ACP v2 agent-side connection returned by + * `AgentApp.connect(...)`. + * + * Use `client` to call client-side ACP methods for the lifetime of the + * connection. + * + * @experimental + */ +export interface AgentConnection extends AcpConnection { + /** + * Context for calling client-side ACP methods. + */ + readonly client: AgentContext; +} +/** + * Experimental draft ACP v2 client-side connection returned by + * `ClientApp.connect(...)`. + * + * Use `agent` to call agent-side ACP methods and session helpers for the + * lifetime of the connection. + * + * @experimental + */ +export interface ClientConnection extends AcpConnection { + /** + * Context for calling agent-side ACP methods. + */ + readonly agent: ClientContext; +} +class AcpContext { + /** @internal */ + constructor( + private readonly cx: ConnectionContext, + private readonly currentRequestId?: JsonRpcId, + ) {} + /** + * Validated initialize exchange, once this connection is initialized. + */ + get initialized(): Promise { + return initializationState(this.cx).initialized; + } + /** @internal */ + protected get initializationLifecycle(): InitializationState { + return initializationState(this.cx); + } + /** + * JSON-RPC id of the request currently being handled. + * + * This is `undefined` for notification handlers and for contexts created + * outside an inbound request, such as `connect(...)` and `connectWith(...)`. + */ + get requestId(): JsonRpcId | undefined { + return this.currentRequestId; + } + /** @internal */ + protected get connectionContext(): ConnectionContext { + return this.cx; + } + /** @hidden SDK helpers use this to identify the connection. */ + [connectionContextOf](): ConnectionContext { + return this.cx; + } + /** @internal */ + protected sendRequest( + method: string, + params?: Req, + mapResponse?: (response: Resp) => Output, + options?: SendRequestOptions, + ): Promise { + return this.cx.sendRequest(method, params, mapResponse, options); + } + /** @internal */ + protected sendNotification(method: string, params?: N): Promise { + return this.cx.sendNotification(method, params); + } + /** @internal */ + protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration { + return this.cx.addDynamicHandler(handler); + } +} +/** + * Experimental draft ACP v2 context passed to agent-side handlers. + * + * Agents use this context to call client-side ACP methods while handling + * requests such as `session/prompt`. + * + * @experimental + */ +export class AgentContext extends AcpContext { + private constructor(cx: ConnectionContext, requestId?: JsonRpcId) { + super(cx, requestId); + } + /** @internal */ + static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext { + return new AgentContext(cx, requestId); + } + /** + * Sends a request to the client by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + */ + request( + method: Method, + params: ClientRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: ExtensionMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request< + Response = unknown, + Params = unknown, + const Method extends string = never, + >( + method: UnrecognizedMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + assertV2MethodDirection(method, clientRequestSpecsByMethod, "request"); + const spec = clientRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + return this.initializationLifecycle + .waitUntilInitialized(method) + .then(() => + this.sendRequest( + method, + params, + spec ? (response) => parseRequestResponse(spec, response) : undefined, + options, + ), + ); + } + /** + * Sends a notification to the client by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: ClientNotificationParamsByMethod[Method], + ): Promise; + notify( + method: typeof schema.PROTOCOL_METHODS.cancel_request, + params: schema.CancelRequestNotification, + ): Promise; + notify( + method: ExtensionMethod, + params?: Params, + ): Promise; + notify( + method: UnrecognizedMethod, + params?: Params, + ): Promise; + notify(method: string, params?: unknown): Promise { + assertV2MethodDirection( + method, + clientNotificationSpecsByMethod, + "notification", + true, + ); + return this.initializationLifecycle + .waitUntilInitialized(method) + .then(() => this.sendNotification(method, params)); + } +} +/** + * Experimental draft ACP v2 context used by clients to call agent-side ACP + * methods. + * + * `connectWith` passes a `ClientContext` to the callback. Client handlers also + * receive one as `ctx.agent` when they need to call back into the agent. + * + * @experimental + */ +export class ClientContext extends AcpContext { + private constructor( + cx: ConnectionContext, + requestId?: JsonRpcId, + private readonly closeOnInitializationFailure?: (error: unknown) => void, + ) { + super(cx, requestId); + } + /** @internal */ + static create( + cx: ConnectionContext, + requestId?: JsonRpcId, + closeOnInitializationFailure?: (error: unknown) => void, + ): ClientContext { + return new ClientContext(cx, requestId, closeOnInitializationFailure); + } + /** @internal */ + [startActiveSession]( + params: schema.NewSessionRequest, + options?: SendRequestOptions, + ): Promise { + return this.request(schema.AGENT_METHODS.session_new, params, options).then( + (response) => this.attachSession(response), + ); + } + /** + * Creates a builder for starting and observing an ACP session. + * + * Pass an absolute path for the common case where only `cwd` is needed, or + * pass a full `NewSessionRequest` when you need MCP servers, `_meta`, or + * additional session fields. + */ + buildSession(cwd: schema.AbsolutePath): SessionBuilder; + buildSession(request: schema.NewSessionRequest): SessionBuilder; + buildSession( + cwdOrRequest: schema.AbsolutePath | schema.NewSessionRequest, + ): SessionBuilder { + if (typeof cwdOrRequest === "string") { + return SessionBuilder.create(this, { + cwd: cwdOrRequest, + mcpServers: [], + }); + } + return SessionBuilder.create(this, cwdOrRequest); + } + /** + * Builds active-session helpers around a `session/new` response. + */ + private attachSession(response: schema.NewSessionResponse): ActiveSession { + const updates = new AsyncQueue(); + const closeSignal = this.connectionContext.signal; + const failUpdatesOnClose = () => { + updates.fail(closeSignal.reason ?? new Error("ACP connection closed")); + }; + if (closeSignal.aborted) { + failUpdatesOnClose(); + } else { + closeSignal.addEventListener("abort", failUpdatesOnClose); + } + const registrations: HandlerRegistration[] = []; + const session = ActiveSession.create( + this, + response, + updates, + registrations, + ); + registrations.push( + sessionUpdateRouter(this.connectionContext).attach(response, { + enqueue: (message) => session[routeActiveSessionUpdate](message), + }), + new HandlerRegistration(() => { + closeSignal.removeEventListener("abort", failUpdatesOnClose); + }), + ); + return session; + } + /** + * Sends a request to the agent by ACP method name. + * + * Built-in method literals infer their params and response types. Custom + * methods can specify their response and params types with generics. + * + * Other requests wait until `initialize` has completed. `initialize` may be + * repeated once the previous one completed and before any other request has + * been sent; otherwise it throws `-32600` synchronously. A repeat that fails + * leaves the previous initialization in effect, and a first `initialize` + * that gets an error response leaves the connection uninitialized, so it can + * be sent again. + * + * Closing or deleting a session is idempotent: a `-32002` (Resource not + * found) response to `session/close` or `session/delete` resolves with an + * empty result instead of rejecting. + */ + request( + method: Method, + params: AgentRequestParamsByMethod[Method], + options?: SendRequestOptions, + ): Promise; + request( + method: ExtensionMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request< + Response = unknown, + Params = unknown, + const Method extends string = never, + >( + method: UnrecognizedMethod, + params?: Params, + options?: SendRequestOptions, + ): Promise; + request( + method: string, + params?: unknown, + options?: SendRequestOptions, + ): Promise { + assertV2MethodDirection(method, agentRequestSpecsByMethod, "request"); + const spec = agentRequestSpecsByMethod[method] as + AcpRequestSpec | undefined; + const state = this.initializationLifecycle; + if (method === schema.AGENT_METHODS.initialize) { + const { wire: request, parsed } = + normalizeOutgoingV2InitializeRequest(params); + state.begin(parsed); + let response: Promise; + // Set when the agent answered with a response this client cannot use, + // as opposed to an error response. + let unusableResponse = false; + try { + response = this.sendRequest( + method, + request, + (value) => { + try { + const parsed = parseRequestResponse(spec!, value); + state.complete(parsed as schema.InitializeResponse); + return parsed; + } catch (error) { + unusableResponse = true; + throw error; + } + }, + options, + ); + } catch (error) { + this.failInitialization(error); + throw error; + } + void response.catch((error) => { + if (state.status === "initializing") { + if (unusableResponse) { + this.failInitialization(error); + } else { + // An error response leaves the connection as it was, so the + // client may send initialize again. + state.failAttempt(); + } + } + }); + return response; + } + state.noteRequest(); + const mapResponse = spec + ? (response: unknown) => parseRequestResponse(spec, response) + : undefined; + return state + .waitUntilInitialized(method) + .then(() => + treatSessionNotFoundAsSuccess( + method, + this.sendRequest(method, params, mapResponse, options), + () => (mapResponse ? mapResponse({}) : {}), + ), + ); + } + /** + * Fails an initialize attempt. Closes the connection unless a previous + * initialization remains in effect. + */ + private failInitialization(error: unknown): void { + const state = this.initializationLifecycle; + state.fail(error); + if (state.status === "failed") { + this.closeOnInitializationFailure?.(error); + } + } + /** + * Sends a notification to the agent by ACP method name. + * + * Built-in method literals infer their params type. Custom notifications can + * specify their params type with a generic. + */ + notify( + method: Method, + params: AgentNotificationParamsByMethod[Method], + ): Promise; + notify( + method: typeof schema.PROTOCOL_METHODS.cancel_request, + params: schema.CancelRequestNotification, + ): Promise; + notify( + method: ExtensionMethod, + params?: Params, + ): Promise; + notify( + method: UnrecognizedMethod, + params?: Params, + ): Promise; + notify(method: string, params?: unknown): Promise { + assertV2MethodDirection( + method, + agentNotificationSpecsByMethod, + "notification", + true, + ); + return this.initializationLifecycle + .waitUntilInitialized(method) + .then(() => this.sendNotification(method, params)); + } +} +class AcpConnectionHandle implements AcpConnection { + constructor(private readonly connection: Connection) {} + get initialized(): Promise { + return initializationState(this.connection.getContext()).initialized; + } + get signal(): AbortSignal { + return this.connection.signal; + } + get closed(): Promise { + return this.connection.closed; + } + close(error?: unknown): void { + this.connection.close(error); + } +} +class AgentConnectionHandle + extends AcpConnectionHandle + implements AgentConnection +{ + readonly client: AgentContext; + private didStartConnectHandlers = false; + constructor( + connection: Connection, + private readonly connectHandlers: readonly AgentConnectHandler[] = [], + ) { + super(connection); + this.client = AgentContext.create(connection.getContext()); + } + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} +class ClientConnectionHandle + extends AcpConnectionHandle + implements ClientConnection +{ + readonly agent: ClientContext; + private didStartConnectHandlers = false; + constructor( + connection: Connection, + private readonly connectHandlers: readonly ClientConnectHandler[] = [], + ) { + super(connection); + this.agent = ClientContext.create( + connection.getContext(), + undefined, + (error) => connection.close(error), + ); + } + /** @internal */ + startConnectHandlers(): void { + if (this.didStartConnectHandlers) { + return; + } + this.didStartConnectHandlers = true; + runConnectHandlers(this, this.connectHandlers); + } +} +function agentConnection( + connection: Connection, + connectHandlers: readonly AgentConnectHandler[] = [], +): AgentConnection { + return new AgentConnectionHandle(connection, connectHandlers); +} +function clientConnection( + connection: Connection, + connectHandlers: readonly ClientConnectHandler[] = [], +): ClientConnection { + return new ClientConnectionHandle(connection, connectHandlers); +} +class AsyncQueue { + private values: Array = []; + private waiters: Array<{ + resolve: (value: T) => void; + reject: (error: unknown) => void; + }> = []; + private failed = false; + private failure: unknown; + enqueue(value: T): void { + if (this.failed) { + return; + } + const waiter = this.waiters.shift(); + if (waiter) { + waiter.resolve(value); + } else { + this.values.push(value); + } + } + fail(error: unknown): void { + if (this.failed) { + return; + } + this.failed = true; + this.failure = error; + for (const waiter of this.waiters.splice(0)) { + waiter.reject(error); + } + } + next(signal?: AbortSignal): Promise { + if (signal?.aborted) { + return Promise.reject(signal.reason); + } + if (this.values.length > 0) { + return Promise.resolve(this.values.shift() as T); + } + if (this.failed) { + return Promise.reject(this.failure); + } + return new Promise((resolve, reject) => { + const cleanup = (): void => { + signal?.removeEventListener("abort", onAbort); + }; + const waiter = { + resolve: (value: T): void => { + cleanup(); + resolve(value); + }, + reject: (error: unknown): void => { + cleanup(); + reject(error); + }, + }; + const onAbort = (): void => { + const index = this.waiters.indexOf(waiter); + if (index >= 0) { + this.waiters.splice(index, 1); + } + waiter.reject(signal?.reason); + }; + this.waiters.push(waiter); + signal?.addEventListener("abort", onAbort, { once: true }); + if (signal?.aborted) { + onAbort(); + } + }); + } +} +/** + * Applies a `capabilities` patch from a `tool_call_update` or + * `terminal_update`: omission leaves it unchanged, `null` clears it, and an + * object replaces it, so `cancel` is supported only when the latest object + * carries a non-null `cancel`. + */ +function applyCancelCapability( + cancellable: Set, + id: Id, + capabilities: + | { + cancel?: unknown; + } + | null + | undefined, +): void { + if (capabilities === undefined) { + return; + } + if (capabilities?.cancel != null) { + cancellable.add(id); + } else { + cancellable.delete(id); + } +} +function cloneNewSessionRequest( + request: schema.NewSessionRequest, +): schema.NewSessionRequest { + return structuredClone(request); +} +/** + * Experimental draft ACP v2 `session/set_config_option` params for + * `ActiveSession.setConfigOption(...)`; the session ID is filled in. + * + * @experimental + */ +export type ActiveSessionSetConfigOptionRequest = + schema.SetSessionConfigOptionRequest extends infer Request + ? Request extends unknown + ? { + [ + Key in keyof Request as Key extends "sessionId" ? never : Key + ]: Request[Key]; + } + : never + : never; +type ActiveSessionQueue = Pick< + AsyncQueue, + "enqueue" | "fail" | "next" +>; +/** + * Experimental draft ACP v2 message produced by an `ActiveSession`. + * + * `session_update` messages expose the typed `session/update` notification and + * `stop` messages report an idle `state_update`. Both are session-scoped: + * a `stop` message does not acknowledge processing or completion of any prompt. + * + * @experimental + */ +export type ActiveSessionMessage = + | { + /** + * Indicates that this message came from a `session/update` notification. + */ + kind: "session_update"; + /** + * Full notification sent by the agent. + */ + notification: schema.UpdateSessionNotification; + /** + * Convenience alias for `notification.update`. + */ + update: schema.SessionUpdate; + } + | { + /** + * Indicates an idle foreground snapshot, not necessarily a new completion. + */ + kind: "stop"; + /** + * Full notification containing the idle state update. + */ + notification: schema.UpdateSessionNotification; + /** + * Convenience alias for `notification.update`. + */ + update: schema.SessionUpdate; + /** + * Stop reason reported by the idle state, when provided. + */ + stopReason: schema.IdleStateUpdate["stopReason"]; + }; +/** + * Experimental draft ACP v2 builder for creating an `ActiveSession`. + * + * Start from `ctx.buildSession("/absolute/cwd")` for the common case, or + * pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session + * needs MCP servers, `_meta`, or additional request fields. All paths in ACP + * payloads should be absolute. + * + * @experimental + */ +export class SessionBuilder { + private request: schema.NewSessionRequest; + private constructor( + private cx: ClientContext, + request: schema.NewSessionRequest, + ) { + this.request = cloneNewSessionRequest(request); + } + /** @internal */ + static create( + cx: ClientContext, + request: schema.NewSessionRequest, + ): SessionBuilder { + return new SessionBuilder(cx, request); + } + /** + * Returns the `session/new` request that will be sent. + * + * The returned object is a defensive copy, so mutating it does not change the + * builder. + */ + toRequest(): schema.NewSessionRequest { + return cloneNewSessionRequest(this.request); + } + /** + * Replaces the additional workspace roots for this session. + * + * `additionalDirectories` expand the session's file-system scope without + * changing `cwd`. Each path should be absolute. + */ + withAdditionalDirectories( + additionalDirectories: schema.AbsolutePath[], + ): this { + this.request = { + ...this.request, + additionalDirectories: [...additionalDirectories], + }; + return this; + } + /** + * Adds one MCP server to the `session/new` request. + */ + withMcpServer(mcpServer: schema.McpServer): this { + this.request = { + ...this.request, + mcpServers: [ + ...(this.request.mcpServers ?? []), + structuredClone(mcpServer), + ], + }; + return this; + } + /** + * Starts the session and returns an `ActiveSession` for prompting and reading + * updates. + * + * Call `dispose()` on the returned session when you no longer need update + * routing, or use `withSession(...)` to scope disposal automatically. + */ + async start(options?: SendRequestOptions): Promise { + return this.cx[startActiveSession](this.toRequest(), options); + } + /** + * Starts the session, runs `op`, and disposes the active-session update + * routing when `op` finishes or throws. + */ + async withSession( + op: (session: ActiveSession) => MaybePromise, + ): Promise { + const session = await this.start(); + try { + return await op(session); + } finally { + session.dispose(); + } + } +} +/** + * Experimental draft ACP v2 convenience wrapper for an active session. + * + * An active session routes `session/update` notifications for one session ID + * into an async queue. Use `prompt(...)` to submit user content and + * `nextUpdate()` to observe the session independently of prompt requests. + * A `stop` message reports idle foreground work, not per-prompt completion. + * + * @experimental + */ +export class ActiveSession { + private currentConfigOptions: Array | undefined; + private latestBackground: Array | undefined; + private readonly cancellableToolCalls = new Set(); + private readonly cancellableTerminals = new Set(); + private constructor( + private cx: ClientContext, + private sessionResponse: schema.NewSessionResponse, + private updates: ActiveSessionQueue, + private registrations: HandlerRegistration[], + ) { + this.currentConfigOptions = sessionResponse.configOptions ?? undefined; + } + /** @internal */ + static create( + cx: ClientContext, + sessionResponse: schema.NewSessionResponse, + updates: ActiveSessionQueue, + registrations: HandlerRegistration[], + ): ActiveSession { + return new ActiveSession(cx, sessionResponse, updates, registrations); + } + /** + * Session ID returned by `session/new`. + */ + get sessionId(): schema.SessionId { + return this.sessionResponse.sessionId; + } + /** + * Current configuration options for this session, if the agent provided any. + * + * Starts with the `configOptions` from `session/new`. It is replaced with the + * full list from each `config_option_update` routed to this session (applied + * when the notification arrives, before it is read with `nextUpdate()`) and + * from each `setConfigOption(...)` response. Updates stop after `dispose()`. + * `newSessionResponse.configOptions` keeps the original `session/new` value. + */ + get configOptions(): Array | undefined { + return this.currentConfigOptions; + } + /** + * Metadata returned when the session was created. + */ + get meta(): + | { + [key: string]: unknown; + } + | null + | undefined { + return this.sessionResponse._meta; + } + /** + * The `background` list from the latest `state_update` routed to this + * session, or `undefined` while background work is not reported. + * + * Each `state_update` replaces it, applied when the notification arrives, + * before it is read with `nextUpdate()`. `[]` means no background work is + * running. A snapshot that omits the list, carries `null` or a malformed + * list, or reports a state this SDK does not know resets it to `undefined`: + * background work is unknown until a list arrives, and nothing should be + * treated as abandoned. Updates stop after `dispose()`. + */ + get background(): ReadonlyArray | undefined { + return this.latestBackground; + } + /** + * Whether `request`'s `subject` references work in the latest `background` + * list: a listed tool call (by the subject's `toolCall.toolCallId`, or a + * command subject's `toolCallId`) or a listed terminal (by a command + * subject's `terminalId`). + * + * `session/cancel` does not cover listed work, so permission requests for + * it stay open. For the cancelled foreground work, the Agent stops waiting + * on its permission requests and cancels them with `$/cancel_request`, and + * the Client answers each cancelled request with the `cancelled` outcome. + * A Client may also answer a request with `cancelled` right after sending + * `session/cancel`, without waiting for `$/cancel_request`, but only when + * it knows the request belongs to the cancelled work. A `false` result + * alone does not establish that: it is also returned for requests without + * a `subject`, custom subjects, and any request while `background` is not + * reported. On `session/close`, the Agent cancels every pending permission + * request in the session with `$/cancel_request`. When an Agent sends a + * permission request with `cancellationSignal` and + * `stopWaitingOnCancel: true`, aborting the signal sends + * `$/cancel_request` and stops waiting for the answer. + */ + isForBackgroundWork(request: schema.RequestPermissionRequest): boolean { + const background = this.latestBackground; + const subject = request.subject; + if (!background || !subject) { + return false; + } + let toolCallId: schema.ToolCallId | null | undefined; + let terminalId: schema.TerminalId | null | undefined; + if (guards.RequestPermissionSubject.isToolCall(subject)) { + toolCallId = subject.toolCall.toolCallId; + } else if (guards.RequestPermissionSubject.isCommand(subject)) { + toolCallId = subject.toolCallId; + terminalId = subject.terminalId; + } + return background.some( + (work) => + (toolCallId != null && + guards.BackgroundWork.isToolCall(work) && + work.toolCallId === toolCallId) || + (terminalId != null && + guards.BackgroundWork.isTerminal(work) && + work.terminalId === terminalId), + ); + } + /** + * Whether the tool call currently advertises `capabilities.cancel`, from + * the `tool_call_update` patches routed to this session. + */ + canCancelToolCall(toolCallId: schema.ToolCallId): boolean { + return this.cancellableToolCalls.has(toolCallId); + } + /** + * Whether the terminal currently advertises `capabilities.cancel`, from the + * `terminal_update` patches routed to this session. + */ + canCancelTerminal(terminalId: schema.TerminalId): boolean { + return this.cancellableTerminals.has(terminalId); + } + /** + * Cancels one tool call with `tool_call/cancel`. + * + * Rejects with a `TypeError`, without sending the request, unless the tool + * call currently advertises `capabilities.cancel` (see + * `canCancelToolCall`). The response means the Agent accepted the + * cancellation, not that the work stopped. The Agent confirms it with a + * `tool_call_update` to a final status. + * + * This only covers tool calls reported in this session. A subagent's tool + * call is reported in its child session, so send + * `methods.agent.toolCall.cancel` through `ClientContext.request` with the + * child's `sessionId`. The tool call's own `capabilities.cancel` enables + * that even when the child session doesn't advertise `cancel`. + * + * The Agent answers `-32602` once the tool call has a final status. This + * includes a request sent again after the first one was accepted. The + * `tool_call_update` with that status reports the outcome. + */ + cancelToolCall( + toolCallId: schema.ToolCallId, + options?: SendRequestOptions, + ): Promise { + if (!this.canCancelToolCall(toolCallId)) { + return Promise.reject( + new TypeError( + `Tool call ${JSON.stringify(toolCallId)} does not advertise cancel`, + ), + ); + } + return this.cx.request( + schema.AGENT_METHODS.tool_call_cancel, + { sessionId: this.sessionId, toolCallId }, + options, + ); + } + /** + * Stops a terminal's process with `terminal/cancel`. + * + * Rejects with a `TypeError`, without sending the request, unless the + * terminal currently advertises `capabilities.cancel` (see + * `canCancelTerminal`). The response means the Agent accepted the + * cancellation, not that the process stopped. The Agent confirms it with a + * `terminal_update` that sets `exitStatus`. The terminal is not released. + * + * This only covers terminals reported in this session. A subagent's + * terminal is reported in its child session, so send + * `methods.agent.terminal.cancel` through `ClientContext.request` with the + * child's `sessionId`. The terminal's own `capabilities.cancel` enables + * that even when the child session doesn't advertise `cancel`. + * + * The Agent answers `-32602` once the process has exited. This includes a + * request sent again after the first one was accepted. The + * `terminal_update` that sets `exitStatus` reports the outcome. + */ + cancelTerminal( + terminalId: schema.TerminalId, + options?: SendRequestOptions, + ): Promise { + if (!this.canCancelTerminal(terminalId)) { + return Promise.reject( + new TypeError( + `Terminal ${JSON.stringify(terminalId)} does not advertise cancel`, + ), + ); + } + return this.cx.request( + schema.AGENT_METHODS.terminal_cancel, + { sessionId: this.sessionId, terminalId }, + options, + ); + } + /** + * Full response returned by `session/new`. + */ + get newSessionResponse(): schema.NewSessionResponse { + return this.sessionResponse; + } + /** + * Sends a prompt to this session. + * + * Strings are converted to one text content block. A single content block is + * wrapped in an array. A prompt must contain at least one block. The returned + * promise resolves with the inserted user message's ID once the agent + * inserts it into the ACP conversation, not when processing finishes. + * + * A prompt may be sent while the agent is working. The agent inserts it + * right away or holds it and inserts it later, in the order received; the + * promise stays pending until then. Aborting `options.cancellationSignal` + * withdraws a held prompt, and `session/cancel` or `session/close` answer + * held prompts with `-32800`. `session/cancel` does not affect a prompt sent + * after it. + * + * Session updates remain independent of this request and have no fixed + * order relative to its response; an idle `state_update` does not establish + * that this message was processed. Rejection is reported only by this + * promise, not by the session update queue. + */ + prompt( + prompt: string | schema.ContentBlock | Array, + options?: SendRequestOptions, + ): Promise { + const blocks = this.promptBlocks(prompt); + if (blocks.length === 0) { + // Clients must not send an empty prompt. + return Promise.reject( + new TypeError("A prompt must contain at least one content block"), + ); + } + return this.cx.request( + schema.AGENT_METHODS.session_prompt, + { + sessionId: this.sessionId, + prompt: blocks, + }, + options, + ); + } + /** + * Sets a configuration option for this session with + * `session/set_config_option`. + * + * The response carries the agent's complete `configOptions` list, which + * replaces `configOptions` on this session. For example, + * `session.setConfigOption({ configId: "model", type: "id", value: "fast" })`. + */ + async setConfigOption( + request: ActiveSessionSetConfigOptionRequest, + options?: SendRequestOptions, + ): Promise { + const response = await this.cx.request( + schema.AGENT_METHODS.session_set_config_option, + { ...request, sessionId: this.sessionId }, + options, + ); + this.currentConfigOptions = response.configOptions; + return response; + } + /** + * Reads the next update or stop message for this session. + * + * Idle updates are always returned as `stop` messages, whether or not a prompt + * is pending. Queued updates are consumed in arrival order. An abort signal + * cancels this read without cancelling session work or discarding updates. + */ + nextUpdate(signal?: AbortSignal): Promise { + return this.updates.next(signal); + } + /** + * Collects agent text from the session queue until the next idle update. + * + * This consumes the same queue as `nextUpdate()`, including already queued + * updates. It does not associate output or idle with any submitted prompt, + * skip updates when a prompt is sent, or wait for a prompt to be inserted. + * Use one reader at a time to avoid splitting the session's updates. + * An abort signal cancels the read without cancelling session work. + * + * Full `agent_message` updates replace content for their `messageId`, while + * `agent_message_chunk` updates append to it. Non-text content and other + * update types are ignored; use `nextUpdate()` when you need them. + */ + async readTextUntilIdle(signal?: AbortSignal): Promise { + const messageOrder: schema.MessageId[] = []; + const messageContent = new Map< + schema.MessageId, + Array + >(); + const ensureMessage = ( + messageId: schema.MessageId, + ): Array => { + let content = messageContent.get(messageId); + if (!content) { + content = []; + messageOrder.push(messageId); + messageContent.set(messageId, content); + } + return content; + }; + for (;;) { + const message = await this.nextUpdate(signal); + if (message.kind === "stop") { + return messageOrder + .flatMap((messageId) => messageContent.get(messageId) ?? []) + .filter(guards.ContentBlock.isText) + .map((content) => content.text) + .join(""); + } + const { update } = message; + if (guards.SessionUpdate.isAgentMessage(update)) { + ensureMessage(update.messageId); + if (update.content !== undefined) { + messageContent.set(update.messageId, update.content ?? []); + } + } else if (guards.SessionUpdate.isAgentMessageChunk(update)) { + ensureMessage(update.messageId).push(update.content); + } + } + } + /** @internal */ + [routeActiveSessionUpdate](message: ActiveSessionMessage): void { + const { update } = message; + if (guards.SessionUpdate.isConfigOptionUpdate(update)) { + this.currentConfigOptions = update.configOptions; + } else if (guards.SessionUpdate.isStateUpdate(update)) { + this.latestBackground = + !guards.StateUpdate.isCustom(update) && Array.isArray(update.background) + ? update.background + : undefined; + } else if (guards.SessionUpdate.isToolCallUpdate(update)) { + applyCancelCapability( + this.cancellableToolCalls, + update.toolCallId, + update.capabilities, + ); + } else if (guards.SessionUpdate.isTerminalUpdate(update)) { + applyCancelCapability( + this.cancellableTerminals, + update.terminalId, + update.capabilities, + ); + } + this.updates.enqueue(message); + } + /** + * Stops routing updates to this active-session helper. + * + * This does not close the ACP session on the agent. Use `ClientContext` + * session lifecycle methods when the protocol session itself should be closed + * or deleted. + */ + dispose(): void { + for (const registration of this.registrations.splice(0)) { + registration.dispose(); + } + this.updates.fail(new Error("Active session disposed")); + } + /** + * Supports explicit resource management with `using`. + */ + [Symbol.dispose](): void { + this.dispose(); + } + private promptBlocks( + prompt: string | schema.ContentBlock | Array, + ): Array { + if (typeof prompt === "string") { + return [{ type: "text", text: prompt }]; + } + if (Array.isArray(prompt)) { + return prompt; + } + return [prompt]; + } +} +/** + * Options used when creating an ACP app. + */ +export type AppOptions = { + /** + * Human-readable name used in JSON-RPC handler descriptions and diagnostics. + */ + name?: string; +}; +/** + * Common context passed to agent-side handlers. + */ +export type AgentHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed client context for calling client-side ACP methods. + */ + client: AgentContext; +}; +/** + * Context passed to agent-side request handlers. + */ +export type AgentRequestContext = AgentHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; +/** + * Context passed to agent-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type AgentNotificationContext = AgentHandlerContext; +/** + * Common context passed to client-side handlers. + */ +export type ClientHandlerContext = { + /** The method being handled, including the actual name in fallback handlers. */ + method: string; + /** + * Parsed request or notification params. + */ + params: Params; + /** + * AbortSignal for the current request, or the connection signal for + * notifications. + */ + signal: AbortSignal; + /** + * Typed agent context for calling agent-side ACP methods. + */ + agent: ClientContext; +}; +/** + * Context passed to client-side request handlers. + */ +export type ClientRequestContext = ClientHandlerContext & { + /** + * JSON-RPC id of the request currently being handled. + */ + requestId: JsonRpcId; +}; +/** + * Context passed to client-side notification handlers. + * + * Notifications do not have JSON-RPC request ids. + */ +export type ClientNotificationContext = ClientHandlerContext; +/** + * Request handler registered on an `AgentApp`. + */ +export type AgentRequestHandler = ( + context: AgentRequestContext, +) => MaybePromise; +/** + * Notification handler registered on an `AgentApp`. + */ +export type AgentNotificationHandler = ( + context: AgentNotificationContext, +) => MaybePromise; +/** + * Request handler registered on a `ClientApp`. + */ +export type ClientRequestHandler = ( + context: ClientRequestContext, +) => MaybePromise; +/** + * Notification handler registered on a `ClientApp`. + */ +export type ClientNotificationHandler = ( + context: ClientNotificationContext, +) => MaybePromise; +/** + * Handler called when an `AgentApp` opens a connection. + */ +export type AgentConnectHandler = ( + connection: AgentConnection, +) => MaybePromise; +/** + * Handler called when a `ClientApp` opens a connection. + */ +export type ClientConnectHandler = ( + connection: ClientConnection, +) => MaybePromise; +type AcpRequestSpec = { + method: string; + params?: ParamsParser; + response?: ParamsParser; + serializeResponse?: (response: HandlerResponse) => Response; +}; +type AcpNotificationSpec = { + method: string; + params?: ParamsParser; +}; +/** + * A generated validator as the parser of received values. + * + * The validators type the tag of an unknown variant as a plain string, while + * the protocol types brand it as an `UnknownVariant`, which only received + * values have. Everything a validator parses is received, so its output has + * the protocol type. + */ +function received(validator: { parse(value: unknown): unknown }): { + parse(value: unknown): T; +} { + return validator as { + parse(value: unknown): T; + }; +} +function requestSpec( + method: string, + params: ParamsParser, + response: ParamsParser, + serializeResponse?: (response: HandlerResponse) => Response, +): AcpRequestSpec { + return { + method, + // Match Rust's empty-payload handling without bypassing required fields. + params: (value) => parseParams(params, value ?? {}), + response, + serializeResponse, + }; +} +function notificationSpec( + method: string, + params: ParamsParser, +): AcpNotificationSpec { + return { method, params }; +} +function specsByMethod< + T extends Record< + string, + { + method: string; + } + >, +>(specs: T): Record { + const byMethod = Object.create(null) as Record; + for (const spec of Object.values(specs) as Array) { + byMethod[spec.method] = spec; + } + return byMethod; +} +const agentRequestSpecs = { + initialize: requestSpec( + schema.AGENT_METHODS.initialize, + parseV2InitializeRequest, + mapV2InitializeResponse, + serializeV2InitializeResponse, + ), + loginAuth: requestSpec< + schema.LoginAuthRequest, + schema.LoginAuthResponse | void, + schema.LoginAuthResponse + >( + schema.AGENT_METHODS.auth_login, + validate.zLoginAuthRequest, + validate.zLoginAuthResponse, + emptyObjectResponse, + ), + newSession: requestSpec( + schema.AGENT_METHODS.session_new, + received(validate.zNewSessionRequest), + received(validate.zNewSessionResponse), + ), + setSessionConfigOption: requestSpec< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >( + schema.AGENT_METHODS.session_set_config_option, + received(validate.zSetSessionConfigOptionRequest), + received(validate.zSetSessionConfigOptionResponse), + ), + prompt: requestSpec( + schema.AGENT_METHODS.session_prompt, + received(validate.zPromptRequest), + received(validate.zPromptResponse), + ), + listSessions: requestSpec< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >( + schema.AGENT_METHODS.session_list, + validate.zListSessionsRequest, + validate.zListSessionsResponse, + ), + deleteSession: requestSpec< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void, + schema.DeleteSessionResponse + >( + schema.AGENT_METHODS.session_delete, + validate.zDeleteSessionRequest, + validate.zDeleteSessionResponse, + emptyObjectResponse, + ), + resumeSession: requestSpec< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >( + schema.AGENT_METHODS.session_resume, + received(validate.zResumeSessionRequest), + received(validate.zResumeSessionResponse), + ), + closeSession: requestSpec< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void, + schema.CloseSessionResponse + >( + schema.AGENT_METHODS.session_close, + validate.zCloseSessionRequest, + validate.zCloseSessionResponse, + emptyObjectResponse, + ), + cancelToolCall: requestSpec< + schema.CancelToolCallRequest, + schema.CancelToolCallResponse | void, + schema.CancelToolCallResponse + >( + schema.AGENT_METHODS.tool_call_cancel, + validate.zCancelToolCallRequest, + validate.zCancelToolCallResponse, + emptyObjectResponse, + ), + cancelTerminal: requestSpec< + schema.CancelTerminalRequest, + schema.CancelTerminalResponse | void, + schema.CancelTerminalResponse + >( + schema.AGENT_METHODS.terminal_cancel, + validate.zCancelTerminalRequest, + validate.zCancelTerminalResponse, + emptyObjectResponse, + ), + logoutAuth: requestSpec< + schema.LogoutAuthRequest, + schema.LogoutAuthResponse | void, + schema.LogoutAuthResponse + >( + schema.AGENT_METHODS.auth_logout, + validate.zLogoutAuthRequest, + validate.zLogoutAuthResponse, + emptyObjectResponse, + ), +}; +const agentNotificationSpecs = { + cancelSession: notificationSpec( + schema.AGENT_METHODS.session_cancel, + validate.zCancelSessionNotification, + ), +}; +const clientRequestSpecs = { + requestPermission: requestSpec< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >( + schema.CLIENT_METHODS.session_request_permission, + received(validate.zRequestPermissionRequest), + received(validate.zRequestPermissionResponse), + ), + createElicitation: requestSpec< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >( + schema.CLIENT_METHODS.elicitation_create, + received(validate.zCreateElicitationRequest), + received(validate.zCreateElicitationResponse), + ), +}; +const clientNotificationSpecs = { + sessionUpdate: notificationSpec( + schema.CLIENT_METHODS.session_update, + received(validate.zUpdateSessionNotification), + ), + completeElicitation: notificationSpec( + schema.CLIENT_METHODS.elicitation_complete, + validate.zCompleteElicitationNotification, + ), +}; +const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs); +const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs); +const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs); +const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs); +/** + * Agent request handlers keyed by ACP protocol method name. + */ +export type AgentRequestHandlersByMethod = { + /** + * Handles `initialize`. + * + * Runs again for each repeated `initialize`, which the Client may send after + * a previous one completed and before any other request; the latest + * successful exchange is authoritative. Other requests that arrive while + * `initialize` is in flight are rejected with `-32600`. + * + * When the Client requests a newer protocol version than v2, params that do + * not parse under v2 are dropped instead of rejected, and a missing or + * malformed `info` is replaced with `{ name: "unknown", version: "unknown" }`. + */ + [schema.AGENT_METHODS.initialize]: AgentRequestHandler< + schema.InitializeRequest, + schema.InitializeResponse + >; + [schema.AGENT_METHODS.auth_login]: AgentRequestHandler< + schema.LoginAuthRequest, + schema.LoginAuthResponse | void + >; + [schema.AGENT_METHODS.session_new]: AgentRequestHandler< + schema.NewSessionRequest, + schema.NewSessionResponse + >; + [schema.AGENT_METHODS.session_set_config_option]: AgentRequestHandler< + schema.SetSessionConfigOptionRequest, + schema.SetSessionConfigOptionResponse + >; + [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< + schema.PromptRequest, + schema.PromptResponse + >; + [schema.AGENT_METHODS.session_list]: AgentRequestHandler< + schema.ListSessionsRequest, + schema.ListSessionsResponse + >; + [schema.AGENT_METHODS.session_delete]: AgentRequestHandler< + schema.DeleteSessionRequest, + schema.DeleteSessionResponse | void + >; + /** + * Handles `session/resume`. + * + * With a `replayFrom` cursor, replay the history as `session/update` + * notifications, then send `replay_complete` exactly once, also when the + * history is empty. Until then, send only replayed history for the + * session and hold its other updates. Requests such as + * `session/request_permission` should wait too. Do not send + * `replay_complete` when `replayFrom` is omitted or `null`, or when the + * replay cannot be finished. Throw `-32602` for an unsupported cursor, + * without replaying anything. + * + * For every successful resume, send the current `state_update` before + * responding, after `replay_complete` when a replay was requested. + */ + [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< + schema.ResumeSessionRequest, + schema.ResumeSessionResponse + >; + /** + * Handles `session/close`. Before responding, cancel every pending + * `session/request_permission` request and elicitation in the session with + * `$/cancel_request`, for example by aborting the `cancellationSignal` + * passed to `AgentContext.request`. Pass `stopWaitingOnCancel: true` with + * it so the pending request promise rejects with `-32800` right away + * instead of waiting for the Client's answer. Closing also stops the + * session's background work. + */ + [schema.AGENT_METHODS.session_close]: AgentRequestHandler< + schema.CloseSessionRequest, + schema.CloseSessionResponse | void + >; + /** + * Handles `tool_call/cancel`. + * + * Respond once the cancellation is accepted, then confirm it with a + * `tool_call_update` to a final status. Throw `-32602` for a tool call + * that is unknown, already final, or not cancellable. This includes a + * request the Client sends again after the first one was accepted and the + * tool call has since reached a final status. Without this handler (and + * without a `"*"` request fallback), the app answers every + * `tool_call/cancel` with `-32602`. + */ + [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< + schema.CancelToolCallRequest, + schema.CancelToolCallResponse | void + >; + /** + * Handles `terminal/cancel`. + * + * Respond once the cancellation is accepted, then confirm it with a + * `terminal_update` that sets `exitStatus`. Cancelling does not release the + * terminal. Throw `-32602` for a terminal that is unknown, has already + * exited, or is not cancellable. This includes a request the Client sends + * again after the first one was accepted and the process has since exited. + * Without this handler (and without a `"*"` request fallback), the app + * answers every `terminal/cancel` with `-32602`. + */ + [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< + schema.CancelTerminalRequest, + schema.CancelTerminalResponse | void + >; + /** + * Handles `auth/logout`. Logging out is idempotent: respond with the same + * empty result when there is no authenticated state to end, for example + * because the Client already logged out. + */ + [schema.AGENT_METHODS.auth_logout]: AgentRequestHandler< + schema.LogoutAuthRequest, + schema.LogoutAuthResponse | void + >; +}; +/** + * ACP request methods that can be handled by an `AgentApp`. + */ +export type AgentRequestMethod = keyof AgentRequestHandlersByMethod & string; +/** + * Agent notification handlers keyed by ACP protocol method name. + */ +export type AgentNotificationHandlersByMethod = { + /** + * Handles `session/cancel`. Stop waiting on the pending + * `session/request_permission` requests of the cancelled foreground work, + * treat them as not approved, and cancel each with `$/cancel_request`, for + * example by aborting the `cancellationSignal` passed to + * `AgentContext.request`. With `stopWaitingOnCancel: true`, aborting the + * signal does both: it sends `$/cancel_request` and rejects the request + * promise with `-32800` without waiting for the Client's answer. Work in + * the latest `background` list keeps running. + */ + [schema.AGENT_METHODS + .session_cancel]: AgentNotificationHandler; +}; +/** + * ACP notification methods that can be handled by an `AgentApp`. + */ +export type AgentNotificationMethod = keyof AgentNotificationHandlersByMethod & + string; +/** + * Client request handlers keyed by ACP protocol method name. + */ +export type ClientRequestHandlersByMethod = { + [schema.CLIENT_METHODS.session_request_permission]: ClientRequestHandler< + schema.RequestPermissionRequest, + schema.RequestPermissionResponse + >; + [schema.CLIENT_METHODS.elicitation_create]: ClientRequestHandler< + schema.CreateElicitationRequest, + schema.CreateElicitationResponse + >; +}; +/** + * ACP request methods that can be handled by a `ClientApp`. + */ +export type ClientRequestMethod = keyof ClientRequestHandlersByMethod & string; +/** + * Client notification handlers keyed by ACP protocol method name. + */ +export type ClientNotificationHandlersByMethod = { + [schema.CLIENT_METHODS + .session_update]: ClientNotificationHandler; + [schema.CLIENT_METHODS + .elicitation_complete]: ClientNotificationHandler; +}; +/** + * ACP notification methods that can be handled by a `ClientApp`. + */ +export type ClientNotificationMethod = + keyof ClientNotificationHandlersByMethod & string; +/** + * Agent request params keyed by ACP protocol method name. + */ +export type AgentRequestParamsByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +/** + * Agent request responses keyed by ACP protocol method name. + */ +export type AgentRequestResponsesByMethod = { + [Method in AgentRequestMethod]: AgentRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; +/** + * Agent notification params keyed by ACP protocol method name. + */ +export type AgentNotificationParamsByMethod = { + [ + Method in AgentNotificationMethod + ]: AgentNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +/** + * Client request params keyed by ACP protocol method name. + */ +export type ClientRequestParamsByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +/** + * Client request responses keyed by ACP protocol method name. + */ +export type ClientRequestResponsesByMethod = { + [ + Method in ClientRequestMethod + ]: ClientRequestHandlersByMethod[Method] extends ( + context: infer _Context, + ) => MaybePromise + ? Exclude + : never; +}; +/** + * Client notification params keyed by ACP protocol method name. + */ +export type ClientNotificationParamsByMethod = { + [ + Method in ClientNotificationMethod + ]: ClientNotificationHandlersByMethod[Method] extends ( + context: infer Context, + ) => MaybePromise + ? Context extends { + params: infer Params; + } + ? Params + : never + : never; +}; +function agentRequestContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): AgentRequestContext { + return { + method, + params, + requestId, + signal, + client, + }; +} +function agentNotificationContext( + params: Params, + client: AgentContext, + signal: AbortSignal, + method: string, +): AgentNotificationContext { + return { + method, + params, + signal, + client, + }; +} +function clientRequestContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + requestId: JsonRpcId, + method: string, +): ClientRequestContext { + return { + method, + params, + requestId, + signal, + agent, + }; +} +function clientNotificationContext( + params: Params, + agent: ClientContext, + signal: AbortSignal, + method: string, +): ClientNotificationContext { + return { + method, + params, + signal, + agent, + }; +} +type ActiveSessionUpdateQueue = Pick; +class SessionUpdateRouter { + private readonly activeSessions = new Map< + string, + Set + >(); + handleMessage(message: IncomingMessage): HandleResult { + if ( + message.kind !== "notification" || + message.method !== schema.CLIENT_METHODS.session_update + ) { + return Handled.no(message); + } + const notification = received( + validate.zUpdateSessionNotification, + ).parse(message.params); + const { update } = notification; + const isIdle = + guards.SessionUpdate.isStateUpdate(update) && + guards.StateUpdate.isIdle(update); + const activeSessions = this.activeSessions.get(notification.sessionId); + if (activeSessions && activeSessions.size > 0) { + for (const session of activeSessions) { + if (isIdle) { + session.enqueue({ + kind: "stop", + notification, + update, + stopReason: update.stopReason, + }); + } else { + session.enqueue({ + kind: "session_update", + notification, + update, + }); + } + } + } + return Handled.no(message); + } + attach( + response: schema.NewSessionResponse, + updates: ActiveSessionUpdateQueue, + ): HandlerRegistration { + const sessions = + this.activeSessions.get(response.sessionId) ?? + new Set(); + sessions.add(updates); + this.activeSessions.set(response.sessionId, sessions); + return new HandlerRegistration(() => { + sessions.delete(updates); + if (sessions.size === 0) { + this.activeSessions.delete(response.sessionId); + } + }); + } +} +const sessionUpdateRouters = new WeakMap< + ConnectionContext, + SessionUpdateRouter +>(); +function sessionUpdateRouter(cx: ConnectionContext): SessionUpdateRouter { + let router = sessionUpdateRouters.get(cx); + if (!router) { + router = new SessionUpdateRouter(); + sessionUpdateRouters.set(cx, router); + } + return router; +} +function runConnectHandlers( + connection: ConnectionHandle, + handlers: ReadonlyArray<(connection: ConnectionHandle) => MaybePromise>, +): void { + for (const handler of handlers) { + let result: MaybePromise; + try { + result = handler(connection); + } catch (error) { + connection.close(error); + throw error; + } + void Promise.resolve(result).catch((error) => { + connection.close(error); + }); + } +} +const appBuilder = Symbol("appBuilder"); +const runAgentConnectHandlers = Symbol("runAgentConnectHandlers"); +const runClientConnectHandlers = Symbol("runClientConnectHandlers"); +type AppConnectOptions = { + readonly deferConnectHandlers?: boolean; +}; +type AgentConnectionState = { + rawConnection: Connection; + connection: AgentConnection; +}; +type ClientConnectionState = { + rawConnection: Connection; + connection: ClientConnection; +}; +function bridgeConnectionClose(source: Connection, peer: Connection): void { + void source.closed.then(async () => { + if (initializationState(source.getContext()).status === "initialized") { + await initializationState(peer.getContext()).initialized.catch(() => {}); + } + peer.closeFromPeer(source.signal.reason); + }); +} +/** + * Creates an agent-side app for the experimental draft ACP v2 API. + * + * Register request and notification handlers by ACP method name, then call + * `connect(stream)` to serve an ACP client. + * + * @experimental + */ +export function agent(options?: AppOptions): AgentApp { + return new AgentApp(options); +} +/** + * Agent-side app builder for the experimental draft ACP v2 API. + * + * Methods on this class register typed request or notification handlers and + * return `this`, so apps can be built with a fluent chain. Handler params are + * parsed with the generated ACP schemas before your handler runs, and thrown + * errors are converted to JSON-RPC errors by the connection layer. + * + * @experimental + */ +export class AgentApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: AgentConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + private readonly requestMethods = new Set(); + private hasInitializeHandler = false; + constructor(options: AppOptions = {}) { + this.builder.withHandler(agentInitializationGuard()); + this.builder.withHandler( + defaultEntityCancelHandler( + (method) => + this.requestMethods.has(method) || this.fallbackKinds.has("request"), + ), + ); + if (options.name) { + this.builder.name(options.name); + } + } + /** @internal */ + [appBuilder](): ConnectionBuilder { + this.assertInitializeHandler(); + return this.builder; + } + /** @internal */ + [runAgentConnectHandlers](connection: AgentConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + /** + * Connects this agent app to a transport stream. + */ + connect(stream: Stream): AgentConnection; + /** @internal */ + connect(stream: Stream, options: AppConnectOptions): AgentConnection; + /** + * Connects this agent app directly to a client app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(client: ClientApp): AgentConnection; + connect( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnection { + return this.connectConnection(target, options).connection; + } + /** + * Connects this agent app to a stream or client app for the lifetime of `op`. + * + * The callback receives an `AgentContext` for calling client-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | ClientApp, + op: (context: AgentContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.client)); + } + /** + * Registers a handler that runs when this agent app opens a connection. + * + * Use this for connection-scoped work that needs to call client-side ACP + * methods outside an inbound request handler, or to set up per-connection + * state that the request handlers use. Requests and notifications sent + * through `connection.client` wait until `initialize` has completed. + * + * Handlers are called synchronously in registration order and are not + * awaited. A handler that throws or rejects closes the connection. When they + * are called depends on who opens the connection: + * + * - `connect(...)` and `connectWith(...)` call them before the connection + * handles its first inbound message, and so does + * {@link AgentProtocolRouter.connect} when it routes to this app. Only the + * work a handler does before its first `await` is guaranteed to come first. + * - The experimental `AcpServer` calls them after the client has completed + * `initialize`. Request handlers, including `initialize`, can run before + * them. + */ + onConnect(handler: AgentConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + /** + * Registers a request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: AgentRequestHandler): this; + onRequest( + method: Method, + handler: AgentRequestHandlersByMethod[Method], + ): this; + onRequest( + method: ExtensionMethod, + params: ParamsParser, + handler: AgentRequestHandler, + ): this; + onRequest( + method: UnrecognizedMethod, + params: ParamsParser, + handler: AgentRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | AgentRequestHandlersByMethod[AgentRequestMethod] + | AgentRequestHandler + | ParamsParser, + handler?: AgentRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as AgentRequestHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "request"); + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = agentRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + if (method === schema.AGENT_METHODS.initialize) { + this.hasInitializeHandler = true; + } + this.requestMethods.add(method); + return this.request( + spec as AcpRequestSpec, + handlerOrParams as AgentRequestHandler, + ); + } + /** + * Registers a notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. Serialize work yourself + * when its effects must be applied in order. + */ + onNotification(method: "*", handler: AgentNotificationHandler): this; + onNotification( + method: Method, + handler: AgentNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: ExtensionMethod, + params: ParamsParser, + handler: AgentNotificationHandler, + ): this; + onNotification( + method: UnrecognizedMethod, + params: ParamsParser, + handler: AgentNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | AgentNotificationHandlersByMethod[AgentNotificationMethod] + | AgentNotificationHandler + | ParamsParser, + handler?: AgentNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as AgentNotificationHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "notification"); + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = agentNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as AgentNotificationHandler, + ); + } + private request( + spec: AcpRequestSpec, + handler: AgentRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + agentRequestContext( + params, + AgentContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.serializeResponse, + spec.method === schema.AGENT_METHODS.initialize + ? { + beforeResponse: (_params, response, cx) => { + initializationState(cx).complete( + mapV2InitializeResponse(response), + ); + }, + onError: (cx) => initializationState(cx).failAttempt(), + } + : undefined, + ); + return this; + } + private notification( + spec: AcpNotificationSpec, + handler: AgentNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + agentNotificationContext( + params, + AgentContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + private connectConnection( + target: Stream | ClientApp, + options: AppConnectOptions = {}, + ): AgentConnectionState { + this.assertInitializeHandler(); + if (isStream(target)) { + const state = this.openStreamConnection(target); + if (!options.deferConnectHandlers) { + this[runAgentConnectHandlers](state.connection); + } + return state; + } + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = clientConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); + try { + target[runClientConnectHandlers](peerConnection); + this[runAgentConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + private openStreamConnection(stream: Stream): AgentConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: agentConnection(rawConnection, this.connectHandlers), + }; + } + private assertInitializeHandler(): void { + if (!this.hasInitializeHandler) { + throw new Error( + "AgentApp requires an initialize request handler before connecting", + ); + } + } +} +/** + * Creates a client-side app for the experimental draft ACP v2 API. + * + * Register request and notification handlers by ACP method name, then use + * `connectWith(...)` to run the workflow that calls agent-side methods. + * + * @experimental + */ +export function client(options?: AppOptions): ClientApp { + return new ClientApp(options); +} +/** + * Client-side app builder for the experimental draft ACP v2 API. + * + * Methods on this class register typed client handlers and return `this`, so + * apps can be built with a fluent chain. `connectWith(...)` is the usual entry + * point for clients because it provides a `ClientContext` for calling + * agent-side requests and session helpers. + * + * @experimental + */ +export class ClientApp { + private readonly builder = Connection.builder(); + private readonly connectHandlers: ClientConnectHandler[] = []; + private readonly fallbackKinds = new Set<"request" | "notification">(); + constructor(options: AppOptions = {}) { + if (options.name) { + this.builder.name(options.name); + } + this.builder.withHandler(clientInitializationGuard()); + this.builder.withHandler({ + handleMessage: (message, cx) => + sessionUpdateRouter(cx).handleMessage(message), + describe: () => "client-session-update-router", + }); + } + /** @internal */ + [appBuilder](): ConnectionBuilder { + return this.builder; + } + /** @internal */ + [runClientConnectHandlers](connection: ClientConnection): void { + runConnectHandlers(connection, this.connectHandlers); + } + /** + * Connects this client app to a transport stream. + */ + connect(stream: Stream): ClientConnection; + /** + * Connects this client app directly to an agent app. + * + * This is useful for tests and in-process examples that do not need a + * transport. + */ + connect(agent: AgentApp): ClientConnection; + connect(target: Stream | AgentApp): ClientConnection { + return this.connectConnection(target).connection; + } + /** + * Connects this client app to a stream or agent app for the lifetime of `op`. + * + * The callback receives a `ClientContext` for calling agent-side methods. + * When `op` resolves or rejects, the connection is closed. + */ + connectWith( + target: Stream | AgentApp, + op: (context: ClientContext) => MaybePromise, + ): Promise { + const { rawConnection, connection } = this.connectConnection(target); + return rawConnection.runUntil(() => op(connection.agent)); + } + /** + * Registers a handler that runs when this client app opens a connection. + * + * Use this for connection-scoped work that needs to call agent-side ACP + * methods outside an inbound request handler. + */ + onConnect(handler: ClientConnectHandler): this { + this.connectHandlers.push(handler); + return this; + } + /** + * Registers a client request handler by ACP method name. + * + * Built-in method literals infer their params and response types from + * `method`. Pass a parser as the second argument to register custom extension + * methods. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + */ + onRequest(method: "*", handler: ClientRequestHandler): this; + onRequest( + method: Method, + handler: ClientRequestHandlersByMethod[Method], + ): this; + onRequest( + method: ExtensionMethod, + params: ParamsParser, + handler: ClientRequestHandler, + ): this; + onRequest( + method: UnrecognizedMethod, + params: ParamsParser, + handler: ClientRequestHandler, + ): this; + onRequest( + method: string, + handlerOrParams: + | ClientRequestHandlersByMethod[ClientRequestMethod] + | ClientRequestHandler + | ParamsParser, + handler?: ClientRequestHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("request")) + throw new Error("A request fallback is already registered."); + this.fallbackKinds.add("request"); + return this.request( + { method }, + handlerOrParams as ClientRequestHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "request"); + return this.request( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = clientRequestSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP request method '${method}'. Pass a params parser for custom methods.`, + ); + } + return this.request( + spec as AcpRequestSpec, + handlerOrParams as ClientRequestHandler, + ); + } + /** + * Registers a client notification handler by ACP method name. + * + * Built-in method literals infer their params type from `method`. Pass a + * parser as the second argument to register custom extension notifications. + * Use `"*"` without a parser for a raw fallback after normal dispatch. + * + * Handlers start in the order notifications arrive, but the connection does + * not wait for an async handler to settle before dispatching the next + * message, so async handlers can run concurrently. ACP requires a session's + * `session/update` notifications to be applied in the order they are + * received, so a `session/update` handler that awaits before applying an + * update must serialize that work itself, for example by chaining it onto a + * per-session promise. {@link ActiveSession} already queues updates in + * arrival order. + */ + onNotification( + method: "*", + handler: ClientNotificationHandler, + ): this; + onNotification( + method: Method, + handler: ClientNotificationHandlersByMethod[Method], + ): this; + onNotification( + method: ExtensionMethod, + params: ParamsParser, + handler: ClientNotificationHandler, + ): this; + onNotification( + method: UnrecognizedMethod, + params: ParamsParser, + handler: ClientNotificationHandler, + ): this; + onNotification( + method: string, + handlerOrParams: + | ClientNotificationHandlersByMethod[ClientNotificationMethod] + | ClientNotificationHandler + | ParamsParser, + handler?: ClientNotificationHandler, + ): this { + if (method === "*") { + if (handler) + throw new Error( + "Wildcard handlers receive raw params; omit the parser.", + ); + if (this.fallbackKinds.has("notification")) + throw new Error("A notification fallback is already registered."); + this.fallbackKinds.add("notification"); + return this.notification( + { method }, + handlerOrParams as ClientNotificationHandler, + ); + } + if (handler) { + assertUnrecognizedV2Method(method, "notification"); + return this.notification( + { method, params: handlerOrParams as ParamsParser }, + handler, + ); + } + const spec = clientNotificationSpecsByMethod[method]; + if (!spec) { + throw new Error( + `Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`, + ); + } + return this.notification( + spec as AcpNotificationSpec, + handlerOrParams as ClientNotificationHandler, + ); + } + private request( + spec: AcpRequestSpec, + handler: ClientRequestHandler, + ): this { + registerAppRequest( + this.builder, + spec, + (params, cx, signal, requestId, method) => + clientRequestContext( + params, + ClientContext.create(cx, requestId), + signal, + requestId, + method, + ), + handler, + spec.serializeResponse, + ); + return this; + } + private notification( + spec: AcpNotificationSpec, + handler: ClientNotificationHandler, + ): this { + registerAppNotification( + this.builder, + spec, + (params, cx, signal, method) => + clientNotificationContext( + params, + ClientContext.create(cx), + signal, + method, + ), + handler, + ); + return this; + } + private connectConnection(target: Stream | AgentApp): ClientConnectionState { + if (isStream(target)) { + const state = this.openStreamConnection(target); + this[runClientConnectHandlers](state.connection); + return state; + } + const [thisStream, peerStream] = memoryStreamPair(); + const peerRawConnection = target[appBuilder]().connect(peerStream); + const peerConnection = agentConnection(peerRawConnection); + const state = this.openStreamConnection(thisStream); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); + try { + target[runAgentConnectHandlers](peerConnection); + this[runClientConnectHandlers](state.connection); + } catch (error) { + peerConnection.close(error); + state.connection.close(error); + throw error; + } + return state; + } + private openStreamConnection(stream: Stream): ClientConnectionState { + const rawConnection = this.builder.connect(stream); + return { + rawConnection, + connection: clientConnection(rawConnection, this.connectHandlers), + }; + } +} diff --git a/src/v2/stable/methods.ts b/src/v2/stable/methods.ts new file mode 100644 index 00000000..7f9484e0 --- /dev/null +++ b/src/v2/stable/methods.ts @@ -0,0 +1,49 @@ +// Generated from src/v2/methods.ts. Do not edit directly. +import * as schema from "../schema/index.js"; +/** + * ACP method-name constants for the experimental draft v2 API. + * + * Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and + * `notify(...)` when you want literal-string type inference without spelling + * protocol strings inline. + * + * @experimental + */ +export const methods = { + agent: { + initialize: schema.AGENT_METHODS.initialize, + auth: { + login: schema.AGENT_METHODS.auth_login, + logout: schema.AGENT_METHODS.auth_logout, + }, + session: { + new: schema.AGENT_METHODS.session_new, + list: schema.AGENT_METHODS.session_list, + delete: schema.AGENT_METHODS.session_delete, + resume: schema.AGENT_METHODS.session_resume, + close: schema.AGENT_METHODS.session_close, + setConfigOption: schema.AGENT_METHODS.session_set_config_option, + prompt: schema.AGENT_METHODS.session_prompt, + cancel: schema.AGENT_METHODS.session_cancel, + }, + toolCall: { + cancel: schema.AGENT_METHODS.tool_call_cancel, + }, + terminal: { + cancel: schema.AGENT_METHODS.terminal_cancel, + }, + }, + client: { + session: { + requestPermission: schema.CLIENT_METHODS.session_request_permission, + update: schema.CLIENT_METHODS.session_update, + }, + elicitation: { + create: schema.CLIENT_METHODS.elicitation_create, + complete: schema.CLIENT_METHODS.elicitation_complete, + }, + }, + protocol: { + cancelRequest: schema.PROTOCOL_METHODS.cancel_request, + }, +} as const;