Add ACP support with Cursor provider (#1355)

Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-04-17 16:21:31 -07:00
1 parent 0f184c28b0
commit 9c64f12ea0
98 files changed
+26746 -862

No files matched your search

+1
View File
@@ -23,6 +23,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
},
{
...shared,
+1
View File
@@ -43,6 +43,7 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+590
View File
@@ -0,0 +1,590 @@
#!/usr/bin/env bun
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";
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const sessionId = "mock-session-1";
let currentModeId = "ask";
let currentModelId = "default";
let parameterizedModelPicker = false;
let currentReasoning = "medium";
let currentContext = "272k";
let currentFast = false;
const cancelledSessions = new Set<string>();
function logExit(reason: string): void {
if (!exitLogPath) {
return;
}
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
});
process.once("SIGINT", () => {
logExit("SIGINT");
process.exit(0);
});
process.once("exit", (code) => {
logExit(`exit:${code}`);
});
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
if (parameterizedModelPicker) {
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
{
id: "mode",
name: "Mode",
category: "mode",
type: "select",
currentValue: currentModeId,
options: availableModes.map((mode) => ({
value: mode.id,
name: mode.name,
...(mode.description ? { description: mode.description } : {}),
})),
},
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: currentModelId,
options: [
{ value: "default", name: "Auto" },
{ value: "composer-2", name: "Composer 2" },
{ value: "gpt-5.4", name: "GPT-5.4" },
{ value: "claude-opus-4-6", name: "Opus 4.6" },
],
},
];
switch (currentModelId) {
case "gpt-5.4":
return [
...baseOptions,
{
id: "reasoning",
name: "Reasoning",
category: "thought_level",
type: "select",
currentValue: currentReasoning,
options: [
{ value: "none", name: "None" },
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
{ value: "extra-high", name: "Extra High" },
],
},
{
id: "context",
name: "Context",
category: "model_config",
type: "select",
currentValue: currentContext,
options: [
{ value: "272k", name: "272K" },
{ value: "1m", name: "1M" },
],
},
{
id: "fast",
name: "Fast",
category: "model_config",
type: "select",
currentValue: String(currentFast),
options: [
{ value: "false", name: "Off" },
{ value: "true", name: "Fast" },
],
},
];
case "composer-2":
return [
...baseOptions,
{
id: "fast",
name: "Fast",
category: "model_config",
type: "select",
currentValue: String(currentFast),
options: [
{ value: "false", name: "Off" },
{ value: "true", name: "Fast" },
],
},
];
case "claude-opus-4-6":
return [
...baseOptions,
{
id: "reasoning",
name: "Reasoning",
category: "thought_level",
type: "select",
currentValue: currentReasoning,
options: [
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
],
},
{
id: "thinking",
name: "Thinking",
category: "model_config",
type: "boolean",
currentValue: true,
},
];
default:
return baseOptions;
}
}
return [
{
id: "model",
name: "Model",
category: "model",
type: "select" as const,
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: ReadonlyArray<AcpSchema.SessionMode> = [
{
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",
},
];
function modeState(): AcpSchema.SessionModeState {
return {
currentModeId,
availableModes,
};
}
const program = Effect.gen(function* () {
const agent = yield* EffectAcpAgent.AcpAgent;
yield* agent.handleInitialize((request) =>
Effect.sync(() => {
parameterizedModelPicker =
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
return {
protocolVersion: 1,
agentCapabilities: { loadSession: true },
};
}),
);
yield* agent.handleAuthenticate(() => Effect.succeed({}));
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 {
configOptions: configOptions(),
};
}),
);
yield* agent.handleCancel(({ sessionId }) =>
Effect.sync(() => {
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
}),
);
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "before tool" },
},
});
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({
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" },
],
});
const cancelled =
cancelledSessions.delete(requestedSessionId) ||
permission.outcome.outcome === "cancelled";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
title: "Terminal",
kind: "execute",
status: "completed",
rawOutput: {
exitCode: 0,
stdout: '{ "name": "t3" }',
stderr: "",
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "hello from mock" },
},
});
return { stopReason: cancelled ? "cancelled" : "end_turn" };
}
if (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,
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));
}
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
: 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({}));
}
return Effect.succeed({});
});
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);
@@ -0,0 +1,435 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import process from "node:process";
import readline from "node:readline";
type JsonPrimitive = null | boolean | number | string;
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
type JsonRpcId = number | string;
type JsonRpcMessage = {
jsonrpc?: string;
id?: JsonRpcId;
method?: string;
params?: JsonValue;
result?: JsonValue;
error?: JsonValue;
headers?: JsonValue;
};
type SelectLeafOption = {
value: string;
label?: string;
name?: string;
};
type SelectGroupOption = {
label?: string;
name?: string;
options: SelectLeafOption[];
};
type SessionConfigOption = {
id: string;
name?: string;
category?: string;
type?: string;
options?: Array<SelectLeafOption | SelectGroupOption>;
};
type SessionNewResult = {
sessionId: string;
configOptions?: SessionConfigOption[];
};
type SetConfigResult = {
configOptions?: SessionConfigOption[];
};
type PendingRequest = {
method: string;
resolve: (value: JsonValue | undefined) => void;
reject: (error: Error) => void;
};
const targetCwd = process.argv[2] ?? process.cwd();
const targetModel = process.argv[3] ?? "gpt-5.4";
const promptText = process.argv[4] ?? "helo";
const targetReasoning = process.env.CURSOR_REASONING ?? "";
const targetContext = process.env.CURSOR_CONTEXT ?? "";
const targetFast = process.env.CURSOR_FAST ?? "";
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
function logSection(title: string, value: unknown) {
process.stdout.write(`\n=== ${title} ===\n`);
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function fail(message: string): never {
throw new Error(message);
}
function asString(value: JsonValue | undefined): string | null {
return typeof value === "string" ? value : null;
}
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
return [];
}
const values: string[] = [];
for (const entry of option.options) {
if (!entry || typeof entry !== "object") {
continue;
}
if ("value" in entry && typeof entry.value === "string") {
values.push(entry.value);
continue;
}
if ("options" in entry && Array.isArray(entry.options)) {
for (const nested of entry.options) {
if (nested && typeof nested === "object" && typeof nested.value === "string") {
values.push(nested.value);
}
}
}
}
return values;
}
function findConfigOption(
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
): SessionConfigOption | undefined {
return configOptions.find(predicate);
}
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
return haystack.includes(keyword.toLowerCase());
}
function sleep(ms: number) {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
class JsonRpcChild {
readonly child: ChildProcessWithoutNullStreams;
readonly pending = new Map<JsonRpcId, PendingRequest>();
nextId = 1;
closed = false;
constructor(bin: string, args: string[], cwd: string) {
this.child = spawn(bin, args, {
cwd,
shell: process.platform === "win32",
stdio: ["pipe", "pipe", "pipe"],
env: process.env,
});
this.child.on("exit", (code, signal) => {
this.closed = true;
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
for (const pending of this.pending.values()) {
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
}
this.pending.clear();
});
this.child.on("error", (error) => {
this.closed = true;
for (const pending of this.pending.values()) {
pending.reject(error);
}
this.pending.clear();
});
const stdout = readline.createInterface({ input: this.child.stdout });
stdout.on("line", (line) => {
void this.handleStdoutLine(line);
});
const stderr = readline.createInterface({ input: this.child.stderr });
stderr.on("line", (line) => {
process.stdout.write(`[stderr] ${line}\n`);
});
}
write(message: JsonRpcMessage) {
if (this.closed) {
fail("ACP process is already closed.");
}
const payload = JSON.stringify({
jsonrpc: "2.0",
headers: [],
...message,
});
process.stdout.write(`>>> ${payload}\n`);
this.child.stdin.write(`${payload}\n`);
}
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
const id = this.nextId++;
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
}, timeoutMs);
this.pending.set(id, {
method,
resolve: (value) => {
clearTimeout(timeout);
resolve(value);
},
reject: (error) => {
clearTimeout(timeout);
reject(error);
},
});
});
this.write({
id,
method,
params,
});
return responsePromise;
}
notify(method: string, params: JsonValue) {
this.write({
method,
params,
});
}
respond(id: JsonRpcId, result: JsonValue) {
this.write({
id,
result,
});
}
respondError(id: JsonRpcId, code: number, message: string) {
this.write({
id,
error: {
code,
message,
},
});
}
async handleStdoutLine(line: string) {
if (line.trim().length === 0) {
return;
}
process.stdout.write(`<<< ${line}\n`);
let message: JsonRpcMessage;
try {
message = JSON.parse(line) as JsonRpcMessage;
} catch (error) {
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
return;
}
if (typeof message.id !== "undefined" && !message.method) {
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
this.pending.delete(message.id);
if (typeof message.error !== "undefined") {
pending.reject(
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
);
return;
}
pending.resolve(message.result);
return;
}
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
this.respond(message.id, {
outcome: {
outcome: "selected",
optionId: "allow",
},
});
return;
}
if (typeof message.id !== "undefined" && message.id !== "") {
this.respondError(
message.id,
-32601,
`Unhandled server request: ${message.method ?? "unknown"}`,
);
}
}
async close() {
if (this.closed) {
return;
}
this.child.kill("SIGTERM");
await sleep(250);
if (!this.closed) {
this.child.kill("SIGKILL");
}
}
}
async function setSelectOptionIfAdvertised(
rpc: JsonRpcChild,
sessionId: string,
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
value: string,
label: string,
) {
if (value.length === 0) {
return configOptions;
}
const option = findConfigOption(configOptions, predicate);
const values = flattenSelectValues(option);
if (!option || !values.includes(value)) {
logSection(`SKIP_${label}`, {
requestedValue: value,
availableValues: values,
});
return configOptions;
}
const response = (await rpc.request("session/set_config_option", {
sessionId,
configId: option.id,
value,
})) as SetConfigResult | null | undefined;
logSection(`SET_${label}_RESPONSE`, response);
return response?.configOptions ?? configOptions;
}
async function main() {
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
try {
const initializeResponse = await rpc.request("initialize", {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: {
name: "cursor-acp-model-mismatch-probe",
version: "0.0.0",
},
});
logSection("INITIALIZE_RESPONSE", initializeResponse);
const authenticateResponse = await rpc.request("authenticate", {
methodId: "cursor_login",
});
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
const sessionResponse = (await rpc.request("session/new", {
cwd: targetCwd,
mcpServers: [],
})) as SessionNewResult;
logSection("SESSION_NEW_RESPONSE", sessionResponse);
const sessionId = asString(sessionResponse.sessionId);
if (!sessionId) {
fail("session/new did not return a sessionId.");
}
let configOptions = sessionResponse.configOptions ?? [];
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
const advertisedModels = flattenSelectValues(modelConfig);
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
if (!modelConfig || modelConfig.type !== "select") {
fail("Cursor ACP did not expose a select-type model config option.");
}
if (!advertisedModels.includes(targetModel)) {
fail(
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
);
}
const setModelResponse = (await rpc.request("session/set_config_option", {
sessionId,
configId: modelConfig.id,
value: targetModel,
})) as SetConfigResult | null | undefined;
logSection("SET_MODEL_RESPONSE", setModelResponse);
configOptions = setModelResponse?.configOptions ?? configOptions;
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "thought_level",
targetReasoning,
"REASONING",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
targetContext,
"CONTEXT",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
targetFast,
"FAST",
);
const promptResponse = await rpc.request("session/prompt", {
sessionId,
prompt: [
{
type: "text",
text: promptText,
},
],
});
logSection("PROMPT_RESPONSE", promptResponse);
await sleep(promptWaitMs);
rpc.notify("session/cancel", { sessionId });
} finally {
await rpc.close();
}
}
void main().catch((error: unknown) => {
process.stderr.write(
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
);
process.exitCode = 1;
});
@@ -19,6 +19,8 @@ import { GitCore } from "../../git/Services/GitCore.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -245,6 +247,7 @@ const makeCheckpointStore = Effect.gen(function* () {
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
return result.stdout;
@@ -11,7 +11,6 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
@@ -30,6 +29,7 @@ import {
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { resolveClaudeApiModelId } from "../../provider/Layers/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
@@ -110,7 +110,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
resolveClaudeApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
@@ -0,0 +1,298 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { expect } from "vitest";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
mkdirSync(binDir, { recursive: true });
writeFileSync(
agentPath,
[
"#!/bin/sh",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
'if [ "$1" != "acp" ]; then',
' printf "%s\\n" "unexpected args: $*" >&2',
" exit 11",
"fi",
`exec bun ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(agentPath, 0o755);
return agentPath;
}
function withFakeAcpAgent<A, E, R>(
env: Record<string, string>,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
const agentPath = makeAcpAgentWrapper(tempDir, env);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return yield* effect.pipe(
Effect.ensuring(
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousSettings.providers.cursor.binaryPath,
},
},
})
.pipe(
Effect.catch(() => Effect.void),
Effect.ensuring(
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
),
Effect.asVoid,
),
),
);
});
}
function waitForFileContent(path: string): Effect.Effect<string> {
return Effect.promise(async () => {
const deadline = Date.now() + 5_000;
for (;;) {
try {
return readFileSync(path, "utf8");
} catch (error) {
if (Date.now() >= deadline) {
throw error instanceof Error ? error : new Error(String(error));
}
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpAgent(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Add generated commit message",
body: "- verify cursor acp model config path",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "gpt-5.4",
options: {
reasoning: "xhigh",
fastMode: true,
contextWindow: "1m",
},
},
});
expect(generated.subject).toBe("Add generated commit message");
expect(generated.body).toBe("- verify cursor acp model config path");
const requests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
expect(
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
).toMatchObject({
_meta: {
parameterizedModelPicker: true,
},
});
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "model" &&
request.params?.value === "gpt-5.4",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "reasoning" &&
request.params?.value === "extra-high",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "context" &&
request.params?.value === "1m",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "fast" &&
request.params?.value === "true",
),
).toBe(true);
expect(
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "text",
text: expect.stringContaining("Staged patch:"),
}),
]),
);
rmSync(requestLogDir, { recursive: true, force: true });
}),
);
});
it.effect("accepts json objects with extra assistant text around them", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-noisy-json",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
expect(generated.body).toBe("");
}),
),
);
it.effect("generates thread titles through Cursor ACP text generation", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
title: '"Trim reconnect spinner status after resume."',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
}),
),
);
it.effect("closes the ACP child process after text generation completes", () => {
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
const exitLogPath = path.join(exitLogDir, "exit.log");
return withFakeAcpAgent(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Close runtime after generation",
body: "",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Close runtime after generation");
const exitLog = yield* waitForFileContent(exitLogPath);
expect(exitLog).toContain("exit:0");
rmSync(exitLogDir, { recursive: true, force: true });
}),
);
});
});
@@ -0,0 +1,352 @@
import { Effect, Layer, Option, Ref, Schema } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { CursorModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import {
type ThreadTitleGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import { sanitizeCommitSubject, sanitizePrTitle, sanitizeThreadTitle } from "../Utils.ts";
import {
applyCursorAcpModelSelection,
makeCursorAcpRuntime,
} from "../../provider/acp/CursorAcpSupport.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CURSOR_TIMEOUT_MS = 180_000;
function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
function mapCursorAcpError(
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
detail: string,
cause: unknown,
): TextGenerationError {
return new TextGenerationError({
operation,
detail,
...(cause !== undefined ? { cause } : {}),
});
}
function isTextGenerationError(error: unknown): error is TextGenerationError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "TextGenerationError"
);
}
const makeCursorTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const runCursorJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: CursorModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const cursorSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.cursor,
).pipe(Effect.catch(() => Effect.undefined));
const outputRef = yield* Ref.make("");
const runtime = yield* makeCursorAcpRuntime({
cursorSettings,
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
});
yield* runtime.handleSessionUpdate((notification) => {
const update = notification.update;
if (update.sessionUpdate !== "agent_message_chunk") {
return Effect.void;
}
const content = update.content;
if (content.type !== "text") {
return Effect.void;
}
return Ref.update(outputRef, (current) => current + content.text);
});
const promptResult = yield* Effect.gen(function* () {
yield* runtime.start();
yield* Effect.ignore(runtime.setMode("ask"));
yield* applyCursorAcpModelSelection({
runtime,
model: modelSelection.model,
modelOptions: modelSelection.options,
mapError: ({ cause, configId, step }) =>
mapCursorAcpError(
operation,
step === "set-config-option"
? `Failed to set Cursor ACP config option "${configId}" for text generation.`
: "Failed to set Cursor ACP base model for text generation.",
cause,
),
});
return yield* runtime.prompt({
prompt: [{ type: "text", text: prompt }],
});
}).pipe(
Effect.timeoutOption(CURSOR_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Cursor Agent request timed out.",
}),
),
onSome: (value) => Effect.succeed(value),
}),
),
Effect.mapError((cause) =>
isTextGenerationError(cause)
? cause
: mapCursorAcpError(operation, "Cursor ACP request failed.", cause),
),
);
const rawResult = (yield* Ref.get(outputRef)).trim();
if (!rawResult) {
return yield* new TextGenerationError({
operation,
detail:
promptResult.stopReason === "cancelled"
? "Cursor ACP request was cancelled."
: "Cursor Agent returned empty output.",
});
}
return yield* Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))(
extractJsonObject(rawResult),
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Cursor Agent returned invalid structured output.",
cause,
}),
),
),
);
}).pipe(
Effect.mapError((cause) =>
isTextGenerationError(cause)
? cause
: mapCursorAcpError(operation, "Cursor ACP text generation failed.", cause),
),
Effect.scoped,
);
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CursorTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"CursorTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"CursorTextGeneration.generateBranchName",
)(function* (input) {
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"CursorTextGeneration.generateThreadTitle",
)(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
} satisfies ThreadTitleGenerationResult;
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration);
@@ -18,6 +18,7 @@ import {
} from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
// ---------------------------------------------------------------------------
@@ -32,6 +33,10 @@ class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
) {}
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
) {}
@@ -43,10 +48,17 @@ class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationSha
const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const cursor = yield* CursorTextGen;
const openCode = yield* OpenCodeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent" ? claude : provider === "opencode" ? openCode : codex;
provider === "claudeAgent"
? claude
: provider === "opencode"
? openCode
: provider === "cursor"
? cursor
: codex;
return {
generateCommitMessage: (input) =>
@@ -73,6 +85,14 @@ const InternalClaudeLayer = Layer.effect(
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
const InternalCursorLayer = Layer.effect(
CursorTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CursorTextGenerationLive));
const InternalOpenCodeLayer = Layer.effect(
OpenCodeTextGen,
Effect.gen(function* () {
@@ -87,5 +107,6 @@ export const RoutingTextGenerationLive = Layer.effect(
).pipe(
Layer.provide(InternalCodexLayer),
Layer.provide(InternalClaudeLayer),
Layer.provide(InternalCursorLayer),
Layer.provide(InternalOpenCodeLayer),
);
@@ -13,7 +13,7 @@ import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent" | "opencode";
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
export interface CommitMessageGenerationInput {
cwd: string;
@@ -266,7 +266,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
@@ -89,9 +89,16 @@ function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolea
: false;
}
function findProviderAdapterRequestError(
cause: Cause.Cause<ProviderServiceError>,
): ProviderAdapterRequestError | undefined {
const failReason = cause.reasons.find(Cause.isFailReason);
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const error = findProviderAdapterRequestError(cause);
if (error) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending approval request") ||
@@ -106,8 +113,8 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
}
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const error = findProviderAdapterRequestError(cause);
if (error) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
@@ -198,6 +205,17 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
? failReason.error
: undefined;
if (providerError) {
return providerError.detail;
}
return Cause.pretty(cause);
};
const setThreadSession = (input: {
readonly threadId: ThreadId;
readonly session: OrchestrationSession;
@@ -211,7 +229,30 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly detail: string;
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
const session = thread?.session;
if (!session) {
return;
}
yield* setThreadSession({
threadId: input.threadId,
session: {
...session,
status: session.status === "stopped" ? "stopped" : "ready",
activeTurnId: null,
lastError: input.detail,
updatedAt: input.createdAt,
},
createdAt: input.createdAt,
});
});
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
});
@@ -300,7 +341,7 @@ const make = Effect.gen(function* () {
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
currentProvider === "claudeAgent" &&
@@ -350,7 +391,7 @@ const make = Effect.gen(function* () {
return startedSession.threadId;
});
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
@@ -360,7 +401,9 @@ const make = Effect.gen(function* () {
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
return yield* Effect.die(
new Error(`Thread '${input.threadId}' was not found in read model.`),
);
}
yield* ensureSessionForThread(
input.threadId,
@@ -384,7 +427,7 @@ const make = Effect.gen(function* () {
const requestedModelSelection =
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
const modelForTurn =
sessionModelSwitch === "unsupported"
sessionModelSwitch === "unsupported" && input.modelSelection === undefined
? activeSession?.model !== undefined
? {
...requestedModelSelection,
@@ -393,13 +436,13 @@ const make = Effect.gen(function* () {
: requestedModelSelection
: input.modelSelection;
yield* providerService.sendTurn({
return {
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
};
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
@@ -558,7 +601,43 @@ const make = Effect.gen(function* () {
}
}
yield* sendTurnForThread({
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
detail,
createdAt: event.payload.createdAt,
}).pipe(
Effect.flatMap(() =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
Effect.catchCause((recoveryCause) =>
Effect.logWarning("provider command reactor failed to recover turn start failure", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(recoveryCause),
originalCause: Cause.pretty(cause),
}),
),
);
const sendTurnRequest = yield* buildSendTurnRequestForThread({
threadId: event.payload.threadId,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
@@ -568,17 +647,17 @@ const make = Effect.gen(function* () {
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
}).pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.map(Option.some),
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
);
if (Option.isNone(sendTurnRequest)) {
return;
}
yield* providerService
.sendTurn(sendTurnRequest.value)
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
@@ -723,6 +723,146 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("preserves completed tool metadata on projected tool activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-tool-completed-with-data"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-tool-completed"),
itemId: asItemId("item-tool-completed"),
payload: {
itemType: "dynamic_tool_call",
status: "completed",
title: "Read file",
data: {
toolCallId: "tool-read-1",
kind: "read",
rawOutput: {
content: 'import * as Effect from "effect/Effect"\n',
},
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-tool-completed-with-data",
);
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
const data =
payload?.data && typeof payload.data === "object"
? (payload.data as Record<string, unknown>)
: undefined;
const rawOutput =
data?.rawOutput && typeof data.rawOutput === "object"
? (data.rawOutput as Record<string, unknown>)
: undefined;
expect(activity?.kind).toBe("tool.completed");
expect(activity?.summary).toBe("Read file");
expect(payload?.itemType).toBe("dynamic_tool_call");
expect(payload?.detail).toBeUndefined();
expect(data?.toolCallId).toBe("tool-read-1");
expect(data?.kind).toBe("read");
expect(rawOutput?.content).toBe('import * as Effect from "effect/Effect"\n');
});
it("normalizes command execution activities to ran-command summaries", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-command-completed"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-command-completed"),
itemId: asItemId("item-command-completed"),
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
detail: "bun run lint",
data: {
toolCallId: "tool-command-1",
kind: "execute",
command: "bun run lint",
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-command-completed",
);
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
expect(activity?.summary).toBe("Ran command");
expect(payload?.detail).toBe("bun run lint");
});
it("uses structured read-file paths when available", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-read-path-completed"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-read-path"),
itemId: asItemId("item-read-path"),
payload: {
itemType: "dynamic_tool_call",
status: "completed",
title: "Read file",
detail: "/tmp/app.ts",
data: {
toolCallId: "tool-read-path-1",
kind: "read",
locations: [{ path: "/tmp/app.ts" }],
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-read-path-completed",
);
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
expect(activity?.summary).toBe("Read file");
expect(payload?.detail).toBe("/tmp/app.ts");
});
it("projects completed plan items into first-class proposed plans", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1392,6 +1532,432 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("flushes and completes buffered assistant text when an approval request opens", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-request-flush",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
itemId: asItemId("item-buffered-request-flush"),
payload: {
streamKind: "assistant_text",
delta: "visible before approval",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
requestId: ApprovalRequestId.make("req-buffered-request-flush"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-request-flush" &&
!message.streaming &&
message.text === "visible before approval",
),
);
const message = thread.messages.find(
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-flush",
);
expect(message?.streaming).toBe(false);
});
it("flushes and completes buffered assistant text when user input is requested", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-user-input-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-user-input-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
itemId: asItemId("item-buffered-user-input-flush"),
payload: {
streamKind: "assistant_text",
delta: "visible before user input",
},
});
harness.emit({
type: "user-input.requested",
eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
requestId: ApprovalRequestId.make("req-buffered-user-input-flush"),
payload: {
questions: [
{
id: "choice",
header: "Choice",
question: "Pick one",
options: [{ label: "A", description: "Option A" }],
},
],
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-user-input-flush" &&
!message.streaming &&
message.text === "visible before user input",
),
);
const message = thread.messages.find(
(entry: ProviderRuntimeTestMessage) =>
entry.id === "assistant:item-buffered-user-input-flush",
);
expect(message?.streaming).toBe(false);
});
it("does not create assistant segments for whitespace-only buffered text at approval boundaries", async () => {
const harness = await createHarness();
const startedAt = "2026-03-28T06:28:00.000Z";
const pausedAt = "2026-03-28T06:28:01.000Z";
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-whitespace-request"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-whitespace-request"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
itemId: asItemId("item-buffered-whitespace-request"),
payload: {
streamKind: "assistant_text",
delta: "\n\n\n",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-whitespace-request"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
requestId: ApprovalRequestId.make("req-buffered-whitespace-request"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
),
);
expect(
thread.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-whitespace-request",
),
).toBe(false);
});
it("starts a new buffered assistant message segment after approval and completes without duplication", async () => {
const harness = await createHarness();
const startedAt = "2026-03-28T06:07:00.000Z";
const pausedAt = "2026-03-28T06:07:01.000Z";
const resumedAt = "2026-03-28T06:07:02.000Z";
const completedAt = "2026-03-28T06:07:03.000Z";
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-append"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-request-append",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-initial"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
itemId: asItemId("item-buffered-request-append"),
payload: {
streamKind: "assistant_text",
delta: "first half",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-append"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
requestId: ApprovalRequestId.make("req-buffered-request-append"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-request-append" &&
!message.streaming &&
message.text === "first half",
),
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-followup"),
provider: "codex",
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
itemId: asItemId("item-buffered-request-append"),
payload: {
streamKind: "assistant_text",
delta: " second half",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered-request-append"),
provider: "codex",
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
itemId: asItemId("item-buffered-request-append"),
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-request-append:segment:1" &&
!message.streaming &&
message.text === " second half",
),
);
const firstMessage = thread.messages.find(
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-append",
);
const resumedMessage = thread.messages.find(
(entry: ProviderRuntimeTestMessage) =>
entry.id === "assistant:item-buffered-request-append:segment:1",
);
expect(firstMessage?.text).toBe("first half");
expect(firstMessage?.streaming).toBe(false);
expect(resumedMessage?.text).toBe(" second half");
expect(resumedMessage?.streaming).toBe(false);
const events = await Effect.runPromise(
Stream.runCollect(harness.engine.readEvents(0)).pipe(
Effect.map((chunk) => Array.from(chunk)),
),
);
const assistantEvents = events.filter(
(event): event is Extract<(typeof events)[number], { type: "thread.message-sent" }> =>
event.type === "thread.message-sent" &&
event.payload.messageId.startsWith("assistant:item-buffered-request-append"),
);
expect(assistantEvents).toHaveLength(4);
expect(assistantEvents[0]?.payload.streaming).toBe(true);
expect(assistantEvents[0]?.payload.text).toBe("first half");
expect(assistantEvents[1]?.payload.streaming).toBe(false);
expect(assistantEvents[1]?.payload.text).toBe("");
expect(assistantEvents[2]?.payload.messageId).toBe(
"assistant:item-buffered-request-append:segment:1",
);
expect(assistantEvents[2]?.payload.streaming).toBe(true);
expect(assistantEvents[2]?.payload.text).toBe(" second half");
expect(assistantEvents[3]?.payload.messageId).toBe(
"assistant:item-buffered-request-append:segment:1",
);
expect(assistantEvents[3]?.payload.streaming).toBe(false);
expect(assistantEvents[3]?.payload.text).toBe("");
});
it("starts a new streaming assistant message segment after approval", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const startedAt = "2026-03-28T07:00:00.000Z";
const pausedAt = "2026-03-28T07:00:01.000Z";
const resumedAt = "2026-03-28T07:00:02.000Z";
const completedAt = "2026-03-28T07:00:03.000Z";
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-request-segment"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-streaming-request-segment",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-initial"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
itemId: asItemId("item-streaming-request-segment"),
payload: {
streamKind: "assistant_text",
delta: "before approval",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-streaming-request-segment"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
requestId: ApprovalRequestId.make("req-streaming-request-segment"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment" &&
!message.streaming &&
message.text === "before approval",
),
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-followup"),
provider: "codex",
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
itemId: asItemId("item-streaming-request-segment"),
payload: {
streamKind: "assistant_text",
delta: " after approval",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-streaming-request-segment"),
provider: "codex",
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
itemId: asItemId("item-streaming-request-segment"),
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment:segment:1" &&
!message.streaming &&
message.text === " after approval",
),
);
expect(
thread.messages.find(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment",
)?.text,
).toBe("before approval");
expect(
thread.messages.find(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment:segment:1",
)?.text,
).toBe(" after approval");
});
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const now = new Date().toISOString();
File diff suppressed because it is too large. Load diff
@@ -42,12 +42,7 @@ import {
type UserInputQuestion,
ClaudeAgentEffort,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
resolveApiModelId,
resolveEffort,
trimOrNull,
} from "@t3tools/shared/model";
import { applyClaudePromptEffortPrefix, resolveEffort, trimOrNull } from "@t3tools/shared/model";
import {
Cause,
DateTime,
@@ -66,7 +61,7 @@ import {
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "./ClaudeProvider.ts";
import { getClaudeModelCapabilities, resolveClaudeApiModelId } from "./ClaudeProvider.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -2829,7 +2824,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const caps = getClaudeModelCapabilities(modelSelection?.model);
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
null) as ClaudeAgentEffort | null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
@@ -2853,7 +2848,13 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(apiModelId ? { model: apiModelId } : {}),
pathToClaudeCodeExecutable: claudeBinaryPath,
settingSources: [...CLAUDE_SETTING_SOURCES],
...(effectiveEffort ? { effort: effectiveEffort } : {}),
// The SDK type lags the CLI here: Opus 4.7 accepts `xhigh` even though
// the published `Options["effort"]` union currently stops at `max`.
...(effectiveEffort
? {
effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions["effort"]>,
}
: {}),
...(permissionMode ? { permissionMode } : {}),
...(permissionMode === "bypassPermissions"
? { allowDangerouslySkipPermissions: true }
@@ -3006,7 +3007,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
if (modelSelection?.model) {
const apiModelId = resolveApiModelId(modelSelection);
const apiModelId = resolveClaudeApiModelId(modelSelection);
if (context.currentApiModelId !== apiModelId) {
yield* Effect.tryPromise({
try: () => context.query.setModel(apiModelId),
@@ -1,5 +1,6 @@
import type {
ClaudeSettings,
ClaudeModelSelection,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
@@ -163,6 +164,14 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
switch (modelSelection.options?.contextWindow) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,687 @@
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
buildCursorDiscoveredModelsFromConfigOptions,
discoverCursorModelCapabilitiesViaAcp,
discoverCursorModelsViaAcp,
getCursorFallbackModels,
getCursorParameterizedModelPickerUnsupportedMessage,
parseCursorAboutOutput,
parseCursorCliConfigChannel,
parseCursorVersionDate,
resolveCursorAcpBaseModelId,
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
return wrapperPath;
}
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const content = await readFile(filePath, "utf8");
if (content.trim().length > 0) {
return content;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
const parameterizedGpt54ConfigOptions = [
{
type: "select",
currentValue: "gpt-5.4-medium-fast",
options: [{ name: "GPT-5.4", value: "gpt-5.4-medium-fast" }],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "medium",
options: [
{ name: "None", value: "none" },
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
{ name: "Extra High", value: "extra-high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "select",
currentValue: "272k",
options: [
{ name: "272K", value: "272k" },
{ name: "1M", value: "1m" },
],
category: "model_config",
id: "context",
name: "Context",
},
{
type: "select",
currentValue: "false",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const parameterizedClaudeConfigOptions = [
{
type: "select",
currentValue: "claude-4.6-opus-high-thinking",
options: [{ name: "Opus 4.6", value: "claude-4.6-opus-high-thinking" }],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "high",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "boolean",
currentValue: true,
category: "model_config",
id: "thinking",
name: "Thinking",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const parameterizedClaudeModelOptionConfigOptions = [
{
type: "select",
currentValue: "claude-opus-4-6",
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "high",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "select",
currentValue: "max",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
{ name: "Max", value: "max" },
],
category: "model_option",
id: "effort",
name: "Effort",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: ":icon-brain:", value: "true" },
],
category: "model_config",
id: "thinking",
name: "Thinking",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const sessionNewCursorConfigOptions = [
{
type: "select",
currentValue: "agent",
options: [
{ name: "Agent", value: "agent", description: "Full agent capabilities with tool access" },
],
category: "mode",
id: "mode",
name: "Mode",
description: "Controls how the agent executes tasks",
},
{
type: "select",
currentValue: "composer-2",
options: [
{ name: "Auto", value: "default" },
{ name: "Composer 2", value: "composer-2" },
{ name: "GPT-5.4", value: "gpt-5.4" },
{ name: "Sonnet 4.6", value: "claude-sonnet-4-6" },
{ name: "Opus 4.6", value: "claude-opus-4-6" },
{ name: "Codex 5.3 Spark", value: "gpt-5.3-codex-spark" },
],
category: "model",
id: "model",
name: "Model",
description: "Controls which model is used for responses",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
description: "Faster speeds.",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "agent",
apiEndpoint: "",
customModels: [],
};
const emptyCapabilities = {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
} as const;
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
expect(
getCursorFallbackModels({
customModels: ["internal/cursor-model"],
}).map((model) => model.slug),
).toEqual(["internal/cursor-model"]);
});
});
describe("buildCursorProviderSnapshot", () => {
it("downgrades ready status to warning when ACP model discovery times out", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: baseCursorSettings,
parsed: {
version: "2026.04.09-f2b0fcd",
status: "ready",
auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
},
discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
}),
).toMatchObject({
status: "warning",
message: "Cursor ACP model discovery timed out after 15000ms.",
models: [],
});
});
it("preserves provider error state while appending discovery warnings", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: {
...baseCursorSettings,
customModels: ["claude-sonnet-4-6"],
},
parsed: {
version: "2026.04.09-f2b0fcd",
status: "error",
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
models: [
{
slug: "claude-sonnet-4-6",
isCustom: true,
},
],
});
});
});
describe("buildCursorCapabilitiesFromConfigOptions", () => {
it("derives model capabilities from parameterized Cursor ACP config options", () => {
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual({
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium", isDefault: true },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "272k", label: "272K", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: [],
});
});
it("detects boolean thinking toggles from model_config options", () => {
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual({
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
});
});
it("prefers the newer model_option effort control over legacy thought_level", () => {
expect(
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
).toEqual({
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "max", label: "Max", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
});
});
});
describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
it("publishes ACP model choices immediately from session/new config options", () => {
expect(buildCursorDiscoveredModelsFromConfigOptions(sessionNewCursorConfigOptions)).toEqual([
{
slug: "default",
name: "Auto",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-sonnet-4-6",
name: "Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex-spark",
name: "Codex 5.3 Spark",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]);
});
});
describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await makeMockAgentWrapper();
const models = await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
});
it("closes the ACP probe runtime after discovery completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog).toContain("SIGTERM");
});
});
describe("discoverCursorModelCapabilitiesViaAcp", () => {
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
const existingModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
];
const models = await Effect.runPromise(
discoverCursorModelCapabilitiesViaAcp(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
existingModels,
).pipe(Effect.provide(NodeServices.layer)),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
});
});
describe("parseCursorAboutOutput", () => {
it("parses json about output and forwards subscription metadata", () => {
expect(
parseCursorAboutOutput({
code: 0,
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
subscriptionTier: "Team",
userEmail: "[email protected]",
}),
stderr: "",
}),
).toEqual({
version: "2026.04.09-f2b0fcd",
status: "ready",
auth: {
status: "authenticated",
type: "Team",
label: "Cursor Team Subscription",
},
});
});
it("treats json about output with a logged-out email as unauthenticated", () => {
expect(
parseCursorAboutOutput({
code: 0,
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
subscriptionTier: "Team",
userEmail: "Not logged in",
}),
stderr: "",
}),
).toEqual({
version: "2026.04.09-f2b0fcd",
status: "error",
auth: {
status: "unauthenticated",
},
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
});
});
it("treats json about output with a null email as unauthenticated", () => {
expect(
parseCursorAboutOutput({
code: 0,
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
subscriptionTier: null,
userEmail: null,
}),
stderr: "",
}),
).toEqual({
version: "2026.04.09-f2b0fcd",
status: "error",
auth: {
status: "unauthenticated",
},
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
});
});
});
describe("Cursor parameterized model picker preview gating", () => {
it("parses Cursor CLI version dates from build versions", () => {
expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
});
it("parses the Cursor CLI channel from cli-config.json", () => {
expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
});
it("returns no warning when the preview requirements are met", () => {
expect(
getCursorParameterizedModelPickerUnsupportedMessage({
version: "2026.04.08-c4e73a3",
channel: "lab",
}),
).toBeUndefined();
});
it("explains when the Cursor Agent version is too old", () => {
expect(
getCursorParameterizedModelPickerUnsupportedMessage({
version: "2026.04.07-c4e73a3",
channel: "lab",
}),
).toContain("too old");
});
it("explains when the Cursor Agent channel is not lab", () => {
expect(
getCursorParameterizedModelPickerUnsupportedMessage({
version: "2026.04.08-c4e73a3",
channel: "stable",
}),
).toContain("lab channel");
});
});
describe("resolveCursorAcpBaseModelId", () => {
it("drops bracket traits without rewriting raw ACP model ids", () => {
expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
"claude-4.6-opus-high-thinking",
);
expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
});
});
describe("resolveCursorAcpConfigUpdates", () => {
it("maps Cursor model options onto separate ACP config option updates", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
reasoning: "xhigh",
fastMode: true,
contextWindow: "1m",
}),
).toEqual([
{ configId: "reasoning", value: "extra-high" },
{ configId: "context", value: "1m" },
{ configId: "fast", value: "true" },
]);
});
it("maps boolean thinking toggles when the model exposes them separately", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, {
thinking: false,
}),
).toEqual([{ configId: "thinking", value: false }]);
});
it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
fastMode: false,
}),
).toEqual([{ configId: "fast", value: "false" }]);
});
it("writes Cursor effort changes through the newer model_option config when available", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, {
reasoning: "max",
thinking: false,
}),
).toEqual([
{ configId: "effort", value: "max" },
{ configId: "thinking", value: "false" },
]);
});
});
File diff suppressed because it is too large. Load diff
@@ -8,6 +8,8 @@ import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
@@ -66,6 +68,23 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeCursorAdapter: CursorAdapterShape = {
provider: "cursor",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
@@ -74,6 +93,7 @@ const layer = it.layer(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
NodeServices.layer,
@@ -87,12 +107,14 @@ layer("ProviderAdapterRegistryLive", (it) => {
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
const openCode = yield* registry.getByProvider("opencode");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
assert.equal(openCode, fakeOpenCodeAdapter);
assert.equal(cursor, fakeCursorAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode"]);
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
}),
);
@@ -17,6 +17,7 @@ import {
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
export interface ProviderAdapterRegistryLiveOptions {
@@ -26,10 +27,16 @@ export interface ProviderAdapterRegistryLiveOptions {
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
options?: ProviderAdapterRegistryLiveOptions,
) {
const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter, yield* OpenCodeAdapter];
: [
yield* CodexAdapter,
yield* ClaudeAdapter,
yield* OpenCodeAdapter,
...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []),
];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -30,12 +30,18 @@ import {
readCodexConfigModelProvider,
} from "./CodexProvider.ts";
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry.ts";
import {
haveProvidersChanged,
mergeProviderSnapshot,
ProviderRegistryLive,
} from "./ProviderRegistry.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
process.env.T3CODE_CURSOR_ENABLED = "1";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
@@ -577,10 +583,106 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
});
it.effect("does not probe provider health during registry startup", () =>
it("preserves previously discovered provider models when a refresh returns none", () => {
const previousProvider = {
provider: "cursor",
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-04-14T00:00:00.000Z",
version: "2026.04.09-f2b0fcd",
models: [
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [{ value: "high", label: "High", isDefault: true }],
supportsFastMode: true,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshedProvider = {
...previousProvider,
checkedAt: "2026-04-14T00:01:00.000Z",
models: [],
} satisfies ServerProvider;
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...previousProvider.models,
]);
});
it("fills missing capabilities from the previous provider snapshot", () => {
const previousProvider = {
provider: "cursor",
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-04-14T00:00:00.000Z",
version: "2026.04.09-f2b0fcd",
models: [
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [{ value: "high", label: "High", isDefault: true }],
supportsFastMode: true,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshedProvider = {
...previousProvider,
checkedAt: "2026-04-14T00:01:00.000Z",
models: [
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
} satisfies ServerProvider;
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...previousProvider.models,
]);
});
it.effect("probes enabled providers in the background during registry startup", () =>
Effect.gen(function* () {
let spawnCount = 0;
const serverSettings = yield* makeMutableServerSettingsService();
const serverSettings = yield* makeMutableServerSettingsService(
Schema.decodeSync(ServerSettings)(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
claudeAgent: { enabled: false },
cursor: { enabled: false },
},
}),
),
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
@@ -616,11 +718,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.deepStrictEqual(yield* registry.getProviders, []);
assert.strictEqual(spawnCount, 0);
const refreshed = yield* registry.refresh("codex");
assert.strictEqual(spawnCount > 0, true);
const refreshed = yield* Effect.gen(function* () {
for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {
const providers = yield* registry.getProviders;
const codexProvider = providers.find((provider) => provider.provider === "codex");
if (codexProvider?.status === "ready") {
return providers;
}
yield* Effect.sleep("10 millis");
}
return yield* registry.getProviders;
});
assert.strictEqual(
refreshed.find((provider) => provider.provider === "codex")?.status,
"ready",
@@ -657,6 +766,19 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
}
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
}
if (joined === "about --format json") {
return {
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
userEmail: null,
}),
stderr: "",
code: 0,
};
}
if (joined === "about") {
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
}
if (joined === "login status") {
return { stdout: "Logged in\n", stderr: "", code: 0 };
}
@@ -671,9 +793,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const initial = yield* registry.getProviders;
assert.deepStrictEqual(initial, []);
const refreshed = yield* registry.refresh("codex");
assert.strictEqual(
refreshed.find((status) => status.provider === "codex")?.status,
@@ -705,6 +824,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
}),
);
it.effect(
"keeps cursor disabled and skips probing when the provider setting is disabled",
() =>
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
Schema.decodeSync(ServerSettings)(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
cursor: {
enabled: false,
},
},
}),
),
);
let cursorSpawned = false;
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
if (command === "agent") {
cursorSpawned = true;
}
const joined = args.join(" ");
if (joined === "--version") {
return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 };
}
if (joined === "login status") {
return { stdout: "Logged in\n", stderr: "", code: 0 };
}
if (joined === "auth status") {
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
}
throw new Error(`Unexpected args: ${command} ${joined}`);
}),
),
);
const runtimeServices = yield* Layer.build(
Layer.mergeAll(
Layer.succeed(ServerSettingsService, serverSettings),
providerRegistryLayer,
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const providers = yield* registry.getProviders;
const cursorProvider = providers.find((provider) => provider.provider === "cursor");
assert.deepStrictEqual(
providers.map((provider) => provider.provider),
["codex", "claudeAgent", "opencode", "cursor"],
);
assert.strictEqual(cursorProvider?.enabled, false);
assert.strictEqual(cursorProvider?.status, "disabled");
assert.strictEqual(
cursorProvider?.message,
"Cursor is disabled in T3 Code settings.",
);
assert.strictEqual(cursorSpawned, false);
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect("skips codex probes entirely when the provider is disabled", () =>
Effect.gen(function* () {
const serverSettingsLayer = ServerSettingsService.layerTest({
@@ -9,12 +9,11 @@ import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "eff
import { ServerConfig } from "../../config.ts";
import { ClaudeProviderLive } from "./ClaudeProvider.ts";
import { CodexProviderLive } from "./CodexProvider.ts";
import { CursorProviderLive } from "./CursorProvider.ts";
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
import type { ClaudeProviderShape } from "../Services/ClaudeProvider.ts";
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
import type { CodexProviderShape } from "../Services/CodexProvider.ts";
import { CodexProvider } from "../Services/CodexProvider.ts";
import type { OpenCodeProviderShape } from "../Services/OpenCodeProvider.ts";
import { CursorProvider } from "../Services/CursorProvider.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
import {
@@ -26,24 +25,67 @@ import {
writeProviderStatusCache,
} from "../providerStatusCache.ts";
type ProviderSnapshotSource = {
readonly provider: ProviderKind;
readonly getSnapshot: Effect.Effect<ServerProvider>;
readonly refresh: Effect.Effect<ServerProvider>;
readonly streamChanges: Stream.Stream<ServerProvider>;
};
const loadProviders = (
codexProvider: CodexProviderShape,
claudeProvider: ClaudeProviderShape,
openCodeProvider: OpenCodeProviderShape,
): Effect.Effect<readonly [ServerProvider, ServerProvider, ServerProvider]> =>
Effect.all(
[codexProvider.getSnapshot, claudeProvider.getSnapshot, openCodeProvider.getSnapshot],
{
concurrency: "unbounded",
},
);
providerSources: ReadonlyArray<ProviderSnapshotSource>,
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
Effect.forEach(providerSources, (providerSource) => providerSource.getSnapshot, {
concurrency: "unbounded",
});
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
(model.capabilities?.reasoningEffortLevels.length ?? 0) > 0 ||
model.capabilities?.supportsFastMode === true ||
model.capabilities?.supportsThinkingToggle === true ||
(model.capabilities?.contextWindowOptions.length ?? 0) > 0 ||
(model.capabilities?.promptInjectedEffortLevels.length ?? 0) > 0;
const mergeProviderModels = (
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
): ReadonlyArray<ServerProvider["models"][number]> => {
if (nextModels.length === 0 && previousModels.length > 0) {
return previousModels;
}
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
const mergedModels = nextModels.map((model) => {
const previousModel = previousBySlug.get(model.slug);
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
return model;
}
return {
...model,
capabilities: previousModel.capabilities,
};
});
const nextSlugs = new Set(nextModels.map((model) => model.slug));
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
};
export const mergeProviderSnapshot = (
previousProvider: ServerProvider | undefined,
nextProvider: ServerProvider,
): ServerProvider =>
!previousProvider
? nextProvider
: {
...nextProvider,
models: mergeProviderModels(previousProvider.models, nextProvider.models),
};
export const haveProvidersChanged = (
previousProviders: ReadonlyArray<ServerProvider>,
nextProviders: ReadonlyArray<ServerProvider>,
): boolean => !Equal.equals(previousProviders, nextProviders);
export const ProviderRegistryLive = Layer.effect(
const ProviderRegistryLiveBase = Layer.effect(
ProviderRegistry,
Effect.gen(function* () {
const codexProvider = yield* CodexProvider;
@@ -52,13 +94,43 @@ export const ProviderRegistryLive = Layer.effect(
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cursorProvider = yield* CursorProvider;
const providerSources = [
{
provider: "codex",
getSnapshot: codexProvider.getSnapshot,
refresh: codexProvider.refresh,
streamChanges: codexProvider.streamChanges,
},
{
provider: "claudeAgent",
getSnapshot: claudeProvider.getSnapshot,
refresh: claudeProvider.refresh,
streamChanges: claudeProvider.streamChanges,
},
{
provider: "opencode",
getSnapshot: openCodeProvider.getSnapshot,
refresh: openCodeProvider.refresh,
streamChanges: openCodeProvider.streamChanges,
},
{
provider: "cursor",
getSnapshot: cursorProvider.getSnapshot,
refresh: cursorProvider.refresh,
streamChanges: cursorProvider.streamChanges,
},
] satisfies ReadonlyArray<ProviderSnapshotSource>;
const activeProviders = PROVIDER_CACHE_IDS;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
PubSub.shutdown,
);
const fallbackProviders = yield* loadProviders(codexProvider, claudeProvider, openCodeProvider);
const fallbackProviders = yield* loadProviders(providerSources);
const cachePathByProvider = new Map(
PROVIDER_CACHE_IDS.map(
activeProviders.map(
(provider) =>
[
provider,
@@ -72,8 +144,9 @@ export const ProviderRegistryLive = Layer.effect(
const fallbackByProvider = new Map(
fallbackProviders.map((provider) => [provider.provider, provider] as const),
);
const cachedProviders = yield* Effect.forEach(
PROVIDER_CACHE_IDS,
activeProviders,
(provider) => {
const filePath = cachePathByProvider.get(provider)!;
const fallbackProvider = fallbackByProvider.get(provider)!;
@@ -124,7 +197,10 @@ export const ProviderRegistryLive = Layer.effect(
);
for (const provider of nextProviders) {
mergedProviders.set(provider.provider, provider);
mergedProviders.set(
provider.provider,
mergeProviderSnapshot(mergedProviders.get(provider.provider), provider),
);
}
const providers = orderProviderSnapshots([...mergedProviders.values()]);
@@ -155,49 +231,40 @@ export const ProviderRegistryLive = Layer.effect(
});
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
switch (provider) {
case "codex":
return yield* codexProvider.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
);
case "claudeAgent":
return yield* claudeProvider.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
);
case "opencode":
return yield* openCodeProvider.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
);
default:
return yield* Effect.all(
[
codexProvider.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
),
claudeProvider.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
),
openCodeProvider.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
),
],
{
concurrency: "unbounded",
discard: true,
},
).pipe(Effect.andThen(Ref.get(providersRef)));
if (provider) {
const providerSource = providerSources.find((candidate) => candidate.provider === provider);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* providerSource.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
);
}
return yield* Effect.forEach(
providerSources,
(providerSource) => providerSource.refresh.pipe(Effect.flatMap(syncProvider)),
{
concurrency: "unbounded",
discard: true,
},
).pipe(Effect.andThen(Ref.get(providersRef)));
});
yield* Stream.runForEach(codexProvider.streamChanges, (provider) =>
syncProvider(provider),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(claudeProvider.streamChanges, (provider) =>
syncProvider(provider),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(openCodeProvider.streamChanges, (provider) =>
syncProvider(provider),
).pipe(Effect.forkScoped);
yield* Effect.forEach(
providerSources,
(providerSource) =>
Stream.runForEach(providerSource.streamChanges, (provider) => syncProvider(provider)).pipe(
Effect.forkScoped,
),
{
concurrency: "unbounded",
discard: true,
},
);
yield* loadProviders(providerSources).pipe(
Effect.flatMap((providers) => upsertProviders(providers, { publish: false })),
);
return {
getProviders: Ref.get(providersRef),
@@ -211,8 +278,15 @@ export const ProviderRegistryLive = Layer.effect(
},
} satisfies ProviderRegistryShape;
}),
).pipe(
Layer.provideMerge(CodexProviderLive),
Layer.provideMerge(ClaudeProviderLive),
Layer.provideMerge(OpenCodeProviderLive),
);
export const ProviderRegistryLive = Layer.unwrap(
Effect.sync(() =>
ProviderRegistryLiveBase.pipe(
Layer.provideMerge(CursorProviderLive),
Layer.provideMerge(CodexProviderLive),
Layer.provideMerge(ClaudeProviderLive),
Layer.provideMerge(OpenCodeProviderLive),
),
),
);
@@ -245,14 +245,17 @@ const hasMetricSnapshot = (
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
const cursor = makeFakeCodexAdapter("cursor");
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(codex.adapter)
: provider === "claudeAgent"
? Effect.succeed(claude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
: provider === "cursor"
? Effect.succeed(cursor.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeAgent", "cursor"]),
};
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
@@ -279,6 +282,7 @@ function makeProviderServiceLayer() {
return {
codex,
claude,
cursor,
layer,
};
}
@@ -1,5 +1,5 @@
import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import { ProviderKind, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer, Option, Schema } from "effect";
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
@@ -24,14 +24,15 @@ function decodeProviderKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
if (providerName === "codex" || providerName === "claudeAgent" || providerName === "opencode") {
return Effect.succeed(providerName);
}
return Effect.fail(
new ProviderSessionDirectoryPersistenceError({
operation,
detail: `Unknown persisted provider '${providerName}'.`,
}),
return Schema.decodeUnknownEffect(ProviderKind)(providerName).pipe(
Effect.mapError(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation,
detail: `Unknown persisted provider '${providerName}'.`,
cause,
}),
),
);
}
@@ -0,0 +1,12 @@
import { Context } from "effect";
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
readonly provider: "cursor";
}
export class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
"t3/provider/Services/CursorAdapter",
) {}
@@ -0,0 +1,9 @@
import { Context } from "effect";
import type { ServerProviderShape } from "./ServerProvider.ts";
export interface CursorProviderShape extends ServerProviderShape {}
export class CursorProvider extends Context.Service<CursorProvider, CursorProviderShape>()(
"t3/provider/Services/CursorProvider",
) {}
@@ -23,7 +23,7 @@ import type {
import type { Effect } from "effect";
import type { Stream } from "effect";
export type ProviderSessionModelSwitchMode = "in-session" | "restart-session" | "unsupported";
export type ProviderSessionModelSwitchMode = "in-session" | "unsupported";
export interface ProviderAdapterCapabilities {
/**
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import * as EffectAcpErrors from "effect-acp/errors";
import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";
describe("AcpAdapterSupport", () => {
it("maps ACP approval decisions to permission outcomes", () => {
expect(acpPermissionOutcome("accept")).toBe("allow-once");
expect(acpPermissionOutcome("acceptForSession")).toBe("allow-always");
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",
}),
);
expect(error._tag).toBe("ProviderAdapterRequestError");
expect(error.message).toContain("Invalid params");
});
});
@@ -0,0 +1,54 @@
import {
type ProviderApprovalDecision,
type ProviderKind,
type ThreadId,
} from "@t3tools/contracts";
import { Schema } from "effect";
import * as EffectAcpErrors from "effect-acp/errors";
import {
ProviderAdapterRequestError,
ProviderAdapterSessionClosedError,
type ProviderAdapterError,
} from "../Errors.ts";
export function mapAcpToAdapterError(
provider: ProviderKind,
threadId: ThreadId,
method: string,
error: EffectAcpErrors.AcpError,
): ProviderAdapterError {
if (Schema.is(EffectAcpErrors.AcpProcessExitedError)(error)) {
return new ProviderAdapterSessionClosedError({
provider,
threadId,
cause: error,
});
}
if (Schema.is(EffectAcpErrors.AcpRequestError)(error)) {
return new ProviderAdapterRequestError({
provider,
method,
detail: error.message,
cause: error,
});
}
return new ProviderAdapterRequestError({
provider,
method,
detail: error.message,
cause: error,
});
}
export function acpPermissionOutcome(decision: ProviderApprovalDecision): string {
switch (decision) {
case "acceptForSession":
return "allow-always";
case "accept":
return "allow-once";
case "decline":
default:
return "reject-once";
}
}
@@ -0,0 +1,155 @@
import { RuntimeRequestId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
makeAcpAssistantItemEvent,
makeAcpContentDeltaEvent,
makeAcpPlanUpdatedEvent,
makeAcpRequestOpenedEvent,
makeAcpRequestResolvedEvent,
makeAcpToolCallEvent,
} from "./AcpCoreRuntimeEvents.ts";
describe("AcpCoreRuntimeEvents", () => {
it("maps ACP permission requests to canonical runtime events", () => {
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
const turnId = TurnId.make("turn-1");
const permissionRequest = {
kind: "execute" as const,
detail: "cat package.json",
toolCall: {
toolCallId: "tool-1",
kind: "execute",
status: "pending" as const,
command: "cat package.json",
detail: "cat package.json",
data: { toolCallId: "tool-1", kind: "execute" },
},
};
expect(
makeAcpRequestOpenedEvent({
stamp,
provider: "cursor",
threadId: "thread-1" as never,
turnId,
requestId: RuntimeRequestId.make("request-1"),
permissionRequest,
detail: "cat package.json",
args: { command: ["cat", "package.json"] },
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: { sessionId: "session-1" },
}),
).toMatchObject({
type: "request.opened",
payload: {
requestType: "exec_command_approval",
detail: "cat package.json",
},
});
expect(
makeAcpRequestResolvedEvent({
stamp,
provider: "cursor",
threadId: "thread-1" as never,
turnId,
requestId: RuntimeRequestId.make("request-1"),
permissionRequest,
decision: "accept",
}),
).toMatchObject({
type: "request.resolved",
payload: {
requestType: "exec_command_approval",
decision: "accept",
},
});
});
it("maps ACP core plan, tool-call, and content updates", () => {
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
const turnId = TurnId.make("turn-1");
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",
kind: "execute",
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,
itemId: "assistant:session-1:segment:0",
text: "hello",
rawPayload: { sessionId: "session-1" },
}),
).toMatchObject({
type: "content.delta",
itemId: "assistant:session-1:segment:0",
payload: {
delta: "hello",
},
});
expect(
makeAcpAssistantItemEvent({
stamp,
provider: "cursor",
threadId: "thread-1" as never,
turnId,
itemId: "assistant:session-1:segment:0",
lifecycle: "item.started",
}),
).toMatchObject({
type: "item.started",
itemId: "assistant:session-1:segment:0",
payload: {
itemType: "assistant_message",
status: "inProgress",
},
});
});
});
@@ -0,0 +1,242 @@
import {
type RuntimeEventRawSource,
RuntimeItemId,
type CanonicalRequestType,
type EventId,
type ProviderApprovalDecision,
type ProviderKind,
type ProviderRuntimeEvent,
type RuntimeRequestId,
type ThreadId,
type ToolLifecycleItemType,
type TurnId,
} from "@t3tools/contracts";
import type { AcpPermissionRequest, AcpPlanUpdate, AcpToolCallState } from "./AcpRuntimeModel.ts";
type AcpAdapterRawSource = Extract<
RuntimeEventRawSource,
"acp.jsonrpc" | `acp.${string}.extension`
>;
interface AcpEventStamp {
readonly eventId: EventId;
readonly createdAt: string;
}
type AcpCanonicalRequestType = Extract<
CanonicalRequestType,
"exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown"
>;
function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonicalRequestType {
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 canonicalItemTypeFromAcpToolKind(kind: string | undefined): 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 runtimeItemStatusFromAcpToolStatus(
status: AcpToolCallState["status"],
): "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 makeAcpRequestOpenedEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly requestId: RuntimeRequestId;
readonly permissionRequest: AcpPermissionRequest;
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: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),
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 permissionRequest: AcpPermissionRequest;
readonly decision: ProviderApprovalDecision;
}): ProviderRuntimeEvent {
return {
type: "request.resolved",
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
requestId: input.requestId,
payload: {
requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),
decision: input.decision,
},
};
}
export function makeAcpPlanUpdatedEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly payload: AcpPlanUpdate;
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 = runtimeItemStatusFromAcpToolStatus(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.make(input.toolCall.toolCallId),
payload: {
itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind),
...(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 makeAcpAssistantItemEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly itemId: string;
readonly lifecycle: "item.started" | "item.completed";
}): ProviderRuntimeEvent {
return {
type: input.lifecycle,
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
itemId: RuntimeItemId.make(input.itemId),
payload: {
itemType: "assistant_message",
status: input.lifecycle === "item.completed" ? "completed" : "inProgress",
},
};
}
export function makeAcpContentDeltaEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly itemId?: string;
readonly text: string;
readonly rawPayload: unknown;
}): ProviderRuntimeEvent {
return {
type: "content.delta",
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
payload: {
streamKind: "assistant_text",
delta: input.text,
},
raw: {
source: "acp.jsonrpc",
method: "session/update",
payload: input.rawPayload,
},
};
}
@@ -0,0 +1,395 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Stream } from "effect";
import { describe, expect } from "vitest";
import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
import type * as EffectAcpProtocol from "effect-acp/protocol";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const bunExe = "bun";
describe("AcpSessionRuntime", () => {
it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
const initializeStarted = requestEvents.find(
(event) => event.method === "initialize" && event.status === "started",
);
expect(initializeStarted?.payload).toMatchObject({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
_meta: { parameterizedModelPicker: true },
},
});
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientCapabilities: {
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
requestLogger: (event) =>
Effect.sync(() => {
requestEvents.push(event);
}),
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
expect(started.sessionId).toBe("mock-session-1");
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes).toHaveLength(4);
expect(notes.map((note) => note._tag)).toEqual([
"PlanUpdated",
"AssistantItemStarted",
"ContentDelta",
"AssistantItemCompleted",
]);
const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
expect(planUpdate?._tag).toBe("PlanUpdated");
if (planUpdate?._tag === "PlanUpdated") {
expect(planUpdate.payload.plan).toHaveLength(2);
}
const assistantStart = notes[1];
const assistantDelta = notes[2];
if (
assistantStart?._tag === "AssistantItemStarted" &&
assistantDelta?._tag === "ContentDelta"
) {
expect(assistantDelta.itemId).toBe(assistantStart.itemId);
}
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("segments assistant text around ACP tool calls", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
expect(notes.map((note) => note._tag)).toEqual([
"AssistantItemStarted",
"ContentDelta",
"AssistantItemCompleted",
"ToolCallUpdated",
"ToolCallUpdated",
"AssistantItemStarted",
"ContentDelta",
]);
const firstStarted = notes[0];
const firstDelta = notes[1];
const firstCompleted = notes[2];
const secondStarted = notes[5];
const secondDelta = notes[6];
expect(firstStarted?._tag).toBe("AssistantItemStarted");
expect(firstCompleted?._tag).toBe("AssistantItemCompleted");
expect(secondStarted?._tag).toBe("AssistantItemStarted");
if (
firstStarted?._tag === "AssistantItemStarted" &&
firstDelta?._tag === "ContentDelta" &&
firstCompleted?._tag === "AssistantItemCompleted" &&
secondStarted?._tag === "AssistantItemStarted" &&
secondDelta?._tag === "ContentDelta"
) {
expect(firstDelta.itemId).toBe(firstStarted.itemId);
expect(firstCompleted.itemId).toBe(firstStarted.itemId);
expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
expect(secondDelta.itemId).toBe(secondStarted.itemId);
}
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: bunExe,
args: [mockAgentPath],
env: {
T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("suppresses generic placeholder tool updates until completion", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 1)));
expect(notes.map((note) => note._tag)).toEqual(["ToolCallUpdated"]);
const toolCall = notes[0];
expect(toolCall?._tag).toBe("ToolCallUpdated");
if (toolCall?._tag === "ToolCallUpdated") {
expect(toolCall.toolCall.status).toBe("completed");
expect(toolCall.toolCall.title).toBe("Read file");
}
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: bunExe,
args: [mockAgentPath],
env: {
T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("logs ACP requests from the shared runtime", () => {
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.setModel("composer-2");
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(
requestEvents.some(
(event) => event.method === "session/set_config_option" && event.status === "started",
),
).toBe(true);
expect(
requestEvents.some(
(event) => event.method === "session/set_config_option" && event.status === "succeeded",
),
).toBe(true);
expect(
requestEvents.some(
(event) => event.method === "session/prompt" && event.status === "started",
),
).toBe(true);
expect(
requestEvents.some(
(event) => event.method === "session/prompt" && event.status === "succeeded",
),
).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
requestLogger: (event) =>
Effect.sync(() => {
requestEvents.push(event);
}),
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("skips no-op session config writes when the requested value is already active", () => {
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.setConfigOption("model", "default");
yield* runtime.setMode("ask");
expect(
requestEvents.some(
(event) => event.method === "session/set_config_option" && event.status === "started",
),
).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
requestLogger: (event) =>
Effect.sync(() => {
requestEvents.push(event);
}),
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(
protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "raw"),
).toBe(true);
expect(
protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "decoded"),
).toBe(true);
expect(
protocolEvents.some((event) => event.direction === "incoming" && event.stage === "raw"),
).toBe(true);
expect(
protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event) =>
Effect.sync(() => {
protocolEvents.push(event);
}),
},
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
const requestLogPath = path.join(tempDir, "requests.ndjson");
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
expect(error._tag).toBe("AcpRequestError");
if (error._tag === "AcpRequestError") {
expect(error.code).toBe(-32602);
expect(error.message).toContain(
'Invalid value "composer-2[fast=false]" for session config option "model"',
);
expect(error.message).toContain("composer-2[fast=true]");
}
const recordedRequests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: { value?: unknown } });
expect(
recordedRequests.some(
(message) =>
message.method === "session/set_config_option" &&
message.params?.value === "composer-2[fast=false]",
),
).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
env: {
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
Effect.ensuring(Effect.sync(() => rmSync(tempDir, { recursive: true, force: true }))),
);
});
});
@@ -0,0 +1,76 @@
import type { ProviderKind, ThreadId } from "@t3tools/contracts";
import { Cause, Effect } from "effect";
import type * as EffectAcpProtocol from "effect-acp/protocol";
import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
import type { AcpSessionRequestLogEvent, AcpSessionRuntimeOptions } from "./AcpSessionRuntime.ts";
function writeNativeAcpLog(input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly kind: "request" | "protocol";
readonly payload: unknown;
}): Effect.Effect<void, never> {
return Effect.gen(function* () {
if (!input.nativeEventLogger) return;
const observedAt = new Date().toISOString();
yield* input.nativeEventLogger.write(
{
observedAt,
event: {
id: crypto.randomUUID(),
kind: input.kind,
provider: input.provider,
createdAt: observedAt,
threadId: input.threadId,
payload: input.payload,
},
},
input.threadId,
);
});
}
function formatRequestLogPayload(event: AcpSessionRequestLogEvent) {
return {
method: event.method,
status: event.status,
request: event.payload,
...(event.result !== undefined ? { result: event.result } : {}),
...(event.cause !== undefined ? { cause: Cause.pretty(event.cause) } : {}),
};
}
export function makeAcpNativeLoggers(input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
}): Pick<AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> {
return {
requestLogger: (event) =>
writeNativeAcpLog({
nativeEventLogger: input.nativeEventLogger,
provider: input.provider,
threadId: input.threadId,
kind: "request",
payload: formatRequestLogPayload(event),
}),
...(input.nativeEventLogger
? {
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
writeNativeAcpLog({
nativeEventLogger: input.nativeEventLogger,
provider: input.provider,
threadId: input.threadId,
kind: "protocol",
payload: event,
}),
} satisfies NonNullable<AcpSessionRuntimeOptions["protocolLogging"]>,
}
: {}),
};
}
@@ -0,0 +1,286 @@
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import {
extractModelConfigId,
mergeToolCallState,
parsePermissionRequest,
parseSessionModeState,
parseSessionUpdateEvent,
} from "./AcpRuntimeModel.ts";
describe("AcpRuntimeModel", () => {
it("parses session mode state from typed ACP session setup responses", () => {
const modeState = parseSessionModeState({
sessionId: "session-1",
modes: {
currentModeId: " code ",
availableModes: [
{ id: " ask ", name: " Ask ", description: " Request approval " },
{ id: " code ", name: " Code " },
],
},
configOptions: [],
} satisfies EffectAcpSchema.NewSessionResponse);
expect(modeState).toEqual({
currentModeId: "code",
availableModes: [
{ id: "ask", name: "Ask", description: "Request approval" },
{ id: "code", name: "Code" },
],
});
});
it("extracts the model config id from typed ACP config options", () => {
const modelConfigId = extractModelConfigId({
sessionId: "session-1",
configOptions: [
{
id: "approval",
name: "Approval Mode",
category: "permission",
type: "select",
currentValue: "ask",
options: [{ value: "ask", name: "Ask" }],
},
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: "default",
options: [{ value: "default", name: "Auto" }],
},
],
} satisfies EffectAcpSchema.NewSessionResponse);
expect(modelConfigId).toBe("model");
});
it("projects typed ACP tool call updates into runtime events", () => {
const created = parseSessionUpdateEvent({
sessionId: "session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-1",
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
executable: "bun",
args: ["run", "typecheck"],
},
content: [
{
type: "content",
content: {
type: "text",
text: "Running checks",
},
},
],
},
} satisfies EffectAcpSchema.SessionNotification);
expect(created.events).toEqual([
{
_tag: "ToolCallUpdated",
toolCall: {
toolCallId: "tool-1",
kind: "execute",
title: "Ran command",
status: "pending",
command: "bun run typecheck",
detail: "bun run typecheck",
data: {
toolCallId: "tool-1",
kind: "execute",
command: "bun run typecheck",
rawInput: {
executable: "bun",
args: ["run", "typecheck"],
},
content: [
{
type: "content",
content: {
type: "text",
text: "Running checks",
},
},
],
},
},
rawPayload: {
sessionId: "session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-1",
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
executable: "bun",
args: ["run", "typecheck"],
},
content: [
{
type: "content",
content: {
type: "text",
text: "Running checks",
},
},
],
},
},
},
]);
const updated = parseSessionUpdateEvent({
sessionId: "session-1",
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-1",
status: "completed",
rawOutput: { exitCode: 0 },
},
} satisfies EffectAcpSchema.SessionNotification);
expect(updated.events).toHaveLength(1);
expect(updated.events[0]?._tag).toBe("ToolCallUpdated");
const createdEvent = created.events[0];
const updatedEvent = updated.events[0];
if (createdEvent?._tag === "ToolCallUpdated" && updatedEvent?._tag === "ToolCallUpdated") {
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",
update: {
sessionUpdate: "plan",
entries: [
{ content: " Inspect state ", priority: "high", status: "completed" },
{ content: "", priority: "medium", status: "in_progress" },
],
},
} satisfies EffectAcpSchema.SessionNotification);
expect(planResult.events).toEqual([
{
_tag: "PlanUpdated",
payload: {
plan: [
{ step: "Inspect state", status: "completed" },
{ step: "Step 2", status: "inProgress" },
],
},
rawPayload: {
sessionId: "session-1",
update: {
sessionUpdate: "plan",
entries: [
{ content: " Inspect state ", priority: "high", status: "completed" },
{ content: "", priority: "medium", status: "in_progress" },
],
},
},
},
]);
const contentResult = parseSessionUpdateEvent({
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: "hello from acp",
},
},
} satisfies EffectAcpSchema.SessionNotification);
expect(contentResult.events).toEqual([
{
_tag: "ContentDelta",
text: "hello from acp",
rawPayload: {
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: "hello from acp",
},
},
},
},
]);
});
it("keeps permission request parsing compatible with loose extension payloads", () => {
const request = parsePermissionRequest({
sessionId: "session-1",
options: [
{
optionId: "allow-once",
name: "Allow once",
kind: "allow_once",
},
],
toolCall: {
toolCallId: "tool-1",
title: "`cat package.json`",
kind: "execute",
status: "pending",
content: [
{
type: "content",
content: {
type: "text",
text: "Not in allowlist",
},
},
],
},
});
expect(request).toMatchObject({
kind: "execute",
detail: "cat package.json",
toolCall: {
toolCallId: "tool-1",
kind: "execute",
status: "pending",
command: "cat package.json",
},
});
});
});
@@ -0,0 +1,482 @@
import type * as EffectAcpSchema from "effect-acp/schema";
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
import type { ToolLifecycleItemType } from "@t3tools/contracts";
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export interface AcpSessionMode {
readonly id: string;
readonly name: string;
readonly description?: string;
}
export interface AcpSessionModeState {
readonly currentModeId: string;
readonly availableModes: ReadonlyArray<AcpSessionMode>;
}
export interface AcpToolCallState {
readonly toolCallId: string;
readonly kind?: string;
readonly title?: string;
readonly status?: "pending" | "inProgress" | "completed" | "failed";
readonly command?: string;
readonly detail?: string;
readonly data: Record<string, unknown>;
}
export interface AcpPlanUpdate {
readonly explanation?: string | null;
readonly plan: ReadonlyArray<{
readonly step: string;
readonly status: "pending" | "inProgress" | "completed";
}>;
}
export interface AcpPermissionRequest {
readonly kind: string | "unknown";
readonly detail?: string;
readonly toolCall?: AcpToolCallState;
}
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;
readonly rawPayload: unknown;
}
| {
readonly _tag: "ToolCallUpdated";
readonly toolCall: AcpToolCallState;
readonly rawPayload: unknown;
}
| {
readonly _tag: "ContentDelta";
readonly itemId?: string;
readonly text: string;
readonly rawPayload: unknown;
};
type AcpSessionSetupResponse =
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
type AcpToolCallUpdate = Extract<
EffectAcpSchema.SessionNotification["update"],
{ readonly sessionUpdate: "tool_call" | "tool_call_update" }
>;
export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
const configOptions = sessionResponse.configOptions;
if (!configOptions) return undefined;
for (const opt of configOptions) {
if (opt.category === "model" && opt.id.trim().length > 0) {
return opt.id.trim();
}
}
return undefined;
}
export function findSessionConfigOption(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
configId: string,
): EffectAcpSchema.SessionConfigOption | undefined {
if (!configOptions) {
return undefined;
}
const normalizedConfigId = configId.trim();
if (!normalizedConfigId) {
return undefined;
}
return configOptions.find((option) => option.id.trim() === normalizedConfigId);
}
export function collectSessionConfigOptionValues(
configOption: EffectAcpSchema.SessionConfigOption,
): ReadonlyArray<string> {
if (configOption.type !== "select") {
return [];
}
return configOption.options.flatMap((entry) =>
"value" in entry ? [entry.value] : entry.options.map((option) => option.value),
);
}
export function parseSessionModeState(
sessionResponse: AcpSessionSetupResponse,
): AcpSessionModeState | undefined {
const modes = sessionResponse.modes;
if (!modes) return undefined;
const currentModeId = modes.currentModeId.trim();
if (!currentModeId) {
return undefined;
}
const availableModes = modes.availableModes
.map((mode) => {
const id = mode.id.trim();
const name = mode.name.trim();
if (!id || !name) {
return undefined;
}
const description = 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 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 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: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
): string | undefined {
if (!content) return undefined;
const chunks = content
.map((entry) => {
if (entry.type !== "content") {
return undefined;
}
const nestedContent = entry.content;
if (nestedContent.type !== "text") {
return undefined;
}
return 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 normalizeToolKind(kind: unknown): string | undefined {
return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
}
function canonicalItemTypeFromAcpToolKind(kind: string | undefined): 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 makeToolCallState(
input: {
readonly toolCallId: string;
readonly title?: string | null | undefined;
readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
readonly rawInput?: unknown;
readonly rawOutput?: unknown;
readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
},
options?: {
readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
},
): AcpToolCallState | undefined {
const toolCallId = input.toolCallId.trim();
if (!toolCallId) {
return undefined;
}
const title = input.title?.trim() || undefined;
const command = extractToolCallCommand(input.rawInput, title);
const textContent = extractTextContentFromToolCallContent(input.content);
const normalizedTitle =
title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
? title
: undefined;
const data: Record<string, unknown> = { toolCallId };
const kind = normalizeToolKind(input.kind);
if (kind) {
data.kind = kind;
}
if (command) {
data.command = command;
}
if (input.rawInput !== undefined) {
data.rawInput = input.rawInput;
}
if (input.rawOutput !== undefined) {
data.rawOutput = input.rawOutput;
}
if (input.content !== undefined) {
data.content = input.content;
}
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 } : {}),
...(status ? { status } : {}),
...(command ? { command } : {}),
...(presentation?.detail ? { detail: presentation.detail } : {}),
data,
};
}
function parseTypedToolCallState(
event: AcpToolCallUpdate,
options?: {
readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
},
): AcpToolCallState | undefined {
return makeToolCallState(
{
toolCallId: event.toolCallId,
title: event.title,
kind: event.kind,
status: event.status,
rawInput: event.rawInput,
rawOutput: event.rawOutput,
content: event.content,
locations: event.locations,
},
options,
);
}
export function mergeToolCallState(
previous: AcpToolCallState | undefined,
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 } : {}),
...(title ? { title } : {}),
...(status ? { status } : {}),
...(command ? { command } : {}),
...(detail ? { detail } : {}),
data: {
...previous?.data,
...next.data,
},
};
}
export function parsePermissionRequest(
params: EffectAcpSchema.RequestPermissionRequest,
): AcpPermissionRequest {
const toolCall = makeToolCallState(
{
toolCallId: params.toolCall.toolCallId,
title: params.toolCall.title,
kind: params.toolCall.kind,
status: params.toolCall.status,
rawInput: params.toolCall.rawInput,
rawOutput: params.toolCall.rawOutput,
content: params.toolCall.content,
locations: params.toolCall.locations,
},
{ fallbackStatus: "pending" },
);
const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
const detail =
toolCall?.command ??
toolCall?.title ??
toolCall?.detail ??
(typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
return {
kind,
...(detail ? { detail } : {}),
...(toolCall ? { toolCall } : {}),
};
}
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
readonly modeId?: string;
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
} {
const upd = params.update;
const events: Array<AcpParsedSessionEvent> = [];
let modeId: string | undefined;
switch (upd.sessionUpdate) {
case "current_mode_update": {
modeId = upd.currentModeId.trim();
if (modeId) {
events.push({
_tag: "ModeChanged",
modeId,
});
}
break;
}
case "plan": {
const plan = upd.entries.map((entry, index) => ({
step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
status: normalizePlanStepStatus(entry.status),
}));
if (plan.length > 0) {
events.push({
_tag: "PlanUpdated",
payload: {
plan,
},
rawPayload: params,
});
}
break;
}
case "tool_call": {
const toolCall = parseTypedToolCallState(upd, {
fallbackStatus: "pending",
});
if (toolCall) {
events.push({
_tag: "ToolCallUpdated",
toolCall,
rawPayload: params,
});
}
break;
}
case "tool_call_update": {
const toolCall = parseTypedToolCallState(upd);
if (toolCall) {
events.push({
_tag: "ToolCallUpdated",
toolCall,
rawPayload: params,
});
}
break;
}
case "agent_message_chunk": {
if (upd.content.type === "text" && upd.content.text.length > 0) {
events.push({
_tag: "ContentDelta",
text: upd.content.text,
rawPayload: params,
});
}
break;
}
default:
break;
}
return { ...(modeId !== undefined ? { modeId } : {}), events };
}
@@ -0,0 +1,722 @@
import { Cause, Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Context, 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,
type AcpParsedSessionEvent,
type AcpSessionModeState,
type AcpToolCallState,
} from "./AcpRuntimeModel.ts";
export interface AcpSpawnInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string;
readonly env?: Readonly<Record<string, string>>;
}
export interface AcpSessionRuntimeOptions {
readonly spawn: AcpSpawnInput;
readonly cwd: string;
readonly resumeSessionId?: string;
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
readonly clientInfo: {
readonly name: string;
readonly version: string;
};
readonly authMethodId: string;
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
readonly protocolLogging?: {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
};
}
export interface AcpSessionRequestLogEvent {
readonly method: string;
readonly payload: unknown;
readonly status: "started" | "succeeded" | "failed";
readonly result?: unknown;
readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
}
export interface AcpSessionRuntimeStartResult {
readonly sessionId: string;
readonly initializeResult: EffectAcpSchema.InitializeResponse;
readonly sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
readonly modelConfigId: string | undefined;
}
export interface AcpSessionRuntimeShape {
readonly handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"];
readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"];
readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"];
readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"];
readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"];
readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"];
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"];
readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"];
readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"];
readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"];
readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"];
readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"];
readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"];
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
readonly prompt: (
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly setMode: (
modeId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
readonly setConfigOption: (
configId: string,
value: string | boolean,
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly request: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
readonly notify: (
method: string,
payload: unknown,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
}
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
type AcpStartState =
| { readonly _tag: "NotStarted" }
| {
readonly _tag: "Starting";
readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
}
| { readonly _tag: "Started"; readonly result: AcpStartedState };
interface AcpAssistantSegmentState {
readonly nextSegmentIndex: number;
readonly activeItemId?: string;
}
interface EnsureActiveAssistantSegmentResult {
readonly itemId: string;
readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
}
export class AcpSessionRuntime extends Context.Service<AcpSessionRuntime, AcpSessionRuntimeShape>()(
"t3/provider/acp/AcpSessionRuntime",
) {
static layer(
options: AcpSessionRuntimeOptions,
): Layer.Layer<
AcpSessionRuntime,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
> {
return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
}
}
const makeAcpSessionRuntime = (
options: AcpSessionRuntimeOptions,
): Effect.Effect<
AcpSessionRuntimeShape,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
> =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
const logRequest = (event: AcpSessionRequestLogEvent) =>
options.requestLogger ? options.requestLogger(event) : Effect.void;
const runLoggedRequest = <A>(
method: string,
payload: unknown,
effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
): Effect.Effect<A, EffectAcpErrors.AcpError> =>
logRequest({ method, payload, status: "started" }).pipe(
Effect.flatMap(() =>
effect.pipe(
Effect.tap((result) =>
logRequest({
method,
payload,
status: "succeeded",
result,
}),
),
Effect.onError((cause) =>
logRequest({
method,
payload,
status: "failed",
cause,
}),
),
),
),
);
const child = yield* spawner
.spawn(
ChildProcess.make(options.spawn.command, [...options.spawn.args], {
...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
...(options.spawn.env ? { env: { ...process.env, ...options.spawn.env } } : {}),
shell: process.platform === "win32",
}),
)
.pipe(
Effect.provideService(Scope.Scope, runtimeScope),
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpSpawnError({
command: options.spawn.command,
cause,
}),
),
);
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,
},
terminal: options.clientCapabilities?.terminal ?? false,
...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
...(options.clientCapabilities?.elicitation
? { elicitation: options.clientCapabilities.elicitation }
: {}),
...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
const getStartedState = Effect.gen(function* () {
const state = yield* Ref.get(startStateRef);
if (state._tag === "Started") {
return state.result;
}
return yield* new EffectAcpErrors.AcpTransportError({
detail: "ACP session runtime has not been started",
cause: new Error("ACP session runtime has not been started"),
});
});
const validateConfigOptionValue = (
configId: string,
value: string | boolean,
): Effect.Effect<void, EffectAcpErrors.AcpError> =>
Effect.gen(function* () {
const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
if (!configOption) {
return;
}
if (configOption.type === "boolean") {
if (typeof value === "boolean") {
return;
}
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected boolean`,
data: {
configId: configOption.id,
expectedType: "boolean",
receivedValue: value,
},
});
}
if (typeof value !== "string") {
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected string`,
data: {
configId: configOption.id,
expectedType: "string",
receivedValue: value,
},
});
}
const allowedValues = collectSessionConfigOptionValues(configOption);
if (allowedValues.includes(value)) {
return;
}
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
data: {
configId: configOption.id,
allowedValues,
receivedValue: value,
},
});
});
const updateConfigOptions = (
response:
| EffectAcpSchema.SetSessionConfigOptionResponse
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse,
): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
Ref.update(modeStateRef, (current) =>
current ? { ...current, currentModeId: modeId } : current,
);
const setConfigOption = (
configId: string,
value: string | boolean,
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
validateConfigOptionValue(configId, value).pipe(
Effect.flatMap(() => getStartedState),
Effect.flatMap((started) =>
Ref.get(configOptionsRef).pipe(
Effect.flatMap((configOptions) => {
const existing = findSessionConfigOption(configOptions, configId);
if (existing && configOptionCurrentValueMatches(existing, value)) {
return Effect.succeed({
configOptions,
} satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
}
const requestPayload =
typeof value === "boolean"
? ({
sessionId: started.sessionId,
configId,
type: "boolean",
value,
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
: ({
sessionId: started.sessionId,
configId,
value: String(value),
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
return runLoggedRequest(
"session/set_config_option",
requestPayload,
acp.agent.setSessionConfigOption(requestPayload),
).pipe(Effect.tap((response) => updateConfigOptions(response)));
}),
),
),
);
const startOnce = Effect.gen(function* () {
const initializePayload = {
protocolVersion: 1,
clientCapabilities: initializeClientCapabilities,
clientInfo: options.clientInfo,
} satisfies EffectAcpSchema.InitializeRequest;
const initializeResult = yield* runLoggedRequest(
"initialize",
initializePayload,
acp.agent.initialize(initializePayload),
);
const authenticatePayload = {
methodId: options.authMethodId,
} satisfies EffectAcpSchema.AuthenticateRequest;
yield* runLoggedRequest(
"authenticate",
authenticatePayload,
acp.agent.authenticate(authenticatePayload),
);
let sessionId: string;
let sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
if (options.resumeSessionId) {
const loadPayload = {
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;
}
} 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;
}
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
const nextState = {
sessionId,
initializeResult,
sessionSetupResult,
modelConfigId: extractModelConfigId(sessionSetupResult),
} satisfies AcpStartedState;
return nextState;
});
const start = Effect.gen(function* () {
const deferred = yield* Deferred.make<
AcpSessionRuntimeStartResult,
EffectAcpErrors.AcpError
>();
const effect = yield* Ref.modify(startStateRef, (state) => {
switch (state._tag) {
case "Started":
return [Effect.succeed(state.result), state] as const;
case "Starting":
return [Deferred.await(state.deferred), state] as const;
case "NotStarted":
return [
startOnce.pipe(
Effect.tap((result) =>
Ref.set(startStateRef, { _tag: "Started", result }).pipe(
Effect.andThen(Deferred.succeed(deferred, result)),
),
),
Effect.onError((cause) =>
Deferred.failCause(deferred, cause).pipe(
Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
),
),
),
{ _tag: "Starting", deferred } satisfies AcpStartState,
] as const;
}
});
return yield* effect;
});
return {
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),
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 })),
),
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),
);
}),
),
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;
});
function sessionConfigOptionsFromSetup(
response:
| {
readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
}
| undefined,
): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
return response?.configOptions ?? [];
}
function configOptionCurrentValueMatches(
configOption: EffectAcpSchema.SessionConfigOption,
value: string | boolean,
): boolean {
const currentValue = configOption.currentValue;
if (configOption.type === "boolean") {
return currentValue === value;
}
if (typeof currentValue !== "string") {
return false;
}
return currentValue.trim() === String(value).trim();
}
const handleSessionUpdate = ({
queue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly params: EffectAcpSchema.SessionNotification;
}): Effect.Effect<void> =>
Effect.gen(function* () {
const parsed = parseSessionUpdateEvent(params);
if (parsed.modeId) {
yield* Ref.update(modeStateRef, (current) =>
current === undefined ? current : updateModeState(current, parsed.modeId!),
);
}
for (const event of parsed.events) {
if (event._tag === "ToolCallUpdated") {
yield* closeActiveAssistantSegment({
queue,
assistantSegmentRef,
});
const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {
const previous = current.get(event.toolCall.toolCallId);
const nextToolCall = mergeToolCallState(previous, event.toolCall);
const next = new Map(current);
if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
next.delete(nextToolCall.toolCallId);
} else {
next.set(nextToolCall.toolCallId, nextToolCall);
}
return [{ previous, merged: nextToolCall }, next] as const;
});
if (!shouldEmitToolCallUpdate(previous, merged)) {
continue;
}
yield* Queue.offer(queue, {
_tag: "ToolCallUpdated",
toolCall: merged,
rawPayload: event.rawPayload,
});
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);
}
});
function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
const normalized = nextModeId.trim();
if (!normalized) {
return modeState;
}
return modeState.availableModes.some((mode) => mode.id === normalized)
? {
...modeState,
currentModeId: normalized,
}
: modeState;
}
function shouldEmitToolCallUpdate(
previous: AcpToolCallState | undefined,
next: AcpToolCallState,
): boolean {
if (next.status === "completed" || next.status === "failed") {
return true;
}
if (!next.detail) {
return false;
}
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
}
const assistantItemId = (sessionId: string, segmentIndex: number) =>
`assistant:${sessionId}:segment:${segmentIndex}`;
const ensureActiveAssistantSegment = ({
queue,
assistantSegmentRef,
sessionId,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly sessionId: string;
}) =>
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
assistantSegmentRef,
(current) => {
if (current.activeItemId) {
return [{ itemId: current.activeItemId }, current] as const;
}
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
return [
{
itemId,
startedEvent: {
_tag: "AssistantItemStarted",
itemId,
} satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
},
{
nextSegmentIndex: current.nextSegmentIndex + 1,
activeItemId: itemId,
} satisfies AcpAssistantSegmentState,
] as const;
},
).pipe(
Effect.flatMap((result) =>
result.startedEvent
? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
: Effect.succeed(result.itemId),
),
);
const closeActiveAssistantSegment = ({
queue,
assistantSegmentRef,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
}) =>
Ref.modify(assistantSegmentRef, (current) => {
if (!current.activeItemId) {
return [undefined, current] as const;
}
return [
{
_tag: "AssistantItemCompleted",
itemId: current.activeItemId,
} satisfies AcpParsedSessionEvent,
{
nextSegmentIndex: current.nextSegmentIndex,
} satisfies AcpAssistantSegmentState,
] as const;
}).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));
@@ -0,0 +1,148 @@
/**
* Optional integration check against a real `agent acp` install.
* Enable with: T3_CURSOR_ACP_PROBE=1 bun run test --filter CursorAcpCliProbe
*/
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 { AcpSessionRuntime } from "./AcpSessionRuntime.ts";
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
it.effect("initialize and authenticate against real agent acp", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toBeDefined();
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientCapabilities: {
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: { name: "t3-probe", version: "0.0.0" },
authMethodId: "cursor_login",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("session/new returns configOptions with a model selector", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
const result = started.sessionSetupResult;
console.log("session/new result:", JSON.stringify(result, null, 2));
expect(typeof started.sessionId).toBe("string");
const configOptions = result.configOptions;
console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
if (Array.isArray(configOptions)) {
const modelConfig = configOptions.find((opt) => opt.category === "model");
const parameterizedOptions = configOptions.filter(
(opt) =>
opt.category === "thought_level" ||
opt.category === "model_option" ||
opt.category === "model_config",
);
console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
console.log(
"Parameterized model config options:",
JSON.stringify(parameterizedOptions, null, 2),
);
expect(modelConfig).toBeDefined();
expect(typeof modelConfig?.id).toBe("string");
}
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientCapabilities: {
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: { name: "t3-probe", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("session/set_config_option switches the model in-session", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
const newResult = started.sessionSetupResult;
const configOptions = newResult.configOptions;
let modelConfigId = "model";
if (Array.isArray(configOptions)) {
const modelConfig = configOptions.find((opt) => opt.category === "model");
if (typeof modelConfig?.id === "string") {
modelConfigId = modelConfig.id;
}
}
const setResult: EffectAcpSchema.SetSessionConfigOptionResponse =
yield* runtime.setConfigOption(modelConfigId, "gpt-5.4");
console.log("session/set_config_option result:", JSON.stringify(setResult, null, 2));
if (Array.isArray(setResult.configOptions)) {
const modelConfig = setResult.configOptions.find((opt) => opt.category === "model");
const parameterizedOptions = setResult.configOptions.filter(
(opt) =>
opt.category === "thought_level" ||
opt.category === "model_option" ||
opt.category === "model_config",
);
if (modelConfig?.type === "select") {
expect(modelConfig.currentValue).toBe("gpt-5.4");
}
expect(parameterizedOptions.length).toBeGreaterThan(0);
}
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientCapabilities: {
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: { name: "t3-probe", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
});
@@ -0,0 +1,108 @@
import { describe, expect, it } from "vitest";
import {
extractAskQuestions,
extractPlanMarkdown,
extractTodosAsPlan,
} from "./CursorAcpExtension.ts";
describe("CursorAcpExtension", () => {
it("extracts ask-question prompts from the real Cursor ACP payload shape", () => {
const questions = extractAskQuestions({
toolCallId: "ask-1",
title: "Need input",
questions: [
{
id: "language",
prompt: "Which language should I use?",
options: [
{ id: "ts", label: "TypeScript" },
{ id: "rs", label: "Rust" },
],
allowMultiple: false,
},
],
});
expect(questions).toEqual([
{
id: "language",
header: "Question",
question: "Which language should I use?",
multiSelect: false,
options: [
{ label: "TypeScript", description: "TypeScript" },
{ label: "Rust", description: "Rust" },
],
},
]);
});
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",
name: "Refactor parser",
overview: "Tighten ACP parsing",
plan: "# Plan\n\n1. Add schemas\n2. Remove casts",
todos: [
{ id: "t1", content: "Add schemas", status: "in_progress" },
{ id: "t2", content: "Remove casts", status: "pending" },
],
isProject: false,
});
expect(planMarkdown).toBe("# Plan\n\n1. Add schemas\n2. Remove casts");
});
it("projects todo updates into a plan shape and drops invalid entries", () => {
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: " " },
],
merge: true,
}),
).toEqual({
plan: [
{ step: "Inspect state", status: "completed" },
{ step: "Apply fix", status: "inProgress" },
{ step: "Fallback title", status: "pending" },
{ step: "Unknown status", status: "pending" },
],
});
});
});
@@ -0,0 +1,99 @@
/**
* 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";
const CursorAskQuestionOption = Schema.Struct({
id: Schema.String,
label: Schema.String,
});
const CursorAskQuestion = Schema.Struct({
id: Schema.String,
prompt: Schema.String,
options: Schema.Array(CursorAskQuestionOption),
allowMultiple: Schema.optional(Schema.Boolean),
});
export const CursorAskQuestionRequest = Schema.Struct({
toolCallId: Schema.String,
title: Schema.optional(Schema.String),
questions: Schema.Array(CursorAskQuestion),
});
const CursorTodoStatus = Schema.String;
const CursorTodo = Schema.Struct({
id: Schema.optional(Schema.String),
content: Schema.optional(Schema.String),
title: Schema.optional(Schema.String),
status: Schema.optional(CursorTodoStatus),
});
const CursorPlanPhase = Schema.Struct({
name: Schema.String,
todos: Schema.Array(CursorTodo),
});
export const CursorCreatePlanRequest = Schema.Struct({
toolCallId: Schema.String,
name: Schema.optional(Schema.String),
overview: Schema.optional(Schema.String),
plan: Schema.String,
todos: Schema.Array(CursorTodo),
isProject: Schema.optional(Schema.Boolean),
phases: Schema.optional(Schema.Array(CursorPlanPhase)),
});
export const CursorUpdateTodosRequest = Schema.Struct({
toolCallId: Schema.String,
todos: Schema.Array(CursorTodo),
merge: Schema.Boolean,
});
export function extractAskQuestions(
params: typeof CursorAskQuestionRequest.Type,
): ReadonlyArray<UserInputQuestion> {
return params.questions.map((question) => ({
id: question.id,
header: "Question",
question: question.prompt,
multiSelect: question.allowMultiple === true,
options:
question.options.length > 0
? question.options.map((option) => ({
label: option.label,
description: option.label,
}))
: [{ label: "OK", description: "Continue" }],
}));
}
export function extractPlanMarkdown(params: typeof CursorCreatePlanRequest.Type): string {
return params.plan || "# Plan\n\n(Cursor did not supply plan text.)";
}
export function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type): {
readonly explanation?: string;
readonly plan: ReadonlyArray<{
readonly step: string;
readonly status: "pending" | "inProgress" | "completed";
}>;
} {
const plan = params.todos.flatMap((todo) => {
const step = todo.content?.trim() ?? todo.title?.trim() ?? "";
if (step === "") {
return [];
}
const status: "pending" | "inProgress" | "completed" =
todo.status === "completed"
? "completed"
: todo.status === "in_progress" || todo.status === "inProgress"
? "inProgress"
: "pending";
return [{ step, status }];
});
return { plan };
}
@@ -0,0 +1,123 @@
import { Effect } from "effect";
import type * as EffectAcpSchema from "effect-acp/schema";
import { describe, expect, it } from "vitest";
import { applyCursorAcpModelSelection, buildCursorAcpSpawnInput } from "./CursorAcpSupport.ts";
const parameterizedGpt54ConfigOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> = [
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: "gpt-5.4-medium-fast",
options: [{ value: "gpt-5.4-medium-fast", name: "GPT-5.4" }],
},
{
id: "reasoning",
name: "Reasoning",
category: "thought_level",
type: "select",
currentValue: "medium",
options: [
{ 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: "272k",
options: [
{ value: "272k", name: "272K" },
{ value: "1m", name: "1M" },
],
},
{
id: "fast",
name: "Fast",
category: "model_config",
type: "select",
currentValue: "false",
options: [
{ value: "false", name: "Off" },
{ value: "true", name: "Fast" },
],
},
];
describe("buildCursorAcpSpawnInput", () => {
it("builds the default Cursor ACP command", () => {
expect(buildCursorAcpSpawnInput(undefined, "/tmp/project")).toEqual({
command: "agent",
args: ["acp"],
cwd: "/tmp/project",
});
});
it("includes the configured api endpoint when present", () => {
expect(
buildCursorAcpSpawnInput(
{
binaryPath: "/usr/local/bin/agent",
apiEndpoint: "http://localhost:3000",
},
"/tmp/project",
),
).toEqual({
command: "/usr/local/bin/agent",
args: ["-e", "http://localhost:3000", "acp"],
cwd: "/tmp/project",
});
});
});
describe("applyCursorAcpModelSelection", () => {
it("sets the base model before applying separate config options", async () => {
const calls: Array<
| { readonly type: "model"; readonly value: string }
| { readonly type: "config"; readonly configId: string; readonly value: string | boolean }
> = [];
const runtime = {
getConfigOptions: Effect.succeed(parameterizedGpt54ConfigOptions),
setModel: (value: string) =>
Effect.sync(() => {
calls.push({ type: "model", value });
}),
setConfigOption: (configId: string, value: string | boolean) =>
Effect.sync(() => {
calls.push({ type: "config", configId, value });
}),
};
await Effect.runPromise(
applyCursorAcpModelSelection({
runtime,
model: "gpt-5.4-medium-fast[reasoning=medium,context=272k]",
modelOptions: {
reasoning: "xhigh",
contextWindow: "1m",
fastMode: true,
},
mapError: ({ step, configId, cause }) =>
new Error(
step === "set-config-option"
? `failed to set config option ${configId}: ${cause.message}`
: `failed to set model: ${cause.message}`,
),
}),
);
expect(calls).toEqual([
{ type: "model", value: "gpt-5.4-medium-fast" },
{ type: "config", configId: "reasoning", value: "extra-high" },
{ type: "config", configId: "context", value: "1m" },
{ type: "config", configId: "fast", value: "true" },
]);
});
});
@@ -0,0 +1,108 @@
import { type CursorModelOptions, type CursorSettings } from "@t3tools/contracts";
import { Effect, Layer, Scope } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import type * as EffectAcpErrors from "effect-acp/errors";
import {
CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
resolveCursorAcpBaseModelId,
resolveCursorAcpConfigUpdates,
} from "../Layers/CursorProvider.ts";
import {
AcpSessionRuntime,
type AcpSessionRuntimeOptions,
type AcpSessionRuntimeShape,
type AcpSpawnInput,
} from "./AcpSessionRuntime.ts";
type CursorAcpRuntimeCursorSettings = Pick<CursorSettings, "apiEndpoint" | "binaryPath">;
export interface CursorAcpRuntimeInput extends Omit<
AcpSessionRuntimeOptions,
"authMethodId" | "clientCapabilities" | "spawn"
> {
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined;
}
export interface CursorAcpModelSelectionErrorContext {
readonly cause: EffectAcpErrors.AcpError;
readonly step: "set-config-option" | "set-model";
readonly configId?: string;
}
export function buildCursorAcpSpawnInput(
cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined,
cwd: string,
): AcpSpawnInput {
return {
command: cursorSettings?.binaryPath || "agent",
args: [
...(cursorSettings?.apiEndpoint ? (["-e", cursorSettings.apiEndpoint] as const) : []),
"acp",
],
cwd,
};
}
export const makeCursorAcpRuntime = (
input: CursorAcpRuntimeInput,
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> =>
Effect.gen(function* () {
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
...input,
spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd),
authMethodId: "cursor_login",
clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
),
),
);
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
});
interface CursorAcpModelSelectionRuntime {
readonly getConfigOptions: AcpSessionRuntimeShape["getConfigOptions"];
readonly setConfigOption: (
configId: string,
value: string | boolean,
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
readonly setModel: (model: string) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
}
export function applyCursorAcpModelSelection<E>(input: {
readonly runtime: CursorAcpModelSelectionRuntime;
readonly model: string | null | undefined;
readonly modelOptions: CursorModelOptions | null | undefined;
readonly mapError: (context: CursorAcpModelSelectionErrorContext) => E;
}): Effect.Effect<void, E> {
return Effect.gen(function* () {
yield* input.runtime.setModel(resolveCursorAcpBaseModelId(input.model)).pipe(
Effect.mapError((cause) =>
input.mapError({
cause,
step: "set-model",
}),
),
);
const configUpdates = resolveCursorAcpConfigUpdates(
yield* input.runtime.getConfigOptions,
input.modelOptions,
);
for (const update of configUpdates) {
yield* input.runtime.setConfigOption(update.configId, update.value).pipe(
Effect.mapError((cause) =>
input.mapError({
cause,
step: "set-config-option",
configId: update.configId,
}),
),
);
}
});
}
@@ -0,0 +1,263 @@
import { describe, it, assert } from "@effect/vitest";
import type { ServerProvider } from "@t3tools/contracts";
import { Deferred, Effect, Fiber, PubSub, Ref, Stream } from "effect";
import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
interface TestSettings {
readonly enabled: boolean;
}
const initialSnapshot: ServerProvider = {
provider: "codex",
enabled: true,
installed: true,
version: null,
status: "warning",
auth: { status: "unknown" },
checkedAt: "2026-04-10T00:00:00.000Z",
message: "Checking provider availability...",
models: [],
slashCommands: [],
skills: [],
};
const refreshedSnapshot: ServerProvider = {
provider: "codex",
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-04-10T00:00:01.000Z",
models: [],
slashCommands: [],
skills: [],
};
const enrichedSnapshot: ServerProvider = {
...refreshedSnapshot,
checkedAt: "2026-04-10T00:00:02.000Z",
models: [
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
};
const refreshedSnapshotSecond: ServerProvider = {
...refreshedSnapshot,
checkedAt: "2026-04-10T00:00:03.000Z",
message: "Refreshed provider availability again.",
};
const enrichedSnapshotSecond: ServerProvider = {
...refreshedSnapshotSecond,
checkedAt: "2026-04-10T00:00:04.000Z",
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
};
describe("makeManagedServerProvider", () => {
it.effect(
"runs the initial provider check in the background and streams the refreshed snapshot",
() =>
Effect.scoped(
Effect.gen(function* () {
const checkCalls = yield* Ref.make(0);
const releaseCheck = yield* Deferred.make<void>();
const provider = yield* makeManagedServerProvider<TestSettings>({
getSettings: Effect.succeed({ enabled: true }),
streamSettings: Stream.empty,
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
initialSnapshot: () => initialSnapshot,
checkProvider: Ref.update(checkCalls, (count) => count + 1).pipe(
Effect.flatMap(() => Deferred.await(releaseCheck)),
Effect.as(refreshedSnapshot),
),
refreshInterval: "1 hour",
});
const initial = yield* provider.getSnapshot;
assert.deepStrictEqual(initial, initialSnapshot);
const updatesFiber = yield* Stream.take(provider.streamChanges, 1).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* Deferred.succeed(releaseCheck, undefined);
const updates = Array.from(yield* Fiber.join(updatesFiber));
const latest = yield* provider.getSnapshot;
assert.deepStrictEqual(updates, [refreshedSnapshot]);
assert.deepStrictEqual(latest, refreshedSnapshot);
assert.strictEqual(yield* Ref.get(checkCalls), 1);
}),
),
);
it.effect("reruns the provider check when streamed settings change", () =>
Effect.scoped(
Effect.gen(function* () {
const settingsRef = yield* Ref.make<TestSettings>({ enabled: true });
const settingsChanges = yield* PubSub.unbounded<TestSettings>();
const checkCalls = yield* Ref.make(0);
const releaseInitialCheck = yield* Deferred.make<void>();
const releaseSettingsCheck = yield* Deferred.make<void>();
const provider = yield* makeManagedServerProvider<TestSettings>({
getSettings: Ref.get(settingsRef),
streamSettings: Stream.fromPubSub(settingsChanges),
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
initialSnapshot: () => initialSnapshot,
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
Effect.flatMap((count) =>
count === 1
? Deferred.await(releaseInitialCheck).pipe(Effect.as(refreshedSnapshot))
: Deferred.await(releaseSettingsCheck).pipe(Effect.as(refreshedSnapshotSecond)),
),
),
refreshInterval: "1 hour",
});
const updatesFiber = yield* Stream.take(provider.streamChanges, 2).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* Deferred.succeed(releaseInitialCheck, undefined);
yield* Ref.set(settingsRef, { enabled: false });
yield* PubSub.publish(settingsChanges, { enabled: false });
yield* Deferred.succeed(releaseSettingsCheck, undefined);
const updates = Array.from(yield* Fiber.join(updatesFiber));
const latest = yield* provider.getSnapshot;
assert.deepStrictEqual(updates, [refreshedSnapshot, refreshedSnapshotSecond]);
assert.deepStrictEqual(latest, refreshedSnapshotSecond);
assert.strictEqual(yield* Ref.get(checkCalls), 2);
}),
),
);
it.effect("streams supplemental snapshot updates after the base provider check completes", () =>
Effect.scoped(
Effect.gen(function* () {
const releaseEnrichment = yield* Deferred.make<void>();
const releaseCheck = yield* Deferred.make<void>();
const provider = yield* makeManagedServerProvider<TestSettings>({
getSettings: Effect.succeed({ enabled: true }),
streamSettings: Stream.empty,
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
initialSnapshot: () => initialSnapshot,
checkProvider: Deferred.await(releaseCheck).pipe(Effect.as(refreshedSnapshot)),
enrichSnapshot: ({ publishSnapshot }) =>
Deferred.await(releaseEnrichment).pipe(
Effect.flatMap(() => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: "1 hour",
});
const updatesFiber = yield* Stream.take(provider.streamChanges, 2).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* Deferred.succeed(releaseCheck, undefined);
yield* Deferred.succeed(releaseEnrichment, undefined);
const updates = Array.from(yield* Fiber.join(updatesFiber));
const latest = yield* provider.getSnapshot;
assert.deepStrictEqual(updates, [refreshedSnapshot, enrichedSnapshot]);
assert.deepStrictEqual(latest, enrichedSnapshot);
}),
),
);
it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () =>
Effect.scoped(
Effect.gen(function* () {
const publishCallbacks: Array<(snapshot: ServerProvider) => Effect.Effect<void>> = [];
const refreshCount = yield* Ref.make(0);
const firstCallbackReady = yield* Deferred.make<void>();
const secondCallbackReady = yield* Deferred.make<void>();
const allowFirstRefresh = yield* Deferred.make<void>();
const provider = yield* makeManagedServerProvider<TestSettings>({
getSettings: Effect.succeed({ enabled: true }),
streamSettings: Stream.empty,
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
initialSnapshot: () => initialSnapshot,
checkProvider: Ref.updateAndGet(refreshCount, (count) => count + 1).pipe(
Effect.flatMap((count) =>
count === 1
? Deferred.await(allowFirstRefresh).pipe(Effect.as(refreshedSnapshot))
: Effect.succeed(refreshedSnapshotSecond),
),
),
enrichSnapshot: ({ publishSnapshot }) =>
Effect.gen(function* () {
publishCallbacks.push(publishSnapshot);
if (publishCallbacks.length === 1) {
yield* Deferred.succeed(firstCallbackReady, undefined).pipe(Effect.ignore);
} else if (publishCallbacks.length === 2) {
yield* Deferred.succeed(secondCallbackReady, undefined).pipe(Effect.ignore);
}
}),
refreshInterval: "1 hour",
});
const updatesFiber = yield* Stream.take(provider.streamChanges, 3).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* Deferred.succeed(allowFirstRefresh, undefined);
yield* Deferred.await(firstCallbackReady);
yield* provider.refresh;
yield* Deferred.await(secondCallbackReady);
yield* publishCallbacks[0]!(enrichedSnapshot);
yield* publishCallbacks[1]!(enrichedSnapshotSecond);
const updates = Array.from(yield* Fiber.join(updatesFiber));
const latest = yield* provider.getSnapshot;
assert.deepStrictEqual(updates, [
refreshedSnapshot,
refreshedSnapshotSecond,
enrichedSnapshotSecond,
]);
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
}),
),
);
});
@@ -1,10 +1,15 @@
import type { ServerProvider } from "@t3tools/contracts";
import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";
import { Duration, Effect, Equal, Fiber, PubSub, Ref, Scope, Stream } from "effect";
import * as Semaphore from "effect/Semaphore";
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
import { ServerSettingsError } from "@t3tools/contracts";
interface ProviderSnapshotState {
readonly snapshot: ServerProvider;
readonly enrichmentGeneration: number;
}
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
Settings,
>(input: {
@@ -13,6 +18,12 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly initialSnapshot: (settings: Settings) => ServerProvider;
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
readonly enrichSnapshot?: (input: {
readonly settings: Settings;
readonly snapshot: ServerProvider;
readonly getSnapshot: Effect.Effect<ServerProvider>;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
}) => Effect.Effect<void>;
readonly refreshInterval?: Duration.Input;
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
const refreshSemaphore = yield* Semaphore.make(1);
@@ -22,8 +33,61 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
);
const initialSettings = yield* input.getSettings;
const initialSnapshot = input.initialSnapshot(initialSettings);
const snapshotRef = yield* Ref.make(initialSnapshot);
const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
snapshot: initialSnapshot,
enrichmentGeneration: 0,
});
const settingsRef = yield* Ref.make(initialSettings);
const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
const scope = yield* Effect.scope;
const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
generation: number,
nextSnapshot: ServerProvider,
) {
const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
return [null, state] as const;
}
return [
nextSnapshot,
{
...state,
snapshot: nextSnapshot,
},
] as const;
});
if (snapshotToPublish === null) {
return;
}
yield* PubSub.publish(changesPubSub, snapshotToPublish);
});
const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
settings: Settings,
snapshot: ServerProvider,
generation: number,
) {
const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
if (previousFiber) {
yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
}
if (!input.enrichSnapshot) {
return;
}
const fiber = yield* input
.enrichSnapshot({
settings,
snapshot,
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
})
.pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
yield* Ref.set(enrichmentFiberRef, fiber);
});
const applySnapshotBase = Effect.fn("applySnapshot")(function* (
nextSettings: Settings,
@@ -33,13 +97,25 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
const previousSettings = yield* Ref.get(settingsRef);
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
yield* Ref.set(settingsRef, nextSettings);
return yield* Ref.get(snapshotRef);
return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
}
const nextSnapshot = yield* input.checkProvider;
const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {
const generation = input.enrichSnapshot
? state.enrichmentGeneration + 1
: state.enrichmentGeneration;
return [
generation,
{
snapshot: nextSnapshot,
enrichmentGeneration: generation,
},
] as const;
});
yield* Ref.set(settingsRef, nextSettings);
yield* Ref.set(snapshotRef, nextSnapshot);
yield* PubSub.publish(changesPubSub, nextSnapshot);
yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
return nextSnapshot;
});
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
@@ -61,6 +137,11 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
),
).pipe(Effect.forkScoped);
yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkScoped,
);
return {
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
@@ -73,10 +73,23 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
}),
);
it("hydrates cached provider status onto current settings-derived models", () => {
it("hydrates cached provider status while preserving current settings-derived models", () => {
const cachedCodex = makeProvider("codex", {
checkedAt: "2026-04-10T12:00:00.000Z",
models: [],
models: [
{
slug: "gpt-5-mini",
name: "GPT-5 Mini",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
message: "Cached message",
skills: [
{
@@ -112,6 +125,21 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
}),
{
...fallbackCodex,
models: [
...fallbackCodex.models,
{
slug: "gpt-5-mini",
name: "GPT-5 Mini",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
installed: cachedCodex.installed,
version: cachedCodex.version,
status: cachedCodex.status,
@@ -6,6 +6,7 @@ export const PROVIDER_CACHE_IDS = [
"codex",
"claudeAgent",
"opencode",
"cursor",
] as const satisfies ReadonlyArray<ServerProvider["provider"]>;
const decodeProviderStatusCache = Schema.decodeUnknownEffect(
@@ -17,6 +18,14 @@ const providerOrderRank = (provider: ServerProvider["provider"]): number => {
return rank === -1 ? Number.MAX_SAFE_INTEGER : rank;
};
const mergeProviderModels = (
fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
cachedModels: ReadonlyArray<ServerProvider["models"][number]>,
): ReadonlyArray<ServerProvider["models"][number]> => {
const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));
return [...fallbackModels, ...cachedModels.filter((model) => !fallbackSlugs.has(model.slug))];
};
export const orderProviderSnapshots = (
providers: ReadonlyArray<ServerProvider>,
): ReadonlyArray<ServerProvider> =>
@@ -38,6 +47,7 @@ export const hydrateCachedProvider = (input: {
const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
const hydratedProvider: ServerProvider = {
...fallbackWithoutMessage,
models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
installed: input.cachedProvider.installed,
version: input.cachedProvider.version,
status: input.cachedProvider.status,
+5
View File
@@ -21,6 +21,7 @@ import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionD
import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime.ts";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter.ts";
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter.ts";
import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter.ts";
import { makeOpenCodeAdapterLive } from "./provider/Layers/OpenCodeAdapter.ts";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService.ts";
@@ -160,10 +161,14 @@ const ProviderLayerLive = Layer.unwrap(
const openCodeAdapterLayer = makeOpenCodeAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const cursorAdapterLayer = makeCursorAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provide(claudeAdapterLayer),
Layer.provide(openCodeAdapterLayer),
Layer.provide(cursorAdapterLayer),
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
);
return makeProviderServiceLive(
+1 -1
View File
@@ -105,7 +105,7 @@ export class ServerSettingsService extends Context.Service<
const ServerSettingsJson = fromLenientJson(ServerSettings);
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode"];
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"];
/**
* Ensure the `textGenerationModelSelection` points to an enabled provider.
+1 -1
View File
@@ -9,7 +9,7 @@ export default defineConfig({
outDir: "dist",
sourcemap: true,
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
inlineOnly: false,
banner: {
js: "#!/usr/bin/env node\n",
@@ -99,6 +99,7 @@ function createBaseServerConfig(): ServerConfig {
providers: {
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [], launchArgs: "" },
cursor: { enabled: true, binaryPath: "", apiEndpoint: "", customModels: [] },
opencode: {
enabled: true,
binaryPath: "",
@@ -612,6 +612,7 @@ export const ChatComposer = memo(
providerStatuses.find((provider) => provider.provider === "claudeAgent")?.models ?? [],
opencode:
providerStatuses.find((provider) => provider.provider === "opencode")?.models ?? [],
cursor: providerStatuses.find((provider) => provider.provider === "cursor")?.models ?? [],
}),
[providerStatuses],
);
@@ -938,7 +938,13 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
const iconConfig = workToneIcon(workEntry.tone);
const EntryIcon = workEntryIcon(workEntry);
const heading = toolWorkEntryHeading(workEntry);
const preview = workEntryPreview(workEntry, workspaceRoot);
const rawPreview = workEntryPreview(workEntry, workspaceRoot);
const preview =
rawPreview &&
normalizeCompactToolLabel(rawPreview).toLowerCase() ===
normalizeCompactToolLabel(heading).toLowerCase()
? null
: rawPreview;
const rawCommand = workEntryRawCommand(workEntry);
const displayText = preview ? `${heading} - ${preview}` : heading;
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
@@ -953,20 +959,20 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
<EntryIcon className="size-3" />
</span>
<div className="min-w-0 flex-1 overflow-hidden">
<div className="max-w-full">
<p
className={cn(
"truncate text-xs leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
title={rawCommand ? undefined : displayText}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview &&
(rawCommand ? (
{rawCommand ? (
<div className="max-w-full">
<p
className={cn(
"truncate text-xs leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
title={displayText}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview && (
<Tooltip>
<TooltipTrigger
closeDelay={0}
@@ -988,11 +994,36 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
</div>
</TooltipPopup>
</Tooltip>
) : (
<span className="text-muted-foreground/55"> - {preview}</span>
))}
</p>
</div>
)}
</p>
</div>
) : (
<Tooltip>
<TooltipTrigger
className="block min-w-0 w-full text-left"
title={displayText}
aria-label={displayText}
>
<p
className={cn(
"truncate text-[11px] leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
</p>
</TooltipTrigger>
<TooltipPopup className="max-w-[min(720px,calc(100vw-2rem))]">
<p className="whitespace-pre-wrap wrap-break-word text-xs leading-5">
{displayText}
</p>
</TooltipPopup>
</Tooltip>
)}
</div>
</div>
{hasChangedFiles && !previewIsChangedFiles && (
@@ -4,6 +4,7 @@ import {
type ModelSelection,
ClaudeModelOptions,
CodexModelOptions,
CursorModelOptions,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_SERVER_SETTINGS,
OpenCodeModelOptions,
@@ -475,6 +476,90 @@ async function mountCodexPicker(props: { model?: string; options?: CodexModelOpt
};
}
async function mountCursorPicker(props: { model?: string; options?: CursorModelOptions }) {
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.cursor;
const cursorThreadId = ThreadId.make("thread-cursor-traits");
const cursorThreadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, cursorThreadId);
const cursorThreadKey = scopedThreadKey(cursorThreadRef);
const host = document.createElement("div");
document.body.append(host);
useComposerDraftStore.setState({
draftsByThreadKey: {
[cursorThreadKey]: {
prompt: "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
cursor: {
provider: "cursor",
model,
...(props.options ? { options: props.options } : {}),
},
},
activeProvider: "cursor",
runtimeMode: null,
interactionMode: null,
},
},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const screen = await render(
<TraitsPicker
provider="cursor"
models={[
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200K", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: [],
},
},
]}
threadRef={cursorThreadRef}
model={model}
prompt=""
modelOptions={props.options}
onPromptChange={() => {}}
/>,
{ container: host },
);
const cleanup = async () => {
await screen.unmount();
host.remove();
};
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
};
}
describe("TraitsPicker (Codex)", () => {
afterEach(() => {
document.body.innerHTML = "";
@@ -628,3 +713,70 @@ describe("TraitsPicker (OpenCode)", () => {
});
});
});
describe("TraitsPicker (Cursor)", () => {
afterEach(() => {
document.body.innerHTML = "";
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
it("uses the selected fast mode menu label for the trigger in fast-only state", async () => {
await using _ = await mountCursorPicker({
model: "composer-2",
options: { fastMode: false },
});
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Normal");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
});
it("shows Normal for Cursor Opus 4.6 when fast mode and context window are both at defaults", async () => {
await using _ = await mountCursorPicker({
model: "claude-opus-4-6",
options: { fastMode: false },
});
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Normal");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("Context Window");
expect(text).toContain("200K (default)");
expect(text).toContain("1M");
});
});
it("shows Normal · 1M for Cursor Opus 4.6 when fast mode is off and context window is overridden", async () => {
await using _ = await mountCursorPicker({
model: "claude-opus-4-6",
options: { fastMode: false, contextWindow: "1m" },
});
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("Normal · 1M");
});
});
});
+146 -43
View File
@@ -1,6 +1,7 @@
import {
type ClaudeModelOptions,
type CodexModelOptions,
type CursorModelOptions,
type OpenCodeModelOptions,
type ProviderKind,
type ProviderModelOptions,
@@ -60,12 +61,22 @@ function getRawEffort(
if (provider === "codex") {
return trimOrNull((modelOptions as CodexModelOptions | undefined)?.reasoningEffort);
}
if (provider === "cursor") {
return trimOrNull((modelOptions as CursorModelOptions | undefined)?.reasoning);
}
if (provider === "opencode") {
return trimOrNull((modelOptions as OpenCodeModelOptions | undefined)?.variant);
}
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort);
}
function getEffortKey(provider: ProviderKind): string {
if (provider === "codex") return "reasoningEffort";
if (provider === "cursor") return "reasoning";
if (provider === "opencode") return "variant";
return "effort";
}
function getRawAgent(modelOptions: ProviderOptions | null | undefined): string | null {
return trimOrNull((modelOptions as OpenCodeModelOptions | undefined)?.agent);
}
@@ -87,8 +98,8 @@ function getRawContextWindow(
provider: ProviderKind,
modelOptions: ProviderOptions | null | undefined,
): string | null {
if (provider === "claudeAgent") {
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.contextWindow);
if (modelOptions && "contextWindow" in modelOptions) {
return trimOrNull(modelOptions.contextWindow);
}
return null;
}
@@ -98,16 +109,7 @@ function buildNextOptions(
modelOptions: ProviderOptions | null | undefined,
patch: Record<string, unknown>,
): ProviderOptions {
if (provider === "codex") {
return { ...(modelOptions as CodexModelOptions | undefined), ...patch } as CodexModelOptions;
}
if (provider === "opencode") {
return {
...(modelOptions as OpenCodeModelOptions | undefined),
...patch,
} as OpenCodeModelOptions;
}
return { ...(modelOptions as ClaudeModelOptions | undefined), ...patch } as ClaudeModelOptions;
return { ...(modelOptions as Record<string, unknown> | undefined), ...patch } as ProviderOptions;
}
function getSelectedTraits(
@@ -137,7 +139,9 @@ function getSelectedTraits(
// Thinking toggle (only for models that support it)
const thinkingEnabled = caps.supportsThinkingToggle
? ((modelOptions as ClaudeModelOptions | undefined)?.thinking ?? true)
? modelOptions && "thinking" in modelOptions
? modelOptions.thinking === true
: null
: null;
// Fast mode
@@ -185,6 +189,51 @@ function getSelectedTraits(
};
}
function getTraitsSectionVisibility(input: {
provider: ProviderKind;
models: ReadonlyArray<ServerProviderModel>;
model: string | null | undefined;
prompt: string;
modelOptions: ProviderOptions | null | undefined;
allowPromptInjectedEffort?: boolean;
}) {
const selected = getSelectedTraits(
input.provider,
input.models,
input.model,
input.prompt,
input.modelOptions,
input.allowPromptInjectedEffort ?? true,
);
const showEffort = selected.effort !== null;
const showThinking = selected.thinkingEnabled !== null;
const showFastMode = selected.caps.supportsFastMode;
const showContextWindow = selected.contextWindowOptions.length > 1;
const showAgent = selected.agentOptions.length > 0;
return {
...selected,
showEffort,
showThinking,
showFastMode,
showContextWindow,
showAgent,
hasAnyControls: showEffort || showThinking || showFastMode || showContextWindow || showAgent,
};
}
export function shouldRenderTraitsControls(input: {
provider: ProviderKind;
models: ReadonlyArray<ServerProviderModel>;
model: string | null | undefined;
prompt: string;
modelOptions: ProviderOptions | null | undefined;
allowPromptInjectedEffort?: boolean;
}): boolean {
return getTraitsSectionVisibility(input).hasAnyControls;
}
export interface TraitsMenuContentProps {
provider: ProviderKind;
models: ReadonlyArray<ServerProviderModel>;
@@ -219,10 +268,11 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
return;
}
setProviderModelOptions(threadTarget, provider, nextOptions, {
model,
persistSticky: true,
});
},
[persistence, provider, setProviderModelOptions],
[model, persistence, provider, setProviderModelOptions],
);
const {
caps,
@@ -234,10 +284,22 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
contextWindow,
defaultContextWindow,
ultrathinkPromptControlled,
showEffort,
showThinking,
showFastMode,
showContextWindow,
ultrathinkInBodyText,
agentOptions,
selectedAgent,
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
hasAnyControls,
} = getTraitsSectionVisibility({
provider,
models,
model,
prompt,
modelOptions,
allowPromptInjectedEffort,
});
const defaultEffort = getDefaultEffort(caps);
const handleEffortChange = useCallback(
@@ -262,7 +324,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
const stripped = prompt.replace(/^Ultrathink:\s*/i, "");
onPromptChange(stripped);
}
const effortKey = provider === "codex" ? "reasoningEffort" : "effort";
const effortKey = getEffortKey(provider);
updateModelOptions(
buildNextOptions(provider, modelOptions, { [effortKey]: nextOption.value }),
);
@@ -280,18 +342,13 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
],
);
if (
effort === null &&
thinkingEnabled === null &&
contextWindowOptions.length <= 1 &&
agentOptions.length === 0
) {
if (!hasAnyControls) {
return null;
}
return (
<>
{effort ? (
{showEffort ? (
<>
<MenuGroup>
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">
@@ -321,7 +378,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
</MenuRadioGroup>
</MenuGroup>
</>
) : thinkingEnabled !== null ? (
) : showThinking ? (
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
<MenuRadioGroup
@@ -337,9 +394,9 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
</MenuRadioGroup>
</MenuGroup>
) : null}
{caps.supportsFastMode ? (
{showFastMode ? (
<>
<MenuDivider />
{showEffort || showThinking ? <MenuDivider /> : null}
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
<MenuRadioGroup
@@ -356,9 +413,9 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
</MenuGroup>
</>
) : null}
{contextWindowOptions.length > 1 ? (
{showContextWindow ? (
<>
<MenuDivider />
{showEffort || showThinking || showFastMode ? <MenuDivider /> : null}
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
Context Window
@@ -431,30 +488,76 @@ export const TraitsPicker = memo(function TraitsPicker({
contextWindow,
defaultContextWindow,
ultrathinkPromptControlled,
selectedAgentLabel,
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
showEffort,
showThinking,
showContextWindow,
} = getTraitsSectionVisibility({
provider,
models,
model,
prompt,
modelOptions,
allowPromptInjectedEffort,
});
const { selectedAgentLabel } = getSelectedTraits(
provider,
models,
model,
prompt,
modelOptions,
allowPromptInjectedEffort,
);
const effortLabel = effort
? (effortLevels.find((l) => l.value === effort)?.label ?? effort)
: null;
const primaryTraitLabel = ultrathinkPromptControlled
? "Ultrathink"
: effortLabel
? effortLabel
: thinkingEnabled === null
? null
: `Thinking ${thinkingEnabled ? "On" : "Off"}`;
const contextWindowLabel =
contextWindowOptions.length > 1 && contextWindow !== defaultContextWindow
showContextWindow && contextWindow !== defaultContextWindow
? (contextWindowOptions.find((o) => o.value === contextWindow)?.label ?? null)
: null;
const triggerLabel = [
ultrathinkPromptControlled
? "Ultrathink"
: effortLabel
? effortLabel
: thinkingEnabled === null
? null
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
...(caps.supportsFastMode && fastModeEnabled ? ["Fast"] : []),
const fastOnlyControl =
caps.supportsFastMode && !showEffort && !showThinking && !showContextWindow;
if (
!shouldRenderTraitsControls({
provider,
models,
model,
prompt,
modelOptions,
allowPromptInjectedEffort,
})
) {
return null;
}
const selectedTriggerTraits = [
primaryTraitLabel,
...(caps.supportsFastMode &&
(fastModeEnabled || (primaryTraitLabel === null && contextWindowLabel !== null))
? [fastModeEnabled ? "Fast" : "Normal"]
: []),
...(contextWindowLabel ? [contextWindowLabel] : []),
...(selectedAgentLabel ? [selectedAgentLabel] : []),
]
.filter(Boolean)
.join(" · ");
].filter(Boolean);
const triggerLabel = fastOnlyControl
? fastModeEnabled
? "Fast"
: "Normal"
: selectedTriggerTraits.length > 0
? selectedTriggerTraits.join(" · ")
: caps.supportsFastMode
? "Normal"
: defaultContextWindow
? (contextWindowOptions.find((option) => option.value === defaultContextWindow)?.label ??
defaultContextWindow)
: (selectedAgentLabel ?? "");
const isCodexStyle = provider === "codex";
@@ -14,7 +14,7 @@ import type { ReactNode } from "react";
import type { DraftId } from "../../composerDraftStore";
import { getProviderModelCapabilities } from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
import { shouldRenderTraitsControls, TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
export type ComposerProviderStateInput = {
provider: ProviderKind;
@@ -33,6 +33,16 @@ export type ComposerProviderState = {
modelPickerIconClassName?: string;
};
type TraitsRenderInput = {
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
};
export type ComposerProviderControls = {
showInteractionModeToggle: boolean;
};
@@ -40,24 +50,8 @@ export type ComposerProviderControls = {
type ProviderRegistryEntry = {
controls: ComposerProviderControls;
getState: (input: ComposerProviderStateInput) => ComposerProviderState;
renderTraitsMenuContent: (input: {
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
}) => ReactNode;
renderTraitsPicker: (input: {
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
}) => ReactNode;
renderTraitsMenuContent: (input: TraitsRenderInput) => ReactNode;
renderTraitsPicker: (input: TraitsRenderInput) => ReactNode;
};
function hasComposerTraitsTarget(input: {
@@ -67,6 +61,39 @@ function hasComposerTraitsTarget(input: {
return input.threadRef !== undefined || input.draftId !== undefined;
}
function renderTraitsControl(
Component: typeof TraitsMenuContent | typeof TraitsPicker,
provider: ProviderKind,
input: TraitsRenderInput,
): ReactNode {
const { threadRef, draftId, model, models, modelOptions, prompt, onPromptChange } = input;
if (
!hasComposerTraitsTarget({ threadRef, draftId }) ||
!shouldRenderTraitsControls({
provider,
models,
model,
modelOptions,
prompt,
})
) {
return null;
}
return (
<Component
provider={provider}
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
);
}
function getProviderStateFromCapabilities(
input: ComposerProviderStateInput,
): ComposerProviderState {
@@ -78,9 +105,11 @@ function getProviderStateFromCapabilities(
? providerOptions.effort
: "reasoningEffort" in providerOptions
? providerOptions.reasoningEffort
: "variant" in providerOptions
? providerOptions.variant
: null
: "reasoning" in providerOptions
? providerOptions.reasoning
: "variant" in providerOptions
? providerOptions.variant
: null
: null;
const normalizedOptions = normalizeProviderModelOptionsWithCapabilities(
provider,
@@ -122,54 +151,15 @@ function createProviderRegistryEntry(
...controls,
},
getState: (input) => getProviderStateFromCapabilities(input),
renderTraitsMenuContent: ({
threadRef,
draftId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) =>
!hasComposerTraitsTarget({ threadRef, draftId }) ? null : (
<TraitsMenuContent
provider={provider}
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
renderTraitsPicker: ({
threadRef,
draftId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) =>
!hasComposerTraitsTarget({ threadRef, draftId }) ? null : (
<TraitsPicker
provider={provider}
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
renderTraitsMenuContent: (input) => renderTraitsControl(TraitsMenuContent, provider, input),
renderTraitsPicker: (input) => renderTraitsControl(TraitsPicker, provider, input),
};
}
const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
codex: createProviderRegistryEntry("codex"),
claudeAgent: createProviderRegistryEntry("claudeAgent"),
cursor: createProviderRegistryEntry("cursor"),
opencode: createProviderRegistryEntry("opencode", {
showInteractionModeToggle: false,
}),
@@ -56,6 +56,7 @@ import {
} from "../../store";
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
import { cn } from "../../lib/utils";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
@@ -103,6 +104,7 @@ const TIMESTAMP_FORMAT_LABELS = {
type InstallProviderSettings = {
provider: ProviderKind;
title: string;
badgeLabel?: string;
binaryPlaceholder: string;
binaryDescription: ReactNode;
serverUrlPlaceholder?: string;
@@ -130,6 +132,13 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [
binaryPlaceholder: "Claude binary path",
binaryDescription: "Path to the Claude binary",
},
{
provider: "cursor",
title: "Cursor",
badgeLabel: "Early Access",
binaryPlaceholder: "Cursor agent binary path",
binaryDescription: "Path to the Cursor agent binary",
},
{
provider: "opencode",
title: "OpenCode",
@@ -530,6 +539,11 @@ export function GeneralSettingsPanel() {
settings.providers.claudeAgent.customModels.length > 0 ||
settings.providers.claudeAgent.launchArgs !== "",
),
cursor: Boolean(
settings.providers.cursor.binaryPath !==
DEFAULT_UNIFIED_SETTINGS.providers.cursor.binaryPath ||
settings.providers.cursor.customModels.length > 0,
),
opencode: Boolean(
settings.providers.opencode.binaryPath !==
DEFAULT_UNIFIED_SETTINGS.providers.opencode.binaryPath ||
@@ -545,6 +559,7 @@ export function GeneralSettingsPanel() {
>({
codex: "",
claudeAgent: "",
cursor: "",
opencode: "",
});
const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<
@@ -572,6 +587,11 @@ export function GeneralSettingsPanel() {
const availableEditors = useServerAvailableEditors();
const observability = useServerObservability();
const serverProviders = useServerProviders();
const visibleProviderSettings = PROVIDER_SETTINGS.filter(
(providerSettings) =>
providerSettings.provider !== "cursor" ||
serverProviders.some((provider) => provider.provider === "cursor"),
);
const codexHomePath = settings.providers.codex.homePath;
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
const diagnosticsDescription = (() => {
@@ -736,7 +756,7 @@ export function GeneralSettingsPanel() {
[settings, updateSettings],
);
const providerCards = PROVIDER_SETTINGS.map((providerSettings) => {
const providerCards = visibleProviderSettings.map((providerSettings) => {
const liveProvider = serverProviders.find(
(candidate) => candidate.provider === providerSettings.provider,
);
@@ -756,6 +776,7 @@ export function GeneralSettingsPanel() {
return {
provider: providerSettings.provider,
title: providerSettings.title,
badgeLabel: providerSettings.badgeLabel,
binaryPlaceholder: providerSettings.binaryPlaceholder,
binaryDescription: providerSettings.binaryDescription,
serverUrlPlaceholder: providerSettings.serverUrlPlaceholder,
@@ -1153,6 +1174,11 @@ export function GeneralSettingsPanel() {
className={cn("size-2 shrink-0 rounded-full", providerCard.statusStyle.dot)}
/>
<h3 className="text-sm font-medium text-foreground">{providerDisplayName}</h3>
{providerCard.badgeLabel ? (
<Badge variant="warning" size="sm" className="shrink-0">
{providerCard.badgeLabel}
</Badge>
) : null}
{providerCard.versionLabel ? (
<code className="text-xs text-muted-foreground">
{providerCard.versionLabel}
+73 -1
View File
@@ -91,7 +91,7 @@ function resetComposerDraftStore() {
}
function modelSelection(
provider: "codex" | "claudeAgent",
provider: "codex" | "claudeAgent" | "cursor",
model: string,
options?: ModelSelection["options"],
): ModelSelection {
@@ -1002,6 +1002,60 @@ describe("composerDraftStore modelSelection", () => {
);
});
it("keeps explicit Cursor reset overrides on the selection", () => {
const store = useComposerDraftStore.getState();
store.setModelSelection(
threadRef,
modelSelection("cursor", "claude-opus-4-6", {
reasoning: "xhigh",
fastMode: true,
thinking: false,
}),
);
store.setProviderModelOptions(threadRef, "cursor", {
reasoning: "medium",
fastMode: false,
thinking: true,
});
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "claude-opus-4-6", {
reasoning: "medium",
fastMode: false,
thinking: true,
}),
);
});
it("preserves the selected Cursor model when only traits change", () => {
const store = useComposerDraftStore.getState();
store.setProviderModelOptions(
threadRef,
"cursor",
{
reasoning: "high",
},
{
model: "gpt-5.4",
persistSticky: true,
},
);
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "gpt-5.4", {
reasoning: "high",
}),
);
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "gpt-5.4", {
reasoning: "high",
}),
);
});
it("updates only the draft when sticky persistence is omitted", () => {
const store = useComposerDraftStore.getState();
@@ -1174,6 +1228,24 @@ describe("composerDraftStore sticky composer settings", () => {
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("codex");
});
it("drops empty cursor model options when normalizing sticky state", () => {
const store = useComposerDraftStore.getState();
store.setStickyModelSelection(
modelSelection("cursor", "gpt-5.4", {
reasoning: undefined,
fastMode: undefined,
thinking: undefined,
contextWindow: undefined,
}),
);
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "gpt-5.4"),
);
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("cursor");
});
it("applies sticky activeProvider to new drafts", () => {
const store = useComposerDraftStore.getState();
const threadId = ThreadId.make("thread-sticky-active-provider");
+64 -13
View File
@@ -1,7 +1,10 @@
import {
CURSOR_REASONING_OPTIONS,
DEFAULT_MODEL_BY_PROVIDER,
type CursorModelOptions,
type CursorReasoningOption,
ClaudeAgentEffort,
CodexReasoningEffort,
DEFAULT_MODEL_BY_PROVIDER,
type EnvironmentId,
ModelSelection,
ProjectId,
@@ -341,6 +344,7 @@ interface ComposerDraftStoreState {
provider: ProviderKind,
nextProviderOptions: ProviderModelOptions[ProviderKind] | null | undefined,
options?: {
model?: string | null | undefined;
persistSticky?: boolean;
},
) => void;
@@ -527,7 +531,9 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
}
function normalizeProviderKind(value: unknown): ProviderKind | null {
return value === "codex" || value === "claudeAgent" || value === "opencode" ? value : null;
return value === "codex" || value === "claudeAgent" || value === "cursor" || value === "opencode"
? value
: null;
}
function normalizeProviderModelOptions(
@@ -544,15 +550,22 @@ function normalizeProviderModelOptions(
candidate?.claudeAgent && typeof candidate.claudeAgent === "object"
? (candidate.claudeAgent as Record<string, unknown>)
: null;
const cursorCandidate =
candidate?.cursor && typeof candidate.cursor === "object"
? (candidate.cursor as Record<string, unknown>)
: null;
const openCodeCandidate =
candidate?.opencode && typeof candidate.opencode === "object"
? (candidate.opencode as Record<string, unknown>)
: null;
const codexReasoningEffort = Schema.is(CodexReasoningEffort)(codexCandidate?.reasoningEffort)
const isCodexReasoningEffort = Schema.is(CodexReasoningEffort);
const isClaudeAgentEffort = Schema.is(ClaudeAgentEffort);
const codexReasoningEffort = isCodexReasoningEffort(codexCandidate?.reasoningEffort)
? codexCandidate.reasoningEffort
: provider === "codex"
? Schema.is(CodexReasoningEffort)(legacy?.effort)
? isCodexReasoningEffort(legacy?.effort)
? legacy.effort
: undefined
: undefined;
@@ -579,7 +592,7 @@ function normalizeProviderModelOptions(
: claudeCandidate?.thinking === false
? false
: undefined;
const claudeEffort = Schema.is(ClaudeAgentEffort)(claudeCandidate?.effort)
const claudeEffort = isClaudeAgentEffort(claudeCandidate?.effort)
? claudeCandidate.effort
: undefined;
const claudeFastMode =
@@ -604,6 +617,43 @@ function normalizeProviderModelOptions(
...(claudeContextWindow !== undefined ? { contextWindow: claudeContextWindow } : {}),
}
: undefined;
const cursorReasoningRaw = cursorCandidate?.reasoning;
const cursorReasoning: CursorReasoningOption | undefined =
typeof cursorReasoningRaw === "string" &&
(CURSOR_REASONING_OPTIONS as readonly string[]).includes(cursorReasoningRaw)
? (cursorReasoningRaw as CursorReasoningOption)
: undefined;
const cursorFastMode =
cursorCandidate?.fastMode === true
? true
: cursorCandidate?.fastMode === false
? false
: undefined;
const cursorThinking =
cursorCandidate?.thinking === true
? true
: cursorCandidate?.thinking === false
? false
: undefined;
const cursorContextWindow =
typeof cursorCandidate?.contextWindow === "string" && cursorCandidate.contextWindow.length > 0
? cursorCandidate.contextWindow
: undefined;
const cursor: CursorModelOptions | undefined =
cursorCandidate !== null
? (() => {
const nextCursor = {
...(cursorReasoning ? { reasoning: cursorReasoning } : {}),
...(cursorFastMode !== undefined ? { fastMode: cursorFastMode } : {}),
...(cursorThinking !== undefined ? { thinking: cursorThinking } : {}),
...(cursorContextWindow !== undefined ? { contextWindow: cursorContextWindow } : {}),
} satisfies CursorModelOptions;
return Object.keys(nextCursor).length > 0 ? nextCursor : undefined;
})()
: undefined;
const openCodeVariant =
typeof openCodeCandidate?.variant === "string" && openCodeCandidate.variant.length > 0
? openCodeCandidate.variant
@@ -620,12 +670,13 @@ function normalizeProviderModelOptions(
}
: undefined;
if (!codex && !claude && !opencode) {
if (!codex && !claude && cursor === undefined && !opencode) {
return null;
}
return {
...(codex ? { codex } : {}),
...(claude ? { claudeAgent: claude } : {}),
...(cursor !== undefined ? { cursor } : {}),
...(opencode ? { opencode } : {}),
};
}
@@ -715,7 +766,7 @@ function legacyToModelSelectionByProvider(
const result: Partial<Record<ProviderKind, ModelSelection>> = {};
// Add entries from the options bag (for non-active providers)
if (modelOptions) {
for (const provider of ["codex", "claudeAgent", "opencode"] as const) {
for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) {
const options = modelOptions[provider];
if (options && Object.keys(options).length > 0) {
result[provider] = createModelSelection(
@@ -2261,7 +2312,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
}
const base = existing ?? createEmptyThreadDraft();
const nextMap = { ...base.modelSelectionByProvider };
for (const provider of ["codex", "claudeAgent", "opencode"] as const) {
for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) {
// Only touch providers explicitly present in the input
if (!normalizedOpts || !(provider in normalizedOpts)) continue;
const opts = normalizedOpts[provider];
@@ -2303,6 +2354,9 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
if (normalizedProvider === null) {
return;
}
const fallbackModel =
normalizeModelSlug(options?.model, normalizedProvider) ??
DEFAULT_MODEL_BY_PROVIDER[normalizedProvider];
// Normalize just this provider's options
const normalizedOpts = normalizeProviderModelOptions(
{ [normalizedProvider]: nextProviderOptions },
@@ -2320,7 +2374,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
if (providerOpts) {
nextMap[normalizedProvider] = createModelSelection(
normalizedProvider,
currentForProvider?.model ?? DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
currentForProvider?.model ?? fallbackModel,
providerOpts,
);
} else if (currentForProvider?.options) {
@@ -2336,10 +2390,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
const stickyBase =
nextStickyMap[normalizedProvider] ??
base.modelSelectionByProvider[normalizedProvider] ??
createModelSelection(
normalizedProvider,
DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
);
createModelSelection(normalizedProvider, fallbackModel);
if (providerOpts) {
nextStickyMap[normalizedProvider] = createModelSelection(
normalizedProvider,
+13
View File
@@ -49,6 +49,13 @@ const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConf
placeholder: "your-claude-model-slug",
example: "claude-sonnet-5-0",
},
cursor: {
provider: "cursor",
title: "Cursor",
description: "Save additional Cursor model slugs for the picker and `/model` command.",
placeholder: "your-cursor-model-slug",
example: "claude-sonnet-4-6",
},
opencode: {
provider: "opencode",
title: "OpenCode",
@@ -176,6 +183,12 @@ export function getCustomModelOptionsByProvider(
"claudeAgent",
selectedProvider === "claudeAgent" ? selectedModel : undefined,
),
cursor: getAppModelOptions(
settings,
providers,
"cursor",
selectedProvider === "cursor" ? selectedModel : undefined,
),
opencode: getAppModelOptions(
settings,
providers,
+38 -2
View File
@@ -1,11 +1,17 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
type CursorModelOptions,
type ModelCapabilities,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import {
hasEffortLevel,
normalizeModelSlug,
resolveContextWindow,
trimOrNull,
} from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
@@ -33,7 +39,10 @@ export function isProviderEnabled(
providers: ReadonlyArray<ServerProvider>,
provider: ProviderKind,
): boolean {
return getProviderSnapshot(providers, provider)?.enabled ?? true;
if (providers.length === 0) {
return true;
}
return getProviderSnapshot(providers, provider)?.enabled ?? false;
}
export function resolveSelectableProvider(
@@ -67,3 +76,30 @@ export function getDefaultServerModel(
DEFAULT_MODEL_BY_PROVIDER[provider]
);
}
export function normalizeCursorModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CursorModelOptions | null | undefined,
): CursorModelOptions | undefined {
const reasoning = trimOrNull(modelOptions?.reasoning);
const reasoningValue =
reasoning && hasEffortLevel(caps, reasoning)
? (reasoning as CursorModelOptions["reasoning"])
: undefined;
const fastMode =
caps.supportsFastMode && typeof modelOptions?.fastMode === "boolean"
? modelOptions.fastMode
: undefined;
const thinking =
caps.supportsThinkingToggle && typeof modelOptions?.thinking === "boolean"
? modelOptions.thinking
: undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: CursorModelOptions = {
...(reasoningValue ? { reasoning: reasoningValue } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
...(thinking !== undefined ? { thinking } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
+193 -29
View File
@@ -921,6 +921,199 @@ describe("deriveWorkLogEntries", () => {
]);
});
it("drops duplicated tool detail when it only repeats the title", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "read-file-generic",
kind: "tool.completed",
summary: "Read File",
payload: {
itemType: "dynamic_tool_call",
title: "Read File",
detail: "Read File",
},
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
expect(entry?.toolTitle).toBe("Read File");
expect(entry?.detail).toBeUndefined();
});
it("uses grep raw output summaries instead of repeating the generic tool label", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "grep-update",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "tool.updated",
summary: "grep",
payload: {
itemType: "web_search",
title: "grep",
detail: "grep",
data: {
toolCallId: "tool-grep-1",
kind: "search",
rawInput: {},
},
},
}),
makeActivity({
id: "grep-complete",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "tool.completed",
summary: "grep",
payload: {
itemType: "web_search",
title: "grep",
detail: "grep",
data: {
toolCallId: "tool-grep-1",
kind: "search",
rawOutput: {
totalFiles: 19,
truncated: false,
},
},
},
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: "grep-complete",
toolTitle: "grep",
detail: "19 files",
itemType: "web_search",
});
});
it("uses completed read-file output previews and still collapses the same tool call", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "read-update",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "tool.updated",
summary: "Read File",
payload: {
itemType: "dynamic_tool_call",
title: "Read File",
detail: "Read File",
data: {
toolCallId: "tool-read-1",
kind: "read",
rawInput: {},
},
},
}),
makeActivity({
id: "read-complete",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "tool.completed",
summary: "Read File",
payload: {
itemType: "dynamic_tool_call",
title: "Read File",
detail: "Read File",
data: {
toolCallId: "tool-read-1",
kind: "read",
rawOutput: {
content:
'import * as Effect from "effect/Effect"\nimport * as Layer from "effect/Layer"\n',
},
},
},
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: "read-complete",
toolTitle: "Read File",
detail: 'import * as Effect from "effect/Effect"',
itemType: "dynamic_tool_call",
});
});
it("does not use command stdout as the detail when Cursor omits the command input", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "cursor-command-complete",
createdAt: "2026-04-16T22:40:42.221Z",
kind: "tool.completed",
summary: "Ran command",
payload: {
itemType: "command_execution",
title: "Ran command",
data: {
toolCallId: "toolu_vrtx_01WypXgRM8PPygBtrVAZwzy5",
kind: "execute",
rawInput: {},
rawOutput: {
exitCode: 0,
stdout: "total 960\napps\npackages\n",
stderr: "",
},
},
},
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
expect(entry).toMatchObject({
id: "cursor-command-complete",
label: "Ran command",
itemType: "command_execution",
toolTitle: "Ran command",
});
expect(entry?.detail).toBeUndefined();
expect(entry?.command).toBeUndefined();
});
it("collapses legacy completed tool rows that are missing tool metadata", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "legacy-read-update",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "tool.updated",
summary: "Read File",
payload: {
itemType: "dynamic_tool_call",
title: "Read File",
detail: "Read File",
data: {
toolCallId: "tool-read-legacy",
kind: "read",
rawInput: {},
},
},
}),
makeActivity({
id: "legacy-read-complete",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "tool.completed",
summary: "Read File",
payload: {
itemType: "dynamic_tool_call",
title: "Read File",
detail: "Read File",
},
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: "legacy-read-complete",
toolTitle: "Read File",
itemType: "dynamic_tool_call",
});
expect(entries[0]?.detail).toBeUndefined();
});
it("collapses repeated lifecycle updates for the same tool call into one entry", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
@@ -1324,32 +1517,3 @@ describe("deriveActiveWorkStartedAt", () => {
).toBe("2026-02-27T21:11:00.000Z");
});
});
describe("PROVIDER_OPTIONS", () => {
it("advertises available providers while keeping Cursor as a placeholder", () => {
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeAgent");
const opencode = PROVIDER_OPTIONS.find((option) => option.value === "opencode");
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
expect(PROVIDER_OPTIONS).toEqual([
{ value: "codex", label: "Codex", available: true },
{ value: "claudeAgent", label: "Claude", available: true },
{ value: "opencode", label: "OpenCode", available: true },
{ value: "cursor", label: "Cursor", available: false },
]);
expect(claude).toEqual({
value: "claudeAgent",
label: "Claude",
available: true,
});
expect(opencode).toEqual({
value: "opencode",
label: "OpenCode",
available: true,
});
expect(cursor).toEqual({
value: "cursor",
label: "Cursor",
available: false,
});
});
});
+149 -19
View File
@@ -1,3 +1,5 @@
import * as Option from "effect/Option";
import * as Arr from "effect/Array";
import {
ApprovalRequestId,
isToolLifecycleItemType,
@@ -20,7 +22,7 @@ import type {
TurnDiffSummary,
} from "./types";
export type ProviderPickerKind = ProviderKind | "cursor";
export type ProviderPickerKind = ProviderKind;
export const PROVIDER_OPTIONS: Array<{
value: ProviderPickerKind;
@@ -30,7 +32,7 @@ export const PROVIDER_OPTIONS: Array<{
{ value: "codex", label: "Codex", available: true },
{ value: "claudeAgent", label: "Claude", available: true },
{ value: "opencode", label: "OpenCode", available: true },
{ value: "cursor", label: "Cursor", available: false },
{ value: "cursor", label: "Cursor", available: true },
];
export interface WorkLogEntry {
@@ -50,6 +52,7 @@ export interface WorkLogEntry {
interface DerivedWorkLogEntry extends WorkLogEntry {
activityKind: OrchestrationThreadActivity["kind"];
collapseKey?: string;
toolCallId?: string;
}
export interface PendingApproval {
@@ -352,12 +355,12 @@ export function deriveActivePlanState(
const allPlanActivities = ordered.filter((activity) => activity.kind === "turn.plan.updated");
// Prefer plan from the current turn; fall back to the most recent plan from any turn
// so that TodoWrite tasks persist across follow-up messages.
const latest =
(latestTurnId
? allPlanActivities.filter((activity) => activity.turnId === latestTurnId).at(-1)
: undefined) ??
allPlanActivities.at(-1) ??
null;
const latest = Option.firstSomeOf([
...(latestTurnId
? Arr.findLast(allPlanActivities, (activity) => activity.turnId === latestTurnId)
: Option.none()),
Arr.last(allPlanActivities),
]).pipe(Option.getOrNull);
if (!latest) {
return null;
}
@@ -515,6 +518,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
? payload.detail
: null;
const taskLabel = taskSummary || taskDetailAsLabel;
const detail = isTaskActivity
? !taskDetailAsLabel &&
payload &&
typeof payload.detail === "string" &&
payload.detail.length > 0
? stripTrailingExitCode(payload.detail).output
: null
: extractToolDetail(payload, title ?? activity.summary);
const toolCallId = isTaskActivity ? null : extractToolCallId(payload);
const entry: DerivedWorkLogEntry = {
id: activity.id,
createdAt: activity.createdAt,
@@ -529,16 +541,8 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
};
const itemType = extractWorkLogItemType(payload);
const requestKind = extractWorkLogRequestKind(payload);
if (
!taskDetailAsLabel &&
payload &&
typeof payload.detail === "string" &&
payload.detail.length > 0
) {
const detail = stripTrailingExitCode(payload.detail).output;
if (detail) {
entry.detail = detail;
}
if (detail) {
entry.detail = detail;
}
if (commandPreview.command) {
entry.command = commandPreview.command;
@@ -558,6 +562,9 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (requestKind) {
entry.requestKind = requestKind;
}
if (toolCallId) {
entry.toolCallId = toolCallId;
}
const collapseKey = deriveToolLifecycleCollapseKey(entry);
if (collapseKey) {
entry.collapseKey = collapseKey;
@@ -593,7 +600,16 @@ function shouldCollapseToolLifecycleEntries(
if (previous.activityKind === "tool.completed") {
return false;
}
return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
if (previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey) {
return true;
}
return (
previous.toolCallId !== undefined &&
next.toolCallId === undefined &&
previous.itemType === next.itemType &&
normalizeCompactToolLabel(previous.toolTitle ?? previous.label) ===
normalizeCompactToolLabel(next.toolTitle ?? next.label)
);
}
function mergeDerivedWorkLogEntries(
@@ -608,6 +624,7 @@ function mergeDerivedWorkLogEntries(
const itemType = next.itemType ?? previous.itemType;
const requestKind = next.requestKind ?? previous.requestKind;
const collapseKey = next.collapseKey ?? previous.collapseKey;
const toolCallId = next.toolCallId ?? previous.toolCallId;
return {
...previous,
...next,
@@ -619,6 +636,7 @@ function mergeDerivedWorkLogEntries(
...(itemType ? { itemType } : {}),
...(requestKind ? { requestKind } : {}),
...(collapseKey ? { collapseKey } : {}),
...(toolCallId ? { toolCallId } : {}),
};
}
@@ -637,6 +655,9 @@ function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | un
if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
return undefined;
}
if (entry.toolCallId) {
return `tool:${entry.toolCallId}`;
}
const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
const detail = entry.detail?.trim() ?? "";
const itemType = entry.itemType ?? "";
@@ -674,6 +695,10 @@ function asTrimmedString(value: unknown): string | null {
return trimmed.length > 0 ? trimmed : null;
}
function asNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function trimMatchingOuterQuotes(value: string): string {
const trimmed = value.trim();
if (
@@ -857,6 +882,111 @@ function extractToolTitle(payload: Record<string, unknown> | null): string | nul
return asTrimmedString(payload?.title);
}
function extractToolCallId(payload: Record<string, unknown> | null): string | null {
const data = asRecord(payload?.data);
return asTrimmedString(data?.toolCallId);
}
function normalizeInlinePreview(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function truncateInlinePreview(value: string, maxLength = 84): string {
if (value.length <= maxLength) {
return value;
}
return `${value.slice(0, maxLength - 1).trimEnd()}…`;
}
function normalizePreviewForComparison(value: string | null | undefined): string | null {
const normalized = asTrimmedString(value);
if (!normalized) {
return null;
}
return normalizeCompactToolLabel(normalizeInlinePreview(normalized)).toLowerCase();
}
function summarizeToolTextOutput(value: string): string | null {
const lines = value
.split(/\r?\n/u)
.map((line) => normalizeInlinePreview(line))
.filter((line) => line.length > 0);
const firstLine = lines.find((line) => line !== "```");
if (firstLine) {
return truncateInlinePreview(firstLine);
}
if (lines.length > 1) {
return `${lines.length.toLocaleString()} lines`;
}
return null;
}
function summarizeToolRawOutput(payload: Record<string, unknown> | null): string | null {
const data = asRecord(payload?.data);
const rawOutput = asRecord(data?.rawOutput);
if (!rawOutput) {
return null;
}
const totalFiles = asNumber(rawOutput.totalFiles);
if (totalFiles !== null) {
const suffix = rawOutput.truncated === true ? "+" : "";
return `${totalFiles.toLocaleString()} file${totalFiles === 1 ? "" : "s"}${suffix}`;
}
const content = asTrimmedString(rawOutput.content);
if (content) {
return summarizeToolTextOutput(content);
}
const stdout = asTrimmedString(rawOutput.stdout);
if (stdout) {
return summarizeToolTextOutput(stdout);
}
return null;
}
function isCommandToolDetail(payload: Record<string, unknown> | null, heading: string): boolean {
const data = asRecord(payload?.data);
const kind = asTrimmedString(data?.kind)?.toLowerCase();
const title = asTrimmedString(payload?.title ?? heading)?.toLowerCase();
return (
extractWorkLogItemType(payload) === "command_execution" ||
kind === "execute" ||
title === "terminal" ||
title === "ran command"
);
}
function extractToolDetail(
payload: Record<string, unknown> | null,
heading: string,
): string | null {
const rawDetail = asTrimmedString(payload?.detail);
const detail = rawDetail ? stripTrailingExitCode(rawDetail).output : null;
const normalizedHeading = normalizePreviewForComparison(heading);
const normalizedDetail = normalizePreviewForComparison(detail);
if (detail && normalizedHeading !== normalizedDetail) {
return detail;
}
if (isCommandToolDetail(payload, heading)) {
return null;
}
const rawOutputSummary = summarizeToolRawOutput(payload);
if (rawOutputSummary) {
const normalizedRawOutputSummary = normalizePreviewForComparison(rawOutputSummary);
if (normalizedRawOutputSummary !== normalizedHeading) {
return rawOutputSummary;
}
}
return null;
}
function stripTrailingExitCode(value: string): {
output: string | null;
exitCode?: number | undefined;
+4 -4
View File
@@ -15,12 +15,12 @@ import type {
OrchestrationThreadShell,
OrchestrationThreadActivity,
ProjectId,
ProviderKind,
ScopedProjectRef,
ScopedThreadRef,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { ProviderKind } from "@t3tools/contracts";
import type { ThreadId, TurnId } from "@t3tools/contracts";
import { Schema } from "effect";
import { resolveModelSlugForProvider } from "@t3tools/shared/model";
import { create } from "zustand";
import {
@@ -1001,7 +1001,7 @@ function toLegacySessionStatus(
}
function toLegacyProvider(providerName: string | null): ProviderKind {
if (providerName === "codex" || providerName === "claudeAgent" || providerName === "opencode") {
if (Schema.is(ProviderKind)(providerName)) {
return providerName;
}
return "codex";
+22
View File
@@ -24,6 +24,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
@@ -65,6 +66,7 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
@@ -149,6 +151,21 @@
"vitest": "catalog:",
},
},
"packages/effect-acp": {
"name": "effect-acp",
"dependencies": {
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/openapi-generator": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"packages/shared": {
"name": "@t3tools/shared",
"version": "0.0.0-alpha.1",
@@ -198,6 +215,7 @@
"catalog": {
"@effect/atom-react": "4.0.0-beta.45",
"@effect/language-service": "0.84.2",
"@effect/openapi-generator": "4.0.0-beta.45",
"@effect/platform-bun": "4.0.0-beta.45",
"@effect/platform-node": "4.0.0-beta.45",
"@effect/platform-node-shared": "4.0.0-beta.45",
@@ -297,6 +315,8 @@
"@effect/language-service": ["@effect/[email protected]", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="],
"@effect/openapi-generator": ["@effect/[email protected]", "", { "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-bun": ["@effect/[email protected]", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.45" }, "peerDependencies": { "effect": "^4.0.0-beta.45" } }, "sha512-dZsbkJ+o4JfKE1OIAlMq8YWhmEfXxtTYennYADK/M/XlOtkFLsc2jkZppDvMznVni6JpFxWc7wd5rUf8jBVP5g=="],
"@effect/platform-node": ["@effect/[email protected]", "", { "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=="],
@@ -1061,6 +1081,8 @@
"effect": ["[email protected]", "", { "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"],
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
"electron-to-chromium": ["[email protected]", "", {}, "sha512-QBMrTWEf00GXZmJyx2lbYD45jpI3TUFnNIzJ5BBc8piGUDwMPa1GV6HJWTZVvY/eiN3fSopl7NRbgGp9sZ9LTA=="],
+1
View File
@@ -10,6 +10,7 @@
"catalog": {
"effect": "4.0.0-beta.45",
"@effect/atom-react": "4.0.0-beta.45",
"@effect/openapi-generator": "4.0.0-beta.45",
"@effect/platform-bun": "4.0.0-beta.45",
"@effect/platform-node": "4.0.0-beta.45",
"@effect/platform-node-shared": "4.0.0-beta.45",
+36 -4
View File
@@ -2,18 +2,28 @@ import { Schema } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
import type { ProviderKind } from "./orchestration.ts";
export const CodexReasoningEffort = Schema.Literals(["xhigh", "high", "medium", "low"]);
export const CODEX_REASONING_EFFORT_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export const CodexReasoningEffort = Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS);
export type CodexReasoningEffort = typeof CodexReasoningEffort.Type;
export const ClaudeAgentEffort = Schema.Literals([
export const CLAUDE_AGENT_EFFORT_OPTIONS = [
"low",
"medium",
"high",
"xhigh",
"max",
"ultrathink",
]);
] as const;
export const ClaudeAgentEffort = Schema.Literals(CLAUDE_AGENT_EFFORT_OPTIONS);
export type ClaudeAgentEffort = typeof ClaudeAgentEffort.Type;
export type ProviderReasoningEffort = CodexReasoningEffort | ClaudeAgentEffort;
export type ClaudeCodeEffort = ClaudeAgentEffort;
export const CURSOR_REASONING_OPTIONS = ["low", "medium", "high", "max", "xhigh"] as const;
export const CursorReasoningOption = Schema.Literals(CURSOR_REASONING_OPTIONS);
export type CursorReasoningOption = typeof CursorReasoningOption.Type;
export type ProviderReasoningEffort =
| CodexReasoningEffort
| ClaudeAgentEffort
| CursorReasoningOption;
export const CodexModelOptions = Schema.Struct({
reasoningEffort: Schema.optional(CodexReasoningEffort),
@@ -29,6 +39,13 @@ export const ClaudeModelOptions = Schema.Struct({
});
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
export const CursorModelOptions = Schema.Struct({
reasoning: Schema.optional(CursorReasoningOption),
fastMode: Schema.optional(Schema.Boolean),
thinking: Schema.optional(Schema.Boolean),
contextWindow: Schema.optional(Schema.String),
});
export type CursorModelOptions = typeof CursorModelOptions.Type;
export const OpenCodeModelOptions = Schema.Struct({
variant: Schema.optional(TrimmedNonEmptyString),
agent: Schema.optional(TrimmedNonEmptyString),
@@ -38,6 +55,7 @@ export type OpenCodeModelOptions = typeof OpenCodeModelOptions.Type;
export const ProviderModelOptions = Schema.Struct({
codex: Schema.optional(CodexModelOptions),
claudeAgent: Schema.optional(ClaudeModelOptions),
cursor: Schema.optional(CursorModelOptions),
opencode: Schema.optional(OpenCodeModelOptions),
});
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
@@ -70,6 +88,7 @@ export type ModelCapabilities = typeof ModelCapabilities.Type;
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
codex: "gpt-5.4",
claudeAgent: "claude-sonnet-4-6",
cursor: "auto",
opencode: "openai/gpt-5",
};
@@ -79,6 +98,7 @@ export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
codex: "gpt-5.4-mini",
claudeAgent: "claude-haiku-4-5",
cursor: "composer-2",
opencode: "openai/gpt-5",
};
@@ -107,6 +127,17 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
"claude-haiku-4.5": "claude-haiku-4-5",
"claude-haiku-4-5-20251001": "claude-haiku-4-5",
},
cursor: {
composer: "composer-2",
"composer-1.5": "composer-1.5",
"composer-1": "composer-1.5",
"opus-4.6-thinking": "claude-opus-4-6",
"opus-4.6": "claude-opus-4-6",
"sonnet-4.6-thinking": "claude-sonnet-4-6",
"sonnet-4.6": "claude-sonnet-4-6",
"opus-4.5-thinking": "claude-opus-4-5",
"opus-4.5": "claude-opus-4-5",
},
opencode: {},
};
@@ -115,5 +146,6 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
codex: "Codex",
claudeAgent: "Claude",
cursor: "Cursor",
opencode: "OpenCode",
};
+14 -2
View File
@@ -1,5 +1,10 @@
import { Effect, Option, Schema, SchemaIssue, Struct } from "effect";
import { ClaudeModelOptions, CodexModelOptions, OpenCodeModelOptions } from "./model.ts";
import {
ClaudeModelOptions,
CodexModelOptions,
CursorModelOptions,
OpenCodeModelOptions,
} from "./model.ts";
import { RepositoryIdentity } from "./environment.ts";
import {
ApprovalRequestId,
@@ -25,7 +30,7 @@ export const ORCHESTRATION_WS_METHODS = {
subscribeThread: "orchestration.subscribeThread",
} as const;
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "opencode"]);
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor", "opencode"]);
export type ProviderKind = typeof ProviderKind.Type;
export const ProviderApprovalPolicy = Schema.Literals([
"untrusted",
@@ -57,6 +62,12 @@ export const ClaudeModelSelection = Schema.Struct({
});
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
export const CursorModelSelection = Schema.Struct({
provider: Schema.Literal("cursor"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(CursorModelOptions),
});
export type CursorModelSelection = typeof CursorModelSelection.Type;
export const OpenCodeModelSelection = Schema.Struct({
provider: Schema.Literal("opencode"),
model: TrimmedNonEmptyString,
@@ -67,6 +78,7 @@ export type OpenCodeModelSelection = typeof OpenCodeModelSelection.Type;
export const ModelSelection = Schema.Union([
CodexModelSelection,
ClaudeModelSelection,
CursorModelSelection,
OpenCodeModelSelection,
]);
export type ModelSelection = typeof ModelSelection.Type;
+20
View File
@@ -68,6 +68,26 @@ describe("ProviderSessionStartInput", () => {
expect(parsed.modelSelection.options?.fastMode).toBe(true);
expect(parsed.runtimeMode).toBe("full-access");
});
it("accepts cursor provider", () => {
const parsed = decodeProviderSessionStartInput({
threadId: "thread-1",
provider: "cursor",
cwd: "/tmp/workspace",
runtimeMode: "full-access",
modelSelection: {
provider: "cursor",
model: "composer-2",
options: { fastMode: true },
},
});
expect(parsed.provider).toBe("cursor");
expect(parsed.modelSelection?.provider).toBe("cursor");
expect(parsed.modelSelection?.model).toBe("composer-2");
if (parsed.modelSelection?.provider === "cursor") {
expect(parsed.modelSelection.options?.fastMode).toBe(true);
}
});
});
describe("ProviderSendTurnInput", () => {
+10 -8
View File
@@ -17,14 +17,16 @@ 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",
"opencode.sdk.event",
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("opencode.sdk.event"),
Schema.Literal("acp.jsonrpc"),
Schema.TemplateLiteral(["acp.", Schema.String, ".extension"]),
]);
export type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type;
+29
View File
@@ -5,6 +5,7 @@ import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
import {
ClaudeModelOptions,
CodexModelOptions,
CursorModelOptions,
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
OpenCodeModelOptions,
} from "./model.ts";
@@ -90,6 +91,13 @@ export const ClaudeSettings = Schema.Struct({
});
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const CursorSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
binaryPath: makeBinaryPathSetting("agent"),
apiEndpoint: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
export type CursorSettings = typeof CursorSettings.Type;
export const OpenCodeSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
binaryPath: makeBinaryPathSetting("opencode"),
@@ -124,6 +132,7 @@ export const ServerSettings = Schema.Struct({
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
@@ -167,6 +176,13 @@ const ClaudeModelOptionsPatch = Schema.Struct({
contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow),
});
const CursorModelOptionsPatch = Schema.Struct({
reasoning: Schema.optionalKey(CursorModelOptions.fields.reasoning),
fastMode: Schema.optionalKey(CursorModelOptions.fields.fastMode),
thinking: Schema.optionalKey(CursorModelOptions.fields.thinking),
contextWindow: Schema.optionalKey(CursorModelOptions.fields.contextWindow),
});
const OpenCodeModelOptionsPatch = Schema.Struct({
variant: Schema.optionalKey(OpenCodeModelOptions.fields.variant),
agent: Schema.optionalKey(OpenCodeModelOptions.fields.agent),
@@ -183,6 +199,11 @@ const ModelSelectionPatch = Schema.Union([
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(ClaudeModelOptionsPatch),
}),
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("cursor")),
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(CursorModelOptionsPatch),
}),
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("opencode")),
model: Schema.optionalKey(TrimmedNonEmptyString),
@@ -204,6 +225,13 @@ const ClaudeSettingsPatch = Schema.Struct({
launchArgs: Schema.optionalKey(Schema.String),
});
const CursorSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
apiEndpoint: Schema.optionalKey(Schema.String),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const OpenCodeSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
@@ -227,6 +255,7 @@ export const ServerSettingsPatch = Schema.Struct({
Schema.Struct({
codex: Schema.optionalKey(CodexSettingsPatch),
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
cursor: Schema.optionalKey(CursorSettingsPatch),
opencode: Schema.optionalKey(OpenCodeSettingsPatch),
}),
),
+55
View File
@@ -0,0 +1,55 @@
{
"name": "effect-acp",
"private": true,
"type": "module",
"exports": {
"./client": {
"types": "./src/client.ts",
"import": "./src/client.ts"
},
"./agent": {
"types": "./src/agent.ts",
"import": "./src/agent.ts"
},
"./schema": {
"types": "./src/schema.ts",
"import": "./src/schema.ts"
},
"./rpc": {
"types": "./src/rpc.ts",
"import": "./src/rpc.ts"
},
"./protocol": {
"types": "./src/protocol.ts",
"import": "./src/protocol.ts"
},
"./terminal": {
"types": "./src/terminal.ts",
"import": "./src/terminal.ts"
},
"./errors": {
"types": "./src/errors.ts",
"import": "./src/errors.ts"
}
},
"scripts": {
"dev": "tsdown src/client.ts src/agent.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/terminal.ts --format esm,cjs --dts --watch --clean",
"build": "tsdown src/client.ts src/agent.ts src/_generated/schema.gen.ts src/rpc.ts src/protocol.ts src/terminal.ts --format esm,cjs --dts --clean",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"generate": "bun run scripts/generate.ts"
},
"dependencies": {
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/openapi-generator": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
+289
View File
@@ -0,0 +1,289 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const CURRENT_SCHEMA_RELEASE = "v0.11.3";
interface GenerateCommandError {
readonly _tag: "GenerateCommandError";
readonly message: string;
}
interface GeneratedPaths {
readonly generatedDir: string;
readonly upstreamSchemaPath: string;
readonly upstreamMetaPath: string;
readonly schemaOutputPath: string;
readonly metaOutputPath: string;
}
const MetaJsonSchema = Schema.Struct({
agentMethods: Schema.Record(Schema.String, Schema.String),
clientMethods: Schema.Record(Schema.String, Schema.String),
version: Schema.Union([Schema.Number, Schema.String]),
});
const UpstreamJsonSchemaSchema = Schema.Struct({
$defs: Schema.Record(Schema.String, Schema.Json),
});
const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
const path = yield* Path.Path;
const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
return {
generatedDir,
upstreamSchemaPath: path.join(generatedDir, "upstream-schema.json"),
upstreamMetaPath: path.join(generatedDir, "upstream-meta.json"),
schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
} satisfies GeneratedPaths;
});
const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
const fs = yield* FileSystem.FileSystem;
const { generatedDir } = yield* getGeneratedPaths();
yield* fs.makeDirectory(generatedDir, { recursive: true });
});
const downloadFile = Effect.fn("downloadFile")(function* (url: string, outputPath: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(outputPath), { recursive: true });
const text = yield* HttpClient.get(url).pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap((response) => response.text),
);
yield* fs.writeFileString(outputPath, text);
});
const downloadSchemas = Effect.fn("downloadSchemas")(function* (tag: string) {
const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
const fs = yield* FileSystem.FileSystem;
const baseUrl = `https://github.com/agentclientprotocol/agent-client-protocol/releases/download/${tag}`;
yield* downloadFile(`${baseUrl}/schema.unstable.json`, upstreamSchemaPath);
yield* downloadFile(`${baseUrl}/meta.unstable.json`, upstreamMetaPath);
yield* Effect.addFinalizer(() =>
Effect.all([fs.remove(upstreamSchemaPath), fs.remove(upstreamMetaPath)]).pipe(
Effect.ignoreCause({ log: true }),
),
);
});
const readJsonFile = Effect.fn("readJsonFile")(function* <
S extends Schema.Top & { readonly DecodingServices: never },
>(schema: S, filePath: string) {
const fs = yield* FileSystem.FileSystem;
const raw = yield* fs.readFileString(filePath);
return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(raw);
});
const writeGeneratedFiles = Effect.fn("writeGeneratedFiles")(function* (
schemaOutput: string,
metaOutput: string,
) {
const fs = yield* FileSystem.FileSystem;
const { metaOutputPath, schemaOutputPath } = yield* getGeneratedPaths();
yield* fs.writeFileString(schemaOutputPath, schemaOutput);
yield* fs.writeFileString(metaOutputPath, metaOutput);
});
function collectSchemaEntries(
chunk: string,
): ReadonlyArray<{ readonly name: string; readonly code: string }> {
const lines = chunk
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith("//"));
const entries: Array<{ name: string; code: string }> = [];
for (let index = 0; index < lines.length; index += 1) {
const typeLine = lines[index];
if (!typeLine?.startsWith("export type ")) {
continue;
}
const constLine = lines[index + 1];
if (!constLine?.startsWith("export const ")) {
throw new Error(`Malformed generator output near: ${typeLine}`);
}
const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
if (!match?.[1]) {
throw new Error(`Could not extract schema name from: ${typeLine}`);
}
entries.push({
name: match[1],
code: `${typeLine}\n${constLine}`,
});
index += 1;
}
return entries;
}
function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map(normalizeNullableTypes);
}
if (value === null || typeof value !== "object") {
return value;
}
const normalizedEntries = Object.entries(value).map(([key, child]) => [
key,
normalizeNullableTypes(child),
]);
const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
string,
typeof Schema.Json.Type
>;
const typeValue = normalizedObject.type;
if (!Array.isArray(typeValue)) {
return normalizedObject;
}
const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
return normalizedObject;
}
const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
if (nonNullTypes.length !== 1) {
return normalizedObject;
}
const nonNullType = nonNullTypes[0]!;
const nextObject: Record<string, typeof Schema.Json.Type> = {};
for (const [key, child] of Object.entries(normalizedObject)) {
if (key !== "type") {
nextObject[key] = child;
}
}
return {
anyOf: [
{
...nextObject,
type: nonNullType,
},
{ type: "null" },
],
};
}
const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: boolean) {
const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
yield* ensureGeneratedDir();
if (!skipDownload) {
yield* Effect.log(`Downloading ACP schema assets for ${CURRENT_SCHEMA_RELEASE}`);
yield* downloadSchemas(CURRENT_SCHEMA_RELEASE);
}
const upstreamSchema = yield* readJsonFile(UpstreamJsonSchemaSchema, upstreamSchemaPath);
const upstreamMeta = yield* readJsonFile(MetaJsonSchema, upstreamMetaPath);
const normalizedDefinitions = Object.fromEntries(
Object.entries(upstreamSchema.$defs).map(([name, schema]) => [
name,
normalizeNullableTypes(schema),
]),
);
const sortedEntries = Object.entries(normalizedDefinitions).toSorted(([left], [right]) =>
left.localeCompare(right),
);
const generatedEntries = new Map<string, string>();
const generator = makeJsonSchemaGenerator();
for (const [name, schema] of sortedEntries) {
generator.addSchema(name, schema as never);
}
const output = generator.generate("openapi-3.1", normalizedDefinitions as never, false).trim();
if (output.length > 0) {
for (const entry of collectSchemaEntries(output)) {
if (!generatedEntries.has(entry.name)) {
generatedEntries.set(entry.name, entry.code);
}
}
}
const prelude = [
`// This file is generated by the effect-acp package. Do not edit manually.`,
`// Current ACP schema release: ${CURRENT_SCHEMA_RELEASE}`,
"",
];
const schemaOutput = [
...prelude,
'import * as Schema from "effect/Schema";',
"",
[...generatedEntries.values()].join("\n\n"),
"",
].join("\n");
const metaOutput = [
...prelude,
`export const AGENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.agentMethods))(upstreamMeta.agentMethods)} as const;`,
"",
`export const CLIENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.clientMethods))(upstreamMeta.clientMethods)} as const;`,
"",
`export const PROTOCOL_VERSION = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.version))(upstreamMeta.version)} as const;`,
"",
].join("\n");
yield* writeGeneratedFiles(schemaOutput, metaOutput);
yield* Effect.log(
`Generated ${generatedEntries.size} ACP schemas from ${CURRENT_SCHEMA_RELEASE}`,
);
const { generatedDir } = yield* getGeneratedPaths();
yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
Effect.flatMap((child) => child.exitCode),
Effect.tap((code) =>
code === 0
? Effect.void
: Effect.fail<GenerateCommandError>({
_tag: "GenerateCommandError",
message: `oxfmt failed with exit code ${code}`,
}),
),
);
});
const generateCommand = Command.make(
"generate",
{
skipDownload: Flag.boolean("skip-download").pipe(Flag.withDefault(false)),
},
({ skipDownload }) => generateSchemas(skipDownload),
).pipe(Command.withDescription("Generate Effect ACP schemas from the pinned ACP release assets."));
const runtimeLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty()]),
NodeServices.layer,
FetchHttpClient.layer,
);
Command.run(generateCommand, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(runtimeLayer),
NodeRuntime.runMain,
);
@@ -0,0 +1,35 @@
// This file is generated by the effect-acp package. Do not edit manually.
// Current ACP schema release: v0.11.3
export const AGENT_METHODS = {
authenticate: "authenticate",
initialize: "initialize",
logout: "logout",
session_cancel: "session/cancel",
session_close: "session/close",
session_fork: "session/fork",
session_list: "session/list",
session_load: "session/load",
session_new: "session/new",
session_prompt: "session/prompt",
session_resume: "session/resume",
session_set_config_option: "session/set_config_option",
session_set_mode: "session/set_mode",
session_set_model: "session/set_model",
} as const;
export const CLIENT_METHODS = {
fs_read_text_file: "fs/read_text_file",
fs_write_text_file: "fs/write_text_file",
session_elicitation: "session/elicitation",
session_elicitation_complete: "session/elicitation/complete",
session_request_permission: "session/request_permission",
session_update: "session/update",
terminal_create: "terminal/create",
terminal_kill: "terminal/kill",
terminal_output: "terminal/output",
terminal_release: "terminal/release",
terminal_wait_for_exit: "terminal/wait_for_exit",
} as const;
export const PROTOCOL_VERSION = 1 as const;
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import { RpcClientError } from "effect/unstable/rpc";
import * as AcpSchema from "../_generated/schema.gen.ts";
import * as AcpError from "../errors.ts";
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
export const callRpc = <A>(
effect: Effect.Effect<A, RpcClientError.RpcClientError | AcpSchema.Error>,
): Effect.Effect<A, AcpError.AcpError> =>
effect.pipe(
Effect.catchTag("RpcClientError", (error) =>
Effect.fail(
new AcpError.AcpTransportError({
detail: error.message,
cause: error,
}),
),
),
Effect.catchIf(Schema.is(AcpSchema.Error), (error) =>
Effect.fail(AcpError.AcpRequestError.fromProtocolError(error)),
),
);
export const runHandler = Effect.fnUntraced(function* <A, B>(
handler: ((payload: A) => Effect.Effect<B, AcpError.AcpError>) | undefined,
payload: A,
method: string,
) {
if (!handler) {
return yield* Effect.fail(AcpError.AcpRequestError.methodNotFound(method).toProtocolError());
}
return yield* handler(payload).pipe(
Effect.mapError((error) =>
Schema.is(AcpError.AcpRequestError)(error)
? error.toProtocolError()
: AcpError.AcpRequestError.internalError(error.message).toProtocolError(),
),
);
});
export function decodeExtRequestRegistration<A, I>(
method: string,
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
) {
return (params: unknown): Effect.Effect<unknown, AcpError.AcpError> =>
Schema.decodeUnknownEffect(payload)(params).pipe(
Effect.mapError((error) =>
AcpError.AcpRequestError.invalidParams(
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
{ issue: error.issue },
),
),
Effect.flatMap((decoded) => handler(decoded)),
);
}
export function decodeExtNotificationRegistration<A, I>(
method: string,
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
) {
return (params: unknown): Effect.Effect<void, AcpError.AcpError> =>
Schema.decodeUnknownEffect(payload)(params).pipe(
Effect.mapError(
(error) =>
new AcpError.AcpProtocolParseError({
detail: `Invalid ${method} notification payload: ${formatSchemaIssue(error.issue)}`,
cause: error,
}),
),
Effect.flatMap((decoded) => handler(decoded)),
);
}
const encoder = new TextEncoder();
const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);
const JsonRpcHeaders = Schema.Array(Schema.Unknown);
export const jsonRpcRequest = <A, I>(method: string, params: Schema.Codec<A, I>) =>
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
id: JsonRpcId,
method: Schema.Literal(method),
params,
headers: JsonRpcHeaders,
});
export const jsonRpcNotification = <A, I>(method: string, params: Schema.Codec<A, I>) =>
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
method: Schema.Literal(method),
params,
});
export const jsonRpcResponse = <A, I>(result: Schema.Codec<A, I>) =>
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
id: JsonRpcId,
result,
});
export const encodeJsonl = <A, I>(schema: Schema.Codec<A, I>, value: A) =>
Effect.map(Schema.encodeEffect(Schema.fromJsonString(schema))(value), (encoded) =>
encoder.encode(`${encoded}\n`),
);
@@ -0,0 +1,54 @@
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Sink from "effect/Sink";
import * as Stdio from "effect/Stdio";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as AcpError from "../errors.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
Stdio.make({
args: Effect.succeed([]),
stdin: handle.stdout,
stdout: () =>
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
typeof chunk === "string" ? encoder.encode(chunk) : chunk,
),
stderr: () => Sink.drain,
});
export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
const output = yield* Queue.unbounded<string>();
return {
stdio: Stdio.make({
args: Effect.succeed([]),
stdin: Stream.fromQueue(input),
stdout: () =>
Sink.forEach((chunk: string | Uint8Array) =>
Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),
),
stderr: () => Sink.drain,
}),
input,
output,
};
});
export const makeTerminationError = (
handle: ChildProcessSpawner.ChildProcessHandle,
): Effect.Effect<AcpError.AcpError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new AcpError.AcpTransportError({
detail: "Failed to determine ACP process exit status",
cause,
}),
onSuccess: (code) => new AcpError.AcpProcessExitedError({ code }),
});
+255
View File
@@ -0,0 +1,255 @@
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import { assert, it } from "@effect/vitest";
import * as AcpAgent from "./agent.ts";
import * as AcpSchema from "./_generated/schema.gen.ts";
import {
encodeJsonl,
jsonRpcNotification,
jsonRpcRequest,
jsonRpcResponse,
} from "./_internal/shared.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const RequestPermissionRequest = jsonRpcRequest(
"session/request_permission",
AcpSchema.RequestPermissionRequest,
);
const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
const SessionCancelNotification = jsonRpcNotification(
"session/cancel",
AcpSchema.CancelNotification,
);
const ExtPingNotification = jsonRpcNotification("x/ping", Schema.Struct({ count: Schema.Number }));
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
it.effect("effect-acp agent handles core agent requests and outbound client requests", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const cancelNotifications = yield* Ref.make<Array<string>>([]);
const extNotifications = yield* Ref.make<Array<number>>([]);
const cancelReceived = yield* Deferred.make<void>();
const extReceived = yield* Deferred.make<void>();
const scope = yield* Scope.make();
const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
yield* Effect.gen(function* () {
const agent = yield* AcpAgent.AcpAgent;
yield* agent.handleInitialize(() =>
Effect.succeed({
protocolVersion: 1,
agentCapabilities: {},
agentInfo: {
name: "mock-agent",
version: "0.0.0",
},
}),
);
yield* agent.handleCancel((notification) =>
Ref.update(cancelNotifications, (current) => [...current, notification.sessionId]).pipe(
Effect.andThen(Deferred.succeed(cancelReceived, undefined)),
),
);
yield* agent.handleExtNotification(
"x/ping",
Schema.Struct({ count: Schema.Number }),
(payload) =>
Ref.update(extNotifications, (current) => [...current, payload.count]).pipe(
Effect.andThen(Deferred.succeed(extReceived, undefined)),
),
);
const permissionFiber = yield* agent.client
.requestPermission({
sessionId: "session-1",
toolCall: {
toolCallId: "tool-1",
title: "Allow mock action",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
})
.pipe(Effect.forkScoped);
const permissionRequest = yield* Schema.decodeEffect(
Schema.fromJsonString(RequestPermissionRequest),
)(yield* Queue.take(output));
assert.equal(permissionRequest.jsonrpc, "2.0");
assert.equal(permissionRequest.method, "session/request_permission");
assert.deepEqual(permissionRequest.params, {
sessionId: "session-1",
toolCall: {
toolCallId: "tool-1",
title: "Allow mock action",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
});
assert.deepEqual(permissionRequest.headers, []);
yield* Queue.offer(
input,
yield* encodeJsonl(RequestPermissionResponse, {
jsonrpc: "2.0",
id: permissionRequest.id,
result: {
outcome: {
outcome: "selected",
optionId: "allow",
},
},
}),
);
const permission = yield* Fiber.join(permissionFiber);
assert.equal(permission.outcome.outcome, "selected");
yield* Queue.offer(
input,
yield* encodeJsonl(InitializeRequest, {
jsonrpc: "2.0",
id: 2,
method: "initialize",
params: {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
},
headers: [],
}),
);
const initResponse = yield* Schema.decodeEffect(Schema.fromJsonString(InitializeResponse))(
yield* Queue.take(output),
);
assert.deepEqual(initResponse, {
jsonrpc: "2.0",
id: 2,
result: {
protocolVersion: 1,
agentCapabilities: {},
agentInfo: {
name: "mock-agent",
version: "0.0.0",
},
},
});
yield* Queue.offer(
input,
yield* encodeJsonl(SessionCancelNotification, {
jsonrpc: "2.0",
method: "session/cancel",
params: {
sessionId: "session-1",
},
}),
);
yield* Queue.offer(
input,
yield* encodeJsonl(ExtPingNotification, {
jsonrpc: "2.0",
method: "x/ping",
params: { count: 2 },
}),
);
yield* Deferred.await(cancelReceived);
yield* Deferred.await(extReceived);
assert.deepEqual(yield* Ref.get(cancelNotifications), ["session-1"]);
assert.deepEqual(yield* Ref.get(extNotifications), [2]);
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
}),
);
it.effect("effect-acp agent uses distinct ids for RPC calls and extension requests", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const scope = yield* Scope.make();
const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
yield* Effect.gen(function* () {
const agent = yield* AcpAgent.AcpAgent;
const permissionFiber = yield* agent.client
.requestPermission({
sessionId: "session-1",
toolCall: {
toolCallId: "tool-1",
title: "Allow mock action",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
})
.pipe(Effect.forkScoped);
const extFiber = yield* agent.client
.extRequest("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const firstOutbound = yield* Queue.take(output);
const secondOutbound = yield* Queue.take(output);
const decodedPermission = Schema.decodeEffect(
Schema.fromJsonString(RequestPermissionRequest),
);
const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
const firstIsPermission = yield* decodedPermission(firstOutbound).pipe(
Effect.match({
onFailure: () => false,
onSuccess: () => true,
}),
);
const permissionRequest = firstIsPermission
? yield* decodedPermission(firstOutbound)
: yield* decodedPermission(secondOutbound);
const extRequest = firstIsPermission
? yield* decodedExt(secondOutbound)
: yield* decodedExt(firstOutbound);
assert.notEqual(permissionRequest.id, extRequest.id);
yield* Queue.offer(
input,
yield* encodeJsonl(RequestPermissionResponse, {
jsonrpc: "2.0",
id: permissionRequest.id,
result: {
outcome: {
outcome: "selected",
optionId: "allow",
},
},
}),
);
yield* Queue.offer(
input,
yield* encodeJsonl(ExtResponse, {
jsonrpc: "2.0",
id: extRequest.id,
result: { ok: true },
}),
);
const permission = yield* Fiber.join(permissionFiber);
assert.equal(permission.outcome.outcome, "selected");
assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
}),
);
+519
View File
@@ -0,0 +1,519 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Stdio from "effect/Stdio";
import * as RpcClient from "effect/unstable/rpc/RpcClient";
import * as RpcServer from "effect/unstable/rpc/RpcServer";
import * as AcpSchema from "./_generated/schema.gen.ts";
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts";
import * as AcpError from "./errors.ts";
import * as AcpProtocol from "./protocol.ts";
import * as AcpRpcs from "./rpc.ts";
import {
callRpc,
decodeExtNotificationRegistration,
decodeExtRequestRegistration,
runHandler,
} from "./_internal/shared.ts";
import * as AcpTerminal from "./terminal.ts";
export interface AcpAgentOptions {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
}
export interface AcpAgentShape {
readonly raw: {
/**
* Stream of inbound ACP notifications observed on the connection.
*/
readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
/**
* Sends a generic ACP extension request.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly request: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, AcpError.AcpError>;
/**
* Sends a generic ACP extension notification.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
};
readonly client: {
/**
* Requests client permission for an operation.
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
*/
readonly requestPermission: (
payload: AcpSchema.RequestPermissionRequest,
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;
/**
* Requests structured user input from the client.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
*/
readonly elicit: (
payload: AcpSchema.ElicitationRequest,
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;
/**
* Requests file contents from the client.
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
*/
readonly readTextFile: (
payload: AcpSchema.ReadTextFileRequest,
) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;
/**
* Writes a text file through the client.
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
*/
readonly writeTextFile: (
payload: AcpSchema.WriteTextFileRequest,
) => Effect.Effect<AcpSchema.WriteTextFileResponse, AcpError.AcpError>;
/**
* Creates a terminal on the client side.
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
*/
readonly createTerminal: (
payload: AcpSchema.CreateTerminalRequest,
) => Effect.Effect<AcpTerminal.AcpTerminal, AcpError.AcpError>;
/**
* Sends a `session/update` notification to the client.
* @see https://agentclientprotocol.com/protocol/schema#session/update
*/
readonly sessionUpdate: (
payload: AcpSchema.SessionNotification,
) => Effect.Effect<void, AcpError.AcpError>;
/**
* Sends a `session/elicitation/complete` notification to the client.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
*/
readonly elicitationComplete: (
payload: AcpSchema.ElicitationCompleteNotification,
) => Effect.Effect<void, AcpError.AcpError>;
/**
* Sends an ACP extension request to the client.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extRequest: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, AcpError.AcpError>;
/**
* Sends an ACP extension notification to the client.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly extNotification: (
method: string,
payload: unknown,
) => Effect.Effect<void, AcpError.AcpError>;
};
/**
* Registers a handler for `initialize`.
* @see https://agentclientprotocol.com/protocol/schema#initialize
*/
readonly handleInitialize: (
handler: (
request: AcpSchema.InitializeRequest,
) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `authenticate`.
* @see https://agentclientprotocol.com/protocol/schema#authenticate
*/
readonly handleAuthenticate: (
handler: (
request: AcpSchema.AuthenticateRequest,
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleLogout: (
handler: (
request: AcpSchema.LogoutRequest,
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleCreateSession: (
handler: (
request: AcpSchema.NewSessionRequest,
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleLoadSession: (
handler: (
request: AcpSchema.LoadSessionRequest,
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleListSessions: (
handler: (
request: AcpSchema.ListSessionsRequest,
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleForkSession: (
handler: (
request: AcpSchema.ForkSessionRequest,
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleResumeSession: (
handler: (
request: AcpSchema.ResumeSessionRequest,
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleCloseSession: (
handler: (
request: AcpSchema.CloseSessionRequest,
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleSetSessionModel: (
handler: (
request: AcpSchema.SetSessionModelRequest,
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleSetSessionConfigOption: (
handler: (
request: AcpSchema.SetSessionConfigOptionRequest,
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handlePrompt: (
handler: (
request: AcpSchema.PromptRequest,
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `session/cancel`.
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
*/
readonly handleCancel: (
handler: (notification: AcpSchema.CancelNotification) => Effect.Effect<void, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleUnknownExtRequest: (
handler: (method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleUnknownExtNotification: (
handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleExtRequest: <A, I>(
method: string,
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
) => Effect.Effect<void>;
readonly handleExtNotification: <A, I>(
method: string,
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
) => Effect.Effect<void>;
}
export class AcpAgent extends Context.Service<AcpAgent, AcpAgentShape>()("effect-acp/AcpAgent") {}
interface AcpCoreAgentRequestHandlers {
initialize?: (
request: AcpSchema.InitializeRequest,
) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
authenticate?: (
request: AcpSchema.AuthenticateRequest,
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
logout?: (
request: AcpSchema.LogoutRequest,
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
createSession?: (
request: AcpSchema.NewSessionRequest,
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
loadSession?: (
request: AcpSchema.LoadSessionRequest,
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
listSessions?: (
request: AcpSchema.ListSessionsRequest,
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
forkSession?: (
request: AcpSchema.ForkSessionRequest,
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
resumeSession?: (
request: AcpSchema.ResumeSessionRequest,
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
closeSession?: (
request: AcpSchema.CloseSessionRequest,
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
setSessionModel?: (
request: AcpSchema.SetSessionModelRequest,
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
setSessionConfigOption?: (
request: AcpSchema.SetSessionConfigOptionRequest,
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
prompt?: (
request: AcpSchema.PromptRequest,
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
}
const decodeCancelNotification = Schema.decodeUnknownEffect(AcpSchema.CancelNotification);
export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
stdio: Stdio.Stdio,
options: AcpAgentOptions = {},
): Effect.fn.Return<AcpAgentShape, never, Scope.Scope> {
const coreHandlers: AcpCoreAgentRequestHandlers = {};
const cancelHandlers: Array<
(notification: AcpSchema.CancelNotification) => Effect.Effect<void, AcpError.AcpError>
> = [];
const extRequestHandlers = new Map<
string,
(params: unknown) => Effect.Effect<unknown, AcpError.AcpError>
>();
const extNotificationHandlers = new Map<
string,
(params: unknown) => Effect.Effect<void, AcpError.AcpError>
>();
let unknownExtRequestHandler:
| ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
| undefined;
let unknownExtNotificationHandler:
| ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
| undefined;
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(AcpRpcs.AgentRpcs.requests.keys()),
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
...(options.logger ? { logger: options.logger } : {}),
onNotification: (notification) => {
if (
notification._tag === "ExtNotification" &&
notification.method === AGENT_METHODS.session_cancel
) {
return decodeCancelNotification(notification.params).pipe(
Effect.mapError(
(error) =>
new AcpError.AcpProtocolParseError({
detail: `Invalid ${AGENT_METHODS.session_cancel} notification payload`,
cause: error,
}),
),
Effect.flatMap((decoded) =>
Effect.forEach(cancelHandlers, (handler) => handler(decoded), { discard: true }),
),
);
}
if (notification._tag !== "ExtNotification") {
return Effect.void;
}
const handler = extNotificationHandlers.get(notification.method);
if (handler) {
return handler(notification.params);
}
return unknownExtNotificationHandler
? unknownExtNotificationHandler(notification.method, notification.params)
: Effect.void;
},
onExtRequest: (method, params) => {
const handler = extRequestHandlers.get(method);
if (handler) {
return handler(params);
}
return unknownExtRequestHandler
? unknownExtRequestHandler(method, params)
: Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
},
});
const agentHandlerLayer = AcpRpcs.AgentRpcs.toLayer(
AcpRpcs.AgentRpcs.of({
[AGENT_METHODS.initialize]: (payload) =>
runHandler(coreHandlers.initialize, payload, AGENT_METHODS.initialize),
[AGENT_METHODS.authenticate]: (payload) =>
runHandler(coreHandlers.authenticate, payload, AGENT_METHODS.authenticate),
[AGENT_METHODS.logout]: (payload) =>
runHandler(coreHandlers.logout, payload, AGENT_METHODS.logout),
[AGENT_METHODS.session_new]: (payload) =>
runHandler(coreHandlers.createSession, payload, AGENT_METHODS.session_new),
[AGENT_METHODS.session_load]: (payload) =>
runHandler(coreHandlers.loadSession, payload, AGENT_METHODS.session_load),
[AGENT_METHODS.session_list]: (payload) =>
runHandler(coreHandlers.listSessions, payload, AGENT_METHODS.session_list),
[AGENT_METHODS.session_fork]: (payload) =>
runHandler(coreHandlers.forkSession, payload, AGENT_METHODS.session_fork),
[AGENT_METHODS.session_resume]: (payload) =>
runHandler(coreHandlers.resumeSession, payload, AGENT_METHODS.session_resume),
[AGENT_METHODS.session_close]: (payload) =>
runHandler(coreHandlers.closeSession, payload, AGENT_METHODS.session_close),
[AGENT_METHODS.session_set_model]: (payload) =>
runHandler(coreHandlers.setSessionModel, payload, AGENT_METHODS.session_set_model),
[AGENT_METHODS.session_set_config_option]: (payload) =>
runHandler(
coreHandlers.setSessionConfigOption,
payload,
AGENT_METHODS.session_set_config_option,
),
[AGENT_METHODS.session_prompt]: (payload) =>
runHandler(coreHandlers.prompt, payload, AGENT_METHODS.session_prompt),
}),
);
yield* RpcServer.make(AcpRpcs.AgentRpcs).pipe(
Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
Effect.provide(agentHandlerLayer),
Effect.forkScoped,
);
let nextRpcRequestId = 1n << 32n;
const rpc = yield* RpcClient.make(AcpRpcs.ClientRpcs, {
generateRequestId: () => nextRpcRequestId++ as never,
}).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
return AcpAgent.of({
raw: {
notifications: transport.incoming,
request: transport.request,
notify: transport.notify,
},
client: {
requestPermission: (payload) =>
callRpc(rpc[CLIENT_METHODS.session_request_permission](payload)),
elicit: (payload) => callRpc(rpc[CLIENT_METHODS.session_elicitation](payload)),
readTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_read_text_file](payload)),
writeTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_write_text_file](payload)),
createTerminal: (payload) =>
callRpc(rpc[CLIENT_METHODS.terminal_create](payload)).pipe(
Effect.map((response) =>
AcpTerminal.makeTerminal({
sessionId: payload.sessionId,
terminalId: response.terminalId,
output: callRpc(
rpc[CLIENT_METHODS.terminal_output]({
sessionId: payload.sessionId,
terminalId: response.terminalId,
}),
),
waitForExit: callRpc(
rpc[CLIENT_METHODS.terminal_wait_for_exit]({
sessionId: payload.sessionId,
terminalId: response.terminalId,
}),
),
kill: callRpc(
rpc[CLIENT_METHODS.terminal_kill]({
sessionId: payload.sessionId,
terminalId: response.terminalId,
}),
),
release: callRpc(
rpc[CLIENT_METHODS.terminal_release]({
sessionId: payload.sessionId,
terminalId: response.terminalId,
}),
),
}),
),
),
sessionUpdate: (payload) => transport.notify(CLIENT_METHODS.session_update, payload),
elicitationComplete: (payload) =>
transport.notify(CLIENT_METHODS.session_elicitation_complete, payload),
extRequest: transport.request,
extNotification: transport.notify,
},
handleInitialize: (handler) =>
Effect.suspend(() => {
coreHandlers.initialize = handler;
return Effect.void;
}),
handleAuthenticate: (handler) =>
Effect.suspend(() => {
coreHandlers.authenticate = handler;
return Effect.void;
}),
handleLogout: (handler) =>
Effect.suspend(() => {
coreHandlers.logout = handler;
return Effect.void;
}),
handleCreateSession: (handler) =>
Effect.suspend(() => {
coreHandlers.createSession = handler;
return Effect.void;
}),
handleLoadSession: (handler) =>
Effect.suspend(() => {
coreHandlers.loadSession = handler;
return Effect.void;
}),
handleListSessions: (handler) =>
Effect.suspend(() => {
coreHandlers.listSessions = handler;
return Effect.void;
}),
handleForkSession: (handler) =>
Effect.suspend(() => {
coreHandlers.forkSession = handler;
return Effect.void;
}),
handleResumeSession: (handler) =>
Effect.suspend(() => {
coreHandlers.resumeSession = handler;
return Effect.void;
}),
handleCloseSession: (handler) =>
Effect.suspend(() => {
coreHandlers.closeSession = handler;
return Effect.void;
}),
handleSetSessionModel: (handler) =>
Effect.suspend(() => {
coreHandlers.setSessionModel = handler;
return Effect.void;
}),
handleSetSessionConfigOption: (handler) =>
Effect.suspend(() => {
coreHandlers.setSessionConfigOption = handler;
return Effect.void;
}),
handlePrompt: (handler) =>
Effect.suspend(() => {
coreHandlers.prompt = handler;
return Effect.void;
}),
handleCancel: (handler) =>
Effect.suspend(() => {
cancelHandlers.push(handler);
return Effect.void;
}),
handleUnknownExtRequest: (handler) =>
Effect.suspend(() => {
unknownExtRequestHandler = handler;
return Effect.void;
}),
handleUnknownExtNotification: (handler) =>
Effect.suspend(() => {
unknownExtNotificationHandler = handler;
return Effect.void;
}),
handleExtRequest: (method, payload, handler) =>
Effect.suspend(() => {
extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
return Effect.void;
}),
handleExtNotification: (method, payload, handler) =>
Effect.suspend(() => {
extNotificationHandlers.set(
method,
decodeExtNotificationRegistration(method, payload, handler),
);
return Effect.void;
}),
});
});
export const layer = (stdio: Stdio.Stdio, options: AcpAgentOptions = {}): Layer.Layer<AcpAgent> =>
Layer.effect(AcpAgent, make(stdio, options));
export const layerStdio = (
options: AcpAgentOptions = {},
): Layer.Layer<AcpAgent, never, Stdio.Stdio> =>
Layer.effect(
AcpAgent,
Effect.flatMap(Effect.service(Stdio.Stdio), (stdio) => make(stdio, options)),
);
+450
View File
@@ -0,0 +1,450 @@
import * as Path from "effect/Path";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import * as AcpClient from "./client.ts";
import * as AcpSchema from "./_generated/schema.gen.ts";
import * as AcpError from "./errors.ts";
import { encodeJsonl, jsonRpcRequest, jsonRpcResponse } from "./_internal/shared.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
);
it.layer(NodeServices.layer)("effect-acp client", (it) => {
const makeHandle = (env?: Record<string, string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
cwd: path.join(import.meta.dirname, ".."),
shell: process.platform === "win32",
...(env ? { env: { ...process.env, ...env } } : {}),
});
return yield* spawner.spawn(command);
});
it.effect("initializes, prompts, receives updates, and handles permission requests", () =>
Effect.gen(function* () {
const updates = yield* Ref.make<Array<unknown>>([]);
const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
const typedRequests = yield* Ref.make<Array<unknown>>([]);
const typedNotifications = yield* Ref.make<Array<unknown>>([]);
const handle = yield* makeHandle();
const scope = yield* Scope.make();
const acpLayer = AcpClient.layerChildProcess(handle);
const context = yield* Layer.buildWithScope(acpLayer, scope);
const ext = yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpClient;
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
yield* acp.handleElicitation(() =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
},
}),
);
yield* acp.handleSessionUpdate((notification) =>
Ref.update(updates, (current) => [...current, notification]),
);
yield* acp.handleElicitationComplete((notification) =>
Ref.update(elicitationCompletions, (current) => [...current, notification]),
);
yield* acp.handleExtRequest(
"x/typed_request",
Schema.Struct({ message: Schema.String }),
(payload) =>
Ref.update(typedRequests, (current) => [...current, payload]).pipe(
Effect.as({
ok: true,
echoedMessage: payload.message,
}),
),
);
yield* acp.handleExtNotification(
"x/typed_notification",
Schema.Struct({ count: Schema.Number }),
(payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
);
const init = yield* acp.agent.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
});
assert.equal(init.protocolVersion, 1);
yield* acp.agent.authenticate({ methodId: "cursor_login" });
const session = yield* acp.agent.createSession({
cwd: process.cwd(),
mcpServers: [],
});
assert.equal(session.sessionId, "mock-session-1");
const prompt = yield* acp.agent.prompt({
sessionId: session.sessionId,
prompt: [{ type: "text", text: "hello" }],
});
assert.equal(prompt.stopReason, "end_turn");
const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
assert.equal(streamed.length, 2);
assert.equal(streamed[0]?._tag, "SessionUpdate");
assert.equal(streamed[1]?._tag, "ElicitationComplete");
assert.equal((yield* Ref.get(updates)).length, 1);
assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
return yield* acp.raw.request("x/echo", {
hello: "world",
});
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
assert.deepEqual(ext, {
echoedMethod: "x/echo",
echoedParams: {
hello: "world",
},
});
}),
);
it.effect(
"returns formatted invalid params when a typed extension request payload is wrong",
() =>
Effect.gen(function* () {
const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
const scope = yield* Scope.make();
const acpLayer = AcpClient.layerChildProcess(handle);
const context = yield* Layer.buildWithScope(acpLayer, scope);
const result = yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpClient;
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
yield* acp.handleElicitation(() =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
},
}),
);
yield* acp.handleExtRequest(
"x/typed_request",
Schema.Struct({ message: Schema.String }),
() => Effect.succeed({ ok: true }),
);
yield* acp.agent.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
});
yield* acp.agent.authenticate({ methodId: "cursor_login" });
const session = yield* acp.agent.createSession({
cwd: process.cwd(),
mcpServers: [],
});
return yield* Effect.exit(
acp.agent.prompt({
sessionId: session.sessionId,
prompt: [{ type: "text", text: "hello" }],
}),
);
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
if (result._tag !== "Failure") {
assert.fail("Expected prompt to fail for invalid typed extension payload");
}
const rendered = Cause.pretty(result.cause);
assert.include(rendered, "Invalid x/typed_request payload:");
assert.include(rendered, "Expected string, got 123");
}),
);
it.effect("replays buffered notifications to handlers registered after they arrive", () =>
Effect.gen(function* () {
const updates = yield* Ref.make<Array<unknown>>([]);
const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
const typedRequests = yield* Ref.make<Array<unknown>>([]);
const typedNotifications = yield* Ref.make<Array<unknown>>([]);
const handle = yield* makeHandle();
const scope = yield* Scope.make();
const acpLayer = AcpClient.layerChildProcess(handle);
const context = yield* Layer.buildWithScope(acpLayer, scope);
yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpClient;
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
yield* acp.handleElicitation(() =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
},
}),
);
yield* acp.handleExtRequest(
"x/typed_request",
Schema.Struct({ message: Schema.String }),
(payload) =>
Ref.update(typedRequests, (current) => [...current, payload]).pipe(
Effect.as({
ok: true,
echoedMessage: payload.message,
}),
),
);
yield* acp.handleExtNotification(
"x/typed_notification",
Schema.Struct({ count: Schema.Number }),
(payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
);
yield* acp.agent.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
});
yield* acp.agent.authenticate({ methodId: "cursor_login" });
const session = yield* acp.agent.createSession({
cwd: process.cwd(),
mcpServers: [],
});
yield* acp.agent.prompt({
sessionId: session.sessionId,
prompt: [{ type: "text", text: "hello" }],
});
yield* acp.handleSessionUpdate((notification) =>
Ref.update(updates, (current) => [...current, notification]),
);
yield* acp.handleElicitationComplete((notification) =>
Ref.update(elicitationCompletions, (current) => [...current, notification]),
);
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 }]);
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
}),
);
it.effect("continues dispatching session updates after one handler fails", () =>
Effect.gen(function* () {
const successfulHandlers = yield* Ref.make(0);
const handle = yield* makeHandle();
const scope = yield* Scope.make();
const acpLayer = AcpClient.layerChildProcess(handle);
const context = yield* Layer.buildWithScope(acpLayer, scope);
yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpClient;
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
yield* acp.handleElicitation(() =>
Effect.succeed({
action: {
action: "accept",
content: {
approved: true,
},
},
}),
);
yield* acp.handleExtRequest(
"x/typed_request",
Schema.Struct({ message: Schema.String }),
() => Effect.succeed({ ok: true }),
);
yield* acp.handleExtNotification(
"x/typed_notification",
Schema.Struct({ count: Schema.Number }),
() => Effect.void,
);
yield* acp.handleSessionUpdate(() =>
Effect.fail(AcpError.AcpRequestError.internalError("session update handler failed")),
);
yield* acp.handleSessionUpdate(() => Ref.update(successfulHandlers, (count) => count + 1));
yield* acp.agent.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
});
yield* acp.agent.authenticate({ methodId: "cursor_login" });
const session = yield* acp.agent.createSession({
cwd: process.cwd(),
mcpServers: [],
});
yield* acp.agent.prompt({
sessionId: session.sessionId,
prompt: [{ type: "text", text: "hello" }],
});
assert.equal(yield* Ref.get(successfulHandlers), 1);
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
}),
);
it.effect("uses distinct ids for RPC calls and extension requests", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const scope = yield* Scope.make();
const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
const initializeFiber = yield* acp.agent
.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: {
name: "effect-acp-test",
version: "0.0.0",
},
})
.pipe(Effect.forkScoped);
const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped);
const firstOutbound = yield* Queue.take(output);
const secondOutbound = yield* Queue.take(output);
const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(
Effect.match({
onFailure: () => false,
onSuccess: () => true,
}),
);
const initializeRequest = firstIsInitialize
? yield* decodedInitialize(firstOutbound)
: yield* decodedInitialize(secondOutbound);
const extRequest = firstIsInitialize
? yield* decodedExt(secondOutbound)
: yield* decodedExt(firstOutbound);
assert.notEqual(initializeRequest.id, extRequest.id);
yield* Queue.offer(
input,
yield* encodeJsonl(InitializeResponse, {
jsonrpc: "2.0",
id: initializeRequest.id,
result: {
protocolVersion: 1,
agentCapabilities: {},
agentInfo: {
name: "mock-agent",
version: "0.0.0",
},
},
}),
);
yield* Queue.offer(
input,
yield* encodeJsonl(ExtResponse, {
jsonrpc: "2.0",
id: extRequest.id,
result: { ok: true },
}),
);
yield* Fiber.join(initializeFiber);
assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
yield* Scope.close(scope, Exit.void);
}),
);
});
+569
View File
@@ -0,0 +1,569 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Stdio from "effect/Stdio";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as RpcClient from "effect/unstable/rpc/RpcClient";
import * as RpcServer from "effect/unstable/rpc/RpcServer";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as AcpError from "./errors.ts";
import * as AcpProtocol from "./protocol.ts";
import * as AcpRpcs from "./rpc.ts";
import * as AcpSchema from "./_generated/schema.gen.ts";
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts";
import {
callRpc,
decodeExtNotificationRegistration,
decodeExtRequestRegistration,
runHandler,
} from "./_internal/shared.ts";
import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
export interface AcpClientOptions {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
}
type AcpClientRaw = {
readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
};
export interface AcpClientShape {
readonly raw: AcpClientRaw;
readonly agent: {
/**
* Initializes the ACP session and negotiates capabilities.
* @see https://agentclientprotocol.com/protocol/schema#initialize
*/
readonly initialize: (
payload: AcpSchema.InitializeRequest,
) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
/**
* Performs ACP authentication when the agent requires it.
* @see https://agentclientprotocol.com/protocol/schema#authenticate
*/
readonly authenticate: (
payload: AcpSchema.AuthenticateRequest,
) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
/**
* Logs out the current ACP identity.
* @see https://agentclientprotocol.com/protocol/schema#logout
*/
readonly logout: (
payload: AcpSchema.LogoutRequest,
) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
/**
* Starts a new ACP session.
* @see https://agentclientprotocol.com/protocol/schema#session/new
*/
readonly createSession: (
payload: AcpSchema.NewSessionRequest,
) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
/**
* Loads a previously saved ACP session.
* @see https://agentclientprotocol.com/protocol/schema#session/load
*/
readonly loadSession: (
payload: AcpSchema.LoadSessionRequest,
) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
/**
* Lists available ACP sessions.
* @see https://agentclientprotocol.com/protocol/schema#session/list
*/
readonly listSessions: (
payload: AcpSchema.ListSessionsRequest,
) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
/**
* Forks an ACP session.
* @see https://agentclientprotocol.com/protocol/schema#session/fork
*/
readonly forkSession: (
payload: AcpSchema.ForkSessionRequest,
) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
/**
* Resumes an ACP session.
* @see https://agentclientprotocol.com/protocol/schema#session/resume
*/
readonly resumeSession: (
payload: AcpSchema.ResumeSessionRequest,
) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
/**
* Closes an ACP session.
* @see https://agentclientprotocol.com/protocol/schema#session/close
*/
readonly closeSession: (
payload: AcpSchema.CloseSessionRequest,
) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
/**
* Selects the active model for a session.
* @see https://agentclientprotocol.com/protocol/schema#session/set_model
*/
readonly setSessionModel: (
payload: AcpSchema.SetSessionModelRequest,
) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
/**
* Updates a session configuration option.
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
*/
readonly setSessionConfigOption: (
payload: AcpSchema.SetSessionConfigOptionRequest,
) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
/**
* Sends a prompt turn to the agent.
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
*/
readonly prompt: (
payload: AcpSchema.PromptRequest,
) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
/**
* Sends a real ACP `session/cancel` notification.
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
*/
readonly cancel: (
payload: AcpSchema.CancelNotification,
) => Effect.Effect<void, AcpError.AcpError>;
};
/**
* Registers a handler for `session/request_permission`.
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
*/
readonly handleRequestPermission: (
handler: (
request: AcpSchema.RequestPermissionRequest,
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `session/elicitation`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
*/
readonly handleElicitation: (
handler: (
request: AcpSchema.ElicitationRequest,
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `fs/read_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
*/
readonly handleReadTextFile: (
handler: (
request: AcpSchema.ReadTextFileRequest,
) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `fs/write_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
*/
readonly handleWriteTextFile: (
handler: (
request: AcpSchema.WriteTextFileRequest,
) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `terminal/create`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
*/
readonly handleCreateTerminal: (
handler: (
request: AcpSchema.CreateTerminalRequest,
) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `terminal/output`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/output
*/
readonly handleTerminalOutput: (
handler: (
request: AcpSchema.TerminalOutputRequest,
) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `terminal/wait_for_exit`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
*/
readonly handleTerminalWaitForExit: (
handler: (
request: AcpSchema.WaitForTerminalExitRequest,
) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `terminal/kill`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/kill
*/
readonly handleTerminalKill: (
handler: (
request: AcpSchema.KillTerminalRequest,
) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `terminal/release`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/release
*/
readonly handleTerminalRelease: (
handler: (
request: AcpSchema.ReleaseTerminalRequest,
) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `session/update`.
* @see https://agentclientprotocol.com/protocol/schema#session/update
*/
readonly handleSessionUpdate: (
handler: (
notification: AcpSchema.SessionNotification,
) => Effect.Effect<void, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a handler for `session/elicitation/complete`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
*/
readonly handleElicitationComplete: (
handler: (
notification: AcpSchema.ElicitationCompleteNotification,
) => Effect.Effect<void, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a fallback extension request handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleUnknownExtRequest: (
handler: (method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a fallback extension notification handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleUnknownExtNotification: (
handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a typed extension request handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleExtRequest: <A, I>(
method: string,
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
) => Effect.Effect<void>;
/**
* Registers a typed extension notification handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleExtNotification: <A, I>(
method: string,
payload: Schema.Codec<A, I>,
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
) => Effect.Effect<void>;
}
export class AcpClient extends Context.Service<AcpClient, AcpClientShape>()(
"effect-acp/AcpClient",
) {}
interface AcpCoreRequestHandlers {
requestPermission?: (
request: AcpSchema.RequestPermissionRequest,
) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;
elicitation?: (
request: AcpSchema.ElicitationRequest,
) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;
readTextFile?: (
request: AcpSchema.ReadTextFileRequest,
) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;
writeTextFile?: (
request: AcpSchema.WriteTextFileRequest,
) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>;
createTerminal?: (
request: AcpSchema.CreateTerminalRequest,
) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>;
terminalOutput?: (
request: AcpSchema.TerminalOutputRequest,
) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
terminalWaitForExit?: (
request: AcpSchema.WaitForTerminalExitRequest,
) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
terminalKill?: (
request: AcpSchema.KillTerminalRequest,
) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>;
terminalRelease?: (
request: AcpSchema.ReleaseTerminalRequest,
) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>;
}
interface AcpNotificationHandlers {
readonly sessionUpdate: BufferedNotificationHandler<AcpSchema.SessionNotification>;
readonly elicitationComplete: BufferedNotificationHandler<AcpSchema.ElicitationCompleteNotification>;
}
interface BufferedNotificationHandler<A> {
readonly handlers: Array<(notification: A) => Effect.Effect<void, AcpError.AcpError>>;
readonly pending: Array<A>;
}
export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
stdio: Stdio.Stdio,
options: AcpClientOptions = {},
terminationError?: Effect.Effect<AcpError.AcpError>,
): Effect.fn.Return<AcpClientShape, never, Scope.Scope> {
const coreHandlers: AcpCoreRequestHandlers = {};
const notificationHandlers: AcpNotificationHandlers = {
sessionUpdate: { handlers: [], pending: [] },
elicitationComplete: { handlers: [], pending: [] },
};
const extRequestHandlers = new Map<
string,
(params: unknown) => Effect.Effect<unknown, AcpError.AcpError>
>();
const extNotificationHandlers = new Map<
string,
(params: unknown) => Effect.Effect<void, AcpError.AcpError>
>();
let unknownExtRequestHandler:
| ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
| undefined;
let unknownExtNotificationHandler:
| ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
| undefined;
const runNotificationHandlers = <A>(
registration: BufferedNotificationHandler<A>,
notification: A,
) =>
Effect.forEach(
registration.handlers,
(handler) => handler(notification).pipe(Effect.catch(() => Effect.void)),
{ discard: true },
);
const flushBufferedNotifications = <A>(registration: BufferedNotificationHandler<A>) =>
Effect.suspend(() => {
if (registration.handlers.length === 0 || registration.pending.length === 0) {
return Effect.void;
}
const pending = registration.pending.splice(0, registration.pending.length);
return Effect.forEach(
pending,
(notification) => runNotificationHandlers(registration, notification),
{
discard: true,
},
);
});
const dispatchNotification = (notification: AcpProtocol.AcpIncomingNotification) => {
switch (notification._tag) {
case "SessionUpdate": {
if (notificationHandlers.sessionUpdate.handlers.length === 0) {
notificationHandlers.sessionUpdate.pending.push(notification.params);
return Effect.void;
}
return runNotificationHandlers(notificationHandlers.sessionUpdate, notification.params);
}
case "ElicitationComplete": {
if (notificationHandlers.elicitationComplete.handlers.length === 0) {
notificationHandlers.elicitationComplete.pending.push(notification.params);
return Effect.void;
}
return runNotificationHandlers(
notificationHandlers.elicitationComplete,
notification.params,
);
}
case "ExtNotification": {
const handler = extNotificationHandlers.get(notification.method);
if (handler) {
return handler(notification.params);
}
return unknownExtNotificationHandler
? unknownExtNotificationHandler(notification.method, notification.params)
: Effect.void;
}
}
};
const dispatchExtRequest = (method: string, params: unknown) => {
const handler = extRequestHandlers.get(method);
if (handler) {
return handler(params);
}
return unknownExtRequestHandler
? unknownExtRequestHandler(method, params)
: Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
};
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio: stdio,
...(terminationError ? { terminationError } : {}),
serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()),
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
...(options.logger ? { logger: options.logger } : {}),
onNotification: dispatchNotification,
onExtRequest: dispatchExtRequest,
});
const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer(
AcpRpcs.ClientRpcs.of({
[CLIENT_METHODS.session_request_permission]: (payload) =>
runHandler(
coreHandlers.requestPermission,
payload,
CLIENT_METHODS.session_request_permission,
),
[CLIENT_METHODS.session_elicitation]: (payload) =>
runHandler(coreHandlers.elicitation, payload, CLIENT_METHODS.session_elicitation),
[CLIENT_METHODS.fs_read_text_file]: (payload) =>
runHandler(coreHandlers.readTextFile, payload, CLIENT_METHODS.fs_read_text_file),
[CLIENT_METHODS.fs_write_text_file]: (payload) =>
runHandler(coreHandlers.writeTextFile, payload, CLIENT_METHODS.fs_write_text_file).pipe(
Effect.map((result) => result ?? {}),
),
[CLIENT_METHODS.terminal_create]: (payload) =>
runHandler(coreHandlers.createTerminal, payload, CLIENT_METHODS.terminal_create),
[CLIENT_METHODS.terminal_output]: (payload) =>
runHandler(coreHandlers.terminalOutput, payload, CLIENT_METHODS.terminal_output),
[CLIENT_METHODS.terminal_wait_for_exit]: (payload) =>
runHandler(
coreHandlers.terminalWaitForExit,
payload,
CLIENT_METHODS.terminal_wait_for_exit,
),
[CLIENT_METHODS.terminal_kill]: (payload) =>
runHandler(coreHandlers.terminalKill, payload, CLIENT_METHODS.terminal_kill).pipe(
Effect.map((result) => result ?? {}),
),
[CLIENT_METHODS.terminal_release]: (payload) =>
runHandler(coreHandlers.terminalRelease, payload, CLIENT_METHODS.terminal_release).pipe(
Effect.map((result) => result ?? {}),
),
}),
);
yield* RpcServer.make(AcpRpcs.ClientRpcs).pipe(
Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
Effect.provide(clientHandlerLayer),
Effect.forkScoped,
);
let nextRpcRequestId = 1n << 32n;
const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs, {
generateRequestId: () => nextRpcRequestId++ as never,
}).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
return AcpClient.of({
raw: {
notifications: transport.incoming,
request: transport.request,
notify: transport.notify,
},
agent: {
initialize: (payload) => callRpc(rpc[AGENT_METHODS.initialize](payload)),
authenticate: (payload) => callRpc(rpc[AGENT_METHODS.authenticate](payload)),
logout: (payload) => callRpc(rpc[AGENT_METHODS.logout](payload)),
createSession: (payload) => callRpc(rpc[AGENT_METHODS.session_new](payload)),
loadSession: (payload) => callRpc(rpc[AGENT_METHODS.session_load](payload)),
listSessions: (payload) => callRpc(rpc[AGENT_METHODS.session_list](payload)),
forkSession: (payload) => callRpc(rpc[AGENT_METHODS.session_fork](payload)),
resumeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_resume](payload)),
closeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_close](payload)),
setSessionModel: (payload) => callRpc(rpc[AGENT_METHODS.session_set_model](payload)),
setSessionConfigOption: (payload) =>
callRpc(rpc[AGENT_METHODS.session_set_config_option](payload)),
prompt: (payload) => callRpc(rpc[AGENT_METHODS.session_prompt](payload)),
cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),
},
handleRequestPermission: (handler) =>
Effect.suspend(() => {
coreHandlers.requestPermission = handler;
return Effect.void;
}),
handleElicitation: (handler) =>
Effect.suspend(() => {
coreHandlers.elicitation = handler;
return Effect.void;
}),
handleReadTextFile: (handler) =>
Effect.suspend(() => {
coreHandlers.readTextFile = handler;
return Effect.void;
}),
handleWriteTextFile: (handler) =>
Effect.suspend(() => {
coreHandlers.writeTextFile = handler;
return Effect.void;
}),
handleCreateTerminal: (handler) =>
Effect.suspend(() => {
coreHandlers.createTerminal = handler;
return Effect.void;
}),
handleTerminalOutput: (handler) =>
Effect.suspend(() => {
coreHandlers.terminalOutput = handler;
return Effect.void;
}),
handleTerminalWaitForExit: (handler) =>
Effect.suspend(() => {
coreHandlers.terminalWaitForExit = handler;
return Effect.void;
}),
handleTerminalKill: (handler) =>
Effect.suspend(() => {
coreHandlers.terminalKill = handler;
return Effect.void;
}),
handleTerminalRelease: (handler) =>
Effect.suspend(() => {
coreHandlers.terminalRelease = handler;
return Effect.void;
}),
handleSessionUpdate: (handler) =>
Effect.suspend(() => {
notificationHandlers.sessionUpdate.handlers.push(handler);
return flushBufferedNotifications(notificationHandlers.sessionUpdate);
}),
handleElicitationComplete: (handler) =>
Effect.suspend(() => {
notificationHandlers.elicitationComplete.handlers.push(handler);
return flushBufferedNotifications(notificationHandlers.elicitationComplete);
}),
handleUnknownExtRequest: (handler) =>
Effect.suspend(() => {
unknownExtRequestHandler = handler;
return Effect.void;
}),
handleUnknownExtNotification: (handler) =>
Effect.suspend(() => {
unknownExtNotificationHandler = handler;
return Effect.void;
}),
handleExtRequest: (method, payload, handler) =>
Effect.suspend(() => {
extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
return Effect.void;
}),
handleExtNotification: (method, payload, handler) =>
Effect.suspend(() => {
extNotificationHandlers.set(
method,
decodeExtNotificationRegistration(method, payload, handler),
);
return Effect.void;
}),
});
});
export const layerChildProcess = (
handle: ChildProcessSpawner.ChildProcessHandle,
options: AcpClientOptions = {},
): Layer.Layer<AcpClient> => {
const stdio = makeChildStdio(handle);
const terminationError = makeTerminationError(handle);
return Layer.effect(AcpClient, make(stdio, options, terminationError));
};
+139
View File
@@ -0,0 +1,139 @@
import * as Schema from "effect/Schema";
import * as AcpSchema from "./_generated/schema.gen.ts";
export class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()("AcpSpawnError", {
command: Schema.optional(Schema.String),
cause: Schema.Defect,
}) {
override get message() {
return this.command
? `Failed to spawn ACP process for command: ${this.command}`
: "Failed to spawn ACP process";
}
}
export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExitedError>()(
"AcpProcessExitedError",
{
code: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return this.code === undefined
? "ACP process exited"
: `ACP process exited with code ${this.code}`;
}
}
export class AcpProtocolParseError extends Schema.TaggedErrorClass<AcpProtocolParseError>()(
"AcpProtocolParseError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return `Failed to parse ACP protocol message: ${this.detail}`;
}
}
export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError>()(
"AcpTransportError",
{
detail: Schema.String,
cause: Schema.Defect,
},
) {}
export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()("AcpRequestError", {
code: AcpSchema.ErrorCode,
errorMessage: Schema.String,
data: Schema.optional(Schema.Unknown),
}) {
override get message() {
return this.errorMessage;
}
static fromProtocolError(error: AcpSchema.Error) {
return new AcpRequestError({
code: error.code,
errorMessage: error.message,
...(error.data !== undefined ? { data: error.data } : {}),
});
}
static parseError(message = "Parse error", data?: unknown) {
return new AcpRequestError({
code: -32700,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static invalidRequest(message = "Invalid request", data?: unknown) {
return new AcpRequestError({
code: -32600,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static methodNotFound(method: string) {
return new AcpRequestError({
code: -32601,
errorMessage: `Method not found: ${method}`,
});
}
static invalidParams(message = "Invalid params", data?: unknown) {
return new AcpRequestError({
code: -32602,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static internalError(message = "Internal error", data?: unknown) {
return new AcpRequestError({
code: -32603,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static authRequired(message = "Authentication required", data?: unknown) {
return new AcpRequestError({
code: -32000,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static resourceNotFound(message = "Resource not found", data?: unknown) {
return new AcpRequestError({
code: -32002,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
toProtocolError() {
return AcpSchema.Error.make({
code: this.code,
message: this.errorMessage,
...(this.data !== undefined ? { data: this.data } : {}),
});
}
}
export const AcpError = Schema.Union([
AcpRequestError,
AcpSpawnError,
AcpProcessExitedError,
AcpProtocolParseError,
AcpTransportError,
]);
export type AcpError = typeof AcpError.Type;
+448
View File
@@ -0,0 +1,448 @@
import * as Path from "effect/Path";
import * as AcpError from "./errors.ts";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as Ref from "effect/Ref";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { it, assert } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as AcpSchema from "./_generated/schema.gen.ts";
import * as AcpProtocol from "./protocol.ts";
import {
encodeJsonl,
jsonRpcNotification,
jsonRpcRequest,
jsonRpcResponse,
} from "./_internal/shared.ts";
import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
const SessionCancelNotification = jsonRpcNotification(
"session/cancel",
AcpSchema.CancelNotification,
);
const SessionUpdateNotification = jsonRpcNotification(
"session/update",
AcpSchema.SessionNotification,
);
const ElicitationCompleteNotification = jsonRpcNotification(
"session/elicitation/complete",
AcpSchema.ElicitationCompleteNotification,
);
const RequestPermissionRequest = jsonRpcRequest(
"session/request_permission",
AcpSchema.RequestPermissionRequest,
);
const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
);
const makeHandle = (env?: Record<string, string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
cwd: path.join(import.meta.dirname, ".."),
shell: process.platform === "win32",
...(env ? { env: { ...process.env, ...env } } : {}),
});
return yield* spawner.spawn(command);
});
it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
it.effect(
"emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
() =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
});
const notifications =
yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
yield* transport.incoming.pipe(
Stream.take(2),
Stream.runCollect,
Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
Effect.forkScoped,
);
yield* transport.notify("session/cancel", { sessionId: "session-1" });
const outbound = yield* Queue.take(output);
assert.deepEqual(
yield* Schema.decodeEffect(Schema.fromJsonString(SessionCancelNotification))(outbound),
{
jsonrpc: "2.0",
method: "session/cancel",
params: {
sessionId: "session-1",
},
},
);
yield* Queue.offer(
input,
yield* encodeJsonl(SessionUpdateNotification, {
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "session-1",
update: {
sessionUpdate: "plan",
entries: [
{
content: "Inspect repository",
priority: "high",
status: "in_progress",
},
],
},
},
}),
);
yield* Queue.offer(
input,
yield* encodeJsonl(ElicitationCompleteNotification, {
jsonrpc: "2.0",
method: "session/elicitation/complete",
params: {
elicitationId: "elicitation-1",
},
}),
);
const [update, completion] = yield* Deferred.await(notifications);
assert.equal(update?._tag, "SessionUpdate");
assert.equal(completion?._tag, "ElicitationComplete");
}),
);
it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
Effect.gen(function* () {
const { stdio } = yield* makeInMemoryStdio();
const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
logOutgoing: true,
logger: (event) =>
Effect.sync(() => {
events.push(event);
}),
});
yield* transport.notify("session/cancel", { sessionId: "session-1" });
assert.deepEqual(events, [
{
direction: "outgoing",
stage: "decoded",
payload: {
_tag: "Request",
id: "",
tag: "session/cancel",
payload: {
sessionId: "session-1",
},
headers: [],
},
},
{
direction: "outgoing",
stage: "raw",
payload:
'{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
},
]);
}),
);
it.effect("fails notification encoding through the declared ACP error channel", () =>
Effect.gen(function* () {
const { stdio } = yield* makeInMemoryStdio();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
});
const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
assert.equal(bigintError.detail, "Failed to encode ACP message");
const circular: Record<string, unknown> = {};
circular.self = circular;
const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
assert.equal(circularError.detail, "Failed to encode ACP message");
}),
);
it.effect("supports generic extension requests over the patched transport", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
});
const response = yield* transport
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
jsonrpc: "2.0",
id: 1,
method: "x/test",
params: {
hello: "world",
},
headers: [],
});
yield* Queue.offer(
input,
yield* encodeJsonl(ExtResponse, {
jsonrpc: "2.0",
id: 1,
result: {
ok: true,
},
}),
);
const resolved = yield* Fiber.join(response);
assert.deepEqual(resolved, { ok: true });
}),
);
it.effect("preserves zero-valued ids for inbound core client requests", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(["session/request_permission"]),
});
const inboundRequest = yield* Deferred.make<unknown>();
yield* transport.serverProtocol
.run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
.pipe(Effect.forkScoped);
yield* Queue.offer(
input,
yield* encodeJsonl(RequestPermissionRequest, {
jsonrpc: "2.0",
id: 0,
method: "session/request_permission",
params: {
sessionId: "session-1",
toolCall: {
toolCallId: "tool-1",
title: "Allow mock action",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
},
headers: [],
}),
);
const message = yield* Deferred.await(inboundRequest);
assert.deepEqual(message, {
_tag: "Request",
id: "0",
tag: "session/request_permission",
payload: {
sessionId: "session-1",
toolCall: {
toolCallId: "tool-1",
title: "Allow mock action",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
},
headers: [],
});
yield* transport.serverProtocol.send(0, {
_tag: "Exit",
requestId: "0",
exit: {
_tag: "Success",
value: {
outcome: {
outcome: "selected",
optionId: "allow",
},
},
},
});
const outbound = yield* Queue.take(output);
assert.deepEqual(
yield* Schema.decodeEffect(Schema.fromJsonString(RequestPermissionResponse))(outbound),
{
jsonrpc: "2.0",
id: 0,
result: {
outcome: {
outcome: "selected",
optionId: "allow",
},
},
},
);
}),
);
it.effect("cleans up interrupted extension requests before a late response arrives", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
});
const lateResponse = yield* Deferred.make<unknown>();
yield* transport.clientProtocol
.run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
.pipe(Effect.forkScoped);
const response = yield* transport
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
jsonrpc: "2.0",
id: 1,
method: "x/test",
params: {
hello: "world",
},
headers: [],
});
yield* Fiber.interrupt(response);
yield* Queue.offer(
input,
yield* encodeJsonl(ExtResponse, {
jsonrpc: "2.0",
id: 1,
result: {
ok: true,
},
}),
);
const message = yield* Deferred.await(lateResponse);
assert.deepEqual(message, {
_tag: "Exit",
requestId: "1",
exit: {
_tag: "Success",
value: {
ok: true,
},
},
});
}),
);
it.effect("propagates the real child exit code when the input stream ends", () =>
Effect.gen(function* () {
const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
const firstMessage = yield* Deferred.make<unknown>();
const termination = yield* Deferred.make<AcpError.AcpError>();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio: makeChildStdio(handle),
terminationError: makeTerminationError(handle),
serverRequestMethods: new Set(),
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
});
yield* transport.clientProtocol
.run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
.pipe(Effect.forkScoped);
const message = yield* Deferred.await(firstMessage);
const exitError = yield* Deferred.await(termination);
assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
readonly _tag: string;
readonly cause: unknown;
};
assert.equal(defect._tag, "RpcClientDefect");
assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
}),
);
it.effect("does not emit a second process-exit error after a decode failure", () =>
Effect.gen(function* () {
const handle = yield* makeHandle({
ACP_MOCK_MALFORMED_OUTPUT: "1",
ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
});
const terminationCalls = yield* Ref.make(0);
const firstMessage = yield* Deferred.make<unknown>();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio: makeChildStdio(handle),
terminationError: makeTerminationError(handle),
serverRequestMethods: new Set(),
onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
});
yield* transport.clientProtocol
.run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
.pipe(Effect.forkScoped);
const message = yield* Deferred.await(firstMessage);
assert.equal(yield* Ref.get(terminationCalls), 1);
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
readonly _tag: string;
readonly cause: unknown;
};
assert.equal(defect._tag, "RpcClientDefect");
assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
}),
);
it.effect("fails pending extension requests with the propagated exit code", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
serverRequestMethods: new Set(),
});
const response = yield* transport
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
yield* Queue.take(output);
yield* Queue.end(input);
const error = yield* Fiber.join(response).pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: () => assert.fail("Expected request to fail after process exit"),
}),
);
assert.instanceOf(error, AcpError.AcpProcessExitedError);
assert.equal(error.code, 0);
}),
);
});
+536
View File
@@ -0,0 +1,536 @@
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Stdio from "effect/Stdio";
import * as RpcClient from "effect/unstable/rpc/RpcClient";
import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
import * as RpcServer from "effect/unstable/rpc/RpcServer";
import * as AcpSchema from "./_generated/schema.gen.ts";
import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
import * as AcpError from "./errors.ts";
export interface AcpProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
readonly stage: "raw" | "decoded" | "decode_failed";
readonly payload: unknown;
}
export type AcpIncomingNotification =
| {
readonly _tag: "SessionUpdate";
readonly method: typeof CLIENT_METHODS.session_update;
readonly params: typeof AcpSchema.SessionNotification.Type;
}
| {
readonly _tag: "ElicitationComplete";
readonly method: typeof CLIENT_METHODS.session_elicitation_complete;
readonly params: typeof AcpSchema.ElicitationCompleteNotification.Type;
}
| {
readonly _tag: "ExtNotification";
readonly method: string;
readonly params: unknown;
};
export interface AcpPatchedProtocolOptions {
readonly stdio: Stdio.Stdio;
readonly terminationError?: Effect.Effect<AcpError.AcpError>;
readonly serverRequestMethods: ReadonlySet<string>;
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
readonly onNotification?: (
notification: AcpIncomingNotification,
) => Effect.Effect<void, AcpError.AcpError, never>;
readonly onExtRequest?: (
method: string,
params: unknown,
) => Effect.Effect<unknown, AcpError.AcpError, never>;
readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
}
export interface AcpPatchedProtocol {
readonly clientProtocol: RpcClient.Protocol["Service"];
readonly serverProtocol: RpcServer.Protocol["Service"];
readonly incoming: Stream.Stream<AcpIncomingNotification>;
readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
}
const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
const decodeElicitationComplete = Schema.decodeUnknownEffect(
AcpSchema.ElicitationCompleteNotification,
);
const parserFactory = RpcSerialization.ndJsonRpc();
export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
options: AcpPatchedProtocolOptions,
): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
const parser = parserFactory.makeUnsafe();
const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();
const disconnects = yield* Queue.unbounded<number>();
const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
const nextRequestId = yield* Ref.make(1n);
const terminationHandled = yield* Ref.make(false);
const extPending = yield* Ref.make(
new Map<string, Deferred.Deferred<unknown, AcpError.AcpError>>(),
);
const logProtocol = (event: AcpProtocolLogEvent) => {
if (event.direction === "incoming" && !options.logIncoming) {
return Effect.void;
}
if (event.direction === "outgoing" && !options.logOutgoing) {
return Effect.void;
}
return (
options.logger?.(event) ??
Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
);
};
const offerOutgoing = Effect.fn("offerOutgoing")(function* (
message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
) {
yield* logProtocol({
direction: "outgoing",
stage: "decoded",
payload: message,
});
const encoded = yield* Effect.try({
try: () => parser.encode(message),
catch: (cause) =>
new AcpError.AcpProtocolParseError({
detail: "Failed to encode ACP message",
cause,
}),
});
if (encoded) {
yield* logProtocol({
direction: "outgoing",
stage: "raw",
payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
});
yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
}
});
const resolveExtPending = (
requestId: string,
onFound: (deferred: Deferred.Deferred<unknown, AcpError.AcpError>) => Effect.Effect<void>,
) =>
Ref.modify(extPending, (pending) => {
const deferred = pending.get(requestId);
if (!deferred) {
return [Effect.void, pending] as const;
}
const next = new Map(pending);
next.delete(requestId);
return [onFound(deferred), next] as const;
}).pipe(Effect.flatten);
const removeExtPending = (requestId: string) =>
Ref.update(extPending, (pending) => {
if (!pending.has(requestId)) {
return pending;
}
const next = new Map(pending);
next.delete(requestId);
return next;
});
const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) =>
resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error));
const completeExtPendingSuccess = (requestId: string, value: unknown) =>
resolveExtPending(requestId, (deferred) => Deferred.succeed(deferred, value));
const failAllExtPending = (error: AcpError.AcpError) =>
Ref.getAndSet(extPending, new Map()).pipe(
Effect.flatMap((pending) =>
Effect.forEach([...pending.values()], (deferred) => Deferred.fail(deferred, error), {
discard: true,
}),
),
);
const dispatchNotification = (notification: AcpIncomingNotification) =>
Queue.offer(notificationQueue, notification).pipe(
Effect.andThen(
options.onNotification
? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
: Effect.void,
),
Effect.asVoid,
);
const emitClientProtocolError = (error: AcpError.AcpError) =>
Queue.offer(clientQueue, {
_tag: "ClientProtocolError",
error: new RpcClientError.RpcClientError({
reason: new RpcClientError.RpcClientDefect({
message: error.message,
cause: error,
}),
}),
}).pipe(Effect.asVoid);
const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError | undefined>) =>
Ref.modify(terminationHandled, (handled) => {
if (handled) {
return [Effect.void, true] as const;
}
return [
Effect.gen(function* () {
yield* Queue.offer(disconnects, 0);
const error = yield* classify();
if (!error) {
return;
}
yield* failAllExtPending(error);
yield* emitClientProtocolError(error);
if (options.onTermination) {
yield* options.onTermination(error);
}
}),
true,
] as const;
}).pipe(Effect.flatten);
const respondWithSuccess = (requestId: string, value: unknown) =>
offerOutgoing({
_tag: "Exit",
requestId,
exit: {
_tag: "Success",
value,
},
});
const respondWithError = (requestId: string, error: AcpError.AcpRequestError) =>
offerOutgoing({
_tag: "Exit",
requestId,
exit: {
_tag: "Failure",
cause: [
{
_tag: "Fail",
error: error.toProtocolError(),
},
],
},
});
const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
if (!options.onExtRequest) {
return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
}
return options.onExtRequest(message.tag, message.payload).pipe(
Effect.matchEffect({
onFailure: (error) => respondWithError(message.id, normalizeToRequestError(error)),
onSuccess: (value) => respondWithSuccess(message.id, value),
}),
);
};
const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
if (message.id === "") {
if (message.tag === CLIENT_METHODS.session_update) {
return decodeSessionUpdate(message.payload).pipe(
Effect.map(
(params) =>
({
_tag: "SessionUpdate",
method: CLIENT_METHODS.session_update,
params,
}) satisfies AcpIncomingNotification,
),
Effect.mapError(
(cause) =>
new AcpError.AcpProtocolParseError({
detail: `Invalid ${CLIENT_METHODS.session_update} notification payload`,
cause,
}),
),
Effect.flatMap(dispatchNotification),
);
}
if (message.tag === CLIENT_METHODS.session_elicitation_complete) {
return decodeElicitationComplete(message.payload).pipe(
Effect.map(
(params) =>
({
_tag: "ElicitationComplete",
method: CLIENT_METHODS.session_elicitation_complete,
params,
}) satisfies AcpIncomingNotification,
),
Effect.mapError(
(cause) =>
new AcpError.AcpProtocolParseError({
detail: `Invalid ${CLIENT_METHODS.session_elicitation_complete} notification payload`,
cause,
}),
),
Effect.flatMap(dispatchNotification),
);
}
return dispatchNotification({
_tag: "ExtNotification",
method: message.tag,
params: message.payload,
});
}
if (!options.serverRequestMethods.has(message.tag)) {
return handleExtRequest(message).pipe(
Effect.catch(() => respondWithError(message.id, AcpError.AcpRequestError.internalError())),
Effect.asVoid,
);
}
return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
};
const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
Ref.get(extPending).pipe(
Effect.flatMap((pending) => {
if (!pending.has(message.requestId)) {
return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
}
if (message.exit._tag === "Success") {
return completeExtPendingSuccess(message.requestId, message.exit.value);
}
const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
if (failure && isProtocolError(failure.error)) {
return completeExtPendingFailure(
message.requestId,
AcpError.AcpRequestError.fromProtocolError(failure.error),
);
}
return completeExtPendingFailure(
message.requestId,
AcpError.AcpRequestError.internalError("Extension request failed"),
);
}),
);
const routeDecodedMessage = (
message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
): Effect.Effect<void, AcpError.AcpError> => {
switch (message._tag) {
case "Request":
return handleRequestEncoded(message);
case "Exit":
return handleExitEncoded(message);
case "Chunk":
return Ref.get(extPending).pipe(
Effect.flatMap((pending) =>
pending.has(message.requestId)
? completeExtPendingFailure(
message.requestId,
AcpError.AcpRequestError.internalError(
"Streaming extension responses are not supported",
),
)
: Queue.offer(clientQueue, message).pipe(Effect.asVoid),
),
);
case "Defect":
case "ClientProtocolError":
case "Pong":
return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
case "Ack":
case "Interrupt":
case "Ping":
case "Eof":
return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
}
};
yield* options.stdio.stdin.pipe(
Stream.runForEach((data) =>
logProtocol({
direction: "incoming",
stage: "raw",
payload: typeof data === "string" ? data : new TextDecoder().decode(data),
}).pipe(
Effect.flatMap(() =>
Effect.try({
try: () =>
parser.decode(data) as ReadonlyArray<
RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
>,
catch: (cause) =>
new AcpError.AcpProtocolParseError({
detail: "Failed to decode ACP wire message",
cause,
}),
}),
),
Effect.tap((messages) =>
logProtocol({
direction: "incoming",
stage: "decoded",
payload: messages,
}),
),
Effect.tapErrorTag("AcpProtocolParseError", (error) =>
logProtocol({
direction: "incoming",
stage: "decode_failed",
payload: {
detail: error.detail,
cause: error.cause,
},
}),
),
Effect.flatMap((messages) =>
Effect.forEach(messages, routeDecodedMessage, {
discard: true,
}),
),
),
),
Effect.matchEffect({
onFailure: (error) => {
const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error)
? error
: new AcpError.AcpTransportError({
detail: error instanceof Error ? error.message : String(error),
cause: error,
});
return handleTermination(() => Effect.succeed(normalized));
},
onSuccess: () =>
handleTermination(
() =>
options.terminationError ??
Effect.succeed(
new AcpError.AcpTransportError({
detail: "ACP input stream ended",
cause: new Error("ACP input stream ended"),
}),
),
),
}),
Effect.forkScoped,
);
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
const clientProtocol = RpcClient.Protocol.of({
run: (_clientId, f) =>
Stream.fromQueue(clientQueue).pipe(
Stream.runForEach((message) => f(message)),
Effect.forever,
),
send: (_clientId, request) => offerOutgoing(request).pipe(Effect.mapError(toRpcClientError)),
supportsAck: true,
supportsTransferables: false,
});
const serverProtocol = RpcServer.Protocol.of({
run: (f) =>
Stream.fromQueue(serverQueue).pipe(
Stream.runForEach((message) => f(0, message)),
Effect.forever,
),
disconnects,
send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
end: (_clientId) => Queue.end(outgoing),
clientIds: Effect.succeed(new Set([0])),
initialMessage: Effect.succeedNone,
supportsAck: true,
supportsTransferables: false,
supportsSpanPropagation: true,
});
const sendNotification = Effect.fn("sendNotification")(function* (
method: string,
payload: unknown,
) {
yield* offerOutgoing({
_tag: "Request",
id: "",
tag: method,
payload,
headers: [],
});
});
const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
const requestId = yield* Ref.modify(
nextRequestId,
(current) => [current, current + 1n] as const,
);
const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
yield* Ref.update(extPending, (pending) => new Map(pending).set(String(requestId), deferred));
yield* offerOutgoing({
_tag: "Request",
id: String(requestId),
tag: method,
payload,
headers: [],
}).pipe(
Effect.catch((error) =>
removeExtPending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
),
);
return yield* Deferred.await(deferred).pipe(
Effect.onInterrupt(() => removeExtPending(String(requestId))),
);
});
return {
clientProtocol,
serverProtocol,
get incoming() {
return Stream.fromQueue(notificationQueue);
},
request: sendRequest,
notify: sendNotification,
} satisfies AcpPatchedProtocol;
});
function isProtocolError(
value: unknown,
): value is { code: number; message: string; data?: unknown } {
return (
typeof value === "object" &&
value !== null &&
"code" in value &&
typeof value.code === "number" &&
"message" in value &&
typeof value.message === "string"
);
}
function normalizeToRequestError(error: AcpError.AcpError): AcpError.AcpRequestError {
return Schema.is(AcpError.AcpRequestError)(error)
? error
: AcpError.AcpRequestError.internalError(error.message);
}
function toRpcClientError(error: AcpError.AcpError): RpcClientError.RpcClientError {
return new RpcClientError.RpcClientError({
reason: new RpcClientError.RpcClientDefect({
message: error.message,
cause: error,
}),
});
}
+158
View File
@@ -0,0 +1,158 @@
import * as Rpc from "effect/unstable/rpc/Rpc";
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
import * as AcpSchema from "./_generated/schema.gen.ts";
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts";
export const InitializeRpc = Rpc.make(AGENT_METHODS.initialize, {
payload: AcpSchema.InitializeRequest,
success: AcpSchema.InitializeResponse,
error: AcpSchema.Error,
});
export const AuthenticateRpc = Rpc.make(AGENT_METHODS.authenticate, {
payload: AcpSchema.AuthenticateRequest,
success: AcpSchema.AuthenticateResponse,
error: AcpSchema.Error,
});
export const LogoutRpc = Rpc.make(AGENT_METHODS.logout, {
payload: AcpSchema.LogoutRequest,
success: AcpSchema.LogoutResponse,
error: AcpSchema.Error,
});
export const NewSessionRpc = Rpc.make(AGENT_METHODS.session_new, {
payload: AcpSchema.NewSessionRequest,
success: AcpSchema.NewSessionResponse,
error: AcpSchema.Error,
});
export const LoadSessionRpc = Rpc.make(AGENT_METHODS.session_load, {
payload: AcpSchema.LoadSessionRequest,
success: AcpSchema.LoadSessionResponse,
error: AcpSchema.Error,
});
export const ListSessionsRpc = Rpc.make(AGENT_METHODS.session_list, {
payload: AcpSchema.ListSessionsRequest,
success: AcpSchema.ListSessionsResponse,
error: AcpSchema.Error,
});
export const ForkSessionRpc = Rpc.make(AGENT_METHODS.session_fork, {
payload: AcpSchema.ForkSessionRequest,
success: AcpSchema.ForkSessionResponse,
error: AcpSchema.Error,
});
export const ResumeSessionRpc = Rpc.make(AGENT_METHODS.session_resume, {
payload: AcpSchema.ResumeSessionRequest,
success: AcpSchema.ResumeSessionResponse,
error: AcpSchema.Error,
});
export const CloseSessionRpc = Rpc.make(AGENT_METHODS.session_close, {
payload: AcpSchema.CloseSessionRequest,
success: AcpSchema.CloseSessionResponse,
error: AcpSchema.Error,
});
export const PromptRpc = Rpc.make(AGENT_METHODS.session_prompt, {
payload: AcpSchema.PromptRequest,
success: AcpSchema.PromptResponse,
error: AcpSchema.Error,
});
export const SetSessionModelRpc = Rpc.make(AGENT_METHODS.session_set_model, {
payload: AcpSchema.SetSessionModelRequest,
success: AcpSchema.SetSessionModelResponse,
error: AcpSchema.Error,
});
export const SetSessionConfigOptionRpc = Rpc.make(AGENT_METHODS.session_set_config_option, {
payload: AcpSchema.SetSessionConfigOptionRequest,
success: AcpSchema.SetSessionConfigOptionResponse,
error: AcpSchema.Error,
});
export const ReadTextFileRpc = Rpc.make(CLIENT_METHODS.fs_read_text_file, {
payload: AcpSchema.ReadTextFileRequest,
success: AcpSchema.ReadTextFileResponse,
error: AcpSchema.Error,
});
export const WriteTextFileRpc = Rpc.make(CLIENT_METHODS.fs_write_text_file, {
payload: AcpSchema.WriteTextFileRequest,
success: AcpSchema.WriteTextFileResponse,
error: AcpSchema.Error,
});
export const RequestPermissionRpc = Rpc.make(CLIENT_METHODS.session_request_permission, {
payload: AcpSchema.RequestPermissionRequest,
success: AcpSchema.RequestPermissionResponse,
error: AcpSchema.Error,
});
export const ElicitationRpc = Rpc.make(CLIENT_METHODS.session_elicitation, {
payload: AcpSchema.ElicitationRequest,
success: AcpSchema.ElicitationResponse,
error: AcpSchema.Error,
});
export const CreateTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_create, {
payload: AcpSchema.CreateTerminalRequest,
success: AcpSchema.CreateTerminalResponse,
error: AcpSchema.Error,
});
export const TerminalOutputRpc = Rpc.make(CLIENT_METHODS.terminal_output, {
payload: AcpSchema.TerminalOutputRequest,
success: AcpSchema.TerminalOutputResponse,
error: AcpSchema.Error,
});
export const ReleaseTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_release, {
payload: AcpSchema.ReleaseTerminalRequest,
success: AcpSchema.ReleaseTerminalResponse,
error: AcpSchema.Error,
});
export const WaitForTerminalExitRpc = Rpc.make(CLIENT_METHODS.terminal_wait_for_exit, {
payload: AcpSchema.WaitForTerminalExitRequest,
success: AcpSchema.WaitForTerminalExitResponse,
error: AcpSchema.Error,
});
export const KillTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_kill, {
payload: AcpSchema.KillTerminalRequest,
success: AcpSchema.KillTerminalResponse,
error: AcpSchema.Error,
});
export const AgentRpcs = RpcGroup.make(
InitializeRpc,
AuthenticateRpc,
LogoutRpc,
NewSessionRpc,
LoadSessionRpc,
ListSessionsRpc,
ForkSessionRpc,
ResumeSessionRpc,
CloseSessionRpc,
PromptRpc,
SetSessionModelRpc,
SetSessionConfigOptionRpc,
);
export const ClientRpcs = RpcGroup.make(
ReadTextFileRpc,
WriteTextFileRpc,
RequestPermissionRpc,
ElicitationRpc,
CreateTerminalRpc,
TerminalOutputRpc,
ReleaseTerminalRpc,
WaitForTerminalExitRpc,
KillTerminalRpc,
);
+2
View File
@@ -0,0 +1,2 @@
export * from "./_generated/schema.gen.ts";
export * from "./_generated/meta.gen.ts";
+45
View File
@@ -0,0 +1,45 @@
import * as Effect from "effect/Effect";
import type * as AcpSchema from "./_generated/schema.gen.ts";
import type * as AcpError from "./errors.ts";
export interface AcpTerminal {
readonly sessionId: string;
readonly terminalId: string;
/** Reads buffered output from the terminal.
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/output
*/
readonly output: Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
/** Waits for terminal exit and returns the exit result.
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
*/
readonly waitForExit: Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
/** Terminates the terminal process.
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/kill
*/
readonly kill: Effect.Effect<AcpSchema.KillTerminalResponse, AcpError.AcpError>;
/** Releases the terminal handle from the ACP session.
* Spec: https://agentclientprotocol.com/protocol/schema#terminal/release
*/
readonly release: Effect.Effect<AcpSchema.ReleaseTerminalResponse, AcpError.AcpError>;
}
export interface MakeTerminalOptions {
readonly sessionId: string;
readonly terminalId: string;
readonly output: Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
readonly waitForExit: Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
readonly kill: Effect.Effect<AcpSchema.KillTerminalResponse, AcpError.AcpError>;
readonly release: Effect.Effect<AcpSchema.ReleaseTerminalResponse, AcpError.AcpError>;
}
export function makeTerminal(options: MakeTerminalOptions): AcpTerminal {
return {
sessionId: options.sessionId,
terminalId: options.terminalId,
output: options.output,
waitForExit: options.waitForExit,
kill: options.kill,
release: options.release,
};
}
@@ -0,0 +1,81 @@
import * as Effect from "effect/Effect";
import * as Console from "effect/Console";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as AcpClient from "../../src/client.ts";
const program = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("cursor-agent", ["acp"], {
cwd: process.cwd(),
shell: process.platform === "win32",
});
const handle = yield* spawner.spawn(command);
const acpLayer = AcpClient.layerChildProcess(handle, {
logIncoming: true,
logOutgoing: true,
});
yield* Effect.gen(function* () {
const acp = yield* AcpClient.AcpClient;
yield* acp.handleRequestPermission(() =>
Effect.succeed({
outcome: {
outcome: "selected",
optionId: "allow",
},
}),
);
// yield* acp.handleSessionUpdate((notification) =>
// Console.log("session/update", JSON.stringify(notification)),
// );
const initialized = yield* acp.agent.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: {
name: "effect-acp-example",
version: "0.0.0",
},
});
yield* Console.log("initialized", JSON.stringify(initialized, null, 4));
const session = yield* acp.agent.createSession({
cwd: process.cwd(),
mcpServers: [],
});
const config = yield* acp.agent.setSessionConfigOption({
sessionId: session.sessionId,
configId: "model",
value: "claude-opus-4-6",
});
yield* Console.log("config", JSON.stringify(config, null, 4));
const result = yield* acp.agent.prompt({
sessionId: session.sessionId,
prompt: [
{
type: "text",
text: "Illustrate your ability to create todo lists and then execute all of them. Do not write the list to disk, illustrate your built in ability!",
},
],
});
yield* Console.log("prompt result", JSON.stringify(result));
yield* acp.agent.cancel({ sessionId: session.sessionId });
}).pipe(Effect.provide(acpLayer));
});
program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
+136
View File
@@ -0,0 +1,136 @@
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as AcpAgent from "../../src/agent.ts";
if (process.env.ACP_MOCK_MALFORMED_OUTPUT === "1") {
process.stdout.write("{not-json}\n");
process.exit(Number(process.env.ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE ?? "0"));
}
if (process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE !== undefined) {
process.exit(Number(process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE));
}
const sessionId = "mock-session-1";
const program = Effect.gen(function* () {
const agent = yield* AcpAgent.AcpAgent;
yield* agent.handleInitialize(() =>
Effect.succeed({
protocolVersion: 1,
agentCapabilities: {
sessionCapabilities: {
list: {},
},
},
agentInfo: {
name: "mock-agent",
version: "0.0.0",
},
}),
);
yield* agent.handleAuthenticate(() => Effect.succeed({}));
yield* agent.handleLogout(() => Effect.succeed({}));
yield* agent.handleCreateSession(() =>
Effect.succeed({
sessionId,
}),
);
yield* agent.handleLoadSession(() => Effect.succeed({}));
yield* agent.handleListSessions(() =>
Effect.succeed({
sessions: [
{
sessionId,
cwd: process.cwd(),
},
],
}),
);
yield* agent.handlePrompt(() =>
Effect.gen(function* () {
yield* agent.client.requestPermission({
sessionId,
options: [
{
optionId: "allow",
name: "Allow",
kind: "allow_once",
},
],
toolCall: {
toolCallId: "tool-1",
title: "Read project files",
},
});
yield* agent.client.elicit({
sessionId,
message: "Need confirmation before continuing.",
mode: "form",
requestedSchema: {
type: "object",
title: "Need confirmation",
properties: {
approved: {
type: "boolean",
title: "Approved",
},
},
required: ["approved"],
},
});
yield* agent.client.sessionUpdate({
sessionId,
update: {
sessionUpdate: "plan",
entries: [
{
content: "Inspect the repository",
priority: "high",
status: "in_progress",
},
],
},
});
yield* agent.client.elicitationComplete({
elicitationId: "elicitation-1",
});
yield* agent.client.extRequest("x/typed_request", {
message: process.env.ACP_MOCK_BAD_TYPED_REQUEST === "1" ? 123 : "hello from typed request",
});
yield* agent.client.extNotification("x/typed_notification", {
count: 2,
});
return {
stopReason: "end_turn" as const,
};
}),
);
yield* agent.handleUnknownExtRequest((method, params) =>
Effect.succeed({
echoedMethod: method,
echoedParams: params ?? null,
}),
);
return yield* Effect.never;
});
program.pipe(
Effect.provide(Layer.provide(AcpAgent.layerStdio(), NodeServices.layer)),
NodeRuntime.runMain,
);
+18
View File
@@ -0,0 +1,18 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"plugins": [
{
"name": "@effect/language-service",
"namespaceImportPackages": ["@effect/platform-node"],
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
}
}
]
},
"include": ["src", "scripts", "test"]
}
+4
View File
@@ -36,6 +36,10 @@
"types": "./src/schemaJson.ts",
"import": "./src/schemaJson.ts"
},
"./toolActivity": {
"types": "./src/toolActivity.ts",
"import": "./src/toolActivity.ts"
},
"./Struct": {
"types": "./src/Struct.ts",
"import": "./src/Struct.ts"
+6 -41
View File
@@ -11,10 +11,8 @@ import {
normalizeClaudeModelOptionsWithCapabilities,
normalizeCodexModelOptionsWithCapabilities,
normalizeModelSlug,
resolveApiModelId,
resolveContextWindow,
resolveEffort,
resolveModelSlug,
resolveModelSlugForProvider,
resolveSelectableModel,
trimOrNull,
@@ -61,17 +59,18 @@ describe("normalizeModelSlug", () => {
});
});
describe("resolveModelSlug", () => {
describe("resolveModelSlugForProvider", () => {
it("returns defaults when the model is missing", () => {
expect(resolveModelSlug(undefined, "codex")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
expect(resolveModelSlugForProvider("codex", undefined)).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe(
DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
);
});
it("preserves normalized unknown models", () => {
expect(resolveModelSlug("custom/internal-model", "codex")).toBe("custom/internal-model");
expect(resolveModelSlugForProvider("codex", "custom/internal-model")).toBe(
"custom/internal-model",
);
});
});
@@ -137,6 +136,7 @@ describe("resolveEffort", () => {
describe("misc helpers", () => {
it("detects ultrathink prompts", () => {
expect(isClaudeUltrathinkPrompt("Please ultrathink about this")).toBe(true);
expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true);
expect(isClaudeUltrathinkPrompt("Investigate")).toBe(false);
});
@@ -195,41 +195,6 @@ describe("resolveContextWindow", () => {
});
});
describe("resolveApiModelId", () => {
it("appends [1m] suffix for 1m context window", () => {
expect(
resolveApiModelId({
provider: "claudeAgent",
model: "claude-opus-4-6",
options: { contextWindow: "1m" },
}),
).toBe("claude-opus-4-6[1m]");
});
it("returns the model as-is for 200k context window", () => {
expect(
resolveApiModelId({
provider: "claudeAgent",
model: "claude-opus-4-6",
options: { contextWindow: "200k" },
}),
).toBe("claude-opus-4-6");
});
it("returns the model as-is when no context window is set", () => {
expect(resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6" })).toBe(
"claude-opus-4-6",
);
expect(
resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6", options: {} }),
).toBe("claude-opus-4-6");
});
it("returns the model as-is for Codex selections", () => {
expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4");
});
});
describe("normalize*ModelOptionsWithCapabilities", () => {
it("preserves explicit false codex fast mode", () => {
expect(
+32 -46
View File
@@ -4,6 +4,7 @@ import {
type ClaudeAgentEffort,
type ClaudeModelOptions,
type CodexModelOptions,
type CursorModelOptions,
type ModelCapabilities,
type ModelSelection,
type OpenCodeModelOptions,
@@ -16,8 +17,6 @@ export interface SelectableModelOption {
name: string;
}
// ── Effort helpers ────────────────────────────────────────────────────
/** Check whether a capabilities object includes a given effort value. */
export function hasEffortLevel(caps: ModelCapabilities, value: string): boolean {
return caps.reasoningEffortLevels.some((l) => l.value === value);
@@ -31,12 +30,9 @@ export function getDefaultEffort(caps: ModelCapabilities): string | null {
/**
* Resolve a raw effort option against capabilities.
*
* Returns the effective effort value — the explicit value if supported and not
* prompt-injected, otherwise the model's default. Returns `undefined` only
* when the model has no effort levels at all.
*
* Prompt-injected efforts (e.g. "ultrathink") are excluded because they are
* applied via prompt text, not the effort API parameter.
* Returns the explicit supported value when present and not prompt-injected,
* otherwise the model default. Returns `undefined` when the model exposes no
* effort levels.
*/
export function resolveEffort(
caps: ModelCapabilities,
@@ -54,8 +50,6 @@ export function resolveEffort(
return defaultValue ?? undefined;
}
// ── Context window helpers ───────────────────────────────────────────
/** Check whether a capabilities object includes a given context window value. */
export function hasContextWindowOption(caps: ModelCapabilities, value: string): boolean {
return caps.contextWindowOptions.some((o) => o.value === value);
@@ -69,14 +63,8 @@ export function getDefaultContextWindow(caps: ModelCapabilities): string | null
/**
* Resolve a raw `contextWindow` option against capabilities.
*
* Returns the effective context window value — the explicit value if supported,
* otherwise the model's default. Returns `undefined` only when the model has
* no context window options at all.
*
* Unlike effort levels (where the API has matching defaults), the context
* window requires an explicit API suffix (e.g. `[1m]`), so we always preserve
* the resolved value to avoid ambiguity between "user chose the default" and
* "not specified".
* Returns the explicit supported value when present, otherwise the model
* default. Returns `undefined` when the model exposes no context window options.
*/
export function resolveContextWindow(
caps: ModelCapabilities,
@@ -119,6 +107,23 @@ export function normalizeClaudeModelOptionsWithCapabilities(
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeCursorModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CursorModelOptions | null | undefined,
): CursorModelOptions | undefined {
const reasoning = resolveEffort(caps, modelOptions?.reasoning);
const thinking = caps.supportsThinkingToggle ? modelOptions?.thinking : undefined;
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: CursorModelOptions = {
...(reasoning ? { reasoning: reasoning as CursorModelOptions["reasoning"] } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
...(thinking !== undefined ? { thinking } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
function resolveLabeledOption(
options: ReadonlyArray<{ value: string; isDefault?: boolean | undefined }> | undefined,
raw: string | null | undefined,
@@ -155,6 +160,8 @@ export function normalizeProviderModelOptionsWithCapabilities(
return normalizeCodexModelOptionsWithCapabilities(caps, modelOptions as CodexModelOptions);
case "claudeAgent":
return normalizeClaudeModelOptionsWithCapabilities(caps, modelOptions as ClaudeModelOptions);
case "cursor":
return normalizeCursorModelOptionsWithCapabilities(caps, modelOptions as CursorModelOptions);
case "opencode":
return normalizeOpenCodeModelOptionsWithCapabilities(
caps,
@@ -220,7 +227,7 @@ export function resolveSelectableModel(
return resolved ? resolved.slug : null;
}
export function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string {
function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string {
const normalized = normalizeModelSlug(model, provider);
if (!normalized) {
return DEFAULT_MODEL_BY_PROVIDER[provider];
@@ -260,6 +267,12 @@ export function createModelSelection(
model,
...(options ? { options: options as ClaudeModelOptions } : {}),
};
case "cursor":
return {
provider,
model,
...(options ? { options: options as CursorModelOptions } : {}),
};
case "opencode":
return {
provider,
@@ -269,33 +282,6 @@ export function createModelSelection(
}
}
/**
* Resolve the actual API model identifier from a model selection.
*
* Provider-aware: each provider can map `contextWindow` (or other options)
* to whatever the API requires — a model-id suffix, a separate parameter, etc.
* The canonical slug stored in the selection stays unchanged so the
* capabilities system keeps working.
*
* Expects `contextWindow` to already be resolved (via `resolveContextWindow`)
* to the effective value, not stripped to `undefined` for defaults.
*/
export function resolveApiModelId(modelSelection: ModelSelection): string {
switch (modelSelection.provider) {
case "claudeAgent": {
switch (modelSelection.options?.contextWindow) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
}
default: {
return modelSelection.model;
}
}
}
export function applyClaudePromptEffortPrefix(
text: string,
effort: ClaudeAgentEffort | null | undefined,
+16 -7
View File
@@ -2,6 +2,7 @@ import {
ServerSettings,
type ClaudeModelOptions,
type CodexModelOptions,
type CursorModelOptions,
type OpenCodeModelOptions,
type ServerSettingsPatch,
} from "@t3tools/contracts";
@@ -90,12 +91,20 @@ export function applyServerSettingsPatch(
selectionPatch.options as ClaudeModelOptions | undefined,
),
}
: {
provider,
model,
...withModelSelectionOptions(
selectionPatch.options as OpenCodeModelOptions | undefined,
),
},
: provider === "cursor"
? {
provider,
model,
...withModelSelectionOptions(
selectionPatch.options as CursorModelOptions | undefined,
),
}
: {
provider,
model,
...withModelSelectionOptions(
selectionPatch.options as OpenCodeModelOptions | undefined,
),
},
};
}
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import { deriveToolActivityPresentation } from "./toolActivity.ts";
describe("toolActivity", () => {
it("normalizes command tools to a stable ran-command label", () => {
expect(
deriveToolActivityPresentation({
itemType: "command_execution",
title: "Terminal",
detail: "Terminal",
data: {
command: "bun run lint",
},
fallbackSummary: "Terminal",
}),
).toEqual({
summary: "Ran command",
detail: "bun run lint",
});
});
it("uses structured file paths for read-file tools when available", () => {
expect(
deriveToolActivityPresentation({
itemType: "dynamic_tool_call",
title: "Read File",
detail: "Read File",
data: {
kind: "read",
locations: [{ path: "/tmp/app.ts" }],
},
fallbackSummary: "Read File",
}),
).toEqual({
summary: "Read file",
detail: "/tmp/app.ts",
});
});
it("drops duplicated generic read-file detail when no path is available", () => {
expect(
deriveToolActivityPresentation({
itemType: "dynamic_tool_call",
title: "Read File",
detail: "Read File",
data: {
kind: "read",
rawInput: {},
},
fallbackSummary: "Read File",
}),
).toEqual({
summary: "Read file",
});
});
});
+257
View File
@@ -0,0 +1,257 @@
import type { ToolLifecycleItemType } from "@t3tools/contracts";
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function asTrimmedString(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function normalizeCommandValue(value: unknown): string | undefined {
const direct = asTrimmedString(value);
if (direct) {
return direct;
}
if (!Array.isArray(value)) {
return undefined;
}
const parts = value
.map((entry) => asTrimmedString(entry))
.filter((entry): entry is string => entry !== undefined);
return parts.length > 0 ? parts.join(" ") : undefined;
}
function stripTrailingExitCode(value: string | undefined): string | undefined {
const trimmed = value?.trim();
if (!trimmed) {
return undefined;
}
const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code \d+>)\s*$/iu.exec(trimmed);
const output = match?.groups?.output?.trim() ?? trimmed;
return output.length > 0 ? output : undefined;
}
function extractCommandFromTitle(title: string | undefined): string | undefined {
if (!title) {
return undefined;
}
const backtickMatch = /`([^`]+)`/u.exec(title);
return backtickMatch?.[1]?.trim() || undefined;
}
function extractToolCommand(data: Record<string, unknown> | undefined, title: string | undefined) {
const item = asRecord(data?.item);
const itemInput = asRecord(item?.input);
const itemResult = asRecord(item?.result);
const rawInput = asRecord(data?.rawInput);
const candidates = [
normalizeCommandValue(item?.command),
normalizeCommandValue(itemInput?.command),
normalizeCommandValue(itemResult?.command),
normalizeCommandValue(data?.command),
normalizeCommandValue(rawInput?.command),
];
const direct = candidates.find((candidate) => candidate !== undefined);
if (direct) {
return direct;
}
const executable = asTrimmedString(rawInput?.executable);
const args = normalizeCommandValue(rawInput?.args);
if (executable && args) {
return `${executable} ${args}`;
}
if (executable) {
return executable;
}
return extractCommandFromTitle(title);
}
function maybePathLike(value: string | undefined): string | undefined {
if (!value) {
return undefined;
}
if (
value.includes("/") ||
value.includes("\\") ||
value.startsWith(".") ||
/\.(?:[a-z0-9]{1,12})$/iu.test(value)
) {
return value;
}
return undefined;
}
function collectPaths(value: unknown, paths: string[], seen: Set<string>, depth: number): void {
if (depth > 4 || paths.length >= 8) {
return;
}
if (Array.isArray(value)) {
for (const entry of value) {
collectPaths(entry, paths, seen, depth + 1);
if (paths.length >= 8) {
return;
}
}
return;
}
const record = asRecord(value);
if (!record) {
return;
}
for (const key of ["path", "filePath", "relativePath", "filename", "newPath", "oldPath"]) {
const candidate = maybePathLike(asTrimmedString(record[key]));
if (!candidate || seen.has(candidate)) {
continue;
}
seen.add(candidate);
paths.push(candidate);
if (paths.length >= 8) {
return;
}
}
for (const nestedKey of ["locations", "item", "input", "result", "rawInput", "data", "changes"]) {
if (!(nestedKey in record)) {
continue;
}
collectPaths(record[nestedKey], paths, seen, depth + 1);
if (paths.length >= 8) {
return;
}
}
}
function extractPrimaryPath(data: Record<string, unknown> | undefined): string | undefined {
const paths: string[] = [];
collectPaths(data, paths, new Set<string>(), 0);
return paths[0];
}
function normalizeEquivalentValue(value: string | undefined): string | undefined {
const trimmed = asTrimmedString(value);
if (!trimmed) {
return undefined;
}
return trimmed
.replace(/\s+/gu, " ")
.replace(/\s+(?:complete|completed|started)\s*$/iu, "")
.trim();
}
function isEquivalent(left: string | undefined, right: string | undefined): boolean {
const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();
const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();
return normalizedLeft !== undefined && normalizedLeft === normalizedRight;
}
function classifyToolAction(input: {
readonly itemType?: ToolLifecycleItemType | null | undefined;
readonly title?: string | undefined;
readonly data?: Record<string, unknown> | undefined;
}): "command" | "read" | "file_change" | "search" | "other" {
const itemType = input.itemType ?? undefined;
const kind = asTrimmedString(input.data?.kind)?.toLowerCase();
const title = asTrimmedString(input.title)?.toLowerCase();
if (itemType === "command_execution" || kind === "execute" || title === "terminal") {
return "command";
}
if (kind === "read" || title === "read file") {
return "read";
}
if (
itemType === "file_change" ||
kind === "edit" ||
kind === "move" ||
kind === "delete" ||
kind === "write"
) {
return "file_change";
}
if (itemType === "web_search" || kind === "search" || title === "find" || title === "grep") {
return "search";
}
return "other";
}
export interface ToolActivityPresentationInput {
readonly itemType?: ToolLifecycleItemType | null | undefined;
readonly title?: string | null | undefined;
readonly detail?: string | null | undefined;
readonly data?: unknown;
readonly fallbackSummary?: string | null | undefined;
}
export interface ToolActivityPresentation {
readonly summary: string;
readonly detail?: string | undefined;
}
export function deriveToolActivityPresentation(
input: ToolActivityPresentationInput,
): ToolActivityPresentation {
const title = asTrimmedString(input.title);
const detail = stripTrailingExitCode(asTrimmedString(input.detail));
const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? "Tool";
const data = asRecord(input.data);
const command = extractToolCommand(data, title);
const primaryPath = extractPrimaryPath(data);
const action = classifyToolAction({
itemType: input.itemType,
title,
data,
});
if (action === "command") {
return {
summary: "Ran command",
...(command ? { detail: command } : {}),
};
}
if (action === "read") {
if (primaryPath) {
return {
summary: "Read file",
detail: primaryPath,
};
}
return {
summary: "Read file",
};
}
if (action === "file_change") {
return {
summary: "Changed files",
...(primaryPath ? { detail: primaryPath } : {}),
};
}
if (action === "search") {
const query =
asTrimmedString(asRecord(data?.rawInput)?.query) ??
asTrimmedString(asRecord(data?.rawInput)?.pattern) ??
asTrimmedString(asRecord(data?.rawInput)?.searchTerm);
return {
summary: "Searched files",
...(query ? { detail: query } : {}),
};
}
if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {
return {
summary: title ?? fallbackSummary,
detail,
};
}
return {
summary: title ?? fallbackSummary,
};
}
+1
View File
@@ -24,6 +24,7 @@ const workspaceFiles = [
"packages/client-runtime/package.json",
"packages/contracts/package.json",
"packages/shared/package.json",
"packages/effect-acp/package.json",
"scripts/package.json",
] as const;