servicify
This commit is contained in:
1 parent
e43002eaf1
commit
d4511012f4
11 files changed
+1728
-1424
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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
@@ -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([]),
|
||||
|
||||
@@ -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
@@ -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 } {
|
||||
|
||||
@@ -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);
|
||||
Reference in new issue
Block a user