agent/client separation
This commit is contained in:
1 parent
b750558c10
commit
ffccd63d1e
14 files changed
+649
-1202
No files matched your search
@@ -1,31 +1,33 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Minimal NDJSON JSON-RPC "agent" for ACP client tests.
|
||||
* Reads stdin lines; writes responses/notifications to stdout.
|
||||
*/
|
||||
import * as readline from "node:readline";
|
||||
import { appendFileSync } from "node:fs";
|
||||
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "effect-acp/schema";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as EffectAcpAgent from "effect-acp/agent";
|
||||
import * as AcpError from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/schema";
|
||||
|
||||
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let nextRequestId = 1;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function configOptions() {
|
||||
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
type: "select" as const,
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
@@ -37,7 +39,7 @@ function configOptions() {
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes = [
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
@@ -54,227 +56,113 @@ const availableModes = [
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
const pendingPermissionRequests = new Map();
|
||||
const pendingAskQuestionRequests = new Map();
|
||||
const cancelledPromptRequestIds = new Set<number | string>();
|
||||
|
||||
function send(obj: unknown) {
|
||||
process.stdout.write(`${JSON.stringify(obj)}\n`);
|
||||
}
|
||||
|
||||
function modeState() {
|
||||
function modeState(): AcpSchema.SessionModeState {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
function sendSessionUpdate(update: unknown, session = sessionId) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: CLIENT_METHODS.session_update,
|
||||
params: {
|
||||
sessionId: session,
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
|
||||
rl.on("line", (line) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(trimmed);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!msg || typeof msg !== "object") return;
|
||||
if (requestLogPath) {
|
||||
appendFileSync(requestLogPath, `${JSON.stringify(msg)}\n`, "utf8");
|
||||
}
|
||||
yield* agent.handleInitialize(() =>
|
||||
Effect.succeed({
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
}),
|
||||
);
|
||||
|
||||
const rpcMessage = msg as {
|
||||
id?: number | string;
|
||||
method?: string;
|
||||
params?: Record<string, unknown>;
|
||||
};
|
||||
const id = rpcMessage.id;
|
||||
const method = rpcMessage.method;
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
|
||||
if (method === undefined && id !== undefined && pendingPermissionRequests.has(id)) {
|
||||
const pending = pendingPermissionRequests.get(id);
|
||||
pendingPermissionRequests.delete(id);
|
||||
const outcome = (rpcMessage.params?.outcome ??
|
||||
(msg as { result?: { outcome?: unknown } }).result?.outcome) as
|
||||
| { outcome?: unknown }
|
||||
| undefined;
|
||||
const cancelled =
|
||||
cancelledPromptRequestIds.has(pending.promptRequestId) ||
|
||||
(typeof outcome === "object" &&
|
||||
outcome !== null &&
|
||||
"outcome" in outcome &&
|
||||
outcome.outcome === "cancelled");
|
||||
cancelledPromptRequestIds.delete(pending.promptRequestId);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: pending.toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
},
|
||||
pending.sessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
pending.sessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: pending.promptRequestId,
|
||||
result: { stopReason: cancelled ? "cancelled" : "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (method === undefined && id !== undefined && pendingAskQuestionRequests.has(id)) {
|
||||
const pending = pendingAskQuestionRequests.get(id);
|
||||
pendingAskQuestionRequests.delete(id);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: pending.promptRequestId,
|
||||
result: { stopReason: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.initialize && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.authenticate && id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: { authenticated: true } });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.session_new && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.session_load && id !== undefined) {
|
||||
const requestedSessionId = rpcMessage.params?.sessionId ?? sessionId;
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
String(requestedSessionId),
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.session_set_config_option && id !== undefined) {
|
||||
if (exitOnSetConfigOption) {
|
||||
process.exit(7);
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: {
|
||||
code: -32602,
|
||||
message: "Mock invalid params for session/set_config_option",
|
||||
data: {
|
||||
method,
|
||||
params: rpcMessage.params,
|
||||
yield* agent.handleSetSessionConfigOption((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (exitOnSetConfigOption) {
|
||||
return yield* Effect.sync(() => {
|
||||
process.exit(7);
|
||||
});
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
"Mock invalid params for session/set_config_option",
|
||||
{
|
||||
method: "session/set_config_option",
|
||||
params: request,
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
const configId = rpcMessage.params?.configId;
|
||||
const value = rpcMessage.params?.value;
|
||||
if (configId === "model" && typeof value === "string") {
|
||||
currentModelId = value;
|
||||
}
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: { configOptions: configOptions() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
);
|
||||
}
|
||||
if (request.configId === "model" && typeof request.value === "string") {
|
||||
currentModelId = request.value;
|
||||
}
|
||||
return {
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
if (method === AGENT_METHODS.session_prompt && id !== undefined) {
|
||||
const requestedSessionId = String(rpcMessage.params?.sessionId ?? sessionId);
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
const permissionRequestId = nextRequestId++;
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
},
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
pendingPermissionRequests.set(permissionRequestId, {
|
||||
promptRequestId: id,
|
||||
sessionId: requestedSessionId,
|
||||
toolCallId,
|
||||
});
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: permissionRequestId,
|
||||
method: CLIENT_METHODS.session_request_permission,
|
||||
params: {
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
@@ -296,21 +184,41 @@ rl.on("line", (line) => {
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (emitAskQuestion) {
|
||||
const askQuestionRequestId = nextRequestId++;
|
||||
pendingAskQuestionRequests.set(askQuestionRequestId, {
|
||||
promptRequestId: id,
|
||||
sessionId: requestedSessionId,
|
||||
});
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: askQuestionRequestId,
|
||||
method: "cursor/ask_question",
|
||||
params: {
|
||||
});
|
||||
|
||||
const cancelled =
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: cancelled ? "cancelled" : "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
title: "Question",
|
||||
questions: [
|
||||
@@ -323,83 +231,112 @@ rl.on("line", (line) => {
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "plan",
|
||||
explanation: `Mock plan while in ${currentModeId}`,
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: { stopReason: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
(method === AGENT_METHODS.session_set_mode || method === "session/mode/set") &&
|
||||
id !== undefined
|
||||
) {
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
|
||||
const nextModeId =
|
||||
typeof rpcMessage.params?.modeId === "string"
|
||||
? rpcMessage.params.modeId
|
||||
: typeof rpcMessage.params?.mode === "string"
|
||||
? rpcMessage.params.mode
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"modeId" in params &&
|
||||
typeof params.modeId === "string"
|
||||
? params.modeId
|
||||
: typeof params === "object" &&
|
||||
params !== null &&
|
||||
"mode" in params &&
|
||||
typeof params.mode === "string"
|
||||
? params.mode
|
||||
: undefined;
|
||||
const requestedSessionId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"sessionId" in params &&
|
||||
typeof params.sessionId === "string"
|
||||
? params.sessionId
|
||||
: sessionId;
|
||||
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
sendSessionUpdate({
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
});
|
||||
return agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.as({}));
|
||||
}
|
||||
send({ jsonrpc: "2.0", id, result: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.session_cancel) {
|
||||
const cancelledSessionId = rpcMessage.params?.sessionId;
|
||||
for (const pending of pendingPermissionRequests.values()) {
|
||||
if (pending.sessionId === cancelledSessionId) {
|
||||
cancelledPromptRequestIds.add(pending.promptRequestId);
|
||||
}
|
||||
}
|
||||
if (id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: null });
|
||||
}
|
||||
return;
|
||||
}
|
||||
return Effect.succeed({});
|
||||
});
|
||||
|
||||
if (id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: { code: -32601, message: `Unhandled method: ${String(method)}` },
|
||||
});
|
||||
}
|
||||
});
|
||||
return yield* Effect.never;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EffectAcpAgent.layerStdio(
|
||||
requestLogPath
|
||||
? {
|
||||
logIncoming: true,
|
||||
logger: (event) => {
|
||||
if (event.direction !== "incoming" || event.stage !== "raw") {
|
||||
return Effect.void;
|
||||
}
|
||||
if (typeof event.payload !== "string") {
|
||||
return Effect.void;
|
||||
}
|
||||
const payload = event.payload;
|
||||
return Effect.sync(() => {
|
||||
appendFileSync(
|
||||
requestLogPath,
|
||||
payload.endsWith("\n") ? payload : `${payload}\n`,
|
||||
"utf8",
|
||||
);
|
||||
});
|
||||
},
|
||||
}
|
||||
: {},
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
NodeRuntime.runMain(program);
|
||||
@@ -71,21 +71,21 @@ export interface AcpSessionRuntimeStartResult {
|
||||
}
|
||||
|
||||
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 handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"];
|
||||
readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"];
|
||||
readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"];
|
||||
readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"];
|
||||
readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"];
|
||||
readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"];
|
||||
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"];
|
||||
readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"];
|
||||
readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"];
|
||||
readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"];
|
||||
readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"];
|
||||
readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"];
|
||||
readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"];
|
||||
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
|
||||
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
@@ -204,7 +204,7 @@ const makeAcpSessionRuntime = (
|
||||
);
|
||||
|
||||
const acpContext = yield* Layer.build(
|
||||
EffectAcpClient.layerFromChildProcessHandle(child, {
|
||||
EffectAcpClient.layerChildProcess(child, {
|
||||
...(options.protocolLogging?.logIncoming !== undefined
|
||||
? { logIncoming: options.protocolLogging.logIncoming }
|
||||
: {}),
|
||||
@@ -215,9 +215,7 @@ const makeAcpSessionRuntime = (
|
||||
}),
|
||||
).pipe(Effect.provideService(Scope.Scope, runtimeScope));
|
||||
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpConnection).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
handleSessionUpdate({
|
||||
@@ -320,7 +318,7 @@ const makeAcpSessionRuntime = (
|
||||
return runLoggedRequest(
|
||||
"session/set_config_option",
|
||||
requestPayload,
|
||||
acp.setSessionConfigOption(requestPayload),
|
||||
acp.agent.setSessionConfigOption(requestPayload),
|
||||
).pipe(Effect.tap((response) => updateConfigOptions(response)));
|
||||
}),
|
||||
);
|
||||
@@ -338,7 +336,7 @@ const makeAcpSessionRuntime = (
|
||||
const initializeResult = yield* runLoggedRequest(
|
||||
"initialize",
|
||||
initializePayload,
|
||||
acp.initialize(initializePayload),
|
||||
acp.agent.initialize(initializePayload),
|
||||
);
|
||||
|
||||
const authenticatePayload = {
|
||||
@@ -348,7 +346,7 @@ const makeAcpSessionRuntime = (
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.authenticate(authenticatePayload),
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
|
||||
let sessionId: string;
|
||||
@@ -365,7 +363,7 @@ const makeAcpSessionRuntime = (
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.loadSession(loadPayload),
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
@@ -378,7 +376,7 @@ const makeAcpSessionRuntime = (
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.createSession(createPayload),
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
@@ -391,7 +389,7 @@ const makeAcpSessionRuntime = (
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.createSession(createPayload),
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
@@ -467,34 +465,27 @@ const makeAcpSessionRuntime = (
|
||||
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",
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.setSessionMode(requestPayload),
|
||||
acp.agent.prompt(requestPayload),
|
||||
);
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
),
|
||||
setMode: (modeId) =>
|
||||
getStartedState.pipe(Effect.flatMap(() => setConfigOption("mode", modeId))),
|
||||
setConfigOption,
|
||||
setModel: (model) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
request: (method, payload) => runLoggedRequest(method, payload, acp.request(method, payload)),
|
||||
notify: acp.notify,
|
||||
request: (method, payload) =>
|
||||
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
|
||||
notify: acp.raw.notify,
|
||||
close,
|
||||
} satisfies AcpSessionRuntimeShape;
|
||||
});
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
"types": "./src/client.ts",
|
||||
"import": "./src/client.ts"
|
||||
},
|
||||
"./agent": {
|
||||
"types": "./src/agent.ts",
|
||||
"import": "./src/agent.ts"
|
||||
},
|
||||
"./schema": {
|
||||
"types": "./src/schema.ts",
|
||||
"import": "./src/schema.ts"
|
||||
@@ -29,8 +33,8 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"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",
|
||||
"dev": "tsdown src/client.ts src/agent.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/terminal.ts --format esm,cjs --dts --watch --clean",
|
||||
"build": "tsdown src/client.ts src/agent.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/terminal.ts --format esm,cjs --dts --clean",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
|
||||
@@ -3,8 +3,8 @@ import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import { RpcClientError } from "effect/unstable/rpc";
|
||||
|
||||
import * as AcpSchema from "../_generated/schema.gen.ts";
|
||||
import * as AcpError from "../errors.ts";
|
||||
import * as AcpSchema from "../_generated/schema.gen";
|
||||
import * as AcpError from "../errors";
|
||||
|
||||
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
|
||||
|
||||
@@ -31,7 +31,7 @@ export const runHandler = Effect.fnUntraced(function* <A, B>(
|
||||
method: string,
|
||||
) {
|
||||
if (!handler) {
|
||||
return yield* Effect.fail(AcpError.AcpRequestError.methodNotFound(method).toProtocolError());
|
||||
return yield* AcpError.AcpRequestError.methodNotFound(method);
|
||||
}
|
||||
return yield* handler(payload).pipe(
|
||||
Effect.mapError((error) =>
|
||||
|
||||
@@ -6,7 +6,7 @@ import * as Sink from "effect/Sink";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as AcpError from "../errors.ts";
|
||||
import * as AcpError from "../errors";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
@@ -10,15 +10,15 @@ import * as Scope from "effect/Scope";
|
||||
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import * as AcpAgent from "./agent.ts";
|
||||
import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
import * as AcpAgent from "./agent";
|
||||
import * as AcpSchema from "./_generated/schema.gen";
|
||||
import {
|
||||
encodeJsonl,
|
||||
jsonRpcNotification,
|
||||
jsonRpcRequest,
|
||||
jsonRpcResponse,
|
||||
} from "./_internal/shared.ts";
|
||||
import { makeInMemoryStdio } from "./_internal/stdio.ts";
|
||||
} from "./_internal/shared";
|
||||
import { makeInMemoryStdio } from "./_internal/stdio";
|
||||
|
||||
const RequestPermissionRequest = jsonRpcRequest(
|
||||
"session/request_permission",
|
||||
@@ -32,8 +32,6 @@ const SessionCancelNotification = jsonRpcNotification(
|
||||
AcpSchema.CancelNotification,
|
||||
);
|
||||
const ExtPingNotification = jsonRpcNotification("x/ping", Schema.Struct({ count: Schema.Number }));
|
||||
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
|
||||
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
|
||||
|
||||
it.effect("effect-acp agent handles core agent requests and outbound client requests", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -87,6 +85,7 @@ it.effect("effect-acp agent handles core agent requests and outbound client requ
|
||||
Schema.fromJsonString(RequestPermissionRequest),
|
||||
)(yield* Queue.take(output));
|
||||
assert.equal(permissionRequest.jsonrpc, "2.0");
|
||||
assert.equal(permissionRequest.id, 1);
|
||||
assert.equal(permissionRequest.method, "session/request_permission");
|
||||
assert.deepEqual(permissionRequest.params, {
|
||||
sessionId: "session-1",
|
||||
@@ -102,7 +101,7 @@ it.effect("effect-acp agent handles core agent requests and outbound client requ
|
||||
input,
|
||||
yield* encodeJsonl(RequestPermissionResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: permissionRequest.id,
|
||||
id: 1,
|
||||
result: {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
@@ -178,78 +177,3 @@ it.effect("effect-acp agent handles core agent requests and outbound client requ
|
||||
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("effect-acp agent uses distinct ids for RPC calls and extension requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
const scope = yield* Scope.make();
|
||||
const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const agent = yield* AcpAgent.AcpAgent;
|
||||
|
||||
const permissionFiber = yield* agent.client
|
||||
.requestPermission({
|
||||
sessionId: "session-1",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
title: "Allow mock action",
|
||||
},
|
||||
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
const extFiber = yield* agent.client
|
||||
.extRequest("x/test", { hello: "world" })
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const firstOutbound = yield* Queue.take(output);
|
||||
const secondOutbound = yield* Queue.take(output);
|
||||
|
||||
const decodedPermission = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RequestPermissionRequest),
|
||||
);
|
||||
const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
|
||||
const firstIsPermission = yield* decodedPermission(firstOutbound).pipe(
|
||||
Effect.match({
|
||||
onFailure: () => false,
|
||||
onSuccess: () => true,
|
||||
}),
|
||||
);
|
||||
|
||||
const permissionRequest = firstIsPermission
|
||||
? yield* decodedPermission(firstOutbound)
|
||||
: yield* decodedPermission(secondOutbound);
|
||||
const extRequest = firstIsPermission
|
||||
? yield* decodedExt(secondOutbound)
|
||||
: yield* decodedExt(firstOutbound);
|
||||
|
||||
assert.notEqual(permissionRequest.id, extRequest.id);
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(RequestPermissionResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: permissionRequest.id,
|
||||
result: {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(ExtResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: extRequest.id,
|
||||
result: { ok: true },
|
||||
}),
|
||||
);
|
||||
|
||||
const permission = yield* Fiber.join(permissionFiber);
|
||||
assert.equal(permission.outcome.outcome, "selected");
|
||||
assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
|
||||
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
|
||||
}),
|
||||
);
|
||||
@@ -1,25 +1,25 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as ServiceMap from "effect/ServiceMap";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
import * as RpcClient from "effect/unstable/rpc/RpcClient";
|
||||
import * as RpcServer from "effect/unstable/rpc/RpcServer";
|
||||
|
||||
import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts";
|
||||
import * as AcpError from "./errors.ts";
|
||||
import * as AcpProtocol from "./protocol.ts";
|
||||
import * as AcpRpcs from "./rpc.ts";
|
||||
import * as AcpSchema from "./_generated/schema.gen";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen";
|
||||
import * as AcpError from "./errors";
|
||||
import * as AcpProtocol from "./protocol";
|
||||
import * as AcpRpcs from "./rpc";
|
||||
import {
|
||||
callRpc,
|
||||
decodeExtNotificationRegistration,
|
||||
decodeExtRequestRegistration,
|
||||
runHandler,
|
||||
} from "./_internal/shared.ts";
|
||||
import * as AcpTerminal from "./terminal.ts";
|
||||
} from "./_internal/shared";
|
||||
import * as AcpTerminal from "./terminal";
|
||||
|
||||
export interface AcpAgentOptions {
|
||||
readonly logIncoming?: boolean;
|
||||
@@ -207,7 +207,9 @@ export interface AcpAgentShape {
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class AcpAgent extends Context.Service<AcpAgent, AcpAgentShape>()("effect-acp/AcpAgent") {}
|
||||
export class AcpAgent extends ServiceMap.Service<AcpAgent, AcpAgentShape>()(
|
||||
"effect-acp/AcpAgent",
|
||||
) {}
|
||||
|
||||
interface AcpCoreAgentRequestHandlers {
|
||||
initialize?: (
|
||||
@@ -360,7 +362,7 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
let nextRpcRequestId = 1n << 32n;
|
||||
let nextRpcRequestId = 1n;
|
||||
const rpc = yield* RpcClient.make(AcpRpcs.ClientRpcs, {
|
||||
generateRequestId: () => nextRpcRequestId++ as never,
|
||||
}).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
|
||||
|
||||
@@ -39,11 +39,11 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
const typedNotifications = yield* Ref.make<Array<unknown>>([]);
|
||||
const handle = yield* makeHandle();
|
||||
const scope = yield* Scope.make();
|
||||
const acpLayer = AcpClient.layerFromChildProcessHandle(handle);
|
||||
const acpLayer = AcpClient.layerChildProcess(handle);
|
||||
const context = yield* Layer.buildWithScope(acpLayer, scope);
|
||||
|
||||
const ext = yield* Effect.gen(function* () {
|
||||
const acp = yield* AcpClient.AcpConnection;
|
||||
const acp = yield* AcpClient.AcpClient;
|
||||
|
||||
yield* acp.handleRequestPermission(() =>
|
||||
Effect.succeed({
|
||||
@@ -86,7 +86,7 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
(payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
|
||||
);
|
||||
|
||||
const init = yield* acp.initialize({
|
||||
const init = yield* acp.agent.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
@@ -99,21 +99,21 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
});
|
||||
assert.equal(init.protocolVersion, 1);
|
||||
|
||||
yield* acp.authenticate({ methodId: "cursor_login" });
|
||||
yield* acp.agent.authenticate({ methodId: "cursor_login" });
|
||||
|
||||
const session = yield* acp.createSession({
|
||||
const session = yield* acp.agent.createSession({
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
assert.equal(session.sessionId, "mock-session-1");
|
||||
|
||||
const prompt = yield* acp.prompt({
|
||||
const prompt = yield* acp.agent.prompt({
|
||||
sessionId: session.sessionId,
|
||||
prompt: [{ type: "text", text: "hello" }],
|
||||
});
|
||||
assert.equal(prompt.stopReason, "end_turn");
|
||||
|
||||
const streamed = yield* Stream.runCollect(Stream.take(acp.notifications, 2));
|
||||
const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
|
||||
assert.equal(streamed.length, 2);
|
||||
assert.equal(streamed[0]?._tag, "SessionUpdate");
|
||||
assert.equal(streamed[1]?._tag, "ElicitationComplete");
|
||||
@@ -122,7 +122,7 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
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", {
|
||||
return yield* acp.raw.request("x/echo", {
|
||||
hello: "world",
|
||||
});
|
||||
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
|
||||
@@ -142,11 +142,11 @@ 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 acpLayer = AcpClient.layerChildProcess(handle);
|
||||
const context = yield* Layer.buildWithScope(acpLayer, scope);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const acp = yield* AcpClient.AcpConnection;
|
||||
const acp = yield* AcpClient.AcpClient;
|
||||
|
||||
yield* acp.handleRequestPermission(() =>
|
||||
Effect.succeed({
|
||||
@@ -172,7 +172,7 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
() => Effect.succeed({ ok: true }),
|
||||
);
|
||||
|
||||
yield* acp.initialize({
|
||||
yield* acp.agent.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
@@ -184,15 +184,15 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
},
|
||||
});
|
||||
|
||||
yield* acp.authenticate({ methodId: "cursor_login" });
|
||||
yield* acp.agent.authenticate({ methodId: "cursor_login" });
|
||||
|
||||
const session = yield* acp.createSession({
|
||||
const session = yield* acp.agent.createSession({
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
|
||||
return yield* Effect.exit(
|
||||
acp.prompt({
|
||||
acp.agent.prompt({
|
||||
sessionId: session.sessionId,
|
||||
prompt: [{ type: "text", text: "hello" }],
|
||||
}),
|
||||
|
||||
+154
-371
@@ -1,37 +1,134 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import * as Scope from "effect/Scope";
|
||||
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 AcpSchema from "./_generated/schema.gen";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen";
|
||||
import * as AcpTerminal from "./terminal";
|
||||
import {
|
||||
callRpc,
|
||||
decodeExtNotificationRegistration,
|
||||
decodeExtRequestRegistration,
|
||||
runHandler,
|
||||
} from "./_internal/shared";
|
||||
import { makeChildStdio, makeTerminationError } from "./_internal/stdio";
|
||||
|
||||
export interface AcpConnectionOptions {
|
||||
export interface AcpClientOptions {
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface AcpConnectionShape {
|
||||
readonly process: ChildProcessSpawner.ChildProcessHandle;
|
||||
/**
|
||||
* Stream of inbound ACP notifications observed on the connection.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/update
|
||||
*/
|
||||
type AcpClientRaw = {
|
||||
readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
|
||||
readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
|
||||
};
|
||||
|
||||
export interface AcpClientShape {
|
||||
readonly raw: AcpClientRaw;
|
||||
readonly agent: {
|
||||
/**
|
||||
* Initializes the ACP session and negotiates capabilities.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#initialize
|
||||
*/
|
||||
readonly initialize: (
|
||||
payload: AcpSchema.InitializeRequest,
|
||||
) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Performs ACP authentication when the agent requires it.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#authenticate
|
||||
*/
|
||||
readonly authenticate: (
|
||||
payload: AcpSchema.AuthenticateRequest,
|
||||
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Logs out the current ACP identity.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#logout
|
||||
*/
|
||||
readonly logout: (
|
||||
payload: AcpSchema.LogoutRequest,
|
||||
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Starts a new ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/new
|
||||
*/
|
||||
readonly createSession: (
|
||||
payload: AcpSchema.NewSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Loads a previously saved ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/load
|
||||
*/
|
||||
readonly loadSession: (
|
||||
payload: AcpSchema.LoadSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Lists available ACP sessions.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/list
|
||||
*/
|
||||
readonly listSessions: (
|
||||
payload: AcpSchema.ListSessionsRequest,
|
||||
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Forks an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/fork
|
||||
*/
|
||||
readonly forkSession: (
|
||||
payload: AcpSchema.ForkSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Resumes an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/resume
|
||||
*/
|
||||
readonly resumeSession: (
|
||||
payload: AcpSchema.ResumeSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Closes an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/close
|
||||
*/
|
||||
readonly closeSession: (
|
||||
payload: AcpSchema.CloseSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Selects the active model for a session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_model
|
||||
*/
|
||||
readonly setSessionModel: (
|
||||
payload: AcpSchema.SetSessionModelRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Updates a session configuration option.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
|
||||
*/
|
||||
readonly setSessionConfigOption: (
|
||||
payload: AcpSchema.SetSessionConfigOptionRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a prompt turn to the agent.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
|
||||
*/
|
||||
readonly prompt: (
|
||||
payload: AcpSchema.PromptRequest,
|
||||
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a real ACP `session/cancel` notification.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
|
||||
*/
|
||||
readonly cancel: (
|
||||
payload: AcpSchema.CancelNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError>;
|
||||
};
|
||||
/**
|
||||
* Registers a handler for `session/request_permission`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
|
||||
@@ -163,230 +260,37 @@ export interface AcpConnectionShape {
|
||||
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
|
||||
*/
|
||||
readonly initialize: (
|
||||
payload: AcpSchema.InitializeRequest,
|
||||
) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Performs ACP authentication when the agent requires it.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#authenticate
|
||||
*/
|
||||
readonly authenticate: (
|
||||
payload: AcpSchema.AuthenticateRequest,
|
||||
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Logs out the current ACP identity.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#logout
|
||||
*/
|
||||
readonly logout: (
|
||||
payload: AcpSchema.LogoutRequest,
|
||||
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Starts a new ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/new
|
||||
*/
|
||||
readonly createSession: (
|
||||
payload: AcpSchema.NewSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Loads a previously saved ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/load
|
||||
*/
|
||||
readonly loadSession: (
|
||||
payload: AcpSchema.LoadSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Lists available ACP sessions.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/list
|
||||
*/
|
||||
readonly listSessions: (
|
||||
payload: AcpSchema.ListSessionsRequest,
|
||||
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Forks an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/fork
|
||||
*/
|
||||
readonly forkSession: (
|
||||
payload: AcpSchema.ForkSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Resumes an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/resume
|
||||
*/
|
||||
readonly resumeSession: (
|
||||
payload: AcpSchema.ResumeSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Closes an ACP session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/close
|
||||
*/
|
||||
readonly closeSession: (
|
||||
payload: AcpSchema.CloseSessionRequest,
|
||||
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Changes the current session mode.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_mode
|
||||
*/
|
||||
readonly setSessionMode: (
|
||||
payload: AcpSchema.SetSessionModeRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionModeResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Selects the active model for a session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_model
|
||||
*/
|
||||
readonly setSessionModel: (
|
||||
payload: AcpSchema.SetSessionModelRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Updates a session configuration option.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
|
||||
*/
|
||||
readonly setSessionConfigOption: (
|
||||
payload: AcpSchema.SetSessionConfigOptionRequest,
|
||||
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a prompt turn to the agent.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
|
||||
*/
|
||||
readonly prompt: (
|
||||
payload: AcpSchema.PromptRequest,
|
||||
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends a real ACP `session/cancel` notification.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
|
||||
*/
|
||||
readonly cancel: (
|
||||
payload: AcpSchema.CancelNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends an ACP extension request.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
/**
|
||||
* Sends an ACP extension notification.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
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 class AcpConnection extends ServiceMap.Service<AcpConnection, AcpConnectionShape>()(
|
||||
"effect-acp/AcpConnection",
|
||||
export class AcpClient extends ServiceMap.Service<AcpClient, AcpClientShape>()(
|
||||
"effect-acp/AcpClient",
|
||||
) {}
|
||||
|
||||
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>;
|
||||
@@ -403,13 +307,11 @@ interface AcpNotificationHandlers {
|
||||
>;
|
||||
}
|
||||
|
||||
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
export const makeFromChildProcessHandle = Effect.fn("makeFromChildProcessHandle")(function* (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
options: AcpConnectionOptions = {},
|
||||
): Effect.fn.Return<AcpConnectionShape, never, Scope.Scope> {
|
||||
export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
|
||||
stdio: Stdio.Stdio,
|
||||
options: AcpClientOptions = {},
|
||||
terminationError?: Effect.Effect<AcpError.AcpError>,
|
||||
): Effect.fn.Return<AcpClientShape, never, Scope.Scope> {
|
||||
const coreHandlers: AcpCoreRequestHandlers = {};
|
||||
const notificationHandlers: AcpNotificationHandlers = {
|
||||
sessionUpdate: [],
|
||||
@@ -467,7 +369,8 @@ export const makeFromChildProcessHandle = Effect.fn("makeFromChildProcessHandle"
|
||||
};
|
||||
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: makeStdioFromChildProcess(handle),
|
||||
stdio: stdio,
|
||||
...(terminationError ? { terminationError } : {}),
|
||||
serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()),
|
||||
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
|
||||
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
|
||||
@@ -519,31 +422,33 @@ export const makeFromChildProcessHandle = Effect.fn("makeFromChildProcessHandle"
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs).pipe(
|
||||
Effect.provideService(RpcClient.Protocol, transport.clientProtocol),
|
||||
);
|
||||
let nextRpcRequestId = 1n;
|
||||
const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs, {
|
||||
generateRequestId: () => nextRpcRequestId++ as never,
|
||||
}).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
|
||||
|
||||
const callRpc = <A>(effect: Effect.Effect<A, RpcClientError.RpcClientError | AcpSchema.Error>) =>
|
||||
effect.pipe(
|
||||
Effect.catchTag("RpcClientError", (error) =>
|
||||
Effect.fail(
|
||||
new AcpError.AcpTransportError({
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(Schema.is(AcpSchema.Error), (error) =>
|
||||
Effect.fail(AcpError.AcpRequestError.fromProtocolError(error)),
|
||||
),
|
||||
);
|
||||
|
||||
const request = <A>(method: string, payload: unknown) =>
|
||||
transport.request(method, payload).pipe(Effect.map((value) => value as A));
|
||||
|
||||
return AcpConnection.of({
|
||||
process: handle,
|
||||
notifications: transport.incoming,
|
||||
return AcpClient.of({
|
||||
raw: {
|
||||
notifications: transport.incoming,
|
||||
request: transport.request,
|
||||
notify: transport.notify,
|
||||
},
|
||||
agent: {
|
||||
initialize: (payload) => callRpc(rpc[AGENT_METHODS.initialize](payload)),
|
||||
authenticate: (payload) => callRpc(rpc[AGENT_METHODS.authenticate](payload)),
|
||||
logout: (payload) => callRpc(rpc[AGENT_METHODS.logout](payload)),
|
||||
createSession: (payload) => callRpc(rpc[AGENT_METHODS.session_new](payload)),
|
||||
loadSession: (payload) => callRpc(rpc[AGENT_METHODS.session_load](payload)),
|
||||
listSessions: (payload) => callRpc(rpc[AGENT_METHODS.session_list](payload)),
|
||||
forkSession: (payload) => callRpc(rpc[AGENT_METHODS.session_fork](payload)),
|
||||
resumeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_resume](payload)),
|
||||
closeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_close](payload)),
|
||||
setSessionModel: (payload) => callRpc(rpc[AGENT_METHODS.session_set_model](payload)),
|
||||
setSessionConfigOption: (payload) =>
|
||||
callRpc(rpc[AGENT_METHODS.session_set_config_option](payload)),
|
||||
prompt: (payload) => callRpc(rpc[AGENT_METHODS.session_prompt](payload)),
|
||||
cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),
|
||||
},
|
||||
handleRequestPermission: (handler) =>
|
||||
Effect.suspend(() => {
|
||||
coreHandlers.requestPermission = handler;
|
||||
@@ -622,136 +527,14 @@ export const makeFromChildProcessHandle = Effect.fn("makeFromChildProcessHandle"
|
||||
);
|
||||
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)),
|
||||
createSession: (payload) => callRpc(rpc[AGENT_METHODS.session_new](payload)),
|
||||
loadSession: (payload) => callRpc(rpc[AGENT_METHODS.session_load](payload)),
|
||||
listSessions: (payload) => callRpc(rpc[AGENT_METHODS.session_list](payload)),
|
||||
forkSession: (payload) => callRpc(rpc[AGENT_METHODS.session_fork](payload)),
|
||||
resumeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_resume](payload)),
|
||||
closeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_close](payload)),
|
||||
setSessionMode: (payload) => callRpc(rpc[AGENT_METHODS.session_set_mode](payload)),
|
||||
setSessionModel: (payload) => callRpc(rpc[AGENT_METHODS.session_set_model](payload)),
|
||||
setSessionConfigOption: (payload) =>
|
||||
callRpc(rpc[AGENT_METHODS.session_set_config_option](payload)),
|
||||
prompt: (payload) => callRpc(rpc[AGENT_METHODS.session_prompt](payload)),
|
||||
cancel: (payload) => transport.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,
|
||||
method: string,
|
||||
) {
|
||||
if (!handler) {
|
||||
return yield* AcpError.AcpRequestError.methodNotFound(method);
|
||||
}
|
||||
return yield* handler(payload).pipe(
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(AcpError.AcpRequestError)(error)
|
||||
? error.toProtocolError()
|
||||
: AcpError.AcpRequestError.internalError(error.message).toProtocolError(),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function decodeExtRequestRegistration<A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
) {
|
||||
return (params: unknown): Effect.Effect<unknown, AcpError.AcpError> =>
|
||||
Schema.decodeUnknownEffect(payload)(params).pipe(
|
||||
Effect.mapError((error) =>
|
||||
AcpError.AcpRequestError.invalidParams(
|
||||
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
|
||||
{ issue: error.issue },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((decoded) => handler(decoded)),
|
||||
);
|
||||
}
|
||||
|
||||
function decodeExtNotificationRegistration<A, I>(
|
||||
method: string,
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
|
||||
) {
|
||||
return (params: unknown): Effect.Effect<void, AcpError.AcpError> =>
|
||||
Schema.decodeUnknownEffect(payload)(params).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${method} notification payload: ${formatSchemaIssue(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((decoded) => handler(decoded)),
|
||||
);
|
||||
}
|
||||
|
||||
function makeStdioFromChildProcess(handle: ChildProcessSpawner.ChildProcessHandle): Stdio.Stdio {
|
||||
return Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
stdin: handle.stdout,
|
||||
stdout: () =>
|
||||
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
|
||||
typeof chunk === "string" ? textEncoder.encode(chunk) : chunk,
|
||||
),
|
||||
stderr: () => Sink.drain,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const layerChildProcess = (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
options: AcpClientOptions = {},
|
||||
): Layer.Layer<AcpClient> => {
|
||||
const stdio = makeChildStdio(handle);
|
||||
const terminationError = makeTerminationError(handle);
|
||||
return Layer.effect(AcpClient, make(stdio, options, terminationError));
|
||||
};
|
||||
@@ -1,49 +1,41 @@
|
||||
import * as Path from "effect/Path";
|
||||
import * as AcpError from "./errors";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
import * as AcpSchema from "./_generated/schema.gen";
|
||||
import * as AcpProtocol from "./protocol";
|
||||
import {
|
||||
encodeJsonl,
|
||||
jsonRpcNotification,
|
||||
jsonRpcRequest,
|
||||
jsonRpcResponse,
|
||||
} from "./_internal/shared";
|
||||
import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
const UnknownJson = Schema.UnknownFromJsonString;
|
||||
|
||||
const encodeJson = Schema.encodeSync(UnknownJson);
|
||||
const decodeJson = Schema.decodeUnknownSync(UnknownJson);
|
||||
|
||||
function makeInMemoryStdio() {
|
||||
return Effect.gen(function* () {
|
||||
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
|
||||
const output = yield* Queue.unbounded<string>();
|
||||
|
||||
return {
|
||||
stdio: Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
stdin: Stream.fromQueue(input),
|
||||
stdout: () =>
|
||||
Sink.forEach((chunk: string | Uint8Array) =>
|
||||
Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),
|
||||
),
|
||||
stderr: () => Sink.drain,
|
||||
}),
|
||||
input,
|
||||
output,
|
||||
};
|
||||
});
|
||||
}
|
||||
const SessionCancelNotification = jsonRpcNotification(
|
||||
"session/cancel",
|
||||
AcpSchema.CancelNotification,
|
||||
);
|
||||
const SessionUpdateNotification = jsonRpcNotification(
|
||||
"session/update",
|
||||
AcpSchema.SessionNotification,
|
||||
);
|
||||
const ElicitationCompleteNotification = jsonRpcNotification(
|
||||
"session/elicitation/complete",
|
||||
AcpSchema.ElicitationCompleteNotification,
|
||||
);
|
||||
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
|
||||
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
|
||||
|
||||
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
|
||||
@@ -61,32 +53,6 @@ const makeHandle = (env?: Record<string, string>) =>
|
||||
return yield* spawner.spawn(command);
|
||||
});
|
||||
|
||||
function makeChildStdio(handle: ChildProcessSpawner.ChildProcessHandle) {
|
||||
return Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
stdin: handle.stdout,
|
||||
stdout: () =>
|
||||
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
|
||||
typeof chunk === "string" ? encoder.encode(chunk) : chunk,
|
||||
),
|
||||
stderr: () => Sink.drain,
|
||||
});
|
||||
}
|
||||
|
||||
function makeProcessExit(
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
): Effect.Effect<number, AcpError.AcpProcessExitedError> {
|
||||
return handle.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpError.AcpProcessExitedError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
it.effect(
|
||||
"emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
|
||||
@@ -109,50 +75,47 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
|
||||
yield* transport.notify("session/cancel", { sessionId: "session-1" });
|
||||
const outbound = yield* Queue.take(output);
|
||||
assert.deepEqual(decodeJson(outbound), {
|
||||
jsonrpc: "2.0",
|
||||
id: "",
|
||||
headers: [],
|
||||
method: "session/cancel",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
assert.deepEqual(
|
||||
yield* Schema.decodeEffect(Schema.fromJsonString(SessionCancelNotification))(outbound),
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: "session/cancel",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encoder.encode(
|
||||
`${encodeJson({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect repository",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
})}\n`,
|
||||
),
|
||||
);
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encoder.encode(
|
||||
`${encodeJson({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/elicitation/complete",
|
||||
params: {
|
||||
elicitationId: "elicitation-1",
|
||||
yield* encodeJsonl(SessionUpdateNotification, {
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect repository",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
})}\n`,
|
||||
),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(ElicitationCompleteNotification, {
|
||||
jsonrpc: "2.0",
|
||||
method: "session/elicitation/complete",
|
||||
params: {
|
||||
elicitationId: "elicitation-1",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const [update, completion] = yield* Deferred.await(notifications);
|
||||
@@ -233,7 +196,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
.request("x/test", { hello: "world" })
|
||||
.pipe(Effect.forkScoped);
|
||||
const outbound = yield* Queue.take(output);
|
||||
assert.deepEqual(decodeJson(outbound), {
|
||||
assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "x/test",
|
||||
@@ -245,15 +208,13 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encoder.encode(
|
||||
`${encodeJson({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: {
|
||||
ok: true,
|
||||
},
|
||||
})}\n`,
|
||||
),
|
||||
yield* encodeJsonl(ExtResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: {
|
||||
ok: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const resolved = yield* Fiber.join(response);
|
||||
@@ -278,7 +239,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
.request("x/test", { hello: "world" })
|
||||
.pipe(Effect.forkScoped);
|
||||
const outbound = yield* Queue.take(output);
|
||||
assert.deepEqual(decodeJson(outbound), {
|
||||
assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "x/test",
|
||||
@@ -291,15 +252,13 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
yield* Fiber.interrupt(response);
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encoder.encode(
|
||||
`${encodeJson({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: {
|
||||
ok: true,
|
||||
},
|
||||
})}\n`,
|
||||
),
|
||||
yield* encodeJsonl(ExtResponse, {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: {
|
||||
ok: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const message = yield* Deferred.await(lateResponse);
|
||||
@@ -320,12 +279,12 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
|
||||
const firstMessage = yield* Deferred.make<unknown>();
|
||||
const processExit = yield* Deferred.make<AcpError.AcpProcessExitedError>();
|
||||
const termination = yield* Deferred.make<AcpError.AcpError>();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: makeChildStdio(handle),
|
||||
processExit: makeProcessExit(handle),
|
||||
terminationError: makeTerminationError(handle),
|
||||
serverRequestMethods: new Set(),
|
||||
onProcessExit: (error) => Deferred.succeed(processExit, error).pipe(Effect.asVoid),
|
||||
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
yield* transport.clientProtocol
|
||||
@@ -333,9 +292,9 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const message = yield* Deferred.await(firstMessage);
|
||||
const exitError = yield* Deferred.await(processExit);
|
||||
const exitError = yield* Deferred.await(termination);
|
||||
assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
|
||||
assert.equal(exitError.code, 7);
|
||||
assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
|
||||
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
||||
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
||||
readonly _tag: string;
|
||||
@@ -353,13 +312,13 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
ACP_MOCK_MALFORMED_OUTPUT: "1",
|
||||
ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
|
||||
});
|
||||
const processExitCalls = yield* Ref.make(0);
|
||||
const terminationCalls = yield* Ref.make(0);
|
||||
const firstMessage = yield* Deferred.make<unknown>();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: makeChildStdio(handle),
|
||||
processExit: makeProcessExit(handle),
|
||||
terminationError: makeTerminationError(handle),
|
||||
serverRequestMethods: new Set(),
|
||||
onProcessExit: () => Ref.update(processExitCalls, (count) => count + 1),
|
||||
onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
|
||||
});
|
||||
|
||||
yield* transport.clientProtocol
|
||||
@@ -367,7 +326,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const message = yield* Deferred.await(firstMessage);
|
||||
assert.equal(yield* Ref.get(processExitCalls), 0);
|
||||
assert.equal(yield* Ref.get(terminationCalls), 1);
|
||||
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
||||
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
||||
readonly _tag: string;
|
||||
@@ -383,7 +342,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
processExit: Effect.succeed(0),
|
||||
terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
|
||||
serverRequestMethods: new Set(),
|
||||
});
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ export type AcpIncomingNotification =
|
||||
|
||||
export interface AcpPatchedProtocolOptions {
|
||||
readonly stdio: Stdio.Stdio;
|
||||
readonly processExit?: Effect.Effect<number | null, AcpError.AcpProcessExitedError>;
|
||||
readonly terminationError?: Effect.Effect<AcpError.AcpError>;
|
||||
readonly serverRequestMethods: ReadonlySet<string>;
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
@@ -54,9 +54,7 @@ export interface AcpPatchedProtocolOptions {
|
||||
method: string,
|
||||
params: unknown,
|
||||
) => Effect.Effect<unknown, AcpError.AcpError, never>;
|
||||
readonly onProcessExit?: (
|
||||
error: AcpError.AcpProcessExitedError,
|
||||
) => Effect.Effect<void, never, never>;
|
||||
readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
|
||||
}
|
||||
|
||||
export interface AcpPatchedProtocol {
|
||||
@@ -189,15 +187,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
}),
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const handleTermination = (
|
||||
classify: () => Effect.Effect<
|
||||
| {
|
||||
readonly error: AcpError.AcpError;
|
||||
readonly processExitError?: AcpError.AcpProcessExitedError | undefined;
|
||||
}
|
||||
| undefined
|
||||
>,
|
||||
) =>
|
||||
const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError | undefined>) =>
|
||||
Ref.modify(terminationHandled, (handled) => {
|
||||
if (handled) {
|
||||
return [Effect.void, true] as const;
|
||||
@@ -205,14 +195,14 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
return [
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(disconnects, 0);
|
||||
const terminated = yield* classify();
|
||||
if (!terminated) {
|
||||
const error = yield* classify();
|
||||
if (!error) {
|
||||
return;
|
||||
}
|
||||
yield* failAllExtPending(terminated.error);
|
||||
yield* emitClientProtocolError(terminated.error);
|
||||
if (terminated.processExitError && options.onProcessExit) {
|
||||
yield* options.onProcessExit(terminated.processExitError);
|
||||
yield* failAllExtPending(error);
|
||||
yield* emitClientProtocolError(error);
|
||||
if (options.onTermination) {
|
||||
yield* options.onTermination(error);
|
||||
}
|
||||
}),
|
||||
true,
|
||||
@@ -423,36 +413,18 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
cause: error,
|
||||
});
|
||||
return handleTermination(() => Effect.succeed({ error: normalized }));
|
||||
return handleTermination(() => Effect.succeed(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"),
|
||||
}),
|
||||
handleTermination(
|
||||
() =>
|
||||
options.terminationError ??
|
||||
Effect.succeed(
|
||||
new AcpError.AcpTransportError({
|
||||
detail: "ACP input stream ended",
|
||||
cause: new Error("ACP input stream ended"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
|
||||
@@ -58,12 +58,6 @@ export const CloseSessionRpc = Rpc.make(AGENT_METHODS.session_close, {
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const SetSessionModeRpc = Rpc.make(AGENT_METHODS.session_set_mode, {
|
||||
payload: AcpSchema.SetSessionModeRequest,
|
||||
success: AcpSchema.SetSessionModeResponse,
|
||||
error: AcpSchema.Error,
|
||||
});
|
||||
|
||||
export const PromptRpc = Rpc.make(AGENT_METHODS.session_prompt, {
|
||||
payload: AcpSchema.PromptRequest,
|
||||
success: AcpSchema.PromptResponse,
|
||||
@@ -146,7 +140,6 @@ export const AgentRpcs = RpcGroup.make(
|
||||
ForkSessionRpc,
|
||||
ResumeSessionRpc,
|
||||
CloseSessionRpc,
|
||||
SetSessionModeRpc,
|
||||
PromptRpc,
|
||||
SetSessionModelRpc,
|
||||
SetSessionConfigOptionRpc,
|
||||
|
||||
@@ -6,20 +6,20 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as AcpClient from "../../src/client";
|
||||
|
||||
Effect.gen(function* () {
|
||||
const program = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("cursor-agent", ["acp"], {
|
||||
cwd: process.cwd(),
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const acpLayer = AcpClient.layerFromChildProcessHandle(handle, {
|
||||
const acpLayer = AcpClient.layerChildProcess(handle, {
|
||||
logIncoming: true,
|
||||
logOutgoing: true,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const acp = yield* AcpClient.AcpConnection;
|
||||
const acp = yield* AcpClient.AcpClient;
|
||||
|
||||
yield* acp.handleRequestPermission(() =>
|
||||
Effect.succeed({
|
||||
@@ -33,7 +33,7 @@ Effect.gen(function* () {
|
||||
Effect.logInfo("session/update", notification),
|
||||
);
|
||||
|
||||
const initialized = yield* acp.initialize({
|
||||
const initialized = yield* acp.agent.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
@@ -46,18 +46,18 @@ Effect.gen(function* () {
|
||||
});
|
||||
yield* Effect.logInfo("initialized", initialized);
|
||||
|
||||
const session = yield* acp.createSession({
|
||||
const session = yield* acp.agent.createSession({
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
|
||||
yield* acp.setSessionConfigOption({
|
||||
yield* acp.agent.setSessionConfigOption({
|
||||
sessionId: session.sessionId,
|
||||
configId: "model",
|
||||
value: "gpt-5.4[reasoning=medium,context=272k,fast=false]",
|
||||
});
|
||||
|
||||
const result = yield* acp.prompt({
|
||||
const result = yield* acp.agent.prompt({
|
||||
sessionId: session.sessionId,
|
||||
prompt: [
|
||||
{
|
||||
@@ -68,6 +68,8 @@ Effect.gen(function* () {
|
||||
});
|
||||
|
||||
yield* Effect.logInfo("prompt result", result);
|
||||
yield* acp.cancel({ sessionId: session.sessionId });
|
||||
yield* acp.agent.cancel({ sessionId: session.sessionId });
|
||||
}).pipe(Effect.provide(acpLayer));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
|
||||
});
|
||||
|
||||
program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
|
||||
+69
-189
@@ -1,9 +1,10 @@
|
||||
import { createInterface } from "node:readline";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as AcpAgent from "../../src/agent";
|
||||
|
||||
if (process.env.ACP_MOCK_MALFORMED_OUTPUT === "1") {
|
||||
process.stdout.write("{not-json}\n");
|
||||
@@ -14,124 +15,49 @@ if (process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE !== undefined) {
|
||||
process.exit(Number(process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE));
|
||||
}
|
||||
|
||||
let nextRequestId = 1000;
|
||||
const pending = new Map<
|
||||
number | string,
|
||||
{ resolve: (value: unknown) => void; reject: (error: unknown) => void }
|
||||
>();
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
function writeMessage(message: unknown) {
|
||||
process.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* AcpAgent.AcpAgent;
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"message" in error &&
|
||||
typeof error.message === "string"
|
||||
) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function respond(id: number | string | null | undefined, result: unknown) {
|
||||
writeMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
function respondError(
|
||||
id: number | string | null | undefined,
|
||||
code: number,
|
||||
message: string,
|
||||
data?: unknown,
|
||||
) {
|
||||
writeMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function notify(method: string, params?: unknown) {
|
||||
writeMessage({
|
||||
jsonrpc: "2.0",
|
||||
method,
|
||||
...(params !== undefined ? { params } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function requestClient(method: string, params?: unknown) {
|
||||
const id = nextRequestId++;
|
||||
writeMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
method,
|
||||
...(params !== undefined ? { params } : {}),
|
||||
});
|
||||
return new Promise<unknown>((resolve, reject) => {
|
||||
pending.set(id, { resolve, reject });
|
||||
});
|
||||
}
|
||||
|
||||
async function handleRequest(message: {
|
||||
readonly id: number | string | null;
|
||||
readonly method: string;
|
||||
readonly params?: unknown;
|
||||
}) {
|
||||
switch (message.method) {
|
||||
case "initialize":
|
||||
respond(message.id, {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: {
|
||||
sessionCapabilities: {
|
||||
list: {},
|
||||
},
|
||||
yield* agent.handleInitialize(() =>
|
||||
Effect.succeed({
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: {
|
||||
sessionCapabilities: {
|
||||
list: {},
|
||||
},
|
||||
agentInfo: {
|
||||
name: "mock-agent",
|
||||
version: "0.0.0",
|
||||
},
|
||||
agentInfo: {
|
||||
name: "mock-agent",
|
||||
version: "0.0.0",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
yield* agent.handleLogout(() => Effect.succeed({}));
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
}),
|
||||
);
|
||||
yield* agent.handleLoadSession(() => Effect.succeed({}));
|
||||
yield* agent.handleListSessions(() =>
|
||||
Effect.succeed({
|
||||
sessions: [
|
||||
{
|
||||
sessionId,
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "authenticate":
|
||||
respond(message.id, {});
|
||||
return;
|
||||
case "logout":
|
||||
respond(message.id, {});
|
||||
return;
|
||||
case "session/new":
|
||||
respond(message.id, {
|
||||
sessionId: "mock-session-1",
|
||||
});
|
||||
return;
|
||||
case "session/load":
|
||||
respond(message.id, {});
|
||||
return;
|
||||
case "session/list":
|
||||
respond(message.id, {
|
||||
sessions: [
|
||||
{
|
||||
sessionId: "mock-session-1",
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
],
|
||||
});
|
||||
return;
|
||||
case "session/prompt": {
|
||||
await requestClient("session/request_permission", {
|
||||
sessionId: "mock-session-1",
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* agent.client.requestPermission({
|
||||
sessionId,
|
||||
options: [
|
||||
{
|
||||
optionId: "allow",
|
||||
@@ -145,8 +71,8 @@ async function handleRequest(message: {
|
||||
},
|
||||
});
|
||||
|
||||
await requestClient("session/elicitation", {
|
||||
sessionId: "mock-session-1",
|
||||
yield* agent.client.elicit({
|
||||
sessionId,
|
||||
message: "Need confirmation before continuing.",
|
||||
mode: "form",
|
||||
requestedSchema: {
|
||||
@@ -162,8 +88,8 @@ async function handleRequest(message: {
|
||||
},
|
||||
});
|
||||
|
||||
notify("session/update", {
|
||||
sessionId: "mock-session-1",
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
@@ -176,81 +102,35 @@ async function handleRequest(message: {
|
||||
},
|
||||
});
|
||||
|
||||
notify("session/elicitation/complete", {
|
||||
yield* agent.client.elicitationComplete({
|
||||
elicitationId: "elicitation-1",
|
||||
});
|
||||
|
||||
await requestClient("x/typed_request", {
|
||||
yield* agent.client.extRequest("x/typed_request", {
|
||||
message: process.env.ACP_MOCK_BAD_TYPED_REQUEST === "1" ? 123 : "hello from typed request",
|
||||
});
|
||||
|
||||
notify("x/typed_notification", {
|
||||
yield* agent.client.extNotification("x/typed_notification", {
|
||||
count: 2,
|
||||
});
|
||||
|
||||
respond(message.id, {
|
||||
stopReason: "end_turn",
|
||||
});
|
||||
return;
|
||||
}
|
||||
default:
|
||||
respond(message.id, {
|
||||
echoedMethod: message.method,
|
||||
echoedParams: message.params ?? null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
return {
|
||||
stopReason: "end_turn" as const,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
function handleResponse(message: {
|
||||
readonly id: number | string | null;
|
||||
readonly result?: unknown;
|
||||
readonly error?: { readonly code: number; readonly message: string; readonly data?: unknown };
|
||||
}) {
|
||||
const pendingRequest = pending.get(message.id ?? "");
|
||||
if (!pendingRequest) {
|
||||
return;
|
||||
}
|
||||
pending.delete(message.id ?? "");
|
||||
if (message.error) {
|
||||
pendingRequest.reject(message.error);
|
||||
} else {
|
||||
pendingRequest.resolve(message.result);
|
||||
}
|
||||
}
|
||||
yield* agent.handleUnknownExtRequest((method, params) =>
|
||||
Effect.succeed({
|
||||
echoedMethod: method,
|
||||
echoedParams: params ?? null,
|
||||
}),
|
||||
);
|
||||
|
||||
rl.on("line", (line) => {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = JSON.parse(trimmed) as
|
||||
| { readonly id: number | string | null; readonly method: string; readonly params?: unknown }
|
||||
| {
|
||||
readonly id: number | string | null;
|
||||
readonly result?: unknown;
|
||||
readonly error?: {
|
||||
readonly code: number;
|
||||
readonly message: string;
|
||||
readonly data?: unknown;
|
||||
};
|
||||
}
|
||||
| { readonly method: string; readonly params?: unknown };
|
||||
|
||||
if ("method" in message && "id" in message) {
|
||||
void handleRequest(message).catch((error) => {
|
||||
respondError(message.id, -32603, errorMessage(error));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if ("id" in message && ("result" in message || "error" in message)) {
|
||||
handleResponse(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if ("method" in message && !("id" in message)) {
|
||||
return;
|
||||
}
|
||||
return yield* Effect.never;
|
||||
});
|
||||
|
||||
program.pipe(
|
||||
Effect.provide(Layer.provide(AcpAgent.layerStdio(), NodeServices.layer)),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
Reference in new issue
Block a user