From 7afe841e21d299bdbdf4e5d052f3b1d319db548e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 27 Mar 2026 12:51:04 -0700 Subject: [PATCH] improve sdk and use it --- apps/server/package.json | 1 + apps/server/scripts/acp-mock-agent.mjs | 315 ---- apps/server/scripts/acp-mock-agent.ts | 733 +++------ .../src/persistence/NodeSqliteClient.ts | 95 +- .../src/provider/Layers/CursorAdapter.test.ts | 18 +- .../src/provider/Layers/CursorAdapter.ts | 1424 ++++------------- .../provider/Layers/ProviderRegistry.test.ts | 7 + .../provider/acp/AcpAdapterSupport.test.ts | 108 +- .../src/provider/acp/AcpAdapterSupport.ts | 185 +++ apps/server/src/provider/acp/AcpErrors.ts | 51 - .../provider/acp/AcpJsonRpcConnection.test.ts | 50 +- .../src/provider/acp/AcpJsonRpcConnection.ts | 256 --- .../src/provider/acp/AcpRuntimeModel.test.ts | 28 +- .../src/provider/acp/AcpRuntimeModel.ts | 115 +- .../src/provider/acp/AcpSessionRuntime.ts | 657 ++------ apps/server/src/provider/acp/AcpTypes.ts | 147 -- .../provider/acp/CursorAcpCliProbe.test.ts | 109 +- .../provider/acp/CursorAcpExtension.test.ts | 45 +- .../src/provider/acp/CursorAcpExtension.ts | 67 +- apps/server/src/serverLayers.ts | 5 +- bun.lock | 53 +- package.json | 16 +- packages/contracts/src/providerRuntime.ts | 18 +- packages/effect-acp/package.json | 74 +- .../effect-acp/src/_generated/schema.gen.ts | 558 +++++-- packages/effect-acp/src/child-process.ts | 11 +- packages/effect-acp/src/client.test.ts | 23 + packages/effect-acp/src/client.ts | 98 +- packages/effect-acp/src/protocol.test.ts | 10 +- packages/effect-acp/src/protocol.ts | 10 +- packages/effect-acp/src/schema.ts | 4 +- .../examples/cursor-acp-client.example.ts | 7 +- .../effect-acp/test/fixtures/acp-mock-peer.ts | 10 + patches/effect@4.0.0-beta.41.patch | 108 ++ 34 files changed, 1900 insertions(+), 3516 deletions(-) delete mode 100644 apps/server/scripts/acp-mock-agent.mjs delete mode 100644 apps/server/src/provider/acp/AcpErrors.ts delete mode 100644 apps/server/src/provider/acp/AcpJsonRpcConnection.ts delete mode 100644 apps/server/src/provider/acp/AcpTypes.ts create mode 100644 patches/effect@4.0.0-beta.41.patch diff --git a/apps/server/package.json b/apps/server/package.json index 250a667a57..0315e5101a 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -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" }, diff --git a/apps/server/scripts/acp-mock-agent.mjs b/apps/server/scripts/acp-mock-agent.mjs deleted file mode 100644 index c828cc453d..0000000000 --- a/apps/server/scripts/acp-mock-agent.mjs +++ /dev/null @@ -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)}` }, - }); - } -}); diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 26ffa084a8..9ab7c9783f 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -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(); - -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 { - if (parameterizedModelPicker) { - const baseOptions: Array = [ - { - 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 { ]; } -const availableModes: ReadonlyArray = [ +const availableModes = [ { id: "ask", name: "Ask", @@ -199,179 +51,185 @@ const availableModes: ReadonlyArray = [ 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; + }; + 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)}` }, + }); + } +}); diff --git a/apps/server/src/persistence/NodeSqliteClient.ts b/apps/server/src/persistence/NodeSqliteClient.ts index 631df9c8b9..8a876dd73e 100644 --- a/apps/server/src/persistence/NodeSqliteClient.ts +++ b/apps/server/src/persistence/NodeSqliteClient.ts @@ -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, raw: boolean) => - Effect.withFiber, 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) : []); - } catch (cause) { - return Effect.fail( - new SqlError({ - reason: classifySqliteError(cause, { - message: "Failed to execute statement", - operation: "execute", + const runStatement = ( + statement: StatementSync, + params: ReadonlyArray, + raw: boolean, + ) => + Effect.withFiber, 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) : []); + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), }), + ); + } + }); + + const run = (sql: string, params: ReadonlyArray, raw = false) => + Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw)); + + const runValues = (sql: string, params: ReadonlyArray) => + 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 + >; + } + statement.run(...(params as any)); + return []; + }, + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), + }), }), ); } diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts index a0af6596ec..94e1b26274 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.test.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts @@ -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) { const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-mock-")); @@ -26,7 +27,7 @@ async function makeMockAgentWrapper(extraEnv?: Record) { .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); diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts index 804a806a2e..0fc47002ee 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.ts @@ -1,33 +1,27 @@ /** - * CursorAdapterLive — Cursor CLI (`agent acp`) via ACP JSON-RPC. + * CursorAdapterLive — Cursor CLI (`agent acp`) via ACP. * * @module CursorAdapterLive */ import * as nodePath from "node:path"; -import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { ApprovalRequestId, EventId, - type ProviderInteractionMode, type ProviderApprovalDecision, + type ProviderInteractionMode, type ProviderRuntimeEvent, type ProviderSession, type ProviderUserInputAnswers, - RuntimeItemId, RuntimeRequestId, type RuntimeMode, type ThreadId, - type ToolLifecycleItemType, TurnId, - type UserInputQuestion, } from "@t3tools/contracts"; import { - Cause, DateTime, Deferred, Effect, - Exit, Fiber, FileSystem, Layer, @@ -36,6 +30,10 @@ import { Schema, Stream, } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import { defineExtRequest } from "effect-acp/client"; +import * as EffectAcpErrors from "effect-acp/errors"; +import type * as EffectAcpSchema from "effect-acp/schema"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; @@ -43,25 +41,37 @@ import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderAdapterProcessError, ProviderAdapterRequestError, - ProviderAdapterSessionClosedError, ProviderAdapterSessionNotFoundError, ProviderAdapterValidationError, - type ProviderAdapterError, } from "../Errors.ts"; +import { makeAcpSessionRuntime, type AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts"; import { - attachAcpJsonRpcConnection, - disposeAcpChild, - spawnAcpChildProcess, - type AcpJsonRpcConnection, -} from "../acp/AcpJsonRpcConnection.ts"; -import type { AcpInboundMessage } from "../acp/AcpTypes.ts"; -import { AcpProcessExitedError, AcpRpcError, type AcpError } from "../acp/AcpErrors.ts"; + acpPermissionOutcome, + makeAcpContentDeltaEvent, + makeAcpPlanUpdatedEvent, + makeAcpRequestOpenedEvent, + makeAcpRequestResolvedEvent, + makeAcpToolCallEvent, + mapAcpToAdapterError, +} from "../acp/AcpAdapterSupport.ts"; +import { + type AcpSessionMode, + type AcpSessionModeState, + parsePermissionRequest, +} from "../acp/AcpRuntimeModel.ts"; +import { + CursorAskQuestionRequest, + CursorCreatePlanRequest, + CursorUpdateTodosRequest, + extractAskQuestions, + extractPlanMarkdown, + extractTodosAsPlan, +} from "../acp/CursorAcpExtension.ts"; import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts"; import { resolveCursorAcpModelId } from "./CursorProvider.ts"; import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; const PROVIDER = "cursor" as const; - const CURSOR_RESUME_VERSION = 1 as const; const ACP_PLAN_MODE_ALIASES = ["plan", "architect"]; const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"]; @@ -72,6 +82,32 @@ export interface CursorAdapterLiveOptions { readonly nativeEventLogger?: EventNdjsonLogger; } +interface PendingApproval { + readonly decision: Deferred.Deferred; + readonly requestType: + | "exec_command_approval" + | "file_read_approval" + | "file_change_approval" + | "unknown"; +} + +interface PendingUserInput { + readonly answers: Deferred.Deferred; +} + +interface CursorSessionContext { + readonly threadId: ThreadId; + session: ProviderSession; + readonly acp: AcpSessionRuntime; + notificationFiber: Fiber.Fiber | undefined; + readonly pendingApprovals: Map; + readonly pendingUserInputs: Map; + readonly turns: Array<{ id: TurnId; items: Array }>; + lastPlanFingerprint: string | undefined; + activeTurnId: TurnId | undefined; + stopped: boolean; +} + function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } @@ -83,18 +119,6 @@ function parseCursorResume(raw: unknown): { sessionId: string } | undefined { return { sessionId: raw.sessionId.trim() }; } -function extractModelConfigId(sessionResponse: unknown): string | undefined { - if (!isRecord(sessionResponse)) return undefined; - const configOptions = sessionResponse.configOptions; - if (!Array.isArray(configOptions)) return undefined; - for (const opt of configOptions) { - if (isRecord(opt) && opt.category === "model" && typeof opt.id === "string") { - return opt.id; - } - } - return undefined; -} - function toMessage(cause: unknown, fallback: string): string { if (cause instanceof Error && cause.message.length > 0) { return cause.message; @@ -102,351 +126,6 @@ function toMessage(cause: unknown, fallback: string): string { return fallback; } -function mapAcpToAdapterError( - threadId: ThreadId, - method: string, - error: AcpError, -): ProviderAdapterError { - if (Schema.is(AcpProcessExitedError)(error)) { - return new ProviderAdapterSessionClosedError({ - provider: PROVIDER, - threadId, - cause: error, - }); - } - if (Schema.is(AcpRpcError)(error)) { - return new ProviderAdapterRequestError({ - provider: PROVIDER, - method, - detail: error.message, - cause: error, - }); - } - return new ProviderAdapterRequestError({ - provider: PROVIDER, - method, - detail: toMessage(error, `${method} failed`), - cause: error, - }); -} - -function acpPermissionOutcome(decision: ProviderApprovalDecision): string { - switch (decision) { - case "acceptForSession": - return "allow-always"; - case "accept": - return "allow-once"; - case "decline": - case "cancel": - default: - return "reject-once"; - } -} - -interface AcpSessionMode { - readonly id: string; - readonly name: string; - readonly description?: string; -} - -interface AcpSessionModeState { - readonly currentModeId: string; - readonly availableModes: ReadonlyArray; -} - -interface AcpToolCallState { - readonly toolCallId: string; - readonly itemType: ToolLifecycleItemType; - readonly title?: string; - readonly status?: "pending" | "inProgress" | "completed" | "failed"; - readonly command?: string; - readonly detail?: string; - readonly data: Record; -} - -function normalizePlanStepStatus(raw: unknown): "pending" | "inProgress" | "completed" { - switch (raw) { - case "completed": - return "completed"; - case "in_progress": - case "inProgress": - return "inProgress"; - default: - return "pending"; - } -} - -function normalizeToolCallStatus( - raw: unknown, - fallback?: "pending" | "inProgress" | "completed" | "failed", -): "pending" | "inProgress" | "completed" | "failed" | undefined { - switch (raw) { - case "pending": - return "pending"; - case "in_progress": - case "inProgress": - return "inProgress"; - case "completed": - return "completed"; - case "failed": - return "failed"; - default: - return fallback; - } -} - -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; - } -} - -function normalizeCommandValue(value: unknown): string | undefined { - if (typeof value === "string" && value.trim().length > 0) { - return value.trim(); - } - if (!Array.isArray(value)) { - return undefined; - } - const parts = value - .map((entry) => (typeof entry === "string" && entry.trim().length > 0 ? entry.trim() : null)) - .filter((entry): entry is string => entry !== null); - return parts.length > 0 ? parts.join(" ") : undefined; -} - -function extractCommandFromTitle(title: string | undefined): string | undefined { - if (!title) { - return undefined; - } - const match = /`([^`]+)`/.exec(title); - return match?.[1]?.trim() || undefined; -} - -function extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined { - if (isRecord(rawInput)) { - const directCommand = normalizeCommandValue(rawInput.command); - if (directCommand) { - return directCommand; - } - const executable = typeof rawInput.executable === "string" ? rawInput.executable.trim() : ""; - const args = normalizeCommandValue(rawInput.args); - if (executable && args) { - return `${executable} ${args}`; - } - if (executable) { - return executable; - } - } - return extractCommandFromTitle(title); -} - -function extractTextContentFromToolCallContent(content: unknown): string | undefined { - if (!Array.isArray(content)) { - return undefined; - } - const chunks = content - .map((entry) => { - if (!isRecord(entry)) { - return undefined; - } - if (entry.type !== "content") { - return undefined; - } - const nestedContent = entry.content; - if (!isRecord(nestedContent) || nestedContent.type !== "text") { - return undefined; - } - return typeof nestedContent.text === "string" && nestedContent.text.trim().length > 0 - ? nestedContent.text.trim() - : undefined; - }) - .filter((entry): entry is string => entry !== undefined); - return chunks.length > 0 ? chunks.join("\n") : undefined; -} - -function toolLifecycleItemTypeFromKind(kind: unknown): ToolLifecycleItemType { - switch (kind) { - case "execute": - return "command_execution"; - case "edit": - case "delete": - case "move": - return "file_change"; - case "search": - case "fetch": - return "web_search"; - default: - return "dynamic_tool_call"; - } -} - -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 parseToolCallState( - raw: unknown, - options?: { - readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed"; - }, -): AcpToolCallState | undefined { - if (!isRecord(raw)) { - return undefined; - } - const toolCallId = typeof raw.toolCallId === "string" ? raw.toolCallId.trim() : ""; - if (!toolCallId) { - return undefined; - } - const title = - typeof raw.title === "string" && raw.title.trim().length > 0 ? raw.title.trim() : undefined; - const command = extractToolCallCommand(raw.rawInput, title); - const textContent = extractTextContentFromToolCallContent(raw.content); - const normalizedTitle = - title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call" - ? title - : undefined; - const detail = command ?? normalizedTitle ?? textContent; - const data: Record = { toolCallId }; - if (typeof raw.kind === "string" && raw.kind.trim().length > 0) { - data.kind = raw.kind.trim(); - } - if (command) { - data.command = command; - } - if (raw.rawInput !== undefined) { - data.rawInput = raw.rawInput; - } - if (raw.rawOutput !== undefined) { - data.rawOutput = raw.rawOutput; - } - if (raw.content !== undefined) { - data.content = raw.content; - } - if (raw.locations !== undefined) { - data.locations = raw.locations; - } - const status = normalizeToolCallStatus(raw.status, options?.fallbackStatus); - return { - toolCallId, - itemType: toolLifecycleItemTypeFromKind(raw.kind), - ...(title ? { title } : {}), - ...(status ? { status } : {}), - ...(command ? { command } : {}), - ...(detail ? { detail } : {}), - data, - } satisfies AcpToolCallState; -} - -function mergeToolCallState( - previous: AcpToolCallState | undefined, - next: AcpToolCallState, -): AcpToolCallState { - const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined; - 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, - itemType: nextKind !== undefined ? next.itemType : (previous?.itemType ?? next.itemType), - ...(title ? { title } : {}), - ...(status ? { status } : {}), - ...(command ? { command } : {}), - ...(detail ? { detail } : {}), - data: { - ...previous?.data, - ...next.data, - }, - } satisfies AcpToolCallState; -} - -function parsePermissionRequest(params: unknown): { - requestType: "exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown"; - detail?: string; - toolCall?: AcpToolCallState; -} { - if (!isRecord(params)) { - return { requestType: "unknown" }; - } - const toolCall = parseToolCallState(params.toolCall, { fallbackStatus: "pending" }); - const requestType = requestTypeFromToolKind( - isRecord(params.toolCall) ? params.toolCall.kind : undefined, - ); - const detail = - toolCall?.command ?? - toolCall?.title ?? - toolCall?.detail ?? - (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined); - return { - requestType, - ...(detail ? { detail } : {}), - ...(toolCall ? { toolCall } : {}), - }; -} - -function parseSessionModeState(raw: unknown): AcpSessionModeState | undefined { - if (!isRecord(raw)) return undefined; - const modes = isRecord(raw.modes) ? raw.modes : raw; - const currentModeId = - typeof modes.currentModeId === "string" && modes.currentModeId.trim().length > 0 - ? modes.currentModeId.trim() - : undefined; - if (!currentModeId) { - return undefined; - } - const rawModes = modes.availableModes; - if (!Array.isArray(rawModes)) { - return undefined; - } - const availableModes = rawModes - .map((mode) => { - if (!isRecord(mode)) return undefined; - const id = typeof mode.id === "string" ? mode.id.trim() : ""; - const name = typeof mode.name === "string" ? mode.name.trim() : ""; - if (!id || !name) { - return undefined; - } - const description = - typeof mode.description === "string" && mode.description.trim().length > 0 - ? mode.description.trim() - : undefined; - return description !== undefined - ? ({ id, name, description } satisfies AcpSessionMode) - : ({ id, name } satisfies AcpSessionMode); - }) - .filter((mode): mode is AcpSessionMode => mode !== undefined); - if (availableModes.length === 0) { - return undefined; - } - return { - currentModeId, - availableModes, - }; -} - function normalizeModeSearchText(mode: AcpSessionMode): string { return [mode.id, mode.name, mode.description] .filter((value): value is string => typeof value === "string" && value.length > 0) @@ -515,172 +194,10 @@ function resolveRequestedModeId(input: { ); } -function updateSessionModeState( - modeState: AcpSessionModeState | undefined, - nextModeId: string, -): AcpSessionModeState | undefined { - if (!modeState) { - return undefined; - } - const normalizedModeId = nextModeId.trim(); - if (!normalizedModeId) { - return modeState; - } - return modeState.availableModes.some((mode) => mode.id === normalizedModeId) - ? { - ...modeState, - currentModeId: normalizedModeId, - } - : modeState; -} - -function isMethodNotFoundRpcError(error: AcpError): boolean { - return ( - Schema.is(AcpRpcError)(error) && - (error.code === -32601 || error.message.toLowerCase().includes("method not found")) - ); -} - -function parseSessionUpdate(params: unknown): { - sessionUpdate?: string; - text?: string; - modeId?: string; - plan?: { - explanation?: string | null; - plan: ReadonlyArray<{ step: string; status: "pending" | "inProgress" | "completed" }>; - }; - toolCall?: AcpToolCallState; -} { - if (!isRecord(params)) return {}; - const upd = params.update; - if (!isRecord(upd)) return {}; - const su = typeof upd.sessionUpdate === "string" ? upd.sessionUpdate : undefined; - const modeId = - typeof upd.modeId === "string" - ? upd.modeId - : typeof upd.currentModeId === "string" - ? upd.currentModeId - : undefined; - if (su === "plan") { - const entries = Array.isArray(upd.entries) ? upd.entries : undefined; - const plan = - entries - ?.map((entry, index) => { - if (!isRecord(entry)) { - return undefined; - } - const step = - typeof entry.content === "string" && entry.content.trim().length > 0 - ? entry.content.trim() - : `Step ${index + 1}`; - return { - step, - status: normalizePlanStepStatus(entry.status), - } as const; - }) - .filter( - ( - entry, - ): entry is { - step: string; - status: "pending" | "inProgress" | "completed"; - } => entry !== undefined, - ) ?? []; - if (plan.length > 0) { - const explanation = - typeof upd.explanation === "string" - ? upd.explanation - : upd.explanation === null - ? null - : undefined; - return { - sessionUpdate: su, - ...(modeId !== undefined ? { modeId } : {}), - plan: { - ...(explanation !== undefined ? { explanation } : {}), - plan, - }, - }; - } - } - if (su === "tool_call" || su === "tool_call_update") { - const toolCall = parseToolCallState( - upd, - su === "tool_call" ? { fallbackStatus: "pending" } : undefined, - ); - if (toolCall) { - return { - sessionUpdate: su, - ...(modeId !== undefined ? { modeId } : {}), - toolCall, - }; - } - } - const content = upd.content; - if (!isRecord(content)) { - return { - ...(su !== undefined ? { sessionUpdate: su } : {}), - ...(modeId !== undefined ? { modeId } : {}), - }; - } - const text = typeof content.text === "string" ? content.text : undefined; - if (su !== undefined && text !== undefined) { - return { - sessionUpdate: su, - text, - ...(modeId !== undefined ? { modeId } : {}), - }; - } - if (su !== undefined) { - return { - sessionUpdate: su, - ...(modeId !== undefined ? { modeId } : {}), - }; - } - if (text !== undefined) { - return { - text, - ...(modeId !== undefined ? { modeId } : {}), - }; - } - return {}; -} - -interface PendingApproval { - readonly decision: Deferred.Deferred; - readonly requestType: - | "exec_command_approval" - | "file_read_approval" - | "file_change_approval" - | "unknown"; -} - -interface PendingUserInput { - readonly answers: Deferred.Deferred; -} - -interface CursorSessionContext { - readonly threadId: ThreadId; - session: ProviderSession; - readonly child: ChildProcessWithoutNullStreams; - readonly conn: AcpJsonRpcConnection; - acpSessionId: string; - /** ACP configId for the model selector (discovered from session/new configOptions). */ - modelConfigId: string | undefined; - notificationFiber: Fiber.Fiber | undefined; - readonly pendingApprovals: Map; - readonly pendingUserInputs: Map; - readonly turns: Array<{ id: TurnId; items: Array }>; - readonly toolCalls: Map; - modeState: AcpSessionModeState | undefined; - lastPlanFingerprint: string | undefined; - activeTurnId: TurnId | undefined; - stopped: boolean; -} - function makeCursorAdapter(options?: CursorAdapterLiveOptions) { return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const serverConfig = yield* Effect.service(ServerConfig); const serverSettingsService = yield* ServerSettingsService; const nativeEventLogger = @@ -701,107 +218,6 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { const offerRuntimeEvent = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid); - const emitPlanUpdate = ( - ctx: CursorSessionContext, - payload: { - explanation?: string | null; - plan: ReadonlyArray<{ step: string; status: "pending" | "inProgress" | "completed" }>; - }, - rawPayload: unknown, - source: "acp.jsonrpc" | "acp.cursor.extension", - method: string, - ) => - Effect.gen(function* () { - const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${JSON.stringify(payload)}`; - if (ctx.lastPlanFingerprint === fingerprint) { - return; - } - ctx.lastPlanFingerprint = fingerprint; - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "turn.plan.updated", - ...stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - payload, - raw: { - source, - method, - payload: rawPayload, - }, - }); - }); - - const emitToolCallEvent = ( - ctx: CursorSessionContext, - toolCall: AcpToolCallState, - rawPayload: unknown, - ) => - Effect.gen(function* () { - const runtimeStatus = runtimeItemStatusFromToolCallStatus(toolCall.status); - const payload = { - itemType: toolCall.itemType, - ...(runtimeStatus ? { status: runtimeStatus } : {}), - ...(toolCall.title ? { title: toolCall.title } : {}), - ...(toolCall.detail ? { detail: toolCall.detail } : {}), - ...(Object.keys(toolCall.data).length > 0 ? { data: toolCall.data } : {}), - }; - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: - toolCall.status === "completed" || toolCall.status === "failed" - ? "item.completed" - : "item.updated", - ...stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - itemId: RuntimeItemId.makeUnsafe(toolCall.toolCallId), - payload, - raw: { - source: "acp.jsonrpc", - method: "session/update", - payload: rawPayload, - }, - }); - if (toolCall.status === "completed" || toolCall.status === "failed") { - ctx.toolCalls.delete(toolCall.toolCallId); - } - }); - - const setSessionMode = (ctx: CursorSessionContext, modeId: string | undefined) => - Effect.gen(function* () { - const normalizedModeId = modeId?.trim(); - if (!normalizedModeId) { - return; - } - if (ctx.modeState?.currentModeId === normalizedModeId) { - return; - } - const setModeParams = { sessionId: ctx.acpSessionId, modeId: normalizedModeId }; - const setModeExit = yield* Effect.exit(ctx.conn.request("session/set_mode", setModeParams)); - if (Exit.isSuccess(setModeExit)) { - ctx.modeState = updateSessionModeState(ctx.modeState, normalizedModeId); - return; - } - const error = Cause.squash(setModeExit.cause) as AcpError; - if (!isMethodNotFoundRpcError(error)) { - return yield* mapAcpToAdapterError(ctx.threadId, "session/set_mode", error); - } - yield* ctx.conn - .request("session/mode/set", { - sessionId: ctx.acpSessionId, - mode: normalizedModeId, - }) - .pipe( - Effect.mapError((cause) => - mapAcpToAdapterError(ctx.threadId, "session/mode/set", cause), - ), - ); - ctx.modeState = updateSessionModeState(ctx.modeState, normalizedModeId); - }); - const logNative = ( threadId: ThreadId, method: string, @@ -828,16 +244,46 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { ); }); + const emitPlanUpdate = ( + ctx: CursorSessionContext, + payload: { + readonly explanation?: string | null; + readonly plan: ReadonlyArray<{ + readonly step: string; + readonly status: "pending" | "inProgress" | "completed"; + }>; + }, + rawPayload: unknown, + source: "acp.jsonrpc" | "acp.cursor.extension", + method: string, + ) => + Effect.gen(function* () { + const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${JSON.stringify(payload)}`; + if (ctx.lastPlanFingerprint === fingerprint) { + return; + } + ctx.lastPlanFingerprint = fingerprint; + yield* offerRuntimeEvent( + makeAcpPlanUpdatedEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: ctx.threadId, + turnId: ctx.activeTurnId, + payload, + source, + method, + rawPayload, + }), + ); + }); + const requireSession = ( threadId: ThreadId, ): Effect.Effect => { const ctx = sessions.get(threadId); if (!ctx || ctx.stopped) { return Effect.fail( - new ProviderAdapterSessionNotFoundError({ - provider: PROVIDER, - threadId, - }), + new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }), ); } return Effect.succeed(ctx); @@ -850,12 +296,11 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { if (ctx.notificationFiber) { yield* Fiber.interrupt(ctx.notificationFiber); } - disposeAcpChild(ctx.child); + yield* Effect.ignore(ctx.acp.close); sessions.delete(ctx.threadId); - const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ type: "session.exited", - ...stamp, + ...(yield* makeEventStamp()), provider: PROVIDER, threadId: ctx.threadId, payload: { exitKind: "graceful" }, @@ -878,7 +323,15 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { issue: "cwd is required and must be non-empty.", }); } + const cwd = nodePath.resolve(input.cwd.trim()); + const cursorModelSelection = + input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined; + const existing = sessions.get(input.threadId); + if (existing && !existing.stopped) { + yield* stopSessionInternal(existing); + } + const spawnOptions = yield* serverSettingsService.getSettings.pipe( Effect.map((settings) => settings.providers.cursor), Effect.map((cursorSettings) => ({ @@ -899,279 +352,172 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { }), ), ); - const cursorModelSelection = - input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined; - const existing = sessions.get(input.threadId); - if (existing && !existing.stopped) { - yield* stopSessionInternal(existing); - } - const child = yield* spawnAcpChildProcess(spawnOptions).pipe( - Effect.mapError( - (e) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: e.message, - cause: e, - }), - ), - ); + const pendingApprovals = new Map(); + const pendingUserInputs = new Map(); + let ctx!: CursorSessionContext; - const conn = yield* attachAcpJsonRpcConnection(child).pipe( + const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId; + + const acp = yield* makeAcpSessionRuntime({ + spawn: spawnOptions, + cwd, + ...(resumeSessionId ? { resumeSessionId } : {}), + clientInfo: { name: "t3-code", version: "0.0.0" }, + authMethodId: "cursor_login", + handlers: { + extRequests: { + "cursor/ask_question": defineExtRequest(CursorAskQuestionRequest, (params) => + Effect.gen(function* () { + yield* logNative( + input.threadId, + "cursor/ask_question", + params, + "acp.cursor.extension", + ); + const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID()); + const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId); + const answers = yield* Deferred.make(); + pendingUserInputs.set(requestId, { answers }); + yield* offerRuntimeEvent({ + type: "user-input.requested", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + turnId: ctx?.activeTurnId, + requestId: runtimeRequestId, + payload: { questions: extractAskQuestions(params) }, + raw: { + source: "acp.cursor.extension", + method: "cursor/ask_question", + payload: params, + }, + }); + const resolved = yield* Deferred.await(answers); + pendingUserInputs.delete(requestId); + yield* offerRuntimeEvent({ + type: "user-input.resolved", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + turnId: ctx?.activeTurnId, + requestId: runtimeRequestId, + payload: { answers: resolved }, + }); + return { answers: resolved }; + }), + ), + "cursor/create_plan": defineExtRequest(CursorCreatePlanRequest, (params) => + Effect.gen(function* () { + yield* logNative( + input.threadId, + "cursor/create_plan", + params, + "acp.cursor.extension", + ); + yield* offerRuntimeEvent({ + type: "turn.proposed.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + turnId: ctx?.activeTurnId, + payload: { planMarkdown: extractPlanMarkdown(params) }, + raw: { + source: "acp.cursor.extension", + method: "cursor/create_plan", + payload: params, + }, + }); + return { accepted: true } as const; + }), + ), + "cursor/update_todos": defineExtRequest(CursorUpdateTodosRequest, (params) => + Effect.gen(function* () { + yield* logNative( + input.threadId, + "cursor/update_todos", + params, + "acp.cursor.extension", + ); + if (ctx) { + yield* emitPlanUpdate( + ctx, + extractTodosAsPlan(params), + params, + "acp.cursor.extension", + "cursor/update_todos", + ); + } + return {}; + }), + ), + }, + requestPermission: (params) => + Effect.gen(function* () { + yield* logNative( + input.threadId, + "session/request_permission", + params, + "acp.jsonrpc", + ); + const permissionRequest = parsePermissionRequest(params); + const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID()); + const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId); + const decision = yield* Deferred.make(); + pendingApprovals.set(requestId, { + decision, + requestType: permissionRequest.requestType, + }); + yield* offerRuntimeEvent( + makeAcpRequestOpenedEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: input.threadId, + turnId: ctx?.activeTurnId, + requestId: runtimeRequestId, + requestType: permissionRequest.requestType, + detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000), + args: params, + source: "acp.jsonrpc", + method: "session/request_permission", + rawPayload: params, + }), + ); + const resolved = yield* Deferred.await(decision); + pendingApprovals.delete(requestId); + yield* offerRuntimeEvent( + makeAcpRequestResolvedEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: input.threadId, + turnId: ctx?.activeTurnId, + requestId: runtimeRequestId, + requestType: permissionRequest.requestType, + decision: resolved, + }), + ); + return { + outcome: { + outcome: "selected" as const, + optionId: acpPermissionOutcome(resolved), + }, + }; + }).pipe(Effect.mapError(EffectAcpErrors.normalizeAcpError)), + }, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), Effect.mapError( (cause) => new ProviderAdapterProcessError({ provider: PROVIDER, threadId: input.threadId, - detail: "Failed to attach ACP JSON-RPC to child process.", + detail: cause.message, cause, }), ), ); - const ctx: CursorSessionContext = { - threadId: input.threadId, - session: {} as ProviderSession, - child, - conn, - acpSessionId: "", - modelConfigId: undefined, - notificationFiber: undefined, - pendingApprovals: new Map(), - pendingUserInputs: new Map(), - turns: [], - toolCalls: new Map(), - modeState: undefined, - lastPlanFingerprint: undefined, - activeTurnId: undefined, - stopped: false, - }; - - const registerHandlers = (ctx: CursorSessionContext) => - Effect.gen(function* () { - yield* conn.registerHandler("session/request_permission", (params, _acpId) => - Effect.gen(function* () { - yield* logNative(ctx.threadId, "session/request_permission", params, "acp.jsonrpc"); - const permissionRequest = parsePermissionRequest(params); - if (permissionRequest.toolCall) { - const previousToolCall = ctx.toolCalls.get(permissionRequest.toolCall.toolCallId); - ctx.toolCalls.set( - permissionRequest.toolCall.toolCallId, - mergeToolCallState(previousToolCall, permissionRequest.toolCall), - ); - } - const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID()); - const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId); - const decision = yield* Deferred.make(); - ctx.pendingApprovals.set(requestId, { - decision, - requestType: permissionRequest.requestType, - }); - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "request.opened", - ...stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - requestId: runtimeRequestId, - payload: { - requestType: permissionRequest.requestType, - ...(permissionRequest.detail - ? { detail: permissionRequest.detail } - : { detail: JSON.stringify(params).slice(0, 2000) }), - args: params, - }, - raw: { - source: "acp.jsonrpc", - method: "session/request_permission", - payload: params, - }, - }); - const d = yield* Deferred.await(decision); - ctx.pendingApprovals.delete(requestId); - const stamp2 = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "request.resolved", - ...stamp2, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - requestId: runtimeRequestId, - payload: { - requestType: permissionRequest.requestType, - decision: d, - }, - }); - return { - outcome: { outcome: "selected", optionId: acpPermissionOutcome(d) }, - }; - }), - ); - - yield* conn.registerHandler("cursor/ask_question", (params, _acpId) => - Effect.gen(function* () { - yield* logNative( - ctx.threadId, - "cursor/ask_question", - params, - "acp.cursor.extension", - ); - const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID()); - const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId); - const answers = yield* Deferred.make(); - ctx.pendingUserInputs.set(requestId, { answers }); - const questions = extractAskQuestions(params); - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "user-input.requested", - ...stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - requestId: runtimeRequestId, - payload: { questions }, - raw: { - source: "acp.cursor.extension", - method: "cursor/ask_question", - payload: params, - }, - }); - const a = yield* Deferred.await(answers); - ctx.pendingUserInputs.delete(requestId); - const stamp2 = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "user-input.resolved", - ...stamp2, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - requestId: runtimeRequestId, - payload: { answers: a }, - }); - return { answers: a }; - }), - ); - - yield* conn.registerHandler("cursor/create_plan", (params, _acpId) => - Effect.gen(function* () { - yield* logNative( - ctx.threadId, - "cursor/create_plan", - params, - "acp.cursor.extension", - ); - const planMarkdown = extractPlanMarkdown(params); - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "turn.proposed.completed", - ...stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - payload: { planMarkdown }, - raw: { - source: "acp.cursor.extension", - method: "cursor/create_plan", - payload: params, - }, - }); - return { accepted: true }; - }), - ); - - yield* conn.registerHandler("cursor/update_todos", (params, _acpId) => - Effect.gen(function* () { - yield* logNative( - ctx.threadId, - "cursor/update_todos", - params, - "acp.cursor.extension", - ); - const plan = extractTodosAsPlan(params); - yield* emitPlanUpdate( - ctx, - plan, - params, - "acp.cursor.extension", - "cursor/update_todos", - ); - return {}; - }), - ); - }); - - yield* registerHandlers(ctx); - - const init = yield* conn - .request("initialize", { - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { name: "t3-code", version: "0.0.0" }, - }) - .pipe(Effect.mapError((e) => mapAcpToAdapterError(input.threadId, "initialize", e))); - - yield* conn - .request("authenticate", { methodId: "cursor_login" }) - .pipe(Effect.mapError((e) => mapAcpToAdapterError(input.threadId, "authenticate", e))); - - const resume = parseCursorResume(input.resumeCursor); - let acpSessionId: string; - let sessionSetupResult: unknown = undefined; - if (resume) { - const loadExit = yield* Effect.exit( - conn.request("session/load", { - sessionId: resume.sessionId, - cwd, - mcpServers: [], - }), - ); - if (Exit.isSuccess(loadExit)) { - acpSessionId = resume.sessionId; - sessionSetupResult = loadExit.value; - } else { - const created = yield* conn - .request("session/new", { cwd, mcpServers: [] }) - .pipe(Effect.mapError((e) => mapAcpToAdapterError(input.threadId, "session/new", e))); - const cr = created as { sessionId?: string }; - if (typeof cr.sessionId !== "string") { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/new", - detail: "session/new missing sessionId", - cause: created, - }); - } - acpSessionId = cr.sessionId; - sessionSetupResult = created; - } - } else { - const created = yield* conn - .request("session/new", { cwd, mcpServers: [] }) - .pipe(Effect.mapError((e) => mapAcpToAdapterError(input.threadId, "session/new", e))); - const cr = created as { sessionId?: string }; - if (typeof cr.sessionId !== "string") { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/new", - detail: "session/new missing sessionId", - cause: created, - }); - } - acpSessionId = cr.sessionId; - sessionSetupResult = created; - } - const now = yield* nowIso; - const resumeCursor = { - schemaVersion: CURSOR_RESUME_VERSION, - sessionId: acpSessionId, - }; - const session: ProviderSession = { provider: PROVIDER, status: "ready", @@ -1179,75 +525,83 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { cwd, model: cursorModelSelection?.model, threadId: input.threadId, - resumeCursor, + resumeCursor: { + schemaVersion: CURSOR_RESUME_VERSION, + sessionId: acp.sessionId, + }, createdAt: now, updatedAt: now, }; - ctx.session = session; - ctx.acpSessionId = acpSessionId; - ctx.modelConfigId = extractModelConfigId(sessionSetupResult); - ctx.modeState = parseSessionModeState(sessionSetupResult); - - const handleNotification = (msg: AcpInboundMessage) => - Effect.gen(function* () { - if (msg._tag !== "notification" || msg.method !== "session/update") return; - yield* logNative(ctx.threadId, "session/update", msg.params, "acp.jsonrpc"); - const p = parseSessionUpdate(msg.params); - if (p.modeId) { - ctx.modeState = updateSessionModeState(ctx.modeState, p.modeId); - } - if (p.sessionUpdate === "plan" && p.plan) { - yield* emitPlanUpdate(ctx, p.plan, msg.params, "acp.jsonrpc", "session/update"); - } - if ( - (p.sessionUpdate === "tool_call" || p.sessionUpdate === "tool_call_update") && - p.toolCall - ) { - const previousToolCall = ctx.toolCalls.get(p.toolCall.toolCallId); - const mergedToolCall = mergeToolCallState(previousToolCall, p.toolCall); - ctx.toolCalls.set(mergedToolCall.toolCallId, mergedToolCall); - yield* emitToolCallEvent(ctx, mergedToolCall, msg.params); - } - if ( - (p.sessionUpdate === "agent_message_chunk" || - p.sessionUpdate === "assistant_message_chunk") && - p.text - ) { - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "content.delta", - ...stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - payload: { - streamKind: "assistant_text", - delta: p.text, - }, - raw: { - source: "acp.jsonrpc", - method: "session/update", - payload: msg.params, - }, - }); - } - }); + ctx = { + threadId: input.threadId, + session, + acp, + notificationFiber: undefined, + pendingApprovals, + pendingUserInputs, + turns: [], + lastPlanFingerprint: undefined, + activeTurnId: undefined, + stopped: false, + }; const nf = yield* Stream.runDrain( - Stream.mapEffect(conn.notifications, handleNotification), + Stream.mapEffect(acp.events, (event) => + Effect.gen(function* () { + switch (event._tag) { + case "ModeChanged": + return; + case "PlanUpdated": + yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc"); + yield* emitPlanUpdate( + ctx, + event.payload, + event.rawPayload, + "acp.jsonrpc", + "session/update", + ); + return; + case "ToolCallUpdated": + yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc"); + yield* offerRuntimeEvent( + makeAcpToolCallEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: ctx.threadId, + turnId: ctx.activeTurnId, + toolCall: event.toolCall, + rawPayload: event.rawPayload, + }), + ); + return; + case "ContentDelta": + yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc"); + yield* offerRuntimeEvent( + makeAcpContentDeltaEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: ctx.threadId, + turnId: ctx.activeTurnId, + text: event.text, + rawPayload: event.rawPayload, + }), + ); + return; + } + }), + ), ).pipe(Effect.forkChild); ctx.notificationFiber = nf; sessions.set(input.threadId, ctx); - const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ type: "session.started", - ...stamp, + ...(yield* makeEventStamp()), provider: PROVIDER, threadId: input.threadId, - payload: { resume: init }, + payload: { resume: acp.initializeResult }, }); yield* offerRuntimeEvent({ type: "session.state.changed", @@ -1261,25 +615,12 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { ...(yield* makeEventStamp()), provider: PROVIDER, threadId: input.threadId, - payload: { providerThreadId: acpSessionId }, + payload: { providerThreadId: acp.sessionId }, }); return session; }); - const setSessionModel = (ctx: CursorSessionContext, model: string) => - Effect.gen(function* () { - const configId = ctx.modelConfigId ?? "model"; - yield* ctx.conn - .request("session/set_config_option", { - sessionId: ctx.acpSessionId, - configId, - value: model, - }) - .pipe(Effect.ignore); - ctx.session = { ...ctx.session, model, updatedAt: yield* nowIso }; - }); - const sendTurn: CursorAdapterShape["sendTurn"] = (input) => Effect.gen(function* () { const ctx = yield* requireSession(input.threadId); @@ -1291,10 +632,15 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { turnModelSelection?.options, ); - yield* setSessionModel(ctx, model); + yield* ctx.acp + .setModel(model) + .pipe( + Effect.mapError((error) => + mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_config_option", error), + ), + ); ctx.activeTurnId = turnId; ctx.lastPlanFingerprint = undefined; - ctx.toolCalls.clear(); ctx.session = { ...ctx.session, activeTurnId: turnId, @@ -1304,21 +650,30 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { const requestedModeId = resolveRequestedModeId({ interactionMode: input.interactionMode, runtimeMode: ctx.session.runtimeMode, - modeState: ctx.modeState, + modeState: yield* ctx.acp.getModeState, }); - yield* Effect.ignore(setSessionMode(ctx, requestedModeId)); + if (requestedModeId) { + yield* Effect.ignore( + ctx.acp + .setMode(requestedModeId) + .pipe( + Effect.mapError((error) => + mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_mode", error), + ), + ), + ); + } - const stampStart = yield* makeEventStamp(); yield* offerRuntimeEvent({ type: "turn.started", - ...stampStart, + ...(yield* makeEventStamp()), provider: PROVIDER, threadId: input.threadId, turnId, payload: { model }, }); - const promptParts: Array> = []; + const promptParts: Array = []; if (input.input?.trim()) { promptParts.push({ type: "text", text: input.input.trim() }); } @@ -1348,10 +703,8 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { ); promptParts.push({ type: "image", - image: { - data: Buffer.from(bytes).toString("base64"), - mimeType: attachment.mimeType, - }, + data: Buffer.from(bytes).toString("base64"), + mimeType: attachment.mimeType, }); } } @@ -1364,12 +717,15 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { }); } - const result = yield* ctx.conn - .request("session/prompt", { - sessionId: ctx.acpSessionId, + const result = yield* ctx.acp + .prompt({ prompt: promptParts, }) - .pipe(Effect.mapError((e) => mapAcpToAdapterError(input.threadId, "session/prompt", e))); + .pipe( + Effect.mapError((error) => + mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), + ), + ); ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); ctx.session = { @@ -1379,17 +735,15 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { model, }; - const pr = result as { stopReason?: string | null }; - const stampEnd = yield* makeEventStamp(); yield* offerRuntimeEvent({ type: "turn.completed", - ...stampEnd, + ...(yield* makeEventStamp()), provider: PROVIDER, threadId: input.threadId, turnId, payload: { state: "completed", - stopReason: pr.stopReason ?? null, + stopReason: result.stopReason ?? null, }, }); @@ -1403,7 +757,13 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) => Effect.gen(function* () { const ctx = yield* requireSession(threadId); - yield* Effect.ignore(ctx.conn.request("session/cancel", { sessionId: ctx.acpSessionId })); + yield* Effect.ignore( + ctx.acp.cancel.pipe( + Effect.mapError((error) => + mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error), + ), + ), + ); }); const respondToRequest: CursorAdapterShape["respondToRequest"] = ( @@ -1445,10 +805,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { const readThread: CursorAdapterShape["readThread"] = (threadId) => Effect.gen(function* () { const ctx = yield* requireSession(threadId); - return { - threadId, - turns: ctx.turns, - }; + return { threadId, turns: ctx.turns }; }); const rollbackThread: CursorAdapterShape["rollbackThread"] = (threadId, numTurns) => @@ -1509,77 +866,6 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { }); } -function extractAskQuestions(params: unknown): ReadonlyArray { - if (!isRecord(params)) return []; - const qs = params.questions ?? params.question; - if (!Array.isArray(qs)) return []; - const out: UserInputQuestion[] = []; - for (const q of qs) { - if (!isRecord(q)) continue; - const id = typeof q.id === "string" ? q.id : "question"; - const header = typeof q.header === "string" ? q.header : "Question"; - const question = typeof q.question === "string" ? q.question : ""; - const rawOpts = q.options; - const options: Array<{ label: string; description: string }> = []; - if (Array.isArray(rawOpts)) { - for (const o of rawOpts) { - if (!isRecord(o)) continue; - const label = typeof o.label === "string" ? o.label : "Option"; - const description = typeof o.description === "string" ? o.description : label; - options.push({ label, description }); - } - } - if (options.length === 0) { - options.push({ label: "OK", description: "Continue" }); - } - out.push({ id, header, question, options }); - } - return out.length > 0 - ? out - : [{ id: "q1", header: "Input", question: "?", options: [{ label: "OK", description: "OK" }] }]; -} - -function extractPlanMarkdown(params: unknown): string { - if (!isRecord(params)) return ""; - const pm = - typeof params.plan === "string" - ? params.plan - : typeof params.planMarkdown === "string" - ? params.planMarkdown - : typeof params.markdown === "string" - ? params.markdown - : ""; - return pm || "# Plan\n\n(Cursor did not supply plan text.)"; -} - -function extractTodosAsPlan(params: unknown): { - explanation?: string; - plan: ReadonlyArray<{ step: string; status: "pending" | "inProgress" | "completed" }>; -} { - if (!isRecord(params)) { - return { plan: [] }; - } - const todos = params.todos ?? params.items; - if (!Array.isArray(todos)) { - return { plan: [] }; - } - const plan = todos.map((t, i) => { - if (!isRecord(t)) { - return { step: `Step ${i + 1}`, status: "pending" as const }; - } - const step = - typeof t.content === "string" - ? t.content - : typeof t.title === "string" - ? t.title - : `Step ${i + 1}`; - const st = t.status; - const status = normalizePlanStepStatus(st); - return { step, status }; - }); - return { plan }; -} - export const CursorAdapterLive = Layer.effect(CursorAdapter, makeCursorAdapter()); export function makeCursorAdapterLive(opts?: CursorAdapterLiveOptions) { diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index ad221f7a51..f65cab55ff 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -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: user@example.com\n", + stderr: "", + code: 0, + }; + } throw new Error(`Unexpected args: ${joined}`); }), ), diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts index 7457713e0a..b6c9aec770 100644 --- a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts +++ b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts @@ -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", + }, + }); }); }); diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.ts b/apps/server/src/provider/acp/AcpAdapterSupport.ts index 914bb7e8c3..7f5664a8a6 100644 --- a/apps/server/src/provider/acp/AcpAdapterSupport.ts +++ b/apps/server/src/provider/acp/AcpAdapterSupport.ts @@ -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, + }, + }; +} diff --git a/apps/server/src/provider/acp/AcpErrors.ts b/apps/server/src/provider/acp/AcpErrors.ts deleted file mode 100644 index edbc10677d..0000000000 --- a/apps/server/src/provider/acp/AcpErrors.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Schema } from "effect"; - -export class AcpSpawnError extends Schema.TaggedErrorClass()("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", { - 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", { - 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", - { - 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; diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index a5e630686e..cba58bb2eb 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -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)), ); }); diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.ts deleted file mode 100644 index bb73a26f49..0000000000 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.ts +++ /dev/null @@ -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 { - 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; - readonly notify: (method: string, params?: unknown) => Effect.Effect; - readonly registerHandler: ( - method: string, - handler: AcpServerRequestHandler, - ) => Effect.Effect; - readonly notifications: Stream.Stream; -} - -export function spawnAcpChildProcess( - input: AcpSpawnInput, -): Effect.Effect { - 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 => - Effect.gen(function* () { - const writeLock = yield* Semaphore.make(1); - const pending = yield* Ref.make( - new Map>(), - ); - const handlers = yield* Ref.make(new Map()); - const nextId = yield* Ref.make(1); - const notificationQueue = yield* Queue.unbounded(); - - 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) => - Effect.try({ - try: () => { - child.stdin.write(`${JSON.stringify(payload)}\n`); - }, - catch: (cause) => - new AcpSpawnError({ - cause, - }), - }); - - const writeSerialized = (payload: Record) => - writeLock.withPermits(1)(writeRawLine(payload)); - - const sendRequest = (method: string, params?: unknown) => - Effect.gen(function* () { - const deferred = yield* Deferred.make(); - 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 => - 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 => - Effect.acquireRelease(spawnAcpChildProcess(input), (child) => - Effect.sync(() => disposeAcpChild(child)), - ).pipe(Effect.flatMap(attachAcpJsonRpcConnection)); diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts b/apps/server/src/provider/acp/AcpRuntimeModel.test.ts index ae12d3112a..c7a5d2e0d6 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.test.ts @@ -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", }, diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index ffd214a5bf..73720df7e7 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -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 { 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 | 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 { - 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 = { 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": { diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index d32e70cb4c..d054009332 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -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; - readonly protocolLogging?: { - readonly logIncoming?: boolean; - readonly logOutgoing?: boolean; - readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect; - }; + readonly authMethodId?: string; + readonly handlers?: Omit; } -export interface AcpSessionRequestLogEvent { - readonly method: string; - readonly payload: unknown; - readonly status: "started" | "succeeded" | "failed"; - readonly result?: unknown; - readonly cause?: Cause.Cause; -} - -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; - readonly getEvents: () => Stream.Stream; + readonly events: Stream.Stream; readonly getModeState: Effect.Effect; - readonly getConfigOptions: Effect.Effect>; readonly prompt: ( payload: Omit, ) => Effect.Effect; @@ -100,89 +63,22 @@ export interface AcpSessionRuntimeShape { method: string, payload: unknown, ) => Effect.Effect; + readonly close: Effect.Effect; } -interface AcpStartedState extends AcpSessionRuntimeStartResult {} - -type AcpStartState = - | { readonly _tag: "NotStarted" } - | { - readonly _tag: "Starting"; - readonly deferred: Deferred.Deferred; - } - | { readonly _tag: "Started"; readonly result: AcpStartedState }; - -interface AcpAssistantSegmentState { - readonly nextSegmentIndex: number; - readonly activeItemId?: string; -} - -interface EnsureActiveAssistantSegmentResult { - readonly itemId: string; - readonly startedEvent?: Extract; -} - -export class AcpSessionRuntime extends Context.Service()( - "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(); const modeStateRef = yield* Ref.make(undefined); const toolCallsRef = yield* Ref.make(new Map()); - const assistantSegmentRef = yield* Ref.make({ nextSegmentIndex: 0 }); - const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined)); - const startStateRef = yield* Ref.make({ _tag: "NotStarted" }); - - const logRequest = (event: AcpSessionRequestLogEvent) => - options.requestLogger ? options.requestLogger(event) : Effect.void; - - const runLoggedRequest = ( - method: string, - payload: unknown, - effect: Effect.Effect, - ): Effect.Effect => - 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; + }).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 => - 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 => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response)); - - const updateCurrentModeId = (modeId: string): Effect.Effect => - Ref.update(modeStateRef, (current) => - current ? { ...current, currentModeId: modeId } : current, - ); - - const setConfigOption = ( - configId: string, - value: string | boolean, - ): Effect.Effect => - 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 | null; - } - | undefined, -): ReadonlyArray { - 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; readonly modeStateRef: Ref.Ref; readonly toolCallsRef: Ref.Ref>; - readonly assistantSegmentRef: Ref.Ref; readonly params: EffectAcpSchema.SessionNotification; -}): Effect.Effect => +}): Effect.Effect => 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; - readonly assistantSegmentRef: Ref.Ref; - readonly sessionId: string; -}) => - Ref.modify( - 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, - }, - { - 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; - readonly assistantSegmentRef: Ref.Ref; -}) => - 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))); diff --git a/apps/server/src/provider/acp/AcpTypes.ts b/apps/server/src/provider/acp/AcpTypes.ts deleted file mode 100644 index 6917c70bc4..0000000000 --- a/apps/server/src/provider/acp/AcpTypes.ts +++ /dev/null @@ -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; - readonly cwd?: string; - /** Merged with `process.env` for the child. */ - readonly env?: Readonly>; -} - -export type AcpServerRequestHandler = ( - params: unknown, - requestId: number | string, -) => Effect.Effect; diff --git a/apps/server/src/provider/acp/CursorAcpCliProbe.test.ts b/apps/server/src/provider/acp/CursorAcpCliProbe.test.ts index deb86f99c0..d577fc56cb 100644 --- a/apps/server/src/provider/acp/CursorAcpCliProbe.test.ts +++ b/apps/server/src/provider/acp/CursorAcpCliProbe.test.ts @@ -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 { - 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; - 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; - 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; - 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)), ); }); diff --git a/apps/server/src/provider/acp/CursorAcpExtension.test.ts b/apps/server/src/provider/acp/CursorAcpExtension.test.ts index 91d50c4a9b..331c389a5c 100644 --- a/apps/server/src/provider/acp/CursorAcpExtension.test.ts +++ b/apps/server/src/provider/acp/CursorAcpExtension.test.ts @@ -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" }, ], }); }); diff --git a/apps/server/src/provider/acp/CursorAcpExtension.ts b/apps/server/src/provider/acp/CursorAcpExtension.ts index dff65535c9..abc78a1c8a 100644 --- a/apps/server/src/provider/acp/CursorAcpExtension.ts +++ b/apps/server/src/provider/acp/CursorAcpExtension.ts @@ -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 }; } diff --git a/apps/server/src/serverLayers.ts b/apps/server/src/serverLayers.ts index d5e3024fd5..f2d518e52f 100644 --- a/apps/server/src/serverLayers.ts +++ b/apps/server/src/serverLayers.ts @@ -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), diff --git a/bun.lock b/bun.lock index a78655c81f..afa2fb786b 100644 --- a/bun.lock +++ b/bun.lock @@ -55,6 +55,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", }, @@ -199,9 +200,9 @@ }, }, }, - "trustedDependencies": [ - "node-pty", - ], + "patchedDependencies": { + "effect@4.0.0-beta.41": "patches/effect@4.0.0-beta.41.patch", + }, "overrides": { "@effect/atom-react": "catalog:", "@effect/platform-bun": "catalog:", @@ -214,13 +215,13 @@ }, "catalog": { "@effect/language-service": "0.75.1", - "@effect/openapi-generator": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b", - "@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", - "@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", - "@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", + "@effect/openapi-generator": "4.0.0-beta.41", + "@effect/platform-node": "4.0.0-beta.41", + "@effect/sql-sqlite-bun": "4.0.0-beta.41", + "@effect/vitest": "4.0.0-beta.41", "@types/bun": "^1.3.9", "@types/node": "^24.10.13", - "effect": "4.0.0-beta.45", + "effect": "4.0.0-beta.41", "tsdown": "^0.20.3", "typescript": "^5.7.3", "vitest": "^4.0.0", @@ -310,21 +311,15 @@ "@effect/atom-react": ["@effect/atom-react@4.0.0-beta.45", "", { "peerDependencies": { "effect": "^4.0.0-beta.45", "react": "^19.2.4", "scheduler": "*" } }, "sha512-jCoiae9UNeis9Yoal1p5V/P4eJK9nX89wORom7X5LpR2Ok920SZJc8dIeYkRXRAp9BCYJ/yWcO8gGLf7do71vg=="], - "@effect/openapi-generator": ["@effect/openapi-generator@https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.25", "effect": "^4.0.0-beta.25" }, "bin": { "openapigen": "./dist/bin.js" } }], + "@effect/openapi-generator": ["@effect/openapi-generator@4.0.0-beta.41", "", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.41", "effect": "^4.0.0-beta.41" }, "bin": { "openapigen": "dist/bin.js" } }, "sha512-7eTTSCFjSyCMaG76fl0YiFEjfdTWaUiTS2mJ4RM0Q7jUfrYyw3rwosPqVJ8N9zWmZSnoUyD+qAD/ZK8hW970hw=="], - "@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25", "ioredis": "^5.7.0" } }], + "@effect/platform-node": ["@effect/platform-node@4.0.0-beta.41", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.41", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41", "ioredis": "^5.7.0" } }, "sha512-lgsWfvJfxwg7xXT5rK3xcPyAFPAYXXJ0u/6yCu2suOMhdR5w2W6oA2L2pIQaqap8qR8uEVB5pHq6dqVfdRP7Nw=="], - "@effect/openapi-generator": ["@effect/openapi-generator@4.0.0-beta.45", "", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.45", "effect": "^4.0.0-beta.45" }, "bin": { "openapigen": "dist/bin.js" } }, "sha512-zT1UPzapV6mZebMuYhoDPQj/FKNn4R+oDgz1hEcQwazal4+lVDyEYGhRl0PgZroy6CP78fAOWNgW7TriGqSlOQ=="], + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.41", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41" } }, "sha512-YzKWz1G8YofCrQ0Thxymlk71CM3q7R1vzO2vtnb7KSHkTJrvrQB8FbZaM8mEddYOoamR25f46lidFKErmmotKg=="], - "@effect/platform-bun": ["@effect/platform-bun@4.0.0-beta.45", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.45" }, "peerDependencies": { "effect": "^4.0.0-beta.45" } }, "sha512-dZsbkJ+o4JfKE1OIAlMq8YWhmEfXxtTYennYADK/M/XlOtkFLsc2jkZppDvMznVni6JpFxWc7wd5rUf8jBVP5g=="], + "@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.41", "", { "peerDependencies": { "effect": "^4.0.0-beta.41" } }, "sha512-z3OvuTKE7GYIMZefKrTHNNuPaXxVpcSZmEAJd8ITap8wHVEEBs4WT+p/CHDae4dlJc6HJeWGSHxQuPVmdC16bA=="], - "@effect/platform-node": ["@effect/platform-node@4.0.0-beta.45", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.45", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.45", "ioredis": "^5.7.0" } }, "sha512-P07NMG4eoy62iLX9szak0hkr7hrwgq5+XMkm7URVug/3zqfZVxEG2kxn9JzVK1lF5WbaVrEKwjt3IkEJxzSPtg=="], - - "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.45", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.45" } }, "sha512-0T4RG18o+aCVUSlmPxA7uAjHJkyE3MS/uRrR5kCNSZQNG3X71wdIbu82wE/MnV6+6YSSPDx/6TVdZWYkJF0JWw=="], - - "@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.45", "", { "peerDependencies": { "effect": "^4.0.0-beta.45" } }, "sha512-sJBBztwI4YxjdjhdyjWelh3KKoZucmmZS2ONeNDIzYgqFlsrwEEUrhVkWf5ch9Io+kUUzeb6q7/SedFoLUWO7g=="], - - "@effect/vitest": ["@effect/vitest@4.0.0-beta.45", "", { "peerDependencies": { "effect": "^4.0.0-beta.45", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-38JA5Z6c2FoEhpVKbl7rjTrMU8Al5T30Kwtb6N3B9kOkyr2SsmvNsP9T65bh03IBh3ak9U//acrkmjS3hLQwKA=="], + "@effect/vitest": ["@effect/vitest@4.0.0-beta.41", "", { "peerDependencies": { "effect": "^4.0.0-beta.41", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-VCwK2Sj1gbCaC7eoipS/pmty1plN08nNKF6z0sn9S3q+6OLCbeJ3+2qKzFQCnpdkvud45HNK3Z9kVCZew6kKhA=="], "@electron/get": ["@electron/get@2.0.3", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="], @@ -1076,11 +1071,7 @@ "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], - "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], - - "effect": ["effect@4.0.0-beta.45", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-vvNrUWqnzBIW1hRMa+zw0CLRW6HLgdu7hQ6K7PT/rS+UY/73Ma11O+Oi9oc9zwL8KcN37M47UDseAdlF0bGNWw=="], - - "effect-acp": ["effect-acp@workspace:packages/effect-acp"], + "effect": ["effect@4.0.0-beta.41", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-kBjbmo2qqXbOgrvZcPgVdgsOOWcGPYwRcvGO3aGPWJhpXxDFNfgtwqtU6asMq2M7LSFRx1SA+3BzJm7FDqtxew=="], "effect-acp": ["effect-acp@workspace:packages/effect-acp"], @@ -2054,18 +2045,6 @@ "@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], - "@effect/openapi-generator/@effect/platform-node": ["@effect/platform-node@4.0.0-beta.41", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.41", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41", "ioredis": "^5.7.0" } }, "sha512-lgsWfvJfxwg7xXT5rK3xcPyAFPAYXXJ0u/6yCu2suOMhdR5w2W6oA2L2pIQaqap8qR8uEVB5pHq6dqVfdRP7Nw=="], - - "@effect/openapi-generator/effect": ["effect@4.0.0-beta.41", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-kBjbmo2qqXbOgrvZcPgVdgsOOWcGPYwRcvGO3aGPWJhpXxDFNfgtwqtU6asMq2M7LSFRx1SA+3BzJm7FDqtxew=="], - - "@effect/platform-node/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - - "@effect/platform-node-shared/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - - "@effect/sql-sqlite-bun/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - - "@effect/vitest/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - "@electron/get/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], "@electron/get/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -2160,8 +2139,6 @@ "@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0-rc.2", "", {}, "sha512-noLx87RwlBEMrTzncWd/FvTxoJ9+ycHNg0n8yyYydIoDsLZuxknKgWRJUqcrVkNrJ74uGyhWQzQaS3q8xfGAhQ=="], - "@effect/openapi-generator/@effect/platform-node/@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.41", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41" } }, "sha512-YzKWz1G8YofCrQ0Thxymlk71CM3q7R1vzO2vtnb7KSHkTJrvrQB8FbZaM8mEddYOoamR25f46lidFKErmmotKg=="], - "@electron/get/fs-extra/jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="], "@electron/get/fs-extra/universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="], diff --git a/package.json b/package.json index f3d56efaf4..5f3d2a2966 100644 --- a/package.json +++ b/package.json @@ -8,11 +8,11 @@ "scripts" ], "catalog": { - "effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", - "@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", - "@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", - "@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", - "@effect/openapi-generator": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b", + "effect": "4.0.0-beta.41", + "@effect/platform-node": "4.0.0-beta.41", + "@effect/sql-sqlite-bun": "4.0.0-beta.41", + "@effect/vitest": "4.0.0-beta.41", + "@effect/openapi-generator": "4.0.0-beta.41", "@effect/language-service": "0.75.1", "@types/bun": "^1.3.9", "@types/node": "^24.10.13", @@ -81,7 +81,7 @@ "apps/web/public" ] }, - "trustedDependencies": [ - "node-pty" - ] + "patchedDependencies": { + "effect@4.0.0-beta.41": "patches/effect@4.0.0-beta.41.patch" + } } diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index be0ccd3bb0..582f8671ce 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -18,15 +18,15 @@ import { ProviderKind } from "./orchestration.ts"; const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown); -const RuntimeEventRawSource = Schema.Literals([ - "codex.app-server.notification", - "codex.app-server.request", - "codex.eventmsg", - "claude.sdk.message", - "claude.sdk.permission", - "codex.sdk.thread-event", - "acp.jsonrpc", - "acp.cursor.extension", +const RuntimeEventRawSource = Schema.Union([ + Schema.Literal("codex.app-server.notification"), + Schema.Literal("codex.app-server.request"), + Schema.Literal("codex.eventmsg"), + Schema.Literal("claude.sdk.message"), + Schema.Literal("claude.sdk.permission"), + Schema.Literal("codex.sdk.thread-event"), + Schema.Literal("acp.jsonrpc"), + Schema.TemplateLiteral(["acp.", Schema.String, ".extension"]), ]); export type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type; diff --git a/packages/effect-acp/package.json b/packages/effect-acp/package.json index c059c57cc3..117c358a2d 100644 --- a/packages/effect-acp/package.json +++ b/packages/effect-acp/package.json @@ -4,74 +4,36 @@ "type": "module", "exports": { "./client": { - "import": { - "types": "./src/client.d.mts", - "default": "./src/client.mjs" - }, - "require": { - "types": "./src/client.d.cts", - "default": "./src/client.cjs" - } + "types": "./src/client.ts", + "import": "./src/client.ts" }, "./server": { - "import": { - "types": "./src/server.d.mts", - "default": "./src/server.mjs" - }, - "require": { - "types": "./src/server.d.cts", - "default": "./src/server.cjs" - } + "types": "./src/server.ts", + "import": "./src/server.ts" }, "./schema": { - "import": { - "types": "./src/_generated/schema.gen.d.mts", - "default": "./src/_generated/schema.gen.mjs" - }, - "require": { - "types": "./src/_generated/schema.gen.d.cts", - "default": "./src/_generated/schema.gen.cjs" - } + "types": "./src/schema.ts", + "import": "./src/schema.ts" }, "./rpc": { - "import": { - "types": "./src/rpc.d.mts", - "default": "./src/rpc.mjs" - }, - "require": { - "types": "./src/rpc.d.cts", - "default": "./src/rpc.cjs" - } + "types": "./src/rpc.ts", + "import": "./src/rpc.ts" }, "./protocol": { - "import": { - "types": "./src/protocol.d.mts", - "default": "./src/protocol.mjs" - }, - "require": { - "types": "./src/protocol.d.cts", - "default": "./src/protocol.cjs" - } + "types": "./src/protocol.ts", + "import": "./src/protocol.ts" }, "./terminal": { - "import": { - "types": "./src/terminal.d.mts", - "default": "./src/terminal.mts" - }, - "require": { - "types": "./src/terminal.d.cts", - "default": "./src/terminal.cjs" - } + "types": "./src/terminal.ts", + "import": "./src/terminal.ts" }, "./child-process": { - "import": { - "types": "./src/child-process.d.mts", - "default": "./src/child-process.mts" - }, - "require": { - "types": "./src/child-process.d.cts", - "default": "./src/child-process.cjs" - } + "types": "./src/child-process.ts", + "import": "./src/child-process.ts" + }, + "./errors": { + "types": "./src/errors.ts", + "import": "./src/errors.ts" } }, "scripts": { diff --git a/packages/effect-acp/src/_generated/schema.gen.ts b/packages/effect-acp/src/_generated/schema.gen.ts index 3a86373fff..e77163a929 100644 --- a/packages/effect-acp/src/_generated/schema.gen.ts +++ b/packages/effect-acp/src/_generated/schema.gen.ts @@ -481,6 +481,17 @@ export const SessionCloseCapabilities = Schema.Struct({ "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nCapabilities for the `session/close` method.\n\nBy supplying `{}` it means that the agent supports closing of sessions.", }); +export type SessionConfigOptionCategory = "mode" | "model" | "thought_level" | string; +export const SessionConfigOptionCategory = Schema.Union([ + Schema.Literal("mode").annotate({ description: "Session mode selector." }), + Schema.Literal("model").annotate({ description: "Model selector." }), + Schema.Literal("thought_level").annotate({ description: "Thought/reasoning level selector." }), + Schema.String.annotate({ title: "other", description: "Unknown / uncategorized selector." }), +]).annotate({ + description: + "Semantic category for a session configuration option.\n\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\ncategories gracefully.\n\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\nCategory names that do not begin with `_` are reserved for the ACP spec.", +}); + export type SessionConfigSelectOption = { readonly _meta?: { readonly [x: string]: unknown } | null; readonly description?: string | null; @@ -1800,40 +1811,97 @@ export type SessionConfigOption = readonly options: | ReadonlyArray | ReadonlyArray; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly category?: SessionConfigOptionCategory | null; + readonly description?: string | null; + readonly id: string; + readonly name: string; } - | { readonly type: "boolean"; readonly currentValue: boolean }; -export const SessionConfigOption = Schema.Union( - [ - Schema.Struct({ - type: Schema.Literal("select"), - currentValue: Schema.String.annotate({ - description: "Unique identifier for a session configuration option value.", - }), - options: Schema.Union([ - Schema.Array(SessionConfigSelectOption).annotate({ - title: "Ungrouped", - description: "A flat list of options with no grouping.", - }), - Schema.Array(SessionConfigSelectGroup).annotate({ - title: "Grouped", - description: "A list of options grouped under headers.", - }), - ]).annotate({ description: "Possible values for a session configuration option." }), - }).annotate({ - description: "A single-value selector (dropdown) session configuration option payload.", + | { + readonly type: "boolean"; + readonly currentValue: boolean; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly category?: SessionConfigOptionCategory | null; + readonly description?: string | null; + readonly id: string; + readonly name: string; + }; +export const SessionConfigOption = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("select"), + currentValue: Schema.String.annotate({ + description: "Unique identifier for a session configuration option value.", }), - Schema.Struct({ - type: Schema.Literal("boolean"), - currentValue: Schema.Boolean.annotate({ - description: "The current value of the boolean option.", + options: Schema.Union([ + Schema.Array(SessionConfigSelectOption).annotate({ + title: "Ungrouped", + description: "A flat list of options with no grouping.", }), - }).annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nA boolean on/off toggle session configuration option payload.", + Schema.Array(SessionConfigSelectGroup).annotate({ + title: "Grouped", + description: "A list of options grouped under headers.", + }), + ]).annotate({ description: "Possible values for a session configuration option." }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + category: Schema.optionalKey( + Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({ + description: "Optional semantic category for this option (UX only).", + }), + ), + description: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional description for the Client to display to the user.", + }), + Schema.Null, + ]), + ), + id: Schema.String.annotate({ + description: "Unique identifier for a session configuration option.", }), - ], - { mode: "oneOf" }, -).annotate({ description: "A session configuration option selector and its current state." }); + name: Schema.String.annotate({ description: "Human-readable label for the option." }), + }).annotate({ description: "A session configuration option selector and its current state." }), + Schema.Struct({ + type: Schema.Literal("boolean"), + currentValue: Schema.Boolean.annotate({ + description: "The current value of the boolean option.", + }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + category: Schema.optionalKey( + Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({ + description: "Optional semantic category for this option (UX only).", + }), + ), + description: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional description for the Client to display to the user.", + }), + Schema.Null, + ]), + ), + id: Schema.String.annotate({ + description: "Unique identifier for a session configuration option.", + }), + name: Schema.String.annotate({ description: "Human-readable label for the option." }), + }).annotate({ description: "A session configuration option selector and its current state." }), +]); export type SessionModeState = { readonly _meta?: { readonly [x: string]: unknown } | null; @@ -3005,8 +3073,18 @@ export type AgentRequest = { readonly title?: string | null; readonly type?: "object"; }; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly message: string; + readonly sessionId: string; + } + | { + readonly mode: "url"; + readonly elicitationId: string; + readonly url: string; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly message: string; + readonly sessionId: string; } - | { readonly mode: "url"; readonly elicitationId: string; readonly url: string } | unknown | null; }; @@ -3285,73 +3363,102 @@ export const AgentRequest = Schema.Struct({ title: "KillTerminalRequest", description: "Request to kill a terminal without releasing it.", }), - Schema.Union( - [ - Schema.Struct({ - mode: Schema.Literal("form"), - requestedSchema: Schema.Struct({ - description: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: "Optional description of what this schema represents.", - }), - Schema.Null, - ]), - ), - properties: Schema.optionalKey( - Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ - description: "Property definitions (must be primitive types).", - default: {}, + Schema.Union([ + Schema.Struct({ + mode: Schema.Literal("form"), + requestedSchema: Schema.Struct({ + description: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional description of what this schema represents.", }), - ), - required: Schema.optionalKey( - Schema.Union([ - Schema.Array(Schema.String).annotate({ - description: "List of required property names.", - }), - Schema.Null, - ]), - ), - title: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ description: "Optional title for the schema." }), - Schema.Null, - ]), - ), - type: Schema.optionalKey( - Schema.Literal("object").annotate({ - description: "Type discriminator for elicitation schemas.", - default: "object", + Schema.Null, + ]), + ), + properties: Schema.optionalKey( + Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ + description: "Property definitions (must be primitive types).", + default: {}, + }), + ), + required: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "List of required property names.", }), - ), - }).annotate({ - description: - "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", - }), + Schema.Null, + ]), + ), + title: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional title for the schema." }), + Schema.Null, + ]), + ), + type: Schema.optionalKey( + Schema.Literal("object").annotate({ + description: "Type discriminator for elicitation schemas.", + default: "object", + }), + ), }).annotate({ description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nForm-based elicitation mode where the client renders a form from the provided schema.", + "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", }), - Schema.Struct({ - mode: Schema.Literal("url"), - elicitationId: Schema.String.annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", - }), - url: Schema.String.annotate({ - description: "The URL to direct the user to.", - format: "uri", - }), - }).annotate({ + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + message: Schema.String.annotate({ + description: "A human-readable message describing what input is needed.", + }), + sessionId: Schema.String.annotate({ description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nURL-based elicitation mode where the client directs the user to a URL.", + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", }), - ], - { mode: "oneOf" }, - ).annotate({ + }).annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", + }), + Schema.Struct({ + mode: Schema.Literal("url"), + elicitationId: Schema.String.annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", + }), + url: Schema.String.annotate({ + description: "The URL to direct the user to.", + format: "uri", + }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + message: Schema.String.annotate({ + description: "A human-readable message describing what input is needed.", + }), + sessionId: Schema.String.annotate({ + description: + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + }), + }).annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", + }), + ]).annotate({ title: "ElicitationRequest", description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequests structured user input via a form or URL.", }), Schema.Unknown.annotate({ title: "ExtMethodRequest", @@ -4490,8 +4597,19 @@ export type ClientRequest = { readonly modeId: string; readonly sessionId: string; } - | { readonly type: "boolean"; readonly value: boolean } - | { readonly value: string } + | { + readonly type: "boolean"; + readonly value: boolean; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly configId: string; + readonly sessionId: string; + } + | { + readonly value: string; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly configId: string; + readonly sessionId: string; + } | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly messageId?: string | null; @@ -4830,19 +4948,52 @@ export const ClientRequest = Schema.Struct({ Schema.Struct({ type: Schema.Literal("boolean"), value: Schema.Boolean.annotate({ description: "The boolean value." }), - }).annotate({ description: 'A boolean value (`type: "boolean"`).' }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + configId: Schema.String.annotate({ + description: "Unique identifier for a session configuration option.", + }), + sessionId: Schema.String.annotate({ + description: + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + }), + }).annotate({ + description: "Request parameters for setting a session configuration option.", + }), Schema.Struct({ value: Schema.String.annotate({ description: "Unique identifier for a session configuration option value.", }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + configId: Schema.String.annotate({ + description: "Unique identifier for a session configuration option.", + }), + sessionId: Schema.String.annotate({ + description: + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + }), }).annotate({ title: "value_id", - description: - "A [`SessionConfigValueId`] string value.\n\nThis is the default when `type` is absent on the wire. Unknown `type`\nvalues with string payloads also gracefully deserialize into this\nvariant.", + description: "Request parameters for setting a session configuration option.", }), ]).annotate({ title: "SetSessionConfigOptionRequest", - description: "Request parameters for setting a session configuration option.", + description: "Sets the current value for a session configuration option.", }), Schema.Struct({ _meta: Schema.optionalKey( @@ -5818,72 +5969,106 @@ export type ElicitationRequest = readonly title?: string | null; readonly type?: "object"; }; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly message: string; + readonly sessionId: string; } - | { readonly mode: "url"; readonly elicitationId: string; readonly url: string }; -export const ElicitationRequest = Schema.Union( - [ - Schema.Struct({ - mode: Schema.Literal("form"), - requestedSchema: Schema.Struct({ - description: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: "Optional description of what this schema represents.", - }), - Schema.Null, - ]), - ), - properties: Schema.optionalKey( - Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ - description: "Property definitions (must be primitive types).", - default: {}, + | { + readonly mode: "url"; + readonly elicitationId: string; + readonly url: string; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly message: string; + readonly sessionId: string; + }; +export const ElicitationRequest = Schema.Union([ + Schema.Struct({ + mode: Schema.Literal("form"), + requestedSchema: Schema.Struct({ + description: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional description of what this schema represents.", }), - ), - required: Schema.optionalKey( - Schema.Union([ - Schema.Array(Schema.String).annotate({ - description: "List of required property names.", - }), - Schema.Null, - ]), - ), - title: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ description: "Optional title for the schema." }), - Schema.Null, - ]), - ), - type: Schema.optionalKey( - Schema.Literal("object").annotate({ - description: "Type discriminator for elicitation schemas.", - default: "object", - }), - ), - }).annotate({ - description: - "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", - }), + Schema.Null, + ]), + ), + properties: Schema.optionalKey( + Schema.Record(Schema.String, ElicitationPropertySchema).annotate({ + description: "Property definitions (must be primitive types).", + default: {}, + }), + ), + required: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ description: "List of required property names." }), + Schema.Null, + ]), + ), + title: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional title for the schema." }), + Schema.Null, + ]), + ), + type: Schema.optionalKey( + Schema.Literal("object").annotate({ + description: "Type discriminator for elicitation schemas.", + default: "object", + }), + ), }).annotate({ description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nForm-based elicitation mode where the client renders a form from the provided schema.", + "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", }), - Schema.Struct({ - mode: Schema.Literal("url"), - elicitationId: Schema.String.annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", - }), - url: Schema.String.annotate({ description: "The URL to direct the user to.", format: "uri" }), - }).annotate({ + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + message: Schema.String.annotate({ + description: "A human-readable message describing what input is needed.", + }), + sessionId: Schema.String.annotate({ description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nURL-based elicitation mode where the client directs the user to a URL.", + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", }), - ], - { mode: "oneOf" }, -).annotate({ - description: - "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", -}); + }).annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", + }), + Schema.Struct({ + mode: Schema.Literal("url"), + elicitationId: Schema.String.annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.", + }), + url: Schema.String.annotate({ description: "The URL to direct the user to.", format: "uri" }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + message: Schema.String.annotate({ + description: "A human-readable message describing what input is needed.", + }), + sessionId: Schema.String.annotate({ + description: + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + }), + }).annotate({ + description: + "**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.", + }), +]); export type ElicitationResponse = { readonly _meta?: { readonly [x: string]: unknown } | null; @@ -7801,17 +7986,6 @@ export const SessionConfigId = Schema.String.annotate({ description: "Unique identifier for a session configuration option.", }); -export type SessionConfigOptionCategory = "mode" | "model" | "thought_level" | string; -export const SessionConfigOptionCategory = Schema.Union([ - Schema.Literal("mode").annotate({ description: "Session mode selector." }), - Schema.Literal("model").annotate({ description: "Model selector." }), - Schema.Literal("thought_level").annotate({ description: "Thought/reasoning level selector." }), - Schema.String.annotate({ title: "other", description: "Unknown / uncategorized selector." }), -]).annotate({ - description: - "Semantic category for a session configuration option.\n\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\ncategories gracefully.\n\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\nCategory names that do not begin with `_` are reserved for the ACP spec.", -}); - export type SessionConfigSelect = { readonly currentValue: string; readonly options: @@ -9533,23 +9707,65 @@ export const SessionUpdate = Schema.Union( }); export type SetSessionConfigOptionRequest = - | { readonly type: "boolean"; readonly value: boolean } - | { readonly value: string }; + | { + readonly type: "boolean"; + readonly value: boolean; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly configId: string; + readonly sessionId: string; + } + | { + readonly value: string; + readonly _meta?: { readonly [x: string]: unknown } | null; + readonly configId: string; + readonly sessionId: string; + }; export const SetSessionConfigOptionRequest = Schema.Union([ Schema.Struct({ type: Schema.Literal("boolean"), value: Schema.Boolean.annotate({ description: "The boolean value." }), - }).annotate({ description: 'A boolean value (`type: "boolean"`).' }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + configId: Schema.String.annotate({ + description: "Unique identifier for a session configuration option.", + }), + sessionId: Schema.String.annotate({ + description: + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + }), + }).annotate({ description: "Request parameters for setting a session configuration option." }), Schema.Struct({ value: Schema.String.annotate({ description: "Unique identifier for a session configuration option value.", }), + _meta: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Unknown).annotate({ + description: + "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)", + }), + Schema.Null, + ]), + ), + configId: Schema.String.annotate({ + description: "Unique identifier for a session configuration option.", + }), + sessionId: Schema.String.annotate({ + description: + "A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)", + }), }).annotate({ title: "value_id", - description: - "A [`SessionConfigValueId`] string value.\n\nThis is the default when `type` is absent on the wire. Unknown `type`\nvalues with string payloads also gracefully deserialize into this\nvariant.", + description: "Request parameters for setting a session configuration option.", }), -]).annotate({ description: "Request parameters for setting a session configuration option." }); +]); export type SetSessionConfigOptionResponse = { readonly _meta?: { readonly [x: string]: unknown } | null; diff --git a/packages/effect-acp/src/child-process.ts b/packages/effect-acp/src/child-process.ts index f9aaf971bb..abfd8468c6 100644 --- a/packages/effect-acp/src/child-process.ts +++ b/packages/effect-acp/src/child-process.ts @@ -1,3 +1,4 @@ +import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Sink from "effect/Sink"; import * as Stdio from "effect/Stdio"; @@ -9,11 +10,13 @@ export function makeStdioFromChildProcess( handle: ChildProcessSpawner.ChildProcessHandle, ): Stdio.Stdio { return Stdio.make({ + args: Effect.succeed([]), stdin: handle.stdout, - stdout: Sink.mapInput(handle.stdin, (chunk) => - typeof chunk === "string" ? textEncoder.encode(chunk) : chunk, - ), - stderr: Sink.drain, + stdout: () => + Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) => + typeof chunk === "string" ? textEncoder.encode(chunk) : chunk, + ), + stderr: () => Sink.drain, }); } diff --git a/packages/effect-acp/src/client.test.ts b/packages/effect-acp/src/client.test.ts index d920850310..5c1fb9ca43 100644 --- a/packages/effect-acp/src/client.test.ts +++ b/packages/effect-acp/src/client.test.ts @@ -1,6 +1,7 @@ import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; @@ -18,6 +19,8 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => { Effect.gen(function* () { const updates = yield* Ref.make>([]); const elicitationCompletions = yield* Ref.make>([]); + const typedRequests = yield* Ref.make>([]); + const typedNotifications = yield* Ref.make>([]); const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -49,6 +52,24 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => { Ref.update(updates, (current) => [...current, notification]), elicitationComplete: (notification) => Ref.update(elicitationCompletions, (current) => [...current, notification]), + extRequests: { + "x/typed_request": AcpClient.defineExtRequest( + Schema.Struct({ message: Schema.String }), + (payload) => + Ref.update(typedRequests, (current) => [...current, payload]).pipe( + Effect.as({ + ok: true, + echoedMessage: payload.message, + }), + ), + ), + }, + extNotifications: { + "x/typed_notification": AcpClient.defineExtNotification( + Schema.Struct({ count: Schema.Number }), + (payload) => Ref.update(typedNotifications, (current) => [...current, payload]), + ), + }, }, }); @@ -85,6 +106,8 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => { assert.equal(streamed[1]?._tag, "ElicitationComplete"); assert.equal((yield* Ref.get(updates)).length, 1); assert.equal((yield* Ref.get(elicitationCompletions)).length, 1); + assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]); + assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]); const ext = yield* client.extRequest("x/echo", { hello: "world", diff --git a/packages/effect-acp/src/client.ts b/packages/effect-acp/src/client.ts index 53c2ca0fd6..082b1b9dea 100644 --- a/packages/effect-acp/src/client.ts +++ b/packages/effect-acp/src/client.ts @@ -14,6 +14,26 @@ import * as AcpSchema from "./_generated/schema.gen"; import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +export interface AcpExtensionRequestRegistration { + readonly payload: Schema.Schema; + readonly handler: (payload: A) => Effect.Effect; +} + +export interface AcpExtensionNotificationRegistration { + readonly payload: Schema.Schema; + readonly handler: (payload: A) => Effect.Effect; +} + +export const defineExtRequest = ( + payload: Schema.Schema, + handler: (payload: A) => Effect.Effect, +): AcpExtensionRequestRegistration => ({ payload, handler }); + +export const defineExtNotification = ( + payload: Schema.Schema, + handler: (payload: A) => Effect.Effect, +): AcpExtensionNotificationRegistration => ({ payload, handler }); + export interface AcpClientHandlers { /** * Handles `session/request_permission`. @@ -100,6 +120,10 @@ export interface AcpClientHandlers { method: string, params: unknown, ) => Effect.Effect; + /** + * Handles extension requests outside the core ACP method set using typed payload decoders. + */ + readonly extRequests?: Readonly>>; /** * Handles extension notifications outside the core ACP method set. * @see https://agentclientprotocol.com/protocol/extensibility @@ -108,6 +132,10 @@ export interface AcpClientHandlers { method: string, params: unknown, ) => Effect.Effect; + /** + * Handles extension notifications outside the core ACP method set using typed payload decoders. + */ + readonly extNotifications?: Readonly>>; } export interface AcpClientConnectOptions { @@ -257,16 +285,29 @@ export const fromChildProcess = Effect.fnUntraced(function* ( ? handlers.elicitationComplete(notification.params) : Effect.void; case "ExtNotification": - return handlers.extNotification - ? handlers.extNotification(notification.method, notification.params) - : Effect.void; + return runExtNotificationHandler( + handlers.extNotifications?.[notification.method], + handlers.extNotification, + notification.method, + notification.params, + ); case "SessionCancel": return handlers.extNotification ? handlers.extNotification(notification.method, notification.params) : Effect.void; } }, - ...(handlers.extRequest ? { onExtRequest: handlers.extRequest } : {}), + ...(handlers.extRequest || handlers.extRequests + ? { + onExtRequest: (method: string, params: unknown) => + runExtRequestHandler( + handlers.extRequests?.[method], + handlers.extRequest, + method, + params, + ), + } + : {}), }); const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer( @@ -354,3 +395,52 @@ const runHandler = Effect.fnUntraced(function* ( }), ); }); + +const decodeUnknownWith = ( + schema: Schema.Schema, + payload: unknown, +): Effect.Effect => + Effect.try({ + try: () => Schema.decodeUnknownSync(schema as never)(payload) as A, + catch: (cause) => + new AcpError.AcpProtocolParseError({ + detail: "Failed to decode typed ACP extension payload", + cause, + }), + }); + +const runExtRequestHandler = ( + registration: AcpExtensionRequestRegistration | undefined, + fallback: + | ((method: string, params: unknown) => Effect.Effect) + | undefined, + method: string, + params: unknown, +): Effect.Effect => { + if (registration) { + return decodeUnknownWith(registration.payload, params).pipe( + Effect.mapError(() => AcpError.AcpRequestError.invalidParams(`Invalid ${method} payload`)), + Effect.flatMap((payload) => registration.handler(payload)), + ); + } + if (fallback) { + return fallback(method, params); + } + return Effect.fail(AcpError.AcpRequestError.methodNotFound(method)); +}; + +const runExtNotificationHandler = ( + registration: AcpExtensionNotificationRegistration | undefined, + fallback: + | ((method: string, params: unknown) => Effect.Effect) + | undefined, + method: string, + params: unknown, +): Effect.Effect => { + if (registration) { + return decodeUnknownWith(registration.payload, params).pipe( + Effect.flatMap((payload) => registration.handler(payload)), + ); + } + return fallback ? fallback(method, params) : Effect.void; +}; diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts index 029ef4e67b..390364c859 100644 --- a/packages/effect-acp/src/protocol.test.ts +++ b/packages/effect-acp/src/protocol.test.ts @@ -21,11 +21,13 @@ function makeInMemoryStdio() { return { stdio: Stdio.make({ + args: Effect.succeed([]), stdin: Stream.fromQueue(input), - stdout: Sink.forEach((chunk: string | Uint8Array) => - Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)), - ), - stderr: Sink.drain, + stdout: () => + Sink.forEach((chunk: string | Uint8Array) => + Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)), + ), + stderr: () => Sink.drain, }), input, output, diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.ts index d103babb1e..553ff3cf39 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -44,12 +44,14 @@ export interface AcpPatchedProtocolOptions { readonly serverRequestMethods: ReadonlySet; readonly onNotification?: ( notification: AcpIncomingNotification, - ) => Effect.Effect; + ) => Effect.Effect; readonly onExtRequest?: ( method: string, params: unknown, - ) => Effect.Effect; - readonly onProcessExit?: (error: AcpError.AcpProcessExitedError) => Effect.Effect; + ) => Effect.Effect; + readonly onProcessExit?: ( + error: AcpError.AcpProcessExitedError, + ) => Effect.Effect; } export interface AcpPatchedProtocol { @@ -376,7 +378,7 @@ export const makeAcpPatchedProtocol = ( Effect.forkScoped, ); - yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout), Effect.forkScoped); + yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped); const clientProtocol = RpcClient.Protocol.of({ run: (f) => diff --git a/packages/effect-acp/src/schema.ts b/packages/effect-acp/src/schema.ts index 8e354aca37..5f40fa7539 100644 --- a/packages/effect-acp/src/schema.ts +++ b/packages/effect-acp/src/schema.ts @@ -1,2 +1,2 @@ -export * from "./_generated/schema.gen.ts"; -export * from "./_generated/meta.gen.ts"; +export * from "./_generated/schema.gen"; +export * from "./_generated/meta.gen"; diff --git a/packages/effect-acp/test/examples/cursor-acp-client.example.ts b/packages/effect-acp/test/examples/cursor-acp-client.example.ts index 0fff9c1f6f..1a3f226952 100644 --- a/packages/effect-acp/test/examples/cursor-acp-client.example.ts +++ b/packages/effect-acp/test/examples/cursor-acp-client.example.ts @@ -47,7 +47,12 @@ Effect.gen(function* () { const result = yield* client.prompt({ sessionId: session.sessionId, - prompt: [{ type: "text", text: "Summarize this repository." }], + prompt: [ + { + type: "text", + text: "Illustrate your ability to create todo lists and then execute all of them. Do not write the list to disk, illustrate your built in ability!", + }, + ], }); yield* Effect.logInfo("prompt result", result); diff --git a/packages/effect-acp/test/fixtures/acp-mock-peer.ts b/packages/effect-acp/test/fixtures/acp-mock-peer.ts index 593ba1820d..ff8b61ea13 100644 --- a/packages/effect-acp/test/fixtures/acp-mock-peer.ts +++ b/packages/effect-acp/test/fixtures/acp-mock-peer.ts @@ -122,6 +122,8 @@ async function handleRequest(message: { }); await requestClient("session/elicitation", { + sessionId: "mock-session-1", + message: "Need confirmation before continuing.", mode: "form", requestedSchema: { type: "object", @@ -154,6 +156,14 @@ async function handleRequest(message: { elicitationId: "elicitation-1", }); + await requestClient("x/typed_request", { + message: "hello from typed request", + }); + + notify("x/typed_notification", { + count: 2, + }); + respond(message.id, { stopReason: "end_turn", }); diff --git a/patches/effect@4.0.0-beta.41.patch b/patches/effect@4.0.0-beta.41.patch new file mode 100644 index 0000000000..f7296bc10c --- /dev/null +++ b/patches/effect@4.0.0-beta.41.patch @@ -0,0 +1,108 @@ +diff --git a/src/SchemaRepresentation.ts b/src/SchemaRepresentation.ts +index e1a87e2b..a7797678 100644 +--- a/src/SchemaRepresentation.ts ++++ b/src/SchemaRepresentation.ts +@@ -3007,7 +3007,14 @@ export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<" + } + } + +- let out = on(js) ++ const hasAnyOf = Array.isArray(js.anyOf) ++ const hasOneOf = Array.isArray(js.oneOf) ++ const base = ++ hasAnyOf || hasOneOf ++ ? ({ ...js, anyOf: undefined, oneOf: undefined } as JsonSchema.JsonSchema) ++ : js ++ ++ let out = on(base) + + const annotations = collectAnnotations(js) + if (annotations !== undefined) { +@@ -3018,6 +3025,14 @@ export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<" + return js.allOf.reduce((acc, curr) => combine(acc, recur(curr)), out) + } + ++ if (hasAnyOf) { ++ out = combine({ _tag: "Union", types: js.anyOf.map((type) => recur(type)), mode: "anyOf" }, out) ++ } ++ ++ if (hasOneOf) { ++ out = combine({ _tag: "Union", types: js.oneOf.map((type) => recur(type)), mode: "oneOf" }, out) ++ } ++ + return out + } + +@@ -3054,12 +3069,7 @@ export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<" + } else { + return { _tag: "Union", types, mode: "anyOf" } + } +- } else if (Array.isArray(js.anyOf)) { +- return { _tag: "Union", types: js.anyOf.map((type) => recur(type)), mode: "anyOf" } +- } else if (Array.isArray(js.oneOf)) { +- return { _tag: "Union", types: js.oneOf.map((type) => recur(type)), mode: "oneOf" } + } +- + const type = isType(js.type) ? js.type : getType(js) + if (type !== undefined) { + switch (type) { +diff --git a/dist/SchemaRepresentation.js b/dist/SchemaRepresentation.js +index 0d3f01d7..c3672558 100644 +--- a/dist/SchemaRepresentation.js ++++ b/dist/SchemaRepresentation.js +@@ -2042,7 +2042,14 @@ export function fromJsonSchemaMultiDocument(document, options) { + js = {}; + } + } +- let out = on(js); ++ const hasAnyOf = Array.isArray(js.anyOf); ++ const hasOneOf = Array.isArray(js.oneOf); ++ const base = hasAnyOf || hasOneOf ? { ++ ...js, ++ anyOf: undefined, ++ oneOf: undefined ++ } : js; ++ let out = on(base); + const annotations = collectAnnotations(js); + if (annotations !== undefined) { + out = combine(out, { +@@ -2053,6 +2060,20 @@ export function fromJsonSchemaMultiDocument(document, options) { + if (Array.isArray(js.allOf)) { + return js.allOf.reduce((acc, curr) => combine(acc, recur(curr)), out); + } ++ if (hasAnyOf) { ++ out = combine({ ++ _tag: "Union", ++ types: js.anyOf.map(type => recur(type)), ++ mode: "anyOf" ++ }, out); ++ } ++ if (hasOneOf) { ++ out = combine({ ++ _tag: "Union", ++ types: js.oneOf.map(type => recur(type)), ++ mode: "oneOf" ++ }, out); ++ } + return out; + } + function on(js) { +@@ -2105,18 +2126,6 @@ export function fromJsonSchemaMultiDocument(document, options) { + mode: "anyOf" + }; + } +- } else if (Array.isArray(js.anyOf)) { +- return { +- _tag: "Union", +- types: js.anyOf.map(type => recur(type)), +- mode: "anyOf" +- }; +- } else if (Array.isArray(js.oneOf)) { +- return { +- _tag: "Union", +- types: js.oneOf.map(type => recur(type)), +- mode: "oneOf" +- }; + } + const type = isType(js.type) ? js.type : getType(js); + if (type !== undefined) {