Add ACP support with Cursor provider (#1355)
Co-authored-by: codex <[email protected]> Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
98 files changed
+26746
-862
No files matched your search
@@ -2,18 +2,28 @@ import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import type { ProviderKind } from "./orchestration.ts";
|
||||
|
||||
export const CodexReasoningEffort = Schema.Literals(["xhigh", "high", "medium", "low"]);
|
||||
export const CODEX_REASONING_EFFORT_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
export const CodexReasoningEffort = Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS);
|
||||
export type CodexReasoningEffort = typeof CodexReasoningEffort.Type;
|
||||
export const ClaudeAgentEffort = Schema.Literals([
|
||||
export const CLAUDE_AGENT_EFFORT_OPTIONS = [
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
"ultrathink",
|
||||
]);
|
||||
] as const;
|
||||
export const ClaudeAgentEffort = Schema.Literals(CLAUDE_AGENT_EFFORT_OPTIONS);
|
||||
export type ClaudeAgentEffort = typeof ClaudeAgentEffort.Type;
|
||||
export type ProviderReasoningEffort = CodexReasoningEffort | ClaudeAgentEffort;
|
||||
export type ClaudeCodeEffort = ClaudeAgentEffort;
|
||||
export const CURSOR_REASONING_OPTIONS = ["low", "medium", "high", "max", "xhigh"] as const;
|
||||
export const CursorReasoningOption = Schema.Literals(CURSOR_REASONING_OPTIONS);
|
||||
export type CursorReasoningOption = typeof CursorReasoningOption.Type;
|
||||
|
||||
export type ProviderReasoningEffort =
|
||||
| CodexReasoningEffort
|
||||
| ClaudeAgentEffort
|
||||
| CursorReasoningOption;
|
||||
|
||||
export const CodexModelOptions = Schema.Struct({
|
||||
reasoningEffort: Schema.optional(CodexReasoningEffort),
|
||||
@@ -29,6 +39,13 @@ export const ClaudeModelOptions = Schema.Struct({
|
||||
});
|
||||
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
|
||||
|
||||
export const CursorModelOptions = Schema.Struct({
|
||||
reasoning: Schema.optional(CursorReasoningOption),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
contextWindow: Schema.optional(Schema.String),
|
||||
});
|
||||
export type CursorModelOptions = typeof CursorModelOptions.Type;
|
||||
export const OpenCodeModelOptions = Schema.Struct({
|
||||
variant: Schema.optional(TrimmedNonEmptyString),
|
||||
agent: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -38,6 +55,7 @@ export type OpenCodeModelOptions = typeof OpenCodeModelOptions.Type;
|
||||
export const ProviderModelOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexModelOptions),
|
||||
claudeAgent: Schema.optional(ClaudeModelOptions),
|
||||
cursor: Schema.optional(CursorModelOptions),
|
||||
opencode: Schema.optional(OpenCodeModelOptions),
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
@@ -70,6 +88,7 @@ export type ModelCapabilities = typeof ModelCapabilities.Type;
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
|
||||
codex: "gpt-5.4",
|
||||
claudeAgent: "claude-sonnet-4-6",
|
||||
cursor: "auto",
|
||||
opencode: "openai/gpt-5",
|
||||
};
|
||||
|
||||
@@ -79,6 +98,7 @@ export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
|
||||
codex: "gpt-5.4-mini",
|
||||
claudeAgent: "claude-haiku-4-5",
|
||||
cursor: "composer-2",
|
||||
opencode: "openai/gpt-5",
|
||||
};
|
||||
|
||||
@@ -107,6 +127,17 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
|
||||
"claude-haiku-4.5": "claude-haiku-4-5",
|
||||
"claude-haiku-4-5-20251001": "claude-haiku-4-5",
|
||||
},
|
||||
cursor: {
|
||||
composer: "composer-2",
|
||||
"composer-1.5": "composer-1.5",
|
||||
"composer-1": "composer-1.5",
|
||||
"opus-4.6-thinking": "claude-opus-4-6",
|
||||
"opus-4.6": "claude-opus-4-6",
|
||||
"sonnet-4.6-thinking": "claude-sonnet-4-6",
|
||||
"sonnet-4.6": "claude-sonnet-4-6",
|
||||
"opus-4.5-thinking": "claude-opus-4-5",
|
||||
"opus-4.5": "claude-opus-4-5",
|
||||
},
|
||||
opencode: {},
|
||||
};
|
||||
|
||||
@@ -115,5 +146,6 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
|
||||
export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
|
||||
codex: "Codex",
|
||||
claudeAgent: "Claude",
|
||||
cursor: "Cursor",
|
||||
opencode: "OpenCode",
|
||||
};
|
||||
@@ -1,5 +1,10 @@
|
||||
import { Effect, Option, Schema, SchemaIssue, Struct } from "effect";
|
||||
import { ClaudeModelOptions, CodexModelOptions, OpenCodeModelOptions } from "./model.ts";
|
||||
import {
|
||||
ClaudeModelOptions,
|
||||
CodexModelOptions,
|
||||
CursorModelOptions,
|
||||
OpenCodeModelOptions,
|
||||
} from "./model.ts";
|
||||
import { RepositoryIdentity } from "./environment.ts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -25,7 +30,7 @@ export const ORCHESTRATION_WS_METHODS = {
|
||||
subscribeThread: "orchestration.subscribeThread",
|
||||
} as const;
|
||||
|
||||
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "opencode"]);
|
||||
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor", "opencode"]);
|
||||
export type ProviderKind = typeof ProviderKind.Type;
|
||||
export const ProviderApprovalPolicy = Schema.Literals([
|
||||
"untrusted",
|
||||
@@ -57,6 +62,12 @@ export const ClaudeModelSelection = Schema.Struct({
|
||||
});
|
||||
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
|
||||
|
||||
export const CursorModelSelection = Schema.Struct({
|
||||
provider: Schema.Literal("cursor"),
|
||||
model: TrimmedNonEmptyString,
|
||||
options: Schema.optionalKey(CursorModelOptions),
|
||||
});
|
||||
export type CursorModelSelection = typeof CursorModelSelection.Type;
|
||||
export const OpenCodeModelSelection = Schema.Struct({
|
||||
provider: Schema.Literal("opencode"),
|
||||
model: TrimmedNonEmptyString,
|
||||
@@ -67,6 +78,7 @@ export type OpenCodeModelSelection = typeof OpenCodeModelSelection.Type;
|
||||
export const ModelSelection = Schema.Union([
|
||||
CodexModelSelection,
|
||||
ClaudeModelSelection,
|
||||
CursorModelSelection,
|
||||
OpenCodeModelSelection,
|
||||
]);
|
||||
export type ModelSelection = typeof ModelSelection.Type;
|
||||
|
||||
@@ -68,6 +68,26 @@ describe("ProviderSessionStartInput", () => {
|
||||
expect(parsed.modelSelection.options?.fastMode).toBe(true);
|
||||
expect(parsed.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("accepts cursor provider", () => {
|
||||
const parsed = decodeProviderSessionStartInput({
|
||||
threadId: "thread-1",
|
||||
provider: "cursor",
|
||||
cwd: "/tmp/workspace",
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
options: { fastMode: true },
|
||||
},
|
||||
});
|
||||
expect(parsed.provider).toBe("cursor");
|
||||
expect(parsed.modelSelection?.provider).toBe("cursor");
|
||||
expect(parsed.modelSelection?.model).toBe("composer-2");
|
||||
if (parsed.modelSelection?.provider === "cursor") {
|
||||
expect(parsed.modelSelection.options?.fastMode).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("ProviderSendTurnInput", () => {
|
||||
|
||||
@@ -17,14 +17,16 @@ import { ProviderKind } from "./orchestration.ts";
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
const RuntimeEventRawSource = Schema.Literals([
|
||||
"codex.app-server.notification",
|
||||
"codex.app-server.request",
|
||||
"codex.eventmsg",
|
||||
"claude.sdk.message",
|
||||
"claude.sdk.permission",
|
||||
"codex.sdk.thread-event",
|
||||
"opencode.sdk.event",
|
||||
const RuntimeEventRawSource = Schema.Union([
|
||||
Schema.Literal("codex.app-server.notification"),
|
||||
Schema.Literal("codex.app-server.request"),
|
||||
Schema.Literal("codex.eventmsg"),
|
||||
Schema.Literal("claude.sdk.message"),
|
||||
Schema.Literal("claude.sdk.permission"),
|
||||
Schema.Literal("codex.sdk.thread-event"),
|
||||
Schema.Literal("opencode.sdk.event"),
|
||||
Schema.Literal("acp.jsonrpc"),
|
||||
Schema.TemplateLiteral(["acp.", Schema.String, ".extension"]),
|
||||
]);
|
||||
export type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
|
||||
import {
|
||||
ClaudeModelOptions,
|
||||
CodexModelOptions,
|
||||
CursorModelOptions,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
OpenCodeModelOptions,
|
||||
} from "./model.ts";
|
||||
@@ -90,6 +91,13 @@ export const ClaudeSettings = Schema.Struct({
|
||||
});
|
||||
export type ClaudeSettings = typeof ClaudeSettings.Type;
|
||||
|
||||
export const CursorSettings = Schema.Struct({
|
||||
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
binaryPath: makeBinaryPathSetting("agent"),
|
||||
apiEndpoint: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
|
||||
});
|
||||
export type CursorSettings = typeof CursorSettings.Type;
|
||||
export const OpenCodeSettings = Schema.Struct({
|
||||
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
binaryPath: makeBinaryPathSetting("opencode"),
|
||||
@@ -124,6 +132,7 @@ export const ServerSettings = Schema.Struct({
|
||||
providers: Schema.Struct({
|
||||
codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
@@ -167,6 +176,13 @@ const ClaudeModelOptionsPatch = Schema.Struct({
|
||||
contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow),
|
||||
});
|
||||
|
||||
const CursorModelOptionsPatch = Schema.Struct({
|
||||
reasoning: Schema.optionalKey(CursorModelOptions.fields.reasoning),
|
||||
fastMode: Schema.optionalKey(CursorModelOptions.fields.fastMode),
|
||||
thinking: Schema.optionalKey(CursorModelOptions.fields.thinking),
|
||||
contextWindow: Schema.optionalKey(CursorModelOptions.fields.contextWindow),
|
||||
});
|
||||
|
||||
const OpenCodeModelOptionsPatch = Schema.Struct({
|
||||
variant: Schema.optionalKey(OpenCodeModelOptions.fields.variant),
|
||||
agent: Schema.optionalKey(OpenCodeModelOptions.fields.agent),
|
||||
@@ -183,6 +199,11 @@ const ModelSelectionPatch = Schema.Union([
|
||||
model: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
options: Schema.optionalKey(ClaudeModelOptionsPatch),
|
||||
}),
|
||||
Schema.Struct({
|
||||
provider: Schema.optionalKey(Schema.Literal("cursor")),
|
||||
model: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
options: Schema.optionalKey(CursorModelOptionsPatch),
|
||||
}),
|
||||
Schema.Struct({
|
||||
provider: Schema.optionalKey(Schema.Literal("opencode")),
|
||||
model: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
@@ -204,6 +225,13 @@ const ClaudeSettingsPatch = Schema.Struct({
|
||||
launchArgs: Schema.optionalKey(Schema.String),
|
||||
});
|
||||
|
||||
const CursorSettingsPatch = Schema.Struct({
|
||||
enabled: Schema.optionalKey(Schema.Boolean),
|
||||
binaryPath: Schema.optionalKey(Schema.String),
|
||||
apiEndpoint: Schema.optionalKey(Schema.String),
|
||||
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
|
||||
});
|
||||
|
||||
const OpenCodeSettingsPatch = Schema.Struct({
|
||||
enabled: Schema.optionalKey(Schema.Boolean),
|
||||
binaryPath: Schema.optionalKey(Schema.String),
|
||||
@@ -227,6 +255,7 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
Schema.Struct({
|
||||
codex: Schema.optionalKey(CodexSettingsPatch),
|
||||
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
|
||||
cursor: Schema.optionalKey(CursorSettingsPatch),
|
||||
opencode: Schema.optionalKey(OpenCodeSettingsPatch),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "effect-acp",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./client": {
|
||||
"types": "./src/client.ts",
|
||||
"import": "./src/client.ts"
|
||||
},
|
||||
"./agent": {
|
||||
"types": "./src/agent.ts",
|
||||
"import": "./src/agent.ts"
|
||||
},
|
||||
"./schema": {
|
||||
"types": "./src/schema.ts",
|
||||
"import": "./src/schema.ts"
|
||||
},
|
||||
"./rpc": {
|
||||
"types": "./src/rpc.ts",
|
||||
"import": "./src/rpc.ts"
|
||||
},
|
||||
"./protocol": {
|
||||
"types": "./src/protocol.ts",
|
||||
"import": "./src/protocol.ts"
|
||||
},
|
||||
"./terminal": {
|
||||
"types": "./src/terminal.ts",
|
||||
"import": "./src/terminal.ts"
|
||||
},
|
||||
"./errors": {
|
||||
"types": "./src/errors.ts",
|
||||
"import": "./src/errors.ts"
|
||||
}
|
||||
},
|
||||
"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",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"generate": "bun run scripts/generate.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/openapi-generator": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
|
||||
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
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;
|
||||
readonly upstreamMetaPath: string;
|
||||
readonly schemaOutputPath: string;
|
||||
readonly metaOutputPath: string;
|
||||
}
|
||||
|
||||
const MetaJsonSchema = Schema.Struct({
|
||||
agentMethods: Schema.Record(Schema.String, Schema.String),
|
||||
clientMethods: Schema.Record(Schema.String, Schema.String),
|
||||
version: Schema.Union([Schema.Number, Schema.String]),
|
||||
});
|
||||
|
||||
const UpstreamJsonSchemaSchema = Schema.Struct({
|
||||
$defs: Schema.Record(Schema.String, Schema.Json),
|
||||
});
|
||||
|
||||
const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
|
||||
return {
|
||||
generatedDir,
|
||||
upstreamSchemaPath: path.join(generatedDir, "upstream-schema.json"),
|
||||
upstreamMetaPath: path.join(generatedDir, "upstream-meta.json"),
|
||||
schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
|
||||
metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
|
||||
} satisfies GeneratedPaths;
|
||||
});
|
||||
|
||||
const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { generatedDir } = yield* getGeneratedPaths();
|
||||
|
||||
yield* fs.makeDirectory(generatedDir, { recursive: true });
|
||||
});
|
||||
|
||||
const downloadFile = Effect.fn("downloadFile")(function* (url: string, outputPath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
yield* fs.makeDirectory(path.dirname(outputPath), { recursive: true });
|
||||
|
||||
const text = yield* HttpClient.get(url).pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.flatMap((response) => response.text),
|
||||
);
|
||||
|
||||
yield* fs.writeFileString(outputPath, text);
|
||||
});
|
||||
|
||||
const downloadSchemas = Effect.fn("downloadSchemas")(function* (tag: string) {
|
||||
const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const baseUrl = `https://github.com/agentclientprotocol/agent-client-protocol/releases/download/${tag}`;
|
||||
|
||||
yield* downloadFile(`${baseUrl}/schema.unstable.json`, upstreamSchemaPath);
|
||||
yield* downloadFile(`${baseUrl}/meta.unstable.json`, upstreamMetaPath);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.all([fs.remove(upstreamSchemaPath), fs.remove(upstreamMetaPath)]).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const readJsonFile = Effect.fn("readJsonFile")(function* <
|
||||
S extends Schema.Top & { readonly DecodingServices: never },
|
||||
>(schema: S, filePath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const raw = yield* fs.readFileString(filePath);
|
||||
return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(raw);
|
||||
});
|
||||
|
||||
const writeGeneratedFiles = Effect.fn("writeGeneratedFiles")(function* (
|
||||
schemaOutput: string,
|
||||
metaOutput: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { metaOutputPath, schemaOutputPath } = yield* getGeneratedPaths();
|
||||
|
||||
yield* fs.writeFileString(schemaOutputPath, schemaOutput);
|
||||
yield* fs.writeFileString(metaOutputPath, metaOutput);
|
||||
});
|
||||
|
||||
function collectSchemaEntries(
|
||||
chunk: string,
|
||||
): ReadonlyArray<{ readonly name: string; readonly code: string }> {
|
||||
const lines = chunk
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0 && !line.startsWith("//"));
|
||||
const entries: Array<{ name: string; code: string }> = [];
|
||||
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const typeLine = lines[index];
|
||||
if (!typeLine?.startsWith("export type ")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const constLine = lines[index + 1];
|
||||
if (!constLine?.startsWith("export const ")) {
|
||||
throw new Error(`Malformed generator output near: ${typeLine}`);
|
||||
}
|
||||
|
||||
const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
|
||||
if (!match?.[1]) {
|
||||
throw new Error(`Could not extract schema name from: ${typeLine}`);
|
||||
}
|
||||
|
||||
entries.push({
|
||||
name: match[1],
|
||||
code: `${typeLine}\n${constLine}`,
|
||||
});
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(normalizeNullableTypes);
|
||||
}
|
||||
if (value === null || typeof value !== "object") {
|
||||
return value;
|
||||
}
|
||||
|
||||
const normalizedEntries = Object.entries(value).map(([key, child]) => [
|
||||
key,
|
||||
normalizeNullableTypes(child),
|
||||
]);
|
||||
const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
|
||||
string,
|
||||
typeof Schema.Json.Type
|
||||
>;
|
||||
const typeValue = normalizedObject.type;
|
||||
|
||||
if (!Array.isArray(typeValue)) {
|
||||
return normalizedObject;
|
||||
}
|
||||
|
||||
const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
|
||||
if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
|
||||
return normalizedObject;
|
||||
}
|
||||
|
||||
const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
|
||||
if (nonNullTypes.length !== 1) {
|
||||
return normalizedObject;
|
||||
}
|
||||
const nonNullType = nonNullTypes[0]!;
|
||||
|
||||
const nextObject: Record<string, typeof Schema.Json.Type> = {};
|
||||
for (const [key, child] of Object.entries(normalizedObject)) {
|
||||
if (key !== "type") {
|
||||
nextObject[key] = child;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
anyOf: [
|
||||
{
|
||||
...nextObject,
|
||||
type: nonNullType,
|
||||
},
|
||||
{ type: "null" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: boolean) {
|
||||
const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
|
||||
|
||||
yield* ensureGeneratedDir();
|
||||
|
||||
if (!skipDownload) {
|
||||
yield* Effect.log(`Downloading ACP schema assets for ${CURRENT_SCHEMA_RELEASE}`);
|
||||
yield* downloadSchemas(CURRENT_SCHEMA_RELEASE);
|
||||
}
|
||||
|
||||
const upstreamSchema = yield* readJsonFile(UpstreamJsonSchemaSchema, upstreamSchemaPath);
|
||||
const upstreamMeta = yield* readJsonFile(MetaJsonSchema, upstreamMetaPath);
|
||||
const normalizedDefinitions = Object.fromEntries(
|
||||
Object.entries(upstreamSchema.$defs).map(([name, schema]) => [
|
||||
name,
|
||||
normalizeNullableTypes(schema),
|
||||
]),
|
||||
);
|
||||
|
||||
const sortedEntries = Object.entries(normalizedDefinitions).toSorted(([left], [right]) =>
|
||||
left.localeCompare(right),
|
||||
);
|
||||
const generatedEntries = new Map<string, string>();
|
||||
const generator = makeJsonSchemaGenerator();
|
||||
|
||||
for (const [name, schema] of sortedEntries) {
|
||||
generator.addSchema(name, schema as never);
|
||||
}
|
||||
|
||||
const output = generator.generate("openapi-3.1", normalizedDefinitions as never, false).trim();
|
||||
if (output.length > 0) {
|
||||
for (const entry of collectSchemaEntries(output)) {
|
||||
if (!generatedEntries.has(entry.name)) {
|
||||
generatedEntries.set(entry.name, entry.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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"),
|
||||
"",
|
||||
].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;`,
|
||||
"",
|
||||
`export const PROTOCOL_VERSION = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.version))(upstreamMeta.version)} as const;`,
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
yield* writeGeneratedFiles(schemaOutput, metaOutput);
|
||||
yield* Effect.log(
|
||||
`Generated ${generatedEntries.size} ACP schemas from ${CURRENT_SCHEMA_RELEASE}`,
|
||||
);
|
||||
|
||||
const { generatedDir } = yield* getGeneratedPaths();
|
||||
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<GenerateCommandError>({
|
||||
_tag: "GenerateCommandError",
|
||||
message: `oxfmt failed with exit code ${code}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const generateCommand = Command.make(
|
||||
"generate",
|
||||
{
|
||||
skipDownload: Flag.boolean("skip-download").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
({ skipDownload }) => generateSchemas(skipDownload),
|
||||
).pipe(Command.withDescription("Generate Effect ACP schemas from the pinned ACP release assets."));
|
||||
|
||||
const runtimeLayer = Layer.mergeAll(
|
||||
Logger.layer([Logger.consolePretty()]),
|
||||
NodeServices.layer,
|
||||
FetchHttpClient.layer,
|
||||
);
|
||||
|
||||
Command.run(generateCommand, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(runtimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -0,0 +1,35 @@
|
||||
// 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",
|
||||
logout: "logout",
|
||||
session_cancel: "session/cancel",
|
||||
session_close: "session/close",
|
||||
session_fork: "session/fork",
|
||||
session_list: "session/list",
|
||||
session_load: "session/load",
|
||||
session_new: "session/new",
|
||||
session_prompt: "session/prompt",
|
||||
session_resume: "session/resume",
|
||||
session_set_config_option: "session/set_config_option",
|
||||
session_set_mode: "session/set_mode",
|
||||
session_set_model: "session/set_model",
|
||||
} as const;
|
||||
|
||||
export const CLIENT_METHODS = {
|
||||
fs_read_text_file: "fs/read_text_file",
|
||||
fs_write_text_file: "fs/write_text_file",
|
||||
session_elicitation: "session/elicitation",
|
||||
session_elicitation_complete: "session/elicitation/complete",
|
||||
session_request_permission: "session/request_permission",
|
||||
session_update: "session/update",
|
||||
terminal_create: "terminal/create",
|
||||
terminal_kill: "terminal/kill",
|
||||
terminal_output: "terminal/output",
|
||||
terminal_release: "terminal/release",
|
||||
terminal_wait_for_exit: "terminal/wait_for_exit",
|
||||
} as const;
|
||||
|
||||
export const PROTOCOL_VERSION = 1 as const;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,111 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import { RpcClientError } from "effect/unstable/rpc";
|
||||
|
||||
import * as AcpSchema from "../_generated/schema.gen.ts";
|
||||
import * as AcpError from "../errors.ts";
|
||||
|
||||
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
|
||||
|
||||
export const callRpc = <A>(
|
||||
effect: Effect.Effect<A, RpcClientError.RpcClientError | AcpSchema.Error>,
|
||||
): Effect.Effect<A, AcpError.AcpError> =>
|
||||
effect.pipe(
|
||||
Effect.catchTag("RpcClientError", (error) =>
|
||||
Effect.fail(
|
||||
new AcpError.AcpTransportError({
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(Schema.is(AcpSchema.Error), (error) =>
|
||||
Effect.fail(AcpError.AcpRequestError.fromProtocolError(error)),
|
||||
),
|
||||
);
|
||||
|
||||
export const runHandler = Effect.fnUntraced(function* <A, B>(
|
||||
handler: ((payload: A) => Effect.Effect<B, AcpError.AcpError>) | undefined,
|
||||
payload: A,
|
||||
method: string,
|
||||
) {
|
||||
if (!handler) {
|
||||
return yield* Effect.fail(AcpError.AcpRequestError.methodNotFound(method).toProtocolError());
|
||||
}
|
||||
return yield* handler(payload).pipe(
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(AcpError.AcpRequestError)(error)
|
||||
? error.toProtocolError()
|
||||
: AcpError.AcpRequestError.internalError(error.message).toProtocolError(),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
export function decodeExtRequestRegistration<A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
) {
|
||||
return (params: unknown): Effect.Effect<unknown, AcpError.AcpError> =>
|
||||
Schema.decodeUnknownEffect(payload)(params).pipe(
|
||||
Effect.mapError((error) =>
|
||||
AcpError.AcpRequestError.invalidParams(
|
||||
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
|
||||
{ issue: error.issue },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((decoded) => handler(decoded)),
|
||||
);
|
||||
}
|
||||
|
||||
export function decodeExtNotificationRegistration<A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) {
|
||||
return (params: unknown): Effect.Effect<void, AcpError.AcpError> =>
|
||||
Schema.decodeUnknownEffect(payload)(params).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${method} notification payload: ${formatSchemaIssue(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((decoded) => handler(decoded)),
|
||||
);
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);
|
||||
const JsonRpcHeaders = Schema.Array(Schema.Unknown);
|
||||
|
||||
export const jsonRpcRequest = <A, I>(method: string, params: Schema.Codec<A, I>) =>
|
||||
Schema.Struct({
|
||||
jsonrpc: Schema.Literal("2.0"),
|
||||
id: JsonRpcId,
|
||||
method: Schema.Literal(method),
|
||||
params,
|
||||
headers: JsonRpcHeaders,
|
||||
});
|
||||
|
||||
export const jsonRpcNotification = <A, I>(method: string, params: Schema.Codec<A, I>) =>
|
||||
Schema.Struct({
|
||||
jsonrpc: Schema.Literal("2.0"),
|
||||
method: Schema.Literal(method),
|
||||
params,
|
||||
});
|
||||
|
||||
export const jsonRpcResponse = <A, I>(result: Schema.Codec<A, I>) =>
|
||||
Schema.Struct({
|
||||
jsonrpc: Schema.Literal("2.0"),
|
||||
id: JsonRpcId,
|
||||
result,
|
||||
});
|
||||
|
||||
export const encodeJsonl = <A, I>(schema: Schema.Codec<A, I>, value: A) =>
|
||||
Effect.map(Schema.encodeEffect(Schema.fromJsonString(schema))(value), (encoded) =>
|
||||
encoder.encode(`${encoded}\n`),
|
||||
);
|
||||
@@ -0,0 +1,54 @@
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as AcpError from "../errors.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
|
||||
Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
stdin: handle.stdout,
|
||||
stdout: () =>
|
||||
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
|
||||
typeof chunk === "string" ? encoder.encode(chunk) : chunk,
|
||||
),
|
||||
stderr: () => Sink.drain,
|
||||
});
|
||||
|
||||
export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
|
||||
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
|
||||
const output = yield* Queue.unbounded<string>();
|
||||
|
||||
return {
|
||||
stdio: Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
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,
|
||||
};
|
||||
});
|
||||
|
||||
export const makeTerminationError = (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
): Effect.Effect<AcpError.AcpError> =>
|
||||
Effect.match(handle.exitCode, {
|
||||
onFailure: (cause) =>
|
||||
new AcpError.AcpTransportError({
|
||||
detail: "Failed to determine ACP process exit status",
|
||||
cause,
|
||||
}),
|
||||
onSuccess: (code) => new AcpError.AcpProcessExitedError({ code }),
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
import * as Deferred from "effect/Deferred";
|
||||
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 { assert, it } from "@effect/vitest";
|
||||
|
||||
import * as AcpAgent from "./agent.ts";
|
||||
import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
import {
|
||||
encodeJsonl,
|
||||
jsonRpcNotification,
|
||||
jsonRpcRequest,
|
||||
jsonRpcResponse,
|
||||
} from "./_internal/shared.ts";
|
||||
import { makeInMemoryStdio } from "./_internal/stdio.ts";
|
||||
|
||||
const RequestPermissionRequest = jsonRpcRequest(
|
||||
"session/request_permission",
|
||||
AcpSchema.RequestPermissionRequest,
|
||||
);
|
||||
const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
|
||||
const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
|
||||
const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
|
||||
const SessionCancelNotification = jsonRpcNotification(
|
||||
"session/cancel",
|
||||
AcpSchema.CancelNotification,
|
||||
);
|
||||
const ExtPingNotification = jsonRpcNotification("x/ping", Schema.Struct({ count: Schema.Number }));
|
||||
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
|
||||
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
|
||||
|
||||
it.effect("effect-acp agent handles core agent requests and outbound client requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
const cancelNotifications = yield* Ref.make<Array<string>>([]);
|
||||
const extNotifications = yield* Ref.make<Array<number>>([]);
|
||||
const cancelReceived = yield* Deferred.make<void>();
|
||||
const extReceived = yield* Deferred.make<void>();
|
||||
const scope = yield* Scope.make();
|
||||
const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const agent = yield* AcpAgent.AcpAgent;
|
||||
|
||||
yield* agent.handleInitialize(() =>
|
||||
Effect.succeed({
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: {},
|
||||
agentInfo: {
|
||||
name: "mock-agent",
|
||||
version: "0.0.0",
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* agent.handleCancel((notification) =>
|
||||
Ref.update(cancelNotifications, (current) => [...current, notification.sessionId]).pipe(
|
||||
Effect.andThen(Deferred.succeed(cancelReceived, undefined)),
|
||||
),
|
||||
);
|
||||
yield* agent.handleExtNotification(
|
||||
"x/ping",
|
||||
Schema.Struct({ count: Schema.Number }),
|
||||
(payload) =>
|
||||
Ref.update(extNotifications, (current) => [...current, payload.count]).pipe(
|
||||
Effect.andThen(Deferred.succeed(extReceived, undefined)),
|
||||
),
|
||||
);
|
||||
|
||||
const permissionFiber = yield* agent.client
|
||||
.requestPermission({
|
||||
sessionId: "session-1",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
title: "Allow mock action",
|
||||
},
|
||||
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const permissionRequest = yield* Schema.decodeEffect(
|
||||
Schema.fromJsonString(RequestPermissionRequest),
|
||||
)(yield* Queue.take(output));
|
||||
assert.equal(permissionRequest.jsonrpc, "2.0");
|
||||
assert.equal(permissionRequest.method, "session/request_permission");
|
||||
assert.deepEqual(permissionRequest.params, {
|
||||
sessionId: "session-1",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
title: "Allow mock action",
|
||||
},
|
||||
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
|
||||
});
|
||||
assert.deepEqual(permissionRequest.headers, []);
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(RequestPermissionResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: permissionRequest.id,
|
||||
result: {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const permission = yield* Fiber.join(permissionFiber);
|
||||
assert.equal(permission.outcome.outcome, "selected");
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(InitializeRequest, {
|
||||
jsonrpc: "2.0",
|
||||
id: 2,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
},
|
||||
clientInfo: {
|
||||
name: "effect-acp-test",
|
||||
version: "0.0.0",
|
||||
},
|
||||
},
|
||||
headers: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const initResponse = yield* Schema.decodeEffect(Schema.fromJsonString(InitializeResponse))(
|
||||
yield* Queue.take(output),
|
||||
);
|
||||
assert.deepEqual(initResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: 2,
|
||||
result: {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: {},
|
||||
agentInfo: {
|
||||
name: "mock-agent",
|
||||
version: "0.0.0",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(SessionCancelNotification, {
|
||||
jsonrpc: "2.0",
|
||||
method: "session/cancel",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(ExtPingNotification, {
|
||||
jsonrpc: "2.0",
|
||||
method: "x/ping",
|
||||
params: { count: 2 },
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Deferred.await(cancelReceived);
|
||||
yield* Deferred.await(extReceived);
|
||||
assert.deepEqual(yield* Ref.get(cancelNotifications), ["session-1"]);
|
||||
assert.deepEqual(yield* Ref.get(extNotifications), [2]);
|
||||
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("effect-acp agent uses distinct ids for RPC calls and extension requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
const scope = yield* Scope.make();
|
||||
const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const agent = yield* AcpAgent.AcpAgent;
|
||||
|
||||
const permissionFiber = yield* agent.client
|
||||
.requestPermission({
|
||||
sessionId: "session-1",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
title: "Allow mock action",
|
||||
},
|
||||
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
const extFiber = yield* agent.client
|
||||
.extRequest("x/test", { hello: "world" })
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const firstOutbound = yield* Queue.take(output);
|
||||
const secondOutbound = yield* Queue.take(output);
|
||||
|
||||
const decodedPermission = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RequestPermissionRequest),
|
||||
);
|
||||
const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
|
||||
const firstIsPermission = yield* decodedPermission(firstOutbound).pipe(
|
||||
Effect.match({
|
||||
onFailure: () => false,
|
||||
onSuccess: () => true,
|
||||
}),
|
||||
);
|
||||
|
||||
const permissionRequest = firstIsPermission
|
||||
? yield* decodedPermission(firstOutbound)
|
||||
: yield* decodedPermission(secondOutbound);
|
||||
const extRequest = firstIsPermission
|
||||
? yield* decodedExt(secondOutbound)
|
||||
: yield* decodedExt(firstOutbound);
|
||||
|
||||
assert.notEqual(permissionRequest.id, extRequest.id);
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(RequestPermissionResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: permissionRequest.id,
|
||||
result: {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(ExtResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: extRequest.id,
|
||||
result: { ok: true },
|
||||
}),
|
||||
);
|
||||
|
||||
const permission = yield* Fiber.join(permissionFiber);
|
||||
assert.equal(permission.outcome.outcome, "selected");
|
||||
assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
|
||||
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,519 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
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 Stdio from "effect/Stdio";
|
||||
import * as RpcClient from "effect/unstable/rpc/RpcClient";
|
||||
import * as RpcServer from "effect/unstable/rpc/RpcServer";
|
||||
|
||||
import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts";
|
||||
import * as AcpError from "./errors.ts";
|
||||
import * as AcpProtocol from "./protocol.ts";
|
||||
import * as AcpRpcs from "./rpc.ts";
|
||||
import {
|
||||
callRpc,
|
||||
decodeExtNotificationRegistration,
|
||||
decodeExtRequestRegistration,
|
||||
runHandler,
|
||||
} from "./_internal/shared.ts";
|
||||
import * as AcpTerminal from "./terminal.ts";
|
||||
|
||||
export interface AcpAgentOptions {
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface AcpAgentShape {
|
||||
readonly raw: {
|
||||
/**
|
||||
* Stream of inbound ACP notifications observed on the connection.
|
||||
*/
|
||||
readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
|
||||
/**
|
||||
* Sends a generic ACP extension request.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly request: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a generic ACP extension notification.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
|
||||
};
|
||||
readonly client: {
|
||||
/**
|
||||
* Requests client permission for an operation.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
|
||||
*/
|
||||
readonly requestPermission: (
|
||||
payload: AcpSchema.RequestPermissionRequest,
|
||||
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Requests structured user input from the client.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
|
||||
*/
|
||||
readonly elicit: (
|
||||
payload: AcpSchema.ElicitationRequest,
|
||||
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Requests file contents from the client.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
|
||||
*/
|
||||
readonly readTextFile: (
|
||||
payload: AcpSchema.ReadTextFileRequest,
|
||||
) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Writes a text file through the client.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
|
||||
*/
|
||||
readonly writeTextFile: (
|
||||
payload: AcpSchema.WriteTextFileRequest,
|
||||
) => Effect.Effect<AcpSchema.WriteTextFileResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Creates a terminal on the client side.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
|
||||
*/
|
||||
readonly createTerminal: (
|
||||
payload: AcpSchema.CreateTerminalRequest,
|
||||
) => Effect.Effect<AcpTerminal.AcpTerminal, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a `session/update` notification to the client.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/update
|
||||
*/
|
||||
readonly sessionUpdate: (
|
||||
payload: AcpSchema.SessionNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError>;
|
||||
/**
|
||||
* 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<void, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends an ACP extension request to the client.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly extRequest: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends an ACP extension notification to the client.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly extNotification: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<void, AcpError.AcpError>;
|
||||
};
|
||||
/**
|
||||
* Registers a handler for `initialize`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#initialize
|
||||
*/
|
||||
readonly handleInitialize: (
|
||||
handler: (
|
||||
request: AcpSchema.InitializeRequest,
|
||||
) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `authenticate`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#authenticate
|
||||
*/
|
||||
readonly handleAuthenticate: (
|
||||
handler: (
|
||||
request: AcpSchema.AuthenticateRequest,
|
||||
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleLogout: (
|
||||
handler: (
|
||||
request: AcpSchema.LogoutRequest,
|
||||
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleCreateSession: (
|
||||
handler: (
|
||||
request: AcpSchema.NewSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleLoadSession: (
|
||||
handler: (
|
||||
request: AcpSchema.LoadSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleListSessions: (
|
||||
handler: (
|
||||
request: AcpSchema.ListSessionsRequest,
|
||||
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleForkSession: (
|
||||
handler: (
|
||||
request: AcpSchema.ForkSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleResumeSession: (
|
||||
handler: (
|
||||
request: AcpSchema.ResumeSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleCloseSession: (
|
||||
handler: (
|
||||
request: AcpSchema.CloseSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleSetSessionModel: (
|
||||
handler: (
|
||||
request: AcpSchema.SetSessionModelRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleSetSessionConfigOption: (
|
||||
handler: (
|
||||
request: AcpSchema.SetSessionConfigOptionRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handlePrompt: (
|
||||
handler: (
|
||||
request: AcpSchema.PromptRequest,
|
||||
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `session/cancel`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
|
||||
*/
|
||||
readonly handleCancel: (
|
||||
handler: (notification: AcpSchema.CancelNotification) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleUnknownExtRequest: (
|
||||
handler: (method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleUnknownExtNotification: (
|
||||
handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleExtRequest: <A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly handleExtNotification: <A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class AcpAgent extends Context.Service<AcpAgent, AcpAgentShape>()("effect-acp/AcpAgent") {}
|
||||
|
||||
interface AcpCoreAgentRequestHandlers {
|
||||
initialize?: (
|
||||
request: AcpSchema.InitializeRequest,
|
||||
) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
|
||||
authenticate?: (
|
||||
request: AcpSchema.AuthenticateRequest,
|
||||
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
|
||||
logout?: (
|
||||
request: AcpSchema.LogoutRequest,
|
||||
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
|
||||
createSession?: (
|
||||
request: AcpSchema.NewSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
|
||||
loadSession?: (
|
||||
request: AcpSchema.LoadSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
|
||||
listSessions?: (
|
||||
request: AcpSchema.ListSessionsRequest,
|
||||
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
|
||||
forkSession?: (
|
||||
request: AcpSchema.ForkSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
|
||||
resumeSession?: (
|
||||
request: AcpSchema.ResumeSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
|
||||
closeSession?: (
|
||||
request: AcpSchema.CloseSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
|
||||
setSessionModel?: (
|
||||
request: AcpSchema.SetSessionModelRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
|
||||
setSessionConfigOption?: (
|
||||
request: AcpSchema.SetSessionConfigOptionRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
|
||||
prompt?: (
|
||||
request: AcpSchema.PromptRequest,
|
||||
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
const decodeCancelNotification = Schema.decodeUnknownEffect(AcpSchema.CancelNotification);
|
||||
|
||||
export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
|
||||
stdio: Stdio.Stdio,
|
||||
options: AcpAgentOptions = {},
|
||||
): Effect.fn.Return<AcpAgentShape, never, Scope.Scope> {
|
||||
const coreHandlers: AcpCoreAgentRequestHandlers = {};
|
||||
const cancelHandlers: Array<
|
||||
(notification: AcpSchema.CancelNotification) => Effect.Effect<void, AcpError.AcpError>
|
||||
> = [];
|
||||
const extRequestHandlers = new Map<
|
||||
string,
|
||||
(params: unknown) => Effect.Effect<unknown, AcpError.AcpError>
|
||||
>();
|
||||
const extNotificationHandlers = new Map<
|
||||
string,
|
||||
(params: unknown) => Effect.Effect<void, AcpError.AcpError>
|
||||
>();
|
||||
let unknownExtRequestHandler:
|
||||
| ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
|
||||
| undefined;
|
||||
let unknownExtNotificationHandler:
|
||||
| ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
|
||||
| undefined;
|
||||
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(AcpRpcs.AgentRpcs.requests.keys()),
|
||||
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
|
||||
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
|
||||
...(options.logger ? { logger: options.logger } : {}),
|
||||
onNotification: (notification) => {
|
||||
if (
|
||||
notification._tag === "ExtNotification" &&
|
||||
notification.method === AGENT_METHODS.session_cancel
|
||||
) {
|
||||
return decodeCancelNotification(notification.params).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${AGENT_METHODS.session_cancel} notification payload`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((decoded) =>
|
||||
Effect.forEach(cancelHandlers, (handler) => handler(decoded), { discard: true }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (notification._tag !== "ExtNotification") {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
const handler = extNotificationHandlers.get(notification.method);
|
||||
if (handler) {
|
||||
return handler(notification.params);
|
||||
}
|
||||
return unknownExtNotificationHandler
|
||||
? unknownExtNotificationHandler(notification.method, notification.params)
|
||||
: Effect.void;
|
||||
},
|
||||
onExtRequest: (method, params) => {
|
||||
const handler = extRequestHandlers.get(method);
|
||||
if (handler) {
|
||||
return handler(params);
|
||||
}
|
||||
return unknownExtRequestHandler
|
||||
? unknownExtRequestHandler(method, params)
|
||||
: Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
},
|
||||
});
|
||||
|
||||
const agentHandlerLayer = AcpRpcs.AgentRpcs.toLayer(
|
||||
AcpRpcs.AgentRpcs.of({
|
||||
[AGENT_METHODS.initialize]: (payload) =>
|
||||
runHandler(coreHandlers.initialize, payload, AGENT_METHODS.initialize),
|
||||
[AGENT_METHODS.authenticate]: (payload) =>
|
||||
runHandler(coreHandlers.authenticate, payload, AGENT_METHODS.authenticate),
|
||||
[AGENT_METHODS.logout]: (payload) =>
|
||||
runHandler(coreHandlers.logout, payload, AGENT_METHODS.logout),
|
||||
[AGENT_METHODS.session_new]: (payload) =>
|
||||
runHandler(coreHandlers.createSession, payload, AGENT_METHODS.session_new),
|
||||
[AGENT_METHODS.session_load]: (payload) =>
|
||||
runHandler(coreHandlers.loadSession, payload, AGENT_METHODS.session_load),
|
||||
[AGENT_METHODS.session_list]: (payload) =>
|
||||
runHandler(coreHandlers.listSessions, payload, AGENT_METHODS.session_list),
|
||||
[AGENT_METHODS.session_fork]: (payload) =>
|
||||
runHandler(coreHandlers.forkSession, payload, AGENT_METHODS.session_fork),
|
||||
[AGENT_METHODS.session_resume]: (payload) =>
|
||||
runHandler(coreHandlers.resumeSession, payload, AGENT_METHODS.session_resume),
|
||||
[AGENT_METHODS.session_close]: (payload) =>
|
||||
runHandler(coreHandlers.closeSession, payload, AGENT_METHODS.session_close),
|
||||
[AGENT_METHODS.session_set_model]: (payload) =>
|
||||
runHandler(coreHandlers.setSessionModel, payload, AGENT_METHODS.session_set_model),
|
||||
[AGENT_METHODS.session_set_config_option]: (payload) =>
|
||||
runHandler(
|
||||
coreHandlers.setSessionConfigOption,
|
||||
payload,
|
||||
AGENT_METHODS.session_set_config_option,
|
||||
),
|
||||
[AGENT_METHODS.session_prompt]: (payload) =>
|
||||
runHandler(coreHandlers.prompt, payload, AGENT_METHODS.session_prompt),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* RpcServer.make(AcpRpcs.AgentRpcs).pipe(
|
||||
Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
|
||||
Effect.provide(agentHandlerLayer),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
let nextRpcRequestId = 1n << 32n;
|
||||
const rpc = yield* RpcClient.make(AcpRpcs.ClientRpcs, {
|
||||
generateRequestId: () => nextRpcRequestId++ as never,
|
||||
}).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
|
||||
|
||||
return AcpAgent.of({
|
||||
raw: {
|
||||
notifications: transport.incoming,
|
||||
request: transport.request,
|
||||
notify: transport.notify,
|
||||
},
|
||||
client: {
|
||||
requestPermission: (payload) =>
|
||||
callRpc(rpc[CLIENT_METHODS.session_request_permission](payload)),
|
||||
elicit: (payload) => callRpc(rpc[CLIENT_METHODS.session_elicitation](payload)),
|
||||
readTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_read_text_file](payload)),
|
||||
writeTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_write_text_file](payload)),
|
||||
createTerminal: (payload) =>
|
||||
callRpc(rpc[CLIENT_METHODS.terminal_create](payload)).pipe(
|
||||
Effect.map((response) =>
|
||||
AcpTerminal.makeTerminal({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
output: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_output]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
waitForExit: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_wait_for_exit]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
kill: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_kill]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
release: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_release]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
sessionUpdate: (payload) => transport.notify(CLIENT_METHODS.session_update, payload),
|
||||
elicitationComplete: (payload) =>
|
||||
transport.notify(CLIENT_METHODS.session_elicitation_complete, payload),
|
||||
extRequest: transport.request,
|
||||
extNotification: transport.notify,
|
||||
},
|
||||
handleInitialize: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.initialize = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleAuthenticate: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.authenticate = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleLogout: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.logout = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleCreateSession: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.createSession = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleLoadSession: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.loadSession = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleListSessions: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.listSessions = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleForkSession: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.forkSession = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleResumeSession: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.resumeSession = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleCloseSession: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.closeSession = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleSetSessionModel: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.setSessionModel = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleSetSessionConfigOption: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.setSessionConfigOption = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handlePrompt: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.prompt = handler;
|
||||
return Effect.void;
|
||||
}),
|
||||
handleCancel: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
cancelHandlers.push(handler);
|
||||
return Effect.void;
|
||||
}),
|
||||
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;
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = (stdio: Stdio.Stdio, options: AcpAgentOptions = {}): Layer.Layer<AcpAgent> =>
|
||||
Layer.effect(AcpAgent, make(stdio, options));
|
||||
|
||||
export const layerStdio = (
|
||||
options: AcpAgentOptions = {},
|
||||
): Layer.Layer<AcpAgent, never, Stdio.Stdio> =>
|
||||
Layer.effect(
|
||||
AcpAgent,
|
||||
Effect.flatMap(Effect.service(Stdio.Stdio), (stdio) => make(stdio, options)),
|
||||
);
|
||||
@@ -0,0 +1,450 @@
|
||||
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 }));
|
||||
|
||||
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<string, string>) =>
|
||||
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<Array<unknown>>([]);
|
||||
const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
|
||||
const typedRequests = yield* Ref.make<Array<unknown>>([]);
|
||||
const typedNotifications = yield* Ref.make<Array<unknown>>([]);
|
||||
const handle = yield* makeHandle();
|
||||
const scope = yield* Scope.make();
|
||||
const acpLayer = AcpClient.layerChildProcess(handle);
|
||||
const context = yield* Layer.buildWithScope(acpLayer, scope);
|
||||
|
||||
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",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
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(() =>
|
||||
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.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: [],
|
||||
});
|
||||
|
||||
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)));
|
||||
|
||||
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");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replays buffered notifications to handlers registered after they arrive", () =>
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* Ref.make<Array<unknown>>([]);
|
||||
const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
|
||||
const typedRequests = yield* Ref.make<Array<unknown>>([]);
|
||||
const typedNotifications = yield* Ref.make<Array<unknown>>([]);
|
||||
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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,569 @@
|
||||
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";
|
||||
|
||||
export interface AcpClientOptions {
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
type AcpClientRaw = {
|
||||
readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
|
||||
readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
|
||||
};
|
||||
|
||||
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<AcpSchema.InitializeResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Performs ACP authentication when the agent requires it.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#authenticate
|
||||
*/
|
||||
readonly authenticate: (
|
||||
payload: AcpSchema.AuthenticateRequest,
|
||||
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Logs out the current ACP identity.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#logout
|
||||
*/
|
||||
readonly logout: (
|
||||
payload: AcpSchema.LogoutRequest,
|
||||
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Starts a new ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/new
|
||||
*/
|
||||
readonly createSession: (
|
||||
payload: AcpSchema.NewSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Loads a previously saved ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/load
|
||||
*/
|
||||
readonly loadSession: (
|
||||
payload: AcpSchema.LoadSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Lists available ACP sessions.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/list
|
||||
*/
|
||||
readonly listSessions: (
|
||||
payload: AcpSchema.ListSessionsRequest,
|
||||
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Forks an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/fork
|
||||
*/
|
||||
readonly forkSession: (
|
||||
payload: AcpSchema.ForkSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Resumes an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/resume
|
||||
*/
|
||||
readonly resumeSession: (
|
||||
payload: AcpSchema.ResumeSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Closes an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/close
|
||||
*/
|
||||
readonly closeSession: (
|
||||
payload: AcpSchema.CloseSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Selects the active model for a session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_model
|
||||
*/
|
||||
readonly setSessionModel: (
|
||||
payload: AcpSchema.SetSessionModelRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Updates a session configuration option.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
|
||||
*/
|
||||
readonly setSessionConfigOption: (
|
||||
payload: AcpSchema.SetSessionConfigOptionRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a prompt turn to the agent.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
|
||||
*/
|
||||
readonly prompt: (
|
||||
payload: AcpSchema.PromptRequest,
|
||||
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a real ACP `session/cancel` notification.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
|
||||
*/
|
||||
readonly cancel: (
|
||||
payload: AcpSchema.CancelNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError>;
|
||||
};
|
||||
/**
|
||||
* Registers a handler for `session/request_permission`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
|
||||
*/
|
||||
readonly handleRequestPermission: (
|
||||
handler: (
|
||||
request: AcpSchema.RequestPermissionRequest,
|
||||
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `session/elicitation`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
|
||||
*/
|
||||
readonly handleElicitation: (
|
||||
handler: (
|
||||
request: AcpSchema.ElicitationRequest,
|
||||
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* 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<AcpSchema.ReadTextFileResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* 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<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `terminal/create`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
|
||||
*/
|
||||
readonly handleCreateTerminal: (
|
||||
handler: (
|
||||
request: AcpSchema.CreateTerminalRequest,
|
||||
) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `terminal/output`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/output
|
||||
*/
|
||||
readonly handleTerminalOutput: (
|
||||
handler: (
|
||||
request: AcpSchema.TerminalOutputRequest,
|
||||
) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* 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<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `terminal/kill`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/kill
|
||||
*/
|
||||
readonly handleTerminalKill: (
|
||||
handler: (
|
||||
request: AcpSchema.KillTerminalRequest,
|
||||
) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `terminal/release`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/release
|
||||
*/
|
||||
readonly handleTerminalRelease: (
|
||||
handler: (
|
||||
request: AcpSchema.ReleaseTerminalRequest,
|
||||
) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `session/update`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/update
|
||||
*/
|
||||
readonly handleSessionUpdate: (
|
||||
handler: (
|
||||
notification: AcpSchema.SessionNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a handler for `session/elicitation/complete`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
|
||||
*/
|
||||
readonly handleElicitationComplete: (
|
||||
handler: (
|
||||
notification: AcpSchema.ElicitationCompleteNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a fallback extension request handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleUnknownExtRequest: (
|
||||
handler: (method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a fallback extension notification handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleUnknownExtNotification: (
|
||||
handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a typed extension request handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleExtRequest: <A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
/**
|
||||
* Registers a typed extension notification handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleExtNotification: <A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class AcpClient extends Context.Service<AcpClient, AcpClientShape>()(
|
||||
"effect-acp/AcpClient",
|
||||
) {}
|
||||
|
||||
interface AcpCoreRequestHandlers {
|
||||
requestPermission?: (
|
||||
request: AcpSchema.RequestPermissionRequest,
|
||||
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;
|
||||
elicitation?: (
|
||||
request: AcpSchema.ElicitationRequest,
|
||||
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;
|
||||
readTextFile?: (
|
||||
request: AcpSchema.ReadTextFileRequest,
|
||||
) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;
|
||||
writeTextFile?: (
|
||||
request: AcpSchema.WriteTextFileRequest,
|
||||
) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>;
|
||||
createTerminal?: (
|
||||
request: AcpSchema.CreateTerminalRequest,
|
||||
) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>;
|
||||
terminalOutput?: (
|
||||
request: AcpSchema.TerminalOutputRequest,
|
||||
) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
|
||||
terminalWaitForExit?: (
|
||||
request: AcpSchema.WaitForTerminalExitRequest,
|
||||
) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
|
||||
terminalKill?: (
|
||||
request: AcpSchema.KillTerminalRequest,
|
||||
) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>;
|
||||
terminalRelease?: (
|
||||
request: AcpSchema.ReleaseTerminalRequest,
|
||||
) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
interface AcpNotificationHandlers {
|
||||
readonly sessionUpdate: BufferedNotificationHandler<AcpSchema.SessionNotification>;
|
||||
readonly elicitationComplete: BufferedNotificationHandler<AcpSchema.ElicitationCompleteNotification>;
|
||||
}
|
||||
|
||||
interface BufferedNotificationHandler<A> {
|
||||
readonly handlers: Array<(notification: A) => Effect.Effect<void, AcpError.AcpError>>;
|
||||
readonly pending: Array<A>;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
|
||||
stdio: Stdio.Stdio,
|
||||
options: AcpClientOptions = {},
|
||||
terminationError?: Effect.Effect<AcpError.AcpError>,
|
||||
): Effect.fn.Return<AcpClientShape, never, Scope.Scope> {
|
||||
const coreHandlers: AcpCoreRequestHandlers = {};
|
||||
const notificationHandlers: AcpNotificationHandlers = {
|
||||
sessionUpdate: { handlers: [], pending: [] },
|
||||
elicitationComplete: { handlers: [], pending: [] },
|
||||
};
|
||||
const extRequestHandlers = new Map<
|
||||
string,
|
||||
(params: unknown) => Effect.Effect<unknown, AcpError.AcpError>
|
||||
>();
|
||||
const extNotificationHandlers = new Map<
|
||||
string,
|
||||
(params: unknown) => Effect.Effect<void, AcpError.AcpError>
|
||||
>();
|
||||
let unknownExtRequestHandler:
|
||||
| ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
|
||||
| undefined;
|
||||
let unknownExtNotificationHandler:
|
||||
| ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
|
||||
| undefined;
|
||||
|
||||
const runNotificationHandlers = <A>(
|
||||
registration: BufferedNotificationHandler<A>,
|
||||
notification: A,
|
||||
) =>
|
||||
Effect.forEach(
|
||||
registration.handlers,
|
||||
(handler) => handler(notification).pipe(Effect.catch(() => Effect.void)),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
const flushBufferedNotifications = <A>(registration: BufferedNotificationHandler<A>) =>
|
||||
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));
|
||||
};
|
||||
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: stdio,
|
||||
...(terminationError ? { terminationError } : {}),
|
||||
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,
|
||||
});
|
||||
|
||||
const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer(
|
||||
AcpRpcs.ClientRpcs.of({
|
||||
[CLIENT_METHODS.session_request_permission]: (payload) =>
|
||||
runHandler(
|
||||
coreHandlers.requestPermission,
|
||||
payload,
|
||||
CLIENT_METHODS.session_request_permission,
|
||||
),
|
||||
[CLIENT_METHODS.session_elicitation]: (payload) =>
|
||||
runHandler(coreHandlers.elicitation, payload, CLIENT_METHODS.session_elicitation),
|
||||
[CLIENT_METHODS.fs_read_text_file]: (payload) =>
|
||||
runHandler(coreHandlers.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(
|
||||
Effect.map((result) => result ?? {}),
|
||||
),
|
||||
[CLIENT_METHODS.terminal_create]: (payload) =>
|
||||
runHandler(coreHandlers.createTerminal, payload, CLIENT_METHODS.terminal_create),
|
||||
[CLIENT_METHODS.terminal_output]: (payload) =>
|
||||
runHandler(coreHandlers.terminalOutput, payload, CLIENT_METHODS.terminal_output),
|
||||
[CLIENT_METHODS.terminal_wait_for_exit]: (payload) =>
|
||||
runHandler(
|
||||
coreHandlers.terminalWaitForExit,
|
||||
payload,
|
||||
CLIENT_METHODS.terminal_wait_for_exit,
|
||||
),
|
||||
[CLIENT_METHODS.terminal_kill]: (payload) =>
|
||||
runHandler(coreHandlers.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(
|
||||
Effect.map((result) => result ?? {}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* RpcServer.make(AcpRpcs.ClientRpcs).pipe(
|
||||
Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
|
||||
Effect.provide(clientHandlerLayer),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
let nextRpcRequestId = 1n << 32n;
|
||||
const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs, {
|
||||
generateRequestId: () => nextRpcRequestId++ as never,
|
||||
}).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;
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layerChildProcess = (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
options: AcpClientOptions = {},
|
||||
): Layer.Layer<AcpClient> => {
|
||||
const stdio = makeChildStdio(handle);
|
||||
const terminationError = makeTerminationError(handle);
|
||||
return Layer.effect(AcpClient, make(stdio, options, terminationError));
|
||||
};
|
||||
@@ -0,0 +1,139 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
|
||||
export class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()("AcpSpawnError", {
|
||||
command: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect,
|
||||
}) {
|
||||
override get message() {
|
||||
return this.command
|
||||
? `Failed to spawn ACP process for command: ${this.command}`
|
||||
: "Failed to spawn ACP process";
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExitedError>()(
|
||||
"AcpProcessExitedError",
|
||||
{
|
||||
code: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return this.code === undefined
|
||||
? "ACP process exited"
|
||||
: `ACP process exited with code ${this.code}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpProtocolParseError extends Schema.TaggedErrorClass<AcpProtocolParseError>()(
|
||||
"AcpProtocolParseError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to parse ACP protocol message: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError>()(
|
||||
"AcpTransportError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect,
|
||||
},
|
||||
) {}
|
||||
|
||||
export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()("AcpRequestError", {
|
||||
code: AcpSchema.ErrorCode,
|
||||
errorMessage: Schema.String,
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
}) {
|
||||
override get message() {
|
||||
return this.errorMessage;
|
||||
}
|
||||
|
||||
static fromProtocolError(error: AcpSchema.Error) {
|
||||
return new AcpRequestError({
|
||||
code: error.code,
|
||||
errorMessage: error.message,
|
||||
...(error.data !== undefined ? { data: error.data } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
static parseError(message = "Parse error", data?: unknown) {
|
||||
return new AcpRequestError({
|
||||
code: -32700,
|
||||
errorMessage: message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
static invalidRequest(message = "Invalid request", data?: unknown) {
|
||||
return new AcpRequestError({
|
||||
code: -32600,
|
||||
errorMessage: message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
static methodNotFound(method: string) {
|
||||
return new AcpRequestError({
|
||||
code: -32601,
|
||||
errorMessage: `Method not found: ${method}`,
|
||||
});
|
||||
}
|
||||
|
||||
static invalidParams(message = "Invalid params", data?: unknown) {
|
||||
return new AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
static internalError(message = "Internal error", data?: unknown) {
|
||||
return new AcpRequestError({
|
||||
code: -32603,
|
||||
errorMessage: message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
static authRequired(message = "Authentication required", data?: unknown) {
|
||||
return new AcpRequestError({
|
||||
code: -32000,
|
||||
errorMessage: message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
static resourceNotFound(message = "Resource not found", data?: unknown) {
|
||||
return new AcpRequestError({
|
||||
code: -32002,
|
||||
errorMessage: message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
toProtocolError() {
|
||||
return AcpSchema.Error.make({
|
||||
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 = typeof AcpError.Type;
|
||||
@@ -0,0 +1,448 @@
|
||||
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 { 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";
|
||||
|
||||
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 mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
|
||||
);
|
||||
|
||||
const makeHandle = (env?: Record<string, string>) =>
|
||||
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.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
it.effect(
|
||||
"emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
});
|
||||
|
||||
const notifications =
|
||||
yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
|
||||
yield* transport.incoming.pipe(
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* transport.notify("session/cancel", { 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",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
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",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(ElicitationCompleteNotification, {
|
||||
jsonrpc: "2.0",
|
||||
method: "session/elicitation/complete",
|
||||
params: {
|
||||
elicitationId: "elicitation-1",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const [update, completion] = yield* Deferred.await(notifications);
|
||||
assert.equal(update?._tag, "SessionUpdate");
|
||||
assert.equal(completion?._tag, "ElicitationComplete");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio } = yield* makeInMemoryStdio();
|
||||
const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
|
||||
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<string, unknown> = {};
|
||||
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();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
});
|
||||
|
||||
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* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(ExtResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: {
|
||||
ok: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
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<unknown>();
|
||||
|
||||
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<unknown>();
|
||||
|
||||
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<unknown>();
|
||||
const termination = yield* Deferred.make<AcpError.AcpError>();
|
||||
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<unknown>();
|
||||
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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,536 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
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 * as Stdio from "effect/Stdio";
|
||||
import * as RpcClient from "effect/unstable/rpc/RpcClient";
|
||||
import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
|
||||
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;
|
||||
}
|
||||
|
||||
export type AcpIncomingNotification =
|
||||
| {
|
||||
readonly _tag: "SessionUpdate";
|
||||
readonly method: typeof CLIENT_METHODS.session_update;
|
||||
readonly params: typeof AcpSchema.SessionNotification.Type;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ElicitationComplete";
|
||||
readonly method: typeof CLIENT_METHODS.session_elicitation_complete;
|
||||
readonly params: typeof AcpSchema.ElicitationCompleteNotification.Type;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ExtNotification";
|
||||
readonly method: string;
|
||||
readonly params: unknown;
|
||||
};
|
||||
|
||||
export interface AcpPatchedProtocolOptions {
|
||||
readonly stdio: Stdio.Stdio;
|
||||
readonly terminationError?: Effect.Effect<AcpError.AcpError>;
|
||||
readonly serverRequestMethods: ReadonlySet<string>;
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
readonly onNotification?: (
|
||||
notification: AcpIncomingNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError, never>;
|
||||
readonly onExtRequest?: (
|
||||
method: string,
|
||||
params: unknown,
|
||||
) => Effect.Effect<unknown, AcpError.AcpError, never>;
|
||||
readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
|
||||
}
|
||||
|
||||
export interface AcpPatchedProtocol {
|
||||
readonly clientProtocol: RpcClient.Protocol["Service"];
|
||||
readonly serverProtocol: RpcServer.Protocol["Service"];
|
||||
readonly incoming: Stream.Stream<AcpIncomingNotification>;
|
||||
readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
|
||||
const decodeElicitationComplete = Schema.decodeUnknownEffect(
|
||||
AcpSchema.ElicitationCompleteNotification,
|
||||
);
|
||||
const parserFactory = RpcSerialization.ndJsonRpc();
|
||||
|
||||
export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
|
||||
options: AcpPatchedProtocolOptions,
|
||||
): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
|
||||
const parser = parserFactory.makeUnsafe();
|
||||
const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
|
||||
const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
|
||||
const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();
|
||||
const disconnects = yield* Queue.unbounded<number>();
|
||||
const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
|
||||
const nextRequestId = yield* Ref.make(1n);
|
||||
const terminationHandled = yield* Ref.make(false);
|
||||
const extPending = yield* Ref.make(
|
||||
new Map<string, Deferred.Deferred<unknown, AcpError.AcpError>>(),
|
||||
);
|
||||
|
||||
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<unknown, AcpError.AcpError>) => Effect.Effect<void>,
|
||||
) =>
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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<AcpError.AcpError | undefined>) =>
|
||||
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<void, AcpError.AcpError> => {
|
||||
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),
|
||||
}).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.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, {
|
||||
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.forkScoped,
|
||||
);
|
||||
|
||||
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
|
||||
|
||||
const clientProtocol = RpcClient.Protocol.of({
|
||||
run: (_clientId, f) =>
|
||||
Stream.fromQueue(clientQueue).pipe(
|
||||
Stream.runForEach((message) => f(message)),
|
||||
Effect.forever,
|
||||
),
|
||||
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,
|
||||
),
|
||||
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,
|
||||
});
|
||||
|
||||
const sendNotification = Effect.fn("sendNotification")(function* (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) {
|
||||
yield* offerOutgoing({
|
||||
_tag: "Request",
|
||||
id: "",
|
||||
tag: method,
|
||||
payload,
|
||||
headers: [],
|
||||
});
|
||||
});
|
||||
|
||||
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<unknown, AcpError.AcpError>();
|
||||
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))),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
clientProtocol,
|
||||
serverProtocol,
|
||||
get incoming() {
|
||||
return Stream.fromQueue(notificationQueue);
|
||||
},
|
||||
request: sendRequest,
|
||||
notify: sendNotification,
|
||||
} satisfies AcpPatchedProtocol;
|
||||
});
|
||||
|
||||
function isProtocolError(
|
||||
value: unknown,
|
||||
): value is { code: number; message: string; data?: unknown } {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"code" in value &&
|
||||
typeof value.code === "number" &&
|
||||
"message" in value &&
|
||||
typeof value.message === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeToRequestError(error: AcpError.AcpError): AcpError.AcpRequestError {
|
||||
return Schema.is(AcpError.AcpRequestError)(error)
|
||||
? error
|
||||
: AcpError.AcpRequestError.internalError(error.message);
|
||||
}
|
||||
|
||||
function toRpcClientError(error: AcpError.AcpError): RpcClientError.RpcClientError {
|
||||
return new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
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";
|
||||
|
||||
export const InitializeRpc = Rpc.make(AGENT_METHODS.initialize, {
|
||||
payload: AcpSchema.InitializeRequest,
|
||||
success: AcpSchema.InitializeResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const AuthenticateRpc = Rpc.make(AGENT_METHODS.authenticate, {
|
||||
payload: AcpSchema.AuthenticateRequest,
|
||||
success: AcpSchema.AuthenticateResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const LogoutRpc = Rpc.make(AGENT_METHODS.logout, {
|
||||
payload: AcpSchema.LogoutRequest,
|
||||
success: AcpSchema.LogoutResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const NewSessionRpc = Rpc.make(AGENT_METHODS.session_new, {
|
||||
payload: AcpSchema.NewSessionRequest,
|
||||
success: AcpSchema.NewSessionResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const LoadSessionRpc = Rpc.make(AGENT_METHODS.session_load, {
|
||||
payload: AcpSchema.LoadSessionRequest,
|
||||
success: AcpSchema.LoadSessionResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const ListSessionsRpc = Rpc.make(AGENT_METHODS.session_list, {
|
||||
payload: AcpSchema.ListSessionsRequest,
|
||||
success: AcpSchema.ListSessionsResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const ForkSessionRpc = Rpc.make(AGENT_METHODS.session_fork, {
|
||||
payload: AcpSchema.ForkSessionRequest,
|
||||
success: AcpSchema.ForkSessionResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const ResumeSessionRpc = Rpc.make(AGENT_METHODS.session_resume, {
|
||||
payload: AcpSchema.ResumeSessionRequest,
|
||||
success: AcpSchema.ResumeSessionResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const CloseSessionRpc = Rpc.make(AGENT_METHODS.session_close, {
|
||||
payload: AcpSchema.CloseSessionRequest,
|
||||
success: AcpSchema.CloseSessionResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const PromptRpc = Rpc.make(AGENT_METHODS.session_prompt, {
|
||||
payload: AcpSchema.PromptRequest,
|
||||
success: AcpSchema.PromptResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const SetSessionModelRpc = Rpc.make(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, {
|
||||
payload: AcpSchema.SetSessionConfigOptionRequest,
|
||||
success: AcpSchema.SetSessionConfigOptionResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const ReadTextFileRpc = Rpc.make(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, {
|
||||
payload: AcpSchema.WriteTextFileRequest,
|
||||
success: AcpSchema.WriteTextFileResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const RequestPermissionRpc = Rpc.make(CLIENT_METHODS.session_request_permission, {
|
||||
payload: AcpSchema.RequestPermissionRequest,
|
||||
success: AcpSchema.RequestPermissionResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const ElicitationRpc = Rpc.make(CLIENT_METHODS.session_elicitation, {
|
||||
payload: AcpSchema.ElicitationRequest,
|
||||
success: AcpSchema.ElicitationResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const CreateTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_create, {
|
||||
payload: AcpSchema.CreateTerminalRequest,
|
||||
success: AcpSchema.CreateTerminalResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const TerminalOutputRpc = Rpc.make(CLIENT_METHODS.terminal_output, {
|
||||
payload: AcpSchema.TerminalOutputRequest,
|
||||
success: AcpSchema.TerminalOutputResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const ReleaseTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_release, {
|
||||
payload: AcpSchema.ReleaseTerminalRequest,
|
||||
success: AcpSchema.ReleaseTerminalResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const WaitForTerminalExitRpc = Rpc.make(CLIENT_METHODS.terminal_wait_for_exit, {
|
||||
payload: AcpSchema.WaitForTerminalExitRequest,
|
||||
success: AcpSchema.WaitForTerminalExitResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const KillTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_kill, {
|
||||
payload: AcpSchema.KillTerminalRequest,
|
||||
success: AcpSchema.KillTerminalResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const AgentRpcs = RpcGroup.make(
|
||||
InitializeRpc,
|
||||
AuthenticateRpc,
|
||||
LogoutRpc,
|
||||
NewSessionRpc,
|
||||
LoadSessionRpc,
|
||||
ListSessionsRpc,
|
||||
ForkSessionRpc,
|
||||
ResumeSessionRpc,
|
||||
CloseSessionRpc,
|
||||
PromptRpc,
|
||||
SetSessionModelRpc,
|
||||
SetSessionConfigOptionRpc,
|
||||
);
|
||||
|
||||
export const ClientRpcs = RpcGroup.make(
|
||||
ReadTextFileRpc,
|
||||
WriteTextFileRpc,
|
||||
RequestPermissionRpc,
|
||||
ElicitationRpc,
|
||||
CreateTerminalRpc,
|
||||
TerminalOutputRpc,
|
||||
ReleaseTerminalRpc,
|
||||
WaitForTerminalExitRpc,
|
||||
KillTerminalRpc,
|
||||
);
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./_generated/schema.gen.ts";
|
||||
export * from "./_generated/meta.gen.ts";
|
||||
@@ -0,0 +1,45 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import type * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
import type * as AcpError from "./errors.ts";
|
||||
|
||||
export interface AcpTerminal {
|
||||
readonly sessionId: string;
|
||||
readonly terminalId: string;
|
||||
/** Reads buffered output from the terminal.
|
||||
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/output
|
||||
*/
|
||||
readonly output: Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
|
||||
/** Waits for terminal exit and returns the exit result.
|
||||
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
|
||||
*/
|
||||
readonly waitForExit: Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
|
||||
/** Terminates the terminal process.
|
||||
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/kill
|
||||
*/
|
||||
readonly kill: Effect.Effect<AcpSchema.KillTerminalResponse, AcpError.AcpError>;
|
||||
/** Releases the terminal handle from the ACP session.
|
||||
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/release
|
||||
*/
|
||||
readonly release: Effect.Effect<AcpSchema.ReleaseTerminalResponse, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export interface MakeTerminalOptions {
|
||||
readonly sessionId: string;
|
||||
readonly terminalId: string;
|
||||
readonly output: Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
|
||||
readonly waitForExit: Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
|
||||
readonly kill: Effect.Effect<AcpSchema.KillTerminalResponse, AcpError.AcpError>;
|
||||
readonly release: Effect.Effect<AcpSchema.ReleaseTerminalResponse, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export function makeTerminal(options: MakeTerminalOptions): AcpTerminal {
|
||||
return {
|
||||
sessionId: options.sessionId,
|
||||
terminalId: options.terminalId,
|
||||
output: options.output,
|
||||
waitForExit: options.waitForExit,
|
||||
kill: options.kill,
|
||||
release: options.release,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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";
|
||||
|
||||
const program = 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,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const acp = yield* AcpClient.AcpClient;
|
||||
|
||||
yield* acp.handleRequestPermission(() =>
|
||||
Effect.succeed({
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
}),
|
||||
);
|
||||
// yield* acp.handleSessionUpdate((notification) =>
|
||||
// Console.log("session/update", JSON.stringify(notification)),
|
||||
// );
|
||||
|
||||
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 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);
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as AcpAgent from "../../src/agent.ts";
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
if (process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE !== undefined) {
|
||||
process.exit(Number(process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE));
|
||||
}
|
||||
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* AcpAgent.AcpAgent;
|
||||
|
||||
yield* agent.handleInitialize(() =>
|
||||
Effect.succeed({
|
||||
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(),
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* agent.client.requestPermission({
|
||||
sessionId,
|
||||
options: [
|
||||
{
|
||||
optionId: "allow",
|
||||
name: "Allow",
|
||||
kind: "allow_once",
|
||||
},
|
||||
],
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
title: "Read project files",
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.elicit({
|
||||
sessionId,
|
||||
message: "Need confirmation before continuing.",
|
||||
mode: "form",
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
title: "Need confirmation",
|
||||
properties: {
|
||||
approved: {
|
||||
type: "boolean",
|
||||
title: "Approved",
|
||||
},
|
||||
},
|
||||
required: ["approved"],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect the repository",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.elicitationComplete({
|
||||
elicitationId: "elicitation-1",
|
||||
});
|
||||
|
||||
yield* agent.client.extRequest("x/typed_request", {
|
||||
message: process.env.ACP_MOCK_BAD_TYPED_REQUEST === "1" ? 123 : "hello from typed request",
|
||||
});
|
||||
|
||||
yield* agent.client.extNotification("x/typed_notification", {
|
||||
count: 2,
|
||||
});
|
||||
|
||||
return {
|
||||
stopReason: "end_turn" as const,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) =>
|
||||
Effect.succeed({
|
||||
echoedMethod: method,
|
||||
echoedParams: params ?? null,
|
||||
}),
|
||||
);
|
||||
|
||||
return yield* Effect.never;
|
||||
});
|
||||
|
||||
program.pipe(
|
||||
Effect.provide(Layer.provide(AcpAgent.layerStdio(), NodeServices.layer)),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"plugins": [
|
||||
{
|
||||
"name": "@effect/language-service",
|
||||
"namespaceImportPackages": ["@effect/platform-node"],
|
||||
"diagnosticSeverity": {
|
||||
"importFromBarrel": "error",
|
||||
"anyUnknownInErrorContext": "warning",
|
||||
"instanceOfSchema": "warning",
|
||||
"deterministicKeys": "warning"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "scripts", "test"]
|
||||
}
|
||||
@@ -36,6 +36,10 @@
|
||||
"types": "./src/schemaJson.ts",
|
||||
"import": "./src/schemaJson.ts"
|
||||
},
|
||||
"./toolActivity": {
|
||||
"types": "./src/toolActivity.ts",
|
||||
"import": "./src/toolActivity.ts"
|
||||
},
|
||||
"./Struct": {
|
||||
"types": "./src/Struct.ts",
|
||||
"import": "./src/Struct.ts"
|
||||
|
||||
@@ -11,10 +11,8 @@ import {
|
||||
normalizeClaudeModelOptionsWithCapabilities,
|
||||
normalizeCodexModelOptionsWithCapabilities,
|
||||
normalizeModelSlug,
|
||||
resolveApiModelId,
|
||||
resolveContextWindow,
|
||||
resolveEffort,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
resolveSelectableModel,
|
||||
trimOrNull,
|
||||
@@ -61,17 +59,18 @@ describe("normalizeModelSlug", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
describe("resolveModelSlugForProvider", () => {
|
||||
it("returns defaults when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined, "codex")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
|
||||
expect(resolveModelSlugForProvider("codex", undefined)).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves normalized unknown models", () => {
|
||||
expect(resolveModelSlug("custom/internal-model", "codex")).toBe("custom/internal-model");
|
||||
expect(resolveModelSlugForProvider("codex", "custom/internal-model")).toBe(
|
||||
"custom/internal-model",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -137,6 +136,7 @@ describe("resolveEffort", () => {
|
||||
|
||||
describe("misc helpers", () => {
|
||||
it("detects ultrathink prompts", () => {
|
||||
expect(isClaudeUltrathinkPrompt("Please ultrathink about this")).toBe(true);
|
||||
expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true);
|
||||
expect(isClaudeUltrathinkPrompt("Investigate")).toBe(false);
|
||||
});
|
||||
@@ -195,41 +195,6 @@ describe("resolveContextWindow", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveApiModelId", () => {
|
||||
it("appends [1m] suffix for 1m context window", () => {
|
||||
expect(
|
||||
resolveApiModelId({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { contextWindow: "1m" },
|
||||
}),
|
||||
).toBe("claude-opus-4-6[1m]");
|
||||
});
|
||||
|
||||
it("returns the model as-is for 200k context window", () => {
|
||||
expect(
|
||||
resolveApiModelId({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { contextWindow: "200k" },
|
||||
}),
|
||||
).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("returns the model as-is when no context window is set", () => {
|
||||
expect(resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6" })).toBe(
|
||||
"claude-opus-4-6",
|
||||
);
|
||||
expect(
|
||||
resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6", options: {} }),
|
||||
).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("returns the model as-is for Codex selections", () => {
|
||||
expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4");
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalize*ModelOptionsWithCapabilities", () => {
|
||||
it("preserves explicit false codex fast mode", () => {
|
||||
expect(
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type ClaudeAgentEffort,
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type CursorModelOptions,
|
||||
type ModelCapabilities,
|
||||
type ModelSelection,
|
||||
type OpenCodeModelOptions,
|
||||
@@ -16,8 +17,6 @@ export interface SelectableModelOption {
|
||||
name: string;
|
||||
}
|
||||
|
||||
// ── Effort helpers ────────────────────────────────────────────────────
|
||||
|
||||
/** Check whether a capabilities object includes a given effort value. */
|
||||
export function hasEffortLevel(caps: ModelCapabilities, value: string): boolean {
|
||||
return caps.reasoningEffortLevels.some((l) => l.value === value);
|
||||
@@ -31,12 +30,9 @@ export function getDefaultEffort(caps: ModelCapabilities): string | null {
|
||||
/**
|
||||
* Resolve a raw effort option against capabilities.
|
||||
*
|
||||
* Returns the effective effort value — the explicit value if supported and not
|
||||
* prompt-injected, otherwise the model's default. Returns `undefined` only
|
||||
* when the model has no effort levels at all.
|
||||
*
|
||||
* Prompt-injected efforts (e.g. "ultrathink") are excluded because they are
|
||||
* applied via prompt text, not the effort API parameter.
|
||||
* Returns the explicit supported value when present and not prompt-injected,
|
||||
* otherwise the model default. Returns `undefined` when the model exposes no
|
||||
* effort levels.
|
||||
*/
|
||||
export function resolveEffort(
|
||||
caps: ModelCapabilities,
|
||||
@@ -54,8 +50,6 @@ export function resolveEffort(
|
||||
return defaultValue ?? undefined;
|
||||
}
|
||||
|
||||
// ── Context window helpers ───────────────────────────────────────────
|
||||
|
||||
/** Check whether a capabilities object includes a given context window value. */
|
||||
export function hasContextWindowOption(caps: ModelCapabilities, value: string): boolean {
|
||||
return caps.contextWindowOptions.some((o) => o.value === value);
|
||||
@@ -69,14 +63,8 @@ export function getDefaultContextWindow(caps: ModelCapabilities): string | null
|
||||
/**
|
||||
* Resolve a raw `contextWindow` option against capabilities.
|
||||
*
|
||||
* Returns the effective context window value — the explicit value if supported,
|
||||
* otherwise the model's default. Returns `undefined` only when the model has
|
||||
* no context window options at all.
|
||||
*
|
||||
* Unlike effort levels (where the API has matching defaults), the context
|
||||
* window requires an explicit API suffix (e.g. `[1m]`), so we always preserve
|
||||
* the resolved value to avoid ambiguity between "user chose the default" and
|
||||
* "not specified".
|
||||
* Returns the explicit supported value when present, otherwise the model
|
||||
* default. Returns `undefined` when the model exposes no context window options.
|
||||
*/
|
||||
export function resolveContextWindow(
|
||||
caps: ModelCapabilities,
|
||||
@@ -119,6 +107,23 @@ export function normalizeClaudeModelOptionsWithCapabilities(
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function normalizeCursorModelOptionsWithCapabilities(
|
||||
caps: ModelCapabilities,
|
||||
modelOptions: CursorModelOptions | null | undefined,
|
||||
): CursorModelOptions | undefined {
|
||||
const reasoning = resolveEffort(caps, modelOptions?.reasoning);
|
||||
const thinking = caps.supportsThinkingToggle ? modelOptions?.thinking : undefined;
|
||||
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: CursorModelOptions = {
|
||||
...(reasoning ? { reasoning: reasoning as CursorModelOptions["reasoning"] } : {}),
|
||||
...(fastMode !== undefined ? { fastMode } : {}),
|
||||
...(thinking !== undefined ? { thinking } : {}),
|
||||
...(contextWindow !== undefined ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
function resolveLabeledOption(
|
||||
options: ReadonlyArray<{ value: string; isDefault?: boolean | undefined }> | undefined,
|
||||
raw: string | null | undefined,
|
||||
@@ -155,6 +160,8 @@ export function normalizeProviderModelOptionsWithCapabilities(
|
||||
return normalizeCodexModelOptionsWithCapabilities(caps, modelOptions as CodexModelOptions);
|
||||
case "claudeAgent":
|
||||
return normalizeClaudeModelOptionsWithCapabilities(caps, modelOptions as ClaudeModelOptions);
|
||||
case "cursor":
|
||||
return normalizeCursorModelOptionsWithCapabilities(caps, modelOptions as CursorModelOptions);
|
||||
case "opencode":
|
||||
return normalizeOpenCodeModelOptionsWithCapabilities(
|
||||
caps,
|
||||
@@ -220,7 +227,7 @@ export function resolveSelectableModel(
|
||||
return resolved ? resolved.slug : null;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string {
|
||||
function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string {
|
||||
const normalized = normalizeModelSlug(model, provider);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
@@ -260,6 +267,12 @@ export function createModelSelection(
|
||||
model,
|
||||
...(options ? { options: options as ClaudeModelOptions } : {}),
|
||||
};
|
||||
case "cursor":
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
...(options ? { options: options as CursorModelOptions } : {}),
|
||||
};
|
||||
case "opencode":
|
||||
return {
|
||||
provider,
|
||||
@@ -269,33 +282,6 @@ export function createModelSelection(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the actual API model identifier from a model selection.
|
||||
*
|
||||
* Provider-aware: each provider can map `contextWindow` (or other options)
|
||||
* to whatever the API requires — a model-id suffix, a separate parameter, etc.
|
||||
* The canonical slug stored in the selection stays unchanged so the
|
||||
* capabilities system keeps working.
|
||||
*
|
||||
* Expects `contextWindow` to already be resolved (via `resolveContextWindow`)
|
||||
* to the effective value, not stripped to `undefined` for defaults.
|
||||
*/
|
||||
export function resolveApiModelId(modelSelection: ModelSelection): string {
|
||||
switch (modelSelection.provider) {
|
||||
case "claudeAgent": {
|
||||
switch (modelSelection.options?.contextWindow) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
return modelSelection.model;
|
||||
}
|
||||
}
|
||||
default: {
|
||||
return modelSelection.model;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function applyClaudePromptEffortPrefix(
|
||||
text: string,
|
||||
effort: ClaudeAgentEffort | null | undefined,
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ServerSettings,
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type CursorModelOptions,
|
||||
type OpenCodeModelOptions,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -90,12 +91,20 @@ export function applyServerSettingsPatch(
|
||||
selectionPatch.options as ClaudeModelOptions | undefined,
|
||||
),
|
||||
}
|
||||
: {
|
||||
provider,
|
||||
model,
|
||||
...withModelSelectionOptions(
|
||||
selectionPatch.options as OpenCodeModelOptions | undefined,
|
||||
),
|
||||
},
|
||||
: provider === "cursor"
|
||||
? {
|
||||
provider,
|
||||
model,
|
||||
...withModelSelectionOptions(
|
||||
selectionPatch.options as CursorModelOptions | undefined,
|
||||
),
|
||||
}
|
||||
: {
|
||||
provider,
|
||||
model,
|
||||
...withModelSelectionOptions(
|
||||
selectionPatch.options as OpenCodeModelOptions | undefined,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { deriveToolActivityPresentation } from "./toolActivity.ts";
|
||||
|
||||
describe("toolActivity", () => {
|
||||
it("normalizes command tools to a stable ran-command label", () => {
|
||||
expect(
|
||||
deriveToolActivityPresentation({
|
||||
itemType: "command_execution",
|
||||
title: "Terminal",
|
||||
detail: "Terminal",
|
||||
data: {
|
||||
command: "bun run lint",
|
||||
},
|
||||
fallbackSummary: "Terminal",
|
||||
}),
|
||||
).toEqual({
|
||||
summary: "Ran command",
|
||||
detail: "bun run lint",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses structured file paths for read-file tools when available", () => {
|
||||
expect(
|
||||
deriveToolActivityPresentation({
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Read File",
|
||||
detail: "Read File",
|
||||
data: {
|
||||
kind: "read",
|
||||
locations: [{ path: "/tmp/app.ts" }],
|
||||
},
|
||||
fallbackSummary: "Read File",
|
||||
}),
|
||||
).toEqual({
|
||||
summary: "Read file",
|
||||
detail: "/tmp/app.ts",
|
||||
});
|
||||
});
|
||||
|
||||
it("drops duplicated generic read-file detail when no path is available", () => {
|
||||
expect(
|
||||
deriveToolActivityPresentation({
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Read File",
|
||||
detail: "Read File",
|
||||
data: {
|
||||
kind: "read",
|
||||
rawInput: {},
|
||||
},
|
||||
fallbackSummary: "Read File",
|
||||
}),
|
||||
).toEqual({
|
||||
summary: "Read file",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
import type { ToolLifecycleItemType } from "@t3tools/contracts";
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function asTrimmedString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeCommandValue(value: unknown): string | undefined {
|
||||
const direct = asTrimmedString(value);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => asTrimmedString(entry))
|
||||
.filter((entry): entry is string => entry !== undefined);
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function stripTrailingExitCode(value: string | undefined): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
if (!trimmed) {
|
||||
return undefined;
|
||||
}
|
||||
const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code \d+>)\s*$/iu.exec(trimmed);
|
||||
const output = match?.groups?.output?.trim() ?? trimmed;
|
||||
return output.length > 0 ? output : undefined;
|
||||
}
|
||||
|
||||
function extractCommandFromTitle(title: string | undefined): string | undefined {
|
||||
if (!title) {
|
||||
return undefined;
|
||||
}
|
||||
const backtickMatch = /`([^`]+)`/u.exec(title);
|
||||
return backtickMatch?.[1]?.trim() || undefined;
|
||||
}
|
||||
|
||||
function extractToolCommand(data: Record<string, unknown> | undefined, title: string | undefined) {
|
||||
const item = asRecord(data?.item);
|
||||
const itemInput = asRecord(item?.input);
|
||||
const itemResult = asRecord(item?.result);
|
||||
const rawInput = asRecord(data?.rawInput);
|
||||
const candidates = [
|
||||
normalizeCommandValue(item?.command),
|
||||
normalizeCommandValue(itemInput?.command),
|
||||
normalizeCommandValue(itemResult?.command),
|
||||
normalizeCommandValue(data?.command),
|
||||
normalizeCommandValue(rawInput?.command),
|
||||
];
|
||||
const direct = candidates.find((candidate) => candidate !== undefined);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
const executable = asTrimmedString(rawInput?.executable);
|
||||
const args = normalizeCommandValue(rawInput?.args);
|
||||
if (executable && args) {
|
||||
return `${executable} ${args}`;
|
||||
}
|
||||
if (executable) {
|
||||
return executable;
|
||||
}
|
||||
return extractCommandFromTitle(title);
|
||||
}
|
||||
|
||||
function maybePathLike(value: string | undefined): string | undefined {
|
||||
if (!value) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
value.includes("/") ||
|
||||
value.includes("\\") ||
|
||||
value.startsWith(".") ||
|
||||
/\.(?:[a-z0-9]{1,12})$/iu.test(value)
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function collectPaths(value: unknown, paths: string[], seen: Set<string>, depth: number): void {
|
||||
if (depth > 4 || paths.length >= 8) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
collectPaths(entry, paths, seen, depth + 1);
|
||||
if (paths.length >= 8) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
const record = asRecord(value);
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
for (const key of ["path", "filePath", "relativePath", "filename", "newPath", "oldPath"]) {
|
||||
const candidate = maybePathLike(asTrimmedString(record[key]));
|
||||
if (!candidate || seen.has(candidate)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(candidate);
|
||||
paths.push(candidate);
|
||||
if (paths.length >= 8) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (const nestedKey of ["locations", "item", "input", "result", "rawInput", "data", "changes"]) {
|
||||
if (!(nestedKey in record)) {
|
||||
continue;
|
||||
}
|
||||
collectPaths(record[nestedKey], paths, seen, depth + 1);
|
||||
if (paths.length >= 8) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractPrimaryPath(data: Record<string, unknown> | undefined): string | undefined {
|
||||
const paths: string[] = [];
|
||||
collectPaths(data, paths, new Set<string>(), 0);
|
||||
return paths[0];
|
||||
}
|
||||
|
||||
function normalizeEquivalentValue(value: string | undefined): string | undefined {
|
||||
const trimmed = asTrimmedString(value);
|
||||
if (!trimmed) {
|
||||
return undefined;
|
||||
}
|
||||
return trimmed
|
||||
.replace(/\s+/gu, " ")
|
||||
.replace(/\s+(?:complete|completed|started)\s*$/iu, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function isEquivalent(left: string | undefined, right: string | undefined): boolean {
|
||||
const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();
|
||||
const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();
|
||||
return normalizedLeft !== undefined && normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function classifyToolAction(input: {
|
||||
readonly itemType?: ToolLifecycleItemType | null | undefined;
|
||||
readonly title?: string | undefined;
|
||||
readonly data?: Record<string, unknown> | undefined;
|
||||
}): "command" | "read" | "file_change" | "search" | "other" {
|
||||
const itemType = input.itemType ?? undefined;
|
||||
const kind = asTrimmedString(input.data?.kind)?.toLowerCase();
|
||||
const title = asTrimmedString(input.title)?.toLowerCase();
|
||||
if (itemType === "command_execution" || kind === "execute" || title === "terminal") {
|
||||
return "command";
|
||||
}
|
||||
if (kind === "read" || title === "read file") {
|
||||
return "read";
|
||||
}
|
||||
if (
|
||||
itemType === "file_change" ||
|
||||
kind === "edit" ||
|
||||
kind === "move" ||
|
||||
kind === "delete" ||
|
||||
kind === "write"
|
||||
) {
|
||||
return "file_change";
|
||||
}
|
||||
if (itemType === "web_search" || kind === "search" || title === "find" || title === "grep") {
|
||||
return "search";
|
||||
}
|
||||
return "other";
|
||||
}
|
||||
|
||||
export interface ToolActivityPresentationInput {
|
||||
readonly itemType?: ToolLifecycleItemType | null | undefined;
|
||||
readonly title?: string | null | undefined;
|
||||
readonly detail?: string | null | undefined;
|
||||
readonly data?: unknown;
|
||||
readonly fallbackSummary?: string | null | undefined;
|
||||
}
|
||||
|
||||
export interface ToolActivityPresentation {
|
||||
readonly summary: string;
|
||||
readonly detail?: string | undefined;
|
||||
}
|
||||
|
||||
export function deriveToolActivityPresentation(
|
||||
input: ToolActivityPresentationInput,
|
||||
): ToolActivityPresentation {
|
||||
const title = asTrimmedString(input.title);
|
||||
const detail = stripTrailingExitCode(asTrimmedString(input.detail));
|
||||
const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? "Tool";
|
||||
const data = asRecord(input.data);
|
||||
const command = extractToolCommand(data, title);
|
||||
const primaryPath = extractPrimaryPath(data);
|
||||
const action = classifyToolAction({
|
||||
itemType: input.itemType,
|
||||
title,
|
||||
data,
|
||||
});
|
||||
|
||||
if (action === "command") {
|
||||
return {
|
||||
summary: "Ran command",
|
||||
...(command ? { detail: command } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "read") {
|
||||
if (primaryPath) {
|
||||
return {
|
||||
summary: "Read file",
|
||||
detail: primaryPath,
|
||||
};
|
||||
}
|
||||
return {
|
||||
summary: "Read file",
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "file_change") {
|
||||
return {
|
||||
summary: "Changed files",
|
||||
...(primaryPath ? { detail: primaryPath } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "search") {
|
||||
const query =
|
||||
asTrimmedString(asRecord(data?.rawInput)?.query) ??
|
||||
asTrimmedString(asRecord(data?.rawInput)?.pattern) ??
|
||||
asTrimmedString(asRecord(data?.rawInput)?.searchTerm);
|
||||
return {
|
||||
summary: "Searched files",
|
||||
...(query ? { detail: query } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {
|
||||
return {
|
||||
summary: title ?? fallbackSummary,
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
summary: title ?? fallbackSummary,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user