servicify

This commit is contained in:
Julius Marminge committed 2026-04-17 16:44:48 -07:00
1 parent e43002eaf1
commit d4511012f4
11 files changed
+1728 -1424

No files matched your search

+166 -158
View File
@@ -27,10 +27,10 @@ import {
Layer,
Queue,
Random,
Scope,
Stream,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { defineExtNotification, defineExtRequest } from "effect-acp/client";
import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -42,7 +42,7 @@ import {
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
} from "../Errors.ts";
import { makeAcpSessionRuntime, type AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
import { AcpSessionRuntime, type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
import {
makeAcpContentDeltaEvent,
@@ -92,7 +92,7 @@ interface PendingUserInput {
interface CursorSessionContext {
readonly threadId: ThreadId;
session: ProviderSession;
readonly acp: AcpSessionRuntime;
readonly acp: AcpSessionRuntimeShape;
notificationFiber: Fiber.Fiber<void, never> | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
@@ -379,158 +379,22 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
threadId: input.threadId,
});
const acp = yield* makeAcpSessionRuntime({
spawn: spawnOptions,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
authMethodId: "cursor_login",
...acpNativeLoggers,
handlers: {
extRequests: {
"cursor/ask_question": defineExtRequest(CursorAskQuestionRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
),
"cursor/create_plan": defineExtRequest(CursorCreatePlanRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
),
},
extNotifications: {
"cursor/update_todos": defineExtNotification(CursorUpdateTodosRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/update_todos",
params,
"acp.cursor.extension",
);
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
}
}),
),
},
requestPermission: (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"session/request_permission",
params,
"acp.jsonrpc",
);
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
},
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
const acpContextScope = yield* Scope.make("sequential");
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
spawn: spawnOptions,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
authMethodId: "cursor_login",
...acpNativeLoggers,
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
),
),
).pipe(
Effect.provideService(Scope.Scope, acpContextScope),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
@@ -541,6 +405,150 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
}),
),
);
const acp = yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
const started = yield* Effect.gen(function* () {
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
);
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
);
yield* acp.handleExtNotification(
"cursor/update_todos",
CursorUpdateTodosRequest,
(params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/update_todos",
params,
"acp.cursor.extension",
);
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
}
}),
);
yield* acp.handleRequestPermission((params) =>
Effect.gen(function* () {
yield* logNative(input.threadId, "session/request_permission", params, "acp.jsonrpc");
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
);
return yield* acp.start();
}).pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
),
);
const now = yield* nowIso;
const session: ProviderSession = {
@@ -552,7 +560,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
threadId: input.threadId,
resumeCursor: {
schemaVersion: CURSOR_RESUME_VERSION,
sessionId: acp.sessionId,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
@@ -626,7 +634,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: acp.initializeResult },
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
@@ -640,7 +648,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: acp.sessionId },
payload: { providerThreadId: started.sessionId },
});
return session;
@@ -8,7 +8,7 @@ import { it } from "@effect/vitest";
import { Effect, Stream } from "effect";
import { describe, expect } from "vitest";
import { makeAcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
import type * as EffectAcpProtocol from "effect-acp/protocol";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -18,18 +18,11 @@ const bunExe = "bun";
describe("AcpSessionRuntime", () => {
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
});
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
expect(runtime.initializeResult).toMatchObject({ protocolVersion: 1 });
expect(runtime.sessionId).toBe("mock-session-1");
expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
expect(started.sessionId).toBe("mock-session-1");
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
@@ -46,25 +39,28 @@ describe("AcpSessionRuntime", () => {
}
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("logs ACP requests from the shared runtime", () =>
Effect.gen(function* () {
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
const runtime = yield* makeAcpSessionRuntime({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
requestLogger: (event) =>
Effect.sync(() => {
requestEvents.push(event);
}),
});
it.effect("logs ACP requests from the shared runtime", () => {
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.setModel("composer-2");
yield* runtime.prompt({
@@ -93,29 +89,32 @@ describe("AcpSessionRuntime", () => {
).toBe(true);
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("emits low-level ACP protocol logs for raw and decoded messages", () =>
Effect.gen(function* () {
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
const runtime = yield* makeAcpSessionRuntime({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event) =>
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
requestLogger: (event) =>
Effect.sync(() => {
protocolEvents.push(event);
requestEvents.push(event);
}),
},
});
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
@@ -135,25 +134,37 @@ describe("AcpSessionRuntime", () => {
).toBe(true);
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("rejects invalid config option values before sending session/set_config_option", () =>
Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const runtime = yield* makeAcpSessionRuntime({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
env: {
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
});
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event) =>
Effect.sync(() => {
protocolEvents.push(event);
}),
},
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
const requestLogPath = path.join(tempDir, "requests.ndjson");
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
expect(error._tag).toBe("AcpRequestError");
@@ -181,6 +192,23 @@ describe("AcpSessionRuntime", () => {
).toBe(false);
rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
env: {
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
});
+260 -127
View File
@@ -1,4 +1,15 @@
import { Cause, Effect, Exit, Queue, Ref, Scope, Stream } from "effect";
import {
Cause,
Deferred,
Effect,
Exit,
Layer,
Queue,
Ref,
Scope,
ServiceMap,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpClient from "effect-acp/client";
import * as EffectAcpErrors from "effect-acp/errors";
@@ -33,7 +44,6 @@ export interface AcpSessionRuntimeOptions {
readonly version: string;
};
readonly authMethodId: string;
readonly handlers?: Omit<EffectAcpClient.AcpClientHandlers, "sessionUpdate">;
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
readonly protocolLogging?: {
readonly logIncoming?: boolean;
@@ -50,7 +60,7 @@ export interface AcpSessionRequestLogEvent {
readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
}
export interface AcpSessionRuntime {
export interface AcpSessionRuntimeStartResult {
readonly sessionId: string;
readonly initializeResult: EffectAcpSchema.InitializeResponse;
readonly sessionSetupResult:
@@ -58,6 +68,25 @@ export interface AcpSessionRuntime {
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
readonly modelConfigId: string | undefined;
}
export interface AcpSessionRuntimeShape {
readonly handleRequestPermission: EffectAcpClient.AcpConnectionShape["handleRequestPermission"];
readonly handleElicitation: EffectAcpClient.AcpConnectionShape["handleElicitation"];
readonly handleReadTextFile: EffectAcpClient.AcpConnectionShape["handleReadTextFile"];
readonly handleWriteTextFile: EffectAcpClient.AcpConnectionShape["handleWriteTextFile"];
readonly handleCreateTerminal: EffectAcpClient.AcpConnectionShape["handleCreateTerminal"];
readonly handleTerminalOutput: EffectAcpClient.AcpConnectionShape["handleTerminalOutput"];
readonly handleTerminalWaitForExit: EffectAcpClient.AcpConnectionShape["handleTerminalWaitForExit"];
readonly handleTerminalKill: EffectAcpClient.AcpConnectionShape["handleTerminalKill"];
readonly handleTerminalRelease: EffectAcpClient.AcpConnectionShape["handleTerminalRelease"];
readonly handleSessionUpdate: EffectAcpClient.AcpConnectionShape["handleSessionUpdate"];
readonly handleElicitationComplete: EffectAcpClient.AcpConnectionShape["handleElicitationComplete"];
readonly handleUnknownExtRequest: EffectAcpClient.AcpConnectionShape["handleUnknownExtRequest"];
readonly handleUnknownExtNotification: EffectAcpClient.AcpConnectionShape["handleUnknownExtNotification"];
readonly handleExtRequest: EffectAcpClient.AcpConnectionShape["handleExtRequest"];
readonly handleExtNotification: EffectAcpClient.AcpConnectionShape["handleExtNotification"];
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
readonly prompt: (
@@ -83,10 +112,35 @@ export interface AcpSessionRuntime {
readonly close: Effect.Effect<void>;
}
export const makeAcpSessionRuntime = (
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
type AcpStartState =
| { readonly _tag: "NotStarted" }
| {
readonly _tag: "Starting";
readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
}
| { readonly _tag: "Started"; readonly result: AcpStartedState };
export class AcpSessionRuntime extends ServiceMap.Service<
AcpSessionRuntime,
AcpSessionRuntimeShape
>()("t3/provider/acp/AcpSessionRuntime") {
static layer(
options: AcpSessionRuntimeOptions,
): Layer.Layer<
AcpSessionRuntime,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
> {
return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
}
}
const makeAcpSessionRuntime = (
options: AcpSessionRuntimeOptions,
): Effect.Effect<
AcpSessionRuntime,
AcpSessionRuntimeShape,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
> =>
@@ -97,6 +151,7 @@ export const makeAcpSessionRuntime = (
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
const logRequest = (event: AcpSessionRequestLogEvent) =>
options.requestLogger ? options.requestLogger(event) : Effect.void;
@@ -148,102 +203,43 @@ export const makeAcpSessionRuntime = (
),
);
const client = yield* EffectAcpClient.fromChildProcess(child, {
...(options.protocolLogging?.logIncoming !== undefined
? { logIncoming: options.protocolLogging.logIncoming }
: {}),
...(options.protocolLogging?.logOutgoing !== undefined
? { logOutgoing: options.protocolLogging.logOutgoing }
: {}),
...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
handlers: {
...options.handlers,
sessionUpdate: (notification) =>
handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
params: notification,
}),
},
}).pipe(Effect.provideService(Scope.Scope, runtimeScope));
const acpContext = yield* Layer.build(
EffectAcpClient.layerFromChildProcessHandle(child, {
...(options.protocolLogging?.logIncoming !== undefined
? { logIncoming: options.protocolLogging.logIncoming }
: {}),
...(options.protocolLogging?.logOutgoing !== undefined
? { logOutgoing: options.protocolLogging.logOutgoing }
: {}),
...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
}),
).pipe(Effect.provideService(Scope.Scope, runtimeScope));
const initializePayload = {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: options.clientInfo,
} satisfies EffectAcpSchema.InitializeRequest;
const initializeResult = yield* runLoggedRequest(
"initialize",
initializePayload,
client.initialize(initializePayload),
const acp = yield* Effect.service(EffectAcpClient.AcpConnection).pipe(
Effect.provide(acpContext),
);
const authenticatePayload = {
methodId: options.authMethodId,
} satisfies EffectAcpSchema.AuthenticateRequest;
yield* runLoggedRequest(
"authenticate",
authenticatePayload,
client.authenticate(authenticatePayload),
yield* acp.handleSessionUpdate((notification) =>
handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
params: notification,
}),
);
let sessionId: string;
let sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
if (options.resumeSessionId) {
const loadPayload = {
sessionId: options.resumeSessionId,
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const resumed = yield* runLoggedRequest(
"session/load",
loadPayload,
client.loadSession(loadPayload),
).pipe(Effect.exit);
if (Exit.isSuccess(resumed)) {
sessionId = options.resumeSessionId;
sessionSetupResult = resumed.value;
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
client.createSession(createPayload),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
client.createSession(createPayload),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
const close = Scope.close(runtimeScope, Exit.void).pipe(Effect.asVoid);
const getStartedState = Effect.gen(function* () {
const state = yield* Ref.get(startStateRef);
if (state._tag === "Started") {
return state.result;
}
return yield* new EffectAcpErrors.AcpTransportError({
detail: "ACP session runtime has not been started",
cause: new Error("ACP session runtime has not been started"),
});
});
const validateConfigOptionValue = (
configId: string,
value: string | boolean,
@@ -306,64 +302,201 @@ export const makeAcpSessionRuntime = (
value: string | boolean,
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
validateConfigOptionValue(configId, value).pipe(
Effect.flatMap(() => {
Effect.flatMap(() => getStartedState),
Effect.flatMap((started) => {
const requestPayload =
typeof value === "boolean"
? ({
sessionId,
sessionId: started.sessionId,
configId,
type: "boolean",
value,
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
: ({
sessionId,
sessionId: started.sessionId,
configId,
value: String(value),
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
return runLoggedRequest(
"session/set_config_option",
requestPayload,
client.setSessionConfigOption(requestPayload),
acp.setSessionConfigOption(requestPayload),
).pipe(Effect.tap((response) => updateConfigOptions(response)));
}),
);
const startOnce = Effect.gen(function* () {
const initializePayload = {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: options.clientInfo,
} satisfies EffectAcpSchema.InitializeRequest;
const initializeResult = yield* runLoggedRequest(
"initialize",
initializePayload,
acp.initialize(initializePayload),
);
const authenticatePayload = {
methodId: options.authMethodId,
} satisfies EffectAcpSchema.AuthenticateRequest;
yield* runLoggedRequest(
"authenticate",
authenticatePayload,
acp.authenticate(authenticatePayload),
);
let sessionId: string;
let sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
if (options.resumeSessionId) {
const loadPayload = {
sessionId: options.resumeSessionId,
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const resumed = yield* runLoggedRequest(
"session/load",
loadPayload,
acp.loadSession(loadPayload),
).pipe(Effect.exit);
if (Exit.isSuccess(resumed)) {
sessionId = options.resumeSessionId;
sessionSetupResult = resumed.value;
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
acp.createSession(createPayload),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
acp.createSession(createPayload),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
const nextState = {
sessionId,
initializeResult,
sessionSetupResult,
modelConfigId: extractModelConfigId(sessionSetupResult),
} satisfies AcpStartedState;
return nextState;
});
const start = Effect.gen(function* () {
const deferred = yield* Deferred.make<
AcpSessionRuntimeStartResult,
EffectAcpErrors.AcpError
>();
const effect = yield* Ref.modify(startStateRef, (state) => {
switch (state._tag) {
case "Started":
return [Effect.succeed(state.result), state] as const;
case "Starting":
return [Deferred.await(state.deferred), state] as const;
case "NotStarted":
return [
startOnce.pipe(
Effect.tap((result) =>
Ref.set(startStateRef, { _tag: "Started", result }).pipe(
Effect.andThen(Deferred.succeed(deferred, result)),
),
),
Effect.onError((cause) =>
Deferred.failCause(deferred, cause).pipe(
Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
),
),
),
{ _tag: "Starting", deferred } satisfies AcpStartState,
] as const;
}
});
return yield* effect;
});
return {
sessionId,
initializeResult,
sessionSetupResult,
modelConfigId: extractModelConfigId(sessionSetupResult),
handleRequestPermission: acp.handleRequestPermission,
handleElicitation: acp.handleElicitation,
handleReadTextFile: acp.handleReadTextFile,
handleWriteTextFile: acp.handleWriteTextFile,
handleCreateTerminal: acp.handleCreateTerminal,
handleTerminalOutput: acp.handleTerminalOutput,
handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
handleTerminalKill: acp.handleTerminalKill,
handleTerminalRelease: acp.handleTerminalRelease,
handleSessionUpdate: acp.handleSessionUpdate,
handleElicitationComplete: acp.handleElicitationComplete,
handleUnknownExtRequest: acp.handleUnknownExtRequest,
handleUnknownExtNotification: acp.handleUnknownExtNotification,
handleExtRequest: acp.handleExtRequest,
handleExtNotification: acp.handleExtNotification,
start: () => start,
events: Stream.fromQueue(eventQueue),
getModeState: Ref.get(modeStateRef),
prompt: (payload) => {
const requestPayload = {
sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
return runLoggedRequest("session/prompt", requestPayload, client.prompt(requestPayload));
},
cancel: client.cancel({ sessionId }),
setMode: (modeId) => {
const requestPayload = {
sessionId,
modeId,
} satisfies EffectAcpSchema.SetSessionModeRequest;
return runLoggedRequest(
"session/set_mode",
requestPayload,
client.setSessionMode(requestPayload),
);
},
prompt: (payload) =>
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
return runLoggedRequest("session/prompt", requestPayload, acp.prompt(requestPayload));
}),
),
cancel: getStartedState.pipe(
Effect.flatMap((started) => acp.cancel({ sessionId: started.sessionId })),
),
setMode: (modeId) =>
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
modeId,
} satisfies EffectAcpSchema.SetSessionModeRequest;
return runLoggedRequest(
"session/set_mode",
requestPayload,
acp.setSessionMode(requestPayload),
);
}),
),
setConfigOption,
setModel: (model) =>
setConfigOption(extractModelConfigId(sessionSetupResult) ?? "model", model).pipe(
getStartedState.pipe(
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
Effect.asVoid,
),
request: (method, payload) =>
runLoggedRequest(method, payload, client.extRequest(method, payload)),
notify: client.extNotification,
request: (method, payload) => runLoggedRequest(method, payload, acp.request(method, payload)),
notify: acp.notify,
close,
} satisfies AcpSessionRuntime;
} satisfies AcpSessionRuntimeShape;
});
function sessionConfigOptionsFromSetup(
@@ -8,42 +8,41 @@ import { Effect } from "effect";
import { describe, expect } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import { makeAcpSessionRuntime } from "./AcpSessionRuntime.ts";
import { AcpSessionRuntime } from "./AcpSessionRuntime.ts";
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
it.effect("initialize and authenticate against real agent acp", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
authMethodId: "cursor_login",
});
expect(runtime.initializeResult).toBeDefined();
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toBeDefined();
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
authMethodId: "cursor_login",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("session/new returns configOptions with a model selector", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
});
const result = runtime.sessionSetupResult;
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
const result = started.sessionSetupResult;
console.log("session/new result:", JSON.stringify(result, null, 2));
expect(typeof runtime.sessionId).toBe("string");
expect(typeof started.sessionId).toBe("string");
const configOptions = result.configOptions;
console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
@@ -55,22 +54,29 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
expect(typeof modelConfig?.id).toBe("string");
}
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("session/set_config_option switches the model in-session", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
});
const newResult = runtime.sessionSetupResult;
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
const newResult = started.sessionSetupResult;
const configOptions = newResult.configOptions;
let modelConfigId = "model";
@@ -93,6 +99,21 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
}
}
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
});
+2 -6
View File
@@ -7,10 +7,6 @@
"types": "./src/client.ts",
"import": "./src/client.ts"
},
"./server": {
"types": "./src/server.ts",
"import": "./src/server.ts"
},
"./schema": {
"types": "./src/schema.ts",
"import": "./src/schema.ts"
@@ -33,8 +29,8 @@
}
},
"scripts": {
"dev": "tsdown src/client.ts src/server.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/server.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/terminal.ts --format esm,cjs --dts --clean",
"dev": "tsdown src/client.ts src/_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/_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",
+132 -119
View File
@@ -1,8 +1,11 @@
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 Layer from "effect/Layer";
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";
@@ -35,89 +38,95 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
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.layerFromChildProcessHandle(handle);
const context = yield* Layer.buildWithScope(acpLayer, scope);
const client = yield* AcpClient.fromChildProcess(handle, {
handlers: {
requestPermission: () =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
const ext = yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpConnection;
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
yield* acp.handleElicitation(() =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
}),
elicitation: () =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
},
}),
sessionUpdate: (notification) =>
Ref.update(updates, (current) => [...current, notification]),
elicitationComplete: (notification) =>
Ref.update(elicitationCompletions, (current) => [...current, notification]),
extRequests: {
"x/typed_request": AcpClient.defineExtRequest(
Schema.Struct({ message: Schema.String }),
(payload) =>
Ref.update(typedRequests, (current) => [...current, payload]).pipe(
Effect.as({
ok: true,
echoedMessage: payload.message,
}),
),
},
}),
);
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.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
extNotifications: {
"x/typed_notification": AcpClient.defineExtNotification(
Schema.Struct({ count: Schema.Number }),
(payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
),
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
},
});
});
assert.equal(init.protocolVersion, 1);
const init = yield* client.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
});
assert.equal(init.protocolVersion, 1);
yield* acp.authenticate({ methodId: "cursor_login" });
yield* client.authenticate({ methodId: "cursor_login" });
const session = yield* acp.createSession({
cwd: process.cwd(),
mcpServers: [],
});
assert.equal(session.sessionId, "mock-session-1");
const session = yield* client.createSession({
cwd: process.cwd(),
mcpServers: [],
});
assert.equal(session.sessionId, "mock-session-1");
const prompt = yield* acp.prompt({
sessionId: session.sessionId,
prompt: [{ type: "text", text: "hello" }],
});
assert.equal(prompt.stopReason, "end_turn");
const prompt = yield* client.prompt({
sessionId: session.sessionId,
prompt: [{ type: "text", text: "hello" }],
});
assert.equal(prompt.stopReason, "end_turn");
const streamed = yield* Stream.runCollect(Stream.take(acp.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 }]);
const streamed = yield* Stream.runCollect(Stream.take(client.updates, 2));
assert.equal(streamed.length, 2);
assert.equal(streamed[0]?._tag, "SessionUpdate");
assert.equal(streamed[1]?._tag, "ElicitationComplete");
assert.equal((yield* Ref.get(updates)).length, 1);
assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
return yield* acp.request("x/echo", {
hello: "world",
});
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
const ext = yield* client.extRequest("x/echo", {
hello: "world",
});
assert.deepEqual(ext, {
echoedMethod: "x/echo",
echoedParams: {
@@ -132,59 +141,63 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
() =>
Effect.gen(function* () {
const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
const scope = yield* Scope.make();
const acpLayer = AcpClient.layerFromChildProcessHandle(handle);
const context = yield* Layer.buildWithScope(acpLayer, scope);
const client = yield* AcpClient.fromChildProcess(handle, {
handlers: {
requestPermission: () =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
const result = yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpConnection;
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
yield* acp.handleElicitation(() =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
}),
elicitation: () =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
},
}),
extRequests: {
"x/typed_request": AcpClient.defineExtRequest(
Schema.Struct({ message: Schema.String }),
() => Effect.succeed({ ok: true }),
),
},
}),
);
yield* acp.handleExtRequest(
"x/typed_request",
Schema.Struct({ message: Schema.String }),
() => Effect.succeed({ ok: true }),
);
yield* acp.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
},
});
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
});
yield* client.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
});
yield* acp.authenticate({ methodId: "cursor_login" });
yield* client.authenticate({ methodId: "cursor_login" });
const session = yield* acp.createSession({
cwd: process.cwd(),
mcpServers: [],
});
const session = yield* client.createSession({
cwd: process.cwd(),
mcpServers: [],
});
const result = yield* Effect.exit(
client.prompt({
sessionId: session.sessionId,
prompt: [{ type: "text", text: "hello" }],
}),
);
return yield* Effect.exit(
acp.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");
+510 -241
View File
@@ -1,162 +1,168 @@
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as ServiceMap from "effect/ServiceMap";
import * as Sink from "effect/Sink";
import * as Stdio from "effect/Stdio";
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 { RpcClientError } from "effect/unstable/rpc";
import * as AcpError from "./errors";
import * as AcpProtocol from "./protocol";
import * as AcpRpcs from "./rpc";
import * as AcpServer from "./server";
import * as AcpSchema from "./_generated/schema.gen";
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { RpcClientError } from "effect/unstable/rpc";
import * as AcpTerminal from "./terminal";
export interface AcpExtensionRequestRegistration<A, I = unknown> {
readonly payload: Schema.Codec<A, I>;
readonly handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>;
}
export interface AcpExtensionNotificationRegistration<A, I = unknown> {
readonly payload: Schema.Codec<A, I>;
readonly handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>;
}
export const defineExtRequest = <A, I>(
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
): AcpExtensionRequestRegistration<A, I> => ({ payload, handler });
export const defineExtNotification = <A, I>(
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
): AcpExtensionNotificationRegistration<A, I> => ({ payload, handler });
export interface AcpClientHandlers {
/**
* Handles `session/request_permission`.
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
*/
readonly requestPermission?: (
request: AcpSchema.RequestPermissionRequest,
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;
/**
* Handles `session/elicitation`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
*/
readonly elicitation?: (
request: AcpSchema.ElicitationRequest,
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;
/**
* Handles `fs/read_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
*/
readonly readTextFile?: (
request: AcpSchema.ReadTextFileRequest,
) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;
/**
* Handles `fs/write_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
*/
readonly writeTextFile?: (
request: AcpSchema.WriteTextFileRequest,
) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>;
/**
* Handles `terminal/create`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
*/
readonly createTerminal?: (
request: AcpSchema.CreateTerminalRequest,
) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>;
/**
* Handles `terminal/output`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/output
*/
readonly terminalOutput?: (
request: AcpSchema.TerminalOutputRequest,
) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
/**
* Handles `terminal/wait_for_exit`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
*/
readonly terminalWaitForExit?: (
request: AcpSchema.WaitForTerminalExitRequest,
) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
/**
* Handles `terminal/kill`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/kill
*/
readonly terminalKill?: (
request: AcpSchema.KillTerminalRequest,
) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>;
/**
* Handles `terminal/release`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/release
*/
readonly terminalRelease?: (
request: AcpSchema.ReleaseTerminalRequest,
) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>;
/**
* Handles `session/update` notifications from the agent.
* @see https://agentclientprotocol.com/protocol/schema#session/update
*/
readonly sessionUpdate?: (
notification: AcpSchema.SessionNotification,
) => Effect.Effect<void, AcpError.AcpError>;
/**
* Handles `session/elicitation/complete` notifications from the agent.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
*/
readonly elicitationComplete?: (
notification: AcpSchema.ElicitationCompleteNotification,
) => Effect.Effect<void, AcpError.AcpError>;
/**
* Handles extension requests outside the core ACP method set.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extRequest?: (
method: string,
params: unknown,
) => Effect.Effect<unknown, AcpError.AcpError>;
/**
* Handles extension requests outside the core ACP method set using typed payload decoders.
*/
readonly extRequests?: Readonly<Record<string, AcpExtensionRequestRegistration<any>>>;
/**
* Handles extension notifications outside the core ACP method set.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extNotification?: (
method: string,
params: unknown,
) => Effect.Effect<void, AcpError.AcpError>;
/**
* Handles extension notifications outside the core ACP method set using typed payload decoders.
*/
readonly extNotifications?: Readonly<Record<string, AcpExtensionNotificationRegistration<any>>>;
}
export interface AcpClientConnectOptions {
readonly command: ChildProcess.Command;
readonly handlers?: AcpClientHandlers;
export interface AcpConnectionOptions {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
}
export interface AcpClientConnection {
export interface AcpConnectionShape {
readonly process: ChildProcessSpawner.ChildProcessHandle;
/**
* Stream of inbound ACP notifications observed on the connection.
* @see https://agentclientprotocol.com/protocol/schema#session/update
*/
readonly updates: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
readonly server: AcpServer.AcpServerConnection;
readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
/**
* 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>;
/**
* Initializes the ACP session and negotiates capabilities.
* @see https://agentclientprotocol.com/protocol/schema#initialize
@@ -185,7 +191,8 @@ export interface AcpClientConnection {
readonly createSession: (
payload: AcpSchema.NewSessionRequest,
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
/** Loads a previously saved ACP session.
/**
* Loads a previously saved ACP session.
* @see https://agentclientprotocol.com/protocol/schema#session/load
*/
readonly loadSession: (
@@ -258,99 +265,249 @@ export interface AcpClientConnection {
* Sends an ACP extension request.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extRequest: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, AcpError.AcpError>;
readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
/**
* Sends an ACP extension notification.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extNotification: (
method: string,
payload: unknown,
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
/**
* 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>;
}
export const fromChildProcess = Effect.fnUntraced(function* (
export class AcpConnection extends ServiceMap.Service<AcpConnection, AcpConnectionShape>()(
"effect-acp/AcpConnection",
) {}
interface AcpCoreRequestHandlers {
/**
* Handles `session/request_permission`.
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
*/
requestPermission?: (
request: AcpSchema.RequestPermissionRequest,
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;
/**
* Handles `session/elicitation`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
*/
elicitation?: (
request: AcpSchema.ElicitationRequest,
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;
/**
* Handles `fs/read_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
*/
readTextFile?: (
request: AcpSchema.ReadTextFileRequest,
) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;
/**
* Handles `fs/write_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
*/
writeTextFile?: (
request: AcpSchema.WriteTextFileRequest,
) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>;
/**
* Handles `terminal/create`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
*/
createTerminal?: (
request: AcpSchema.CreateTerminalRequest,
) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>;
/**
* Handles `terminal/output`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/output
*/
terminalOutput?: (
request: AcpSchema.TerminalOutputRequest,
) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
/**
* Handles `terminal/wait_for_exit`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
*/
terminalWaitForExit?: (
request: AcpSchema.WaitForTerminalExitRequest,
) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
/**
* Handles `terminal/kill`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/kill
*/
terminalKill?: (
request: AcpSchema.KillTerminalRequest,
) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>;
/**
* Handles `terminal/release`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/release
*/
terminalRelease?: (
request: AcpSchema.ReleaseTerminalRequest,
) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>;
}
interface AcpNotificationHandlers {
readonly sessionUpdate: Array<
(notification: AcpSchema.SessionNotification) => Effect.Effect<void, AcpError.AcpError>
>;
readonly elicitationComplete: Array<
(
notification: AcpSchema.ElicitationCompleteNotification,
) => Effect.Effect<void, AcpError.AcpError>
>;
}
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
const textEncoder = new TextEncoder();
export const makeFromChildProcessHandle = Effect.fn("makeFromChildProcessHandle")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
options: {
readonly handlers?: AcpClientHandlers;
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
} = {},
): Effect.fn.Return<AcpClientConnection, never, Scope.Scope> {
const handlers = options.handlers ?? {};
options: AcpConnectionOptions = {},
): Effect.fn.Return<AcpConnectionShape, never, Scope.Scope> {
const coreHandlers: AcpCoreRequestHandlers = {};
const notificationHandlers: AcpNotificationHandlers = {
sessionUpdate: [],
elicitationComplete: [],
};
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 dispatchNotification = (notification: AcpProtocol.AcpIncomingNotification) => {
switch (notification._tag) {
case "SessionUpdate":
return Effect.forEach(
notificationHandlers.sessionUpdate,
(handler) => handler(notification.params),
{ discard: true },
);
case "ElicitationComplete":
return Effect.forEach(
notificationHandlers.elicitationComplete,
(handler) => handler(notification.params),
{ discard: true },
);
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: makeStdioFromChildProcess(handle),
processExit: handle.exitCode.pipe(
Effect.map(Number),
Effect.mapError(
(cause) =>
new AcpError.AcpProcessExitedError({
cause,
}),
),
),
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: (notification) => {
switch (notification._tag) {
case "SessionUpdate":
return handlers.sessionUpdate ? handlers.sessionUpdate(notification.params) : Effect.void;
case "ElicitationComplete":
return handlers.elicitationComplete
? handlers.elicitationComplete(notification.params)
: Effect.void;
case "ExtNotification":
return runExtNotificationHandler(
handlers.extNotifications?.[notification.method],
handlers.extNotification,
notification.method,
notification.params,
);
}
},
...(handlers.extRequest || handlers.extRequests
? {
onExtRequest: (method: string, params: unknown) =>
runExtRequestHandler(
handlers.extRequests?.[method],
handlers.extRequest,
method,
params,
),
}
: {}),
onNotification: dispatchNotification,
onExtRequest: dispatchExtRequest,
});
const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer(
AcpRpcs.ClientRpcs.of({
[CLIENT_METHODS.session_request_permission]: (payload) =>
runHandler(handlers.requestPermission, payload, CLIENT_METHODS.session_request_permission),
runHandler(
coreHandlers.requestPermission,
payload,
CLIENT_METHODS.session_request_permission,
),
[CLIENT_METHODS.session_elicitation]: (payload) =>
runHandler(handlers.elicitation, payload, CLIENT_METHODS.session_elicitation),
runHandler(coreHandlers.elicitation, payload, CLIENT_METHODS.session_elicitation),
[CLIENT_METHODS.fs_read_text_file]: (payload) =>
runHandler(handlers.readTextFile, payload, CLIENT_METHODS.fs_read_text_file),
runHandler(coreHandlers.readTextFile, payload, CLIENT_METHODS.fs_read_text_file),
[CLIENT_METHODS.fs_write_text_file]: (payload) =>
runHandler(handlers.writeTextFile, payload, CLIENT_METHODS.fs_write_text_file).pipe(
runHandler(coreHandlers.writeTextFile, payload, CLIENT_METHODS.fs_write_text_file).pipe(
Effect.map((result) => result ?? {}),
),
[CLIENT_METHODS.terminal_create]: (payload) =>
runHandler(handlers.createTerminal, payload, CLIENT_METHODS.terminal_create),
runHandler(coreHandlers.createTerminal, payload, CLIENT_METHODS.terminal_create),
[CLIENT_METHODS.terminal_output]: (payload) =>
runHandler(handlers.terminalOutput, payload, CLIENT_METHODS.terminal_output),
runHandler(coreHandlers.terminalOutput, payload, CLIENT_METHODS.terminal_output),
[CLIENT_METHODS.terminal_wait_for_exit]: (payload) =>
runHandler(handlers.terminalWaitForExit, payload, CLIENT_METHODS.terminal_wait_for_exit),
runHandler(
coreHandlers.terminalWaitForExit,
payload,
CLIENT_METHODS.terminal_wait_for_exit,
),
[CLIENT_METHODS.terminal_kill]: (payload) =>
runHandler(handlers.terminalKill, payload, CLIENT_METHODS.terminal_kill).pipe(
runHandler(coreHandlers.terminalKill, payload, CLIENT_METHODS.terminal_kill).pipe(
Effect.map((result) => result ?? {}),
),
[CLIENT_METHODS.terminal_release]: (payload) =>
runHandler(handlers.terminalRelease, payload, CLIENT_METHODS.terminal_release).pipe(
runHandler(coreHandlers.terminalRelease, payload, CLIENT_METHODS.terminal_release).pipe(
Effect.map((result) => result ?? {}),
),
}),
@@ -381,12 +538,90 @@ export const fromChildProcess = Effect.fnUntraced(function* (
),
);
const server = AcpServer.makeAcpServerConnection(transport);
const request = <A>(method: string, payload: unknown) =>
transport.request(method, payload).pipe(Effect.map((value) => value as A));
return {
return AcpConnection.of({
process: handle,
updates: transport.notifications.incoming,
server,
notifications: transport.incoming,
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.push(handler);
return Effect.void;
}),
handleElicitationComplete: (handler) =>
Effect.suspend(() => {
notificationHandlers.elicitationComplete.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;
}),
initialize: (payload) => callRpc(rpc[AGENT_METHODS.initialize](payload)),
authenticate: (payload) => callRpc(rpc[AGENT_METHODS.authenticate](payload)),
logout: (payload) => callRpc(rpc[AGENT_METHODS.logout](payload)),
@@ -401,12 +636,62 @@ export const fromChildProcess = Effect.fnUntraced(function* (
setSessionConfigOption: (payload) =>
callRpc(rpc[AGENT_METHODS.session_set_config_option](payload)),
prompt: (payload) => callRpc(rpc[AGENT_METHODS.session_prompt](payload)),
cancel: (payload) => transport.notifications.sendSessionCancel(payload),
extRequest: transport.sendRequest,
extNotification: transport.notifications.sendExtNotification,
} satisfies AcpClientConnection;
cancel: (payload) => transport.notify("session/cancel", payload),
request: transport.request,
notify: transport.notify,
requestPermission: (payload) =>
request<AcpSchema.RequestPermissionResponse>(
CLIENT_METHODS.session_request_permission,
payload,
),
elicit: (payload) =>
request<AcpSchema.ElicitationResponse>(CLIENT_METHODS.session_elicitation, payload),
readTextFile: (payload) =>
request<AcpSchema.ReadTextFileResponse>(CLIENT_METHODS.fs_read_text_file, payload),
writeTextFile: (payload) =>
request<AcpSchema.WriteTextFileResponse>(CLIENT_METHODS.fs_write_text_file, payload).pipe(
Effect.map((response) => response ?? {}),
),
createTerminal: (payload) =>
request<AcpSchema.CreateTerminalResponse>(CLIENT_METHODS.terminal_create, payload).pipe(
Effect.map((response) =>
AcpTerminal.makeTerminal({
sessionId: payload.sessionId,
terminalId: response.terminalId,
output: request<AcpSchema.TerminalOutputResponse>(CLIENT_METHODS.terminal_output, {
sessionId: payload.sessionId,
terminalId: response.terminalId,
}),
waitForExit: request<AcpSchema.WaitForTerminalExitResponse>(
CLIENT_METHODS.terminal_wait_for_exit,
{
sessionId: payload.sessionId,
terminalId: response.terminalId,
},
),
kill: request<AcpSchema.KillTerminalResponse>(CLIENT_METHODS.terminal_kill, {
sessionId: payload.sessionId,
terminalId: response.terminalId,
}).pipe(Effect.map((result) => result ?? {})),
release: request<AcpSchema.ReleaseTerminalResponse>(CLIENT_METHODS.terminal_release, {
sessionId: payload.sessionId,
terminalId: response.terminalId,
}).pipe(Effect.map((result) => result ?? {})),
}),
),
),
sessionUpdate: (payload) => transport.notify(CLIENT_METHODS.session_update, payload),
elicitationComplete: (payload) =>
transport.notify(CLIENT_METHODS.session_elicitation_complete, payload),
} satisfies AcpConnectionShape);
});
export const layerFromChildProcessHandle = (
handle: ChildProcessSpawner.ChildProcessHandle,
options: AcpConnectionOptions = {},
): Layer.Layer<AcpConnection> =>
Layer.effect(AcpConnection, makeFromChildProcessHandle(handle, options));
const runHandler = Effect.fnUntraced(function* <A, B>(
handler: ((payload: A) => Effect.Effect<B, AcpError.AcpError>) | undefined,
payload: A,
@@ -416,51 +701,38 @@ const runHandler = Effect.fnUntraced(function* <A, B>(
return yield* AcpError.AcpRequestError.methodNotFound(method);
}
return yield* handler(payload).pipe(
Effect.mapError((error) => {
return Schema.is(AcpError.AcpRequestError)(error)
Effect.mapError((error) =>
Schema.is(AcpError.AcpRequestError)(error)
? error.toProtocolError()
: AcpError.AcpRequestError.internalError(error.message).toProtocolError();
}),
: AcpError.AcpRequestError.internalError(error.message).toProtocolError(),
),
);
});
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
const runExtRequestHandler = <A, I>(
registration: AcpExtensionRequestRegistration<A, I> | undefined,
fallback:
| ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
| undefined,
function decodeExtRequestRegistration<A, I>(
method: string,
params: unknown,
): Effect.Effect<unknown, AcpError.AcpError> => {
if (registration) {
return Schema.decodeUnknownEffect(registration.payload)(params).pipe(
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((payload) => registration.handler(payload)),
Effect.flatMap((decoded) => handler(decoded)),
);
}
if (fallback) {
return fallback(method, params);
}
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
};
}
const runExtNotificationHandler = <A, I>(
registration: AcpExtensionNotificationRegistration<A, I> | undefined,
fallback:
| ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
| undefined,
function decodeExtNotificationRegistration<A, I>(
method: string,
params: unknown,
): Effect.Effect<void, AcpError.AcpError> => {
if (registration) {
return Schema.decodeUnknownEffect(registration.payload)(params).pipe(
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({
@@ -468,13 +740,10 @@ const runExtNotificationHandler = <A, I>(
cause: error,
}),
),
Effect.flatMap((payload) => registration.handler(payload)),
Effect.flatMap((decoded) => handler(decoded)),
);
}
return fallback ? fallback(method, params) : Effect.void;
};
}
const textEncoder = new TextEncoder();
function makeStdioFromChildProcess(handle: ChildProcessSpawner.ChildProcessHandle): Stdio.Stdio {
return Stdio.make({
args: Effect.succeed([]),
+8 -12
View File
@@ -100,14 +100,14 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
const notifications =
yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
yield* transport.notifications.incoming.pipe(
yield* transport.incoming.pipe(
Stream.take(2),
Stream.runCollect,
Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
Effect.forkScoped,
);
yield* transport.notifications.sendSessionCancel({ sessionId: "session-1" });
yield* transport.notify("session/cancel", { sessionId: "session-1" });
const outbound = yield* Queue.take(output);
assert.deepEqual(decodeJson(outbound), {
jsonrpc: "2.0",
@@ -175,7 +175,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
}),
});
yield* transport.notifications.sendSessionCancel({ sessionId: "session-1" });
yield* transport.notify("session/cancel", { sessionId: "session-1" });
assert.deepEqual(events, [
{
@@ -209,17 +209,13 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
serverRequestMethods: new Set(),
});
const bigintError = yield* transport.notifications
.sendExtNotification("x/test", 1n)
.pipe(Effect.flip);
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.notifications
.sendExtNotification("x/test", circular)
.pipe(Effect.flip);
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");
}),
@@ -234,7 +230,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
});
const response = yield* transport
.sendRequest("x/test", { hello: "world" })
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
assert.deepEqual(decodeJson(outbound), {
@@ -279,7 +275,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
.pipe(Effect.forkScoped);
const response = yield* transport
.sendRequest("x/test", { hello: "world" })
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
assert.deepEqual(decodeJson(outbound), {
@@ -392,7 +388,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
});
const response = yield* transport
.sendRequest("x/test", { hello: "world" })
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
yield* Queue.take(output);
yield* Queue.end(input);
+444 -459
View File
@@ -62,20 +62,9 @@ export interface AcpPatchedProtocolOptions {
export interface AcpPatchedProtocol {
readonly clientProtocol: RpcClient.Protocol["Service"];
readonly serverProtocol: RpcServer.Protocol["Service"];
readonly notifications: {
readonly incoming: Stream.Stream<AcpIncomingNotification>;
readonly sendSessionCancel: (
payload: typeof AcpSchema.CancelNotification.Type,
) => Effect.Effect<void, AcpError.AcpError>;
readonly sendExtNotification: (
method: string,
payload: unknown,
) => Effect.Effect<void, AcpError.AcpError>;
};
readonly sendRequest: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, AcpError.AcpError>;
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);
@@ -84,471 +73,467 @@ const decodeElicitationComplete = Schema.decodeUnknownEffect(
);
const parserFactory = RpcSerialization.ndJsonRpc();
export const makeAcpPatchedProtocol = (
export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
options: AcpPatchedProtocolOptions,
): Effect.Effect<AcpPatchedProtocol, never, Scope.Scope> =>
Effect.gen(function* () {
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>>(),
): 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 = (message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded) =>
Effect.try({
try: () => parser.encode(message),
catch: (cause) =>
new AcpError.AcpProtocolParseError({
detail: "Failed to encode ACP message",
cause,
}),
}).pipe(
Effect.tap(() =>
logProtocol({
direction: "outgoing",
stage: "decoded",
payload: message,
}),
),
Effect.flatMap((encoded) =>
encoded === undefined
? Effect.void
: logProtocol({
direction: "outgoing",
stage: "raw",
payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
}).pipe(Effect.flatMap(() => Queue.offer(outgoing, encoded).pipe(Effect.asVoid))),
),
);
const logProtocol = (event: AcpProtocolLogEvent) => {
if (event.direction === "incoming" && !options.logIncoming) {
return Effect.void;
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;
}
if (event.direction === "outgoing" && !options.logOutgoing) {
return Effect.void;
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;
}
return (
options.logger?.(event) ??
Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
);
};
const next = new Map(pending);
next.delete(requestId);
return next;
});
const offerOutgoing = (message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded) =>
Effect.try({
try: () => parser.encode(message),
catch: (cause) =>
new AcpError.AcpProtocolParseError({
detail: "Failed to encode ACP message",
cause,
}),
}).pipe(
Effect.tap(() =>
logProtocol({
direction: "outgoing",
stage: "decoded",
payload: message,
}),
),
Effect.flatMap((encoded) =>
encoded === undefined
? Effect.void
: logProtocol({
direction: "outgoing",
stage: "raw",
payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
}).pipe(Effect.flatMap(() => Queue.offer(outgoing, encoded).pipe(Effect.asVoid))),
),
);
const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) =>
resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error));
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 completeExtPendingSuccess = (requestId: string, value: unknown) =>
resolveExtPending(requestId, (deferred) => Deferred.succeed(deferred, value));
const failAllExtPending = (error: AcpError.AcpError) =>
Ref.get(extPending).pipe(
Effect.flatMap((pending) =>
Effect.forEach([...pending.values()], (deferred) => Deferred.fail(deferred, error), {
discard: true,
}),
),
Effect.andThen(Ref.set(extPending, new Map())),
);
const dispatchNotification = (notification: AcpIncomingNotification) =>
Queue.offer(notificationQueue, notification).pipe(
Effect.andThen(
options.onNotification
? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
: Effect.void,
),
Effect.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<
| {
readonly error: AcpError.AcpError;
readonly processExitError?: AcpError.AcpProcessExitedError | undefined;
}
const next = new Map(pending);
next.delete(requestId);
return [onFound(deferred), next] as const;
}).pipe(Effect.flatten);
| undefined
>,
) =>
Ref.modify(terminationHandled, (handled) => {
if (handled) {
return [Effect.void, true] as const;
}
return [
Effect.gen(function* () {
yield* Queue.offer(disconnects, 0);
const terminated = yield* classify();
if (!terminated) {
return;
}
yield* failAllExtPending(terminated.error);
yield* emitClientProtocolError(terminated.error);
if (terminated.processExitError && options.onProcessExit) {
yield* options.onProcessExit(terminated.processExitError);
}
}),
true,
] 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 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,
});
}
const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) =>
resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error));
if (!options.serverRequestMethods.has(message.tag)) {
return handleExtRequest(message).pipe(
Effect.catch(() => respondWithError(message.id, AcpError.AcpRequestError.internalError())),
Effect.asVoid,
);
}
const completeExtPendingSuccess = (requestId: string, value: unknown) =>
resolveExtPending(requestId, (deferred) => Deferred.succeed(deferred, value));
return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
};
const failAllExtPending = (error: AcpError.AcpError) =>
Ref.get(extPending).pipe(
Effect.flatMap((pending) =>
Effect.forEach([...pending.values()], (deferred) => Deferred.fail(deferred, error), {
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.andThen(Ref.set(extPending, new Map())),
);
const dispatchNotification = (notification: AcpIncomingNotification) =>
Queue.offer(notificationQueue, notification).pipe(
Effect.andThen(
options.onNotification
? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
: Effect.void,
),
Effect.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<
| {
readonly error: AcpError.AcpError;
readonly processExitError?: AcpError.AcpProcessExitedError | undefined;
}
| undefined
>,
) =>
Ref.modify(terminationHandled, (handled) => {
if (handled) {
return [Effect.void, true] as const;
}
return [
Effect.gen(function* () {
yield* Queue.offer(disconnects, 0);
const terminated = yield* classify();
if (!terminated) {
return;
}
yield* failAllExtPending(terminated.error);
yield* emitClientProtocolError(terminated.error);
if (terminated.processExitError && options.onProcessExit) {
yield* options.onProcessExit(terminated.processExitError);
}
}),
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({ error: normalized }));
},
onSuccess: () =>
handleTermination(() =>
options.processExit
? options.processExit.pipe(
Effect.match({
onFailure: (processExitError) =>
({
error: processExitError,
processExitError,
}) as const,
onSuccess: (code) => {
const processExitError =
code === null
? new AcpError.AcpProcessExitedError({})
: new AcpError.AcpProcessExitedError({ code });
return {
error: processExitError,
processExitError,
} as const;
},
}),
)
: Effect.succeed({
error: 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: (f) =>
Stream.fromQueue(clientQueue).pipe(
Stream.runForEach((message) => f(message)),
Effect.forever,
),
send: (request) => offerOutgoing(request).pipe(Effect.mapError(toRpcClientError)),
supportsAck: true,
supportsTransferables: false,
});
const serverProtocol = RpcServer.Protocol.of({
run: (f) =>
Stream.fromQueue(serverQueue).pipe(
Stream.runForEach((message) => f(0, message)),
Effect.forever,
),
disconnects,
send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
end: () => Queue.end(outgoing).pipe(Effect.orDie),
clientIds: Effect.succeed(new Set([0])),
initialMessage: Effect.succeedNone,
supportsAck: true,
supportsTransferables: false,
supportsSpanPropagation: true,
});
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,
notifications: {
incoming: Stream.fromQueue(notificationQueue),
sendSessionCancel: (payload) => sendNotification("session/cancel", payload),
sendExtNotification: sendNotification,
),
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({ error: normalized }));
},
sendRequest,
} satisfies AcpPatchedProtocol;
onSuccess: () =>
handleTermination(() =>
options.processExit
? options.processExit.pipe(
Effect.match({
onFailure: (processExitError) =>
({
error: processExitError,
processExitError,
}) as const,
onSuccess: (code) => {
const processExitError =
code === null
? new AcpError.AcpProcessExitedError({})
: new AcpError.AcpProcessExitedError({ code });
return {
error: processExitError,
processExitError,
} as const;
},
}),
)
: Effect.succeed({
error: 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: (f) =>
Stream.fromQueue(clientQueue).pipe(
Stream.runForEach((message) => f(message)),
Effect.forever,
),
send: (request) => offerOutgoing(request).pipe(Effect.mapError(toRpcClientError)),
supportsAck: true,
supportsTransferables: false,
});
const serverProtocol = RpcServer.Protocol.of({
run: (f) =>
Stream.fromQueue(serverQueue).pipe(
Stream.runForEach((message) => f(0, message)),
Effect.forever,
),
disconnects,
send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
end: () => Queue.end(outgoing).pipe(Effect.orDie),
clientIds: Effect.succeed(new Set([0])),
initialMessage: Effect.succeedNone,
supportsAck: true,
supportsTransferables: false,
supportsSpanPropagation: true,
});
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 } {
-135
View File
@@ -1,135 +0,0 @@
import * as Effect from "effect/Effect";
import * as AcpSchema from "./_generated/schema.gen";
import { CLIENT_METHODS } from "./_generated/meta.gen";
import type * as AcpError from "./errors";
import type * as AcpProtocol from "./protocol";
import * as AcpTerminal from "./terminal";
export interface AcpServerConnection {
/**
* Sends a `session/update` notification to the client.
* @see https://agentclientprotocol.com/protocol/schema#session/update
*/
readonly sessionUpdate: (
payload: AcpSchema.SessionNotification,
) => Effect.Effect<void, AcpError.AcpError>;
/**
* 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 an ACP extension request.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extRequest: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, 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 notification.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extNotification: (
method: string,
payload: unknown,
) => Effect.Effect<void, AcpError.AcpError>;
}
export const makeAcpServerConnection = (
transport: AcpProtocol.AcpPatchedProtocol,
): AcpServerConnection => {
const request = <A>(method: string, payload: unknown) =>
transport.sendRequest(method, payload).pipe(Effect.map((value) => value as A));
return {
sessionUpdate: (payload) =>
transport.notifications.sendExtNotification(CLIENT_METHODS.session_update, payload),
requestPermission: (payload) =>
request<AcpSchema.RequestPermissionResponse>(
CLIENT_METHODS.session_request_permission,
payload,
),
elicit: (payload) =>
request<AcpSchema.ElicitationResponse>(CLIENT_METHODS.session_elicitation, payload),
readTextFile: (payload) =>
request<AcpSchema.ReadTextFileResponse>(CLIENT_METHODS.fs_read_text_file, payload),
writeTextFile: (payload) =>
request<AcpSchema.WriteTextFileResponse>(CLIENT_METHODS.fs_write_text_file, payload).pipe(
Effect.map((response) => response ?? {}),
),
createTerminal: (payload) =>
request<AcpSchema.CreateTerminalResponse>(CLIENT_METHODS.terminal_create, payload).pipe(
Effect.map((response) =>
AcpTerminal.makeTerminal({
sessionId: payload.sessionId,
terminalId: response.terminalId,
output: request<AcpSchema.TerminalOutputResponse>(CLIENT_METHODS.terminal_output, {
sessionId: payload.sessionId,
terminalId: response.terminalId,
}),
waitForExit: request<AcpSchema.WaitForTerminalExitResponse>(
CLIENT_METHODS.terminal_wait_for_exit,
{
sessionId: payload.sessionId,
terminalId: response.terminalId,
},
),
kill: request<AcpSchema.KillTerminalResponse>(CLIENT_METHODS.terminal_kill, {
sessionId: payload.sessionId,
terminalId: response.terminalId,
}).pipe(Effect.map((result) => result ?? {})),
release: request<AcpSchema.ReleaseTerminalResponse>(CLIENT_METHODS.terminal_release, {
sessionId: payload.sessionId,
terminalId: response.terminalId,
}).pipe(Effect.map((result) => result ?? {})),
}),
),
),
extRequest: transport.sendRequest,
elicitationComplete: (payload) =>
transport.notifications.sendExtNotification(
CLIENT_METHODS.session_elicitation_complete,
payload,
),
extNotification: transport.notifications.sendExtNotification,
};
};
@@ -13,71 +13,61 @@ Effect.gen(function* () {
shell: process.platform === "win32",
});
const handle = yield* spawner.spawn(command);
const client = yield* AcpClient.fromChildProcess(handle, {
const acpLayer = AcpClient.layerFromChildProcessHandle(handle, {
logIncoming: true,
logOutgoing: true,
handlers: {
requestPermission: () =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
sessionUpdate: (notification) => Effect.logInfo("session/update", notification),
},
});
const initialized = yield* client.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-example",
version: "0.0.0",
},
});
yield* Effect.logInfo("initialized", initialized);
yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpConnection;
const session = yield* client.createSession({
cwd: process.cwd(),
mcpServers: [],
});
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
yield* acp.handleSessionUpdate((notification) =>
Effect.logInfo("session/update", notification),
);
yield* client.setSessionConfigOption({
sessionId: session.sessionId,
configId: "model",
value: "gpt-5.4[reasoning=medium,context=272k,fast=false]",
});
// yield* client.setSessionConfigOption({
// sessionId: session.sessionId,
// configId: "reasoning_effort",
// value: "high",
// });
// yield* client.setSessionConfigOption({
// sessionId: session.sessionId,
// configId: "context_size",
// value: "1m",
// });
// yield* client.setSessionConfigOption({
// sessionId: session.sessionId,
// configId: "fast_mode",
// type: "boolean",
// value: true,
// });
const result = yield* client.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!",
const initialized = yield* acp.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
],
});
clientInfo: {
name: "effect-acp-example",
version: "0.0.0",
},
});
yield* Effect.logInfo("initialized", initialized);
yield* Effect.logInfo("prompt result", result);
yield* client.cancel({ sessionId: session.sessionId });
const session = yield* acp.createSession({
cwd: process.cwd(),
mcpServers: [],
});
yield* acp.setSessionConfigOption({
sessionId: session.sessionId,
configId: "model",
value: "gpt-5.4[reasoning=medium,context=272k,fast=false]",
});
const result = yield* acp.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* Effect.logInfo("prompt result", result);
yield* acp.cancel({ sessionId: session.sessionId });
}).pipe(Effect.provide(acpLayer));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);