diff --git a/bun.lock b/bun.lock index 35d9915b41..a78655c81f 100644 --- a/bun.lock +++ b/bun.lock @@ -213,15 +213,12 @@ "vite": "^8.0.0", }, "catalog": { - "@effect/atom-react": "4.0.0-beta.45", - "@effect/language-service": "0.84.2", - "@effect/openapi-generator": "4.0.0-beta.45", - "@effect/platform-bun": "4.0.0-beta.45", - "@effect/platform-node": "4.0.0-beta.45", - "@effect/platform-node-shared": "4.0.0-beta.45", - "@effect/sql-sqlite-bun": "4.0.0-beta.45", - "@effect/vitest": "4.0.0-beta.45", - "@types/bun": "^1.3.11", + "@effect/language-service": "0.75.1", + "@effect/openapi-generator": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b", + "@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", + "@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", + "@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", + "@types/bun": "^1.3.9", "@types/node": "^24.10.13", "effect": "4.0.0-beta.45", "tsdown": "^0.20.3", @@ -313,7 +310,9 @@ "@effect/atom-react": ["@effect/atom-react@4.0.0-beta.45", "", { "peerDependencies": { "effect": "^4.0.0-beta.45", "react": "^19.2.4", "scheduler": "*" } }, "sha512-jCoiae9UNeis9Yoal1p5V/P4eJK9nX89wORom7X5LpR2Ok920SZJc8dIeYkRXRAp9BCYJ/yWcO8gGLf7do71vg=="], - "@effect/language-service": ["@effect/language-service@0.84.2", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="], + "@effect/openapi-generator": ["@effect/openapi-generator@https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.25", "effect": "^4.0.0-beta.25" }, "bin": { "openapigen": "./dist/bin.js" } }], + + "@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25", "ioredis": "^5.7.0" } }], "@effect/openapi-generator": ["@effect/openapi-generator@4.0.0-beta.45", "", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.45", "effect": "^4.0.0-beta.45" }, "bin": { "openapigen": "dist/bin.js" } }, "sha512-zT1UPzapV6mZebMuYhoDPQj/FKNn4R+oDgz1hEcQwazal4+lVDyEYGhRl0PgZroy6CP78fAOWNgW7TriGqSlOQ=="], @@ -1083,6 +1082,8 @@ "effect-acp": ["effect-acp@workspace:packages/effect-acp"], + "effect-acp": ["effect-acp@workspace:packages/effect-acp"], + "electron": ["electron@40.6.0", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="], "electron-to-chromium": ["electron-to-chromium@1.5.313", "", {}, "sha512-QBMrTWEf00GXZmJyx2lbYD45jpI3TUFnNIzJ5BBc8piGUDwMPa1GV6HJWTZVvY/eiN3fSopl7NRbgGp9sZ9LTA=="], @@ -2053,6 +2054,18 @@ "@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], + "@effect/openapi-generator/@effect/platform-node": ["@effect/platform-node@4.0.0-beta.41", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.41", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41", "ioredis": "^5.7.0" } }, "sha512-lgsWfvJfxwg7xXT5rK3xcPyAFPAYXXJ0u/6yCu2suOMhdR5w2W6oA2L2pIQaqap8qR8uEVB5pHq6dqVfdRP7Nw=="], + + "@effect/openapi-generator/effect": ["effect@4.0.0-beta.41", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-kBjbmo2qqXbOgrvZcPgVdgsOOWcGPYwRcvGO3aGPWJhpXxDFNfgtwqtU6asMq2M7LSFRx1SA+3BzJm7FDqtxew=="], + + "@effect/platform-node/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], + + "@effect/platform-node-shared/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], + + "@effect/sql-sqlite-bun/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], + + "@effect/vitest/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], + "@electron/get/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], "@electron/get/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -2147,6 +2160,8 @@ "@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0-rc.2", "", {}, "sha512-noLx87RwlBEMrTzncWd/FvTxoJ9+ycHNg0n8yyYydIoDsLZuxknKgWRJUqcrVkNrJ74uGyhWQzQaS3q8xfGAhQ=="], + "@effect/openapi-generator/@effect/platform-node/@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.41", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41" } }, "sha512-YzKWz1G8YofCrQ0Thxymlk71CM3q7R1vzO2vtnb7KSHkTJrvrQB8FbZaM8mEddYOoamR25f46lidFKErmmotKg=="], + "@electron/get/fs-extra/jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="], "@electron/get/fs-extra/universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="], diff --git a/package.json b/package.json index 93a75d5b7e..f3d56efaf4 100644 --- a/package.json +++ b/package.json @@ -8,16 +8,13 @@ "scripts" ], "catalog": { - "effect": "4.0.0-beta.45", - "@effect/atom-react": "4.0.0-beta.45", - "@effect/openapi-generator": "4.0.0-beta.45", - "@effect/platform-bun": "4.0.0-beta.45", - "@effect/platform-node": "4.0.0-beta.45", - "@effect/platform-node-shared": "4.0.0-beta.45", - "@effect/sql-sqlite-bun": "4.0.0-beta.45", - "@effect/vitest": "4.0.0-beta.45", - "@effect/language-service": "0.84.2", - "@types/bun": "^1.3.11", + "effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", + "@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", + "@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", + "@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", + "@effect/openapi-generator": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b", + "@effect/language-service": "0.75.1", + "@types/bun": "^1.3.9", "@types/node": "^24.10.13", "tsdown": "^0.20.3", "typescript": "^5.7.3", diff --git a/packages/effect-acp/package.json b/packages/effect-acp/package.json index 296d64fc4f..c059c57cc3 100644 --- a/packages/effect-acp/package.json +++ b/packages/effect-acp/package.json @@ -4,37 +4,79 @@ "type": "module", "exports": { "./client": { - "types": "./src/client.ts", - "import": "./src/client.ts" + "import": { + "types": "./src/client.d.mts", + "default": "./src/client.mjs" + }, + "require": { + "types": "./src/client.d.cts", + "default": "./src/client.cjs" + } }, - "./agent": { - "types": "./src/agent.ts", - "import": "./src/agent.ts" + "./server": { + "import": { + "types": "./src/server.d.mts", + "default": "./src/server.mjs" + }, + "require": { + "types": "./src/server.d.cts", + "default": "./src/server.cjs" + } }, "./schema": { - "types": "./src/schema.ts", - "import": "./src/schema.ts" + "import": { + "types": "./src/_generated/schema.gen.d.mts", + "default": "./src/_generated/schema.gen.mjs" + }, + "require": { + "types": "./src/_generated/schema.gen.d.cts", + "default": "./src/_generated/schema.gen.cjs" + } }, "./rpc": { - "types": "./src/rpc.ts", - "import": "./src/rpc.ts" + "import": { + "types": "./src/rpc.d.mts", + "default": "./src/rpc.mjs" + }, + "require": { + "types": "./src/rpc.d.cts", + "default": "./src/rpc.cjs" + } }, "./protocol": { - "types": "./src/protocol.ts", - "import": "./src/protocol.ts" + "import": { + "types": "./src/protocol.d.mts", + "default": "./src/protocol.mjs" + }, + "require": { + "types": "./src/protocol.d.cts", + "default": "./src/protocol.cjs" + } }, "./terminal": { - "types": "./src/terminal.ts", - "import": "./src/terminal.ts" + "import": { + "types": "./src/terminal.d.mts", + "default": "./src/terminal.mts" + }, + "require": { + "types": "./src/terminal.d.cts", + "default": "./src/terminal.cjs" + } }, - "./errors": { - "types": "./src/errors.ts", - "import": "./src/errors.ts" + "./child-process": { + "import": { + "types": "./src/child-process.d.mts", + "default": "./src/child-process.mts" + }, + "require": { + "types": "./src/child-process.d.cts", + "default": "./src/child-process.cjs" + } } }, "scripts": { - "dev": "tsdown src/client.ts src/agent.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/terminal.ts --format esm,cjs --dts --watch --clean", - "build": "tsdown src/client.ts src/agent.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/terminal.ts --format esm,cjs --dts --clean", + "dev": "tsdown src/client.ts src/server.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/child-process.ts src/terminal.ts --format esm,cjs --dts --watch --clean", + "build": "tsdown src/client.ts src/server.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/child-process.ts src/terminal.ts --format esm,cjs --dts --clean", "prepare": "effect-language-service patch", "typecheck": "tsc --noEmit", "test": "vitest run", diff --git a/packages/effect-acp/scripts/generate.ts b/packages/effect-acp/scripts/generate.ts index f2837c4f85..09d43205dc 100644 --- a/packages/effect-acp/scripts/generate.ts +++ b/packages/effect-acp/scripts/generate.ts @@ -10,11 +10,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; const CURRENT_SCHEMA_RELEASE = "v0.11.3"; -interface GenerateCommandError { - readonly _tag: "GenerateCommandError"; - readonly message: string; -} - interface GeneratedPaths { readonly generatedDir: string; readonly upstreamSchemaPath: string; @@ -224,14 +219,7 @@ const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: bo } } - const prelude = [ - `// This file is generated by the effect-acp package. Do not edit manually.`, - `// Current ACP schema release: ${CURRENT_SCHEMA_RELEASE}`, - "", - ]; - const schemaOutput = [ - ...prelude, 'import * as Schema from "effect/Schema";', "", [...generatedEntries.values()].join("\n\n"), @@ -239,7 +227,6 @@ const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: bo ].join("\n"); const metaOutput = [ - ...prelude, `export const AGENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.agentMethods))(upstreamMeta.agentMethods)} as const;`, "", `export const CLIENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.clientMethods))(upstreamMeta.clientMethods)} as const;`, @@ -257,14 +244,7 @@ const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: bo yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe( Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))), Effect.flatMap((child) => child.exitCode), - Effect.tap((code) => - code === 0 - ? Effect.void - : Effect.fail({ - _tag: "GenerateCommandError", - message: `oxfmt failed with exit code ${code}`, - }), - ), + Effect.tap(() => Effect.log("Formatted generated files")), ); }); diff --git a/packages/effect-acp/src/_generated/meta.gen.ts b/packages/effect-acp/src/_generated/meta.gen.ts index 5d2dd3dd3d..b1b719a202 100644 --- a/packages/effect-acp/src/_generated/meta.gen.ts +++ b/packages/effect-acp/src/_generated/meta.gen.ts @@ -1,6 +1,3 @@ -// This file is generated by the effect-acp package. Do not edit manually. -// Current ACP schema release: v0.11.3 - export const AGENT_METHODS = { authenticate: "authenticate", initialize: "initialize", diff --git a/packages/effect-acp/src/_generated/schema.gen.ts b/packages/effect-acp/src/_generated/schema.gen.ts index 73fdc75236..3a86373fff 100644 --- a/packages/effect-acp/src/_generated/schema.gen.ts +++ b/packages/effect-acp/src/_generated/schema.gen.ts @@ -1,6 +1,3 @@ -// This file is generated by the effect-acp package. Do not edit manually. -// Current ACP schema release: v0.11.3 - import * as Schema from "effect/Schema"; export type AuthEnvVar = { @@ -484,17 +481,6 @@ export const SessionCloseCapabilities = Schema.Struct({ "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nCapabilities for the `session/close` method.\n\nBy supplying `{}` it means that the agent supports closing of sessions.", }); -export type SessionConfigOptionCategory = "mode" | "model" | "thought_level" | string; -export const SessionConfigOptionCategory = Schema.Union([ - Schema.Literal("mode").annotate({ description: "Session mode selector." }), - Schema.Literal("model").annotate({ description: "Model selector." }), - Schema.Literal("thought_level").annotate({ description: "Thought/reasoning level selector." }), - Schema.String.annotate({ title: "other", description: "Unknown / uncategorized selector." }), -]).annotate({ - description: - "Semantic category for a session configuration option.\n\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\ncategories gracefully.\n\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\nCategory names that do not begin with `_` are reserved for the ACP spec.", -}); - export type SessionConfigSelectOption = { readonly _meta?: { readonly [x: string]: unknown } | null; readonly description?: string | null; @@ -1814,97 +1800,40 @@ export type SessionConfigOption = readonly options: | ReadonlyArray | ReadonlyArray; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly category?: SessionConfigOptionCategory | null; - readonly description?: string | null; - readonly id: string; - readonly name: string; } - | { - readonly type: "boolean"; - readonly currentValue: boolean; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly category?: SessionConfigOptionCategory | null; - readonly description?: string | null; - readonly id: string; - readonly name: string; - }; -export const SessionConfigOption = Schema.Union([ - Schema.Struct({ - type: Schema.Literal("select"), - currentValue: Schema.String.annotate({ - description: "Unique identifier for a session configuration option value.", - }), - options: Schema.Union([ - Schema.Array(SessionConfigSelectOption).annotate({ - title: "Ungrouped", - description: "A flat list of options with no grouping.", + | { readonly type: "boolean"; readonly currentValue: boolean }; +export const SessionConfigOption = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("select"), + currentValue: Schema.String.annotate({ + description: "Unique identifier for a session configuration option value.", }), - Schema.Array(SessionConfigSelectGroup).annotate({ - title: "Grouped", - description: "A list of options grouped under headers.", - }), - ]).annotate({ description: "Possible values for a session configuration option." }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + options: Schema.Union([ + Schema.Array(SessionConfigSelectOption).annotate({ + title: "Ungrouped", + description: "A flat list of options with no grouping.", }), - Schema.Null, - ]), - ), - category: Schema.optionalKey( - Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({ - description: "Optional semantic category for this option (UX only).", - }), - ), - description: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: "Optional description for the Client to display to the user.", + Schema.Array(SessionConfigSelectGroup).annotate({ + title: "Grouped", + description: "A list of options grouped under headers.", }), - Schema.Null, - ]), - ), - id: Schema.String.annotate({ - description: "Unique identifier for a session configuration option.", + ]).annotate({ description: "Possible values for a session configuration option." }), + }).annotate({ + description: "A single-value selector (dropdown) session configuration option payload.", }), - name: Schema.String.annotate({ description: "Human-readable label for the option." }), - }).annotate({ description: "A session configuration option selector and its current state." }), - Schema.Struct({ - type: Schema.Literal("boolean"), - currentValue: Schema.Boolean.annotate({ - description: "The current value of the boolean option.", - }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - category: Schema.optionalKey( - Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({ - description: "Optional semantic category for this option (UX only).", + Schema.Struct({ + type: Schema.Literal("boolean"), + currentValue: Schema.Boolean.annotate({ + description: "The current value of the boolean option.", }), - ), - description: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: "Optional description for the Client to display to the user.", - }), - Schema.Null, - ]), - ), - id: Schema.String.annotate({ - description: "Unique identifier for a session configuration option.", + }).annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nA boolean on/off toggle session configuration option payload.", }), - name: Schema.String.annotate({ description: "Human-readable label for the option." }), - }).annotate({ description: "A session configuration option selector and its current state." }), -]); + ], + { mode: "oneOf" }, +).annotate({ description: "A session configuration option selector and its current state." }); export type SessionModeState = { readonly _meta?: { readonly [x: string]: unknown } | null; @@ -3076,18 +3005,8 @@ export type AgentRequest = { readonly title?: string | null; readonly type?: "object"; }; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly message: string; - readonly sessionId: string; - } - | { - readonly mode: "url"; - readonly elicitationId: string; - readonly url: string; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly message: string; - readonly sessionId: string; } + | { readonly mode: "url"; readonly elicitationId: string; readonly url: string } | unknown | null; }; @@ -3366,102 +3285,73 @@ export const AgentRequest = Schema.Struct({ title: "KillTerminalRequest", description: "Request to kill a terminal without releasing it.", }), - Schema.Union([ - Schema.Struct({ - mode: Schema.Literal("form"), - requestedSchema: Schema.Struct({ - description: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: "Optional description of what this schema represents.", + Schema.Union( + [ + Schema.Struct({ + mode: Schema.Literal("form"), + requestedSchema: Schema.Struct({ + description: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional description of what this schema represents.", + }), + Schema.Null, + ]), + ), + properties: Schema.optionalKey( + Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ + description: "Property definitions (must be primitive types).", + default: {}, }), - Schema.Null, - ]), - ), - properties: Schema.optionalKey( - Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ - description: "Property definitions (must be primitive types).", - default: {}, - }), - ), - required: Schema.optionalKey( - Schema.Union([ - Schema.Array(Schema.String).annotate({ - description: "List of required property names.", + ), + required: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "List of required property names.", + }), + Schema.Null, + ]), + ), + title: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional title for the schema." }), + Schema.Null, + ]), + ), + type: Schema.optionalKey( + Schema.Literal("object").annotate({ + description: "Type discriminator for elicitation schemas.", + default: "object", }), - Schema.Null, - ]), - ), - title: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ description: "Optional title for the schema." }), - Schema.Null, - ]), - ), - type: Schema.optionalKey( - Schema.Literal("object").annotate({ - description: "Type discriminator for elicitation schemas.", - default: "object", - }), - ), + ), + }).annotate({ + description: + "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", + }), }).annotate({ description: - "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nForm-based elicitation mode where the client renders a form from the provided schema.", }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - message: Schema.String.annotate({ - description: "A human-readable message describing what input is needed.", - }), - sessionId: Schema.String.annotate({ + Schema.Struct({ + mode: Schema.Literal("url"), + elicitationId: Schema.String.annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", + }), + url: Schema.String.annotate({ + description: "The URL to direct the user to.", + format: "uri", + }), + }).annotate({ description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nURL-based elicitation mode where the client directs the user to a URL.", }), - }).annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", - }), - Schema.Struct({ - mode: Schema.Literal("url"), - elicitationId: Schema.String.annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", - }), - url: Schema.String.annotate({ - description: "The URL to direct the user to.", - format: "uri", - }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - message: Schema.String.annotate({ - description: "A human-readable message describing what input is needed.", - }), - sessionId: Schema.String.annotate({ - description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", - }), - }).annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", - }), - ]).annotate({ + ], + { mode: "oneOf" }, + ).annotate({ title: "ElicitationRequest", description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequests structured user input via a form or URL.", + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", }), Schema.Unknown.annotate({ title: "ExtMethodRequest", @@ -4600,19 +4490,8 @@ export type ClientRequest = { readonly modeId: string; readonly sessionId: string; } - | { - readonly type: "boolean"; - readonly value: boolean; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly configId: string; - readonly sessionId: string; - } - | { - readonly value: string; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly configId: string; - readonly sessionId: string; - } + | { readonly type: "boolean"; readonly value: boolean } + | { readonly value: string } | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly messageId?: string | null; @@ -4951,52 +4830,19 @@ export const ClientRequest = Schema.Struct({ Schema.Struct({ type: Schema.Literal("boolean"), value: Schema.Boolean.annotate({ description: "The boolean value." }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - configId: Schema.String.annotate({ - description: "Unique identifier for a session configuration option.", - }), - sessionId: Schema.String.annotate({ - description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", - }), - }).annotate({ - description: "Request parameters for setting a session configuration option.", - }), + }).annotate({ description: 'A boolean value (`type: "boolean"`).' }), Schema.Struct({ value: Schema.String.annotate({ description: "Unique identifier for a session configuration option value.", }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - configId: Schema.String.annotate({ - description: "Unique identifier for a session configuration option.", - }), - sessionId: Schema.String.annotate({ - description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", - }), }).annotate({ title: "value_id", - description: "Request parameters for setting a session configuration option.", + description: + "A [`SessionConfigValueId`] string value.\n\nThis is the default when `type` is absent on the wire. Unknown `type`\nvalues with string payloads also gracefully deserialize into this\nvariant.", }), ]).annotate({ title: "SetSessionConfigOptionRequest", - description: "Sets the current value for a session configuration option.", + description: "Request parameters for setting a session configuration option.", }), Schema.Struct({ _meta: Schema.optionalKey( @@ -5972,106 +5818,72 @@ export type ElicitationRequest = readonly title?: string | null; readonly type?: "object"; }; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly message: string; - readonly sessionId: string; } - | { - readonly mode: "url"; - readonly elicitationId: string; - readonly url: string; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly message: string; - readonly sessionId: string; - }; -export const ElicitationRequest = Schema.Union([ - Schema.Struct({ - mode: Schema.Literal("form"), - requestedSchema: Schema.Struct({ - description: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: "Optional description of what this schema represents.", + | { readonly mode: "url"; readonly elicitationId: string; readonly url: string }; +export const ElicitationRequest = Schema.Union( + [ + Schema.Struct({ + mode: Schema.Literal("form"), + requestedSchema: Schema.Struct({ + description: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional description of what this schema represents.", + }), + Schema.Null, + ]), + ), + properties: Schema.optionalKey( + Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ + description: "Property definitions (must be primitive types).", + default: {}, }), - Schema.Null, - ]), - ), - properties: Schema.optionalKey( - Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ - description: "Property definitions (must be primitive types).", - default: {}, - }), - ), - required: Schema.optionalKey( - Schema.Union([ - Schema.Array(Schema.String).annotate({ description: "List of required property names." }), - Schema.Null, - ]), - ), - title: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ description: "Optional title for the schema." }), - Schema.Null, - ]), - ), - type: Schema.optionalKey( - Schema.Literal("object").annotate({ - description: "Type discriminator for elicitation schemas.", - default: "object", - }), - ), + ), + required: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "List of required property names.", + }), + Schema.Null, + ]), + ), + title: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional title for the schema." }), + Schema.Null, + ]), + ), + type: Schema.optionalKey( + Schema.Literal("object").annotate({ + description: "Type discriminator for elicitation schemas.", + default: "object", + }), + ), + }).annotate({ + description: + "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", + }), }).annotate({ description: - "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nForm-based elicitation mode where the client renders a form from the provided schema.", }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - message: Schema.String.annotate({ - description: "A human-readable message describing what input is needed.", - }), - sessionId: Schema.String.annotate({ + Schema.Struct({ + mode: Schema.Literal("url"), + elicitationId: Schema.String.annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", + }), + url: Schema.String.annotate({ description: "The URL to direct the user to.", format: "uri" }), + }).annotate({ description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nURL-based elicitation mode where the client directs the user to a URL.", }), - }).annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", - }), - Schema.Struct({ - mode: Schema.Literal("url"), - elicitationId: Schema.String.annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", - }), - url: Schema.String.annotate({ description: "The URL to direct the user to.", format: "uri" }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - message: Schema.String.annotate({ - description: "A human-readable message describing what input is needed.", - }), - sessionId: Schema.String.annotate({ - description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", - }), - }).annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", - }), -]); + ], + { mode: "oneOf" }, +).annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", +}); export type ElicitationResponse = { readonly _meta?: { readonly [x: string]: unknown } | null; @@ -7989,6 +7801,17 @@ export const SessionConfigId = Schema.String.annotate({ description: "Unique identifier for a session configuration option.", }); +export type SessionConfigOptionCategory = "mode" | "model" | "thought_level" | string; +export const SessionConfigOptionCategory = Schema.Union([ + Schema.Literal("mode").annotate({ description: "Session mode selector." }), + Schema.Literal("model").annotate({ description: "Model selector." }), + Schema.Literal("thought_level").annotate({ description: "Thought/reasoning level selector." }), + Schema.String.annotate({ title: "other", description: "Unknown / uncategorized selector." }), +]).annotate({ + description: + "Semantic category for a session configuration option.\n\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\ncategories gracefully.\n\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\nCategory names that do not begin with `_` are reserved for the ACP spec.", +}); + export type SessionConfigSelect = { readonly currentValue: string; readonly options: @@ -9710,65 +9533,23 @@ export const SessionUpdate = Schema.Union( }); export type SetSessionConfigOptionRequest = - | { - readonly type: "boolean"; - readonly value: boolean; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly configId: string; - readonly sessionId: string; - } - | { - readonly value: string; - readonly _meta?: { readonly [x: string]: unknown } | null; - readonly configId: string; - readonly sessionId: string; - }; + | { readonly type: "boolean"; readonly value: boolean } + | { readonly value: string }; export const SetSessionConfigOptionRequest = Schema.Union([ Schema.Struct({ type: Schema.Literal("boolean"), value: Schema.Boolean.annotate({ description: "The boolean value." }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - configId: Schema.String.annotate({ - description: "Unique identifier for a session configuration option.", - }), - sessionId: Schema.String.annotate({ - description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", - }), - }).annotate({ description: "Request parameters for setting a session configuration option." }), + }).annotate({ description: 'A boolean value (`type: "boolean"`).' }), Schema.Struct({ value: Schema.String.annotate({ description: "Unique identifier for a session configuration option value.", }), - _meta: Schema.optionalKey( - Schema.Union([ - Schema.Record(Schema.String, Schema.Unknown).annotate({ - description: - "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", - }), - Schema.Null, - ]), - ), - configId: Schema.String.annotate({ - description: "Unique identifier for a session configuration option.", - }), - sessionId: Schema.String.annotate({ - description: - "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", - }), }).annotate({ title: "value_id", - description: "Request parameters for setting a session configuration option.", + description: + "A [`SessionConfigValueId`] string value.\n\nThis is the default when `type` is absent on the wire. Unknown `type`\nvalues with string payloads also gracefully deserialize into this\nvariant.", }), -]); +]).annotate({ description: "Request parameters for setting a session configuration option." }); export type SetSessionConfigOptionResponse = { readonly _meta?: { readonly [x: string]: unknown } | null; diff --git a/packages/effect-acp/src/child-process.ts b/packages/effect-acp/src/child-process.ts new file mode 100644 index 0000000000..f9aaf971bb --- /dev/null +++ b/packages/effect-acp/src/child-process.ts @@ -0,0 +1,21 @@ +import * as Layer from "effect/Layer"; +import * as Sink from "effect/Sink"; +import * as Stdio from "effect/Stdio"; +import type { ChildProcessSpawner } from "effect/unstable/process"; + +const textEncoder = new TextEncoder(); + +export function makeStdioFromChildProcess( + handle: ChildProcessSpawner.ChildProcessHandle, +): Stdio.Stdio { + return Stdio.make({ + stdin: handle.stdout, + stdout: Sink.mapInput(handle.stdin, (chunk) => + typeof chunk === "string" ? textEncoder.encode(chunk) : chunk, + ), + stderr: Sink.drain, + }); +} + +export const layerStdioFromChildProcess = (handle: ChildProcessSpawner.ChildProcessHandle) => + Layer.succeed(Stdio.Stdio, makeStdioFromChildProcess(handle)); diff --git a/packages/effect-acp/src/client.test.ts b/packages/effect-acp/src/client.test.ts index b867231ad7..d920850310 100644 --- a/packages/effect-acp/src/client.test.ts +++ b/packages/effect-acp/src/client.test.ts @@ -1,173 +1,42 @@ import * as Path from "effect/Path"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, assert } from "@effect/vitest"; -import * as AcpClient from "./client.ts"; -import * as AcpSchema from "./_generated/schema.gen.ts"; -import * as AcpError from "./errors.ts"; -import { encodeJsonl, jsonRpcRequest, jsonRpcResponse } from "./_internal/shared.ts"; -import { makeInMemoryStdio } from "./_internal/stdio.ts"; - -const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest); -const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse); -const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String })); -const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean })); +import * as AcpClient from "./client"; const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) => path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"), ); it.layer(NodeServices.layer)("effect-acp client", (it) => { - const makeHandle = (env?: Record) => - Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], { - cwd: path.join(import.meta.dirname, ".."), - shell: process.platform === "win32", - ...(env ? { env: { ...process.env, ...env } } : {}), - }); - return yield* spawner.spawn(command); - }); - it.effect("initializes, prompts, receives updates, and handles permission requests", () => Effect.gen(function* () { const updates = yield* Ref.make>([]); const elicitationCompletions = yield* Ref.make>([]); - const typedRequests = yield* Ref.make>([]); - const typedNotifications = yield* Ref.make>([]); - const handle = yield* makeHandle(); - const scope = yield* Scope.make(); - const acpLayer = AcpClient.layerChildProcess(handle); - const context = yield* Layer.buildWithScope(acpLayer, scope); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; - const ext = yield* Effect.gen(function* () { - const acp = yield* AcpClient.AcpClient; - - yield* acp.handleRequestPermission(() => - Effect.succeed({ - outcome: { - outcome: "selected", - optionId: "allow", - }, - }), - ); - yield* acp.handleElicitation(() => - Effect.succeed({ - action: { - action: "accept", - content: { - approved: true, - }, - }, - }), - ); - yield* acp.handleSessionUpdate((notification) => - Ref.update(updates, (current) => [...current, notification]), - ); - yield* acp.handleElicitationComplete((notification) => - Ref.update(elicitationCompletions, (current) => [...current, notification]), - ); - yield* acp.handleExtRequest( - "x/typed_request", - Schema.Struct({ message: Schema.String }), - (payload) => - Ref.update(typedRequests, (current) => [...current, payload]).pipe( - Effect.as({ - ok: true, - echoedMessage: payload.message, - }), - ), - ); - yield* acp.handleExtNotification( - "x/typed_notification", - Schema.Struct({ count: Schema.Number }), - (payload) => Ref.update(typedNotifications, (current) => [...current, payload]), - ); - - const init = yield* acp.agent.initialize({ - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { - name: "effect-acp-test", - version: "0.0.0", - }, - }); - assert.equal(init.protocolVersion, 1); - - yield* acp.agent.authenticate({ methodId: "cursor_login" }); - - const session = yield* acp.agent.createSession({ - cwd: process.cwd(), - mcpServers: [], - }); - assert.equal(session.sessionId, "mock-session-1"); - - const prompt = yield* acp.agent.prompt({ - sessionId: session.sessionId, - prompt: [{ type: "text", text: "hello" }], - }); - assert.equal(prompt.stopReason, "end_turn"); - - const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2)); - assert.equal(streamed.length, 2); - assert.equal(streamed[0]?._tag, "SessionUpdate"); - assert.equal(streamed[1]?._tag, "ElicitationComplete"); - assert.equal((yield* Ref.get(updates)).length, 1); - assert.equal((yield* Ref.get(elicitationCompletions)).length, 1); - assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]); - assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]); - - return yield* acp.raw.request("x/echo", { - hello: "world", - }); - }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void))); - - assert.deepEqual(ext, { - echoedMethod: "x/echo", - echoedParams: { - hello: "world", - }, + const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], { + cwd: path.join(import.meta.dirname, ".."), + shell: process.platform === "win32", }); - }), - ); + const handle = yield* spawner.spawn(command); - it.effect( - "returns formatted invalid params when a typed extension request payload is wrong", - () => - Effect.gen(function* () { - const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" }); - const scope = yield* Scope.make(); - const acpLayer = AcpClient.layerChildProcess(handle); - const context = yield* Layer.buildWithScope(acpLayer, scope); - - const result = yield* Effect.gen(function* () { - const acp = yield* AcpClient.AcpClient; - - yield* acp.handleRequestPermission(() => + const client = yield* AcpClient.fromChildProcess(handle, { + handlers: { + requestPermission: () => Effect.succeed({ outcome: { outcome: "selected", optionId: "allow", }, }), - ); - yield* acp.handleElicitation(() => + elicitation: () => Effect.succeed({ action: { action: "accept", @@ -176,275 +45,56 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => { }, }, }), - ); - yield* acp.handleExtRequest( - "x/typed_request", - Schema.Struct({ message: Schema.String }), - () => Effect.succeed({ ok: true }), - ); + sessionUpdate: (notification) => + Ref.update(updates, (current) => [...current, notification]), + elicitationComplete: (notification) => + Ref.update(elicitationCompletions, (current) => [...current, notification]), + }, + }); - yield* acp.agent.initialize({ - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { - name: "effect-acp-test", - version: "0.0.0", - }, - }); + const init = yield* client.initialize({ + protocolVersion: 1, + clientCapabilities: { + fs: { readTextFile: false, writeTextFile: false }, + terminal: false, + }, + clientInfo: { + name: "effect-acp-test", + version: "0.0.0", + }, + }); + assert.equal(init.protocolVersion, 1); - yield* acp.agent.authenticate({ methodId: "cursor_login" }); + yield* client.authenticate({ methodId: "cursor_login" }); - const session = yield* acp.agent.createSession({ - cwd: process.cwd(), - mcpServers: [], - }); + const session = yield* client.createSession({ + cwd: process.cwd(), + mcpServers: [], + }); + assert.equal(session.sessionId, "mock-session-1"); - return yield* Effect.exit( - acp.agent.prompt({ - sessionId: session.sessionId, - prompt: [{ type: "text", text: "hello" }], - }), - ); - }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void))); + const prompt = yield* client.prompt({ + sessionId: session.sessionId, + prompt: [{ type: "text", text: "hello" }], + }); + assert.equal(prompt.stopReason, "end_turn"); - if (result._tag !== "Failure") { - assert.fail("Expected prompt to fail for invalid typed extension payload"); - } - const rendered = Cause.pretty(result.cause); - assert.include(rendered, "Invalid x/typed_request payload:"); - assert.include(rendered, "Expected string, got 123"); - }), - ); + const streamed = yield* Stream.runCollect(Stream.take(client.updates, 2)); + assert.equal(streamed.length, 2); + assert.equal(streamed[0]?._tag, "SessionUpdate"); + assert.equal(streamed[1]?._tag, "ElicitationComplete"); + assert.equal((yield* Ref.get(updates)).length, 1); + assert.equal((yield* Ref.get(elicitationCompletions)).length, 1); - it.effect("replays buffered notifications to handlers registered after they arrive", () => - Effect.gen(function* () { - const updates = yield* Ref.make>([]); - const elicitationCompletions = yield* Ref.make>([]); - const typedRequests = yield* Ref.make>([]); - const typedNotifications = yield* Ref.make>([]); - const handle = yield* makeHandle(); - const scope = yield* Scope.make(); - const acpLayer = AcpClient.layerChildProcess(handle); - const context = yield* Layer.buildWithScope(acpLayer, scope); - - yield* Effect.gen(function* () { - const acp = yield* AcpClient.AcpClient; - - yield* acp.handleRequestPermission(() => - Effect.succeed({ - outcome: { - outcome: "selected", - optionId: "allow", - }, - }), - ); - yield* acp.handleElicitation(() => - Effect.succeed({ - action: { - action: "accept", - content: { - approved: true, - }, - }, - }), - ); - yield* acp.handleExtRequest( - "x/typed_request", - Schema.Struct({ message: Schema.String }), - (payload) => - Ref.update(typedRequests, (current) => [...current, payload]).pipe( - Effect.as({ - ok: true, - echoedMessage: payload.message, - }), - ), - ); - yield* acp.handleExtNotification( - "x/typed_notification", - Schema.Struct({ count: Schema.Number }), - (payload) => Ref.update(typedNotifications, (current) => [...current, payload]), - ); - - yield* acp.agent.initialize({ - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { - name: "effect-acp-test", - version: "0.0.0", - }, - }); - yield* acp.agent.authenticate({ methodId: "cursor_login" }); - - const session = yield* acp.agent.createSession({ - cwd: process.cwd(), - mcpServers: [], - }); - yield* acp.agent.prompt({ - sessionId: session.sessionId, - prompt: [{ type: "text", text: "hello" }], - }); - - yield* acp.handleSessionUpdate((notification) => - Ref.update(updates, (current) => [...current, notification]), - ); - yield* acp.handleElicitationComplete((notification) => - Ref.update(elicitationCompletions, (current) => [...current, notification]), - ); - - assert.equal((yield* Ref.get(updates)).length, 1); - assert.equal((yield* Ref.get(elicitationCompletions)).length, 1); - assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]); - assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]); - }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void))); - }), - ); - - it.effect("continues dispatching session updates after one handler fails", () => - Effect.gen(function* () { - const successfulHandlers = yield* Ref.make(0); - const handle = yield* makeHandle(); - const scope = yield* Scope.make(); - const acpLayer = AcpClient.layerChildProcess(handle); - const context = yield* Layer.buildWithScope(acpLayer, scope); - - yield* Effect.gen(function* () { - const acp = yield* AcpClient.AcpClient; - - yield* acp.handleRequestPermission(() => - Effect.succeed({ - outcome: { - outcome: "selected", - optionId: "allow", - }, - }), - ); - yield* acp.handleElicitation(() => - Effect.succeed({ - action: { - action: "accept", - content: { - approved: true, - }, - }, - }), - ); - yield* acp.handleExtRequest( - "x/typed_request", - Schema.Struct({ message: Schema.String }), - () => Effect.succeed({ ok: true }), - ); - yield* acp.handleExtNotification( - "x/typed_notification", - Schema.Struct({ count: Schema.Number }), - () => Effect.void, - ); - yield* acp.handleSessionUpdate(() => - Effect.fail(AcpError.AcpRequestError.internalError("session update handler failed")), - ); - yield* acp.handleSessionUpdate(() => Ref.update(successfulHandlers, (count) => count + 1)); - - yield* acp.agent.initialize({ - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { - name: "effect-acp-test", - version: "0.0.0", - }, - }); - yield* acp.agent.authenticate({ methodId: "cursor_login" }); - - const session = yield* acp.agent.createSession({ - cwd: process.cwd(), - mcpServers: [], - }); - yield* acp.agent.prompt({ - sessionId: session.sessionId, - prompt: [{ type: "text", text: "hello" }], - }); - - assert.equal(yield* Ref.get(successfulHandlers), 1); - }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void))); - }), - ); - - it.effect("uses distinct ids for RPC calls and extension requests", () => - Effect.gen(function* () { - const { stdio, input, output } = yield* makeInMemoryStdio(); - const scope = yield* Scope.make(); - const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope)); - - const initializeFiber = yield* acp.agent - .initialize({ - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { - name: "effect-acp-test", - version: "0.0.0", - }, - }) - .pipe(Effect.forkScoped); - const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped); - - const firstOutbound = yield* Queue.take(output); - const secondOutbound = yield* Queue.take(output); - - const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest)); - const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest)); - const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe( - Effect.match({ - onFailure: () => false, - onSuccess: () => true, - }), - ); - - const initializeRequest = firstIsInitialize - ? yield* decodedInitialize(firstOutbound) - : yield* decodedInitialize(secondOutbound); - const extRequest = firstIsInitialize - ? yield* decodedExt(secondOutbound) - : yield* decodedExt(firstOutbound); - - assert.notEqual(initializeRequest.id, extRequest.id); - - yield* Queue.offer( - input, - yield* encodeJsonl(InitializeResponse, { - jsonrpc: "2.0", - id: initializeRequest.id, - result: { - protocolVersion: 1, - agentCapabilities: {}, - agentInfo: { - name: "mock-agent", - version: "0.0.0", - }, - }, - }), - ); - yield* Queue.offer( - input, - yield* encodeJsonl(ExtResponse, { - jsonrpc: "2.0", - id: extRequest.id, - result: { ok: true }, - }), - ); - - yield* Fiber.join(initializeFiber); - assert.deepEqual(yield* Fiber.join(extFiber), { ok: true }); - yield* Scope.close(scope, Exit.void); + const ext = yield* client.extRequest("x/echo", { + hello: "world", + }); + assert.deepEqual(ext, { + echoedMethod: "x/echo", + echoedParams: { + hello: "world", + }, + }); }), ); }); diff --git a/packages/effect-acp/src/client.ts b/packages/effect-acp/src/client.ts index 3052726ede..53c2ca0fd6 100644 --- a/packages/effect-acp/src/client.ts +++ b/packages/effect-acp/src/client.ts @@ -1,445 +1,298 @@ -import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; -import * as Stdio from "effect/Stdio"; -import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as RpcClient from "effect/unstable/rpc/RpcClient"; import * as RpcServer from "effect/unstable/rpc/RpcServer"; -import { ChildProcessSpawner } from "effect/unstable/process"; -import * as AcpError from "./errors.ts"; -import * as AcpProtocol from "./protocol.ts"; -import * as AcpRpcs from "./rpc.ts"; -import * as AcpSchema from "./_generated/schema.gen.ts"; -import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts"; -import { - callRpc, - decodeExtNotificationRegistration, - decodeExtRequestRegistration, - runHandler, -} from "./_internal/shared.ts"; -import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts"; +import { makeStdioFromChildProcess } from "./child-process"; +import * as AcpError from "./errors"; +import * as AcpProtocol from "./protocol"; +import * as AcpRpcs from "./rpc"; +import * as AcpServer from "./server"; +import * as AcpSchema from "./_generated/schema.gen"; +import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -export interface AcpClientOptions { - readonly logIncoming?: boolean; - readonly logOutgoing?: boolean; - readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect; -} - -type AcpClientRaw = { - readonly notifications: Stream.Stream; - readonly request: (method: string, payload: unknown) => Effect.Effect; - readonly notify: (method: string, payload: unknown) => Effect.Effect; -}; - -export interface AcpClientShape { - readonly raw: AcpClientRaw; - readonly agent: { - /** - * Initializes the ACP session and negotiates capabilities. - * @see https://agentclientprotocol.com/protocol/schema#initialize - */ - readonly initialize: ( - payload: AcpSchema.InitializeRequest, - ) => Effect.Effect; - /** - * Performs ACP authentication when the agent requires it. - * @see https://agentclientprotocol.com/protocol/schema#authenticate - */ - readonly authenticate: ( - payload: AcpSchema.AuthenticateRequest, - ) => Effect.Effect; - /** - * Logs out the current ACP identity. - * @see https://agentclientprotocol.com/protocol/schema#logout - */ - readonly logout: ( - payload: AcpSchema.LogoutRequest, - ) => Effect.Effect; - /** - * Starts a new ACP session. - * @see https://agentclientprotocol.com/protocol/schema#session/new - */ - readonly createSession: ( - payload: AcpSchema.NewSessionRequest, - ) => Effect.Effect; - /** - * Loads a previously saved ACP session. - * @see https://agentclientprotocol.com/protocol/schema#session/load - */ - readonly loadSession: ( - payload: AcpSchema.LoadSessionRequest, - ) => Effect.Effect; - /** - * Lists available ACP sessions. - * @see https://agentclientprotocol.com/protocol/schema#session/list - */ - readonly listSessions: ( - payload: AcpSchema.ListSessionsRequest, - ) => Effect.Effect; - /** - * Forks an ACP session. - * @see https://agentclientprotocol.com/protocol/schema#session/fork - */ - readonly forkSession: ( - payload: AcpSchema.ForkSessionRequest, - ) => Effect.Effect; - /** - * Resumes an ACP session. - * @see https://agentclientprotocol.com/protocol/schema#session/resume - */ - readonly resumeSession: ( - payload: AcpSchema.ResumeSessionRequest, - ) => Effect.Effect; - /** - * Closes an ACP session. - * @see https://agentclientprotocol.com/protocol/schema#session/close - */ - readonly closeSession: ( - payload: AcpSchema.CloseSessionRequest, - ) => Effect.Effect; - /** - * Selects the active model for a session. - * @see https://agentclientprotocol.com/protocol/schema#session/set_model - */ - readonly setSessionModel: ( - payload: AcpSchema.SetSessionModelRequest, - ) => Effect.Effect; - /** - * Updates a session configuration option. - * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option - */ - readonly setSessionConfigOption: ( - payload: AcpSchema.SetSessionConfigOptionRequest, - ) => Effect.Effect; - /** - * Sends a prompt turn to the agent. - * @see https://agentclientprotocol.com/protocol/schema#session/prompt - */ - readonly prompt: ( - payload: AcpSchema.PromptRequest, - ) => Effect.Effect; - /** - * Sends a real ACP `session/cancel` notification. - * @see https://agentclientprotocol.com/protocol/schema#session/cancel - */ - readonly cancel: ( - payload: AcpSchema.CancelNotification, - ) => Effect.Effect; - }; +export interface AcpClientHandlers { /** - * Registers a handler for `session/request_permission`. + * Handles `session/request_permission`. * @see https://agentclientprotocol.com/protocol/schema#session/request_permission */ - readonly handleRequestPermission: ( - handler: ( - request: AcpSchema.RequestPermissionRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `session/elicitation`. - * @see https://agentclientprotocol.com/protocol/schema#session/elicitation - */ - readonly handleElicitation: ( - handler: ( - request: AcpSchema.ElicitationRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `fs/read_text_file`. - * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file - */ - readonly handleReadTextFile: ( - handler: ( - request: AcpSchema.ReadTextFileRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `fs/write_text_file`. - * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file - */ - readonly handleWriteTextFile: ( - handler: ( - request: AcpSchema.WriteTextFileRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `terminal/create`. - * @see https://agentclientprotocol.com/protocol/schema#terminal/create - */ - readonly handleCreateTerminal: ( - handler: ( - request: AcpSchema.CreateTerminalRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `terminal/output`. - * @see https://agentclientprotocol.com/protocol/schema#terminal/output - */ - readonly handleTerminalOutput: ( - handler: ( - request: AcpSchema.TerminalOutputRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `terminal/wait_for_exit`. - * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit - */ - readonly handleTerminalWaitForExit: ( - handler: ( - request: AcpSchema.WaitForTerminalExitRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `terminal/kill`. - * @see https://agentclientprotocol.com/protocol/schema#terminal/kill - */ - readonly handleTerminalKill: ( - handler: ( - request: AcpSchema.KillTerminalRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `terminal/release`. - * @see https://agentclientprotocol.com/protocol/schema#terminal/release - */ - readonly handleTerminalRelease: ( - handler: ( - request: AcpSchema.ReleaseTerminalRequest, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `session/update`. - * @see https://agentclientprotocol.com/protocol/schema#session/update - */ - readonly handleSessionUpdate: ( - handler: ( - notification: AcpSchema.SessionNotification, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a handler for `session/elicitation/complete`. - * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete - */ - readonly handleElicitationComplete: ( - handler: ( - notification: AcpSchema.ElicitationCompleteNotification, - ) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a fallback extension request handler. - * @see https://agentclientprotocol.com/protocol/extensibility - */ - readonly handleUnknownExtRequest: ( - handler: (method: string, params: unknown) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a fallback extension notification handler. - * @see https://agentclientprotocol.com/protocol/extensibility - */ - readonly handleUnknownExtNotification: ( - handler: (method: string, params: unknown) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a typed extension request handler. - * @see https://agentclientprotocol.com/protocol/extensibility - */ - readonly handleExtRequest: ( - method: string, - payload: Schema.Codec, - handler: (payload: A) => Effect.Effect, - ) => Effect.Effect; - /** - * Registers a typed extension notification handler. - * @see https://agentclientprotocol.com/protocol/extensibility - */ - readonly handleExtNotification: ( - method: string, - payload: Schema.Codec, - handler: (payload: A) => Effect.Effect, - ) => Effect.Effect; -} - -export class AcpClient extends Context.Service()( - "effect-acp/AcpClient", -) {} - -interface AcpCoreRequestHandlers { - requestPermission?: ( + readonly requestPermission?: ( request: AcpSchema.RequestPermissionRequest, ) => Effect.Effect; - elicitation?: ( + /** + * Handles `session/elicitation`. + * @see https://agentclientprotocol.com/protocol/schema#session/elicitation + */ + readonly elicitation?: ( request: AcpSchema.ElicitationRequest, ) => Effect.Effect; - readTextFile?: ( + /** + * Handles `fs/read_text_file`. + * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file + */ + readonly readTextFile?: ( request: AcpSchema.ReadTextFileRequest, ) => Effect.Effect; - writeTextFile?: ( + /** + * Handles `fs/write_text_file`. + * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file + */ + readonly writeTextFile?: ( request: AcpSchema.WriteTextFileRequest, ) => Effect.Effect; - createTerminal?: ( + /** + * Handles `terminal/create`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/create + */ + readonly createTerminal?: ( request: AcpSchema.CreateTerminalRequest, ) => Effect.Effect; - terminalOutput?: ( + /** + * Handles `terminal/output`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/output + */ + readonly terminalOutput?: ( request: AcpSchema.TerminalOutputRequest, ) => Effect.Effect; - terminalWaitForExit?: ( + /** + * Handles `terminal/wait_for_exit`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit + */ + readonly terminalWaitForExit?: ( request: AcpSchema.WaitForTerminalExitRequest, ) => Effect.Effect; - terminalKill?: ( + /** + * Handles `terminal/kill`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/kill + */ + readonly terminalKill?: ( request: AcpSchema.KillTerminalRequest, ) => Effect.Effect; - terminalRelease?: ( + /** + * Handles `terminal/release`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/release + */ + readonly terminalRelease?: ( request: AcpSchema.ReleaseTerminalRequest, ) => Effect.Effect; + /** + * Handles `session/update` notifications from the agent. + * @see https://agentclientprotocol.com/protocol/schema#session/update + */ + readonly sessionUpdate?: ( + notification: AcpSchema.SessionNotification, + ) => Effect.Effect; + /** + * Handles `session/elicitation/complete` notifications from the agent. + * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete + */ + readonly elicitationComplete?: ( + notification: AcpSchema.ElicitationCompleteNotification, + ) => Effect.Effect; + /** + * Handles extension requests outside the core ACP method set. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly extRequest?: ( + method: string, + params: unknown, + ) => Effect.Effect; + /** + * Handles extension notifications outside the core ACP method set. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly extNotification?: ( + method: string, + params: unknown, + ) => Effect.Effect; } -interface AcpNotificationHandlers { - readonly sessionUpdate: BufferedNotificationHandler; - readonly elicitationComplete: BufferedNotificationHandler; +export interface AcpClientConnectOptions { + readonly command: ChildProcess.Command; + readonly handlers?: AcpClientHandlers; } -interface BufferedNotificationHandler { - readonly handlers: Array<(notification: A) => Effect.Effect>; - readonly pending: Array; +export interface AcpClientConnection { + readonly process: ChildProcessSpawner.ChildProcessHandle; + /** + * Stream of inbound ACP notifications observed on the connection. + * @see https://agentclientprotocol.com/protocol/schema#session/update + */ + readonly updates: Stream.Stream; + readonly server: AcpServer.AcpServerConnection; + /** + * Initializes the ACP session and negotiates capabilities. + * @see https://agentclientprotocol.com/protocol/schema#initialize + */ + readonly initialize: ( + payload: AcpSchema.InitializeRequest, + ) => Effect.Effect; + /** + * Performs ACP authentication when the agent requires it. + * @see https://agentclientprotocol.com/protocol/schema#authenticate + */ + readonly authenticate: ( + payload: AcpSchema.AuthenticateRequest, + ) => Effect.Effect; + /** + * Logs out the current ACP identity. + * @see https://agentclientprotocol.com/protocol/schema#logout + */ + readonly logout: ( + payload: AcpSchema.LogoutRequest, + ) => Effect.Effect; + /** + * Starts a new ACP session. + * @see https://agentclientprotocol.com/protocol/schema#session/new + */ + readonly createSession: ( + payload: AcpSchema.NewSessionRequest, + ) => Effect.Effect; + /** Loads a previously saved ACP session. + * @see https://agentclientprotocol.com/protocol/schema#session/load + */ + readonly loadSession: ( + payload: AcpSchema.LoadSessionRequest, + ) => Effect.Effect; + /** + * Lists available ACP sessions. + * @see https://agentclientprotocol.com/protocol/schema#session/list + */ + readonly listSessions: ( + payload: AcpSchema.ListSessionsRequest, + ) => Effect.Effect; + /** + * Forks an ACP session. + * @see https://agentclientprotocol.com/protocol/schema#session/fork + */ + readonly forkSession: ( + payload: AcpSchema.ForkSessionRequest, + ) => Effect.Effect; + /** + * Resumes an ACP session. + * @see https://agentclientprotocol.com/protocol/schema#session/resume + */ + readonly resumeSession: ( + payload: AcpSchema.ResumeSessionRequest, + ) => Effect.Effect; + /** + * Closes an ACP session. + * @see https://agentclientprotocol.com/protocol/schema#session/close + */ + readonly closeSession: ( + payload: AcpSchema.CloseSessionRequest, + ) => Effect.Effect; + /** + * Changes the current session mode. + * @see https://agentclientprotocol.com/protocol/schema#session/set_mode + */ + readonly setSessionMode: ( + payload: AcpSchema.SetSessionModeRequest, + ) => Effect.Effect; + /** + * Selects the active model for a session. + * @see https://agentclientprotocol.com/protocol/schema#session/set_model + */ + readonly setSessionModel: ( + payload: AcpSchema.SetSessionModelRequest, + ) => Effect.Effect; + /** + * Updates a session configuration option. + * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option + */ + readonly setSessionConfigOption: ( + payload: AcpSchema.SetSessionConfigOptionRequest, + ) => Effect.Effect; + /** + * Sends a prompt turn to the agent. + * @see https://agentclientprotocol.com/protocol/schema#session/prompt + */ + readonly prompt: ( + payload: AcpSchema.PromptRequest, + ) => Effect.Effect; + /** + * Sends a real ACP `session/cancel` notification. + * @see https://agentclientprotocol.com/protocol/schema#session/cancel + */ + readonly cancel: ( + payload: AcpSchema.CancelNotification, + ) => Effect.Effect; + /** + * Sends an ACP extension request. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly extRequest: ( + method: string, + payload: unknown, + ) => Effect.Effect; + /** + * Sends an ACP extension notification. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly extNotification: ( + method: string, + payload: unknown, + ) => Effect.Effect; } -export const make = Effect.fn("effect-acp/AcpClient.make")(function* ( - stdio: Stdio.Stdio, - options: AcpClientOptions = {}, - terminationError?: Effect.Effect, -): Effect.fn.Return { - const coreHandlers: AcpCoreRequestHandlers = {}; - const notificationHandlers: AcpNotificationHandlers = { - sessionUpdate: { handlers: [], pending: [] }, - elicitationComplete: { handlers: [], pending: [] }, - }; - const extRequestHandlers = new Map< - string, - (params: unknown) => Effect.Effect - >(); - const extNotificationHandlers = new Map< - string, - (params: unknown) => Effect.Effect - >(); - let unknownExtRequestHandler: - | ((method: string, params: unknown) => Effect.Effect) - | undefined; - let unknownExtNotificationHandler: - | ((method: string, params: unknown) => Effect.Effect) - | undefined; - - const runNotificationHandlers = ( - registration: BufferedNotificationHandler, - notification: A, - ) => - Effect.forEach( - registration.handlers, - (handler) => handler(notification).pipe(Effect.catch(() => Effect.void)), - { discard: true }, - ); - - const flushBufferedNotifications = (registration: BufferedNotificationHandler) => - Effect.suspend(() => { - if (registration.handlers.length === 0 || registration.pending.length === 0) { - return Effect.void; - } - const pending = registration.pending.splice(0, registration.pending.length); - return Effect.forEach( - pending, - (notification) => runNotificationHandlers(registration, notification), - { - discard: true, - }, - ); - }); - - const dispatchNotification = (notification: AcpProtocol.AcpIncomingNotification) => { - switch (notification._tag) { - case "SessionUpdate": { - if (notificationHandlers.sessionUpdate.handlers.length === 0) { - notificationHandlers.sessionUpdate.pending.push(notification.params); - return Effect.void; - } - return runNotificationHandlers(notificationHandlers.sessionUpdate, notification.params); - } - case "ElicitationComplete": { - if (notificationHandlers.elicitationComplete.handlers.length === 0) { - notificationHandlers.elicitationComplete.pending.push(notification.params); - return Effect.void; - } - return runNotificationHandlers( - notificationHandlers.elicitationComplete, - notification.params, - ); - } - case "ExtNotification": { - const handler = extNotificationHandlers.get(notification.method); - if (handler) { - return handler(notification.params); - } - return unknownExtNotificationHandler - ? unknownExtNotificationHandler(notification.method, notification.params) - : Effect.void; - } - } - }; - - const dispatchExtRequest = (method: string, params: unknown) => { - const handler = extRequestHandlers.get(method); - if (handler) { - return handler(params); - } - return unknownExtRequestHandler - ? unknownExtRequestHandler(method, params) - : Effect.fail(AcpError.AcpRequestError.methodNotFound(method)); - }; - +export const fromChildProcess = Effect.fnUntraced(function* ( + handle: ChildProcessSpawner.ChildProcessHandle, + options: { + readonly handlers?: AcpClientHandlers; + } = {}, +): Effect.fn.Return { + const handlers = options.handlers ?? {}; const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio: stdio, - ...(terminationError ? { terminationError } : {}), + stdio: makeStdioFromChildProcess(handle), serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()), - ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}), - ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}), - ...(options.logger ? { logger: options.logger } : {}), - onNotification: dispatchNotification, - onExtRequest: dispatchExtRequest, + onNotification: (notification) => { + switch (notification._tag) { + case "SessionUpdate": + return handlers.sessionUpdate ? handlers.sessionUpdate(notification.params) : Effect.void; + case "ElicitationComplete": + return handlers.elicitationComplete + ? handlers.elicitationComplete(notification.params) + : Effect.void; + case "ExtNotification": + return handlers.extNotification + ? handlers.extNotification(notification.method, notification.params) + : Effect.void; + case "SessionCancel": + return handlers.extNotification + ? handlers.extNotification(notification.method, notification.params) + : Effect.void; + } + }, + ...(handlers.extRequest ? { onExtRequest: handlers.extRequest } : {}), }); const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer( AcpRpcs.ClientRpcs.of({ [CLIENT_METHODS.session_request_permission]: (payload) => - runHandler( - coreHandlers.requestPermission, - payload, - CLIENT_METHODS.session_request_permission, - ), + runHandler(handlers.requestPermission, payload, CLIENT_METHODS.session_request_permission), [CLIENT_METHODS.session_elicitation]: (payload) => - runHandler(coreHandlers.elicitation, payload, CLIENT_METHODS.session_elicitation), + runHandler(handlers.elicitation, payload, CLIENT_METHODS.session_elicitation), [CLIENT_METHODS.fs_read_text_file]: (payload) => - runHandler(coreHandlers.readTextFile, payload, CLIENT_METHODS.fs_read_text_file), + runHandler(handlers.readTextFile, payload, CLIENT_METHODS.fs_read_text_file), [CLIENT_METHODS.fs_write_text_file]: (payload) => - runHandler(coreHandlers.writeTextFile, payload, CLIENT_METHODS.fs_write_text_file).pipe( + runHandler(handlers.writeTextFile, payload, CLIENT_METHODS.fs_write_text_file).pipe( Effect.map((result) => result ?? {}), ), [CLIENT_METHODS.terminal_create]: (payload) => - runHandler(coreHandlers.createTerminal, payload, CLIENT_METHODS.terminal_create), + runHandler(handlers.createTerminal, payload, CLIENT_METHODS.terminal_create), [CLIENT_METHODS.terminal_output]: (payload) => - runHandler(coreHandlers.terminalOutput, payload, CLIENT_METHODS.terminal_output), + runHandler(handlers.terminalOutput, payload, CLIENT_METHODS.terminal_output), [CLIENT_METHODS.terminal_wait_for_exit]: (payload) => - runHandler( - coreHandlers.terminalWaitForExit, - payload, - CLIENT_METHODS.terminal_wait_for_exit, - ), + runHandler(handlers.terminalWaitForExit, payload, CLIENT_METHODS.terminal_wait_for_exit), [CLIENT_METHODS.terminal_kill]: (payload) => - runHandler(coreHandlers.terminalKill, payload, CLIENT_METHODS.terminal_kill).pipe( + runHandler(handlers.terminalKill, payload, CLIENT_METHODS.terminal_kill).pipe( Effect.map((result) => result ?? {}), ), [CLIENT_METHODS.terminal_release]: (payload) => - runHandler(coreHandlers.terminalRelease, payload, CLIENT_METHODS.terminal_release).pipe( + runHandler(handlers.terminalRelease, payload, CLIENT_METHODS.terminal_release).pipe( Effect.map((result) => result ?? {}), ), }), @@ -451,119 +304,53 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* ( Effect.forkScoped, ); - let nextRpcRequestId = 1n << 32n; - const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs, { - generateRequestId: () => nextRpcRequestId++ as never, - }).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol)); + const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs).pipe( + Effect.provideService(RpcClient.Protocol, transport.clientProtocol), + ); - return AcpClient.of({ - raw: { - notifications: transport.incoming, - request: transport.request, - notify: transport.notify, - }, - agent: { - initialize: (payload) => callRpc(rpc[AGENT_METHODS.initialize](payload)), - authenticate: (payload) => callRpc(rpc[AGENT_METHODS.authenticate](payload)), - logout: (payload) => callRpc(rpc[AGENT_METHODS.logout](payload)), - createSession: (payload) => callRpc(rpc[AGENT_METHODS.session_new](payload)), - loadSession: (payload) => callRpc(rpc[AGENT_METHODS.session_load](payload)), - listSessions: (payload) => callRpc(rpc[AGENT_METHODS.session_list](payload)), - forkSession: (payload) => callRpc(rpc[AGENT_METHODS.session_fork](payload)), - resumeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_resume](payload)), - closeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_close](payload)), - setSessionModel: (payload) => callRpc(rpc[AGENT_METHODS.session_set_model](payload)), - setSessionConfigOption: (payload) => - callRpc(rpc[AGENT_METHODS.session_set_config_option](payload)), - prompt: (payload) => callRpc(rpc[AGENT_METHODS.session_prompt](payload)), - cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload), - }, - handleRequestPermission: (handler) => - Effect.suspend(() => { - coreHandlers.requestPermission = handler; - return Effect.void; - }), - handleElicitation: (handler) => - Effect.suspend(() => { - coreHandlers.elicitation = handler; - return Effect.void; - }), - handleReadTextFile: (handler) => - Effect.suspend(() => { - coreHandlers.readTextFile = handler; - return Effect.void; - }), - handleWriteTextFile: (handler) => - Effect.suspend(() => { - coreHandlers.writeTextFile = handler; - return Effect.void; - }), - handleCreateTerminal: (handler) => - Effect.suspend(() => { - coreHandlers.createTerminal = handler; - return Effect.void; - }), - handleTerminalOutput: (handler) => - Effect.suspend(() => { - coreHandlers.terminalOutput = handler; - return Effect.void; - }), - handleTerminalWaitForExit: (handler) => - Effect.suspend(() => { - coreHandlers.terminalWaitForExit = handler; - return Effect.void; - }), - handleTerminalKill: (handler) => - Effect.suspend(() => { - coreHandlers.terminalKill = handler; - return Effect.void; - }), - handleTerminalRelease: (handler) => - Effect.suspend(() => { - coreHandlers.terminalRelease = handler; - return Effect.void; - }), - handleSessionUpdate: (handler) => - Effect.suspend(() => { - notificationHandlers.sessionUpdate.handlers.push(handler); - return flushBufferedNotifications(notificationHandlers.sessionUpdate); - }), - handleElicitationComplete: (handler) => - Effect.suspend(() => { - notificationHandlers.elicitationComplete.handlers.push(handler); - return flushBufferedNotifications(notificationHandlers.elicitationComplete); - }), - handleUnknownExtRequest: (handler) => - Effect.suspend(() => { - unknownExtRequestHandler = handler; - return Effect.void; - }), - handleUnknownExtNotification: (handler) => - Effect.suspend(() => { - unknownExtNotificationHandler = handler; - return Effect.void; - }), - handleExtRequest: (method, payload, handler) => - Effect.suspend(() => { - extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler)); - return Effect.void; - }), - handleExtNotification: (method, payload, handler) => - Effect.suspend(() => { - extNotificationHandlers.set( - method, - decodeExtNotificationRegistration(method, payload, handler), - ); - return Effect.void; - }), - }); + const callRpc = (effect: Effect.Effect) => + effect.pipe(Effect.mapError(AcpError.normalizeAcpError)); + + const server = AcpServer.makeAcpServerConnection(transport); + + return { + process: handle, + updates: transport.notifications.incoming, + server, + initialize: (payload) => callRpc(rpc[AGENT_METHODS.initialize](payload)), + authenticate: (payload) => callRpc(rpc[AGENT_METHODS.authenticate](payload)), + logout: (payload) => callRpc(rpc[AGENT_METHODS.logout](payload)), + createSession: (payload) => callRpc(rpc[AGENT_METHODS.session_new](payload)), + loadSession: (payload) => callRpc(rpc[AGENT_METHODS.session_load](payload)), + listSessions: (payload) => callRpc(rpc[AGENT_METHODS.session_list](payload)), + forkSession: (payload) => callRpc(rpc[AGENT_METHODS.session_fork](payload)), + resumeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_resume](payload)), + closeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_close](payload)), + setSessionMode: (payload) => callRpc(rpc[AGENT_METHODS.session_set_mode](payload)), + setSessionModel: (payload) => callRpc(rpc[AGENT_METHODS.session_set_model](payload)), + setSessionConfigOption: (payload) => + callRpc(rpc[AGENT_METHODS.session_set_config_option](payload)), + prompt: (payload) => callRpc(rpc[AGENT_METHODS.session_prompt](payload)), + cancel: (payload) => transport.notifications.sendSessionCancel(payload), + extRequest: transport.sendRequest, + extNotification: transport.notifications.sendExtNotification, + } satisfies AcpClientConnection; }); -export const layerChildProcess = ( - handle: ChildProcessSpawner.ChildProcessHandle, - options: AcpClientOptions = {}, -): Layer.Layer => { - const stdio = makeChildStdio(handle); - const terminationError = makeTerminationError(handle); - return Layer.effect(AcpClient, make(stdio, options, terminationError)); -}; +const runHandler = Effect.fnUntraced(function* ( + handler: ((payload: A) => Effect.Effect) | undefined, + payload: A, + method: string, +) { + if (!handler) { + return yield* AcpError.AcpRequestError.methodNotFound(method); + } + return yield* handler(payload).pipe( + Effect.mapError((error) => { + const normalized = AcpError.normalizeAcpError(error); + return Schema.is(AcpError.AcpRequestError)(normalized) + ? normalized.toProtocolError() + : AcpError.AcpRequestError.internalError(normalized.message).toProtocolError(); + }), + ); +}); diff --git a/packages/effect-acp/src/errors.ts b/packages/effect-acp/src/errors.ts index b2fa39120d..0c216f915d 100644 --- a/packages/effect-acp/src/errors.ts +++ b/packages/effect-acp/src/errors.ts @@ -1,10 +1,13 @@ import * as Schema from "effect/Schema"; +import * as RpcClientError from "effect/unstable/rpc/RpcClientError"; -import * as AcpSchema from "./_generated/schema.gen.ts"; +import * as AcpSchema from "./_generated/schema.gen"; + +export type AcpProtocolError = AcpSchema.Error; export class AcpSpawnError extends Schema.TaggedErrorClass()("AcpSpawnError", { command: Schema.optional(Schema.String), - cause: Schema.Defect, + cause: Schema.optional(Schema.Defect), }) { override get message() { return this.command @@ -22,8 +25,8 @@ export class AcpProcessExitedError extends Schema.TaggedErrorClass()("AcpRequestError", { - code: AcpSchema.ErrorCode, + code: Schema.Number, errorMessage: Schema.String, data: Schema.optional(Schema.Unknown), }) { @@ -56,7 +63,7 @@ export class AcpRequestError extends Schema.TaggedErrorClass()( return this.errorMessage; } - static fromProtocolError(error: AcpSchema.Error) { + static fromProtocolError(error: AcpProtocolError) { return new AcpRequestError({ code: error.code, errorMessage: error.message, @@ -119,21 +126,57 @@ export class AcpRequestError extends Schema.TaggedErrorClass()( }); } - toProtocolError() { - return AcpSchema.Error.make({ + toProtocolError(): AcpProtocolError { + return { code: this.code, message: this.errorMessage, ...(this.data !== undefined ? { data: this.data } : {}), - }); + }; } } -export const AcpError = Schema.Union([ - AcpRequestError, - AcpSpawnError, - AcpProcessExitedError, - AcpProtocolParseError, - AcpTransportError, -]); +export type AcpError = + | AcpRequestError + | AcpSpawnError + | AcpProcessExitedError + | AcpProtocolParseError + | AcpTransportError; -export type AcpError = typeof AcpError.Type; +export function normalizeAcpError(error: unknown): AcpError { + if ( + Schema.is(AcpRequestError)(error) || + Schema.is(AcpSpawnError)(error) || + Schema.is(AcpProcessExitedError)(error) || + Schema.is(AcpProtocolParseError)(error) || + Schema.is(AcpTransportError)(error) + ) { + return error; + } + + if (Schema.is(RpcClientError.RpcClientError)(error)) { + return new AcpTransportError({ + detail: error.message, + cause: error, + }); + } + + if (isProtocolError(error)) { + return AcpRequestError.fromProtocolError(error); + } + + return new AcpTransportError({ + detail: error instanceof Error ? error.message : String(error), + ...(error !== undefined ? { cause: error } : {}), + }); +} + +function isProtocolError(value: unknown): value is AcpProtocolError { + return ( + typeof value === "object" && + value !== null && + "code" in value && + typeof value.code === "number" && + "message" in value && + typeof value.message === "string" + ); +} diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts index 8aaa0810cb..029ef4e67b 100644 --- a/packages/effect-acp/src/protocol.test.ts +++ b/packages/effect-acp/src/protocol.test.ts @@ -1,62 +1,37 @@ -import * as Path from "effect/Path"; -import * as AcpError from "./errors.ts"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as Queue from "effect/Queue"; -import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import * as Ref from "effect/Ref"; -import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import * as Sink from "effect/Sink"; +import * as Stdio from "effect/Stdio"; import { it, assert } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as AcpSchema from "./_generated/schema.gen.ts"; -import * as AcpProtocol from "./protocol.ts"; -import { - encodeJsonl, - jsonRpcNotification, - jsonRpcRequest, - jsonRpcResponse, -} from "./_internal/shared.ts"; -import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts"; +import * as AcpProtocol from "./protocol"; -const SessionCancelNotification = jsonRpcNotification( - "session/cancel", - AcpSchema.CancelNotification, -); -const SessionUpdateNotification = jsonRpcNotification( - "session/update", - AcpSchema.SessionNotification, -); -const ElicitationCompleteNotification = jsonRpcNotification( - "session/elicitation/complete", - AcpSchema.ElicitationCompleteNotification, -); -const RequestPermissionRequest = jsonRpcRequest( - "session/request_permission", - AcpSchema.RequestPermissionRequest, -); -const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse); -const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String })); -const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean })); +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); -const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) => - path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"), -); +function makeInMemoryStdio() { + return Effect.gen(function* () { + const input = yield* Queue.unbounded(); + const output = yield* Queue.unbounded(); -const makeHandle = (env?: Record) => - Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], { - cwd: path.join(import.meta.dirname, ".."), - shell: process.platform === "win32", - ...(env ? { env: { ...process.env, ...env } } : {}), - }); - return yield* spawner.spawn(command); + return { + stdio: Stdio.make({ + stdin: Stream.fromQueue(input), + stdout: Sink.forEach((chunk: string | Uint8Array) => + Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)), + ), + stderr: Sink.drain, + }), + input, + output, + }; }); +} it.layer(NodeServices.layer)("effect-acp protocol", (it) => { it.effect( @@ -71,56 +46,57 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { const notifications = yield* Deferred.make>(); - yield* transport.incoming.pipe( + yield* transport.notifications.incoming.pipe( Stream.take(2), Stream.runCollect, Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)), Effect.forkScoped, ); - yield* transport.notify("session/cancel", { sessionId: "session-1" }); + yield* transport.notifications.sendSessionCancel({ sessionId: "session-1" }); const outbound = yield* Queue.take(output); - assert.deepEqual( - yield* Schema.decodeEffect(Schema.fromJsonString(SessionCancelNotification))(outbound), - { - jsonrpc: "2.0", - method: "session/cancel", - params: { - sessionId: "session-1", - }, + assert.deepEqual(JSON.parse(outbound), { + jsonrpc: "2.0", + method: "session/cancel", + params: { + sessionId: "session-1", }, - ); + }); yield* Queue.offer( input, - yield* encodeJsonl(SessionUpdateNotification, { - jsonrpc: "2.0", - method: "session/update", - params: { - sessionId: "session-1", - update: { - sessionUpdate: "plan", - entries: [ - { - content: "Inspect repository", - priority: "high", - status: "in_progress", - }, - ], + encoder.encode( + `${JSON.stringify({ + jsonrpc: "2.0", + method: "session/update", + params: { + sessionId: "session-1", + update: { + sessionUpdate: "plan", + entries: [ + { + content: "Inspect repository", + priority: "high", + status: "in_progress", + }, + ], + }, }, - }, - }), + })}\n`, + ), ); yield* Queue.offer( input, - yield* encodeJsonl(ElicitationCompleteNotification, { - jsonrpc: "2.0", - method: "session/elicitation/complete", - params: { - elicitationId: "elicitation-1", - }, - }), + encoder.encode( + `${JSON.stringify({ + jsonrpc: "2.0", + method: "session/elicitation/complete", + params: { + elicitationId: "elicitation-1", + }, + })}\n`, + ), ); const [update, completion] = yield* Deferred.await(notifications); @@ -129,66 +105,6 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { }), ); - it.effect("logs outgoing notifications when logOutgoing is enabled", () => - Effect.gen(function* () { - const { stdio } = yield* makeInMemoryStdio(); - const events: Array = []; - const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio, - serverRequestMethods: new Set(), - logOutgoing: true, - logger: (event) => - Effect.sync(() => { - events.push(event); - }), - }); - - yield* transport.notify("session/cancel", { sessionId: "session-1" }); - - assert.deepEqual(events, [ - { - direction: "outgoing", - stage: "decoded", - payload: { - _tag: "Request", - id: "", - tag: "session/cancel", - payload: { - sessionId: "session-1", - }, - headers: [], - }, - }, - { - direction: "outgoing", - stage: "raw", - payload: - '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n', - }, - ]); - }), - ); - - it.effect("fails notification encoding through the declared ACP error channel", () => - Effect.gen(function* () { - const { stdio } = yield* makeInMemoryStdio(); - const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio, - serverRequestMethods: new Set(), - }); - - const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip); - assert.instanceOf(bigintError, AcpError.AcpProtocolParseError); - assert.equal(bigintError.detail, "Failed to encode ACP message"); - - const circular: Record = {}; - circular.self = circular; - const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip); - assert.instanceOf(circularError, AcpError.AcpProtocolParseError); - assert.equal(circularError.detail, "Failed to encode ACP message"); - }), - ); - it.effect("supports generic extension requests over the patched transport", () => Effect.gen(function* () { const { stdio, input, output } = yield* makeInMemoryStdio(); @@ -198,10 +114,10 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { }); const response = yield* transport - .request("x/test", { hello: "world" }) + .sendRequest("x/test", { hello: "world" }) .pipe(Effect.forkScoped); const outbound = yield* Queue.take(output); - assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), { + assert.deepEqual(JSON.parse(outbound), { jsonrpc: "2.0", id: 1, method: "x/test", @@ -213,236 +129,19 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { yield* Queue.offer( input, - yield* encodeJsonl(ExtResponse, { - jsonrpc: "2.0", - id: 1, - result: { - ok: true, - }, - }), + encoder.encode( + `${JSON.stringify({ + jsonrpc: "2.0", + id: 1, + result: { + ok: true, + }, + })}\n`, + ), ); const resolved = yield* Fiber.join(response); assert.deepEqual(resolved, { ok: true }); }), ); - - it.effect("preserves zero-valued ids for inbound core client requests", () => - Effect.gen(function* () { - const { stdio, input, output } = yield* makeInMemoryStdio(); - const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio, - serverRequestMethods: new Set(["session/request_permission"]), - }); - const inboundRequest = yield* Deferred.make(); - - yield* transport.serverProtocol - .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid)) - .pipe(Effect.forkScoped); - - yield* Queue.offer( - input, - yield* encodeJsonl(RequestPermissionRequest, { - jsonrpc: "2.0", - id: 0, - method: "session/request_permission", - params: { - sessionId: "session-1", - toolCall: { - toolCallId: "tool-1", - title: "Allow mock action", - }, - options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], - }, - headers: [], - }), - ); - - const message = yield* Deferred.await(inboundRequest); - assert.deepEqual(message, { - _tag: "Request", - id: "0", - tag: "session/request_permission", - payload: { - sessionId: "session-1", - toolCall: { - toolCallId: "tool-1", - title: "Allow mock action", - }, - options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], - }, - headers: [], - }); - - yield* transport.serverProtocol.send(0, { - _tag: "Exit", - requestId: "0", - exit: { - _tag: "Success", - value: { - outcome: { - outcome: "selected", - optionId: "allow", - }, - }, - }, - }); - - const outbound = yield* Queue.take(output); - assert.deepEqual( - yield* Schema.decodeEffect(Schema.fromJsonString(RequestPermissionResponse))(outbound), - { - jsonrpc: "2.0", - id: 0, - result: { - outcome: { - outcome: "selected", - optionId: "allow", - }, - }, - }, - ); - }), - ); - - it.effect("cleans up interrupted extension requests before a late response arrives", () => - Effect.gen(function* () { - const { stdio, input, output } = yield* makeInMemoryStdio(); - const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio, - serverRequestMethods: new Set(), - }); - const lateResponse = yield* Deferred.make(); - - yield* transport.clientProtocol - .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid)) - .pipe(Effect.forkScoped); - - const response = yield* transport - .request("x/test", { hello: "world" }) - .pipe(Effect.forkScoped); - const outbound = yield* Queue.take(output); - assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), { - jsonrpc: "2.0", - id: 1, - method: "x/test", - params: { - hello: "world", - }, - headers: [], - }); - - yield* Fiber.interrupt(response); - yield* Queue.offer( - input, - yield* encodeJsonl(ExtResponse, { - jsonrpc: "2.0", - id: 1, - result: { - ok: true, - }, - }), - ); - - const message = yield* Deferred.await(lateResponse); - assert.deepEqual(message, { - _tag: "Exit", - requestId: "1", - exit: { - _tag: "Success", - value: { - ok: true, - }, - }, - }); - }), - ); - - it.effect("propagates the real child exit code when the input stream ends", () => - Effect.gen(function* () { - const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" }); - const firstMessage = yield* Deferred.make(); - const termination = yield* Deferred.make(); - const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio: makeChildStdio(handle), - terminationError: makeTerminationError(handle), - serverRequestMethods: new Set(), - onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid), - }); - - yield* transport.clientProtocol - .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid)) - .pipe(Effect.forkScoped); - - const message = yield* Deferred.await(firstMessage); - const exitError = yield* Deferred.await(termination); - assert.instanceOf(exitError, AcpError.AcpProcessExitedError); - assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7); - assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError"); - const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as { - readonly _tag: string; - readonly cause: unknown; - }; - assert.equal(defect._tag, "RpcClientDefect"); - assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError); - assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7); - }), - ); - - it.effect("does not emit a second process-exit error after a decode failure", () => - Effect.gen(function* () { - const handle = yield* makeHandle({ - ACP_MOCK_MALFORMED_OUTPUT: "1", - ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23", - }); - const terminationCalls = yield* Ref.make(0); - const firstMessage = yield* Deferred.make(); - const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio: makeChildStdio(handle), - terminationError: makeTerminationError(handle), - serverRequestMethods: new Set(), - onTermination: () => Ref.update(terminationCalls, (count) => count + 1), - }); - - yield* transport.clientProtocol - .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid)) - .pipe(Effect.forkScoped); - - const message = yield* Deferred.await(firstMessage); - assert.equal(yield* Ref.get(terminationCalls), 1); - assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError"); - const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as { - readonly _tag: string; - readonly cause: unknown; - }; - assert.equal(defect._tag, "RpcClientDefect"); - assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError); - }), - ); - - it.effect("fails pending extension requests with the propagated exit code", () => - Effect.gen(function* () { - const { stdio, input, output } = yield* makeInMemoryStdio(); - const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ - stdio, - terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })), - serverRequestMethods: new Set(), - }); - - const response = yield* transport - .request("x/test", { hello: "world" }) - .pipe(Effect.forkScoped); - yield* Queue.take(output); - yield* Queue.end(input); - - const error = yield* Fiber.join(response).pipe( - Effect.match({ - onFailure: (error) => error, - onSuccess: () => assert.fail("Expected request to fail after process exit"), - }), - ); - assert.instanceOf(error, AcpError.AcpProcessExitedError); - assert.equal(error.code, 0); - }), - ); }); diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.ts index 204cf979c3..d103babb1e 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -13,15 +13,9 @@ import * as RpcMessage from "effect/unstable/rpc/RpcMessage"; import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"; import * as RpcServer from "effect/unstable/rpc/RpcServer"; -import * as AcpSchema from "./_generated/schema.gen.ts"; -import { CLIENT_METHODS } from "./_generated/meta.gen.ts"; -import * as AcpError from "./errors.ts"; - -export interface AcpProtocolLogEvent { - readonly direction: "incoming" | "outgoing"; - readonly stage: "raw" | "decoded" | "decode_failed"; - readonly payload: unknown; -} +import * as AcpSchema from "./_generated/schema.gen"; +import { CLIENT_METHODS } from "./_generated/meta.gen"; +import * as AcpError from "./errors"; export type AcpIncomingNotification = | { @@ -29,6 +23,11 @@ export type AcpIncomingNotification = readonly method: typeof CLIENT_METHODS.session_update; readonly params: typeof AcpSchema.SessionNotification.Type; } + | { + readonly _tag: "SessionCancel"; + readonly method: "session/cancel"; + readonly params: typeof AcpSchema.CancelNotification.Type; + } | { readonly _tag: "ElicitationComplete"; readonly method: typeof CLIENT_METHODS.session_elicitation_complete; @@ -42,470 +41,419 @@ export type AcpIncomingNotification = export interface AcpPatchedProtocolOptions { readonly stdio: Stdio.Stdio; - readonly terminationError?: Effect.Effect; readonly serverRequestMethods: ReadonlySet; - readonly logIncoming?: boolean; - readonly logOutgoing?: boolean; - readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect; readonly onNotification?: ( notification: AcpIncomingNotification, - ) => Effect.Effect; + ) => Effect.Effect; readonly onExtRequest?: ( method: string, params: unknown, - ) => Effect.Effect; - readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect; + ) => Effect.Effect; + readonly onProcessExit?: (error: AcpError.AcpProcessExitedError) => Effect.Effect; } export interface AcpPatchedProtocol { readonly clientProtocol: RpcClient.Protocol["Service"]; readonly serverProtocol: RpcServer.Protocol["Service"]; - readonly incoming: Stream.Stream; - readonly request: (method: string, payload: unknown) => Effect.Effect; - readonly notify: (method: string, payload: unknown) => Effect.Effect; + readonly notifications: { + readonly incoming: Stream.Stream; + readonly sendSessionCancel: ( + payload: typeof AcpSchema.CancelNotification.Type, + ) => Effect.Effect; + readonly sendExtNotification: ( + method: string, + payload: unknown, + ) => Effect.Effect; + }; + readonly sendRequest: ( + method: string, + payload: unknown, + ) => Effect.Effect; } const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification); +const decodeSessionCancel = Schema.decodeUnknownEffect(AcpSchema.CancelNotification); const decodeElicitationComplete = Schema.decodeUnknownEffect( AcpSchema.ElicitationCompleteNotification, ); const parserFactory = RpcSerialization.ndJsonRpc(); -export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* ( +export const makeAcpPatchedProtocol = ( options: AcpPatchedProtocolOptions, -): Effect.fn.Return { - const parser = parserFactory.makeUnsafe(); - const serverQueue = yield* Queue.unbounded(); - const clientQueue = yield* Queue.unbounded(); - const notificationQueue = yield* Queue.unbounded(); - const disconnects = yield* Queue.unbounded(); - const outgoing = yield* Queue.unbounded>(); - const nextRequestId = yield* Ref.make(1n); - const terminationHandled = yield* Ref.make(false); - const extPending = yield* Ref.make( - new Map>(), - ); - - const logProtocol = (event: AcpProtocolLogEvent) => { - if (event.direction === "incoming" && !options.logIncoming) { - return Effect.void; - } - if (event.direction === "outgoing" && !options.logOutgoing) { - return Effect.void; - } - return ( - options.logger?.(event) ?? - Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event })) - ); - }; - - const offerOutgoing = Effect.fn("offerOutgoing")(function* ( - message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, - ) { - yield* logProtocol({ - direction: "outgoing", - stage: "decoded", - payload: message, - }); - - const encoded = yield* Effect.try({ - try: () => parser.encode(message), - catch: (cause) => - new AcpError.AcpProtocolParseError({ - detail: "Failed to encode ACP message", - cause, - }), - }); - - if (encoded) { - yield* logProtocol({ - direction: "outgoing", - stage: "raw", - payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded), - }); - - yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid); - } - }); - - const resolveExtPending = ( - requestId: string, - onFound: (deferred: Deferred.Deferred) => Effect.Effect, - ) => - Ref.modify(extPending, (pending) => { - const deferred = pending.get(requestId); - if (!deferred) { - return [Effect.void, pending] as const; - } - const next = new Map(pending); - next.delete(requestId); - return [onFound(deferred), next] as const; - }).pipe(Effect.flatten); - - const removeExtPending = (requestId: string) => - Ref.update(extPending, (pending) => { - if (!pending.has(requestId)) { - return pending; - } - const next = new Map(pending); - next.delete(requestId); - return next; - }); - - const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) => - resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error)); - - const completeExtPendingSuccess = (requestId: string, value: unknown) => - resolveExtPending(requestId, (deferred) => Deferred.succeed(deferred, value)); - - const failAllExtPending = (error: AcpError.AcpError) => - Ref.getAndSet(extPending, new Map()).pipe( - Effect.flatMap((pending) => - Effect.forEach([...pending.values()], (deferred) => Deferred.fail(deferred, error), { - discard: true, - }), - ), +): Effect.Effect => + Effect.gen(function* () { + const parser = parserFactory.makeUnsafe(); + const serverQueue = yield* Queue.unbounded(); + const clientQueue = yield* Queue.unbounded(); + const notificationQueue = yield* Queue.unbounded(); + const disconnects = yield* Queue.unbounded(); + const outgoing = yield* Queue.unbounded>(); + const nextRequestId = yield* Ref.make(1n); + const extPending = yield* Ref.make( + new Map>(), ); - const dispatchNotification = (notification: AcpIncomingNotification) => - Queue.offer(notificationQueue, notification).pipe( - Effect.andThen( - options.onNotification - ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void)) - : Effect.void, - ), - Effect.asVoid, - ); - - const emitClientProtocolError = (error: AcpError.AcpError) => - Queue.offer(clientQueue, { - _tag: "ClientProtocolError", - error: new RpcClientError.RpcClientError({ - reason: new RpcClientError.RpcClientDefect({ - message: error.message, - cause: error, - }), - }), - }).pipe(Effect.asVoid); - - const handleTermination = (classify: () => Effect.Effect) => - Ref.modify(terminationHandled, (handled) => { - if (handled) { - return [Effect.void, true] as const; - } - return [ - Effect.gen(function* () { - yield* Queue.offer(disconnects, 0); - const error = yield* classify(); - if (!error) { - return; - } - yield* failAllExtPending(error); - yield* emitClientProtocolError(error); - if (options.onTermination) { - yield* options.onTermination(error); - } - }), - true, - ] as const; - }).pipe(Effect.flatten); - - const respondWithSuccess = (requestId: string, value: unknown) => - offerOutgoing({ - _tag: "Exit", - requestId, - exit: { - _tag: "Success", - value, - }, - }); - - const respondWithError = (requestId: string, error: AcpError.AcpRequestError) => - offerOutgoing({ - _tag: "Exit", - requestId, - exit: { - _tag: "Failure", - cause: [ - { - _tag: "Fail", - error: error.toProtocolError(), - }, - ], - }, - }); - - const handleExtRequest = (message: RpcMessage.RequestEncoded) => { - if (!options.onExtRequest) { - return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag)); - } - return options.onExtRequest(message.tag, message.payload).pipe( - Effect.matchEffect({ - onFailure: (error) => respondWithError(message.id, normalizeToRequestError(error)), - onSuccess: (value) => respondWithSuccess(message.id, value), - }), - ); - }; - - const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => { - if (message.id === "") { - if (message.tag === CLIENT_METHODS.session_update) { - return decodeSessionUpdate(message.payload).pipe( - Effect.map( - (params) => - ({ - _tag: "SessionUpdate", - method: CLIENT_METHODS.session_update, - params, - }) satisfies AcpIncomingNotification, - ), - Effect.mapError( - (cause) => - new AcpError.AcpProtocolParseError({ - detail: `Invalid ${CLIENT_METHODS.session_update} notification payload`, - cause, - }), - ), - Effect.flatMap(dispatchNotification), - ); - } - if (message.tag === CLIENT_METHODS.session_elicitation_complete) { - return decodeElicitationComplete(message.payload).pipe( - Effect.map( - (params) => - ({ - _tag: "ElicitationComplete", - method: CLIENT_METHODS.session_elicitation_complete, - params, - }) satisfies AcpIncomingNotification, - ), - Effect.mapError( - (cause) => - new AcpError.AcpProtocolParseError({ - detail: `Invalid ${CLIENT_METHODS.session_elicitation_complete} notification payload`, - cause, - }), - ), - Effect.flatMap(dispatchNotification), - ); - } - return dispatchNotification({ - _tag: "ExtNotification", - method: message.tag, - params: message.payload, - }); - } - - if (!options.serverRequestMethods.has(message.tag)) { - return handleExtRequest(message).pipe( - Effect.catch(() => respondWithError(message.id, AcpError.AcpRequestError.internalError())), - Effect.asVoid, - ); - } - - return Queue.offer(serverQueue, message).pipe(Effect.asVoid); - }; - - const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) => - Ref.get(extPending).pipe( - Effect.flatMap((pending) => { - if (!pending.has(message.requestId)) { - return Queue.offer(clientQueue, message).pipe(Effect.asVoid); - } - if (message.exit._tag === "Success") { - return completeExtPendingSuccess(message.requestId, message.exit.value); - } - const failure = message.exit.cause.find((entry) => entry._tag === "Fail"); - if (failure && isProtocolError(failure.error)) { - return completeExtPendingFailure( - message.requestId, - AcpError.AcpRequestError.fromProtocolError(failure.error), - ); - } - return completeExtPendingFailure( - message.requestId, - AcpError.AcpRequestError.internalError("Extension request failed"), - ); - }), - ); - - const routeDecodedMessage = ( - message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, - ): Effect.Effect => { - switch (message._tag) { - case "Request": - return handleRequestEncoded(message); - case "Exit": - return handleExitEncoded(message); - case "Chunk": - return Ref.get(extPending).pipe( - Effect.flatMap((pending) => - pending.has(message.requestId) - ? completeExtPendingFailure( - message.requestId, - AcpError.AcpRequestError.internalError( - "Streaming extension responses are not supported", - ), - ) - : Queue.offer(clientQueue, message).pipe(Effect.asVoid), - ), - ); - case "Defect": - case "ClientProtocolError": - case "Pong": - return Queue.offer(clientQueue, message).pipe(Effect.asVoid); - case "Ack": - case "Interrupt": - case "Ping": - case "Eof": - return Queue.offer(serverQueue, message).pipe(Effect.asVoid); - } - }; - - yield* options.stdio.stdin.pipe( - Stream.runForEach((data) => - logProtocol({ - direction: "incoming", - stage: "raw", - payload: typeof data === "string" ? data : new TextDecoder().decode(data), + const offerOutgoing = (message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded) => + Effect.try({ + try: () => parser.encode(message), + catch: (cause) => + new AcpError.AcpProtocolParseError({ + detail: "Failed to encode ACP message", + cause, + }), }).pipe( - Effect.flatMap(() => - Effect.try({ - try: () => - parser.decode(data) as ReadonlyArray< - RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded - >, - catch: (cause) => - new AcpError.AcpProtocolParseError({ - detail: "Failed to decode ACP wire message", - cause, - }), - }), + Effect.flatMap((encoded) => + encoded === undefined ? Effect.void : Queue.offer(outgoing, encoded).pipe(Effect.asVoid), ), - Effect.tap((messages) => - logProtocol({ - direction: "incoming", - stage: "decoded", - payload: messages, - }), - ), - Effect.tapErrorTag("AcpProtocolParseError", (error) => - logProtocol({ - direction: "incoming", - stage: "decode_failed", - payload: { - detail: error.detail, - cause: error.cause, - }, - }), - ), - Effect.flatMap((messages) => - Effect.forEach(messages, routeDecodedMessage, { + ); + + const resolveExtPending = ( + requestId: string, + onFound: (deferred: Deferred.Deferred) => Effect.Effect, + ) => + Ref.modify(extPending, (pending) => { + const deferred = pending.get(requestId); + if (!deferred) { + return [Effect.void, pending] as const; + } + const next = new Map(pending); + next.delete(requestId); + return [onFound(deferred), next] as const; + }).pipe(Effect.flatten); + + const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) => + resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error)); + + const completeExtPendingSuccess = (requestId: string, value: unknown) => + resolveExtPending(requestId, (deferred) => Deferred.succeed(deferred, value)); + + const failAllExtPending = (error: AcpError.AcpError) => + Ref.get(extPending).pipe( + Effect.flatMap((pending) => + Effect.forEach([...pending.values()], (deferred) => Deferred.fail(deferred, error), { discard: true, }), ), - ), - ), - Effect.matchEffect({ - onFailure: (error) => { - const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error) - ? error - : new AcpError.AcpTransportError({ - detail: error instanceof Error ? error.message : String(error), - cause: error, - }); - return handleTermination(() => Effect.succeed(normalized)); - }, - onSuccess: () => - handleTermination( - () => - options.terminationError ?? - Effect.succeed( - new AcpError.AcpTransportError({ - detail: "ACP input stream ended", - cause: new Error("ACP input stream ended"), - }), - ), + Effect.andThen(Ref.set(extPending, new Map())), + ); + + const dispatchNotification = (notification: AcpIncomingNotification) => + Queue.offer(notificationQueue, notification).pipe( + Effect.andThen( + options.onNotification + ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void)) + : Effect.void, ), - }), - Effect.forkScoped, - ); + Effect.asVoid, + ); - yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped); + const respondWithSuccess = (requestId: string, value: unknown) => + offerOutgoing({ + _tag: "Exit", + requestId, + exit: { + _tag: "Success", + value, + }, + }); - const clientProtocol = RpcClient.Protocol.of({ - run: (_clientId, f) => - Stream.fromQueue(clientQueue).pipe( - Stream.runForEach((message) => f(message)), - Effect.forever, + const respondWithError = (requestId: string, error: AcpError.AcpRequestError) => + offerOutgoing({ + _tag: "Exit", + requestId, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: error.toProtocolError(), + }, + ], + }, + }); + + const handleExtRequest = (message: RpcMessage.RequestEncoded) => { + if (!options.onExtRequest) { + return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag)); + } + return options.onExtRequest(message.tag, message.payload).pipe( + Effect.matchEffect({ + onFailure: (error) => respondWithError(message.id, normalizeToRequestError(error)), + onSuccess: (value) => respondWithSuccess(message.id, value), + }), + ); + }; + + const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => { + if (message.id === "") { + if (message.tag === CLIENT_METHODS.session_update) { + return decodeSessionUpdate(message.payload).pipe( + Effect.map( + (params) => + ({ + _tag: "SessionUpdate", + method: CLIENT_METHODS.session_update, + params, + }) satisfies AcpIncomingNotification, + ), + Effect.mapError( + (cause) => + new AcpError.AcpProtocolParseError({ + detail: `Invalid ${CLIENT_METHODS.session_update} notification payload`, + cause, + }), + ), + Effect.flatMap(dispatchNotification), + ); + } + if (message.tag === "session/cancel") { + return decodeSessionCancel(message.payload).pipe( + Effect.map( + (params) => + ({ + _tag: "SessionCancel", + method: "session/cancel", + params, + }) satisfies AcpIncomingNotification, + ), + Effect.mapError( + (cause) => + new AcpError.AcpProtocolParseError({ + detail: "Invalid session/cancel notification payload", + cause, + }), + ), + Effect.flatMap(dispatchNotification), + ); + } + if (message.tag === CLIENT_METHODS.session_elicitation_complete) { + return decodeElicitationComplete(message.payload).pipe( + Effect.map( + (params) => + ({ + _tag: "ElicitationComplete", + method: CLIENT_METHODS.session_elicitation_complete, + params, + }) satisfies AcpIncomingNotification, + ), + Effect.mapError( + (cause) => + new AcpError.AcpProtocolParseError({ + detail: `Invalid ${CLIENT_METHODS.session_elicitation_complete} notification payload`, + cause, + }), + ), + Effect.flatMap(dispatchNotification), + ); + } + return dispatchNotification({ + _tag: "ExtNotification", + method: message.tag, + params: message.payload, + }); + } + + if (!options.serverRequestMethods.has(message.tag)) { + return handleExtRequest(message).pipe( + Effect.catch(() => + respondWithError(message.id, AcpError.AcpRequestError.internalError()), + ), + Effect.asVoid, + ); + } + + return Queue.offer(serverQueue, message).pipe(Effect.asVoid); + }; + + const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) => + Ref.get(extPending).pipe( + Effect.flatMap((pending) => { + if (!pending.has(message.requestId)) { + return Queue.offer(clientQueue, message).pipe(Effect.asVoid); + } + if (message.exit._tag === "Success") { + return completeExtPendingSuccess(message.requestId, message.exit.value); + } + const failure = message.exit.cause.find((entry) => entry._tag === "Fail"); + if (failure && isProtocolError(failure.error)) { + return completeExtPendingFailure( + message.requestId, + AcpError.AcpRequestError.fromProtocolError(failure.error), + ); + } + return completeExtPendingFailure( + message.requestId, + AcpError.AcpRequestError.internalError("Extension request failed"), + ); + }), + ); + + const routeDecodedMessage = ( + message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, + ): Effect.Effect => { + switch (message._tag) { + case "Request": + return handleRequestEncoded(message); + case "Exit": + return handleExitEncoded(message); + case "Chunk": + return Ref.get(extPending).pipe( + Effect.flatMap((pending) => + pending.has(message.requestId) + ? completeExtPendingFailure( + message.requestId, + AcpError.AcpRequestError.internalError( + "Streaming extension responses are not supported", + ), + ) + : Queue.offer(clientQueue, message).pipe(Effect.asVoid), + ), + ); + case "Defect": + case "ClientProtocolError": + case "Pong": + return Queue.offer(clientQueue, message).pipe(Effect.asVoid); + case "Ack": + case "Interrupt": + case "Ping": + case "Eof": + return Queue.offer(serverQueue, message).pipe(Effect.asVoid); + } + }; + + yield* options.stdio.stdin.pipe( + Stream.runForEach((data) => + Effect.try({ + try: () => + parser.decode(data) as ReadonlyArray< + RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded + >, + catch: (cause) => + new AcpError.AcpProtocolParseError({ + detail: "Failed to decode ACP wire message", + cause, + }), + }).pipe( + Effect.flatMap((messages) => + Effect.forEach(messages, routeDecodedMessage, { + discard: true, + }), + ), + ), ), - send: (_clientId, request) => offerOutgoing(request).pipe(Effect.mapError(toRpcClientError)), - supportsAck: true, - supportsTransferables: false, - }); - - const serverProtocol = RpcServer.Protocol.of({ - run: (f) => - Stream.fromQueue(serverQueue).pipe( - Stream.runForEach((message) => f(0, message)), - Effect.forever, + Effect.catch((error) => { + const normalized = AcpError.normalizeAcpError(error); + const rpcClientError = new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: normalized.message, + cause: normalized, + }), + }); + return Queue.offer(clientQueue, { + _tag: "ClientProtocolError", + error: rpcClientError, + }).pipe(Effect.asVoid); + }), + Effect.ensuring( + Effect.gen(function* () { + const error = new AcpError.AcpProcessExitedError({}); + yield* Queue.offer(disconnects, 0); + yield* failAllExtPending(error); + yield* Queue.offer(clientQueue, { + _tag: "ClientProtocolError", + error: new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: error.message, + cause: error, + }), + }), + }); + if (options.onProcessExit) { + yield* options.onProcessExit(error); + } + }), ), - disconnects, - send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie), - end: (_clientId) => Queue.end(outgoing), - clientIds: Effect.succeed(new Set([0])), - initialMessage: Effect.succeedNone, - supportsAck: true, - supportsTransferables: false, - supportsSpanPropagation: true, - }); + Effect.forkScoped, + ); - const sendNotification = Effect.fn("sendNotification")(function* ( - method: string, - payload: unknown, - ) { - yield* offerOutgoing({ - _tag: "Request", - id: "", - tag: method, - payload, - headers: [], + yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout), Effect.forkScoped); + + const clientProtocol = RpcClient.Protocol.of({ + run: (f) => + Stream.fromQueue(clientQueue).pipe( + Stream.runForEach((message) => f(message)), + Effect.forever, + ), + send: (request) => offerOutgoing(request).pipe(Effect.mapError(toRpcClientError)), + supportsAck: true, + supportsTransferables: false, }); - }); - const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) { - const requestId = yield* Ref.modify( - nextRequestId, - (current) => [current, current + 1n] as const, - ); - const deferred = yield* Deferred.make(); - yield* Ref.update(extPending, (pending) => new Map(pending).set(String(requestId), deferred)); - yield* offerOutgoing({ - _tag: "Request", - id: String(requestId), - tag: method, - payload, - headers: [], - }).pipe( - Effect.catch((error) => - removeExtPending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))), - ), - ); - return yield* Deferred.await(deferred).pipe( - Effect.onInterrupt(() => removeExtPending(String(requestId))), - ); - }); + const serverProtocol = RpcServer.Protocol.of({ + run: (f) => + Stream.fromQueue(serverQueue).pipe( + Stream.runForEach((message) => f(0, message)), + Effect.forever, + ), + disconnects, + send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie), + end: () => Queue.end(outgoing).pipe(Effect.orDie), + clientIds: Effect.succeed(new Set([0])), + initialMessage: Effect.succeedNone, + supportsAck: true, + supportsTransferables: false, + supportsSpanPropagation: true, + }); - return { - clientProtocol, - serverProtocol, - get incoming() { - return Stream.fromQueue(notificationQueue); - }, - request: sendRequest, - notify: sendNotification, - } satisfies AcpPatchedProtocol; -}); + const sendNotification = (method: string, payload: unknown) => + Queue.offer( + outgoing, + `${JSON.stringify({ + jsonrpc: "2.0", + method, + ...(payload !== undefined ? { params: payload } : {}), + })}\n`, + ).pipe(Effect.asVoid, Effect.mapError(AcpError.normalizeAcpError)); + + const sendRequest = (method: string, payload: unknown) => + Effect.gen(function* () { + const requestId = yield* Ref.modify( + nextRequestId, + (current) => [current, current + 1n] as const, + ); + const deferred = yield* Deferred.make(); + yield* Ref.update(extPending, (pending) => + new Map(pending).set(String(requestId), deferred), + ); + yield* offerOutgoing({ + _tag: "Request", + id: String(requestId), + tag: method, + payload, + headers: [], + }).pipe( + Effect.catch((error) => + Ref.update(extPending, (pending) => { + const next = new Map(pending); + next.delete(String(requestId)); + return next; + }).pipe(Effect.andThen(Effect.fail(error))), + ), + ); + return yield* Deferred.await(deferred); + }); + + return { + clientProtocol, + serverProtocol, + notifications: { + incoming: Stream.fromQueue(notificationQueue), + sendSessionCancel: (payload) => sendNotification("session/cancel", payload), + sendExtNotification: sendNotification, + }, + sendRequest, + } satisfies AcpPatchedProtocol; + }); function isProtocolError( value: unknown, @@ -520,10 +468,11 @@ function isProtocolError( ); } -function normalizeToRequestError(error: AcpError.AcpError): AcpError.AcpRequestError { - return Schema.is(AcpError.AcpRequestError)(error) - ? error - : AcpError.AcpRequestError.internalError(error.message); +function normalizeToRequestError(error: unknown): AcpError.AcpRequestError { + const normalized = AcpError.normalizeAcpError(error); + return Schema.is(AcpError.AcpRequestError)(normalized) + ? normalized + : AcpError.AcpRequestError.internalError(normalized.message); } function toRpcClientError(error: AcpError.AcpError): RpcClientError.RpcClientError { diff --git a/packages/effect-acp/src/rpc.ts b/packages/effect-acp/src/rpc.ts index 93d903e787..c3faa3847f 100644 --- a/packages/effect-acp/src/rpc.ts +++ b/packages/effect-acp/src/rpc.ts @@ -1,133 +1,130 @@ +import * as Schema from "effect/Schema"; import * as Rpc from "effect/unstable/rpc/Rpc"; import * as RpcGroup from "effect/unstable/rpc/RpcGroup"; -import * as AcpSchema from "./_generated/schema.gen.ts"; -import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts"; +import * as AcpSchema from "./_generated/schema.gen"; +import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen"; -export const InitializeRpc = Rpc.make(AGENT_METHODS.initialize, { +function makeAcpRpc< + const Tag extends string, + Payload extends Schema.Top | Schema.Struct.Fields, + Success extends Schema.Top, +>(tag: Tag, options: { readonly payload: Payload; readonly success: Success }) { + return Rpc.make(tag, { + payload: options.payload, + success: options.success, + error: AcpSchema.Error, + }); +} + +export const InitializeRpc = makeAcpRpc(AGENT_METHODS.initialize, { payload: AcpSchema.InitializeRequest, success: AcpSchema.InitializeResponse, - error: AcpSchema.Error, }); -export const AuthenticateRpc = Rpc.make(AGENT_METHODS.authenticate, { +export const AuthenticateRpc = makeAcpRpc(AGENT_METHODS.authenticate, { payload: AcpSchema.AuthenticateRequest, success: AcpSchema.AuthenticateResponse, - error: AcpSchema.Error, }); -export const LogoutRpc = Rpc.make(AGENT_METHODS.logout, { +export const LogoutRpc = makeAcpRpc(AGENT_METHODS.logout, { payload: AcpSchema.LogoutRequest, success: AcpSchema.LogoutResponse, - error: AcpSchema.Error, }); -export const NewSessionRpc = Rpc.make(AGENT_METHODS.session_new, { +export const NewSessionRpc = makeAcpRpc(AGENT_METHODS.session_new, { payload: AcpSchema.NewSessionRequest, success: AcpSchema.NewSessionResponse, - error: AcpSchema.Error, }); -export const LoadSessionRpc = Rpc.make(AGENT_METHODS.session_load, { +export const LoadSessionRpc = makeAcpRpc(AGENT_METHODS.session_load, { payload: AcpSchema.LoadSessionRequest, success: AcpSchema.LoadSessionResponse, - error: AcpSchema.Error, }); -export const ListSessionsRpc = Rpc.make(AGENT_METHODS.session_list, { +export const ListSessionsRpc = makeAcpRpc(AGENT_METHODS.session_list, { payload: AcpSchema.ListSessionsRequest, success: AcpSchema.ListSessionsResponse, - error: AcpSchema.Error, }); -export const ForkSessionRpc = Rpc.make(AGENT_METHODS.session_fork, { +export const ForkSessionRpc = makeAcpRpc(AGENT_METHODS.session_fork, { payload: AcpSchema.ForkSessionRequest, success: AcpSchema.ForkSessionResponse, - error: AcpSchema.Error, }); -export const ResumeSessionRpc = Rpc.make(AGENT_METHODS.session_resume, { +export const ResumeSessionRpc = makeAcpRpc(AGENT_METHODS.session_resume, { payload: AcpSchema.ResumeSessionRequest, success: AcpSchema.ResumeSessionResponse, - error: AcpSchema.Error, }); -export const CloseSessionRpc = Rpc.make(AGENT_METHODS.session_close, { +export const CloseSessionRpc = makeAcpRpc(AGENT_METHODS.session_close, { payload: AcpSchema.CloseSessionRequest, success: AcpSchema.CloseSessionResponse, - error: AcpSchema.Error, }); -export const PromptRpc = Rpc.make(AGENT_METHODS.session_prompt, { +export const SetSessionModeRpc = makeAcpRpc(AGENT_METHODS.session_set_mode, { + payload: AcpSchema.SetSessionModeRequest, + success: AcpSchema.SetSessionModeResponse, +}); + +export const PromptRpc = makeAcpRpc(AGENT_METHODS.session_prompt, { payload: AcpSchema.PromptRequest, success: AcpSchema.PromptResponse, - error: AcpSchema.Error, }); -export const SetSessionModelRpc = Rpc.make(AGENT_METHODS.session_set_model, { +export const SetSessionModelRpc = makeAcpRpc(AGENT_METHODS.session_set_model, { payload: AcpSchema.SetSessionModelRequest, success: AcpSchema.SetSessionModelResponse, - error: AcpSchema.Error, }); -export const SetSessionConfigOptionRpc = Rpc.make(AGENT_METHODS.session_set_config_option, { +export const SetSessionConfigOptionRpc = makeAcpRpc(AGENT_METHODS.session_set_config_option, { payload: AcpSchema.SetSessionConfigOptionRequest, success: AcpSchema.SetSessionConfigOptionResponse, - error: AcpSchema.Error, }); -export const ReadTextFileRpc = Rpc.make(CLIENT_METHODS.fs_read_text_file, { +export const ReadTextFileRpc = makeAcpRpc(CLIENT_METHODS.fs_read_text_file, { payload: AcpSchema.ReadTextFileRequest, success: AcpSchema.ReadTextFileResponse, - error: AcpSchema.Error, }); -export const WriteTextFileRpc = Rpc.make(CLIENT_METHODS.fs_write_text_file, { +export const WriteTextFileRpc = makeAcpRpc(CLIENT_METHODS.fs_write_text_file, { payload: AcpSchema.WriteTextFileRequest, success: AcpSchema.WriteTextFileResponse, - error: AcpSchema.Error, }); -export const RequestPermissionRpc = Rpc.make(CLIENT_METHODS.session_request_permission, { +export const RequestPermissionRpc = makeAcpRpc(CLIENT_METHODS.session_request_permission, { payload: AcpSchema.RequestPermissionRequest, success: AcpSchema.RequestPermissionResponse, - error: AcpSchema.Error, }); -export const ElicitationRpc = Rpc.make(CLIENT_METHODS.session_elicitation, { +export const ElicitationRpc = makeAcpRpc(CLIENT_METHODS.session_elicitation, { payload: AcpSchema.ElicitationRequest, success: AcpSchema.ElicitationResponse, - error: AcpSchema.Error, }); -export const CreateTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_create, { +export const CreateTerminalRpc = makeAcpRpc(CLIENT_METHODS.terminal_create, { payload: AcpSchema.CreateTerminalRequest, success: AcpSchema.CreateTerminalResponse, - error: AcpSchema.Error, }); -export const TerminalOutputRpc = Rpc.make(CLIENT_METHODS.terminal_output, { +export const TerminalOutputRpc = makeAcpRpc(CLIENT_METHODS.terminal_output, { payload: AcpSchema.TerminalOutputRequest, success: AcpSchema.TerminalOutputResponse, - error: AcpSchema.Error, }); -export const ReleaseTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_release, { +export const ReleaseTerminalRpc = makeAcpRpc(CLIENT_METHODS.terminal_release, { payload: AcpSchema.ReleaseTerminalRequest, success: AcpSchema.ReleaseTerminalResponse, - error: AcpSchema.Error, }); -export const WaitForTerminalExitRpc = Rpc.make(CLIENT_METHODS.terminal_wait_for_exit, { +export const WaitForTerminalExitRpc = makeAcpRpc(CLIENT_METHODS.terminal_wait_for_exit, { payload: AcpSchema.WaitForTerminalExitRequest, success: AcpSchema.WaitForTerminalExitResponse, - error: AcpSchema.Error, }); -export const KillTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_kill, { +export const KillTerminalRpc = makeAcpRpc(CLIENT_METHODS.terminal_kill, { payload: AcpSchema.KillTerminalRequest, success: AcpSchema.KillTerminalResponse, - error: AcpSchema.Error, }); export const AgentRpcs = RpcGroup.make( @@ -140,6 +137,7 @@ export const AgentRpcs = RpcGroup.make( ForkSessionRpc, ResumeSessionRpc, CloseSessionRpc, + SetSessionModeRpc, PromptRpc, SetSessionModelRpc, SetSessionConfigOptionRpc, @@ -156,3 +154,6 @@ export const ClientRpcs = RpcGroup.make( WaitForTerminalExitRpc, KillTerminalRpc, ); + +export const ClientRequestMethodSet = new Set(ClientRpcs.requests.keys()); +export const AgentRequestMethodSet = new Set(AgentRpcs.requests.keys()); diff --git a/packages/effect-acp/src/server.ts b/packages/effect-acp/src/server.ts new file mode 100644 index 0000000000..36e9d39421 --- /dev/null +++ b/packages/effect-acp/src/server.ts @@ -0,0 +1,135 @@ +import * as Effect from "effect/Effect"; + +import * as AcpSchema from "./_generated/schema.gen"; +import { CLIENT_METHODS } from "./_generated/meta.gen"; +import type * as AcpError from "./errors"; +import type * as AcpProtocol from "./protocol"; +import * as AcpTerminal from "./terminal"; + +export interface AcpServerConnection { + /** + * Sends a `session/update` notification to the client. + * @see https://agentclientprotocol.com/protocol/schema#session/update + */ + readonly sessionUpdate: ( + payload: AcpSchema.SessionNotification, + ) => Effect.Effect; + /** + * Requests client permission for an operation. + * @see https://agentclientprotocol.com/protocol/schema#session/request_permission + */ + readonly requestPermission: ( + payload: AcpSchema.RequestPermissionRequest, + ) => Effect.Effect; + /** + * Requests structured user input from the client. + * @see https://agentclientprotocol.com/protocol/schema#session/elicitation + */ + readonly elicit: ( + payload: AcpSchema.ElicitationRequest, + ) => Effect.Effect; + /** + * Requests file contents from the client. + * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file + */ + readonly readTextFile: ( + payload: AcpSchema.ReadTextFileRequest, + ) => Effect.Effect; + /** + * Writes a text file through the client. + * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file + */ + readonly writeTextFile: ( + payload: AcpSchema.WriteTextFileRequest, + ) => Effect.Effect; + /** + * Creates a terminal on the client side. + * @see https://agentclientprotocol.com/protocol/schema#terminal/create + */ + readonly createTerminal: ( + payload: AcpSchema.CreateTerminalRequest, + ) => Effect.Effect; + /** + * Sends an ACP extension request. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly extRequest: ( + method: string, + payload: unknown, + ) => Effect.Effect; + /** + * Sends a `session/elicitation/complete` notification to the client. + * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete + */ + readonly elicitationComplete: ( + payload: AcpSchema.ElicitationCompleteNotification, + ) => Effect.Effect; + /** + * Sends an ACP extension notification. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly extNotification: ( + method: string, + payload: unknown, + ) => Effect.Effect; +} + +export const makeAcpServerConnection = ( + transport: AcpProtocol.AcpPatchedProtocol, +): AcpServerConnection => { + const request = (method: string, payload: unknown) => + transport.sendRequest(method, payload).pipe(Effect.map((value) => value as A)); + + return { + sessionUpdate: (payload) => + transport.notifications.sendExtNotification(CLIENT_METHODS.session_update, payload), + requestPermission: (payload) => + request( + CLIENT_METHODS.session_request_permission, + payload, + ), + elicit: (payload) => + request(CLIENT_METHODS.session_elicitation, payload), + readTextFile: (payload) => + request(CLIENT_METHODS.fs_read_text_file, payload), + writeTextFile: (payload) => + request(CLIENT_METHODS.fs_write_text_file, payload).pipe( + Effect.map((response) => response ?? {}), + ), + createTerminal: (payload) => + request(CLIENT_METHODS.terminal_create, payload).pipe( + Effect.map((response) => + AcpTerminal.makeTerminal({ + sessionId: payload.sessionId, + terminalId: response.terminalId, + output: request(CLIENT_METHODS.terminal_output, { + sessionId: payload.sessionId, + terminalId: response.terminalId, + }), + waitForExit: request( + CLIENT_METHODS.terminal_wait_for_exit, + { + sessionId: payload.sessionId, + terminalId: response.terminalId, + }, + ), + kill: request(CLIENT_METHODS.terminal_kill, { + sessionId: payload.sessionId, + terminalId: response.terminalId, + }).pipe(Effect.map((result) => result ?? {})), + release: request(CLIENT_METHODS.terminal_release, { + sessionId: payload.sessionId, + terminalId: response.terminalId, + }).pipe(Effect.map((result) => result ?? {})), + }), + ), + ), + extRequest: transport.sendRequest, + elicitationComplete: (payload) => + transport.notifications.sendExtNotification( + CLIENT_METHODS.session_elicitation_complete, + payload, + ), + extNotification: transport.notifications.sendExtNotification, + }; +}; diff --git a/packages/effect-acp/src/terminal.ts b/packages/effect-acp/src/terminal.ts index 088ff86373..6fad3d0825 100644 --- a/packages/effect-acp/src/terminal.ts +++ b/packages/effect-acp/src/terminal.ts @@ -1,7 +1,7 @@ import * as Effect from "effect/Effect"; -import type * as AcpSchema from "./_generated/schema.gen.ts"; -import type * as AcpError from "./errors.ts"; +import type * as AcpSchema from "./_generated/schema.gen"; +import type * as AcpError from "./errors"; export interface AcpTerminal { readonly sessionId: string; @@ -43,3 +43,7 @@ export function makeTerminal(options: MakeTerminalOptions): AcpTerminal { release: options.release, }; } + +export const TerminalHandle = { + make: makeTerminal, +}; diff --git a/packages/effect-acp/test/examples/cursor-acp-client.example.ts b/packages/effect-acp/test/examples/cursor-acp-client.example.ts index 929ed62640..0fff9c1f6f 100644 --- a/packages/effect-acp/test/examples/cursor-acp-client.example.ts +++ b/packages/effect-acp/test/examples/cursor-acp-client.example.ts @@ -1,81 +1,55 @@ import * as Effect from "effect/Effect"; -import * as Console from "effect/Console"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; -import * as AcpClient from "../../src/client.ts"; +import * as AcpClient from "../../src/client"; -const program = Effect.gen(function* () { +Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const command = ChildProcess.make("cursor-agent", ["acp"], { cwd: process.cwd(), shell: process.platform === "win32", }); const handle = yield* spawner.spawn(command); - const acpLayer = AcpClient.layerChildProcess(handle, { - logIncoming: true, - logOutgoing: true, + const client = yield* AcpClient.fromChildProcess(handle, { + handlers: { + requestPermission: () => + Effect.succeed({ + outcome: { + outcome: "selected", + optionId: "allow", + }, + }), + sessionUpdate: (notification) => Effect.logInfo("session/update", notification), + }, }); - yield* Effect.gen(function* () { - const acp = yield* AcpClient.AcpClient; + const initialized = yield* client.initialize({ + protocolVersion: 1, + clientCapabilities: { + fs: { readTextFile: false, writeTextFile: false }, + terminal: false, + }, + clientInfo: { + name: "effect-acp-example", + version: "0.0.0", + }, + }); + yield* Effect.logInfo("initialized", initialized); - yield* acp.handleRequestPermission(() => - Effect.succeed({ - outcome: { - outcome: "selected", - optionId: "allow", - }, - }), - ); - // yield* acp.handleSessionUpdate((notification) => - // Console.log("session/update", JSON.stringify(notification)), - // ); + const session = yield* client.createSession({ + cwd: process.cwd(), + mcpServers: [], + }); + yield* Effect.logInfo("created session", { sessionId: session.sessionId }); - const initialized = yield* acp.agent.initialize({ - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - _meta: { - parameterizedModelPicker: true, - }, - }, - clientInfo: { - name: "effect-acp-example", - version: "0.0.0", - }, - }); - yield* Console.log("initialized", JSON.stringify(initialized, null, 4)); + const result = yield* client.prompt({ + sessionId: session.sessionId, + prompt: [{ type: "text", text: "Summarize this repository." }], + }); - const session = yield* acp.agent.createSession({ - cwd: process.cwd(), - mcpServers: [], - }); - - const config = yield* acp.agent.setSessionConfigOption({ - sessionId: session.sessionId, - configId: "model", - value: "claude-opus-4-6", - }); - - yield* Console.log("config", JSON.stringify(config, null, 4)); - - const result = yield* acp.agent.prompt({ - sessionId: session.sessionId, - prompt: [ - { - type: "text", - text: "Illustrate your ability to create todo lists and then execute all of them. Do not write the list to disk, illustrate your built in ability!", - }, - ], - }); - - yield* Console.log("prompt result", JSON.stringify(result)); - yield* acp.agent.cancel({ sessionId: session.sessionId }); - }).pipe(Effect.provide(acpLayer)); -}); - -program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain); + yield* Effect.logInfo("prompt result", result); + yield* client.cancel({ sessionId: session.sessionId }); +}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain); diff --git a/packages/effect-acp/test/fixtures/acp-mock-peer.ts b/packages/effect-acp/test/fixtures/acp-mock-peer.ts index 7ff88a2c7e..593ba1820d 100644 --- a/packages/effect-acp/test/fixtures/acp-mock-peer.ts +++ b/packages/effect-acp/test/fixtures/acp-mock-peer.ts @@ -1,63 +1,113 @@ -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; +import { createInterface } from "node:readline"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +const rl = createInterface({ + input: process.stdin, + crlfDelay: Infinity, +}); -import * as AcpAgent from "../../src/agent.ts"; +let nextRequestId = 1000; +const pending = new Map< + number | string, + { resolve: (value: unknown) => void; reject: (error: unknown) => void } +>(); -if (process.env.ACP_MOCK_MALFORMED_OUTPUT === "1") { - process.stdout.write("{not-json}\n"); - process.exit(Number(process.env.ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE ?? "0")); +function writeMessage(message: unknown) { + process.stdout.write(`${JSON.stringify(message)}\n`); } -if (process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE !== undefined) { - process.exit(Number(process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE)); +function respond(id: number | string | null | undefined, result: unknown) { + writeMessage({ + jsonrpc: "2.0", + id, + result, + }); } -const sessionId = "mock-session-1"; +function respondError( + id: number | string | null | undefined, + code: number, + message: string, + data?: unknown, +) { + writeMessage({ + jsonrpc: "2.0", + id, + error: { + code, + message, + ...(data !== undefined ? { data } : {}), + }, + }); +} -const program = Effect.gen(function* () { - const agent = yield* AcpAgent.AcpAgent; +function notify(method: string, params?: unknown) { + writeMessage({ + jsonrpc: "2.0", + method, + ...(params !== undefined ? { params } : {}), + }); +} - yield* agent.handleInitialize(() => - Effect.succeed({ - protocolVersion: 1, - agentCapabilities: { - sessionCapabilities: { - list: {}, +function requestClient(method: string, params?: unknown) { + const id = nextRequestId++; + writeMessage({ + jsonrpc: "2.0", + id, + method, + ...(params !== undefined ? { params } : {}), + }); + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }); + }); +} + +async function handleRequest(message: { + readonly id: number | string | null; + readonly method: string; + readonly params?: unknown; +}) { + switch (message.method) { + case "initialize": + respond(message.id, { + protocolVersion: 1, + agentCapabilities: { + sessionCapabilities: { + list: {}, + }, }, - }, - agentInfo: { - name: "mock-agent", - version: "0.0.0", - }, - }), - ); - - yield* agent.handleAuthenticate(() => Effect.succeed({})); - yield* agent.handleLogout(() => Effect.succeed({})); - yield* agent.handleCreateSession(() => - Effect.succeed({ - sessionId, - }), - ); - yield* agent.handleLoadSession(() => Effect.succeed({})); - yield* agent.handleListSessions(() => - Effect.succeed({ - sessions: [ - { - sessionId, - cwd: process.cwd(), + agentInfo: { + name: "mock-agent", + version: "0.0.0", }, - ], - }), - ); - - yield* agent.handlePrompt(() => - Effect.gen(function* () { - yield* agent.client.requestPermission({ - sessionId, + }); + return; + case "authenticate": + respond(message.id, {}); + return; + case "logout": + respond(message.id, {}); + return; + case "session/new": + respond(message.id, { + sessionId: "mock-session-1", + }); + return; + case "session/load": + respond(message.id, {}); + return; + case "session/list": + respond(message.id, { + sessions: [ + { + sessionId: "mock-session-1", + cwd: process.cwd(), + }, + ], + }); + return; + case "session/prompt": { + await requestClient("session/request_permission", { + sessionId: "mock-session-1", options: [ { optionId: "allow", @@ -71,9 +121,7 @@ const program = Effect.gen(function* () { }, }); - yield* agent.client.elicit({ - sessionId, - message: "Need confirmation before continuing.", + await requestClient("session/elicitation", { mode: "form", requestedSchema: { type: "object", @@ -88,8 +136,8 @@ const program = Effect.gen(function* () { }, }); - yield* agent.client.sessionUpdate({ - sessionId, + notify("session/update", { + sessionId: "mock-session-1", update: { sessionUpdate: "plan", entries: [ @@ -102,35 +150,73 @@ const program = Effect.gen(function* () { }, }); - yield* agent.client.elicitationComplete({ + notify("session/elicitation/complete", { elicitationId: "elicitation-1", }); - yield* agent.client.extRequest("x/typed_request", { - message: process.env.ACP_MOCK_BAD_TYPED_REQUEST === "1" ? 123 : "hello from typed request", + respond(message.id, { + stopReason: "end_turn", }); - - yield* agent.client.extNotification("x/typed_notification", { - count: 2, + return; + } + default: + respond(message.id, { + echoedMethod: message.method, + echoedParams: message.params ?? null, }); + return; + } +} - return { - stopReason: "end_turn" as const, - }; - }), - ); +function handleResponse(message: { + readonly id: number | string | null; + readonly result?: unknown; + readonly error?: { readonly code: number; readonly message: string; readonly data?: unknown }; +}) { + const pendingRequest = pending.get(message.id ?? ""); + if (!pendingRequest) { + return; + } + pending.delete(message.id ?? ""); + if (message.error) { + pendingRequest.reject(message.error); + } else { + pendingRequest.resolve(message.result); + } +} - yield* agent.handleUnknownExtRequest((method, params) => - Effect.succeed({ - echoedMethod: method, - echoedParams: params ?? null, - }), - ); +rl.on("line", (line) => { + const trimmed = line.trim(); + if (trimmed.length === 0) { + return; + } - return yield* Effect.never; + const message = JSON.parse(trimmed) as + | { readonly id: number | string | null; readonly method: string; readonly params?: unknown } + | { + readonly id: number | string | null; + readonly result?: unknown; + readonly error?: { + readonly code: number; + readonly message: string; + readonly data?: unknown; + }; + } + | { readonly method: string; readonly params?: unknown }; + + if ("method" in message && "id" in message) { + void handleRequest(message).catch((error) => { + respondError(message.id, -32603, error instanceof Error ? error.message : String(error)); + }); + return; + } + + if ("id" in message && ("result" in message || "error" in message)) { + handleResponse(message); + return; + } + + if ("method" in message && !("id" in message)) { + return; + } }); - -program.pipe( - Effect.provide(Layer.provide(AcpAgent.layerStdio(), NodeServices.layer)), - NodeRuntime.runMain, -);