Log ACP requests and preserve turn-start failures
- add request and protocol logging for ACP sessions - validate session config values before sending them - keep provider turn-start failures on the thread session - add coverage for ACP runtime and orchestration errors Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
8c358a89ef
commit
eedac90be5
18 files changed
+931
-528
No files matched your search
@@ -11,6 +11,8 @@ import { AGENT_METHODS, CLIENT_METHODS } from "effect-acp/schema";
|
||||
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const sessionId = "mock-session-1";
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
@@ -181,6 +183,24 @@ rl.on("line", (line) => {
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.session_set_config_option && id !== undefined) {
|
||||
if (exitOnSetConfigOption) {
|
||||
process.exit(7);
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: {
|
||||
code: -32602,
|
||||
message: "Mock invalid params for session/set_config_option",
|
||||
data: {
|
||||
method,
|
||||
params: rpcMessage.params,
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
const configId = rpcMessage.params?.configId;
|
||||
const value = rpcMessage.params?.value;
|
||||
if (configId === "model" && typeof value === "string") {
|
||||
|
||||
@@ -357,199 +357,59 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("generates a thread title on the first turn", async () => {
|
||||
it("records session lastError and clears active turn when provider turn start fails", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const seededTitle = "Please investigate reconnect failures after restar...";
|
||||
harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" }));
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-title-seed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
title: seededTitle,
|
||||
}),
|
||||
harness.sendTurn.mockImplementation(
|
||||
() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "cursor",
|
||||
method: "session/set_config_option",
|
||||
detail: 'Invalid value for session config option "model"',
|
||||
}),
|
||||
) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-title"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-session-error"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title"),
|
||||
messageId: asMessageId("user-message-session-error"),
|
||||
role: "user",
|
||||
text: "Please investigate reconnect failures after restarting the session.",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
titleSeed: seededTitle,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||
expect(harness.generateThreadTitle.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Please investigate reconnect failures after restarting the session.",
|
||||
});
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Generated title"
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
});
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Generated title");
|
||||
});
|
||||
|
||||
it("does not overwrite an existing custom thread title on the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const seededTitle = "Please investigate reconnect failures after restar...";
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-title-custom"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
title: "Keep this custom title",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-title-preserve"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title-preserve"),
|
||||
role: "user",
|
||||
text: "Please investigate reconnect failures after restarting the session.",
|
||||
attachments: [],
|
||||
},
|
||||
titleSeed: seededTitle,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Keep this custom title");
|
||||
});
|
||||
|
||||
it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const seededTitle = "Fix reconnect spinner on resume";
|
||||
harness.generateThreadTitle.mockReturnValue(
|
||||
Effect.succeed({
|
||||
title: "Reconnect spinner resume bug",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-title-formatted-seed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
title: seededTitle,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-title-formatted"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title-formatted"),
|
||||
role: "user",
|
||||
text: "[effort:high]\\n\\nFix reconnect spinner on resume",
|
||||
attachments: [],
|
||||
},
|
||||
titleSeed: seededTitle,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Reconnect spinner resume bug"
|
||||
thread?.session?.lastError ===
|
||||
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"' &&
|
||||
thread.session.status === "ready" &&
|
||||
thread.session.activeTurnId === null
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
||||
});
|
||||
|
||||
it("generates a worktree branch name for the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-branch"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
branch: "t3code/1234abcd",
|
||||
worktreePath: "/tmp/provider-project-worktree",
|
||||
}),
|
||||
);
|
||||
|
||||
harness.generateBranchName.mockImplementation((input: unknown) =>
|
||||
Effect.succeed({
|
||||
branch:
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"modelSelection" in input &&
|
||||
typeof input.modelSelection === "object" &&
|
||||
input.modelSelection !== null &&
|
||||
"model" in input.modelSelection &&
|
||||
typeof input.modelSelection.model === "string"
|
||||
? `feature/${input.modelSelection.model}`
|
||||
: "feature/generated",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-branch-model"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-branch-model"),
|
||||
role: "user",
|
||||
text: "Add a safer reconnect backoff.",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.refreshStatus.mock.calls.length === 1);
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Add a safer reconnect backoff.",
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session).toMatchObject({
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
lastError:
|
||||
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"',
|
||||
});
|
||||
expect(harness.refreshStatus.mock.calls[0]?.[0]).toBe("/tmp/provider-project-worktree");
|
||||
});
|
||||
|
||||
it("forwards codex model options through session start and turn send", async () => {
|
||||
@@ -1402,37 +1262,30 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a fresh session when only projected session state exists", async () => {
|
||||
it("preserves provider method context when turn start fails", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
harness.sendTurn.mockImplementation(
|
||||
() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "cursor",
|
||||
method: "session/set_config_option",
|
||||
detail: "Invalid cursor/set_config_option payload: Expected string, got null",
|
||||
}),
|
||||
) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-error"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-stale"),
|
||||
messageId: asMessageId("user-message-provider-error"),
|
||||
role: "user",
|
||||
text: "resume codex",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -1441,19 +1294,77 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining(
|
||||
"Provider adapter request failed (cursor) for session/set_config_option",
|
||||
),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the full rendered cause for non-adapter turn start failures", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.sendTurn.mockImplementation(
|
||||
() =>
|
||||
Effect.fail(
|
||||
new Error("Invalid params", { cause: new Error("session/prompt failed") }),
|
||||
) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-raw-error"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-raw-error"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("session/prompt failed"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -96,9 +96,16 @@ function findProviderAdapterRequestError(
|
||||
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
|
||||
}
|
||||
|
||||
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 = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending approval request") ||
|
||||
@@ -114,7 +121,7 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
||||
|
||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
||||
}
|
||||
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
|
||||
@@ -205,29 +212,16 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const setThreadSessionErrorIfActive = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* setThreadSession({
|
||||
threadId: input.threadId,
|
||||
session: {
|
||||
...thread.session,
|
||||
status: "error",
|
||||
activeTurnId: null,
|
||||
lastError: input.detail,
|
||||
updatedAt: input.createdAt,
|
||||
},
|
||||
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.message;
|
||||
}
|
||||
return Cause.pretty(cause);
|
||||
};
|
||||
|
||||
const setThreadSession = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -659,22 +653,23 @@ const make = Effect.gen(function* () {
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
const detail = Cause.pretty(cause);
|
||||
return Effect.gen(function* () {
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
yield* setThreadSessionErrorIfActive({
|
||||
threadId: event.payload.threadId,
|
||||
detail,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
});
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -27,12 +27,10 @@ import {
|
||||
Layer,
|
||||
Queue,
|
||||
Random,
|
||||
Schema,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { defineExtRequest } from "effect-acp/client";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import { defineExtNotification, defineExtRequest } from "effect-acp/client";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
@@ -59,6 +57,7 @@ import {
|
||||
type AcpSessionModeState,
|
||||
parsePermissionRequest,
|
||||
} from "../acp/AcpRuntimeModel.ts";
|
||||
import { makeAcpNativeLoggers } from "../acp/AcpNativeLogging.ts";
|
||||
import {
|
||||
CursorAskQuestionRequest,
|
||||
CursorCreatePlanRequest,
|
||||
@@ -358,6 +357,11 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
|
||||
let ctx!: CursorSessionContext;
|
||||
|
||||
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
|
||||
const acp = yield* makeAcpSessionRuntime({
|
||||
spawn: spawnOptions,
|
||||
@@ -365,6 +369,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
authMethodId: "cursor_login",
|
||||
...acpNativeLoggers,
|
||||
handlers: {
|
||||
extRequests: {
|
||||
"cursor/ask_question": defineExtRequest(CursorAskQuestionRequest, (params) =>
|
||||
@@ -431,7 +436,9 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
|
||||
return { accepted: true } as const;
|
||||
}),
|
||||
),
|
||||
"cursor/update_todos": defineExtRequest(CursorUpdateTodosRequest, (params) =>
|
||||
},
|
||||
extNotifications: {
|
||||
"cursor/update_todos": defineExtNotification(CursorUpdateTodosRequest, (params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
@@ -448,7 +455,6 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
|
||||
"cursor/update_todos",
|
||||
);
|
||||
}
|
||||
return {};
|
||||
}),
|
||||
),
|
||||
},
|
||||
@@ -502,7 +508,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
}).pipe(Effect.mapError(EffectAcpErrors.normalizeAcpError)),
|
||||
}),
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
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 { makeAcpSessionRuntime } from "./AcpSessionRuntime.ts";
|
||||
import { makeAcpSessionRuntime, 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");
|
||||
@@ -22,6 +25,7 @@ describe("AcpSessionRuntime", () => {
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
});
|
||||
|
||||
expect(runtime.initializeResult).toMatchObject({ protocolVersion: 1 });
|
||||
@@ -44,4 +48,139 @@ describe("AcpSessionRuntime", () => {
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("logs ACP requests from the shared runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
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);
|
||||
}),
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("emits low-level ACP protocol logs for raw and decoded messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
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);
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid config option values before sending session/set_config_option", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
|
||||
const requestLogPath = path.join(tempDir, "requests.ndjson");
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
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" },
|
||||
});
|
||||
|
||||
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]");
|
||||
}
|
||||
|
||||
yield* runtime.close;
|
||||
|
||||
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);
|
||||
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -86,6 +86,31 @@ export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse):
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function findSessionConfigOption(
|
||||
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
|
||||
configId: string,
|
||||
): EffectAcpSchema.SessionConfigOption | undefined {
|
||||
if (!configOptions) {
|
||||
return undefined;
|
||||
}
|
||||
const normalizedConfigId = configId.trim();
|
||||
if (!normalizedConfigId) {
|
||||
return undefined;
|
||||
}
|
||||
return configOptions.find((option) => option.id.trim() === normalizedConfigId);
|
||||
}
|
||||
|
||||
export function collectSessionConfigOptionValues(
|
||||
configOption: EffectAcpSchema.SessionConfigOption,
|
||||
): ReadonlyArray<string> {
|
||||
if (configOption.type !== "select") {
|
||||
return [];
|
||||
}
|
||||
return configOption.options.flatMap((entry) =>
|
||||
"value" in entry ? [entry.value] : entry.options.map((option) => option.value),
|
||||
);
|
||||
}
|
||||
|
||||
export function parseSessionModeState(
|
||||
sessionResponse: AcpSessionSetupResponse,
|
||||
): AcpSessionModeState | undefined {
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { Effect, Exit, Queue, Ref, Scope, Stream } from "effect";
|
||||
import { Cause, Effect, Exit, Queue, Ref, Scope, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpClient from "effect-acp/client";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import {
|
||||
collectSessionConfigOptionValues,
|
||||
extractModelConfigId,
|
||||
findSessionConfigOption,
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
@@ -29,8 +32,22 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
readonly authMethodId?: string;
|
||||
readonly authMethodId: string;
|
||||
readonly handlers?: Omit<EffectAcpClient.AcpClientHandlers, "sessionUpdate">;
|
||||
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 AcpSessionRuntime {
|
||||
@@ -79,6 +96,38 @@ export const makeAcpSessionRuntime = (
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
|
||||
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(
|
||||
@@ -100,6 +149,13 @@ export const makeAcpSessionRuntime = (
|
||||
);
|
||||
|
||||
const client = yield* EffectAcpClient.fromChildProcess(child, {
|
||||
...(options.protocolLogging?.logIncoming !== undefined
|
||||
? { logIncoming: options.protocolLogging.logIncoming }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logOutgoing !== undefined
|
||||
? { logOutgoing: options.protocolLogging.logOutgoing }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
|
||||
handlers: {
|
||||
...options.handlers,
|
||||
sessionUpdate: (notification) =>
|
||||
@@ -112,18 +168,30 @@ export const makeAcpSessionRuntime = (
|
||||
},
|
||||
}).pipe(Effect.provideService(Scope.Scope, runtimeScope));
|
||||
|
||||
const initializeResult = yield* client.initialize({
|
||||
const initializePayload = {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
},
|
||||
clientInfo: options.clientInfo,
|
||||
});
|
||||
} satisfies EffectAcpSchema.InitializeRequest;
|
||||
|
||||
yield* client.authenticate({
|
||||
methodId: options.authMethodId ?? "cursor_login",
|
||||
});
|
||||
const initializeResult = yield* runLoggedRequest(
|
||||
"initialize",
|
||||
initializePayload,
|
||||
client.initialize(initializePayload),
|
||||
);
|
||||
|
||||
const authenticatePayload = {
|
||||
methodId: options.authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
client.authenticate(authenticatePayload),
|
||||
);
|
||||
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
@@ -131,37 +199,135 @@ export const makeAcpSessionRuntime = (
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const resumed = yield* client
|
||||
.loadSession({
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
})
|
||||
.pipe(Effect.exit);
|
||||
const loadPayload = {
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
client.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const created = yield* client.createSession({
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
});
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
client.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
} else {
|
||||
const created = yield* client.createSession({
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
});
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
client.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
|
||||
|
||||
const close = Scope.close(runtimeScope, Exit.void).pipe(Effect.asVoid);
|
||||
|
||||
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 setConfigOption = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
|
||||
validateConfigOptionValue(configId, value).pipe(
|
||||
Effect.flatMap(() => {
|
||||
const requestPayload =
|
||||
typeof value === "boolean"
|
||||
? ({
|
||||
sessionId,
|
||||
configId,
|
||||
type: "boolean",
|
||||
value,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
sessionId,
|
||||
configId,
|
||||
value: String(value),
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
|
||||
return runLoggedRequest(
|
||||
"session/set_config_option",
|
||||
requestPayload,
|
||||
client.setSessionConfigOption(requestPayload),
|
||||
).pipe(Effect.tap((response) => updateConfigOptions(response)));
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
initializeResult,
|
||||
@@ -169,46 +335,47 @@ export const makeAcpSessionRuntime = (
|
||||
modelConfigId: extractModelConfigId(sessionSetupResult),
|
||||
events: Stream.fromQueue(eventQueue),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
prompt: (payload) =>
|
||||
client.prompt({
|
||||
prompt: (payload) => {
|
||||
const requestPayload = {
|
||||
sessionId,
|
||||
...payload,
|
||||
}),
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
return runLoggedRequest("session/prompt", requestPayload, client.prompt(requestPayload));
|
||||
},
|
||||
cancel: client.cancel({ sessionId }),
|
||||
setMode: (modeId) =>
|
||||
client.setSessionMode({
|
||||
setMode: (modeId) => {
|
||||
const requestPayload = {
|
||||
sessionId,
|
||||
modeId,
|
||||
}),
|
||||
setConfigOption: (configId, value) =>
|
||||
client.setSessionConfigOption(
|
||||
typeof value === "boolean"
|
||||
? ({
|
||||
sessionId,
|
||||
configId,
|
||||
type: "boolean",
|
||||
value,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
sessionId,
|
||||
configId,
|
||||
value: String(value),
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest),
|
||||
),
|
||||
} satisfies EffectAcpSchema.SetSessionModeRequest;
|
||||
return runLoggedRequest(
|
||||
"session/set_mode",
|
||||
requestPayload,
|
||||
client.setSessionMode(requestPayload),
|
||||
);
|
||||
},
|
||||
setConfigOption,
|
||||
setModel: (model) =>
|
||||
client
|
||||
.setSessionConfigOption({
|
||||
sessionId,
|
||||
configId: extractModelConfigId(sessionSetupResult) ?? "model",
|
||||
value: model,
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
request: client.extRequest,
|
||||
setConfigOption(extractModelConfigId(sessionSetupResult) ?? "model", model).pipe(
|
||||
Effect.asVoid,
|
||||
),
|
||||
request: (method, payload) =>
|
||||
runLoggedRequest(method, payload, client.extRequest(method, payload)),
|
||||
notify: client.extNotification,
|
||||
close,
|
||||
} satisfies AcpSessionRuntime;
|
||||
});
|
||||
|
||||
function sessionConfigOptionsFromSetup(
|
||||
response:
|
||||
| {
|
||||
readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
|
||||
}
|
||||
| undefined,
|
||||
): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
|
||||
return response?.configOptions ?? [];
|
||||
}
|
||||
|
||||
const handleSessionUpdate = ({
|
||||
queue,
|
||||
modeStateRef,
|
||||
@@ -219,7 +386,7 @@ const handleSessionUpdate = ({
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly params: EffectAcpSchema.SessionNotification;
|
||||
}): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
}): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseSessionUpdateEvent(params);
|
||||
if (parsed.modeId) {
|
||||
@@ -249,7 +416,7 @@ const handleSessionUpdate = ({
|
||||
}
|
||||
yield* Queue.offer(queue, event);
|
||||
}
|
||||
}).pipe(Effect.mapError(EffectAcpErrors.normalizeAcpError));
|
||||
});
|
||||
|
||||
function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
|
||||
const normalized = nextModeId.trim();
|
||||
|
||||
@@ -21,6 +21,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
authMethodId: "cursor_login",
|
||||
});
|
||||
expect(runtime.initializeResult).toBeDefined();
|
||||
yield* runtime.close;
|
||||
@@ -30,6 +31,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
|
||||
it.effect("session/new returns configOptions with a model selector", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
authMethodId: "cursor_login",
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
@@ -59,6 +61,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
|
||||
it.effect("session/set_config_option switches the model in-session", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
authMethodId: "cursor_login",
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
|
||||
@@ -29,6 +29,7 @@ describe("CursorAcpExtension", () => {
|
||||
id: "language",
|
||||
header: "Question",
|
||||
question: "Which language should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "TypeScript", description: "TypeScript" },
|
||||
{ label: "Rust", description: "Rust" },
|
||||
@@ -37,6 +38,35 @@ describe("CursorAcpExtension", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("defaults ask-question multi-select to false when Cursor omits allowMultiple", () => {
|
||||
const questions = extractAskQuestions({
|
||||
toolCallId: "ask-2",
|
||||
questions: [
|
||||
{
|
||||
id: "mode",
|
||||
prompt: "Which mode should I use?",
|
||||
options: [
|
||||
{ id: "agent", label: "Agent" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "mode",
|
||||
header: "Question",
|
||||
question: "Which mode should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Agent", description: "Agent" },
|
||||
{ label: "Plan", description: "Plan" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("extracts plan markdown from the real Cursor create-plan payload shape", () => {
|
||||
const planMarkdown = extractPlanMarkdown({
|
||||
toolCallId: "plan-1",
|
||||
@@ -53,20 +83,25 @@ describe("CursorAcpExtension", () => {
|
||||
expect(planMarkdown).toBe("# Plan\n\n1. Add schemas\n2. Remove casts");
|
||||
});
|
||||
|
||||
it("projects todo updates into a plan shape", () => {
|
||||
it("projects todo updates into a plan shape and drops invalid entries", () => {
|
||||
expect(
|
||||
extractTodosAsPlan({
|
||||
toolCallId: "todos-1",
|
||||
todos: [
|
||||
{ content: "Inspect state", status: "completed" },
|
||||
{ title: "Apply fix", status: "in_progress" },
|
||||
{},
|
||||
{ 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: "Step 3", status: "pending" },
|
||||
{ step: "Fallback title", status: "pending" },
|
||||
{ step: "Unknown status", status: "pending" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,35 +10,31 @@ const CursorAskQuestion = Schema.Struct({
|
||||
id: Schema.String,
|
||||
prompt: Schema.String,
|
||||
options: Schema.Array(CursorAskQuestionOption),
|
||||
allowMultiple: Schema.Boolean,
|
||||
allowMultiple: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
export const CursorAskQuestionRequest = Schema.Struct({
|
||||
toolCallId: Schema.optional(Schema.String),
|
||||
toolCallId: Schema.String,
|
||||
title: Schema.optional(Schema.String),
|
||||
questions: Schema.Array(CursorAskQuestion),
|
||||
});
|
||||
|
||||
const CursorTodoStatus = Schema.Union([
|
||||
Schema.Literal("pending"),
|
||||
Schema.Literal("in_progress"),
|
||||
Schema.Literal("completed"),
|
||||
Schema.Literal("cancelled"),
|
||||
]);
|
||||
const CursorTodoStatus = Schema.String;
|
||||
|
||||
const CursorTodo = Schema.Struct({
|
||||
id: Schema.optional(Schema.String),
|
||||
content: Schema.optional(Schema.String),
|
||||
status: CursorTodoStatus,
|
||||
title: Schema.optional(Schema.String),
|
||||
status: Schema.optional(CursorTodoStatus),
|
||||
});
|
||||
|
||||
const CursorPlanPhase = Schema.Struct({
|
||||
name: Schema.optional(Schema.String),
|
||||
name: Schema.String,
|
||||
todos: Schema.Array(CursorTodo),
|
||||
});
|
||||
|
||||
export const CursorCreatePlanRequest = Schema.Struct({
|
||||
toolCallId: Schema.optional(Schema.String),
|
||||
toolCallId: Schema.String,
|
||||
name: Schema.optional(Schema.String),
|
||||
overview: Schema.optional(Schema.String),
|
||||
plan: Schema.String,
|
||||
@@ -47,7 +43,11 @@ export const CursorCreatePlanRequest = Schema.Struct({
|
||||
phases: Schema.optional(Schema.Array(CursorPlanPhase)),
|
||||
});
|
||||
|
||||
export const CursorUpdateTodosRequest = Schema.Unknown;
|
||||
export const CursorUpdateTodosRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
todos: Schema.Array(CursorTodo),
|
||||
merge: Schema.Boolean,
|
||||
});
|
||||
|
||||
export function extractAskQuestions(
|
||||
params: typeof CursorAskQuestionRequest.Type,
|
||||
@@ -56,7 +56,7 @@ export function extractAskQuestions(
|
||||
id: question.id,
|
||||
header: "Question",
|
||||
question: question.prompt,
|
||||
multiSelect: question.allowMultiple,
|
||||
multiSelect: question.allowMultiple === true,
|
||||
options:
|
||||
question.options.length > 0
|
||||
? question.options.map((option) => ({
|
||||
@@ -78,39 +78,23 @@ export function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type)
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
} {
|
||||
if (typeof params !== "object" || params === null) {
|
||||
return { plan: [] };
|
||||
}
|
||||
const record = params as {
|
||||
readonly todos?: ReadonlyArray<{
|
||||
readonly content?: string;
|
||||
readonly title?: string;
|
||||
readonly status?: string;
|
||||
}>;
|
||||
readonly items?: ReadonlyArray<{
|
||||
readonly content?: string;
|
||||
readonly title?: string;
|
||||
readonly status?: string;
|
||||
}>;
|
||||
};
|
||||
const todos = record.todos ?? record.items;
|
||||
if (!todos) {
|
||||
return { plan: [] };
|
||||
}
|
||||
const plan = todos.map((t, i) => {
|
||||
const plan = params.todos.flatMap((todo) => {
|
||||
const step =
|
||||
typeof t?.content === "string"
|
||||
? t.content
|
||||
: typeof t?.title === "string"
|
||||
? t.title
|
||||
: `Step ${i + 1}`;
|
||||
typeof todo.content === "string"
|
||||
? todo.content.trim()
|
||||
: typeof todo.title === "string"
|
||||
? todo.title.trim()
|
||||
: "";
|
||||
if (!step) {
|
||||
return [];
|
||||
}
|
||||
const status: "pending" | "inProgress" | "completed" =
|
||||
t?.status === "completed"
|
||||
todo.status === "completed"
|
||||
? "completed"
|
||||
: t?.status === "in_progress" || t?.status === "inProgress"
|
||||
: todo.status === "in_progress" || todo.status === "inProgress"
|
||||
? "inProgress"
|
||||
: "pending";
|
||||
return { step, status };
|
||||
return [{ step, status }];
|
||||
});
|
||||
return { plan };
|
||||
}
|
||||
@@ -160,11 +160,15 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("Work log");
|
||||
});
|
||||
|
||||
it("formats changed file paths from the workspace root", async () => {
|
||||
it("adds a hover title for full work log text", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
@@ -173,17 +177,33 @@ describe("MessagesTimeline", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
label: "Updated files",
|
||||
tone: "tool",
|
||||
changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
|
||||
label: "Provider turn start failed",
|
||||
tone: "error",
|
||||
detail:
|
||||
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"',
|
||||
},
|
||||
},
|
||||
]}
|
||||
workspaceRoot="C:/Users/mike/dev-stuff/t3code"
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
|
||||
expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
|
||||
expect(markup).toContain(
|
||||
'title="Provider turn start failed - Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model""',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -958,71 +958,29 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
<EntryIcon className="size-3" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
{rawCommand ? (
|
||||
<div className="max-w-full">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
className="block min-w-0 w-full text-left"
|
||||
title={displayText}
|
||||
aria-label={displayText}
|
||||
>
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-xs leading-5",
|
||||
"truncate text-[11px] 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}
|
||||
delay={75}
|
||||
render={
|
||||
<span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">
|
||||
{" "}
|
||||
- {preview}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
align="start"
|
||||
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
|
||||
side="top"
|
||||
>
|
||||
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
|
||||
{rawCommand}
|
||||
</div>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
|
||||
</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>
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup className="max-w-[min(720px,calc(100vw-2rem))]">
|
||||
<p className="whitespace-pre-wrap break-words text-xs leading-5">{displayText}</p>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
{hasChangedFiles && !previewIsChangedFiles && (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Path from "effect/Path";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -15,20 +16,25 @@ const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
);
|
||||
|
||||
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 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",
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const handle = yield* makeHandle();
|
||||
|
||||
const client = yield* AcpClient.fromChildProcess(handle, {
|
||||
handlers: {
|
||||
@@ -120,4 +126,72 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
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 client = yield* AcpClient.fromChildProcess(handle, {
|
||||
handlers: {
|
||||
requestPermission: () =>
|
||||
Effect.succeed({
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
}),
|
||||
elicitation: () =>
|
||||
Effect.succeed({
|
||||
action: {
|
||||
action: "accept",
|
||||
content: {
|
||||
approved: true,
|
||||
},
|
||||
},
|
||||
}),
|
||||
extRequests: {
|
||||
"x/typed_request": AcpClient.defineExtRequest(
|
||||
Schema.Struct({ message: Schema.String }),
|
||||
() => Effect.succeed({ ok: true }),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* client.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
},
|
||||
clientInfo: {
|
||||
name: "effect-acp-test",
|
||||
version: "0.0.0",
|
||||
},
|
||||
});
|
||||
|
||||
yield* client.authenticate({ methodId: "cursor_login" });
|
||||
|
||||
const session = yield* client.createSession({
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
|
||||
const result = yield* Effect.exit(
|
||||
client.prompt({
|
||||
sessionId: session.sessionId,
|
||||
prompt: [{ type: "text", text: "hello" }],
|
||||
}),
|
||||
);
|
||||
|
||||
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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as RpcClient from "effect/unstable/rpc/RpcClient";
|
||||
@@ -13,26 +14,27 @@ import * as AcpServer from "./server";
|
||||
import * as AcpSchema from "./_generated/schema.gen";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { RpcClientError } from "effect/unstable/rpc";
|
||||
|
||||
export interface AcpExtensionRequestRegistration<A> {
|
||||
readonly payload: Schema.Schema<A>;
|
||||
export interface AcpExtensionRequestRegistration<A, I = unknown> {
|
||||
readonly payload: Schema.Codec<A, I>;
|
||||
readonly handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export interface AcpExtensionNotificationRegistration<A> {
|
||||
readonly payload: Schema.Schema<A>;
|
||||
export interface AcpExtensionNotificationRegistration<A, I = unknown> {
|
||||
readonly payload: Schema.Codec<A, I>;
|
||||
readonly handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export const defineExtRequest = <A>(
|
||||
payload: Schema.Schema<A>,
|
||||
export const defineExtRequest = <A, I>(
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
): AcpExtensionRequestRegistration<A> => ({ payload, handler });
|
||||
): AcpExtensionRequestRegistration<A, I> => ({ payload, handler });
|
||||
|
||||
export const defineExtNotification = <A>(
|
||||
payload: Schema.Schema<A>,
|
||||
export const defineExtNotification = <A, I>(
|
||||
payload: Schema.Codec<A, I>,
|
||||
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
|
||||
): AcpExtensionNotificationRegistration<A> => ({ payload, handler });
|
||||
): AcpExtensionNotificationRegistration<A, I> => ({ payload, handler });
|
||||
|
||||
export interface AcpClientHandlers {
|
||||
/**
|
||||
@@ -141,6 +143,9 @@ export interface AcpClientHandlers {
|
||||
export interface AcpClientConnectOptions {
|
||||
readonly command: ChildProcess.Command;
|
||||
readonly handlers?: AcpClientHandlers;
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface AcpClientConnection {
|
||||
@@ -270,12 +275,18 @@ export const fromChildProcess = Effect.fnUntraced(function* (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
options: {
|
||||
readonly handlers?: AcpClientHandlers;
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
} = {},
|
||||
): Effect.fn.Return<AcpClientConnection, never, Scope.Scope> {
|
||||
const handlers = options.handlers ?? {};
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: makeStdioFromChildProcess(handle),
|
||||
serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()),
|
||||
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
|
||||
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
|
||||
...(options.logger ? { logger: options.logger } : {}),
|
||||
onNotification: (notification) => {
|
||||
switch (notification._tag) {
|
||||
case "SessionUpdate":
|
||||
@@ -349,8 +360,20 @@ export const fromChildProcess = Effect.fnUntraced(function* (
|
||||
Effect.provideService(RpcClient.Protocol, transport.clientProtocol),
|
||||
);
|
||||
|
||||
const callRpc = <A, E>(effect: Effect.Effect<A, E>) =>
|
||||
effect.pipe(Effect.mapError(AcpError.normalizeAcpError));
|
||||
const callRpc = <A>(effect: Effect.Effect<A, RpcClientError.RpcClientError | AcpSchema.Error>) =>
|
||||
effect.pipe(
|
||||
Effect.catchTag("RpcClientError", (error) =>
|
||||
Effect.fail(
|
||||
new AcpError.AcpTransportError({
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(Schema.is(AcpSchema.Error), (error) =>
|
||||
Effect.fail(AcpError.AcpRequestError.fromProtocolError(error)),
|
||||
),
|
||||
);
|
||||
|
||||
const server = AcpServer.makeAcpServerConnection(transport);
|
||||
|
||||
@@ -388,29 +411,17 @@ const runHandler = Effect.fnUntraced(function* <A, B>(
|
||||
}
|
||||
return yield* handler(payload).pipe(
|
||||
Effect.mapError((error) => {
|
||||
const normalized = AcpError.normalizeAcpError(error);
|
||||
return Schema.is(AcpError.AcpRequestError)(normalized)
|
||||
? normalized.toProtocolError()
|
||||
: AcpError.AcpRequestError.internalError(normalized.message).toProtocolError();
|
||||
return Schema.is(AcpError.AcpRequestError)(error)
|
||||
? error.toProtocolError()
|
||||
: AcpError.AcpRequestError.internalError(error.message).toProtocolError();
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const decodeUnknownWith = <A>(
|
||||
schema: Schema.Schema<A>,
|
||||
payload: unknown,
|
||||
): Effect.Effect<A, AcpError.AcpError> =>
|
||||
Effect.try({
|
||||
try: () => Schema.decodeUnknownSync(schema as never)(payload) as A,
|
||||
catch: (cause) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: "Failed to decode typed ACP extension payload",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
|
||||
|
||||
const runExtRequestHandler = <A>(
|
||||
registration: AcpExtensionRequestRegistration<A> | undefined,
|
||||
const runExtRequestHandler = <A, I>(
|
||||
registration: AcpExtensionRequestRegistration<A, I> | undefined,
|
||||
fallback:
|
||||
| ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
|
||||
| undefined,
|
||||
@@ -418,8 +429,13 @@ const runExtRequestHandler = <A>(
|
||||
params: unknown,
|
||||
): Effect.Effect<unknown, AcpError.AcpError> => {
|
||||
if (registration) {
|
||||
return decodeUnknownWith(registration.payload, params).pipe(
|
||||
Effect.mapError(() => AcpError.AcpRequestError.invalidParams(`Invalid ${method} payload`)),
|
||||
return Schema.decodeUnknownEffect(registration.payload)(params).pipe(
|
||||
Effect.mapError((error) =>
|
||||
AcpError.AcpRequestError.invalidParams(
|
||||
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
|
||||
{ issue: error.issue },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((payload) => registration.handler(payload)),
|
||||
);
|
||||
}
|
||||
@@ -429,8 +445,8 @@ const runExtRequestHandler = <A>(
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
};
|
||||
|
||||
const runExtNotificationHandler = <A>(
|
||||
registration: AcpExtensionNotificationRegistration<A> | undefined,
|
||||
const runExtNotificationHandler = <A, I>(
|
||||
registration: AcpExtensionNotificationRegistration<A, I> | undefined,
|
||||
fallback:
|
||||
| ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
|
||||
| undefined,
|
||||
@@ -438,7 +454,14 @@ const runExtNotificationHandler = <A>(
|
||||
params: unknown,
|
||||
): Effect.Effect<void, AcpError.AcpError> => {
|
||||
if (registration) {
|
||||
return decodeUnknownWith(registration.payload, params).pipe(
|
||||
return Schema.decodeUnknownEffect(registration.payload)(params).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${method} notification payload: ${formatSchemaIssue(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((payload) => registration.handler(payload)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
|
||||
|
||||
import * as AcpSchema from "./_generated/schema.gen";
|
||||
|
||||
export type AcpProtocolError = AcpSchema.Error;
|
||||
|
||||
export class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()("AcpSpawnError", {
|
||||
command: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
cause: Schema.Defect,
|
||||
}) {
|
||||
override get message() {
|
||||
return this.command
|
||||
@@ -46,16 +43,12 @@ export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError
|
||||
"AcpTransportError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
cause: Schema.Defect,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
) {}
|
||||
|
||||
export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()("AcpRequestError", {
|
||||
code: Schema.Number,
|
||||
code: AcpSchema.ErrorCode,
|
||||
errorMessage: Schema.String,
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
}) {
|
||||
@@ -63,7 +56,7 @@ export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()(
|
||||
return this.errorMessage;
|
||||
}
|
||||
|
||||
static fromProtocolError(error: AcpProtocolError) {
|
||||
static fromProtocolError(error: AcpSchema.Error) {
|
||||
return new AcpRequestError({
|
||||
code: error.code,
|
||||
errorMessage: error.message,
|
||||
@@ -126,57 +119,21 @@ export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()(
|
||||
});
|
||||
}
|
||||
|
||||
toProtocolError(): AcpProtocolError {
|
||||
return {
|
||||
toProtocolError() {
|
||||
return AcpSchema.Error.makeUnsafe({
|
||||
code: this.code,
|
||||
message: this.errorMessage,
|
||||
...(this.data !== undefined ? { data: this.data } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export type AcpError =
|
||||
| AcpRequestError
|
||||
| AcpSpawnError
|
||||
| AcpProcessExitedError
|
||||
| AcpProtocolParseError
|
||||
| AcpTransportError;
|
||||
|
||||
export function normalizeAcpError(error: unknown): AcpError {
|
||||
if (
|
||||
Schema.is(AcpRequestError)(error) ||
|
||||
Schema.is(AcpSpawnError)(error) ||
|
||||
Schema.is(AcpProcessExitedError)(error) ||
|
||||
Schema.is(AcpProtocolParseError)(error) ||
|
||||
Schema.is(AcpTransportError)(error)
|
||||
) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (Schema.is(RpcClientError.RpcClientError)(error)) {
|
||||
return new AcpTransportError({
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (isProtocolError(error)) {
|
||||
return AcpRequestError.fromProtocolError(error);
|
||||
}
|
||||
|
||||
return new AcpTransportError({
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function isProtocolError(value: unknown): value is AcpProtocolError {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"code" in value &&
|
||||
typeof value.code === "number" &&
|
||||
"message" in value &&
|
||||
typeof value.message === "string"
|
||||
);
|
||||
}
|
||||
export const AcpError = Schema.Union([
|
||||
AcpRequestError,
|
||||
AcpSpawnError,
|
||||
AcpProcessExitedError,
|
||||
AcpProtocolParseError,
|
||||
AcpTransportError,
|
||||
]);
|
||||
|
||||
export type AcpError = typeof AcpError.Type;
|
||||
@@ -17,6 +17,12 @@ import * as AcpSchema from "./_generated/schema.gen";
|
||||
import { CLIENT_METHODS } from "./_generated/meta.gen";
|
||||
import * as AcpError from "./errors";
|
||||
|
||||
export interface AcpProtocolLogEvent {
|
||||
readonly direction: "incoming" | "outgoing";
|
||||
readonly stage: "raw" | "decoded" | "decode_failed";
|
||||
readonly payload: unknown;
|
||||
}
|
||||
|
||||
export type AcpIncomingNotification =
|
||||
| {
|
||||
readonly _tag: "SessionUpdate";
|
||||
@@ -42,6 +48,9 @@ export type AcpIncomingNotification =
|
||||
export interface AcpPatchedProtocolOptions {
|
||||
readonly stdio: Stdio.Stdio;
|
||||
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>;
|
||||
@@ -95,6 +104,19 @@ export const makeAcpPatchedProtocol = (
|
||||
new Map<string, Deferred.Deferred<unknown, AcpError.AcpError>>(),
|
||||
);
|
||||
|
||||
const logProtocol = (event: AcpProtocolLogEvent) => {
|
||||
if (event.direction === "incoming" && !options.logIncoming) {
|
||||
return Effect.void;
|
||||
}
|
||||
if (event.direction === "outgoing" && !options.logOutgoing) {
|
||||
return Effect.void;
|
||||
}
|
||||
return (
|
||||
options.logger?.(event) ??
|
||||
Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
|
||||
);
|
||||
};
|
||||
|
||||
const offerOutgoing = (message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded) =>
|
||||
Effect.try({
|
||||
try: () => parser.encode(message),
|
||||
@@ -104,8 +126,21 @@ export const makeAcpPatchedProtocol = (
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.tap(() =>
|
||||
logProtocol({
|
||||
direction: "outgoing",
|
||||
stage: "decoded",
|
||||
payload: message,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((encoded) =>
|
||||
encoded === undefined ? Effect.void : Queue.offer(outgoing, encoded).pipe(Effect.asVoid),
|
||||
encoded === undefined
|
||||
? Effect.void
|
||||
: logProtocol({
|
||||
direction: "outgoing",
|
||||
stage: "raw",
|
||||
payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
|
||||
}).pipe(Effect.flatMap(() => Queue.offer(outgoing, encoded).pipe(Effect.asVoid))),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -325,17 +360,41 @@ export const makeAcpPatchedProtocol = (
|
||||
|
||||
yield* options.stdio.stdin.pipe(
|
||||
Stream.runForEach((data) =>
|
||||
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,
|
||||
}),
|
||||
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,
|
||||
@@ -344,7 +403,12 @@ export const makeAcpPatchedProtocol = (
|
||||
),
|
||||
),
|
||||
Effect.catch((error) => {
|
||||
const normalized = AcpError.normalizeAcpError(error);
|
||||
const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error)
|
||||
? error
|
||||
: new AcpError.AcpTransportError({
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
cause: error,
|
||||
});
|
||||
const rpcClientError = new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: normalized.message,
|
||||
@@ -415,7 +479,7 @@ export const makeAcpPatchedProtocol = (
|
||||
method,
|
||||
...(payload !== undefined ? { params: payload } : {}),
|
||||
})}\n`,
|
||||
).pipe(Effect.asVoid, Effect.mapError(AcpError.normalizeAcpError));
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const sendRequest = (method: string, payload: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -470,11 +534,10 @@ function isProtocolError(
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeToRequestError(error: unknown): AcpError.AcpRequestError {
|
||||
const normalized = AcpError.normalizeAcpError(error);
|
||||
return Schema.is(AcpError.AcpRequestError)(normalized)
|
||||
? normalized
|
||||
: AcpError.AcpRequestError.internalError(normalized.message);
|
||||
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 {
|
||||
|
||||
@@ -14,6 +14,8 @@ Effect.gen(function* () {
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const client = yield* AcpClient.fromChildProcess(handle, {
|
||||
logIncoming: true,
|
||||
logOutgoing: true,
|
||||
handlers: {
|
||||
requestPermission: () =>
|
||||
Effect.succeed({
|
||||
@@ -43,7 +45,13 @@ Effect.gen(function* () {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
yield* Effect.logInfo("created session", { sessionId: session.sessionId });
|
||||
|
||||
const update = yield* client.setSessionConfigOption({
|
||||
sessionId: session.sessionId,
|
||||
configId: "model",
|
||||
value: "gpt-5.4[reasoning=xhigh,context=272k,fast=false]",
|
||||
});
|
||||
yield* Effect.logInfo("updated model", update);
|
||||
|
||||
const result = yield* client.prompt({
|
||||
sessionId: session.sessionId,
|
||||
|
||||
+17
-2
@@ -15,6 +15,21 @@ function writeMessage(message: unknown) {
|
||||
process.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"message" in error &&
|
||||
typeof error.message === "string"
|
||||
) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function respond(id: number | string | null | undefined, result: unknown) {
|
||||
writeMessage({
|
||||
jsonrpc: "2.0",
|
||||
@@ -157,7 +172,7 @@ async function handleRequest(message: {
|
||||
});
|
||||
|
||||
await requestClient("x/typed_request", {
|
||||
message: "hello from typed request",
|
||||
message: process.env.ACP_MOCK_BAD_TYPED_REQUEST === "1" ? 123 : "hello from typed request",
|
||||
});
|
||||
|
||||
notify("x/typed_notification", {
|
||||
@@ -216,7 +231,7 @@ rl.on("line", (line) => {
|
||||
|
||||
if ("method" in message && "id" in message) {
|
||||
void handleRequest(message).catch((error) => {
|
||||
respondError(message.id, -32603, error instanceof Error ? error.message : String(error));
|
||||
respondError(message.id, -32603, errorMessage(error));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user