This commit is contained in:
Julius Marminge committed 2026-04-17 16:44:48 -07:00
1 parent e1cba531a2
commit 52f4c7e0f3
19 files changed
+1238 -208

No files matched your search

+92
View File
@@ -12,6 +12,9 @@ import type * as AcpSchema from "effect-acp/schema";
const requestLogPath = process.env.T3_ACP_REQUEST_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";
@@ -136,6 +139,56 @@ const program = Effect.gen(function* () {
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";
@@ -217,6 +270,45 @@ const program = Effect.gen(function* () {
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",
@@ -13,7 +13,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { Deferred, Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
@@ -1409,6 +1409,60 @@ describe("ProviderCommandReactor", () => {
});
});
it("processes approval responses while a provider turn is still in flight", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const unblockSendTurn = Effect.runSync(Deferred.make<void>());
harness.sendTurn.mockImplementation(() =>
Deferred.await(unblockSendTurn).pipe(
Effect.as({
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-blocked-approval"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-blocked-approval"),
role: "user",
text: "need approval while turn is running",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-approval-respond-during-send-turn"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("approval-request-while-send-turn-blocked"),
decision: "acceptForSession",
createdAt: now,
}),
);
await waitFor(() => harness.respondToRequest.mock.calls.length === 1);
expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
requestId: "approval-request-while-send-turn-blocked",
decision: "acceptForSession",
});
await Effect.runPromise(Deferred.succeed(unblockSendTurn, undefined));
});
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -590,26 +590,7 @@ const make = Effect.gen(function* () {
...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),
};
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
threadId: event.payload.threadId,
branch: thread.branch,
worktreePath: thread.worktreePath,
...generationInput,
}).pipe(Effect.forkScoped);
if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {
yield* maybeGenerateThreadTitleForFirstTurn({
threadId: event.payload.threadId,
cwd: generationCwd,
...generationInput,
}).pipe(Effect.forkScoped);
}
}
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
@@ -626,22 +607,9 @@ const make = Effect.gen(function* () {
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,
@@ -652,25 +620,8 @@ const make = Effect.gen(function* () {
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
}).pipe(
Effect.catchCause((cause) => {
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.map(Option.some),
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
);
if (Option.isNone(sendTurnRequest)) {
@@ -679,7 +630,7 @@ const make = Effect.gen(function* () {
yield* providerService
.sendTurn(sendTurnRequest.value)
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
.pipe(Effect.catchCause(handleTurnStartFailure), Effect.forkScoped);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
@@ -738,8 +738,7 @@ describe("ProviderRuntimeIngestion", () => {
payload: {
itemType: "dynamic_tool_call",
status: "completed",
title: "Read File",
detail: "Read File",
title: "Read file",
data: {
toolCallId: "tool-read-1",
kind: "read",
@@ -772,13 +771,98 @@ describe("ProviderRuntimeIngestion", () => {
: undefined;
expect(activity?.kind).toBe("tool.completed");
expect(activity?.summary).toBe("Read file");
expect(payload?.itemType).toBe("dynamic_tool_call");
expect(payload?.detail).toBe("Read File");
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();
@@ -1487,7 +1571,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
requestId: ApprovalRequestId.make("req-buffered-request-flush"),
requestId: ApprovalRequestId.makeUnsafe("req-buffered-request-flush"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
@@ -1547,7 +1631,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
requestId: ApprovalRequestId.make("req-buffered-user-input-flush"),
requestId: ApprovalRequestId.makeUnsafe("req-buffered-user-input-flush"),
payload: {
questions: [
{
@@ -1615,7 +1699,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
requestId: ApprovalRequestId.make("req-buffered-whitespace-request"),
requestId: ApprovalRequestId.makeUnsafe("req-buffered-whitespace-request"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
@@ -1677,7 +1761,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
requestId: ApprovalRequestId.make("req-buffered-request-append"),
requestId: ApprovalRequestId.makeUnsafe("req-buffered-request-append"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
@@ -1809,7 +1893,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
requestId: ApprovalRequestId.make("req-streaming-request-segment"),
requestId: ApprovalRequestId.makeUnsafe("req-streaming-request-segment"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
@@ -38,6 +38,12 @@ interface AssistantSegmentState {
activeMessageId: MessageId | null;
}
interface AssistantSegmentState {
baseKey: string;
nextSegmentIndex: number;
activeMessageId: MessageId | null;
}
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
@@ -112,6 +118,16 @@ function assistantSegmentBaseKeyFromEvent(event: ProviderRuntimeEvent): string {
return String(event.itemId ?? event.turnId ?? event.eventId);
}
function assistantSegmentMessageId(baseKey: string, segmentIndex: number): MessageId {
return MessageId.makeUnsafe(
segmentIndex === 0 ? `assistant:${baseKey}` : `assistant:${baseKey}:segment:${segmentIndex}`,
);
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function assistantSegmentMessageId(baseKey: string, segmentIndex: number): MessageId {
return MessageId.make(
segmentIndex === 0 ? `assistant:${baseKey}` : `assistant:${baseKey}:segment:${segmentIndex}`,
@@ -95,7 +95,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper());
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
Stream.runCollect,
Effect.forkChild,
);
@@ -129,18 +129,32 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
"thread.started",
"turn.started",
"turn.plan.updated",
"item.started",
"content.delta",
"item.completed",
"turn.completed",
] as const) {
assert.include(types, t);
}
const assistantStarted = runtimeEvents.find(
(event) => event.type === "item.started" && event.payload.itemType === "assistant_message",
);
assert.isDefined(assistantStarted);
const delta = runtimeEvents.find((e) => e.type === "content.delta");
assert.isDefined(delta);
if (delta?.type === "content.delta") {
assert.equal(delta.payload.delta, "hello from mock");
assert.match(String(delta.itemId), /^assistant:mock-session-1:segment:0$/);
}
const assistantCompleted = runtimeEvents.find(
(event) =>
event.type === "item.completed" && event.payload.itemType === "assistant_message",
);
assert.isDefined(assistantCompleted);
const planUpdate = runtimeEvents.find((event) => event.type === "turn.plan.updated");
assert.isDefined(planUpdate);
if (planUpdate?.type === "turn.plan.updated") {
@@ -201,59 +215,228 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.stopSession(threadId);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const modeRequest = requests.find((entry) => entry.method === "session/set_mode");
const modeRequest = requests.find(
(entry) =>
entry.method === "session/set_mode" ||
(entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "mode"),
);
assert.isDefined(modeRequest);
assert.deepStrictEqual(modeRequest?.params, {
sessionId: "mock-session-1",
modeId: "architect",
});
assert.equal(
(modeRequest?.params as Record<string, unknown> | undefined)?.sessionId,
"mock-session-1",
);
assert.include(
["architect", "plan"],
String(
(modeRequest?.params as Record<string, unknown> | undefined)?.modeId ??
(modeRequest?.params as Record<string, unknown> | undefined)?.value,
),
);
}),
);
it.effect("streams ACP tool calls and approvals on the active turn in real time", () =>
Effect.gen(function* () {
const previousEmitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS;
process.env.T3_ACP_EMIT_TOOL_CALLS = "1";
it.effect(
"streams ACP tool calls and approvals on the active turn in approval-required mode",
() =>
Effect.gen(function* () {
const previousEmitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS;
process.env.T3_ACP_EMIT_TOOL_CALLS = "1";
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.makeUnsafe("cursor-tool-call-probe");
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const settledEventTypes = new Set<string>();
const settledEventsReady = yield* Deferred.make<void>();
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.makeUnsafe("cursor-tool-call-probe");
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const settledEventTypes = new Set<string>();
const settledEventsReady = yield* Deferred.make<void>();
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_EMIT_TOOL_CALLS: "1" }),
);
yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_EMIT_TOOL_CALLS: "1" }),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "request.opened" && event.requestId) {
yield* adapter.respondToRequest(
threadId,
ApprovalRequestId.makeUnsafe(String(event.requestId)),
"accept",
);
}
if (
event.type === "turn.completed" ||
event.type === "item.completed" ||
event.type === "content.delta"
) {
settledEventTypes.add(event.type);
if (settledEventTypes.size === 3) {
yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie);
yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
}
}),
).pipe(Effect.forkChild);
if (event.type === "request.opened" && event.requestId) {
yield* adapter.respondToRequest(
threadId,
ApprovalRequestId.makeUnsafe(String(event.requestId)),
"accept",
);
}
if (
event.type === "turn.completed" ||
(event.type === "item.completed" && event.payload.itemType === "command_execution") ||
event.type === "content.delta"
) {
settledEventTypes.add(event.type);
if (settledEventTypes.size === 3) {
yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie);
}
}
}),
).pipe(Effect.forkChild);
const program = Effect.gen(function* () {
yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { provider: "cursor", model: "default" },
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run a tool call",
attachments: [],
});
yield* Deferred.await(settledEventsReady);
const threadEvents = runtimeEvents.filter(
(event) => String(event.threadId) === String(threadId),
);
assert.includeMembers(
threadEvents.map((event) => event.type),
[
"session.started",
"session.state.changed",
"thread.started",
"turn.started",
"request.opened",
"request.resolved",
"item.updated",
"item.completed",
"content.delta",
"turn.completed",
],
);
const turnEvents = threadEvents.filter(
(event) => String(event.turnId) === String(turn.turnId),
);
const toolUpdates = turnEvents.filter((event) => event.type === "item.updated");
assert.lengthOf(toolUpdates, 2);
for (const toolUpdate of toolUpdates) {
if (toolUpdate.type !== "item.updated") {
continue;
}
assert.equal(toolUpdate.payload.itemType, "command_execution");
assert.equal(toolUpdate.payload.status, "inProgress");
assert.equal(toolUpdate.payload.detail, "cat server/package.json");
assert.equal(String(toolUpdate.itemId), "tool-call-1");
}
const requestOpened = turnEvents.find((event) => event.type === "request.opened");
assert.isDefined(requestOpened);
if (requestOpened?.type === "request.opened") {
assert.equal(String(requestOpened.turnId), String(turn.turnId));
assert.equal(requestOpened.payload.requestType, "exec_command_approval");
assert.equal(requestOpened.payload.detail, "cat server/package.json");
}
const requestResolved = turnEvents.find((event) => event.type === "request.resolved");
assert.isDefined(requestResolved);
if (requestResolved?.type === "request.resolved") {
assert.equal(String(requestResolved.turnId), String(turn.turnId));
assert.equal(requestResolved.payload.requestType, "exec_command_approval");
assert.equal(requestResolved.payload.decision, "accept");
}
const toolCompleted = turnEvents.find(
(event) =>
event.type === "item.completed" && event.payload.itemType === "command_execution",
);
assert.isDefined(toolCompleted);
if (toolCompleted?.type === "item.completed") {
assert.equal(String(toolCompleted.turnId), String(turn.turnId));
assert.equal(toolCompleted.payload.itemType, "command_execution");
assert.equal(toolCompleted.payload.status, "completed");
assert.equal(toolCompleted.payload.detail, "cat server/package.json");
assert.equal(String(toolCompleted.itemId), "tool-call-1");
}
const contentDelta = turnEvents.find((event) => event.type === "content.delta");
assert.isDefined(contentDelta);
if (contentDelta?.type === "content.delta") {
assert.equal(String(contentDelta.turnId), String(turn.turnId));
assert.equal(contentDelta.payload.delta, "hello from mock");
assert.equal(String(contentDelta.itemId), "assistant:mock-session-1:segment:0");
}
});
yield* program.pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousEmitToolCalls === undefined) {
delete process.env.T3_ACP_EMIT_TOOL_CALLS;
} else {
process.env.T3_ACP_EMIT_TOOL_CALLS = previousEmitToolCalls;
}
}),
),
);
}).pipe(
Effect.provide(
makeCursorAdapterLive().pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-adapter-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
),
),
);
it.effect(
"auto-approves ACP tool permissions in full-access mode without approval runtime events",
() =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.makeUnsafe("cursor-full-access-auto-approve");
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const settledEventTypes = new Set<string>();
const settledEventsReady = yield* Deferred.make<void>();
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const argvLogPath = path.join(tempDir, "argv.txt");
yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath, { T3_ACP_EMIT_TOOL_CALLS: "1" }),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
if (
event.type === "turn.completed" ||
(event.type === "item.completed" && event.payload.itemType === "command_execution") ||
event.type === "content.delta"
) {
settledEventTypes.add(event.type);
if (settledEventTypes.size === 3) {
yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie);
}
}
}),
).pipe(Effect.forkChild);
const program = Effect.gen(function* () {
yield* adapter.startSession({
threadId,
provider: "cursor",
@@ -267,100 +450,174 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
input: "run a tool call",
attachments: [],
});
yield* Deferred.await(settledEventsReady);
const threadEvents = runtimeEvents.filter(
(event) => String(event.threadId) === String(threadId),
yield* Deferred.await(settledEventsReady);
yield* Fiber.interrupt(runtimeEventsFiber);
const turnEvents = runtimeEvents.filter(
(event) =>
String(event.threadId) === String(threadId) &&
String(event.turnId) === String(turn.turnId),
);
assert.notInclude(
turnEvents.map((event) => event.type),
"request.opened",
);
assert.notInclude(
turnEvents.map((event) => event.type),
"request.resolved",
);
assert.includeMembers(
threadEvents.map((event) => event.type),
[
"session.started",
"session.state.changed",
"thread.started",
"turn.started",
"request.opened",
"request.resolved",
"item.updated",
"item.completed",
"content.delta",
"turn.completed",
],
turnEvents.map((event) => event.type),
["item.updated", "item.completed", "content.delta", "turn.completed"],
);
const turnEvents = threadEvents.filter(
(event) => String(event.turnId) === String(turn.turnId),
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const permissionResponse = requests.find(
(entry) =>
!("method" in entry) &&
typeof entry.result === "object" &&
entry.result !== null &&
"outcome" in entry.result &&
typeof entry.result.outcome === "object" &&
entry.result.outcome !== null &&
"outcome" in entry.result.outcome &&
entry.result.outcome.outcome === "selected" &&
"optionId" in entry.result.outcome &&
entry.result.outcome.optionId === "allow-always",
);
const toolUpdates = turnEvents.filter((event) => event.type === "item.updated");
assert.lengthOf(toolUpdates, 2);
for (const toolUpdate of toolUpdates) {
if (toolUpdate.type !== "item.updated") {
continue;
}
assert.equal(toolUpdate.payload.itemType, "command_execution");
assert.equal(toolUpdate.payload.status, "inProgress");
assert.equal(toolUpdate.payload.detail, "cat server/package.json");
assert.equal(String(toolUpdate.itemId), "tool-call-1");
}
assert.isDefined(permissionResponse);
const requestOpened = turnEvents.find((event) => event.type === "request.opened");
assert.isDefined(requestOpened);
if (requestOpened?.type === "request.opened") {
assert.equal(String(requestOpened.turnId), String(turn.turnId));
assert.equal(requestOpened.payload.requestType, "exec_command_approval");
assert.equal(requestOpened.payload.detail, "cat server/package.json");
}
yield* adapter.stopSession(threadId);
}),
);
const requestResolved = turnEvents.find((event) => event.type === "request.resolved");
assert.isDefined(requestResolved);
if (requestResolved?.type === "request.resolved") {
assert.equal(String(requestResolved.turnId), String(turn.turnId));
assert.equal(requestResolved.payload.requestType, "exec_command_approval");
assert.equal(requestResolved.payload.decision, "accept");
}
it.effect("segments assistant messages around ACP tool activity in full-access mode", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.makeUnsafe("cursor-assistant-tool-segmentation");
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const settledEventTypes = new Set<string>();
const settledEventsReady = yield* Deferred.make<void>();
const toolCompleted = turnEvents.find((event) => event.type === "item.completed");
assert.isDefined(toolCompleted);
if (toolCompleted?.type === "item.completed") {
assert.equal(String(toolCompleted.turnId), String(turn.turnId));
assert.equal(toolCompleted.payload.itemType, "command_execution");
assert.equal(toolCompleted.payload.status, "completed");
assert.equal(toolCompleted.payload.detail, "cat server/package.json");
assert.equal(String(toolCompleted.itemId), "tool-call-1");
}
const contentDelta = turnEvents.find((event) => event.type === "content.delta");
assert.isDefined(contentDelta);
if (contentDelta?.type === "content.delta") {
assert.equal(String(contentDelta.turnId), String(turn.turnId));
assert.equal(contentDelta.payload.delta, "hello from mock");
}
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1" }),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
yield* program.pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousEmitToolCalls === undefined) {
delete process.env.T3_ACP_EMIT_TOOL_CALLS;
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
if (
event.type === "content.delta" ||
(event.type === "item.completed" && event.payload.itemType === "command_execution") ||
event.type === "turn.completed"
) {
if (event.type === "content.delta") {
settledEventTypes.add(`delta:${event.payload.delta}`);
} else {
process.env.T3_ACP_EMIT_TOOL_CALLS = previousEmitToolCalls;
settledEventTypes.add(event.type);
}
}),
),
if (
settledEventTypes.has("delta:before tool") &&
settledEventTypes.has("delta:after tool") &&
settledEventTypes.has("item.completed") &&
settledEventTypes.has("turn.completed")
) {
yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie);
}
}
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run an interleaved tool call",
attachments: [],
});
yield* Deferred.await(settledEventsReady);
yield* Fiber.interrupt(runtimeEventsFiber);
const turnEvents = runtimeEvents.filter(
(event) =>
String(event.threadId) === String(threadId) &&
String(event.turnId) === String(turn.turnId),
);
}).pipe(
Effect.provide(
makeCursorAdapterLive().pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-adapter-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
),
),
const firstAssistantStartIndex = turnEvents.findIndex(
(event) => event.type === "item.started" && event.payload.itemType === "assistant_message",
);
const firstAssistantDeltaIndex = turnEvents.findIndex(
(event) => event.type === "content.delta" && event.payload.delta === "before tool",
);
const assistantBoundaryIndex = turnEvents.findIndex(
(event) =>
event.type === "item.completed" && event.payload.itemType === "assistant_message",
);
const toolUpdateIndex = turnEvents.findIndex(
(event) => event.type === "item.updated" && event.payload.itemType === "command_execution",
);
const toolCompletedIndex = turnEvents.findIndex(
(event) =>
event.type === "item.completed" && event.payload.itemType === "command_execution",
);
const secondAssistantStartIndex = turnEvents.findIndex(
(event, index) =>
index > toolCompletedIndex &&
event.type === "item.started" &&
event.payload.itemType === "assistant_message",
);
const secondAssistantDeltaIndex = turnEvents.findIndex(
(event) => event.type === "content.delta" && event.payload.delta === "after tool",
);
assert.isAtLeast(firstAssistantStartIndex, 0);
assert.isAtLeast(firstAssistantDeltaIndex, 0);
assert.isAtLeast(assistantBoundaryIndex, 0);
assert.isAtLeast(toolUpdateIndex, 0);
assert.isAtLeast(toolCompletedIndex, 0);
assert.isAtLeast(secondAssistantStartIndex, 0);
assert.isAtLeast(secondAssistantDeltaIndex, 0);
assert.isBelow(firstAssistantStartIndex, firstAssistantDeltaIndex);
assert.isBelow(firstAssistantDeltaIndex, assistantBoundaryIndex);
assert.isBelow(assistantBoundaryIndex, toolUpdateIndex);
assert.isBelow(toolUpdateIndex, toolCompletedIndex);
assert.isBelow(toolCompletedIndex, secondAssistantStartIndex);
assert.isBelow(secondAssistantStartIndex, secondAssistantDeltaIndex);
const assistantStarts = turnEvents.filter(
(event) => event.type === "item.started" && event.payload.itemType === "assistant_message",
);
const assistantDeltas = turnEvents.filter((event) => event.type === "content.delta");
assert.lengthOf(assistantStarts, 2);
assert.lengthOf(assistantDeltas, 2);
if (
assistantStarts[0]?.type === "item.started" &&
assistantStarts[1]?.type === "item.started" &&
assistantDeltas[0]?.type === "content.delta" &&
assistantDeltas[1]?.type === "content.delta"
) {
assert.notEqual(String(assistantStarts[0].itemId), String(assistantStarts[1].itemId));
assert.equal(String(assistantDeltas[0].itemId), String(assistantStarts[0].itemId));
assert.equal(String(assistantDeltas[1].itemId), String(assistantStarts[1].itemId));
}
yield* adapter.stopSession(threadId);
}),
);
it.effect("cancels pending ACP approvals and marks the turn cancelled when interrupted", () =>
@@ -405,7 +662,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
runtimeMode: "approval-required",
modelSelection: { provider: "cursor", model: "default" },
});
@@ -475,7 +732,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
runtimeMode: "approval-required",
modelSelection: { provider: "cursor", model: "default" },
});
@@ -579,7 +836,9 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const setConfigRequests = requests.filter(
(entry) => entry.method === "session/set_config_option",
(entry) =>
entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "model",
);
assert.isAbove(setConfigRequests.length, 0, "should call session/set_config_option");
assert.equal((setConfigRequests[0]?.params as Record<string, unknown>)?.value, "composer-2");
@@ -45,6 +45,7 @@ import {
import { AcpSessionRuntime, type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
import {
makeAcpAssistantItemEvent,
makeAcpContentDeltaEvent,
makeAcpPlanUpdatedEvent,
makeAcpRequestOpenedEvent,
@@ -207,6 +208,22 @@ function resolveRequestedModeId(input: {
);
}
function selectAutoApprovedPermissionOption(
request: EffectAcpSchema.RequestPermissionRequest,
): string | undefined {
const allowAlwaysOption = request.options.find((option) => option.kind === "allow_always");
if (typeof allowAlwaysOption?.optionId === "string" && allowAlwaysOption.optionId.trim()) {
return allowAlwaysOption.optionId.trim();
}
const allowOnceOption = request.options.find((option) => option.kind === "allow_once");
if (typeof allowOnceOption?.optionId === "string" && allowOnceOption.optionId.trim()) {
return allowOnceOption.optionId.trim();
}
return undefined;
}
function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -496,6 +513,17 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
yield* acp.handleRequestPermission((params) =>
Effect.gen(function* () {
yield* logNative(input.threadId, "session/request_permission", params, "acp.jsonrpc");
if (ctx?.session.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
return {
outcome: {
outcome: "selected" as const,
optionId: autoApprovedOptionId,
},
};
}
}
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
@@ -585,6 +613,30 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
switch (event._tag) {
case "ModeChanged":
return;
case "AssistantItemStarted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.started",
}),
);
return;
case "AssistantItemCompleted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.completed",
}),
);
return;
case "PlanUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* emitPlanUpdate(
@@ -616,6 +668,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
}),
@@ -895,7 +948,9 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
listSessions,
hasSession,
stopAll,
streamEvents: Stream.fromQueue(runtimeEventQueue),
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
} satisfies CursorAdapterShape;
});
}
@@ -2,6 +2,7 @@ import { RuntimeRequestId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
makeAcpAssistantItemEvent,
makeAcpContentDeltaEvent,
makeAcpPlanUpdatedEvent,
makeAcpRequestOpenedEvent,
@@ -121,14 +122,34 @@ describe("AcpCoreRuntimeEvents", () => {
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",
},
});
});
});
@@ -191,11 +191,34 @@ export function makeAcpToolCallEvent(input: {
};
}
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.makeUnsafe(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 {
@@ -205,6 +228,7 @@ export function makeAcpContentDeltaEvent(input: {
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
...(input.itemId ? { itemId: RuntimeItemId.makeUnsafe(input.itemId) } : {}),
payload: {
streamKind: "assistant_text",
delta: input.text,
@@ -29,14 +29,27 @@ describe("AcpSessionRuntime", () => {
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 2)));
expect(notes).toHaveLength(2);
expect(notes.map((note) => note._tag)).toEqual(["PlanUpdated", "ContentDelta"]);
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 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);
}
yield* runtime.close;
}).pipe(
@@ -56,6 +69,109 @@ describe("AcpSessionRuntime", () => {
),
);
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.events, 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);
}
yield* runtime.close;
}).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.events, 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");
}
yield* runtime.close;
}).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* () {
@@ -90,7 +90,7 @@ describe("AcpRuntimeModel", () => {
toolCall: {
toolCallId: "tool-1",
kind: "execute",
title: "Terminal",
title: "Ran command",
status: "pending",
command: "bun run typecheck",
detail: "bun run typecheck",
@@ -157,6 +157,8 @@ describe("AcpRuntimeModel", () => {
expect(mergeToolCallState(createdEvent.toolCall, updatedEvent.toolCall)).toMatchObject({
toolCallId: "tool-1",
status: "completed",
title: "Ran command",
detail: "bun run typecheck",
command: "bun run typecheck",
});
}
@@ -1,4 +1,6 @@
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);
@@ -44,6 +46,14 @@ 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;
@@ -56,6 +66,7 @@ export type AcpParsedSessionEvent =
}
| {
readonly _tag: "ContentDelta";
readonly itemId?: string;
readonly text: string;
readonly rawPayload: unknown;
};
@@ -230,6 +241,22 @@ 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;
@@ -256,7 +283,6 @@ function makeToolCallState(
title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
? title
: undefined;
const detail = command ?? normalizedTitle ?? textContent;
const data: Record<string, unknown> = { toolCallId };
const kind = normalizeToolKind(input.kind);
if (kind) {
@@ -277,14 +303,30 @@ function makeToolCallState(
if (input.locations !== undefined) {
data.locations = input.locations;
}
const fallbackDetail = command ?? normalizedTitle ?? textContent;
const hasPresentationSeed =
title !== undefined ||
kind !== undefined ||
command !== undefined ||
normalizedTitle !== undefined ||
textContent !== undefined;
const presentation = hasPresentationSeed
? deriveToolActivityPresentation({
itemType: canonicalItemTypeFromAcpToolKind(kind),
title,
detail: fallbackDetail,
data,
fallbackSummary: title ?? "Tool",
})
: undefined;
const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
return {
toolCallId,
...(kind ? { kind } : {}),
...(title ? { title } : {}),
...(presentation?.summary ? { title: presentation.summary } : {}),
...(status ? { status } : {}),
...(command ? { command } : {}),
...(detail ? { detail } : {}),
...(presentation?.detail ? { detail: presentation.detail } : {}),
data,
};
}
@@ -122,6 +122,16 @@ type AcpStartState =
}
| { 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 ServiceMap.Service<
AcpSessionRuntime,
AcpSessionRuntimeShape
@@ -150,6 +160,7 @@ 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 assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
@@ -222,6 +233,7 @@ const makeAcpSessionRuntime = (
queue: eventQueue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params: notification,
}),
);
@@ -465,10 +477,23 @@ const makeAcpSessionRuntime = (
sessionId: started.sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
return runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
return closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
}).pipe(
Effect.andThen(
runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
),
),
Effect.tap(() =>
closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
}),
),
);
}),
),
@@ -504,11 +529,13 @@ 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* () {
@@ -520,7 +547,11 @@ const handleSessionUpdate = ({
}
for (const event of parsed.events) {
if (event._tag === "ToolCallUpdated") {
const merged = yield* Ref.modify(toolCallsRef, (current) => {
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);
@@ -529,8 +560,11 @@ const handleSessionUpdate = ({
} else {
next.set(nextToolCall.toolCallId, nextToolCall);
}
return [nextToolCall, next] as const;
return [{ previous, merged: nextToolCall }, next] as const;
});
if (!shouldEmitToolCallUpdate(previous, merged)) {
continue;
}
yield* Queue.offer(queue, {
_tag: "ToolCallUpdated",
toolCall: merged,
@@ -538,6 +572,24 @@ const handleSessionUpdate = ({
});
continue;
}
if (event._tag === "ContentDelta") {
if (event.text.trim().length === 0) {
const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
if (!assistantSegmentState.activeItemId) {
continue;
}
}
const itemId = yield* ensureActiveAssistantSegment({
queue,
assistantSegmentRef,
sessionId: params.sessionId,
});
yield* Queue.offer(queue, {
...event,
itemId,
});
continue;
}
yield* Queue.offer(queue, event);
}
});
@@ -554,3 +606,79 @@ function updateModeState(modeState: AcpSessionModeState, nextModeId: string): Ac
}
: modeState;
}
function shouldEmitToolCallUpdate(
previous: AcpToolCallState | undefined,
next: AcpToolCallState,
): boolean {
if (next.status === "completed" || next.status === "failed") {
return true;
}
if (!next.detail) {
return false;
}
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
}
const assistantItemId = (sessionId: string, segmentIndex: number) =>
`assistant:${sessionId}:segment:${segmentIndex}`;
const ensureActiveAssistantSegment = ({
queue,
assistantSegmentRef,
sessionId,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly sessionId: string;
}) =>
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
assistantSegmentRef,
(current) => {
if (current.activeItemId) {
return [{ itemId: current.activeItemId }, current] as const;
}
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
return [
{
itemId,
startedEvent: {
_tag: "AssistantItemStarted",
itemId,
} satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
},
{
nextSegmentIndex: current.nextSegmentIndex + 1,
activeItemId: itemId,
} satisfies AcpAssistantSegmentState,
] as const;
},
).pipe(
Effect.flatMap((result) =>
result.startedEvent
? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
: Effect.succeed(result.itemId),
),
);
const closeActiveAssistantSegment = ({
queue,
assistantSegmentRef,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
}) =>
Ref.modify(assistantSegmentRef, (current) => {
if (!current.activeItemId) {
return [undefined, current] as const;
}
return [
{
_tag: "AssistantItemCompleted",
itemId: current.activeItemId,
} satisfies AcpParsedSessionEvent,
{
nextSegmentIndex: current.nextSegmentIndex,
} satisfies AcpAssistantSegmentState,
] as const;
}).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));
+3
View File
@@ -200,6 +200,9 @@
},
},
},
"patchedDependencies": {
"[email protected]": "patches/[email protected]",
},
"overrides": {
"@effect/atom-react": "catalog:",
"@effect/platform-bun": "catalog:",
+3
View File
@@ -80,5 +80,8 @@
"workerDirectory": [
"apps/web/public"
]
},
"patchedDependencies": {
"[email protected]": "patches/[email protected]"
}
}
+84 -1
View File
@@ -34,6 +34,11 @@ 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 }));
@@ -158,7 +163,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
direction: "outgoing",
stage: "raw",
payload:
'{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
'{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"headers":[]}\n',
},
]);
}),
@@ -222,6 +227,84 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
}),
);
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();
@@ -1,4 +1,5 @@
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";
@@ -30,7 +31,7 @@ const program = Effect.gen(function* () {
}),
);
yield* acp.handleSessionUpdate((notification) =>
Effect.logInfo("session/update", notification),
Console.log("session/update", JSON.stringify(notification)),
);
const initialized = yield* acp.agent.initialize({
@@ -44,7 +45,7 @@ const program = Effect.gen(function* () {
version: "0.0.0",
},
});
yield* Effect.logInfo("initialized", initialized);
yield* Console.log("initialized", JSON.stringify(initialized));
const session = yield* acp.agent.createSession({
cwd: process.cwd(),
@@ -67,7 +68,7 @@ const program = Effect.gen(function* () {
],
});
yield* Effect.logInfo("prompt result", result);
yield* Console.log("prompt result", JSON.stringify(result));
yield* acp.agent.cancel({ sessionId: session.sessionId });
}).pipe(Effect.provide(acpLayer));
});
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { deriveToolActivityPresentation } from "./toolActivity.ts";
import { deriveToolActivityPresentation } from "./toolActivity";
describe("toolActivity", () => {
it("normalizes command tools to a stable ran-command label", () => {
+96
View File
@@ -0,0 +1,96 @@
diff --git a/dist/unstable/rpc/RpcSerialization.js b/dist/unstable/rpc/RpcSerialization.js
index 26dc4f2608580af60306a99243a9abf2b3581640..7c25eeb940428fc2844c986cbb98b989518e7f5a 100644
--- a/dist/unstable/rpc/RpcSerialization.js
+++ b/dist/unstable/rpc/RpcSerialization.js
@@ -139,7 +139,7 @@ function decodeJsonRpcRaw(decoded, batches) {
}
function decodeJsonRpcMessage(decoded) {
if ("method" in decoded) {
- if (!decoded.id && decoded.method.startsWith("@effect/rpc/")) {
+ if (decoded.id == null && decoded.method.startsWith("@effect/rpc/")) {
const tag = decoded.method.slice("@effect/rpc/".length);
const requestId = decoded.params?.requestId;
return requestId ? {
@@ -151,7 +151,7 @@ function decodeJsonRpcMessage(decoded) {
}
return {
_tag: "Request",
- id: decoded.id ? String(decoded.id) : "",
+ id: decoded.id != null ? String(decoded.id) : "",
tag: decoded.method,
payload: decoded.params ?? null,
headers: decoded.headers ?? [],
@@ -241,7 +241,7 @@ function encodeJsonRpcMessage(response) {
jsonrpc: "2.0",
method: response.tag,
params: response.payload,
- id: response.id && Number(response.id),
+ id: response.id !== "" ? Number(response.id) : undefined,
headers: response.headers,
traceId: response.traceId,
spanId: response.spanId,
@@ -271,14 +271,14 @@ function encodeJsonRpcMessage(response) {
if (response.exit._tag === "Success") {
return {
jsonrpc: "2.0",
- id: response.requestId ? Number(response.requestId) : undefined,
+ id: response.requestId !== "" ? Number(response.requestId) : undefined,
result: response.exit.value
};
}
const error = response.exit.cause.find(failure => failure._tag === "Fail");
return {
jsonrpc: "2.0",
- id: response.requestId ? Number(response.requestId) : undefined,
+ id: response.requestId !== "" ? Number(response.requestId) : undefined,
error: response.exit._tag === "Failure" ? {
_tag: "Cause",
code: error && Predicate.hasProperty(error, "code") ? Number(error.code) : 0,
diff --git a/src/unstable/rpc/RpcSerialization.ts b/src/unstable/rpc/RpcSerialization.ts
index 319effeabbc94237cd1a11799ac5d9bbd39d0170..66e82004de888b38f19a792886b461daa1789c55 100644
--- a/src/unstable/rpc/RpcSerialization.ts
+++ b/src/unstable/rpc/RpcSerialization.ts
@@ -180,7 +180,7 @@ function decodeJsonRpcRaw(
function decodeJsonRpcMessage(decoded: JsonRpcMessage): RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded {
if ("method" in decoded) {
- if (!decoded.id && decoded.method.startsWith("@effect/rpc/")) {
+ if (decoded.id == null && decoded.method.startsWith("@effect/rpc/")) {
const tag = decoded.method.slice("@effect/rpc/".length) as
| RpcMessage.FromServerEncoded["_tag"]
| Exclude<RpcMessage.FromClientEncoded["_tag"], "Request">
@@ -194,7 +194,7 @@ function decodeJsonRpcMessage(decoded: JsonRpcMessage): RpcMessage.FromClientEnc
}
return {
_tag: "Request",
- id: decoded.id ? String(decoded.id) : "",
+ id: decoded.id != null ? String(decoded.id) : "",
tag: decoded.method,
payload: decoded.params ?? null,
headers: decoded.headers ?? [],
@@ -308,7 +308,7 @@ function encodeJsonRpcMessage(response: RpcMessage.FromServerEncoded | RpcMessag
jsonrpc: "2.0",
method: response.tag,
params: response.payload,
- id: response.id && Number(response.id),
+ id: response.id !== "" ? Number(response.id) : undefined,
headers: response.headers,
traceId: response.traceId,
spanId: response.spanId,
@@ -335,14 +335,14 @@ function encodeJsonRpcMessage(response: RpcMessage.FromServerEncoded | RpcMessag
if (response.exit._tag === "Success") {
return {
jsonrpc: "2.0",
- id: response.requestId ? Number(response.requestId) : undefined,
+ id: response.requestId !== "" ? Number(response.requestId) : undefined,
result: response.exit.value
} as any
}
const error = response.exit.cause.find((failure) => failure._tag === "Fail")
return {
jsonrpc: "2.0",
- id: response.requestId ? Number(response.requestId) : undefined,
+ id: response.requestId !== "" ? Number(response.requestId) : undefined,
error: response.exit._tag === "Failure" ?
{
_tag: "Cause",