improve sdk and use it
This commit is contained in:
1 parent
f30e603732
commit
7afe841e21
34 files changed
+1900
-3516
No files matched your search
@@ -32,6 +32,7 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
},
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 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";
|
||||
|
||||
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 sessionId = "mock-session-1";
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let nextRequestId = 1;
|
||||
|
||||
function configOptions() {
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
|
||||
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
description: "Request permission before making any changes",
|
||||
},
|
||||
{
|
||||
id: "architect",
|
||||
name: "Architect",
|
||||
description: "Design and plan software systems without implementation",
|
||||
},
|
||||
{
|
||||
id: "code",
|
||||
name: "Code",
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
const pendingPermissionRequests = new Map();
|
||||
|
||||
function send(obj) {
|
||||
process.stdout.write(`${JSON.stringify(obj)}\n`);
|
||||
}
|
||||
|
||||
function modeState() {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
function sendSessionUpdate(update, session = sessionId) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: session,
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
const id = msg.id;
|
||||
const method = msg.method;
|
||||
|
||||
if (method === undefined && id !== undefined && pendingPermissionRequests.has(id)) {
|
||||
const pending = pendingPermissionRequests.get(id);
|
||||
pendingPermissionRequests.delete(id);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: pending.toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
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: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "initialize" && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "authenticate" && id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: { authenticated: true } });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/new" && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/load" && id !== undefined) {
|
||||
const requestedSessionId = msg.params?.sessionId ?? sessionId;
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/set_config_option" && id !== undefined) {
|
||||
const configId = msg.params?.configId;
|
||||
const value = msg.params?.value;
|
||||
if (configId === "model" && typeof value === "string") {
|
||||
currentModelId = value;
|
||||
}
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: { configOptions: configOptions() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/prompt" && id !== undefined) {
|
||||
const requestedSessionId = msg.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"],
|
||||
},
|
||||
},
|
||||
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: "session/request_permission",
|
||||
params: {
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
title: "`cat server/package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist: cat server/package.json",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
});
|
||||
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 === "session/set_mode" || method === "session/mode/set") && id !== undefined) {
|
||||
const nextModeId =
|
||||
typeof msg.params?.modeId === "string"
|
||||
? msg.params.modeId
|
||||
: typeof msg.params?.mode === "string"
|
||||
? msg.params.mode
|
||||
: undefined;
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
sendSessionUpdate({
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
});
|
||||
}
|
||||
send({ jsonrpc: "2.0", id, result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/cancel" && id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
if (id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: { code: -32601, message: `Unhandled method: ${String(method)}` },
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,176 +1,28 @@
|
||||
#!/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 * 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";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "effect-acp/schema";
|
||||
|
||||
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "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 promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
}
|
||||
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
logExit("SIGINT");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("exit", (code) => {
|
||||
logExit(`exit:${code}`);
|
||||
});
|
||||
|
||||
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
if (parameterizedModelPicker) {
|
||||
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentModeId,
|
||||
options: availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
...(mode.description ? { description: mode.description } : {}),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ value: "claude-opus-4-6", name: "Opus 4.6" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
switch (currentModelId) {
|
||||
case "gpt-5.4":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "none", name: "None" },
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "extra-high", name: "Extra High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "context",
|
||||
name: "Context",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: currentContext,
|
||||
options: [
|
||||
{ value: "272k", name: "272K" },
|
||||
{ value: "1m", name: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "composer-2":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "claude-opus-4-6":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
category: "model_config",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
];
|
||||
default:
|
||||
return baseOptions;
|
||||
}
|
||||
}
|
||||
let nextRequestId = 1;
|
||||
|
||||
function configOptions() {
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select" as const,
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
@@ -182,7 +34,7 @@ function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
const availableModes = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
@@ -199,179 +51,185 @@ const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
const pendingPermissionRequests = new Map();
|
||||
|
||||
function modeState(): AcpSchema.SessionModeState {
|
||||
function send(obj: unknown) {
|
||||
process.stdout.write(`${JSON.stringify(obj)}\n`);
|
||||
}
|
||||
|
||||
function modeState() {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
function sendSessionUpdate(update: unknown, session = sessionId) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: CLIENT_METHODS.session_update,
|
||||
params: {
|
||||
sessionId: session,
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
yield* agent.handleInitialize((request) =>
|
||||
Effect.sync(() => {
|
||||
parameterizedModelPicker =
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
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");
|
||||
}
|
||||
|
||||
const rpcMessage = msg as {
|
||||
id?: number | string;
|
||||
method?: string;
|
||||
params?: Record<string, unknown>;
|
||||
};
|
||||
const id = rpcMessage.id;
|
||||
const method = rpcMessage.method;
|
||||
|
||||
if (method === undefined && id !== undefined && pendingPermissionRequests.has(id)) {
|
||||
const pending = pendingPermissionRequests.get(id);
|
||||
pendingPermissionRequests.delete(id);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: pending.toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
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: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.initialize && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
if (method === AGENT_METHODS.authenticate && id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: { authenticated: true } });
|
||||
return;
|
||||
}
|
||||
|
||||
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" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (request.configId === "mode" && typeof request.value === "string") {
|
||||
currentModeId = request.value;
|
||||
}
|
||||
if (request.configId === "model" && typeof request.value === "string") {
|
||||
currentModelId = request.value;
|
||||
}
|
||||
if (request.configId === "reasoning" && typeof request.value === "string") {
|
||||
currentReasoning = request.value;
|
||||
}
|
||||
if (request.configId === "context" && typeof request.value === "string") {
|
||||
currentContext = request.value;
|
||||
}
|
||||
if (request.configId === "fast") {
|
||||
currentFast = request.value === true || request.value === "true";
|
||||
}
|
||||
return {
|
||||
if (method === AGENT_METHODS.session_new && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
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;
|
||||
}
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
if (method === AGENT_METHODS.session_set_config_option && id !== undefined) {
|
||||
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 (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "before tool" },
|
||||
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.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["echo", "hello"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "hello",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "after tool" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
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"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
},
|
||||
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: {
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
@@ -393,198 +251,77 @@ const program = Effect.gen(function* () {
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
|
||||
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",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "plan",
|
||||
explanation: `Mock plan while in ${currentModeId}`,
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
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 (emitGenericToolPlaceholders) {
|
||||
const toolCallId = "tool-call-generic-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Read File",
|
||||
kind: "read",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
content: "package.json\n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
title: "Question",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Which scope?",
|
||||
options: [
|
||||
{ id: "workspace", label: "Workspace" },
|
||||
{ id: "session", label: "Session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
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",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: promptResponseText ?? "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
],
|
||||
},
|
||||
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
|
||||
) {
|
||||
const nextModeId =
|
||||
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
|
||||
typeof rpcMessage.params?.modeId === "string"
|
||||
? rpcMessage.params.modeId
|
||||
: typeof rpcMessage.params?.mode === "string"
|
||||
? rpcMessage.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();
|
||||
return agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.as({}));
|
||||
sendSessionUpdate({
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
});
|
||||
}
|
||||
send({ jsonrpc: "2.0", id, result: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
return Effect.succeed({});
|
||||
});
|
||||
if (method === AGENT_METHODS.session_cancel) {
|
||||
if (id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: null });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
if (id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: { code: -32601, message: `Unhandled method: ${String(method)}` },
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -20,7 +20,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as Reactivity from "effect/unstable/reactivity/Reactivity";
|
||||
import * as Client from "effect/unstable/sql/SqlClient";
|
||||
import type { Connection } from "effect/unstable/sql/SqlConnection";
|
||||
import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError";
|
||||
import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError";
|
||||
import * as Statement from "effect/unstable/sql/Statement";
|
||||
|
||||
const ATTR_DB_SYSTEM_NAME = "db.system.name";
|
||||
@@ -102,38 +102,73 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
return value;
|
||||
};
|
||||
|
||||
const prepareCache = yield* Cache.make({
|
||||
capacity: options.prepareCacheSize ?? 200,
|
||||
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
const prepareCache = yield* Cache.make({
|
||||
capacity: options.prepareCacheSize ?? 200,
|
||||
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
|
||||
try {
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
const runStatement = (
|
||||
statement: StatementSync,
|
||||
params: ReadonlyArray<unknown>,
|
||||
raw: boolean,
|
||||
) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
|
||||
try {
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
|
||||
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
|
||||
|
||||
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
|
||||
Effect.acquireUseRelease(
|
||||
Cache.get(prepareCache, sql),
|
||||
(statement) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(true);
|
||||
// Safe to cast to array after we've setReturnArrays(true)
|
||||
return statement.all(...(params as any)) as unknown as ReadonlyArray<
|
||||
ReadonlyArray<unknown>
|
||||
>;
|
||||
}
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ import { makeCursorAdapterLive } from "./CursorAdapter.ts";
|
||||
import { resolveCursorAcpModelId } from "./CursorProvider.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.mjs");
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const bunExe = "bun";
|
||||
|
||||
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-mock-"));
|
||||
@@ -26,7 +27,7 @@ async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
@@ -48,7 +49,7 @@ printf '%s\t' "$@" >> ${JSON.stringify(argvLogPath)}
|
||||
printf '\n' >> ${JSON.stringify(argvLogPath)}
|
||||
export T3_ACP_REQUEST_LOG_PATH=${JSON.stringify(requestLogPath)}
|
||||
${envExports}
|
||||
exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
@@ -140,13 +141,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
const planUpdate = runtimeEvents.find((event) => event.type === "turn.plan.updated");
|
||||
assert.isDefined(planUpdate);
|
||||
if (planUpdate?.type === "turn.plan.updated") {
|
||||
assert.deepStrictEqual(planUpdate.payload, {
|
||||
explanation: "Mock plan while in code",
|
||||
plan: [
|
||||
{ step: "Inspect mock ACP state", status: "completed" },
|
||||
{ step: "Implement the requested change", status: "inProgress" },
|
||||
],
|
||||
});
|
||||
assert.deepStrictEqual(planUpdate.payload.plan, [
|
||||
{ step: "Inspect mock ACP state", status: "completed" },
|
||||
{ step: "Implement the requested change", status: "inProgress" },
|
||||
]);
|
||||
}
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -772,6 +772,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
if (joined === "login status") {
|
||||
return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "about") {
|
||||
return {
|
||||
stdout: "Version: 1.0.0\nUser Email: [email protected]\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { RuntimeRequestId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";
|
||||
import {
|
||||
acpPermissionOutcome,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "./AcpAdapterSupport.ts";
|
||||
|
||||
describe("AcpAdapterSupport", () => {
|
||||
it("maps ACP approval decisions to permission outcomes", () => {
|
||||
@@ -10,18 +16,92 @@ describe("AcpAdapterSupport", () => {
|
||||
expect(acpPermissionOutcome("decline")).toBe("reject-once");
|
||||
});
|
||||
|
||||
it("maps ACP request errors to provider adapter request errors", () => {
|
||||
const error = mapAcpToAdapterError(
|
||||
"cursor",
|
||||
"thread-1" as never,
|
||||
"session/prompt",
|
||||
new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: "Invalid params",
|
||||
}),
|
||||
);
|
||||
it("builds shared ACP-backed runtime events", () => {
|
||||
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
|
||||
const turnId = TurnId.makeUnsafe("turn-1");
|
||||
|
||||
expect(error._tag).toBe("ProviderAdapterRequestError");
|
||||
expect(error.message).toContain("Invalid params");
|
||||
expect(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
requestId: RuntimeRequestId.makeUnsafe("request-1"),
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
args: { command: ["cat", "package.json"] },
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "request.opened",
|
||||
provider: "cursor",
|
||||
turnId,
|
||||
payload: {
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
payload: {
|
||||
plan: [{ step: "Inspect state", status: "inProgress" }],
|
||||
},
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/update_todos",
|
||||
rawPayload: { todos: [] },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "turn.plan.updated",
|
||||
raw: {
|
||||
method: "cursor/update_todos",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpToolCallEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Terminal",
|
||||
detail: "bun run test",
|
||||
data: { command: "bun run test" },
|
||||
},
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
text: "hello",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
delta: "hello",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,12 @@
|
||||
import {
|
||||
RuntimeItemId,
|
||||
type EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderKind,
|
||||
type ProviderRuntimeEvent,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type RuntimeRequestId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
@@ -11,6 +16,30 @@ import {
|
||||
ProviderAdapterSessionClosedError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import type { AcpToolCallState } from "./AcpRuntimeModel.ts";
|
||||
|
||||
export type AcpAdapterRawSource = "acp.jsonrpc" | `acp.${string}.extension`;
|
||||
|
||||
export interface AcpEventStamp {
|
||||
readonly eventId: EventId;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
function runtimeItemStatusFromToolCallStatus(
|
||||
status: "pending" | "inProgress" | "completed" | "failed" | undefined,
|
||||
): "inProgress" | "completed" | "failed" | undefined {
|
||||
switch (status) {
|
||||
case "pending":
|
||||
case "inProgress":
|
||||
return "inProgress";
|
||||
case "completed":
|
||||
return "completed";
|
||||
case "failed":
|
||||
return "failed";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function mapAcpToAdapterError(
|
||||
provider: ProviderKind,
|
||||
@@ -48,7 +77,163 @@ export function acpPermissionOutcome(decision: ProviderApprovalDecision): string
|
||||
case "accept":
|
||||
return "allow-once";
|
||||
case "decline":
|
||||
case "cancel":
|
||||
default:
|
||||
return "reject-once";
|
||||
}
|
||||
}
|
||||
|
||||
export function makeAcpRequestOpenedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly requestType:
|
||||
| "exec_command_approval"
|
||||
| "file_read_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown";
|
||||
readonly detail: string;
|
||||
readonly args: unknown;
|
||||
readonly source: AcpAdapterRawSource;
|
||||
readonly method: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "request.opened",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
requestId: input.requestId,
|
||||
payload: {
|
||||
requestType: input.requestType,
|
||||
detail: input.detail,
|
||||
args: input.args,
|
||||
},
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpRequestResolvedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly requestType:
|
||||
| "exec_command_approval"
|
||||
| "file_read_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown";
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "request.resolved",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
requestId: input.requestId,
|
||||
payload: {
|
||||
requestType: input.requestType,
|
||||
decision: input.decision,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpPlanUpdatedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly payload: {
|
||||
readonly explanation?: string | null;
|
||||
readonly plan: ReadonlyArray<{
|
||||
readonly step: string;
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
};
|
||||
readonly source: AcpAdapterRawSource;
|
||||
readonly method: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "turn.plan.updated",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
payload: input.payload,
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpToolCallEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly toolCall: AcpToolCallState;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
const runtimeStatus = runtimeItemStatusFromToolCallStatus(input.toolCall.status);
|
||||
return {
|
||||
type:
|
||||
input.toolCall.status === "completed" || input.toolCall.status === "failed"
|
||||
? "item.completed"
|
||||
: "item.updated",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
itemId: RuntimeItemId.makeUnsafe(input.toolCall.toolCallId),
|
||||
payload: {
|
||||
itemType: input.toolCall.itemType,
|
||||
...(runtimeStatus ? { status: runtimeStatus } : {}),
|
||||
...(input.toolCall.title ? { title: input.toolCall.title } : {}),
|
||||
...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),
|
||||
...(Object.keys(input.toolCall.data).length > 0 ? { data: input.toolCall.data } : {}),
|
||||
},
|
||||
raw: {
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpContentDeltaEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly text: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "content.delta",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: input.text,
|
||||
},
|
||||
raw: {
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()("AcpSpawnError", {
|
||||
command: Schema.optional(Schema.String),
|
||||
args: Schema.optional(Schema.Array(Schema.String)),
|
||||
shell: Schema.optional(Schema.Boolean),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message() {
|
||||
return `Failed to spawn ACP process: ${this.cause instanceof Error ? this.cause.message : String(this.cause)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpParseError extends Schema.TaggedErrorClass<AcpParseError>()("AcpParseError", {
|
||||
line: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message() {
|
||||
return `Failed to parse ACP message: ${this.line}`;
|
||||
}
|
||||
}
|
||||
export class AcpRpcError extends Schema.TaggedErrorClass<AcpRpcError>()("AcpRpcError", {
|
||||
code: Schema.Number,
|
||||
errorMessage: Schema.optional(Schema.String),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
}) {
|
||||
override get message() {
|
||||
return `Failed to send ACP RPC message (code: ${this.code}, message: ${this.errorMessage}, data: ${JSON.stringify(this.data)})`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExitedError>()(
|
||||
"AcpProcessExitedError",
|
||||
{
|
||||
code: Schema.NullOr(Schema.Number),
|
||||
signal: Schema.NullOr(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `ACP process exited with code ${this.code} and signal ${this.signal}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const AcpError = Schema.Union([
|
||||
AcpSpawnError,
|
||||
AcpParseError,
|
||||
AcpRpcError,
|
||||
AcpProcessExitedError,
|
||||
]);
|
||||
|
||||
export type AcpError = typeof AcpError.Type;
|
||||
@@ -6,46 +6,42 @@ import { it } from "@effect/vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { makeAcpJsonRpcConnection } from "./AcpJsonRpcConnection.ts";
|
||||
import { makeAcpSessionRuntime } from "./AcpSessionRuntime.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.mjs");
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const bunExe = "bun";
|
||||
|
||||
describe("AcpJsonRpcConnection", () => {
|
||||
it.effect("performs initialize → session/new → session/prompt against mock agent", () =>
|
||||
describe("AcpSessionRuntime", () => {
|
||||
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: process.execPath,
|
||||
args: [mockAgentPath],
|
||||
});
|
||||
|
||||
const initResult = yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
});
|
||||
expect(initResult).toMatchObject({ protocolVersion: 1 });
|
||||
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
expect(runtime.initializeResult).toMatchObject({ protocolVersion: 1 });
|
||||
expect(runtime.sessionId).toBe("mock-session-1");
|
||||
|
||||
const newResult = yield* conn.request("session/new", {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
expect(newResult).toMatchObject({ sessionId: "mock-session-1" });
|
||||
|
||||
const promptResult = yield* conn.request("session/prompt", {
|
||||
sessionId: "mock-session-1",
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = yield* Stream.runCollect(Stream.take(conn.notifications, 1));
|
||||
expect(notes.length).toBe(1);
|
||||
expect(notes[0]?._tag).toBe("notification");
|
||||
if (notes[0]?._tag === "notification") {
|
||||
expect(notes[0].method).toBe("session/update");
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 2)));
|
||||
expect(notes).toHaveLength(2);
|
||||
expect(notes.map((note) => note._tag)).toEqual(["PlanUpdated", "ContentDelta"]);
|
||||
const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
|
||||
expect(planUpdate?._tag).toBe("PlanUpdated");
|
||||
if (planUpdate?._tag === "PlanUpdated") {
|
||||
expect(planUpdate.payload.plan).toHaveLength(2);
|
||||
}
|
||||
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,256 +0,0 @@
|
||||
import { createInterface } from "node:readline";
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
|
||||
import {
|
||||
Cause,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
Queue,
|
||||
Ref,
|
||||
Schema,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
} from "effect";
|
||||
|
||||
import {
|
||||
AcpError,
|
||||
AcpParseError,
|
||||
AcpProcessExitedError,
|
||||
AcpRpcError,
|
||||
AcpSpawnError,
|
||||
} from "./AcpErrors.ts";
|
||||
import {
|
||||
decodeAcpInboundFromJsonLine,
|
||||
type AcpInboundMessage,
|
||||
type AcpServerRequestHandler,
|
||||
type AcpSpawnInput,
|
||||
} from "./AcpTypes.ts";
|
||||
|
||||
const JSON_RPC_VERSION = "2.0";
|
||||
|
||||
function parseInboundLine(line: string): Effect.Effect<AcpInboundMessage | null, AcpParseError> {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
const lineSnippet = trimmed.slice(0, 500);
|
||||
return decodeAcpInboundFromJsonLine(trimmed).pipe(
|
||||
Effect.mapError((cause) => new AcpParseError({ line: lineSnippet, cause })),
|
||||
);
|
||||
}
|
||||
|
||||
export interface AcpJsonRpcConnection {
|
||||
readonly request: (method: string, params?: unknown) => Effect.Effect<unknown, AcpError>;
|
||||
readonly notify: (method: string, params?: unknown) => Effect.Effect<void, AcpError>;
|
||||
readonly registerHandler: (
|
||||
method: string,
|
||||
handler: AcpServerRequestHandler,
|
||||
) => Effect.Effect<void>;
|
||||
readonly notifications: Stream.Stream<AcpInboundMessage, never>;
|
||||
}
|
||||
|
||||
export function spawnAcpChildProcess(
|
||||
input: AcpSpawnInput,
|
||||
): Effect.Effect<ChildProcessWithoutNullStreams, AcpSpawnError, never> {
|
||||
const shell = process.platform === "win32";
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const c = spawn(input.command, [...input.args], {
|
||||
cwd: input.cwd,
|
||||
env: { ...process.env, ...input.env },
|
||||
stdio: ["pipe", "pipe", "inherit"],
|
||||
shell,
|
||||
});
|
||||
if (!c.stdin || !c.stdout) {
|
||||
throw new Error("Child process missing stdio pipes.");
|
||||
}
|
||||
return c as unknown as ChildProcessWithoutNullStreams;
|
||||
},
|
||||
catch: (cause) => new AcpSpawnError({ command: input.command, args: input.args, shell, cause }),
|
||||
});
|
||||
}
|
||||
|
||||
export function disposeAcpChild(child: ChildProcessWithoutNullStreams) {
|
||||
try {
|
||||
child.stdin?.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
child.kill("SIGTERM");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach JSON-RPC framing to an existing child process (caller owns spawn/kill).
|
||||
*/
|
||||
export const attachAcpJsonRpcConnection = (
|
||||
child: ChildProcessWithoutNullStreams,
|
||||
): Effect.Effect<AcpJsonRpcConnection, never, never> =>
|
||||
Effect.gen(function* () {
|
||||
const writeLock = yield* Semaphore.make(1);
|
||||
const pending = yield* Ref.make(
|
||||
new Map<number | string, Deferred.Deferred<unknown, AcpError>>(),
|
||||
);
|
||||
const handlers = yield* Ref.make(new Map<string, AcpServerRequestHandler>());
|
||||
const nextId = yield* Ref.make(1);
|
||||
const notificationQueue = yield* Queue.unbounded<AcpInboundMessage>();
|
||||
|
||||
const failAllPending = (error: AcpError) =>
|
||||
Ref.get(pending).pipe(
|
||||
Effect.flatMap((map) =>
|
||||
Effect.forEach([...map.values()], (def) => Deferred.fail(def, error), {
|
||||
discard: true,
|
||||
}),
|
||||
),
|
||||
Effect.tap(() => Ref.set(pending, new Map())),
|
||||
);
|
||||
|
||||
const writeRawLine = (payload: Record<string, unknown>) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
child.stdin.write(`${JSON.stringify(payload)}\n`);
|
||||
},
|
||||
catch: (cause) =>
|
||||
new AcpSpawnError({
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const writeSerialized = (payload: Record<string, unknown>) =>
|
||||
writeLock.withPermits(1)(writeRawLine(payload));
|
||||
|
||||
const sendRequest = (method: string, params?: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
const deferred = yield* Deferred.make<unknown, AcpError>();
|
||||
yield* writeLock.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const id = yield* Ref.get(nextId);
|
||||
yield* Ref.set(nextId, id + 1);
|
||||
yield* Ref.update(pending, (map) => new Map(map).set(id, deferred));
|
||||
yield* writeRawLine({
|
||||
jsonrpc: JSON_RPC_VERSION,
|
||||
id,
|
||||
method,
|
||||
...(params !== undefined ? { params } : {}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return yield* Deferred.await(deferred);
|
||||
});
|
||||
|
||||
const sendNotify = (method: string, params?: unknown) =>
|
||||
writeSerialized({
|
||||
jsonrpc: JSON_RPC_VERSION,
|
||||
method,
|
||||
...(params !== undefined ? { params } : {}),
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const respondResult = (id: number | string, result: unknown) =>
|
||||
writeSerialized({ jsonrpc: JSON_RPC_VERSION, id, result });
|
||||
|
||||
const respondError = (id: number | string, message: string, code = -32601) =>
|
||||
writeSerialized({
|
||||
jsonrpc: JSON_RPC_VERSION,
|
||||
id,
|
||||
error: { code, message },
|
||||
});
|
||||
|
||||
const handleOneLine = (line: string): Effect.Effect<void, AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const parseExit = yield* parseInboundLine(line).pipe(Effect.exit);
|
||||
if (Exit.isFailure(parseExit)) {
|
||||
return;
|
||||
}
|
||||
if (parseExit.value === null) {
|
||||
return;
|
||||
}
|
||||
const msg = parseExit.value;
|
||||
|
||||
if (msg._tag === "response") {
|
||||
const map = yield* Ref.get(pending);
|
||||
const def = map.get(msg.id);
|
||||
if (!def) return;
|
||||
const next = new Map(map);
|
||||
next.delete(msg.id);
|
||||
yield* Ref.set(pending, next);
|
||||
if (msg.error) {
|
||||
yield* Deferred.fail(
|
||||
def,
|
||||
new AcpRpcError({
|
||||
code: msg.error.code,
|
||||
...(msg.error.data !== undefined ? { data: msg.error.data } : {}),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
yield* Deferred.succeed(def, msg.result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg._tag === "notification") {
|
||||
yield* Queue.offer(notificationQueue, msg);
|
||||
return;
|
||||
}
|
||||
|
||||
const handlerMap = yield* Ref.get(handlers);
|
||||
const handler = handlerMap.get(msg.method);
|
||||
if (!handler) {
|
||||
yield* respondError(msg.id, `Method not found: ${msg.method}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const exit = yield* Effect.exit(handler(msg.params, msg.id));
|
||||
if (Exit.isSuccess(exit)) {
|
||||
yield* respondResult(msg.id, exit.value);
|
||||
} else {
|
||||
const left = Cause.squash(exit.cause);
|
||||
yield* respondError(msg.id, Schema.is(AcpError)(left) ? left.message : String(left));
|
||||
}
|
||||
});
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
child.once("close", (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
const err = new AcpProcessExitedError({ code, signal });
|
||||
void Effect.runPromise(
|
||||
failAllPending(err).pipe(Effect.tap(() => Queue.shutdown(notificationQueue))),
|
||||
).catch(() => {
|
||||
/* ignore shutdown races */
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
||||
yield* Effect.sync(() => {
|
||||
rl.on("line", (ln: string) => {
|
||||
void Effect.runPromise(handleOneLine(ln)).catch(() => {
|
||||
/* parse/handler errors are non-fatal for the transport */
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const registerHandler = (method: string, handler: AcpServerRequestHandler) =>
|
||||
Ref.update(handlers, (map) => new Map(map).set(method, handler));
|
||||
|
||||
return {
|
||||
request: sendRequest,
|
||||
notify: sendNotify,
|
||||
registerHandler,
|
||||
notifications: Stream.fromQueue(notificationQueue),
|
||||
} satisfies AcpJsonRpcConnection;
|
||||
});
|
||||
|
||||
/**
|
||||
* Spawns an ACP agent process and exposes NDJSON JSON-RPC over stdio.
|
||||
* Run under `Effect.scoped` so the child is disposed when the scope ends.
|
||||
*/
|
||||
export const makeAcpJsonRpcConnection = (
|
||||
input: AcpSpawnInput,
|
||||
): Effect.Effect<AcpJsonRpcConnection, AcpSpawnError, Scope.Scope> =>
|
||||
Effect.acquireRelease(spawnAcpChildProcess(input), (child) =>
|
||||
Effect.sync(() => disposeAcpChild(child)),
|
||||
).pipe(Effect.flatMap(attachAcpJsonRpcConnection));
|
||||
@@ -89,8 +89,8 @@ describe("AcpRuntimeModel", () => {
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
title: "Ran command",
|
||||
itemType: "command_execution",
|
||||
title: "Terminal",
|
||||
status: "pending",
|
||||
command: "bun run typecheck",
|
||||
detail: "bun run typecheck",
|
||||
@@ -157,31 +157,11 @@ describe("AcpRuntimeModel", () => {
|
||||
expect(mergeToolCallState(createdEvent.toolCall, updatedEvent.toolCall)).toMatchObject({
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "bun run typecheck",
|
||||
command: "bun run typecheck",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("trims padded current mode updates before emitting a mode change", () => {
|
||||
const result = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId: " code ",
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
expect(result.modeId).toBe("code");
|
||||
expect(result.events).toEqual([
|
||||
{
|
||||
_tag: "ModeChanged",
|
||||
modeId: "code",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("projects typed ACP plan and content updates", () => {
|
||||
const planResult = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
@@ -273,11 +253,11 @@ describe("AcpRuntimeModel", () => {
|
||||
});
|
||||
|
||||
expect(request).toMatchObject({
|
||||
kind: "execute",
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
itemType: "command_execution",
|
||||
status: "pending",
|
||||
command: "cat package.json",
|
||||
},
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
|
||||
import type { ToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -19,7 +18,7 @@ export interface AcpSessionModeState {
|
||||
|
||||
export interface AcpToolCallState {
|
||||
readonly toolCallId: string;
|
||||
readonly kind?: string;
|
||||
readonly itemType: ToolLifecycleItemType;
|
||||
readonly title?: string;
|
||||
readonly status?: "pending" | "inProgress" | "completed" | "failed";
|
||||
readonly command?: string;
|
||||
@@ -36,7 +35,11 @@ export interface AcpPlanUpdate {
|
||||
}
|
||||
|
||||
export interface AcpPermissionRequest {
|
||||
readonly kind: string | "unknown";
|
||||
readonly requestType:
|
||||
| "exec_command_approval"
|
||||
| "file_read_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown";
|
||||
readonly detail?: string;
|
||||
readonly toolCall?: AcpToolCallState;
|
||||
}
|
||||
@@ -46,14 +49,6 @@ export type AcpParsedSessionEvent =
|
||||
readonly _tag: "ModeChanged";
|
||||
readonly modeId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "AssistantItemStarted";
|
||||
readonly itemId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "AssistantItemCompleted";
|
||||
readonly itemId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "PlanUpdated";
|
||||
readonly payload: AcpPlanUpdate;
|
||||
@@ -66,7 +61,6 @@ export type AcpParsedSessionEvent =
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ContentDelta";
|
||||
readonly itemId?: string;
|
||||
readonly text: string;
|
||||
readonly rawPayload: unknown;
|
||||
};
|
||||
@@ -92,31 +86,6 @@ export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse):
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function findSessionConfigOption(
|
||||
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
|
||||
configId: string,
|
||||
): EffectAcpSchema.SessionConfigOption | undefined {
|
||||
if (!configOptions) {
|
||||
return undefined;
|
||||
}
|
||||
const normalizedConfigId = configId.trim();
|
||||
if (!normalizedConfigId) {
|
||||
return undefined;
|
||||
}
|
||||
return configOptions.find((option) => option.id.trim() === normalizedConfigId);
|
||||
}
|
||||
|
||||
export function collectSessionConfigOptionValues(
|
||||
configOption: EffectAcpSchema.SessionConfigOption,
|
||||
): ReadonlyArray<string> {
|
||||
if (configOption.type !== "select") {
|
||||
return [];
|
||||
}
|
||||
return configOption.options.flatMap((entry) =>
|
||||
"value" in entry ? [entry.value] : entry.options.map((option) => option.value),
|
||||
);
|
||||
}
|
||||
|
||||
export function parseSessionModeState(
|
||||
sessionResponse: AcpSessionSetupResponse,
|
||||
): AcpSessionModeState | undefined {
|
||||
@@ -237,11 +206,7 @@ function extractTextContentFromToolCallContent(
|
||||
return chunks.length > 0 ? chunks.join("\n") : undefined;
|
||||
}
|
||||
|
||||
function normalizeToolKind(kind: unknown): string | undefined {
|
||||
return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
|
||||
}
|
||||
|
||||
function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
|
||||
function toolLifecycleItemTypeFromKind(kind: unknown): ToolLifecycleItemType {
|
||||
switch (kind) {
|
||||
case "execute":
|
||||
return "command_execution";
|
||||
@@ -257,6 +222,23 @@ function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecyc
|
||||
}
|
||||
}
|
||||
|
||||
function requestTypeFromToolKind(
|
||||
kind: unknown,
|
||||
): "exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown" {
|
||||
switch (kind) {
|
||||
case "execute":
|
||||
return "exec_command_approval";
|
||||
case "read":
|
||||
return "file_read_approval";
|
||||
case "edit":
|
||||
case "delete":
|
||||
case "move":
|
||||
return "file_change_approval";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function makeToolCallState(
|
||||
input: {
|
||||
readonly toolCallId: string;
|
||||
@@ -283,10 +265,10 @@ function makeToolCallState(
|
||||
title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
|
||||
? title
|
||||
: undefined;
|
||||
const detail = command ?? normalizedTitle ?? textContent;
|
||||
const data: Record<string, unknown> = { toolCallId };
|
||||
const kind = normalizeToolKind(input.kind);
|
||||
if (kind) {
|
||||
data.kind = kind;
|
||||
if (input.kind) {
|
||||
data.kind = input.kind;
|
||||
}
|
||||
if (command) {
|
||||
data.command = command;
|
||||
@@ -303,30 +285,14 @@ function makeToolCallState(
|
||||
if (input.locations !== undefined) {
|
||||
data.locations = input.locations;
|
||||
}
|
||||
const fallbackDetail = command ?? normalizedTitle ?? textContent;
|
||||
const hasPresentationSeed =
|
||||
title !== undefined ||
|
||||
kind !== undefined ||
|
||||
command !== undefined ||
|
||||
normalizedTitle !== undefined ||
|
||||
textContent !== undefined;
|
||||
const presentation = hasPresentationSeed
|
||||
? deriveToolActivityPresentation({
|
||||
itemType: canonicalItemTypeFromAcpToolKind(kind),
|
||||
title,
|
||||
detail: fallbackDetail,
|
||||
data,
|
||||
fallbackSummary: title ?? "Tool",
|
||||
})
|
||||
: undefined;
|
||||
const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
|
||||
return {
|
||||
toolCallId,
|
||||
...(kind ? { kind } : {}),
|
||||
...(presentation?.summary ? { title: presentation.summary } : {}),
|
||||
itemType: toolLifecycleItemTypeFromKind(input.kind),
|
||||
...(title ? { title } : {}),
|
||||
...(status ? { status } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(presentation?.detail ? { detail: presentation.detail } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
data,
|
||||
};
|
||||
}
|
||||
@@ -357,14 +323,13 @@ export function mergeToolCallState(
|
||||
next: AcpToolCallState,
|
||||
): AcpToolCallState {
|
||||
const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
|
||||
const kind = nextKind ?? previous?.kind;
|
||||
const title = next.title ?? previous?.title;
|
||||
const status = next.status ?? previous?.status;
|
||||
const command = next.command ?? previous?.command;
|
||||
const detail = next.detail ?? previous?.detail;
|
||||
return {
|
||||
toolCallId: next.toolCallId,
|
||||
...(kind ? { kind } : {}),
|
||||
itemType: nextKind !== undefined ? next.itemType : (previous?.itemType ?? next.itemType),
|
||||
...(title ? { title } : {}),
|
||||
...(status ? { status } : {}),
|
||||
...(command ? { command } : {}),
|
||||
@@ -392,14 +357,14 @@ export function parsePermissionRequest(
|
||||
},
|
||||
{ fallbackStatus: "pending" },
|
||||
);
|
||||
const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
|
||||
const requestType = requestTypeFromToolKind(params.toolCall.kind);
|
||||
const detail =
|
||||
toolCall?.command ??
|
||||
toolCall?.title ??
|
||||
toolCall?.detail ??
|
||||
(typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
|
||||
return {
|
||||
kind,
|
||||
requestType,
|
||||
...(detail ? { detail } : {}),
|
||||
...(toolCall ? { toolCall } : {}),
|
||||
};
|
||||
@@ -415,13 +380,11 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat
|
||||
|
||||
switch (upd.sessionUpdate) {
|
||||
case "current_mode_update": {
|
||||
modeId = upd.currentModeId.trim();
|
||||
if (modeId) {
|
||||
events.push({
|
||||
_tag: "ModeChanged",
|
||||
modeId,
|
||||
});
|
||||
}
|
||||
modeId = upd.currentModeId;
|
||||
events.push({
|
||||
_tag: "ModeChanged",
|
||||
modeId,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "plan": {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { Cause, Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Context, Stream } from "effect";
|
||||
import { Effect, Exit, Queue, Ref, Scope, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpClient from "effect-acp/client";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import {
|
||||
collectSessionConfigOptionValues,
|
||||
extractModelConfigId,
|
||||
findSessionConfigOption,
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
@@ -28,29 +25,15 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly spawn: AcpSpawnInput;
|
||||
readonly cwd: string;
|
||||
readonly resumeSessionId?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
readonly clientInfo: {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
readonly authMethodId: string;
|
||||
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
|
||||
readonly protocolLogging?: {
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
};
|
||||
readonly authMethodId?: string;
|
||||
readonly handlers?: Omit<EffectAcpClient.AcpClientHandlers, "sessionUpdate">;
|
||||
}
|
||||
|
||||
export interface AcpSessionRequestLogEvent {
|
||||
readonly method: string;
|
||||
readonly payload: unknown;
|
||||
readonly status: "started" | "succeeded" | "failed";
|
||||
readonly result?: unknown;
|
||||
readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeStartResult {
|
||||
export interface AcpSessionRuntime {
|
||||
readonly sessionId: string;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
readonly sessionSetupResult:
|
||||
@@ -58,28 +41,8 @@ export interface AcpSessionRuntimeStartResult {
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
readonly modelConfigId: string | undefined;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeShape {
|
||||
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 getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
|
||||
readonly prompt: (
|
||||
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
|
||||
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
|
||||
@@ -100,89 +63,22 @@ export interface AcpSessionRuntimeShape {
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly close: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
|
||||
|
||||
type AcpStartState =
|
||||
| { readonly _tag: "NotStarted" }
|
||||
| {
|
||||
readonly _tag: "Starting";
|
||||
readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
| { readonly _tag: "Started"; readonly result: AcpStartedState };
|
||||
|
||||
interface AcpAssistantSegmentState {
|
||||
readonly nextSegmentIndex: number;
|
||||
readonly activeItemId?: string;
|
||||
}
|
||||
|
||||
interface EnsureActiveAssistantSegmentResult {
|
||||
readonly itemId: string;
|
||||
readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
|
||||
}
|
||||
|
||||
export class AcpSessionRuntime extends Context.Service<AcpSessionRuntime, AcpSessionRuntimeShape>()(
|
||||
"t3/provider/acp/AcpSessionRuntime",
|
||||
) {
|
||||
static layer(
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Layer.Layer<
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
|
||||
}
|
||||
}
|
||||
|
||||
const makeAcpSessionRuntime = (
|
||||
export const makeAcpSessionRuntime = (
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntimeShape,
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const runtimeScope = yield* Scope.make("sequential");
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
|
||||
|
||||
const logRequest = (event: AcpSessionRequestLogEvent) =>
|
||||
options.requestLogger ? options.requestLogger(event) : Effect.void;
|
||||
|
||||
const runLoggedRequest = <A>(
|
||||
method: string,
|
||||
payload: unknown,
|
||||
effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
|
||||
): Effect.Effect<A, EffectAcpErrors.AcpError> =>
|
||||
logRequest({ method, payload, status: "started" }).pipe(
|
||||
Effect.flatMap(() =>
|
||||
effect.pipe(
|
||||
Effect.tap((result) =>
|
||||
logRequest({
|
||||
method,
|
||||
payload,
|
||||
status: "succeeded",
|
||||
result,
|
||||
}),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
logRequest({
|
||||
method,
|
||||
payload,
|
||||
status: "failed",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
@@ -203,379 +99,127 @@ const makeAcpSessionRuntime = (
|
||||
),
|
||||
);
|
||||
|
||||
const acpContext = yield* Layer.build(
|
||||
EffectAcpClient.layerChildProcess(child, {
|
||||
...(options.protocolLogging?.logIncoming !== undefined
|
||||
? { logIncoming: options.protocolLogging.logIncoming }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logOutgoing !== undefined
|
||||
? { logOutgoing: options.protocolLogging.logOutgoing }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
|
||||
}),
|
||||
).pipe(Effect.provideService(Scope.Scope, runtimeScope));
|
||||
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
}),
|
||||
);
|
||||
|
||||
const initializeClientCapabilities = {
|
||||
fs: {
|
||||
readTextFile: false,
|
||||
writeTextFile: false,
|
||||
...options.clientCapabilities?.fs,
|
||||
const client = yield* EffectAcpClient.fromChildProcess(child, {
|
||||
handlers: {
|
||||
...options.handlers,
|
||||
sessionUpdate: (notification) =>
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
params: notification,
|
||||
}),
|
||||
},
|
||||
terminal: options.clientCapabilities?.terminal ?? false,
|
||||
...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
|
||||
...(options.clientCapabilities?.elicitation
|
||||
? { elicitation: options.clientCapabilities.elicitation }
|
||||
: {}),
|
||||
...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
|
||||
} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
|
||||
}).pipe(Effect.provideService(Scope.Scope, runtimeScope));
|
||||
|
||||
const getStartedState = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(startStateRef);
|
||||
if (state._tag === "Started") {
|
||||
return state.result;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpTransportError({
|
||||
detail: "ACP session runtime has not been started",
|
||||
cause: new Error("ACP session runtime has not been started"),
|
||||
});
|
||||
const initializeResult = yield* client.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
},
|
||||
clientInfo: options.clientInfo,
|
||||
});
|
||||
|
||||
const validateConfigOptionValue = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
|
||||
if (!configOption) {
|
||||
return;
|
||||
}
|
||||
if (configOption.type === "boolean") {
|
||||
if (typeof value === "boolean") {
|
||||
return;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected boolean`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "boolean",
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (typeof value !== "string") {
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected string`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "string",
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
}
|
||||
const allowedValues = collectSessionConfigOptionValues(configOption);
|
||||
if (allowedValues.includes(value)) {
|
||||
return;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
allowedValues,
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
});
|
||||
yield* client.authenticate({
|
||||
methodId: options.authMethodId ?? "cursor_login",
|
||||
});
|
||||
|
||||
const updateConfigOptions = (
|
||||
response:
|
||||
| EffectAcpSchema.SetSessionConfigOptionResponse
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
|
||||
|
||||
const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
|
||||
Ref.update(modeStateRef, (current) =>
|
||||
current ? { ...current, currentModeId: modeId } : current,
|
||||
);
|
||||
|
||||
const setConfigOption = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
|
||||
validateConfigOptionValue(configId, value).pipe(
|
||||
Effect.flatMap(() => getStartedState),
|
||||
Effect.flatMap((started) =>
|
||||
Ref.get(configOptionsRef).pipe(
|
||||
Effect.flatMap((configOptions) => {
|
||||
const existing = findSessionConfigOption(configOptions, configId);
|
||||
if (existing && configOptionCurrentValueMatches(existing, value)) {
|
||||
return Effect.succeed({
|
||||
configOptions,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
|
||||
}
|
||||
const requestPayload =
|
||||
typeof value === "boolean"
|
||||
? ({
|
||||
sessionId: started.sessionId,
|
||||
configId,
|
||||
type: "boolean",
|
||||
value,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
sessionId: started.sessionId,
|
||||
configId,
|
||||
value: String(value),
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
|
||||
return runLoggedRequest(
|
||||
"session/set_config_option",
|
||||
requestPayload,
|
||||
acp.agent.setSessionConfigOption(requestPayload),
|
||||
).pipe(Effect.tap((response) => updateConfigOptions(response)));
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const startOnce = Effect.gen(function* () {
|
||||
const initializePayload = {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: initializeClientCapabilities,
|
||||
clientInfo: options.clientInfo,
|
||||
} satisfies EffectAcpSchema.InitializeRequest;
|
||||
|
||||
const initializeResult = yield* runLoggedRequest(
|
||||
"initialize",
|
||||
initializePayload,
|
||||
acp.agent.initialize(initializePayload),
|
||||
);
|
||||
|
||||
const authenticatePayload = {
|
||||
methodId: options.authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const loadPayload = {
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const resumed = yield* client
|
||||
.loadSession({
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
})
|
||||
.pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
const created = yield* client.createSession({
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
});
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
|
||||
|
||||
const nextState = {
|
||||
sessionId,
|
||||
initializeResult,
|
||||
sessionSetupResult,
|
||||
modelConfigId: extractModelConfigId(sessionSetupResult),
|
||||
} satisfies AcpStartedState;
|
||||
return nextState;
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
const deferred = yield* Deferred.make<
|
||||
AcpSessionRuntimeStartResult,
|
||||
EffectAcpErrors.AcpError
|
||||
>();
|
||||
const effect = yield* Ref.modify(startStateRef, (state) => {
|
||||
switch (state._tag) {
|
||||
case "Started":
|
||||
return [Effect.succeed(state.result), state] as const;
|
||||
case "Starting":
|
||||
return [Deferred.await(state.deferred), state] as const;
|
||||
case "NotStarted":
|
||||
return [
|
||||
startOnce.pipe(
|
||||
Effect.tap((result) =>
|
||||
Ref.set(startStateRef, { _tag: "Started", result }).pipe(
|
||||
Effect.andThen(Deferred.succeed(deferred, result)),
|
||||
),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
Deferred.failCause(deferred, cause).pipe(
|
||||
Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ _tag: "Starting", deferred } satisfies AcpStartState,
|
||||
] as const;
|
||||
}
|
||||
} else {
|
||||
const created = yield* client.createSession({
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
});
|
||||
return yield* effect;
|
||||
});
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
|
||||
const close = Scope.close(runtimeScope, Exit.void).pipe(Effect.asVoid);
|
||||
|
||||
return {
|
||||
handleRequestPermission: acp.handleRequestPermission,
|
||||
handleElicitation: acp.handleElicitation,
|
||||
handleReadTextFile: acp.handleReadTextFile,
|
||||
handleWriteTextFile: acp.handleWriteTextFile,
|
||||
handleCreateTerminal: acp.handleCreateTerminal,
|
||||
handleTerminalOutput: acp.handleTerminalOutput,
|
||||
handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
|
||||
handleTerminalKill: acp.handleTerminalKill,
|
||||
handleTerminalRelease: acp.handleTerminalRelease,
|
||||
handleSessionUpdate: acp.handleSessionUpdate,
|
||||
handleElicitationComplete: acp.handleElicitationComplete,
|
||||
handleUnknownExtRequest: acp.handleUnknownExtRequest,
|
||||
handleUnknownExtNotification: acp.handleUnknownExtNotification,
|
||||
handleExtRequest: acp.handleExtRequest,
|
||||
handleExtNotification: acp.handleExtNotification,
|
||||
start: () => start,
|
||||
getEvents: () => Stream.fromQueue(eventQueue),
|
||||
sessionId,
|
||||
initializeResult,
|
||||
sessionSetupResult,
|
||||
modelConfigId: extractModelConfigId(sessionSetupResult),
|
||||
events: Stream.fromQueue(eventQueue),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
getConfigOptions: Ref.get(configOptionsRef),
|
||||
prompt: (payload) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
...payload,
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
return closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
),
|
||||
client.prompt({
|
||||
sessionId,
|
||||
...payload,
|
||||
}),
|
||||
cancel: client.cancel({ sessionId }),
|
||||
setMode: (modeId) =>
|
||||
Ref.get(modeStateRef).pipe(
|
||||
Effect.flatMap((modeState) => {
|
||||
if (modeState?.currentModeId === modeId) {
|
||||
return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
|
||||
}
|
||||
return setConfigOption("mode", modeId).pipe(
|
||||
Effect.tap(() => updateCurrentModeId(modeId)),
|
||||
Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
|
||||
);
|
||||
}),
|
||||
client.setSessionMode({
|
||||
sessionId,
|
||||
modeId,
|
||||
}),
|
||||
setConfigOption: (configId, value) =>
|
||||
client.setSessionConfigOption(
|
||||
typeof value === "boolean"
|
||||
? ({
|
||||
sessionId,
|
||||
configId,
|
||||
type: "boolean",
|
||||
value,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
sessionId,
|
||||
configId,
|
||||
value: String(value),
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest),
|
||||
),
|
||||
setConfigOption,
|
||||
setModel: (model) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
request: (method, payload) =>
|
||||
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
|
||||
notify: acp.raw.notify,
|
||||
} satisfies AcpSessionRuntimeShape;
|
||||
client
|
||||
.setSessionConfigOption({
|
||||
sessionId,
|
||||
configId: extractModelConfigId(sessionSetupResult) ?? "model",
|
||||
value: model,
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
request: client.extRequest,
|
||||
notify: client.extNotification,
|
||||
close,
|
||||
} satisfies AcpSessionRuntime;
|
||||
});
|
||||
|
||||
function sessionConfigOptionsFromSetup(
|
||||
response:
|
||||
| {
|
||||
readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
|
||||
}
|
||||
| undefined,
|
||||
): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
|
||||
return response?.configOptions ?? [];
|
||||
}
|
||||
|
||||
function configOptionCurrentValueMatches(
|
||||
configOption: EffectAcpSchema.SessionConfigOption,
|
||||
value: string | boolean,
|
||||
): boolean {
|
||||
const currentValue = configOption.currentValue;
|
||||
if (configOption.type === "boolean") {
|
||||
return currentValue === value;
|
||||
}
|
||||
if (typeof currentValue !== "string") {
|
||||
return false;
|
||||
}
|
||||
return currentValue.trim() === String(value).trim();
|
||||
}
|
||||
|
||||
const handleSessionUpdate = ({
|
||||
queue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly params: EffectAcpSchema.SessionNotification;
|
||||
}): Effect.Effect<void> =>
|
||||
}): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseSessionUpdateEvent(params);
|
||||
if (parsed.modeId) {
|
||||
@@ -585,11 +229,7 @@ const handleSessionUpdate = ({
|
||||
}
|
||||
for (const event of parsed.events) {
|
||||
if (event._tag === "ToolCallUpdated") {
|
||||
yield* closeActiveAssistantSegment({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
});
|
||||
const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {
|
||||
const merged = yield* Ref.modify(toolCallsRef, (current) => {
|
||||
const previous = current.get(event.toolCall.toolCallId);
|
||||
const nextToolCall = mergeToolCallState(previous, event.toolCall);
|
||||
const next = new Map(current);
|
||||
@@ -598,11 +238,8 @@ const handleSessionUpdate = ({
|
||||
} else {
|
||||
next.set(nextToolCall.toolCallId, nextToolCall);
|
||||
}
|
||||
return [{ previous, merged: nextToolCall }, next] as const;
|
||||
return [nextToolCall, next] as const;
|
||||
});
|
||||
if (!shouldEmitToolCallUpdate(previous, merged)) {
|
||||
continue;
|
||||
}
|
||||
yield* Queue.offer(queue, {
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall: merged,
|
||||
@@ -610,27 +247,9 @@ const handleSessionUpdate = ({
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (event._tag === "ContentDelta") {
|
||||
if (event.text.trim().length === 0) {
|
||||
const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
|
||||
if (!assistantSegmentState.activeItemId) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const itemId = yield* ensureActiveAssistantSegment({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId: params.sessionId,
|
||||
});
|
||||
yield* Queue.offer(queue, {
|
||||
...event,
|
||||
itemId,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
yield* Queue.offer(queue, event);
|
||||
}
|
||||
});
|
||||
}).pipe(Effect.mapError(EffectAcpErrors.normalizeAcpError));
|
||||
|
||||
function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
|
||||
const normalized = nextModeId.trim();
|
||||
@@ -644,79 +263,3 @@ function updateModeState(modeState: AcpSessionModeState, nextModeId: string): Ac
|
||||
}
|
||||
: modeState;
|
||||
}
|
||||
|
||||
function shouldEmitToolCallUpdate(
|
||||
previous: AcpToolCallState | undefined,
|
||||
next: AcpToolCallState,
|
||||
): boolean {
|
||||
if (next.status === "completed" || next.status === "failed") {
|
||||
return true;
|
||||
}
|
||||
if (!next.detail) {
|
||||
return false;
|
||||
}
|
||||
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
|
||||
}
|
||||
|
||||
const assistantItemId = (sessionId: string, segmentIndex: number) =>
|
||||
`assistant:${sessionId}:segment:${segmentIndex}`;
|
||||
|
||||
const ensureActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
}) =>
|
||||
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
|
||||
assistantSegmentRef,
|
||||
(current) => {
|
||||
if (current.activeItemId) {
|
||||
return [{ itemId: current.activeItemId }, current] as const;
|
||||
}
|
||||
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
|
||||
return [
|
||||
{
|
||||
itemId,
|
||||
startedEvent: {
|
||||
_tag: "AssistantItemStarted",
|
||||
itemId,
|
||||
} satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
|
||||
},
|
||||
{
|
||||
nextSegmentIndex: current.nextSegmentIndex + 1,
|
||||
activeItemId: itemId,
|
||||
} satisfies AcpAssistantSegmentState,
|
||||
] as const;
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.startedEvent
|
||||
? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
|
||||
: Effect.succeed(result.itemId),
|
||||
),
|
||||
);
|
||||
|
||||
const closeActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
}) =>
|
||||
Ref.modify(assistantSegmentRef, (current) => {
|
||||
if (!current.activeItemId) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
return [
|
||||
{
|
||||
_tag: "AssistantItemCompleted",
|
||||
itemId: current.activeItemId,
|
||||
} satisfies AcpParsedSessionEvent,
|
||||
{
|
||||
nextSegmentIndex: current.nextSegmentIndex,
|
||||
} satisfies AcpAssistantSegmentState,
|
||||
] as const;
|
||||
}).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));
|
||||
@@ -1,147 +0,0 @@
|
||||
import { Effect, Option, Schema, SchemaIssue, SchemaTransformation } from "effect";
|
||||
|
||||
import type { AcpError } from "./AcpErrors.ts";
|
||||
|
||||
/** JSON-RPC 2.0 error object on the wire. */
|
||||
export const JsonRpcErrorPayload = Schema.Struct({
|
||||
code: Schema.Number,
|
||||
message: Schema.String,
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
/** Parsed JSON object from one NDJSON line before JSON-RPC classification. */
|
||||
export const JsonRpcInboundWire = Schema.Struct({
|
||||
jsonrpc: Schema.optional(Schema.String),
|
||||
id: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
|
||||
method: Schema.optional(Schema.String),
|
||||
params: Schema.optional(Schema.Unknown),
|
||||
result: Schema.optional(Schema.Unknown),
|
||||
error: Schema.optional(JsonRpcErrorPayload),
|
||||
});
|
||||
|
||||
export const AcpInboundResponse = Schema.TaggedStruct("response", {
|
||||
id: Schema.Union([Schema.String, Schema.Number]),
|
||||
result: Schema.optional(Schema.Unknown),
|
||||
error: Schema.optional(JsonRpcErrorPayload),
|
||||
});
|
||||
|
||||
export const AcpInboundRequest = Schema.TaggedStruct("request", {
|
||||
id: Schema.Union([Schema.String, Schema.Number]),
|
||||
method: Schema.String,
|
||||
params: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
export const AcpInboundNotification = Schema.TaggedStruct("notification", {
|
||||
method: Schema.String,
|
||||
params: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
/**
|
||||
* Inbound JSON-RPC messages from the ACP agent (stdout), after line framing.
|
||||
*/
|
||||
export const AcpInboundMessage = Schema.Union([
|
||||
AcpInboundResponse,
|
||||
AcpInboundRequest,
|
||||
AcpInboundNotification,
|
||||
]);
|
||||
|
||||
export type AcpInboundMessage = typeof AcpInboundMessage.Type;
|
||||
|
||||
const jsonRpcWireToInbound = SchemaTransformation.transformOrFail({
|
||||
decode: (parsed: typeof JsonRpcInboundWire.Type) => {
|
||||
const id = parsed.id;
|
||||
const method = parsed.method;
|
||||
const hasId = id !== undefined && id !== null;
|
||||
const hasMethod = typeof method === "string";
|
||||
|
||||
if (hasId && (parsed.result !== undefined || parsed.error !== undefined)) {
|
||||
const err = parsed.error;
|
||||
const rpcError =
|
||||
err !== undefined
|
||||
? {
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
...(err.data !== undefined ? { data: err.data } : {}),
|
||||
}
|
||||
: undefined;
|
||||
return Effect.succeed(
|
||||
AcpInboundResponse.makeUnsafe({
|
||||
id,
|
||||
...(parsed.result !== undefined ? { result: parsed.result } : {}),
|
||||
...(rpcError ? { error: rpcError } : {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (hasMethod && hasId) {
|
||||
return Effect.succeed(
|
||||
AcpInboundRequest.makeUnsafe({
|
||||
id,
|
||||
method,
|
||||
...(parsed.params !== undefined ? { params: parsed.params } : {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (hasMethod && !hasId) {
|
||||
return Effect.succeed(
|
||||
AcpInboundNotification.makeUnsafe({
|
||||
method,
|
||||
...(parsed.params !== undefined ? { params: parsed.params } : {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(parsed), {
|
||||
message: "Unrecognized JSON-RPC inbound message shape",
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
encode: (msg: AcpInboundMessage) => {
|
||||
if (msg._tag === "response") {
|
||||
return Effect.succeed({
|
||||
jsonrpc: "2.0" as const,
|
||||
id: msg.id,
|
||||
...(msg.result !== undefined ? { result: msg.result } : {}),
|
||||
...(msg.error !== undefined ? { error: msg.error } : {}),
|
||||
});
|
||||
}
|
||||
if (msg._tag === "request") {
|
||||
return Effect.succeed({
|
||||
jsonrpc: "2.0" as const,
|
||||
id: msg.id,
|
||||
method: msg.method,
|
||||
...(msg.params !== undefined ? { params: msg.params } : {}),
|
||||
});
|
||||
}
|
||||
return Effect.succeed({
|
||||
jsonrpc: "2.0" as const,
|
||||
method: msg.method,
|
||||
...(msg.params !== undefined ? { params: msg.params } : {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const jsonRpcWireDecodedToInbound = JsonRpcInboundWire.pipe(
|
||||
Schema.decodeTo(Schema.toType(AcpInboundMessage), jsonRpcWireToInbound),
|
||||
);
|
||||
|
||||
/** Decode one NDJSON line (JSON string) to a classified inbound message. */
|
||||
export const AcpInboundFromJsonLine = Schema.fromJsonString(jsonRpcWireDecodedToInbound);
|
||||
|
||||
export const decodeAcpInboundFromJsonLine = Schema.decodeEffect(AcpInboundFromJsonLine);
|
||||
|
||||
export interface AcpSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string;
|
||||
/** Merged with `process.env` for the child. */
|
||||
readonly env?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export type AcpServerRequestHandler = (
|
||||
params: unknown,
|
||||
requestId: number | string,
|
||||
) => Effect.Effect<unknown, AcpError>;
|
||||
@@ -6,125 +6,90 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { makeAcpJsonRpcConnection } from "./AcpJsonRpcConnection.ts";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
import { makeAcpSessionRuntime } from "./AcpSessionRuntime.ts";
|
||||
|
||||
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
|
||||
it.effect("initialize and authenticate against real agent acp", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
const init = yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
});
|
||||
expect(init).toBeDefined();
|
||||
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
expect(runtime.initializeResult).toBeDefined();
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("session/new returns configOptions with a model selector", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
});
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
|
||||
const result = yield* conn.request("session/new", {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
const result = runtime.sessionSetupResult;
|
||||
console.log("session/new result:", JSON.stringify(result, null, 2));
|
||||
|
||||
expect(isRecord(result)).toBe(true);
|
||||
const r = result as Record<string, unknown>;
|
||||
expect(typeof r.sessionId).toBe("string");
|
||||
expect(typeof runtime.sessionId).toBe("string");
|
||||
|
||||
const configOptions = r.configOptions;
|
||||
const configOptions = result.configOptions;
|
||||
console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
|
||||
|
||||
if (Array.isArray(configOptions)) {
|
||||
const modelConfig = configOptions.find(
|
||||
(opt: unknown) => isRecord(opt) && opt.category === "model",
|
||||
);
|
||||
const modelConfig = configOptions.find((opt) => opt.category === "model");
|
||||
console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
|
||||
expect(modelConfig).toBeDefined();
|
||||
expect(isRecord(modelConfig) && typeof modelConfig.id === "string").toBe(true);
|
||||
expect(typeof modelConfig?.id).toBe("string");
|
||||
}
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("session/set_config_option switches the model in-session", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
});
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
|
||||
const newResult = (yield* conn.request("session/new", {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
})) as Record<string, unknown>;
|
||||
const sessionId = newResult.sessionId as string;
|
||||
const newResult = runtime.sessionSetupResult;
|
||||
|
||||
const configOptions = newResult.configOptions;
|
||||
let modelConfigId = "model";
|
||||
if (Array.isArray(configOptions)) {
|
||||
const modelConfig = configOptions.find(
|
||||
(opt: unknown) => isRecord(opt) && opt.category === "model",
|
||||
);
|
||||
if (isRecord(modelConfig) && typeof modelConfig.id === "string") {
|
||||
const modelConfig = configOptions.find((opt) => opt.category === "model");
|
||||
if (typeof modelConfig?.id === "string") {
|
||||
modelConfigId = modelConfig.id;
|
||||
}
|
||||
}
|
||||
|
||||
const setResult = yield* conn.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: modelConfigId,
|
||||
value: "composer-2",
|
||||
});
|
||||
const setResult: EffectAcpSchema.SetSessionConfigOptionResponse =
|
||||
yield* runtime.setConfigOption(modelConfigId, "composer-2");
|
||||
|
||||
console.log("session/set_config_option result:", JSON.stringify(setResult, null, 2));
|
||||
|
||||
expect(isRecord(setResult)).toBe(true);
|
||||
const sr = setResult as Record<string, unknown>;
|
||||
if (Array.isArray(sr.configOptions)) {
|
||||
const modelConfig = sr.configOptions.find(
|
||||
(opt: unknown) => isRecord(opt) && opt.category === "model",
|
||||
);
|
||||
if (isRecord(modelConfig)) {
|
||||
if (Array.isArray(setResult.configOptions)) {
|
||||
const modelConfig = setResult.configOptions.find((opt) => opt.category === "model");
|
||||
if (modelConfig?.type === "select") {
|
||||
expect(modelConfig.currentValue).toBe("composer-2");
|
||||
}
|
||||
}
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -29,7 +29,6 @@ describe("CursorAcpExtension", () => {
|
||||
id: "language",
|
||||
header: "Question",
|
||||
question: "Which language should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "TypeScript", description: "TypeScript" },
|
||||
{ label: "Rust", description: "Rust" },
|
||||
@@ -38,35 +37,6 @@ describe("CursorAcpExtension", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("defaults ask-question multi-select to false when Cursor omits allowMultiple", () => {
|
||||
const questions = extractAskQuestions({
|
||||
toolCallId: "ask-2",
|
||||
questions: [
|
||||
{
|
||||
id: "mode",
|
||||
prompt: "Which mode should I use?",
|
||||
options: [
|
||||
{ id: "agent", label: "Agent" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "mode",
|
||||
header: "Question",
|
||||
question: "Which mode should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Agent", description: "Agent" },
|
||||
{ label: "Plan", description: "Plan" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("extracts plan markdown from the real Cursor create-plan payload shape", () => {
|
||||
const planMarkdown = extractPlanMarkdown({
|
||||
toolCallId: "plan-1",
|
||||
@@ -83,25 +53,20 @@ describe("CursorAcpExtension", () => {
|
||||
expect(planMarkdown).toBe("# Plan\n\n1. Add schemas\n2. Remove casts");
|
||||
});
|
||||
|
||||
it("projects todo updates into a plan shape and drops invalid entries", () => {
|
||||
it("projects todo updates into a plan shape", () => {
|
||||
expect(
|
||||
extractTodosAsPlan({
|
||||
toolCallId: "todos-1",
|
||||
todos: [
|
||||
{ id: "1", content: "Inspect state", status: "completed" },
|
||||
{ id: "2", content: " Apply fix ", status: "in_progress" },
|
||||
{ id: "3", title: "Fallback title", status: "pending" },
|
||||
{ id: "4", content: "Unknown status", status: "weird_status" },
|
||||
{ id: "5", content: " " },
|
||||
{ content: "Inspect state", status: "completed" },
|
||||
{ title: "Apply fix", status: "in_progress" },
|
||||
{},
|
||||
],
|
||||
merge: true,
|
||||
}),
|
||||
).toEqual({
|
||||
plan: [
|
||||
{ step: "Inspect state", status: "completed" },
|
||||
{ step: "Apply fix", status: "inProgress" },
|
||||
{ step: "Fallback title", status: "pending" },
|
||||
{ step: "Unknown status", status: "pending" },
|
||||
{ step: "Step 3", status: "pending" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
/**
|
||||
* Public Docs: https://cursor.com/docs/cli/acp#cursor-extension-methods
|
||||
* Additional reference provided by the Cursor team: https://anysphere.enterprise.slack.com/files/U068SSJE141/F0APT1HSZRP/cursor-acp-extension-method-schemas.md
|
||||
*/
|
||||
import type { UserInputQuestion } from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
|
||||
@@ -14,31 +10,35 @@ const CursorAskQuestion = Schema.Struct({
|
||||
id: Schema.String,
|
||||
prompt: Schema.String,
|
||||
options: Schema.Array(CursorAskQuestionOption),
|
||||
allowMultiple: Schema.optional(Schema.Boolean),
|
||||
allowMultiple: Schema.Boolean,
|
||||
});
|
||||
|
||||
export const CursorAskQuestionRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
toolCallId: Schema.optional(Schema.String),
|
||||
title: Schema.optional(Schema.String),
|
||||
questions: Schema.Array(CursorAskQuestion),
|
||||
});
|
||||
|
||||
const CursorTodoStatus = Schema.String;
|
||||
const CursorTodoStatus = Schema.Union([
|
||||
Schema.Literal("pending"),
|
||||
Schema.Literal("in_progress"),
|
||||
Schema.Literal("completed"),
|
||||
Schema.Literal("cancelled"),
|
||||
]);
|
||||
|
||||
const CursorTodo = Schema.Struct({
|
||||
id: Schema.optional(Schema.String),
|
||||
content: Schema.optional(Schema.String),
|
||||
title: Schema.optional(Schema.String),
|
||||
status: Schema.optional(CursorTodoStatus),
|
||||
status: CursorTodoStatus,
|
||||
});
|
||||
|
||||
const CursorPlanPhase = Schema.Struct({
|
||||
name: Schema.String,
|
||||
name: Schema.optional(Schema.String),
|
||||
todos: Schema.Array(CursorTodo),
|
||||
});
|
||||
|
||||
export const CursorCreatePlanRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
toolCallId: Schema.optional(Schema.String),
|
||||
name: Schema.optional(Schema.String),
|
||||
overview: Schema.optional(Schema.String),
|
||||
plan: Schema.String,
|
||||
@@ -47,11 +47,7 @@ export const CursorCreatePlanRequest = Schema.Struct({
|
||||
phases: Schema.optional(Schema.Array(CursorPlanPhase)),
|
||||
});
|
||||
|
||||
export const CursorUpdateTodosRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
todos: Schema.Array(CursorTodo),
|
||||
merge: Schema.Boolean,
|
||||
});
|
||||
export const CursorUpdateTodosRequest = Schema.Unknown;
|
||||
|
||||
export function extractAskQuestions(
|
||||
params: typeof CursorAskQuestionRequest.Type,
|
||||
@@ -60,7 +56,7 @@ export function extractAskQuestions(
|
||||
id: question.id,
|
||||
header: "Question",
|
||||
question: question.prompt,
|
||||
multiSelect: question.allowMultiple === true,
|
||||
multiSelect: question.allowMultiple,
|
||||
options:
|
||||
question.options.length > 0
|
||||
? question.options.map((option) => ({
|
||||
@@ -82,18 +78,39 @@ export function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type)
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
} {
|
||||
const plan = params.todos.flatMap((todo) => {
|
||||
const step = todo.content?.trim() ?? todo.title?.trim() ?? "";
|
||||
if (step === "") {
|
||||
return [];
|
||||
}
|
||||
if (typeof params !== "object" || params === null) {
|
||||
return { plan: [] };
|
||||
}
|
||||
const record = params as {
|
||||
readonly todos?: ReadonlyArray<{
|
||||
readonly content?: string;
|
||||
readonly title?: string;
|
||||
readonly status?: string;
|
||||
}>;
|
||||
readonly items?: ReadonlyArray<{
|
||||
readonly content?: string;
|
||||
readonly title?: string;
|
||||
readonly status?: string;
|
||||
}>;
|
||||
};
|
||||
const todos = record.todos ?? record.items;
|
||||
if (!todos) {
|
||||
return { plan: [] };
|
||||
}
|
||||
const plan = todos.map((t, i) => {
|
||||
const step =
|
||||
typeof t?.content === "string"
|
||||
? t.content
|
||||
: typeof t?.title === "string"
|
||||
? t.title
|
||||
: `Step ${i + 1}`;
|
||||
const status: "pending" | "inProgress" | "completed" =
|
||||
todo.status === "completed"
|
||||
t?.status === "completed"
|
||||
? "completed"
|
||||
: todo.status === "in_progress" || todo.status === "inProgress"
|
||||
: t?.status === "in_progress" || t?.status === "inProgress"
|
||||
? "inProgress"
|
||||
: "pending";
|
||||
return [{ step, status }];
|
||||
return { step, status };
|
||||
});
|
||||
return { plan };
|
||||
}
|
||||
@@ -83,10 +83,7 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
);
|
||||
const cursorAdapterLayer = makeCursorAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const acpAdapterLayer = makeAcpAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
).pipe(Layer.provide(AcpAgentRegistryLive));
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
|
||||
Reference in new issue
Block a user